@causyne/agent 1.20.10 → 1.20.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.
- package/LICENSE +1 -1
- package/docs/ARCHITECTURE.md +24 -1
- package/package.json +1 -1
- package/src/acp/client.js +9 -2
- package/src/acp/client.ts +11 -2
- package/src/acp/protocol.ts +9 -0
- package/src/agentLoop.js +504 -119
- package/src/agentLoop.ts +477 -121
- package/src/browser/browserRuntime.js +47 -0
- package/src/browser/browserRuntime.ts +45 -0
- package/src/browser/causyneBrowser.js +60 -31
- package/src/browser/causyneBrowser.ts +37 -12
- package/src/browser/workspacePreview.js +52 -0
- package/src/browser/workspacePreview.ts +49 -0
- package/src/core/planCache.js +5 -0
- package/src/core/planCache.ts +5 -0
- package/src/decisionPolicy.js +9 -0
- package/src/decisionPolicy.ts +8 -0
- package/src/historyPruner.js +251 -0
- package/src/historyPruner.ts +263 -0
- package/src/infra/atomicWriter.js +49 -0
- package/src/infra/atomicWriter.ts +63 -0
- package/src/infra/telemetry.js +38 -0
- package/src/infra/telemetry.ts +68 -0
- package/src/observer/coldObserver.js +12 -7
- package/src/observer/coldObserver.ts +12 -7
- package/src/observer/evidence.js +8 -2
- package/src/observer/evidence.ts +9 -2
- package/src/outputRecovery.js +36 -0
- package/src/outputRecovery.ts +33 -0
- package/src/providers/acp.js +114 -46
- package/src/providers/acp.ts +129 -46
- package/src/providers/antigravity.js +262 -91
- package/src/providers/antigravity.ts +270 -99
- package/src/providers/antigravityBridge.js +58 -0
- package/src/providers/antigravityBridge.ts +51 -0
- package/src/providers/base.d.ts +9 -0
- package/src/providers/budgetEnforcer.js +110 -0
- package/src/providers/budgetEnforcer.ts +122 -0
- package/src/providers/collaborationPolicy.js +6 -0
- package/src/providers/collaborationPolicy.ts +7 -0
- package/src/providers/loopGuard.js +84 -0
- package/src/providers/loopGuard.ts +105 -0
- package/src/providers/pi.js +19 -6
- package/src/providers/pi.ts +19 -7
- package/src/providers/toolContracts.js +36 -0
- package/src/providers/toolContracts.ts +48 -0
- package/src/session/sidechainEvents.js +49 -0
- package/src/session/sidechainEvents.ts +98 -0
- package/src/skillsManager.d.ts +1 -0
- package/src/smartToolsUse.js +123 -4
- package/src/smartToolsUse.ts +136 -4
- package/src/stallGuard.js +3 -12
- package/src/stallGuard.ts +3 -12
- package/src/subagent/sidechainHarness.js +66 -0
- package/src/subagent/sidechainHarness.ts +91 -0
- package/src/taskContinuation.js +12 -0
- package/src/taskContinuation.ts +13 -0
- package/src/tokenTracker.js +406 -539
- package/src/tokenTracker.ts +569 -0
- package/src/toolPacks.d.ts +2 -0
- package/src/toolPacks.js +1 -1
- package/src/tools/argumentValidation.js +56 -0
- package/src/tools/argumentValidation.ts +50 -0
- package/src/tools/browserAutomator.js +2 -2
- package/src/tools/browserAutomator.ts +3 -2
- package/src/tools/deferredMcpSearch.js +188 -201
- package/src/tools/deferredMcpSearch.ts +250 -0
- package/src/tools/generateMediaViaApi.js +305 -331
- package/src/tools/generateMediaViaApi.ts +330 -0
- package/src/tools/historyPruner.js +5 -0
- package/src/tools/historyPruner.ts +5 -0
- package/src/tools/payloadSanitizer.js +92 -0
- package/src/tools/payloadSanitizer.ts +113 -0
- package/src/tools/registry.d.ts +1 -0
- package/src/tools/sysRun.js +47 -18
- package/src/tools/sysRun.ts +52 -20
- package/src/tools/toolOutputStore.js +180 -0
- package/src/tools/toolOutputStore.ts +209 -0
- package/src/tools/toolSelfRepair.js +26 -1
- package/src/tools/toolSelfRepair.ts +25 -1
- package/src/tui/chatRenderer.d.ts +1 -0
- package/src/tui/chatRenderer.js +4 -2
- package/src/tui/codeStreamRenderer.js +36 -8
- package/src/tui/codeStreamRenderer.ts +38 -8
- package/src/tui/stageSurface.js +1 -0
- package/src/tui/text.js +4 -1
- package/src/tokenTracker.d.ts +0 -1
package/src/providers/acp.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { formatToolContracts, toolContractUpdate } from './toolContracts.js';
|
|
1
2
|
import { canonicalModelId } from '../modelIds.js';
|
|
2
3
|
import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
|
|
3
4
|
import { saveCachedModels } from '../dynamicCatalogue.js';
|
|
@@ -6,6 +7,23 @@ import { AcpClient } from '../acp/client.js';
|
|
|
6
7
|
import { getPeerProfile } from '../acp/peerProfiles.js';
|
|
7
8
|
import { BUILTIN_PEER_PRESETS } from '../acp/agentCatalog.js';
|
|
8
9
|
import type { RequestPermissionRequest, SessionUpdate } from '../acp/protocol.js';
|
|
10
|
+
import { createHash } from 'node:crypto';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { PEER_COLLABORATION_POLICY } from './collaborationPolicy.js';
|
|
13
|
+
|
|
14
|
+
interface AcpTransportSnapshot {
|
|
15
|
+
conversationId: string;
|
|
16
|
+
workspaceRoot: string;
|
|
17
|
+
systemHashes: string[];
|
|
18
|
+
historyHashes: string[];
|
|
19
|
+
toolHash: string;
|
|
20
|
+
tools: unknown[];
|
|
21
|
+
lastResponse: { content: string; toolCalls: ChatResponseToolCall[] };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function fingerprint(value: unknown): string {
|
|
25
|
+
return createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
26
|
+
}
|
|
9
27
|
|
|
10
28
|
export function isAcpProvider(provider?: string | null): boolean {
|
|
11
29
|
if (!provider) return false;
|
|
@@ -21,10 +39,13 @@ export class AcpProvider extends LLMProvider {
|
|
|
21
39
|
private activeClient: AcpClient | null = null;
|
|
22
40
|
private activeSessionId: string | null = null;
|
|
23
41
|
private currentTurnAborted = false;
|
|
42
|
+
private currentTurnSawAction = false;
|
|
24
43
|
private currentTurnChunkHandler: ((chunk: string) => void) | null = null;
|
|
25
44
|
private currentTurnReasoningHandler: ((chunk: string) => void) | null = null;
|
|
26
45
|
private currentTurnNativeActionHandler: ((action: ChatResponseAction) => void) | null = null;
|
|
27
46
|
private readonly liveFileActions = new Map<string, ChatResponseAction>();
|
|
47
|
+
private transportSnapshot: AcpTransportSnapshot | null = null;
|
|
48
|
+
private peerServices: ChatOptions | null = null;
|
|
28
49
|
|
|
29
50
|
constructor(config: ProviderConfig = {}) {
|
|
30
51
|
super(config);
|
|
@@ -73,16 +94,10 @@ export class AcpProvider extends LLMProvider {
|
|
|
73
94
|
|
|
74
95
|
formatConversation(messages: any[], tools: any[] = []): string {
|
|
75
96
|
const lines: string[] = [];
|
|
76
|
-
lines.push('[System Instructions]\nYou are
|
|
97
|
+
lines.push('[System Instructions]\nYou are collaborating with Causyne Agent over the Agent Client Protocol (ACP). Use the negotiated ACP capabilities and preserve configured native tools, MCPs, skills, and project settings. When requesting workspace tools from the Causyne host, format your calls as:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\nCausyne Agent coordinates, validates, and executes the tools in the active workspace and returns results back to you, preserving your full reasoning and ACP capabilities. ' + PEER_COLLABORATION_POLICY + '\n\n[Language & Communication Directive]\nDynamically reflect and match the exact language used by the user in their prompt. Respond naturally in that same language.');
|
|
77
98
|
|
|
78
99
|
if (tools && tools.length > 0) {
|
|
79
|
-
const toolSummaries = tools
|
|
80
|
-
const name = t.name || t.function?.name || 'unknown';
|
|
81
|
-
const desc = t.description || t.function?.description || '';
|
|
82
|
-
const params = t.parameters || t.input_schema || t.function?.parameters || {};
|
|
83
|
-
const paramKeys = Object.keys(params.properties || {}).join(', ');
|
|
84
|
-
return `- ${name}(${paramKeys}): ${desc}`;
|
|
85
|
-
}).join('\n');
|
|
100
|
+
const toolSummaries = formatToolContracts(tools);
|
|
86
101
|
lines.push(`[Available Tools]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`);
|
|
87
102
|
}
|
|
88
103
|
const seenToolOutputs = new Set<string>();
|
|
@@ -133,7 +148,7 @@ export class AcpProvider extends LLMProvider {
|
|
|
133
148
|
return lines.join('\n\n');
|
|
134
149
|
}
|
|
135
150
|
|
|
136
|
-
formatPromptBlocks(messages: any[], tools: any[] = [], imageSupport = false): any[] {
|
|
151
|
+
formatPromptBlocks(messages: any[], tools: any[] = [], imageSupport = false, includeBridgeInstructions = true, toolContext = ''): any[] {
|
|
137
152
|
const blocks: any[] = [];
|
|
138
153
|
let pending: string[] = [];
|
|
139
154
|
const flush = () => {
|
|
@@ -142,21 +157,17 @@ export class AcpProvider extends LLMProvider {
|
|
|
142
157
|
pending = [];
|
|
143
158
|
};
|
|
144
159
|
|
|
145
|
-
|
|
160
|
+
if (includeBridgeInstructions) {
|
|
161
|
+
pending.push('[System Instructions]\nYou are collaborating with Causyne Agent over the Agent Client Protocol (ACP). Use the negotiated ACP capabilities and preserve configured native tools, MCPs, skills, and project settings. When requesting workspace tools from the Causyne host, format your calls as:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\nCausyne Agent coordinates, validates, and executes the tools in the active workspace and returns results back to you, preserving your full reasoning and ACP capabilities. ' + PEER_COLLABORATION_POLICY);
|
|
162
|
+
}
|
|
146
163
|
|
|
147
164
|
if (tools && tools.length > 0) {
|
|
148
|
-
const toolSummaries = tools
|
|
149
|
-
|
|
150
|
-
const desc = t.description || t.function?.description || '';
|
|
151
|
-
const params = t.parameters || t.input_schema || t.function?.parameters || {};
|
|
152
|
-
const paramKeys = Object.keys(params.properties || {}).join(', ');
|
|
153
|
-
return `- ${name}(${paramKeys}): ${desc}`;
|
|
154
|
-
}).join('\n');
|
|
155
|
-
pending.push(`[Available Tools]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`);
|
|
165
|
+
const toolSummaries = formatToolContracts(tools);
|
|
166
|
+
pending.push(`[Current Available Tools — this list replaces earlier tool lists]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`);
|
|
156
167
|
}
|
|
157
168
|
|
|
158
|
-
|
|
159
|
-
|
|
169
|
+
if (toolContext) pending.push(toolContext);
|
|
170
|
+
|
|
160
171
|
for (const msg of messages) {
|
|
161
172
|
const role = this._roleLabel(msg);
|
|
162
173
|
let text = '';
|
|
@@ -166,23 +177,10 @@ export class AcpProvider extends LLMProvider {
|
|
|
166
177
|
text = msg.content.map((c: any) => typeof c === 'string' ? c : (c?.text || '')).filter(Boolean).join('\n');
|
|
167
178
|
}
|
|
168
179
|
|
|
169
|
-
if (msg.role === 'tool' && text.trim()) {
|
|
170
|
-
const normalized = text.trim();
|
|
171
|
-
if (seenToolOutputs.has(normalized)) {
|
|
172
|
-
continue;
|
|
173
|
-
}
|
|
174
|
-
seenToolOutputs.add(normalized);
|
|
175
|
-
}
|
|
176
|
-
|
|
177
180
|
if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
|
|
178
181
|
for (const tc of msg.tool_calls) {
|
|
179
182
|
const fn = tc.function || {};
|
|
180
183
|
const fnArgs = typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {});
|
|
181
|
-
const callSig = `${fn.name}:${fnArgs}`;
|
|
182
|
-
if (seenAssistantCalls.has(callSig)) {
|
|
183
|
-
continue;
|
|
184
|
-
}
|
|
185
|
-
seenAssistantCalls.add(callSig);
|
|
186
184
|
text += `\n<tool_call>{"name": "${fn.name}", "arguments": ${fnArgs}}</tool_call>`;
|
|
187
185
|
}
|
|
188
186
|
}
|
|
@@ -310,7 +308,7 @@ export class AcpProvider extends LLMProvider {
|
|
|
310
308
|
return calls;
|
|
311
309
|
}
|
|
312
310
|
|
|
313
|
-
private async getOrCreateClient(signal?: AbortSignal): Promise<{ client: AcpClient; sessionId: string }> {
|
|
311
|
+
private async getOrCreateClient(signal?: AbortSignal, workspaceRoot = process.cwd()): Promise<{ client: AcpClient; sessionId: string }> {
|
|
314
312
|
if (signal?.aborted) {
|
|
315
313
|
const abortErr = new Error('ACP request aborted by user');
|
|
316
314
|
abortErr.name = 'AbortError';
|
|
@@ -323,13 +321,20 @@ export class AcpProvider extends LLMProvider {
|
|
|
323
321
|
const client = new AcpClient({
|
|
324
322
|
command: this.command,
|
|
325
323
|
args: this.args,
|
|
326
|
-
cwd:
|
|
324
|
+
cwd: workspaceRoot,
|
|
327
325
|
promptTimeoutMs: 900_000,
|
|
326
|
+
allowHostTools: true,
|
|
328
327
|
permissionHandler: async (req: RequestPermissionRequest) => {
|
|
329
|
-
if (this.currentTurnAborted || signal?.aborted) return { outcome: 'cancelled' };
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
328
|
+
if (this.currentTurnAborted || this.peerServices?.signal?.aborted) return { outcome: 'cancelled' };
|
|
329
|
+
return this.peerServices?.onPeerPermission?.(req) ?? { outcome: 'cancelled' };
|
|
330
|
+
},
|
|
331
|
+
fsReadHandler: async (file, options) => {
|
|
332
|
+
if (!this.peerServices?.onPeerFileRead) throw new Error('The ACP client has no file-read service attached');
|
|
333
|
+
return this.peerServices.onPeerFileRead(file, options);
|
|
334
|
+
},
|
|
335
|
+
fsWriteHandler: async (file, content) => {
|
|
336
|
+
if (!this.peerServices?.onPeerFileWrite) throw new Error('The ACP client has no file-write service attached');
|
|
337
|
+
await this.peerServices.onPeerFileWrite(file, content);
|
|
333
338
|
},
|
|
334
339
|
onUpdate: (_sessionId: string, update: SessionUpdate) => {
|
|
335
340
|
if (this.currentTurnAborted) return;
|
|
@@ -344,10 +349,13 @@ export class AcpProvider extends LLMProvider {
|
|
|
344
349
|
const text = updateObj.content?.type === 'text' ? updateObj.content.text : '';
|
|
345
350
|
if (text && this.currentTurnChunkHandler) this.currentTurnChunkHandler(text);
|
|
346
351
|
} else if (updateObj.sessionUpdate === 'tool_call' || updateObj.sessionUpdate === 'tool_call_update') {
|
|
352
|
+
this.currentTurnSawAction = true;
|
|
347
353
|
const id = String(updateObj.toolCallId || '');
|
|
348
354
|
const earlier = this.liveFileActions.get(id);
|
|
349
355
|
const kind = updateObj.kind || (earlier?.name === 'fs_edit' ? 'edit' : earlier?.name === 'fs_delete' ? 'delete' : earlier?.name === 'fs_move' ? 'move' : '');
|
|
350
|
-
const name = kind === 'edit' ? 'fs_edit' : kind === 'delete' ? 'fs_delete' : kind === 'move' ? 'fs_move'
|
|
356
|
+
const name = kind === 'edit' ? 'fs_edit' : kind === 'delete' ? 'fs_delete' : kind === 'move' ? 'fs_move'
|
|
357
|
+
: kind === 'read' ? 'fs_read' : kind === 'search' ? 'codebase_search' : kind === 'fetch' ? 'web_fetch'
|
|
358
|
+
: kind === 'execute' ? 'sysRun' : String(updateObj.title || earlier?.name || 'provider_tool');
|
|
351
359
|
if (name && id) {
|
|
352
360
|
const diff = Array.isArray(updateObj.content)
|
|
353
361
|
? updateObj.content.find((item: any) => item?.type === 'diff')
|
|
@@ -360,7 +368,7 @@ export class AcpProvider extends LLMProvider {
|
|
|
360
368
|
...(updateObj.locations?.[0]?.path ? { path: updateObj.locations[0].path } : {})
|
|
361
369
|
};
|
|
362
370
|
const status = updateObj.status === 'completed' ? 'completed' : updateObj.status === 'failed' ? 'failed' : 'running';
|
|
363
|
-
const action: ChatResponseAction = { name, status, parameters,
|
|
371
|
+
const action: ChatResponseAction = { id: `acp:${id}`, name, status, parameters,
|
|
364
372
|
detail: String(parameters.path || updateObj.title || '') };
|
|
365
373
|
if (status === 'running') this.liveFileActions.set(id, action);
|
|
366
374
|
else this.liveFileActions.delete(id);
|
|
@@ -377,7 +385,7 @@ export class AcpProvider extends LLMProvider {
|
|
|
377
385
|
});
|
|
378
386
|
|
|
379
387
|
await client.start(signal);
|
|
380
|
-
const sessionId = await client.newSession(
|
|
388
|
+
const sessionId = await client.newSession(workspaceRoot, this.peerServices?.peerMcpServers || [], signal);
|
|
381
389
|
|
|
382
390
|
const sessionModels = client.getSessionModels(sessionId);
|
|
383
391
|
const liveModels = sessionModels.availableModels;
|
|
@@ -455,6 +463,7 @@ export class AcpProvider extends LLMProvider {
|
|
|
455
463
|
const client = this.activeClient;
|
|
456
464
|
this.activeClient = null;
|
|
457
465
|
this.activeSessionId = null;
|
|
466
|
+
this.transportSnapshot = null;
|
|
458
467
|
if (client) {
|
|
459
468
|
try {
|
|
460
469
|
await client.close();
|
|
@@ -465,7 +474,9 @@ export class AcpProvider extends LLMProvider {
|
|
|
465
474
|
}
|
|
466
475
|
|
|
467
476
|
override async chat(messages: any[], options: ChatOptions = {}): Promise<ChatResponse> {
|
|
477
|
+
this.peerServices = options;
|
|
468
478
|
this.currentTurnAborted = Boolean(options.signal?.aborted);
|
|
479
|
+
this.currentTurnSawAction = false;
|
|
469
480
|
if (this.currentTurnAborted) {
|
|
470
481
|
const abortErr = new Error('ACP request aborted by user');
|
|
471
482
|
abortErr.name = 'AbortError';
|
|
@@ -480,11 +491,57 @@ export class AcpProvider extends LLMProvider {
|
|
|
480
491
|
};
|
|
481
492
|
options.signal?.addEventListener('abort', onAbort, { once: true });
|
|
482
493
|
try {
|
|
483
|
-
const
|
|
494
|
+
const workspaceRoot = path.resolve(String(options.workspaceRoot || process.cwd()));
|
|
495
|
+
const conversationId = String(options.conversationId || options.taskId || '__default__');
|
|
496
|
+
const systemMessages = messages.filter(message => message.role === 'system');
|
|
497
|
+
const historyMessages = messages.filter(message => message.role !== 'system');
|
|
498
|
+
const systemHashes = systemMessages.map(fingerprint);
|
|
499
|
+
const historyHashes = historyMessages.map(fingerprint);
|
|
500
|
+
const toolHash = fingerprint(options.tools || []);
|
|
501
|
+
let previous = this.transportSnapshot;
|
|
502
|
+
|
|
503
|
+
const sessionChanged = previous && (
|
|
504
|
+
previous.workspaceRoot !== workspaceRoot || previous.conversationId !== conversationId
|
|
505
|
+
);
|
|
506
|
+
const historyDiverged = previous && (
|
|
507
|
+
historyHashes.length < previous.historyHashes.length ||
|
|
508
|
+
previous.historyHashes.some((hash, index) => historyHashes[index] !== hash)
|
|
509
|
+
);
|
|
510
|
+
const systemShapeChanged = previous && systemHashes.length < previous.systemHashes.length;
|
|
511
|
+
if (sessionChanged || historyDiverged || systemShapeChanged) {
|
|
512
|
+
await this.close();
|
|
513
|
+
previous = null;
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
const { client, sessionId } = await this.getOrCreateClient(options.signal, workspaceRoot);
|
|
484
517
|
|
|
485
518
|
const supportsImages = client.agentCapabilities?.promptCapabilities?.image === true;
|
|
486
|
-
|
|
487
|
-
|
|
519
|
+
let promptMessages = messages;
|
|
520
|
+
let promptTools = options.tools || [];
|
|
521
|
+
let includeBridgeInstructions = true;
|
|
522
|
+
let toolContext = '';
|
|
523
|
+
if (previous) {
|
|
524
|
+
const changedSystem = systemMessages.filter((_, index) => systemHashes[index] !== previous.systemHashes[index]);
|
|
525
|
+
const newHistory = historyMessages.slice(previous.historyHashes.length);
|
|
526
|
+
// The peer already generated its previous assistant turn. AgentLoop
|
|
527
|
+
// records that turn for stateless BYOK APIs; replaying it into ACP would
|
|
528
|
+
// duplicate the peer's own response before the next tool result.
|
|
529
|
+
const firstNew = newHistory[0];
|
|
530
|
+
if (firstNew?.role === 'assistant' &&
|
|
531
|
+
firstNew.content === previous.lastResponse.content &&
|
|
532
|
+
fingerprint(firstNew.tool_calls || []) === fingerprint(previous.lastResponse.toolCalls)) {
|
|
533
|
+
newHistory.shift();
|
|
534
|
+
}
|
|
535
|
+
promptMessages = [
|
|
536
|
+
...changedSystem.map(message => ({ ...message, content: `[Current system context — replaces the prior version of this section]\n${message.content}` })),
|
|
537
|
+
...newHistory
|
|
538
|
+
];
|
|
539
|
+
toolContext = toolContractUpdate(options.tools || [], previous.tools);
|
|
540
|
+
promptTools = [];
|
|
541
|
+
includeBridgeInstructions = false;
|
|
542
|
+
}
|
|
543
|
+
let promptBlocks = this.formatPromptBlocks(promptMessages, promptTools, supportsImages, includeBridgeInstructions, toolContext);
|
|
544
|
+
let promptText = promptBlocks.filter(b => b.type === 'text').map(b => b.text).join('\n\n');
|
|
488
545
|
|
|
489
546
|
let result;
|
|
490
547
|
try {
|
|
@@ -493,9 +550,14 @@ export class AcpProvider extends LLMProvider {
|
|
|
493
550
|
if (this.currentTurnAborted || options.signal?.aborted || promptErr?.name === 'AbortError') {
|
|
494
551
|
throw promptErr;
|
|
495
552
|
}
|
|
553
|
+
// Replaying after a peer executed native tools can duplicate mutations
|
|
554
|
+
// and charges. Restart only before any observed native action.
|
|
555
|
+
if (this.currentTurnSawAction) throw promptErr;
|
|
496
556
|
// If peer failed before any user abort, try recreating client once in case connection dropped
|
|
497
557
|
await this.close();
|
|
498
|
-
const fresh = await this.getOrCreateClient(options.signal);
|
|
558
|
+
const fresh = await this.getOrCreateClient(options.signal, workspaceRoot);
|
|
559
|
+
promptBlocks = this.formatPromptBlocks(messages, options.tools, fresh.client.agentCapabilities?.promptCapabilities?.image === true);
|
|
560
|
+
promptText = promptBlocks.filter(b => b.type === 'text').map(b => b.text).join('\n\n');
|
|
499
561
|
result = await fresh.client.prompt(fresh.sessionId, promptBlocks, options.signal);
|
|
500
562
|
}
|
|
501
563
|
|
|
@@ -511,6 +573,11 @@ export class AcpProvider extends LLMProvider {
|
|
|
511
573
|
// Strip tool call XML from chat content display
|
|
512
574
|
let content = rawContent.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim();
|
|
513
575
|
|
|
576
|
+
this.transportSnapshot = {
|
|
577
|
+
conversationId, workspaceRoot, systemHashes, historyHashes, toolHash, tools: structuredClone(options.tools || []),
|
|
578
|
+
lastResponse: { content: content || (toolCalls.length > 0 ? '' : `Turn completed by ${this.peerId} over ACP.`), toolCalls }
|
|
579
|
+
};
|
|
580
|
+
|
|
514
581
|
const response: ChatResponse = {
|
|
515
582
|
content: content || (toolCalls.length > 0 ? '' : `Turn completed by ${this.peerId} over ACP.`),
|
|
516
583
|
usage: {
|
|
@@ -521,6 +588,21 @@ export class AcpProvider extends LLMProvider {
|
|
|
521
588
|
cacheMeasurement: 'unavailable'
|
|
522
589
|
}
|
|
523
590
|
};
|
|
591
|
+
const usage = result?.usage;
|
|
592
|
+
if (usage && Number.isFinite(usage.inputTokens) && usage.inputTokens >= 0
|
|
593
|
+
&& Number.isFinite(usage.outputTokens) && usage.outputTokens >= 0) {
|
|
594
|
+
const safeCount = (value: number | undefined): number => Number.isFinite(value) ? Math.max(0, value ?? 0) : 0;
|
|
595
|
+
const cached = safeCount(usage.cachedReadTokens);
|
|
596
|
+
const writes = safeCount(usage.cachedWriteTokens);
|
|
597
|
+
response.usage = {
|
|
598
|
+
promptTokens: usage.inputTokens + cached + writes,
|
|
599
|
+
uncachedPromptTokens: usage.inputTokens + writes,
|
|
600
|
+
completionTokens: usage.outputTokens + safeCount(usage.thoughtTokens),
|
|
601
|
+
cachedPromptTokens: cached,
|
|
602
|
+
measurement: 'provider_reported',
|
|
603
|
+
cacheMeasurement: usage.cachedReadTokens !== undefined ? 'provider_reported' : 'unavailable'
|
|
604
|
+
};
|
|
605
|
+
}
|
|
524
606
|
if (toolCalls.length > 0) {
|
|
525
607
|
response.toolCalls = toolCalls;
|
|
526
608
|
}
|
|
@@ -539,6 +621,7 @@ export class AcpProvider extends LLMProvider {
|
|
|
539
621
|
throw new Error(`ACP Peer Agent (${this.peerId}) Error: ${msg}. Make sure "${this.command}" is installed and running.`);
|
|
540
622
|
} finally {
|
|
541
623
|
options.signal?.removeEventListener('abort', onAbort);
|
|
624
|
+
this.peerServices = null;
|
|
542
625
|
this.currentTurnChunkHandler = null;
|
|
543
626
|
this.currentTurnReasoningHandler = null;
|
|
544
627
|
this.currentTurnNativeActionHandler = null;
|