@causyne/agent 1.18.0 → 1.20.0
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/package.json +1 -1
- package/src/agentLoop.js +2348 -2531
- package/src/agentLoop.ts +2865 -0
- package/src/checkpoints.d.ts +4 -0
- package/src/cliMode.js +30 -17
- package/src/commands.js +307 -57
- package/src/config.js +22 -0
- package/src/contextManager.d.ts +10 -0
- package/src/continuum/adapters/antigravity.js +193 -0
- package/src/continuum/adapters/antigravity.ts +204 -0
- package/src/continuum/adapters/base.js +48 -0
- package/src/continuum/adapters/base.ts +57 -0
- package/src/continuum/adapters/causyne.js +66 -0
- package/src/continuum/adapters/causyne.ts +72 -0
- package/src/continuum/adapters/claudeCode.js +171 -0
- package/src/continuum/adapters/claudeCode.ts +179 -0
- package/src/continuum/adapters/codex.js +181 -0
- package/src/continuum/adapters/codex.ts +193 -0
- package/src/continuum/adapters/opencode.js +134 -0
- package/src/continuum/adapters/opencode.ts +153 -0
- package/src/continuum/compactor.js +54 -0
- package/src/continuum/compactor.ts +83 -0
- package/src/continuum/index.js +8 -0
- package/src/continuum/index.ts +9 -0
- package/src/continuum/ingest.js +63 -0
- package/src/continuum/ingest.ts +89 -0
- package/src/continuum/sanitizer.js +55 -0
- package/src/continuum/sanitizer.ts +59 -0
- package/src/continuum/scanner.js +86 -0
- package/src/continuum/scanner.ts +106 -0
- package/src/continuum/types.js +3 -0
- package/src/continuum/types.ts +51 -0
- package/src/continuum/ui/continuumPicker.js +111 -0
- package/src/continuum/ui/continuumPicker.ts +145 -0
- package/src/cortex/autoCondenser.d.ts +2 -0
- package/src/cortex/vectorDb.d.ts +1 -0
- package/src/designPalettes.d.ts +2 -0
- package/src/devMode.d.ts +1 -0
- package/src/dynamicCatalogue.js +5 -3
- package/src/dynamicCatalogue.ts +7 -4
- package/src/embodimentSession.d.ts +2 -0
- package/src/entrypoint.js +12 -0
- package/src/memory.d.ts +1 -0
- package/src/memoryManager.d.ts +1 -0
- package/src/memoryManager.js +10 -6
- package/src/modelIds.d.ts +2 -0
- package/src/outputStore.d.ts +4 -0
- package/src/providers/acp.js +320 -299
- package/src/providers/acp.ts +360 -0
- package/src/providers/antigravity.js +387 -278
- package/src/providers/antigravity.ts +450 -0
- package/src/providers/base.d.ts +68 -0
- package/src/providers/factory.d.ts +1 -0
- package/src/provisioning/capabilityProvisioner.d.ts +2 -0
- package/src/sandbox.d.ts +1 -0
- package/src/sessionJournal.js +14 -1
- package/src/sessionJournal.ts +21 -1
- package/src/skillsManager.d.ts +3 -0
- package/src/slopDetector.d.ts +3 -0
- package/src/taskBuffer.d.ts +1 -0
- package/src/tokenTracker.d.ts +1 -0
- package/src/toolPacks.d.ts +8 -0
- package/src/tools/registry.d.ts +4 -0
- package/src/tui/chatRenderer.js +148 -8
- package/src/tui/clipboardSync.js +36 -0
- package/src/tui/clipboardSync.ts +36 -0
- package/src/tui/dialogs.js +15 -2
- package/src/tui/home.js +2 -1
- package/src/tui/modelPicker.js +254 -0
- package/src/tui/modelPicker.ts +318 -0
- package/src/tui/prompt.js +90 -8
- package/src/tui/selectList.js +20 -0
- package/src/tui/sessionPicker.js +185 -0
- package/src/tui/sessionPicker.ts +259 -0
- package/src/tui/stageSurface.js +9 -0
- package/src/tui/statusLine.js +5 -5
package/src/providers/acp.js
CHANGED
|
@@ -4,325 +4,346 @@ import { LLMProvider } from './base.js';
|
|
|
4
4
|
import { AcpClient } from '../acp/client.js';
|
|
5
5
|
import { getPeerProfile } from '../acp/peerProfiles.js';
|
|
6
6
|
import { BUILTIN_PEER_PRESETS } from '../acp/agentCatalog.js';
|
|
7
|
-
|
|
8
7
|
export function isAcpProvider(provider) {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
8
|
+
if (!provider)
|
|
9
|
+
return false;
|
|
10
|
+
const p = String(provider).toLowerCase();
|
|
11
|
+
return p === 'acp' || p.startsWith('acp/') || p.startsWith('acp:') ||
|
|
12
|
+
['opencode', 'claude', 'codex', 'cursor', 'hermes', 'goose', 'copilot'].includes(p);
|
|
13
13
|
}
|
|
14
|
-
|
|
15
14
|
export class AcpProvider extends LLMProvider {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
15
|
+
peerId;
|
|
16
|
+
command;
|
|
17
|
+
args;
|
|
18
|
+
activeClient = null;
|
|
19
|
+
activeSessionId = null;
|
|
20
|
+
currentTurnChunkHandler = null;
|
|
21
|
+
currentTurnReasoningHandler = null;
|
|
22
|
+
constructor(config = {}) {
|
|
23
|
+
super(config);
|
|
24
|
+
const providerStr = String(config.provider || '').toLowerCase().trim();
|
|
25
|
+
const configuredModel = typeof config.model === 'string' ? config.model.trim() : '';
|
|
26
|
+
let resolvedPeer = '';
|
|
27
|
+
if (providerStr.startsWith('acp/') || providerStr.startsWith('acp:')) {
|
|
28
|
+
resolvedPeer = providerStr.slice(4).split('/')[0] || '';
|
|
29
|
+
}
|
|
30
|
+
else if (providerStr && providerStr !== 'acp') {
|
|
31
|
+
resolvedPeer = providerStr;
|
|
32
|
+
}
|
|
33
|
+
else if (config.peer) {
|
|
34
|
+
resolvedPeer = String(config.peer).toLowerCase();
|
|
35
|
+
}
|
|
36
|
+
else if (configuredModel && configuredModel !== 'acp' && BUILTIN_PEER_PRESETS[configuredModel.toLowerCase()]) {
|
|
37
|
+
resolvedPeer = configuredModel.toLowerCase();
|
|
38
|
+
}
|
|
39
|
+
this.peerId = resolvedPeer || 'opencode';
|
|
40
|
+
const peerDefault = DEFAULT_MODEL_BY_PROVIDER[`acp/${this.peerId}`]
|
|
41
|
+
|| DEFAULT_MODEL_BY_PROVIDER[`acp`]
|
|
42
|
+
|| this.peerId;
|
|
43
|
+
const modelIsPeerName = !configuredModel || configuredModel === 'acp' || configuredModel === this.peerId;
|
|
44
|
+
this.model = canonicalModelId(modelIsPeerName ? peerDefault : configuredModel);
|
|
45
|
+
const profile = getPeerProfile(this.peerId);
|
|
46
|
+
if (profile) {
|
|
47
|
+
this.command = profile.command;
|
|
48
|
+
this.args = profile.args || [];
|
|
49
|
+
}
|
|
50
|
+
else {
|
|
51
|
+
const preset = BUILTIN_PEER_PRESETS[this.peerId];
|
|
52
|
+
if (preset) {
|
|
53
|
+
this.command = preset.command;
|
|
54
|
+
this.args = preset.args || [];
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
this.command = config.command || this.peerId;
|
|
58
|
+
this.args = config.args || ['acp'];
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
this.visionModels = ['*'];
|
|
62
|
+
this.audioModels = [];
|
|
57
63
|
}
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
const
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
64
|
+
formatConversation(messages, tools = []) {
|
|
65
|
+
const lines = [];
|
|
66
|
+
lines.push('[System Instructions]\nYou are acting as an AI reasoning engine for Causyne Agent over ACP. Do NOT invoke your own internal host CLI tools or execute commands directly. When an action or tool is required, output an explicit tool call in this exact format:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\nCausyne Agent will execute the tool in its secure environment and return the results back to you.');
|
|
67
|
+
if (tools && tools.length > 0) {
|
|
68
|
+
const toolSummaries = tools.map(t => {
|
|
69
|
+
const name = t.name || t.function?.name || 'unknown';
|
|
70
|
+
const desc = t.description || t.function?.description || '';
|
|
71
|
+
const params = t.parameters || t.input_schema || t.function?.parameters || {};
|
|
72
|
+
const paramKeys = Object.keys(params.properties || {}).join(', ');
|
|
73
|
+
return `- ${name}(${paramKeys}): ${desc}`;
|
|
74
|
+
}).join('\n');
|
|
75
|
+
lines.push(`[Available Tools]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`);
|
|
76
|
+
}
|
|
77
|
+
for (const msg of messages) {
|
|
78
|
+
const role = msg.role === 'user'
|
|
79
|
+
? 'User'
|
|
80
|
+
: (msg.role === 'assistant'
|
|
81
|
+
? 'Assistant'
|
|
82
|
+
: (msg.role === 'system'
|
|
83
|
+
? 'System Instructions'
|
|
84
|
+
: (msg.role === 'tool'
|
|
85
|
+
? `Tool Result (${msg.name || 'tool'})`
|
|
86
|
+
: 'Context')));
|
|
87
|
+
let text = '';
|
|
88
|
+
if (typeof msg.content === 'string') {
|
|
89
|
+
text = msg.content;
|
|
90
|
+
}
|
|
91
|
+
else if (Array.isArray(msg.content)) {
|
|
92
|
+
text = msg.content.map((c) => typeof c === 'string' ? c : (c?.text || '')).filter(Boolean).join('\n');
|
|
93
|
+
}
|
|
94
|
+
if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
|
|
95
|
+
for (const tc of msg.tool_calls) {
|
|
96
|
+
const fn = tc.function || {};
|
|
97
|
+
const fnArgs = typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {});
|
|
98
|
+
text += `\n<tool_call>{"name": "${fn.name}", "arguments": ${fnArgs}}</tool_call>`;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (text.trim()) {
|
|
102
|
+
lines.push(`[${role}]\n${text.trim()}`);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return lines.join('\n\n');
|
|
76
106
|
}
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
for (const tc of msg.tool_calls) {
|
|
97
|
-
const fn = tc.function || {};
|
|
98
|
-
const fnArgs = typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {});
|
|
99
|
-
text += `\n<tool_call>{"name": "${fn.name}", "arguments": ${fnArgs}}</tool_call>`;
|
|
107
|
+
formatPromptBlocks(messages, tools = [], imageSupport = false) {
|
|
108
|
+
const blocks = [];
|
|
109
|
+
let pending = [];
|
|
110
|
+
const flush = () => {
|
|
111
|
+
if (pending.length === 0)
|
|
112
|
+
return;
|
|
113
|
+
blocks.push({ type: 'text', text: pending.join('\n\n') });
|
|
114
|
+
pending = [];
|
|
115
|
+
};
|
|
116
|
+
pending.push('[System Instructions]\nYou are acting as an AI reasoning engine for Causyne Agent over ACP. Do NOT invoke your own internal host CLI tools or execute commands directly. When an action or tool is required, output an explicit tool call in this exact format:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\nCausyne Agent will execute the tool in its secure environment and return the results back to you.');
|
|
117
|
+
if (tools && tools.length > 0) {
|
|
118
|
+
const toolSummaries = tools.map(t => {
|
|
119
|
+
const name = t.name || t.function?.name || 'unknown';
|
|
120
|
+
const desc = t.description || t.function?.description || '';
|
|
121
|
+
const params = t.parameters || t.input_schema || t.function?.parameters || {};
|
|
122
|
+
const paramKeys = Object.keys(params.properties || {}).join(', ');
|
|
123
|
+
return `- ${name}(${paramKeys}): ${desc}`;
|
|
124
|
+
}).join('\n');
|
|
125
|
+
pending.push(`[Available Tools]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`);
|
|
100
126
|
}
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
127
|
+
for (const msg of messages) {
|
|
128
|
+
const role = this._roleLabel(msg);
|
|
129
|
+
let text = '';
|
|
130
|
+
if (typeof msg.content === 'string') {
|
|
131
|
+
text = msg.content;
|
|
132
|
+
}
|
|
133
|
+
else if (Array.isArray(msg.content)) {
|
|
134
|
+
text = msg.content.map((c) => typeof c === 'string' ? c : (c?.text || '')).filter(Boolean).join('\n');
|
|
135
|
+
}
|
|
136
|
+
if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
|
|
137
|
+
for (const tc of msg.tool_calls) {
|
|
138
|
+
const fn = tc.function || {};
|
|
139
|
+
const fnArgs = typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {});
|
|
140
|
+
text += `\n<tool_call>{"name": "${fn.name}", "arguments": ${fnArgs}}</tool_call>`;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
if (text.trim()) {
|
|
144
|
+
pending.push(`[${role}]\n${text.trim()}`);
|
|
145
|
+
}
|
|
146
|
+
if (Array.isArray(msg.content)) {
|
|
147
|
+
for (const part of msg.content) {
|
|
148
|
+
const image = this._imageBlock(part);
|
|
149
|
+
if (!image)
|
|
150
|
+
continue;
|
|
151
|
+
flush();
|
|
152
|
+
if (imageSupport) {
|
|
153
|
+
blocks.push(image);
|
|
154
|
+
}
|
|
155
|
+
else {
|
|
156
|
+
pending.push(`[Image omitted — ${this.peerId} does not accept image input]`);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
flush();
|
|
162
|
+
return blocks.length > 0 ? blocks : [{ type: 'text', text: 'Continue.' }];
|
|
106
163
|
}
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
formatPromptBlocks(messages, tools = [], imageSupport = false) {
|
|
118
|
-
const blocks = [];
|
|
119
|
-
let pending = [];
|
|
120
|
-
const flush = () => {
|
|
121
|
-
if (pending.length === 0) return;
|
|
122
|
-
blocks.push({ type: 'text', text: pending.join('\n\n') });
|
|
123
|
-
pending = [];
|
|
124
|
-
};
|
|
125
|
-
|
|
126
|
-
pending.push(`[System Instructions]\nYou are acting as an AI reasoning engine for Causyne Agent over ACP. Do NOT invoke your own internal host CLI tools or execute commands directly. When an action or tool is required, output an explicit tool call in this exact format:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\nCausyne Agent will execute the tool in its secure environment and return the results back to you.`);
|
|
127
|
-
|
|
128
|
-
if (tools && tools.length > 0) {
|
|
129
|
-
const toolSummaries = tools.map(t => {
|
|
130
|
-
const name = t.name || t.function?.name || 'unknown';
|
|
131
|
-
const desc = t.description || t.function?.description || '';
|
|
132
|
-
const params = t.parameters || t.input_schema || t.function?.parameters || {};
|
|
133
|
-
const paramKeys = Object.keys(params.properties || {}).join(', ');
|
|
134
|
-
return `- ${name}(${paramKeys}): ${desc}`;
|
|
135
|
-
}).join('\n');
|
|
136
|
-
pending.push(`[Available Tools]\nYou may invoke tools when needed by outputting:\n<tool_call>{"name": "tool_name", "arguments": { ... }}</tool_call>\n\n${toolSummaries}`);
|
|
164
|
+
_roleLabel(msg) {
|
|
165
|
+
if (msg.role === 'user')
|
|
166
|
+
return 'User';
|
|
167
|
+
if (msg.role === 'assistant')
|
|
168
|
+
return 'Assistant';
|
|
169
|
+
if (msg.role === 'system')
|
|
170
|
+
return 'System Instructions';
|
|
171
|
+
if (msg.role === 'tool')
|
|
172
|
+
return `Tool Result (${msg.name || 'tool'})`;
|
|
173
|
+
return 'Context';
|
|
137
174
|
}
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
text = msg.content;
|
|
144
|
-
} else if (Array.isArray(msg.content)) {
|
|
145
|
-
text = msg.content.map(c => typeof c === 'string' ? c : (c?.text || '')).filter(Boolean).join('\n');
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
if (msg.tool_calls && Array.isArray(msg.tool_calls)) {
|
|
149
|
-
for (const tc of msg.tool_calls) {
|
|
150
|
-
const fn = tc.function || {};
|
|
151
|
-
const fnArgs = typeof fn.arguments === 'string' ? fn.arguments : JSON.stringify(fn.arguments || {});
|
|
152
|
-
text += `\n<tool_call>{"name": "${fn.name}", "arguments": ${fnArgs}}</tool_call>`;
|
|
175
|
+
_imageBlock(part) {
|
|
176
|
+
if (!part || typeof part !== 'object')
|
|
177
|
+
return null;
|
|
178
|
+
if (part.type === 'image' && part.source?.type === 'base64') {
|
|
179
|
+
return { type: 'image', mimeType: part.source.media_type, data: part.source.data };
|
|
153
180
|
}
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
if (Array.isArray(msg.content)) {
|
|
161
|
-
for (const part of msg.content) {
|
|
162
|
-
const image = this._imageBlock(part);
|
|
163
|
-
if (!image) continue;
|
|
164
|
-
flush();
|
|
165
|
-
if (imageSupport) {
|
|
166
|
-
blocks.push(image);
|
|
167
|
-
} else {
|
|
168
|
-
pending.push(`[Image omitted — ${this.peerId} does not accept image input]`);
|
|
169
|
-
}
|
|
181
|
+
if (part.type === 'image_url' && typeof part.image_url?.url === 'string') {
|
|
182
|
+
const match = part.image_url.url.match(/^data:([^;]+);base64,(.+)$/);
|
|
183
|
+
if (match)
|
|
184
|
+
return { type: 'image', mimeType: match[1], data: match[2] };
|
|
170
185
|
}
|
|
171
|
-
|
|
172
|
-
}
|
|
173
|
-
|
|
174
|
-
flush();
|
|
175
|
-
return blocks.length > 0 ? blocks : [{ type: 'text', text: 'Continue.' }];
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
_roleLabel(msg) {
|
|
179
|
-
if (msg.role === 'user') return 'User';
|
|
180
|
-
if (msg.role === 'assistant') return 'Assistant';
|
|
181
|
-
if (msg.role === 'system') return 'System Instructions';
|
|
182
|
-
if (msg.role === 'tool') return `Tool Result (${msg.name || 'tool'})`;
|
|
183
|
-
return 'Context';
|
|
184
|
-
}
|
|
185
|
-
|
|
186
|
-
_imageBlock(part) {
|
|
187
|
-
if (!part || typeof part !== 'object') return null;
|
|
188
|
-
if (part.type === 'image' && part.source?.type === 'base64') {
|
|
189
|
-
return { type: 'image', mimeType: part.source.media_type, data: part.source.data };
|
|
186
|
+
return null;
|
|
190
187
|
}
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
188
|
+
extractToolCalls(text) {
|
|
189
|
+
const calls = [];
|
|
190
|
+
if (!text || typeof text !== 'string')
|
|
191
|
+
return calls;
|
|
192
|
+
const regex = /<tool_call>([\s\S]*?)<\/tool_call>/g;
|
|
193
|
+
let match;
|
|
194
|
+
let index = 0;
|
|
195
|
+
while ((match = regex.exec(text)) !== null) {
|
|
196
|
+
try {
|
|
197
|
+
const raw = match[1]?.trim() || '';
|
|
198
|
+
const parsed = JSON.parse(raw);
|
|
199
|
+
const name = parsed.name || parsed.tool || parsed.function?.name;
|
|
200
|
+
if (name) {
|
|
201
|
+
const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
|
|
202
|
+
calls.push({
|
|
203
|
+
id: `acp_call_${Date.now()}_${index++}`,
|
|
204
|
+
type: 'function',
|
|
205
|
+
function: {
|
|
206
|
+
name,
|
|
207
|
+
arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
|
|
208
|
+
}
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
// ignore malformed tool_call blocks
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (calls.length === 0) {
|
|
217
|
+
const fenceRegex = /```(?:tool_call|json)?\s*(\{[\s\S]*?"name"\s*:\s*[\s\S]*?\})\s*```/g;
|
|
218
|
+
while ((match = fenceRegex.exec(text)) !== null) {
|
|
219
|
+
try {
|
|
220
|
+
const raw = match[1]?.trim() || '';
|
|
221
|
+
const parsed = JSON.parse(raw);
|
|
222
|
+
const name = parsed.name || parsed.tool || parsed.function?.name;
|
|
223
|
+
if (name) {
|
|
224
|
+
const rawArgs = parsed.arguments !== undefined ? parsed.arguments : (parsed.parameters !== undefined ? parsed.parameters : (parsed.input !== undefined ? parsed.input : (parsed.function?.arguments || {})));
|
|
225
|
+
calls.push({
|
|
226
|
+
id: `acp_call_${Date.now()}_${index++}`,
|
|
227
|
+
type: 'function',
|
|
228
|
+
function: {
|
|
229
|
+
name,
|
|
230
|
+
arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
catch {
|
|
236
|
+
// ignore
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
return calls;
|
|
194
241
|
}
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
242
|
+
async getOrCreateClient() {
|
|
243
|
+
if (this.activeClient && this.activeSessionId) {
|
|
244
|
+
return { client: this.activeClient, sessionId: this.activeSessionId };
|
|
245
|
+
}
|
|
246
|
+
const client = new AcpClient({
|
|
247
|
+
command: this.command,
|
|
248
|
+
args: this.args,
|
|
249
|
+
cwd: process.cwd(),
|
|
250
|
+
promptTimeoutMs: 180_000,
|
|
251
|
+
permissionHandler: async (req) => {
|
|
252
|
+
const allowOpt = req.options?.find(o => o.kind === 'allow_once' || o.kind === 'allow_always' || o.optionId === 'allow');
|
|
253
|
+
if (allowOpt)
|
|
254
|
+
return { outcome: 'selected', optionId: allowOpt.optionId };
|
|
255
|
+
return { outcome: 'cancelled' };
|
|
256
|
+
},
|
|
257
|
+
onUpdate: (_sessionId, update) => {
|
|
258
|
+
if (update && typeof update === 'object') {
|
|
259
|
+
const updateObj = update;
|
|
260
|
+
if (updateObj.sessionUpdate === 'agent_thought_chunk') {
|
|
261
|
+
const thought = updateObj.content?.text || updateObj.thought || (typeof updateObj.content === 'string' ? updateObj.content : '');
|
|
262
|
+
if (thought && this.currentTurnReasoningHandler) {
|
|
263
|
+
this.currentTurnReasoningHandler(thought);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
else if ('textDelta' in updateObj) {
|
|
267
|
+
const delta = updateObj.textDelta;
|
|
268
|
+
if (delta && typeof delta === 'string' && this.currentTurnChunkHandler) {
|
|
269
|
+
this.currentTurnChunkHandler(delta);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
216
273
|
}
|
|
217
|
-
|
|
274
|
+
});
|
|
275
|
+
await client.start();
|
|
276
|
+
const sessionId = await client.newSession(process.cwd());
|
|
277
|
+
let targetModel = this.model;
|
|
278
|
+
if (this.peerId === 'opencode' && targetModel !== this.peerId && !targetModel.startsWith('opencode/')) {
|
|
279
|
+
targetModel = `opencode/${targetModel}`;
|
|
218
280
|
}
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
281
|
+
if (targetModel && targetModel !== 'acp' && targetModel !== this.peerId) {
|
|
282
|
+
try {
|
|
283
|
+
await client.setSessionModel(sessionId, targetModel);
|
|
284
|
+
}
|
|
285
|
+
catch {
|
|
286
|
+
// peer does not support setSessionModel
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
this.activeClient = client;
|
|
290
|
+
this.activeSessionId = sessionId;
|
|
291
|
+
return { client, sessionId };
|
|
222
292
|
}
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
id: `acp_call_${Date.now()}_${index++}`,
|
|
234
|
-
type: 'function',
|
|
235
|
-
function: {
|
|
236
|
-
name,
|
|
237
|
-
arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
|
|
238
|
-
}
|
|
239
|
-
});
|
|
240
|
-
}
|
|
241
|
-
} catch {
|
|
242
|
-
// ignore
|
|
293
|
+
async close() {
|
|
294
|
+
if (this.activeClient) {
|
|
295
|
+
try {
|
|
296
|
+
await this.activeClient.close();
|
|
297
|
+
}
|
|
298
|
+
catch {
|
|
299
|
+
// ignore close error
|
|
300
|
+
}
|
|
301
|
+
this.activeClient = null;
|
|
302
|
+
this.activeSessionId = null;
|
|
243
303
|
}
|
|
244
|
-
}
|
|
245
304
|
}
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
async chat(messages, options = {}) {
|
|
251
|
-
const client = new AcpClient({
|
|
252
|
-
command: this.command,
|
|
253
|
-
args: this.args,
|
|
254
|
-
cwd: process.cwd(),
|
|
255
|
-
promptTimeoutMs: 180_000,
|
|
256
|
-
permissionHandler: async (req) => {
|
|
257
|
-
// Auto-approve peer permissions (allow once / allow always)
|
|
258
|
-
const allowOpt = req.options?.find(o => o.kind === 'allow_once' || o.kind === 'allow_always' || o.optionId === 'allow');
|
|
259
|
-
if (allowOpt) return { outcome: 'selected', optionId: allowOpt.optionId };
|
|
260
|
-
return { outcome: 'cancelled' };
|
|
261
|
-
}
|
|
262
|
-
});
|
|
263
|
-
|
|
264
|
-
try {
|
|
265
|
-
await client.start();
|
|
266
|
-
const sessionId = await client.newSession(process.cwd());
|
|
267
|
-
|
|
268
|
-
// OpenCode ids are namespaced (`opencode/<model>`); every other peer
|
|
269
|
-
// takes the id its own CLI publishes. When the resolved model IS the peer
|
|
270
|
-
// name, the peer's configured default is meant and no override is sent.
|
|
271
|
-
let targetModel = this.model;
|
|
272
|
-
if (this.peerId === 'opencode' && targetModel !== this.peerId && !targetModel.startsWith('opencode/')) {
|
|
273
|
-
targetModel = `opencode/${targetModel}`;
|
|
274
|
-
}
|
|
275
|
-
if (targetModel && targetModel !== 'acp' && targetModel !== this.peerId) {
|
|
305
|
+
async chat(messages, options = {}) {
|
|
306
|
+
this.currentTurnChunkHandler = options.onChunk || null;
|
|
307
|
+
this.currentTurnReasoningHandler = options.onReasoningChunk || null;
|
|
276
308
|
try {
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
309
|
+
const { client, sessionId } = await this.getOrCreateClient();
|
|
310
|
+
const supportsImages = client.agentCapabilities?.promptCapabilities?.image === true;
|
|
311
|
+
const promptBlocks = this.formatPromptBlocks(messages, options.tools, supportsImages);
|
|
312
|
+
const promptText = promptBlocks.filter(b => b.type === 'text').map(b => b.text).join('\n\n');
|
|
313
|
+
let result;
|
|
314
|
+
try {
|
|
315
|
+
result = await client.prompt(sessionId, promptBlocks);
|
|
316
|
+
}
|
|
317
|
+
catch (promptErr) {
|
|
318
|
+
// If peer failed, try recreating client once in case connection dropped
|
|
319
|
+
await this.close();
|
|
320
|
+
const fresh = await this.getOrCreateClient();
|
|
321
|
+
result = await fresh.client.prompt(fresh.sessionId, promptBlocks);
|
|
322
|
+
}
|
|
323
|
+
let rawContent = (result?.text || '').trim();
|
|
324
|
+
const toolCalls = this.extractToolCalls(rawContent);
|
|
325
|
+
// Strip tool call XML from chat content display
|
|
326
|
+
let content = rawContent.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim();
|
|
327
|
+
const response = {
|
|
328
|
+
content: content || (toolCalls.length > 0 ? '' : `Turn completed by ${this.peerId} over ACP.`),
|
|
329
|
+
usage: {
|
|
330
|
+
promptTokens: Math.ceil(promptText.length / 4),
|
|
331
|
+
completionTokens: Math.ceil(rawContent.length / 4),
|
|
332
|
+
cachedPromptTokens: 0
|
|
333
|
+
}
|
|
334
|
+
};
|
|
335
|
+
if (toolCalls.length > 0) {
|
|
336
|
+
response.toolCalls = toolCalls;
|
|
337
|
+
}
|
|
338
|
+
return response;
|
|
280
339
|
}
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
const promptText = promptBlocks.filter(b => b.type === 'text').map(b => b.text).join('\n\n');
|
|
286
|
-
let result;
|
|
287
|
-
try {
|
|
288
|
-
result = await client.prompt(sessionId, promptBlocks);
|
|
289
|
-
} catch (promptErr) {
|
|
290
|
-
// If opencode failed with beam-free, attempt fallback to flint-40b-free
|
|
291
|
-
if (this.peerId === 'opencode' && targetModel !== 'opencode/flint-40b-free') {
|
|
292
|
-
try {
|
|
293
|
-
await client.setSessionModel(sessionId, 'opencode/flint-40b-free');
|
|
294
|
-
result = await client.prompt(sessionId, promptBlocks);
|
|
295
|
-
} catch {
|
|
296
|
-
throw promptErr;
|
|
297
|
-
}
|
|
298
|
-
} else {
|
|
299
|
-
throw promptErr;
|
|
340
|
+
catch (err) {
|
|
341
|
+
await this.close();
|
|
342
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
343
|
+
throw new Error(`ACP Peer Agent (${this.peerId}) Error: ${msg}. Make sure "${this.command}" is installed and running.`);
|
|
300
344
|
}
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
let rawContent = (result?.text || '').trim();
|
|
304
|
-
const toolCalls = this.extractToolCalls(rawContent);
|
|
305
|
-
|
|
306
|
-
// Strip tool call XML from chat content display
|
|
307
|
-
let content = rawContent.replace(/<tool_call>[\s\S]*?<\/tool_call>/g, '').trim();
|
|
308
|
-
|
|
309
|
-
const response = {
|
|
310
|
-
content: content || (toolCalls.length > 0 ? '' : `Turn completed by ${this.peerId} over ACP.`),
|
|
311
|
-
usage: {
|
|
312
|
-
promptTokens: Math.ceil(promptText.length / 4),
|
|
313
|
-
completionTokens: Math.ceil(rawContent.length / 4),
|
|
314
|
-
cachedPromptTokens: 0
|
|
345
|
+
finally {
|
|
346
|
+
this.currentTurnChunkHandler = null;
|
|
315
347
|
}
|
|
316
|
-
};
|
|
317
|
-
if (toolCalls.length > 0) {
|
|
318
|
-
response.toolCalls = toolCalls;
|
|
319
|
-
}
|
|
320
|
-
return response;
|
|
321
|
-
} catch (err) {
|
|
322
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
323
|
-
throw new Error(`ACP Peer Agent (${this.peerId}) Error: ${msg}. Make sure "${this.command}" is installed and running.`);
|
|
324
|
-
} finally {
|
|
325
|
-
await client.close();
|
|
326
348
|
}
|
|
327
|
-
}
|
|
328
349
|
}
|