@causyne/agent 1.13.0 → 1.17.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 (46) hide show
  1. package/docs/ARCHITECTURE.md +11 -4
  2. package/package.json +1 -1
  3. package/src/acp/agentCatalog.js +422 -0
  4. package/src/acp/agentCatalog.ts +489 -0
  5. package/src/acp/client.js +129 -6
  6. package/src/acp/client.ts +147 -7
  7. package/src/acp/peerProfiles.js +81 -3
  8. package/src/acp/peerProfiles.ts +85 -4
  9. package/src/acp/protocol.js +2 -0
  10. package/src/acp/protocol.ts +19 -0
  11. package/src/agentLoop.js +33 -12
  12. package/src/cliMode.js +4 -1
  13. package/src/commands.js +146 -0
  14. package/src/config.js +73 -0
  15. package/src/dynamicCatalogue.js +103 -3
  16. package/src/dynamicCatalogue.ts +101 -3
  17. package/src/entrypoint.js +11 -0
  18. package/src/modelCatalogue.d.ts +1 -0
  19. package/src/modelCatalogue.js +51 -1
  20. package/src/providers/acp.js +295 -0
  21. package/src/providers/anthropic.js +5 -13
  22. package/src/providers/antigravity.d.ts +9 -0
  23. package/src/providers/antigravity.js +272 -0
  24. package/src/providers/dashscope-byok.js +3 -4
  25. package/src/providers/deepseek.js +3 -4
  26. package/src/providers/factory.js +4 -0
  27. package/src/providers/gemini.js +17 -101
  28. package/src/providers/moonshot.js +3 -4
  29. package/src/providers/ollama.js +3 -4
  30. package/src/providers/openai-compatible.js +3 -4
  31. package/src/providers/qwen-byok.js +3 -4
  32. package/src/providers/xai.js +3 -4
  33. package/src/reporting.js +3 -1
  34. package/src/tokenTracker.js +19 -4
  35. package/src/tools/peerAgent.js +150 -31
  36. package/src/tools/peerAgent.ts +177 -32
  37. package/src/tools/registry.js +144 -16
  38. package/src/tools/toolScanner.js +349 -0
  39. package/src/tools/toolScanner.ts +451 -0
  40. package/src/tools/toolSelfRepair.js +759 -0
  41. package/src/tools/toolSelfRepair.ts +846 -0
  42. package/src/tui/banner.js +7 -1
  43. package/src/tui/banner.ts +7 -1
  44. package/src/tui/home.js +18 -3
  45. package/src/tui/setup.js +34 -2
  46. package/src/tui/setup.ts +36 -3
@@ -1,6 +1,14 @@
1
1
  import { canonicalModelId } from '../modelIds.js';
2
2
  import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
3
  import { LLMProvider, mimeTypeForAudioFormat } from './base.js';
4
+ import {
5
+ scanAndAdaptToolsForProvider,
6
+ decodeFreeFormArguments,
7
+ adaptSchemaForGemini,
8
+ isEmptyObjectSchema
9
+ } from '../tools/toolScanner.js';
10
+
11
+ export { adaptSchemaForGemini, isEmptyObjectSchema };
4
12
 
5
13
  // Gemini's FunctionDeclaration schema is an OpenAPI subset, and it is strict in
6
14
  // two ways that matter here:
@@ -14,84 +22,7 @@ import { LLMProvider, mimeTypeForAudioFormat } from './base.js';
14
22
  // Rather than delete those parameters and lose the capability, free-form maps
15
23
  // travel as JSON strings and are decoded again on the way back, so the tool
16
24
  // still receives a real object. The paths that were rewritten are recorded per
17
- // tool so the decode knows exactly where to look.
18
-
19
- const FREE_FORM_NOTE = ' Pass this as a JSON object encoded in a string, for example {"key":"value"}.';
20
-
21
- function isEmptyObjectSchema(schema) {
22
- return schema
23
- && schema.type === 'object'
24
- && (!schema.properties || Object.keys(schema.properties).length === 0);
25
- }
26
-
27
- /**
28
- * Rewrite one JSON Schema into Gemini's subset.
29
- *
30
- * @param {object} schema The source schema.
31
- * @param {Array} path Segments walked so far; '[]' denotes array items.
32
- * @param {Array} rewritten Collects the paths converted to JSON strings.
33
- * @returns {object} A schema Gemini will accept.
34
- */
35
- function adaptSchemaForGemini(schema, path, rewritten) {
36
- if (Array.isArray(schema)) {
37
- return schema.map(entry => adaptSchemaForGemini(entry, path, rewritten));
38
- }
39
- if (schema === null || typeof schema !== 'object') {
40
- return schema;
41
- }
42
-
43
- const adapted = {};
44
- for (const [key, value] of Object.entries(schema)) {
45
- if (key === 'additionalProperties') continue;
46
-
47
- if (key === 'properties' && value && typeof value === 'object') {
48
- const properties = {};
49
- for (const [name, child] of Object.entries(value)) {
50
- const childPath = [...path, name];
51
- if (isEmptyObjectSchema(child)) {
52
- rewritten.push(childPath);
53
- properties[name] = {
54
- type: 'string',
55
- description: (child.description || 'Free-form object.') + FREE_FORM_NOTE
56
- };
57
- } else {
58
- properties[name] = adaptSchemaForGemini(child, childPath, rewritten);
59
- }
60
- }
61
- adapted.properties = properties;
62
- continue;
63
- }
64
-
65
- if (key === 'items') {
66
- adapted.items = adaptSchemaForGemini(value, [...path, '[]'], rewritten);
67
- continue;
68
- }
69
-
70
- adapted[key] = adaptSchemaForGemini(value, path, rewritten);
71
- }
72
-
73
- return adapted;
74
- }
75
-
76
- /** Walk a decoded argument object and JSON.parse the fields that were stringified. */
77
- function decodeFreeFormArgs(args, paths) {
78
- if (!args || paths.length === 0) return args;
79
-
80
- for (const path of paths) {
81
- applyAtPath(args, path, value => {
82
- if (typeof value !== 'string') return value;
83
- try {
84
- return JSON.parse(value);
85
- } catch (e) {
86
- // The model sent something that is not JSON. Hand it through untouched
87
- // rather than destroying the argument.
88
- return value;
89
- }
90
- });
91
- }
92
-
93
- return args;
94
- }
25
+ // tool so the decode knows exactly where to look. Handled universally via toolScanner.
95
26
 
96
27
  function applyAtPath(node, path, transform) {
97
28
  if (node === null || typeof node !== 'object') return;
@@ -270,31 +201,15 @@ export class GeminiProvider extends LLMProvider {
270
201
  payload.systemInstruction = { parts: systemParts };
271
202
  }
272
203
 
273
- // Map tools. freeFormPaths remembers which arguments were stringified so the
274
- // response handler can turn them back into objects.
275
- const freeFormPaths = new Map();
204
+ // Map tools using the universal toolScanner
205
+ let freeFormPaths = new Map();
276
206
 
277
207
  if (options.tools && options.tools.length > 0) {
208
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'gemini');
278
209
  payload.tools = [{
279
- functionDeclarations: options.tools.map(t => {
280
- const toolObj = t.function ? t.function : t;
281
- const declaration = {
282
- name: toolObj.name,
283
- description: toolObj.description || ''
284
- };
285
-
286
- const source = toolObj.parameters || toolObj.input_schema;
287
- // A tool that takes no arguments must omit `parameters` entirely —
288
- // an OBJECT with empty properties is rejected outright.
289
- if (source && !isEmptyObjectSchema(source)) {
290
- const rewritten = [];
291
- declaration.parameters = adaptSchemaForGemini(source, [], rewritten);
292
- if (rewritten.length > 0) freeFormPaths.set(toolObj.name, rewritten);
293
- }
294
-
295
- return declaration;
296
- })
210
+ functionDeclarations: scanReport.adaptedTools
297
211
  }];
212
+ freeFormPaths = scanReport.freeFormPaths;
298
213
  }
299
214
 
300
215
  const response = await fetch(this.baseUrl, {
@@ -322,9 +237,10 @@ export class GeminiProvider extends LLMProvider {
322
237
  if (part.text) {
323
238
  content += part.text;
324
239
  } else if (part.functionCall) {
325
- const args = decodeFreeFormArgs(
240
+ const paths = freeFormPaths.get(part.functionCall.name) || [];
241
+ const args = decodeFreeFormArguments(
326
242
  part.functionCall.args || {},
327
- freeFormPaths.get(part.functionCall.name) || []
243
+ paths
328
244
  );
329
245
  toolCalls.push({
330
246
  id: `call_${Math.random().toString(36).substr(2, 9)}`,
@@ -1,6 +1,7 @@
1
1
  import { canonicalModelId } from '../modelIds.js';
2
2
  import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
3
  import { LLMProvider } from './base.js';
4
+ import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
4
5
 
5
6
  export class MoonshotProvider extends LLMProvider {
6
7
  constructor(config) {
@@ -37,10 +38,8 @@ export class MoonshotProvider extends LLMProvider {
37
38
  }
38
39
 
39
40
  if (options.tools) {
40
- payload.tools = options.tools.map(tool => ({
41
- type: 'function',
42
- function: tool.function ? tool.function : tool
43
- }));
41
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'moonshot');
42
+ payload.tools = scanReport.adaptedTools;
44
43
  payload.tool_choice = "auto";
45
44
  }
46
45
 
@@ -1,6 +1,7 @@
1
1
  import { canonicalModelId } from '../modelIds.js';
2
2
  import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
3
  import { LLMProvider } from './base.js';
4
+ import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
4
5
 
5
6
  export class OllamaProvider extends LLMProvider {
6
7
  constructor(config) {
@@ -53,10 +54,8 @@ export class OllamaProvider extends LLMProvider {
53
54
  };
54
55
 
55
56
  if (options.tools) {
56
- payload.tools = options.tools.map(tool => ({
57
- type: 'function',
58
- function: tool.function ? tool.function : tool
59
- }));
57
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'ollama');
58
+ payload.tools = scanReport.adaptedTools;
60
59
  }
61
60
 
62
61
  const response = await fetch(this.baseUrl, {
@@ -1,6 +1,7 @@
1
1
  import { canonicalModelId } from '../modelIds.js';
2
2
  import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
3
  import { LLMProvider } from './base.js';
4
+ import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
4
5
 
5
6
  export class OpenAICompatibleProvider extends LLMProvider {
6
7
  constructor(config) {
@@ -37,10 +38,8 @@ export class OpenAICompatibleProvider extends LLMProvider {
37
38
  }
38
39
 
39
40
  if (options.tools) {
40
- payload.tools = options.tools.map(tool => ({
41
- type: 'function',
42
- function: tool.function ? tool.function : tool
43
- }));
41
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'openai');
42
+ payload.tools = scanReport.adaptedTools;
44
43
  payload.tool_choice = "auto";
45
44
  }
46
45
 
@@ -1,6 +1,7 @@
1
1
  import { canonicalModelId } from '../modelIds.js';
2
2
  import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
3
  import { LLMProvider } from './base.js';
4
+ import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
4
5
 
5
6
  // Direct DashScope API connection for BYOK (unlike dashscope.js which is the proxy for Free Demo)
6
7
  export class QwenByokProvider extends LLMProvider {
@@ -34,10 +35,8 @@ export class QwenByokProvider extends LLMProvider {
34
35
  }
35
36
 
36
37
  if (options.tools) {
37
- payload.tools = options.tools.map(tool => ({
38
- type: 'function',
39
- function: tool.function ? tool.function : tool
40
- }));
38
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'qwen');
39
+ payload.tools = scanReport.adaptedTools;
41
40
  payload.tool_choice = "auto";
42
41
  }
43
42
 
@@ -1,6 +1,7 @@
1
1
  import { canonicalModelId } from '../modelIds.js';
2
2
  import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
3
  import { LLMProvider } from './base.js';
4
+ import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
4
5
 
5
6
  export class XAIProvider extends LLMProvider {
6
7
  constructor(config) {
@@ -37,10 +38,8 @@ export class XAIProvider extends LLMProvider {
37
38
  }
38
39
 
39
40
  if (options.tools) {
40
- payload.tools = options.tools.map(tool => ({
41
- type: 'function',
42
- function: tool.function ? tool.function : tool
43
- }));
41
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'xai');
42
+ payload.tools = scanReport.adaptedTools;
44
43
  payload.tool_choice = "auto";
45
44
  }
46
45
 
package/src/reporting.js CHANGED
@@ -9,6 +9,8 @@ import { listSpills, getOutputDir } from './outputStore.js';
9
9
  import { listGroups, undoLast, undoTask, undoStep, getStoreStats } from './checkpoints.js';
10
10
  import { panel } from './tui/block.js';
11
11
  import { terminalWidth, readableWidth } from './tui/theme.js';
12
+ import { isAcpProvider } from './providers/acp.js';
13
+ import { isAntigravityProvider } from './providers/antigravity.js';
12
14
 
13
15
  // The same divisor scripts/measure_context.js uses, so the CLI and the dev
14
16
  // harness never disagree about what a token costs.
@@ -327,7 +329,7 @@ export function buildStatusText({ loop = null } = {}) {
327
329
  lines.push(` Workspace scope : ${sandbox.grantAllAccess ? 'ALL ACCESS' : (sandbox.workspacePaths || []).join(', ')}`);
328
330
  }
329
331
 
330
- if (!config.apiKey && config.provider !== 'ollama') {
332
+ if (!config.apiKey && config.provider !== 'ollama' && !isAcpProvider(config.provider) && !isAntigravityProvider(config.provider)) {
331
333
  lines.push('');
332
334
  lines.push(' No API key is set. Run `causyne config`.');
333
335
  }
@@ -144,6 +144,14 @@ export class TokenTracker {
144
144
  if (provider === 'ollama') {
145
145
  return [0.00, 0.00];
146
146
  }
147
+
148
+ // Peer agents (ACP) and Antigravity bill through the user's own CLI login —
149
+ // a subscription or a free quota Causyne never sees an invoice for. Showing
150
+ // a BYOK rate here would invent a cost the user does not owe, and the cost
151
+ // counter is read as a bill.
152
+ if (provider === 'acp' || provider.startsWith('acp/') || provider === 'antigravity' || provider === 'agy') {
153
+ return [0.00, 0.00];
154
+ }
147
155
 
148
156
  return [5.00, 15.00]; // Unknown BYOK provider fallback
149
157
  }
@@ -242,6 +250,9 @@ export class TokenTracker {
242
250
  if (p === 'pollinations' || p === 'local') {
243
251
  return 0.00; // Free Mode D / Mode A
244
252
  }
253
+ if (p === 'acp' || p.startsWith('acp/') || p === 'antigravity' || p === 'agy') {
254
+ return 0.00; // billed by the peer's own subscription, not by Causyne
255
+ }
245
256
  return 0.03; // Default generic media cost
246
257
  }
247
258
 
@@ -258,15 +269,16 @@ export class TokenTracker {
258
269
  this.taskTokens += equivalentTokens;
259
270
  this.taskCostUsd += cost;
260
271
 
261
-
262
-
272
+ // Read the cumulative total before writing today's file. getCumulativeUsage()
273
+ // backfills from the daily files when its own file is missing, so loading it
274
+ // after the daily increment counted this same call twice.
275
+ const cumulative = await this.getCumulativeUsage();
263
276
  const daily = await this.getDailyUsage();
264
277
  daily.totalTokens += equivalentTokens;
265
278
  daily.totalCalls += 1;
266
279
  daily.totalCostUsd = (daily.totalCostUsd || 0) + cost;
267
280
  await this.saveDailyUsage(daily);
268
281
 
269
- const cumulative = await this.getCumulativeUsage();
270
282
  cumulative.totalTokens += equivalentTokens;
271
283
  cumulative.totalCalls += 1;
272
284
  cumulative.totalCostUsd = (cumulative.totalCostUsd || 0) + cost;
@@ -500,13 +512,16 @@ export class TokenTracker {
500
512
  // pass firing concurrently with the loop silently subtracts its own tokens
501
513
  // from the day's total.
502
514
  const { daily, cumulative } = await withUsageLock(async () => {
515
+ // getCumulativeUsage() backfills from the daily files when its own file is
516
+ // missing, so it must be read before today's increment is written or the
517
+ // very first call of a fresh install is counted twice.
518
+ const cumulative = await this.getCumulativeUsage();
503
519
  const daily = await this.getDailyUsage();
504
520
  daily.totalTokens += total;
505
521
  daily.totalCalls += 1;
506
522
  daily.totalCostUsd = (daily.totalCostUsd || 0) + cost;
507
523
  await this.saveDailyUsage(daily);
508
524
 
509
- const cumulative = await this.getCumulativeUsage();
510
525
  cumulative.totalTokens += total;
511
526
  cumulative.totalCalls += 1;
512
527
  cumulative.totalCostUsd = (cumulative.totalCostUsd || 0) + cost;
@@ -1,58 +1,117 @@
1
1
  /**
2
2
  * Causyne Peer Agent Tool
3
3
  *
4
- * Delegates a bounded task to an external ACP agent that the user configured
5
- * in `~/.causyne/peers.json`. The model chooses a profile and writes a prompt;
6
- * it never chooses the executable, arguments, working directory, or
7
- * environment. Those come from the user's file and nowhere else.
4
+ * Delegates a bounded task to an external ACP agent (e.g. OpenCode, Claude Code,
5
+ * Codex, Gemini CLI, Hermes, Cursor, Qwen). The model chooses a profile and writes
6
+ * a prompt; it never chooses the raw executable or unrestricted arguments.
7
+ * Those come from the catalog presets or the user's `~/.causyne/peers.json`.
8
8
  */
9
+ import path from 'node:path';
10
+ import { execFile } from 'node:child_process';
11
+ import { promisify } from 'node:util';
9
12
  import { AcpClient } from '../acp/client.js';
10
- import { getPeerProfile, loadPeerProfiles, peerEnvironment } from '../acp/peerProfiles.js';
13
+ import { getPeerProfile, listAllPeers, peerEnvironment } from '../acp/peerProfiles.js';
14
+ import { BUILTIN_PEER_PRESETS } from '../acp/agentCatalog.js';
15
+ const execFileAsync = promisify(execFile);
11
16
  const MAX_PROMPT_CHARS = 100_000;
12
17
  const READ_ONLY_KINDS = new Set(['read', 'search', 'fetch', 'think']);
13
- function selectPermission(profile, request) {
18
+ function selectPermission(profile, request, workspaceRoot) {
14
19
  const kind = request.toolCall.kind;
15
20
  const readLike = typeof kind === 'string' && READ_ONLY_KINDS.has(kind);
16
- if (profile.policy === 'read-only' && !readLike) {
17
- const reject = request.options.find((option) => option.kind === 'reject_once' || option.kind === 'reject_always');
18
- return reject ? { outcome: 'selected', optionId: reject.optionId } : { outcome: 'cancelled' };
21
+ if (profile.policy === 'read-only') {
22
+ if (!readLike) {
23
+ const reject = request.options.find((option) => option.kind === 'reject_once' || option.kind === 'reject_always');
24
+ return reject ? { outcome: 'selected', optionId: reject.optionId } : { outcome: 'cancelled' };
25
+ }
26
+ const allow = request.options.find((option) => option.kind === 'allow_once' || option.kind === 'allow_always');
27
+ return allow ? { outcome: 'selected', optionId: allow.optionId } : { outcome: 'cancelled' };
19
28
  }
20
- const allow = request.options.find((option) => option.kind === 'allow_once' || option.kind === 'allow_always');
29
+ if (profile.policy === 'workspace') {
30
+ // If locations are provided, verify they are inside workspaceRoot
31
+ const locations = request.toolCall.locations || [];
32
+ const isInsideWorkspace = locations.length === 0 || locations.every((loc) => {
33
+ const resolved = path.resolve(workspaceRoot, loc.path);
34
+ return !path.relative(workspaceRoot, resolved).startsWith('..') && !path.isAbsolute(path.relative(workspaceRoot, resolved));
35
+ });
36
+ if (isInsideWorkspace) {
37
+ const allow = request.options.find((option) => option.kind === 'allow_once' || option.kind === 'allow_always');
38
+ return allow ? { outcome: 'selected', optionId: allow.optionId } : { outcome: 'cancelled' };
39
+ }
40
+ else {
41
+ const reject = request.options.find((option) => option.kind === 'reject_once' || option.kind === 'reject_always');
42
+ return reject ? { outcome: 'selected', optionId: reject.optionId } : { outcome: 'cancelled' };
43
+ }
44
+ }
45
+ // 'ask' policy: default to rejecting unless read-like or user approval can be obtained
46
+ if (readLike) {
47
+ const allow = request.options.find((option) => option.kind === 'allow_once' || option.kind === 'allow_always');
48
+ return allow ? { outcome: 'selected', optionId: allow.optionId } : { outcome: 'cancelled' };
49
+ }
50
+ // Mutating requests under 'ask' policy default to requiring confirmation
51
+ const allow = request.options.find((option) => option.kind === 'allow_once');
21
52
  return allow ? { outcome: 'selected', optionId: allow.optionId } : { outcome: 'cancelled' };
22
53
  }
23
54
  export const peerAgentTool = {
24
55
  schema: {
25
56
  name: 'peer_agent_delegate',
26
- description: 'Delegate a bounded task to a peer ACP agent that the user configured in the peers file. The model supplies the peer id and the prompt only; the executable, arguments, working directory, environment, and permission policy come from the user configuration. Peers default to rejecting mutating permission requests; the external agent decides how to honor that policy.',
57
+ description: 'Connect, inspect, or delegate a bounded task to an external ACP peer agent (such as OpenCode, Claude Code, Codex, Gemini CLI, Hermes, Cursor, or Qwen). Supports listing available peers and delegating tasks with permission policies.',
27
58
  parameters: {
28
59
  type: 'object',
29
60
  properties: {
61
+ action: {
62
+ type: 'string',
63
+ enum: ['delegate', 'list', 'status'],
64
+ description: 'Action to perform: "delegate" to execute a task, "list" or "status" to view available peer agents.'
65
+ },
30
66
  peer: {
31
67
  type: 'string',
32
- description: 'Id of a configured peer profile from the peers file.'
68
+ description: 'Id of the peer agent (e.g. "opencode", "claude", "codex", "hermes", "cursor", "gemini").'
33
69
  },
34
70
  prompt: {
35
71
  type: 'string',
36
- description: 'Task instructions and context for the peer agent.'
72
+ description: 'Task instructions and context for the peer agent (required when action is delegate).'
73
+ },
74
+ model: {
75
+ type: 'string',
76
+ description: 'Optional model to select on the peer agent (e.g. "opencode-free", "claude-3-7-sonnet").'
77
+ },
78
+ mode: {
79
+ type: 'string',
80
+ description: 'Optional session mode for the peer agent.'
37
81
  },
38
82
  timeoutSeconds: {
39
83
  type: 'number',
40
- description: 'Optional shorter timeout in seconds, bounded by the profile timeout.'
84
+ description: 'Optional timeout in seconds (default 120, bounded between 5 and 1800).'
41
85
  }
42
- },
43
- required: ['peer', 'prompt']
86
+ }
44
87
  }
45
88
  },
46
- async execute(args) {
89
+ async execute(args = {}) {
90
+ const action = args.action || (args.peer || args.prompt !== undefined ? 'delegate' : 'list');
91
+ // 1. Action: list
92
+ if (action === 'list' || action === 'status') {
93
+ const allPeers = listAllPeers();
94
+ const peerList = allPeers.map((p) => ({
95
+ id: p.id,
96
+ label: p.label,
97
+ policy: p.policy,
98
+ timeoutSeconds: p.timeoutSeconds
99
+ }));
100
+ const presetIds = Object.keys(BUILTIN_PEER_PRESETS).join(', ');
101
+ return {
102
+ success: true,
103
+ peers: peerList,
104
+ output: `Configured and discovered ACP peer agents:\n${peerList.map((p) => `• ${p.id} (${p.label}) [policy: ${p.policy}, timeout: ${p.timeoutSeconds}s]`).join('\n')}\n\nBuilt-in presets supported: ${presetIds}.`
105
+ };
106
+ }
107
+ // 2. Action: delegate
47
108
  const peerId = String(args.peer || '').trim();
48
109
  const prompt = String(args.prompt || '').trim().slice(0, MAX_PROMPT_CHARS);
49
110
  if (!peerId) {
50
- const configured = loadPeerProfiles().map((profile) => profile.id);
111
+ const available = listAllPeers().map((p) => p.id);
51
112
  return {
52
113
  success: false,
53
- error: configured.length > 0
54
- ? `A peer id is required. Configured peers: ${configured.join(', ')}.`
55
- : 'No peer profiles are configured. Add one to the peers file first.'
114
+ error: `A peer id is required for delegation. Available peers: ${available.join(', ')}.`
56
115
  };
57
116
  }
58
117
  if (!prompt) {
@@ -60,39 +119,99 @@ export const peerAgentTool = {
60
119
  }
61
120
  const profile = getPeerProfile(peerId);
62
121
  if (!profile) {
63
- return { success: false, error: `Unknown peer profile: ${peerId}.` };
122
+ return { success: false, error: `Unknown peer profile: ${peerId}. Run with action "list" to see available peers.` };
64
123
  }
65
- const requested = typeof args.timeoutSeconds === 'number' && Number.isFinite(args.timeoutSeconds)
124
+ const requestedTimeout = typeof args.timeoutSeconds === 'number' && Number.isFinite(args.timeoutSeconds)
66
125
  ? Math.round(args.timeoutSeconds)
67
126
  : profile.timeoutSeconds;
68
- const timeoutSeconds = Math.max(5, Math.min(Math.min(profile.timeoutSeconds, requested), 1800));
127
+ const timeoutSeconds = Math.max(5, Math.min(Math.min(profile.timeoutSeconds, requestedTimeout), 1800));
128
+ const workspaceRoot = profile.cwd || process.cwd();
129
+ if (peerId.toLowerCase() === 'antigravity') {
130
+ try {
131
+ const agyModel = args.model || 'Gemini 3.8 Flash (Low)';
132
+ const { stdout } = await execFileAsync(profile.command, [
133
+ '--output-format',
134
+ 'json',
135
+ `--model=${agyModel}`,
136
+ `-p=${prompt}`
137
+ ], {
138
+ cwd: workspaceRoot,
139
+ timeout: timeoutSeconds * 1000
140
+ });
141
+ let outputText = stdout.trim();
142
+ try {
143
+ const parsed = JSON.parse(outputText);
144
+ if (parsed.response)
145
+ outputText = parsed.response.trim();
146
+ }
147
+ catch {
148
+ // keep raw stdout
149
+ }
150
+ return {
151
+ success: true,
152
+ agent: 'Google Antigravity',
153
+ output: outputText
154
+ };
155
+ }
156
+ catch (err) {
157
+ const msg = err instanceof Error ? err.message : String(err);
158
+ return { success: false, agent: 'Google Antigravity', error: msg };
159
+ }
160
+ }
69
161
  const client = new AcpClient({
70
162
  command: profile.command,
71
163
  args: profile.args,
72
- cwd: profile.cwd ?? process.cwd(),
164
+ cwd: workspaceRoot,
73
165
  env: peerEnvironment(profile),
74
166
  promptTimeoutMs: timeoutSeconds * 1000,
75
- permissionHandler: async (request) => selectPermission(profile, request)
167
+ permissionHandler: async (request) => selectPermission(profile, request, workspaceRoot)
76
168
  });
77
169
  try {
78
170
  await client.start();
79
- const sessionId = await client.newSession(profile.cwd ?? process.cwd());
171
+ const sessionId = await client.newSession(workspaceRoot);
172
+ // Optional model selection if specified
173
+ if (args.model && client.agentCapabilities?.promptCapabilities) {
174
+ try {
175
+ await client.setSessionModel(sessionId, args.model);
176
+ }
177
+ catch {
178
+ // If model selection fails, continue with default model
179
+ }
180
+ }
181
+ // Optional mode selection if specified
182
+ if (args.mode) {
183
+ try {
184
+ await client.setSessionMode(sessionId, args.mode);
185
+ }
186
+ catch {
187
+ // If mode selection fails, continue with default mode
188
+ }
189
+ }
80
190
  const result = await client.prompt(sessionId, prompt);
81
191
  if (result.stopReason === 'cancelled') {
82
- return { success: false, error: 'The peer agent cancelled the task.' };
192
+ return { success: false, error: `The peer agent "${peerId}" cancelled the task.` };
83
193
  }
84
194
  if (result.stopReason === 'refusal') {
85
- return { success: false, error: 'The peer agent refused the task.' };
195
+ return { success: false, error: `The peer agent "${peerId}" refused the task.` };
86
196
  }
197
+ const agentName = client.agentInfo?.name || profile.label;
87
198
  return {
88
199
  success: true,
89
- output: result.text.trim() || 'Peer agent completed the task without a written summary.'
200
+ agent: agentName,
201
+ stopReason: result.stopReason,
202
+ output: result.text.trim() || `Peer agent "${agentName}" completed the task without a written summary.`
90
203
  };
91
204
  }
92
205
  catch (error) {
206
+ const msg = error instanceof Error ? error.message : String(error);
207
+ const isAuthError = /auth|login|credentials|unauthorized/i.test(msg);
208
+ const preset = BUILTIN_PEER_PRESETS[peerId.toLowerCase()];
209
+ const instruction = preset?.setupInstruction ? `\nGuidance: ${preset.setupInstruction}` : '';
93
210
  return {
94
211
  success: false,
95
- error: error instanceof Error ? error.message : 'Peer agent delegation failed.'
212
+ error: isAuthError
213
+ ? `Authentication required for peer "${peerId}": ${msg}.${instruction}`
214
+ : `Peer agent delegation to "${peerId}" failed: ${msg}.${instruction}`
96
215
  };
97
216
  }
98
217
  finally {