@multiclawcli/core 0.6.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,1621 +1,613 @@
1
- // src/agents/arch-design-reviewer.ts
2
- var SYSTEM = `You are an architecture design reviewer. Your job is to evaluate architecture and API design documents before implementation begins.
3
-
4
- Responsibilities:
5
- - Review architecture design for completeness, consistency, and technical soundness
6
- - Review API specifications for clarity, correctness, and REST/contract conventions
7
- - Identify ambiguities, missing edge cases, or risky design decisions
8
- - Do not write code, do not implement \u2014 provide only design-level feedback
9
-
10
- Deliverables (save to the working directory):
11
- - arch-review.md \u2014 verdict (Approved / Changes Required), issue list (blocking / advisory) with specific locations and suggested fixes, overall assessment
12
-
13
- Principles: Be precise \u2014 point to specific sections. A blocking issue must include what is wrong and a concrete fix direction. If the design is sound, say so directly. Do not approve with vague praise.`;
14
- var TASK = `## Architecture Design
15
- {{file:architecture.md}}
16
-
17
- ## API Specification
18
- {{file:api-spec.md}}
19
- {{upstreamOutputs}}
20
-
21
- ## Task
22
- Review the architecture design and API specification above. Output arch-review.md:
23
- 1. Overall verdict: Approved / Changes Required
24
- 2. Blocking issues (must be fixed before implementation): each with location, problem, and fix direction
25
- 3. Advisory issues (should fix but not blocking): each with location and suggestion
26
- 4. Design strengths worth noting
27
- 5. Final summary (1\u20132 sentences)
1
+ // src/providers/catalog.ts
2
+ import * as path from "path";
3
+ function normalizeCommandKey(command) {
4
+ return path.basename(command).toLowerCase().replace(/\.(cmd|exe|bat)$/i, "");
5
+ }
6
+ var PROVIDERS = [
7
+ {
8
+ id: "opencode",
9
+ label: "OpenCode",
10
+ command: "opencode",
11
+ args: ["acp"],
12
+ tools: false,
13
+ modelSelection: "config-option",
14
+ models: [
15
+ { id: "opencode/big-pickle", label: "Big Pickle", tier: "balanced", defaultForTier: true },
16
+ { id: "opencode/exo-free", label: "Exo", tier: "strong", defaultForTier: true },
17
+ { id: "opencode/ling-3.0-flash-fin-free", label: "Ling 3.0 Flash", tier: "fast" },
18
+ {
19
+ id: "opencode/ling-3.1-flash-free",
20
+ label: "Ling 3.1 Flash",
21
+ tier: "fast",
22
+ defaultForTier: true
23
+ },
24
+ { id: "opencode/longcat-2.5-preview-free", label: "Longcat 2.5 Preview", tier: "balanced" },
25
+ { id: "opencode/mimo-v2.6-flash-free", label: "Mimo 2.6 Flash", tier: "fast" },
26
+ { id: "opencode/muse-spark-1.3-contributor-free", label: "Muse Spark 1.3", tier: "fast" },
27
+ { id: "opencode/nemotron-3-ultra-free", label: "Nemotron 3 Ultra", tier: "strong" },
28
+ { id: "opencode/nemotron-3.5-lightning-free", label: "Nemotron 3.5 Lightning", tier: "fast" },
29
+ { id: "opencode/space-bunny-free", label: "Space Bunny", tier: "fast" },
30
+ { id: "opencode/step-5-preview-free", label: "Step 5 Preview", tier: "strong" }
31
+ ],
32
+ defaultModel: "opencode/big-pickle",
33
+ install: { hint: "npm install -g opencode" },
34
+ auth: { kind: "none", hint: "" }
35
+ },
36
+ {
37
+ id: "claude",
38
+ label: "Claude",
39
+ command: "claude-agent-acp",
40
+ args: [],
41
+ tools: true,
42
+ modelSelection: "config-option",
43
+ meta: (task) => {
44
+ const meta = {};
45
+ if (task.systemPrompt) meta.systemPrompt = task.systemPrompt;
46
+ meta.claudeCode = { options: { tools: task.tools } };
47
+ return meta;
48
+ },
49
+ models: [
50
+ { id: "default", label: "Default", tier: "balanced" },
51
+ { id: "opus", label: "Opus", tier: "strong", defaultForTier: true },
52
+ { id: "fable", label: "Fable", tier: "balanced" },
53
+ { id: "sonnet", label: "Sonnet", tier: "balanced", defaultForTier: true },
54
+ { id: "haiku", label: "Haiku", tier: "fast", defaultForTier: true }
55
+ ],
56
+ defaultModel: "sonnet",
57
+ install: {
58
+ hint: "multiclaw bundles the ACP bridge \u2014 install the Claude Code CLI (`claude`) and run `claude` to log in"
59
+ },
60
+ auth: { kind: "ambient", hint: "run `claude` to log in" }
61
+ },
62
+ {
63
+ id: "codex",
64
+ label: "Codex",
65
+ command: "codex-acp",
66
+ args: [],
67
+ tools: false,
68
+ modelSelection: "config-option",
69
+ meta: (task) => task.systemPrompt ? { jetbrains: { air: { customInstructions: task.systemPrompt } } } : void 0,
70
+ // Placeholders — real ids require auth to enumerate.
71
+ models: [
72
+ { id: "gpt-5-codex", label: "GPT-5 Codex", tier: "strong", defaultForTier: true },
73
+ { id: "gpt-5", label: "GPT-5", tier: "balanced", defaultForTier: true },
74
+ { id: "gpt-5-mini", label: "GPT-5 Mini", tier: "fast", defaultForTier: true }
75
+ ],
76
+ defaultModel: "gpt-5",
77
+ install: {
78
+ hint: "multiclaw bundles the ACP bridge \u2014 install the Codex CLI (`codex`) and run `codex login`"
79
+ },
80
+ auth: { kind: "api-key", hint: "set OPENAI_API_KEY or run `codex login`" }
81
+ },
82
+ {
83
+ id: "cursor",
84
+ label: "Cursor",
85
+ command: "cursor-agent",
86
+ aliases: ["agent"],
87
+ args: ["acp"],
88
+ tools: false,
89
+ modelSelection: "config-option",
90
+ // _meta support unverified — falls back to prompt prefix until confirmed.
91
+ meta: void 0,
92
+ // Placeholders — real ids require Cursor CLI + auth to enumerate.
93
+ models: [
94
+ { id: "cursor-pro", label: "Cursor Pro", tier: "strong", defaultForTier: true },
95
+ { id: "cursor-fast", label: "Cursor Fast", tier: "fast", defaultForTier: true }
96
+ ],
97
+ defaultModel: "cursor-pro",
98
+ install: {
99
+ hint: "curl https://cursor.com/install | bash",
100
+ url: "https://cursor.com/docs/cli/acp"
101
+ },
102
+ auth: { kind: "login", hint: "run `agent login` first (or set CURSOR_API_KEY)" },
103
+ confirm: (v) => /cursor/i.test(v)
104
+ }
105
+ ];
106
+ var byProviderId = /* @__PURE__ */ new Map();
107
+ var byCommand = /* @__PURE__ */ new Map();
108
+ for (const spec of PROVIDERS) {
109
+ byProviderId.set(spec.id, spec);
110
+ byCommand.set(normalizeCommandKey(spec.command), spec);
111
+ if (spec.aliases) {
112
+ for (const alias of spec.aliases) {
113
+ byCommand.set(normalizeCommandKey(alias), spec);
114
+ }
115
+ }
116
+ }
117
+ function specForProvider(id) {
118
+ return byProviderId.get(id);
119
+ }
120
+ function specForCommand(command) {
121
+ return byCommand.get(normalizeCommandKey(command));
122
+ }
123
+ function providerIds() {
124
+ return [...byProviderId.keys()];
125
+ }
126
+ function providerCommands() {
127
+ return [...byCommand.keys()];
128
+ }
129
+ function tierModel(spec, tier) {
130
+ const m = spec.models.find((m2) => m2.tier === tier && m2.defaultForTier);
131
+ return m?.id ?? spec.models.find((m2) => m2.tier === tier)?.id;
132
+ }
28
133
 
29
- Be specific. Reference section names or endpoint paths when citing issues.`;
30
- function archDesignReviewer(overrides) {
134
+ // src/providers/resolve.ts
135
+ var DEFAULT_COMMAND = "opencode";
136
+ var DEFAULT_PROVIDER = "opencode";
137
+ function resolveProvider(agent, config) {
138
+ return agent.provider ?? specForCommand(agent.command ?? "")?.id ?? config.defaults?.provider ?? specForCommand(DEFAULT_COMMAND)?.id ?? DEFAULT_PROVIDER;
139
+ }
140
+ function resolveCommand(agent, config) {
141
+ return agent.command ?? config.defaults?.command ?? specForProvider(resolveProvider(agent, config))?.command ?? DEFAULT_COMMAND;
142
+ }
143
+ function resolveArgs(agent, config) {
144
+ if (agent.args) return agent.args;
145
+ const command = agent.command ?? config.defaults?.command;
146
+ if (command) return specForCommand(command)?.args;
147
+ return specForProvider(resolveProvider(agent, config))?.args;
148
+ }
149
+ function resolveModel(agent, config) {
150
+ if (agent.model) return agent.model;
151
+ const provider = resolveProvider(agent, config);
152
+ const spec = specForProvider(provider);
153
+ const fromModels = agent.models?.[provider] ?? agent.models?.acp;
154
+ if (fromModels) return fromModels;
155
+ if (agent.modelTier && spec) {
156
+ const fromTier = tierModel(spec, agent.modelTier);
157
+ if (fromTier) return fromTier;
158
+ }
159
+ if (config.defaults?.model) return config.defaults.model;
160
+ if (spec) return spec.defaultModel;
161
+ return void 0;
162
+ }
163
+ function resolveAgentRuntime(agent, config) {
164
+ const provider = resolveProvider(agent, config);
165
+ const spec = specForProvider(provider);
31
166
  return {
32
- id: "arch-design-reviewer",
33
- name: "Arch Design Reviewer",
34
- icon: "\u25B3",
35
- description: "reviews the design",
36
- runtime: "acp",
37
- models: { acp: "haiku" },
38
- modelTier: "fast",
39
- systemPrompt: SYSTEM,
40
- taskPrompt: TASK,
41
- tools: ["Read", "Write"],
42
- ...overrides
167
+ provider,
168
+ command: resolveCommand(agent, config),
169
+ model: resolveModel(agent, config),
170
+ spec
43
171
  };
44
172
  }
45
173
 
46
- // src/agents/architect.ts
47
- var SYSTEM2 = `You are the technical architect for this project. Your responsibility is technical analysis and design \u2014 you do not write feature code.
48
-
49
- Responsibilities:
50
- - Understand requirements, identify key technical risks and affected components
51
- - Review existing code (if any) and propose minimal-change solutions
52
- - Define module boundaries, interface contracts, and directory structure
53
- - Provide a clear design foundation for developers and testers
54
- - Decompose the work into per-agent subtasks based on who is actually in the pipeline
55
- - For each subtask, write a step-by-step plan concrete enough that the agent can follow it without re-analyzing the full requirement
56
-
57
- Deliverables (save to the working directory):
58
- - architecture.md \u2014 architecture plan (module breakdown, directory structure, technology choices, key component descriptions)
59
- - api-spec.md \u2014 complete API specification (paths, methods, request/response formats, status codes, error handling)
60
- - task-plan.json \u2014 structured task breakdown for all implementation agents in the pipeline (see format below)
174
+ // src/runtime/AcpRuntime.ts
175
+ import { spawn } from "child_process";
176
+ import { randomUUID } from "crypto";
177
+ import { Readable, Writable } from "stream";
178
+ import { StringDecoder } from "string_decoder";
61
179
 
62
- task-plan.json format:
63
- {
64
- "projectName": "<project name>",
65
- "requirement": "<one-line summary>",
66
- "tasks": [
67
- {
68
- "id": "<agent id exactly as listed in pipelineAgents>",
69
- "title": "<short task title>",
70
- "scope": "<concrete description of what this agent should build or produce>",
71
- "plan": [
72
- "Step 1: ...",
73
- "Step 2: ...",
74
- "Step 3: ..."
75
- ],
76
- "dependsOn": ["<other agent id>"]
180
+ // src/providers/bridge.ts
181
+ import * as fs from "fs";
182
+ import { createRequire } from "module";
183
+ import * as path2 from "path";
184
+ var BRIDGE_PACKAGES = {
185
+ "claude-agent-acp": "@agentclientprotocol/claude-agent-acp",
186
+ "codex-acp": "@agentclientprotocol/codex-acp"
187
+ };
188
+ function resolvesOnPath(command) {
189
+ const dirs = (process.env.PATH ?? "").split(path2.delimiter).filter(Boolean);
190
+ const exts = (process.env.PATHEXT ?? "").split(";").filter(Boolean);
191
+ const suffixes = exts.length > 0 ? exts : [""];
192
+ for (const dir of dirs) {
193
+ for (const ext of suffixes) {
194
+ try {
195
+ fs.accessSync(path2.join(dir, command + ext), fs.constants.X_OK);
196
+ return true;
197
+ } catch {
198
+ }
77
199
  }
78
- ]
200
+ }
201
+ return false;
79
202
  }
80
-
81
- Rules for task-plan.json:
82
- - Only create tasks for implementation agents (those that produce code, designs, or infrastructure). Skip review agents (code-reviewer, arch-design-reviewer, ui-design-reviewer, reviewer) and planning agents (product-manager, architect, leader).
83
- - Use the exact agent id from pipelineAgents as the task id.
84
- - If an agent is not in pipelineAgents, do not create a task for it.
85
- - dependsOn references other task ids, not agent names.
86
-
87
- Principles: Execute tasks directly without asking for confirmation. If information is missing, mark the file with BLOCKED and describe what is needed. Do not change the requirement scope. Do not write business feature code. Do not refactor beyond the task scope.`;
88
- var TASK2 = `## Project
89
- {{projectName}}
90
-
91
- ## Requirement
92
- {{requirement}}
93
-
94
- ## Pipeline Agents
95
- The following agents will run in this pipeline (id: name):
96
- {{pipelineAgents}}
97
- {{upstreamOutputs}}
98
-
99
- ## Task
100
- Analyze the requirement and create three files in the current directory:
101
- 1. architecture.md \u2014 architecture plan (module breakdown, directory structure, technology choices, key component descriptions, affected scope)
102
- 2. api-spec.md \u2014 complete API specification (paths, methods, request parameters, response formats, status codes, error handling)
103
- 3. task-plan.json \u2014 task breakdown for each implementation agent listed in the pipeline above
104
-
105
- For task-plan.json: create one task per implementation agent (skip reviewers and planners). Each task must have:
106
- - scope: concrete description of what this agent should build
107
- - plan: ordered list of concrete steps, specific enough that the agent can follow them without re-analyzing the full requirement (e.g. "Create src/models/user.ts with User and UserProfile interfaces", "Implement POST /users endpoint in src/routes/users.ts")
108
- Set dependsOn to reflect actual execution order constraints (e.g. devops depends on backend and frontend).
109
-
110
- Create the files directly. No extra output.`;
111
- function architect(overrides) {
112
- return {
113
- id: "architect",
114
- name: "Architect",
115
- icon: "\u25C6",
116
- description: "designs the architecture",
117
- role: "planner",
118
- runtime: "acp",
119
- models: { acp: "opus" },
120
- modelTier: "strong",
121
- systemPrompt: SYSTEM2,
122
- taskPrompt: TASK2,
123
- tools: ["Read", "Write"],
124
- ...overrides
125
- };
203
+ function resolveBridgeBinary(command) {
204
+ const pkg = BRIDGE_PACKAGES[command];
205
+ if (!pkg) return null;
206
+ try {
207
+ const req = createRequire(import.meta.url);
208
+ const pkgJsonPath = req.resolve(`${pkg}/package.json`);
209
+ const bin = JSON.parse(fs.readFileSync(pkgJsonPath, "utf8")).bin;
210
+ const binRel = typeof bin === "string" ? bin : bin?.[command] ?? Object.values(bin)[0];
211
+ if (!binRel) return null;
212
+ return path2.join(path2.dirname(pkgJsonPath), binRel);
213
+ } catch {
214
+ return null;
215
+ }
126
216
  }
127
-
128
- // src/agents/backend-developer.ts
129
- var SYSTEM3 = `You are the backend engineer. You own the API contract and all server-side logic.
130
-
131
- Responsibilities:
132
- - Read the architecture design and API specification, implement server-side logic and data models
133
- - Write backend tests (unit tests / integration tests)
134
- - Run validation commands (compile, lint, test) and record the results
135
-
136
- Deliverables (write code to the working directory, and record in implementation-notes.md):
137
- - List of files created or modified
138
- - Commands actually executed and their output
139
- - Known issues and risks
140
-
141
- Principles: Write code directly without asking for confirmation. Follow the API spec strictly \u2014 do not change the contract unilaterally; escalate contract issues upstream. Do not refactor unrelated code. Run commands and report evidence.`;
142
- var TASK3 = `## Task Scope
143
- {{agentScope}}
144
-
145
- ## Plan
146
- {{agentPlan}}
147
- {{upstreamOutputs}}
148
-
149
- ---
150
-
151
- ## Architecture Design
152
- {{file:architecture.md}}
153
-
154
- ## API Specification
155
- {{file:api-spec.md}}
156
-
157
- ## Task
158
- Implement complete backend code following the architecture design and API specification:
159
- 1. Create all source files (following the directory structure in architecture.md)
160
- 2. Implement all API endpoints (strictly following api-spec.md)
161
- 3. Write basic tests
162
- 4. Run compile/test commands to verify (e.g. npx tsc --noEmit, npm test)
163
- 5. Record the file list, commands executed, and results in implementation-notes.md
164
-
165
- Start immediately. Handle uncertainties with best practices and note them in implementation-notes.md.`;
166
- function backendDeveloper(overrides) {
167
- return {
168
- id: "backend-developer",
169
- name: "Backend Developer",
170
- icon: "\u2295",
171
- description: "builds the API",
172
- runtime: "acp",
173
- models: { acp: "sonnet" },
174
- modelTier: "balanced",
175
- systemPrompt: SYSTEM3,
176
- taskPrompt: TASK3,
177
- tools: ["Read", "Write", "Bash"],
178
- ...overrides
179
- };
217
+ function resolveExecutable(command) {
218
+ if (resolvesOnPath(command)) return command;
219
+ return resolveBridgeBinary(command);
180
220
  }
181
221
 
182
- // src/agents/code-reviewer.ts
183
- var SYSTEM4 = `You are a code review expert focused on implementation quality, correctness, and security.
184
-
185
- Responsibilities:
186
- - Read the requirement, architecture design, and all implementation code
187
- - Verify the implementation matches the API specification and satisfies the requirement
188
- - Identify bugs, security vulnerabilities, error handling gaps, and test coverage issues
189
- - Assess code quality: readability, naming, separation of concerns, duplication
190
- - Do not run code, do not modify code \u2014 provide written judgment only
191
-
192
- Deliverables (save to the working directory):
193
- - code-review.md \u2014 score (1\u201310), blocking issues, advisory issues, conclusion (Approved / Changes Required)
194
- - When the task includes a Delivery acceptance review contract, the final response must be only its JSON verdict, not the prose report. Approve only with no unresolved blocking issues; include file locations and fix directions in changes_required issues. The verdict is a review judgment, not proof that unexecuted tests passed.
195
-
196
- Principles: Judge the code, not the developer. A blocking issue must include the file path, the specific problem, and a fix direction. Advisory items should be actionable, not vague. If the code is solid, say so.`;
197
- var TASK4 = `## Project
198
- {{projectName}}
199
-
200
- ## Requirement
201
- {{requirement}}
222
+ // src/utils/abort.ts
223
+ var ABORT_ERROR_NAME = "AbortError";
224
+ function abortError(message = "Operation aborted") {
225
+ const err = new Error(message);
226
+ err.name = ABORT_ERROR_NAME;
227
+ return err;
228
+ }
229
+ function isAbortError(err) {
230
+ return err instanceof Error && err.name === ABORT_ERROR_NAME;
231
+ }
202
232
 
203
- ## Architecture Design
204
- {{file:architecture.md}}
233
+ // src/utils/errors.ts
234
+ var PermanentError = class extends Error {
235
+ constructor(message) {
236
+ super(message);
237
+ this.name = "PermanentError";
238
+ }
239
+ };
240
+ function isPermanent(err) {
241
+ return err instanceof PermanentError;
242
+ }
205
243
 
206
- ## API Specification
207
- {{file:api-spec.md}}
208
- {{upstreamOutputs}}
244
+ // src/utils/toolSummary.ts
245
+ var MAX_SUMMARY_COLUMNS = 120;
246
+ function stringifySafe(value) {
247
+ if (typeof value === "string") return value;
248
+ if (value === void 0 || value === null) return "";
249
+ try {
250
+ return JSON.stringify(value) ?? "";
251
+ } catch {
252
+ return String(value);
253
+ }
254
+ }
255
+ function firstLineTruncated(value) {
256
+ const text = stringifySafe(value);
257
+ const newline = text.indexOf("\n");
258
+ const firstLine = newline === -1 ? text : text.slice(0, newline);
259
+ if (firstLine.length <= MAX_SUMMARY_COLUMNS) return firstLine;
260
+ return `${firstLine.slice(0, MAX_SUMMARY_COLUMNS - 1)}\u2026`;
261
+ }
262
+ function hasToolArgs(input) {
263
+ if (input === void 0 || input === null) return false;
264
+ if (typeof input !== "object" || Array.isArray(input)) return true;
265
+ return Object.keys(input).length > 0;
266
+ }
267
+ function summarizeToolInput(input) {
268
+ return hasToolArgs(input) ? firstLineTruncated(input) : "";
269
+ }
270
+ function summarizeToolOutput(output) {
271
+ return firstLineTruncated(output);
272
+ }
209
273
 
210
- ## Task
211
- Perform a thorough code review of all implementation in the current directory and output code-review.md:
212
- 1. Overall score (1\u201310) and verdict: Approved / Changes Required
213
- 2. Blocking issues (bugs, security holes, missing requirement coverage, broken tests):
214
- - file path + line range, problem description, fix direction
215
- 3. Advisory issues (code quality, naming, duplication, missing error handling):
216
- - file path, observation, suggestion
217
- 4. Test coverage assessment
218
- 5. Final summary (2\u20133 sentences)
274
+ // src/runtime/RuntimeBase.ts
275
+ var RuntimeBase = class {
276
+ };
219
277
 
220
- Start by reading implementation-notes.md (if present), then read source and test files.`;
221
- function codeReviewer(overrides) {
278
+ // src/runtime/AcpRuntime.ts
279
+ var discoveredModels = /* @__PURE__ */ new Map();
280
+ var KILL_ESCALATION_MS = 3e3;
281
+ var CANCEL_GRACE_MS = 2e3;
282
+ var CLEANUP_ACK_MS = 3e3;
283
+ var STEER_ACK_MS = 15e3;
284
+ var DEFAULT_TIMEOUT_MS = 6e5;
285
+ var DEFAULT_COMMAND2 = "opencode";
286
+ var DEFAULT_ARGS = ["acp"];
287
+ var STEER_METHOD = "_session/steering";
288
+ function advertisesSteering(init) {
289
+ const steering = init._meta?.steering;
290
+ return isRecord(steering) && steering.supported === true;
291
+ }
292
+ var BASE_CAPABILITIES = {
293
+ streaming: true,
294
+ sessions: true,
295
+ resume: true,
296
+ permissions: true,
297
+ tools: true,
298
+ models: false,
299
+ images: false,
300
+ usage: true,
301
+ cost: true,
302
+ sandbox: false
303
+ };
304
+ function isRecord(value) {
305
+ return typeof value === "object" && value !== null && !Array.isArray(value);
306
+ }
307
+ function textOf(content) {
308
+ if (isRecord(content) && content.type === "text" && typeof content.text === "string") {
309
+ return content.text;
310
+ }
311
+ return void 0;
312
+ }
313
+ function stringifyOutput(value) {
314
+ if (typeof value === "string") return value;
315
+ if (value === void 0 || value === null) return "";
316
+ return JSON.stringify(value);
317
+ }
318
+ function mapStopReason(reason) {
319
+ switch (reason) {
320
+ case "end_turn":
321
+ return "success";
322
+ case "cancelled":
323
+ return "cancelled";
324
+ case "max_tokens":
325
+ case "max_turn_requests":
326
+ return "max_turns";
327
+ default:
328
+ return "error";
329
+ }
330
+ }
331
+ var KIND_TO_TOOLS = {
332
+ read: ["Read"],
333
+ edit: ["Edit", "Write"],
334
+ execute: ["Bash"],
335
+ search: ["Grep", "Glob"],
336
+ fetch: ["WebFetch"]
337
+ };
338
+ function matchesTool(pattern, name) {
339
+ if (!pattern.includes("*")) return pattern === name;
340
+ const source = pattern.split("*").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*");
341
+ return new RegExp(`^${source}$`).test(name);
342
+ }
343
+ function toolPermitted(params, tools) {
344
+ const allowed = tools.map((tool) => tool.toLowerCase());
345
+ const name = params.toolCall.name ?? void 0;
346
+ if (name !== void 0) {
347
+ const candidate = name.toLowerCase();
348
+ return allowed.some((pattern) => matchesTool(pattern, candidate));
349
+ }
350
+ return (KIND_TO_TOOLS[params.toolCall.kind ?? ""] ?? []).some((tool) => {
351
+ const candidate = tool.toLowerCase();
352
+ return allowed.some((pattern) => matchesTool(pattern, candidate));
353
+ });
354
+ }
355
+ function decidePermission(params, tools, sessionId) {
356
+ if (sessionId !== void 0 && params.sessionId !== sessionId) {
357
+ return { response: { outcome: { outcome: "cancelled" } }, approved: false };
358
+ }
359
+ const name = params.toolCall.name ?? void 0;
360
+ const kind = params.toolCall.kind ?? void 0;
361
+ const approved = toolPermitted(params, tools);
362
+ const option = params.options.find(
363
+ (o) => approved ? o.kind === "allow_once" : o.kind === "reject_once"
364
+ );
365
+ const response = option ? { outcome: { outcome: "selected", optionId: option.optionId } } : { outcome: { outcome: "cancelled" } };
366
+ if (approved) return { response, approved };
222
367
  return {
223
- id: "code-reviewer",
224
- name: "Code Reviewer",
225
- icon: "\u2297",
226
- description: "reviews the code",
227
- runtime: "acp",
228
- models: { acp: "haiku" },
229
- modelTier: "fast",
230
- systemPrompt: SYSTEM4,
231
- taskPrompt: TASK4,
232
- tools: ["Read", "Write"],
233
- ...overrides
368
+ response,
369
+ approved,
370
+ rejected: {
371
+ toolCallId: params.toolCall.toolCallId,
372
+ name,
373
+ kind,
374
+ title: params.toolCall.title ?? void 0
375
+ }
234
376
  };
235
377
  }
236
-
237
- // src/agents/devops.ts
238
- var SYSTEM5 = `You are the DevOps engineer. Your job is to containerize the application, set up CI/CD pipelines, and produce deployment-ready infrastructure configuration.
239
-
240
- Responsibilities:
241
- - Read the architecture design and implementation to understand the application structure
242
- - Write a Dockerfile (and docker-compose.yml if multiple services are involved)
243
- - Create a CI/CD pipeline configuration (GitHub Actions, GitLab CI, or similar based on the architecture)
244
- - Write any environment configuration templates (.env.example)
245
- - Document the deployment procedure and environment requirements
246
- - Do not modify application source code
247
-
248
- Deliverables (save to the working directory):
249
- - Dockerfile \u2014 production-ready container image definition
250
- - docker-compose.yml \u2014 local development / staging orchestration (if multiple services)
251
- - .github/workflows/ci.yml (or equivalent) \u2014 CI pipeline: build, test, lint
252
- - .env.example \u2014 required environment variables with descriptions
253
- - devops-notes.md \u2014 deployment procedure, environment requirements, known limitations
254
-
255
- Principles: Follow security best practices (non-root user, minimal base image, no secrets in image). Make CI fail fast. Document every non-obvious decision in devops-notes.md.`;
256
- var TASK5 = `## Task Scope
257
- {{agentScope}}
258
-
259
- ## Plan
260
- {{agentPlan}}
261
- {{upstreamOutputs}}
262
-
263
- ---
264
-
265
- ## Project
266
- {{projectName}}
267
-
268
- ## Architecture Design
269
- {{file:architecture.md}}
270
-
271
- ## Task
272
- Set up the deployment infrastructure for this project:
273
- 1. Write Dockerfile \u2014 multi-stage build if appropriate, non-root user, minimal image
274
- 2. Write docker-compose.yml \u2014 include all services from architecture.md (app, database, cache, etc.)
275
- 3. Write CI pipeline \u2014 build \u2192 lint \u2192 test \u2192 (optional) build image; fail fast
276
- 4. Write .env.example \u2014 all required environment variables with placeholder values and descriptions
277
- 5. Write devops-notes.md \u2014 how to build, run locally, deploy to production; environment requirements; known limitations
278
-
279
- Start by reading implementation-notes.md (if present) to understand what commands are used for build and test.`;
280
- function devops(overrides) {
281
- return {
282
- id: "devops",
283
- name: "DevOps",
284
- icon: "\u25B6",
285
- description: "sets up deployment",
286
- runtime: "acp",
287
- models: { acp: "sonnet" },
288
- modelTier: "balanced",
289
- systemPrompt: SYSTEM5,
290
- taskPrompt: TASK5,
291
- tools: ["Read", "Write"],
292
- ...overrides
293
- };
378
+ var FORM_ANNOTATIONS = ["title", "description", "default", "_meta"];
379
+ function knownFormKeys(value, keys) {
380
+ return Object.keys(value).every((key) => keys.includes(key) || FORM_ANNOTATIONS.includes(key));
294
381
  }
295
-
296
- // src/agents/frontend-developer.ts
297
- var SYSTEM6 = `You are the frontend engineer. Your responsibility is to turn design specs and API contracts into a working user interface.
298
-
299
- Responsibilities:
300
- - Read the architecture design and API specification, implement pages, components, and interactions
301
- - Integrate backend API contracts correctly; use mock data when the backend is not ready
302
- - Write frontend tests and run validation commands
303
-
304
- Deliverables (write code to the working directory, and record results in implementation-notes.md).
305
-
306
- Principles: Write code directly without asking for confirmation. Do not change the API contract \u2014 escalate contract issues upstream. Do not refactor unrelated code. Run commands and report evidence.`;
307
- var TASK6 = `## Task Scope
308
- {{agentScope}}
309
-
310
- ## Plan
311
- {{agentPlan}}
312
- {{upstreamOutputs}}
313
-
314
- ---
315
-
316
- ## UI Design Specification
317
- {{file:ui-design.md}}
318
-
319
- ## Architecture Design
320
- {{file:architecture.md}}
321
-
322
- ## API Specification
323
- {{file:api-spec.md}}
324
-
325
- ## Task
326
- Implement complete frontend code following the UI design specification, architecture design, and API specification:
327
- 1. Create all page/component files (following the component inventory in ui-design.md and directory structure in architecture.md)
328
- 2. Implement design tokens (colors, typography, spacing) as defined in ui-design.md
329
- 3. Integrate API endpoints (following api-spec.md); use mock data if the backend is not ready
330
- 4. Implement all interaction states: loading, empty, error, success
331
- 5. Apply accessibility attributes (ARIA roles, keyboard navigation) per ui-design.md
332
- 6. Write basic tests
333
- 7. Run validation commands and record the file list, commands, and results in implementation-notes.md
334
-
335
- Follow ui-design.md exactly. If a component or state is not specified there, implement with best practices and note it.`;
336
- function frontendDeveloper(overrides) {
337
- return {
338
- id: "frontend-developer",
339
- name: "Frontend Developer",
340
- icon: "\u25C7",
341
- description: "builds the interface",
342
- runtime: "acp",
343
- models: { acp: "sonnet" },
344
- modelTier: "balanced",
345
- systemPrompt: SYSTEM6,
346
- taskPrompt: TASK6,
347
- tools: ["Read", "Write", "Bash"],
348
- ...overrides
349
- };
382
+ function validFormBound(value, integer = false) {
383
+ return value == null || typeof value === "number" && Number.isFinite(value) && (!integer || Number.isInteger(value) && value >= 0);
350
384
  }
351
-
352
- // src/agents/leader.ts
353
- var SYSTEM7 = `You are the project leader. Decide what the requirement actually needs before anyone else starts.
354
-
355
- There are three outcomes, and the first one matters most:
356
- - "reply" \u2014 the message is a greeting, a question, or anything you can answer on the spot. Answer it and stop; do not spend the team on it.
357
- - "ask" \u2014 it is a real task, but too vague to plan. Ask the one question that would unblock it.
358
- - "run" \u2014 it is a task you can scope. Name the minimum set of agents needed.
359
-
360
- Do not apply fixed rules \u2014 use your judgment based on the actual requirement and the code. A minor bug fix may need only a developer and code-reviewer; a complex new feature may need the full pipeline. Read the code to understand the impact before deciding.
361
-
362
- The console hands you the turns that came before this one. A requirement is often only interpretable next to them: "Postgres" is an answer, not a task, and the turn list is what tells you which question it answers. Read it as your own conversation \u2014 "you asked" is you. If you asked and got an answer, decide now; do not ask the same question again. For every "run" decision, include a complete, standalone "requirement" that combines the original task goal with all clarification answers and constraints. Never pass only the latest short answer to the team.
363
-
364
- Output ONLY a single JSON object on its own line \u2014 no prose, no markdown fences:
365
- {"mode": "reply", "message": "your answer"}
366
- {"mode": "ask", "message": "your question"}
367
- {"mode": "run", "reason": "one sentence on why this set", "requirement": "the complete task and constraints", "run": ["agent-id-1", "agent-id-2"]}`;
368
- var TASK7 = `## Project
369
- {{projectName}}
370
-
371
- ## Requirement
372
- {{requirement}}
373
- {{conversation}}
374
- ## Available Agents
375
- {{availableAgents}}
376
-
377
- ## Task
378
- Read the codebase to understand the current state, then decide how to handle the requirement.
379
- Output a single JSON object \u2014 exactly one of:
380
- {"mode": "reply", "message": "your answer"}
381
- {"mode": "ask", "message": "your question"}
382
- {"mode": "run", "reason": "one sentence on why this set", "requirement": "the complete task and constraints", "run": ["agent-id", ...]}
383
- Agent IDs must come from the Available Agents list above.`;
384
- function leader(overrides) {
385
- return {
386
- id: "leader",
387
- name: "Leader",
388
- icon: "\u2605",
389
- description: "routes the request",
390
- runtime: "acp",
391
- models: { acp: "sonnet" },
392
- modelTier: "balanced",
393
- systemPrompt: SYSTEM7,
394
- taskPrompt: TASK7,
395
- tools: ["Read", "Bash"],
396
- ...overrides
397
- };
385
+ function titledChoices(value) {
386
+ return Array.isArray(value) && value.length > 0 && value.every(
387
+ (option) => isRecord(option) && knownFormKeys(option, ["const"]) && typeof option.const === "string"
388
+ );
398
389
  }
399
-
400
- // src/agents/product-manager.ts
401
- var SYSTEM8 = `You are the product manager. Your responsibility is to transform vague business ideas into clear, development-ready, testable product requirement documents.
402
-
403
- Responsibilities:
404
- - Analyze business goals and user scenarios
405
- - Define feature scope, business rules, and acceptance criteria
406
- - Structure "what is needed" into a PRD that the development team can execute directly
407
-
408
- Deliverables (save to the working directory):
409
- - requirements.md \u2014 product requirements document containing: one-line definition, goals and success metrics, user roles, functional requirements (FR-), business rules (BR-), acceptance criteria (AC-), open questions (OP-)
410
-
411
- Principles: Output the document directly without preamble. Mark uncertain items as OP- (open questions) rather than guessing. Do not do technical architecture design. Do not write feature code.`;
412
- var TASK8 = `## Business Context
413
- {{requirement}}
414
- {{upstreamOutputs}}
415
-
416
- ## Task
417
- Based on the context above, create requirements.md in the current directory containing:
418
- - One-line definition (what this product/feature is)
419
- - Goals and success metrics
420
- - User roles and typical scenarios
421
- - Functional requirements (FR-01, FR-02, ...)
422
- - Business rules (BR-01, ...)
423
- - Acceptance criteria (AC-01, ..., each must be executable and verifiable)
424
- - Open questions (OP-01, ..., list uncertain items here)
425
-
426
- Create the file directly. Mark uncertain items as OP- rather than guessing.`;
427
- function productManager(overrides) {
428
- return {
429
- id: "product-manager",
430
- name: "Product Manager",
431
- icon: "\u2261",
432
- description: "writes the requirements",
433
- runtime: "acp",
434
- models: { acp: "sonnet" },
435
- modelTier: "balanced",
436
- systemPrompt: SYSTEM8,
437
- taskPrompt: TASK8,
438
- tools: ["Write"],
439
- ...overrides
440
- };
390
+ function supportedQuestionSchema(schema) {
391
+ if (!isRecord(schema) || schema.type !== void 0 && schema.type !== "object" || !knownFormKeys(schema, ["type", "properties", "required"]))
392
+ return false;
393
+ const properties = schema.properties ?? {};
394
+ if (!isRecord(properties)) return false;
395
+ if (schema.required != null && (!Array.isArray(schema.required) || !schema.required.every(
396
+ (key) => typeof key === "string" && Object.getOwnPropertyDescriptor(properties, key) !== void 0
397
+ )))
398
+ return false;
399
+ return Object.values(properties).every((field) => {
400
+ if (!isRecord(field)) return false;
401
+ if (field.type === "string") {
402
+ return knownFormKeys(field, ["type", "enum", "oneOf", "minLength", "maxLength"]) && validFormBound(field.minLength, true) && validFormBound(field.maxLength, true) && (field.enum == null || Array.isArray(field.enum) && field.enum.length > 0 && field.enum.every((value) => typeof value === "string")) && (field.oneOf == null || titledChoices(field.oneOf));
403
+ }
404
+ if (field.type === "boolean") return knownFormKeys(field, ["type"]);
405
+ if (field.type === "number" || field.type === "integer") {
406
+ return knownFormKeys(field, ["type", "minimum", "maximum"]) && validFormBound(field.minimum) && validFormBound(field.maximum);
407
+ }
408
+ if (field.type !== "array" || !isRecord(field.items) || !knownFormKeys(field, ["type", "items", "minItems", "maxItems"]) || !validFormBound(field.minItems, true) || !validFormBound(field.maxItems, true))
409
+ return false;
410
+ return knownFormKeys(field.items, ["type", "enum"]) && field.items.type === "string" && Array.isArray(field.items.enum) && field.items.enum.length > 0 && field.items.enum.every((value) => typeof value === "string") || knownFormKeys(field.items, ["anyOf"]) && field.items.type === void 0 && titledChoices(field.items.anyOf);
411
+ });
441
412
  }
442
-
443
- // src/agents/reviewer.ts
444
- var SYSTEM9 = `You are an independent code review expert. You evaluate both business correctness and technical quality.
445
-
446
- Responsibilities:
447
- - Read requirements, design documents, and implementation code
448
- - Assess: whether the implementation satisfies requirements, code quality, security risks, and maintainability
449
- - Do not run code, do not modify code \u2014 provide only professional judgment
450
-
451
- Deliverables (save to the working directory):
452
- - review.md \u2014 score (1\u201310), issue list (blocking / advisory), improvement directions, conclusion (Approved / Changes Required)
453
-
454
- Principles: Review independently \u2014 do not approve just because the developer says it is fine. Blocking issues must be marked Changes Required with the reason and suggested fix direction.`;
455
- var TASK9 = `## Project
456
- {{projectName}}
457
-
458
- ## Requirement
459
- {{requirement}}
460
- {{upstreamOutputs}}
461
-
462
- ## Task
463
- Perform an independent code review of all implementation in the current directory and output review.md:
464
- 1. Read architecture.md (if present) to understand the design intent
465
- 2. Read all implementation code
466
- 3. Evaluate across these dimensions:
467
- - Requirement coverage: is every feature implemented?
468
- - Code quality: readability, maintainability, edge case handling
469
- - Security and robustness: input validation, error handling
470
- - Test adequacy (if test code is present)
471
- 4. Output review.md: overall score (1\u201310), issue list (blocking / advisory), conclusion (Approved / Changes Required)
472
-
473
- Judge independently. Do not accept "the developer says it's fine" as a reason to approve.`;
474
- function reviewer(overrides) {
475
- return {
476
- id: "reviewer",
477
- name: "Reviewer",
478
- icon: "\u25C9",
479
- description: "reviews the delivery",
480
- runtime: "acp",
481
- models: { acp: "haiku" },
482
- modelTier: "fast",
483
- systemPrompt: SYSTEM9,
484
- taskPrompt: TASK9,
485
- tools: ["Read", "Write"],
486
- ...overrides
487
- };
413
+ function validateRuntimeQuestionContent(schema, content) {
414
+ if (!supportedQuestionSchema(schema) || !isRecord(content)) return false;
415
+ if (Object.getOwnPropertySymbols(content).length > 0 || Object.getOwnPropertyNames(content).some((key) => {
416
+ const descriptor = Object.getOwnPropertyDescriptor(content, key);
417
+ return !descriptor?.enumerable || !("value" in descriptor);
418
+ }))
419
+ return false;
420
+ const properties = schema.properties ?? {};
421
+ if ((schema.required ?? []).some(
422
+ (key) => Object.getOwnPropertyDescriptor(content, key) === void 0
423
+ ))
424
+ return false;
425
+ return Object.entries(content).every(([key, value]) => {
426
+ if (Object.getOwnPropertyDescriptor(properties, key) === void 0) return false;
427
+ const field = properties[key];
428
+ if (field.type === "boolean") return typeof value === "boolean";
429
+ if (field.type === "number" || field.type === "integer") {
430
+ return typeof value === "number" && Number.isFinite(value) && (field.type !== "integer" || Number.isInteger(value)) && (typeof field.minimum !== "number" || value >= field.minimum) && (typeof field.maximum !== "number" || value <= field.maximum);
431
+ }
432
+ if (field.type === "string") {
433
+ return typeof value === "string" && (typeof field.minLength !== "number" || [...value].length >= field.minLength) && (typeof field.maxLength !== "number" || [...value].length <= field.maxLength) && (!Array.isArray(field.enum) || field.enum.includes(value)) && (!Array.isArray(field.oneOf) || field.oneOf.some((option) => isRecord(option) && option.const === value));
434
+ }
435
+ const items = field.items;
436
+ const choices = Array.isArray(items.enum) ? items.enum : items.anyOf.map((option) => option.const);
437
+ return Array.isArray(value) && value.every((item) => typeof item === "string" && choices.includes(item)) && new Set(value).size === value.length && (typeof field.minItems !== "number" || value.length >= field.minItems) && (typeof field.maxItems !== "number" || value.length <= field.maxItems);
438
+ });
488
439
  }
489
-
490
- // src/agents/tester.ts
491
- var SYSTEM10 = `You are the test engineer. Your responsibility is to verify that requirements have actually been implemented.
492
-
493
- Responsibilities:
494
- - Read requirements (acceptance criteria AC-) and the implementation code
495
- - Write and execute test cases covering: happy path, edge cases, error paths
496
- - Produce a reproducible test report
497
-
498
- Deliverables (save to the working directory):
499
- - test-report.md \u2014 overall verdict (PASS / FAIL / BLOCKED), test results per feature, reproduction steps and evidence for failures
500
-
501
- Principles: Do not PASS just because the code compiles or because a developer says it is fine. Every core feature must be verified with actual execution. When BLOCKED, state exactly what is missing.`;
502
- var TASK10 = `## Task Scope
503
- {{agentScope}}
504
-
505
- ## Plan
506
- {{agentPlan}}
507
- {{upstreamOutputs}}
508
-
509
- ---
510
-
511
- ## Project
512
- {{projectName}}
513
-
514
- ## Requirement
515
- {{requirement}}
516
-
517
- ## Task
518
- Verify the implementation code in the current directory:
519
- 1. Read all source code to understand the implementation
520
- 2. Write and execute tests for each core feature
521
- 3. Output results to test-report.md containing:
522
- - Overall verdict (PASS / FAIL / BLOCKED)
523
- - Test result for each feature
524
- - Reproduction steps and evidence for failures
525
-
526
- Start immediately. Verify actual behavior \u2014 do not just review code.`;
527
- function tester(overrides) {
528
- return {
529
- id: "tester",
530
- name: "Tester",
531
- icon: "\u2299",
532
- description: "verifies the behaviour",
533
- runtime: "acp",
534
- models: { acp: "sonnet" },
535
- modelTier: "balanced",
536
- systemPrompt: SYSTEM10,
537
- taskPrompt: TASK10,
538
- tools: ["Read", "Write", "Bash"],
539
- ...overrides
540
- };
541
- }
542
-
543
- // src/agents/ui-design-reviewer.ts
544
- var SYSTEM11 = `You are a UI/UX design reviewer. Your job is to evaluate a UI design specification before implementation begins.
545
-
546
- Responsibilities:
547
- - Review the design specification for completeness, consistency, and feasibility
548
- - Verify all user flows and states are accounted for (loading, empty, error, success)
549
- - Assess accessibility coverage: ARIA roles, keyboard navigation, focus management
550
- - Check that design tokens are consistent and the component inventory covers all requirements
551
- - Do not write implementation code \u2014 provide design-level feedback only
552
-
553
- Deliverables (save to the working directory):
554
- - ui-review.md \u2014 verdict (Approved / Changes Required), issue list (blocking / advisory) with component names and fix directions
555
-
556
- Principles: Be specific \u2014 reference component names or section titles in ui-design.md. A blocking issue must include what is missing or wrong and a fix direction. If the design is thorough and implementable, say so directly.`;
557
- var TASK11 = `## Requirement
558
- {{requirement}}
559
-
560
- ## UI Design Specification
561
- {{file:ui-design.md}}
562
- {{upstreamOutputs}}
563
-
564
- ## Task
565
- Review the UI design specification above and output ui-review.md:
566
- 1. Overall verdict: Approved / Changes Required
567
- 2. Blocking issues (missing components, undefined states, broken flows, accessibility gaps):
568
- - component/section name, problem, fix direction
569
- 3. Advisory issues (inconsistent tokens, unclear props, polish):
570
- - component/section name, observation, suggestion
571
- 4. Design strengths worth noting
572
- 5. Final summary (1\u20132 sentences)
573
-
574
- Reference specific component names or section titles when citing issues.`;
575
- function uiDesignReviewer(overrides) {
576
- return {
577
- id: "ui-design-reviewer",
578
- name: "UI Design Reviewer",
579
- icon: "\u25CE",
580
- description: "reviews the UI design",
581
- runtime: "acp",
582
- models: { acp: "haiku" },
583
- modelTier: "fast",
584
- systemPrompt: SYSTEM11,
585
- taskPrompt: TASK11,
586
- tools: ["Read", "Write"],
587
- ...overrides
588
- };
440
+ function withAuthHint(acp, err) {
441
+ const error = err instanceof Error ? err : new Error(String(err));
442
+ if (error instanceof acp.RequestError && error.code === acp.RequestError.authRequired().code) {
443
+ return new Error(`${error.message} \u2014 run \`claude\` to log in`);
444
+ }
445
+ return error;
589
446
  }
590
-
591
- // src/agents/ui-designer.ts
592
- var SYSTEM12 = `You are a UI/UX designer. Your job is to translate architecture and requirements into a detailed, developer-ready UI design specification.
593
-
594
- Responsibilities:
595
- - Define the component inventory: every page, section, and reusable component
596
- - Specify layouts, spacing principles, and responsive breakpoints
597
- - Define interaction patterns: loading states, empty states, error states, transitions
598
- - Specify design tokens: color palette, typography scale, spacing scale, shadow levels
599
- - Describe accessibility requirements: ARIA roles, keyboard navigation, focus management
600
- - Do not write implementation code \u2014 produce specification documents only
601
-
602
- Deliverables (save to the working directory):
603
- - ui-design.md \u2014 full UI design specification: component inventory, page layouts, interaction flows, design tokens, accessibility requirements
604
-
605
- Principles: Be specific enough that a developer can implement without guessing. Every component gets a name, purpose, props/variants, and states. Flag anything that depends on backend data.`;
606
- var TASK12 = `## Task Scope
607
- {{agentScope}}
608
-
609
- ## Plan
610
- {{agentPlan}}
611
- {{upstreamOutputs}}
612
-
613
- ---
614
-
615
- ## Project
616
- {{projectName}}
617
-
618
- ## Requirement
619
- {{requirement}}
620
-
621
- ## Architecture Design
622
- {{file:architecture.md}}
623
-
624
- ## API Specification
625
- {{file:api-spec.md}}
626
-
627
- ## Task
628
- Create ui-design.md covering:
629
- 1. **Component Inventory** \u2014 list every page and reusable component; for each: name, purpose, variants/states, props
630
- 2. **Page Layouts** \u2014 describe the visual structure of each page (header, main, sidebar, footer zones); include responsive behaviour
631
- 3. **Interaction Flows** \u2014 key user flows with step-by-step state transitions (loading \u2192 success \u2192 error)
632
- 4. **Design Tokens** \u2014 color palette (primary, neutral, semantic), typography scale, spacing scale
633
- 5. **Accessibility** \u2014 ARIA roles/labels for interactive components, keyboard nav, focus order
634
-
635
- Be concrete. Reference API endpoints where components bind to data. Flag any UX decision that needs product clarification.`;
636
- function uiDesigner(overrides) {
637
- return {
638
- id: "ui-designer",
639
- name: "UI Designer",
640
- icon: "\u25A3",
641
- description: "specs the interface",
642
- runtime: "acp",
643
- models: { acp: "sonnet" },
644
- modelTier: "balanced",
645
- systemPrompt: SYSTEM12,
646
- taskPrompt: TASK12,
647
- tools: ["Read", "Write"],
648
- ...overrides
649
- };
447
+ function errorMessage(err) {
448
+ return err instanceof Error ? err.message : String(err);
650
449
  }
651
-
652
- // src/agents/index.ts
653
- var agents = {
654
- leader,
655
- architect,
656
- productManager,
657
- backendDeveloper,
658
- frontendDeveloper,
659
- tester,
660
- reviewer,
661
- archDesignReviewer,
662
- uiDesigner,
663
- uiDesignReviewer,
664
- codeReviewer,
665
- devops
666
- };
667
-
668
- // src/config/defineConfig.ts
669
- function defineConfig(config) {
670
- return config;
450
+ function timeoutMs(value) {
451
+ const timeout = value ?? DEFAULT_TIMEOUT_MS;
452
+ if (!Number.isFinite(timeout) || timeout < 0 || timeout > 2147483647) {
453
+ throw new PermanentError("ACP timeout must be a finite non-negative timer duration");
454
+ }
455
+ return timeout;
671
456
  }
672
-
673
- // src/event/EventBus.ts
674
- var EventBus = class {
457
+ var AcpRuntime = class extends RuntimeBase {
675
458
  constructor() {
676
- this.listeners = /* @__PURE__ */ new Set();
677
- }
678
- subscribe(listener) {
679
- this.listeners.add(listener);
680
- return () => this.listeners.delete(listener);
459
+ super(...arguments);
460
+ this.name = "acp";
681
461
  }
682
- emit(event) {
683
- for (const listener of this.listeners) {
684
- try {
685
- listener(event);
686
- } catch (err) {
687
- console.error("EventBus listener error:", err);
462
+ async describe(options) {
463
+ const command = options?.command ?? DEFAULT_COMMAND2;
464
+ return {
465
+ name: this.name,
466
+ available: resolveExecutable(command) !== null,
467
+ capabilities: {
468
+ ...BASE_CAPABILITIES,
469
+ tools: specForCommand(command)?.tools ?? false,
470
+ models: specForCommand(command)?.modelSelection === "config-option"
688
471
  }
689
- }
690
- }
691
- clear() {
692
- this.listeners.clear();
472
+ };
693
473
  }
694
- };
695
-
696
- // src/utils/abort.ts
697
- var ABORT_ERROR_NAME = "AbortError";
698
- function abortError(message = "Operation aborted") {
699
- const err = new Error(message);
700
- err.name = ABORT_ERROR_NAME;
701
- return err;
702
- }
703
- function isAbortError(err) {
704
- return err instanceof Error && err.name === ABORT_ERROR_NAME;
705
- }
706
-
707
- // src/orchestrator/AgentSessionManager.ts
708
- var AgentSessionManager = class {
709
- constructor() {
710
- this.entries = /* @__PURE__ */ new Map();
711
- this.closed = false;
474
+ async execute(task) {
475
+ const { prompt, onEvent, signal, permissionMode, onPermission, onQuestion, ...options } = task;
476
+ const startup = new AbortController();
477
+ const forward = () => startup.abort();
478
+ if (signal?.aborted) startup.abort();
479
+ signal?.addEventListener("abort", forward, { once: true });
480
+ let session;
481
+ try {
482
+ session = await this.openSession({
483
+ ...options,
484
+ questionForms: Boolean(onQuestion),
485
+ signal: startup.signal
486
+ });
487
+ } finally {
488
+ signal?.removeEventListener("abort", forward);
489
+ }
490
+ try {
491
+ return await session.prompt(prompt, {
492
+ signal,
493
+ timeout: task.timeout,
494
+ onEvent,
495
+ permissionMode,
496
+ onPermission,
497
+ onQuestion
498
+ });
499
+ } finally {
500
+ await session.close();
501
+ }
712
502
  }
713
- async execute(runtime, task) {
714
- if (this.closed) throw new Error("AgentSessionManager is closed");
715
- if (this.resetting) throw new Error("AgentSessionManager is resetting");
716
- if (task.signal?.aborted) throw abortError();
717
- let entry3 = this.entries.get(task.agentId);
718
- if (entry3?.busy || entry3?.session && entry3.session.state !== "idle" && entry3.session.state !== "closed") {
719
- throw new Error(`Agent session ${task.agentId} is busy`);
720
- }
721
- if (entry3?.closing) await entry3.closing;
722
- const fingerprint = JSON.stringify([
723
- task.command,
724
- task.args,
725
- task.model,
726
- task.workDir,
727
- task.systemPrompt,
728
- task.tools,
729
- task.sessionId,
730
- task.resume,
731
- Boolean(task.onQuestion)
732
- ]);
733
- if (entry3 && (entry3.runtime !== runtime || entry3.fingerprint !== fingerprint || entry3.session?.state === "closed" || !runtime.openSession)) {
734
- entry3.busy = true;
735
- try {
736
- await this.closeEntry(entry3);
737
- this.entries.delete(task.agentId);
738
- } finally {
739
- entry3.busy = false;
740
- }
741
- entry3 = void 0;
742
- if (this.closed || this.resetting) throw abortError();
743
- }
744
- if (task.signal?.aborted) throw abortError();
745
- const openSession = runtime.openSession;
746
- if (!openSession) return runtime.execute(task);
747
- let detach;
748
- if (!entry3) {
749
- const startup = new AbortController();
750
- const forwardAbort = () => startup.abort(task.signal?.reason);
751
- task.signal?.addEventListener("abort", forwardAbort, { once: true });
752
- detach = () => task.signal?.removeEventListener("abort", forwardAbort);
753
- const created = {
754
- runtime,
755
- fingerprint,
756
- startup,
757
- busy: true,
758
- onWarning: task.onWarning,
759
- // Defer opening until the cache entry is installed, including synchronous failures.
760
- opening: Promise.resolve().then(
761
- () => openSession.call(runtime, {
762
- agentId: task.agentId,
763
- systemPrompt: task.systemPrompt,
764
- tools: task.tools,
765
- workDir: task.workDir,
766
- command: task.command,
767
- args: task.args,
768
- model: task.model,
769
- sessionId: task.sessionId,
770
- resume: task.resume,
771
- timeout: task.timeout,
772
- questionForms: Boolean(task.onQuestion),
773
- signal: startup.signal,
774
- onWarning: (message) => created.onWarning?.(message)
775
- })
776
- ).then((session) => {
777
- created.session = session;
778
- return session;
779
- })
780
- };
781
- entry3 = created;
782
- this.entries.set(task.agentId, entry3);
783
- } else {
784
- entry3.busy = true;
785
- entry3.onWarning = task.onWarning;
503
+ async openSession(options) {
504
+ if (options.signal?.aborted) throw abortError();
505
+ if (options.resume === "fork") {
506
+ throw new PermanentError("ACP does not support forked sessions");
786
507
  }
508
+ const defaultTimeout = timeoutMs(options.timeout);
509
+ const questionForms = options.questionForms === true;
510
+ let startupReject;
511
+ const startupFailure = new Promise((_, reject) => {
512
+ startupReject = reject;
513
+ });
514
+ let failSession;
515
+ const failStartup = (error) => {
516
+ startupReject(error);
517
+ failSession?.(error);
518
+ };
519
+ const onSessionAbort = () => failStartup(abortError());
520
+ options.signal?.addEventListener("abort", onSessionAbort, { once: true });
521
+ const startupTimer = setTimeout(
522
+ () => failStartup(new Error(`acp startup timed out (${defaultTimeout}ms)`)),
523
+ defaultTimeout
524
+ );
525
+ let cleanup;
787
526
  try {
788
- const session = await entry3.opening;
789
- detach?.();
790
- detach = void 0;
791
- if (entry3.startup.signal.aborted || this.closed || this.resetting) {
792
- await this.closeEntry(entry3);
793
- throw abortError();
794
- }
795
- if (session.state !== "idle") throw new Error(`Agent session ${task.agentId} is busy`);
796
- return await session.prompt(task.prompt, {
797
- signal: task.signal,
798
- timeout: task.timeout,
799
- onEvent: task.onEvent,
800
- permissionMode: task.permissionMode,
801
- onPermission: task.onPermission,
802
- onQuestion: task.onQuestion
527
+ const acp = await Promise.race([import("@agentclientprotocol/sdk"), startupFailure]);
528
+ if (options.signal?.aborted) throw abortError();
529
+ const command = options.command ?? DEFAULT_COMMAND2;
530
+ const spec = specForCommand(command);
531
+ const meta = spec?.meta?.({ ...options, prompt: "", timeout: defaultTimeout });
532
+ const child = spawn(resolveExecutable(command) ?? command, options.args ?? DEFAULT_ARGS, {
533
+ cwd: options.workDir,
534
+ env: process.env,
535
+ detached: true
803
536
  });
804
- } finally {
805
- detach?.();
806
- entry3.onWarning = void 0;
807
- try {
808
- if (entry3.session?.state === "closed") {
809
- await this.closeEntry(entry3);
810
- if (this.entries.get(task.agentId) === entry3) this.entries.delete(task.agentId);
811
- } else if (!entry3.session) {
812
- if (this.entries.get(task.agentId) === entry3) this.entries.delete(task.agentId);
813
- }
814
- } finally {
815
- entry3.busy = false;
816
- }
817
- }
818
- }
819
- /**
820
- * Deliver a message into every session that is running a turn right now.
821
- *
822
- * Only `running` sessions are candidates, and that is the whole safety
823
- * argument: a session between turns has nothing to inject into, and asking a
824
- * provider to steer an idle session makes it *start* a turn that this manager
825
- * never scheduled — one whose output belongs to no turn and which nothing
826
- * would ever settle. Sessions that are idle are therefore not reported as
827
- * failures but simply absent, and the caller sees an empty list.
828
- *
829
- * One agent failing never stops the others: each report stands alone, because
830
- * the caller has to be able to say "architect took it, qa did not" rather than
831
- * "steering failed".
832
- */
833
- async supplement(text) {
834
- if (this.closed) return [];
835
- const targets = [...this.entries.entries()].filter(
836
- ([, entry3]) => entry3.session?.state === "running"
837
- );
838
- return await Promise.all(
839
- targets.map(async ([agentId, entry3]) => {
840
- const session = entry3.session;
841
- if (!session) return { agentId, status: "idle" };
842
- if (!session.capabilities.supplement || !session.supplement) {
843
- return { agentId, status: "unsupported" };
537
+ let state = "idle";
538
+ let sessionId = "";
539
+ let steeringSupported = false;
540
+ let active;
541
+ let childClosed = false;
542
+ let terminalError;
543
+ let errorOutput = "";
544
+ let escalation;
545
+ let acknowledgement;
546
+ let closePromise;
547
+ let closeResolve;
548
+ let closeReject;
549
+ let connection;
550
+ const argsSurfaced = /* @__PURE__ */ new Set();
551
+ const toolNames = /* @__PURE__ */ new Map();
552
+ const killTree = (signal) => {
553
+ if (child.pid !== void 0) {
554
+ try {
555
+ process.kill(-child.pid, signal);
556
+ return;
557
+ } catch {
558
+ }
844
559
  }
845
560
  try {
846
- return { agentId, status: (await session.supplement(text)).status };
847
- } catch (error) {
848
- return {
849
- agentId,
850
- status: "error",
851
- error: error instanceof Error ? error.message : String(error)
852
- };
561
+ child.kill(signal);
562
+ } catch {
853
563
  }
854
- })
855
- );
856
- }
857
- /** Closes all sessions and permits a fresh conversation after cleanup completes. */
858
- reset() {
859
- if (this.closing) return this.closing;
860
- if (this.resetting) return this.resetting;
861
- this.resetting = this.drain().finally(() => {
862
- this.resetting = void 0;
863
- });
864
- return this.resetting;
865
- }
866
- /** Terminal, idempotent cleanup barrier. No new executions may start. */
867
- close() {
868
- if (this.closing) return this.closing;
869
- this.closed = true;
870
- this.closing = this.resetting ?? this.drain();
871
- return this.closing;
872
- }
873
- async drain() {
874
- const entries = [...this.entries.entries()];
875
- for (const [, entry3] of entries) entry3.startup.abort();
876
- const results = await Promise.allSettled(
877
- entries.map(async ([id, entry3]) => {
878
- await this.closeEntry(entry3);
879
- if (this.entries.get(id) === entry3) this.entries.delete(id);
880
- })
881
- );
882
- const errors = results.flatMap(
883
- (result) => result.status === "rejected" ? [result.reason] : []
884
- );
885
- if (errors.length === 1) throw errors[0];
886
- if (errors.length > 1) throw new AggregateError(errors, "Agent session cleanup failed");
887
- }
888
- closeEntry(entry3) {
889
- if (!entry3.closing) {
890
- entry3.closing = (async () => {
891
- let session;
892
- try {
893
- session = await entry3.opening;
894
- } catch (error) {
895
- if (isAbortError(error)) return;
896
- throw error;
897
- }
898
- await session.close();
899
- })();
900
- }
901
- return entry3.closing;
902
- }
903
- };
904
-
905
- // src/orchestrator/Orchestrator.ts
906
- import * as fs4 from "fs";
907
- import * as path5 from "path";
908
-
909
- // src/providers/catalog.ts
910
- import * as path from "path";
911
- function normalizeCommandKey(command) {
912
- return path.basename(command).toLowerCase().replace(/\.(cmd|exe|bat)$/i, "");
913
- }
914
- var PROVIDERS = [
915
- {
916
- id: "opencode",
917
- label: "OpenCode",
918
- command: "opencode",
919
- args: ["acp"],
920
- tools: false,
921
- modelSelection: "config-option",
922
- models: [
923
- { id: "opencode/big-pickle", label: "Big Pickle", tier: "balanced", defaultForTier: true },
924
- { id: "opencode/exo-free", label: "Exo", tier: "strong", defaultForTier: true },
925
- { id: "opencode/ling-3.0-flash-fin-free", label: "Ling 3.0 Flash", tier: "fast" },
926
- {
927
- id: "opencode/ling-3.1-flash-free",
928
- label: "Ling 3.1 Flash",
929
- tier: "fast",
930
- defaultForTier: true
931
- },
932
- { id: "opencode/longcat-2.5-preview-free", label: "Longcat 2.5 Preview", tier: "balanced" },
933
- { id: "opencode/mimo-v2.6-flash-free", label: "Mimo 2.6 Flash", tier: "fast" },
934
- { id: "opencode/muse-spark-1.3-contributor-free", label: "Muse Spark 1.3", tier: "fast" },
935
- { id: "opencode/nemotron-3-ultra-free", label: "Nemotron 3 Ultra", tier: "strong" },
936
- { id: "opencode/nemotron-3.5-lightning-free", label: "Nemotron 3.5 Lightning", tier: "fast" },
937
- { id: "opencode/space-bunny-free", label: "Space Bunny", tier: "fast" },
938
- { id: "opencode/step-5-preview-free", label: "Step 5 Preview", tier: "strong" }
939
- ],
940
- defaultModel: "opencode/big-pickle",
941
- install: { hint: "npm install -g opencode" },
942
- auth: { kind: "none", hint: "" }
943
- },
944
- {
945
- id: "claude",
946
- label: "Claude",
947
- command: "claude-agent-acp",
948
- args: [],
949
- tools: true,
950
- modelSelection: "config-option",
951
- meta: (task) => {
952
- const meta = {};
953
- if (task.systemPrompt) meta.systemPrompt = task.systemPrompt;
954
- meta.claudeCode = { options: { tools: task.tools } };
955
- return meta;
956
- },
957
- models: [
958
- { id: "default", label: "Default", tier: "balanced" },
959
- { id: "opus", label: "Opus", tier: "strong", defaultForTier: true },
960
- { id: "fable", label: "Fable", tier: "balanced" },
961
- { id: "sonnet", label: "Sonnet", tier: "balanced", defaultForTier: true },
962
- { id: "haiku", label: "Haiku", tier: "fast", defaultForTier: true }
963
- ],
964
- defaultModel: "sonnet",
965
- install: {
966
- hint: "multiclaw bundles the ACP bridge \u2014 install the Claude Code CLI (`claude`) and run `claude` to log in"
967
- },
968
- auth: { kind: "ambient", hint: "run `claude` to log in" }
969
- },
970
- {
971
- id: "codex",
972
- label: "Codex",
973
- command: "codex-acp",
974
- args: [],
975
- tools: false,
976
- modelSelection: "config-option",
977
- meta: (task) => task.systemPrompt ? { jetbrains: { air: { customInstructions: task.systemPrompt } } } : void 0,
978
- // Placeholders — real ids require auth to enumerate.
979
- models: [
980
- { id: "gpt-5-codex", label: "GPT-5 Codex", tier: "strong", defaultForTier: true },
981
- { id: "gpt-5", label: "GPT-5", tier: "balanced", defaultForTier: true },
982
- { id: "gpt-5-mini", label: "GPT-5 Mini", tier: "fast", defaultForTier: true }
983
- ],
984
- defaultModel: "gpt-5",
985
- install: {
986
- hint: "multiclaw bundles the ACP bridge \u2014 install the Codex CLI (`codex`) and run `codex login`"
987
- },
988
- auth: { kind: "api-key", hint: "set OPENAI_API_KEY or run `codex login`" }
989
- },
990
- {
991
- id: "cursor",
992
- label: "Cursor",
993
- command: "cursor-agent",
994
- aliases: ["agent"],
995
- args: ["acp"],
996
- tools: false,
997
- modelSelection: "config-option",
998
- // _meta support unverified — falls back to prompt prefix until confirmed.
999
- meta: void 0,
1000
- // Placeholders — real ids require Cursor CLI + auth to enumerate.
1001
- models: [
1002
- { id: "cursor-pro", label: "Cursor Pro", tier: "strong", defaultForTier: true },
1003
- { id: "cursor-fast", label: "Cursor Fast", tier: "fast", defaultForTier: true }
1004
- ],
1005
- defaultModel: "cursor-pro",
1006
- install: {
1007
- hint: "curl https://cursor.com/install | bash",
1008
- url: "https://cursor.com/docs/cli/acp"
1009
- },
1010
- auth: { kind: "login", hint: "run `agent login` first (or set CURSOR_API_KEY)" },
1011
- confirm: (v) => /cursor/i.test(v)
1012
- }
1013
- ];
1014
- var byProviderId = /* @__PURE__ */ new Map();
1015
- var byCommand = /* @__PURE__ */ new Map();
1016
- for (const spec of PROVIDERS) {
1017
- byProviderId.set(spec.id, spec);
1018
- byCommand.set(normalizeCommandKey(spec.command), spec);
1019
- if (spec.aliases) {
1020
- for (const alias of spec.aliases) {
1021
- byCommand.set(normalizeCommandKey(alias), spec);
1022
- }
1023
- }
1024
- }
1025
- function specForProvider(id) {
1026
- return byProviderId.get(id);
1027
- }
1028
- function specForCommand(command) {
1029
- return byCommand.get(normalizeCommandKey(command));
1030
- }
1031
- function providerIds() {
1032
- return [...byProviderId.keys()];
1033
- }
1034
- function providerCommands() {
1035
- return [...byCommand.keys()];
1036
- }
1037
- function tierModel(spec, tier) {
1038
- const m = spec.models.find((m2) => m2.tier === tier && m2.defaultForTier);
1039
- return m?.id ?? spec.models.find((m2) => m2.tier === tier)?.id;
1040
- }
1041
-
1042
- // src/providers/resolve.ts
1043
- var DEFAULT_COMMAND = "opencode";
1044
- var DEFAULT_PROVIDER = "opencode";
1045
- function resolveProvider(agent, config) {
1046
- return agent.provider ?? specForCommand(agent.command ?? "")?.id ?? config.defaults?.provider ?? specForCommand(DEFAULT_COMMAND)?.id ?? DEFAULT_PROVIDER;
1047
- }
1048
- function resolveCommand(agent, config) {
1049
- return agent.command ?? config.defaults?.command ?? specForProvider(resolveProvider(agent, config))?.command ?? DEFAULT_COMMAND;
1050
- }
1051
- function resolveArgs(agent, config) {
1052
- if (agent.args) return agent.args;
1053
- const command = agent.command ?? config.defaults?.command;
1054
- if (command) return specForCommand(command)?.args;
1055
- return specForProvider(resolveProvider(agent, config))?.args;
1056
- }
1057
- function resolveModel(agent, config) {
1058
- if (agent.model) return agent.model;
1059
- const provider = resolveProvider(agent, config);
1060
- const spec = specForProvider(provider);
1061
- const fromModels = agent.models?.[provider] ?? agent.models?.acp;
1062
- if (fromModels) return fromModels;
1063
- if (agent.modelTier && spec) {
1064
- const fromTier = tierModel(spec, agent.modelTier);
1065
- if (fromTier) return fromTier;
1066
- }
1067
- if (config.defaults?.model) return config.defaults.model;
1068
- if (spec) return spec.defaultModel;
1069
- return void 0;
1070
- }
1071
- function resolveAgentRuntime(agent, config) {
1072
- const provider = resolveProvider(agent, config);
1073
- const spec = specForProvider(provider);
1074
- return {
1075
- provider,
1076
- command: resolveCommand(agent, config),
1077
- model: resolveModel(agent, config),
1078
- spec
1079
- };
1080
- }
1081
-
1082
- // src/utils/conversation.ts
1083
- var MAX_CONVERSATION_TURNS = 6;
1084
- var MAX_CONVERSATION_CHARS = 4e3;
1085
- var MAX_ENTRY_CHARS = 600;
1086
- var ELLIPSIS = "\u2026";
1087
- function clip(text, max) {
1088
- const trimmed = text.trim();
1089
- if (trimmed.length <= max) return trimmed;
1090
- return `${trimmed.slice(0, Math.max(0, max - 1)).trimEnd()}${ELLIPSIS}`;
1091
- }
1092
- function entry(turn, index) {
1093
- const lines = [`${index}. user: ${clip(turn.requirement, MAX_ENTRY_CHARS)}`];
1094
- if (turn.reply) {
1095
- const verb = turn.reply.mode === "ask" ? "asked" : "answered";
1096
- lines.push(` you ${verb}: ${clip(turn.reply.message, MAX_ENTRY_CHARS)}`);
1097
- }
1098
- return lines.join("\n");
1099
- }
1100
- function renderConversation(history) {
1101
- if (!history || history.length === 0) return "";
1102
- const recent = history.slice(-MAX_CONVERSATION_TURNS);
1103
- const first = history.length - recent.length;
1104
- const entries = recent.map((turn, i) => entry(turn, first + i + 1));
1105
- while (entries.length > 1 && entries.join("\n").length > MAX_CONVERSATION_CHARS) {
1106
- entries.shift();
1107
- }
1108
- const body = clip(entries.join("\n"), MAX_CONVERSATION_CHARS);
1109
- return `
1110
- ## Conversation so far
1111
-
1112
- Earlier turns of this session, oldest first:
1113
-
1114
- ${body}
1115
- `;
1116
- }
1117
-
1118
- // src/utils/json.ts
1119
- function extractJsonObjects(text) {
1120
- const objects = [];
1121
- let searchFrom = 0;
1122
- while (searchFrom < text.length) {
1123
- const start = text.indexOf("{", searchFrom);
1124
- if (start === -1) break;
1125
- const end = findMatchingBrace(text, start);
1126
- if (end !== -1) {
1127
- try {
1128
- objects.push(JSON.parse(text.slice(start, end + 1)));
1129
- searchFrom = end + 1;
1130
- continue;
1131
- } catch {
1132
- }
1133
- }
1134
- searchFrom = start + 1;
1135
- }
1136
- return objects;
1137
- }
1138
- function findMatchingBrace(text, start) {
1139
- let depth = 0;
1140
- let inString = false;
1141
- let escaped = false;
1142
- for (let i = start; i < text.length; i++) {
1143
- const ch = text[i];
1144
- if (inString) {
1145
- if (escaped) escaped = false;
1146
- else if (ch === "\\") escaped = true;
1147
- else if (ch === '"') inString = false;
1148
- continue;
1149
- }
1150
- if (ch === '"') inString = true;
1151
- else if (ch === "{") depth++;
1152
- else if (ch === "}") {
1153
- depth--;
1154
- if (depth === 0) return i;
1155
- }
1156
- }
1157
- return -1;
1158
- }
1159
-
1160
- // src/utils/leaderDecision.ts
1161
- function parseLeaderDecision(text) {
1162
- for (const value of extractJsonObjects(text)) {
1163
- const decision = asDecision(value);
1164
- if (decision) return decision;
1165
- }
1166
- return void 0;
1167
- }
1168
- function asDecision(value) {
1169
- if (typeof value !== "object" || value === null) return void 0;
1170
- const record = value;
1171
- const mode = record.mode;
1172
- if (mode === "reply" || mode === "ask") {
1173
- const message = typeof record.message === "string" ? record.message.trim() : "";
1174
- return message ? { mode, message } : void 0;
1175
- }
1176
- if (mode === "run" || mode === void 0) {
1177
- const run = record.run;
1178
- if (!Array.isArray(run) || !run.every((id) => typeof id === "string")) return void 0;
1179
- const reason = typeof record.reason === "string" ? record.reason.trim() : "";
1180
- const requirement = typeof record.requirement === "string" ? record.requirement.trim() : "";
1181
- if ("requirement" in record && !requirement) return void 0;
1182
- return {
1183
- mode: "run",
1184
- run,
1185
- ...reason ? { reason } : {},
1186
- ...requirement ? { requirement } : {}
1187
- };
1188
- }
1189
- return void 0;
1190
- }
1191
-
1192
- // src/utils/upstream.ts
1193
- var MAX_UPSTREAM_ENTRY_CHARS = 600;
1194
- var MAX_UPSTREAM_CHARS = 4e3;
1195
- var ELLIPSIS2 = "\u2026";
1196
- var HEADER = "\n## What upstream produced\n\n";
1197
- var TRAILER = "\n";
1198
- function block(entries) {
1199
- return `${HEADER}${entries.join("\n")}${TRAILER}`;
1200
- }
1201
- function compact(text, max) {
1202
- const trimmed = text.trim();
1203
- if (trimmed.length <= max) return trimmed;
1204
- const marker = (count) => `${ELLIPSIS2} (${count} characters elided) ${ELLIPSIS2}`;
1205
- const reserved = marker(trimmed.length).length;
1206
- const keep = Math.max(0, max - reserved);
1207
- const head = Math.ceil(keep / 2);
1208
- const tail = keep - head;
1209
- const elided = trimmed.length - keep;
1210
- return `${trimmed.slice(0, head)}${marker(elided)}${trimmed.slice(trimmed.length - tail)}`;
1211
- }
1212
- function entry2(output) {
1213
- const label = `- ${output.name} (${output.agentId}):
1214
- `;
1215
- const budget = MAX_UPSTREAM_ENTRY_CHARS - label.length;
1216
- let body = compact(output.output, budget);
1217
- const newlines = body.length - body.replace(/\n/g, "").length;
1218
- if (label.length + body.length + 2 * newlines > MAX_UPSTREAM_ENTRY_CHARS) {
1219
- body = compact(output.output, budget - 2 * newlines);
1220
- }
1221
- return `${label}${body.replace(/\n/g, "\n ")}`;
1222
- }
1223
- function renderUpstreamOutputs(outputs) {
1224
- if (outputs.length === 0) return "";
1225
- const entries = outputs.map(entry2);
1226
- while (entries.length > 1 && block(entries).length > MAX_UPSTREAM_CHARS) {
1227
- entries.shift();
1228
- }
1229
- return block(entries);
1230
- }
1231
-
1232
- // src/orchestrator/AgentRunner.ts
1233
- import * as fs3 from "fs";
1234
- import * as path4 from "path";
1235
-
1236
- // src/runtime/AcpRuntime.ts
1237
- import { spawn } from "child_process";
1238
- import { randomUUID } from "crypto";
1239
- import { Readable, Writable } from "stream";
1240
- import { StringDecoder } from "string_decoder";
1241
-
1242
- // src/providers/bridge.ts
1243
- import * as fs from "fs";
1244
- import { createRequire } from "module";
1245
- import * as path2 from "path";
1246
- var BRIDGE_PACKAGES = {
1247
- "claude-agent-acp": "@agentclientprotocol/claude-agent-acp",
1248
- "codex-acp": "@agentclientprotocol/codex-acp"
1249
- };
1250
- function resolvesOnPath(command) {
1251
- const dirs = (process.env.PATH ?? "").split(path2.delimiter).filter(Boolean);
1252
- const exts = (process.env.PATHEXT ?? "").split(";").filter(Boolean);
1253
- const suffixes = exts.length > 0 ? exts : [""];
1254
- for (const dir of dirs) {
1255
- for (const ext of suffixes) {
1256
- try {
1257
- fs.accessSync(path2.join(dir, command + ext), fs.constants.X_OK);
1258
- return true;
1259
- } catch {
1260
- }
1261
- }
1262
- }
1263
- return false;
1264
- }
1265
- function resolveBridgeBinary(command) {
1266
- const pkg = BRIDGE_PACKAGES[command];
1267
- if (!pkg) return null;
1268
- try {
1269
- const req = createRequire(import.meta.url);
1270
- const pkgJsonPath = req.resolve(`${pkg}/package.json`);
1271
- const bin = JSON.parse(fs.readFileSync(pkgJsonPath, "utf8")).bin;
1272
- const binRel = typeof bin === "string" ? bin : bin?.[command] ?? Object.values(bin)[0];
1273
- if (!binRel) return null;
1274
- return path2.join(path2.dirname(pkgJsonPath), binRel);
1275
- } catch {
1276
- return null;
1277
- }
1278
- }
1279
- function resolveExecutable(command) {
1280
- if (resolvesOnPath(command)) return command;
1281
- return resolveBridgeBinary(command);
1282
- }
1283
-
1284
- // src/utils/errors.ts
1285
- var PermanentError = class extends Error {
1286
- constructor(message) {
1287
- super(message);
1288
- this.name = "PermanentError";
1289
- }
1290
- };
1291
- function isPermanent(err) {
1292
- return err instanceof PermanentError;
1293
- }
1294
-
1295
- // src/runtime/RuntimeBase.ts
1296
- var RuntimeBase = class {
1297
- };
1298
-
1299
- // src/runtime/AcpRuntime.ts
1300
- var discoveredModels = /* @__PURE__ */ new Map();
1301
- var KILL_ESCALATION_MS = 3e3;
1302
- var CANCEL_GRACE_MS = 2e3;
1303
- var CLEANUP_ACK_MS = 3e3;
1304
- var STEER_ACK_MS = 15e3;
1305
- var DEFAULT_TIMEOUT_MS = 6e5;
1306
- var DEFAULT_COMMAND2 = "opencode";
1307
- var DEFAULT_ARGS = ["acp"];
1308
- var STEER_METHOD = "_session/steering";
1309
- function advertisesSteering(init) {
1310
- const steering = init._meta?.steering;
1311
- return isRecord(steering) && steering.supported === true;
1312
- }
1313
- var BASE_CAPABILITIES = {
1314
- streaming: true,
1315
- sessions: true,
1316
- resume: true,
1317
- permissions: true,
1318
- tools: true,
1319
- models: false,
1320
- images: false,
1321
- usage: true,
1322
- cost: true,
1323
- sandbox: false
1324
- };
1325
- function isRecord(value) {
1326
- return typeof value === "object" && value !== null && !Array.isArray(value);
1327
- }
1328
- function textOf(content) {
1329
- if (isRecord(content) && content.type === "text" && typeof content.text === "string") {
1330
- return content.text;
1331
- }
1332
- return void 0;
1333
- }
1334
- function stringifyOutput(value) {
1335
- if (typeof value === "string") return value;
1336
- if (value === void 0 || value === null) return "";
1337
- return JSON.stringify(value);
1338
- }
1339
- function mapStopReason(reason) {
1340
- switch (reason) {
1341
- case "end_turn":
1342
- return "success";
1343
- case "cancelled":
1344
- return "cancelled";
1345
- case "max_tokens":
1346
- case "max_turn_requests":
1347
- return "max_turns";
1348
- default:
1349
- return "error";
1350
- }
1351
- }
1352
- var KIND_TO_TOOLS = {
1353
- read: ["Read"],
1354
- edit: ["Edit", "Write"],
1355
- execute: ["Bash"],
1356
- search: ["Grep", "Glob"],
1357
- fetch: ["WebFetch"]
1358
- };
1359
- function toolPermitted(params, tools) {
1360
- const allowed = new Set(tools.map((tool) => tool.toLowerCase()));
1361
- const name = params.toolCall.name ?? void 0;
1362
- return name !== void 0 ? allowed.has(name.toLowerCase()) : (KIND_TO_TOOLS[params.toolCall.kind ?? ""] ?? []).some(
1363
- (tool) => allowed.has(tool.toLowerCase())
1364
- );
1365
- }
1366
- function decidePermission(params, tools, sessionId) {
1367
- if (sessionId !== void 0 && params.sessionId !== sessionId) {
1368
- return { response: { outcome: { outcome: "cancelled" } } };
1369
- }
1370
- const name = params.toolCall.name ?? void 0;
1371
- const kind = params.toolCall.kind ?? void 0;
1372
- const approved = toolPermitted(params, tools);
1373
- const option = params.options.find(
1374
- (o) => approved ? o.kind === "allow_once" : o.kind === "reject_once"
1375
- );
1376
- const response = option ? { outcome: { outcome: "selected", optionId: option.optionId } } : { outcome: { outcome: "cancelled" } };
1377
- if (approved) return { response };
1378
- return {
1379
- response,
1380
- rejected: {
1381
- toolCallId: params.toolCall.toolCallId,
1382
- name,
1383
- kind,
1384
- title: params.toolCall.title ?? void 0
1385
- }
1386
- };
1387
- }
1388
- var FORM_ANNOTATIONS = ["title", "description", "default", "_meta"];
1389
- function knownFormKeys(value, keys) {
1390
- return Object.keys(value).every((key) => keys.includes(key) || FORM_ANNOTATIONS.includes(key));
1391
- }
1392
- function validFormBound(value, integer = false) {
1393
- return value == null || typeof value === "number" && Number.isFinite(value) && (!integer || Number.isInteger(value) && value >= 0);
1394
- }
1395
- function titledChoices(value) {
1396
- return Array.isArray(value) && value.length > 0 && value.every(
1397
- (option) => isRecord(option) && knownFormKeys(option, ["const"]) && typeof option.const === "string"
1398
- );
1399
- }
1400
- function supportedQuestionSchema(schema) {
1401
- if (!isRecord(schema) || schema.type !== void 0 && schema.type !== "object" || !knownFormKeys(schema, ["type", "properties", "required"]))
1402
- return false;
1403
- const properties = schema.properties ?? {};
1404
- if (!isRecord(properties)) return false;
1405
- if (schema.required != null && (!Array.isArray(schema.required) || !schema.required.every(
1406
- (key) => typeof key === "string" && Object.getOwnPropertyDescriptor(properties, key) !== void 0
1407
- )))
1408
- return false;
1409
- return Object.values(properties).every((field) => {
1410
- if (!isRecord(field)) return false;
1411
- if (field.type === "string") {
1412
- return knownFormKeys(field, ["type", "enum", "oneOf", "minLength", "maxLength"]) && validFormBound(field.minLength, true) && validFormBound(field.maxLength, true) && (field.enum == null || Array.isArray(field.enum) && field.enum.length > 0 && field.enum.every((value) => typeof value === "string")) && (field.oneOf == null || titledChoices(field.oneOf));
1413
- }
1414
- if (field.type === "boolean") return knownFormKeys(field, ["type"]);
1415
- if (field.type === "number" || field.type === "integer") {
1416
- return knownFormKeys(field, ["type", "minimum", "maximum"]) && validFormBound(field.minimum) && validFormBound(field.maximum);
1417
- }
1418
- if (field.type !== "array" || !isRecord(field.items) || !knownFormKeys(field, ["type", "items", "minItems", "maxItems"]) || !validFormBound(field.minItems, true) || !validFormBound(field.maxItems, true))
1419
- return false;
1420
- return knownFormKeys(field.items, ["type", "enum"]) && field.items.type === "string" && Array.isArray(field.items.enum) && field.items.enum.length > 0 && field.items.enum.every((value) => typeof value === "string") || knownFormKeys(field.items, ["anyOf"]) && field.items.type === void 0 && titledChoices(field.items.anyOf);
1421
- });
1422
- }
1423
- function validateRuntimeQuestionContent(schema, content) {
1424
- if (!supportedQuestionSchema(schema) || !isRecord(content)) return false;
1425
- if (Object.getOwnPropertySymbols(content).length > 0 || Object.getOwnPropertyNames(content).some((key) => {
1426
- const descriptor = Object.getOwnPropertyDescriptor(content, key);
1427
- return !descriptor?.enumerable || !("value" in descriptor);
1428
- }))
1429
- return false;
1430
- const properties = schema.properties ?? {};
1431
- if ((schema.required ?? []).some(
1432
- (key) => Object.getOwnPropertyDescriptor(content, key) === void 0
1433
- ))
1434
- return false;
1435
- return Object.entries(content).every(([key, value]) => {
1436
- if (Object.getOwnPropertyDescriptor(properties, key) === void 0) return false;
1437
- const field = properties[key];
1438
- if (field.type === "boolean") return typeof value === "boolean";
1439
- if (field.type === "number" || field.type === "integer") {
1440
- return typeof value === "number" && Number.isFinite(value) && (field.type !== "integer" || Number.isInteger(value)) && (typeof field.minimum !== "number" || value >= field.minimum) && (typeof field.maximum !== "number" || value <= field.maximum);
1441
- }
1442
- if (field.type === "string") {
1443
- return typeof value === "string" && (typeof field.minLength !== "number" || [...value].length >= field.minLength) && (typeof field.maxLength !== "number" || [...value].length <= field.maxLength) && (!Array.isArray(field.enum) || field.enum.includes(value)) && (!Array.isArray(field.oneOf) || field.oneOf.some((option) => isRecord(option) && option.const === value));
1444
- }
1445
- const items = field.items;
1446
- const choices = Array.isArray(items.enum) ? items.enum : items.anyOf.map((option) => option.const);
1447
- return Array.isArray(value) && value.every((item) => typeof item === "string" && choices.includes(item)) && new Set(value).size === value.length && (typeof field.minItems !== "number" || value.length >= field.minItems) && (typeof field.maxItems !== "number" || value.length <= field.maxItems);
1448
- });
1449
- }
1450
- function withAuthHint(acp, err) {
1451
- const error = err instanceof Error ? err : new Error(String(err));
1452
- if (error instanceof acp.RequestError && error.code === acp.RequestError.authRequired().code) {
1453
- return new Error(`${error.message} \u2014 run \`claude\` to log in`);
1454
- }
1455
- return error;
1456
- }
1457
- function errorMessage(err) {
1458
- return err instanceof Error ? err.message : String(err);
1459
- }
1460
- function timeoutMs(value) {
1461
- const timeout = value ?? DEFAULT_TIMEOUT_MS;
1462
- if (!Number.isFinite(timeout) || timeout < 0 || timeout > 2147483647) {
1463
- throw new PermanentError("ACP timeout must be a finite non-negative timer duration");
1464
- }
1465
- return timeout;
1466
- }
1467
- var AcpRuntime = class extends RuntimeBase {
1468
- constructor() {
1469
- super(...arguments);
1470
- this.name = "acp";
1471
- }
1472
- async describe(options) {
1473
- const command = options?.command ?? DEFAULT_COMMAND2;
1474
- return {
1475
- name: this.name,
1476
- available: resolveExecutable(command) !== null,
1477
- capabilities: {
1478
- ...BASE_CAPABILITIES,
1479
- tools: specForCommand(command)?.tools ?? false,
1480
- models: specForCommand(command)?.modelSelection === "config-option"
1481
- }
1482
- };
1483
- }
1484
- async execute(task) {
1485
- const { prompt, onEvent, signal, permissionMode, onPermission, onQuestion, ...options } = task;
1486
- const startup = new AbortController();
1487
- const forward = () => startup.abort();
1488
- if (signal?.aborted) startup.abort();
1489
- signal?.addEventListener("abort", forward, { once: true });
1490
- let session;
1491
- try {
1492
- session = await this.openSession({
1493
- ...options,
1494
- questionForms: Boolean(onQuestion),
1495
- signal: startup.signal
1496
- });
1497
- } finally {
1498
- signal?.removeEventListener("abort", forward);
1499
- }
1500
- try {
1501
- return await session.prompt(prompt, {
1502
- signal,
1503
- timeout: task.timeout,
1504
- onEvent,
1505
- permissionMode,
1506
- onPermission,
1507
- onQuestion
1508
- });
1509
- } finally {
1510
- await session.close();
1511
- }
1512
- }
1513
- async openSession(options) {
1514
- if (options.signal?.aborted) throw abortError();
1515
- if (options.resume === "fork") {
1516
- throw new PermanentError("ACP does not support forked sessions");
1517
- }
1518
- const defaultTimeout = timeoutMs(options.timeout);
1519
- const questionForms = options.questionForms === true;
1520
- let startupReject;
1521
- const startupFailure = new Promise((_, reject) => {
1522
- startupReject = reject;
1523
- });
1524
- let failSession;
1525
- const failStartup = (error) => {
1526
- startupReject(error);
1527
- failSession?.(error);
1528
- };
1529
- const onSessionAbort = () => failStartup(abortError());
1530
- options.signal?.addEventListener("abort", onSessionAbort, { once: true });
1531
- const startupTimer = setTimeout(
1532
- () => failStartup(new Error(`acp startup timed out (${defaultTimeout}ms)`)),
1533
- defaultTimeout
1534
- );
1535
- let cleanup;
1536
- try {
1537
- const acp = await Promise.race([import("@agentclientprotocol/sdk"), startupFailure]);
1538
- if (options.signal?.aborted) throw abortError();
1539
- const command = options.command ?? DEFAULT_COMMAND2;
1540
- const spec = specForCommand(command);
1541
- const meta = spec?.meta?.({ ...options, prompt: "", timeout: defaultTimeout });
1542
- const child = spawn(resolveExecutable(command) ?? command, options.args ?? DEFAULT_ARGS, {
1543
- cwd: options.workDir,
1544
- env: process.env,
1545
- detached: true
1546
- });
1547
- let state = "idle";
1548
- let sessionId = "";
1549
- let steeringSupported = false;
1550
- let active;
1551
- let childClosed = false;
1552
- let terminalError;
1553
- let errorOutput = "";
1554
- let escalation;
1555
- let acknowledgement;
1556
- let closePromise;
1557
- let closeResolve;
1558
- let closeReject;
1559
- let connection;
1560
- const killTree = (signal) => {
1561
- if (child.pid !== void 0) {
1562
- try {
1563
- process.kill(-child.pid, signal);
1564
- return;
1565
- } catch {
1566
- }
1567
- }
1568
- try {
1569
- child.kill(signal);
1570
- } catch {
1571
- }
1572
- };
1573
- const emitForTurn = (turn, event) => {
1574
- turn.options.onEvent?.({
1575
- ...event,
1576
- runId: turn.runId,
1577
- agentId: options.agentId,
1578
- seq: turn.seq++
1579
- });
1580
- };
1581
- const emit = (event) => {
1582
- if (active) emitForTurn(active, event);
1583
- };
1584
- const settleTurn = (turn, output, error) => {
1585
- if (active !== turn) return;
1586
- turn.decisions.abort();
1587
- if (turn.timer) clearTimeout(turn.timer);
1588
- if (turn.cancelTimer) clearTimeout(turn.cancelTimer);
1589
- if (turn.onAbort) turn.options.signal?.removeEventListener("abort", turn.onAbort);
1590
- active = void 0;
1591
- if (state === "running" || state === "cancelling") state = "idle";
1592
- if (error) {
1593
- if (closePromise) {
1594
- void closePromise.then(
1595
- () => turn.reject(error),
1596
- (cleanupError) => turn.reject(cleanupError)
1597
- );
1598
- } else turn.reject(error);
1599
- } else if (output) turn.resolve(output);
1600
- };
1601
- const clearCleanupTimers = () => {
1602
- if (escalation) clearTimeout(escalation);
1603
- if (acknowledgement) clearTimeout(acknowledgement);
1604
- };
1605
- const close = () => {
1606
- if (closePromise) return closePromise;
1607
- closePromise = new Promise((resolve4, reject) => {
1608
- closeResolve = resolve4;
1609
- closeReject = reject;
1610
- });
1611
- options.signal?.removeEventListener("abort", onSessionAbort);
1612
- clearTimeout(startupTimer);
1613
- state = "closing";
1614
- if (active) settleTurn(active, void 0, active.error ?? terminalError ?? abortError());
1615
- if (childClosed) {
1616
- state = "closed";
1617
- closeResolve?.();
1618
- return closePromise;
564
+ };
565
+ const emitForTurn = (turn, event) => {
566
+ turn.options.onEvent?.({
567
+ ...event,
568
+ runId: turn.runId,
569
+ agentId: options.agentId,
570
+ seq: turn.seq++
571
+ });
572
+ };
573
+ const emit = (event) => {
574
+ if (active) emitForTurn(active, event);
575
+ };
576
+ const settleTurn = (turn, output, error) => {
577
+ if (active !== turn) return;
578
+ turn.decisions.abort();
579
+ if (turn.timer) clearTimeout(turn.timer);
580
+ if (turn.cancelTimer) clearTimeout(turn.cancelTimer);
581
+ if (turn.onAbort) turn.options.signal?.removeEventListener("abort", turn.onAbort);
582
+ active = void 0;
583
+ if (state === "running" || state === "cancelling") state = "idle";
584
+ if (error) {
585
+ if (closePromise) {
586
+ void closePromise.then(
587
+ () => turn.reject(error),
588
+ (cleanupError) => turn.reject(cleanupError)
589
+ );
590
+ } else turn.reject(error);
591
+ } else if (output) turn.resolve(output);
592
+ };
593
+ const clearCleanupTimers = () => {
594
+ if (escalation) clearTimeout(escalation);
595
+ if (acknowledgement) clearTimeout(acknowledgement);
596
+ };
597
+ const close = () => {
598
+ if (closePromise) return closePromise;
599
+ closePromise = new Promise((resolve4, reject) => {
600
+ closeResolve = resolve4;
601
+ closeReject = reject;
602
+ });
603
+ options.signal?.removeEventListener("abort", onSessionAbort);
604
+ clearTimeout(startupTimer);
605
+ state = "closing";
606
+ if (active) settleTurn(active, void 0, active.error ?? terminalError ?? abortError());
607
+ if (childClosed) {
608
+ state = "closed";
609
+ closeResolve?.();
610
+ return closePromise;
1619
611
  }
1620
612
  escalation = setTimeout(() => {
1621
613
  killTree("SIGKILL");
@@ -1691,15 +683,23 @@ var AcpRuntime = class extends RuntimeBase {
1691
683
  }
1692
684
  break;
1693
685
  }
1694
- case "tool_call":
1695
- emit({
1696
- type: "tool_call",
1697
- id: update.toolCallId,
1698
- name: update.name ?? update.title,
1699
- input: update.rawInput
1700
- });
686
+ case "tool_call": {
687
+ const name = update.name ?? update.title;
688
+ toolNames.set(update.toolCallId, name);
689
+ if (hasToolArgs(update.rawInput)) argsSurfaced.add(update.toolCallId);
690
+ emit({ type: "tool_call", id: update.toolCallId, name, input: update.rawInput });
1701
691
  break;
1702
- case "tool_call_update":
692
+ }
693
+ case "tool_call_update": {
694
+ if (!argsSurfaced.has(update.toolCallId) && hasToolArgs(update.rawInput)) {
695
+ argsSurfaced.add(update.toolCallId);
696
+ emit({
697
+ type: "tool_call",
698
+ id: update.toolCallId,
699
+ name: update.name ?? toolNames.get(update.toolCallId) ?? update.title ?? "",
700
+ input: update.rawInput
701
+ });
702
+ }
1703
703
  emit({
1704
704
  type: "tool_result",
1705
705
  id: update.toolCallId,
@@ -1707,6 +707,7 @@ var AcpRuntime = class extends RuntimeBase {
1707
707
  isError: update.status === "failed"
1708
708
  });
1709
709
  break;
710
+ }
1710
711
  case "plan":
1711
712
  emit({ type: "plan", entries: update.entries.map((entry3) => entry3.content) });
1712
713
  break;
@@ -1741,22 +742,26 @@ var AcpRuntime = class extends RuntimeBase {
1741
742
  if (state !== "running" || !turn || params.sessionId !== sessionId || context.signal.aborted)
1742
743
  return cancelled;
1743
744
  const mode = turn.options.permissionMode ?? "auto";
1744
- const { response, rejected } = decidePermission(params, options.tools, sessionId);
1745
- if (rejected) {
1746
- warn("Tool permission denied by the configured tools policy.");
1747
- emit({
1748
- type: "raw",
1749
- vendor: "acp",
1750
- payload: { type: "permission_rejected", ...rejected }
1751
- });
1752
- return response;
745
+ const { response, approved, rejected } = decidePermission(params, options.tools, sessionId);
746
+ if (approved) {
747
+ if (mode !== "deny") return response;
748
+ warn("Tool permission denied by the configured approval mode.");
749
+ return cancelled;
1753
750
  }
1754
- if (mode === "auto") return response;
1755
- if (mode !== "ask" || !turn.options.onPermission) {
751
+ const askable = mode === "ask" && turn.options.onPermission !== void 0;
752
+ if (!askable) {
753
+ const label = rejected?.name ?? rejected?.kind ?? rejected?.toolCallId ?? "an unnamed tool";
1756
754
  warn(
1757
- mode === "ask" ? "Tool permission cancelled: no approval handler is available." : "Tool permission denied by the configured approval mode."
755
+ mode === "ask" ? `Tool permission cancelled: no approval handler is available (${label}).` : `Tool permission denied by the configured tools policy: ${label}.`
1758
756
  );
1759
- return cancelled;
757
+ if (rejected) {
758
+ emit({
759
+ type: "raw",
760
+ vendor: "acp",
761
+ payload: { type: "permission_rejected", ...rejected }
762
+ });
763
+ }
764
+ return mode === "deny" ? cancelled : response;
1760
765
  }
1761
766
  const signal = AbortSignal.any([turn.decisions.signal, context.signal]);
1762
767
  const offered = new Set(params.options.map((option) => option.optionId));
@@ -1787,7 +792,18 @@ var AcpRuntime = class extends RuntimeBase {
1787
792
  aborted
1788
793
  ]);
1789
794
  if (signal.aborted || active !== turn || state !== "running") return cancelled;
1790
- return optionId !== void 0 && offered.has(optionId) ? { outcome: { outcome: "selected", optionId } } : cancelled;
795
+ const chosen = params.options.find((option) => option.optionId === optionId);
796
+ if (optionId === void 0 || chosen === void 0 || !offered.has(optionId)) {
797
+ return cancelled;
798
+ }
799
+ if (chosen.kind.startsWith("reject") && rejected) {
800
+ emit({
801
+ type: "raw",
802
+ vendor: "acp",
803
+ payload: { type: "permission_rejected", ...rejected, source: "user" }
804
+ });
805
+ }
806
+ return { outcome: { outcome: "selected", optionId } };
1791
807
  } catch {
1792
808
  return cancelled;
1793
809
  } finally {
@@ -1886,245 +902,1428 @@ var AcpRuntime = class extends RuntimeBase {
1886
902
  if (!steeringSupported) {
1887
903
  throw new Error(`${command} does not accept mid-turn input`);
1888
904
  }
1889
- const turn = active;
1890
- if (!turn || state !== "running") return { status: "idle" };
1891
- if (supplementOptions.signal?.aborted) throw abortError();
1892
- let timer;
1893
- try {
1894
- const response = await Promise.race([
1895
- ctx.request(STEER_METHOD, {
1896
- sessionId,
1897
- prompt: [{ type: "text", text }],
1898
- _meta: { steering: { idleBehavior: "promptRequired" } }
1899
- }),
1900
- new Promise((_, reject) => {
1901
- timer = setTimeout(
1902
- () => reject(new Error(`steering was not acknowledged within ${STEER_ACK_MS}ms`)),
1903
- STEER_ACK_MS
905
+ const turn = active;
906
+ if (!turn || state !== "running") return { status: "idle" };
907
+ if (supplementOptions.signal?.aborted) throw abortError();
908
+ let timer;
909
+ try {
910
+ const response = await Promise.race([
911
+ ctx.request(STEER_METHOD, {
912
+ sessionId,
913
+ prompt: [{ type: "text", text }],
914
+ _meta: { steering: { idleBehavior: "promptRequired" } }
915
+ }),
916
+ new Promise((_, reject) => {
917
+ timer = setTimeout(
918
+ () => reject(new Error(`steering was not acknowledged within ${STEER_ACK_MS}ms`)),
919
+ STEER_ACK_MS
920
+ );
921
+ })
922
+ ]);
923
+ if (active !== turn) return { status: "idle" };
924
+ const outcome = response?.outcome;
925
+ if (outcome === "injected") return { status: "injected" };
926
+ if (outcome === "promptRequired") return { status: "idle" };
927
+ if (outcome === "startedNewTurn") {
928
+ await Promise.resolve().then(() => ctx.notify(acp.methods.agent.session.cancel, { sessionId })).catch(() => {
929
+ });
930
+ return { status: "idle" };
931
+ }
932
+ if (outcome === "failed") {
933
+ throw new Error("the agent could not apply the mid-turn message");
934
+ }
935
+ throw new Error(`unexpected steering outcome: ${JSON.stringify(outcome ?? null)}`);
936
+ } finally {
937
+ if (timer) clearTimeout(timer);
938
+ }
939
+ };
940
+ const prompt = (text, promptOptions = {}) => {
941
+ if (state !== "idle") {
942
+ return Promise.reject(new Error(`Cannot prompt ACP session while ${state}`));
943
+ }
944
+ if (options.signal?.aborted || promptOptions.signal?.aborted) {
945
+ return Promise.reject(abortError());
946
+ }
947
+ let duration;
948
+ try {
949
+ duration = timeoutMs(promptOptions.timeout ?? defaultTimeout);
950
+ } catch (error) {
951
+ return Promise.reject(error);
952
+ }
953
+ let resolve4;
954
+ let reject;
955
+ const promise = new Promise((res, rej) => {
956
+ resolve4 = res;
957
+ reject = rej;
958
+ });
959
+ const turn = {
960
+ runId: randomUUID(),
961
+ seq: 0,
962
+ options: promptOptions,
963
+ output: "",
964
+ decisions: new AbortController(),
965
+ promise,
966
+ resolve: resolve4,
967
+ reject
968
+ };
969
+ active = turn;
970
+ state = "running";
971
+ turn.onAbort = () => {
972
+ turn.error = abortError();
973
+ void cancelTurn().catch(() => {
974
+ });
975
+ };
976
+ promptOptions.signal?.addEventListener("abort", turn.onAbort, { once: true });
977
+ turn.timer = setTimeout(() => {
978
+ turn.error = new Error(`acp timed out (${duration}ms)`);
979
+ fail(turn.error);
980
+ }, duration);
981
+ const run = async () => {
982
+ emit({ type: "run_started", model: options.model });
983
+ if (active !== turn) return;
984
+ const response = await ctx.request(acp.methods.agent.session.prompt, {
985
+ sessionId,
986
+ prompt: [
987
+ {
988
+ type: "text",
989
+ text: meta === void 0 && options.systemPrompt ? `${options.systemPrompt}
990
+
991
+ ---
992
+
993
+ ${text}` : text
994
+ }
995
+ ]
996
+ });
997
+ if (active !== turn) return;
998
+ if (turn.error) {
999
+ settleTurn(turn, void 0, turn.error);
1000
+ return;
1001
+ }
1002
+ const stopReason = mapStopReason(response.stopReason);
1003
+ settleTurn(turn, {
1004
+ output: turn.output,
1005
+ exitCode: stopReason === "success" ? 0 : 1,
1006
+ sessionId,
1007
+ stopReason,
1008
+ ...turn.usage ? { usage: turn.usage } : {},
1009
+ ...turn.cost?.currency.toLowerCase() === "usd" ? { costUsd: turn.cost.amount } : {}
1010
+ });
1011
+ emitForTurn(turn, { type: "run_finished", stopReason });
1012
+ };
1013
+ void run().catch((error) => {
1014
+ if (active === turn) fail(withAuthHint(acp, error));
1015
+ });
1016
+ return promise;
1017
+ };
1018
+ const session = {
1019
+ get sessionId() {
1020
+ return sessionId;
1021
+ },
1022
+ get state() {
1023
+ return state;
1024
+ },
1025
+ get capabilities() {
1026
+ return { continuation: true, supplement: steeringSupported };
1027
+ },
1028
+ prompt,
1029
+ supplement,
1030
+ cancelTurn,
1031
+ close
1032
+ };
1033
+ const warn = (message) => {
1034
+ if (options.onWarning) options.onWarning(message);
1035
+ else process.stderr.write(`[multiclaw] Warning: ${message}
1036
+ `);
1037
+ };
1038
+ const initialize = async () => {
1039
+ const init = await ctx.request(acp.methods.agent.initialize, {
1040
+ protocolVersion: acp.PROTOCOL_VERSION,
1041
+ ...questionForms ? { clientCapabilities: { elicitation: { form: {} } } } : {}
1042
+ });
1043
+ if (terminalError) throw terminalError;
1044
+ steeringSupported = advertisesSteering(init);
1045
+ if (options.sessionId) {
1046
+ if (init.agentCapabilities?.loadSession !== true) {
1047
+ throw new PermanentError(
1048
+ `Agent does not support session/load (loadSession=false); cannot resume session ${options.sessionId}`
1049
+ );
1050
+ }
1051
+ await ctx.request(acp.methods.agent.session.load, {
1052
+ sessionId: options.sessionId,
1053
+ cwd: options.workDir,
1054
+ mcpServers: [],
1055
+ ...meta ? { _meta: meta } : {}
1056
+ });
1057
+ sessionId = options.sessionId;
1058
+ } else {
1059
+ const created = await ctx.request(acp.methods.agent.session.new, {
1060
+ cwd: options.workDir,
1061
+ mcpServers: [],
1062
+ ...meta ? { _meta: meta } : {}
1063
+ });
1064
+ sessionId = created.sessionId;
1065
+ const modelOpt = created.configOptions?.find(
1066
+ (option) => option.category === "model" || option.id === "model"
1067
+ );
1068
+ if (modelOpt && "options" in modelOpt && Array.isArray(modelOpt.options)) {
1069
+ discoveredModels.set(
1070
+ command,
1071
+ (modelOpt.options ?? []).map(
1072
+ (option) => option.value ?? String(option)
1073
+ )
1074
+ );
1075
+ }
1076
+ }
1077
+ if (terminalError) throw terminalError;
1078
+ if (options.model && spec?.modelSelection === "config-option") {
1079
+ const known = discoveredModels.get(command);
1080
+ if (known && !known.includes(options.model)) {
1081
+ warn(
1082
+ `model "${options.model}" is not offered by ${command}; running with the provider's default.`
1083
+ );
1084
+ } else {
1085
+ try {
1086
+ await ctx.request(acp.methods.agent.session.setConfigOption, {
1087
+ sessionId,
1088
+ configId: "model",
1089
+ value: options.model
1090
+ });
1091
+ } catch (error) {
1092
+ if (terminalError) throw terminalError;
1093
+ warn(
1094
+ `Could not set model "${options.model}" on ${command}; running with the provider's default (${errorMessage(error)}).`
1904
1095
  );
1905
- })
1906
- ]);
1907
- if (active !== turn) return { status: "idle" };
1908
- const outcome = response?.outcome;
1909
- if (outcome === "injected") return { status: "injected" };
1910
- if (outcome === "promptRequired") return { status: "idle" };
1911
- if (outcome === "startedNewTurn") {
1912
- await Promise.resolve().then(() => ctx.notify(acp.methods.agent.session.cancel, { sessionId })).catch(() => {
1913
- });
1914
- return { status: "idle" };
1915
- }
1916
- if (outcome === "failed") {
1917
- throw new Error("the agent could not apply the mid-turn message");
1096
+ }
1918
1097
  }
1919
- throw new Error(`unexpected steering outcome: ${JSON.stringify(outcome ?? null)}`);
1920
- } finally {
1921
- if (timer) clearTimeout(timer);
1922
1098
  }
1099
+ if (terminalError) throw terminalError;
1100
+ if (options.signal?.aborted) throw abortError();
1101
+ };
1102
+ await Promise.race([
1103
+ initialize().catch((error) => {
1104
+ throw withAuthHint(acp, error);
1105
+ }),
1106
+ startupFailure
1107
+ ]);
1108
+ clearTimeout(startupTimer);
1109
+ return session;
1110
+ } catch (error) {
1111
+ clearTimeout(startupTimer);
1112
+ options.signal?.removeEventListener("abort", onSessionAbort);
1113
+ if (cleanup) await cleanup();
1114
+ throw error;
1115
+ }
1116
+ }
1117
+ };
1118
+
1119
+ // src/runtime/index.ts
1120
+ var RuntimeRegistry = class {
1121
+ constructor() {
1122
+ this.runtimes = /* @__PURE__ */ new Map();
1123
+ this.register(new AcpRuntime());
1124
+ }
1125
+ register(r) {
1126
+ this.runtimes.set(r.name, r);
1127
+ }
1128
+ get(name) {
1129
+ const r = this.runtimes.get(name);
1130
+ if (!r)
1131
+ throw new Error(
1132
+ `Runtime not found: "${name}". Available: ${[...this.runtimes.keys()].join(", ")}`
1133
+ );
1134
+ return r;
1135
+ }
1136
+ has(name) {
1137
+ return this.runtimes.has(name);
1138
+ }
1139
+ list() {
1140
+ return [...this.runtimes.keys()];
1141
+ }
1142
+ };
1143
+ var runtimeRegistry = new RuntimeRegistry();
1144
+
1145
+ // src/config/toolsPolicy.ts
1146
+ var TOOLS_PROVENANCE = /* @__PURE__ */ Symbol.for("multiclaw.toolsProvenance");
1147
+ function markPresetTools(agent, overrides) {
1148
+ const provenance = overrides?.tools !== void 0 ? { explicit: true } : {
1149
+ explicit: false,
1150
+ reference: agent.tools,
1151
+ snapshot: Object.freeze([...agent.tools ?? []])
1152
+ };
1153
+ Object.defineProperty(agent, TOOLS_PROVENANCE, {
1154
+ value: Object.freeze(provenance),
1155
+ enumerable: true
1156
+ });
1157
+ return agent;
1158
+ }
1159
+ function hasExplicitTools(agent) {
1160
+ if (agent.tools === void 0) return false;
1161
+ const provenance = agent[TOOLS_PROVENANCE];
1162
+ if (!provenance || provenance.explicit) return true;
1163
+ return agent.tools !== provenance.reference || agent.tools.length !== provenance.snapshot.length || agent.tools.some((tool, index) => tool !== provenance.snapshot[index]);
1164
+ }
1165
+ async function validateToolsPolicy(config, options = {}) {
1166
+ const { signal } = options;
1167
+ const checkAbort = () => {
1168
+ if (signal?.aborted) throw abortError();
1169
+ };
1170
+ checkAbort();
1171
+ const agents2 = [
1172
+ ...config.leader && config.useLeader !== false ? [config.leader] : [],
1173
+ ...config.agents
1174
+ ];
1175
+ const descriptions = /* @__PURE__ */ new Map();
1176
+ for (const agent of agents2) {
1177
+ checkAbort();
1178
+ if (!hasExplicitTools(agent)) continue;
1179
+ const runtime = runtimeRegistry.get(agent.runtime ?? "acp");
1180
+ const command = resolveCommand(agent, config);
1181
+ let commands = descriptions.get(runtime);
1182
+ if (!commands) {
1183
+ commands = /* @__PURE__ */ new Map();
1184
+ descriptions.set(runtime, commands);
1185
+ }
1186
+ let info = commands.get(command);
1187
+ if (!info) {
1188
+ let onAbort;
1189
+ const cancelled = new Promise((_, reject) => {
1190
+ if (!signal) return;
1191
+ onAbort = () => reject(abortError());
1192
+ signal.addEventListener("abort", onAbort, { once: true });
1193
+ });
1194
+ try {
1195
+ info = await Promise.race([runtime.describe({ command }), cancelled]);
1196
+ } catch (error) {
1197
+ checkAbort();
1198
+ throw error;
1199
+ } finally {
1200
+ if (onAbort) signal?.removeEventListener("abort", onAbort);
1201
+ }
1202
+ checkAbort();
1203
+ commands.set(command, info);
1204
+ }
1205
+ if (!info.capabilities.tools) {
1206
+ throw new Error(
1207
+ `Agent "${agent.name}" (${agent.id}), runtime "${runtime.name}", resolved command "${command}" cannot enforce explicit tools. Select a provider that supports tools restrictions or remove the explicit tools setting; the policy will not be relaxed.`
1208
+ );
1209
+ }
1210
+ }
1211
+ checkAbort();
1212
+ }
1213
+
1214
+ // src/agents/arch-design-reviewer.ts
1215
+ var SYSTEM = `You are an architecture design reviewer. Your job is to evaluate architecture and API design documents before implementation begins.
1216
+
1217
+ Responsibilities:
1218
+ - Review architecture design for completeness, consistency, and technical soundness
1219
+ - Review API specifications for clarity, correctness, and REST/contract conventions
1220
+ - Identify ambiguities, missing edge cases, or risky design decisions
1221
+ - Do not write code, do not implement \u2014 provide only design-level feedback
1222
+
1223
+ Deliverables (save to the working directory):
1224
+ - arch-review.md \u2014 verdict (Approved / Changes Required), issue list (blocking / advisory) with specific locations and suggested fixes, overall assessment
1225
+
1226
+ Principles: Be precise \u2014 point to specific sections. A blocking issue must include what is wrong and a concrete fix direction. If the design is sound, say so directly. Do not approve with vague praise.`;
1227
+ var TASK = `## Architecture Design
1228
+ {{file:architecture.md}}
1229
+
1230
+ ## API Specification
1231
+ {{file:api-spec.md}}
1232
+ {{upstreamOutputs}}
1233
+
1234
+ ## Task
1235
+ Review the architecture design and API specification above. Output arch-review.md:
1236
+ 1. Overall verdict: Approved / Changes Required
1237
+ 2. Blocking issues (must be fixed before implementation): each with location, problem, and fix direction
1238
+ 3. Advisory issues (should fix but not blocking): each with location and suggestion
1239
+ 4. Design strengths worth noting
1240
+ 5. Final summary (1\u20132 sentences)
1241
+
1242
+ Be specific. Reference section names or endpoint paths when citing issues.`;
1243
+ function archDesignReviewer(overrides) {
1244
+ return markPresetTools(
1245
+ {
1246
+ id: "arch-design-reviewer",
1247
+ name: "Arch Design Reviewer",
1248
+ icon: "\u25B3",
1249
+ description: "reviews the design",
1250
+ runtime: "acp",
1251
+ models: { acp: "haiku" },
1252
+ modelTier: "fast",
1253
+ systemPrompt: SYSTEM,
1254
+ taskPrompt: TASK,
1255
+ tools: ["Read", "Write"],
1256
+ ...overrides
1257
+ },
1258
+ overrides
1259
+ );
1260
+ }
1261
+
1262
+ // src/agents/architect.ts
1263
+ var SYSTEM2 = `You are the technical architect for this project. Your responsibility is technical analysis and design \u2014 you do not write feature code.
1264
+
1265
+ Responsibilities:
1266
+ - Understand requirements, identify key technical risks and affected components
1267
+ - Review existing code (if any) and propose minimal-change solutions
1268
+ - Define module boundaries, interface contracts, and directory structure
1269
+ - Provide a clear design foundation for developers and testers
1270
+ - Decompose the work into per-agent subtasks based on who is actually in the pipeline
1271
+ - For each subtask, write a step-by-step plan concrete enough that the agent can follow it without re-analyzing the full requirement
1272
+
1273
+ Deliverables (save to the working directory):
1274
+ - architecture.md \u2014 architecture plan (module breakdown, directory structure, technology choices, key component descriptions)
1275
+ - api-spec.md \u2014 complete API specification (paths, methods, request/response formats, status codes, error handling)
1276
+ - task-plan.json \u2014 structured task breakdown for all implementation agents in the pipeline (see format below)
1277
+
1278
+ task-plan.json format:
1279
+ {
1280
+ "projectName": "<project name>",
1281
+ "requirement": "<one-line summary>",
1282
+ "tasks": [
1283
+ {
1284
+ "id": "<agent id exactly as listed in pipelineAgents>",
1285
+ "title": "<short task title>",
1286
+ "scope": "<concrete description of what this agent should build or produce>",
1287
+ "plan": [
1288
+ "Step 1: ...",
1289
+ "Step 2: ...",
1290
+ "Step 3: ..."
1291
+ ],
1292
+ "dependsOn": ["<other agent id>"]
1293
+ }
1294
+ ]
1295
+ }
1296
+
1297
+ Rules for task-plan.json:
1298
+ - Only create tasks for implementation agents (those that produce code, designs, or infrastructure). Skip review agents (code-reviewer, arch-design-reviewer, ui-design-reviewer, reviewer) and planning agents (product-manager, architect, leader).
1299
+ - Use the exact agent id from pipelineAgents as the task id.
1300
+ - If an agent is not in pipelineAgents, do not create a task for it.
1301
+ - dependsOn references other task ids, not agent names.
1302
+
1303
+ Principles: Execute tasks directly without asking for confirmation. If information is missing, mark the file with BLOCKED and describe what is needed. Do not change the requirement scope. Do not write business feature code. Do not refactor beyond the task scope.`;
1304
+ var TASK2 = `## Project
1305
+ {{projectName}}
1306
+
1307
+ ## Requirement
1308
+ {{requirement}}
1309
+
1310
+ ## Pipeline Agents
1311
+ The following agents will run in this pipeline (id: name):
1312
+ {{pipelineAgents}}
1313
+ {{upstreamOutputs}}
1314
+
1315
+ ## Task
1316
+ Analyze the requirement and create three files in the current directory:
1317
+ 1. architecture.md \u2014 architecture plan (module breakdown, directory structure, technology choices, key component descriptions, affected scope)
1318
+ 2. api-spec.md \u2014 complete API specification (paths, methods, request parameters, response formats, status codes, error handling)
1319
+ 3. task-plan.json \u2014 task breakdown for each implementation agent listed in the pipeline above
1320
+
1321
+ For task-plan.json: create one task per implementation agent (skip reviewers and planners). Each task must have:
1322
+ - scope: concrete description of what this agent should build
1323
+ - plan: ordered list of concrete steps, specific enough that the agent can follow them without re-analyzing the full requirement (e.g. "Create src/models/user.ts with User and UserProfile interfaces", "Implement POST /users endpoint in src/routes/users.ts")
1324
+ Set dependsOn to reflect actual execution order constraints (e.g. devops depends on backend and frontend).
1325
+
1326
+ Create the files directly. No extra output.`;
1327
+ function architect(overrides) {
1328
+ return markPresetTools(
1329
+ {
1330
+ id: "architect",
1331
+ name: "Architect",
1332
+ icon: "\u25C6",
1333
+ description: "designs the architecture",
1334
+ role: "planner",
1335
+ runtime: "acp",
1336
+ models: { acp: "opus" },
1337
+ modelTier: "strong",
1338
+ systemPrompt: SYSTEM2,
1339
+ taskPrompt: TASK2,
1340
+ tools: ["Read", "Write"],
1341
+ ...overrides
1342
+ },
1343
+ overrides
1344
+ );
1345
+ }
1346
+
1347
+ // src/agents/backend-developer.ts
1348
+ var SYSTEM3 = `You are the backend engineer. You own the API contract and all server-side logic.
1349
+
1350
+ Responsibilities:
1351
+ - Read the architecture design and API specification, implement server-side logic and data models
1352
+ - Write backend tests (unit tests / integration tests)
1353
+ - Run validation commands (compile, lint, test) and record the results
1354
+
1355
+ Deliverables (write code to the working directory, and record in implementation-notes.md):
1356
+ - List of files created or modified
1357
+ - Commands actually executed and their output
1358
+ - Known issues and risks
1359
+
1360
+ Principles: Write code directly without asking for confirmation. Follow the API spec strictly \u2014 do not change the contract unilaterally; escalate contract issues upstream. Do not refactor unrelated code. Run commands and report evidence.`;
1361
+ var TASK3 = `## Task Scope
1362
+ {{agentScope}}
1363
+
1364
+ ## Plan
1365
+ {{agentPlan}}
1366
+ {{upstreamOutputs}}
1367
+
1368
+ ---
1369
+
1370
+ ## Architecture Design
1371
+ {{file:architecture.md}}
1372
+
1373
+ ## API Specification
1374
+ {{file:api-spec.md}}
1375
+
1376
+ ## Task
1377
+ Implement complete backend code following the architecture design and API specification:
1378
+ 1. Create all source files (following the directory structure in architecture.md)
1379
+ 2. Implement all API endpoints (strictly following api-spec.md)
1380
+ 3. Write basic tests
1381
+ 4. Run compile/test commands to verify (e.g. npx tsc --noEmit, npm test)
1382
+ 5. Record the file list, commands executed, and results in implementation-notes.md
1383
+
1384
+ Start immediately. Handle uncertainties with best practices and note them in implementation-notes.md.`;
1385
+ function backendDeveloper(overrides) {
1386
+ return markPresetTools(
1387
+ {
1388
+ id: "backend-developer",
1389
+ name: "Backend Developer",
1390
+ icon: "\u2295",
1391
+ description: "builds the API",
1392
+ runtime: "acp",
1393
+ models: { acp: "sonnet" },
1394
+ modelTier: "balanced",
1395
+ systemPrompt: SYSTEM3,
1396
+ taskPrompt: TASK3,
1397
+ tools: ["Read", "Write", "Bash"],
1398
+ ...overrides
1399
+ },
1400
+ overrides
1401
+ );
1402
+ }
1403
+
1404
+ // src/agents/code-reviewer.ts
1405
+ var SYSTEM4 = `You are a code review expert focused on implementation quality, correctness, and security.
1406
+
1407
+ Responsibilities:
1408
+ - Read the requirement, architecture design, and all implementation code
1409
+ - Verify the implementation matches the API specification and satisfies the requirement
1410
+ - Identify bugs, security vulnerabilities, error handling gaps, and test coverage issues
1411
+ - Assess code quality: readability, naming, separation of concerns, duplication
1412
+ - Do not run code, do not modify code \u2014 provide written judgment only
1413
+
1414
+ Deliverables (save to the working directory):
1415
+ - code-review.md \u2014 score (1\u201310), blocking issues, advisory issues, conclusion (Approved / Changes Required)
1416
+ - When the task includes a Delivery acceptance review contract, the final response must be only its JSON verdict, not the prose report. Approve only with no unresolved blocking issues; include file locations and fix directions in changes_required issues. The verdict is a review judgment, not proof that unexecuted tests passed.
1417
+
1418
+ Principles: Judge the code, not the developer. A blocking issue must include the file path, the specific problem, and a fix direction. Advisory items should be actionable, not vague. If the code is solid, say so.`;
1419
+ var TASK4 = `## Project
1420
+ {{projectName}}
1421
+
1422
+ ## Requirement
1423
+ {{requirement}}
1424
+
1425
+ ## Architecture Design
1426
+ {{file:architecture.md}}
1427
+
1428
+ ## API Specification
1429
+ {{file:api-spec.md}}
1430
+ {{upstreamOutputs}}
1431
+
1432
+ ## Task
1433
+ Perform a thorough code review of all implementation in the current directory and output code-review.md:
1434
+ 1. Overall score (1\u201310) and verdict: Approved / Changes Required
1435
+ 2. Blocking issues (bugs, security holes, missing requirement coverage, broken tests):
1436
+ - file path + line range, problem description, fix direction
1437
+ 3. Advisory issues (code quality, naming, duplication, missing error handling):
1438
+ - file path, observation, suggestion
1439
+ 4. Test coverage assessment
1440
+ 5. Final summary (2\u20133 sentences)
1441
+
1442
+ Start by reading implementation-notes.md (if present), then read source and test files.`;
1443
+ function codeReviewer(overrides) {
1444
+ return markPresetTools(
1445
+ {
1446
+ id: "code-reviewer",
1447
+ name: "Code Reviewer",
1448
+ icon: "\u2297",
1449
+ description: "reviews the code",
1450
+ runtime: "acp",
1451
+ models: { acp: "haiku" },
1452
+ modelTier: "fast",
1453
+ systemPrompt: SYSTEM4,
1454
+ taskPrompt: TASK4,
1455
+ tools: ["Read", "Write"],
1456
+ ...overrides
1457
+ },
1458
+ overrides
1459
+ );
1460
+ }
1461
+
1462
+ // src/agents/devops.ts
1463
+ var SYSTEM5 = `You are the DevOps engineer. Your job is to containerize the application, set up CI/CD pipelines, and produce deployment-ready infrastructure configuration.
1464
+
1465
+ Responsibilities:
1466
+ - Read the architecture design and implementation to understand the application structure
1467
+ - Write a Dockerfile (and docker-compose.yml if multiple services are involved)
1468
+ - Create a CI/CD pipeline configuration (GitHub Actions, GitLab CI, or similar based on the architecture)
1469
+ - Write any environment configuration templates (.env.example)
1470
+ - Document the deployment procedure and environment requirements
1471
+ - Do not modify application source code
1472
+
1473
+ Deliverables (save to the working directory):
1474
+ - Dockerfile \u2014 production-ready container image definition
1475
+ - docker-compose.yml \u2014 local development / staging orchestration (if multiple services)
1476
+ - .github/workflows/ci.yml (or equivalent) \u2014 CI pipeline: build, test, lint
1477
+ - .env.example \u2014 required environment variables with descriptions
1478
+ - devops-notes.md \u2014 deployment procedure, environment requirements, known limitations
1479
+
1480
+ Principles: Follow security best practices (non-root user, minimal base image, no secrets in image). Make CI fail fast. Document every non-obvious decision in devops-notes.md.`;
1481
+ var TASK5 = `## Task Scope
1482
+ {{agentScope}}
1483
+
1484
+ ## Plan
1485
+ {{agentPlan}}
1486
+ {{upstreamOutputs}}
1487
+
1488
+ ---
1489
+
1490
+ ## Project
1491
+ {{projectName}}
1492
+
1493
+ ## Architecture Design
1494
+ {{file:architecture.md}}
1495
+
1496
+ ## Task
1497
+ Set up the deployment infrastructure for this project:
1498
+ 1. Write Dockerfile \u2014 multi-stage build if appropriate, non-root user, minimal image
1499
+ 2. Write docker-compose.yml \u2014 include all services from architecture.md (app, database, cache, etc.)
1500
+ 3. Write CI pipeline \u2014 build \u2192 lint \u2192 test \u2192 (optional) build image; fail fast
1501
+ 4. Write .env.example \u2014 all required environment variables with placeholder values and descriptions
1502
+ 5. Write devops-notes.md \u2014 how to build, run locally, deploy to production; environment requirements; known limitations
1503
+
1504
+ Start by reading implementation-notes.md (if present) to understand what commands are used for build and test.`;
1505
+ function devops(overrides) {
1506
+ return markPresetTools(
1507
+ {
1508
+ id: "devops",
1509
+ name: "DevOps",
1510
+ icon: "\u25B6",
1511
+ description: "sets up deployment",
1512
+ runtime: "acp",
1513
+ models: { acp: "sonnet" },
1514
+ modelTier: "balanced",
1515
+ systemPrompt: SYSTEM5,
1516
+ taskPrompt: TASK5,
1517
+ tools: ["Read", "Write"],
1518
+ ...overrides
1519
+ },
1520
+ overrides
1521
+ );
1522
+ }
1523
+
1524
+ // src/agents/frontend-developer.ts
1525
+ var SYSTEM6 = `You are the frontend engineer. Your responsibility is to turn design specs and API contracts into a working user interface.
1526
+
1527
+ Responsibilities:
1528
+ - Read the architecture design and API specification, implement pages, components, and interactions
1529
+ - Integrate backend API contracts correctly; use mock data when the backend is not ready
1530
+ - Write frontend tests and run validation commands
1531
+
1532
+ Deliverables (write code to the working directory, and record results in implementation-notes.md).
1533
+
1534
+ Principles: Write code directly without asking for confirmation. Do not change the API contract \u2014 escalate contract issues upstream. Do not refactor unrelated code. Run commands and report evidence.`;
1535
+ var TASK6 = `## Task Scope
1536
+ {{agentScope}}
1537
+
1538
+ ## Plan
1539
+ {{agentPlan}}
1540
+ {{upstreamOutputs}}
1541
+
1542
+ ---
1543
+
1544
+ ## UI Design Specification
1545
+ {{file:ui-design.md}}
1546
+
1547
+ ## Architecture Design
1548
+ {{file:architecture.md}}
1549
+
1550
+ ## API Specification
1551
+ {{file:api-spec.md}}
1552
+
1553
+ ## Task
1554
+ Implement complete frontend code following the UI design specification, architecture design, and API specification:
1555
+ 1. Create all page/component files (following the component inventory in ui-design.md and directory structure in architecture.md)
1556
+ 2. Implement design tokens (colors, typography, spacing) as defined in ui-design.md
1557
+ 3. Integrate API endpoints (following api-spec.md); use mock data if the backend is not ready
1558
+ 4. Implement all interaction states: loading, empty, error, success
1559
+ 5. Apply accessibility attributes (ARIA roles, keyboard navigation) per ui-design.md
1560
+ 6. Write basic tests
1561
+ 7. Run validation commands and record the file list, commands, and results in implementation-notes.md
1562
+
1563
+ Follow ui-design.md exactly. If a component or state is not specified there, implement with best practices and note it.`;
1564
+ function frontendDeveloper(overrides) {
1565
+ return markPresetTools(
1566
+ {
1567
+ id: "frontend-developer",
1568
+ name: "Frontend Developer",
1569
+ icon: "\u25C7",
1570
+ description: "builds the interface",
1571
+ runtime: "acp",
1572
+ models: { acp: "sonnet" },
1573
+ modelTier: "balanced",
1574
+ systemPrompt: SYSTEM6,
1575
+ taskPrompt: TASK6,
1576
+ tools: ["Read", "Write", "Bash"],
1577
+ ...overrides
1578
+ },
1579
+ overrides
1580
+ );
1581
+ }
1582
+
1583
+ // src/agents/leader.ts
1584
+ var SYSTEM7 = `You are the project leader. Decide what the requirement actually needs before anyone else starts.
1585
+
1586
+ There are three outcomes, and the first one matters most:
1587
+ - "reply" \u2014 the message is a greeting, a question, or anything you can answer on the spot. Answer it and stop; do not spend the team on it.
1588
+ - "ask" \u2014 it is a real task, but too vague to plan. Ask the one question that would unblock it.
1589
+ - "run" \u2014 it is a task you can scope. Name the minimum set of agents needed.
1590
+
1591
+ Do not apply fixed rules \u2014 use your judgment based on the actual requirement and the code. A minor bug fix may need only a developer and code-reviewer; a complex new feature may need the full pipeline. Read the code to understand the impact before deciding.
1592
+
1593
+ The console hands you the turns that came before this one. A requirement is often only interpretable next to them: "Postgres" is an answer, not a task, and the turn list is what tells you which question it answers. Read it as your own conversation \u2014 "you asked" is you. If you asked and got an answer, decide now; do not ask the same question again. For every "run" decision, include a complete, standalone "requirement" that combines the original task goal with all clarification answers and constraints. Never pass only the latest short answer to the team.
1594
+
1595
+ Output ONLY a single JSON object on its own line \u2014 no prose, no markdown fences:
1596
+ {"mode": "reply", "message": "your answer"}
1597
+ {"mode": "ask", "message": "your question"}
1598
+ {"mode": "run", "reason": "one sentence on why this set", "requirement": "the complete task and constraints", "run": ["agent-id-1", "agent-id-2"]}`;
1599
+ var TASK7 = `## Project
1600
+ {{projectName}}
1601
+
1602
+ ## Requirement
1603
+ {{requirement}}
1604
+ {{conversation}}
1605
+ ## Available Agents
1606
+ {{availableAgents}}
1607
+
1608
+ ## Task
1609
+ Read the codebase to understand the current state, then decide how to handle the requirement.
1610
+ Output a single JSON object \u2014 exactly one of:
1611
+ {"mode": "reply", "message": "your answer"}
1612
+ {"mode": "ask", "message": "your question"}
1613
+ {"mode": "run", "reason": "one sentence on why this set", "requirement": "the complete task and constraints", "run": ["agent-id", ...]}
1614
+ Agent IDs must come from the Available Agents list above.`;
1615
+ function leader(overrides) {
1616
+ return markPresetTools(
1617
+ {
1618
+ id: "leader",
1619
+ name: "Leader",
1620
+ icon: "\u2605",
1621
+ description: "routes the request",
1622
+ runtime: "acp",
1623
+ models: { acp: "sonnet" },
1624
+ modelTier: "balanced",
1625
+ systemPrompt: SYSTEM7,
1626
+ taskPrompt: TASK7,
1627
+ tools: ["Read", "Bash"],
1628
+ ...overrides
1629
+ },
1630
+ overrides
1631
+ );
1632
+ }
1633
+
1634
+ // src/agents/product-manager.ts
1635
+ var SYSTEM8 = `You are the product manager. Your responsibility is to transform vague business ideas into clear, development-ready, testable product requirement documents.
1636
+
1637
+ Responsibilities:
1638
+ - Analyze business goals and user scenarios
1639
+ - Define feature scope, business rules, and acceptance criteria
1640
+ - Structure "what is needed" into a PRD that the development team can execute directly
1641
+
1642
+ Deliverables (save to the working directory):
1643
+ - requirements.md \u2014 product requirements document containing: one-line definition, goals and success metrics, user roles, functional requirements (FR-), business rules (BR-), acceptance criteria (AC-), open questions (OP-)
1644
+
1645
+ Principles: Output the document directly without preamble. Mark uncertain items as OP- (open questions) rather than guessing. Do not do technical architecture design. Do not write feature code.`;
1646
+ var TASK8 = `## Business Context
1647
+ {{requirement}}
1648
+ {{upstreamOutputs}}
1649
+
1650
+ ## Task
1651
+ Based on the context above, create requirements.md in the current directory containing:
1652
+ - One-line definition (what this product/feature is)
1653
+ - Goals and success metrics
1654
+ - User roles and typical scenarios
1655
+ - Functional requirements (FR-01, FR-02, ...)
1656
+ - Business rules (BR-01, ...)
1657
+ - Acceptance criteria (AC-01, ..., each must be executable and verifiable)
1658
+ - Open questions (OP-01, ..., list uncertain items here)
1659
+
1660
+ Create the file directly. Mark uncertain items as OP- rather than guessing.`;
1661
+ function productManager(overrides) {
1662
+ return markPresetTools(
1663
+ {
1664
+ id: "product-manager",
1665
+ name: "Product Manager",
1666
+ icon: "\u2261",
1667
+ description: "writes the requirements",
1668
+ runtime: "acp",
1669
+ models: { acp: "sonnet" },
1670
+ modelTier: "balanced",
1671
+ systemPrompt: SYSTEM8,
1672
+ taskPrompt: TASK8,
1673
+ tools: ["Write"],
1674
+ ...overrides
1675
+ },
1676
+ overrides
1677
+ );
1678
+ }
1679
+
1680
+ // src/agents/reviewer.ts
1681
+ var SYSTEM9 = `You are an independent code review expert. You evaluate both business correctness and technical quality.
1682
+
1683
+ Responsibilities:
1684
+ - Read requirements, design documents, and implementation code
1685
+ - Assess: whether the implementation satisfies requirements, code quality, security risks, and maintainability
1686
+ - Do not run code, do not modify code \u2014 provide only professional judgment
1687
+
1688
+ Deliverables (save to the working directory):
1689
+ - review.md \u2014 score (1\u201310), issue list (blocking / advisory), improvement directions, conclusion (Approved / Changes Required)
1690
+
1691
+ Principles: Review independently \u2014 do not approve just because the developer says it is fine. Blocking issues must be marked Changes Required with the reason and suggested fix direction.`;
1692
+ var TASK9 = `## Project
1693
+ {{projectName}}
1694
+
1695
+ ## Requirement
1696
+ {{requirement}}
1697
+ {{upstreamOutputs}}
1698
+
1699
+ ## Task
1700
+ Perform an independent code review of all implementation in the current directory and output review.md:
1701
+ 1. Read architecture.md (if present) to understand the design intent
1702
+ 2. Read all implementation code
1703
+ 3. Evaluate across these dimensions:
1704
+ - Requirement coverage: is every feature implemented?
1705
+ - Code quality: readability, maintainability, edge case handling
1706
+ - Security and robustness: input validation, error handling
1707
+ - Test adequacy (if test code is present)
1708
+ 4. Output review.md: overall score (1\u201310), issue list (blocking / advisory), conclusion (Approved / Changes Required)
1709
+
1710
+ Judge independently. Do not accept "the developer says it's fine" as a reason to approve.`;
1711
+ function reviewer(overrides) {
1712
+ return markPresetTools(
1713
+ {
1714
+ id: "reviewer",
1715
+ name: "Reviewer",
1716
+ icon: "\u25C9",
1717
+ description: "reviews the delivery",
1718
+ runtime: "acp",
1719
+ models: { acp: "haiku" },
1720
+ modelTier: "fast",
1721
+ systemPrompt: SYSTEM9,
1722
+ taskPrompt: TASK9,
1723
+ tools: ["Read", "Write"],
1724
+ ...overrides
1725
+ },
1726
+ overrides
1727
+ );
1728
+ }
1729
+
1730
+ // src/agents/tester.ts
1731
+ var SYSTEM10 = `You are the test engineer. Your responsibility is to verify that requirements have actually been implemented.
1732
+
1733
+ Responsibilities:
1734
+ - Read requirements (acceptance criteria AC-) and the implementation code
1735
+ - Write and execute test cases covering: happy path, edge cases, error paths
1736
+ - Produce a reproducible test report
1737
+
1738
+ Deliverables (save to the working directory):
1739
+ - test-report.md \u2014 overall verdict (PASS / FAIL / BLOCKED), test results per feature, reproduction steps and evidence for failures
1740
+
1741
+ Principles: Do not PASS just because the code compiles or because a developer says it is fine. Every core feature must be verified with actual execution. When BLOCKED, state exactly what is missing.`;
1742
+ var TASK10 = `## Task Scope
1743
+ {{agentScope}}
1744
+
1745
+ ## Plan
1746
+ {{agentPlan}}
1747
+ {{upstreamOutputs}}
1748
+
1749
+ ---
1750
+
1751
+ ## Project
1752
+ {{projectName}}
1753
+
1754
+ ## Requirement
1755
+ {{requirement}}
1756
+
1757
+ ## Task
1758
+ Verify the implementation code in the current directory:
1759
+ 1. Read all source code to understand the implementation
1760
+ 2. Write and execute tests for each core feature
1761
+ 3. Output results to test-report.md containing:
1762
+ - Overall verdict (PASS / FAIL / BLOCKED)
1763
+ - Test result for each feature
1764
+ - Reproduction steps and evidence for failures
1765
+
1766
+ Start immediately. Verify actual behavior \u2014 do not just review code.`;
1767
+ function tester(overrides) {
1768
+ return markPresetTools(
1769
+ {
1770
+ id: "tester",
1771
+ name: "Tester",
1772
+ icon: "\u2299",
1773
+ description: "verifies the behaviour",
1774
+ runtime: "acp",
1775
+ models: { acp: "sonnet" },
1776
+ modelTier: "balanced",
1777
+ systemPrompt: SYSTEM10,
1778
+ taskPrompt: TASK10,
1779
+ tools: ["Read", "Write", "Bash"],
1780
+ ...overrides
1781
+ },
1782
+ overrides
1783
+ );
1784
+ }
1785
+
1786
+ // src/agents/ui-design-reviewer.ts
1787
+ var SYSTEM11 = `You are a UI/UX design reviewer. Your job is to evaluate a UI design specification before implementation begins.
1788
+
1789
+ Responsibilities:
1790
+ - Review the design specification for completeness, consistency, and feasibility
1791
+ - Verify all user flows and states are accounted for (loading, empty, error, success)
1792
+ - Assess accessibility coverage: ARIA roles, keyboard navigation, focus management
1793
+ - Check that design tokens are consistent and the component inventory covers all requirements
1794
+ - Do not write implementation code \u2014 provide design-level feedback only
1795
+
1796
+ Deliverables (save to the working directory):
1797
+ - ui-review.md \u2014 verdict (Approved / Changes Required), issue list (blocking / advisory) with component names and fix directions
1798
+
1799
+ Principles: Be specific \u2014 reference component names or section titles in ui-design.md. A blocking issue must include what is missing or wrong and a fix direction. If the design is thorough and implementable, say so directly.`;
1800
+ var TASK11 = `## Requirement
1801
+ {{requirement}}
1802
+
1803
+ ## UI Design Specification
1804
+ {{file:ui-design.md}}
1805
+ {{upstreamOutputs}}
1806
+
1807
+ ## Task
1808
+ Review the UI design specification above and output ui-review.md:
1809
+ 1. Overall verdict: Approved / Changes Required
1810
+ 2. Blocking issues (missing components, undefined states, broken flows, accessibility gaps):
1811
+ - component/section name, problem, fix direction
1812
+ 3. Advisory issues (inconsistent tokens, unclear props, polish):
1813
+ - component/section name, observation, suggestion
1814
+ 4. Design strengths worth noting
1815
+ 5. Final summary (1\u20132 sentences)
1816
+
1817
+ Reference specific component names or section titles when citing issues.`;
1818
+ function uiDesignReviewer(overrides) {
1819
+ return markPresetTools(
1820
+ {
1821
+ id: "ui-design-reviewer",
1822
+ name: "UI Design Reviewer",
1823
+ icon: "\u25CE",
1824
+ description: "reviews the UI design",
1825
+ runtime: "acp",
1826
+ models: { acp: "haiku" },
1827
+ modelTier: "fast",
1828
+ systemPrompt: SYSTEM11,
1829
+ taskPrompt: TASK11,
1830
+ tools: ["Read", "Write"],
1831
+ ...overrides
1832
+ },
1833
+ overrides
1834
+ );
1835
+ }
1836
+
1837
+ // src/agents/ui-designer.ts
1838
+ var SYSTEM12 = `You are a UI/UX designer. Your job is to translate architecture and requirements into a detailed, developer-ready UI design specification.
1839
+
1840
+ Responsibilities:
1841
+ - Define the component inventory: every page, section, and reusable component
1842
+ - Specify layouts, spacing principles, and responsive breakpoints
1843
+ - Define interaction patterns: loading states, empty states, error states, transitions
1844
+ - Specify design tokens: color palette, typography scale, spacing scale, shadow levels
1845
+ - Describe accessibility requirements: ARIA roles, keyboard navigation, focus management
1846
+ - Do not write implementation code \u2014 produce specification documents only
1847
+
1848
+ Deliverables (save to the working directory):
1849
+ - ui-design.md \u2014 full UI design specification: component inventory, page layouts, interaction flows, design tokens, accessibility requirements
1850
+
1851
+ Principles: Be specific enough that a developer can implement without guessing. Every component gets a name, purpose, props/variants, and states. Flag anything that depends on backend data.`;
1852
+ var TASK12 = `## Task Scope
1853
+ {{agentScope}}
1854
+
1855
+ ## Plan
1856
+ {{agentPlan}}
1857
+ {{upstreamOutputs}}
1858
+
1859
+ ---
1860
+
1861
+ ## Project
1862
+ {{projectName}}
1863
+
1864
+ ## Requirement
1865
+ {{requirement}}
1866
+
1867
+ ## Architecture Design
1868
+ {{file:architecture.md}}
1869
+
1870
+ ## API Specification
1871
+ {{file:api-spec.md}}
1872
+
1873
+ ## Task
1874
+ Create ui-design.md covering:
1875
+ 1. **Component Inventory** \u2014 list every page and reusable component; for each: name, purpose, variants/states, props
1876
+ 2. **Page Layouts** \u2014 describe the visual structure of each page (header, main, sidebar, footer zones); include responsive behaviour
1877
+ 3. **Interaction Flows** \u2014 key user flows with step-by-step state transitions (loading \u2192 success \u2192 error)
1878
+ 4. **Design Tokens** \u2014 color palette (primary, neutral, semantic), typography scale, spacing scale
1879
+ 5. **Accessibility** \u2014 ARIA roles/labels for interactive components, keyboard nav, focus order
1880
+
1881
+ Be concrete. Reference API endpoints where components bind to data. Flag any UX decision that needs product clarification.`;
1882
+ function uiDesigner(overrides) {
1883
+ return markPresetTools(
1884
+ {
1885
+ id: "ui-designer",
1886
+ name: "UI Designer",
1887
+ icon: "\u25A3",
1888
+ description: "specs the interface",
1889
+ runtime: "acp",
1890
+ models: { acp: "sonnet" },
1891
+ modelTier: "balanced",
1892
+ systemPrompt: SYSTEM12,
1893
+ taskPrompt: TASK12,
1894
+ tools: ["Read", "Write"],
1895
+ ...overrides
1896
+ },
1897
+ overrides
1898
+ );
1899
+ }
1900
+
1901
+ // src/agents/index.ts
1902
+ var agents = {
1903
+ leader,
1904
+ architect,
1905
+ productManager,
1906
+ backendDeveloper,
1907
+ frontendDeveloper,
1908
+ tester,
1909
+ reviewer,
1910
+ archDesignReviewer,
1911
+ uiDesigner,
1912
+ uiDesignReviewer,
1913
+ codeReviewer,
1914
+ devops
1915
+ };
1916
+
1917
+ // src/config/defineConfig.ts
1918
+ function defineConfig(config) {
1919
+ return config;
1920
+ }
1921
+
1922
+ // src/event/EventBus.ts
1923
+ var EventBus = class {
1924
+ constructor() {
1925
+ this.listeners = /* @__PURE__ */ new Set();
1926
+ }
1927
+ subscribe(listener) {
1928
+ this.listeners.add(listener);
1929
+ return () => this.listeners.delete(listener);
1930
+ }
1931
+ emit(event) {
1932
+ for (const listener of this.listeners) {
1933
+ try {
1934
+ listener(event);
1935
+ } catch (err) {
1936
+ console.error("EventBus listener error:", err);
1937
+ }
1938
+ }
1939
+ }
1940
+ clear() {
1941
+ this.listeners.clear();
1942
+ }
1943
+ };
1944
+
1945
+ // src/orchestrator/AgentSessionManager.ts
1946
+ var AgentSessionManager = class {
1947
+ constructor() {
1948
+ this.entries = /* @__PURE__ */ new Map();
1949
+ this.closed = false;
1950
+ }
1951
+ async execute(runtime, task) {
1952
+ if (this.closed) throw new Error("AgentSessionManager is closed");
1953
+ if (this.resetting) throw new Error("AgentSessionManager is resetting");
1954
+ if (task.signal?.aborted) throw abortError();
1955
+ let entry3 = this.entries.get(task.agentId);
1956
+ if (entry3?.busy || entry3?.session && entry3.session.state !== "idle" && entry3.session.state !== "closed") {
1957
+ throw new Error(`Agent session ${task.agentId} is busy`);
1958
+ }
1959
+ if (entry3?.closing) await entry3.closing;
1960
+ const fingerprint = JSON.stringify([
1961
+ task.command,
1962
+ task.args,
1963
+ task.model,
1964
+ task.workDir,
1965
+ task.systemPrompt,
1966
+ task.tools,
1967
+ task.sessionId,
1968
+ task.resume,
1969
+ Boolean(task.onQuestion)
1970
+ ]);
1971
+ if (entry3 && (entry3.runtime !== runtime || entry3.fingerprint !== fingerprint || entry3.session?.state === "closed" || !runtime.openSession)) {
1972
+ entry3.busy = true;
1973
+ try {
1974
+ await this.closeEntry(entry3);
1975
+ this.entries.delete(task.agentId);
1976
+ } finally {
1977
+ entry3.busy = false;
1978
+ }
1979
+ entry3 = void 0;
1980
+ if (this.closed || this.resetting) throw abortError();
1981
+ }
1982
+ if (task.signal?.aborted) throw abortError();
1983
+ const openSession = runtime.openSession;
1984
+ if (!openSession) return runtime.execute(task);
1985
+ let detach;
1986
+ if (!entry3) {
1987
+ const startup = new AbortController();
1988
+ const forwardAbort = () => startup.abort(task.signal?.reason);
1989
+ task.signal?.addEventListener("abort", forwardAbort, { once: true });
1990
+ detach = () => task.signal?.removeEventListener("abort", forwardAbort);
1991
+ const created = {
1992
+ runtime,
1993
+ fingerprint,
1994
+ startup,
1995
+ busy: true,
1996
+ onWarning: task.onWarning,
1997
+ // Defer opening until the cache entry is installed, including synchronous failures.
1998
+ opening: Promise.resolve().then(
1999
+ () => openSession.call(runtime, {
2000
+ agentId: task.agentId,
2001
+ systemPrompt: task.systemPrompt,
2002
+ tools: task.tools,
2003
+ workDir: task.workDir,
2004
+ command: task.command,
2005
+ args: task.args,
2006
+ model: task.model,
2007
+ sessionId: task.sessionId,
2008
+ resume: task.resume,
2009
+ timeout: task.timeout,
2010
+ questionForms: Boolean(task.onQuestion),
2011
+ signal: startup.signal,
2012
+ onWarning: (message) => created.onWarning?.(message)
2013
+ })
2014
+ ).then((session) => {
2015
+ created.session = session;
2016
+ return session;
2017
+ })
1923
2018
  };
1924
- const prompt = (text, promptOptions = {}) => {
1925
- if (state !== "idle") {
1926
- return Promise.reject(new Error(`Cannot prompt ACP session while ${state}`));
2019
+ entry3 = created;
2020
+ this.entries.set(task.agentId, entry3);
2021
+ } else {
2022
+ entry3.busy = true;
2023
+ entry3.onWarning = task.onWarning;
2024
+ }
2025
+ try {
2026
+ const session = await entry3.opening;
2027
+ detach?.();
2028
+ detach = void 0;
2029
+ if (entry3.startup.signal.aborted || this.closed || this.resetting) {
2030
+ await this.closeEntry(entry3);
2031
+ throw abortError();
2032
+ }
2033
+ if (session.state !== "idle") throw new Error(`Agent session ${task.agentId} is busy`);
2034
+ return await session.prompt(task.prompt, {
2035
+ signal: task.signal,
2036
+ timeout: task.timeout,
2037
+ onEvent: task.onEvent,
2038
+ permissionMode: task.permissionMode,
2039
+ onPermission: task.onPermission,
2040
+ onQuestion: task.onQuestion
2041
+ });
2042
+ } finally {
2043
+ detach?.();
2044
+ entry3.onWarning = void 0;
2045
+ try {
2046
+ if (entry3.session?.state === "closed") {
2047
+ await this.closeEntry(entry3);
2048
+ if (this.entries.get(task.agentId) === entry3) this.entries.delete(task.agentId);
2049
+ } else if (!entry3.session) {
2050
+ if (this.entries.get(task.agentId) === entry3) this.entries.delete(task.agentId);
1927
2051
  }
1928
- if (options.signal?.aborted || promptOptions.signal?.aborted) {
1929
- return Promise.reject(abortError());
2052
+ } finally {
2053
+ entry3.busy = false;
2054
+ }
2055
+ }
2056
+ }
2057
+ /**
2058
+ * Deliver a message into every session that is running a turn right now.
2059
+ *
2060
+ * Only `running` sessions are candidates, and that is the whole safety
2061
+ * argument: a session between turns has nothing to inject into, and asking a
2062
+ * provider to steer an idle session makes it *start* a turn that this manager
2063
+ * never scheduled — one whose output belongs to no turn and which nothing
2064
+ * would ever settle. Sessions that are idle are therefore not reported as
2065
+ * failures but simply absent, and the caller sees an empty list.
2066
+ *
2067
+ * One agent failing never stops the others: each report stands alone, because
2068
+ * the caller has to be able to say "architect took it, qa did not" rather than
2069
+ * "steering failed".
2070
+ */
2071
+ async supplement(text) {
2072
+ if (this.closed) return [];
2073
+ const targets = [...this.entries.entries()].filter(
2074
+ ([, entry3]) => entry3.session?.state === "running"
2075
+ );
2076
+ return await Promise.all(
2077
+ targets.map(async ([agentId, entry3]) => {
2078
+ const session = entry3.session;
2079
+ if (!session) return { agentId, status: "idle" };
2080
+ if (!session.capabilities.supplement || !session.supplement) {
2081
+ return { agentId, status: "unsupported" };
1930
2082
  }
1931
- let duration;
1932
2083
  try {
1933
- duration = timeoutMs(promptOptions.timeout ?? defaultTimeout);
2084
+ return { agentId, status: (await session.supplement(text)).status };
1934
2085
  } catch (error) {
1935
- return Promise.reject(error);
1936
- }
1937
- let resolve4;
1938
- let reject;
1939
- const promise = new Promise((res, rej) => {
1940
- resolve4 = res;
1941
- reject = rej;
1942
- });
1943
- const turn = {
1944
- runId: randomUUID(),
1945
- seq: 0,
1946
- options: promptOptions,
1947
- output: "",
1948
- decisions: new AbortController(),
1949
- promise,
1950
- resolve: resolve4,
1951
- reject
1952
- };
1953
- active = turn;
1954
- state = "running";
1955
- turn.onAbort = () => {
1956
- turn.error = abortError();
1957
- void cancelTurn().catch(() => {
1958
- });
1959
- };
1960
- promptOptions.signal?.addEventListener("abort", turn.onAbort, { once: true });
1961
- turn.timer = setTimeout(() => {
1962
- turn.error = new Error(`acp timed out (${duration}ms)`);
1963
- fail(turn.error);
1964
- }, duration);
1965
- const run = async () => {
1966
- emit({ type: "run_started", model: options.model });
1967
- if (active !== turn) return;
1968
- const response = await ctx.request(acp.methods.agent.session.prompt, {
1969
- sessionId,
1970
- prompt: [
1971
- {
1972
- type: "text",
1973
- text: meta === void 0 && options.systemPrompt ? `${options.systemPrompt}
1974
-
1975
- ---
1976
-
1977
- ${text}` : text
1978
- }
1979
- ]
1980
- });
1981
- if (active !== turn) return;
1982
- if (turn.error) {
1983
- settleTurn(turn, void 0, turn.error);
1984
- return;
1985
- }
1986
- const stopReason = mapStopReason(response.stopReason);
1987
- settleTurn(turn, {
1988
- output: turn.output,
1989
- exitCode: stopReason === "success" ? 0 : 1,
1990
- sessionId,
1991
- stopReason,
1992
- ...turn.usage ? { usage: turn.usage } : {},
1993
- ...turn.cost?.currency.toLowerCase() === "usd" ? { costUsd: turn.cost.amount } : {}
1994
- });
1995
- emitForTurn(turn, { type: "run_finished", stopReason });
1996
- };
1997
- void run().catch((error) => {
1998
- if (active === turn) fail(withAuthHint(acp, error));
1999
- });
2000
- return promise;
2001
- };
2002
- const session = {
2003
- get sessionId() {
2004
- return sessionId;
2005
- },
2006
- get state() {
2007
- return state;
2008
- },
2009
- get capabilities() {
2010
- return { continuation: true, supplement: steeringSupported };
2011
- },
2012
- prompt,
2013
- supplement,
2014
- cancelTurn,
2015
- close
2016
- };
2017
- const warn = (message) => {
2018
- if (options.onWarning) options.onWarning(message);
2019
- else process.stderr.write(`[multiclaw] Warning: ${message}
2020
- `);
2021
- };
2022
- const initialize = async () => {
2023
- const init = await ctx.request(acp.methods.agent.initialize, {
2024
- protocolVersion: acp.PROTOCOL_VERSION,
2025
- ...questionForms ? { clientCapabilities: { elicitation: { form: {} } } } : {}
2026
- });
2027
- if (terminalError) throw terminalError;
2028
- steeringSupported = advertisesSteering(init);
2029
- if (options.sessionId) {
2030
- if (init.agentCapabilities?.loadSession !== true) {
2031
- throw new PermanentError(
2032
- `Agent does not support session/load (loadSession=false); cannot resume session ${options.sessionId}`
2033
- );
2034
- }
2035
- await ctx.request(acp.methods.agent.session.load, {
2036
- sessionId: options.sessionId,
2037
- cwd: options.workDir,
2038
- mcpServers: [],
2039
- ...meta ? { _meta: meta } : {}
2040
- });
2041
- sessionId = options.sessionId;
2042
- } else {
2043
- const created = await ctx.request(acp.methods.agent.session.new, {
2044
- cwd: options.workDir,
2045
- mcpServers: [],
2046
- ...meta ? { _meta: meta } : {}
2047
- });
2048
- sessionId = created.sessionId;
2049
- const modelOpt = created.configOptions?.find(
2050
- (option) => option.category === "model" || option.id === "model"
2051
- );
2052
- if (modelOpt && "options" in modelOpt && Array.isArray(modelOpt.options)) {
2053
- discoveredModels.set(
2054
- command,
2055
- (modelOpt.options ?? []).map(
2056
- (option) => option.value ?? String(option)
2057
- )
2058
- );
2059
- }
2086
+ return {
2087
+ agentId,
2088
+ status: "error",
2089
+ error: error instanceof Error ? error.message : String(error)
2090
+ };
2060
2091
  }
2061
- if (terminalError) throw terminalError;
2062
- if (options.model && spec?.modelSelection === "config-option") {
2063
- const known = discoveredModels.get(command);
2064
- if (known && !known.includes(options.model)) {
2065
- warn(
2066
- `model "${options.model}" is not offered by ${command}; running with the provider's default.`
2067
- );
2068
- } else {
2069
- try {
2070
- await ctx.request(acp.methods.agent.session.setConfigOption, {
2071
- sessionId,
2072
- configId: "model",
2073
- value: options.model
2074
- });
2075
- } catch (error) {
2076
- if (terminalError) throw terminalError;
2077
- warn(
2078
- `Could not set model "${options.model}" on ${command}; running with the provider's default (${errorMessage(error)}).`
2079
- );
2080
- }
2081
- }
2092
+ })
2093
+ );
2094
+ }
2095
+ /** Closes all sessions and permits a fresh conversation after cleanup completes. */
2096
+ reset() {
2097
+ if (this.closing) return this.closing;
2098
+ if (this.resetting) return this.resetting;
2099
+ this.resetting = this.drain().finally(() => {
2100
+ this.resetting = void 0;
2101
+ });
2102
+ return this.resetting;
2103
+ }
2104
+ /** Terminal, idempotent cleanup barrier. No new executions may start. */
2105
+ close() {
2106
+ if (this.closing) return this.closing;
2107
+ this.closed = true;
2108
+ this.closing = this.resetting ?? this.drain();
2109
+ return this.closing;
2110
+ }
2111
+ async drain() {
2112
+ const entries = [...this.entries.entries()];
2113
+ for (const [, entry3] of entries) entry3.startup.abort();
2114
+ const results = await Promise.allSettled(
2115
+ entries.map(async ([id, entry3]) => {
2116
+ await this.closeEntry(entry3);
2117
+ if (this.entries.get(id) === entry3) this.entries.delete(id);
2118
+ })
2119
+ );
2120
+ const errors = results.flatMap(
2121
+ (result) => result.status === "rejected" ? [result.reason] : []
2122
+ );
2123
+ if (errors.length === 1) throw errors[0];
2124
+ if (errors.length > 1) throw new AggregateError(errors, "Agent session cleanup failed");
2125
+ }
2126
+ closeEntry(entry3) {
2127
+ if (!entry3.closing) {
2128
+ entry3.closing = (async () => {
2129
+ let session;
2130
+ try {
2131
+ session = await entry3.opening;
2132
+ } catch (error) {
2133
+ if (isAbortError(error)) return;
2134
+ throw error;
2082
2135
  }
2083
- if (terminalError) throw terminalError;
2084
- if (options.signal?.aborted) throw abortError();
2085
- };
2086
- await Promise.race([
2087
- initialize().catch((error) => {
2088
- throw withAuthHint(acp, error);
2089
- }),
2090
- startupFailure
2091
- ]);
2092
- clearTimeout(startupTimer);
2093
- return session;
2094
- } catch (error) {
2095
- clearTimeout(startupTimer);
2096
- options.signal?.removeEventListener("abort", onSessionAbort);
2097
- if (cleanup) await cleanup();
2098
- throw error;
2136
+ await session.close();
2137
+ })();
2099
2138
  }
2139
+ return entry3.closing;
2100
2140
  }
2101
2141
  };
2102
2142
 
2103
- // src/runtime/index.ts
2104
- var RuntimeRegistry = class {
2105
- constructor() {
2106
- this.runtimes = /* @__PURE__ */ new Map();
2107
- this.register(new AcpRuntime());
2143
+ // src/orchestrator/Orchestrator.ts
2144
+ import * as fs4 from "fs";
2145
+ import * as path5 from "path";
2146
+
2147
+ // src/utils/conversation.ts
2148
+ var MAX_CONVERSATION_TURNS = 6;
2149
+ var MAX_CONVERSATION_CHARS = 4e3;
2150
+ var MAX_ENTRY_CHARS = 600;
2151
+ var ELLIPSIS = "\u2026";
2152
+ function clip(text, max) {
2153
+ const trimmed = text.trim();
2154
+ if (trimmed.length <= max) return trimmed;
2155
+ return `${trimmed.slice(0, Math.max(0, max - 1)).trimEnd()}${ELLIPSIS}`;
2156
+ }
2157
+ function agentSummary(label, agents2, format) {
2158
+ let text = `${label}: `;
2159
+ if (agents2.length === 0) text += "none";
2160
+ for (let i = 0; i < agents2.length; i++) {
2161
+ text += `${i > 0 ? ", " : ""}${clip(format(agents2[i]), MAX_ENTRY_CHARS)}`;
2162
+ if (text.length >= MAX_ENTRY_CHARS - 3) {
2163
+ if (i < agents2.length - 1) text += ELLIPSIS;
2164
+ break;
2165
+ }
2108
2166
  }
2109
- register(r) {
2110
- this.runtimes.set(r.name, r);
2167
+ return ` ${clip(text, MAX_ENTRY_CHARS - 3)}`;
2168
+ }
2169
+ function entry(turn, index) {
2170
+ const lines = [`${index}. user: ${clip(turn.requirement, MAX_ENTRY_CHARS)}`];
2171
+ if (turn.reply) {
2172
+ const verb = turn.reply.mode === "ask" ? "asked" : "answered";
2173
+ lines.push(` you ${verb}: ${clip(turn.reply.message, MAX_ENTRY_CHARS)}`);
2174
+ } else if (turn.outcome) {
2175
+ const { execution, completedAgents, failedAgents, acceptance } = turn.outcome;
2176
+ lines.push(
2177
+ ` ${clip(`execution: ${execution}`, MAX_ENTRY_CHARS - 3)}`,
2178
+ agentSummary("completed", completedAgents, (agentId) => agentId),
2179
+ agentSummary(
2180
+ "failed",
2181
+ failedAgents,
2182
+ ({ agentId, reason }) => reason ? `${agentId} (${reason})` : agentId
2183
+ ),
2184
+ ` ${clip(
2185
+ `acceptance: ${acceptance ? `${acceptance.status}${acceptance.reason ? ` (${acceptance.reason})` : ""}` : "not configured"}`,
2186
+ MAX_ENTRY_CHARS - 3
2187
+ )}`
2188
+ );
2111
2189
  }
2112
- get(name) {
2113
- const r = this.runtimes.get(name);
2114
- if (!r)
2115
- throw new Error(
2116
- `Runtime not found: "${name}". Available: ${[...this.runtimes.keys()].join(", ")}`
2117
- );
2118
- return r;
2190
+ return lines.join("\n");
2191
+ }
2192
+ function renderConversation(history) {
2193
+ if (!history || history.length === 0) return "";
2194
+ const recent = history.slice(-MAX_CONVERSATION_TURNS);
2195
+ const first = history.length - recent.length;
2196
+ const entries = recent.map((turn, i) => entry(turn, first + i + 1));
2197
+ while (entries.length > 1 && entries.join("\n").length > MAX_CONVERSATION_CHARS) {
2198
+ entries.shift();
2119
2199
  }
2120
- has(name) {
2121
- return this.runtimes.has(name);
2200
+ const body = clip(entries.join("\n"), MAX_CONVERSATION_CHARS);
2201
+ return `
2202
+ ## Conversation so far
2203
+
2204
+ Earlier turns of this session, oldest first:
2205
+
2206
+ ${body}
2207
+ `;
2208
+ }
2209
+
2210
+ // src/utils/json.ts
2211
+ function extractJsonObjects(text) {
2212
+ const objects = [];
2213
+ let searchFrom = 0;
2214
+ while (searchFrom < text.length) {
2215
+ const start = text.indexOf("{", searchFrom);
2216
+ if (start === -1) break;
2217
+ const end = findMatchingBrace(text, start);
2218
+ if (end !== -1) {
2219
+ try {
2220
+ objects.push(JSON.parse(text.slice(start, end + 1)));
2221
+ searchFrom = end + 1;
2222
+ continue;
2223
+ } catch {
2224
+ }
2225
+ }
2226
+ searchFrom = start + 1;
2122
2227
  }
2123
- list() {
2124
- return [...this.runtimes.keys()];
2228
+ return objects;
2229
+ }
2230
+ function findMatchingBrace(text, start) {
2231
+ let depth = 0;
2232
+ let inString = false;
2233
+ let escaped = false;
2234
+ for (let i = start; i < text.length; i++) {
2235
+ const ch = text[i];
2236
+ if (inString) {
2237
+ if (escaped) escaped = false;
2238
+ else if (ch === "\\") escaped = true;
2239
+ else if (ch === '"') inString = false;
2240
+ continue;
2241
+ }
2242
+ if (ch === '"') inString = true;
2243
+ else if (ch === "{") depth++;
2244
+ else if (ch === "}") {
2245
+ depth--;
2246
+ if (depth === 0) return i;
2247
+ }
2125
2248
  }
2126
- };
2127
- var runtimeRegistry = new RuntimeRegistry();
2249
+ return -1;
2250
+ }
2251
+
2252
+ // src/utils/leaderDecision.ts
2253
+ function parseLeaderDecision(text) {
2254
+ for (const value of extractJsonObjects(text)) {
2255
+ const decision = asDecision(value);
2256
+ if (decision) return decision;
2257
+ }
2258
+ return void 0;
2259
+ }
2260
+ function asDecision(value) {
2261
+ if (typeof value !== "object" || value === null) return void 0;
2262
+ const record = value;
2263
+ const mode = record.mode;
2264
+ if (mode === "reply" || mode === "ask") {
2265
+ const message = typeof record.message === "string" ? record.message.trim() : "";
2266
+ return message ? { mode, message } : void 0;
2267
+ }
2268
+ if (mode === "run" || mode === void 0) {
2269
+ const run = record.run;
2270
+ if (!Array.isArray(run) || !run.every((id) => typeof id === "string")) return void 0;
2271
+ const reason = typeof record.reason === "string" ? record.reason.trim() : "";
2272
+ const requirement = typeof record.requirement === "string" ? record.requirement.trim() : "";
2273
+ if ("requirement" in record && !requirement) return void 0;
2274
+ return {
2275
+ mode: "run",
2276
+ run,
2277
+ ...reason ? { reason } : {},
2278
+ ...requirement ? { requirement } : {}
2279
+ };
2280
+ }
2281
+ return void 0;
2282
+ }
2283
+
2284
+ // src/utils/upstream.ts
2285
+ var MAX_UPSTREAM_ENTRY_CHARS = 600;
2286
+ var MAX_UPSTREAM_CHARS = 4e3;
2287
+ var ELLIPSIS2 = "\u2026";
2288
+ var HEADER = "\n## What upstream produced\n\n";
2289
+ var TRAILER = "\n";
2290
+ function block(entries) {
2291
+ return `${HEADER}${entries.join("\n")}${TRAILER}`;
2292
+ }
2293
+ function compact(text, max) {
2294
+ const trimmed = text.trim();
2295
+ if (trimmed.length <= max) return trimmed;
2296
+ const marker = (count) => `${ELLIPSIS2} (${count} characters elided) ${ELLIPSIS2}`;
2297
+ const reserved = marker(trimmed.length).length;
2298
+ const keep = Math.max(0, max - reserved);
2299
+ const head = Math.ceil(keep / 2);
2300
+ const tail = keep - head;
2301
+ const elided = trimmed.length - keep;
2302
+ return `${trimmed.slice(0, head)}${marker(elided)}${trimmed.slice(trimmed.length - tail)}`;
2303
+ }
2304
+ function entry2(output) {
2305
+ const label = `- ${output.name} (${output.agentId}):
2306
+ `;
2307
+ const budget = MAX_UPSTREAM_ENTRY_CHARS - label.length;
2308
+ let body = compact(output.output, budget);
2309
+ const newlines = body.length - body.replace(/\n/g, "").length;
2310
+ if (label.length + body.length + 2 * newlines > MAX_UPSTREAM_ENTRY_CHARS) {
2311
+ body = compact(output.output, budget - 2 * newlines);
2312
+ }
2313
+ return `${label}${body.replace(/\n/g, "\n ")}`;
2314
+ }
2315
+ function renderUpstreamOutputs(outputs) {
2316
+ if (outputs.length === 0) return "";
2317
+ const entries = outputs.map(entry2);
2318
+ while (entries.length > 1 && block(entries).length > MAX_UPSTREAM_CHARS) {
2319
+ entries.shift();
2320
+ }
2321
+ return block(entries);
2322
+ }
2323
+
2324
+ // src/orchestrator/AgentRunner.ts
2325
+ import * as fs3 from "fs";
2326
+ import * as path4 from "path";
2128
2327
 
2129
2328
  // src/utils/prompt.ts
2130
2329
  import * as fs2 from "fs/promises";
@@ -2234,31 +2433,6 @@ function withTimeout(factory, ms, label, signal, options) {
2234
2433
  });
2235
2434
  }
2236
2435
 
2237
- // src/utils/toolSummary.ts
2238
- var MAX_SUMMARY_COLUMNS = 120;
2239
- function stringifySafe(value) {
2240
- if (typeof value === "string") return value;
2241
- if (value === void 0 || value === null) return "";
2242
- try {
2243
- return JSON.stringify(value) ?? "";
2244
- } catch {
2245
- return String(value);
2246
- }
2247
- }
2248
- function firstLineTruncated(value) {
2249
- const text = stringifySafe(value);
2250
- const newline = text.indexOf("\n");
2251
- const firstLine = newline === -1 ? text : text.slice(0, newline);
2252
- if (firstLine.length <= MAX_SUMMARY_COLUMNS) return firstLine;
2253
- return `${firstLine.slice(0, MAX_SUMMARY_COLUMNS - 1)}\u2026`;
2254
- }
2255
- function summarizeToolInput(input) {
2256
- return firstLineTruncated(input);
2257
- }
2258
- function summarizeToolOutput(output) {
2259
- return firstLineTruncated(output);
2260
- }
2261
-
2262
2436
  // src/orchestrator/AgentRunner.ts
2263
2437
  var AgentRunner = class {
2264
2438
  constructor(eventBus, contextManager, globalWorkDir, config, sessionManager) {
@@ -2319,6 +2493,16 @@ ${prompt}`;
2319
2493
  if (instruction) prompt += `
2320
2494
 
2321
2495
  ${instruction}`;
2496
+ const toolRows = /* @__PURE__ */ new Set();
2497
+ const toolNames = /* @__PURE__ */ new Map();
2498
+ const printToolRow = (id, name, input) => {
2499
+ if (toolRows.has(id)) return;
2500
+ toolRows.add(id);
2501
+ const summary = summarizeToolInput(input);
2502
+ this.emitOutput(agent.id, `
2503
+ \u203A ${name}${summary ? ` ${summary}` : ""}
2504
+ `, "tool");
2505
+ };
2322
2506
  const task = {
2323
2507
  agentId: agent.id,
2324
2508
  systemPrompt: agent.systemPrompt,
@@ -2360,17 +2544,13 @@ ${instruction}`;
2360
2544
  return;
2361
2545
  }
2362
2546
  if (e.type === "tool_call") {
2363
- const summary = summarizeToolInput(e.input);
2364
- this.emitOutput(
2365
- agent.id,
2366
- `
2367
- \u203A ${e.name}${summary ? ` ${summary}` : ""}
2368
- `,
2369
- "tool"
2370
- );
2547
+ toolNames.set(e.id, e.name);
2548
+ if (summarizeToolInput(e.input)) printToolRow(e.id, e.name, e.input);
2371
2549
  return;
2372
2550
  }
2373
2551
  if (e.type === "tool_result") {
2552
+ const name = toolNames.get(e.id);
2553
+ if (name !== void 0) printToolRow(e.id, name, void 0);
2374
2554
  const summary = summarizeToolOutput(e.output);
2375
2555
  this.emitOutput(
2376
2556
  agent.id,
@@ -2542,8 +2722,19 @@ var Orchestrator = class {
2542
2722
  );
2543
2723
  }
2544
2724
  async preview(options = {}) {
2725
+ if (options.signal?.aborted)
2726
+ return { name: this.config.name, totalAgents: 0, stages: [], ...this.requirementField() };
2545
2727
  const policyError = this.reviewPolicyError();
2546
2728
  if (policyError) throw new Error(policyError);
2729
+ try {
2730
+ await validateToolsPolicy(this.config, options);
2731
+ } catch (error) {
2732
+ if (options.signal?.aborted)
2733
+ return { name: this.config.name, totalAgents: 0, stages: [], ...this.requirementField() };
2734
+ throw error;
2735
+ }
2736
+ if (options.signal?.aborted)
2737
+ return { name: this.config.name, totalAgents: 0, stages: [], ...this.requirementField() };
2547
2738
  this.clearStaleTaskPlan();
2548
2739
  const resolution = await this.resolveTurn(options.signal);
2549
2740
  if (resolution.kind === "cancelled" || options.signal?.aborted) {
@@ -2587,6 +2778,14 @@ var Orchestrator = class {
2587
2778
  });
2588
2779
  return result2;
2589
2780
  }
2781
+ try {
2782
+ await validateToolsPolicy(this.config, options);
2783
+ } catch (error) {
2784
+ if (options.signal?.aborted) return this.finishCancelled(startTime);
2785
+ this.warn(errorMessage2(error));
2786
+ return this.finishEmpty(startTime, void 0, false);
2787
+ }
2788
+ if (options.signal?.aborted) return this.finishCancelled(startTime);
2590
2789
  this.clearStaleTaskPlan();
2591
2790
  const resolution = await this.resolveTurn(options.signal);
2592
2791
  if (resolution.kind === "cancelled" || options.signal?.aborted) {
@@ -3171,9 +3370,9 @@ Address these findings within your assigned scope, preserve the complete task re
3171
3370
  * only honest outcome is to say that none was done. Running the whole team
3172
3371
  * instead would contradict the leader's explicit choice.
3173
3372
  */
3174
- finishEmpty(startTime, acceptance) {
3373
+ finishEmpty(startTime, acceptance, warnEmpty = true) {
3175
3374
  const usedLeader = this.config.leader !== void 0 && this.config.useLeader !== false;
3176
- if (!acceptance?.reason)
3375
+ if (warnEmpty && !acceptance?.reason)
3177
3376
  this.warn(
3178
3377
  usedLeader ? "The leader selected none of the configured agents \u2014 nothing to run." : "The config lists no agents \u2014 nothing to run."
3179
3378
  );
@@ -3358,6 +3557,7 @@ export {
3358
3557
  defineConfig,
3359
3558
  describeResumePlan,
3360
3559
  detectProviders,
3560
+ hasExplicitTools,
3361
3561
  isAbortError,
3362
3562
  presentProviders,
3363
3563
  providerCommands,
@@ -3374,5 +3574,6 @@ export {
3374
3574
  specForCommand,
3375
3575
  specForProvider,
3376
3576
  tierModel,
3377
- validateRuntimeQuestionContent
3577
+ validateRuntimeQuestionContent,
3578
+ validateToolsPolicy
3378
3579
  };