-
Notifications
You must be signed in to change notification settings - Fork 709
Expand file tree
/
Copy pathagent.ts
More file actions
1639 lines (1552 loc) · 63.8 KB
/
agent.ts
File metadata and controls
1639 lines (1552 loc) · 63.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Agent runtime wrapper — the live generate path in v0.2.
*
* Routes a `generate()`-shaped request through `@mariozechner/pi-agent-core`
* with the v0.2 design tool set (set_title, set_todos,
* str_replace_based_edit_tool, done, generate_image_asset, skill, scaffold,
* preview, tweaks, ask — see `defaultTools` below). Streams `turn_start` /
* `message_update` / `turn_end` lifecycle events through `onEvent` so the
* renderer can drive the chat/preview UI.
*
* pi-agent-core quirks worth remembering:
* - `Agent` does NOT accept `model` / `systemPrompt` / `tools` as top-level
* constructor args. They live in `options.initialState`.
* - There is no `agent.run()` returning `{finalText, usage}`. We call
* `agent.prompt(userMessage)` (Promise<void>) and read the final
* assistant message + usage from `agent.state.messages` after settlement.
* - The stream delta event is `message_update` with
* `assistantMessageEvent.type === 'text_delta'`, not a top-level
* `text_delta` event.
*/
import path from 'node:path';
import {
Agent,
type AgentEvent,
type AgentMessage,
type AgentTool,
type AgentToolResult,
} from '@mariozechner/pi-agent-core';
import type {
ImageContent as PiAiImageContent,
Message as PiAiMessage,
Model as PiAiModel,
} from '@mariozechner/pi-ai';
import type { RetryDecision, RetryReason } from '@open-codesign/providers';
import {
classifyError,
claudeCodeIdentityHeaders,
inferReasoning,
isProviderAbortedTransportError,
isTransportLevelError,
looksLikeClaudeOAuthToken,
normalizeGeminiModelId,
shouldForceClaudeCodeIdentity,
withBackoff,
} from '@open-codesign/providers';
import {
type ChatMessage,
CodesignError,
canonicalBaseUrl,
DEFAULT_SOURCE_ENTRY,
type DesignRunPreferencesV1,
ERROR_CODES,
formatDesignMdForPrompt,
LEGACY_SOURCE_ENTRY,
type ModelRef,
type ResourceStateV1,
validateDesignMd,
type WireApi,
} from '@open-codesign/shared';
import type { TSchema } from '@sinclair/typebox';
import { buildTransformContext } from './context-prune.js';
import { remapProviderError } from './errors.js';
import type { GenerateInput, GenerateOutput } from './index.js';
import { reasoningForModel } from './index.js';
import {
type Collected,
createDesignSourceArtifact,
stripEmptyFences,
} from './lib/artifact-collect.js';
import {
buildContextSections,
buildUserPromptWithContext,
formatProjectDesignSystemContext,
formatProjectInstructionsContext,
formatProjectSettingsContext,
formatUntrustedContext,
} from './lib/context-format.js';
import { NOOP_LOGGER } from './logger.js';
import type {
PromptFeatureConfidence,
PromptFeatureMode,
PromptFeatureProfile,
PromptFeatureProvenance,
PromptFeatureSetting,
} from './prompts/compose-full.js';
import { composeSystemPrompt } from './prompts/index.js';
import { collectResourceManifest } from './resource-manifest.js';
import {
assertFinalizationGate,
cloneResourceState,
recordDone,
recordLoadedResource,
recordMutation,
recordScaffold,
} from './resource-state.js';
import { buildRunProtocolPreflight, type RunProtocolState } from './run-protocol.js';
import { availableToolNames } from './tool-manifest.js';
import { makeAskTool } from './tools/ask.js';
import { type DoneDetails, type DoneRuntimeVerifier, makeDoneTool } from './tools/done.js';
import {
type GenerateImageAssetFn,
makeGenerateImageAssetTool,
} from './tools/generate-image-asset.js';
import { makeInspectWorkspaceTool } from './tools/inspect-workspace.js';
import { makePreviewTool } from './tools/preview.js';
import { makeScaffoldTool, type ScaffoldDetails } from './tools/scaffold.js';
import { makeSetTitleTool } from './tools/set-title.js';
import { makeSetTodosTool } from './tools/set-todos.js';
import { makeSkillTool } from './tools/skill.js';
import { makeTextEditorTool, type TextEditorFsCallbacks } from './tools/text-editor.js';
import { makeTweaksTool } from './tools/tweaks.js';
/** Local mirror of the assistant message shape that pi-agent-core emits (via
* pi-ai). Declared here so this file does not take a direct dependency on
* `@mariozechner/pi-ai`'s types; keep this shape in lockstep with the real
* pi-ai `AssistantMessage` whenever pi-agent-core is upgraded. */
interface PiAssistantMessage {
role: 'assistant';
content: Array<{ type: string; text?: string }>;
api: string;
provider: string;
model: string;
usage?: {
input?: number;
output?: number;
cost?: { total?: number };
};
stopReason: 'stop' | 'length' | 'toolUse' | 'error' | 'aborted';
errorMessage?: string;
timestamp: number;
}
// Prompt assembly and artifact collection helpers live in ./lib/context-format.ts
// and ./lib/artifact-collect.ts (shared with index.ts).
//
// Note: extractLooseArtifact / extractHtmlDocument were removed in favour of
// str_replace_based_edit_tool + virtual fs. See
// `if (collected.artifacts.length === 0 && deps.fs)` below for the only
// supported recovery.
// ---------------------------------------------------------------------------
// Model resolution — unified single path. We never query pi-ai's registry;
// instead we build the pi-ai Model shape directly from `cfg.providers[id]`
// (wire + baseUrl + modelId). This means:
// - builtin providers (anthropic/openai/openrouter) take the same path as
// imported ones (claude-code-imported, codex-*, custom proxies)
// - there is no "unknown model" error — a missing entry is a config bug
// the caller must surface, not an error to swallow
// - cost / context-window metadata comes from pi-ai's registry historically,
// but the user has opted to drop cost display, so we use optimistic
// defaults (cost 0) that do not block requests
// ---------------------------------------------------------------------------
interface PiModel {
id: string;
name: string;
api: string;
provider: string;
baseUrl: string;
reasoning: boolean;
compat?: {
supportsDeveloperRole?: boolean;
supportsReasoningEffort?: boolean;
supportsStore?: boolean;
supportsStrictMode?: boolean;
maxTokensField?: 'max_completion_tokens' | 'max_tokens';
};
input: ('text' | 'image')[];
cost: { input: number; output: number; cacheRead: number; cacheWrite: number };
contextWindow: number;
maxTokens: number;
headers?: Record<string, string>;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null;
}
function isResponsesReasoningItem(value: unknown): boolean {
return isRecord(value) && value['type'] === 'reasoning';
}
export function sanitizeOpenAIResponsesPayloadForStoreFalse(payload: unknown): unknown {
if (!isRecord(payload) || payload['store'] !== false || !Array.isArray(payload['input'])) {
return payload;
}
return {
...payload,
input: payload['input'].filter((entry) => !isResponsesReasoningItem(entry)),
};
}
function apiForWire(wire: WireApi | undefined): string {
if (wire === 'anthropic') return 'anthropic-messages';
if (wire === 'openai-responses') return 'openai-responses';
if (wire === 'openai-codex-responses') return 'openai-codex-responses';
// openai-chat is the canonical wire for everything else that uses the
// openai chat-completions wire format (openai, openrouter, deepseek, etc.).
return 'openai-completions';
}
function supportsOpenAIDeveloperRole(wire: WireApi | undefined, baseUrl: string): boolean {
if (wire !== 'openai-chat') return true;
const host = (() => {
try {
return new URL(baseUrl).hostname.toLowerCase();
} catch {
return '';
}
})();
return host === 'api.openai.com' || host.endsWith('.openai.com') || host === 'openrouter.ai';
}
function openAIChatCompatForBaseUrl(
wire: WireApi | undefined,
baseUrl: string,
): PiModel['compat'] | undefined {
if (wire !== 'openai-chat') return undefined;
let host = '';
try {
host = new URL(baseUrl).hostname.toLowerCase();
} catch {
return { supportsDeveloperRole: false };
}
if (host === 'api.deepinfra.com' || host.endsWith('.deepinfra.com')) {
return {
supportsDeveloperRole: false,
supportsReasoningEffort: false,
supportsStore: false,
supportsStrictMode: false,
maxTokensField: 'max_tokens',
};
}
if (!supportsOpenAIDeveloperRole(wire, baseUrl)) {
return { supportsDeveloperRole: false };
}
return undefined;
}
function supportsImageInput(wire: WireApi | undefined, modelId: string): boolean {
if (wire === 'anthropic' || wire === 'openai-responses' || wire === 'openai-codex-responses') {
return true;
}
if (wire === 'openai-chat') {
return true;
}
const lower = modelId.toLowerCase();
return (
lower.includes('vision') ||
lower.includes('vl') ||
lower.includes('multimodal') ||
lower.includes('gpt-4o') ||
lower.includes('gpt-5') ||
lower.includes('claude-3') ||
lower.includes('claude-sonnet-4') ||
lower.includes('claude-opus-4')
);
}
const BUILTIN_PUBLIC_BASE_URLS: Record<string, string> = {
anthropic: 'https://api.anthropic.com',
openai: 'https://api.openai.com/v1',
openrouter: 'https://openrouter.ai/api/v1',
};
function buildPiModel(
model: ModelRef,
wire: WireApi | undefined,
baseUrl: string | undefined,
httpHeaders?: Record<string, string> | undefined,
apiKey?: string,
): PiModel {
// Fall through to the canonical public endpoint for the 3 first-party
// BYOK providers when the caller omitted baseUrl. This is a fact about
// those endpoints (api.anthropic.com is anthropic), not a registry lookup for a
// model registry — imported / custom providers still require baseUrl and
// will throw if absent.
const resolvedBaseUrl =
baseUrl && baseUrl.trim().length > 0
? baseUrl
: (BUILTIN_PUBLIC_BASE_URLS[model.provider] ?? '');
if (resolvedBaseUrl.length === 0) {
throw new CodesignError(
`Provider "${model.provider}" has no baseUrl configured. Add one in Settings or re-import the config.`,
ERROR_CODES.PROVIDER_BASE_URL_MISSING,
);
}
// Defensive: canonicalize stored baseUrl before handing to pi-ai. Rescues
// legacy configs that persisted pre-normalization (e.g. raw `/v1/chat/completions`
// pasted in an older build). No-op for configs saved post-fix.
// For openai-codex-responses, canonicalBaseUrl only strips trailing slashes
// — pi-ai's codex wire appends `/codex/responses` from the bare base itself.
const canonicalBase = wire ? canonicalBaseUrl(resolvedBaseUrl, wire) : resolvedBaseUrl;
const effectiveModelId = normalizeGeminiModelId(model.modelId, canonicalBase);
const out: PiModel = {
id: effectiveModelId,
name: effectiveModelId,
api: apiForWire(wire),
provider: model.provider,
baseUrl: canonicalBase,
reasoning: inferReasoning(wire, effectiveModelId, canonicalBase),
input: supportsImageInput(wire, effectiveModelId) ? ['text', 'image'] : ['text'],
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
contextWindow: 200000,
maxTokens: 32000,
};
const compat = openAIChatCompatForBaseUrl(wire, canonicalBase);
if (compat !== undefined) out.compat = compat;
if (httpHeaders !== undefined) out.headers = httpHeaders;
// sub2api / claude2api gateways 403 any request without claude-cli
// identity headers. pi-ai only emits them for sk-ant-oat OAuth tokens —
// so a custom anthropic baseUrl keyed by a plain token hits the edge WAF.
// Inject them here too (this path goes through pi-agent-core, which
// forwards model.headers to pi-ai). User-supplied headers keep precedence.
// Skip when the key already looks OAuth-shaped: pi-ai's OAuth branch
// injects the same set, and leaving that the single source keeps us from
// silently overriding future pi-ai header updates on the OAuth path.
if (
shouldForceClaudeCodeIdentity(wire, canonicalBase) &&
(apiKey === undefined || !looksLikeClaudeOAuthToken(apiKey))
) {
out.headers = { ...claudeCodeIdentityHeaders(), ...(out.headers ?? {}) };
}
return out;
}
// ---------------------------------------------------------------------------
// Tool-use guidance appended to the system prompt when agentic tools are
// active. Keeps the base prompt (shared with the non-agent path) unchanged.
// ---------------------------------------------------------------------------
const MAX_DONE_ERROR_ROUNDS = 3;
function featureMode(mode: DesignRunPreferencesV1['tweaks'] | undefined): PromptFeatureMode {
if (mode === 'yes') return 'enabled';
if (mode === 'no') return 'disabled';
return 'auto';
}
function featureSetting(
preferences: DesignRunPreferencesV1 | undefined,
key: 'tweaks' | 'bitmapAssets' | 'reusableSystem',
): PromptFeatureSetting {
const routing = preferences?.routing?.[key];
return {
mode: featureMode(preferences?.[key]),
provenance: (routing?.provenance ?? 'default') as PromptFeatureProvenance,
confidence: (routing?.confidence ?? 'low') as PromptFeatureConfidence,
...(routing?.reason !== undefined ? { reason: routing.reason } : {}),
};
}
function featureProfileFromRunPreferences(
preferences: DesignRunPreferencesV1 | undefined,
): PromptFeatureProfile {
return {
tweaks: featureSetting(preferences, 'tweaks'),
bitmapAssets: featureSetting(preferences, 'bitmapAssets'),
reusableSystem: featureSetting(preferences, 'reusableSystem'),
...(preferences?.visualDirection ? { visualDirection: preferences.visualDirection } : {}),
};
}
function explicitDisabled(setting: PromptFeatureProfile['tweaks']): boolean {
return (
typeof setting !== 'string' &&
setting.mode === 'disabled' &&
setting.provenance === 'explicit' &&
setting.confidence === 'high'
);
}
function featureModeValue(setting: PromptFeatureProfile['tweaks']): PromptFeatureMode {
return typeof setting === 'string' ? setting : setting.mode;
}
function isAutoDesignName(name: string | undefined): boolean {
return name === 'Untitled design' || /^Untitled design \d+$/.test(name ?? '');
}
function autoTitleFromPrompt(prompt: string): string {
const condensed = prompt.replace(/\s+/g, ' ').trim();
if (condensed.length === 0) return 'Untitled design';
return condensed.length > 40 ? `${condensed.slice(0, 40).trimEnd()}…` : condensed;
}
function emitPreflightSetTitle(onEvent: GenerateViaAgentDeps['onEvent'], title: string): void {
if (!onEvent) return;
const toolCallId = 'host-set-title';
onEvent({
type: 'tool_execution_start',
toolCallId,
toolName: 'set_title',
args: { title },
} as AgentEvent);
onEvent({
type: 'tool_execution_end',
toolCallId,
toolName: 'set_title',
isError: false,
result: {
content: [{ type: 'text', text: `Title set: ${title}` }],
details: { title },
},
} as AgentEvent);
}
function todosRequiredResult(
toolName: string,
): AgentToolResult<{ status: string; reason: string }> {
return {
content: [
{
type: 'text',
text: `Call set_todos before editing, previewing, or finishing. Then retry ${toolName}.`,
},
],
details: { status: 'blocked', reason: 'todos_required' },
};
}
function wrapTodosState<TParams extends TSchema, TDetails>(
tool: AgentTool<TParams, TDetails>,
state: RunProtocolState,
): AgentTool<TParams, TDetails> {
return {
...tool,
async execute(toolCallId, params) {
const result = await tool.execute(toolCallId, params);
state.todosSet = true;
return result;
},
};
}
function wrapPlanningGate<TParams extends TSchema, TDetails>(
tool: AgentTool<TParams, TDetails>,
state: RunProtocolState,
options: {
allowBeforeTodos?: ((params: unknown) => boolean) | undefined;
} = {},
): AgentTool<TParams, TDetails> {
return {
...tool,
async execute(toolCallId, params) {
if (
state.requiresTodosBeforeMutation &&
!state.todosSet &&
options.allowBeforeTodos?.(params) !== true
) {
return todosRequiredResult(tool.name) as AgentToolResult<TDetails>;
}
return await tool.execute(toolCallId, params);
},
};
}
function isTextEditorView(params: unknown): boolean {
return (
typeof params === 'object' &&
params !== null &&
(params as { command?: unknown }).command === 'view'
);
}
function imageDataUrlToContent(dataUrl: string): PiAiImageContent | null {
const match = /^data:([^;,]+);base64,([A-Za-z0-9+/]+={0,2})$/i.exec(dataUrl.trim());
if (match === null) return null;
const mimeType = match[1];
const data = match[2];
if (mimeType === undefined || data === undefined || !mimeType.startsWith('image/')) return null;
return { type: 'image', data, mimeType };
}
function attachmentImagesForModel(input: GenerateInput, model: PiModel): PiAiImageContent[] {
if (!model.input.includes('image')) return [];
return (input.attachments ?? []).flatMap((attachment) => {
if (!attachment.imageDataUrl) return [];
const image = imageDataUrlToContent(attachment.imageDataUrl);
return image === null ? [] : [image];
});
}
function agenticToolGuidance(input: {
inspectWorkspace: boolean;
featureProfile: PromptFeatureProfile;
currentDesignName?: string | undefined;
}): string {
const titleStep = isAutoDesignName(input.currentDesignName)
? '1. The current design title is still auto-generated. Call `set_title` once as the first tool call, before `set_todos`, `view`, `scaffold`, or file edits. Use a 2-5 word title that describes what is being designed.'
: '1. For a fresh design, call `set_title` once. For continuation or existing-source turns, do not call `set_title` unless the user explicitly asks to rename or pivot to a new artifact.';
const tweakStep = explicitDisabled(input.featureProfile.tweaks)
? `${input.inspectWorkspace ? '6' : '5'}. Do not call \`tweaks()\` unless the user explicitly asks for controls later.`
: featureModeValue(input.featureProfile.tweaks) === 'enabled'
? `${input.inspectWorkspace ? '6' : '5'}. Create 2-5 high-leverage EDITMODE controls, then call \`tweaks()\`.`
: `${input.inspectWorkspace ? '6' : '5'}. Decide agentically whether \`tweaks()\` would materially improve iteration; do not rely on harness guesses.`;
const requiredSteps = [
titleStep,
'2. For multi-step or ambiguous work, call `set_todos` early with a short checklist. Do not delay a ready file mutation solely to add todos.',
'3. Load optional resources explicitly before relying on them. Use `skill(name)` for method guidance. When the request matches an available frame, shell, primitive, deck, report, or starter, call `scaffold({kind, destPath})` before writing the primary artifact; do not substitute a virtual `frames/*` or `skills/*` view for scaffolded workspace source.',
...(input.inspectWorkspace
? [
'4. When the workspace brief says files or reference materials are present, call `inspect_workspace` before editing, then `view` the specific files you need.',
]
: []),
`${input.inspectWorkspace ? '5' : '4'}. Match the workspace files to the request. For visual/web work, write/edit the primary preview source at \`${DEFAULT_SOURCE_ENTRY}\`; for document-first work, create the requested Markdown/handoff file without inventing a visual shell.`,
tweakStep,
`${input.inspectWorkspace ? '7' : '6'}. Call \`preview(path)\` for previewable HTML/JSX/TSX files after the final mutation, then call \`done(path)\` as the final self-check. If done reports errors, fix and retry, but stop after ${MAX_DONE_ERROR_ROUNDS} error rounds.`,
];
return [
'## Workspace output contract',
'',
'- The workspace filesystem is the deliverable. Chat text is never the artifact.',
`- For visual/web deliverables, write the primary design source to \`${DEFAULT_SOURCE_ENTRY}\` with \`str_replace_based_edit_tool\`.`,
'- Multi-deliverable packages are allowed when useful: preview source, DESIGN.md, Markdown handoff docs, data files, and local assets can all belong to one design.',
'- For document-first requests such as design briefs, content outlines, or handoff notes, create the requested `.md` file directly and skip `App.jsx` unless a visual preview is also useful.',
'- Prefer progressive generation when it is natural: write a coherent first pass, then add sections, data, interactions, and polish in focused edits before previewing.',
'- Fresh visual sequence: `set_title` -> optional `set_todos`/`skill` -> required `scaffold` when a matching starter/frame/shell/primitive exists -> `create App.jsx` with a coherent first pass -> focused edits if needed -> `preview(App.jsx)`.',
'- Fresh document sequence: `set_title` -> optional `set_todos`/`skill` -> create the requested document file -> `done(path)` self-check.',
'- Do not call `preview` while a previewable artifact is still only a scaffold, loading state, skeleton, placeholder, or empty lower section. Preview should represent a coherent first pass unless the user explicitly asked for a loading-state design.',
'- Existing-source sequence: optional `set_todos` -> `inspect_workspace` when available -> `view` the source -> `str_replace`/`insert`. Do not edit an existing source from memory, and do not rebuild unless the user explicitly asks.',
'- If the design is still named `Untitled design` or `Untitled design N`, naming is not optional: call `set_title` before other work, even when a scaffold or reference source already exists.',
'- Use `create` for new files; follow-up edits use `view`, `str_replace`, or `insert`.',
'- Do not emit `<artifact>` tags, fenced source blocks, raw HTML/JSX/CSS, or HTML wrappers in chat.',
'- Local workspace assets and scaffolded files are allowed. External scripts remain restricted by the base output rules.',
'- Interleave major tool groups with one short assistant progress sentence: what you are about to inspect/write/preview/fix, or what the preview showed. Keep it under 18 words and do not reveal hidden reasoning.',
'',
'## Tool loop',
'',
...requiredSteps,
'',
'## File-edit discipline',
'',
'- Keep `old_str` small and unique. Large replacements waste context and are fragile.',
'- For existing files, call `view` in the same run before `str_replace` or `insert`; use the latest viewed text, not memory.',
'- A complete first `create` is acceptable when the target file is ready. Keep follow-up edits focused so they remain reliable.',
'- Never view just to check whether an edit succeeded; the tool reports failures.',
].join('\n');
}
const IMAGE_ASSET_TOOL_GUIDANCE = [
'## Bitmap asset generation',
'',
'Use `generate_image_asset` only for named or clearly beneficial bitmap slots: hero, product, poster, background, illustration, or rendered logo.',
'Before writing the design source, inventory required assets and request all bitmap assets in one batch. One named bitmap slot equals one tool call.',
'Use inline SVG/CSS for charts, simple icons, flat geometric marks, gradients, and UI chrome.',
'Each call needs a production prompt, accurate `purpose`, matching `aspectRatio`, meaningful `alt`, and optional `filenameHint`.',
'Reference the returned local `assets/...` path from the design source.',
].join('\n');
// ---------------------------------------------------------------------------
// Transport-level retry helpers.
// ---------------------------------------------------------------------------
const MAX_TRANSPORT_RETRIES = 2;
/**
* Remove the failed final turn from the agent message history so a fresh agent
* can retry with a clean slate. Walks backwards from the terminal error
* assistant message to find the user message that started the turn, removing
* all intermediate tool-call / toolResult entries in between.
*/
export function stripFailedTurn(messages: readonly AgentMessage[]): AgentMessage[] {
let errorIndex = -1;
for (let i = messages.length - 1; i >= 0; i--) {
const msg = messages[i];
if (!msg) continue;
if (errorIndex === -1) {
const stopReason = (msg as PiAssistantMessage).stopReason;
if (msg.role === 'assistant' && (stopReason === 'error' || stopReason === 'aborted')) {
errorIndex = i;
}
continue;
}
if (msg.role === 'user') {
return [...messages.slice(0, i), ...messages.slice(errorIndex + 1)];
}
}
return errorIndex === -1 ? [...messages] : messages.slice(0, errorIndex);
}
function trackFsMutations(
fs: TextEditorFsCallbacks,
resourceState: ResourceStateV1,
): TextEditorFsCallbacks {
return {
view: (path) => fs.view(path),
listDir: (dir) => fs.listDir(dir),
async create(path, content) {
const result = await fs.create(path, content);
recordMutation(resourceState);
return result;
},
async strReplace(path, oldStr, newStr) {
const result = await fs.strReplace(path, oldStr, newStr);
recordMutation(resourceState);
return result;
},
async insert(path, line, text) {
const result = await fs.insert(path, line, text);
recordMutation(resourceState);
return result;
},
};
}
function wrapSkillState(
tool: AgentTool<TSchema, unknown>,
resourceState: ResourceStateV1,
): AgentTool<TSchema, unknown> {
return {
...tool,
async execute(id, params, signal): Promise<AgentToolResult<unknown>> {
const result = await tool.execute(id, params, signal);
const details = result.details as { name?: unknown; status?: unknown } | undefined;
if (details?.status === 'loaded' && typeof details.name === 'string') {
recordLoadedResource(resourceState, details.name);
}
return result;
},
};
}
function wrapScaffoldState(
tool: AgentTool<TSchema, unknown>,
resourceState: ResourceStateV1,
): AgentTool<TSchema, unknown> {
return {
...tool,
async execute(id, params, signal): Promise<AgentToolResult<unknown>> {
const result = await tool.execute(id, params, signal);
const details = result.details as ScaffoldDetails | undefined;
if (details && 'ok' in details && details.ok === true) {
recordScaffold(resourceState, {
kind: details.kind,
destPath: details.destPath,
bytes: details.bytes,
});
}
return result;
},
};
}
function wrapDoneState(
tool: AgentTool<TSchema, unknown>,
resourceState: ResourceStateV1,
onRepairLimitReached?: (() => void) | undefined,
): AgentTool<TSchema, unknown> {
let errorRounds = 0;
return {
...tool,
executionMode: 'sequential',
async execute(id, params, signal): Promise<AgentToolResult<unknown>> {
const result = await tool.execute(id, params, signal);
const details = result.details as DoneDetails | undefined;
if (details) {
recordDone(resourceState, {
status: details.status,
path: details.path,
errorCount: details.errors.length,
});
if (details.status === 'ok') {
errorRounds = 0;
} else {
errorRounds += 1;
if (errorRounds >= MAX_DONE_ERROR_ROUNDS) {
onRepairLimitReached?.();
return {
...result,
content: [{ type: 'text', text: formatDoneRepairLimitText(details) }],
terminate: true,
};
}
}
}
return result;
},
};
}
function formatDoneRepairLimitText(details: DoneDetails): string {
const remainingErrors =
details.errors.length === 0
? ['- done() still reported errors, but no actionable verifier details were returned.']
: details.errors.map(
(error) => `- ${error.message}${error.lineno ? ` (line ${error.lineno})` : ''}`,
);
return [
'has_errors',
`Repair limit reached after ${MAX_DONE_ERROR_ROUNDS} done() error rounds.`,
'STOP. Do not call done, preview, edit, or any other tool again.',
'The host will keep the latest artifact when possible and surface these warnings to the user.',
'',
'Remaining verifier output:',
...remainingErrors,
].join('\n');
}
function isReasoningContentRoundTripError(errorMessage: string | undefined): boolean {
if (!errorMessage) return false;
const message = errorMessage.toLowerCase();
return message.includes('reasoning_content');
}
function finiteUsageNumber(value: unknown): number {
return typeof value === 'number' && Number.isFinite(value) ? value : 0;
}
function aggregateAssistantUsage(messages: readonly AgentMessage[]): {
inputTokens: number;
outputTokens: number;
costUsd: number;
} {
const totals = { inputTokens: 0, outputTokens: 0, costUsd: 0 };
for (const message of messages) {
if (message.role !== 'assistant') continue;
const usage = (message as PiAssistantMessage).usage;
totals.inputTokens += finiteUsageNumber(usage?.input);
totals.outputTokens += finiteUsageNumber(usage?.output);
totals.costUsd += finiteUsageNumber(usage?.cost?.total);
}
return totals;
}
function stripTerminalAssistantFailure(messages: readonly AgentMessage[]): AgentMessage[] {
const out = [...messages];
const last = out[out.length - 1];
if (
last?.role === 'assistant' &&
((last as PiAssistantMessage).stopReason === 'error' ||
(last as PiAssistantMessage).stopReason === 'aborted')
) {
out.pop();
}
return out;
}
function prepareReasoningFallback(messages: readonly AgentMessage[]): {
messages: AgentMessage[];
mode: 'continue' | 'prompt';
} {
const cleanMessages = stripTerminalAssistantFailure(messages);
const last = cleanMessages[cleanMessages.length - 1];
if (last?.role === 'toolResult') {
return { messages: cleanMessages, mode: 'continue' };
}
if (last?.role === 'user') {
return { messages: cleanMessages.slice(0, -1), mode: 'prompt' };
}
return { messages: cleanMessages, mode: 'prompt' };
}
function projectContextSections(context: GenerateInput['projectContext']): string[] {
if (!context) return [];
const sections: string[] = [];
if (context.agentsMd?.trim()) {
sections.push(formatProjectInstructionsContext(context.agentsMd.trim()));
}
if (context.designMd?.trim()) {
const findings = validateDesignMd(context.designMd);
const errors = findings.filter((finding) => finding.severity === 'error');
if (errors.length > 0) {
throw new CodesignError(
`DESIGN.md is not valid Google design.md: ${errors
.slice(0, 3)
.map((finding) => `${finding.path}: ${finding.message}`)
.join('; ')}`,
ERROR_CODES.CONFIG_SCHEMA_INVALID,
);
}
sections.push(formatProjectDesignSystemContext(formatDesignMdForPrompt(context.designMd)));
}
if (context.invalidDesignMd?.raw.trim()) {
const errors = context.invalidDesignMd.errors.length
? context.invalidDesignMd.errors
: ['DESIGN.md failed Google design.md validation.'];
sections.push(
[
'# Project Design System Repair Required (DESIGN.md)',
'',
'The workspace has a DESIGN.md file, but it is not valid Google design.md yet.',
'Treat the current file as design-system draft data only. Before calling `done(path)`, repair DESIGN.md with `str_replace_based_edit_tool` so it validates.',
'',
'Validation errors:',
...errors.map((message) => `- ${message}`),
'',
formatUntrustedContext(
'invalid_design_md',
'The following workspace DESIGN.md failed validation.',
context.invalidDesignMd.raw,
),
].join('\n'),
);
}
if (context.settingsJson?.trim()) {
sections.push(formatProjectSettingsContext(context.settingsJson.trim()));
}
return sections;
}
function workspaceFiles(fs: TextEditorFsCallbacks | undefined): string[] {
if (!fs) return [];
return fs
.listDir('.')
.filter((file) => file.trim().length > 0)
.sort((a, b) => a.localeCompare(b));
}
function isVirtualTemplatePath(file: string): boolean {
const normalized = file.replace(/\\/g, '/').toLowerCase();
return normalized.startsWith('frames/') || normalized.startsWith('skills/');
}
function sourceCandidates(
files: readonly string[],
fs: TextEditorFsCallbacks | undefined,
): string[] {
if (!fs) return [];
const candidates = files.filter((file) => {
if (isVirtualTemplatePath(file)) return false;
if (!/\.(?:jsx|tsx|html?)$/i.test(file)) return false;
const viewed = fs.view(file);
return viewed !== null && viewed.content.trim().length > 0;
});
return candidates
.sort((a, b) => {
const score = (file: string): number => {
const lower = file.toLowerCase();
if (lower === DEFAULT_SOURCE_ENTRY.toLowerCase()) return 0;
if (lower === LEGACY_SOURCE_ENTRY.toLowerCase()) return 1;
if (lower.endsWith('/app.jsx') || lower.endsWith('/app.tsx')) return 2;
if (lower.endsWith('/index.html')) return 3;
return 10;
};
return score(a) - score(b) || a.localeCompare(b);
})
.slice(0, 8);
}
function buildWorkspaceBrief(
input: GenerateInput,
fs: TextEditorFsCallbacks | undefined,
): string | null {
if (!fs) return null;
const files = workspaceFiles(fs);
const sources = sourceCandidates(files, fs);
const hasDesignMd = fs.view('DESIGN.md') !== null;
const hasAgentsMd = fs.view('AGENTS.md') !== null;
const hasSettingsJson = fs.view('.codesign/settings.json') !== null;
const attachmentCount = input.attachments?.length ?? 0;
const imageCount = (input.attachments ?? []).filter((file) =>
file.mediaType?.startsWith('image/'),
).length;
const currentDesignName = input.currentDesignName?.trim();
const needsTitle = isAutoDesignName(currentDesignName);
const hasReferenceUrl = input.referenceUrl !== null && input.referenceUrl !== undefined;
const hasReferenceMaterials =
attachmentCount > 0 ||
hasReferenceUrl ||
(input.designSystem !== null && input.designSystem !== undefined);
const lines = [
'Workspace context:',
currentDesignName
? `- Current design title: ${currentDesignName}${needsTitle ? ' (auto-generated; call set_title before other tools).' : '.'}`
: '- Current design title: unknown.',
sources.length > 0
? `- Existing source candidates: ${sources.join(', ')}`
: `- No existing design source was found. Create ${DEFAULT_SOURCE_ENTRY} for visual/web work, or create the requested document/handoff file for document-first work.`,
`- DESIGN.md: ${hasDesignMd ? 'present; treat it as the design baton for this workspace.' : 'absent.'}`,
`- AGENTS.md: ${hasAgentsMd ? 'present' : 'absent'}`,
`- .codesign/settings.json: ${hasSettingsJson ? 'present' : 'absent'}`,
`- Reference materials: attached file(s): ${attachmentCount}; image file(s): ${imageCount}; reference URL: ${hasReferenceUrl ? 'yes' : 'no'}; linked design-system scan: ${input.designSystem ? 'yes' : 'no'}.`,
];
lines.push(
needsTitle
? sources.length > 0
? 'This workspace has source files, but the visible design title is still an auto-generated placeholder. First call `set_title` once, then inspect/view/edit. Preserve and extend existing source unless the user explicitly asks for a rebuild.'
: `This is an empty auto-named workspace. First call \`set_title\` once, then create ${DEFAULT_SOURCE_ENTRY} for visual/web work or the requested document file for document-first work. Use set_todos for multi-step work.`
: sources.length > 0
? 'Before editing existing source files, inspect the workspace when available, then view the current source file. Use set_todos when the edit has multiple steps. Existing-source sequence: optional `set_todos` -> `inspect_workspace` when available -> `view` the source -> `str_replace`/`insert`. For continuation or existing-source turns, do not call `set_title`; preserve and extend the current design unless the user explicitly asks for a rebuild.'
: `This is an empty workspace. For visual/web work, create ${DEFAULT_SOURCE_ENTRY} when the first pass is ready; for document-first work, create the requested document file. Use set_todos for multi-step work.`,
);
if (hasDesignMd) {
lines.push(
'DESIGN.md is present; read and preserve it as the design baton before changing visual tokens.',
);
} else if (sources.length > 0) {
lines.push(
'If stable visual decisions emerge across screens, reference-driven work, componentization, or prototype work, create or update a minimal DESIGN.md.',
);
}
if (hasReferenceMaterials) {
lines.push(
'Reference materials are available; extract design cues before writing or editing source.',
);
}
return lines.join('\n');
}
function buildTurnPrompt(input: GenerateInput, fs: TextEditorFsCallbacks | undefined): string {
const prompt = input.prompt.trim();
if (input.systemPrompt) return prompt;
const brief = buildWorkspaceBrief(input, fs);
if (brief === null) return prompt;
return [brief, '', 'User request:', prompt].join('\n');
}
// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------
// Public API.
// ---------------------------------------------------------------------------
export type { AgentEvent };
export interface GenerateViaAgentDeps {
/** Optional subscriber for Agent lifecycle + streaming events. */
onEvent?: ((event: AgentEvent) => void) | undefined;
/** Retry callback — invoked with placeholder reasons today; present so the
* IPC layer can reuse the same onRetry signature as the legacy path. */
onRetry?: ((info: RetryReason) => void) | undefined;
/** Tools the agent can call. When set, overrides the built-in default toolset.
* Pass `[]` to explicitly run without tools in focused tests. */
tools?: AgentTool<TSchema, unknown>[] | undefined;
/**
* Virtual filesystem callbacks for str_replace_based_edit_tool. When provided,
* the default toolset includes `str_replace_based_edit_tool` wired to
* these callbacks. When undefined, edit/done are hidden from the default
* toolset.
*/
fs?: TextEditorFsCallbacks | undefined;
/**
* When true, the agent system prompt is augmented with guidance to use
* set_todos for plans and str_replace_based_edit_tool to write/edit
* files. Default: true whenever at least one tool is active.
*/
encourageToolUse?: boolean | undefined;
/**
* Optional host-injected runtime verifier for the `done` tool. When set,
* `done` invokes this callback with the artifact source so the host can
* mount it in a real runtime (e.g. hidden BrowserWindow) and surface
* console / load errors back to the agent. Without it, `done` is limited to
* static lint checks.
*/
runtimeVerify?: DoneRuntimeVerifier | undefined;
/**
* Optional bitmap asset generator. When provided, the default toolset adds
* `generate_image_asset`; the main design agent decides when a hero/product/
* poster/background asset is worth generating.
*/
generateImageAsset?: GenerateImageAssetFn | undefined;
/** Called when aggressive context pruning triggers (context > 200KB). */
onAggressivePrune?: (() => void) | undefined;
/** Called after the agent finishes with the full conversation messages. */
onComplete?: ((messages: AgentMessage[]) => void) | undefined;
}
/**
* Route a generate request through pi-agent-core's Agent and the v0.2 design
* tool surface. Events are emitted so the desktop shell can stream progress,
* tool calls, and file updates while preserving the GenerateOutput boundary.
*/
export async function generateViaAgent(
input: GenerateInput,
deps: GenerateViaAgentDeps = {},
): Promise<GenerateOutput> {
const log = input.logger ?? NOOP_LOGGER;
const ctx = {
provider: input.model.provider,
modelId: input.model.modelId,
} as const;
if (!input.prompt.trim()) {
throw new CodesignError('Prompt cannot be empty', ERROR_CODES.INPUT_EMPTY_PROMPT);
}
const initialApiKey = input.apiKey.trim();
if (initialApiKey.length === 0 && input.allowKeyless !== true) {
throw new CodesignError('Missing API key', ERROR_CODES.PROVIDER_AUTH_MISSING);
}
if (!input.systemPrompt && input.mode && input.mode !== 'create') {
throw new CodesignError(
'generateViaAgent() built-in prompt only supports mode "create".',
ERROR_CODES.INPUT_UNSUPPORTED_MODE,
);
}
log.info('[generate] step=resolve_model', ctx);
const resolveStart = Date.now();
const piModel = buildPiModel(
input.model,
input.wire,
input.baseUrl,
input.httpHeaders,
initialApiKey,
);
log.info('[generate] step=resolve_model.ok', { ...ctx, ms: Date.now() - resolveStart });