@bastani/atomic 0.9.20-alpha.10 → 0.9.20-alpha.12

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/dist/builtin/intercom/package.json +1 -1
  3. package/dist/builtin/mcp/package.json +1 -1
  4. package/dist/builtin/subagents/CHANGELOG.md +13 -0
  5. package/dist/builtin/subagents/package.json +1 -1
  6. package/dist/builtin/subagents/skills/tdd/SKILL.md +10 -2
  7. package/dist/builtin/subagents/skills/tdd/mocking.md +4 -0
  8. package/dist/builtin/subagents/skills/tdd/test-audit.md +105 -0
  9. package/dist/builtin/subagents/skills/tdd/tests.md +3 -1
  10. package/dist/builtin/subagents/src/extension/index.bundle.mjs +2 -1
  11. package/dist/builtin/web-access/package.json +1 -1
  12. package/dist/builtin/workflows/CHANGELOG.md +17 -0
  13. package/dist/builtin/workflows/README.md +1 -1
  14. package/dist/builtin/workflows/builtin/adversarial-verification.js +3 -3
  15. package/dist/builtin/workflows/builtin/{chunk-7ps7bnb4.js → chunk-0nrgfbag.js} +1 -1
  16. package/dist/builtin/workflows/builtin/{chunk-2npg6daz.js → chunk-2hak3b7g.js} +1 -1
  17. package/dist/builtin/workflows/builtin/{chunk-twefqrv0.js → chunk-73c5tayt.js} +36 -3
  18. package/dist/builtin/workflows/builtin/{chunk-18yz7r43.js → chunk-bzdvx2xr.js} +1 -1
  19. package/dist/builtin/workflows/builtin/{chunk-24c235x7.js → chunk-crw7q5g1.js} +1 -1
  20. package/dist/builtin/workflows/builtin/{chunk-f8jjd90r.js → chunk-cw86srkf.js} +1 -1
  21. package/dist/builtin/workflows/builtin/{chunk-z5xdqrs6.js → chunk-jaj27rqc.js} +1 -1
  22. package/dist/builtin/workflows/builtin/{chunk-gxrhbnaj.js → chunk-kspvwc24.js} +2 -2
  23. package/dist/builtin/workflows/builtin/{chunk-ynded223.js → chunk-maqv731g.js} +3 -3
  24. package/dist/builtin/workflows/builtin/{chunk-1pd5zcfa.js → chunk-vkmpdat4.js} +1 -1
  25. package/dist/builtin/workflows/builtin/{chunk-2jv44yz7.js → chunk-w18kbz63.js} +1 -1
  26. package/dist/builtin/workflows/builtin/{chunk-ad864596.js → chunk-wh19f5ee.js} +3 -3
  27. package/dist/builtin/workflows/builtin/classify-and-act.js +3 -3
  28. package/dist/builtin/workflows/builtin/fan-out-and-synthesize.js +3 -3
  29. package/dist/builtin/workflows/builtin/generate-and-filter.js +3 -3
  30. package/dist/builtin/workflows/builtin/goal.js +4 -4
  31. package/dist/builtin/workflows/builtin/index.js +12 -12
  32. package/dist/builtin/workflows/builtin/loop-until-done.js +3 -3
  33. package/dist/builtin/workflows/builtin/open-claude-design.js +3 -3
  34. package/dist/builtin/workflows/builtin/ralph.js +4 -4
  35. package/dist/builtin/workflows/builtin/steering-context.js +1 -1
  36. package/dist/builtin/workflows/builtin/tournament.js +3 -3
  37. package/dist/builtin/workflows/package.json +1 -1
  38. package/dist/builtin/workflows/src/extension/index.bundle.mjs +105 -33
  39. package/dist/builtin/workflows/src/index.js +93 -27
  40. package/dist/core/context-tool-pairing.d.ts +10 -14
  41. package/dist/core/context-tool-pairing.d.ts.map +1 -1
  42. package/dist/core/context-tool-pairing.js +99 -28
  43. package/dist/core/context-tool-pairing.js.map +1 -1
  44. package/dist/core/messages.d.ts.map +1 -1
  45. package/dist/core/messages.js +2 -1
  46. package/dist/core/messages.js.map +1 -1
  47. package/dist/core/system-prompt.js +2 -2
  48. package/dist/core/system-prompt.js.map +1 -1
  49. package/docs/computer-use.md +31 -7
  50. package/docs/getting-started/first-session.md +1 -1
  51. package/docs/skills.md +2 -2
  52. package/docs/usage.md +1 -1
  53. package/docs/workflows/operations.md +3 -1
  54. package/docs/workflows/reliable-design.md +1 -1
  55. package/docs/workflows/verification.md +25 -7
  56. package/docs/workflows.md +1 -1
  57. package/npm-shrinkwrap.json +32 -32
  58. package/package.json +3 -3
@@ -1,43 +1,48 @@
1
- /**
2
- * Structural tool-pairing guard for provider-bound context.
3
- *
4
- * `repairOrphanToolResults` already collapses the recoverable forms of this
5
- * invariant at conversion time: orphaned or duplicate `tool_result` blocks and
6
- * tool calls interrupted before their result was persisted. None need to reach
7
- * the provider.
8
- *
9
- * A `tool_use` id announced by more than one assistant message is a different
10
- * problem. It means the transcript itself carries the same assistant turn twice,
11
- * so there is no safe repair — dropping either copy guesses at which tool results
12
- * belong to it. The provider answers that with an opaque 400 that kills the turn,
13
- * so fail here instead, naming the ids.
14
- */
1
+ function isToolCallBlock(block) {
2
+ if (!block || typeof block !== "object")
3
+ return false;
4
+ const candidate = block;
5
+ return candidate.type === "toolCall" && typeof candidate.id === "string";
6
+ }
7
+ function toolCallBlocks(message) {
8
+ const content = message.content;
9
+ return Array.isArray(content) ? content.filter(isToolCallBlock) : [];
10
+ }
11
+ function responseId(message) {
12
+ const id = message.responseId;
13
+ return typeof id === "string" && id !== "" ? id : undefined;
14
+ }
15
+ function isSameAssistantTurn(first, second) {
16
+ if (first === second)
17
+ return true;
18
+ const firstResponse = responseId(first);
19
+ const secondResponse = responseId(second);
20
+ if (firstResponse !== undefined && secondResponse !== undefined)
21
+ return firstResponse === secondResponse;
22
+ return first.timestamp === second.timestamp && JSON.stringify(first) === JSON.stringify(second);
23
+ }
15
24
  export function findDuplicateToolCallIds(messages) {
16
- const seen = new Set();
25
+ const announcers = new Map();
17
26
  const duplicates = new Set();
18
27
  for (const message of messages) {
19
28
  if (message.role !== "assistant")
20
29
  continue;
21
30
  if (message.excludeFromContext === true)
22
31
  continue;
23
- const content = message.content;
24
- if (!Array.isArray(content))
25
- continue;
26
- for (const block of content) {
27
- if (!block || typeof block !== "object")
32
+ for (const id of new Set(toolCallBlocks(message).map((block) => block.id))) {
33
+ const previous = announcers.get(id);
34
+ if (!previous) {
35
+ announcers.set(id, [message]);
28
36
  continue;
29
- const candidate = block;
30
- if (candidate.type !== "toolCall" || typeof candidate.id !== "string")
31
- continue;
32
- if (seen.has(candidate.id))
33
- duplicates.add(candidate.id);
34
- else
35
- seen.add(candidate.id);
37
+ }
38
+ if (previous.some((earlier) => isSameAssistantTurn(earlier, message)))
39
+ duplicates.add(id);
40
+ previous.push(message);
36
41
  }
37
42
  }
38
43
  return [...duplicates];
39
44
  }
40
- /** Throw a descriptive error when context carries a tool call id more than once. */
45
+ /** Throw a descriptive error when context carries the same assistant turn more than once. */
41
46
  export function assertToolPairingInvariant(messages) {
42
47
  const duplicates = findDuplicateToolCallIds(messages);
43
48
  if (duplicates.length === 0)
@@ -47,4 +52,70 @@ export function assertToolPairingInvariant(messages) {
47
52
  `${duplicates.join(", ")} ${plural ? "appear" : "appears"} in more than one assistant message. ` +
48
53
  "The request was not sent.");
49
54
  }
55
+ const EMPTY_TOOL_CALL_ID_BASE = "call";
56
+ function uniqueToolCallId(original, turn, used) {
57
+ const base = `${original || EMPTY_TOOL_CALL_ID_BASE}_${turn}`;
58
+ let candidate = base;
59
+ for (let attempt = 1; used.has(candidate); attempt++)
60
+ candidate = `${base}_${attempt}`;
61
+ return candidate;
62
+ }
63
+ function needsToolCallRename(blocks, used) {
64
+ const seen = new Set();
65
+ for (const { id } of blocks) {
66
+ if (id === "" || used.has(id) || seen.has(id))
67
+ return true;
68
+ seen.add(id);
69
+ }
70
+ return false;
71
+ }
72
+ /**
73
+ * Give every tool call a non-empty id that no earlier call in the context uses.
74
+ *
75
+ * A reused or empty id is renamed after its assistant turn, and the tool results
76
+ * following that turn (up to the next assistant message) are renamed with it in
77
+ * call order. Renaming depends only on earlier messages, so the derived ids stay
78
+ * stable as the conversation grows and do not invalidate provider prompt caches.
79
+ * Messages that need no change are returned as the same objects.
80
+ */
81
+ export function uniquifyToolCallIds(messages) {
82
+ const used = new Set();
83
+ let renamedResultIds;
84
+ let changed = false;
85
+ let turn = 0;
86
+ const uniquified = messages.map((message) => {
87
+ if (message.role === "assistant") {
88
+ turn++;
89
+ renamedResultIds = undefined;
90
+ const blocks = toolCallBlocks(message);
91
+ if (!needsToolCallRename(blocks, used)) {
92
+ for (const block of blocks)
93
+ used.add(block.id);
94
+ return message;
95
+ }
96
+ const pairing = new Map();
97
+ const content = message.content.map((block) => {
98
+ if (!isToolCallBlock(block))
99
+ return block;
100
+ const id = block.id !== "" && !used.has(block.id) ? block.id : uniqueToolCallId(block.id, turn, used);
101
+ used.add(id);
102
+ pairing.set(block.id, [...(pairing.get(block.id) ?? []), id]);
103
+ return id === block.id ? block : { ...block, id };
104
+ });
105
+ renamedResultIds = pairing;
106
+ changed = true;
107
+ return { ...message, content };
108
+ }
109
+ if (message.role !== "toolResult" || !renamedResultIds)
110
+ return message;
111
+ const toolCallId = message.toolCallId;
112
+ if (typeof toolCallId !== "string")
113
+ return message;
114
+ const id = renamedResultIds.get(toolCallId)?.shift();
115
+ if (id === undefined || id === toolCallId)
116
+ return message;
117
+ return { ...message, toolCallId: id };
118
+ });
119
+ return changed ? uniquified : messages;
120
+ }
50
121
  //# sourceMappingURL=context-tool-pairing.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"context-tool-pairing.js","sourceRoot":"","sources":["../../src/core/context-tool-pairing.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,wBAAwB,CAAC,QAAiC;IACzE,MAAM,IAAI,GAAG,IAAI,GAAG,EAAU,CAAC;IAC/B,MAAM,UAAU,GAAG,IAAI,GAAG,EAAU,CAAC;IACrC,KAAK,MAAM,OAAO,IAAI,QAAQ,EAAE,CAAC;QAChC,IAAI,OAAO,CAAC,IAAI,KAAK,WAAW;YAAE,SAAS;QAC3C,IAAK,OAA4C,CAAC,kBAAkB,KAAK,IAAI;YAAE,SAAS;QACxF,MAAM,OAAO,GAAI,OAAiC,CAAC,OAAO,CAAC;QAC3D,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC;YAAE,SAAS;QACtC,KAAK,MAAM,KAAK,IAAI,OAAO,EAAE,CAAC;YAC7B,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ;gBAAE,SAAS;YAClD,MAAM,SAAS,GAAG,KAAyC,CAAC;YAC5D,IAAI,SAAS,CAAC,IAAI,KAAK,UAAU,IAAI,OAAO,SAAS,CAAC,EAAE,KAAK,QAAQ;gBAAE,SAAS;YAChF,IAAI,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC;gBAAE,UAAU,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;;gBACpD,IAAI,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE,CAAC,CAAC;QAC7B,CAAC;IACF,CAAC;IACD,OAAO,CAAC,GAAG,UAAU,CAAC,CAAC;AACxB,CAAC;AAED,oFAAoF;AACpF,MAAM,UAAU,0BAA0B,CAAC,QAAiC;IAC3E,MAAM,UAAU,GAAG,wBAAwB,CAAC,QAAQ,CAAC,CAAC;IACtD,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO;IACpC,MAAM,MAAM,GAAG,UAAU,CAAC,MAAM,GAAG,CAAC,CAAC;IACrC,MAAM,IAAI,KAAK,CACd,+DAA+D,MAAM,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,GAAG;QACtF,GAAG,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,SAAS,uCAAuC;QAChG,2BAA2B,CAC5B,CAAC;AACH,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\n\n/**\n * Structural tool-pairing guard for provider-bound context.\n *\n * `repairOrphanToolResults` already collapses the recoverable forms of this\n * invariant at conversion time: orphaned or duplicate `tool_result` blocks and\n * tool calls interrupted before their result was persisted. None need to reach\n * the provider.\n *\n * A `tool_use` id announced by more than one assistant message is a different\n * problem. It means the transcript itself carries the same assistant turn twice,\n * so there is no safe repair — dropping either copy guesses at which tool results\n * belong to it. The provider answers that with an opaque 400 that kills the turn,\n * so fail here instead, naming the ids.\n */\nexport function findDuplicateToolCallIds(messages: readonly AgentMessage[]): string[] {\n\tconst seen = new Set<string>();\n\tconst duplicates = new Set<string>();\n\tfor (const message of messages) {\n\t\tif (message.role !== \"assistant\") continue;\n\t\tif ((message as { excludeFromContext?: boolean }).excludeFromContext === true) continue;\n\t\tconst content = (message as { content?: unknown }).content;\n\t\tif (!Array.isArray(content)) continue;\n\t\tfor (const block of content) {\n\t\t\tif (!block || typeof block !== \"object\") continue;\n\t\t\tconst candidate = block as { type?: unknown; id?: unknown };\n\t\t\tif (candidate.type !== \"toolCall\" || typeof candidate.id !== \"string\") continue;\n\t\t\tif (seen.has(candidate.id)) duplicates.add(candidate.id);\n\t\t\telse seen.add(candidate.id);\n\t\t}\n\t}\n\treturn [...duplicates];\n}\n\n/** Throw a descriptive error when context carries a tool call id more than once. */\nexport function assertToolPairingInvariant(messages: readonly AgentMessage[]): void {\n\tconst duplicates = findDuplicateToolCallIds(messages);\n\tif (duplicates.length === 0) return;\n\tconst plural = duplicates.length > 1;\n\tthrow new Error(\n\t\t`Context is structurally invalid for the provider: tool call ${plural ? \"ids\" : \"id\"} ` +\n\t\t\t`${duplicates.join(\", \")} ${plural ? \"appear\" : \"appears\"} in more than one assistant message. ` +\n\t\t\t\"The request was not sent.\",\n\t);\n}\n"]}
1
+ {"version":3,"file":"context-tool-pairing.js","sourceRoot":"","sources":["../../src/core/context-tool-pairing.ts"],"names":[],"mappings":"AA6BA,SAAS,eAAe,CAAC,KAAc;IACtC,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACtD,MAAM,SAAS,GAAG,KAAyC,CAAC;IAC5D,OAAO,SAAS,CAAC,IAAI,KAAK,UAAU,IAAI,OAAO,SAAS,CAAC,EAAE,KAAK,QAAQ,CAAC;AAC1E,CAAC;AAED,SAAS,cAAc,CAAC,OAAqB;IAC5C,MAAM,OAAO,GAAI,OAAiC,CAAC,OAAO,CA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K,SAAS,IAAI,EAAE,KAAK,UAAU;YAAE,OAAO,OAAO,CAAC;QAC1D,OAAO,EAAE,GAAG,OAAO,EAAE,UAAU,EAAE,EAAE,EAAc,CAAC;IACnD,CAAC,CAAC,CAAC;IACH,OAAO,OAAO,CAAC,CAAC,CAAC,UAAU,CAAC,CAAC,CAAC,QAAQ,CAAC;AACxC,CAAC","sourcesContent":["import type { AgentMessage } from \"@earendil-works/pi-agent-core\";\n\n/**\n * Structural tool-pairing guard and repair for provider-bound context.\n *\n * `repairOrphanToolResults` already collapses the recoverable forms of this\n * invariant at conversion time: orphaned or duplicate `tool_result` blocks and\n * tool calls interrupted before their result was persisted. None need to reach\n * the provider.\n *\n * Some models (Kimi numbers calls `bash:0`, `bash:1`, … from zero in every\n * response) or providers (no id at all) reuse a tool call id across separate\n * assistant turns. Each turn's results follow it directly, so pairing by\n * position is unambiguous: `uniquifyToolCallIds` renames the reused ids in\n * derived context and leaves the transcript untouched.\n *\n * The same assistant turn appearing twice is a different problem. The transcript\n * itself is corrupt (#2051), so there is no safe repair — dropping either copy\n * guesses at which tool results belong to it. The provider answers that with an\n * opaque 400 that kills the turn, so fail here instead, naming the ids.\n */\n\ninterface ToolCallBlock {\n\ttype: \"toolCall\";\n\tid: string;\n\tname?: unknown;\n\targuments?: unknown;\n}\n\nfunction isToolCallBlock(block: unknown): block is ToolCallBlock {\n\tif (!block || typeof block !== \"object\") return false;\n\tconst candidate = block as { type?: unknown; id?: unknown };\n\treturn candidate.type === \"toolCall\" && typeof candidate.id === \"string\";\n}\n\nfunction toolCallBlocks(message: AgentMessage): ToolCallBlock[] {\n\tconst content = (message as { content?: unknown }).content;\n\treturn Array.isArray(content) ? content.filter(isToolCallBlock) : [];\n}\n\nfunction responseId(message: AgentMessage): string | undefined {\n\tconst id = (message as { responseId?: unknown }).responseId;\n\treturn typeof id === \"string\" && id !== \"\" ? id : undefined;\n}\n\nfunction isSameAssistantTurn(first: AgentMessage, second: AgentMessage): boolean {\n\tif (first === second) return true;\n\tconst firstResponse = responseId(first);\n\tconst secondResponse = responseId(second);\n\tif (firstResponse !== undefined && secondResponse !== undefined) return firstResponse === secondResponse;\n\treturn first.timestamp === second.timestamp && JSON.stringify(first) === JSON.stringify(second);\n}\n\nexport function findDuplicateToolCallIds(messages: readonly AgentMessage[]): string[] {\n\tconst announcers = new Map<string, AgentMessage[]>();\n\tconst duplicates = new Set<string>();\n\tfor (const message of messages) {\n\t\tif (message.role !== \"assistant\") continue;\n\t\tif ((message as { excludeFromContext?: boolean }).excludeFromContext === true) continue;\n\t\tfor (const id of new Set(toolCallBlocks(message).map((block) => block.id))) {\n\t\t\tconst previous = announcers.get(id);\n\t\t\tif (!previous) {\n\t\t\t\tannouncers.set(id, [message]);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (previous.some((earlier) => isSameAssistantTurn(earlier, message))) duplicates.add(id);\n\t\t\tprevious.push(message);\n\t\t}\n\t}\n\treturn [...duplicates];\n}\n\n/** Throw a descriptive error when context carries the same assistant turn more than once. */\nexport function assertToolPairingInvariant(messages: readonly AgentMessage[]): void {\n\tconst duplicates = findDuplicateToolCallIds(messages);\n\tif (duplicates.length === 0) return;\n\tconst plural = duplicates.length > 1;\n\tthrow new Error(\n\t\t`Context is structurally invalid for the provider: tool call ${plural ? \"ids\" : \"id\"} ` +\n\t\t\t`${duplicates.join(\", \")} ${plural ? \"appear\" : \"appears\"} in more than one assistant message. ` +\n\t\t\t\"The request was not sent.\",\n\t);\n}\n\nconst EMPTY_TOOL_CALL_ID_BASE = \"call\";\n\nfunction uniqueToolCallId(original: string, turn: number, used: ReadonlySet<string>): string {\n\tconst base = `${original || EMPTY_TOOL_CALL_ID_BASE}_${turn}`;\n\tlet candidate = base;\n\tfor (let attempt = 1; used.has(candidate); attempt++) candidate = `${base}_${attempt}`;\n\treturn candidate;\n}\n\nfunction needsToolCallRename(blocks: readonly ToolCallBlock[], used: ReadonlySet<string>): boolean {\n\tconst seen = new Set<string>();\n\tfor (const { id } of blocks) {\n\t\tif (id === \"\" || used.has(id) || seen.has(id)) return true;\n\t\tseen.add(id);\n\t}\n\treturn false;\n}\n\n/**\n * Give every tool call a non-empty id that no earlier call in the context uses.\n *\n * A reused or empty id is renamed after its assistant turn, and the tool results\n * following that turn (up to the next assistant message) are renamed with it in\n * call order. Renaming depends only on earlier messages, so the derived ids stay\n * stable as the conversation grows and do not invalidate provider prompt caches.\n * Messages that need no change are returned as the same objects.\n */\nexport function uniquifyToolCallIds<TMessage extends AgentMessage>(messages: TMessage[]): TMessage[] {\n\tconst used = new Set<string>();\n\tlet renamedResultIds: Map<string, string[]> | undefined;\n\tlet changed = false;\n\tlet turn = 0;\n\tconst uniquified = messages.map((message): TMessage => {\n\t\tif (message.role === \"assistant\") {\n\t\t\tturn++;\n\t\t\trenamedResultIds = undefined;\n\t\t\tconst blocks = toolCallBlocks(message);\n\t\t\tif (!needsToolCallRename(blocks, used)) {\n\t\t\t\tfor (const block of blocks) used.add(block.id);\n\t\t\t\treturn message;\n\t\t\t}\n\t\t\tconst pairing = new Map<string, string[]>();\n\t\t\tconst content = (message as { content: unknown[] }).content.map((block) => {\n\t\t\t\tif (!isToolCallBlock(block)) return block;\n\t\t\t\tconst id = block.id !== \"\" && !used.has(block.id) ? block.id : uniqueToolCallId(block.id, turn, used);\n\t\t\t\tused.add(id);\n\t\t\t\tpairing.set(block.id, [...(pairing.get(block.id) ?? []), id]);\n\t\t\t\treturn id === block.id ? block : { ...block, id };\n\t\t\t});\n\t\t\trenamedResultIds = pairing;\n\t\t\tchanged = true;\n\t\t\treturn { ...message, content } as TMessage;\n\t\t}\n\t\tif (message.role !== \"toolResult\" || !renamedResultIds) return message;\n\t\tconst toolCallId = (message as { toolCallId?: unknown }).toolCallId;\n\t\tif (typeof toolCallId !== \"string\") return message;\n\t\tconst id = renamedResultIds.get(toolCallId)?.shift();\n\t\tif (id === undefined || id === toolCallId) return message;\n\t\treturn { ...message, toolCallId: id } as TMessage;\n\t});\n\treturn changed ? u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AAE,MAAM,GACxB,0BAA0B,CAY5B;AA2BD;;;;;;;;GAQG;AACH,wBAAgB,qCAAqC,CAAC,QAAQ,SAAS,YAAY,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,QAAQ,EAAE,CAuCrH;AAED;;;;;;;;;;GAUG;AACH,MAAM,WAAW,yBAAyB;IACzC,6EAA6E;IAC7E,cAAc,CAAC,EAAE,OAAO,CAAC;CACzB;AAED,wBAAgB,uBAAuB,CAAC,QAAQ,SAAS,YAAY,EACpE,QAAQ,EAAE,QAAQ,EAAE,EACpB,OAAO,GAAE,yBAA8B,GACrC,CAAC,QAAQ,GAAG,iBAAiB,CAAC,EAAE,CAsElC;AAED;;;;;;;GAOG;AACH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,OAAO,EAAE,CAkDhE"}
@@ -4,6 +4,7 @@
4
4
  * Extends the base AgentMessage type with coding-agent specific message types,
5
5
  * and provides a transformer to convert them to LLM-compatible messages.
6
6
  */
7
+ import { uniquifyToolCallIds } from "./context-tool-pairing.js";
7
8
  export const BRANCH_SUMMARY_PREFIX = `The following is a summary of a branch that this conversation came back from:
8
9
 
9
10
  <summary>
@@ -373,6 +374,6 @@ export function convertToLlm(messages) {
373
374
  }
374
375
  })
375
376
  .filter((m) => m !== undefined);
376
- return repairOrphanToolResults(converted);
377
+ return repairOrphanToolResults(uniquifyToolCallIds(converted));
377
378
  }
378
379
  //# sourceMappingURL=messages.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"messages.js","sourceRoot":"","sources":["../../src/core/messages.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAKH,MAAM,CAAC,MAAM,qBAAqB,GAAG;;;CAGpC,CAAC;AAEF,MAAM,CAAC,MAAM,qBAAqB,GAAG,YAAY,CAAC;AAsDlD,4FAA4F;AAC5F,MAAM,UAAU,uBAAuB,CAAyB,OAAU;IACzE,QAAQ,OAAO,CAAC,IAAI,EAAE,CAAC;QACtB,KAAK,MAAM,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;YACH,KAAK,MAAM,EAAE,CAAC;gBACb,IAAI,CAAC,wBAAwB,CAAC,CAAC,CAAC;oBAAE,OAAO,SAAS,CAAC;gBACnD,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,OAAO,CAAC;oBAAE,OAAO,CAAC,CAAC;gBACxC,OAAO,EAAE,GAAG,CAAC,EAAE,OAAO,EAAE,2BAA2B,CAAC,CAAC,CAAC,OAAO,CAAC,EAAa,CAAC;YAC7E,CAAC;YACD,KAAK,QAAQ;gBACZ,OAAO,CAAC,CAAC;YACV,KAAK,WAAW,CAAC;YACjB,KAAK,YAAY;gBAChB,OAAO,CAAC,CAAC;YACV,KAAK,mBAAmB;gBACvB,iFAAiF;gBACjF,OAAO,SAAS,CAAC;YAClB,SAAS,CAAC;gBACT,2FAA2F;gBAC3F,MAAM,gBAAgB,GAAU,CAAC,CAAC;gBAClC,KAAK,gBAAgB,CAAC;gBACtB,OAAO,SAAS,CAAC;YAClB,CAAC;QACF,CAAC;IACF,CAAC,CAAC;SACD,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC;IACjC,OAAO,uBAAuB,CAAC,SAAS,CAAC,CAAC;AAC3C,CAAC","sourcesContent":["/**\n * Custom message types and transformers for the coding agent.\n *\n * Extends the base AgentMessage type with coding-agent specific message types,\n * and provides a transformer to convert them to LLM-compatible messages.\n */\n\nimport type { ImageContent, Message, TextContent, ToolResultMessage } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\n\nexport const BRANCH_SUMMARY_PREFIX = `The following is a summary of a branch that this conversation came back from:\n\n<summary>\n`;\n\nexport const BRANCH_SUMMARY_SUFFIX = `</summary>`;\n\n/**\n * Message type for bash executions via the ! command.\n */\nexport interface BashExecutionMessage {\n\trole: \"bashExecution\";\n\tcommand: string;\n\toutput: string;\n\texitCode: number | undefined;\n\tcancelled: boolean;\n\ttruncated: boolean;\n\tfullOutputPath?: string;\n\ttimestamp: number;\n\t/** If true, this message is excluded from LLM context (!! prefix) */\n\texcludeFromContext?: boolean;\n}\n\n/**\n * Message type for extension-injected messages via sendMessage().\n * These are custom messages that extensions can inject into the conversation.\n */\n\nexport interface CustomMessage<T = unknown> {\n\trole: \"custom\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdisplay: boolean;\n\tdetails?: T;\n\ttimestamp: number;\n}\n\nexport type StageAdmittedCustomMessage<T = unknown> = CustomMessage<T> & {\n\t/** Stable producer identity used for exactly-once workflow-stage admission. */\n\tstageAdmissionKey?: string;\n\t/** Whether this admission joined active stage work or started after the assistant had settled. */\n};\n\nexport interface BranchSummaryMessage {\n\trole: \"branchSummary\";\n\tsummary: string;\n\tfromId: string | null;\n\ttimestamp: number;\n}\n\n// Extend CustomAgentMessages via declaration merging\ndeclare module \"@earendil-works/pi-agent-core\" {\n\tinterface CustomAgentMessages {\n\t\tbashExecution: BashExecutionMessage;\n\t\tcustom: CustomMessage;\n\t\tbranchSummary: BranchSummaryMessage;\n\t}\n}\n\n/** Normalize lax JavaScript/legacy message input before it reaches history or providers. */\nexport function normalizeMessageContent<T extends AgentMessage>(message: T): T {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\tcase \"assistant\":\n\t\tcase \"toolResult\":\n\t\tcase \"custom\":\n\t\t\treturn message.content == null ? ({ ...message, content: [] } as T) : message;\n\t\tdefault:\n\t\t\treturn message;\n\t}\n}\n\nexport function userLikeContentBlockIsLlmVisible(block: unknown): boolean {\n\tif (!block || typeof block !== \"object\") return false;\n\tconst candidate = block as { type?: unknown; text?: unknown };\n\tif (candidate.type === \"image\") return true;\n\tif (candidate.type === \"text\") return typeof candidate.text === \"string\" && candidate.text.trim().length > 0;\n\t// Future provider-supported blocks must fail visible; only malformed/untyped blocks fail closed.\n\treturn typeof candidate.type === \"string\" && candidate.type.trim().length > 0;\n}\n\n/** Whether user/custom content survives provider conversion as a visible input. */\nexport function userLikeContentIsLlmVisible(\n\tcontent: unknown,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tif (typeof content === \"string\") return content.trim().length > 0;\n\tif (!Array.isArray(content)) return false;\n\treturn content.some((block, index) => !deletedBlockIndexes.has(index) && userLikeContentBlockIsLlmVisible(block));\n}\n\n/** Whether an Atomic message emits an LLM-visible user-like turn boundary. */\nexport function messageStartsLlmUserTurn(\n\tmessage: AgentMessage,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\t\treturn userLikeContentIsLlmVisible(message.content, deletedBlockIndexes);\n\t\tcase \"custom\":\n\t\t\treturn (\n\t\t\t\t(message as CustomMessage & { excludeFromContext?: boolean }).excludeFromContext !== true &&\n\t\t\t\tuserLikeContentIsLlmVisible(message.content, deletedBlockIndexes)\n\t\t\t);\n\t\tcase \"branchSummary\":\n\t\t\t// Empty summaries are omitted by session reconstruction. Whitespace is\n\t\t\t// visible because the branch-summary wrapper itself is non-whitespace.\n\t\t\treturn typeof message.summary === \"string\" && message.summary.length > 0;\n\t\tcase \"bashExecution\":\n\t\t\treturn message.excludeFromContext !== true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n/** Whether an Atomic message survives conversion into provider-visible context. */\nexport function messageIsLlmVisible(\n\tmessage: AgentMessage,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tif (message.role === \"system\" || message.role === \"assistant\" || message.role === \"toolResult\") return true;\n\treturn messageStartsLlmUserTurn(message, deletedBlockIndexes);\n}\n\n/** Filter invalid user-like blocks only in transient provider-bound content. */\nfunction filterUserLikeContentBlocks(content: unknown[]): unknown[] {\n\treturn content.filter(userLikeContentBlockIsLlmVisible);\n}\n\n/** Normalize raw blocks only in the transient LLM-compatible message returned by convertToLlm. */\nfunction normalizeRawRedactedThinking(message: AgentMessage): AgentMessage {\n\tif (message.role !== \"assistant\" || !Array.isArray(message.content)) return message;\n\tlet changed = false;\n\tconst content = message.content.map((block) => {\n\t\tif (!block || typeof block !== \"object\") return block;\n\t\tconst candidate = block as { type?: unknown; data?: unknown };\n\t\tif (candidate.type !== \"redacted_thinking\" || typeof candidate.data !== \"string\") return block;\n\t\tchanged = true;\n\t\treturn {\n\t\t\ttype: \"thinking\" as const,\n\t\t\tthinking: \"\",\n\t\t\tthinkingSignature: candidate.data,\n\t\t\tredacted: true,\n\t\t};\n\t});\n\treturn changed ? ({ ...message, content } as AgentMessage) : message;\n}\n\n/**\n * Convert a BashExecutionMessage to user message text for LLM context.\n */\nexport function bashExecutionToText(msg: BashExecutionMessage): string {\n\tlet text = `Ran \\`${msg.command}\\`\\n`;\n\tif (msg.output) {\n\t\ttext += `\\`\\`\\`\\n${msg.output}\\n\\`\\`\\``;\n\t} else {\n\t\ttext += \"(no output)\";\n\t}\n\tif (msg.cancelled) {\n\t\ttext += \"\\n\\n(command cancelled)\";\n\t} else if (msg.exitCode !== null && msg.exitCode !== undefined && msg.exitCode !== 0) {\n\t\ttext += `\\n\\nCommand exited with code ${msg.exitCode}`;\n\t}\n\tif (msg.truncated && msg.fullOutputPath) {\n\t\ttext += `\\n\\n[Output truncated. Full output: ${msg.fullOutputPath}]`;\n\t}\n\treturn text;\n}\n\nexport const VERBATIM_COMPACTION_PREFIX =\n\t'The earlier conversation was compacted. Below is the verbatim transcript of the retained lines; elided spans are marked \"(filtered N lines)\".\\n\\n';\nconst verbatimCompactionMessages = new WeakSet<CustomMessage>();\n\nexport function isVerbatimCompactionMessage(message: CustomMessage): boolean {\n\treturn verbatimCompactionMessages.has(message);\n}\n\n/**\n * Create the visible custom-role boundary used to replay a verbatim compaction.\n *\n * `retainedTail` holds the serialized kept tail. Its text merges into the boundary text and\n * its image blocks stay intact, so preserved content is not reduced to a placeholder.\n */\nexport function createVerbatimCompactionMessage(\n\tcompactedText: string,\n\ttokensBefore: number,\n\ttimestamp: string,\n\tdetails?: unknown,\n\tretainedTail?: readonly (TextContent | ImageContent)[],\n): CustomMessage {\n\tconst content: (TextContent | ImageContent)[] = [{ type: \"text\", text: VERBATIM_COMPACTION_PREFIX + compactedText }];\n\tfor (const block of retainedTail ?? []) {\n\t\tconst last = content[content.length - 1];\n\t\tif (block.type === \"text\" && last.type === \"text\") last.text += block.text;\n\t\telse content.push({ ...block });\n\t}\n\t// Ensure the authoritative whole-context count survives on the message details so\n\t// the boundary renderer can show it even when the caller supplied its own details\n\t// object. An existing tokensBefore is never overridden (#2052).\n\tconst mergedDetails = (() => {\n\t\tif (details === undefined) return { tokensBefore };\n\t\tif (typeof details !== \"object\" || details === null) return details;\n\t\treturn \"tokensBefore\" in details ? details : { ...details, tokensBefore };\n\t})();\n\tconst message = createCustomMessage(\"compaction\", content, true, mergedDetails, timestamp);\n\tverbatimCompactionMessages.add(message);\n\treturn message;\n}\n\nexport function createBranchSummaryMessage(summary: string, fromId: string, timestamp: string): BranchSummaryMessage {\n\treturn {\n\t\trole: \"branchSummary\",\n\t\tsummary,\n\t\tfromId,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n}\n\n/** Convert CustomMessageEntry to AgentMessage format */\nexport function createCustomMessage(\n\tcustomType: string,\n\tcontent: string | (TextContent | ImageContent)[],\n\tdisplay: boolean,\n\tdetails: unknown | undefined,\n\ttimestamp: string,\n\texcludeFromContext?: boolean,\n\tstageAdmissionKey?: string,\n): StageAdmittedCustomMessage {\n\tconst message: StageAdmittedCustomMessage & { excludeFromContext?: boolean } = {\n\t\trole: \"custom\",\n\t\tcustomType,\n\t\tcontent: content ?? [],\n\t\tdisplay,\n\t\tdetails,\n\t\t...(stageAdmissionKey === undefined ? {} : { stageAdmissionKey }),\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n\tif (excludeFromContext === true) message.excludeFromContext = true;\n\treturn message;\n}\n\ninterface AssistantToolCallRef {\n\tid: string;\n\tname: string;\n}\n\nfunction collectAssistantToolCalls(message: AgentMessage): AssistantToolCallRef[] {\n\tconst content = (message as { content?: unknown }).content;\n\tconst calls: AssistantToolCallRef[] = [];\n\tif (!Array.isArray(content)) return calls;\n\tfor (const block of content) {\n\t\tif (!block || typeof block !== \"object\") continue;\n\t\tconst candidate = block as { type?: unknown; id?: unknown; name?: unknown };\n\t\tif (candidate.type === \"toolCall\" && typeof candidate.id === \"string\" && typeof candidate.name === \"string\") {\n\t\t\tcalls.push({ id: candidate.id, name: candidate.name });\n\t\t}\n\t}\n\treturn calls;\n}\n\nfunction getToolResultCallId(message: AgentMessage): string | undefined {\n\tif (message.role !== \"toolResult\") return undefined;\n\tconst toolCallId = (message as { toolCallId?: unknown }).toolCallId;\n\treturn typeof toolCallId === \"string\" ? toolCallId : undefined;\n}\n\n/**\n * Keep every tool result adjacent to the assistant turn that announced it.\n *\n * A message admitted while a tool batch is still running (an Intercom delivery, a\n * workflow lifecycle card, a durable stage admission) is persisted between the tool\n * call and its result in raw history. The provider requires the results to follow the\n * call directly, so derived context defers such messages until the batch is answered.\n * The durable transcript keeps its admission order.\n */\nexport function deferMessagesInterleavedWithToolBatch<TMessage extends AgentMessage>(messages: TMessage[]): TMessage[] {\n\tlet pending: Set<string> | undefined;\n\tlet deferred: TMessage[] = [];\n\tlet changed = false;\n\tconst ordered: TMessage[] = [];\n\tconst flushDeferred = (): void => {\n\t\tif (deferred.length > 0) {\n\t\t\tordered.push(...deferred);\n\t\t\tdeferred = [];\n\t\t}\n\t\tpending = undefined;\n\t};\n\tfor (const message of messages) {\n\t\tif (message.role === \"assistant\") {\n\t\t\tflushDeferred();\n\t\t\tordered.push(message);\n\t\t\tconst calls = collectAssistantToolCalls(message);\n\t\t\tpending =\n\t\t\t\tmessage.stopReason === \"toolUse\" && calls.length > 0 ? new Set(calls.map((call) => call.id)) : undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (pending) {\n\t\t\tconst toolCallId = getToolResultCallId(message);\n\t\t\tif (toolCallId !== undefined && pending.has(toolCallId)) {\n\t\t\t\tordered.push(message);\n\t\t\t\tpending.delete(toolCallId);\n\t\t\t\tif (pending.size === 0) flushDeferred();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (message.role !== \"system\") {\n\t\t\t\tdeferred.push(message);\n\t\t\t\tchanged = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tordered.push(message);\n\t}\n\tflushDeferred();\n\treturn changed ? ordered : messages;\n}\n\n/**\n * Enforce the provider's tool-pairing invariant on a converted message list.\n *\n * A provider rejects orphaned/duplicate `tool_result` blocks and any later turn\n * that crosses an unanswered `tool_use`. Keep exactly the first result for each\n * announced id. If a persisted session continues after its engine died before\n * recording every result, insert provider-only error results before that later\n * turn. The repair exists only in derived context; the durable transcript stays\n * unchanged, and the text makes no claim about whether admitted work completed\n * or produced side effects.\n */\nexport interface ToolCallPairRepairOptions {\n\t/** Close a final unanswered tool call when reopening an inactive session. */\n\trepairTrailing?: boolean;\n}\n\nexport function repairOrphanToolResults<TMessage extends AgentMessage>(\n\tmessages: TMessage[],\n\toptions: ToolCallPairRepairOptions = {},\n): (TMessage | ToolResultMessage)[] {\n\tlet allowedToolCallIds: Set<string> | undefined;\n\tlet answeredToolCallIds: Set<string> | undefined;\n\tlet pendingToolCalls: AssistantToolCallRef[] = [];\n\tlet pendingTimestamp = 0;\n\tlet changed = false;\n\tconst repaired: (TMessage | ToolResultMessage)[] = [];\n\tconst flushUnanswered = (): void => {\n\t\tfor (const call of pendingToolCalls) {\n\t\t\tif (answeredToolCallIds?.has(call.id)) continue;\n\t\t\tconst interrupted: ToolResultMessage = {\n\t\t\t\trole: \"toolResult\",\n\t\t\t\ttoolCallId: call.id,\n\t\t\t\ttoolName: call.name,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Tool execution was interrupted after it started; its result is unavailable. Inspect side effects before deciding whether to retry it.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tisError: true,\n\t\t\t\ttimestamp: pendingTimestamp,\n\t\t\t};\n\t\t\trepaired.push(interrupted);\n\t\t\tchanged = true;\n\t\t}\n\t\tallowedToolCallIds = undefined;\n\t\tansweredToolCallIds = undefined;\n\t\tpendingToolCalls = [];\n\t};\n\tfor (const message of messages) {\n\t\t// Instruction/tool updates never close a pending tool batch.\n\t\tif (message.role === \"system\") {\n\t\t\trepaired.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role === \"assistant\") {\n\t\t\tflushUnanswered();\n\t\t\tconst announcedToolCalls = collectAssistantToolCalls(message);\n\t\t\t// Only toolUse turns represent admitted executions. Error, aborted, and\n\t\t\t// length-limited turns may contain partial calls that providers discard.\n\t\t\tpendingToolCalls = message.stopReason === \"toolUse\" ? announcedToolCalls : [];\n\t\t\tallowedToolCallIds = new Set(announcedToolCalls.map((call) => call.id));\n\t\t\tansweredToolCallIds = new Set<string>();\n\t\t\tpendingTimestamp = message.timestamp;\n\t\t\trepaired.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst toolCallId = getToolResultCallId(message);\n\t\t\tif (toolCallId && allowedToolCallIds?.has(toolCallId) && answeredToolCallIds?.has(toolCallId) === false) {\n\t\t\t\tansweredToolCallIds.add(toolCallId);\n\t\t\t\trepaired.push(message);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tchanged = true;\n\t\t\tcontinue;\n\t\t}\n\t\t// A context-excluded card admitted while a tool was still running sits between\n\t\t// the call and its result in raw history but never reaches the provider, so it\n\t\t// cannot close the pending batch.\n\t\tif (!messageStartsLlmUserTurn(message)) {\n\t\t\trepaired.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tflushUnanswered();\n\t\trepaired.push(message);\n\t}\n\tif (options.repairTrailing) flushUnanswered();\n\treturn changed ? repaired : messages;\n}\n\n/**\n * Transform AgentMessages (including custom types) to LLM-compatible Messages.\n *\n * This is used by:\n * - Agent's transormToLlm option (for prompt calls and queued messages)\n * - Branch summarization (for summarizing abandoned branches)\n * - Custom extensions and tools\n */\nexport function convertToLlm(messages: AgentMessage[]): Message[] {\n\tconst converted = messages\n\t\t.map((rawMessage): Message | undefined => {\n\t\t\tconst m = normalizeRawRedactedThinking(normalizeMessageContent(rawMessage));\n\t\t\tswitch (m.role) {\n\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: bashExecutionToText(m) }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"custom\": {\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\tconst content =\n\t\t\t\t\t\ttypeof m.content === \"string\"\n\t\t\t\t\t\t\t? [{ type: \"text\" as const, text: m.content }]\n\t\t\t\t\t\t\t: (filterUserLikeContentBlocks(m.content) as Message[\"content\"]);\n\t\t\t\t\treturn { role: \"user\", content, timestamp: m.timestamp } as Message;\n\t\t\t\t}\n\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: BRANCH_SUMMARY_PREFIX + m.summary + BRANCH_SUMMARY_SUFFIX }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"user\": {\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\tif (!Array.isArray(m.content)) return m;\n\t\t\t\t\treturn { ...m, content: filterUserLikeContentBlocks(m.content) } as Message;\n\t\t\t\t}\n\t\t\t\tcase \"system\":\n\t\t\t\t\treturn m;\n\t\t\t\tcase \"assistant\":\n\t\t\t\tcase \"toolResult\":\n\t\t\t\t\treturn m;\n\t\t\t\tcase \"compactionSummary\":\n\t\t\t\t\t// Legacy generated summaries remain archival and never enter active LLM context.\n\t\t\t\t\treturn undefined;\n\t\t\t\tdefault: {\n\t\t\t\t\t// Exhaustiveness guard: new AgentMessage roles must define provider conversion explicitly.\n\t\t\t\t\tconst _exhaustiveCheck: never = m;\n\t\t\t\t\tvoid _exhaustiveCheck;\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.filter((m) => m !== undefined);\n\treturn repairOrphanToolResults(converted);\n}\n"]}
1
+ {"version":3,"file":"messages.js","sourceRoot":"","sources":["../../src/core/messages.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAIH,OAAO,EAAE,mBAAmB,EAAE,MAAM,2BAA2B,CAAC;AAEhE,MAAM,CAAC,MAAM,qBAAqB,GAAG;;;CAGpC,CAAC;AAEF,MAAM,CAAC,MAAM,qBAAqB,GAAG,YAAY,CAAC;AAsDlD,4FAA4F;AAC5F,MAAM,UAAU,uBAAuB,CAAyB,OAAU;IACzE,QAAQ,OAAO,CAAC,IAAI,EAAE,CAAC;QACtB,KAAK,MAAM,CAAC;QACZ,KAAK,WAAW,CAAC;QACjB,KAAK,YAAY,CAAC;QAClB,KAAK,QAAQ;YACZ,OAAO,OAAO,CAAC,OAAO,IAAI,IAAI,CAAC,CAAC,CAAE,EAAE,GAAG,OAAO,EAAE,OAAO,EAAE,EAAE,EAAQ,CAAC,CAAC,CAAC,OAAO,CAAC;QAC/E;YACC,OAAO,OAAO,CAAC;IACjB,CAAC;AACF,CAAC;AAED,MAAM,UAAU,gCAAgC,CAAC,KAAc;IAC9D,IAAI,CAAC,KAAK,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACtD,MAAM,SAAS,GAAG,KAA2C,CAAC;IAC9D,IAAI,SAAS,CAAC,IAAI,KAAK,OAAO;QAAE,OAAO,IAAI,CAAC;IAC5C,IAAI,SAAS,CAAC,IAAI,KAAK,MAAM;QAAE,OAAO,OAAO,SAAS,C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AAK,gBAAgB,CAAC;gBACtB,OAAO,SAAS,CAAC;YAClB,CAAC;QACF,CAAC;IACF,CAAC,CAAC;SACD,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC;IACjC,OAAO,uBAAuB,CAAC,mBAAmB,CAAC,SAAS,CAAC,CAAC,CAAC;AAChE,CAAC","sourcesContent":["/**\n * Custom message types and transformers for the coding agent.\n *\n * Extends the base AgentMessage type with coding-agent specific message types,\n * and provides a transformer to convert them to LLM-compatible messages.\n */\n\nimport type { ImageContent, Message, TextContent, ToolResultMessage } from \"@bastani/pi-ai/compat\";\nimport type { AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport { uniquifyToolCallIds } from \"./context-tool-pairing.js\";\n\nexport const BRANCH_SUMMARY_PREFIX = `The following is a summary of a branch that this conversation came back from:\n\n<summary>\n`;\n\nexport const BRANCH_SUMMARY_SUFFIX = `</summary>`;\n\n/**\n * Message type for bash executions via the ! command.\n */\nexport interface BashExecutionMessage {\n\trole: \"bashExecution\";\n\tcommand: string;\n\toutput: string;\n\texitCode: number | undefined;\n\tcancelled: boolean;\n\ttruncated: boolean;\n\tfullOutputPath?: string;\n\ttimestamp: number;\n\t/** If true, this message is excluded from LLM context (!! prefix) */\n\texcludeFromContext?: boolean;\n}\n\n/**\n * Message type for extension-injected messages via sendMessage().\n * These are custom messages that extensions can inject into the conversation.\n */\n\nexport interface CustomMessage<T = unknown> {\n\trole: \"custom\";\n\tcustomType: string;\n\tcontent: string | (TextContent | ImageContent)[];\n\tdisplay: boolean;\n\tdetails?: T;\n\ttimestamp: number;\n}\n\nexport type StageAdmittedCustomMessage<T = unknown> = CustomMessage<T> & {\n\t/** Stable producer identity used for exactly-once workflow-stage admission. */\n\tstageAdmissionKey?: string;\n\t/** Whether this admission joined active stage work or started after the assistant had settled. */\n};\n\nexport interface BranchSummaryMessage {\n\trole: \"branchSummary\";\n\tsummary: string;\n\tfromId: string | null;\n\ttimestamp: number;\n}\n\n// Extend CustomAgentMessages via declaration merging\ndeclare module \"@earendil-works/pi-agent-core\" {\n\tinterface CustomAgentMessages {\n\t\tbashExecution: BashExecutionMessage;\n\t\tcustom: CustomMessage;\n\t\tbranchSummary: BranchSummaryMessage;\n\t}\n}\n\n/** Normalize lax JavaScript/legacy message input before it reaches history or providers. */\nexport function normalizeMessageContent<T extends AgentMessage>(message: T): T {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\tcase \"assistant\":\n\t\tcase \"toolResult\":\n\t\tcase \"custom\":\n\t\t\treturn message.content == null ? ({ ...message, content: [] } as T) : message;\n\t\tdefault:\n\t\t\treturn message;\n\t}\n}\n\nexport function userLikeContentBlockIsLlmVisible(block: unknown): boolean {\n\tif (!block || typeof block !== \"object\") return false;\n\tconst candidate = block as { type?: unknown; text?: unknown };\n\tif (candidate.type === \"image\") return true;\n\tif (candidate.type === \"text\") return typeof candidate.text === \"string\" && candidate.text.trim().length > 0;\n\t// Future provider-supported blocks must fail visible; only malformed/untyped blocks fail closed.\n\treturn typeof candidate.type === \"string\" && candidate.type.trim().length > 0;\n}\n\n/** Whether user/custom content survives provider conversion as a visible input. */\nexport function userLikeContentIsLlmVisible(\n\tcontent: unknown,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tif (typeof content === \"string\") return content.trim().length > 0;\n\tif (!Array.isArray(content)) return false;\n\treturn content.some((block, index) => !deletedBlockIndexes.has(index) && userLikeContentBlockIsLlmVisible(block));\n}\n\n/** Whether an Atomic message emits an LLM-visible user-like turn boundary. */\nexport function messageStartsLlmUserTurn(\n\tmessage: AgentMessage,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tswitch (message.role) {\n\t\tcase \"user\":\n\t\t\treturn userLikeContentIsLlmVisible(message.content, deletedBlockIndexes);\n\t\tcase \"custom\":\n\t\t\treturn (\n\t\t\t\t(message as CustomMessage & { excludeFromContext?: boolean }).excludeFromContext !== true &&\n\t\t\t\tuserLikeContentIsLlmVisible(message.content, deletedBlockIndexes)\n\t\t\t);\n\t\tcase \"branchSummary\":\n\t\t\t// Empty summaries are omitted by session reconstruction. Whitespace is\n\t\t\t// visible because the branch-summary wrapper itself is non-whitespace.\n\t\t\treturn typeof message.summary === \"string\" && message.summary.length > 0;\n\t\tcase \"bashExecution\":\n\t\t\treturn message.excludeFromContext !== true;\n\t\tdefault:\n\t\t\treturn false;\n\t}\n}\n\n/** Whether an Atomic message survives conversion into provider-visible context. */\nexport function messageIsLlmVisible(\n\tmessage: AgentMessage,\n\tdeletedBlockIndexes: ReadonlySet<number> = new Set<number>(),\n): boolean {\n\tif (message.role === \"system\" || message.role === \"assistant\" || message.role === \"toolResult\") return true;\n\treturn messageStartsLlmUserTurn(message, deletedBlockIndexes);\n}\n\n/** Filter invalid user-like blocks only in transient provider-bound content. */\nfunction filterUserLikeContentBlocks(content: unknown[]): unknown[] {\n\treturn content.filter(userLikeContentBlockIsLlmVisible);\n}\n\n/** Normalize raw blocks only in the transient LLM-compatible message returned by convertToLlm. */\nfunction normalizeRawRedactedThinking(message: AgentMessage): AgentMessage {\n\tif (message.role !== \"assistant\" || !Array.isArray(message.content)) return message;\n\tlet changed = false;\n\tconst content = message.content.map((block) => {\n\t\tif (!block || typeof block !== \"object\") return block;\n\t\tconst candidate = block as { type?: unknown; data?: unknown };\n\t\tif (candidate.type !== \"redacted_thinking\" || typeof candidate.data !== \"string\") return block;\n\t\tchanged = true;\n\t\treturn {\n\t\t\ttype: \"thinking\" as const,\n\t\t\tthinking: \"\",\n\t\t\tthinkingSignature: candidate.data,\n\t\t\tredacted: true,\n\t\t};\n\t});\n\treturn changed ? ({ ...message, content } as AgentMessage) : message;\n}\n\n/**\n * Convert a BashExecutionMessage to user message text for LLM context.\n */\nexport function bashExecutionToText(msg: BashExecutionMessage): string {\n\tlet text = `Ran \\`${msg.command}\\`\\n`;\n\tif (msg.output) {\n\t\ttext += `\\`\\`\\`\\n${msg.output}\\n\\`\\`\\``;\n\t} else {\n\t\ttext += \"(no output)\";\n\t}\n\tif (msg.cancelled) {\n\t\ttext += \"\\n\\n(command cancelled)\";\n\t} else if (msg.exitCode !== null && msg.exitCode !== undefined && msg.exitCode !== 0) {\n\t\ttext += `\\n\\nCommand exited with code ${msg.exitCode}`;\n\t}\n\tif (msg.truncated && msg.fullOutputPath) {\n\t\ttext += `\\n\\n[Output truncated. Full output: ${msg.fullOutputPath}]`;\n\t}\n\treturn text;\n}\n\nexport const VERBATIM_COMPACTION_PREFIX =\n\t'The earlier conversation was compacted. Below is the verbatim transcript of the retained lines; elided spans are marked \"(filtered N lines)\".\\n\\n';\nconst verbatimCompactionMessages = new WeakSet<CustomMessage>();\n\nexport function isVerbatimCompactionMessage(message: CustomMessage): boolean {\n\treturn verbatimCompactionMessages.has(message);\n}\n\n/**\n * Create the visible custom-role boundary used to replay a verbatim compaction.\n *\n * `retainedTail` holds the serialized kept tail. Its text merges into the boundary text and\n * its image blocks stay intact, so preserved content is not reduced to a placeholder.\n */\nexport function createVerbatimCompactionMessage(\n\tcompactedText: string,\n\ttokensBefore: number,\n\ttimestamp: string,\n\tdetails?: unknown,\n\tretainedTail?: readonly (TextContent | ImageContent)[],\n): CustomMessage {\n\tconst content: (TextContent | ImageContent)[] = [{ type: \"text\", text: VERBATIM_COMPACTION_PREFIX + compactedText }];\n\tfor (const block of retainedTail ?? []) {\n\t\tconst last = content[content.length - 1];\n\t\tif (block.type === \"text\" && last.type === \"text\") last.text += block.text;\n\t\telse content.push({ ...block });\n\t}\n\t// Ensure the authoritative whole-context count survives on the message details so\n\t// the boundary renderer can show it even when the caller supplied its own details\n\t// object. An existing tokensBefore is never overridden (#2052).\n\tconst mergedDetails = (() => {\n\t\tif (details === undefined) return { tokensBefore };\n\t\tif (typeof details !== \"object\" || details === null) return details;\n\t\treturn \"tokensBefore\" in details ? details : { ...details, tokensBefore };\n\t})();\n\tconst message = createCustomMessage(\"compaction\", content, true, mergedDetails, timestamp);\n\tverbatimCompactionMessages.add(message);\n\treturn message;\n}\n\nexport function createBranchSummaryMessage(summary: string, fromId: string, timestamp: string): BranchSummaryMessage {\n\treturn {\n\t\trole: \"branchSummary\",\n\t\tsummary,\n\t\tfromId,\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n}\n\n/** Convert CustomMessageEntry to AgentMessage format */\nexport function createCustomMessage(\n\tcustomType: string,\n\tcontent: string | (TextContent | ImageContent)[],\n\tdisplay: boolean,\n\tdetails: unknown | undefined,\n\ttimestamp: string,\n\texcludeFromContext?: boolean,\n\tstageAdmissionKey?: string,\n): StageAdmittedCustomMessage {\n\tconst message: StageAdmittedCustomMessage & { excludeFromContext?: boolean } = {\n\t\trole: \"custom\",\n\t\tcustomType,\n\t\tcontent: content ?? [],\n\t\tdisplay,\n\t\tdetails,\n\t\t...(stageAdmissionKey === undefined ? {} : { stageAdmissionKey }),\n\t\ttimestamp: new Date(timestamp).getTime(),\n\t};\n\tif (excludeFromContext === true) message.excludeFromContext = true;\n\treturn message;\n}\n\ninterface AssistantToolCallRef {\n\tid: string;\n\tname: string;\n}\n\nfunction collectAssistantToolCalls(message: AgentMessage): AssistantToolCallRef[] {\n\tconst content = (message as { content?: unknown }).content;\n\tconst calls: AssistantToolCallRef[] = [];\n\tif (!Array.isArray(content)) return calls;\n\tfor (const block of content) {\n\t\tif (!block || typeof block !== \"object\") continue;\n\t\tconst candidate = block as { type?: unknown; id?: unknown; name?: unknown };\n\t\tif (candidate.type === \"toolCall\" && typeof candidate.id === \"string\" && typeof candidate.name === \"string\") {\n\t\t\tcalls.push({ id: candidate.id, name: candidate.name });\n\t\t}\n\t}\n\treturn calls;\n}\n\nfunction getToolResultCallId(message: AgentMessage): string | undefined {\n\tif (message.role !== \"toolResult\") return undefined;\n\tconst toolCallId = (message as { toolCallId?: unknown }).toolCallId;\n\treturn typeof toolCallId === \"string\" ? toolCallId : undefined;\n}\n\n/**\n * Keep every tool result adjacent to the assistant turn that announced it.\n *\n * A message admitted while a tool batch is still running (an Intercom delivery, a\n * workflow lifecycle card, a durable stage admission) is persisted between the tool\n * call and its result in raw history. The provider requires the results to follow the\n * call directly, so derived context defers such messages until the batch is answered.\n * The durable transcript keeps its admission order.\n */\nexport function deferMessagesInterleavedWithToolBatch<TMessage extends AgentMessage>(messages: TMessage[]): TMessage[] {\n\tlet pending: Set<string> | undefined;\n\tlet deferred: TMessage[] = [];\n\tlet changed = false;\n\tconst ordered: TMessage[] = [];\n\tconst flushDeferred = (): void => {\n\t\tif (deferred.length > 0) {\n\t\t\tordered.push(...deferred);\n\t\t\tdeferred = [];\n\t\t}\n\t\tpending = undefined;\n\t};\n\tfor (const message of messages) {\n\t\tif (message.role === \"assistant\") {\n\t\t\tflushDeferred();\n\t\t\tordered.push(message);\n\t\t\tconst calls = collectAssistantToolCalls(message);\n\t\t\tpending =\n\t\t\t\tmessage.stopReason === \"toolUse\" && calls.length > 0 ? new Set(calls.map((call) => call.id)) : undefined;\n\t\t\tcontinue;\n\t\t}\n\t\tif (pending) {\n\t\t\tconst toolCallId = getToolResultCallId(message);\n\t\t\tif (toolCallId !== undefined && pending.has(toolCallId)) {\n\t\t\t\tordered.push(message);\n\t\t\t\tpending.delete(toolCallId);\n\t\t\t\tif (pending.size === 0) flushDeferred();\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (message.role !== \"system\") {\n\t\t\t\tdeferred.push(message);\n\t\t\t\tchanged = true;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t}\n\t\tordered.push(message);\n\t}\n\tflushDeferred();\n\treturn changed ? ordered : messages;\n}\n\n/**\n * Enforce the provider's tool-pairing invariant on a converted message list.\n *\n * A provider rejects orphaned/duplicate `tool_result` blocks and any later turn\n * that crosses an unanswered `tool_use`. Keep exactly the first result for each\n * announced id. If a persisted session continues after its engine died before\n * recording every result, insert provider-only error results before that later\n * turn. The repair exists only in derived context; the durable transcript stays\n * unchanged, and the text makes no claim about whether admitted work completed\n * or produced side effects.\n */\nexport interface ToolCallPairRepairOptions {\n\t/** Close a final unanswered tool call when reopening an inactive session. */\n\trepairTrailing?: boolean;\n}\n\nexport function repairOrphanToolResults<TMessage extends AgentMessage>(\n\tmessages: TMessage[],\n\toptions: ToolCallPairRepairOptions = {},\n): (TMessage | ToolResultMessage)[] {\n\tlet allowedToolCallIds: Set<string> | undefined;\n\tlet answeredToolCallIds: Set<string> | undefined;\n\tlet pendingToolCalls: AssistantToolCallRef[] = [];\n\tlet pendingTimestamp = 0;\n\tlet changed = false;\n\tconst repaired: (TMessage | ToolResultMessage)[] = [];\n\tconst flushUnanswered = (): void => {\n\t\tfor (const call of pendingToolCalls) {\n\t\t\tif (answeredToolCallIds?.has(call.id)) continue;\n\t\t\tconst interrupted: ToolResultMessage = {\n\t\t\t\trole: \"toolResult\",\n\t\t\t\ttoolCallId: call.id,\n\t\t\t\ttoolName: call.name,\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: \"Tool execution was interrupted after it started; its result is unavailable. Inspect side effects before deciding whether to retry it.\",\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tisError: true,\n\t\t\t\ttimestamp: pendingTimestamp,\n\t\t\t};\n\t\t\trepaired.push(interrupted);\n\t\t\tchanged = true;\n\t\t}\n\t\tallowedToolCallIds = undefined;\n\t\tansweredToolCallIds = undefined;\n\t\tpendingToolCalls = [];\n\t};\n\tfor (const message of messages) {\n\t\t// Instruction/tool updates never close a pending tool batch.\n\t\tif (message.role === \"system\") {\n\t\t\trepaired.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role === \"assistant\") {\n\t\t\tflushUnanswered();\n\t\t\tconst announcedToolCalls = collectAssistantToolCalls(message);\n\t\t\t// Only toolUse turns represent admitted executions. Error, aborted, and\n\t\t\t// length-limited turns may contain partial calls that providers discard.\n\t\t\tpendingToolCalls = message.stopReason === \"toolUse\" ? announcedToolCalls : [];\n\t\t\tallowedToolCallIds = new Set(announcedToolCalls.map((call) => call.id));\n\t\t\tansweredToolCallIds = new Set<string>();\n\t\t\tpendingTimestamp = message.timestamp;\n\t\t\trepaired.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tif (message.role === \"toolResult\") {\n\t\t\tconst toolCallId = getToolResultCallId(message);\n\t\t\tif (toolCallId && allowedToolCallIds?.has(toolCallId) && answeredToolCallIds?.has(toolCallId) === false) {\n\t\t\t\tansweredToolCallIds.add(toolCallId);\n\t\t\t\trepaired.push(message);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tchanged = true;\n\t\t\tcontinue;\n\t\t}\n\t\t// A context-excluded card admitted while a tool was still running sits between\n\t\t// the call and its result in raw history but never reaches the provider, so it\n\t\t// cannot close the pending batch.\n\t\tif (!messageStartsLlmUserTurn(message)) {\n\t\t\trepaired.push(message);\n\t\t\tcontinue;\n\t\t}\n\t\tflushUnanswered();\n\t\trepaired.push(message);\n\t}\n\tif (options.repairTrailing) flushUnanswered();\n\treturn changed ? repaired : messages;\n}\n\n/**\n * Transform AgentMessages (including custom types) to LLM-compatible Messages.\n *\n * This is used by:\n * - Agent's transormToLlm option (for prompt calls and queued messages)\n * - Branch summarization (for summarizing abandoned branches)\n * - Custom extensions and tools\n */\nexport function convertToLlm(messages: AgentMessage[]): Message[] {\n\tconst converted = messages\n\t\t.map((rawMessage): Message | undefined => {\n\t\t\tconst m = normalizeRawRedactedThinking(normalizeMessageContent(rawMessage));\n\t\t\tswitch (m.role) {\n\t\t\t\tcase \"bashExecution\":\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\", text: bashExecutionToText(m) }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"custom\": {\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\tconst content =\n\t\t\t\t\t\ttypeof m.content === \"string\"\n\t\t\t\t\t\t\t? [{ type: \"text\" as const, text: m.content }]\n\t\t\t\t\t\t\t: (filterUserLikeContentBlocks(m.content) as Message[\"content\"]);\n\t\t\t\t\treturn { role: \"user\", content, timestamp: m.timestamp } as Message;\n\t\t\t\t}\n\t\t\t\tcase \"branchSummary\":\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\treturn {\n\t\t\t\t\t\trole: \"user\",\n\t\t\t\t\t\tcontent: [{ type: \"text\" as const, text: BRANCH_SUMMARY_PREFIX + m.summary + BRANCH_SUMMARY_SUFFIX }],\n\t\t\t\t\t\ttimestamp: m.timestamp,\n\t\t\t\t\t};\n\t\t\t\tcase \"user\": {\n\t\t\t\t\tif (!messageStartsLlmUserTurn(m)) return undefined;\n\t\t\t\t\tif (!Array.isArray(m.content)) return m;\n\t\t\t\t\treturn { ...m, content: filterUserLikeContentBlocks(m.content) } as Message;\n\t\t\t\t}\n\t\t\t\tcase \"system\":\n\t\t\t\t\treturn m;\n\t\t\t\tcase \"assistant\":\n\t\t\t\tcase \"toolResult\":\n\t\t\t\t\treturn m;\n\t\t\t\tcase \"compactionSummary\":\n\t\t\t\t\t// Legacy generated summaries remain archival and never enter active LLM context.\n\t\t\t\t\treturn undefined;\n\t\t\t\tdefault: {\n\t\t\t\t\t// Exhaustiveness guard: new AgentMessage roles must define provider conversion explicitly.\n\t\t\t\t\tconst _exhaustiveCheck: never = m;\n\t\t\t\t\tvoid _exhaustiveCheck;\n\t\t\t\t\treturn undefined;\n\t\t\t\t}\n\t\t\t}\n\t\t})\n\t\t.filter((m) => m !== undefined);\n\treturn repairOrphanToolResults(uniquifyToolCallIds(converted));\n}\n"]}
@@ -69,7 +69,7 @@ function buildRules(selectedTools, toolGuidelines, promptGuidelines) {
69
69
  " - When you author a commit, PR, issue, or issue/review comment for a task, record how it ran: `Assistant-workflow: <workflow name> (run <runId>)` for a registered or custom workflow, or `Assistant-workflow: inline` when no workflow was used; and `Assistant-duration: <elapsed> <converged|blocked|abandoned>, estimated <estimate>` (for example `Assistant-duration: 42m converged, estimated 30m`), measuring wall-clock time from launch or task start until acceptance was proven or work stopped, including resumes and repair rounds. Take elapsed time from workflow status timing or timestamps you recorded (for example `date` at task start); write `unmeasured` rather than guess. Put these as trailers alongside `Assistant-model` in commits (git trailers, or the equivalent commit-message metadata in the repository's version control system) and as the same `Key: value` lines in PR/merge request, issue, and comment bodies. For multi-commit work, record the workflow on each commit and the final duration once, in the last commit or the PR body.",
70
70
  " - In the same artifacts, record how the result was verified with one `Assistant-verification: <method> <passed|failed|unavailable>: <what it proved or why>` line per method that actually ran or was attempted (for example `Assistant-verification: herdr terminal E2E passed: /tasks lists running tasks first at 80x24`, `Assistant-verification: vitest unit passed: npm run test:unit`, or `Assistant-verification: cua-driver unavailable: Accessibility permission not granted`). Name the concrete mechanism, such as unit, integration, or E2E tests, agent-browser, Cua Driver, herdr or tmux terminal automation, the qlty CLI, typecheck or lint, or a manual scenario, and the command or scenario it exercised. Record only checks that ran and their observed outcome; never record a skipped, mocked, or planned check as passed.",
71
71
  " - When the user states or reveals a durable preference about how they work (a correction, a rejected approach, scope, review, tooling, or communication style), record it in the same artifacts as `User-preference: <one line, in the user's terms>`, and tie it to the requesting user with a `Co-authored-by: <name> <email>` trailer taken from their version control identity (for example `git config user.name`/`user.email`) unless that line is already present; in PR, issue, and comment bodies, add the same line or their hosting account (for example from `gh api user`). Record only what the user expressed or their own edits show; never record secrets, credentials, or personal details unrelated to the work. If repository rules restrict commit or PR formats, fit the records into what they allow.",
72
- " - Before choosing between a workflow and inline work, choosing how to verify a change, estimating a duration, or interpreting an ambiguous request, mine these records with the rest of the history using the repository's version control system and its hosting CLI, for example `git log --format='%h %an <%ae> %s%n%(trailers:key=Assistant-workflow,key=Assistant-duration,key=Assistant-verification,key=User-preference,key=Co-authored-by)'` with `gh pr list --state all --search 'Assistant-workflow in:body'` on GitHub, or the equivalent commands for other systems and hosts (for example `glab` on GitLab). Compare tasks of similar kind and size, and state the sample size with the median and range. Treat fewer than five comparable records as anecdotal, and prefer the more recent record when two conflict. When choosing verification, start from the methods that proved comparable changes (the same files, subsystem, or kind of change), reuse their commands and scenarios, and do not retry a setup recorded as `unavailable` without a reason to expect a different result; past records never replace the project's required checks. Prioritize preferences tied to the requesting user by their co-author line, commit author, or hosting account. When the user has none that cover the situation, fall back to other contributors' relevant preferences as repository conventions; the user's own records and current request override them, so users can always encode their own preference. This history is a guide, not the decision: the current request, the task itself, and explicit user instructions decide between a workflow and inline work.",
72
+ " - Before choosing between a workflow and inline work, choosing how to verify a change, estimating a duration, or interpreting an ambiguous request, mine these records with the rest of the history using the repository's version control system and its hosting CLI, for example `git log --format='%h %an <%ae> %s%n%(trailers:key=Assistant-workflow,key=Assistant-duration,key=Assistant-verification,key=User-preference,key=Co-authored-by)'` with `gh pr list --state all --search 'Assistant-workflow in:body'` on GitHub, or the equivalent commands for other systems and hosts (for example `glab` on GitLab). Compare tasks of similar kind and size, and state the sample size with the median and range. Treat fewer than five comparable records as anecdotal, and prefer the more recent record when two conflict. When choosing verification, start from the methods that proved comparable changes (the same files, subsystem, or kind of change), reuse their commands and scenarios, and do not retry a setup recorded as `unavailable` without a reason to expect a different result; past records never replace the project's required checks. Prioritize preferences tied to the requesting user by their co-author line, commit author, or hosting account. When the user has none that cover the situation, fall back to other contributors' relevant preferences as repository conventions; the user's own records and current request override them, so users can always encode their own preference. This history is a guide, not the decision: the current request, the task itself, and explicit user instructions decide between a workflow and inline work. Missing, sparse, or mostly inline workflow history is not evidence that the user prefers inline work: records exist only for tasks that wrote them, and past inline runs may reflect an earlier default rather than a choice. Without a recorded or stated preference that covers the situation, judge the task's shape yourself and choose a workflow when it would help, then let comparable records and the user's preferences refine that call.",
73
73
  ].join("\n"));
74
74
  }
75
75
  for (const name of selectedTools) {
@@ -121,7 +121,7 @@ Atomic documentation (read when the user asks about model choice, computer use o
121
121
  - When asked about: atomic workflows (docs/workflows.md), extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), atomic packages (docs/packages.md)
122
122
  - Bundled integrations use the same docs root in npm and binary installations: MCP servers (docs/mcp-servers.md), web access (docs/web-access.md), intercom (docs/intercom.md), subagents (docs/subagents.md), workflows (docs/workflows.md). Read these guides rather than guessing paths inside builtin packages.
123
123
  - When the user asks which model to choose for a task, read ${docsPath}/models/model-selection.md and ${docsPath}/models/evals.md, then consult https://artificialanalysis.ai/ for the relevant benchmark charts and methodology. Match the task to individual evaluations rather than an aggregate winner. Cite the benchmark, source date, exact model/effort and cost or latency tradeoff; distinguish measured results from recommendations. If live evidence is unavailable, label the dated docs snapshot instead of claiming a refresh. Check the configured catalog before giving an exact provider/model or thinking setting; catalog presence is not proof of live access.
124
- - For computer use (CUA) on desktop apps, simulators and emulators, use Cua Driver through the bundled cua-driver skill and one-shot \`cua-driver call <tool>\` commands: when a model chooses the next action (interactive sessions or any workflow stage acting outside ctx.tool), use the CLI; when workflow TypeScript code owns the sequence and postcondition, use the @trycua/cua-driver TypeScript SDK inside ctx.tool. If \`cua-driver --version\` fails, make one bounded attempt with upstream's one-line executable installer and report its side effects. The executable installer does not install an agent skill; ignore upstream README's optional skill-install steps, never run \`cua-driver skills install\` or \`clawhub install @cua/driver\`, and do not link or copy a skill into \`~/.agents/skills/cua-driver\`. Atomic already bundles it; leave any existing user-level skill alone. Run every cua-driver command with CUA_DRIVER_RS_TELEMETRY_ENABLED=false and follow ${docsPath}/computer-use.md for install, readiness and permissions. Prefer the agent-browser skill for what it covers: websites and web apps in Chrome/Chromium, Electron desktop apps such as VS Code, Slack, Discord, Figma, Notion and Spotify, Slack workspaces, and cloud browsers. Use cua-driver for everything else (native desktop apps, iOS simulators, Android emulators, OS dialogs and permission prompts, non-Chromium browsers) and whenever agent-browser hits a limitation. For terminal automation/testing, prefer herdr on macOS, Linux and Windows; install it if missing when network access and permissions permit, and fall back to tmux or native Windows psmux if installation or use is not possible. Load the matching skill and ${docsPath}/workflows/verification.md. Preserve the pinned herdr skill's explicit-request and HERDR_ENV=1 requirements; never control a focused session from outside Herdr. Check installed capabilities, use dedicated sessions, respect desktop permissions, and stop before destructive actions. These CLIs are not interchangeable, and skills do not grant tools or authorization.
124
+ - For computer use (CUA) on desktop apps, simulators and emulators, use Cua Driver through the bundled cua-driver skill and one-shot \`cua-driver call <tool>\` commands: when a model chooses the next action (interactive sessions or any workflow stage acting outside ctx.tool), use the CLI; when workflow TypeScript code owns the sequence and postcondition, use the @trycua/cua-driver TypeScript SDK inside ctx.tool. If \`cua-driver --version\` fails, make one bounded attempt with upstream's one-line executable installer and report its side effects. The executable installer does not install an agent skill; ignore upstream README's optional skill-install steps, never run \`cua-driver skills install\` or \`clawhub install @cua/driver\`, and do not link or copy a skill into \`~/.agents/skills/cua-driver\`. Atomic already bundles it; leave any existing user-level skill alone. Run every cua-driver command with CUA_DRIVER_RS_TELEMETRY_ENABLED=false and follow ${docsPath}/computer-use.md for install, readiness and permissions. Prefer the agent-browser skill for what it covers, because its text snapshots cost far fewer tokens than screenshot-driven CUA: websites and web apps in Chrome/Chromium, Mobile Safari in the iOS Simulator or on a connected iPhone/iPad (\`agent-browser -p ios\`, macOS with Xcode and Appium), Electron desktop apps such as VS Code, Slack, Discord, Figma, Notion and Spotify and other apps exposing a CDP port, Slack workspaces, and cloud browsers. Use cua-driver for everything else (native desktop apps, native iOS apps in the iOS Simulator, Android emulators, OS dialogs and permission prompts, desktop Safari and other non-Chromium browsers) and whenever agent-browser hits a limitation. For terminal automation/testing, prefer herdr on macOS, Linux and Windows; install it if missing when network access and permissions permit, and fall back to tmux or native Windows psmux if installation or use is not possible. Load the matching skill and ${docsPath}/workflows/verification.md. Preserve the pinned herdr skill's explicit-request and HERDR_ENV=1 requirements; never control a focused session from outside Herdr. Check installed capabilities, use dedicated sessions, respect desktop permissions, and stop before destructive actions. These CLIs are not interchangeable, and skills do not grant tools or authorization.
125
125
  - Also skip \`cua-driver skills update\` and any skill installation into other agent directories such as \`~/.claude/skills\`; updating the executable is separate from installing or updating a skill.
126
126
  - When working on Atomic topics, read the docs and examples, and follow .md cross-references before implementing
127
127
  - Always read Atomic .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;
@@ -1 +1 @@
1
- {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AAEhE,MAAM,oBAAoB,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,mBAAmB,EAAE,MAAM,CAAU,CAAC;AA4DvH,MAAM,0BAA0B,GAAG,oBAAoB,CAAC;AACxD,gGAAgG;AAChG,MAAM,UAAU,iCAAiC,CAAC,KAA+B;IAChF,OAAO;QACN,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,aAAa,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,aAAa,IAAI,oBAAoB,CAAC,CAAC;QACjE,YAAY,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,YAAY,IAAI,EAAE,CAAC,EAAE;QAC/C,cAAc,EAAE,MAAM,CAAC,WAAW,CACjC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,cAAc,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC,CAC/F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AC,EAAE,CAAC,CAAC;AACjG,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,wBAAwB,CACvC,QAAuC,EACvC,OAA6B;IAE7B,MAAM,KAAK,GAAkC,EAAE,CAAC;IAChD,KAAK,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QACpD,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,IAAI;YAAE,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IACjD,CAAC;IACD,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC1C,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,SAAS;YAAE,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IACrD,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getSystemMessageText } from \"@bastani/pi-ai\";\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nconst DEFAULT_PROMPT_TOOLS = [\"read\", \"bash\", \"edit\", \"write\", \"find\", \"search\", \"ask_user_question\", \"todo\"] as const;\n\nexport interface SystemPromptModel {\n\t/** Provider identifier for the selected model. */\n\tprovider: string;\n\t/** Stable provider-specific model identifier. */\n\tid: string;\n\t/** Human-readable model name, when available. */\n\tname?: string;\n}\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces the default prefix). */\n\tcustomPrompt?: string;\n\t/** Exact full prompt replacement set by a before_agent_start handler. */\n\tforceSystemPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write, find, search, ask_user_question, todo] */\n\tselectedTools?: string[];\n\t/** Tool names explicitly excluded by the caller and omitted from generated guidance. */\n\texcludedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Guideline bullets contributed by each tool, keyed by tool name. */\n\ttoolGuidelines?: Record<string, string[]>;\n\t/** Additional guideline bullets appended to the default system prompt rules. */\n\tpromptGuidelines?: string[];\n\t/** Text appended from user configuration before project context, skills, and cwd. */\n\tappendSystemPrompt?: string;\n\t/** Additional XML-wrapped prompt sections keyed by tag name. */\n\tsections?: Record<string, string>;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Currently selected model, used for model-aware prompt metadata. */\n\tselectedModel?: SystemPromptModel;\n\t/** Current reasoning/thinking level for the selected model. */\n\tselectedThinkingLevel?: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n}\n\nexport type NormalizedBuildSystemPromptOptions = BuildSystemPromptOptions & {\n\tselectedTools: string[];\n\ttoolSnippets: Record<string, string>;\n\ttoolGuidelines: Record<string, string[]>;\n\tpromptGuidelines: string[];\n\tappendSystemPrompt: string;\n\tsections: Record<string, string>;\n\tcontextFiles: Array<{ path: string; content: string }>;\n\tskills: Skill[];\n};\n\n/**\n * Ordered system prompt sections, keyed by name. `preamble` is untagged text; every other\n * section is wrapped in a tag of the same name so the model can match later updates to it.\n * These become `SystemMessage.sections` in the transcript.\n */\nexport type SystemPromptSections = Record<string, string>;\n\nconst SYSTEM_PROMPT_SECTION_NAME = /^[a-z][a-z0-9_-]*$/;\n/** Normalize prompt input into the mutable, collection-complete shape exposed to extensions. */\nexport function normalizeBuildSystemPromptOptions(input: BuildSystemPromptOptions): NormalizedBuildSystemPromptOptions {\n\treturn {\n\t\tcustomPrompt: input.customPrompt,\n\t\tforceSystemPrompt: input.forceSystemPrompt,\n\t\tselectedTools: [...(input.selectedTools ?? DEFAULT_PROMPT_TOOLS)],\n\t\ttoolSnippets: { ...(input.toolSnippets ?? {}) },\n\t\ttoolGuidelines: Object.fromEntries(\n\t\t\tObject.entries(input.toolGuidelines ?? {}).map(([name, guidelines]) => [name, [...guidelines]]),\n\t\t),\n\t\tpromptGuidelines: [...(input.promptGuidelines ?? [])],\n\t\tappendSystemPrompt: input.appendSystemPrompt ?? \"\",\n\t\tsections: { ...(input.sections ?? {}) },\n\t\tcwd: input.cwd,\n\t\t...(input.excludedTools === undefined ? {} : { excludedTools: [...input.excludedTools] }),\n\t\t...(input.selectedModel === undefined ? {} : { selectedModel: { ...input.selectedModel } }),\n\t\t...(input.selectedThinkingLevel === undefined ? {} : { selectedThinkingLevel: input.selectedThinkingLevel }),\n\t\tcontextFiles: (input.contextFiles ?? []).map((file) => ({ ...file })),\n\t\tskills: (input.skills ?? []).map((skill) => ({ ...skill })),\n\t};\n}\n\nfunction renderProjectContext(contextFiles: Array<{ path: string; content: string }>): string {\n\treturn [\n\t\t\"Project-specific instructions and guidelines:\",\n\t\t...contextFiles.map(\n\t\t\t({ path, content }) => `<project_instructions path=\"${path}\">\\n${content}\\n</project_instructions>`,\n\t\t),\n\t].join(\"\\n\\n\");\n}\n\nfunction buildRules(\n\tselectedTools: string[],\n\ttoolGuidelines: Record<string, string[]>,\n\tpromptGuidelines: string[],\n): string {\n\tconst rules: string[] = [];\n\tconst seen = new Set<string>();\n\tconst addRule = (rule: string): void => {\n\t\tconst normalized = rule.trim();\n\t\tif (!normalized || seen.has(normalized)) return;\n\t\tseen.add(normalized);\n\t\trules.push(normalized);\n\t};\n\n\tconst tools = selectedTools;\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasPowerShell = tools.includes(\"powershell\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst shouldIncludeAskUserFallbackGuidance = tools.length > 0 && !tools.includes(\"ask_user_question\");\n\tconst addGuideline = addRule;\n\tif ((hasBash || hasPowerShell) && !hasFind && !hasLs) {\n\t\tif (hasBash && hasPowerShell) {\n\t\t\taddRule(\"Use bash or PowerShell for file operations like listing, searching, and finding files\");\n\t\t} else if (hasPowerShell) {\n\t\t\taddRule(\"Use PowerShell for file operations like listing, searching, and finding files\");\n\t\t} else {\n\t\t\taddRule(\"Use bash for file operations like ls, rg, find\");\n\t\t}\n\t}\n\tif (shouldIncludeAskUserFallbackGuidance) {\n\t\taddGuideline(\n\t\t\t\"If an equivalent user-question tool is available, use it for all questions to the user instead of plain text, including confirmations and approvals, following its supported schema. When no usable question tool or human-input channel exists, do not stall on a question: choose the interpretation best supported by the repository and the stated objective, state the assumption in your response, and continue fully autonomously on best judgment. Tool unavailability alone is not a blocker. Preserve safety and authorization constraints.\",\n\t\t);\n\t}\n\tif (hasBash || hasPowerShell) {\n\t\taddGuideline(\n\t\t\t\"**Repository intent**: When working in a repository, infer how its maintainers actually work before imposing defaults: review recent commits, open and merged PRs, issues and their comments, and project/board status when tooling allows (for example `git log` and the `gh` CLI) to learn conventions, priorities, and scope norms. Better, identify the requesting user (`git config user.name`/`user.email`, `gh api user`) and study their own commits, PRs, reviews, and issue comments so you interpret ambiguous requests the way they would, aligning style, scope, and process with their patterns.\",\n\t\t);\n\t\taddGuideline(\n\t\t\t[\n\t\t\t\t\"**Execution history**: Leave a mineable record of how each task was executed and what the user prefers, and mine those records to calibrate later work. The records only accumulate value if every task writes them. If the user, a context file, or `APPEND_SYSTEM.md` asks you not to record some or all of these records, skip those records.\",\n\t\t\t\t\" - When you author a commit, PR, issue, or issue/review comment for a task, record how it ran: `Assistant-workflow: <workflow name> (run <runId>)` for a registered or custom workflow, or `Assistant-workflow: inline` when no workflow was used; and `Assistant-duration: <elapsed> <converged|blocked|abandoned>, estimated <estimate>` (for example `Assistant-duration: 42m converged, estimated 30m`), measuring wall-clock time from launch or task start until acceptance was proven or work stopped, including resumes and repair rounds. Take elapsed time from workflow status timing or timestamps you recorded (for example `date` at task start); write `unmeasured` rather than guess. Put these as trailers alongside `Assistant-model` in commits (git trailers, or the equivalent commit-message metadata in the repository's version control system) and as the same `Key: value` lines in PR/merge request, issue, and comment bodies. For multi-commit work, record the workflow on each commit and the final duration once, in the last commit or the PR body.\",\n\t\t\t\t\" - In the same artifacts, record how the result was verified with one `Assistant-verification: <method> <passed|failed|unavailable>: <what it proved or why>` line per method that actually ran or was attempted (for example `Assistant-verification: herdr terminal E2E passed: /tasks lists running tasks first at 80x24`, `Assistant-verification: vitest unit passed: npm run test:unit`, or `Assistant-verification: cua-driver unavailable: Accessibility permission not granted`). Name the concrete mechanism, such as unit, integration, or E2E tests, agent-browser, Cua Driver, herdr or tmux terminal automation, the qlty CLI, typecheck or lint, or a manual scenario, and the command or scenario it exercised. Record only checks that ran and their observed outcome; never record a skipped, mocked, or planned check as passed.\",\n\t\t\t\t\" - When the user states or reveals a durable preference about how they work (a correction, a rejected approach, scope, review, tooling, or communication style), record it in the same artifacts as `User-preference: <one line, in the user's terms>`, and tie it to the requesting user with a `Co-authored-by: <name> <email>` trailer taken from their version control identity (for example `git config user.name`/`user.email`) unless that line is already present; in PR, issue, and comment bodies, add the same line or their hosting account (for example from `gh api user`). Record only what the user expressed or their own edits show; never record secrets, credentials, or personal details unrelated to the work. If repository rules restrict commit or PR formats, fit the records into what they allow.\",\n\t\t\t\t\" - Before choosing between a workflow and inline work, choosing how to verify a change, estimating a duration, or interpreting an ambiguous request, mine these records with the rest of the history using the repository's version control system and its hosting CLI, for example `git log --format='%h %an <%ae> %s%n%(trailers:key=Assistant-workflow,key=Assistant-duration,key=Assistant-verification,key=User-preference,key=Co-authored-by)'` with `gh pr list --state all --search 'Assistant-workflow in:body'` on GitHub, or the equivalent commands for other systems and hosts (for example `glab` on GitLab). Compare tasks of similar kind and size, and state the sample size with the median and range. Treat fewer than five comparable records as anecdotal, and prefer the more recent record when two conflict. When choosing verification, start from the methods that proved comparable changes (the same files, subsystem, or kind of change), reuse their commands and scenarios, and do not retry a setup recorded as `unavailable` without a reason to expect a different result; past records never replace the project's required checks. Prioritize preferences tied to the requesting user by their co-author line, commit author, or hosting account. When the user has none that cover the situation, fall back to other contributors' relevant preferences as repository conventions; the user's own records and current request override them, so users can always encode their own preference. This history is a guide, not the decision: the current request, the task itself, and explicit user instructions decide between a workflow and inline work.\",\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t}\n\n\tfor (const name of selectedTools) {\n\t\tfor (const rule of toolGuidelines[name] ?? []) addRule(rule);\n\t}\n\tfor (const rule of promptGuidelines) addRule(rule);\n\taddRule(\n\t\t\"Write self-describing code and do not add comments unless the user explicitly asks for them or the task instructions call for them. Code that needs a comment to be understood is a smell: restructure it with clearer names, smaller units, or explicit types instead\",\n\t);\n\taddRule(\"Be concise in your responses\");\n\taddRule(\"Show file paths clearly when working with files\");\n\treturn rules.map((rule) => `- ${rule}`).join(\"\\n\");\n}\n\n/** Build the ordered, independently replaceable sections of the structured system prompt. */\nexport function buildSystemPromptSections(input: BuildSystemPromptOptions): SystemPromptSections {\n\tconst options = normalizeBuildSystemPromptOptions(input);\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\ttoolGuidelines,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tsections: customSections,\n\t\tcwd,\n\t\tcontextFiles,\n\t\tskills,\n\t} = options;\n\tconst explicitlyExcludedTools = new Set(options.excludedTools ?? []);\n\tconst tools = selectedTools.filter((name) => !explicitlyExcludedTools.has(name));\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\tconst modelName = options.selectedModel?.name?.trim() || options.selectedModel?.id || \"unknown\";\n\tconst modelReasoningLevel = options.selectedThinkingLevel?.trim() || \"off\";\n\tconst now = new Date();\n\tconst date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}`;\n\n\tfor (const name of Object.keys(customSections)) {\n\t\tif (!SYSTEM_PROMPT_SECTION_NAME.test(name) || name === \"preamble\") {\n\t\t\tthrow new Error(`Invalid system prompt section name: ${name}`);\n\t\t}\n\t}\n\n\tconst promptSections: Record<string, string> = {};\n\tif (customPrompt) {\n\t\tpromptSections.preamble = customPrompt;\n\t} else {\n\t\tpromptSections.preamble =\n\t\t\t\"You are an expert coding assistant operating named Atomic, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\";\n\t\tconst visibleTools = tools.filter((name) => !!toolSnippets[name]);\n\t\tconst toolsList =\n\t\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets[name]}`).join(\"\\n\") : \"(none)\";\n\t\tpromptSections.tools = `Available tools:\\n${toolsList}\\n\\nIn addition to the tools above, you may have access to other custom tools depending on the project.`;\n\t\tpromptSections.rules = `Guidelines:\\n${buildRules(tools, toolGuidelines, promptGuidelines)}`;\n\t\tpromptSections.docs = `\nAtomic documentation (read when the user asks about model choice, computer use or automation, MCP, web access, intercom, subagents, or customizing Atomic itself, its SDK, creating workflows, packages, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- Docs/examples references above must be resolved against these absolute roots; e.g. docs/foo.md means ${docsPath}/foo.md and examples/bar means ${examplesPath}/bar.\n- When asked about: atomic workflows (docs/workflows.md), extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), atomic packages (docs/packages.md)\n- Bundled integrations use the same docs root in npm and binary installations: MCP servers (docs/mcp-servers.md), web access (docs/web-access.md), intercom (docs/intercom.md), subagents (docs/subagents.md), workflows (docs/workflows.md). Read these guides rather than guessing paths inside builtin packages.\n- When the user asks which model to choose for a task, read ${docsPath}/models/model-selection.md and ${docsPath}/models/evals.md, then consult https://artificialanalysis.ai/ for the relevant benchmark charts and methodology. Match the task to individual evaluations rather than an aggregate winner. Cite the benchmark, source date, exact model/effort and cost or latency tradeoff; distinguish measured results from recommendations. If live evidence is unavailable, label the dated docs snapshot instead of claiming a refresh. Check the configured catalog before giving an exact provider/model or thinking setting; catalog presence is not proof of live access.\n- For computer use (CUA) on desktop apps, simulators and emulators, use Cua Driver through the bundled cua-driver skill and one-shot \\`cua-driver call <tool>\\` commands: when a model chooses the next action (interactive sessions or any workflow stage acting outside ctx.tool), use the CLI; when workflow TypeScript code owns the sequence and postcondition, use the @trycua/cua-driver TypeScript SDK inside ctx.tool. If \\`cua-driver --version\\` fails, make one bounded attempt with upstream's one-line executable installer and report its side effects. The executable installer does not install an agent skill; ignore upstream README's optional skill-install steps, never run \\`cua-driver skills install\\` or \\`clawhub install @cua/driver\\`, and do not link or copy a skill into \\`~/.agents/skills/cua-driver\\`. Atomic already bundles it; leave any existing user-level skill alone. Run every cua-driver command with CUA_DRIVER_RS_TELEMETRY_ENABLED=false and follow ${docsPath}/computer-use.md for install, readiness and permissions. Prefer the agent-browser skill for what it covers: websites and web apps in Chrome/Chromium, Electron desktop apps such as VS Code, Slack, Discord, Figma, Notion and Spotify, Slack workspaces, and cloud browsers. Use cua-driver for everything else (native desktop apps, iOS simulators, Android emulators, OS dialogs and permission prompts, non-Chromium browsers) and whenever agent-browser hits a limitation. For terminal automation/testing, prefer herdr on macOS, Linux and Windows; install it if missing when network access and permissions permit, and fall back to tmux or native Windows psmux if installation or use is not possible. Load the matching skill and ${docsPath}/workflows/verification.md. Preserve the pinned herdr skill's explicit-request and HERDR_ENV=1 requirements; never control a focused session from outside Herdr. Check installed capabilities, use dedicated sessions, respect desktop permissions, and stop before destructive actions. These CLIs are not interchangeable, and skills do not grant tools or authorization.\n- Also skip \\`cua-driver skills update\\` and any skill installation into other agent directories such as \\`~/.claude/skills\\`; updating the executable is separate from installing or updating a skill.\n- When working on Atomic topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read Atomic .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\t}\n\n\tif (appendSystemPrompt) promptSections.addendum = appendSystemPrompt;\n\tif (contextFiles.length > 0) promptSections.project_context = renderProjectContext(contextFiles);\n\tconst skillFileReadTool = ([\"read\", \"bash\"] as const).find((tool) => tools.includes(tool));\n\tif (skillFileReadTool && skills.length > 0) {\n\t\tconst skillsPrompt = formatSkillsForPrompt(skills, skillFileReadTool).trim();\n\t\tif (skillsPrompt) promptSections.skills = skillsPrompt;\n\t}\n\tpromptSections.model = `Model name (used for commit attribution): ${modelName}\\nModel reasoning level: ${modelReasoningLevel}`;\n\tpromptSections.date = `Current date: ${date}`;\n\tpromptSections.cwd = `Current working directory: ${cwd.replace(/\\\\/g, \"/\")}`;\n\tfor (const [name, content] of Object.entries(customSections)) {\n\t\tif (content) promptSections[name] = content;\n\t}\n\n\tconst sections: SystemPromptSections = { preamble: promptSections.preamble };\n\tfor (const [name, content] of Object.entries(promptSections)) {\n\t\tif (name !== \"preamble\") sections[name] = `<${name}>\\n${content}\\n</${name}>`;\n\t}\n\treturn sections;\n}\n\n/**\n * The complete prompt state for `input`. A forced prompt is opaque and lives in `content`\n * with no sections; otherwise `content` is empty and the structured sections carry the prompt.\n */\nexport function buildSystemPromptState(input: BuildSystemPromptOptions): {\n\tcontent: string;\n\tsections?: SystemPromptSections;\n} {\n\tif (input.forceSystemPrompt !== undefined) return { content: input.forceSystemPrompt };\n\treturn { content: \"\", sections: buildSystemPromptSections(input) };\n}\n\n/** Build the system prompt text, rendered exactly as the transcript's system message replays it. */\nexport function buildSystemPrompt(input: BuildSystemPromptOptions): string {\n\treturn getSystemMessageText({ role: \"system\", ...buildSystemPromptState(input), timestamp: 0 });\n}\n\n/**\n * Diff the sections the model currently has (replayed from the transcript, so never null)\n * against the desired ones. Returns a `SystemMessage.sections` patch, or undefined when\n * nothing changed.\n */\nexport function diffSystemPromptSections(\n\tprevious: Record<string, string | null>,\n\tcurrent: SystemPromptSections,\n): Record<string, string | null> | undefined {\n\tconst patch: Record<string, string | null> = {};\n\tfor (const [name, text] of Object.entries(current)) {\n\t\tif (previous[name] !== text) patch[name] = text;\n\t}\n\tfor (const name of Object.keys(previous)) {\n\t\tif (current[name] === undefined) patch[name] = null;\n\t}\n\treturn Object.keys(patch).length > 0 ? patch : undefined;\n}\n"]}
1
+ {"version":3,"file":"system-prompt.js","sourceRoot":"","sources":["../../src/core/system-prompt.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,oBAAoB,EAAE,MAAM,gBAAgB,CAAC;AACtD,OAAO,EAAE,WAAW,EAAE,eAAe,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAC3E,OAAO,EAAE,qBAAqB,EAAc,MAAM,aAAa,CAAC;AAEhE,MAAM,oBAAoB,GAAG,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,mBAAmB,EAAE,MAAM,CAAU,CAAC;AA4DvH,MAAM,0BAA0B,GAAG,oBAAoB,CAAC;AACxD,gGAAgG;AAChG,MAAM,UAAU,iCAAiC,CAAC,KAA+B;IAChF,OAAO;QACN,YAAY,EAAE,KAAK,CAAC,YAAY;QAChC,iBAAiB,EAAE,KAAK,CAAC,iBAAiB;QAC1C,aAAa,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,aAAa,IAAI,oBAAoB,CAAC,CAAC;QACjE,YAAY,EAAE,EAAE,GAAG,CAAC,KAAK,CAAC,YAAY,IAAI,EAAE,CAAC,EAAE;QAC/C,cAAc,EAAE,MAAM,CAAC,WAAW,CACjC,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,cAAc,IAAI,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,UAAU,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,EAAE,CAAC,GAAG,UAAU,CAAC,CAAC,CAAC,CAC/F;QACD,gBAAgB,EAAE,CAAC,GAAG,CAAC,KAAK,CAAC,gBAAgB,IAAI,EAAE,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B,CACvC,QAAuC,EACvC,OAA6B;IAE7B,MAAM,KAAK,GAAkC,EAAE,CAAC;IAChD,KAAK,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QACpD,IAAI,QAAQ,CAAC,IAAI,CAAC,KAAK,IAAI;YAAE,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IACjD,CAAC;IACD,KAAK,MAAM,IAAI,IAAI,MAAM,CAAC,IAAI,CAAC,QAAQ,CAAC,EAAE,CAAC;QAC1C,IAAI,OAAO,CAAC,IAAI,CAAC,KAAK,SAAS;YAAE,KAAK,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IACrD,CAAC;IACD,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,SAAS,CAAC;AAC1D,CAAC","sourcesContent":["/**\n * System prompt construction and project context loading\n */\n\nimport { getSystemMessageText } from \"@bastani/pi-ai\";\nimport { getDocsPath, getExamplesPath, getReadmePath } from \"../config.js\";\nimport { formatSkillsForPrompt, type Skill } from \"./skills.ts\";\n\nconst DEFAULT_PROMPT_TOOLS = [\"read\", \"bash\", \"edit\", \"write\", \"find\", \"search\", \"ask_user_question\", \"todo\"] as const;\n\nexport interface SystemPromptModel {\n\t/** Provider identifier for the selected model. */\n\tprovider: string;\n\t/** Stable provider-specific model identifier. */\n\tid: string;\n\t/** Human-readable model name, when available. */\n\tname?: string;\n}\n\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces the default prefix). */\n\tcustomPrompt?: string;\n\t/** Exact full prompt replacement set by a before_agent_start handler. */\n\tforceSystemPrompt?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write, find, search, ask_user_question, todo] */\n\tselectedTools?: string[];\n\t/** Tool names explicitly excluded by the caller and omitted from generated guidance. */\n\texcludedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Guideline bullets contributed by each tool, keyed by tool name. */\n\ttoolGuidelines?: Record<string, string[]>;\n\t/** Additional guideline bullets appended to the default system prompt rules. */\n\tpromptGuidelines?: string[];\n\t/** Text appended from user configuration before project context, skills, and cwd. */\n\tappendSystemPrompt?: string;\n\t/** Additional XML-wrapped prompt sections keyed by tag name. */\n\tsections?: Record<string, string>;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Currently selected model, used for model-aware prompt metadata. */\n\tselectedModel?: SystemPromptModel;\n\t/** Current reasoning/thinking level for the selected model. */\n\tselectedThinkingLevel?: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: Skill[];\n}\n\nexport type NormalizedBuildSystemPromptOptions = BuildSystemPromptOptions & {\n\tselectedTools: string[];\n\ttoolSnippets: Record<string, string>;\n\ttoolGuidelines: Record<string, string[]>;\n\tpromptGuidelines: string[];\n\tappendSystemPrompt: string;\n\tsections: Record<string, string>;\n\tcontextFiles: Array<{ path: string; content: string }>;\n\tskills: Skill[];\n};\n\n/**\n * Ordered system prompt sections, keyed by name. `preamble` is untagged text; every other\n * section is wrapped in a tag of the same name so the model can match later updates to it.\n * These become `SystemMessage.sections` in the transcript.\n */\nexport type SystemPromptSections = Record<string, string>;\n\nconst SYSTEM_PROMPT_SECTION_NAME = /^[a-z][a-z0-9_-]*$/;\n/** Normalize prompt input into the mutable, collection-complete shape exposed to extensions. */\nexport function normalizeBuildSystemPromptOptions(input: BuildSystemPromptOptions): NormalizedBuildSystemPromptOptions {\n\treturn {\n\t\tcustomPrompt: input.customPrompt,\n\t\tforceSystemPrompt: input.forceSystemPrompt,\n\t\tselectedTools: [...(input.selectedTools ?? DEFAULT_PROMPT_TOOLS)],\n\t\ttoolSnippets: { ...(input.toolSnippets ?? {}) },\n\t\ttoolGuidelines: Object.fromEntries(\n\t\t\tObject.entries(input.toolGuidelines ?? {}).map(([name, guidelines]) => [name, [...guidelines]]),\n\t\t),\n\t\tpromptGuidelines: [...(input.promptGuidelines ?? [])],\n\t\tappendSystemPrompt: input.appendSystemPrompt ?? \"\",\n\t\tsections: { ...(input.sections ?? {}) },\n\t\tcwd: input.cwd,\n\t\t...(input.excludedTools === undefined ? {} : { excludedTools: [...input.excludedTools] }),\n\t\t...(input.selectedModel === undefined ? {} : { selectedModel: { ...input.selectedModel } }),\n\t\t...(input.selectedThinkingLevel === undefined ? {} : { selectedThinkingLevel: input.selectedThinkingLevel }),\n\t\tcontextFiles: (input.contextFiles ?? []).map((file) => ({ ...file })),\n\t\tskills: (input.skills ?? []).map((skill) => ({ ...skill })),\n\t};\n}\n\nfunction renderProjectContext(contextFiles: Array<{ path: string; content: string }>): string {\n\treturn [\n\t\t\"Project-specific instructions and guidelines:\",\n\t\t...contextFiles.map(\n\t\t\t({ path, content }) => `<project_instructions path=\"${path}\">\\n${content}\\n</project_instructions>`,\n\t\t),\n\t].join(\"\\n\\n\");\n}\n\nfunction buildRules(\n\tselectedTools: string[],\n\ttoolGuidelines: Record<string, string[]>,\n\tpromptGuidelines: string[],\n): string {\n\tconst rules: string[] = [];\n\tconst seen = new Set<string>();\n\tconst addRule = (rule: string): void => {\n\t\tconst normalized = rule.trim();\n\t\tif (!normalized || seen.has(normalized)) return;\n\t\tseen.add(normalized);\n\t\trules.push(normalized);\n\t};\n\n\tconst tools = selectedTools;\n\tconst hasBash = tools.includes(\"bash\");\n\tconst hasPowerShell = tools.includes(\"powershell\");\n\tconst hasFind = tools.includes(\"find\");\n\tconst hasLs = tools.includes(\"ls\");\n\tconst shouldIncludeAskUserFallbackGuidance = tools.length > 0 && !tools.includes(\"ask_user_question\");\n\tconst addGuideline = addRule;\n\tif ((hasBash || hasPowerShell) && !hasFind && !hasLs) {\n\t\tif (hasBash && hasPowerShell) {\n\t\t\taddRule(\"Use bash or PowerShell for file operations like listing, searching, and finding files\");\n\t\t} else if (hasPowerShell) {\n\t\t\taddRule(\"Use PowerShell for file operations like listing, searching, and finding files\");\n\t\t} else {\n\t\t\taddRule(\"Use bash for file operations like ls, rg, find\");\n\t\t}\n\t}\n\tif (shouldIncludeAskUserFallbackGuidance) {\n\t\taddGuideline(\n\t\t\t\"If an equivalent user-question tool is available, use it for all questions to the user instead of plain text, including confirmations and approvals, following its supported schema. When no usable question tool or human-input channel exists, do not stall on a question: choose the interpretation best supported by the repository and the stated objective, state the assumption in your response, and continue fully autonomously on best judgment. Tool unavailability alone is not a blocker. Preserve safety and authorization constraints.\",\n\t\t);\n\t}\n\tif (hasBash || hasPowerShell) {\n\t\taddGuideline(\n\t\t\t\"**Repository intent**: When working in a repository, infer how its maintainers actually work before imposing defaults: review recent commits, open and merged PRs, issues and their comments, and project/board status when tooling allows (for example `git log` and the `gh` CLI) to learn conventions, priorities, and scope norms. Better, identify the requesting user (`git config user.name`/`user.email`, `gh api user`) and study their own commits, PRs, reviews, and issue comments so you interpret ambiguous requests the way they would, aligning style, scope, and process with their patterns.\",\n\t\t);\n\t\taddGuideline(\n\t\t\t[\n\t\t\t\t\"**Execution history**: Leave a mineable record of how each task was executed and what the user prefers, and mine those records to calibrate later work. The records only accumulate value if every task writes them. If the user, a context file, or `APPEND_SYSTEM.md` asks you not to record some or all of these records, skip those records.\",\n\t\t\t\t\" - When you author a commit, PR, issue, or issue/review comment for a task, record how it ran: `Assistant-workflow: <workflow name> (run <runId>)` for a registered or custom workflow, or `Assistant-workflow: inline` when no workflow was used; and `Assistant-duration: <elapsed> <converged|blocked|abandoned>, estimated <estimate>` (for example `Assistant-duration: 42m converged, estimated 30m`), measuring wall-clock time from launch or task start until acceptance was proven or work stopped, including resumes and repair rounds. Take elapsed time from workflow status timing or timestamps you recorded (for example `date` at task start); write `unmeasured` rather than guess. Put these as trailers alongside `Assistant-model` in commits (git trailers, or the equivalent commit-message metadata in the repository's version control system) and as the same `Key: value` lines in PR/merge request, issue, and comment bodies. For multi-commit work, record the workflow on each commit and the final duration once, in the last commit or the PR body.\",\n\t\t\t\t\" - In the same artifacts, record how the result was verified with one `Assistant-verification: <method> <passed|failed|unavailable>: <what it proved or why>` line per method that actually ran or was attempted (for example `Assistant-verification: herdr terminal E2E passed: /tasks lists running tasks first at 80x24`, `Assistant-verification: vitest unit passed: npm run test:unit`, or `Assistant-verification: cua-driver unavailable: Accessibility permission not granted`). Name the concrete mechanism, such as unit, integration, or E2E tests, agent-browser, Cua Driver, herdr or tmux terminal automation, the qlty CLI, typecheck or lint, or a manual scenario, and the command or scenario it exercised. Record only checks that ran and their observed outcome; never record a skipped, mocked, or planned check as passed.\",\n\t\t\t\t\" - When the user states or reveals a durable preference about how they work (a correction, a rejected approach, scope, review, tooling, or communication style), record it in the same artifacts as `User-preference: <one line, in the user's terms>`, and tie it to the requesting user with a `Co-authored-by: <name> <email>` trailer taken from their version control identity (for example `git config user.name`/`user.email`) unless that line is already present; in PR, issue, and comment bodies, add the same line or their hosting account (for example from `gh api user`). Record only what the user expressed or their own edits show; never record secrets, credentials, or personal details unrelated to the work. If repository rules restrict commit or PR formats, fit the records into what they allow.\",\n\t\t\t\t\" - Before choosing between a workflow and inline work, choosing how to verify a change, estimating a duration, or interpreting an ambiguous request, mine these records with the rest of the history using the repository's version control system and its hosting CLI, for example `git log --format='%h %an <%ae> %s%n%(trailers:key=Assistant-workflow,key=Assistant-duration,key=Assistant-verification,key=User-preference,key=Co-authored-by)'` with `gh pr list --state all --search 'Assistant-workflow in:body'` on GitHub, or the equivalent commands for other systems and hosts (for example `glab` on GitLab). Compare tasks of similar kind and size, and state the sample size with the median and range. Treat fewer than five comparable records as anecdotal, and prefer the more recent record when two conflict. When choosing verification, start from the methods that proved comparable changes (the same files, subsystem, or kind of change), reuse their commands and scenarios, and do not retry a setup recorded as `unavailable` without a reason to expect a different result; past records never replace the project's required checks. Prioritize preferences tied to the requesting user by their co-author line, commit author, or hosting account. When the user has none that cover the situation, fall back to other contributors' relevant preferences as repository conventions; the user's own records and current request override them, so users can always encode their own preference. This history is a guide, not the decision: the current request, the task itself, and explicit user instructions decide between a workflow and inline work. Missing, sparse, or mostly inline workflow history is not evidence that the user prefers inline work: records exist only for tasks that wrote them, and past inline runs may reflect an earlier default rather than a choice. Without a recorded or stated preference that covers the situation, judge the task's shape yourself and choose a workflow when it would help, then let comparable records and the user's preferences refine that call.\",\n\t\t\t].join(\"\\n\"),\n\t\t);\n\t}\n\n\tfor (const name of selectedTools) {\n\t\tfor (const rule of toolGuidelines[name] ?? []) addRule(rule);\n\t}\n\tfor (const rule of promptGuidelines) addRule(rule);\n\taddRule(\n\t\t\"Write self-describing code and do not add comments unless the user explicitly asks for them or the task instructions call for them. Code that needs a comment to be understood is a smell: restructure it with clearer names, smaller units, or explicit types instead\",\n\t);\n\taddRule(\"Be concise in your responses\");\n\taddRule(\"Show file paths clearly when working with files\");\n\treturn rules.map((rule) => `- ${rule}`).join(\"\\n\");\n}\n\n/** Build the ordered, independently replaceable sections of the structured system prompt. */\nexport function buildSystemPromptSections(input: BuildSystemPromptOptions): SystemPromptSections {\n\tconst options = normalizeBuildSystemPromptOptions(input);\n\tconst {\n\t\tcustomPrompt,\n\t\tselectedTools,\n\t\ttoolSnippets,\n\t\ttoolGuidelines,\n\t\tpromptGuidelines,\n\t\tappendSystemPrompt,\n\t\tsections: customSections,\n\t\tcwd,\n\t\tcontextFiles,\n\t\tskills,\n\t} = options;\n\tconst explicitlyExcludedTools = new Set(options.excludedTools ?? []);\n\tconst tools = selectedTools.filter((name) => !explicitlyExcludedTools.has(name));\n\tconst readmePath = getReadmePath();\n\tconst docsPath = getDocsPath();\n\tconst examplesPath = getExamplesPath();\n\tconst modelName = options.selectedModel?.name?.trim() || options.selectedModel?.id || \"unknown\";\n\tconst modelReasoningLevel = options.selectedThinkingLevel?.trim() || \"off\";\n\tconst now = new Date();\n\tconst date = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, \"0\")}-${String(now.getDate()).padStart(2, \"0\")}`;\n\n\tfor (const name of Object.keys(customSections)) {\n\t\tif (!SYSTEM_PROMPT_SECTION_NAME.test(name) || name === \"preamble\") {\n\t\t\tthrow new Error(`Invalid system prompt section name: ${name}`);\n\t\t}\n\t}\n\n\tconst promptSections: Record<string, string> = {};\n\tif (customPrompt) {\n\t\tpromptSections.preamble = customPrompt;\n\t} else {\n\t\tpromptSections.preamble =\n\t\t\t\"You are an expert coding assistant operating named Atomic, a coding agent harness. You help users by reading files, executing commands, editing code, and writing new files.\";\n\t\tconst visibleTools = tools.filter((name) => !!toolSnippets[name]);\n\t\tconst toolsList =\n\t\t\tvisibleTools.length > 0 ? visibleTools.map((name) => `- ${name}: ${toolSnippets[name]}`).join(\"\\n\") : \"(none)\";\n\t\tpromptSections.tools = `Available tools:\\n${toolsList}\\n\\nIn addition to the tools above, you may have access to other custom tools depending on the project.`;\n\t\tpromptSections.rules = `Guidelines:\\n${buildRules(tools, toolGuidelines, promptGuidelines)}`;\n\t\tpromptSections.docs = `\nAtomic documentation (read when the user asks about model choice, computer use or automation, MCP, web access, intercom, subagents, or customizing Atomic itself, its SDK, creating workflows, packages, extensions, themes, skills, or TUI):\n- Main documentation: ${readmePath}\n- Additional docs: ${docsPath}\n- Examples: ${examplesPath} (extensions, custom tools, SDK)\n- Docs/examples references above must be resolved against these absolute roots; e.g. docs/foo.md means ${docsPath}/foo.md and examples/bar means ${examplesPath}/bar.\n- When asked about: atomic workflows (docs/workflows.md), extensions (docs/extensions.md, examples/extensions/), themes (docs/themes.md), skills (docs/skills.md), prompt templates (docs/prompt-templates.md), TUI components (docs/tui.md), keybindings (docs/keybindings.md), SDK integrations (docs/sdk.md), custom providers (docs/custom-provider.md), adding models (docs/models.md), atomic packages (docs/packages.md)\n- Bundled integrations use the same docs root in npm and binary installations: MCP servers (docs/mcp-servers.md), web access (docs/web-access.md), intercom (docs/intercom.md), subagents (docs/subagents.md), workflows (docs/workflows.md). Read these guides rather than guessing paths inside builtin packages.\n- When the user asks which model to choose for a task, read ${docsPath}/models/model-selection.md and ${docsPath}/models/evals.md, then consult https://artificialanalysis.ai/ for the relevant benchmark charts and methodology. Match the task to individual evaluations rather than an aggregate winner. Cite the benchmark, source date, exact model/effort and cost or latency tradeoff; distinguish measured results from recommendations. If live evidence is unavailable, label the dated docs snapshot instead of claiming a refresh. Check the configured catalog before giving an exact provider/model or thinking setting; catalog presence is not proof of live access.\n- For computer use (CUA) on desktop apps, simulators and emulators, use Cua Driver through the bundled cua-driver skill and one-shot \\`cua-driver call <tool>\\` commands: when a model chooses the next action (interactive sessions or any workflow stage acting outside ctx.tool), use the CLI; when workflow TypeScript code owns the sequence and postcondition, use the @trycua/cua-driver TypeScript SDK inside ctx.tool. If \\`cua-driver --version\\` fails, make one bounded attempt with upstream's one-line executable installer and report its side effects. The executable installer does not install an agent skill; ignore upstream README's optional skill-install steps, never run \\`cua-driver skills install\\` or \\`clawhub install @cua/driver\\`, and do not link or copy a skill into \\`~/.agents/skills/cua-driver\\`. Atomic already bundles it; leave any existing user-level skill alone. Run every cua-driver command with CUA_DRIVER_RS_TELEMETRY_ENABLED=false and follow ${docsPath}/computer-use.md for install, readiness and permissions. Prefer the agent-browser skill for what it covers, because its text snapshots cost far fewer tokens than screenshot-driven CUA: websites and web apps in Chrome/Chromium, Mobile Safari in the iOS Simulator or on a connected iPhone/iPad (\\`agent-browser -p ios\\`, macOS with Xcode and Appium), Electron desktop apps such as VS Code, Slack, Discord, Figma, Notion and Spotify and other apps exposing a CDP port, Slack workspaces, and cloud browsers. Use cua-driver for everything else (native desktop apps, native iOS apps in the iOS Simulator, Android emulators, OS dialogs and permission prompts, desktop Safari and other non-Chromium browsers) and whenever agent-browser hits a limitation. For terminal automation/testing, prefer herdr on macOS, Linux and Windows; install it if missing when network access and permissions permit, and fall back to tmux or native Windows psmux if installation or use is not possible. Load the matching skill and ${docsPath}/workflows/verification.md. Preserve the pinned herdr skill's explicit-request and HERDR_ENV=1 requirements; never control a focused session from outside Herdr. Check installed capabilities, use dedicated sessions, respect desktop permissions, and stop before destructive actions. These CLIs are not interchangeable, and skills do not grant tools or authorization.\n- Also skip \\`cua-driver skills update\\` and any skill installation into other agent directories such as \\`~/.claude/skills\\`; updating the executable is separate from installing or updating a skill.\n- When working on Atomic topics, read the docs and examples, and follow .md cross-references before implementing\n- Always read Atomic .md files completely and follow links to related docs (e.g., tui.md for TUI API details)`;\n\t}\n\n\tif (appendSystemPrompt) promptSections.addendum = appendSystemPrompt;\n\tif (contextFiles.length > 0) promptSections.project_context = renderProjectContext(contextFiles);\n\tconst skillFileReadTool = ([\"read\", \"bash\"] as const).find((tool) => tools.includes(tool));\n\tif (skillFileReadTool && skills.length > 0) {\n\t\tconst skillsPrompt = formatSkillsForPrompt(skills, skillFileReadTool).trim();\n\t\tif (skillsPrompt) promptSections.skills = skillsPrompt;\n\t}\n\tpromptSections.model = `Model name (used for commit attribution): ${modelName}\\nModel reasoning level: ${modelReasoningLevel}`;\n\tpromptSections.date = `Current date: ${date}`;\n\tpromptSections.cwd = `Current working directory: ${cwd.replace(/\\\\/g, \"/\")}`;\n\tfor (const [name, content] of Object.entries(customSections)) {\n\t\tif (content) promptSections[name] = content;\n\t}\n\n\tconst sections: SystemPromptSections = { preamble: promptSections.preamble };\n\tfor (const [name, content] of Object.entries(promptSections)) {\n\t\tif (name !== \"preamble\") sections[name] = `<${name}>\\n${content}\\n</${name}>`;\n\t}\n\treturn sections;\n}\n\n/**\n * The complete prompt state for `input`. A forced prompt is opaque and lives in `content`\n * with no sections; otherwise `content` is empty and the structured sections carry the prompt.\n */\nexport function buildSystemPromptState(input: BuildSystemPromptOptions): {\n\tcontent: string;\n\tsections?: SystemPromptSections;\n} {\n\tif (input.forceSystemPrompt !== undefined) return { content: input.forceSystemPrompt };\n\treturn { content: \"\", sections: buildSystemPromptSections(input) };\n}\n\n/** Build the system prompt text, rendered exactly as the transcript's system message replays it. */\nexport function buildSystemPrompt(input: BuildSystemPromptOptions): string {\n\treturn getSystemMessageText({ role: \"system\", ...buildSystemPromptState(input), timestamp: 0 });\n}\n\n/**\n * Diff the sections the model currently has (replayed from the transcript, so never null)\n * against the desired ones. Returns a `SystemMessage.sections` patch, or undefined when\n * nothing changed.\n */\nexport function diffSystemPromptSections(\n\tprevious: Record<string, string | null>,\n\tcurrent: SystemPromptSections,\n): Record<string, string | null> | undefined {\n\tconst patch: Record<string, string | null> = {};\n\tfor (const [name, text] of Object.entries(current)) {\n\t\tif (previous[name] !== text) patch[name] = text;\n\t}\n\tfor (const name of Object.keys(previous)) {\n\t\tif (current[name] === undefined) patch[name] = null;\n\t}\n\treturn Object.keys(patch).length > 0 ? patch : undefined;\n}\n"]}