@causyne/agent 1.12.0 → 1.14.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 (45) hide show
  1. package/docs/THIRD_PARTY_NOTICES.md +1 -1
  2. package/package.json +2 -2
  3. package/src/acp/agentCatalog.js +389 -0
  4. package/src/acp/agentCatalog.ts +455 -0
  5. package/src/acp/client.js +127 -4
  6. package/src/acp/client.ts +145 -5
  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/commands.js +108 -0
  13. package/src/engines/deck.js +105 -0
  14. package/src/engines/deck.ts +109 -0
  15. package/src/engines/design.js +123 -0
  16. package/src/engines/design.ts +141 -0
  17. package/src/engines/effect.js +128 -0
  18. package/src/engines/effect.ts +142 -0
  19. package/src/engines/grid.js +106 -0
  20. package/src/engines/grid.ts +121 -0
  21. package/src/engines/light.js +107 -0
  22. package/src/engines/light.ts +122 -0
  23. package/src/engines/pdf.js +108 -0
  24. package/src/engines/pdf.ts +124 -0
  25. package/src/engines/registry.js +15 -1
  26. package/src/engines/registry.ts +15 -1
  27. package/src/engines/word.js +112 -0
  28. package/src/engines/word.ts +127 -0
  29. package/src/entrypoint.js +11 -0
  30. package/src/providers/anthropic.js +5 -13
  31. package/src/providers/dashscope-byok.js +3 -4
  32. package/src/providers/deepseek.js +3 -4
  33. package/src/providers/gemini.js +17 -101
  34. package/src/providers/moonshot.js +3 -4
  35. package/src/providers/ollama.js +3 -4
  36. package/src/providers/openai-compatible.js +3 -4
  37. package/src/providers/qwen-byok.js +3 -4
  38. package/src/providers/xai.js +3 -4
  39. package/src/tools/peerAgent.js +115 -31
  40. package/src/tools/peerAgent.ts +143 -32
  41. package/src/tools/registry.js +144 -16
  42. package/src/tools/toolScanner.js +349 -0
  43. package/src/tools/toolScanner.ts +451 -0
  44. package/src/tools/toolSelfRepair.js +759 -0
  45. package/src/tools/toolSelfRepair.ts +846 -0
@@ -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
  // Models that support server-side tool search (defer_loading + tool_reference
6
7
  // expansion). On these, Causyne hands Anthropic the complete 69-tool catalogue
@@ -306,20 +307,11 @@ export class AnthropicProvider extends LLMProvider {
306
307
  const useToolSearch = this.supportsToolSearch();
307
308
  const coreToolCount = Number.isInteger(options.coreToolCount) ? options.coreToolCount : options.tools.length;
308
309
 
309
- const converted = options.tools.map((t, index) => {
310
- const toolObj = t.function ? t.function : t;
311
- const tool = {
312
- name: toolObj.name,
313
- description: toolObj.description || '',
314
- input_schema: toolObj.parameters || toolObj.input_schema || { type: 'object', properties: {} }
315
- };
316
- // Beyond the core toolset, let the API hold schemas server-side and
317
- // surface them only when Claude searches for them.
318
- if (useToolSearch && index >= coreToolCount) {
319
- tool.defer_loading = true;
320
- }
321
- return tool;
310
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'anthropic', {
311
+ useToolSearch,
312
+ coreToolCount
322
313
  });
314
+ const converted = scanReport.adaptedTools;
323
315
 
324
316
  if (useToolSearch) {
325
317
  payload.tools = [
@@ -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 DashscopeByokProvider extends LLMProvider {
@@ -44,10 +45,8 @@ export class DashscopeByokProvider extends LLMProvider {
44
45
  }
45
46
 
46
47
  if (options.tools) {
47
- payload.tools = options.tools.map(tool => ({
48
- type: 'function',
49
- function: tool.function ? tool.function : tool
50
- }));
48
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'dashscope');
49
+ payload.tools = scanReport.adaptedTools;
51
50
  payload.tool_choice = "auto";
52
51
  }
53
52
 
@@ -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 DeepSeekProvider extends LLMProvider {
6
7
  constructor(config) {
@@ -38,10 +39,8 @@ export class DeepSeekProvider extends LLMProvider {
38
39
  }
39
40
 
40
41
  if (options.tools) {
41
- payload.tools = options.tools.map(tool => ({
42
- type: 'function',
43
- function: tool.function ? tool.function : tool
44
- }));
42
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'deepseek');
43
+ payload.tools = scanReport.adaptedTools;
45
44
  payload.tool_choice = "auto";
46
45
  }
47
46
 
@@ -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
 
@@ -1,58 +1,114 @@
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';
9
10
  import { AcpClient } from '../acp/client.js';
10
- import { getPeerProfile, loadPeerProfiles, peerEnvironment } from '../acp/peerProfiles.js';
11
+ import { getPeerProfile, listAllPeers, peerEnvironment } from '../acp/peerProfiles.js';
12
+ import { BUILTIN_PEER_PRESETS } from '../acp/agentCatalog.js';
11
13
  const MAX_PROMPT_CHARS = 100_000;
12
14
  const READ_ONLY_KINDS = new Set(['read', 'search', 'fetch', 'think']);
13
- function selectPermission(profile, request) {
15
+ function selectPermission(profile, request, workspaceRoot) {
14
16
  const kind = request.toolCall.kind;
15
17
  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' };
18
+ if (profile.policy === 'read-only') {
19
+ if (!readLike) {
20
+ const reject = request.options.find((option) => option.kind === 'reject_once' || option.kind === 'reject_always');
21
+ return reject ? { outcome: 'selected', optionId: reject.optionId } : { outcome: 'cancelled' };
22
+ }
23
+ const allow = request.options.find((option) => option.kind === 'allow_once' || option.kind === 'allow_always');
24
+ return allow ? { outcome: 'selected', optionId: allow.optionId } : { outcome: 'cancelled' };
25
+ }
26
+ if (profile.policy === 'workspace') {
27
+ // If locations are provided, verify they are inside workspaceRoot
28
+ const locations = request.toolCall.locations || [];
29
+ const isInsideWorkspace = locations.length === 0 || locations.every((loc) => {
30
+ const resolved = path.resolve(workspaceRoot, loc.path);
31
+ return !path.relative(workspaceRoot, resolved).startsWith('..') && !path.isAbsolute(path.relative(workspaceRoot, resolved));
32
+ });
33
+ if (isInsideWorkspace) {
34
+ const allow = request.options.find((option) => option.kind === 'allow_once' || option.kind === 'allow_always');
35
+ return allow ? { outcome: 'selected', optionId: allow.optionId } : { outcome: 'cancelled' };
36
+ }
37
+ else {
38
+ const reject = request.options.find((option) => option.kind === 'reject_once' || option.kind === 'reject_always');
39
+ return reject ? { outcome: 'selected', optionId: reject.optionId } : { outcome: 'cancelled' };
40
+ }
41
+ }
42
+ // 'ask' policy: default to rejecting unless read-like or user approval can be obtained
43
+ if (readLike) {
44
+ const allow = request.options.find((option) => option.kind === 'allow_once' || option.kind === 'allow_always');
45
+ return allow ? { outcome: 'selected', optionId: allow.optionId } : { outcome: 'cancelled' };
19
46
  }
20
- const allow = request.options.find((option) => option.kind === 'allow_once' || option.kind === 'allow_always');
47
+ // Mutating requests under 'ask' policy default to requiring confirmation
48
+ const allow = request.options.find((option) => option.kind === 'allow_once');
21
49
  return allow ? { outcome: 'selected', optionId: allow.optionId } : { outcome: 'cancelled' };
22
50
  }
23
51
  export const peerAgentTool = {
24
52
  schema: {
25
53
  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.',
54
+ 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
55
  parameters: {
28
56
  type: 'object',
29
57
  properties: {
58
+ action: {
59
+ type: 'string',
60
+ enum: ['delegate', 'list', 'status'],
61
+ description: 'Action to perform: "delegate" to execute a task, "list" or "status" to view available peer agents.'
62
+ },
30
63
  peer: {
31
64
  type: 'string',
32
- description: 'Id of a configured peer profile from the peers file.'
65
+ description: 'Id of the peer agent (e.g. "opencode", "claude", "codex", "hermes", "cursor", "gemini").'
33
66
  },
34
67
  prompt: {
35
68
  type: 'string',
36
- description: 'Task instructions and context for the peer agent.'
69
+ description: 'Task instructions and context for the peer agent (required when action is delegate).'
70
+ },
71
+ model: {
72
+ type: 'string',
73
+ description: 'Optional model to select on the peer agent (e.g. "opencode-free", "claude-3-7-sonnet").'
74
+ },
75
+ mode: {
76
+ type: 'string',
77
+ description: 'Optional session mode for the peer agent.'
37
78
  },
38
79
  timeoutSeconds: {
39
80
  type: 'number',
40
- description: 'Optional shorter timeout in seconds, bounded by the profile timeout.'
81
+ description: 'Optional timeout in seconds (default 120, bounded between 5 and 1800).'
41
82
  }
42
- },
43
- required: ['peer', 'prompt']
83
+ }
44
84
  }
45
85
  },
46
- async execute(args) {
86
+ async execute(args = {}) {
87
+ const action = args.action || (args.peer || args.prompt !== undefined ? 'delegate' : 'list');
88
+ // 1. Action: list
89
+ if (action === 'list' || action === 'status') {
90
+ const allPeers = listAllPeers();
91
+ const peerList = allPeers.map((p) => ({
92
+ id: p.id,
93
+ label: p.label,
94
+ policy: p.policy,
95
+ timeoutSeconds: p.timeoutSeconds
96
+ }));
97
+ const presetIds = Object.keys(BUILTIN_PEER_PRESETS).join(', ');
98
+ return {
99
+ success: true,
100
+ peers: peerList,
101
+ 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}.`
102
+ };
103
+ }
104
+ // 2. Action: delegate
47
105
  const peerId = String(args.peer || '').trim();
48
106
  const prompt = String(args.prompt || '').trim().slice(0, MAX_PROMPT_CHARS);
49
107
  if (!peerId) {
50
- const configured = loadPeerProfiles().map((profile) => profile.id);
108
+ const available = listAllPeers().map((p) => p.id);
51
109
  return {
52
110
  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.'
111
+ error: `A peer id is required for delegation. Available peers: ${available.join(', ')}.`
56
112
  };
57
113
  }
58
114
  if (!prompt) {
@@ -60,39 +116,67 @@ export const peerAgentTool = {
60
116
  }
61
117
  const profile = getPeerProfile(peerId);
62
118
  if (!profile) {
63
- return { success: false, error: `Unknown peer profile: ${peerId}.` };
119
+ return { success: false, error: `Unknown peer profile: ${peerId}. Run with action "list" to see available peers.` };
64
120
  }
65
- const requested = typeof args.timeoutSeconds === 'number' && Number.isFinite(args.timeoutSeconds)
121
+ const requestedTimeout = typeof args.timeoutSeconds === 'number' && Number.isFinite(args.timeoutSeconds)
66
122
  ? Math.round(args.timeoutSeconds)
67
123
  : profile.timeoutSeconds;
68
- const timeoutSeconds = Math.max(5, Math.min(Math.min(profile.timeoutSeconds, requested), 1800));
124
+ const timeoutSeconds = Math.max(5, Math.min(Math.min(profile.timeoutSeconds, requestedTimeout), 1800));
125
+ const workspaceRoot = profile.cwd || process.cwd();
69
126
  const client = new AcpClient({
70
127
  command: profile.command,
71
128
  args: profile.args,
72
- cwd: profile.cwd ?? process.cwd(),
129
+ cwd: workspaceRoot,
73
130
  env: peerEnvironment(profile),
74
131
  promptTimeoutMs: timeoutSeconds * 1000,
75
- permissionHandler: async (request) => selectPermission(profile, request)
132
+ permissionHandler: async (request) => selectPermission(profile, request, workspaceRoot)
76
133
  });
77
134
  try {
78
135
  await client.start();
79
- const sessionId = await client.newSession(profile.cwd ?? process.cwd());
136
+ const sessionId = await client.newSession(workspaceRoot);
137
+ // Optional model selection if specified
138
+ if (args.model && client.agentCapabilities?.promptCapabilities) {
139
+ try {
140
+ await client.setSessionModel(sessionId, args.model);
141
+ }
142
+ catch {
143
+ // If model selection fails, continue with default model
144
+ }
145
+ }
146
+ // Optional mode selection if specified
147
+ if (args.mode) {
148
+ try {
149
+ await client.setSessionMode(sessionId, args.mode);
150
+ }
151
+ catch {
152
+ // If mode selection fails, continue with default mode
153
+ }
154
+ }
80
155
  const result = await client.prompt(sessionId, prompt);
81
156
  if (result.stopReason === 'cancelled') {
82
- return { success: false, error: 'The peer agent cancelled the task.' };
157
+ return { success: false, error: `The peer agent "${peerId}" cancelled the task.` };
83
158
  }
84
159
  if (result.stopReason === 'refusal') {
85
- return { success: false, error: 'The peer agent refused the task.' };
160
+ return { success: false, error: `The peer agent "${peerId}" refused the task.` };
86
161
  }
162
+ const agentName = client.agentInfo?.name || profile.label;
87
163
  return {
88
164
  success: true,
89
- output: result.text.trim() || 'Peer agent completed the task without a written summary.'
165
+ agent: agentName,
166
+ stopReason: result.stopReason,
167
+ output: result.text.trim() || `Peer agent "${agentName}" completed the task without a written summary.`
90
168
  };
91
169
  }
92
170
  catch (error) {
171
+ const msg = error instanceof Error ? error.message : String(error);
172
+ const isAuthError = /auth|login|credentials|unauthorized/i.test(msg);
173
+ const preset = BUILTIN_PEER_PRESETS[peerId.toLowerCase()];
174
+ const instruction = preset?.setupInstruction ? `\nGuidance: ${preset.setupInstruction}` : '';
93
175
  return {
94
176
  success: false,
95
- error: error instanceof Error ? error.message : 'Peer agent delegation failed.'
177
+ error: isAuthError
178
+ ? `Authentication required for peer "${peerId}": ${msg}.${instruction}`
179
+ : `Peer agent delegation to "${peerId}" failed: ${msg}.${instruction}`
96
180
  };
97
181
  }
98
182
  finally {