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