@causyne/agent 1.20.13 → 1.20.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/package.json +1 -1
  2. package/src/SmartTools.js +33 -0
  3. package/src/SmartTools.ts +37 -0
  4. package/src/acp/client.js +157 -4
  5. package/src/acp/client.ts +152 -5
  6. package/src/agentLoop.js +857 -178
  7. package/src/agentLoop.ts +865 -183
  8. package/src/browser/browserRuntime.js +8 -1
  9. package/src/browser/browserRuntime.ts +8 -1
  10. package/src/browser/causyneBrowser.js +20 -4
  11. package/src/browser/causyneBrowser.ts +20 -4
  12. package/src/browser/urlPolicy.js +35 -0
  13. package/src/browser/urlPolicy.ts +34 -0
  14. package/src/cliMode.js +6 -2
  15. package/src/commands.js +14 -0
  16. package/src/contextManager.d.ts +1 -0
  17. package/src/core/contextCompactor.js +277 -0
  18. package/src/core/contextCompactor.ts +353 -0
  19. package/src/decideTools.js +157 -0
  20. package/src/decideTools.ts +195 -0
  21. package/src/decisionPolicy.js +5 -3
  22. package/src/decisionPolicy.ts +5 -3
  23. package/src/implementationPlan.js +284 -0
  24. package/src/implementationPlan.ts +275 -0
  25. package/src/observer/coldObserver.js +10 -4
  26. package/src/observer/coldObserver.ts +15 -7
  27. package/src/observer/evidence.js +11 -5
  28. package/src/observer/evidence.ts +13 -6
  29. package/src/observer.js +196 -0
  30. package/src/observer.ts +287 -0
  31. package/src/providers/acp.js +362 -109
  32. package/src/providers/acp.ts +359 -111
  33. package/src/providers/antigravity.js +133 -105
  34. package/src/providers/antigravity.ts +130 -109
  35. package/src/providers/base.d.ts +3 -0
  36. package/src/providers/budgetEnforcer.js +13 -0
  37. package/src/providers/budgetEnforcer.ts +13 -3
  38. package/src/provisioning/capabilityProvisioner.js +14 -10
  39. package/src/sandbox.js +4 -2
  40. package/src/saveTools.js +146 -0
  41. package/src/saveTools.ts +169 -0
  42. package/src/session/cachePressure.js +77 -0
  43. package/src/session/cachePressure.ts +122 -0
  44. package/src/smartToolsUse.js +69 -12
  45. package/src/smartToolsUse.ts +103 -12
  46. package/src/taskShape.js +7 -7
  47. package/src/taskShape.ts +7 -7
  48. package/src/timeMachine.js +55 -20
  49. package/src/timeMachine.ts +64 -20
  50. package/src/toolPacks.js +217 -310
  51. package/src/toolPacks.ts +505 -0
  52. package/src/tools/deferredMcpSearch.js +21 -13
  53. package/src/tools/deferredMcpSearch.ts +23 -15
  54. package/src/tools/updatePlan.js +2 -2
  55. package/src/tools/updatePlan.ts +2 -2
  56. package/src/toolsList.js +203 -0
  57. package/src/toolsList.ts +224 -0
  58. package/src/tui/chatRenderer.js +49 -14
  59. package/src/tui/codeStreamRenderer.js +16 -5
  60. package/src/tui/codeStreamRenderer.ts +14 -4
  61. package/src/tui/prompt.js +4 -2
  62. package/src/tui/sessionSidebar.js +10 -2
  63. package/src/tui/sessionSidebar.ts +10 -3
  64. package/src/tui/stageSurface.js +27 -1
  65. package/src/tui/text.d.ts +1 -0
  66. package/src/tui/turnRail.js +274 -0
  67. package/src/tui/turnRail.ts +334 -0
  68. package/src/types/contracts.ts +103 -0
  69. package/src/verificationPlan.js +141 -0
  70. package/src/verificationPlan.ts +166 -0
  71. package/src/toolPacks.d.ts +0 -10
@@ -1,4 +1,4 @@
1
- import { formatToolContracts, toolContractUpdate } from './toolContracts.js';
1
+ import { formatToolContracts, normalizeToolContracts, toolContractUpdate } from './toolContracts.js';
2
2
  import { canonicalModelId } from '../modelIds.js';
3
3
  import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
4
4
  import { saveCachedModels } from '../dynamicCatalogue.js';
@@ -6,16 +6,19 @@ import { LLMProvider, type ProviderConfig, type ChatOptions, type ChatResponse,
6
6
  import { AcpClient } from '../acp/client.js';
7
7
  import { getPeerProfile } from '../acp/peerProfiles.js';
8
8
  import { BUILTIN_PEER_PRESETS } from '../acp/agentCatalog.js';
9
- import type { RequestPermissionRequest, SessionUpdate } from '../acp/protocol.js';
9
+ import type { RequestPermissionRequest, SessionUpdate, ToolKind } from '../acp/protocol.js';
10
10
  import { createHash } from 'node:crypto';
11
11
  import path from 'node:path';
12
12
  import { PEER_COLLABORATION_POLICY } from './collaborationPolicy.js';
13
+ import { extractToolCallJsonObjects, stripToolCallMarkup } from '../implementationPlan.js';
13
14
 
14
15
  interface AcpTransportSnapshot {
15
16
  conversationId: string;
16
17
  workspaceRoot: string;
17
18
  systemHashes: string[];
18
19
  historyHashes: string[];
20
+ historyRoles: string[];
21
+ userPromptHashes: string[];
19
22
  toolHash: string;
20
23
  tools: unknown[];
21
24
  lastResponse: { content: string; toolCalls: ChatResponseToolCall[] };
@@ -43,7 +46,13 @@ export class AcpProvider extends LLMProvider {
43
46
  private currentTurnChunkHandler: ((chunk: string) => void) | null = null;
44
47
  private currentTurnReasoningHandler: ((chunk: string) => void) | null = null;
45
48
  private currentTurnNativeActionHandler: ((action: ChatResponseAction) => void) | null = null;
49
+ private currentTurnPlanHandler: ((plan: unknown) => void) | null = null;
46
50
  private readonly liveFileActions = new Map<string, ChatResponseAction>();
51
+ private readonly turnActions = new Map<string, ChatResponseAction>();
52
+ private turnReasoning = '';
53
+ private turnText = '';
54
+ private hostHandoff: ChatResponseToolCall[] = [];
55
+ private toolRoutingError: ChatResponse['toolRoutingError'];
47
56
  private transportSnapshot: AcpTransportSnapshot | null = null;
48
57
  private peerServices: ChatOptions | null = null;
49
58
 
@@ -94,7 +103,17 @@ export class AcpProvider extends LLMProvider {
94
103
 
95
104
  formatConversation(messages: any[], tools: any[] = []): string {
96
105
  const lines: string[] = [];
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.');
106
+ lines.push(
107
+ '[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. ' +
108
+ PEER_COLLABORATION_POLICY +
109
+ '\n\n[ACP Tool Routing & Workspace Boundary Rules]\n' +
110
+ '1. NATIVE FUNCTION CHANNEL vs CAUSYNE HOST XML CHANNEL:\n' +
111
+ ' - Your native function-calling channel ONLY accepts your own native tools (such as `read`, `write`, `edit`, `bash`, `glob`, `grep`, `todowrite`, and configured MCP tools). Use your native tools directly for workspace file reads/writes, shell commands, and todo checklists (use `todowrite` if available instead of calling `update_plan` as a native function).\n' +
112
+ ' - Causyne host tools listed under [Available Tools] / [Current Available Tools] (such as `browser_act`, `screenshot`, `vision_inspect_ui`, `update_plan`, `memory_write`, `ui_forge`, `astryx_oracle`, `tool_search`) are NOT registered in your native function-calling schema. NEVER invoke them as native function calls (`to=browser_act` or `to=update_plan`), NEVER call `tool_call` as a native tool, and NEVER emit dummy `bash` (`echo`) calls while trying to invoke them.\n' +
113
+ ' - To invoke a Causyne host tool, write `<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>` directly in your assistant text response with NO native function call in that step; Causyne will execute the host tool and return the result on the next turn.\n' +
114
+ '2. WORKSPACE PATH BOUNDARY (NO /tmp):\n' +
115
+ ' - Keep ALL temporary files, server logs, and headless browser screenshots inside the active workspace directory (for example, `./.shots/preview.png` or `./server.log`). NEVER write to, read from, or `cp`/`mv` paths in `/tmp` or outside the workspace root, as the host sandbox rejects `/tmp` access.\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.'
116
+ );
98
117
 
99
118
  if (tools && tools.length > 0) {
100
119
  const toolSummaries = formatToolContracts(tools);
@@ -158,12 +177,22 @@ export class AcpProvider extends LLMProvider {
158
177
  };
159
178
 
160
179
  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);
180
+ pending.push(
181
+ '[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. ' +
182
+ PEER_COLLABORATION_POLICY +
183
+ '\n\n[ACP Tool Routing & Workspace Boundary Rules]\n' +
184
+ '1. NATIVE FUNCTION CHANNEL vs CAUSYNE HOST XML CHANNEL:\n' +
185
+ ' - Your native function-calling channel ONLY accepts your own native tools (such as `read`, `write`, `edit`, `bash`, `glob`, `grep`, `todowrite`, and configured MCP tools). Use your native tools directly for workspace file reads/writes, shell commands, and todo checklists (use `todowrite` if available instead of calling `update_plan` as a native function).\n' +
186
+ ' - Causyne host tools listed under [Current Available Tools] (such as `browser_act`, `screenshot`, `vision_inspect_ui`, `update_plan`, `memory_write`, `ui_forge`, `astryx_oracle`, `tool_search`) are NOT registered in your native function-calling schema. NEVER invoke them as native function calls (`to=browser_act` or `to=update_plan`), NEVER call `tool_call` as a native tool, and NEVER emit dummy `bash` (`echo`) calls while trying to invoke them.\n' +
187
+ ' - To invoke a Causyne host tool, write `<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>` directly in your assistant text response with NO native function call in that step; Causyne will execute the host tool and return the result on the next turn.\n' +
188
+ '2. WORKSPACE PATH BOUNDARY (NO /tmp):\n' +
189
+ ' - Keep ALL temporary files, server logs, and headless browser screenshots inside the active workspace directory (for example, `./.shots/preview.png` or `./server.log`). NEVER write to, read from, or `cp`/`mv` paths in `/tmp` or outside the workspace root, as the host sandbox rejects `/tmp` access.'
190
+ );
162
191
  }
163
192
 
164
193
  if (tools && tools.length > 0) {
165
194
  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}`);
195
+ pending.push(`[Current Available Tools — replaces earlier host tools only; peer-native tools remain available]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`);
167
196
  }
168
197
 
169
198
  if (toolContext) pending.push(toolContext);
@@ -186,7 +215,12 @@ export class AcpProvider extends LLMProvider {
186
215
  }
187
216
 
188
217
  if (text.trim()) {
189
- pending.push(`[${role}]\n${text.trim()}`);
218
+ if (msg.role === 'tool') {
219
+ flush();
220
+ blocks.push({ type: 'text', text: `[${role}]\n${text.trim()}` });
221
+ } else {
222
+ pending.push(`[${role}]\n${text.trim()}`);
223
+ }
190
224
  }
191
225
 
192
226
  if (Array.isArray(msg.content)) {
@@ -230,82 +264,85 @@ export class AcpProvider extends LLMProvider {
230
264
  extractToolCalls(text: string): ChatResponseToolCall[] {
231
265
  const calls: ChatResponseToolCall[] = [];
232
266
  if (!text || typeof text !== 'string') return calls;
233
- const regex = /<tool_call>([\s\S]*?)<\/tool_call>/g;
234
- let match: RegExpExecArray | null;
235
267
  let index = 0;
236
- while ((match = regex.exec(text)) !== null) {
237
- try {
238
- const raw = match[1]?.trim() || '';
239
- const parsed = JSON.parse(raw);
240
- const name = parsed.name || parsed.tool || parsed.function?.name;
241
- if (name) {
242
- const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
243
- calls.push({
244
- id: `acp_call_${Date.now()}_${index++}`,
245
- type: 'function',
246
- function: {
247
- name,
248
- arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
249
- }
250
- });
251
- }
252
- } catch {
253
- // ignore malformed tool_call blocks
254
- }
255
- }
256
-
257
- if (calls.length === 0) {
258
- const fenceRegex = /```(?:tool_call|json)?\s*(\{[\s\S]*?"name"\s*:\s*[\s\S]*?\})\s*```/g;
259
- while ((match = fenceRegex.exec(text)) !== null) {
260
- try {
261
- const raw = match[1]?.trim() || '';
262
- const parsed = JSON.parse(raw);
263
- const name = parsed.name || parsed.tool || parsed.function?.name;
264
- if (name) {
265
- const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
266
- calls.push({
267
- id: `acp_call_${Date.now()}_${index++}`,
268
- type: 'function',
269
- function: {
270
- name,
271
- arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
272
- }
273
- });
274
- }
275
- } catch {
276
- // ignore
268
+ for (const parsed of extractToolCallJsonObjects(text)) {
269
+ const fnObj = parsed.function && typeof parsed.function === 'object'
270
+ ? (parsed.function as Record<string, unknown>)
271
+ : null;
272
+ const name = String(parsed.name || parsed.tool || fnObj?.name || '').trim();
273
+ if (!name) continue;
274
+ const rawArgs = parsed.arguments !== undefined
275
+ ? parsed.arguments
276
+ : parsed.parameters !== undefined
277
+ ? parsed.parameters
278
+ : parsed.input !== undefined
279
+ ? parsed.input
280
+ : (fnObj?.arguments ?? {});
281
+ calls.push({
282
+ id: `acp_call_${Date.now()}_${index++}`,
283
+ type: 'function',
284
+ function: {
285
+ name,
286
+ arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
277
287
  }
278
- }
288
+ });
279
289
  }
290
+ return calls;
291
+ }
280
292
 
281
- if (calls.length === 0) {
282
- const openIndex = text.lastIndexOf('<tool_call>');
283
- if (openIndex !== -1 && text.indexOf('</tool_call>', openIndex) === -1) {
284
- const partial = text.slice(openIndex + '<tool_call>'.length).trim();
285
- for (const suffix of ['', '}', '}}', '}}}', '"}', '"}}', '"}}}', '"}]}}', '"]}}', '"]}}}']) {
286
- try {
287
- const parsed = JSON.parse(partial + suffix);
288
- const name = parsed.name || parsed.tool || parsed.function?.name;
289
- if (name) {
290
- const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
291
- calls.push({
292
- id: `acp_call_${Date.now()}_0`,
293
- type: 'function',
294
- function: {
295
- name,
296
- arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
297
- }
298
- });
299
- break;
300
- }
301
- } catch {
302
- // try next candidate
293
+ /** Yield a complete host request before the peer starts another native loop. */
294
+ private acceptText(chunk: string, sessionId: string, client: AcpClient): void {
295
+ if (this.hostHandoff.length > 0) return;
296
+ this.turnText += chunk;
297
+ this.currentTurnChunkHandler?.(chunk);
298
+ // Streaming JSON must never be suffix-repaired into an executable call.
299
+ // Only complete, explicitly delimited envelopes are eligible for handoff.
300
+ const envelopes: string[] = [];
301
+ const opening = /<tool_call>\s*/gi;
302
+ let match: RegExpExecArray | null;
303
+ while ((match = opening.exec(this.turnText))) {
304
+ const start = opening.lastIndex;
305
+ if (this.turnText[start] !== '{') continue;
306
+ let depth = 0;
307
+ let quoted = false;
308
+ let escaped = false;
309
+ for (let index = start; index < this.turnText.length; index++) {
310
+ const char = this.turnText[index];
311
+ if (quoted) {
312
+ if (escaped) escaped = false;
313
+ else if (char === '\\') escaped = true;
314
+ else if (char === '"') quoted = false;
315
+ } else if (char === '"') quoted = true;
316
+ else if (char === '{') depth++;
317
+ else if (char === '}' && --depth === 0) {
318
+ const closing = /^\s*<\/tool_call>/i.exec(this.turnText.slice(index + 1));
319
+ if (closing) {
320
+ envelopes.push(this.turnText.slice(match.index, index + 1 + closing[0].length));
321
+ opening.lastIndex = index + 1 + closing[0].length;
303
322
  }
323
+ break;
304
324
  }
305
325
  }
306
326
  }
307
-
308
- return calls;
327
+ const available = new Set(normalizeToolContracts(this.peerServices?.tools || []).map(tool => tool.name));
328
+ const calls = envelopes.flatMap(envelope => {
329
+ try {
330
+ const parsed: unknown = JSON.parse(envelope.replace(/^<tool_call>/i, '').replace(/<\/tool_call>$/i, ''));
331
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return [];
332
+ return this.extractToolCalls(`<tool_call>${JSON.stringify(parsed)}</tool_call>`);
333
+ } catch { return []; }
334
+ }).filter(call => {
335
+ if (!available.has(call.function.name)) return false;
336
+ try {
337
+ const args: unknown = JSON.parse(call.function.arguments);
338
+ return args !== null && typeof args === 'object' && !Array.isArray(args);
339
+ } catch { return false; }
340
+ });
341
+ if (calls.length === 0) return;
342
+ this.hostHandoff = calls;
343
+ // This is a control handoff, not a user abort. Keep the ACP session alive
344
+ // so the next prompt delivers the actual host result without replaying work.
345
+ client.notifyCancel(sessionId);
309
346
  }
310
347
 
311
348
  private async getOrCreateClient(signal?: AbortSignal, workspaceRoot = process.cwd()): Promise<{ client: AcpClient; sessionId: string }> {
@@ -323,62 +360,225 @@ export class AcpProvider extends LLMProvider {
323
360
  args: this.args,
324
361
  cwd: workspaceRoot,
325
362
  promptTimeoutMs: 900_000,
363
+ inactivityTimeoutMs: 120_000,
326
364
  allowHostTools: true,
327
365
  permissionHandler: async (req: RequestPermissionRequest) => {
328
- if (this.currentTurnAborted || this.peerServices?.signal?.aborted) return { outcome: 'cancelled' };
329
- return this.peerServices?.onPeerPermission?.(req) ?? { outcome: 'cancelled' };
366
+ if (this.currentTurnAborted || this.peerServices?.signal?.aborted || this.hostHandoff.length > 0 || this.toolRoutingError) return { outcome: 'cancelled' };
367
+ const toolCallId = req.toolCall?.toolCallId;
368
+ const earlier = toolCallId ? (this.turnActions.get(toolCallId) || this.liveFileActions.get(toolCallId)) : undefined;
369
+ let effectiveReq = req;
370
+ if (earlier && req.toolCall) {
371
+ const mappedKind: ToolKind = earlier.name === 'fs_read' ? 'read'
372
+ : (earlier.name === 'fs_write' || earlier.name === 'fs_edit') ? 'edit'
373
+ : earlier.name === 'fs_delete' ? 'delete'
374
+ : earlier.name === 'fs_move' ? 'move'
375
+ : earlier.name === 'sysRun' ? 'execute'
376
+ : earlier.name === 'web_fetch' ? 'fetch'
377
+ : (req.toolCall.kind || 'other');
378
+ if (mappedKind !== req.toolCall.kind) {
379
+ effectiveReq = {
380
+ ...req,
381
+ toolCall: {
382
+ ...req.toolCall,
383
+ kind: mappedKind
384
+ }
385
+ };
386
+ }
387
+ }
388
+ return this.peerServices?.onPeerPermission?.(effectiveReq) ?? { outcome: 'cancelled' };
330
389
  },
331
390
  fsReadHandler: async (file, options) => {
391
+ if (this.hostHandoff.length > 0 || this.toolRoutingError) throw new Error('ACP turn yielded to the host');
332
392
  if (!this.peerServices?.onPeerFileRead) throw new Error('The ACP client has no file-read service attached');
333
- return this.peerServices.onPeerFileRead(file, options);
393
+ const content = await this.peerServices.onPeerFileRead(file, options);
394
+ this.currentTurnSawAction = true;
395
+ const hasTrackedRead = [...this.turnActions.values()].some(
396
+ a => a.name === 'fs_read' && (a.detail === file || a.parameters?.path === file)
397
+ );
398
+ if (!hasTrackedRead) {
399
+ const synthId = `fs_read:${file}`;
400
+ this.turnActions.set(synthId, {
401
+ id: `acp:${synthId}`,
402
+ name: 'fs_read',
403
+ status: 'completed',
404
+ parameters: { path: file },
405
+ detail: file
406
+ });
407
+ }
408
+ return content;
334
409
  },
335
410
  fsWriteHandler: async (file, content) => {
411
+ if (this.hostHandoff.length > 0 || this.toolRoutingError) throw new Error('ACP turn yielded to the host');
336
412
  if (!this.peerServices?.onPeerFileWrite) throw new Error('The ACP client has no file-write service attached');
337
413
  await this.peerServices.onPeerFileWrite(file, content);
414
+ this.currentTurnSawAction = true;
415
+ const hasTrackedWrite = [...this.turnActions.values()].some(
416
+ a => (a.name === 'fs_write' || a.name === 'fs_edit') && (a.detail === file || a.parameters?.path === file)
417
+ );
418
+ if (!hasTrackedWrite) {
419
+ const synthId = `fs_write:${file}`;
420
+ this.turnActions.set(synthId, {
421
+ id: `acp:${synthId}`,
422
+ name: 'fs_write',
423
+ status: 'completed',
424
+ parameters: { path: file, content },
425
+ detail: file
426
+ });
427
+ }
338
428
  },
339
- onUpdate: (_sessionId: string, update: SessionUpdate) => {
429
+ onUpdate: (sessionId: string, update: SessionUpdate) => {
340
430
  if (this.currentTurnAborted) return;
341
431
  if (update && typeof update === 'object') {
342
432
  const updateObj = update as any;
343
433
  if (updateObj.sessionUpdate === 'agent_thought_chunk') {
344
434
  const thought = updateObj.content?.text || updateObj.thought || (typeof updateObj.content === 'string' ? updateObj.content : '');
345
- if (thought && this.currentTurnReasoningHandler) {
346
- this.currentTurnReasoningHandler(thought);
435
+ if (thought) {
436
+ this.turnReasoning += thought;
437
+ if (this.currentTurnReasoningHandler) {
438
+ this.currentTurnReasoningHandler(thought);
439
+ }
347
440
  }
348
441
  } else if (updateObj.sessionUpdate === 'agent_message_chunk') {
349
442
  const text = updateObj.content?.type === 'text' ? updateObj.content.text : '';
350
- if (text && this.currentTurnChunkHandler) this.currentTurnChunkHandler(text);
443
+ if (text) this.acceptText(text, sessionId, client);
444
+ } else if (updateObj.sessionUpdate === 'plan') {
445
+ if (Array.isArray(updateObj.entries) && updateObj.entries.length > 0) {
446
+ this.currentTurnPlanHandler?.({ entries: updateObj.entries });
447
+ }
351
448
  } else if (updateObj.sessionUpdate === 'tool_call' || updateObj.sessionUpdate === 'tool_call_update') {
352
449
  this.currentTurnSawAction = true;
353
450
  const id = String(updateObj.toolCallId || '');
354
- const earlier = this.liveFileActions.get(id);
355
- const kind = updateObj.kind || (earlier?.name === 'fs_edit' ? 'edit' : earlier?.name === 'fs_delete' ? 'delete' : earlier?.name === 'fs_move' ? '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');
451
+ const earlier = this.liveFileActions.get(id) || this.turnActions.get(id);
452
+ const earlierKind = earlier?.name === 'fs_edit' ? 'edit'
453
+ : earlier?.name === 'fs_delete' ? 'delete'
454
+ : earlier?.name === 'fs_move' ? 'move'
455
+ : earlier?.name === 'fs_read' ? 'read'
456
+ : earlier?.name === 'codebase_search' ? 'search'
457
+ : earlier?.name === 'web_fetch' ? 'fetch'
458
+ : earlier?.name === 'sysRun' ? 'execute'
459
+ : '';
460
+ const kind = updateObj.kind || earlierKind;
461
+ const rawTitle = String(updateObj.title || '').trim();
462
+ const input = updateObj.rawInput && typeof updateObj.rawInput === 'object' ? updateObj.rawInput : {};
463
+ const rawOutputObj = updateObj.rawOutput && typeof updateObj.rawOutput === 'object'
464
+ ? updateObj.rawOutput as Record<string, any>
465
+ : null;
466
+ const hasTodoPayload = Array.isArray((input as any).todos)
467
+ || Array.isArray((earlier?.parameters as any)?.todos)
468
+ || Array.isArray(rawOutputObj?.todos)
469
+ || Array.isArray(rawOutputObj?.metadata?.todos)
470
+ || /^\d+\s+todos?$/i.test(rawTitle);
471
+ const name = kind === 'edit' ? 'fs_edit'
472
+ : kind === 'delete' ? 'fs_delete'
473
+ : kind === 'move' ? 'fs_move'
474
+ : kind === 'read' ? 'fs_read'
475
+ : kind === 'search' ? 'codebase_search'
476
+ : kind === 'fetch' ? 'web_fetch'
477
+ : kind === 'execute' ? 'sysRun'
478
+ : hasTodoPayload ? 'todowrite'
479
+ : (earlier?.name && earlier.name !== 'provider_tool' ? earlier.name : (rawTitle || 'provider_tool'));
359
480
  if (name && id) {
360
481
  const diff = Array.isArray(updateObj.content)
361
482
  ? updateObj.content.find((item: any) => item?.type === 'diff')
362
483
  : null;
363
- const input = updateObj.rawInput && typeof updateObj.rawInput === 'object' ? updateObj.rawInput : {};
484
+ const isInvalidPseudoTool = rawTitle.toLowerCase() === 'invalid'
485
+ || earlier?.parameters?.__invalidTool === true
486
+ || (typeof input.error === 'string' && input.error.length > 0 && typeof input.tool === 'string');
487
+ if (isInvalidPseudoTool) {
488
+ const requested = typeof input.tool === 'string' ? input.tool : '';
489
+ if (!this.toolRoutingError && requested && normalizeToolContracts(this.peerServices?.tools || []).some(tool => tool.name === requested)) {
490
+ this.toolRoutingError = { tool: requested, message: 'Host tool requested through the peer-native channel' };
491
+ client.notifyCancel(sessionId);
492
+ }
493
+ this.liveFileActions.delete(id);
494
+ this.turnActions.delete(id);
495
+ return;
496
+ }
497
+ const locationPath = updateObj.locations?.[0]?.path;
498
+ const inputPath = typeof input.path === 'string' ? input.path
499
+ : typeof input.filePath === 'string' ? input.filePath
500
+ : typeof input.file === 'string' ? input.file
501
+ : '';
502
+ const resolvedPath = name === 'sysRun'
503
+ ? ''
504
+ : (diff?.path || locationPath || inputPath || (typeof earlier?.parameters?.path === 'string' ? earlier.parameters.path : ''));
364
505
  const parameters: Record<string, unknown> = {
365
- ...(earlier?.parameters || {}), ...input,
366
- ...(diff?.path ? { path: diff.path } : {}),
367
- ...(diff?.newText ? { content: diff.newText } : {}),
368
- ...(updateObj.locations?.[0]?.path ? { path: updateObj.locations[0].path } : {})
506
+ ...(earlier?.parameters || {}),
507
+ ...input,
508
+ ...(resolvedPath ? { path: resolvedPath } : {}),
509
+ ...(diff?.newText ? { content: diff.newText } : {})
369
510
  };
511
+ const planCandidate = Array.isArray((parameters as any).todos) ? { todos: (parameters as any).todos }
512
+ : Array.isArray((parameters as any).plan) ? { plan: (parameters as any).plan }
513
+ : Array.isArray(rawOutputObj?.todos) ? { todos: rawOutputObj.todos }
514
+ : Array.isArray(rawOutputObj?.metadata?.todos) ? { todos: rawOutputObj.metadata.todos }
515
+ : null;
516
+ if (planCandidate) {
517
+ this.currentTurnPlanHandler?.(planCandidate);
518
+ }
519
+ const commandDetail = typeof parameters.command === 'string' ? parameters.command
520
+ : typeof parameters.cmd === 'string' ? parameters.cmd
521
+ : '';
522
+ const rawToolCandidate = typeof (parameters as any).tool === 'string' ? (parameters as any).tool
523
+ : typeof (input as any).tool === 'string' ? (input as any).tool
524
+ : '';
525
+ const isInvalidToolAttempt = rawToolCandidate.toLowerCase() === 'invalid'
526
+ || rawTitle.toLowerCase() === 'invalid'
527
+ || rawTitle.toLowerCase() === 'invalid tool'
528
+ || name.toLowerCase() === 'invalid tool'
529
+ || name.toLowerCase() === 'invalid'
530
+ || (typeof parameters.error === 'string' && /Model tried to call unavailable tool/i.test(parameters.error));
531
+ if (isInvalidToolAttempt || (name === 'sysRun' && (commandDetail.trim() === 'true' || commandDetail.trim() === ':'))) {
532
+ this.liveFileActions.delete(id);
533
+ this.turnActions.delete(id);
534
+ return;
535
+ }
536
+ const queryDetail = typeof parameters.query === 'string' ? parameters.query
537
+ : typeof parameters.pattern === 'string' ? parameters.pattern
538
+ : typeof parameters.url === 'string' ? parameters.url
539
+ : '';
540
+ const titleIsGeneric = !rawTitle
541
+ || /^(read|write|edit|multiedit|delete|move|search|grep|glob|fetch|execute|bash|sh|zsh|terminal|provider_tool)$/i.test(rawTitle)
542
+ || rawTitle.toLowerCase() === name.toLowerCase();
543
+ const detail = String(
544
+ commandDetail
545
+ || resolvedPath
546
+ || queryDetail
547
+ || (!titleIsGeneric ? rawTitle : '')
548
+ || earlier?.detail
549
+ || ''
550
+ );
370
551
  const status = updateObj.status === 'completed' ? 'completed' : updateObj.status === 'failed' ? 'failed' : 'running';
371
- const action: ChatResponseAction = { id: `acp:${id}`, name, status, parameters,
372
- detail: String(parameters.path || updateObj.title || '') };
552
+ const isEmptyPendingStub = updateObj.status === 'pending'
553
+ && !detail
554
+ && Object.keys(input).length === 0
555
+ && !diff?.newText
556
+ && !planCandidate;
557
+ const action: ChatResponseAction = {
558
+ id: `acp:${id}`,
559
+ name,
560
+ status,
561
+ parameters: { ...parameters, __pendingStub: isEmptyPendingStub },
562
+ detail
563
+ };
564
+ const shouldNotify = !isEmptyPendingStub && (
565
+ !earlier
566
+ || earlier.parameters?.__pendingStub === true
567
+ || earlier.status !== status
568
+ || earlier.name !== name
569
+ || earlier.detail !== detail
570
+ || Boolean(diff?.newText && diff.newText !== earlier?.parameters?.content)
571
+ );
572
+ this.turnActions.set(id, action);
373
573
  if (status === 'running') this.liveFileActions.set(id, action);
374
574
  else this.liveFileActions.delete(id);
375
- this.currentTurnNativeActionHandler?.(action);
575
+ if (shouldNotify) {
576
+ this.currentTurnNativeActionHandler?.(action);
577
+ }
376
578
  }
377
579
  } else if ('textDelta' in updateObj) {
378
580
  const delta = updateObj.textDelta;
379
- if (delta && typeof delta === 'string' && this.currentTurnChunkHandler) {
380
- this.currentTurnChunkHandler(delta);
381
- }
581
+ if (delta && typeof delta === 'string') this.acceptText(delta, sessionId, client);
382
582
  }
383
583
  }
384
584
  }
@@ -448,6 +648,7 @@ export class AcpProvider extends LLMProvider {
448
648
  this.currentTurnChunkHandler = null;
449
649
  this.currentTurnReasoningHandler = null;
450
650
  this.currentTurnNativeActionHandler = null;
651
+ this.currentTurnPlanHandler = null;
451
652
  this.liveFileActions.clear();
452
653
  if (this.activeClient && this.activeSessionId) {
453
654
  try {
@@ -485,7 +686,13 @@ export class AcpProvider extends LLMProvider {
485
686
  this.currentTurnChunkHandler = options.onChunk || null;
486
687
  this.currentTurnReasoningHandler = options.onReasoningChunk || null;
487
688
  this.currentTurnNativeActionHandler = options.onNativeAction || null;
689
+ this.currentTurnPlanHandler = options.onPlanUpdate || null;
488
690
  this.liveFileActions.clear();
691
+ this.turnActions.clear();
692
+ this.turnReasoning = '';
693
+ this.turnText = '';
694
+ this.hostHandoff = [];
695
+ this.toolRoutingError = undefined;
489
696
  const onAbort = (): void => {
490
697
  this.abort();
491
698
  };
@@ -503,10 +710,14 @@ export class AcpProvider extends LLMProvider {
503
710
  const sessionChanged = previous && (
504
711
  previous.workspaceRoot !== workspaceRoot || previous.conversationId !== conversationId
505
712
  );
506
- const historyDiverged = previous && (
507
- historyHashes.length < previous.historyHashes.length ||
508
- previous.historyHashes.some((hash, index) => historyHashes[index] !== hash)
509
- );
713
+ const historyShortened = Boolean(previous && historyHashes.length < previous.historyHashes.length);
714
+ const roleDiverged = Boolean(previous && !historyShortened && previous.historyRoles?.some(
715
+ (role, index) => historyMessages[index]?.role !== role
716
+ ));
717
+ const userPromptDiverged = Boolean(previous && !historyShortened && previous.userPromptHashes?.some(
718
+ (hash, index) => hash && fingerprint(historyMessages[index]?.content) !== hash
719
+ ));
720
+ const historyDiverged = historyShortened || roleDiverged || userPromptDiverged;
510
721
  const systemShapeChanged = previous && systemHashes.length < previous.systemHashes.length;
511
722
  if (sessionChanged || historyDiverged || systemShapeChanged) {
512
723
  await this.close();
@@ -528,13 +739,24 @@ export class AcpProvider extends LLMProvider {
528
739
  // duplicate the peer's own response before the next tool result.
529
740
  const firstNew = newHistory[0];
530
741
  if (firstNew?.role === 'assistant' &&
531
- firstNew.content === previous.lastResponse.content &&
742
+ (firstNew.content === previous.lastResponse.content ||
743
+ (!previous.lastResponse.content && firstNew.content === 'No final response was provided.')) &&
532
744
  fingerprint(firstNew.tool_calls || []) === fingerprint(previous.lastResponse.toolCalls)) {
533
745
  newHistory.shift();
534
746
  }
747
+ const filteredNewHistory = newHistory.filter(
748
+ message => !(message?.role === 'assistant' && message?.content === 'No final response was provided.' && (!message.tool_calls || message.tool_calls.length === 0))
749
+ );
750
+ const toolResultMessages = filteredNewHistory.filter(m => m?.role === 'tool');
751
+ const otherHistory = filteredNewHistory.filter(m => m?.role !== 'tool');
752
+ const formattedChangedSystem = changedSystem.map(message => ({
753
+ ...message,
754
+ content: `[Context Update]\n${message.content}`
755
+ }));
535
756
  promptMessages = [
536
- ...changedSystem.map(message => ({ ...message, content: `[Current system context — replaces the prior version of this section]\n${message.content}` })),
537
- ...newHistory
757
+ ...toolResultMessages,
758
+ ...otherHistory,
759
+ ...formattedChangedSystem
538
760
  ];
539
761
  toolContext = toolContractUpdate(options.tools || [], previous.tools);
540
762
  promptTools = [];
@@ -568,18 +790,28 @@ export class AcpProvider extends LLMProvider {
568
790
  }
569
791
 
570
792
  let rawContent = (result?.text || '').trim();
571
- const toolCalls = this.extractToolCalls(rawContent);
793
+ const toolCalls = this.hostHandoff.length > 0 ? this.hostHandoff : this.extractToolCalls(rawContent);
572
794
 
573
- // Strip tool call XML from chat content display
574
- let content = rawContent.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim();
795
+ // Strip tool call XML / DSML from chat content display
796
+ let content = stripToolCallMarkup(rawContent);
797
+ const externalActions = [...this.turnActions.values()];
798
+ const incompleteFromActions = !content && toolCalls.length === 0 && externalActions.length > 0;
799
+ const finalContent = content || (toolCalls.length > 0 || incompleteFromActions ? '' : `Turn completed by ${this.peerId} over ACP.`);
575
800
 
576
801
  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 }
802
+ conversationId,
803
+ workspaceRoot,
804
+ systemHashes,
805
+ historyHashes,
806
+ historyRoles: historyMessages.map(m => m.role),
807
+ userPromptHashes: historyMessages.map(m => m.role === 'user' ? fingerprint(m.content) : ''),
808
+ toolHash,
809
+ tools: structuredClone(options.tools || []),
810
+ lastResponse: { content: finalContent, toolCalls }
579
811
  };
580
812
 
581
813
  const response: ChatResponse = {
582
- content: content || (toolCalls.length > 0 ? '' : `Turn completed by ${this.peerId} over ACP.`),
814
+ content: finalContent,
583
815
  usage: {
584
816
  promptTokens: Math.ceil(promptText.length / 4),
585
817
  completionTokens: Math.ceil(rawContent.length / 4),
@@ -588,6 +820,13 @@ export class AcpProvider extends LLMProvider {
588
820
  cacheMeasurement: 'unavailable'
589
821
  }
590
822
  };
823
+ if (externalActions.length > 0) {
824
+ response.externalActions = externalActions;
825
+ }
826
+ if (this.toolRoutingError && toolCalls.length === 0) response.toolRoutingError = this.toolRoutingError;
827
+ if (this.turnReasoning.trim()) {
828
+ response.reasoningContent = this.turnReasoning;
829
+ }
591
830
  const usage = result?.usage;
592
831
  if (usage && Number.isFinite(usage.inputTokens) && usage.inputTokens >= 0
593
832
  && Number.isFinite(usage.outputTokens) && usage.outputTokens >= 0) {
@@ -602,11 +841,16 @@ export class AcpProvider extends LLMProvider {
602
841
  measurement: 'provider_reported',
603
842
  cacheMeasurement: usage.cachedReadTokens !== undefined ? 'provider_reported' : 'unavailable'
604
843
  };
844
+ // OpenCode's ACP service builds usage from its final assistant message,
845
+ // not all internal inference/tool turns. Do not label it a task total.
846
+ response.usage.measurementScope = this.peerId === 'opencode' ? 'last_model_call' : 'peer_reported';
605
847
  }
606
848
  if (toolCalls.length > 0) {
607
849
  response.toolCalls = toolCalls;
608
850
  }
609
- if (result?.stopReason === 'max_tokens' || result?.stopReason === 'max_turn_requests') {
851
+ if (result?.stopReason === 'max_tokens' || result?.stopReason === 'max_turn_requests' || incompleteFromActions
852
+ || externalActions.some(action => action.status === 'running')
853
+ || (result?.stopReason === 'cancelled' && toolCalls.length === 0)) {
610
854
  response.incompleteTurn = true;
611
855
  }
612
856
  return response;
@@ -618,6 +862,9 @@ export class AcpProvider extends LLMProvider {
618
862
  throw abortErr;
619
863
  }
620
864
  const msg = err instanceof Error ? err.message : String(err);
865
+ if (msg.startsWith('ACP Peer Agent') || msg.includes('Free usage limit reached') || msg.includes('quota') || msg.includes('rate limit') || msg.includes('stalled')) {
866
+ throw (err instanceof Error ? err : new Error(msg));
867
+ }
621
868
  throw new Error(`ACP Peer Agent (${this.peerId}) Error: ${msg}. Make sure "${this.command}" is installed and running.`);
622
869
  } finally {
623
870
  options.signal?.removeEventListener('abort', onAbort);
@@ -625,6 +872,7 @@ export class AcpProvider extends LLMProvider {
625
872
  this.currentTurnChunkHandler = null;
626
873
  this.currentTurnReasoningHandler = null;
627
874
  this.currentTurnNativeActionHandler = null;
875
+ this.currentTurnPlanHandler = null;
628
876
  this.liveFileActions.clear();
629
877
  }
630
878
  }