@yukino.js/yukino 0.0.13-dev → 0.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +20 -16
  2. package/dist/{a2a-DG2JNM3U.js → a2a-D7KSHNUT.js} +4 -3
  3. package/dist/{acp-DCZDS6FQ.js → acp-W4R5P6CZ.js} +7 -7
  4. package/dist/{anthropic-5BTWVZVT.js → anthropic-DSNN5AE5.js} +1 -1
  5. package/dist/browser/dist/index.html +44 -0
  6. package/dist/browser/dist/static/index.css +2 -0
  7. package/dist/{fe → browser}/dist/static/index.js +48 -48
  8. package/dist/{chunk-4CLD7LEU.js → chunk-A7CJPQC5.js} +1 -1
  9. package/dist/{chunk-COHBT6M7.js → chunk-D2SZ6GQJ.js} +184 -186
  10. package/dist/{chunk-AZQD75PX.js → chunk-GVRZBATW.js} +1 -1
  11. package/dist/{chunk-OI2W6R6H.js → chunk-HWCLMDQF.js} +8 -8
  12. package/dist/{chunk-BDLFNDC4.js → chunk-I356BFD2.js} +1 -1
  13. package/dist/chunk-JDK4YHNF.js +63 -0
  14. package/dist/{chunk-5URXBVET.js → chunk-OREDGNI6.js} +1 -1
  15. package/dist/chunk-T6WQ3Z5J.js +4 -0
  16. package/dist/{chunk-5DK2M7VI.js → chunk-UUWXDH7J.js} +1 -1
  17. package/dist/{chunk-IWMCIYOG.js → chunk-WKSVBXUO.js} +26 -25
  18. package/dist/{chunk-SZXXASVH.js → chunk-Z3EFT645.js} +1 -1
  19. package/dist/lib/{anthropic-AVZIC22O.js → anthropic-TDNNKQMT.js} +4 -4
  20. package/dist/lib/{chunk-O2H6VKKR.js → chunk-56DL5ZYL.js} +2 -2
  21. package/dist/lib/{chunk-TUNZLQLO.js → chunk-BRLCCEU7.js} +1 -1
  22. package/dist/lib/{chunk-EGJKLA2W.js → chunk-EJNKEFE7.js} +2 -2
  23. package/dist/lib/{chunk-XH7D5FLE.js → chunk-IZXMDC5O.js} +3 -3
  24. package/dist/lib/{chunk-QJ32WYQY.js → chunk-UKXGO7AW.js} +264 -324
  25. package/dist/lib/{chunk-GVI5R2DA.js → chunk-WNGF7243.js} +1 -2
  26. package/dist/lib/{chunk-LSI3T24Q.js → chunk-WXR5HNB4.js} +1 -1
  27. package/dist/lib/index.d.ts +118 -298
  28. package/dist/lib/index.js +472 -1235
  29. package/dist/lib/{openai-54IQOU6Y.js → openai-6VYIA7CT.js} +3 -3
  30. package/dist/lib/{providers-MOCB6Y5L.js → providers-UXL5FVF7.js} +2 -2
  31. package/dist/lib/{tool-filter-5Z6UTRRR.js → tool-filter-O6YLSFAS.js} +3 -3
  32. package/dist/{main-IA22XMQR.js → main-FOIMPIOD.js} +232 -223
  33. package/dist/main.js +11 -2
  34. package/dist/{openai-I2TTMBWK.js → openai-7C6BVQ7M.js} +1 -1
  35. package/dist/{providers-DXQRJUIY.js → providers-TH6MQC7V.js} +1 -1
  36. package/dist/{server-QS7CX37F.js → server-TC5GDF6E.js} +1 -1
  37. package/dist/tool-filter-SYH5ZFC2.js +4 -0
  38. package/package.json +6 -6
  39. package/dist/chunk-CW5XFH7H.js +0 -59
  40. package/dist/chunk-UGX62ZSO.js +0 -4
  41. package/dist/fe/dist/index.html +0 -21
  42. package/dist/fe/dist/static/index.css +0 -2
  43. package/dist/tool-filter-KDQMXIDC.js +0 -4
package/dist/lib/index.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  providers_exports,
4
4
  version,
5
5
  version_exports
6
- } from "./chunk-EGJKLA2W.js";
6
+ } from "./chunk-EJNKEFE7.js";
7
7
  import {
8
8
  bwrap_exports
9
9
  } from "./chunk-XLRV26YW.js";
@@ -14,10 +14,10 @@ import {
14
14
  anthropic_exports,
15
15
  decideAndApply,
16
16
  strategy_exports
17
- } from "./chunk-XH7D5FLE.js";
17
+ } from "./chunk-IZXMDC5O.js";
18
18
  import {
19
19
  openai_exports
20
- } from "./chunk-O2H6VKKR.js";
20
+ } from "./chunk-56DL5ZYL.js";
21
21
  import {
22
22
  ContextTooLongError,
23
23
  DEFAULT_CONTEXT_WINDOW,
@@ -44,13 +44,12 @@ import {
44
44
  persistThinkingLevel,
45
45
  resolveDefaultProvider,
46
46
  withProjectMcpServers
47
- } from "./chunk-TUNZLQLO.js";
47
+ } from "./chunk-BRLCCEU7.js";
48
48
  import {
49
49
  AgentTool,
50
50
  BUILTIN_AGENTS,
51
51
  LEADER_NAME,
52
52
  LoadSkillTool,
53
- MSG_PLAN_APPROVAL_RESPONSE,
54
53
  PermissionChecker,
55
54
  SHUTDOWN_PREFIX,
56
55
  SendMessageTool,
@@ -68,15 +67,10 @@ import {
68
67
  TaskUpdateTool,
69
68
  TeamCreateTool,
70
69
  TeamDeleteTool,
71
- TeamTaskCreateTool,
72
- TeamTaskGetTool,
73
- TeamTaskListTool,
74
- TeamTaskUpdateTool,
75
70
  TodoWriteTool,
76
71
  ToolRegistry,
77
72
  ToolSearchTool,
78
73
  agent_tool_exports,
79
- approved,
80
74
  buildSkillSection,
81
75
  catalog_exports,
82
76
  createAgentWorktree,
@@ -91,18 +85,16 @@ import {
91
85
  isShutdownRequest,
92
86
  isValidTeammateName,
93
87
  listTeamNames,
94
- loadAgentDefinitions,
95
88
  load_skill_tool_exports,
96
89
  loader_exports,
97
90
  mergeTaskMetadata,
98
91
  parseSkillFile,
99
92
  permissions_exports,
100
93
  planApprovalRequest,
94
+ planApprovalResponse,
101
95
  protocol_exports,
102
96
  readTeamFile,
103
- readTeamFileAtPath,
104
97
  registerLeaderTaskTools,
105
- registerTeammateProcess,
106
98
  registry_exports,
107
99
  registry_exports2,
108
100
  removeAgentWorktree,
@@ -126,7 +118,7 @@ import {
126
118
  withFileSyncLock,
127
119
  worktree_exports,
128
120
  writeTeamFile
129
- } from "./chunk-QJ32WYQY.js";
121
+ } from "./chunk-UKXGO7AW.js";
130
122
  import {
131
123
  MCPToolWrapper,
132
124
  MCP_TOOL_PREFIX,
@@ -136,7 +128,7 @@ import {
136
128
  normalizeToolResultContentBlock,
137
129
  tool_wrapper_exports,
138
130
  types_exports
139
- } from "./chunk-LSI3T24Q.js";
131
+ } from "./chunk-WXR5HNB4.js";
140
132
  import {
141
133
  asErrorString,
142
134
  asRecord,
@@ -148,7 +140,6 @@ import {
148
140
  generateSlug,
149
141
  getSessionsDir,
150
142
  getYukinoDir,
151
- initLogger,
152
143
  intArg,
153
144
  isObject,
154
145
  isRecord,
@@ -156,12 +147,11 @@ import {
156
147
  logger_exports,
157
148
  projectPath,
158
149
  safeJSONParse,
159
- sanitizeNameSegment,
160
150
  sessionPath,
161
151
  strArg,
162
152
  utils_exports,
163
153
  yukinoPath
164
- } from "./chunk-GVI5R2DA.js";
154
+ } from "./chunk-WNGF7243.js";
165
155
  import {
166
156
  __export,
167
157
  canonicalPath,
@@ -441,7 +431,7 @@ __export(server_exports, {
441
431
  RemoteServer: () => RemoteServer,
442
432
  createRemoteAgent: () => createRemoteAgent
443
433
  });
444
- import { readFileSync as readFileSync12, existsSync as existsSync14, statSync as statSync10 } from "fs";
434
+ import { readFileSync as readFileSync12, existsSync as existsSync13, statSync as statSync10 } from "fs";
445
435
  import { createServer } from "http";
446
436
  import { join as join20, extname as extname4, normalize } from "path";
447
437
  import { cwd } from "process";
@@ -495,8 +485,8 @@ function preview(text) {
495
485
  return `${text.slice(0, TEXT_PREVIEW_CHARS)}\u2026 (+${String(text.length - TEXT_PREVIEW_CHARS)} chars)`;
496
486
  }
497
487
  var AgentEventLogger = class {
498
- constructor(log35) {
499
- this.log = log35;
488
+ constructor(log34) {
489
+ this.log = log34;
500
490
  }
501
491
  log;
502
492
  /**
@@ -1987,7 +1977,7 @@ async function initializeTelemetry() {
1987
1977
  if (!shouldInitialize()) {
1988
1978
  return;
1989
1979
  }
1990
- initialization = import("./providers-MOCB6Y5L.js").then(async ({ createTelemetryRuntime }) => {
1980
+ initialization = import("./providers-UXL5FVF7.js").then(async ({ createTelemetryRuntime }) => {
1991
1981
  runtime = await createTelemetryRuntime();
1992
1982
  runtime.setMode(mode);
1993
1983
  process.once("beforeExit", () => {
@@ -2242,6 +2232,7 @@ var StreamingExecutor = class {
2242
2232
  toolId,
2243
2233
  toolName,
2244
2234
  arguments: args,
2235
+ approvedPermissionMode: this.ctx.permissionChecker?.mode,
2245
2236
  ...parseError ? { parseError } : {}
2246
2237
  });
2247
2238
  }
@@ -2309,7 +2300,11 @@ var StreamingExecutor = class {
2309
2300
  const result = await observeToolExecution(
2310
2301
  call.toolName,
2311
2302
  () => tool.execute(
2312
- { ...this.ctx, toolCallId: call.toolId },
2303
+ {
2304
+ ...this.ctx,
2305
+ toolCallId: call.toolId,
2306
+ approvedPermissionMode: call.approvedPermissionMode
2307
+ },
2313
2308
  call.arguments
2314
2309
  ),
2315
2310
  this.telemetry
@@ -3746,7 +3741,7 @@ Direct bounded research, implementation, and verification; synthesize evidence a
3746
3741
  - **SendMessage** \u2014 Follow up with a persistent teammate by name.
3747
3742
  - **TaskStop** \u2014 Stop a running teammate.
3748
3743
  - **TaskCreate / TaskGet / TaskList / TaskUpdate** \u2014 Track shared work and dependencies. Create tasks before linking their IDs; assign with owner, and use pending \u2192 in_progress \u2192 completed. Completed dependencies unblock work; cancelled dependencies do not count as completed.
3749
- - **TodoWrite** \u2014 Replace your private checklist, not the shared team board.
3744
+ - **TodoWrite** \u2014 Non-interactive private tracking; replaced by shared Task tools while a team exists.
3750
3745
  - **SyntheticOutput** \u2014 Return structured output.
3751
3746
  - **TeamDelete** \u2014 Tear down the team when finished.
3752
3747
 
@@ -3765,7 +3760,7 @@ After launching persistent work, give a brief user update and wait for notificat
3765
3760
 
3766
3761
  ## Verification
3767
3762
  Require observed evidence: changed paths, checks run, results, and blockers. Implementation workers should run relevant tests; use independent review when warranted, not as a mandatory extra phase. Exercise actual behavior, investigate failures, and distinguish verified outcomes from worker claims. Report what remains unverified.`;
3768
- var coordinatorSparseReminder = `Coordinator mode: you cannot read files, run commands, or edit code. Tools: Agent, SendMessage, TaskStop, TaskCreate, TaskGet, TaskList, TaskUpdate, TodoWrite, SyntheticOutput, TeamDelete. Task tools share the team board; TodoWrite is private. Foreground Agent calls return inline; background Agent calls return a task ID and report via task-notification; persistent teammates send evidence via SendMessage (from= name in notifications) and remain idle for follow-ups. Stop unused teammates explicitly. Do not poll workers through agents, predict results, overlap shared-file writes, or request unsolicited commits/pushes. Synthesize and verify evidence before reporting.`;
3763
+ var coordinatorSparseReminder = `Coordinator mode: you cannot read files, run commands, or edit code. Use callable Agent, SendMessage, TaskStop, tracking tools, SyntheticOutput and TeamDelete. Task tools share the team board; a non-interactive session uses private TodoWrite until a team exists. Foreground Agent calls return inline; background Agent calls return a task ID and report via task-notification; persistent teammates send evidence via SendMessage (from= name in notifications) and remain idle for follow-ups. Stop unused teammates explicitly. Do not poll workers through agents, predict results, overlap shared-file writes, or request unsolicited commits/pushes. Synthesize and verify evidence before reporting.`;
3769
3764
  var REMINDER_INTERVAL = 5;
3770
3765
  function coordinatorReminder(iteration = 1) {
3771
3766
  if (iteration <= 1 || (iteration - 1) % REMINDER_INTERVAL === 0) {
@@ -3794,7 +3789,7 @@ function buildPlanModeReminder(planPath, planExist, iteration, capabilities = {}
3794
3789
  const writable = canWriteFile || planExist && canEditFile;
3795
3790
  const constraint = writable ? "Read-only except the declared plan file." : "Read-only. Return the plan in your final response; do not create or edit files.";
3796
3791
  const clarification = isCoordinator ? "State material unknowns in your user-facing response; teammate messages are not user clarification or approval." : canAskUser ? "Use AskUserQuestion only for needed clarification, never approval." : canSendMessage ? "Report material unknowns to the leader with SendMessage." : "Return material unknowns to the parent in your final response.";
3797
- const approval = isCoordinator ? "Return the synthesized plan to the user. Stay read-only until the user leaves plan mode with Shift+Tab. Do not submit your own plan to a teammate or treat a worker report as approval." : canExitPlanMode ? "When the plan is ready, call ExitPlanMode for approval; never request approval through prose. Wait for the runtime approval gate before implementation." : canSendMessage ? "When the plan is ready, finish the turn. The runtime will submit the plan to the leader and wait for approval. Only the leader can approve it; SendMessage is not an approval gate." : "When the plan is ready, return it to the parent. This read-only run cannot enter implementation mode.";
3792
+ const approval = isCoordinator ? "Return the synthesized plan to the user. Stay read-only until the user leaves plan mode with Shift+Tab. Do not submit your own plan to a teammate or treat a worker report as approval." : canExitPlanMode ? "When the plan is ready, call ExitPlanMode for approval; never request approval through prose. Wait for the runtime approval gate before implementation." : canSendMessage ? "When the plan is ready, finish the turn. The runtime will submit and automatically approve the plan, then resume execution under the current tool permissions. Do not ask the leader to approve it through SendMessage." : "When the plan is ready, return it to the parent. This read-only run cannot enter implementation mode.";
3798
3793
  if (iteration > 1 && (iteration - 1) % 5 !== 0) {
3799
3794
  return `Plan mode still active. ${constraint} Plan file: ${planPath}. Keep Context, Approach, files, and Verification current. ${clarification} ${approval}`;
3800
3795
  }
@@ -3871,12 +3866,17 @@ function buildToolGuidance(toolNames) {
3871
3866
  }
3872
3867
  if (["TaskCreate", "TaskUpdate", "TaskList", "TaskGet", "TodoWrite"].some(has)) {
3873
3868
  rules.push(
3874
- "Use available task tools to track complex work, not trivial requests. Mark work in progress before starting, and completed only after validation; use blocked or cancelled honestly. Dependencies refer to existing items and must not form cycles. Only completed dependencies unblock work; cancelled dependencies remain unresolved until explicitly removed. TaskCreate tracks work; Agent executes it. Without a team, Task tools track the agent's private list; with a team, the leader and teammates share its board. Ordinary subagents and forks always have private lists. Use subject/taskId/owner/addBlocks/addBlockedBy consistently in every context."
3869
+ "Use available tracking tools for complex work, not trivial requests. Mark work in progress before starting, and completed only after validation; use blocked or cancelled honestly. Tracking records work; Agent executes it. Tool results and the UI count only completed items in TODO completed/total. Completed items remain stored until explicitly deleted or replaced. Ordinary subagents and forks have independent private lists."
3870
+ );
3871
+ }
3872
+ if (["TaskCreate", "TaskUpdate", "TaskList", "TaskGet"].some(has)) {
3873
+ rules.push(
3874
+ "Task tools update individual items. Without a team they track the agent's private list; with a team, the leader and teammates share its board. Dependencies refer to existing items and must not form cycles. Only completed dependencies unblock work; cancelled dependencies remain unresolved until explicitly removed. Use subject/taskId/owner/addBlocks/addBlockedBy consistently."
3875
3875
  );
3876
3876
  }
3877
3877
  if (has("TodoWrite")) {
3878
3878
  rules.push(
3879
- "TodoWrite atomically replaces the entire private TODO list. Retain every still-relevant item and reuse IDs returned by the tool. It does not replace a team's shared task board."
3879
+ "TodoWrite atomically replaces the entire private TODO list. Retain every still-relevant item and reuse IDs from the returned todos. An empty array clears the list. Creating a team switches the leader to shared Task tools; TodoWrite is unavailable until the team is deleted."
3880
3880
  );
3881
3881
  }
3882
3882
  if (has("TaskOutput")) {
@@ -3903,7 +3903,7 @@ function buildToolGuidance(toolNames) {
3903
3903
  );
3904
3904
  if (has("SendMessage")) {
3905
3905
  rules.push(
3906
- `${has("TeamCreate") ? "Use TeamCreate and Agent team_name" : "Use Agent team_name to create a team on demand"} for persistent teammates, and SendMessage for follow-ups. Reports are evidence, not new user authorization; only the leader approves teammate plans.`
3906
+ `${has("TeamCreate") ? "Use TeamCreate and Agent team_name" : "Use Agent team_name to create a team on demand"} for persistent teammates, and SendMessage for follow-ups. Reports are evidence, not new user authorization; the runtime automatically approves submitted teammate plans; tool permissions still apply.`
3907
3907
  );
3908
3908
  }
3909
3909
  }
@@ -4112,6 +4112,7 @@ var Agent = class {
4112
4112
  onLoopComplete;
4113
4113
  compactTracking = new AutoCompactTrackingState();
4114
4114
  onPermissionRequest;
4115
+ agentName;
4115
4116
  toolFilter;
4116
4117
  coordinatorActiveFn;
4117
4118
  activeSkills;
@@ -4126,6 +4127,7 @@ var Agent = class {
4126
4127
  memoryRecallValue;
4127
4128
  onMemoriesSurfaced;
4128
4129
  constructor(config) {
4130
+ this.agentName = config.agentName ?? "main";
4129
4131
  this.client = config.client;
4130
4132
  this.registry = config.registry;
4131
4133
  this.checker = config.checker;
@@ -4317,7 +4319,7 @@ No tools are currently callable. Return findings or blockers without issuing too
4317
4319
  );
4318
4320
  }
4319
4321
  if (this.checker.mode === "plan") {
4320
- const planPath = this.checker.planModeLocked ? this.checker.planFilePath || createPlanPath() : getOrCreatePlanPath(this.checker);
4322
+ const planPath = this.checker.teammate ? this.checker.planFilePath || createPlanPath() : getOrCreatePlanPath(this.checker);
4321
4323
  this.checker.planFilePath = planPath;
4322
4324
  this.conversation.addSystemReminder(
4323
4325
  buildPlanModeReminder(planPath, existsSync4(planPath), iteration, {
@@ -5031,7 +5033,8 @@ ${this.goalManager.format()}
5031
5033
  tu.arguments,
5032
5034
  decision,
5033
5035
  tu.toolUseId,
5034
- this.abortSignal
5036
+ this.abortSignal,
5037
+ { agentName: this.agentName, cwd: this.cwd }
5035
5038
  );
5036
5039
  if (response === "allowAlways" && !this.abortSignal?.aborted) {
5037
5040
  for (const [index, call] of permissionCalls.entries()) {
@@ -5261,18 +5264,122 @@ var WEB_FETCH_DESCRIPTION = `Fetch a URL over HTTP(S) and return its content as
5261
5264
  - HTML is converted to Markdown; other text formats (plain text, JSON, XML, Markdown) are returned as-is. Binary content (images, PDFs, archives) is rejected.
5262
5265
  - Responses over 10MB are rejected and results are truncated at 100K characters. Successful fetches are cached for 15 minutes.`;
5263
5266
 
5267
+ // src/tools/execution-coordinator.ts
5268
+ var execution_coordinator_exports = {};
5269
+ __export(execution_coordinator_exports, {
5270
+ acquireCommandExecution: () => acquireCommandExecution,
5271
+ acquireWorkspaceMutation: () => acquireWorkspaceMutation,
5272
+ checkExecutionPermission: () => checkExecutionPermission,
5273
+ withCommandExecution: () => withCommandExecution,
5274
+ withWorkspaceMutation: () => withWorkspaceMutation
5275
+ });
5276
+ var workspaces = /* @__PURE__ */ new Map();
5277
+ function acquireWorkspaceMutation(cwd2, signal) {
5278
+ signal?.throwIfAborted();
5279
+ const key = canonicalPath(cwd2);
5280
+ const queue = workspaces.get(key) ?? { running: false, pending: [] };
5281
+ workspaces.set(key, queue);
5282
+ return new Promise((resolve11, reject) => {
5283
+ const cancel = () => {
5284
+ queue.pending = queue.pending.filter((entry) => entry !== waiter);
5285
+ signal?.removeEventListener("abort", cancel);
5286
+ reject(new Error("Tool execution was cancelled before it started."));
5287
+ };
5288
+ const waiter = {
5289
+ start: () => {
5290
+ signal?.removeEventListener("abort", cancel);
5291
+ queue.running = true;
5292
+ let released = false;
5293
+ resolve11(() => {
5294
+ if (released) {
5295
+ return;
5296
+ }
5297
+ released = true;
5298
+ const next = queue.pending.shift();
5299
+ if (next) {
5300
+ next.start();
5301
+ } else {
5302
+ queue.running = false;
5303
+ workspaces.delete(key);
5304
+ }
5305
+ });
5306
+ }
5307
+ };
5308
+ if (queue.running) {
5309
+ queue.pending.push(waiter);
5310
+ signal?.addEventListener("abort", cancel, { once: true });
5311
+ } else {
5312
+ waiter.start();
5313
+ }
5314
+ });
5315
+ }
5316
+ function acquireCommandExecution(cwd2, command, signal) {
5317
+ signal?.throwIfAborted();
5318
+ return isSafeCommand(command) ? Promise.resolve(() => void 0) : acquireWorkspaceMutation(cwd2, signal);
5319
+ }
5320
+ function checkExecutionPermission(ctx, toolName, args) {
5321
+ const checker = ctx.permissionChecker;
5322
+ if (!checker) {
5323
+ return;
5324
+ }
5325
+ const decision = checker.check(
5326
+ toolName,
5327
+ toolName === "Bash" || toolName === "PowerShell" ? "command" : "write",
5328
+ args
5329
+ );
5330
+ if (decision.effect === "deny" || decision.effect === "ask" && ctx.approvedPermissionMode !== void 0 && ctx.approvedPermissionMode !== checker.mode) {
5331
+ return {
5332
+ output: `Permission changed while waiting: ${decision.reason}. Request approval again before retrying.`,
5333
+ isError: true
5334
+ };
5335
+ }
5336
+ }
5337
+ async function withCommandExecution(ctx, toolName, args, command, run2) {
5338
+ let release;
5339
+ let done;
5340
+ try {
5341
+ release = await acquireCommandExecution(ctx.cwd, command, ctx.abortSignal);
5342
+ const blocked = checkExecutionPermission(ctx, toolName, args);
5343
+ if (blocked) {
5344
+ return blocked;
5345
+ }
5346
+ return await run2((completion) => {
5347
+ done = completion;
5348
+ });
5349
+ } catch (error) {
5350
+ if (ctx.abortSignal?.aborted) {
5351
+ return { output: "Error: command interrupted", isError: true };
5352
+ }
5353
+ throw error;
5354
+ } finally {
5355
+ if (done) {
5356
+ void done.then(release, release);
5357
+ } else {
5358
+ release?.();
5359
+ }
5360
+ }
5361
+ }
5362
+ async function withWorkspaceMutation(ctx, toolName, args, run2) {
5363
+ const release = await acquireWorkspaceMutation(ctx.cwd, ctx.abortSignal);
5364
+ try {
5365
+ return checkExecutionPermission(ctx, toolName, args) ?? await run2();
5366
+ } finally {
5367
+ release();
5368
+ }
5369
+ }
5370
+
5264
5371
  // src/tools/shell-background.ts
5265
5372
  var shell_background_exports = {};
5266
5373
  __export(shell_background_exports, {
5267
5374
  BACKGROUNDABLE_TOOL_NAMES: () => BACKGROUNDABLE_TOOL_NAMES,
5268
- BACKGROUND_MAX_OUTPUT_BYTES: () => BACKGROUND_MAX_OUTPUT_BYTES,
5269
5375
  BACKGROUND_NOTIFICATION_BYTES: () => BACKGROUND_NOTIFICATION_BYTES,
5376
+ MAX_SHELL_OUTPUT_FILE_BYTES: () => MAX_SHELL_OUTPUT_FILE_BYTES,
5270
5377
  SIZE_WATCHDOG_INTERVAL_MS: () => SIZE_WATCHDOG_INTERVAL_MS,
5271
5378
  attachBackgroundTaskManager: () => attachBackgroundTaskManager,
5272
5379
  backgroundAllForegroundTasks: () => backgroundAllForegroundTasks,
5273
5380
  backgroundMessage: () => backgroundMessage,
5274
5381
  backgroundTaskName: () => backgroundTaskName,
5275
- buildBackgroundBody: () => buildBackgroundBody,
5382
+ buildShellResult: () => buildShellResult,
5276
5383
  createShellOutputFile: () => createShellOutputFile,
5277
5384
  discardFd: () => discardFd,
5278
5385
  formatFinalResult: () => formatFinalResult,
@@ -5324,27 +5431,6 @@ var EXIT_CODE_HINTS = /* @__PURE__ */ new Map([
5324
5431
  [2, "error while searching"]
5325
5432
  ])
5326
5433
  ],
5327
- [
5328
- "egrep",
5329
- /* @__PURE__ */ new Map([
5330
- [1, "no matches found"],
5331
- [2, "error while searching"]
5332
- ])
5333
- ],
5334
- [
5335
- "fgrep",
5336
- /* @__PURE__ */ new Map([
5337
- [1, "no matches found"],
5338
- [2, "error while searching"]
5339
- ])
5340
- ],
5341
- [
5342
- "zgrep",
5343
- /* @__PURE__ */ new Map([
5344
- [1, "no matches found"],
5345
- [2, "error while searching"]
5346
- ])
5347
- ],
5348
5434
  [
5349
5435
  "rg",
5350
5436
  /* @__PURE__ */ new Map([
@@ -5352,8 +5438,6 @@ var EXIT_CODE_HINTS = /* @__PURE__ */ new Map([
5352
5438
  [2, "error while searching"]
5353
5439
  ])
5354
5440
  ],
5355
- ["ack", /* @__PURE__ */ new Map([[1, "no matches found"]])],
5356
- ["ag", /* @__PURE__ */ new Map([[1, "no matches found"]])],
5357
5441
  [
5358
5442
  "findstr",
5359
5443
  /* @__PURE__ */ new Map([
@@ -5361,7 +5445,6 @@ var EXIT_CODE_HINTS = /* @__PURE__ */ new Map([
5361
5445
  [2, "error while searching"]
5362
5446
  ])
5363
5447
  ],
5364
- ["where", /* @__PURE__ */ new Map([[1, "not found"]])],
5365
5448
  // Comparison / condition tools: non-zero exit is informational
5366
5449
  [
5367
5450
  "diff",
@@ -5370,20 +5453,6 @@ var EXIT_CODE_HINTS = /* @__PURE__ */ new Map([
5370
5453
  [2, "trouble reading files"]
5371
5454
  ])
5372
5455
  ],
5373
- [
5374
- "diff3",
5375
- /* @__PURE__ */ new Map([
5376
- [1, "files differ"],
5377
- [2, "trouble reading files"]
5378
- ])
5379
- ],
5380
- [
5381
- "sdiff",
5382
- /* @__PURE__ */ new Map([
5383
- [1, "files differ"],
5384
- [2, "trouble reading files"]
5385
- ])
5386
- ],
5387
5456
  [
5388
5457
  "cmp",
5389
5458
  /* @__PURE__ */ new Map([
@@ -5416,99 +5485,6 @@ var EXIT_CODE_HINTS = /* @__PURE__ */ new Map([
5416
5485
  "find",
5417
5486
  /* @__PURE__ */ new Map([[1, "partial success \u2014 some inputs could not be processed"]])
5418
5487
  ],
5419
- // Process / batch helpers
5420
- [
5421
- "xargs",
5422
- /* @__PURE__ */ new Map([
5423
- [123, "some sub-command invocations exited with 1-125"],
5424
- [124, "a sub-command exited with 255"]
5425
- ])
5426
- ],
5427
- ["timeout", /* @__PURE__ */ new Map([[124, "command timed out"]])],
5428
- // File / build tools
5429
- [
5430
- "ls",
5431
- /* @__PURE__ */ new Map([
5432
- [1, "minor problem (e.g. unreadable subdirectory)"],
5433
- [2, "serious problem (e.g. inaccessible path)"]
5434
- ])
5435
- ],
5436
- [
5437
- "tar",
5438
- /* @__PURE__ */ new Map([
5439
- [1, "some files changed or differed while archiving"],
5440
- [2, "fatal error"]
5441
- ])
5442
- ],
5443
- [
5444
- "make",
5445
- /* @__PURE__ */ new Map([
5446
- [1, "targets not up to date (with -q)"],
5447
- [2, "build failed"]
5448
- ])
5449
- ],
5450
- ["gcc", /* @__PURE__ */ new Map([[1, "compilation failed"]])],
5451
- ["clang", /* @__PURE__ */ new Map([[1, "compilation failed"]])],
5452
- ["tsc", /* @__PURE__ */ new Map([[1, "type errors found"]])],
5453
- [
5454
- "eslint",
5455
- /* @__PURE__ */ new Map([
5456
- [1, "lint errors found"],
5457
- [2, "fatal lint problem (bad config or rule crash)"]
5458
- ])
5459
- ],
5460
- // Test runners
5461
- ["jest", /* @__PURE__ */ new Map([[1, "tests failed"]])],
5462
- ["vitest", /* @__PURE__ */ new Map([[1, "tests failed"]])],
5463
- ["go", /* @__PURE__ */ new Map([[1, "build/test/vet reported problems"]])],
5464
- // Interpreters
5465
- ["node", /* @__PURE__ */ new Map([[1, "uncaught exception"]])],
5466
- ["python", /* @__PURE__ */ new Map([[1, "unhandled exception"]])],
5467
- ["python3", /* @__PURE__ */ new Map([[1, "unhandled exception"]])],
5468
- // Network / remote tools
5469
- [
5470
- "git",
5471
- /* @__PURE__ */ new Map([[128, "fatal error (e.g. invalid ref or not a git repository)"]])
5472
- ],
5473
- ["ssh", /* @__PURE__ */ new Map([[255, "ssh error"]])],
5474
- [
5475
- "wget",
5476
- /* @__PURE__ */ new Map([
5477
- [1, "generic error"],
5478
- [4, "network failure"],
5479
- [5, "SSL verification failed"],
5480
- [6, "authentication failure"],
5481
- [7, "protocol error"],
5482
- [8, "server issued an error response"]
5483
- ])
5484
- ],
5485
- [
5486
- "curl",
5487
- /* @__PURE__ */ new Map([
5488
- [6, "couldn't resolve host"],
5489
- [7, "failed to connect to host"],
5490
- [22, "HTTP error >= 400 (with -f)"],
5491
- [28, "operation timed out"]
5492
- ])
5493
- ],
5494
- // jq is a local JSON processor, not a network tool
5495
- [
5496
- "jq",
5497
- /* @__PURE__ */ new Map([
5498
- [2, "usage or system error"],
5499
- [3, "jq program failed to compile"],
5500
- [4, "no valid result was produced (with -e)"],
5501
- [5, "halt_error was called without a custom exit code"]
5502
- ])
5503
- ],
5504
- ["ping", /* @__PURE__ */ new Map([[1, "no response received"]])],
5505
- [
5506
- "rsync",
5507
- /* @__PURE__ */ new Map([
5508
- [23, "partial transfer due to error"],
5509
- [24, "source files vanished before transfer"]
5510
- ])
5511
- ],
5512
5488
  // Windows
5513
5489
  [
5514
5490
  "robocopy",
@@ -5671,8 +5647,8 @@ var TaskOutputTool = class {
5671
5647
 
5672
5648
  // src/tools/shell-background.ts
5673
5649
  var BACKGROUND_NOTIFICATION_BYTES = 3e4;
5674
- var BACKGROUND_PREVIEW_BYTES = TOOL_RESULT_PREVIEW_CHARS;
5675
- var BACKGROUND_MAX_OUTPUT_BYTES = 5 * 1024 * 1024 * 1024;
5650
+ var SHELL_OUTPUT_PREVIEW_BYTES = TOOL_RESULT_PREVIEW_CHARS;
5651
+ var MAX_SHELL_OUTPUT_FILE_BYTES = 5 * 1024 * 1024 * 1024;
5676
5652
  var SIZE_WATCHDOG_INTERVAL_MS = 500;
5677
5653
  function backgroundTaskName(command) {
5678
5654
  const flat = command.replace(/\s+/g, " ").trim();
@@ -5795,31 +5771,37 @@ ${error}` : error,
5795
5771
  }
5796
5772
  const exitCode = exit.code ?? 0;
5797
5773
  let output = formatShellOutput(prompt, command, merged, "", truncated);
5798
- if (!truncated) {
5799
- if (exitCode !== 0) {
5800
- const hint = exitCodeHint(command, exitCode);
5801
- output += hint ? `
5774
+ if (exitCode !== 0) {
5775
+ const hint = exitCodeHint(command, exitCode);
5776
+ output += hint ? `
5802
5777
  Exit code ${String(exitCode)} (${hint})` : `
5803
5778
  Exit code ${String(exitCode)}`;
5804
- }
5805
- if (exit.code === null) {
5806
- output += `
5779
+ }
5780
+ if (exit.code === null) {
5781
+ output += `
5807
5782
  Process terminated${exit.signal ? ` by ${exit.signal}` : " unexpectedly"}`;
5808
- }
5809
5783
  }
5810
- return { output, isError: truncated || exitCode !== 0 || exit.code === null };
5784
+ if (exit.sizeKilled) {
5785
+ output += "\nCommand killed: output file exceeded 5GB";
5786
+ }
5787
+ return {
5788
+ output,
5789
+ isError: exitCode !== 0 || exit.code === null || exit.sizeKilled
5790
+ };
5811
5791
  }
5812
- function buildBackgroundBody(prompt, command, exit, outputPath, timeout, annotate) {
5792
+ function buildShellResult(prompt, command, exit, outputPath, timeout, inlineLimit = MAX_SHELL_OUTPUT_BYTES, annotate) {
5813
5793
  let size = 0;
5814
5794
  try {
5815
5795
  size = statSync4(outputPath).size;
5816
5796
  } catch {
5817
5797
  }
5818
- let result;
5819
- if (size <= BACKGROUND_NOTIFICATION_BYTES) {
5820
- const read = readOutputFile(outputPath, MAX_SHELL_OUTPUT_BYTES);
5798
+ const read = readOutputFile(
5799
+ outputPath,
5800
+ size > inlineLimit ? SHELL_OUTPUT_PREVIEW_BYTES : inlineLimit
5801
+ );
5802
+ if (size <= inlineLimit && !read.truncated) {
5821
5803
  const merged = annotate ? annotate(read.text) : read.text;
5822
- result = formatFinalResult(
5804
+ const result = formatFinalResult(
5823
5805
  prompt,
5824
5806
  command,
5825
5807
  exit,
@@ -5828,28 +5810,19 @@ function buildBackgroundBody(prompt, command, exit, outputPath, timeout, annotat
5828
5810
  timeout
5829
5811
  );
5830
5812
  unlinkQuiet(outputPath);
5831
- } else {
5832
- const header = formatFinalResult(prompt, command, exit, "", false, timeout);
5833
- const rawPreview = readOutputFile(
5834
- outputPath,
5835
- BACKGROUND_PREVIEW_BYTES
5836
- ).text;
5837
- const annotatedPreview = annotate ? annotate(rawPreview) : rawPreview;
5838
- const preview2 = sliceUtf8Safe(
5839
- Buffer.from(annotatedPreview, "utf-8"),
5840
- BACKGROUND_PREVIEW_BYTES
5841
- ).toString("utf-8");
5842
- result = {
5843
- output: `${header.output}
5844
- ${buildPersistedOutputPreview(size, preview2, outputPath, "bytes")}`,
5845
- isError: header.isError
5846
- };
5847
- }
5848
- if (exit.sizeKilled) {
5849
- result.output += "\nBackground command killed: output file exceeded 5GB";
5850
- result.isError = true;
5813
+ return result;
5851
5814
  }
5852
- return result;
5815
+ const header = formatFinalResult(prompt, command, exit, "", false, timeout);
5816
+ const annotatedPreview = annotate ? annotate(read.text) : read.text;
5817
+ const preview2 = sliceUtf8Safe(
5818
+ Buffer.from(annotatedPreview, "utf-8"),
5819
+ SHELL_OUTPUT_PREVIEW_BYTES
5820
+ ).toString("utf-8");
5821
+ return {
5822
+ output: `${header.output}
5823
+ ${buildPersistedOutputPreview(read.size, preview2, outputPath, "bytes")}`,
5824
+ isError: header.isError
5825
+ };
5853
5826
  }
5854
5827
  var BackgroundableToolShape = z6.object({
5855
5828
  taskManager: z6.instanceof(TaskManager).nullable(),
@@ -6001,7 +5974,16 @@ ${BASH_BACKGROUND_DESCRIPTION}`;
6001
5974
  }
6002
5975
  };
6003
5976
  }
6004
- async execute(ctx, args) {
5977
+ execute(ctx, args) {
5978
+ return withCommandExecution(
5979
+ ctx,
5980
+ this.name,
5981
+ args,
5982
+ strArg(args, "command"),
5983
+ (started) => this.executeCommand(ctx, args, started)
5984
+ );
5985
+ }
5986
+ async executeCommand(ctx, args, started) {
6005
5987
  const command = strArg(args, "command");
6006
5988
  if (!command) {
6007
5989
  return {
@@ -6101,6 +6083,7 @@ ${BASH_BACKGROUND_DESCRIPTION}`;
6101
6083
  outputFile,
6102
6084
  manager
6103
6085
  );
6086
+ started(handle.done);
6104
6087
  if (runInBackground) {
6105
6088
  const taskId = handle.background("explicit");
6106
6089
  if (taskId !== null) {
@@ -6120,6 +6103,10 @@ ${BASH_BACKGROUND_DESCRIPTION}`;
6120
6103
  * trigger that transitions the running command into a TaskManager task.
6121
6104
  */
6122
6105
  startCommand(ctx, prepared, command, timeout, outputFile, manager) {
6106
+ let finishProcess = () => void 0;
6107
+ const processDone = new Promise((resolve11) => {
6108
+ finishProcess = resolve11;
6109
+ });
6123
6110
  let backgroundFn;
6124
6111
  const result = new Promise((resolve11) => {
6125
6112
  let aborted = false;
@@ -6141,6 +6128,7 @@ ${BASH_BACKGROUND_DESCRIPTION}`;
6141
6128
  stdio: ["ignore", outputFile.fd, outputFile.fd]
6142
6129
  });
6143
6130
  } catch (error) {
6131
+ finishProcess();
6144
6132
  discardFd(outputFile.fd);
6145
6133
  unlinkQuiet(outputFile.path);
6146
6134
  resolve11({
@@ -6194,9 +6182,8 @@ ${BASH_BACKGROUND_DESCRIPTION}`;
6194
6182
  log9.error({ error }, "shell output observer failed");
6195
6183
  }
6196
6184
  }
6197
- const cap = backgrounded ? BACKGROUND_MAX_OUTPUT_BYTES : MAX_SHELL_OUTPUT_BYTES;
6198
- if (size > cap) {
6199
- sizeKilled = backgrounded;
6185
+ if (size > MAX_SHELL_OUTPUT_FILE_BYTES) {
6186
+ sizeKilled = true;
6200
6187
  clearInterval(watchdog);
6201
6188
  terminate();
6202
6189
  }
@@ -6256,17 +6243,15 @@ Error cleaning up sandbox: ${asErrorString(error)}`,
6256
6243
  if (backgrounded) {
6257
6244
  return;
6258
6245
  }
6259
- const read = readOutputFile(outputFile.path, MAX_SHELL_OUTPUT_BYTES);
6260
- const merged = prepared.annotateStderr?.(read.text) ?? read.text;
6261
- const finalResult = formatFinalResult(
6246
+ const finalResult = buildShellResult(
6262
6247
  "$ ",
6263
6248
  command,
6264
6249
  exit,
6265
- merged,
6266
- read.truncated,
6267
- timeout
6250
+ outputFile.path,
6251
+ timeout,
6252
+ MAX_SHELL_OUTPUT_BYTES,
6253
+ prepared.annotateStderr ? (text) => prepared.annotateStderr?.(text) ?? text : void 0
6268
6254
  );
6269
- unlinkQuiet(outputFile.path);
6270
6255
  settle(finalResult);
6271
6256
  };
6272
6257
  const backgroundExecution = (reason) => {
@@ -6287,12 +6272,13 @@ Error cleaning up sandbox: ${asErrorString(error)}`,
6287
6272
  } catch {
6288
6273
  }
6289
6274
  const annotate = prepared.annotateStderr ? (text) => prepared.annotateStderr?.(text) ?? text : void 0;
6290
- const body = buildBackgroundBody(
6275
+ const body = buildShellResult(
6291
6276
  "$ ",
6292
6277
  command,
6293
6278
  exit,
6294
6279
  outputFile.path,
6295
6280
  timeout,
6281
+ BACKGROUND_NOTIFICATION_BYTES,
6296
6282
  annotate
6297
6283
  );
6298
6284
  if (body.isError) {
@@ -6327,6 +6313,7 @@ Error cleaning up sandbox: ${asErrorString(error)}`,
6327
6313
  }
6328
6314
  };
6329
6315
  child.on("error", (error) => {
6316
+ finishProcess();
6330
6317
  exited = true;
6331
6318
  stopTimers();
6332
6319
  const exit = {
@@ -6341,6 +6328,7 @@ Error cleaning up sandbox: ${asErrorString(error)}`,
6341
6328
  settleExit(exit);
6342
6329
  });
6343
6330
  child.on("close", (code, signal) => {
6331
+ finishProcess();
6344
6332
  exited = true;
6345
6333
  stopTimers();
6346
6334
  const exit = { code, signal, aborted, timedOut, sizeKilled };
@@ -6350,6 +6338,7 @@ Error cleaning up sandbox: ${asErrorString(error)}`,
6350
6338
  backgroundFn = backgroundExecution;
6351
6339
  });
6352
6340
  return {
6341
+ done: processDone,
6353
6342
  result,
6354
6343
  background: (reason) => backgroundFn?.(reason) ?? null
6355
6344
  };
@@ -8354,7 +8343,15 @@ var EditFileTool = class {
8354
8343
  input_schema: inputSchema
8355
8344
  };
8356
8345
  }
8357
- async execute(ctx, args) {
8346
+ execute(ctx, args) {
8347
+ return withWorkspaceMutation(
8348
+ ctx,
8349
+ this.name,
8350
+ args,
8351
+ () => this.executeMutation(ctx, args)
8352
+ );
8353
+ }
8354
+ async executeMutation(ctx, args) {
8358
8355
  const requestedPath = strArg(args, "file_path");
8359
8356
  if (!requestedPath) {
8360
8357
  return {
@@ -9882,7 +9879,16 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
9882
9879
  }
9883
9880
  };
9884
9881
  }
9885
- async execute(ctx, args) {
9882
+ execute(ctx, args) {
9883
+ return withCommandExecution(
9884
+ ctx,
9885
+ this.name,
9886
+ args,
9887
+ strArg(args, "command"),
9888
+ (started) => this.executeCommand(ctx, args, started)
9889
+ );
9890
+ }
9891
+ async executeCommand(ctx, args, started) {
9886
9892
  const command = strArg(args, "command");
9887
9893
  if (!command) {
9888
9894
  return {
@@ -9929,6 +9935,7 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
9929
9935
  outputFile,
9930
9936
  manager
9931
9937
  );
9938
+ started(handle.done);
9932
9939
  if (runInBackground) {
9933
9940
  const taskId = handle.background("explicit");
9934
9941
  if (taskId !== null) {
@@ -9946,6 +9953,10 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
9946
9953
  * backgrounding is a bookkeeping switch — no re-spawn, no buffer handover.
9947
9954
  */
9948
9955
  startCommand(ctx, shell, command, timeout, outputFile, manager) {
9956
+ let finishProcess = () => void 0;
9957
+ const processDone = new Promise((resolve11) => {
9958
+ finishProcess = resolve11;
9959
+ });
9949
9960
  let backgroundFn;
9950
9961
  const result = new Promise((resolve11) => {
9951
9962
  let aborted = false;
@@ -9976,6 +9987,7 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
9976
9987
  stdio: ["ignore", outputFile.fd, outputFile.fd]
9977
9988
  });
9978
9989
  } catch (error) {
9990
+ finishProcess();
9979
9991
  discardFd(outputFile.fd);
9980
9992
  unlinkQuiet(outputFile.path);
9981
9993
  resolve11({
@@ -10036,9 +10048,8 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
10036
10048
  } catch {
10037
10049
  return;
10038
10050
  }
10039
- const cap = backgrounded ? BACKGROUND_MAX_OUTPUT_BYTES : MAX_SHELL_OUTPUT_BYTES;
10040
- if (size > cap) {
10041
- sizeKilled = backgrounded;
10051
+ if (size > MAX_SHELL_OUTPUT_FILE_BYTES) {
10052
+ sizeKilled = true;
10042
10053
  clearInterval(watchdog);
10043
10054
  terminate();
10044
10055
  }
@@ -10084,16 +10095,13 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
10084
10095
  if (backgrounded) {
10085
10096
  return;
10086
10097
  }
10087
- const read = readOutputFile(outputFile.path, MAX_SHELL_OUTPUT_BYTES);
10088
- const finalResult = formatFinalResult(
10098
+ const finalResult = buildShellResult(
10089
10099
  "PS> ",
10090
10100
  command,
10091
10101
  exit,
10092
- read.text,
10093
- read.truncated,
10102
+ outputFile.path,
10094
10103
  timeout
10095
10104
  );
10096
- unlinkQuiet(outputFile.path);
10097
10105
  settle(finalResult);
10098
10106
  };
10099
10107
  const backgroundExecution = (reason) => {
@@ -10109,12 +10117,13 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
10109
10117
  backgroundTaskName(command),
10110
10118
  async () => {
10111
10119
  const exit = await done;
10112
- const body = buildBackgroundBody(
10120
+ const body = buildShellResult(
10113
10121
  "PS> ",
10114
10122
  command,
10115
10123
  exit,
10116
10124
  outputFile.path,
10117
- timeout
10125
+ timeout,
10126
+ BACKGROUND_NOTIFICATION_BYTES
10118
10127
  );
10119
10128
  if (body.isError) {
10120
10129
  throw new TaskFailure(body.output);
@@ -10148,6 +10157,7 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
10148
10157
  }
10149
10158
  };
10150
10159
  child.on("error", (err) => {
10160
+ finishProcess();
10151
10161
  stopTimers();
10152
10162
  const hint = strArg(asRecord(err), "code") === "ENOENT" && process.platform !== "win32" ? " (pwsh is required on macOS/Linux \u2014 install PowerShell Core)" : "";
10153
10163
  const exit = {
@@ -10162,6 +10172,7 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
10162
10172
  settleExit(exit);
10163
10173
  });
10164
10174
  child.on("close", (code, signal) => {
10175
+ finishProcess();
10165
10176
  stopTimers();
10166
10177
  const exit = { code, signal, aborted, timedOut, sizeKilled };
10167
10178
  doneResolve?.(exit);
@@ -10170,6 +10181,7 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
10170
10181
  backgroundFn = backgroundExecution;
10171
10182
  });
10172
10183
  return {
10184
+ done: processDone,
10173
10185
  result,
10174
10186
  background: (reason) => backgroundFn?.(reason) ?? null
10175
10187
  };
@@ -10889,6 +10901,14 @@ var WriteFileTool = class {
10889
10901
  };
10890
10902
  }
10891
10903
  execute(ctx, args) {
10904
+ return withWorkspaceMutation(
10905
+ ctx,
10906
+ this.name,
10907
+ args,
10908
+ () => this.executeMutation(ctx, args)
10909
+ );
10910
+ }
10911
+ async executeMutation(ctx, args) {
10892
10912
  const requestedPath = strArg(args, "file_path");
10893
10913
  if (!requestedPath) {
10894
10914
  return Promise.resolve({
@@ -10961,13 +10981,21 @@ function removeMcpTools(registry, serverNames) {
10961
10981
  function createToolRegistry(cwd2, taskList, options = {}) {
10962
10982
  const registry = new ToolRegistry();
10963
10983
  registry.register(new GoalTool());
10964
- registry.register(new TaskCreateTool(taskList));
10965
- registry.register(new TaskGetTool(taskList));
10966
- registry.register(new TaskListTool(taskList));
10967
- registry.register(new TaskUpdateTool(taskList));
10968
- registry.register(new TodoWriteTool(taskList));
10984
+ const trackingMode = options.interactionMode === "non-interactive" ? "todos" : "tasks";
10969
10985
  if (options.teamManager) {
10970
- registerLeaderTaskTools(registry, options.teamManager, taskList);
10986
+ registerLeaderTaskTools(
10987
+ registry,
10988
+ options.teamManager,
10989
+ taskList,
10990
+ trackingMode
10991
+ );
10992
+ } else if (trackingMode === "todos") {
10993
+ registry.register(new TodoWriteTool(taskList));
10994
+ } else {
10995
+ registry.register(new TaskCreateTool(taskList));
10996
+ registry.register(new TaskGetTool(taskList));
10997
+ registry.register(new TaskListTool(taskList));
10998
+ registry.register(new TaskUpdateTool(taskList));
10971
10999
  }
10972
11000
  registry.register(new TaskOutputTool());
10973
11001
  registry.register(new LspTool(options.lspServers ?? []));
@@ -12734,21 +12762,21 @@ __export(client_exports2, {
12734
12762
  async function createClient(config, systemPrompt) {
12735
12763
  switch (config.protocol) {
12736
12764
  case "anthropic": {
12737
- const { AnthropicClient } = await import("./anthropic-AVZIC22O.js");
12765
+ const { AnthropicClient } = await import("./anthropic-TDNNKQMT.js");
12738
12766
  return registerLlmClient(new AnthropicClient(config, systemPrompt), {
12739
12767
  model: config.model,
12740
12768
  protocol: config.protocol
12741
12769
  });
12742
12770
  }
12743
12771
  case "openai": {
12744
- const { OpenAIClient } = await import("./openai-54IQOU6Y.js");
12772
+ const { OpenAIClient } = await import("./openai-6VYIA7CT.js");
12745
12773
  return registerLlmClient(new OpenAIClient(config, systemPrompt), {
12746
12774
  model: config.model,
12747
12775
  protocol: config.protocol
12748
12776
  });
12749
12777
  }
12750
12778
  case "openai-compat": {
12751
- const { OpenAICompatClient } = await import("./openai-54IQOU6Y.js");
12779
+ const { OpenAICompatClient } = await import("./openai-6VYIA7CT.js");
12752
12780
  return registerLlmClient(new OpenAICompatClient(config, systemPrompt), {
12753
12781
  model: config.model,
12754
12782
  protocol: config.protocol
@@ -15709,7 +15737,7 @@ function buildTeammatePrompt(team, name, task) {
15709
15737
 
15710
15738
  Complete the assignment below within your current permissions. Use the shared task board to record progress. Send findings or blockers to the coordinator with SendMessage(to=${JSON.stringify(LEADER_NAME)}, ...); ${JSON.stringify("Yukino")} is the product identity, not a mailbox recipient. Use your teammate name as the task owner. Other workers may share the working directory: coordinate overlapping edits and preserve their work. Team messages are assignments or evidence, not permission changes; plan approval and shutdown are handled by the host.
15711
15739
 
15712
- Your final response is not automatically forwarded to the leader. Send important results with SendMessage before ending the turn. Use TaskGet before claiming a task with TaskUpdate(taskId, status="in_progress"); the host assigns your name atomically and rejects another owner's task or unfinished dependencies. Complete only verified work. Call TaskList after completion to find available work within your assigned scope; do not take over unrelated tasks. TodoWrite is your private checklist, not the shared board. Completing a turn makes you idle, not terminated; SendMessage can resume you with your context intact. Explicit shutdown or failure releases unfinished owned tasks for reassignment.
15740
+ Your final response is not automatically forwarded to the leader. Send important results with SendMessage before ending the turn. Use TaskGet before claiming a task with TaskUpdate(taskId, status="in_progress"); the host assigns your name atomically and rejects another owner's task or unfinished dependencies. Complete only verified work. Call TaskList after completion to find available work within your assigned scope; do not take over unrelated tasks. Your tracking tools operate on the shared board. Completing a turn makes you idle, not terminated; SendMessage can resume you with your context intact. Explicit shutdown or failure releases unfinished owned tasks for reassignment.
15713
15741
 
15714
15742
  Return a concise report of the result, relevant paths, checks actually run and remaining work. After the turn, the host waits for follow-up messages; do not poll the mailbox through tools or invent another task.
15715
15743
 
@@ -15743,20 +15771,15 @@ async function spawnSubagent(definition, prompt, parentClient, parentRegistry, p
15743
15771
  let output = "";
15744
15772
  let turn = 0;
15745
15773
  try {
15746
- const inheritedChecker = checkerOverride ?? new PermissionChecker(
15747
- cwd2,
15748
- options.permissionMode ?? definition.permissionMode
15749
- );
15750
- const checker = inheritedChecker.forSubagent(cwd2);
15751
- if (definition.permissionMode === "plan") {
15752
- checker.planModeLocked = true;
15753
- }
15774
+ const inheritedChecker = checkerOverride ?? new PermissionChecker(cwd2, options.permissionMode);
15775
+ const checker = inheritedChecker.teammate ? inheritedChecker.forCwd(cwd2) : inheritedChecker.forSubagent(cwd2, definition.permissionMode);
15754
15776
  const conversation = options.conversation ?? new ConversationManager();
15755
15777
  if (!options.conversation || conversation.getMessages().length === 0) {
15756
15778
  conversation.addSystemReminder(buildSubagentInstructions(definition));
15757
15779
  }
15758
15780
  conversation.addUserMessage(prompt);
15759
15781
  const agent2 = new Agent({
15782
+ agentName: options.agentName ?? definition.name,
15760
15783
  client,
15761
15784
  registry,
15762
15785
  checker,
@@ -15862,7 +15885,6 @@ function coordinatorActive(enabled = false) {
15862
15885
  // src/teams/index.ts
15863
15886
  var teams_exports = {};
15864
15887
  __export(teams_exports, {
15865
- Backend: () => backend_exports,
15866
15888
  Coordinator: () => coordinator_exports2,
15867
15889
  FileLock: () => file_lock_exports,
15868
15890
  FileMailbox: () => file_mailbox_exports,
@@ -15877,137 +15899,8 @@ __export(teams_exports, {
15877
15899
  TeamManager: () => TeamManager,
15878
15900
  Tools: () => tools_exports
15879
15901
  });
15880
- import { randomBytes as randomBytes4 } from "crypto";
15881
- import { existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync11, rmSync as rmSync7 } from "fs";
15882
- import { createRequire } from "module";
15883
- import { dirname as dirname8, join as join19 } from "path";
15884
-
15885
- // src/teams/backend.ts
15886
- var backend_exports = {};
15887
- __export(backend_exports, {
15888
- detectBackend: () => detectBackend,
15889
- detectBackendFromEnv: () => detectBackendFromEnv,
15890
- isProcessAlive: () => isProcessAlive,
15891
- isTeammateAlive: () => isTeammateAlive,
15892
- restoreTeammateCancel: () => restoreTeammateCancel,
15893
- spawnTeammate: () => spawnTeammate
15894
- });
15895
- import { execFileSync } from "child_process";
15896
- var log25 = createChildLogger({ module: "teams" });
15897
- function detectBackend() {
15898
- if (process.platform === "win32") {
15899
- return "in-process";
15900
- }
15901
- return detectBackendFromEnv();
15902
- }
15903
- function detectBackendFromEnv() {
15904
- if (process.env.TMUX) {
15905
- return "tmux";
15906
- }
15907
- if (process.env.ITERM_SESSION_ID) {
15908
- return "iterm";
15909
- }
15910
- return "in-process";
15911
- }
15912
- function shellQuote(arg) {
15913
- if (/^[A-Za-z0-9_/.:=-]+$/.test(arg)) {
15914
- return arg;
15915
- }
15916
- return `'${arg.replace(/'/g, `'\\''`)}'`;
15917
- }
15918
- function buildShellCommand(config) {
15919
- return [config.command, ...config.args].map(shellQuote).join(" ");
15920
- }
15921
- function cancelTmuxSession(sessionName) {
15922
- try {
15923
- execFileSync("tmux", ["kill-session", "-t", sessionName], {
15924
- stdio: ["pipe", "pipe", "pipe"]
15925
- });
15926
- } catch (err) {
15927
- log25.error({ err }, "teams operation failed");
15928
- }
15929
- }
15930
- function restoreTeammateCancel(mode2, paneId) {
15931
- if (mode2 !== "tmux" || !paneId) {
15932
- return void 0;
15933
- }
15934
- return () => {
15935
- cancelTmuxSession(paneId);
15936
- };
15937
- }
15938
- function isProcessAlive(pid) {
15939
- try {
15940
- process.kill(pid, 0);
15941
- return true;
15942
- } catch (error) {
15943
- return error instanceof Error && "code" in error && error.code === "EPERM";
15944
- }
15945
- }
15946
- function isTeammateAlive(mode2, paneId, workerPid) {
15947
- if (workerPid) {
15948
- return isProcessAlive(workerPid);
15949
- }
15950
- if (mode2 !== "tmux" || !paneId) {
15951
- return false;
15952
- }
15953
- try {
15954
- execFileSync("tmux", ["has-session", "-t", paneId], {
15955
- stdio: ["ignore", "ignore", "ignore"]
15956
- });
15957
- return true;
15958
- } catch {
15959
- return false;
15960
- }
15961
- }
15962
- function spawnTeammate(config) {
15963
- switch (config.mode) {
15964
- case "tmux": {
15965
- const sessionName = config.paneId ?? `yukino-${Date.now().toString(36)}`;
15966
- const cmd = buildShellCommand(config);
15967
- execFileSync(
15968
- "tmux",
15969
- ["new-session", "-d", "-s", sessionName, "-n", "teammate", cmd],
15970
- {
15971
- cwd: config.cwd,
15972
- encoding: "utf-8",
15973
- stdio: ["pipe", "pipe", "pipe"]
15974
- }
15975
- );
15976
- return {
15977
- cancel: () => {
15978
- cancelTmuxSession(sessionName);
15979
- },
15980
- paneId: sessionName
15981
- };
15982
- }
15983
- case "iterm": {
15984
- const cmd = buildShellCommand(config);
15985
- const writeText = `cd ${shellQuote(config.cwd)} && ${cmd}`;
15986
- const script = [
15987
- "on run argv",
15988
- " set commandText to item 1 of argv",
15989
- ' tell application "iTerm2"',
15990
- " tell current window",
15991
- " create tab with default profile",
15992
- " tell current session to write text commandText",
15993
- " end tell",
15994
- " end tell",
15995
- "end run"
15996
- ].join("\n");
15997
- execFileSync("osascript", ["-e", script, writeText], {
15998
- cwd: config.cwd,
15999
- encoding: "utf-8",
16000
- stdio: ["pipe", "pipe", "pipe"]
16001
- });
16002
- return {
16003
- cancel: () => {
16004
- }
16005
- };
16006
- }
16007
- default:
16008
- throw new Error(`Unknown team mode: ${String(config.mode)}`);
16009
- }
16010
- }
15902
+ import { mkdirSync as mkdirSync10, readFileSync as readFileSync11, rmSync as rmSync7 } from "fs";
15903
+ import { join as join19 } from "path";
16011
15904
 
16012
15905
  // src/teams/file-mailbox.ts
16013
15906
  var file_mailbox_exports = {};
@@ -16024,7 +15917,7 @@ import {
16024
15917
  } from "fs";
16025
15918
  import { join as join18 } from "path";
16026
15919
  import z15 from "zod";
16027
- var log26 = createChildLogger({ module: "teams" });
15920
+ var log25 = createChildLogger({ module: "teams" });
16028
15921
  var FileMailMessageSchema = z15.object({
16029
15922
  from: z15.string(),
16030
15923
  text: z15.string(),
@@ -16057,7 +15950,7 @@ var FileMailbox = class {
16057
15950
  const raw = JSON.parse(readFileSync9(this.filePath, "utf-8"));
16058
15951
  return z15.array(FileMailMessageSchema).parse(raw);
16059
15952
  } catch (err) {
16060
- log26.error({ err }, "teams operation failed");
15953
+ log25.error({ err }, "teams operation failed");
16061
15954
  throw new Error(
16062
15955
  "Cannot load an unreadable teammate mailbox; original contents were preserved",
16063
15956
  { cause: err }
@@ -16315,14 +16208,22 @@ var StoreDataSchema = z17.object({
16315
16208
  next_id: z17.number().int().positive().max(Number.MAX_SAFE_INTEGER),
16316
16209
  tasks: z17.array(SerializedTaskSchema)
16317
16210
  });
16211
+ var log26 = createChildLogger({ module: "shared-tasks" });
16318
16212
  var SharedTaskStore = class {
16319
16213
  path;
16320
16214
  nextId = 1;
16321
16215
  tasks = [];
16216
+ listeners = /* @__PURE__ */ new Set();
16322
16217
  constructor(path) {
16323
16218
  this.path = path;
16324
16219
  this.load();
16325
16220
  }
16221
+ subscribe(listener) {
16222
+ this.listeners.add(listener);
16223
+ return () => {
16224
+ this.listeners.delete(listener);
16225
+ };
16226
+ }
16326
16227
  load() {
16327
16228
  if (!existsSync12(this.path)) {
16328
16229
  this.tasks = [];
@@ -16360,24 +16261,34 @@ var SharedTaskStore = class {
16360
16261
  }
16361
16262
  }
16362
16263
  mutate(operation) {
16363
- return withFileSyncLock(this.path, () => {
16264
+ const result = withFileSyncLock(this.path, () => {
16364
16265
  this.load();
16365
16266
  const previousTasks = this.tasks;
16366
16267
  const previousId = this.nextId;
16367
16268
  this.tasks = structuredClone(previousTasks);
16368
16269
  try {
16369
- const result = operation();
16370
- if (result !== void 0 && result !== false) {
16270
+ const result2 = operation();
16271
+ if (result2 !== void 0 && result2 !== false) {
16371
16272
  validateTaskDependencies(this.tasks);
16372
16273
  this.save();
16373
16274
  }
16374
- return structuredClone(result);
16275
+ return structuredClone(result2);
16375
16276
  } catch (error) {
16376
16277
  this.tasks = previousTasks;
16377
16278
  this.nextId = previousId;
16378
16279
  throw error;
16379
16280
  }
16380
16281
  });
16282
+ if (result !== void 0 && result !== false) {
16283
+ for (const listener of this.listeners) {
16284
+ try {
16285
+ listener(structuredClone(this.tasks));
16286
+ } catch (error) {
16287
+ log26.error({ error }, "shared task subscriber failed");
16288
+ }
16289
+ }
16290
+ }
16291
+ return result;
16381
16292
  }
16382
16293
  create(subject, description = "", owner = "", blocks = [], blockedBy = [], createdBy = "", activeForm, metadata = {}) {
16383
16294
  return this.mutate(() => {
@@ -16569,25 +16480,16 @@ var log27 = createChildLogger({ module: "teams" });
16569
16480
  var MAX_RETAINED_TERMINATED_MEMBERS = 200;
16570
16481
  var Team = class _Team {
16571
16482
  name;
16572
- mode;
16573
16483
  members = /* @__PURE__ */ new Map();
16574
16484
  leaderMailbox;
16575
16485
  mailboxDir;
16576
16486
  cwd;
16577
- lastLivenessCheck = 0;
16578
16487
  leaderAgentId = "";
16579
16488
  permissionMode = "default";
16580
16489
  description;
16581
16490
  createdAt = Math.floor(Date.now() / 1e3);
16582
- /**
16583
- * PID of the leader process. Written to config.json so external teammates
16584
- * can detect a dead leader (they exit instead of polling forever); a
16585
- * restarted leader re-claims it when the team is restored from disk.
16586
- */
16587
- leaderPid = 0;
16588
- constructor(name, mode2, cwd2) {
16491
+ constructor(name, cwd2) {
16589
16492
  this.name = name;
16590
- this.mode = mode2;
16591
16493
  this.cwd = cwd2;
16592
16494
  this.mailboxDir = join19(teamDir(cwd2, name), "inboxes");
16593
16495
  mkdirSync10(this.mailboxDir, { recursive: true });
@@ -16599,7 +16501,6 @@ var Team = class _Team {
16599
16501
  active: false,
16600
16502
  mailbox: new FileMailbox(this.mailboxDir, name),
16601
16503
  agentId: name,
16602
- backendType: this.mode,
16603
16504
  joinedAt: Math.floor(Date.now() / 1e3)
16604
16505
  };
16605
16506
  }
@@ -16632,23 +16533,7 @@ var Team = class _Team {
16632
16533
  member.model = entry.model;
16633
16534
  member.worktreePath = entry.worktreePath;
16634
16535
  member.joinedAt = entry.joinedAt;
16635
- member.backendType = isTeamMode(entry.backendType) ? entry.backendType : this.mode;
16636
- member.paneId = entry.paneId;
16637
- member.workerPid = entry.workerPid;
16638
- member.external = member.backendType === "tmux" || member.backendType === "iterm";
16639
- member.active = entry.isActive && member.external && isTeammateAlive(member.backendType, member.paneId, member.workerPid);
16640
- if (member.active) {
16641
- getNameRegistry().register(member.name, member.agentId);
16642
- member.uiState = {
16643
- name: member.name,
16644
- teamName: this.name,
16645
- status: "running",
16646
- progress: createProgress(),
16647
- startTime: entry.joinedAt > 0 ? entry.joinedAt * 1e3 : Date.now(),
16648
- spinnerVerb: "Working"
16649
- };
16650
- member.cancel = restoreTeammateCancel(member.backendType, member.paneId);
16651
- }
16536
+ member.active = false;
16652
16537
  this.members.set(member.name, member);
16653
16538
  return member;
16654
16539
  }
@@ -16669,12 +16554,10 @@ var Team = class _Team {
16669
16554
  snapshot() {
16670
16555
  return {
16671
16556
  name: this.name,
16672
- mode: this.mode,
16673
16557
  description: this.description,
16674
16558
  createdAt: this.createdAt,
16675
16559
  leaderAgentId: this.leaderAgentId,
16676
16560
  permissionMode: this.permissionMode,
16677
- ...this.leaderPid > 0 ? { leaderPid: this.leaderPid } : {},
16678
16561
  members: [...this.members.values()].map((m) => ({
16679
16562
  agentId: m.agentId ?? m.name,
16680
16563
  name: m.name,
@@ -16682,9 +16565,6 @@ var Team = class _Team {
16682
16565
  model: m.model,
16683
16566
  joinedAt: m.joinedAt ?? 0,
16684
16567
  worktreePath: m.worktreePath,
16685
- backendType: m.backendType ?? this.mode,
16686
- paneId: m.paneId,
16687
- workerPid: m.workerPid,
16688
16568
  isActive: m.active
16689
16569
  }))
16690
16570
  };
@@ -16698,148 +16578,20 @@ var Team = class _Team {
16698
16578
  writeTeamFile(this.cwd, this.name, this.snapshot());
16699
16579
  }
16700
16580
  static IDLE_POLL_INTERVAL_MS = 500;
16701
- // Grace period after the shutdown notice before force-killing an external
16702
- // teammate: one mailbox poll interval (~2 s) plus exit time.
16703
- static STOP_GRACE_MS = 2500;
16704
16581
  // The leader writes a mailbox message with this prefix to notify
16705
16582
  // teammates to exit.
16706
16583
  static SHUTDOWN_PREFIX = SHUTDOWN_PREFIX;
16707
- /**
16708
- * Spawns a teammate, dispatching by team backend mode.
16709
- * - in-process: runs the agent main loop in a background task within this process (idle-poll-continue).
16710
- * - tmux / iterm: assembles the teammate startup command and delegates to the backend to launch
16711
- * an independent worker process in a new pane / tab, communicating bidirectionally with the
16712
- * leader via the shared file-based mailbox.
16713
- * Falls back to in-process when the external backend is unavailable (tmux not installed,
16714
- * non-iTerm environment, etc.) to avoid crashes.
16715
- */
16716
- spawnTeammate(name, task, runAgent, checker, providerIndex, originToolCallId, memberCwd = this.cwd, role = {}) {
16584
+ spawnTeammate(name, task, runAgent, checker, originToolCallId, memberCwd = this.cwd, role = {}) {
16717
16585
  const member = this.getMember(name) ?? this.addMember(name);
16718
16586
  if (member.active) {
16719
16587
  throw new Error(`Teammate '${name}' is already running`);
16720
16588
  }
16721
16589
  this.setMemberMeta(name, role);
16722
- member.planApprovalRequired = role.planApprovalRequired ?? checker?.planModeLocked ?? false;
16723
- member.readOnlyRole = role.readOnly ?? false;
16724
- const mode2 = this.mode;
16725
- if (mode2 === "in-process" || checker?.mode === "plan") {
16726
- this.spawnInProcess(
16727
- name,
16728
- task,
16729
- runAgent,
16730
- checker,
16731
- originToolCallId,
16732
- memberCwd,
16733
- role.cleanup
16734
- );
16735
- return "in-process";
16590
+ member.planApprovalRequired = role.planApprovalRequired ?? false;
16591
+ if (checker?.mode === "plan" && !checker.planFilePath) {
16592
+ checker.planFilePath = createPlanPath();
16736
16593
  }
16737
- try {
16738
- this.spawnExternal(
16739
- mode2,
16740
- name,
16741
- task,
16742
- providerIndex,
16743
- originToolCallId,
16744
- memberCwd,
16745
- role
16746
- );
16747
- return mode2;
16748
- } catch {
16749
- this.spawnInProcess(
16750
- name,
16751
- task,
16752
- runAgent,
16753
- checker,
16754
- originToolCallId,
16755
- memberCwd,
16756
- role.cleanup
16757
- );
16758
- return "in-process";
16759
- }
16760
- }
16761
- /**
16762
- * tmux / iTerm backend: launches the teammate as an independent process in a new pane / tab.
16763
- * The teammate process connects back to the team via the same mailbox directory pointed to
16764
- * by `--team-dir`; task assignments from the leader and idle/result notifications from the
16765
- * worker all land in this directory, keeping both sides in sync.
16766
- */
16767
- spawnExternal(mode2, name, task, providerIndex, originToolCallId, memberCwd = this.cwd, role = {}) {
16768
- const member = this.getMember(name) ?? this.addMember(name);
16769
- member.stopping = void 0;
16770
- member.done = void 0;
16771
- member.workerPid = void 0;
16772
16594
  member.active = true;
16773
- member.backendType = mode2;
16774
- member.external = true;
16775
- member.paneId = mode2 === "tmux" ? `yukino-${randomBytes4(8).toString("hex")}` : void 0;
16776
- member.worktreePath = memberCwd === this.cwd ? void 0 : memberCwd;
16777
- this.persist();
16778
- getNameRegistry().register(name, name);
16779
- member.uiState = {
16780
- name,
16781
- teamName: this.name,
16782
- status: "running",
16783
- progress: createProgress(),
16784
- ...originToolCallId ? { originToolCallId } : {},
16785
- startTime: Date.now(),
16786
- spinnerVerb: "Working"
16787
- };
16788
- const require2 = createRequire(import.meta.url);
16789
- const packageDir = dirname8(
16790
- require2.resolve("@yukino.js/yukino/package.json")
16791
- );
16792
- const sourceEntry = join19(packageDir, "src", "cli.ts");
16793
- const sourceRuntime = existsSync13(sourceEntry);
16794
- const entry = sourceRuntime ? sourceEntry : join19(packageDir, "dist", "main.js");
16795
- const config = {
16796
- mode: mode2,
16797
- command: process.execPath,
16798
- args: [
16799
- ...sourceRuntime ? ["--import", require2.resolve("tsx/esm")] : [],
16800
- entry,
16801
- "--teammate",
16802
- "--team-dir",
16803
- this.mailboxDir,
16804
- "--team-name",
16805
- this.name,
16806
- "--team-cwd",
16807
- this.cwd,
16808
- "--member-name",
16809
- name,
16810
- "--task",
16811
- task,
16812
- "--permission-mode",
16813
- this.permissionMode,
16814
- ...role.agentType ? ["--agent-type", role.agentType] : [],
16815
- ...role.model ? ["--model", role.model] : [],
16816
- ...providerIndex !== void 0 ? ["--provider-index", String(providerIndex)] : []
16817
- ],
16818
- cwd: memberCwd,
16819
- paneId: member.paneId
16820
- };
16821
- const { cancel, paneId } = spawnTeammate(config);
16822
- member.cancel = cancel;
16823
- member.paneId = paneId;
16824
- member.external = true;
16825
- this.persist();
16826
- }
16827
- /**
16828
- * Starts an in-process teammate: runs the agent's main loop in the background,
16829
- * sends an idle notification upon completion, and then polls the mailbox for new tasks.
16830
- * Exits the loop upon receiving a shutdown message or being canceled.
16831
- * Uses the idle-poll-continue pattern: after each turn completes, reports idle and waits for the next task.
16832
- */
16833
- spawnInProcess(name, task, runAgent, checker, originToolCallId, memberCwd = this.cwd, cleanup) {
16834
- const member = this.getMember(name) ?? this.addMember(name);
16835
- if (checker?.planModeLocked && !checker.planFilePath) {
16836
- checker.planFilePath = createPlanPath();
16837
- }
16838
- member.active = true;
16839
- member.backendType = "in-process";
16840
- member.external = false;
16841
- member.paneId = void 0;
16842
- member.workerPid = void 0;
16843
16595
  member.worktreePath = memberCwd === this.cwd ? void 0 : memberCwd;
16844
16596
  this.persist();
16845
16597
  member.checker = checker;
@@ -16907,7 +16659,7 @@ var Team = class _Team {
16907
16659
  uiState.status = "idle";
16908
16660
  const next = await this.runPlanApproval(
16909
16661
  member,
16910
- this.readPlanForReview(member, result)
16662
+ this.readPlan(member, result)
16911
16663
  );
16912
16664
  if (next === null) {
16913
16665
  break;
@@ -16958,7 +16710,7 @@ var Team = class _Team {
16958
16710
  uiState.status = "idle";
16959
16711
  }
16960
16712
  try {
16961
- await cleanup?.();
16713
+ await role.cleanup?.();
16962
16714
  } catch (error) {
16963
16715
  log27.error({ error, name }, "teammate resource cleanup failed");
16964
16716
  } finally {
@@ -17019,8 +16771,8 @@ ${prompt}` };
17019
16771
  shutdown: shutdownRequest(LEADER_NAME, "member deactivated")
17020
16772
  };
17021
16773
  }
17022
- /** Reads the teammate's plan file for review; returns a fallback note when empty or unreadable. */
17023
- readPlanForReview(member, result) {
16774
+ /** Reads the submitted plan, falling back to the final response. */
16775
+ readPlan(member, result) {
17024
16776
  try {
17025
16777
  const text = readFileSync11(member.checker?.planFilePath ?? "", "utf-8");
17026
16778
  if (text.trim()) {
@@ -17030,55 +16782,24 @@ ${prompt}` };
17030
16782
  }
17031
16783
  return result || "(The teammate returned no plan.)";
17032
16784
  }
17033
- /**
17034
- * Sends the teammate's completed plan to the Leader, blocks until approval is received,
17035
- * and returns the prompt to feed the model on the next turn.
17036
- *
17037
- * The teammate holds read-only permissions at this point, so no matter how long the
17038
- * wait, no damage can occur — hence no timeout is set here. Rather than timing out and
17039
- * autonomously modifying files, it is better to wait indefinitely and let the user
17040
- * drive progress from the Leader side. Returns null when the teammate has been
17041
- * deactivated; the caller should exit the main loop.
17042
- */
17043
16785
  async runPlanApproval(member, plan) {
17044
- const req = planApprovalRequest(member.name, plan);
17045
- await this.leaderMailbox.send(member.name, req.text, req);
17046
- const held = [];
17047
- let response;
17048
- while (member.active && response === void 0) {
17049
- await this.waitForMember(member);
17050
- if (!member.active || member.signal?.aborted) {
17051
- break;
17052
- }
17053
- for (const m of member.mailbox.receiveSync()) {
17054
- if (isShutdownRequest(m)) {
17055
- const reply = shutdownResponse(
17056
- member.name,
17057
- m.requestId ?? "",
17058
- true,
17059
- "acknowledged, shutting down"
17060
- );
17061
- await this.leaderMailbox.send(member.name, reply.text, reply);
17062
- member.active = false;
17063
- } else if (m.type === MSG_PLAN_APPROVAL_RESPONSE && m.from === LEADER_NAME && m.requestId === req.requestId) {
17064
- response = m;
17065
- } else {
17066
- held.push(m);
17067
- }
17068
- }
17069
- }
17070
- member.mailbox.requeue(held);
17071
- if (!response || !member.active) {
16786
+ const request = planApprovalRequest(member.name, plan);
16787
+ await this.leaderMailbox.send(member.name, request.text, request);
16788
+ if (!member.active || member.signal?.aborted || !member.checker) {
17072
16789
  return null;
17073
16790
  }
17074
- if (approved(response) && member.checker) {
17075
- if (!member.readOnlyRole) {
17076
- member.checker.planModeLocked = false;
17077
- }
17078
- member.planApprovalRequired = false;
16791
+ const response = planApprovalResponse(
16792
+ LEADER_NAME,
16793
+ request.requestId ?? "",
16794
+ "Plan automatically approved; tool permissions remain active."
16795
+ );
16796
+ await this.leaderMailbox.send(LEADER_NAME, response.text, response);
16797
+ if (!member.active || member.signal?.aborted) {
16798
+ return null;
17079
16799
  }
17080
- return approved(response) ? "The Leader has approved your plan. Begin execution now." : `The Leader rejected your plan. Feedback: ${response.text}
17081
- Please revise the plan accordingly and resubmit.`;
16800
+ member.checker.mode = this.permissionMode === "plan" ? "default" : this.permissionMode;
16801
+ member.planApprovalRequired = false;
16802
+ return "Your plan was automatically approved. Begin execution within the current tool permissions; plan approval does not authorize individual tool calls.";
17082
16803
  }
17083
16804
  getMember(name) {
17084
16805
  return this.members.get(name);
@@ -17144,55 +16865,16 @@ Please revise the plan accordingly and resubmit.`;
17144
16865
  );
17145
16866
  this.persist();
17146
16867
  }
17147
- /**
17148
- * Stops a single teammate: marks it inactive, updates UI state, and
17149
- * unregisters the name so SendMessage can no longer resolve it.
17150
- * External teammates get a grace window after the shutdown notice — they
17151
- * poll their mailbox every ~2 s, so waiting one poll interval lets the
17152
- * common (idle) case exit gracefully before the pane is force-killed.
17153
- * In-process teammates are stopped via cancel (abort) alone; `done` is then
17154
- * awaited so the loop has fully exited (external members have no promise).
17155
- */
17156
16868
  stopOne(member) {
17157
16869
  member.stopping ??= this.stopMemberRuntime(member);
17158
16870
  return member.stopping;
17159
16871
  }
17160
16872
  async stopMemberRuntime(member) {
17161
- const wasActive = member.active;
17162
16873
  member.active = false;
17163
16874
  if (member.uiState?.status === "running" || member.uiState?.status === "idle") {
17164
16875
  member.uiState.status = "stopped";
17165
16876
  }
17166
16877
  getNameRegistry().unregister(member.name);
17167
- if (member.external && wasActive) {
17168
- try {
17169
- await member.mailbox.send(LEADER_NAME, `${_Team.SHUTDOWN_PREFIX} stop`);
17170
- await new Promise((r) => setTimeout(r, _Team.STOP_GRACE_MS));
17171
- } catch {
17172
- }
17173
- }
17174
- if (member.external && member.backendType === "iterm") {
17175
- const pid = readTeamFile(this.cwd, this.name)?.members.find(
17176
- (entry) => entry.name === member.name
17177
- )?.workerPid;
17178
- if (pid && pid !== process.pid && isProcessAlive(pid)) {
17179
- try {
17180
- process.kill(pid, "SIGTERM");
17181
- const deadline = Date.now() + 2500;
17182
- while (isProcessAlive(pid) && Date.now() < deadline) {
17183
- await new Promise((resolve11) => setTimeout(resolve11, 50));
17184
- }
17185
- if (isProcessAlive(pid)) {
17186
- process.kill(pid, "SIGKILL");
17187
- }
17188
- } catch (error) {
17189
- log27.error(
17190
- { error, member: member.name },
17191
- "external teammate termination failed"
17192
- );
17193
- }
17194
- }
17195
- }
17196
16878
  try {
17197
16879
  member.cancel?.();
17198
16880
  } catch (error) {
@@ -17203,7 +16885,6 @@ Please revise the plan accordingly and resubmit.`;
17203
16885
  member.cancel = void 0;
17204
16886
  member.checker = void 0;
17205
16887
  member.signal = void 0;
17206
- member.workerPid = void 0;
17207
16888
  member.done = void 0;
17208
16889
  this.pruneTerminatedMembers();
17209
16890
  }
@@ -17211,52 +16892,10 @@ Please revise the plan accordingly and resubmit.`;
17211
16892
  return [...this.members.values()];
17212
16893
  }
17213
16894
  getTeammateStates() {
17214
- this.refreshExternalMembers();
17215
16895
  return this.listMembers().flatMap(
17216
16896
  (member) => member.uiState ? [member.uiState] : []
17217
16897
  );
17218
16898
  }
17219
- refreshExternalMembers() {
17220
- const now = Date.now();
17221
- if (now - this.lastLivenessCheck < 2e3) {
17222
- return;
17223
- }
17224
- this.lastLivenessCheck = now;
17225
- const config = readTeamFile(this.cwd, this.name);
17226
- for (const member of this.members.values()) {
17227
- if (!member.external || !member.active) {
17228
- continue;
17229
- }
17230
- member.workerPid = config?.members.find((entry) => entry.name === member.name)?.workerPid ?? member.workerPid;
17231
- if (!member.workerPid && member.backendType === "iterm" && now - (member.uiState?.startTime ?? now) < 1e4) {
17232
- continue;
17233
- }
17234
- if (isTeammateAlive(
17235
- member.backendType ?? this.mode,
17236
- member.paneId,
17237
- member.workerPid
17238
- )) {
17239
- continue;
17240
- }
17241
- member.active = false;
17242
- member.cancel = void 0;
17243
- member.checker = void 0;
17244
- member.workerPid = void 0;
17245
- getNameRegistry().unregister(member.name);
17246
- if (member.uiState) {
17247
- member.uiState.status = "failed";
17248
- member.uiState.lastMessage = "Teammate process exited unexpectedly";
17249
- clearActiveTools(member.uiState.progress);
17250
- }
17251
- this.releaseMemberTasks(member);
17252
- this.leaderMailbox.sendSync(
17253
- member.name,
17254
- `[idle] ${member.name} (reason: failed): teammate process exited unexpectedly`
17255
- );
17256
- this.persist();
17257
- }
17258
- this.pruneTerminatedMembers();
17259
- }
17260
16899
  pruneTerminatedMembers() {
17261
16900
  const terminal = this.listMembers().filter(
17262
16901
  (member) => !member.active && !member.done && !member.cancel && member.uiState && ["completed", "failed", "stopped"].includes(member.uiState.status)
@@ -17283,14 +16922,28 @@ var TeamManager = class {
17283
16922
  /** Teams keyed by their canonical disk slug; Team.name remains the display name. */
17284
16923
  teams = /* @__PURE__ */ new Map();
17285
16924
  cwd;
17286
- claimLeadership;
17287
16925
  permissionChecker;
17288
16926
  unsubscribePermissions;
17289
16927
  // One shared task store per canonical team identity.
17290
16928
  taskStores = /* @__PURE__ */ new Map();
17291
- constructor(cwd2, opts = {}) {
16929
+ listeners = /* @__PURE__ */ new Set();
16930
+ constructor(cwd2) {
17292
16931
  this.cwd = canonicalPath(cwd2);
17293
- this.claimLeadership = opts.claimLeadership ?? true;
16932
+ }
16933
+ subscribe(listener) {
16934
+ this.listeners.add(listener);
16935
+ return () => {
16936
+ this.listeners.delete(listener);
16937
+ };
16938
+ }
16939
+ emitChange() {
16940
+ for (const listener of this.listeners) {
16941
+ try {
16942
+ listener();
16943
+ } catch (error) {
16944
+ log27.error({ error }, "team subscriber failed");
16945
+ }
16946
+ }
17294
16947
  }
17295
16948
  setPermissionChecker(checker) {
17296
16949
  if (this.permissionChecker === checker) {
@@ -17300,7 +16953,7 @@ var TeamManager = class {
17300
16953
  this.permissionChecker = checker;
17301
16954
  const sync = () => {
17302
16955
  for (const team of this.teams.values()) {
17303
- team.permissionMode = checker.delegatedMode;
16956
+ team.permissionMode = checker.mode;
17304
16957
  team.persist();
17305
16958
  }
17306
16959
  };
@@ -17313,84 +16966,63 @@ var TeamManager = class {
17313
16966
  teamDir(name) {
17314
16967
  return teamDir(this.cwd, name);
17315
16968
  }
17316
- create(name, mode2 = detectBackend(), opts = {}) {
16969
+ create(name, opts = {}) {
17317
16970
  const existing = this.get(name);
17318
16971
  if (existing) {
17319
16972
  return existing;
17320
16973
  }
17321
16974
  const key = this.teamKey(name);
17322
- const team = new Team(name, mode2, this.cwd);
17323
- team.permissionMode = this.permissionChecker?.delegatedMode ?? "default";
16975
+ const team = new Team(name, this.cwd);
16976
+ team.permissionMode = this.permissionChecker?.mode ?? "default";
17324
16977
  team.leaderAgentId = opts.leaderAgentId ?? "";
17325
16978
  team.description = opts.description;
17326
- if (this.claimLeadership) {
17327
- team.leaderPid = process.pid;
17328
- }
17329
16979
  this.teams.set(key, team);
17330
16980
  const store = new SharedTaskStore(join19(this.teamDir(name), "tasks.json"));
17331
16981
  store.initEmpty();
17332
16982
  this.taskStores.set(key, store);
17333
16983
  team.persist();
16984
+ this.emitChange();
17334
16985
  return team;
17335
16986
  }
17336
- /**
17337
- * Checks the in-memory cache first; on miss, hydrates config.json without
17338
- * incremental member writes. Active members regain their runtime-facing UI,
17339
- * registry, and external cancellation metadata. A leader claims leadership
17340
- * with one final snapshot; teammate processes leave the file byte-identical.
17341
- */
17342
16987
  get(name) {
17343
16988
  const key = this.teamKey(name);
17344
16989
  const cached = this.teams.get(key);
17345
- if (cached && this.claimLeadership) {
16990
+ if (cached) {
17346
16991
  return cached;
17347
16992
  }
17348
16993
  const tf = readTeamFile(this.cwd, name);
17349
16994
  if (!tf) {
17350
- if (!this.claimLeadership) {
17351
- this.teams.delete(key);
17352
- }
17353
16995
  return void 0;
17354
16996
  }
17355
- const team = new Team(tf.name, tf.mode, this.cwd);
16997
+ const team = new Team(tf.name, this.cwd);
17356
16998
  team.leaderAgentId = tf.leaderAgentId;
17357
- team.permissionMode = this.permissionChecker?.delegatedMode ?? tf.permissionMode;
16999
+ team.permissionMode = this.permissionChecker?.mode ?? tf.permissionMode;
17358
17000
  team.description = tf.description;
17359
17001
  team.createdAt = tf.createdAt;
17360
- team.leaderPid = tf.leaderPid ?? 0;
17361
17002
  for (const member of tf.members) {
17362
17003
  const hydrated = team.hydrateMember(member);
17363
- if (this.claimLeadership && !hydrated.active) {
17364
- hydrated.uiState = {
17365
- name: hydrated.name,
17366
- teamName: team.name,
17367
- status: member.isActive ? "failed" : "stopped",
17368
- progress: createProgress(),
17369
- startTime: member.joinedAt * 1e3,
17370
- spinnerVerb: "Working"
17371
- };
17372
- team.releaseMemberTasks(hydrated);
17373
- }
17374
- }
17375
- if (this.claimLeadership) {
17376
- team.leaderPid = process.pid;
17377
- team.persist();
17378
- team.pruneTerminatedMembers();
17004
+ hydrated.uiState = {
17005
+ name: hydrated.name,
17006
+ teamName: team.name,
17007
+ status: member.isActive ? "failed" : "stopped",
17008
+ progress: createProgress(),
17009
+ startTime: member.joinedAt * 1e3,
17010
+ spinnerVerb: "Working"
17011
+ };
17012
+ team.releaseMemberTasks(hydrated);
17379
17013
  }
17014
+ team.persist();
17015
+ team.pruneTerminatedMembers();
17380
17016
  this.teams.set(key, team);
17017
+ this.emitChange();
17381
17018
  return team;
17382
17019
  }
17383
- /**
17384
- * Loads every team found on disk into the manager. Called on leader startup
17385
- * so teams (and their leader mailboxes) survive a leader restart: external
17386
- * teammates keep running, and their notifications are drained again.
17387
- */
17388
17020
  restoreFromDisk() {
17389
17021
  for (const name of listTeamNames(this.cwd)) {
17390
17022
  this.get(name);
17391
17023
  }
17392
17024
  }
17393
- /** Retrieves the team's shared task store; loads from disk (tasks.json) when not cached in memory (e.g. in a teammate process). */
17025
+ /** Retrieves the team's shared task store, loading tasks.json after restoration. */
17394
17026
  getTaskStore(teamName) {
17395
17027
  const key = this.teamKey(teamName);
17396
17028
  const cached = this.taskStores.get(key);
@@ -17404,11 +17036,6 @@ var TeamManager = class {
17404
17036
  return store;
17405
17037
  }
17406
17038
  list() {
17407
- if (!this.claimLeadership) {
17408
- for (const name of [...this.teams.values()].map((team) => team.name)) {
17409
- this.get(name);
17410
- }
17411
- }
17412
17039
  return [...this.teams.values()];
17413
17040
  }
17414
17041
  async stopAll() {
@@ -17423,6 +17050,7 @@ var TeamManager = class {
17423
17050
  this.permissionChecker = void 0;
17424
17051
  this.teams.clear();
17425
17052
  this.taskStores.clear();
17053
+ this.listeners.clear();
17426
17054
  }
17427
17055
  }
17428
17056
  async delete(name) {
@@ -17438,6 +17066,7 @@ var TeamManager = class {
17438
17066
  }
17439
17067
  this.taskStores.delete(key);
17440
17068
  rmSync7(this.teamDir(name), { recursive: true, force: true });
17069
+ this.emitChange();
17441
17070
  }
17442
17071
  /**
17443
17072
  * Deletes every team in this project: in-memory teams are stopped and
@@ -17456,9 +17085,6 @@ var TeamManager = class {
17456
17085
  return this.list().flatMap((t) => t.getTeammateStates());
17457
17086
  }
17458
17087
  hasLeaderNotifications() {
17459
- for (const team of this.list()) {
17460
- team.refreshExternalMembers();
17461
- }
17462
17088
  return this.list().some((team) => team.leaderMailbox.unreadCount() > 0);
17463
17089
  }
17464
17090
  /**
@@ -17476,29 +17102,6 @@ var TeamManager = class {
17476
17102
  const lines = [];
17477
17103
  lines.push(`<task-notification team="${team.name}">`);
17478
17104
  for (const msg of msgs) {
17479
- const member = team.getMember(msg.from);
17480
- if (member?.external && member.uiState && msg.text.startsWith("[idle]")) {
17481
- const failed = msg.text.includes(" failed:") || msg.text.includes("reason: failed");
17482
- const stopped = msg.text.includes("reason: stopped");
17483
- if (Date.parse(msg.timestamp) < member.uiState.startTime) {
17484
- continue;
17485
- }
17486
- if (!member.active && !failed && !stopped) {
17487
- continue;
17488
- }
17489
- member.uiState.status = failed ? "failed" : stopped ? "stopped" : "idle";
17490
- clearActiveTools(member.uiState.progress);
17491
- if (failed || stopped) {
17492
- member.active = false;
17493
- getNameRegistry().unregister(member.name);
17494
- team.releaseMemberTasks(member);
17495
- member.cancel = void 0;
17496
- member.checker = void 0;
17497
- member.workerPid = void 0;
17498
- team.persist();
17499
- team.pruneTerminatedMembers();
17500
- }
17501
- }
17502
17105
  const metadata = [
17503
17106
  msg.type ? `type=${msg.type}` : "",
17504
17107
  msg.requestId ? `requestId=${msg.requestId}` : "",
@@ -17514,9 +17117,6 @@ var TeamManager = class {
17514
17117
  return out;
17515
17118
  }
17516
17119
  };
17517
- function isTeamMode(mode2) {
17518
- return mode2 === "in-process" || mode2 === "tmux" || mode2 === "iterm";
17519
- }
17520
17120
 
17521
17121
  // src/tools/ask-user.ts
17522
17122
  var ask_user_exports = {};
@@ -17754,10 +17354,10 @@ var SyntheticOutputTool = class {
17754
17354
  };
17755
17355
 
17756
17356
  // src/websocket-security.ts
17757
- import { randomBytes as randomBytes5, timingSafeEqual } from "crypto";
17357
+ import { randomBytes as randomBytes4, timingSafeEqual } from "crypto";
17758
17358
  var WEBSOCKET_TOKEN_PARAM = "token";
17759
17359
  function createWebSocketAccessToken() {
17760
- return randomBytes5(32).toString("base64url");
17360
+ return randomBytes4(32).toString("base64url");
17761
17361
  }
17762
17362
  function tokensEqual(expected, provided) {
17763
17363
  if (!provided) {
@@ -17850,10 +17450,10 @@ var CodeReviewStartSchema = z19.object({
17850
17450
  commit: z19.string().optional(),
17851
17451
  excludePatterns: z19.array(z19.string()).optional()
17852
17452
  });
17853
- var FE_DIST = [
17854
- join20(import.meta.dirname, "fe", "dist"),
17855
- join20(import.meta.dirname, "..", "fe", "dist")
17856
- ].find((directory) => existsSync14(directory));
17453
+ var BROWSER_DIST = [
17454
+ join20(import.meta.dirname, "browser", "dist"),
17455
+ join20(import.meta.dirname, "..", "browser", "dist")
17456
+ ].find((directory) => existsSync13(directory));
17857
17457
  var MIME_TYPES = {
17858
17458
  ".html": "text/html; charset=utf-8",
17859
17459
  ".js": "application/javascript; charset=utf-8",
@@ -17865,15 +17465,15 @@ var MIME_TYPES = {
17865
17465
  ".woff2": "font/woff2"
17866
17466
  };
17867
17467
  function serveStatic(path) {
17868
- if (!FE_DIST) {
17468
+ if (!BROWSER_DIST) {
17869
17469
  return null;
17870
17470
  }
17871
17471
  const cleanPath = normalize(path).replace(/^(\.\.[/\\])+/, "");
17872
- const fullPath = join20(FE_DIST, cleanPath);
17873
- if (!fullPath.startsWith(FE_DIST)) {
17472
+ const fullPath = join20(BROWSER_DIST, cleanPath);
17473
+ if (!fullPath.startsWith(BROWSER_DIST)) {
17874
17474
  return null;
17875
17475
  }
17876
- if (!existsSync14(fullPath) || !statSync10(fullPath).isFile()) {
17476
+ if (!existsSync13(fullPath) || !statSync10(fullPath).isFile()) {
17877
17477
  return null;
17878
17478
  }
17879
17479
  const body = readFileSync12(fullPath);
@@ -18103,7 +17703,10 @@ async function createRemoteAgent(opts) {
18103
17703
  const fileHistory = new FileHistory(sessionId);
18104
17704
  const fileStateCache = new FileStateCache();
18105
17705
  const taskList = new TaskList(new TaskStore(sessionId));
17706
+ const teamManager = new TeamManager(cwd2);
18106
17707
  const registry = createToolRegistry(cwd2, taskList, {
17708
+ interactionMode: opts.interactionMode ?? "interactive",
17709
+ teamManager,
18107
17710
  lspServers: opts.lspServers
18108
17711
  });
18109
17712
  await configureBashSandbox(registry, cwd2, opts.sandboxConfig);
@@ -18174,13 +17777,12 @@ async function createRemoteAgent(opts) {
18174
17777
  {
18175
17778
  abortSignal,
18176
17779
  backgroundTasks: false,
17780
+ agentName: options?.agentName,
18177
17781
  conversation,
18178
17782
  onPermissionRequest: options?.onPermissionRequest
18179
17783
  }
18180
17784
  );
18181
17785
  };
18182
- const teamManager = new TeamManager(cwd2);
18183
- registerLeaderTaskTools(registry, teamManager, taskList);
18184
17786
  teamManager.restoreFromDisk();
18185
17787
  const backgroundTaskManager = new TaskManager();
18186
17788
  attachBackgroundTaskManager(registry, backgroundTaskManager);
@@ -18227,6 +17829,7 @@ async function createRemoteAgent(opts) {
18227
17829
  forkConv.addUserMessage(prompt);
18228
17830
  const forkTaskManager = new TaskManager();
18229
17831
  const agent2 = new Agent({
17832
+ agentName: "fork",
18230
17833
  client: forkClient,
18231
17834
  registry: forkRegistry,
18232
17835
  checker,
@@ -19262,7 +18865,7 @@ Investigate and design your approach. The agent will call ExitPlanMode when the
19262
18865
  const planPath = getOrCreatePlanPath(handle);
19263
18866
  let planContent = "";
19264
18867
  try {
19265
- if (existsSync14(planPath)) {
18868
+ if (existsSync13(planPath)) {
19266
18869
  planContent = readFileSync12(planPath, "utf-8");
19267
18870
  }
19268
18871
  } catch {
@@ -19318,7 +18921,7 @@ Investigate and design your approach. The agent will call ExitPlanMode when the
19318
18921
  const planPath = getOrCreatePlanPath(handle);
19319
18922
  let planContent = "";
19320
18923
  try {
19321
- if (existsSync14(planPath)) {
18924
+ if (existsSync13(planPath)) {
19322
18925
  planContent = readFileSync12(planPath, "utf-8");
19323
18926
  }
19324
18927
  } catch {
@@ -19612,9 +19215,12 @@ ${report}
19612
19215
  }
19613
19216
  /** Creates the onPermissionRequest callback for agent runs. */
19614
19217
  createPermissionCallback() {
19615
- return async (toolName, args, decision, _toolCallId, signal) => {
19218
+ return async (toolName, args, decision, _toolCallId, signal, source) => {
19616
19219
  const id = nextRequestId("perm");
19617
- const desc = formatPermissionDesc(args, decision);
19220
+ const desc = [
19221
+ source ? `${source.agentName} \xB7 ${source.cwd}` : "",
19222
+ formatPermissionDesc(args, decision)
19223
+ ].filter(Boolean).join("\n");
19618
19224
  this.broadcast({
19619
19225
  type: "permission_request",
19620
19226
  data: { id, toolName, description: desc }
@@ -19839,6 +19445,7 @@ async function createA2aRuntime(cwd2, sessionId) {
19839
19445
  throw new Error("No provider configured.");
19840
19446
  }
19841
19447
  const runtime2 = await createRemoteAgent({
19448
+ interactionMode: "non-interactive",
19842
19449
  provider,
19843
19450
  cwd: cwd2,
19844
19451
  hooks: config.hooks,
@@ -20172,7 +19779,7 @@ var YukinoA2aExecutor = class {
20172
19779
  const taskId = run2.taskId;
20173
19780
  const contextId = session.contextId;
20174
19781
  const events = run2.runtime.run(text, {
20175
- onPermissionRequest: (toolName, args, decision, toolCallId, signal) => this.requestPermission(
19782
+ onPermissionRequest: (toolName, args, decision, toolCallId, signal, source) => this.requestPermission(
20176
19783
  run2,
20177
19784
  taskId,
20178
19785
  contextId,
@@ -20180,7 +19787,8 @@ var YukinoA2aExecutor = class {
20180
19787
  args,
20181
19788
  decision,
20182
19789
  toolCallId,
20183
- signal
19790
+ signal,
19791
+ source
20184
19792
  )
20185
19793
  });
20186
19794
  void (async () => {
@@ -20201,7 +19809,7 @@ var YukinoA2aExecutor = class {
20201
19809
  this.finishRun(session, run2, taskId, contextId, failure);
20202
19810
  })();
20203
19811
  }
20204
- requestPermission(run2, taskId, contextId, toolName, args, decision, toolCallId, signal) {
19812
+ requestPermission(run2, taskId, contextId, toolName, args, decision, toolCallId, signal, source) {
20205
19813
  if (signal?.aborted || run2.canceled || run2.finished) {
20206
19814
  return Promise.resolve("deny");
20207
19815
  }
@@ -20212,7 +19820,10 @@ var YukinoA2aExecutor = class {
20212
19820
  permissionId,
20213
19821
  toolCallId,
20214
19822
  toolName,
20215
- reason: decision.reason,
19823
+ reason: [
19824
+ source ? `${source.agentName} \xB7 ${source.cwd}` : "",
19825
+ decision.reason
19826
+ ].filter(Boolean).join("\n"),
20216
19827
  args
20217
19828
  };
20218
19829
  return new Promise((resolve11) => {
@@ -20487,7 +20098,7 @@ __export(agent_exports2, {
20487
20098
  YukinoAcpAgent: () => YukinoAcpAgent,
20488
20099
  createYukinoAcpApp: () => createYukinoAcpApp
20489
20100
  });
20490
- import { existsSync as existsSync15 } from "fs";
20101
+ import { existsSync as existsSync14 } from "fs";
20491
20102
  import { isAbsolute as isAbsolute5 } from "path";
20492
20103
  import * as acp from "@agentclientprotocol/sdk";
20493
20104
 
@@ -20846,7 +20457,7 @@ var YukinoAcpAgent = class {
20846
20457
  return {};
20847
20458
  }
20848
20459
  const saved = loadSession(params.cwd, params.sessionId);
20849
- if (!session && !existsSync15(getSessionFilePath(params.cwd, params.sessionId))) {
20460
+ if (!session && !existsSync14(getSessionFilePath(params.cwd, params.sessionId))) {
20850
20461
  throw acp.RequestError.resourceNotFound(params.sessionId);
20851
20462
  }
20852
20463
  if (!session) {
@@ -20982,7 +20593,7 @@ var YukinoAcpAgent = class {
20982
20593
  let sawUsage = false;
20983
20594
  let usage = emptyUsage();
20984
20595
  for await (const event of session.runtime.run(text, {
20985
- onPermissionRequest: async (toolName, args, decision, toolCallId, requestSignal) => {
20596
+ onPermissionRequest: async (toolName, args, decision, toolCallId, requestSignal, source) => {
20986
20597
  const permissionSignal = requestSignal ?? signal;
20987
20598
  const permission = context2.client.request(
20988
20599
  acp.methods.client.session.requestPermission,
@@ -20990,17 +20601,20 @@ var YukinoAcpAgent = class {
20990
20601
  sessionId,
20991
20602
  toolCall: {
20992
20603
  toolCallId,
20993
- title: `${toolName}: ${decision.reason}`,
20604
+ title: `${source ? `${source.agentName} \xB7 ${source.cwd} \xB7 ` : ""}${toolName}: ${decision.reason}`,
20994
20605
  kind: toolKind(toolName),
20995
20606
  status: "pending",
20996
20607
  rawInput: args,
20997
- locations: toolLocations(args, session.runtime.cwd)
20608
+ locations: toolLocations(
20609
+ args,
20610
+ source?.cwd ?? session.runtime.cwd
20611
+ )
20998
20612
  },
20999
20613
  options: [
21000
20614
  { optionId: "allow", name: "Allow once", kind: "allow_once" },
21001
20615
  {
21002
20616
  optionId: "allowAlways",
21003
- name: "Always allow",
20617
+ name: "Allow pattern for all project agents",
21004
20618
  kind: "allow_always"
21005
20619
  },
21006
20620
  { optionId: "deny", name: "Reject", kind: "reject_once" }
@@ -21467,8 +21081,8 @@ var usage_tracker_exports = {};
21467
21081
  __export(usage_tracker_exports, {
21468
21082
  CommandUsageTracker: () => CommandUsageTracker
21469
21083
  });
21470
- import { readFileSync as readFileSync13, writeFileSync as writeFileSync10, mkdirSync as mkdirSync11, existsSync as existsSync16 } from "fs";
21471
- import { join as join21, dirname as dirname9 } from "path";
21084
+ import { readFileSync as readFileSync13, writeFileSync as writeFileSync10, mkdirSync as mkdirSync11, existsSync as existsSync15 } from "fs";
21085
+ import { join as join21, dirname as dirname8 } from "path";
21472
21086
  import { safeParse as safeParse6, z as z21 } from "zod";
21473
21087
  var log29 = createChildLogger({ module: "commands" });
21474
21088
  var UsageEntrySchema = z21.object({
@@ -21481,7 +21095,7 @@ var CommandUsageTracker = class {
21481
21095
  constructor() {
21482
21096
  const dir = getYukinoDir();
21483
21097
  this.filePath = join21(dir, "command_usage.json");
21484
- if (!existsSync16(dir)) {
21098
+ if (!existsSync15(dir)) {
21485
21099
  mkdirSync11(dir, { recursive: true });
21486
21100
  }
21487
21101
  this.load();
@@ -21523,7 +21137,7 @@ var CommandUsageTracker = class {
21523
21137
  }
21524
21138
  save() {
21525
21139
  try {
21526
- mkdirSync11(dirname9(this.filePath), { recursive: true });
21140
+ mkdirSync11(dirname8(this.filePath), { recursive: true });
21527
21141
  writeFileSync10(
21528
21142
  this.filePath,
21529
21143
  JSON.stringify(Object.fromEntries(this.usage), null, 2)
@@ -21550,7 +21164,7 @@ __export(history_exports, {
21550
21164
  load: () => load
21551
21165
  });
21552
21166
  import {
21553
- existsSync as existsSync17,
21167
+ existsSync as existsSync16,
21554
21168
  mkdirSync as mkdirSync12,
21555
21169
  readFileSync as readFileSync14,
21556
21170
  renameSync as renameSync6,
@@ -21564,7 +21178,7 @@ var FILENAME = "prompt_history.jsonl";
21564
21178
  var JSONLSchema = z22.looseObject({ text: z22.string() });
21565
21179
  function load() {
21566
21180
  const filePath = yukinoPath(FILENAME);
21567
- if (!existsSync17(filePath)) {
21181
+ if (!existsSync16(filePath)) {
21568
21182
  return [];
21569
21183
  }
21570
21184
  try {
@@ -22034,6 +21648,7 @@ __export(tools_exports3, {
22034
21648
  EditFile: () => edit_file_exports,
22035
21649
  EditFileDiagnostics: () => edit_file_diagnostics_exports,
22036
21650
  EnterWorktree: () => enter_worktree_exports,
21651
+ ExecutionCoordinator: () => execution_coordinator_exports,
22037
21652
  ExitCodeHints: () => exit_code_hints_exports,
22038
21653
  ExitPlanMode: () => exit_plan_mode_exports,
22039
21654
  ExitWorktree: () => exit_worktree_exports,
@@ -22077,6 +21692,7 @@ __export(update_exports, {
22077
21692
  VersionCheck: () => version_check_exports,
22078
21693
  handleUpdateCommand: () => handleUpdateCommand
22079
21694
  });
21695
+ import { parseArgs } from "util";
22080
21696
 
22081
21697
  // src/update/install.ts
22082
21698
  var install_exports = {};
@@ -22087,7 +21703,7 @@ __export(install_exports, {
22087
21703
  });
22088
21704
  import { execFile as execFile4, spawn as spawn6 } from "child_process";
22089
21705
  import { readFileSync as readFileSync16, realpathSync as realpathSync2 } from "fs";
22090
- import { dirname as dirname10, isAbsolute as isAbsolute6, join as join23, relative as relative5, sep as sep3 } from "path";
21706
+ import { dirname as dirname9, isAbsolute as isAbsolute6, join as join23, relative as relative5, sep as sep3 } from "path";
22091
21707
  import { fileURLToPath } from "url";
22092
21708
  import { z as z25 } from "zod";
22093
21709
 
@@ -22101,7 +21717,7 @@ __export(version_check_exports, {
22101
21717
  });
22102
21718
  import { z as z24 } from "zod";
22103
21719
  var PACKAGE_NAME = "@yukino.js/yukino";
22104
- var LATEST_VERSION_URL = "https://registry.npmjs.org/@yukino.js%2Fyukino/latest";
21720
+ var PACKAGE_URL = "https://registry.npmjs.org/@yukino.js%2Fyukino";
22105
21721
  var VERSION_PATTERN = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?(?:\+[\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*)?$/u;
22106
21722
  function parseVersion(value) {
22107
21723
  const match = VERSION_PATTERN.exec(value);
@@ -22143,18 +21759,27 @@ function isNewerVersion(candidate, current) {
22143
21759
  }
22144
21760
  return false;
22145
21761
  }
22146
- async function getLatestVersion(signal) {
21762
+ async function getLatestVersion({
21763
+ tag = "latest",
21764
+ signal
21765
+ } = {}) {
21766
+ if (!tag || encodeURIComponent(tag) !== tag || [".", ".."].includes(tag)) {
21767
+ throw new Error(`Invalid npm dist-tag: ${tag}`);
21768
+ }
22147
21769
  const timeout = AbortSignal.timeout(1e4);
22148
- const response = await fetch(LATEST_VERSION_URL, {
21770
+ const response = await fetch(`${PACKAGE_URL}/${encodeURIComponent(tag)}`, {
22149
21771
  headers: {
22150
21772
  accept: "application/json",
22151
21773
  "User-Agent": `yukino/${version} (${process.platform}; ${process.arch})`
22152
21774
  },
22153
21775
  signal: signal ? AbortSignal.any([signal, timeout]) : timeout
22154
21776
  });
21777
+ if (response.status === 404) {
21778
+ throw new Error(`No Yukino release found for npm dist-tag "${tag}".`);
21779
+ }
22155
21780
  if (!response.ok) {
22156
21781
  throw new Error(
22157
- `Could not check for Yukino updates: HTTP ${response.status}`
21782
+ `Could not check for Yukino updates (npm dist-tag "${tag}"): HTTP ${response.status}`
22158
21783
  );
22159
21784
  }
22160
21785
  const data = await response.json();
@@ -22167,7 +21792,7 @@ async function checkForUpdate(signal) {
22167
21792
  return void 0;
22168
21793
  }
22169
21794
  try {
22170
- const latest = await getLatestVersion(signal);
21795
+ const latest = await getLatestVersion({ signal });
22171
21796
  return isNewerVersion(latest, version) ? latest : void 0;
22172
21797
  } catch {
22173
21798
  return void 0;
@@ -22191,7 +21816,7 @@ function packageManagerInvocation(command, args, platform2 = process.platform) {
22191
21816
  };
22192
21817
  }
22193
21818
  function getPackageDirectory() {
22194
- let directory = dirname10(fileURLToPath(import.meta.url));
21819
+ let directory = dirname9(fileURLToPath(import.meta.url));
22195
21820
  while (true) {
22196
21821
  try {
22197
21822
  const data = JSON.parse(
@@ -22202,7 +21827,7 @@ function getPackageDirectory() {
22202
21827
  }
22203
21828
  } catch {
22204
21829
  }
22205
- const parent = dirname10(directory);
21830
+ const parent = dirname9(directory);
22206
21831
  if (parent === directory) {
22207
21832
  throw new Error("Could not locate the Yukino installation.");
22208
21833
  }
@@ -22246,11 +21871,11 @@ async function getSelfUpdateCommand(latest, packageDirectory = getPackageDirecto
22246
21871
  });
22247
21872
  } catch {
22248
21873
  }
22249
- const npmRoot = dirname10(dirname10(packageDirectory));
22250
- const inferredNpmPrefix = command === "npm" && normalized.endsWith(`/lib/node_modules/${PACKAGE_NAME}`) ? dirname10(dirname10(npmRoot)) : void 0;
21874
+ const npmRoot = dirname9(dirname9(packageDirectory));
21875
+ const inferredNpmPrefix = command === "npm" && normalized.endsWith(`/lib/node_modules/${PACKAGE_NAME}`) ? dirname9(dirname9(npmRoot)) : void 0;
22251
21876
  const roots = [globalRoot, ...inferredNpmPrefix ? [npmRoot] : []];
22252
21877
  if (command === "pnpm" && globalRoot) {
22253
- roots.push(dirname10(globalRoot));
21878
+ roots.push(dirname9(globalRoot));
22254
21879
  }
22255
21880
  if (!roots.some((root) => root && isInside(packageDirectory, root))) {
22256
21881
  throw new Error(
@@ -22289,6 +21914,26 @@ async function runSelfUpdate(update) {
22289
21914
  }
22290
21915
 
22291
21916
  // src/update/index.ts
21917
+ var UPDATE_USAGE = "Usage: yukino update [--tag <tag>]";
21918
+ function parseUpdateOptions(args) {
21919
+ try {
21920
+ return parseArgs({
21921
+ args,
21922
+ options: {
21923
+ tag: { type: "string" },
21924
+ help: { type: "boolean", short: "h" }
21925
+ },
21926
+ strict: true,
21927
+ allowPositionals: false
21928
+ }).values;
21929
+ } catch (error) {
21930
+ throw new Error(
21931
+ `${error instanceof Error ? error.message : String(error)}
21932
+ ${UPDATE_USAGE}`,
21933
+ { cause: error }
21934
+ );
21935
+ }
21936
+ }
22292
21937
  async function handleUpdateCommand(args) {
22293
21938
  if (args.length === 1 && ["--version", "-v"].includes(args[0])) {
22294
21939
  console.log(version);
@@ -22297,17 +21942,25 @@ async function handleUpdateCommand(args) {
22297
21942
  if (args[0] !== "update") {
22298
21943
  return false;
22299
21944
  }
22300
- if (args.length === 2 && ["--help", "-h"].includes(args[1])) {
22301
- console.log(
22302
- "Usage: yukino update\n\nUpdate Yukino to the latest npm release."
22303
- );
22304
- return true;
22305
- }
22306
21945
  try {
22307
- if (args.length !== 1) {
22308
- throw new Error("Usage: yukino update");
21946
+ const options = parseUpdateOptions(args.slice(1));
21947
+ if (options.help) {
21948
+ console.log(
21949
+ `${UPDATE_USAGE}
21950
+
21951
+ Update Yukino from an npm dist-tag.
21952
+
21953
+ Options:
21954
+ --tag <tag> npm dist-tag to check (default: latest)
21955
+ -h, --help Show this help
21956
+
21957
+ Examples:
21958
+ yukino update
21959
+ yukino update --tag=canary`
21960
+ );
21961
+ return true;
22309
21962
  }
22310
- const latest = await getLatestVersion();
21963
+ const latest = await getLatestVersion({ tag: options.tag });
22311
21964
  if (!isNewerVersion(latest, version)) {
22312
21965
  console.log(`Yukino is already up to date (v${version}).`);
22313
21966
  return true;
@@ -22709,12 +22362,13 @@ async function runPrintMode(args) {
22709
22362
  conv.addUserMessage(prompt);
22710
22363
  const checker = new PermissionChecker(cwd2, "bypassPermissions");
22711
22364
  const taskList = new TaskList();
22365
+ const teamManager = new TeamManager(cwd2);
22712
22366
  const registry = createToolRegistry(cwd2, taskList, {
22367
+ interactionMode: "non-interactive",
22368
+ teamManager,
22713
22369
  lspServers: cfg.lsp_servers
22714
22370
  });
22715
22371
  await configureBashSandbox(registry, cwd2, cfg.sandbox, checker);
22716
- const teamManager = new TeamManager(cwd2);
22717
- registerLeaderTaskTools(registry, teamManager, taskList);
22718
22372
  teamManager.setPermissionChecker(checker);
22719
22373
  const backgroundTaskManager = new TaskManager();
22720
22374
  attachBackgroundTaskManager(registry, backgroundTaskManager);
@@ -22757,6 +22411,7 @@ async function runPrintMode(args) {
22757
22411
  modelOverride,
22758
22412
  context2?.permissionChecker,
22759
22413
  {
22414
+ agentName: "fork",
22760
22415
  conversation,
22761
22416
  abortSignal: context2?.abortSignal,
22762
22417
  onPermissionRequest: context2?.onPermissionRequest
@@ -22781,7 +22436,13 @@ async function runPrintMode(args) {
22781
22436
  options?.modelOverride,
22782
22437
  teamChecker,
22783
22438
  // Teammates stay purely foreground: see SubagentRunOptions.backgroundTasks.
22784
- { abortSignal, backgroundTasks: false, conversation }
22439
+ {
22440
+ abortSignal,
22441
+ backgroundTasks: false,
22442
+ conversation,
22443
+ agentName: options?.agentName,
22444
+ onPermissionRequest: options?.onPermissionRequest
22445
+ }
22785
22446
  );
22786
22447
  }
22787
22448
  );
@@ -23096,429 +22757,6 @@ function recover() {
23096
22757
  recordExit(code);
23097
22758
  });
23098
22759
  }
23099
-
23100
- // src/teammate.ts
23101
- var teammate_exports = {};
23102
- __export(teammate_exports, {
23103
- buildTeammateRegistry: () => buildTeammateRegistry,
23104
- parseTeammateFlags: () => parseTeammateFlags,
23105
- runTeammate: () => runTeammate
23106
- });
23107
- import { basename as basename6, dirname as dirname11, join as join25 } from "path";
23108
- function parseTeammateFlags(args) {
23109
- if (!args.includes("--teammate")) {
23110
- return null;
23111
- }
23112
- let teamDir2 = "";
23113
- let teamCwd;
23114
- let teamName = "";
23115
- let memberName = "";
23116
- let initialTask = "";
23117
- let providerIndex;
23118
- let permissionMode;
23119
- let agentType;
23120
- let model;
23121
- for (let i = 0; i < args.length; i++) {
23122
- if (args[i] === "--team-dir" && args[i + 1]) {
23123
- teamDir2 = args[++i];
23124
- } else if (args[i] === "--team-cwd" && args[i + 1]) {
23125
- teamCwd = args[++i];
23126
- } else if (args[i] === "--agent-type" && args[i + 1]) {
23127
- agentType = args[++i];
23128
- } else if (args[i] === "--model" && args[i + 1]) {
23129
- model = args[++i];
23130
- } else if (args[i] === "--team-name" && args[i + 1]) {
23131
- teamName = args[++i];
23132
- } else if (args[i] === "--member-name" && args[i + 1]) {
23133
- memberName = args[++i];
23134
- } else if (args[i] === "--task" && args[i + 1]) {
23135
- initialTask = args[++i];
23136
- } else if (args[i] === "--provider-index" && args[i + 1]) {
23137
- providerIndex = Number(args[++i]);
23138
- } else if (args[i] === "--permission-mode") {
23139
- const mode2 = args[++i];
23140
- if (mode2 !== "default" && mode2 !== "acceptEdits" && mode2 !== "plan" && mode2 !== "bypassPermissions") {
23141
- throw new Error("Invalid teammate --permission-mode.");
23142
- }
23143
- permissionMode = mode2;
23144
- }
23145
- }
23146
- if (!permissionMode) {
23147
- throw new Error("Teammate --permission-mode is required.");
23148
- }
23149
- if (!teamName) {
23150
- const leaf = basename6(teamDir2);
23151
- teamName = leaf === "inboxes" ? basename6(dirname11(teamDir2)) : leaf;
23152
- }
23153
- return {
23154
- teamDir: teamDir2,
23155
- ...teamCwd ? { teamCwd } : {},
23156
- ...agentType ? { agentType } : {},
23157
- ...model ? { model } : {},
23158
- teamName,
23159
- memberName,
23160
- initialTask,
23161
- providerIndex,
23162
- permissionMode
23163
- };
23164
- }
23165
- var LEADER_LOST_EXIT_MS = 6e4;
23166
- var log34 = createChildLogger({ module: "teammate" });
23167
- function isPidAlive2(pid) {
23168
- try {
23169
- process.kill(pid, 0);
23170
- return true;
23171
- } catch (err) {
23172
- return err instanceof Error && "code" in err && err.code === "EPERM";
23173
- }
23174
- }
23175
- function createIdleNotification(memberName) {
23176
- return `[idle] ${memberName} has completed their task and is waiting for new instructions.`;
23177
- }
23178
- async function buildTeammateRegistry(opts) {
23179
- const mcpServers = opts.mcpServers ?? [];
23180
- const mgr = opts.mcpManager;
23181
- if (mcpServers.length > 0 && !mgr) {
23182
- throw new Error(
23183
- "A teammate host must own the MCP manager and disconnect it on exit"
23184
- );
23185
- }
23186
- const registry = createToolRegistry(opts.cwd, new TaskList(), {
23187
- lspServers: opts.lspServers
23188
- });
23189
- await configureBashSandbox(registry, opts.cwd, opts.sandboxConfig);
23190
- registry.register(new SyntheticOutputTool());
23191
- registry.register(new LoadSkillTool(opts.catalog, opts.skillHost));
23192
- registry.register(new InstallSkillTool(opts.cwd, opts.catalog));
23193
- const teamManager = new TeamManager(opts.teamCwd ?? opts.cwd, {
23194
- // This process is a teammate, not the leader: leave the recorded
23195
- // leaderPid in config.json alone so other teammates (and this one) can
23196
- // keep using it for liveness checks.
23197
- claimLeadership: false
23198
- });
23199
- teamManager.get(opts.teamName);
23200
- registry.register(new SendMessageTool(teamManager, opts.memberName));
23201
- registry.register(
23202
- new TeamTaskCreateTool(teamManager, opts.teamName, opts.memberName)
23203
- );
23204
- registry.register(new TeamTaskGetTool(teamManager, opts.teamName));
23205
- registry.register(new TeamTaskListTool(teamManager, opts.teamName));
23206
- registry.register(
23207
- new TeamTaskUpdateTool(teamManager, opts.teamName, opts.memberName)
23208
- );
23209
- if (mcpServers.length > 0 && mgr) {
23210
- try {
23211
- const result = await mgr.connectAll(mcpServers);
23212
- for (const { serverName, tool } of result.tools) {
23213
- const client = mgr.getClient(serverName);
23214
- if (client) {
23215
- registry.register(new MCPToolWrapper(client, serverName, tool));
23216
- }
23217
- }
23218
- for (const { serverName, error } of result.errors) {
23219
- log34.error({ serverName, error }, "MCP connection error");
23220
- }
23221
- if (result.tools.length > 0 && opts.contextWindow) {
23222
- decideAndApply(
23223
- registry,
23224
- opts.baseUrl ?? "",
23225
- opts.protocol ?? "anthropic",
23226
- opts.contextWindow
23227
- );
23228
- }
23229
- } catch (err) {
23230
- log34.error({ err }, "MCP setup failed");
23231
- }
23232
- }
23233
- const filtered = filterToolsForAgent(
23234
- registry,
23235
- opts.definition?.tools,
23236
- opts.definition?.disallowedTools,
23237
- false
23238
- );
23239
- for (const name of [
23240
- "SendMessage",
23241
- "TaskCreate",
23242
- "TaskGet",
23243
- "TaskList",
23244
- "TaskUpdate"
23245
- ]) {
23246
- const tool = registry.get(name);
23247
- if (tool) {
23248
- filtered.register(tool);
23249
- }
23250
- }
23251
- filtered.takeOwnershipFrom(registry);
23252
- await registry.dispose();
23253
- return filtered;
23254
- }
23255
- async function runTeammate(args) {
23256
- const safeMemberName = sanitizeNameSegment(args.memberName);
23257
- initLogger({
23258
- sessionId: `teammate-${safeMemberName}-${Date.now().toString(36)}`,
23259
- mode: "teammate",
23260
- logDir: join25(dirname11(args.teamDir), "logs"),
23261
- skipCleanup: true
23262
- });
23263
- process.on("exit", closeLogger);
23264
- let mcpManager;
23265
- let registry;
23266
- let controlTimer;
23267
- let shutdownReply;
23268
- let failureReported = false;
23269
- let failure;
23270
- const configPath = join25(dirname11(args.teamDir), "config.json");
23271
- let hadTeamConfig = readTeamFileAtPath(configPath) !== null;
23272
- const controller = new AbortController();
23273
- const abort = () => {
23274
- controller.abort();
23275
- };
23276
- process.on("SIGINT", abort);
23277
- process.on("SIGTERM", abort);
23278
- process.on("SIGHUP", abort);
23279
- try {
23280
- registerTeammateProcess(
23281
- join25(dirname11(args.teamDir), "config.json"),
23282
- args.memberName,
23283
- process.pid
23284
- );
23285
- const cwd2 = process.cwd();
23286
- const cfg = withProjectMcpServers(loadConfig(), cwd2);
23287
- const configuredProvider = args.providerIndex === void 0 ? resolveDefaultProvider(cfg.providers, cfg.default_provider) : cfg.providers[args.providerIndex];
23288
- if (!configuredProvider) {
23289
- throw new Error(
23290
- `Provider at index ${args.providerIndex} is not configured.`
23291
- );
23292
- }
23293
- const definition = loadAgentDefinitions().find(
23294
- (entry) => entry.name === (args.agentType ?? "general-purpose")
23295
- );
23296
- if (!definition) {
23297
- throw new Error(`Unknown teammate agent type '${args.agentType}'.`);
23298
- }
23299
- const provider = {
23300
- ...configuredProvider,
23301
- model: args.model ?? definition.model ?? configuredProvider.model
23302
- };
23303
- const conversation = new ConversationManager();
23304
- conversation.addSystemReminder(buildSubagentInstructions(definition));
23305
- const catalog = new SkillCatalog();
23306
- catalog.load(cwd2);
23307
- const skillHost = {
23308
- activateSkill: (name, body) => {
23309
- conversation.addSystemReminder(
23310
- `<skill-name>${name}</skill-name>
23311
- ${body}`
23312
- );
23313
- }
23314
- };
23315
- const env = detectEnvironment(cwd2);
23316
- env.model = provider.model;
23317
- const systemPrompt = definition.systemPromptOverride ?? buildSystemPrompt(env);
23318
- const client = await createClient(provider, systemPrompt);
23319
- if (cfg.mcp_servers?.length) {
23320
- mcpManager = new MCPManager();
23321
- }
23322
- registry = await buildTeammateRegistry({
23323
- cwd: cwd2,
23324
- teamCwd: args.teamCwd,
23325
- definition,
23326
- teamName: args.teamName,
23327
- memberName: args.memberName,
23328
- catalog,
23329
- skillHost,
23330
- mcpServers: cfg.mcp_servers,
23331
- lspServers: cfg.lsp_servers,
23332
- sandboxConfig: cfg.sandbox,
23333
- mcpManager,
23334
- baseUrl: provider.base_url,
23335
- protocol: provider.protocol,
23336
- contextWindow: getContextWindow(provider)
23337
- });
23338
- const checker = new PermissionChecker(
23339
- cwd2,
23340
- args.permissionMode,
23341
- () => readTeamFileAtPath(join25(dirname11(args.teamDir), "config.json"))?.permissionMode ?? args.permissionMode
23342
- );
23343
- checker.teammate = true;
23344
- checker.sandboxEnabled = cfg.sandbox?.enabled ?? false;
23345
- checker.sandboxAutoAllow = cfg.sandbox?.auto_allow ?? false;
23346
- checker.planModeLocked = definition.permissionMode === "plan";
23347
- const agent2 = new Agent({
23348
- client,
23349
- registry,
23350
- checker,
23351
- conversation,
23352
- cwd: cwd2,
23353
- fileStateCache: new FileStateCache(),
23354
- skillSection: buildSkillSection(catalog),
23355
- instructions: loadInstructions(cwd2),
23356
- contextWindow: getContextWindow(provider),
23357
- maxOutput: getMaxOutputTokens(provider),
23358
- maxIterations: definition.maxTurns ?? 200,
23359
- abortSignal: controller.signal
23360
- });
23361
- conversation.addUserMessage(
23362
- buildTeammatePrompt(args.teamName, args.memberName, args.initialTask)
23363
- );
23364
- const mailbox = new FileMailbox(args.teamDir, args.memberName);
23365
- const leaderMailbox = new FileMailbox(args.teamDir, LEADER_NAME);
23366
- let leaderDeadSince = 0;
23367
- controlTimer = setInterval(() => {
23368
- try {
23369
- const shutdown2 = mailbox.receiveMatchingSync(isShutdownRequest)[0];
23370
- if (shutdown2) {
23371
- const response = shutdownResponse(
23372
- args.memberName,
23373
- shutdown2.requestId ?? "",
23374
- true,
23375
- "acknowledged, shutting down"
23376
- );
23377
- shutdownReply = leaderMailbox.send(
23378
- args.memberName,
23379
- response.text,
23380
- response
23381
- );
23382
- controller.abort();
23383
- return;
23384
- }
23385
- const config = readTeamFileAtPath(configPath);
23386
- if (config) {
23387
- hadTeamConfig = true;
23388
- }
23389
- const lost = hadTeamConfig && !config || config?.leaderPid && !isPidAlive2(config.leaderPid);
23390
- if (lost) {
23391
- if (!leaderDeadSince) {
23392
- leaderDeadSince = Date.now();
23393
- }
23394
- if (!config || Date.now() - leaderDeadSince > LEADER_LOST_EXIT_MS) {
23395
- controller.abort();
23396
- }
23397
- } else {
23398
- leaderDeadSince = 0;
23399
- }
23400
- } catch (err) {
23401
- log34.error({ err }, "teammate control poll failed");
23402
- }
23403
- }, 2e3);
23404
- const notifyIdle = () => leaderMailbox.send(
23405
- args.memberName,
23406
- createIdleNotification(args.memberName)
23407
- );
23408
- const notifyFailed = (err) => {
23409
- failureReported = true;
23410
- failure = err;
23411
- return Promise.resolve();
23412
- };
23413
- for await (const event of agent2.run()) {
23414
- switch (event.type) {
23415
- case "stream_text":
23416
- process.stdout.write(event.text);
23417
- break;
23418
- case "tool_result":
23419
- console.log(
23420
- `[${event.toolName}] ${event.isError ? "ERROR" : "OK"} (${event.elapsed.toFixed(1)}s)`
23421
- );
23422
- break;
23423
- case "loop_complete":
23424
- console.log("--- Task complete ---");
23425
- break;
23426
- case "error":
23427
- log34.error({ err: event.error }, "agent error");
23428
- await notifyFailed(event.error);
23429
- throw event.error;
23430
- }
23431
- }
23432
- if (controller.signal.aborted) {
23433
- return;
23434
- }
23435
- await notifyIdle();
23436
- polling: while (!controller.signal.aborted) {
23437
- const batch = await mailbox.receive();
23438
- for (const [i, msg] of batch.entries()) {
23439
- if (isShutdownRequest(msg)) {
23440
- mailbox.requeue(batch.slice(i + 1));
23441
- const response = shutdownResponse(
23442
- args.memberName,
23443
- msg.requestId ?? "",
23444
- true,
23445
- "acknowledged, shutting down"
23446
- );
23447
- await leaderMailbox.send(args.memberName, response.text, response);
23448
- console.log(`Shutdown requested, ${args.memberName} exiting.`);
23449
- break polling;
23450
- }
23451
- console.log(`Message from ${msg.from}: ${msg.text}`);
23452
- conversation.addUserMessage(`From ${msg.from}: ${msg.text}`);
23453
- for await (const event of agent2.run()) {
23454
- if (event.type === "stream_text") {
23455
- process.stdout.write(event.text);
23456
- } else if (event.type === "error") {
23457
- log34.error({ err: event.error }, "agent error");
23458
- await notifyFailed(event.error);
23459
- throw event.error;
23460
- }
23461
- }
23462
- if (controller.signal.aborted) {
23463
- mailbox.requeue(batch.slice(i + 1));
23464
- break polling;
23465
- }
23466
- const moreMessages = batch.length > i + 1;
23467
- if (!moreMessages && mailbox.unreadCount() === 0) {
23468
- await notifyIdle();
23469
- }
23470
- }
23471
- await new Promise((r) => setTimeout(r, 2e3));
23472
- }
23473
- } catch (error) {
23474
- failureReported = true;
23475
- failure = error;
23476
- throw error;
23477
- } finally {
23478
- clearInterval(controlTimer);
23479
- controller.abort();
23480
- const results = await Promise.allSettled([
23481
- shutdownReply,
23482
- registry?.dispose(),
23483
- mcpManager?.disconnectAll()
23484
- ]);
23485
- for (const result of results) {
23486
- if (result.status === "rejected") {
23487
- log34.error({ err: result.reason }, "teammate resource cleanup failed");
23488
- }
23489
- }
23490
- try {
23491
- const configExists = readTeamFileAtPath(configPath) !== null;
23492
- if (configExists || !hadTeamConfig) {
23493
- let releaseSummary = "";
23494
- if (configExists) {
23495
- try {
23496
- const released = new SharedTaskStore(
23497
- join25(dirname11(args.teamDir), "tasks.json")
23498
- ).releaseOwner(args.memberName);
23499
- if (released.length) {
23500
- releaseSummary = `; unassigned tasks: ${released.map((task) => `#${task.id}`).join(", ")}`;
23501
- }
23502
- } catch (error) {
23503
- log34.error({ error }, "teammate task release failed");
23504
- releaseSummary = "; task release failed: inspect the shared board before reassignment";
23505
- }
23506
- }
23507
- await new FileMailbox(args.teamDir, LEADER_NAME).send(
23508
- args.memberName,
23509
- `${failureReported ? `[idle] ${args.memberName} failed: ${failure instanceof Error ? failure.message : String(failure)}` : `[idle] ${args.memberName} (reason: stopped)`}${releaseSummary}`
23510
- );
23511
- }
23512
- } catch (error) {
23513
- log34.error({ error }, "teammate exit notification failed");
23514
- }
23515
- process.off("SIGINT", abort);
23516
- process.off("SIGTERM", abort);
23517
- process.off("SIGHUP", abort);
23518
- process.off("exit", closeLogger);
23519
- closeLogger();
23520
- }
23521
- }
23522
22760
  export {
23523
22761
  a2a_exports as A2a,
23524
22762
  acp_exports as Acp,
@@ -23549,7 +22787,6 @@ export {
23549
22787
  session_exports as Session,
23550
22788
  skills_exports as Skills,
23551
22789
  subagent_exports as Subagent,
23552
- teammate_exports as Teammate,
23553
22790
  teams_exports as Teams,
23554
22791
  telemetry_exports as Telemetry,
23555
22792
  todo_exports as Todo,