@causyne/agent 1.20.0 → 1.20.7

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 (130) hide show
  1. package/README.md +13 -9
  2. package/SECURITY.md +1 -4
  3. package/package.json +1 -1
  4. package/src/acp/client.js +176 -26
  5. package/src/acp/client.ts +167 -25
  6. package/src/acp/protocol.js +116 -0
  7. package/src/acp/protocol.ts +163 -0
  8. package/src/acp/server.js +5 -6
  9. package/src/acp/server.ts +4 -6
  10. package/src/agentLoop.d.ts +1 -0
  11. package/src/agentLoop.js +681 -245
  12. package/src/agentLoop.ts +708 -262
  13. package/src/agentPolicy.js +9 -0
  14. package/src/agentPolicy.ts +9 -0
  15. package/src/approvalPolicy.js +55 -0
  16. package/src/approvalPolicy.ts +66 -0
  17. package/src/browser/browserRuntime.js +217 -14
  18. package/src/browser/browserRuntime.ts +255 -14
  19. package/src/browser/causyneBrowser.js +1215 -68
  20. package/src/browser/causyneBrowser.ts +1340 -72
  21. package/src/cliMode.js +52 -29
  22. package/src/commands.js +141 -17
  23. package/src/config.js +22 -12
  24. package/src/continuum/ui/continuumPicker.js +18 -1
  25. package/src/continuum/ui/continuumPicker.ts +19 -1
  26. package/src/dynamicCatalogue.js +87 -20
  27. package/src/dynamicCatalogue.ts +85 -15
  28. package/src/launchIntent.js +40 -0
  29. package/src/launchIntent.ts +49 -0
  30. package/src/memoryManager.js +26 -2
  31. package/src/modelCatalogue.js +2 -0
  32. package/src/planCache.js +320 -11
  33. package/src/planCache.ts +402 -13
  34. package/src/providers/acp.js +173 -18
  35. package/src/providers/acp.ts +169 -19
  36. package/src/providers/antigravity.d.ts +5 -1
  37. package/src/providers/antigravity.js +674 -34
  38. package/src/providers/antigravity.ts +707 -35
  39. package/src/providers/base.d.ts +10 -0
  40. package/src/providers/factory.js +2 -0
  41. package/src/providers/pi.js +161 -0
  42. package/src/providers/pi.ts +148 -0
  43. package/src/provisioning/capabilityProvisioner.js +17 -0
  44. package/src/provisioning/capabilityTools.js +1 -1
  45. package/src/sandbox.js +30 -39
  46. package/src/sessionJournal.js +53 -10
  47. package/src/sessionJournal.ts +64 -10
  48. package/src/taskShape.js +9 -9
  49. package/src/taskShape.ts +9 -9
  50. package/src/timeMachine.js +124 -0
  51. package/src/timeMachine.ts +141 -0
  52. package/src/toolPacks.js +4 -10
  53. package/src/tools/archive.js +196 -59
  54. package/src/tools/archive.ts +220 -0
  55. package/src/tools/browserAutomator.js +78 -9
  56. package/src/tools/browserAutomator.ts +90 -9
  57. package/src/tools/desktopOpen.js +114 -31
  58. package/src/tools/desktopOpen.ts +144 -0
  59. package/src/tools/gitExec.js +5 -3
  60. package/src/tools/nativeEngine.js +4 -3
  61. package/src/tools/nativeEngine.ts +5 -3
  62. package/src/tools/openSourceToolProvisioner.js +5 -4
  63. package/src/tools/openSourceToolProvisioner.ts +5 -4
  64. package/src/tools/registry.js +3 -0
  65. package/src/tools/screenshot.js +55 -71
  66. package/src/tools/screenshot.ts +70 -0
  67. package/src/tools/sysRun.js +284 -117
  68. package/src/tools/sysRun.ts +347 -0
  69. package/src/tools/toolSelfRepair.js +109 -2
  70. package/src/tools/toolSelfRepair.ts +100 -2
  71. package/src/tools/updatePlan.js +49 -1
  72. package/src/tools/updatePlan.ts +43 -1
  73. package/src/tools/viewImage.js +93 -78
  74. package/src/tools/viewImage.ts +116 -0
  75. package/src/tools/webFetch.js +20 -6
  76. package/src/tools/webFetch.ts +26 -6
  77. package/src/tui/activityLayout.js +9 -0
  78. package/src/tui/activityLayout.ts +10 -0
  79. package/src/tui/block.d.ts +1 -0
  80. package/src/tui/chatRenderer.d.ts +23 -0
  81. package/src/tui/chatRenderer.js +49 -49
  82. package/src/tui/clipboardSync.js +28 -1
  83. package/src/tui/clipboardSync.ts +26 -1
  84. package/src/tui/codeProgress.js +299 -0
  85. package/src/tui/codeProgress.ts +304 -0
  86. package/src/tui/codeStreamRenderer.js +132 -0
  87. package/src/tui/codeStreamRenderer.ts +141 -0
  88. package/src/tui/commandPresentation.js +11 -0
  89. package/src/tui/commandPresentation.ts +18 -0
  90. package/src/tui/completion.js +45 -13
  91. package/src/tui/composerControls.js +131 -0
  92. package/src/tui/composerControls.ts +184 -0
  93. package/src/tui/diff.d.ts +2 -0
  94. package/src/tui/home.js +4 -2
  95. package/src/tui/homeTransition.js +21 -0
  96. package/src/tui/homeTransition.ts +27 -0
  97. package/src/tui/homeView.js +62 -0
  98. package/src/tui/homeView.ts +91 -0
  99. package/src/tui/layout.js +46 -0
  100. package/src/tui/layout.ts +52 -0
  101. package/src/tui/messageActionPlacement.js +16 -0
  102. package/src/tui/messageActionPlacement.ts +25 -0
  103. package/src/tui/messageInteraction.js +221 -0
  104. package/src/tui/messageInteraction.ts +275 -0
  105. package/src/tui/modelPicker.js +4 -24
  106. package/src/tui/modelPicker.ts +4 -20
  107. package/src/tui/mouseHover.js +6 -0
  108. package/src/tui/mouseHover.ts +5 -0
  109. package/src/tui/prompt.js +175 -101
  110. package/src/tui/resizeRecovery.js +15 -0
  111. package/src/tui/resizeRecovery.ts +27 -0
  112. package/src/tui/scrollInteraction.js +97 -0
  113. package/src/tui/scrollInteraction.ts +189 -0
  114. package/src/tui/sessionLayout.js +12 -0
  115. package/src/tui/sessionLayout.ts +12 -0
  116. package/src/tui/sessionPicker.js +111 -16
  117. package/src/tui/sessionPicker.ts +121 -16
  118. package/src/tui/sessionSidebar.js +78 -0
  119. package/src/tui/sessionSidebar.ts +95 -0
  120. package/src/tui/setup.js +1 -1
  121. package/src/tui/setup.ts +1 -1
  122. package/src/tui/stageSurface.js +120 -58
  123. package/src/tui/text.d.ts +6 -0
  124. package/src/tui/textLayout.js +23 -0
  125. package/src/tui/textLayout.ts +28 -0
  126. package/src/tui/viewport.js +204 -279
  127. package/src/tui/viewport.ts +326 -0
  128. package/src/types/contracts.ts +54 -0
  129. package/src/utils/paths.js +5 -4
  130. package/src/utils/paths.ts +5 -5
package/src/acp/client.ts CHANGED
@@ -6,10 +6,12 @@ import {
6
6
  ACP_ERROR_CODES,
7
7
  ACP_METHODS,
8
8
  ACP_PROTOCOL_VERSION,
9
+ extractAcpSessionModels,
9
10
  isJsonRpcRequest,
10
11
  isJsonRpcResponse
11
12
  } from './protocol.js';
12
13
  import type {
14
+ AcpDiscoveredSessionModels,
13
15
  ContentBlock,
14
16
  InitializeRequest,
15
17
  InitializeResult,
@@ -52,6 +54,13 @@ interface PendingRequest {
52
54
  reject: (error: Error) => void;
53
55
  timer: NodeJS.Timeout;
54
56
  method: string;
57
+ cleanup?: () => void;
58
+ }
59
+
60
+ function createAbortError(message = 'ACP operation aborted by user'): Error {
61
+ const err = new Error(message);
62
+ err.name = 'AbortError';
63
+ return err;
55
64
  }
56
65
 
57
66
  const MAX_STDERR_CHARS = 4000;
@@ -67,6 +76,12 @@ export class AcpClient {
67
76
  private closed = false;
68
77
  private exitError: Error | null = null;
69
78
  private initResult: InitializeResult | null = null;
79
+ private readonly sessionModels = new Map<string, AcpDiscoveredSessionModels>();
80
+ private latestSessionModels: AcpDiscoveredSessionModels = {
81
+ availableModels: [],
82
+ modelLabels: {},
83
+ usesConfigOption: false
84
+ };
70
85
 
71
86
  constructor(options: AcpClientOptions) {
72
87
  this.options = options;
@@ -88,7 +103,59 @@ export class AcpClient {
88
103
  return this.initResult?.authMethods;
89
104
  }
90
105
 
91
- async start(): Promise<InitializeResult> {
106
+ get discoveredModels(): string[] {
107
+ return [...this.latestSessionModels.availableModels];
108
+ }
109
+
110
+ get currentModelId(): string | undefined {
111
+ return this.latestSessionModels.currentModelId;
112
+ }
113
+
114
+ get modelLabels(): Record<string, string> {
115
+ return { ...this.latestSessionModels.modelLabels };
116
+ }
117
+
118
+ getSessionModels(sessionId?: string): AcpDiscoveredSessionModels {
119
+ if (sessionId && this.sessionModels.has(sessionId)) {
120
+ const state = this.sessionModels.get(sessionId)!;
121
+ return {
122
+ currentModelId: state.currentModelId,
123
+ availableModels: [...state.availableModels],
124
+ modelLabels: { ...state.modelLabels },
125
+ usesConfigOption: state.usesConfigOption,
126
+ configOptionId: state.configOptionId
127
+ };
128
+ }
129
+ return {
130
+ currentModelId: this.latestSessionModels.currentModelId,
131
+ availableModels: [...this.latestSessionModels.availableModels],
132
+ modelLabels: { ...this.latestSessionModels.modelLabels },
133
+ usesConfigOption: this.latestSessionModels.usesConfigOption,
134
+ configOptionId: this.latestSessionModels.configOptionId
135
+ };
136
+ }
137
+
138
+ private recordSessionModels(sessionId: string, payload: unknown): void {
139
+ const extracted = extractAcpSessionModels(payload);
140
+ if (extracted.availableModels.length === 0 && !extracted.currentModelId) {
141
+ return;
142
+ }
143
+ const existing = this.sessionModels.get(sessionId);
144
+ const merged: AcpDiscoveredSessionModels = {
145
+ currentModelId: extracted.currentModelId ?? existing?.currentModelId,
146
+ availableModels: extracted.availableModels.length > 0
147
+ ? extracted.availableModels
148
+ : (existing?.availableModels ?? []),
149
+ modelLabels: { ...(existing?.modelLabels ?? {}), ...extracted.modelLabels },
150
+ usesConfigOption: extracted.usesConfigOption || Boolean(existing?.usesConfigOption),
151
+ configOptionId: extracted.configOptionId ?? existing?.configOptionId
152
+ };
153
+ this.sessionModels.set(sessionId, merged);
154
+ this.latestSessionModels = merged;
155
+ }
156
+
157
+ async start(signal?: AbortSignal): Promise<InitializeResult> {
158
+ if (signal?.aborted) throw createAbortError();
92
159
  if (this.child) throw new Error('client already started');
93
160
  const args = this.options.args ?? [];
94
161
  const child = spawn(this.options.command, args, {
@@ -101,6 +168,7 @@ export class AcpClient {
101
168
 
102
169
  child.stdout.setEncoding('utf8');
103
170
  child.stdout.on('data', (chunk: string) => {
171
+ if (this.closed) return;
104
172
  this.buffer += chunk;
105
173
  void this.drain();
106
174
  });
@@ -109,8 +177,8 @@ export class AcpClient {
109
177
  this.stderrTail = `${this.stderrTail}${chunk}`.slice(-MAX_STDERR_CHARS);
110
178
  });
111
179
  child.on('error', (error) => this.failAll(new Error(`agent process failed: ${error.message}`)));
112
- child.on('exit', (code, signal) => {
113
- const detail = this.stderrTail.trim() || `exit code ${code ?? 'null'}${signal ? ` signal ${signal}` : ''}`;
180
+ child.on('exit', (code, exitSignal) => {
181
+ const detail = this.stderrTail.trim() || `exit code ${code ?? 'null'}${exitSignal ? ` signal ${exitSignal}` : ''}`;
114
182
  this.failAll(new Error(`agent process exited: ${detail}`));
115
183
  });
116
184
 
@@ -127,19 +195,20 @@ export class AcpClient {
127
195
  clientInfo: { name: 'Causyne Agent', version: this.options.clientVersion ?? '0.0.0' }
128
196
  };
129
197
 
130
- const result = await this.request<InitializeResult>(ACP_METHODS.INITIALIZE, params, 30_000);
198
+ const result = await this.request<InitializeResult>(ACP_METHODS.INITIALIZE, params, 30_000, signal);
131
199
  this.initResult = result;
132
200
  return result;
133
201
  }
134
202
 
135
- async newSession(cwd: string, mcpServers: unknown[] = []): Promise<string> {
203
+ async newSession(cwd: string, mcpServers: unknown[] = [], signal?: AbortSignal): Promise<string> {
136
204
  const result = await this.request<{ sessionId?: unknown }>(ACP_METHODS.NEW_SESSION, {
137
205
  cwd,
138
206
  mcpServers
139
- }, 30_000);
207
+ }, 30_000, signal);
140
208
  if (!result || typeof result.sessionId !== 'string' || !result.sessionId) {
141
209
  throw new Error('agent did not return a session id');
142
210
  }
211
+ this.recordSessionModels(result.sessionId, result);
143
212
  return result.sessionId;
144
213
  }
145
214
 
@@ -150,11 +219,35 @@ export class AcpClient {
150
219
  }, 30_000);
151
220
  }
152
221
 
153
- async setSessionModel(sessionId: string, modelId: string): Promise<void> {
154
- await this.request<void>(ACP_METHODS.SET_MODEL, {
155
- sessionId,
156
- modelId
157
- }, 30_000);
222
+ async setSessionModel(sessionId: string, modelId: string, signal?: AbortSignal): Promise<void> {
223
+ const state = this.sessionModels.get(sessionId) ?? this.latestSessionModels;
224
+ try {
225
+ const res = await this.request<unknown>(ACP_METHODS.SET_MODEL, {
226
+ sessionId,
227
+ modelId
228
+ }, 5_000, signal);
229
+ this.recordSessionModels(sessionId, res);
230
+ const updated = this.sessionModels.get(sessionId);
231
+ if (updated) {
232
+ updated.currentModelId = modelId;
233
+ this.latestSessionModels = updated;
234
+ }
235
+ return;
236
+ } catch (err: unknown) {
237
+ if (signal?.aborted || (err instanceof Error && err.name === 'AbortError')) {
238
+ throw err;
239
+ }
240
+ if (state.usesConfigOption) {
241
+ const res = await this.request<unknown>(ACP_METHODS.SET_CONFIG_OPTION, {
242
+ sessionId,
243
+ configId: state.configOptionId || 'model',
244
+ value: modelId
245
+ }, 5_000, signal);
246
+ this.recordSessionModels(sessionId, res);
247
+ return;
248
+ }
249
+ throw err;
250
+ }
158
251
  }
159
252
 
160
253
  async setSessionMode(sessionId: string, modeId: string): Promise<void> {
@@ -165,36 +258,51 @@ export class AcpClient {
165
258
  }
166
259
 
167
260
  async loadSession(sessionId: string, cwd?: string): Promise<unknown> {
168
- return await this.request<unknown>(ACP_METHODS.LOAD, {
261
+ const res = await this.request<unknown>(ACP_METHODS.LOAD, {
169
262
  sessionId,
170
263
  cwd: cwd || this.options.cwd
171
264
  }, 30_000);
265
+ this.recordSessionModels(sessionId, res);
266
+ return res;
172
267
  }
173
268
 
174
- async prompt(sessionId: string, input: string | ContentBlock[]): Promise<AcpPromptResult> {
269
+ async prompt(sessionId: string, input: string | ContentBlock[], signal?: AbortSignal): Promise<AcpPromptResult> {
270
+ if (signal?.aborted) throw createAbortError();
175
271
  const blocks: ContentBlock[] = typeof input === 'string' ? [{ type: 'text', text: input }] : input;
176
272
  let collected = '';
177
273
  const collector = (update: SessionUpdate): void => {
178
- this.options.onUpdate?.(sessionId, update);
274
+ if (signal?.aborted) return;
275
+ // handleLine already notifies options.onUpdate for this session. Calling
276
+ // it again here duplicated every live chunk and file-action frame.
179
277
  if (update.sessionUpdate === 'agent_message_chunk' && update.content.type === 'text') {
180
278
  collected = `${collected}${update.content.text}`.slice(0, MAX_UPDATE_CHARS);
181
279
  }
182
280
  };
183
281
  const previous = this.updateListener;
184
282
  this.updateListener = (sessionIdFromEvent, update) => {
283
+ if (signal?.aborted) return;
185
284
  previous?.(sessionIdFromEvent, update);
186
285
  if (sessionIdFromEvent === sessionId) collector(update);
187
286
  };
287
+ const onAbort = (): void => {
288
+ try {
289
+ this.notifyCancel(sessionId);
290
+ } catch {
291
+ // ignore cancel write failure
292
+ }
293
+ };
294
+ signal?.addEventListener('abort', onAbort, { once: true });
188
295
  try {
189
296
  const response = await this.request<PromptResponse>(ACP_METHODS.PROMPT, {
190
297
  sessionId,
191
298
  prompt: blocks
192
- }, this.options.promptTimeoutMs ?? 15 * 60 * 1000);
299
+ }, this.options.promptTimeoutMs ?? 15 * 60 * 1000, signal);
193
300
  return {
194
301
  stopReason: response?.stopReason ?? 'end_turn',
195
302
  text: collected
196
303
  };
197
304
  } finally {
305
+ signal?.removeEventListener('abort', onAbort);
198
306
  this.updateListener = previous;
199
307
  }
200
308
  }
@@ -211,20 +319,37 @@ export class AcpClient {
211
319
  if (this.closed) return;
212
320
  this.closed = true;
213
321
  const child = this.child;
322
+ this.child = null;
214
323
  this.failAll(new Error('client closed'));
215
324
  if (!child) return;
325
+ if (child.exitCode !== null || child.signalCode !== null) return;
216
326
  await new Promise<void>((resolve) => {
217
- const timer = setTimeout(() => {
218
- child.kill('SIGKILL');
219
- resolve();
220
- }, 1500);
221
- child.once('exit', () => {
327
+ let settled = false;
328
+ const done = (): void => {
329
+ if (settled) return;
330
+ settled = true;
222
331
  clearTimeout(timer);
223
332
  resolve();
224
- });
225
- child.kill('SIGTERM');
333
+ };
334
+ const timer = setTimeout(() => {
335
+ try { child.kill('SIGKILL'); } catch { /* ignore */ }
336
+ done();
337
+ }, 250);
338
+ if (typeof timer.unref === 'function') timer.unref();
339
+ child.once('exit', done);
340
+ try {
341
+ child.stdin.destroy();
342
+ child.stdout.destroy();
343
+ child.stderr.destroy();
344
+ } catch {
345
+ // ignore stream destroy errors
346
+ }
347
+ try {
348
+ child.kill('SIGTERM');
349
+ } catch {
350
+ done();
351
+ }
226
352
  });
227
- this.child = null;
228
353
  }
229
354
 
230
355
  private updateListener: ((sessionId: string, update: SessionUpdate) => void) | null = null;
@@ -267,6 +392,7 @@ export class AcpClient {
267
392
  if (method === ACP_METHODS.UPDATE) {
268
393
  const params = (parsed as { params?: SessionNotification }).params;
269
394
  if (params && typeof params.sessionId === 'string' && params.update) {
395
+ this.recordSessionModels(params.sessionId, params.update);
270
396
  this.updateListener?.(params.sessionId, params.update);
271
397
  this.options.onUpdate?.(params.sessionId, params.update);
272
398
  }
@@ -381,6 +507,7 @@ export class AcpClient {
381
507
  const pending = this.pending.get(response.id);
382
508
  if (!pending) return;
383
509
  clearTimeout(pending.timer);
510
+ pending.cleanup?.();
384
511
  this.pending.delete(response.id);
385
512
  if (response.error) {
386
513
  const err = new Error(`${pending.method} failed: ${response.error.message}`);
@@ -392,20 +519,34 @@ export class AcpClient {
392
519
  pending.resolve(response.result);
393
520
  }
394
521
 
395
- private request<T>(method: string, params: unknown, timeoutMs: number): Promise<T> {
522
+ private request<T>(method: string, params: unknown, timeoutMs: number, signal?: AbortSignal): Promise<T> {
523
+ if (signal?.aborted) return Promise.reject(createAbortError());
396
524
  if (!this.child || this.closed) return Promise.reject(new Error('agent process is not running'));
397
525
  if (this.exitError) return Promise.reject(this.exitError);
398
526
  const id = this.nextId++;
399
527
  return new Promise<T>((resolve, reject) => {
528
+ const cleanup = (): void => {
529
+ signal?.removeEventListener('abort', onAbort);
530
+ };
531
+ const onAbort = (): void => {
532
+ clearTimeout(timer);
533
+ cleanup();
534
+ this.pending.delete(id);
535
+ reject(createAbortError());
536
+ };
400
537
  const timer = setTimeout(() => {
538
+ cleanup();
401
539
  this.pending.delete(id);
402
540
  reject(new Error(`${method} timed out after ${timeoutMs}ms`));
403
541
  }, timeoutMs);
542
+ if (typeof timer.unref === 'function') timer.unref();
543
+ signal?.addEventListener('abort', onAbort, { once: true });
404
544
  this.pending.set(id, {
405
545
  resolve: (value) => resolve(value as T),
406
546
  reject,
407
547
  timer,
408
- method
548
+ method,
549
+ cleanup
409
550
  });
410
551
  this.write({ jsonrpc: '2.0', id, method, params });
411
552
  });
@@ -415,6 +556,7 @@ export class AcpClient {
415
556
  this.exitError = error;
416
557
  for (const [id, pending] of this.pending) {
417
558
  clearTimeout(pending.timer);
559
+ pending.cleanup?.();
418
560
  pending.reject(error);
419
561
  this.pending.delete(id);
420
562
  }
@@ -18,6 +18,7 @@ export const ACP_METHODS = {
18
18
  CLOSE: 'session/close',
19
19
  SET_MODE: 'session/set_mode',
20
20
  SET_MODEL: 'session/set_model',
21
+ SET_CONFIG_OPTION: 'session/set_config_option',
21
22
  AUTHENTICATE: 'authenticate',
22
23
  REQUEST_PERMISSION: 'session/request_permission',
23
24
  READ_TEXT_FILE: 'fs/read_text_file',
@@ -55,3 +56,118 @@ export function isJsonRpcNotification(value) {
55
56
  const record = value;
56
57
  return record.jsonrpc === '2.0' && typeof record.method === 'string' && !('id' in record);
57
58
  }
59
+ /**
60
+ * Extract live available models and active model ID from any ACP session/new,
61
+ * session/load, session/set_config_option, or session/update payload.
62
+ */
63
+ export function extractAcpSessionModels(payload) {
64
+ const availableModels = [];
65
+ const modelLabels = {};
66
+ let currentModelId;
67
+ let usesConfigOption = false;
68
+ let configOptionId;
69
+ if (!payload || typeof payload !== 'object') {
70
+ return { availableModels, modelLabels, usesConfigOption };
71
+ }
72
+ const record = payload;
73
+ const registerModel = (rawId, rawLabel) => {
74
+ if (typeof rawId !== 'string')
75
+ return;
76
+ const id = rawId.trim();
77
+ if (!id)
78
+ return;
79
+ if (!availableModels.includes(id)) {
80
+ availableModels.push(id);
81
+ }
82
+ if (typeof rawLabel === 'string' && rawLabel.trim()) {
83
+ modelLabels[id] = rawLabel.trim();
84
+ }
85
+ };
86
+ // 1. Inspect ACP v1 configOptions (e.g. OpenCode, Claude Agent ACP, Codex ACP, Gemini ACP)
87
+ const configOptions = Array.isArray(record.configOptions) ? record.configOptions : [];
88
+ for (const rawOpt of configOptions) {
89
+ if (!rawOpt || typeof rawOpt !== 'object')
90
+ continue;
91
+ const opt = rawOpt;
92
+ const optId = typeof opt.id === 'string' ? opt.id.trim().toLowerCase() : '';
93
+ const optCategory = typeof opt.category === 'string' ? opt.category.trim().toLowerCase() : '';
94
+ if (optCategory !== 'model' && optId !== 'model' && optId !== 'models')
95
+ continue;
96
+ usesConfigOption = true;
97
+ configOptionId = typeof opt.id === 'string' && opt.id.trim() ? opt.id.trim() : 'model';
98
+ if (typeof opt.currentValue === 'string' && opt.currentValue.trim()) {
99
+ currentModelId = opt.currentValue.trim();
100
+ }
101
+ const options = Array.isArray(opt.options) ? opt.options : [];
102
+ for (const entry of options) {
103
+ if (!entry || typeof entry !== 'object')
104
+ continue;
105
+ const entryObj = entry;
106
+ if (Array.isArray(entryObj.options)) {
107
+ for (const sub of entryObj.options) {
108
+ if (sub && typeof sub === 'object') {
109
+ const subObj = sub;
110
+ registerModel(subObj.value ?? subObj.modelId ?? subObj.id, subObj.name ?? subObj.label);
111
+ }
112
+ }
113
+ }
114
+ else {
115
+ registerModel(entryObj.value ?? entryObj.modelId ?? entryObj.id, entryObj.name ?? entryObj.label);
116
+ }
117
+ }
118
+ }
119
+ // 2. Inspect ACP models state ({ currentModelId, availableModels })
120
+ const modelsField = record.models;
121
+ if (modelsField && typeof modelsField === 'object' && !Array.isArray(modelsField)) {
122
+ const modelsObj = modelsField;
123
+ if (!currentModelId && typeof modelsObj.currentModelId === 'string' && modelsObj.currentModelId.trim()) {
124
+ currentModelId = modelsObj.currentModelId.trim();
125
+ }
126
+ const list = Array.isArray(modelsObj.availableModels) ? modelsObj.availableModels : [];
127
+ for (const item of list) {
128
+ if (typeof item === 'string') {
129
+ registerModel(item);
130
+ }
131
+ else if (item && typeof item === 'object') {
132
+ const itemObj = item;
133
+ registerModel(itemObj.modelId ?? itemObj.id ?? itemObj.value, itemObj.name ?? itemObj.label);
134
+ }
135
+ }
136
+ }
137
+ else if (Array.isArray(modelsField)) {
138
+ for (const item of modelsField) {
139
+ if (typeof item === 'string') {
140
+ registerModel(item);
141
+ }
142
+ else if (item && typeof item === 'object') {
143
+ const itemObj = item;
144
+ registerModel(itemObj.modelId ?? itemObj.id ?? itemObj.value, itemObj.name ?? itemObj.label);
145
+ }
146
+ }
147
+ }
148
+ // 3. Inspect top-level availableModels / currentModelId if present
149
+ if (!currentModelId && typeof record.currentModelId === 'string' && record.currentModelId.trim()) {
150
+ currentModelId = record.currentModelId.trim();
151
+ }
152
+ if (Array.isArray(record.availableModels)) {
153
+ for (const item of record.availableModels) {
154
+ if (typeof item === 'string') {
155
+ registerModel(item);
156
+ }
157
+ else if (item && typeof item === 'object') {
158
+ const itemObj = item;
159
+ registerModel(itemObj.modelId ?? itemObj.id ?? itemObj.value, itemObj.name ?? itemObj.label);
160
+ }
161
+ }
162
+ }
163
+ if (currentModelId && !availableModels.includes(currentModelId)) {
164
+ availableModels.unshift(currentModelId);
165
+ }
166
+ return {
167
+ currentModelId,
168
+ availableModels,
169
+ modelLabels,
170
+ usesConfigOption,
171
+ configOptionId
172
+ };
173
+ }
@@ -20,6 +20,7 @@ export const ACP_METHODS = {
20
20
  CLOSE: 'session/close',
21
21
  SET_MODE: 'session/set_mode',
22
22
  SET_MODEL: 'session/set_model',
23
+ SET_CONFIG_OPTION: 'session/set_config_option',
23
24
  AUTHENTICATE: 'authenticate',
24
25
  REQUEST_PERMISSION: 'session/request_permission',
25
26
  READ_TEXT_FILE: 'fs/read_text_file',
@@ -187,6 +188,50 @@ export interface SessionModeState {
187
188
  availableModes: SessionMode[];
188
189
  }
189
190
 
191
+ export interface AcpModelInfo {
192
+ modelId?: string;
193
+ id?: string;
194
+ value?: string;
195
+ name?: string;
196
+ label?: string;
197
+ description?: string;
198
+ }
199
+
200
+ export interface SessionModelState {
201
+ currentModelId?: string;
202
+ availableModels?: Array<AcpModelInfo | string>;
203
+ }
204
+
205
+ export interface SessionConfigSelectOption {
206
+ value: string;
207
+ name?: string;
208
+ description?: string;
209
+ }
210
+
211
+ export interface SessionConfigSelectGroup {
212
+ group: string;
213
+ name?: string;
214
+ options: SessionConfigSelectOption[];
215
+ }
216
+
217
+ export interface SessionConfigOption {
218
+ id: string;
219
+ name?: string;
220
+ description?: string;
221
+ category?: string;
222
+ type?: string;
223
+ currentValue?: string;
224
+ options?: Array<SessionConfigSelectOption | SessionConfigSelectGroup>;
225
+ }
226
+
227
+ export interface AcpDiscoveredSessionModels {
228
+ currentModelId?: string | undefined;
229
+ availableModels: string[];
230
+ modelLabels: Record<string, string>;
231
+ usesConfigOption: boolean;
232
+ configOptionId?: string | undefined;
233
+ }
234
+
190
235
  export interface McpServer {
191
236
  name: string;
192
237
  command?: string;
@@ -205,6 +250,8 @@ export interface NewSessionRequest {
205
250
  export interface NewSessionResponse {
206
251
  sessionId: string;
207
252
  modes?: SessionModeState;
253
+ models?: SessionModelState;
254
+ configOptions?: SessionConfigOption[];
208
255
  }
209
256
 
210
257
  export interface PromptRequest {
@@ -473,3 +520,119 @@ export function isJsonRpcNotification(value: unknown): value is JsonRpcNotificat
473
520
  const record = value as Record<string, unknown>;
474
521
  return record.jsonrpc === '2.0' && typeof record.method === 'string' && !('id' in record);
475
522
  }
523
+
524
+ /**
525
+ * Extract live available models and active model ID from any ACP session/new,
526
+ * session/load, session/set_config_option, or session/update payload.
527
+ */
528
+ export function extractAcpSessionModels(payload: unknown): AcpDiscoveredSessionModels {
529
+ const availableModels: string[] = [];
530
+ const modelLabels: Record<string, string> = {};
531
+ let currentModelId: string | undefined;
532
+ let usesConfigOption = false;
533
+ let configOptionId: string | undefined;
534
+
535
+ if (!payload || typeof payload !== 'object') {
536
+ return { availableModels, modelLabels, usesConfigOption };
537
+ }
538
+
539
+ const record = payload as Record<string, unknown>;
540
+
541
+ const registerModel = (rawId: unknown, rawLabel?: unknown): void => {
542
+ if (typeof rawId !== 'string') return;
543
+ const id = rawId.trim();
544
+ if (!id) return;
545
+ if (!availableModels.includes(id)) {
546
+ availableModels.push(id);
547
+ }
548
+ if (typeof rawLabel === 'string' && rawLabel.trim()) {
549
+ modelLabels[id] = rawLabel.trim();
550
+ }
551
+ };
552
+
553
+ // 1. Inspect ACP v1 configOptions (e.g. OpenCode, Claude Agent ACP, Codex ACP, Gemini ACP)
554
+ const configOptions = Array.isArray(record.configOptions) ? record.configOptions : [];
555
+ for (const rawOpt of configOptions) {
556
+ if (!rawOpt || typeof rawOpt !== 'object') continue;
557
+ const opt = rawOpt as Record<string, unknown>;
558
+ const optId = typeof opt.id === 'string' ? opt.id.trim().toLowerCase() : '';
559
+ const optCategory = typeof opt.category === 'string' ? opt.category.trim().toLowerCase() : '';
560
+ if (optCategory !== 'model' && optId !== 'model' && optId !== 'models') continue;
561
+
562
+ usesConfigOption = true;
563
+ configOptionId = typeof opt.id === 'string' && opt.id.trim() ? opt.id.trim() : 'model';
564
+ if (typeof opt.currentValue === 'string' && opt.currentValue.trim()) {
565
+ currentModelId = opt.currentValue.trim();
566
+ }
567
+
568
+ const options = Array.isArray(opt.options) ? opt.options : [];
569
+ for (const entry of options) {
570
+ if (!entry || typeof entry !== 'object') continue;
571
+ const entryObj = entry as Record<string, unknown>;
572
+ if (Array.isArray(entryObj.options)) {
573
+ for (const sub of entryObj.options) {
574
+ if (sub && typeof sub === 'object') {
575
+ const subObj = sub as Record<string, unknown>;
576
+ registerModel(subObj.value ?? subObj.modelId ?? subObj.id, subObj.name ?? subObj.label);
577
+ }
578
+ }
579
+ } else {
580
+ registerModel(entryObj.value ?? entryObj.modelId ?? entryObj.id, entryObj.name ?? entryObj.label);
581
+ }
582
+ }
583
+ }
584
+
585
+ // 2. Inspect ACP models state ({ currentModelId, availableModels })
586
+ const modelsField = record.models;
587
+ if (modelsField && typeof modelsField === 'object' && !Array.isArray(modelsField)) {
588
+ const modelsObj = modelsField as Record<string, unknown>;
589
+ if (!currentModelId && typeof modelsObj.currentModelId === 'string' && modelsObj.currentModelId.trim()) {
590
+ currentModelId = modelsObj.currentModelId.trim();
591
+ }
592
+ const list = Array.isArray(modelsObj.availableModels) ? modelsObj.availableModels : [];
593
+ for (const item of list) {
594
+ if (typeof item === 'string') {
595
+ registerModel(item);
596
+ } else if (item && typeof item === 'object') {
597
+ const itemObj = item as Record<string, unknown>;
598
+ registerModel(itemObj.modelId ?? itemObj.id ?? itemObj.value, itemObj.name ?? itemObj.label);
599
+ }
600
+ }
601
+ } else if (Array.isArray(modelsField)) {
602
+ for (const item of modelsField) {
603
+ if (typeof item === 'string') {
604
+ registerModel(item);
605
+ } else if (item && typeof item === 'object') {
606
+ const itemObj = item as Record<string, unknown>;
607
+ registerModel(itemObj.modelId ?? itemObj.id ?? itemObj.value, itemObj.name ?? itemObj.label);
608
+ }
609
+ }
610
+ }
611
+
612
+ // 3. Inspect top-level availableModels / currentModelId if present
613
+ if (!currentModelId && typeof record.currentModelId === 'string' && record.currentModelId.trim()) {
614
+ currentModelId = record.currentModelId.trim();
615
+ }
616
+ if (Array.isArray(record.availableModels)) {
617
+ for (const item of record.availableModels) {
618
+ if (typeof item === 'string') {
619
+ registerModel(item);
620
+ } else if (item && typeof item === 'object') {
621
+ const itemObj = item as Record<string, unknown>;
622
+ registerModel(itemObj.modelId ?? itemObj.id ?? itemObj.value, itemObj.name ?? itemObj.label);
623
+ }
624
+ }
625
+ }
626
+
627
+ if (currentModelId && !availableModels.includes(currentModelId)) {
628
+ availableModels.unshift(currentModelId);
629
+ }
630
+
631
+ return {
632
+ currentModelId,
633
+ availableModels,
634
+ modelLabels,
635
+ usesConfigOption,
636
+ configOptionId
637
+ };
638
+ }
package/src/acp/server.js CHANGED
@@ -3,7 +3,7 @@ import fs from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { AgentLoop } from '../agentLoop.js';
5
5
  import { createApprovalScope } from '../approvalGrants.js';
6
- import { createSession, getSession, saveSessionMessages } from '../sessionJournal.js';
6
+ import { createSession, getSession, saveSessionMessages, forkSession } from '../sessionJournal.js';
7
7
  import { ACP_ERROR_CODES, ACP_METHODS, ACP_PROTOCOL_VERSION, isJsonRpcNotification, isJsonRpcRequest, isJsonRpcResponse } from './protocol.js';
8
8
  const MODE_TO_AUTONOMY = {
9
9
  autonomous: 'A',
@@ -670,11 +670,10 @@ export class AcpServer {
670
670
  }
671
671
  this.bindWorkspace(cwd);
672
672
  const title = `Fork of ${source?.title || sourceRecord?.title || 'Untitled'}`;
673
- const created = createSession(cwd, title, false);
674
- if (sourceRecord && sourceRecord.messages.length > 0) {
675
- saveSessionMessages(created.id, sourceRecord.messages);
676
- }
677
- const session = this.addSession(created.id, cwd, title, source?.modeId ?? MODES.currentModeId);
673
+ const forked = forkSession(params.sessionId, { title, makeActive: false, workspace: cwd });
674
+ if (!forked)
675
+ throw this.paramsError('Failed to fork session journal');
676
+ const session = this.addSession(forked.id, cwd, title, source?.modeId ?? MODES.currentModeId);
678
677
  return this.sessionResponse(session);
679
678
  }
680
679
  replayTranscript(session, messages) {