@causyne/agent 1.20.12 → 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.
- package/LICENSE +1 -1
- package/package.json +1 -1
- package/src/SmartTools.js +33 -0
- package/src/SmartTools.ts +37 -0
- package/src/acp/client.js +157 -4
- package/src/acp/client.ts +152 -5
- package/src/agentLoop.js +857 -178
- package/src/agentLoop.ts +865 -183
- package/src/browser/browserRuntime.js +8 -1
- package/src/browser/browserRuntime.ts +8 -1
- package/src/browser/causyneBrowser.js +20 -4
- package/src/browser/causyneBrowser.ts +20 -4
- package/src/browser/urlPolicy.js +35 -0
- package/src/browser/urlPolicy.ts +34 -0
- package/src/cliMode.js +6 -2
- package/src/commands.js +14 -0
- package/src/contextManager.d.ts +1 -0
- package/src/core/contextCompactor.js +277 -0
- package/src/core/contextCompactor.ts +353 -0
- package/src/decideTools.js +157 -0
- package/src/decideTools.ts +195 -0
- package/src/decisionPolicy.js +5 -3
- package/src/decisionPolicy.ts +5 -3
- package/src/implementationPlan.js +284 -0
- package/src/implementationPlan.ts +275 -0
- package/src/observer/coldObserver.js +10 -4
- package/src/observer/coldObserver.ts +15 -7
- package/src/observer/evidence.js +11 -5
- package/src/observer/evidence.ts +13 -6
- package/src/observer.js +196 -0
- package/src/observer.ts +287 -0
- package/src/providers/acp.js +362 -109
- package/src/providers/acp.ts +359 -111
- package/src/providers/antigravity.js +133 -105
- package/src/providers/antigravity.ts +130 -109
- package/src/providers/base.d.ts +3 -0
- package/src/providers/budgetEnforcer.js +13 -0
- package/src/providers/budgetEnforcer.ts +13 -3
- package/src/provisioning/capabilityProvisioner.js +14 -10
- package/src/sandbox.js +4 -2
- package/src/saveTools.js +146 -0
- package/src/saveTools.ts +169 -0
- package/src/session/cachePressure.js +77 -0
- package/src/session/cachePressure.ts +122 -0
- package/src/smartToolsUse.js +69 -12
- package/src/smartToolsUse.ts +103 -12
- package/src/taskShape.js +7 -7
- package/src/taskShape.ts +7 -7
- package/src/timeMachine.js +55 -20
- package/src/timeMachine.ts +64 -20
- package/src/toolPacks.js +217 -310
- package/src/toolPacks.ts +505 -0
- package/src/tools/deferredMcpSearch.js +21 -13
- package/src/tools/deferredMcpSearch.ts +23 -15
- package/src/tools/updatePlan.js +2 -2
- package/src/tools/updatePlan.ts +2 -2
- package/src/toolsList.js +203 -0
- package/src/toolsList.ts +224 -0
- package/src/tui/chatRenderer.js +49 -14
- package/src/tui/codeStreamRenderer.js +16 -5
- package/src/tui/codeStreamRenderer.ts +14 -4
- package/src/tui/prompt.js +4 -2
- package/src/tui/sessionSidebar.js +10 -2
- package/src/tui/sessionSidebar.ts +10 -3
- package/src/tui/stageSurface.js +27 -1
- package/src/tui/text.d.ts +1 -0
- package/src/tui/turnRail.js +274 -0
- package/src/tui/turnRail.ts +334 -0
- package/src/types/contracts.ts +103 -0
- package/src/verificationPlan.js +141 -0
- package/src/verificationPlan.ts +166 -0
- package/src/toolPacks.d.ts +0 -10
package/src/providers/acp.js
CHANGED
|
@@ -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';
|
|
@@ -9,6 +9,7 @@ import { BUILTIN_PEER_PRESETS } from '../acp/agentCatalog.js';
|
|
|
9
9
|
import { createHash } from 'node:crypto';
|
|
10
10
|
import path from 'node:path';
|
|
11
11
|
import { PEER_COLLABORATION_POLICY } from './collaborationPolicy.js';
|
|
12
|
+
import { extractToolCallJsonObjects, stripToolCallMarkup } from '../implementationPlan.js';
|
|
12
13
|
function fingerprint(value) {
|
|
13
14
|
return createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
|
14
15
|
}
|
|
@@ -30,7 +31,13 @@ export class AcpProvider extends LLMProvider {
|
|
|
30
31
|
currentTurnChunkHandler = null;
|
|
31
32
|
currentTurnReasoningHandler = null;
|
|
32
33
|
currentTurnNativeActionHandler = null;
|
|
34
|
+
currentTurnPlanHandler = null;
|
|
33
35
|
liveFileActions = new Map();
|
|
36
|
+
turnActions = new Map();
|
|
37
|
+
turnReasoning = '';
|
|
38
|
+
turnText = '';
|
|
39
|
+
hostHandoff = [];
|
|
40
|
+
toolRoutingError;
|
|
34
41
|
transportSnapshot = null;
|
|
35
42
|
peerServices = null;
|
|
36
43
|
constructor(config = {}) {
|
|
@@ -81,7 +88,15 @@ export class AcpProvider extends LLMProvider {
|
|
|
81
88
|
}
|
|
82
89
|
formatConversation(messages, tools = []) {
|
|
83
90
|
const lines = [];
|
|
84
|
-
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. ' +
|
|
91
|
+
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. ' +
|
|
92
|
+
PEER_COLLABORATION_POLICY +
|
|
93
|
+
'\n\n[ACP Tool Routing & Workspace Boundary Rules]\n' +
|
|
94
|
+
'1. NATIVE FUNCTION CHANNEL vs CAUSYNE HOST XML CHANNEL:\n' +
|
|
95
|
+
' - 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' +
|
|
96
|
+
' - 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' +
|
|
97
|
+
' - 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' +
|
|
98
|
+
'2. WORKSPACE PATH BOUNDARY (NO /tmp):\n' +
|
|
99
|
+
' - 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.');
|
|
85
100
|
if (tools && tools.length > 0) {
|
|
86
101
|
const toolSummaries = formatToolContracts(tools);
|
|
87
102
|
lines.push(`[Available Tools]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`);
|
|
@@ -140,11 +155,19 @@ export class AcpProvider extends LLMProvider {
|
|
|
140
155
|
pending = [];
|
|
141
156
|
};
|
|
142
157
|
if (includeBridgeInstructions) {
|
|
143
|
-
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. ' +
|
|
158
|
+
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. ' +
|
|
159
|
+
PEER_COLLABORATION_POLICY +
|
|
160
|
+
'\n\n[ACP Tool Routing & Workspace Boundary Rules]\n' +
|
|
161
|
+
'1. NATIVE FUNCTION CHANNEL vs CAUSYNE HOST XML CHANNEL:\n' +
|
|
162
|
+
' - 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' +
|
|
163
|
+
' - 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' +
|
|
164
|
+
' - 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' +
|
|
165
|
+
'2. WORKSPACE PATH BOUNDARY (NO /tmp):\n' +
|
|
166
|
+
' - 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.');
|
|
144
167
|
}
|
|
145
168
|
if (tools && tools.length > 0) {
|
|
146
169
|
const toolSummaries = formatToolContracts(tools);
|
|
147
|
-
pending.push(`[Current Available Tools —
|
|
170
|
+
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}`);
|
|
148
171
|
}
|
|
149
172
|
if (toolContext)
|
|
150
173
|
pending.push(toolContext);
|
|
@@ -165,7 +188,13 @@ export class AcpProvider extends LLMProvider {
|
|
|
165
188
|
}
|
|
166
189
|
}
|
|
167
190
|
if (text.trim()) {
|
|
168
|
-
|
|
191
|
+
if (msg.role === 'tool') {
|
|
192
|
+
flush();
|
|
193
|
+
blocks.push({ type: 'text', text: `[${role}]\n${text.trim()}` });
|
|
194
|
+
}
|
|
195
|
+
else {
|
|
196
|
+
pending.push(`[${role}]\n${text.trim()}`);
|
|
197
|
+
}
|
|
169
198
|
}
|
|
170
199
|
if (Array.isArray(msg.content)) {
|
|
171
200
|
for (const part of msg.content) {
|
|
@@ -213,82 +242,102 @@ export class AcpProvider extends LLMProvider {
|
|
|
213
242
|
const calls = [];
|
|
214
243
|
if (!text || typeof text !== 'string')
|
|
215
244
|
return calls;
|
|
216
|
-
const regex = /<tool_call>([\s\S]*?)<\/tool_call>/g;
|
|
217
|
-
let match;
|
|
218
245
|
let index = 0;
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
}
|
|
233
|
-
|
|
246
|
+
for (const parsed of extractToolCallJsonObjects(text)) {
|
|
247
|
+
const fnObj = parsed.function && typeof parsed.function === 'object'
|
|
248
|
+
? parsed.function
|
|
249
|
+
: null;
|
|
250
|
+
const name = String(parsed.name || parsed.tool || fnObj?.name || '').trim();
|
|
251
|
+
if (!name)
|
|
252
|
+
continue;
|
|
253
|
+
const rawArgs = parsed.arguments !== undefined
|
|
254
|
+
? parsed.arguments
|
|
255
|
+
: parsed.parameters !== undefined
|
|
256
|
+
? parsed.parameters
|
|
257
|
+
: parsed.input !== undefined
|
|
258
|
+
? parsed.input
|
|
259
|
+
: (fnObj?.arguments ?? {});
|
|
260
|
+
calls.push({
|
|
261
|
+
id: `acp_call_${Date.now()}_${index++}`,
|
|
262
|
+
type: 'function',
|
|
263
|
+
function: {
|
|
264
|
+
name,
|
|
265
|
+
arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
|
|
234
266
|
}
|
|
235
|
-
}
|
|
236
|
-
catch {
|
|
237
|
-
// ignore malformed tool_call blocks
|
|
238
|
-
}
|
|
267
|
+
});
|
|
239
268
|
}
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
269
|
+
return calls;
|
|
270
|
+
}
|
|
271
|
+
/** Yield a complete host request before the peer starts another native loop. */
|
|
272
|
+
acceptText(chunk, sessionId, client) {
|
|
273
|
+
if (this.hostHandoff.length > 0)
|
|
274
|
+
return;
|
|
275
|
+
this.turnText += chunk;
|
|
276
|
+
this.currentTurnChunkHandler?.(chunk);
|
|
277
|
+
// Streaming JSON must never be suffix-repaired into an executable call.
|
|
278
|
+
// Only complete, explicitly delimited envelopes are eligible for handoff.
|
|
279
|
+
const envelopes = [];
|
|
280
|
+
const opening = /<tool_call>\s*/gi;
|
|
281
|
+
let match;
|
|
282
|
+
while ((match = opening.exec(this.turnText))) {
|
|
283
|
+
const start = opening.lastIndex;
|
|
284
|
+
if (this.turnText[start] !== '{')
|
|
285
|
+
continue;
|
|
286
|
+
let depth = 0;
|
|
287
|
+
let quoted = false;
|
|
288
|
+
let escaped = false;
|
|
289
|
+
for (let index = start; index < this.turnText.length; index++) {
|
|
290
|
+
const char = this.turnText[index];
|
|
291
|
+
if (quoted) {
|
|
292
|
+
if (escaped)
|
|
293
|
+
escaped = false;
|
|
294
|
+
else if (char === '\\')
|
|
295
|
+
escaped = true;
|
|
296
|
+
else if (char === '"')
|
|
297
|
+
quoted = false;
|
|
261
298
|
}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
const name = parsed.name || parsed.tool || parsed.function?.name;
|
|
272
|
-
if (name) {
|
|
273
|
-
const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
|
|
274
|
-
calls.push({
|
|
275
|
-
id: `acp_call_${Date.now()}_0`,
|
|
276
|
-
type: 'function',
|
|
277
|
-
function: {
|
|
278
|
-
name,
|
|
279
|
-
arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
|
|
280
|
-
}
|
|
281
|
-
});
|
|
282
|
-
break;
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
catch {
|
|
286
|
-
// try next candidate
|
|
299
|
+
else if (char === '"')
|
|
300
|
+
quoted = true;
|
|
301
|
+
else if (char === '{')
|
|
302
|
+
depth++;
|
|
303
|
+
else if (char === '}' && --depth === 0) {
|
|
304
|
+
const closing = /^\s*<\/tool_call>/i.exec(this.turnText.slice(index + 1));
|
|
305
|
+
if (closing) {
|
|
306
|
+
envelopes.push(this.turnText.slice(match.index, index + 1 + closing[0].length));
|
|
307
|
+
opening.lastIndex = index + 1 + closing[0].length;
|
|
287
308
|
}
|
|
309
|
+
break;
|
|
288
310
|
}
|
|
289
311
|
}
|
|
290
312
|
}
|
|
291
|
-
|
|
313
|
+
const available = new Set(normalizeToolContracts(this.peerServices?.tools || []).map(tool => tool.name));
|
|
314
|
+
const calls = envelopes.flatMap(envelope => {
|
|
315
|
+
try {
|
|
316
|
+
const parsed = JSON.parse(envelope.replace(/^<tool_call>/i, '').replace(/<\/tool_call>$/i, ''));
|
|
317
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
|
|
318
|
+
return [];
|
|
319
|
+
return this.extractToolCalls(`<tool_call>${JSON.stringify(parsed)}</tool_call>`);
|
|
320
|
+
}
|
|
321
|
+
catch {
|
|
322
|
+
return [];
|
|
323
|
+
}
|
|
324
|
+
}).filter(call => {
|
|
325
|
+
if (!available.has(call.function.name))
|
|
326
|
+
return false;
|
|
327
|
+
try {
|
|
328
|
+
const args = JSON.parse(call.function.arguments);
|
|
329
|
+
return args !== null && typeof args === 'object' && !Array.isArray(args);
|
|
330
|
+
}
|
|
331
|
+
catch {
|
|
332
|
+
return false;
|
|
333
|
+
}
|
|
334
|
+
});
|
|
335
|
+
if (calls.length === 0)
|
|
336
|
+
return;
|
|
337
|
+
this.hostHandoff = calls;
|
|
338
|
+
// This is a control handoff, not a user abort. Keep the ACP session alive
|
|
339
|
+
// so the next prompt delivers the actual host result without replaying work.
|
|
340
|
+
client.notifyCancel(sessionId);
|
|
292
341
|
}
|
|
293
342
|
async getOrCreateClient(signal, workspaceRoot = process.cwd()) {
|
|
294
343
|
if (signal?.aborted) {
|
|
@@ -304,72 +353,231 @@ export class AcpProvider extends LLMProvider {
|
|
|
304
353
|
args: this.args,
|
|
305
354
|
cwd: workspaceRoot,
|
|
306
355
|
promptTimeoutMs: 900_000,
|
|
356
|
+
inactivityTimeoutMs: 120_000,
|
|
307
357
|
allowHostTools: true,
|
|
308
358
|
permissionHandler: async (req) => {
|
|
309
|
-
if (this.currentTurnAborted || this.peerServices?.signal?.aborted)
|
|
359
|
+
if (this.currentTurnAborted || this.peerServices?.signal?.aborted || this.hostHandoff.length > 0 || this.toolRoutingError)
|
|
310
360
|
return { outcome: 'cancelled' };
|
|
311
|
-
|
|
361
|
+
const toolCallId = req.toolCall?.toolCallId;
|
|
362
|
+
const earlier = toolCallId ? (this.turnActions.get(toolCallId) || this.liveFileActions.get(toolCallId)) : undefined;
|
|
363
|
+
let effectiveReq = req;
|
|
364
|
+
if (earlier && req.toolCall) {
|
|
365
|
+
const mappedKind = earlier.name === 'fs_read' ? 'read'
|
|
366
|
+
: (earlier.name === 'fs_write' || earlier.name === 'fs_edit') ? 'edit'
|
|
367
|
+
: earlier.name === 'fs_delete' ? 'delete'
|
|
368
|
+
: earlier.name === 'fs_move' ? 'move'
|
|
369
|
+
: earlier.name === 'sysRun' ? 'execute'
|
|
370
|
+
: earlier.name === 'web_fetch' ? 'fetch'
|
|
371
|
+
: (req.toolCall.kind || 'other');
|
|
372
|
+
if (mappedKind !== req.toolCall.kind) {
|
|
373
|
+
effectiveReq = {
|
|
374
|
+
...req,
|
|
375
|
+
toolCall: {
|
|
376
|
+
...req.toolCall,
|
|
377
|
+
kind: mappedKind
|
|
378
|
+
}
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
return this.peerServices?.onPeerPermission?.(effectiveReq) ?? { outcome: 'cancelled' };
|
|
312
383
|
},
|
|
313
384
|
fsReadHandler: async (file, options) => {
|
|
385
|
+
if (this.hostHandoff.length > 0 || this.toolRoutingError)
|
|
386
|
+
throw new Error('ACP turn yielded to the host');
|
|
314
387
|
if (!this.peerServices?.onPeerFileRead)
|
|
315
388
|
throw new Error('The ACP client has no file-read service attached');
|
|
316
|
-
|
|
389
|
+
const content = await this.peerServices.onPeerFileRead(file, options);
|
|
390
|
+
this.currentTurnSawAction = true;
|
|
391
|
+
const hasTrackedRead = [...this.turnActions.values()].some(a => a.name === 'fs_read' && (a.detail === file || a.parameters?.path === file));
|
|
392
|
+
if (!hasTrackedRead) {
|
|
393
|
+
const synthId = `fs_read:${file}`;
|
|
394
|
+
this.turnActions.set(synthId, {
|
|
395
|
+
id: `acp:${synthId}`,
|
|
396
|
+
name: 'fs_read',
|
|
397
|
+
status: 'completed',
|
|
398
|
+
parameters: { path: file },
|
|
399
|
+
detail: file
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
return content;
|
|
317
403
|
},
|
|
318
404
|
fsWriteHandler: async (file, content) => {
|
|
405
|
+
if (this.hostHandoff.length > 0 || this.toolRoutingError)
|
|
406
|
+
throw new Error('ACP turn yielded to the host');
|
|
319
407
|
if (!this.peerServices?.onPeerFileWrite)
|
|
320
408
|
throw new Error('The ACP client has no file-write service attached');
|
|
321
409
|
await this.peerServices.onPeerFileWrite(file, content);
|
|
410
|
+
this.currentTurnSawAction = true;
|
|
411
|
+
const hasTrackedWrite = [...this.turnActions.values()].some(a => (a.name === 'fs_write' || a.name === 'fs_edit') && (a.detail === file || a.parameters?.path === file));
|
|
412
|
+
if (!hasTrackedWrite) {
|
|
413
|
+
const synthId = `fs_write:${file}`;
|
|
414
|
+
this.turnActions.set(synthId, {
|
|
415
|
+
id: `acp:${synthId}`,
|
|
416
|
+
name: 'fs_write',
|
|
417
|
+
status: 'completed',
|
|
418
|
+
parameters: { path: file, content },
|
|
419
|
+
detail: file
|
|
420
|
+
});
|
|
421
|
+
}
|
|
322
422
|
},
|
|
323
|
-
onUpdate: (
|
|
423
|
+
onUpdate: (sessionId, update) => {
|
|
324
424
|
if (this.currentTurnAborted)
|
|
325
425
|
return;
|
|
326
426
|
if (update && typeof update === 'object') {
|
|
327
427
|
const updateObj = update;
|
|
328
428
|
if (updateObj.sessionUpdate === 'agent_thought_chunk') {
|
|
329
429
|
const thought = updateObj.content?.text || updateObj.thought || (typeof updateObj.content === 'string' ? updateObj.content : '');
|
|
330
|
-
if (thought
|
|
331
|
-
this.
|
|
430
|
+
if (thought) {
|
|
431
|
+
this.turnReasoning += thought;
|
|
432
|
+
if (this.currentTurnReasoningHandler) {
|
|
433
|
+
this.currentTurnReasoningHandler(thought);
|
|
434
|
+
}
|
|
332
435
|
}
|
|
333
436
|
}
|
|
334
437
|
else if (updateObj.sessionUpdate === 'agent_message_chunk') {
|
|
335
438
|
const text = updateObj.content?.type === 'text' ? updateObj.content.text : '';
|
|
336
|
-
if (text
|
|
337
|
-
this.
|
|
439
|
+
if (text)
|
|
440
|
+
this.acceptText(text, sessionId, client);
|
|
441
|
+
}
|
|
442
|
+
else if (updateObj.sessionUpdate === 'plan') {
|
|
443
|
+
if (Array.isArray(updateObj.entries) && updateObj.entries.length > 0) {
|
|
444
|
+
this.currentTurnPlanHandler?.({ entries: updateObj.entries });
|
|
445
|
+
}
|
|
338
446
|
}
|
|
339
447
|
else if (updateObj.sessionUpdate === 'tool_call' || updateObj.sessionUpdate === 'tool_call_update') {
|
|
340
448
|
this.currentTurnSawAction = true;
|
|
341
449
|
const id = String(updateObj.toolCallId || '');
|
|
342
|
-
const earlier = this.liveFileActions.get(id);
|
|
343
|
-
const
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
450
|
+
const earlier = this.liveFileActions.get(id) || this.turnActions.get(id);
|
|
451
|
+
const earlierKind = earlier?.name === 'fs_edit' ? 'edit'
|
|
452
|
+
: earlier?.name === 'fs_delete' ? 'delete'
|
|
453
|
+
: earlier?.name === 'fs_move' ? 'move'
|
|
454
|
+
: earlier?.name === 'fs_read' ? 'read'
|
|
455
|
+
: earlier?.name === 'codebase_search' ? 'search'
|
|
456
|
+
: earlier?.name === 'web_fetch' ? 'fetch'
|
|
457
|
+
: earlier?.name === 'sysRun' ? 'execute'
|
|
458
|
+
: '';
|
|
459
|
+
const kind = updateObj.kind || earlierKind;
|
|
460
|
+
const rawTitle = String(updateObj.title || '').trim();
|
|
461
|
+
const input = updateObj.rawInput && typeof updateObj.rawInput === 'object' ? updateObj.rawInput : {};
|
|
462
|
+
const rawOutputObj = updateObj.rawOutput && typeof updateObj.rawOutput === 'object'
|
|
463
|
+
? updateObj.rawOutput
|
|
464
|
+
: null;
|
|
465
|
+
const hasTodoPayload = Array.isArray(input.todos)
|
|
466
|
+
|| Array.isArray(earlier?.parameters?.todos)
|
|
467
|
+
|| Array.isArray(rawOutputObj?.todos)
|
|
468
|
+
|| Array.isArray(rawOutputObj?.metadata?.todos)
|
|
469
|
+
|| /^\d+\s+todos?$/i.test(rawTitle);
|
|
470
|
+
const name = kind === 'edit' ? 'fs_edit'
|
|
471
|
+
: kind === 'delete' ? 'fs_delete'
|
|
472
|
+
: kind === 'move' ? 'fs_move'
|
|
473
|
+
: kind === 'read' ? 'fs_read'
|
|
474
|
+
: kind === 'search' ? 'codebase_search'
|
|
475
|
+
: kind === 'fetch' ? 'web_fetch'
|
|
476
|
+
: kind === 'execute' ? 'sysRun'
|
|
477
|
+
: hasTodoPayload ? 'todowrite'
|
|
478
|
+
: (earlier?.name && earlier.name !== 'provider_tool' ? earlier.name : (rawTitle || 'provider_tool'));
|
|
347
479
|
if (name && id) {
|
|
348
480
|
const diff = Array.isArray(updateObj.content)
|
|
349
481
|
? updateObj.content.find((item) => item?.type === 'diff')
|
|
350
482
|
: null;
|
|
351
|
-
const
|
|
483
|
+
const isInvalidPseudoTool = rawTitle.toLowerCase() === 'invalid'
|
|
484
|
+
|| earlier?.parameters?.__invalidTool === true
|
|
485
|
+
|| (typeof input.error === 'string' && input.error.length > 0 && typeof input.tool === 'string');
|
|
486
|
+
if (isInvalidPseudoTool) {
|
|
487
|
+
const requested = typeof input.tool === 'string' ? input.tool : '';
|
|
488
|
+
if (!this.toolRoutingError && requested && normalizeToolContracts(this.peerServices?.tools || []).some(tool => tool.name === requested)) {
|
|
489
|
+
this.toolRoutingError = { tool: requested, message: 'Host tool requested through the peer-native channel' };
|
|
490
|
+
client.notifyCancel(sessionId);
|
|
491
|
+
}
|
|
492
|
+
this.liveFileActions.delete(id);
|
|
493
|
+
this.turnActions.delete(id);
|
|
494
|
+
return;
|
|
495
|
+
}
|
|
496
|
+
const locationPath = updateObj.locations?.[0]?.path;
|
|
497
|
+
const inputPath = typeof input.path === 'string' ? input.path
|
|
498
|
+
: typeof input.filePath === 'string' ? input.filePath
|
|
499
|
+
: typeof input.file === 'string' ? input.file
|
|
500
|
+
: '';
|
|
501
|
+
const resolvedPath = name === 'sysRun'
|
|
502
|
+
? ''
|
|
503
|
+
: (diff?.path || locationPath || inputPath || (typeof earlier?.parameters?.path === 'string' ? earlier.parameters.path : ''));
|
|
352
504
|
const parameters = {
|
|
353
|
-
...(earlier?.parameters || {}),
|
|
354
|
-
...
|
|
355
|
-
...(
|
|
356
|
-
...(
|
|
505
|
+
...(earlier?.parameters || {}),
|
|
506
|
+
...input,
|
|
507
|
+
...(resolvedPath ? { path: resolvedPath } : {}),
|
|
508
|
+
...(diff?.newText ? { content: diff.newText } : {})
|
|
357
509
|
};
|
|
510
|
+
const planCandidate = Array.isArray(parameters.todos) ? { todos: parameters.todos }
|
|
511
|
+
: Array.isArray(parameters.plan) ? { plan: parameters.plan }
|
|
512
|
+
: Array.isArray(rawOutputObj?.todos) ? { todos: rawOutputObj.todos }
|
|
513
|
+
: Array.isArray(rawOutputObj?.metadata?.todos) ? { todos: rawOutputObj.metadata.todos }
|
|
514
|
+
: null;
|
|
515
|
+
if (planCandidate) {
|
|
516
|
+
this.currentTurnPlanHandler?.(planCandidate);
|
|
517
|
+
}
|
|
518
|
+
const commandDetail = typeof parameters.command === 'string' ? parameters.command
|
|
519
|
+
: typeof parameters.cmd === 'string' ? parameters.cmd
|
|
520
|
+
: '';
|
|
521
|
+
const rawToolCandidate = typeof parameters.tool === 'string' ? parameters.tool
|
|
522
|
+
: typeof input.tool === 'string' ? input.tool
|
|
523
|
+
: '';
|
|
524
|
+
const isInvalidToolAttempt = rawToolCandidate.toLowerCase() === 'invalid'
|
|
525
|
+
|| rawTitle.toLowerCase() === 'invalid'
|
|
526
|
+
|| rawTitle.toLowerCase() === 'invalid tool'
|
|
527
|
+
|| name.toLowerCase() === 'invalid tool'
|
|
528
|
+
|| name.toLowerCase() === 'invalid'
|
|
529
|
+
|| (typeof parameters.error === 'string' && /Model tried to call unavailable tool/i.test(parameters.error));
|
|
530
|
+
if (isInvalidToolAttempt || (name === 'sysRun' && (commandDetail.trim() === 'true' || commandDetail.trim() === ':'))) {
|
|
531
|
+
this.liveFileActions.delete(id);
|
|
532
|
+
this.turnActions.delete(id);
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
const queryDetail = typeof parameters.query === 'string' ? parameters.query
|
|
536
|
+
: typeof parameters.pattern === 'string' ? parameters.pattern
|
|
537
|
+
: typeof parameters.url === 'string' ? parameters.url
|
|
538
|
+
: '';
|
|
539
|
+
const titleIsGeneric = !rawTitle
|
|
540
|
+
|| /^(read|write|edit|multiedit|delete|move|search|grep|glob|fetch|execute|bash|sh|zsh|terminal|provider_tool)$/i.test(rawTitle)
|
|
541
|
+
|| rawTitle.toLowerCase() === name.toLowerCase();
|
|
542
|
+
const detail = String(commandDetail
|
|
543
|
+
|| resolvedPath
|
|
544
|
+
|| queryDetail
|
|
545
|
+
|| (!titleIsGeneric ? rawTitle : '')
|
|
546
|
+
|| earlier?.detail
|
|
547
|
+
|| '');
|
|
358
548
|
const status = updateObj.status === 'completed' ? 'completed' : updateObj.status === 'failed' ? 'failed' : 'running';
|
|
359
|
-
const
|
|
360
|
-
detail
|
|
549
|
+
const isEmptyPendingStub = updateObj.status === 'pending'
|
|
550
|
+
&& !detail
|
|
551
|
+
&& Object.keys(input).length === 0
|
|
552
|
+
&& !diff?.newText
|
|
553
|
+
&& !planCandidate;
|
|
554
|
+
const action = {
|
|
555
|
+
id: `acp:${id}`,
|
|
556
|
+
name,
|
|
557
|
+
status,
|
|
558
|
+
parameters: { ...parameters, __pendingStub: isEmptyPendingStub },
|
|
559
|
+
detail
|
|
560
|
+
};
|
|
561
|
+
const shouldNotify = !isEmptyPendingStub && (!earlier
|
|
562
|
+
|| earlier.parameters?.__pendingStub === true
|
|
563
|
+
|| earlier.status !== status
|
|
564
|
+
|| earlier.name !== name
|
|
565
|
+
|| earlier.detail !== detail
|
|
566
|
+
|| Boolean(diff?.newText && diff.newText !== earlier?.parameters?.content));
|
|
567
|
+
this.turnActions.set(id, action);
|
|
361
568
|
if (status === 'running')
|
|
362
569
|
this.liveFileActions.set(id, action);
|
|
363
570
|
else
|
|
364
571
|
this.liveFileActions.delete(id);
|
|
365
|
-
|
|
572
|
+
if (shouldNotify) {
|
|
573
|
+
this.currentTurnNativeActionHandler?.(action);
|
|
574
|
+
}
|
|
366
575
|
}
|
|
367
576
|
}
|
|
368
577
|
else if ('textDelta' in updateObj) {
|
|
369
578
|
const delta = updateObj.textDelta;
|
|
370
|
-
if (delta && typeof delta === 'string'
|
|
371
|
-
this.
|
|
372
|
-
}
|
|
579
|
+
if (delta && typeof delta === 'string')
|
|
580
|
+
this.acceptText(delta, sessionId, client);
|
|
373
581
|
}
|
|
374
582
|
}
|
|
375
583
|
}
|
|
@@ -433,6 +641,7 @@ export class AcpProvider extends LLMProvider {
|
|
|
433
641
|
this.currentTurnChunkHandler = null;
|
|
434
642
|
this.currentTurnReasoningHandler = null;
|
|
435
643
|
this.currentTurnNativeActionHandler = null;
|
|
644
|
+
this.currentTurnPlanHandler = null;
|
|
436
645
|
this.liveFileActions.clear();
|
|
437
646
|
if (this.activeClient && this.activeSessionId) {
|
|
438
647
|
try {
|
|
@@ -470,7 +679,13 @@ export class AcpProvider extends LLMProvider {
|
|
|
470
679
|
this.currentTurnChunkHandler = options.onChunk || null;
|
|
471
680
|
this.currentTurnReasoningHandler = options.onReasoningChunk || null;
|
|
472
681
|
this.currentTurnNativeActionHandler = options.onNativeAction || null;
|
|
682
|
+
this.currentTurnPlanHandler = options.onPlanUpdate || null;
|
|
473
683
|
this.liveFileActions.clear();
|
|
684
|
+
this.turnActions.clear();
|
|
685
|
+
this.turnReasoning = '';
|
|
686
|
+
this.turnText = '';
|
|
687
|
+
this.hostHandoff = [];
|
|
688
|
+
this.toolRoutingError = undefined;
|
|
474
689
|
const onAbort = () => {
|
|
475
690
|
this.abort();
|
|
476
691
|
};
|
|
@@ -485,8 +700,10 @@ export class AcpProvider extends LLMProvider {
|
|
|
485
700
|
const toolHash = fingerprint(options.tools || []);
|
|
486
701
|
let previous = this.transportSnapshot;
|
|
487
702
|
const sessionChanged = previous && (previous.workspaceRoot !== workspaceRoot || previous.conversationId !== conversationId);
|
|
488
|
-
const
|
|
489
|
-
|
|
703
|
+
const historyShortened = Boolean(previous && historyHashes.length < previous.historyHashes.length);
|
|
704
|
+
const roleDiverged = Boolean(previous && !historyShortened && previous.historyRoles?.some((role, index) => historyMessages[index]?.role !== role));
|
|
705
|
+
const userPromptDiverged = Boolean(previous && !historyShortened && previous.userPromptHashes?.some((hash, index) => hash && fingerprint(historyMessages[index]?.content) !== hash));
|
|
706
|
+
const historyDiverged = historyShortened || roleDiverged || userPromptDiverged;
|
|
490
707
|
const systemShapeChanged = previous && systemHashes.length < previous.systemHashes.length;
|
|
491
708
|
if (sessionChanged || historyDiverged || systemShapeChanged) {
|
|
492
709
|
await this.close();
|
|
@@ -506,13 +723,22 @@ export class AcpProvider extends LLMProvider {
|
|
|
506
723
|
// duplicate the peer's own response before the next tool result.
|
|
507
724
|
const firstNew = newHistory[0];
|
|
508
725
|
if (firstNew?.role === 'assistant' &&
|
|
509
|
-
firstNew.content === previous.lastResponse.content
|
|
726
|
+
(firstNew.content === previous.lastResponse.content ||
|
|
727
|
+
(!previous.lastResponse.content && firstNew.content === 'No final response was provided.')) &&
|
|
510
728
|
fingerprint(firstNew.tool_calls || []) === fingerprint(previous.lastResponse.toolCalls)) {
|
|
511
729
|
newHistory.shift();
|
|
512
730
|
}
|
|
731
|
+
const filteredNewHistory = newHistory.filter(message => !(message?.role === 'assistant' && message?.content === 'No final response was provided.' && (!message.tool_calls || message.tool_calls.length === 0)));
|
|
732
|
+
const toolResultMessages = filteredNewHistory.filter(m => m?.role === 'tool');
|
|
733
|
+
const otherHistory = filteredNewHistory.filter(m => m?.role !== 'tool');
|
|
734
|
+
const formattedChangedSystem = changedSystem.map(message => ({
|
|
735
|
+
...message,
|
|
736
|
+
content: `[Context Update]\n${message.content}`
|
|
737
|
+
}));
|
|
513
738
|
promptMessages = [
|
|
514
|
-
...
|
|
515
|
-
...
|
|
739
|
+
...toolResultMessages,
|
|
740
|
+
...otherHistory,
|
|
741
|
+
...formattedChangedSystem
|
|
516
742
|
];
|
|
517
743
|
toolContext = toolContractUpdate(options.tools || [], previous.tools);
|
|
518
744
|
promptTools = [];
|
|
@@ -545,15 +771,25 @@ export class AcpProvider extends LLMProvider {
|
|
|
545
771
|
throw abortErr;
|
|
546
772
|
}
|
|
547
773
|
let rawContent = (result?.text || '').trim();
|
|
548
|
-
const toolCalls = this.extractToolCalls(rawContent);
|
|
549
|
-
// Strip tool call XML from chat content display
|
|
550
|
-
let content = rawContent
|
|
774
|
+
const toolCalls = this.hostHandoff.length > 0 ? this.hostHandoff : this.extractToolCalls(rawContent);
|
|
775
|
+
// Strip tool call XML / DSML from chat content display
|
|
776
|
+
let content = stripToolCallMarkup(rawContent);
|
|
777
|
+
const externalActions = [...this.turnActions.values()];
|
|
778
|
+
const incompleteFromActions = !content && toolCalls.length === 0 && externalActions.length > 0;
|
|
779
|
+
const finalContent = content || (toolCalls.length > 0 || incompleteFromActions ? '' : `Turn completed by ${this.peerId} over ACP.`);
|
|
551
780
|
this.transportSnapshot = {
|
|
552
|
-
conversationId,
|
|
553
|
-
|
|
781
|
+
conversationId,
|
|
782
|
+
workspaceRoot,
|
|
783
|
+
systemHashes,
|
|
784
|
+
historyHashes,
|
|
785
|
+
historyRoles: historyMessages.map(m => m.role),
|
|
786
|
+
userPromptHashes: historyMessages.map(m => m.role === 'user' ? fingerprint(m.content) : ''),
|
|
787
|
+
toolHash,
|
|
788
|
+
tools: structuredClone(options.tools || []),
|
|
789
|
+
lastResponse: { content: finalContent, toolCalls }
|
|
554
790
|
};
|
|
555
791
|
const response = {
|
|
556
|
-
content:
|
|
792
|
+
content: finalContent,
|
|
557
793
|
usage: {
|
|
558
794
|
promptTokens: Math.ceil(promptText.length / 4),
|
|
559
795
|
completionTokens: Math.ceil(rawContent.length / 4),
|
|
@@ -562,6 +798,14 @@ export class AcpProvider extends LLMProvider {
|
|
|
562
798
|
cacheMeasurement: 'unavailable'
|
|
563
799
|
}
|
|
564
800
|
};
|
|
801
|
+
if (externalActions.length > 0) {
|
|
802
|
+
response.externalActions = externalActions;
|
|
803
|
+
}
|
|
804
|
+
if (this.toolRoutingError && toolCalls.length === 0)
|
|
805
|
+
response.toolRoutingError = this.toolRoutingError;
|
|
806
|
+
if (this.turnReasoning.trim()) {
|
|
807
|
+
response.reasoningContent = this.turnReasoning;
|
|
808
|
+
}
|
|
565
809
|
const usage = result?.usage;
|
|
566
810
|
if (usage && Number.isFinite(usage.inputTokens) && usage.inputTokens >= 0
|
|
567
811
|
&& Number.isFinite(usage.outputTokens) && usage.outputTokens >= 0) {
|
|
@@ -576,11 +820,16 @@ export class AcpProvider extends LLMProvider {
|
|
|
576
820
|
measurement: 'provider_reported',
|
|
577
821
|
cacheMeasurement: usage.cachedReadTokens !== undefined ? 'provider_reported' : 'unavailable'
|
|
578
822
|
};
|
|
823
|
+
// OpenCode's ACP service builds usage from its final assistant message,
|
|
824
|
+
// not all internal inference/tool turns. Do not label it a task total.
|
|
825
|
+
response.usage.measurementScope = this.peerId === 'opencode' ? 'last_model_call' : 'peer_reported';
|
|
579
826
|
}
|
|
580
827
|
if (toolCalls.length > 0) {
|
|
581
828
|
response.toolCalls = toolCalls;
|
|
582
829
|
}
|
|
583
|
-
if (result?.stopReason === 'max_tokens' || result?.stopReason === 'max_turn_requests'
|
|
830
|
+
if (result?.stopReason === 'max_tokens' || result?.stopReason === 'max_turn_requests' || incompleteFromActions
|
|
831
|
+
|| externalActions.some(action => action.status === 'running')
|
|
832
|
+
|| (result?.stopReason === 'cancelled' && toolCalls.length === 0)) {
|
|
584
833
|
response.incompleteTurn = true;
|
|
585
834
|
}
|
|
586
835
|
return response;
|
|
@@ -593,6 +842,9 @@ export class AcpProvider extends LLMProvider {
|
|
|
593
842
|
throw abortErr;
|
|
594
843
|
}
|
|
595
844
|
const msg = err instanceof Error ? err.message : String(err);
|
|
845
|
+
if (msg.startsWith('ACP Peer Agent') || msg.includes('Free usage limit reached') || msg.includes('quota') || msg.includes('rate limit') || msg.includes('stalled')) {
|
|
846
|
+
throw (err instanceof Error ? err : new Error(msg));
|
|
847
|
+
}
|
|
596
848
|
throw new Error(`ACP Peer Agent (${this.peerId}) Error: ${msg}. Make sure "${this.command}" is installed and running.`);
|
|
597
849
|
}
|
|
598
850
|
finally {
|
|
@@ -601,6 +853,7 @@ export class AcpProvider extends LLMProvider {
|
|
|
601
853
|
this.currentTurnChunkHandler = null;
|
|
602
854
|
this.currentTurnReasoningHandler = null;
|
|
603
855
|
this.currentTurnNativeActionHandler = null;
|
|
856
|
+
this.currentTurnPlanHandler = null;
|
|
604
857
|
this.liveFileActions.clear();
|
|
605
858
|
}
|
|
606
859
|
}
|