@bastani/atomic 0.9.20-alpha.9 → 0.9.20
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.
- package/CHANGELOG.md +247 -0
- package/dist/builtin/intercom/CHANGELOG.md +25 -0
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/CHANGELOG.md +13 -0
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/CHANGELOG.md +50 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/skills/tdd/SKILL.md +10 -2
- package/dist/builtin/subagents/skills/tdd/mocking.md +4 -0
- package/dist/builtin/subagents/skills/tdd/test-audit.md +105 -0
- package/dist/builtin/subagents/skills/tdd/tests.md +3 -1
- package/dist/builtin/subagents/src/extension/index.bundle.mjs +2 -1
- package/dist/builtin/web-access/CHANGELOG.md +13 -0
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +138 -0
- package/dist/builtin/workflows/README.md +1 -1
- package/dist/builtin/workflows/builtin/adversarial-verification.js +3 -3
- package/dist/builtin/workflows/builtin/{chunk-7ps7bnb4.js → chunk-0nrgfbag.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-2npg6daz.js → chunk-2hak3b7g.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-twefqrv0.js → chunk-73c5tayt.js} +36 -3
- package/dist/builtin/workflows/builtin/{chunk-18yz7r43.js → chunk-bzdvx2xr.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-24c235x7.js → chunk-crw7q5g1.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-f8jjd90r.js → chunk-cw86srkf.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-z5xdqrs6.js → chunk-jaj27rqc.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-gxrhbnaj.js → chunk-kspvwc24.js} +2 -2
- package/dist/builtin/workflows/builtin/{chunk-ynded223.js → chunk-maqv731g.js} +3 -3
- package/dist/builtin/workflows/builtin/{chunk-1pd5zcfa.js → chunk-vkmpdat4.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-2jv44yz7.js → chunk-w18kbz63.js} +1 -1
- package/dist/builtin/workflows/builtin/{chunk-ad864596.js → chunk-wh19f5ee.js} +3 -3
- package/dist/builtin/workflows/builtin/classify-and-act.js +3 -3
- package/dist/builtin/workflows/builtin/fan-out-and-synthesize.js +3 -3
- package/dist/builtin/workflows/builtin/generate-and-filter.js +3 -3
- package/dist/builtin/workflows/builtin/goal.js +4 -4
- package/dist/builtin/workflows/builtin/index.js +12 -12
- package/dist/builtin/workflows/builtin/loop-until-done.js +3 -3
- package/dist/builtin/workflows/builtin/open-claude-design.js +3 -3
- package/dist/builtin/workflows/builtin/ralph.js +4 -4
- package/dist/builtin/workflows/builtin/steering-context.js +1 -1
- package/dist/builtin/workflows/builtin/tournament.js +3 -3
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/extension/index.bundle.mjs +105 -33
- package/dist/builtin/workflows/src/index.js +93 -27
- package/dist/core/agent-session-queue-pause.d.ts.map +1 -1
- package/dist/core/agent-session-queue-pause.js +2 -1
- package/dist/core/agent-session-queue-pause.js.map +1 -1
- package/dist/core/context-tool-pairing.d.ts +10 -14
- package/dist/core/context-tool-pairing.d.ts.map +1 -1
- package/dist/core/context-tool-pairing.js +99 -28
- package/dist/core/context-tool-pairing.js.map +1 -1
- package/dist/core/messages.d.ts.map +1 -1
- package/dist/core/messages.js +2 -1
- package/dist/core/messages.js.map +1 -1
- package/dist/core/system-prompt.js +2 -2
- package/dist/core/system-prompt.js.map +1 -1
- package/docs/computer-use.md +31 -7
- package/docs/getting-started/first-session.md +1 -1
- package/docs/skills.md +2 -2
- package/docs/usage.md +1 -1
- package/docs/workflows/operations.md +3 -1
- package/docs/workflows/reliable-design.md +1 -1
- package/docs/workflows/verification.md +25 -7
- package/docs/workflows.md +1 -1
- package/npm-shrinkwrap.json +32 -32
- package/package.json +3 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-queue-pause.js","sourceRoot":"","sources":["../../src/core/agent-session-queue-pause.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,kCAAkC,EAAE,MAAM,wCAAwC,CAAC;AAG5F,KAAK,UAAU,0BAA0B,CAAC,UAAoC;IAC7E,IAAI,iBAA4C,CAAC;IACjD,MAAM,OAAO,CAAC,GAAG,CAChB,UAAU,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,EAAE,EAAE;QACjC,IAAI,CAAC;YACJ,MAAM,QAAQ,CAAC;QAChB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YAChB,iBAAiB,KAAK,GAAG,EAAE;gBAC1B,MAAM,KAAK,CAAC;YACb,CAAC,CAAC;QACH,CAAC;IACF,CAAC,CAAC,CACF,CAAC;IACF,iBAAiB,EAAE,EAAE,CAAC;AACvB,CAAC;AAED,yFAAyF;AACzF,MAAM,UAAU,2BAA2B,CAC1C,UAAkD;IAElD,MAAM,OAAO,GAAG,UAAU,CAAC,MAAM,CAAC,CAAC,QAAQ,EAA6B,EAAE,CAAC,QAAQ,KAAK,SAAS,CAAC,CAAC;IACnG,OAAO,OAAO,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,0BAA0B,CAAC,OAAO,CAAC,CAAC;AAC/E,CAAC;AAED,uFAAuF;AACvF,MAAM,UAAU,mBAAmB;IAClC,MAAM,KAAK,GAAG,kCAAkC,CAAC,IAAI,CAAC,CAAC;IACvD,IAAI,KAAK,KAAK,IAAI,EAAE,CAAC;QACpB,KAAK,CAAC,mBAAmB,EAAE,CAAC;QAC5B,OAAO;IACR,CAAC;IACD,IAAI,IAAI,CAAC,qBAAqB;QAAE,OAAO;IACvC,IAAI,CAAC,qBAAqB,GAAG,IAAI,CAAC;IAClC,IAAI,CAAC,iCAAiC,GAAG,SAAS,CAAC;IACnD,IAA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AC,KAAK,CAAC,WAAW,EAAE,CAAC;QAC/B,MAAM,OAAO,CAAC,UAAU,CACvB,CAAC,gBAAgB,EAAE,mBAAmB,EAAE,aAAa,CAAC,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,KAAK,SAAS,CAAC,CAC7F,CAAC;QACF,MAAM,IAAI,CAAC,gBAAgB,CAAC;IAC7B,CAAC,CAAC,EAAE,CAAC;IACL,IAAI,IAAI,CAAC,qBAAqB,EAAE,CAAC;QAChC,MAAM,OAAO,GAAG,2BAA2B,CAAC,CAAC,IAAI,CAAC,iCAAiC,EAAE,QAAQ,CAAC,CAAC,CAAC;QAChG,IAAI,OAAO,KAAK,SAAS;YAAE,OAAO,QAAQ,CAAC;QAC3C,IAAI,CAAC,iCAAiC,GAAG,OAAO,CAAC;QACjD,KAAK,OAAO,CAAC,KAAK,CAAC,GAAG,EAAE,GAAE,CAAC,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,QAAQ,CAAC;AACjB,CAAC","sourcesContent":["import { resolveWorkflowStageDeliveryTarget } from \"./agent-session-delivery-forwarding.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\n\nasync function settlePauseAbortBoundaries(boundaries: readonly Promise<void>[]): Promise<void> {\n\tlet throwFirstFailure: (() => never) | undefined;\n\tawait Promise.all(\n\t\tboundaries.map(async (boundary) => {\n\t\t\ttry {\n\t\t\t\tawait boundary;\n\t\t\t} catch (error) {\n\t\t\t\tthrowFirstFailure ??= () => {\n\t\t\t\t\tthrow error;\n\t\t\t\t};\n\t\t\t}\n\t\t}),\n\t);\n\tthrowFirstFailure?.();\n}\n\n/** Compose pause settlement without exposing an early rejection from one constituent. */\nexport function composePauseAbortBoundaries(\n\tboundaries: readonly (Promise<void> | undefined)[],\n): Promise<void> | undefined {\n\tconst pending = boundaries.filter((boundary): boundary is Promise<void> => boundary !== undefined);\n\treturn pending.length === 0 ? undefined : settlePauseAbortBoundaries(pending);\n}\n\n/** Synchronously hold raw queue entries before pausing and aborting an active turn. */\nexport function pauseQueuedMessages(this: AgentSession): void {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) {\n\t\towner.pauseQueuedMessages();\n\t\treturn;\n\t}\n\tif (this._queuedMessagesPaused) return;\n\tthis._queuedMessagesPaused = true;\n\tthis._queuedMessagesPauseAbortBoundary = undefined;\n\tthis._ensureActiveInterruptQueueHold();\n}\n\n/** Release a pause hold without starting a turn; report whether raw work was released. */\nexport async function resumeQueuedMessages(this: AgentSession, beforeRelease?: () => void): Promise<boolean> {\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner.resumeQueuedMessages(beforeRelease);\n\tif (!this._queuedMessagesPaused) return false;\n\tconst abortBoundary = this._queuedMessagesPauseAbortBoundary;\n\tif (abortBoundary !== undefined) {\n\t\ttry {\n\t\t\tawait abortBoundary;\n\t\t} catch (error) {\n\t\t\t// Keep the hold closed across a failed abort. The rejecting explicit\n\t\t\t// resume observes that boundary and retires it so a later resume can retry.\n\t\t\tif (this._queuedMessagesPauseAbortBoundary === abortBoundary) {\n\t\t\t\tthis._queuedMessagesPauseAbortBoundary = undefined;\n\t\t\t}\n\t\t\tthrow error;\n\t\t}\n\t}\n\tif (this._pendingInterruptDeliveries > 0) await this._interruptDeliveryQueue;\n\t// An admitted-message recovery turn is a session-owned turn starter that begins\n\t// after the abort boundary settles. Releasing while it streams would let the\n\t// caller's follow-on prompt hit the streaming guard (issue #2362).\n\tconst recoveryTurn = this._admittedRecoveryTurn;\n\tif (recoveryTurn !== undefined) await recoveryTurn;\n\tif (!this._queuedMessagesPaused) return false;\n\tbeforeRelease?.();\n\tconst hold = this._activeInterruptQueueHold;\n\tconst released = hold !== undefined && (hold.steering.length > 0 || hold.followUp.length > 0);\n\tthis._queuedMessagesPaused = false;\n\tthis._agentRunAbortRequested = false;\n\tthis._queuedMessagesPauseAbortBoundary = undefined;\n\tthis._restoreAndClearActiveInterruptQueueHold();\n\treturn released;\n}\n\n/** Abort an ordinary turn and synchronously publish its pause-associated settlement boundary. */\nexport function abort(this: AgentSession): Promise<void> {\n\tthis._extensionRunner.cancelHostInput();\n\tconst owner = resolveWorkflowStageDeliveryTarget(this);\n\tif (owner !== this) return owner.abort();\n\treturn abortCurrentGeneration.call(this);\n}\n\n/** Internal teardown never redirects cancellation into a replacement generation. */\nexport function abortCurrentGeneration(this: AgentSession): Promise<void> {\n\tthis._extensionRunner.cancelHostInput();\n\tthis._agentRunAbortRequested = true;\n\tthis._cacheWarmer?.cancel();\n\tthis._postCompactionContinuationToken += 1;\n\tif (this._subagentMessageAdmission) {\n\t\t// Cancellation is terminal for a child. Hold even deliveries whose\n\t\t// protocol-safe persistence is still pending so they cannot restart it.\n\t\tthis._subagentMessageAdmission.seal();\n\t}\n\tconst ownsStageDeliveries = resolveWorkflowStageDeliveryTarget(this) === this;\n\tif ((this._subagentMessageAdmission || this._workflowStageAdmission) && ownsStageDeliveries) {\n\t\t// Unlike a priority interrupt's native abort, an explicit stop must also\n\t\t// block deferred input from starting a turn after preflight or settlement.\n\t\t// A stage's generation remains host-owned; only explicit resume releases it.\n\t\tthis.pauseQueuedMessages();\n\t}\n\tthis.abortRetry();\n\tthis._compactionAbortController?.abort();\n\tthis._autoCompactionAbortController?.abort();\n\tthis._branchSummaryAbortController?.abort();\n\tthis.agent.abort();\n\tconst manualCompaction = this._manualCompactionPromise;\n\tconst automaticCompaction = this._autoCompactionCompletion;\n\tconst branchSummary = this._branchSummaryCompletion;\n\tconst boundary = (async () => {\n\t\tawait this.agent.waitForIdle();\n\t\tawait Promise.allSettled(\n\t\t\t[manualCompaction, automaticCompaction, branchSummary].filter((value) => value !== undefined),\n\t\t);\n\t\tawait this._agentEventQueue;\n\t})();\n\tif (this._queuedMessagesPaused) {\n\t\tconst tracked = composePauseAbortBoundaries([this._queuedMessagesPauseAbortBoundary, boundary]);\n\t\tif (tracked === undefined) return boundary;\n\t\tthis._queuedMessagesPauseAbortBoundary = tracked;\n\t\tvoid tracked.catch(() => {});\n\t}\n\treturn boundary;\n}\n"]}
|
|
@@ -1,19 +1,15 @@
|
|
|
1
1
|
import type { AgentMessage } from "@earendil-works/pi-agent-core";
|
|
2
|
+
export declare function findDuplicateToolCallIds(messages: readonly AgentMessage[]): string[];
|
|
3
|
+
/** Throw a descriptive error when context carries the same assistant turn more than once. */
|
|
4
|
+
export declare function assertToolPairingInvariant(messages: readonly AgentMessage[]): void;
|
|
2
5
|
/**
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* `repairOrphanToolResults` already collapses the recoverable forms of this
|
|
6
|
-
* invariant at conversion time: orphaned or duplicate `tool_result` blocks and
|
|
7
|
-
* tool calls interrupted before their result was persisted. None need to reach
|
|
8
|
-
* the provider.
|
|
6
|
+
* Give every tool call a non-empty id that no earlier call in the context uses.
|
|
9
7
|
*
|
|
10
|
-
* A
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
8
|
+
* A reused or empty id is renamed after its assistant turn, and the tool results
|
|
9
|
+
* following that turn (up to the next assistant message) are renamed with it in
|
|
10
|
+
* call order. Renaming depends only on earlier messages, so the derived ids stay
|
|
11
|
+
* stable as the conversation grows and do not invalidate provider prompt caches.
|
|
12
|
+
* Messages that need no change are returned as the same objects.
|
|
15
13
|
*/
|
|
16
|
-
export declare function
|
|
17
|
-
/** Throw a descriptive error when context carries a tool call id more than once. */
|
|
18
|
-
export declare function assertToolPairingInvariant(messages: readonly AgentMessage[]): void;
|
|
14
|
+
export declare function uniquifyToolCallIds<TMessage extends AgentMessage>(messages: TMessage[]): TMessage[];
|
|
19
15
|
//# sourceMappingURL=context-tool-pairing.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"context-tool-pairing.d.ts","sourceRoot":"","sources":["../../src/core/context-tool-pairing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;
|
|
1
|
+
{"version":3,"file":"context-tool-pairing.d.ts","sourceRoot":"","sources":["../../src/core/context-tool-pairing.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAqDlE,wBAAgB,wBAAwB,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,MAAM,EAAE,CAiBpF;AAED,6FAA6F;AAC7F,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,SAAS,YAAY,EAAE,GAAG,IAAI,CASlF;AAoBD;;;;;;;;GAQG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,SAAS,YAAY,EAAE,QAAQ,EAAE,QAAQ,EAAE,GAAG,QAAQ,EAAE,CAkCnG"}
|
|
@@ -1,43 +1,48 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
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
|
|
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
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
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
|
-
|
|
30
|
-
if (
|
|
31
|
-
|
|
32
|
-
|
|
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
|
|
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,CAAC;IAC3D,OAAO,KAAK,CAAC,OAA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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 ? uniquified : messages;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/core/messages.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AACnG,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;
|
|
1
|
+
{"version":3,"file":"messages.d.ts","sourceRoot":"","sources":["../../src/core/messages.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,OAAO,EAAE,WAAW,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AACnG,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAGlE,eAAO,MAAM,qBAAqB,iGAGjC,CAAC;AAEF,eAAO,MAAM,qBAAqB,eAAe,CAAC;AAElD;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACpC,IAAI,EAAE,eAAe,CAAC;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,GAAG,SAAS,CAAC;IAC7B,SAAS,EAAE,OAAO,CAAC;IACnB,SAAS,EAAE,OAAO,CAAC;IACnB,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,SAAS,EAAE,MAAM,CAAC;IAClB,qEAAqE;IACrE,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED;;;GAGG;AAEH,MAAM,WAAW,aAAa,CAAC,CAAC,GAAG,OAAO;IACzC,IAAI,EAAE,QAAQ,CAAC;IACf,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,EAAE,MAAM,GAAG,CAAC,WAAW,GAAG,YAAY,CAAC,EAAE,CAAC;IACjD,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,CAAC,EAAE,CAAC,CAAC;IACZ,SAAS,EAAE,MAAM,CAAC;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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,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;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AAC;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,qBAAq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IAAI,EAAE,MAAM;oBACZ,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAe,EAAE,IAAI,EAAE,qBAAqB,GAAG,CAAC,CAAC,OAAO,GAAG,qBAAqB,EAAE,CAAC;oBACrG,SAAS,EAAE,CAAC,CAAC,SAAS;iBACtB,CAAC;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,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
|
|
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)`;
|