@yukino.js/yukino 0.0.13 → 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 (38) hide show
  1. package/README.md +12 -10
  2. package/dist/{a2a-DKWMWGID.js → a2a-D7KSHNUT.js} +4 -3
  3. package/dist/{acp-RL6DKS3R.js → acp-W4R5P6CZ.js} +7 -7
  4. package/dist/{anthropic-74ALYMH2.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-A5G5NTDB.js → chunk-D2SZ6GQJ.js} +184 -186
  9. package/dist/{chunk-APJAUOF6.js → chunk-GVRZBATW.js} +1 -1
  10. package/dist/{chunk-CJSMVCUF.js → chunk-I356BFD2.js} +1 -1
  11. package/dist/chunk-JDK4YHNF.js +63 -0
  12. package/dist/{chunk-NEU4ER5V.js → chunk-T6WQ3Z5J.js} +1 -1
  13. package/dist/{chunk-6JUOKMSJ.js → chunk-UUWXDH7J.js} +1 -1
  14. package/dist/{chunk-6FSIG63T.js → chunk-WKSVBXUO.js} +10 -9
  15. package/dist/{chunk-556TRLPT.js → chunk-Z3EFT645.js} +1 -1
  16. package/dist/lib/{anthropic-EQRUGP2C.js → anthropic-TDNNKQMT.js} +4 -4
  17. package/dist/lib/{chunk-EGT7BJRD.js → chunk-56DL5ZYL.js} +2 -2
  18. package/dist/lib/{chunk-WWCSFKMR.js → chunk-BRLCCEU7.js} +1 -1
  19. package/dist/lib/{chunk-JYCSWXCR.js → chunk-EJNKEFE7.js} +2 -2
  20. package/dist/lib/{chunk-CDMR25FD.js → chunk-IZXMDC5O.js} +3 -3
  21. package/dist/lib/{chunk-UBVKYJFI.js → chunk-UKXGO7AW.js} +143 -300
  22. package/dist/lib/{chunk-HUTUNNDX.js → chunk-WNGF7243.js} +0 -1
  23. package/dist/lib/{chunk-FUJDUZTH.js → chunk-WXR5HNB4.js} +1 -1
  24. package/dist/lib/index.d.ts +70 -275
  25. package/dist/lib/index.js +385 -1243
  26. package/dist/lib/{openai-B3I5WBFT.js → openai-6VYIA7CT.js} +3 -3
  27. package/dist/lib/{providers-EJ4VBHNP.js → providers-UXL5FVF7.js} +2 -2
  28. package/dist/lib/{tool-filter-TURPCYFR.js → tool-filter-O6YLSFAS.js} +3 -3
  29. package/dist/{main-JEEKFCGX.js → main-FOIMPIOD.js} +220 -221
  30. package/dist/main.js +2 -2
  31. package/dist/{providers-U23PWAHG.js → providers-TH6MQC7V.js} +1 -1
  32. package/dist/{server-EOSEQPNY.js → server-TC5GDF6E.js} +1 -1
  33. package/dist/tool-filter-SYH5ZFC2.js +4 -0
  34. package/package.json +6 -6
  35. package/dist/chunk-SCR7NDDL.js +0 -63
  36. package/dist/fe/dist/index.html +0 -21
  37. package/dist/fe/dist/static/index.css +0 -2
  38. package/dist/tool-filter-UDSHRE5F.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-JYCSWXCR.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-CDMR25FD.js";
17
+ } from "./chunk-IZXMDC5O.js";
18
18
  import {
19
19
  openai_exports
20
- } from "./chunk-EGT7BJRD.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-WWCSFKMR.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-UBVKYJFI.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-FUJDUZTH.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-HUTUNNDX.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(log36) {
499
- this.log = log36;
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-EJ4VBHNP.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
@@ -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
  }
@@ -3908,7 +3903,7 @@ function buildToolGuidance(toolNames) {
3908
3903
  );
3909
3904
  if (has("SendMessage")) {
3910
3905
  rules.push(
3911
- `${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.`
3912
3907
  );
3913
3908
  }
3914
3909
  }
@@ -4117,6 +4112,7 @@ var Agent = class {
4117
4112
  onLoopComplete;
4118
4113
  compactTracking = new AutoCompactTrackingState();
4119
4114
  onPermissionRequest;
4115
+ agentName;
4120
4116
  toolFilter;
4121
4117
  coordinatorActiveFn;
4122
4118
  activeSkills;
@@ -4131,6 +4127,7 @@ var Agent = class {
4131
4127
  memoryRecallValue;
4132
4128
  onMemoriesSurfaced;
4133
4129
  constructor(config) {
4130
+ this.agentName = config.agentName ?? "main";
4134
4131
  this.client = config.client;
4135
4132
  this.registry = config.registry;
4136
4133
  this.checker = config.checker;
@@ -4322,7 +4319,7 @@ No tools are currently callable. Return findings or blockers without issuing too
4322
4319
  );
4323
4320
  }
4324
4321
  if (this.checker.mode === "plan") {
4325
- 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);
4326
4323
  this.checker.planFilePath = planPath;
4327
4324
  this.conversation.addSystemReminder(
4328
4325
  buildPlanModeReminder(planPath, existsSync4(planPath), iteration, {
@@ -5036,7 +5033,8 @@ ${this.goalManager.format()}
5036
5033
  tu.arguments,
5037
5034
  decision,
5038
5035
  tu.toolUseId,
5039
- this.abortSignal
5036
+ this.abortSignal,
5037
+ { agentName: this.agentName, cwd: this.cwd }
5040
5038
  );
5041
5039
  if (response === "allowAlways" && !this.abortSignal?.aborted) {
5042
5040
  for (const [index, call] of permissionCalls.entries()) {
@@ -5266,18 +5264,122 @@ var WEB_FETCH_DESCRIPTION = `Fetch a URL over HTTP(S) and return its content as
5266
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.
5267
5265
  - Responses over 10MB are rejected and results are truncated at 100K characters. Successful fetches are cached for 15 minutes.`;
5268
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
+
5269
5371
  // src/tools/shell-background.ts
5270
5372
  var shell_background_exports = {};
5271
5373
  __export(shell_background_exports, {
5272
5374
  BACKGROUNDABLE_TOOL_NAMES: () => BACKGROUNDABLE_TOOL_NAMES,
5273
- BACKGROUND_MAX_OUTPUT_BYTES: () => BACKGROUND_MAX_OUTPUT_BYTES,
5274
5375
  BACKGROUND_NOTIFICATION_BYTES: () => BACKGROUND_NOTIFICATION_BYTES,
5376
+ MAX_SHELL_OUTPUT_FILE_BYTES: () => MAX_SHELL_OUTPUT_FILE_BYTES,
5275
5377
  SIZE_WATCHDOG_INTERVAL_MS: () => SIZE_WATCHDOG_INTERVAL_MS,
5276
5378
  attachBackgroundTaskManager: () => attachBackgroundTaskManager,
5277
5379
  backgroundAllForegroundTasks: () => backgroundAllForegroundTasks,
5278
5380
  backgroundMessage: () => backgroundMessage,
5279
5381
  backgroundTaskName: () => backgroundTaskName,
5280
- buildBackgroundBody: () => buildBackgroundBody,
5382
+ buildShellResult: () => buildShellResult,
5281
5383
  createShellOutputFile: () => createShellOutputFile,
5282
5384
  discardFd: () => discardFd,
5283
5385
  formatFinalResult: () => formatFinalResult,
@@ -5329,27 +5431,6 @@ var EXIT_CODE_HINTS = /* @__PURE__ */ new Map([
5329
5431
  [2, "error while searching"]
5330
5432
  ])
5331
5433
  ],
5332
- [
5333
- "egrep",
5334
- /* @__PURE__ */ new Map([
5335
- [1, "no matches found"],
5336
- [2, "error while searching"]
5337
- ])
5338
- ],
5339
- [
5340
- "fgrep",
5341
- /* @__PURE__ */ new Map([
5342
- [1, "no matches found"],
5343
- [2, "error while searching"]
5344
- ])
5345
- ],
5346
- [
5347
- "zgrep",
5348
- /* @__PURE__ */ new Map([
5349
- [1, "no matches found"],
5350
- [2, "error while searching"]
5351
- ])
5352
- ],
5353
5434
  [
5354
5435
  "rg",
5355
5436
  /* @__PURE__ */ new Map([
@@ -5357,8 +5438,6 @@ var EXIT_CODE_HINTS = /* @__PURE__ */ new Map([
5357
5438
  [2, "error while searching"]
5358
5439
  ])
5359
5440
  ],
5360
- ["ack", /* @__PURE__ */ new Map([[1, "no matches found"]])],
5361
- ["ag", /* @__PURE__ */ new Map([[1, "no matches found"]])],
5362
5441
  [
5363
5442
  "findstr",
5364
5443
  /* @__PURE__ */ new Map([
@@ -5366,7 +5445,6 @@ var EXIT_CODE_HINTS = /* @__PURE__ */ new Map([
5366
5445
  [2, "error while searching"]
5367
5446
  ])
5368
5447
  ],
5369
- ["where", /* @__PURE__ */ new Map([[1, "not found"]])],
5370
5448
  // Comparison / condition tools: non-zero exit is informational
5371
5449
  [
5372
5450
  "diff",
@@ -5375,20 +5453,6 @@ var EXIT_CODE_HINTS = /* @__PURE__ */ new Map([
5375
5453
  [2, "trouble reading files"]
5376
5454
  ])
5377
5455
  ],
5378
- [
5379
- "diff3",
5380
- /* @__PURE__ */ new Map([
5381
- [1, "files differ"],
5382
- [2, "trouble reading files"]
5383
- ])
5384
- ],
5385
- [
5386
- "sdiff",
5387
- /* @__PURE__ */ new Map([
5388
- [1, "files differ"],
5389
- [2, "trouble reading files"]
5390
- ])
5391
- ],
5392
5456
  [
5393
5457
  "cmp",
5394
5458
  /* @__PURE__ */ new Map([
@@ -5421,99 +5485,6 @@ var EXIT_CODE_HINTS = /* @__PURE__ */ new Map([
5421
5485
  "find",
5422
5486
  /* @__PURE__ */ new Map([[1, "partial success \u2014 some inputs could not be processed"]])
5423
5487
  ],
5424
- // Process / batch helpers
5425
- [
5426
- "xargs",
5427
- /* @__PURE__ */ new Map([
5428
- [123, "some sub-command invocations exited with 1-125"],
5429
- [124, "a sub-command exited with 255"]
5430
- ])
5431
- ],
5432
- ["timeout", /* @__PURE__ */ new Map([[124, "command timed out"]])],
5433
- // File / build tools
5434
- [
5435
- "ls",
5436
- /* @__PURE__ */ new Map([
5437
- [1, "minor problem (e.g. unreadable subdirectory)"],
5438
- [2, "serious problem (e.g. inaccessible path)"]
5439
- ])
5440
- ],
5441
- [
5442
- "tar",
5443
- /* @__PURE__ */ new Map([
5444
- [1, "some files changed or differed while archiving"],
5445
- [2, "fatal error"]
5446
- ])
5447
- ],
5448
- [
5449
- "make",
5450
- /* @__PURE__ */ new Map([
5451
- [1, "targets not up to date (with -q)"],
5452
- [2, "build failed"]
5453
- ])
5454
- ],
5455
- ["gcc", /* @__PURE__ */ new Map([[1, "compilation failed"]])],
5456
- ["clang", /* @__PURE__ */ new Map([[1, "compilation failed"]])],
5457
- ["tsc", /* @__PURE__ */ new Map([[1, "type errors found"]])],
5458
- [
5459
- "eslint",
5460
- /* @__PURE__ */ new Map([
5461
- [1, "lint errors found"],
5462
- [2, "fatal lint problem (bad config or rule crash)"]
5463
- ])
5464
- ],
5465
- // Test runners
5466
- ["jest", /* @__PURE__ */ new Map([[1, "tests failed"]])],
5467
- ["vitest", /* @__PURE__ */ new Map([[1, "tests failed"]])],
5468
- ["go", /* @__PURE__ */ new Map([[1, "build/test/vet reported problems"]])],
5469
- // Interpreters
5470
- ["node", /* @__PURE__ */ new Map([[1, "uncaught exception"]])],
5471
- ["python", /* @__PURE__ */ new Map([[1, "unhandled exception"]])],
5472
- ["python3", /* @__PURE__ */ new Map([[1, "unhandled exception"]])],
5473
- // Network / remote tools
5474
- [
5475
- "git",
5476
- /* @__PURE__ */ new Map([[128, "fatal error (e.g. invalid ref or not a git repository)"]])
5477
- ],
5478
- ["ssh", /* @__PURE__ */ new Map([[255, "ssh error"]])],
5479
- [
5480
- "wget",
5481
- /* @__PURE__ */ new Map([
5482
- [1, "generic error"],
5483
- [4, "network failure"],
5484
- [5, "SSL verification failed"],
5485
- [6, "authentication failure"],
5486
- [7, "protocol error"],
5487
- [8, "server issued an error response"]
5488
- ])
5489
- ],
5490
- [
5491
- "curl",
5492
- /* @__PURE__ */ new Map([
5493
- [6, "couldn't resolve host"],
5494
- [7, "failed to connect to host"],
5495
- [22, "HTTP error >= 400 (with -f)"],
5496
- [28, "operation timed out"]
5497
- ])
5498
- ],
5499
- // jq is a local JSON processor, not a network tool
5500
- [
5501
- "jq",
5502
- /* @__PURE__ */ new Map([
5503
- [2, "usage or system error"],
5504
- [3, "jq program failed to compile"],
5505
- [4, "no valid result was produced (with -e)"],
5506
- [5, "halt_error was called without a custom exit code"]
5507
- ])
5508
- ],
5509
- ["ping", /* @__PURE__ */ new Map([[1, "no response received"]])],
5510
- [
5511
- "rsync",
5512
- /* @__PURE__ */ new Map([
5513
- [23, "partial transfer due to error"],
5514
- [24, "source files vanished before transfer"]
5515
- ])
5516
- ],
5517
5488
  // Windows
5518
5489
  [
5519
5490
  "robocopy",
@@ -5676,8 +5647,8 @@ var TaskOutputTool = class {
5676
5647
 
5677
5648
  // src/tools/shell-background.ts
5678
5649
  var BACKGROUND_NOTIFICATION_BYTES = 3e4;
5679
- var BACKGROUND_PREVIEW_BYTES = TOOL_RESULT_PREVIEW_CHARS;
5680
- 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;
5681
5652
  var SIZE_WATCHDOG_INTERVAL_MS = 500;
5682
5653
  function backgroundTaskName(command) {
5683
5654
  const flat = command.replace(/\s+/g, " ").trim();
@@ -5800,31 +5771,37 @@ ${error}` : error,
5800
5771
  }
5801
5772
  const exitCode = exit.code ?? 0;
5802
5773
  let output = formatShellOutput(prompt, command, merged, "", truncated);
5803
- if (!truncated) {
5804
- if (exitCode !== 0) {
5805
- const hint = exitCodeHint(command, exitCode);
5806
- output += hint ? `
5774
+ if (exitCode !== 0) {
5775
+ const hint = exitCodeHint(command, exitCode);
5776
+ output += hint ? `
5807
5777
  Exit code ${String(exitCode)} (${hint})` : `
5808
5778
  Exit code ${String(exitCode)}`;
5809
- }
5810
- if (exit.code === null) {
5811
- output += `
5779
+ }
5780
+ if (exit.code === null) {
5781
+ output += `
5812
5782
  Process terminated${exit.signal ? ` by ${exit.signal}` : " unexpectedly"}`;
5813
- }
5814
5783
  }
5815
- 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
+ };
5816
5791
  }
5817
- function buildBackgroundBody(prompt, command, exit, outputPath, timeout, annotate) {
5792
+ function buildShellResult(prompt, command, exit, outputPath, timeout, inlineLimit = MAX_SHELL_OUTPUT_BYTES, annotate) {
5818
5793
  let size = 0;
5819
5794
  try {
5820
5795
  size = statSync4(outputPath).size;
5821
5796
  } catch {
5822
5797
  }
5823
- let result;
5824
- if (size <= BACKGROUND_NOTIFICATION_BYTES) {
5825
- 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) {
5826
5803
  const merged = annotate ? annotate(read.text) : read.text;
5827
- result = formatFinalResult(
5804
+ const result = formatFinalResult(
5828
5805
  prompt,
5829
5806
  command,
5830
5807
  exit,
@@ -5833,28 +5810,19 @@ function buildBackgroundBody(prompt, command, exit, outputPath, timeout, annotat
5833
5810
  timeout
5834
5811
  );
5835
5812
  unlinkQuiet(outputPath);
5836
- } else {
5837
- const header = formatFinalResult(prompt, command, exit, "", false, timeout);
5838
- const rawPreview = readOutputFile(
5839
- outputPath,
5840
- BACKGROUND_PREVIEW_BYTES
5841
- ).text;
5842
- const annotatedPreview = annotate ? annotate(rawPreview) : rawPreview;
5843
- const preview2 = sliceUtf8Safe(
5844
- Buffer.from(annotatedPreview, "utf-8"),
5845
- BACKGROUND_PREVIEW_BYTES
5846
- ).toString("utf-8");
5847
- result = {
5848
- output: `${header.output}
5849
- ${buildPersistedOutputPreview(size, preview2, outputPath, "bytes")}`,
5850
- isError: header.isError
5851
- };
5852
- }
5853
- if (exit.sizeKilled) {
5854
- result.output += "\nBackground command killed: output file exceeded 5GB";
5855
- result.isError = true;
5813
+ return result;
5856
5814
  }
5857
- 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
+ };
5858
5826
  }
5859
5827
  var BackgroundableToolShape = z6.object({
5860
5828
  taskManager: z6.instanceof(TaskManager).nullable(),
@@ -6006,7 +5974,16 @@ ${BASH_BACKGROUND_DESCRIPTION}`;
6006
5974
  }
6007
5975
  };
6008
5976
  }
6009
- 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) {
6010
5987
  const command = strArg(args, "command");
6011
5988
  if (!command) {
6012
5989
  return {
@@ -6106,6 +6083,7 @@ ${BASH_BACKGROUND_DESCRIPTION}`;
6106
6083
  outputFile,
6107
6084
  manager
6108
6085
  );
6086
+ started(handle.done);
6109
6087
  if (runInBackground) {
6110
6088
  const taskId = handle.background("explicit");
6111
6089
  if (taskId !== null) {
@@ -6125,6 +6103,10 @@ ${BASH_BACKGROUND_DESCRIPTION}`;
6125
6103
  * trigger that transitions the running command into a TaskManager task.
6126
6104
  */
6127
6105
  startCommand(ctx, prepared, command, timeout, outputFile, manager) {
6106
+ let finishProcess = () => void 0;
6107
+ const processDone = new Promise((resolve11) => {
6108
+ finishProcess = resolve11;
6109
+ });
6128
6110
  let backgroundFn;
6129
6111
  const result = new Promise((resolve11) => {
6130
6112
  let aborted = false;
@@ -6146,6 +6128,7 @@ ${BASH_BACKGROUND_DESCRIPTION}`;
6146
6128
  stdio: ["ignore", outputFile.fd, outputFile.fd]
6147
6129
  });
6148
6130
  } catch (error) {
6131
+ finishProcess();
6149
6132
  discardFd(outputFile.fd);
6150
6133
  unlinkQuiet(outputFile.path);
6151
6134
  resolve11({
@@ -6199,9 +6182,8 @@ ${BASH_BACKGROUND_DESCRIPTION}`;
6199
6182
  log9.error({ error }, "shell output observer failed");
6200
6183
  }
6201
6184
  }
6202
- const cap = backgrounded ? BACKGROUND_MAX_OUTPUT_BYTES : MAX_SHELL_OUTPUT_BYTES;
6203
- if (size > cap) {
6204
- sizeKilled = backgrounded;
6185
+ if (size > MAX_SHELL_OUTPUT_FILE_BYTES) {
6186
+ sizeKilled = true;
6205
6187
  clearInterval(watchdog);
6206
6188
  terminate();
6207
6189
  }
@@ -6261,17 +6243,15 @@ Error cleaning up sandbox: ${asErrorString(error)}`,
6261
6243
  if (backgrounded) {
6262
6244
  return;
6263
6245
  }
6264
- const read = readOutputFile(outputFile.path, MAX_SHELL_OUTPUT_BYTES);
6265
- const merged = prepared.annotateStderr?.(read.text) ?? read.text;
6266
- const finalResult = formatFinalResult(
6246
+ const finalResult = buildShellResult(
6267
6247
  "$ ",
6268
6248
  command,
6269
6249
  exit,
6270
- merged,
6271
- read.truncated,
6272
- timeout
6250
+ outputFile.path,
6251
+ timeout,
6252
+ MAX_SHELL_OUTPUT_BYTES,
6253
+ prepared.annotateStderr ? (text) => prepared.annotateStderr?.(text) ?? text : void 0
6273
6254
  );
6274
- unlinkQuiet(outputFile.path);
6275
6255
  settle(finalResult);
6276
6256
  };
6277
6257
  const backgroundExecution = (reason) => {
@@ -6292,12 +6272,13 @@ Error cleaning up sandbox: ${asErrorString(error)}`,
6292
6272
  } catch {
6293
6273
  }
6294
6274
  const annotate = prepared.annotateStderr ? (text) => prepared.annotateStderr?.(text) ?? text : void 0;
6295
- const body = buildBackgroundBody(
6275
+ const body = buildShellResult(
6296
6276
  "$ ",
6297
6277
  command,
6298
6278
  exit,
6299
6279
  outputFile.path,
6300
6280
  timeout,
6281
+ BACKGROUND_NOTIFICATION_BYTES,
6301
6282
  annotate
6302
6283
  );
6303
6284
  if (body.isError) {
@@ -6332,6 +6313,7 @@ Error cleaning up sandbox: ${asErrorString(error)}`,
6332
6313
  }
6333
6314
  };
6334
6315
  child.on("error", (error) => {
6316
+ finishProcess();
6335
6317
  exited = true;
6336
6318
  stopTimers();
6337
6319
  const exit = {
@@ -6346,6 +6328,7 @@ Error cleaning up sandbox: ${asErrorString(error)}`,
6346
6328
  settleExit(exit);
6347
6329
  });
6348
6330
  child.on("close", (code, signal) => {
6331
+ finishProcess();
6349
6332
  exited = true;
6350
6333
  stopTimers();
6351
6334
  const exit = { code, signal, aborted, timedOut, sizeKilled };
@@ -6355,6 +6338,7 @@ Error cleaning up sandbox: ${asErrorString(error)}`,
6355
6338
  backgroundFn = backgroundExecution;
6356
6339
  });
6357
6340
  return {
6341
+ done: processDone,
6358
6342
  result,
6359
6343
  background: (reason) => backgroundFn?.(reason) ?? null
6360
6344
  };
@@ -8359,7 +8343,15 @@ var EditFileTool = class {
8359
8343
  input_schema: inputSchema
8360
8344
  };
8361
8345
  }
8362
- 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) {
8363
8355
  const requestedPath = strArg(args, "file_path");
8364
8356
  if (!requestedPath) {
8365
8357
  return {
@@ -9887,7 +9879,16 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
9887
9879
  }
9888
9880
  };
9889
9881
  }
9890
- 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) {
9891
9892
  const command = strArg(args, "command");
9892
9893
  if (!command) {
9893
9894
  return {
@@ -9934,6 +9935,7 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
9934
9935
  outputFile,
9935
9936
  manager
9936
9937
  );
9938
+ started(handle.done);
9937
9939
  if (runInBackground) {
9938
9940
  const taskId = handle.background("explicit");
9939
9941
  if (taskId !== null) {
@@ -9951,6 +9953,10 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
9951
9953
  * backgrounding is a bookkeeping switch — no re-spawn, no buffer handover.
9952
9954
  */
9953
9955
  startCommand(ctx, shell, command, timeout, outputFile, manager) {
9956
+ let finishProcess = () => void 0;
9957
+ const processDone = new Promise((resolve11) => {
9958
+ finishProcess = resolve11;
9959
+ });
9954
9960
  let backgroundFn;
9955
9961
  const result = new Promise((resolve11) => {
9956
9962
  let aborted = false;
@@ -9981,6 +9987,7 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
9981
9987
  stdio: ["ignore", outputFile.fd, outputFile.fd]
9982
9988
  });
9983
9989
  } catch (error) {
9990
+ finishProcess();
9984
9991
  discardFd(outputFile.fd);
9985
9992
  unlinkQuiet(outputFile.path);
9986
9993
  resolve11({
@@ -10041,9 +10048,8 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
10041
10048
  } catch {
10042
10049
  return;
10043
10050
  }
10044
- const cap = backgrounded ? BACKGROUND_MAX_OUTPUT_BYTES : MAX_SHELL_OUTPUT_BYTES;
10045
- if (size > cap) {
10046
- sizeKilled = backgrounded;
10051
+ if (size > MAX_SHELL_OUTPUT_FILE_BYTES) {
10052
+ sizeKilled = true;
10047
10053
  clearInterval(watchdog);
10048
10054
  terminate();
10049
10055
  }
@@ -10089,16 +10095,13 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
10089
10095
  if (backgrounded) {
10090
10096
  return;
10091
10097
  }
10092
- const read = readOutputFile(outputFile.path, MAX_SHELL_OUTPUT_BYTES);
10093
- const finalResult = formatFinalResult(
10098
+ const finalResult = buildShellResult(
10094
10099
  "PS> ",
10095
10100
  command,
10096
10101
  exit,
10097
- read.text,
10098
- read.truncated,
10102
+ outputFile.path,
10099
10103
  timeout
10100
10104
  );
10101
- unlinkQuiet(outputFile.path);
10102
10105
  settle(finalResult);
10103
10106
  };
10104
10107
  const backgroundExecution = (reason) => {
@@ -10114,12 +10117,13 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
10114
10117
  backgroundTaskName(command),
10115
10118
  async () => {
10116
10119
  const exit = await done;
10117
- const body = buildBackgroundBody(
10120
+ const body = buildShellResult(
10118
10121
  "PS> ",
10119
10122
  command,
10120
10123
  exit,
10121
10124
  outputFile.path,
10122
- timeout
10125
+ timeout,
10126
+ BACKGROUND_NOTIFICATION_BYTES
10123
10127
  );
10124
10128
  if (body.isError) {
10125
10129
  throw new TaskFailure(body.output);
@@ -10153,6 +10157,7 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
10153
10157
  }
10154
10158
  };
10155
10159
  child.on("error", (err) => {
10160
+ finishProcess();
10156
10161
  stopTimers();
10157
10162
  const hint = strArg(asRecord(err), "code") === "ENOENT" && process.platform !== "win32" ? " (pwsh is required on macOS/Linux \u2014 install PowerShell Core)" : "";
10158
10163
  const exit = {
@@ -10167,6 +10172,7 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
10167
10172
  settleExit(exit);
10168
10173
  });
10169
10174
  child.on("close", (code, signal) => {
10175
+ finishProcess();
10170
10176
  stopTimers();
10171
10177
  const exit = { code, signal, aborted, timedOut, sizeKilled };
10172
10178
  doneResolve?.(exit);
@@ -10175,6 +10181,7 @@ ${POWERSHELL_BACKGROUND_DESCRIPTION}`;
10175
10181
  backgroundFn = backgroundExecution;
10176
10182
  });
10177
10183
  return {
10184
+ done: processDone,
10178
10185
  result,
10179
10186
  background: (reason) => backgroundFn?.(reason) ?? null
10180
10187
  };
@@ -10894,6 +10901,14 @@ var WriteFileTool = class {
10894
10901
  };
10895
10902
  }
10896
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) {
10897
10912
  const requestedPath = strArg(args, "file_path");
10898
10913
  if (!requestedPath) {
10899
10914
  return Promise.resolve({
@@ -12747,21 +12762,21 @@ __export(client_exports2, {
12747
12762
  async function createClient(config, systemPrompt) {
12748
12763
  switch (config.protocol) {
12749
12764
  case "anthropic": {
12750
- const { AnthropicClient } = await import("./anthropic-EQRUGP2C.js");
12765
+ const { AnthropicClient } = await import("./anthropic-TDNNKQMT.js");
12751
12766
  return registerLlmClient(new AnthropicClient(config, systemPrompt), {
12752
12767
  model: config.model,
12753
12768
  protocol: config.protocol
12754
12769
  });
12755
12770
  }
12756
12771
  case "openai": {
12757
- const { OpenAIClient } = await import("./openai-B3I5WBFT.js");
12772
+ const { OpenAIClient } = await import("./openai-6VYIA7CT.js");
12758
12773
  return registerLlmClient(new OpenAIClient(config, systemPrompt), {
12759
12774
  model: config.model,
12760
12775
  protocol: config.protocol
12761
12776
  });
12762
12777
  }
12763
12778
  case "openai-compat": {
12764
- const { OpenAICompatClient } = await import("./openai-B3I5WBFT.js");
12779
+ const { OpenAICompatClient } = await import("./openai-6VYIA7CT.js");
12765
12780
  return registerLlmClient(new OpenAICompatClient(config, systemPrompt), {
12766
12781
  model: config.model,
12767
12782
  protocol: config.protocol
@@ -15756,20 +15771,15 @@ async function spawnSubagent(definition, prompt, parentClient, parentRegistry, p
15756
15771
  let output = "";
15757
15772
  let turn = 0;
15758
15773
  try {
15759
- const inheritedChecker = checkerOverride ?? new PermissionChecker(
15760
- cwd2,
15761
- options.permissionMode ?? definition.permissionMode
15762
- );
15763
- const checker = inheritedChecker.forSubagent(cwd2);
15764
- if (definition.permissionMode === "plan") {
15765
- checker.planModeLocked = true;
15766
- }
15774
+ const inheritedChecker = checkerOverride ?? new PermissionChecker(cwd2, options.permissionMode);
15775
+ const checker = inheritedChecker.teammate ? inheritedChecker.forCwd(cwd2) : inheritedChecker.forSubagent(cwd2, definition.permissionMode);
15767
15776
  const conversation = options.conversation ?? new ConversationManager();
15768
15777
  if (!options.conversation || conversation.getMessages().length === 0) {
15769
15778
  conversation.addSystemReminder(buildSubagentInstructions(definition));
15770
15779
  }
15771
15780
  conversation.addUserMessage(prompt);
15772
15781
  const agent2 = new Agent({
15782
+ agentName: options.agentName ?? definition.name,
15773
15783
  client,
15774
15784
  registry,
15775
15785
  checker,
@@ -15875,7 +15885,6 @@ function coordinatorActive(enabled = false) {
15875
15885
  // src/teams/index.ts
15876
15886
  var teams_exports = {};
15877
15887
  __export(teams_exports, {
15878
- Backend: () => backend_exports,
15879
15888
  Coordinator: () => coordinator_exports2,
15880
15889
  FileLock: () => file_lock_exports,
15881
15890
  FileMailbox: () => file_mailbox_exports,
@@ -15890,137 +15899,8 @@ __export(teams_exports, {
15890
15899
  TeamManager: () => TeamManager,
15891
15900
  Tools: () => tools_exports
15892
15901
  });
15893
- import { randomBytes as randomBytes4 } from "crypto";
15894
- import { existsSync as existsSync13, mkdirSync as mkdirSync10, readFileSync as readFileSync11, rmSync as rmSync7 } from "fs";
15895
- import { createRequire } from "module";
15896
- import { dirname as dirname8, join as join19 } from "path";
15897
-
15898
- // src/teams/backend.ts
15899
- var backend_exports = {};
15900
- __export(backend_exports, {
15901
- detectBackend: () => detectBackend,
15902
- detectBackendFromEnv: () => detectBackendFromEnv,
15903
- isProcessAlive: () => isProcessAlive,
15904
- isTeammateAlive: () => isTeammateAlive,
15905
- restoreTeammateCancel: () => restoreTeammateCancel,
15906
- spawnTeammate: () => spawnTeammate
15907
- });
15908
- import { execFileSync } from "child_process";
15909
- var log25 = createChildLogger({ module: "teams" });
15910
- function detectBackend() {
15911
- if (process.platform === "win32") {
15912
- return "in-process";
15913
- }
15914
- return detectBackendFromEnv();
15915
- }
15916
- function detectBackendFromEnv() {
15917
- if (process.env.TMUX) {
15918
- return "tmux";
15919
- }
15920
- if (process.env.ITERM_SESSION_ID) {
15921
- return "iterm";
15922
- }
15923
- return "in-process";
15924
- }
15925
- function shellQuote(arg) {
15926
- if (/^[A-Za-z0-9_/.:=-]+$/.test(arg)) {
15927
- return arg;
15928
- }
15929
- return `'${arg.replace(/'/g, `'\\''`)}'`;
15930
- }
15931
- function buildShellCommand(config) {
15932
- return [config.command, ...config.args].map(shellQuote).join(" ");
15933
- }
15934
- function cancelTmuxSession(sessionName) {
15935
- try {
15936
- execFileSync("tmux", ["kill-session", "-t", sessionName], {
15937
- stdio: ["pipe", "pipe", "pipe"]
15938
- });
15939
- } catch (err) {
15940
- log25.error({ err }, "teams operation failed");
15941
- }
15942
- }
15943
- function restoreTeammateCancel(mode2, paneId) {
15944
- if (mode2 !== "tmux" || !paneId) {
15945
- return void 0;
15946
- }
15947
- return () => {
15948
- cancelTmuxSession(paneId);
15949
- };
15950
- }
15951
- function isProcessAlive(pid) {
15952
- try {
15953
- process.kill(pid, 0);
15954
- return true;
15955
- } catch (error) {
15956
- return error instanceof Error && "code" in error && error.code === "EPERM";
15957
- }
15958
- }
15959
- function isTeammateAlive(mode2, paneId, workerPid) {
15960
- if (workerPid) {
15961
- return isProcessAlive(workerPid);
15962
- }
15963
- if (mode2 !== "tmux" || !paneId) {
15964
- return false;
15965
- }
15966
- try {
15967
- execFileSync("tmux", ["has-session", "-t", paneId], {
15968
- stdio: ["ignore", "ignore", "ignore"]
15969
- });
15970
- return true;
15971
- } catch {
15972
- return false;
15973
- }
15974
- }
15975
- function spawnTeammate(config) {
15976
- switch (config.mode) {
15977
- case "tmux": {
15978
- const sessionName = config.paneId ?? `yukino-${Date.now().toString(36)}`;
15979
- const cmd = buildShellCommand(config);
15980
- execFileSync(
15981
- "tmux",
15982
- ["new-session", "-d", "-s", sessionName, "-n", "teammate", cmd],
15983
- {
15984
- cwd: config.cwd,
15985
- encoding: "utf-8",
15986
- stdio: ["pipe", "pipe", "pipe"]
15987
- }
15988
- );
15989
- return {
15990
- cancel: () => {
15991
- cancelTmuxSession(sessionName);
15992
- },
15993
- paneId: sessionName
15994
- };
15995
- }
15996
- case "iterm": {
15997
- const cmd = buildShellCommand(config);
15998
- const writeText = `cd ${shellQuote(config.cwd)} && ${cmd}`;
15999
- const script = [
16000
- "on run argv",
16001
- " set commandText to item 1 of argv",
16002
- ' tell application "iTerm2"',
16003
- " tell current window",
16004
- " create tab with default profile",
16005
- " tell current session to write text commandText",
16006
- " end tell",
16007
- " end tell",
16008
- "end run"
16009
- ].join("\n");
16010
- execFileSync("osascript", ["-e", script, writeText], {
16011
- cwd: config.cwd,
16012
- encoding: "utf-8",
16013
- stdio: ["pipe", "pipe", "pipe"]
16014
- });
16015
- return {
16016
- cancel: () => {
16017
- }
16018
- };
16019
- }
16020
- default:
16021
- throw new Error(`Unknown team mode: ${String(config.mode)}`);
16022
- }
16023
- }
15902
+ import { mkdirSync as mkdirSync10, readFileSync as readFileSync11, rmSync as rmSync7 } from "fs";
15903
+ import { join as join19 } from "path";
16024
15904
 
16025
15905
  // src/teams/file-mailbox.ts
16026
15906
  var file_mailbox_exports = {};
@@ -16037,7 +15917,7 @@ import {
16037
15917
  } from "fs";
16038
15918
  import { join as join18 } from "path";
16039
15919
  import z15 from "zod";
16040
- var log26 = createChildLogger({ module: "teams" });
15920
+ var log25 = createChildLogger({ module: "teams" });
16041
15921
  var FileMailMessageSchema = z15.object({
16042
15922
  from: z15.string(),
16043
15923
  text: z15.string(),
@@ -16070,7 +15950,7 @@ var FileMailbox = class {
16070
15950
  const raw = JSON.parse(readFileSync9(this.filePath, "utf-8"));
16071
15951
  return z15.array(FileMailMessageSchema).parse(raw);
16072
15952
  } catch (err) {
16073
- log26.error({ err }, "teams operation failed");
15953
+ log25.error({ err }, "teams operation failed");
16074
15954
  throw new Error(
16075
15955
  "Cannot load an unreadable teammate mailbox; original contents were preserved",
16076
15956
  { cause: err }
@@ -16328,7 +16208,7 @@ var StoreDataSchema = z17.object({
16328
16208
  next_id: z17.number().int().positive().max(Number.MAX_SAFE_INTEGER),
16329
16209
  tasks: z17.array(SerializedTaskSchema)
16330
16210
  });
16331
- var log27 = createChildLogger({ module: "shared-tasks" });
16211
+ var log26 = createChildLogger({ module: "shared-tasks" });
16332
16212
  var SharedTaskStore = class {
16333
16213
  path;
16334
16214
  nextId = 1;
@@ -16404,7 +16284,7 @@ var SharedTaskStore = class {
16404
16284
  try {
16405
16285
  listener(structuredClone(this.tasks));
16406
16286
  } catch (error) {
16407
- log27.error({ error }, "shared task subscriber failed");
16287
+ log26.error({ error }, "shared task subscriber failed");
16408
16288
  }
16409
16289
  }
16410
16290
  }
@@ -16596,29 +16476,20 @@ var SharedTaskStore = class {
16596
16476
  };
16597
16477
 
16598
16478
  // src/teams/index.ts
16599
- var log28 = createChildLogger({ module: "teams" });
16479
+ var log27 = createChildLogger({ module: "teams" });
16600
16480
  var MAX_RETAINED_TERMINATED_MEMBERS = 200;
16601
16481
  var Team = class _Team {
16602
16482
  name;
16603
- mode;
16604
16483
  members = /* @__PURE__ */ new Map();
16605
16484
  leaderMailbox;
16606
16485
  mailboxDir;
16607
16486
  cwd;
16608
- lastLivenessCheck = 0;
16609
16487
  leaderAgentId = "";
16610
16488
  permissionMode = "default";
16611
16489
  description;
16612
16490
  createdAt = Math.floor(Date.now() / 1e3);
16613
- /**
16614
- * PID of the leader process. Written to config.json so external teammates
16615
- * can detect a dead leader (they exit instead of polling forever); a
16616
- * restarted leader re-claims it when the team is restored from disk.
16617
- */
16618
- leaderPid = 0;
16619
- constructor(name, mode2, cwd2) {
16491
+ constructor(name, cwd2) {
16620
16492
  this.name = name;
16621
- this.mode = mode2;
16622
16493
  this.cwd = cwd2;
16623
16494
  this.mailboxDir = join19(teamDir(cwd2, name), "inboxes");
16624
16495
  mkdirSync10(this.mailboxDir, { recursive: true });
@@ -16630,7 +16501,6 @@ var Team = class _Team {
16630
16501
  active: false,
16631
16502
  mailbox: new FileMailbox(this.mailboxDir, name),
16632
16503
  agentId: name,
16633
- backendType: this.mode,
16634
16504
  joinedAt: Math.floor(Date.now() / 1e3)
16635
16505
  };
16636
16506
  }
@@ -16663,23 +16533,7 @@ var Team = class _Team {
16663
16533
  member.model = entry.model;
16664
16534
  member.worktreePath = entry.worktreePath;
16665
16535
  member.joinedAt = entry.joinedAt;
16666
- member.backendType = isTeamMode(entry.backendType) ? entry.backendType : this.mode;
16667
- member.paneId = entry.paneId;
16668
- member.workerPid = entry.workerPid;
16669
- member.external = member.backendType === "tmux" || member.backendType === "iterm";
16670
- member.active = entry.isActive && member.external && isTeammateAlive(member.backendType, member.paneId, member.workerPid);
16671
- if (member.active) {
16672
- getNameRegistry().register(member.name, member.agentId);
16673
- member.uiState = {
16674
- name: member.name,
16675
- teamName: this.name,
16676
- status: "running",
16677
- progress: createProgress(),
16678
- startTime: entry.joinedAt > 0 ? entry.joinedAt * 1e3 : Date.now(),
16679
- spinnerVerb: "Working"
16680
- };
16681
- member.cancel = restoreTeammateCancel(member.backendType, member.paneId);
16682
- }
16536
+ member.active = false;
16683
16537
  this.members.set(member.name, member);
16684
16538
  return member;
16685
16539
  }
@@ -16700,12 +16554,10 @@ var Team = class _Team {
16700
16554
  snapshot() {
16701
16555
  return {
16702
16556
  name: this.name,
16703
- mode: this.mode,
16704
16557
  description: this.description,
16705
16558
  createdAt: this.createdAt,
16706
16559
  leaderAgentId: this.leaderAgentId,
16707
16560
  permissionMode: this.permissionMode,
16708
- ...this.leaderPid > 0 ? { leaderPid: this.leaderPid } : {},
16709
16561
  members: [...this.members.values()].map((m) => ({
16710
16562
  agentId: m.agentId ?? m.name,
16711
16563
  name: m.name,
@@ -16713,9 +16565,6 @@ var Team = class _Team {
16713
16565
  model: m.model,
16714
16566
  joinedAt: m.joinedAt ?? 0,
16715
16567
  worktreePath: m.worktreePath,
16716
- backendType: m.backendType ?? this.mode,
16717
- paneId: m.paneId,
16718
- workerPid: m.workerPid,
16719
16568
  isActive: m.active
16720
16569
  }))
16721
16570
  };
@@ -16729,148 +16578,20 @@ var Team = class _Team {
16729
16578
  writeTeamFile(this.cwd, this.name, this.snapshot());
16730
16579
  }
16731
16580
  static IDLE_POLL_INTERVAL_MS = 500;
16732
- // Grace period after the shutdown notice before force-killing an external
16733
- // teammate: one mailbox poll interval (~2 s) plus exit time.
16734
- static STOP_GRACE_MS = 2500;
16735
16581
  // The leader writes a mailbox message with this prefix to notify
16736
16582
  // teammates to exit.
16737
16583
  static SHUTDOWN_PREFIX = SHUTDOWN_PREFIX;
16738
- /**
16739
- * Spawns a teammate, dispatching by team backend mode.
16740
- * - in-process: runs the agent main loop in a background task within this process (idle-poll-continue).
16741
- * - tmux / iterm: assembles the teammate startup command and delegates to the backend to launch
16742
- * an independent worker process in a new pane / tab, communicating bidirectionally with the
16743
- * leader via the shared file-based mailbox.
16744
- * Falls back to in-process when the external backend is unavailable (tmux not installed,
16745
- * non-iTerm environment, etc.) to avoid crashes.
16746
- */
16747
- spawnTeammate(name, task, runAgent, checker, providerIndex, originToolCallId, memberCwd = this.cwd, role = {}) {
16584
+ spawnTeammate(name, task, runAgent, checker, originToolCallId, memberCwd = this.cwd, role = {}) {
16748
16585
  const member = this.getMember(name) ?? this.addMember(name);
16749
16586
  if (member.active) {
16750
16587
  throw new Error(`Teammate '${name}' is already running`);
16751
16588
  }
16752
16589
  this.setMemberMeta(name, role);
16753
- member.planApprovalRequired = role.planApprovalRequired ?? checker?.planModeLocked ?? false;
16754
- member.readOnlyRole = role.readOnly ?? false;
16755
- const mode2 = this.mode;
16756
- if (mode2 === "in-process" || checker?.mode === "plan") {
16757
- this.spawnInProcess(
16758
- name,
16759
- task,
16760
- runAgent,
16761
- checker,
16762
- originToolCallId,
16763
- memberCwd,
16764
- role.cleanup
16765
- );
16766
- return "in-process";
16767
- }
16768
- try {
16769
- this.spawnExternal(
16770
- mode2,
16771
- name,
16772
- task,
16773
- providerIndex,
16774
- originToolCallId,
16775
- memberCwd,
16776
- role
16777
- );
16778
- return mode2;
16779
- } catch {
16780
- this.spawnInProcess(
16781
- name,
16782
- task,
16783
- runAgent,
16784
- checker,
16785
- originToolCallId,
16786
- memberCwd,
16787
- role.cleanup
16788
- );
16789
- return "in-process";
16790
- }
16791
- }
16792
- /**
16793
- * tmux / iTerm backend: launches the teammate as an independent process in a new pane / tab.
16794
- * The teammate process connects back to the team via the same mailbox directory pointed to
16795
- * by `--team-dir`; task assignments from the leader and idle/result notifications from the
16796
- * worker all land in this directory, keeping both sides in sync.
16797
- */
16798
- spawnExternal(mode2, name, task, providerIndex, originToolCallId, memberCwd = this.cwd, role = {}) {
16799
- const member = this.getMember(name) ?? this.addMember(name);
16800
- member.stopping = void 0;
16801
- member.done = void 0;
16802
- member.workerPid = void 0;
16803
- member.active = true;
16804
- member.backendType = mode2;
16805
- member.external = true;
16806
- member.paneId = mode2 === "tmux" ? `yukino-${randomBytes4(8).toString("hex")}` : void 0;
16807
- member.worktreePath = memberCwd === this.cwd ? void 0 : memberCwd;
16808
- this.persist();
16809
- getNameRegistry().register(name, name);
16810
- member.uiState = {
16811
- name,
16812
- teamName: this.name,
16813
- status: "running",
16814
- progress: createProgress(),
16815
- ...originToolCallId ? { originToolCallId } : {},
16816
- startTime: Date.now(),
16817
- spinnerVerb: "Working"
16818
- };
16819
- const require2 = createRequire(import.meta.url);
16820
- const packageDir = dirname8(
16821
- require2.resolve("@yukino.js/yukino/package.json")
16822
- );
16823
- const sourceEntry = join19(packageDir, "src", "cli.ts");
16824
- const sourceRuntime = existsSync13(sourceEntry);
16825
- const entry = sourceRuntime ? sourceEntry : join19(packageDir, "dist", "main.js");
16826
- const config = {
16827
- mode: mode2,
16828
- command: process.execPath,
16829
- args: [
16830
- ...sourceRuntime ? ["--import", require2.resolve("tsx/esm")] : [],
16831
- entry,
16832
- "--teammate",
16833
- "--team-dir",
16834
- this.mailboxDir,
16835
- "--team-name",
16836
- this.name,
16837
- "--team-cwd",
16838
- this.cwd,
16839
- "--member-name",
16840
- name,
16841
- "--task",
16842
- task,
16843
- "--permission-mode",
16844
- this.permissionMode,
16845
- ...role.agentType ? ["--agent-type", role.agentType] : [],
16846
- ...role.model ? ["--model", role.model] : [],
16847
- ...providerIndex !== void 0 ? ["--provider-index", String(providerIndex)] : []
16848
- ],
16849
- cwd: memberCwd,
16850
- paneId: member.paneId
16851
- };
16852
- const { cancel, paneId } = spawnTeammate(config);
16853
- member.cancel = cancel;
16854
- member.paneId = paneId;
16855
- member.external = true;
16856
- this.persist();
16857
- }
16858
- /**
16859
- * Starts an in-process teammate: runs the agent's main loop in the background,
16860
- * sends an idle notification upon completion, and then polls the mailbox for new tasks.
16861
- * Exits the loop upon receiving a shutdown message or being canceled.
16862
- * Uses the idle-poll-continue pattern: after each turn completes, reports idle and waits for the next task.
16863
- */
16864
- spawnInProcess(name, task, runAgent, checker, originToolCallId, memberCwd = this.cwd, cleanup) {
16865
- const member = this.getMember(name) ?? this.addMember(name);
16866
- if (checker?.planModeLocked && !checker.planFilePath) {
16590
+ member.planApprovalRequired = role.planApprovalRequired ?? false;
16591
+ if (checker?.mode === "plan" && !checker.planFilePath) {
16867
16592
  checker.planFilePath = createPlanPath();
16868
16593
  }
16869
16594
  member.active = true;
16870
- member.backendType = "in-process";
16871
- member.external = false;
16872
- member.paneId = void 0;
16873
- member.workerPid = void 0;
16874
16595
  member.worktreePath = memberCwd === this.cwd ? void 0 : memberCwd;
16875
16596
  this.persist();
16876
16597
  member.checker = checker;
@@ -16938,7 +16659,7 @@ var Team = class _Team {
16938
16659
  uiState.status = "idle";
16939
16660
  const next = await this.runPlanApproval(
16940
16661
  member,
16941
- this.readPlanForReview(member, result)
16662
+ this.readPlan(member, result)
16942
16663
  );
16943
16664
  if (next === null) {
16944
16665
  break;
@@ -16976,7 +16697,7 @@ var Team = class _Team {
16976
16697
  uiState.lastMessage = "Stopped";
16977
16698
  terminalMessage = `[idle] ${name} (reason: stopped)`;
16978
16699
  } else {
16979
- log28.error({ err }, "teams operation failed");
16700
+ log27.error({ err }, "teams operation failed");
16980
16701
  uiState.status = "failed";
16981
16702
  uiState.lastMessage = asErrorString(err);
16982
16703
  terminalMessage = `[idle] ${name} (reason: failed): ${asErrorString(err)}`;
@@ -16989,9 +16710,9 @@ var Team = class _Team {
16989
16710
  uiState.status = "idle";
16990
16711
  }
16991
16712
  try {
16992
- await cleanup?.();
16713
+ await role.cleanup?.();
16993
16714
  } catch (error) {
16994
- log28.error({ error, name }, "teammate resource cleanup failed");
16715
+ log27.error({ error, name }, "teammate resource cleanup failed");
16995
16716
  } finally {
16996
16717
  try {
16997
16718
  this.releaseMemberTasks(member);
@@ -17012,7 +16733,7 @@ var Team = class _Team {
17012
16733
  }
17013
16734
  }
17014
16735
  })().catch((error) => {
17015
- log28.error(
16736
+ log27.error(
17016
16737
  { error, name },
17017
16738
  "teammate loop failed while reporting termination"
17018
16739
  );
@@ -17050,8 +16771,8 @@ ${prompt}` };
17050
16771
  shutdown: shutdownRequest(LEADER_NAME, "member deactivated")
17051
16772
  };
17052
16773
  }
17053
- /** Reads the teammate's plan file for review; returns a fallback note when empty or unreadable. */
17054
- readPlanForReview(member, result) {
16774
+ /** Reads the submitted plan, falling back to the final response. */
16775
+ readPlan(member, result) {
17055
16776
  try {
17056
16777
  const text = readFileSync11(member.checker?.planFilePath ?? "", "utf-8");
17057
16778
  if (text.trim()) {
@@ -17061,55 +16782,24 @@ ${prompt}` };
17061
16782
  }
17062
16783
  return result || "(The teammate returned no plan.)";
17063
16784
  }
17064
- /**
17065
- * Sends the teammate's completed plan to the Leader, blocks until approval is received,
17066
- * and returns the prompt to feed the model on the next turn.
17067
- *
17068
- * The teammate holds read-only permissions at this point, so no matter how long the
17069
- * wait, no damage can occur — hence no timeout is set here. Rather than timing out and
17070
- * autonomously modifying files, it is better to wait indefinitely and let the user
17071
- * drive progress from the Leader side. Returns null when the teammate has been
17072
- * deactivated; the caller should exit the main loop.
17073
- */
17074
16785
  async runPlanApproval(member, plan) {
17075
- const req = planApprovalRequest(member.name, plan);
17076
- await this.leaderMailbox.send(member.name, req.text, req);
17077
- const held = [];
17078
- let response;
17079
- while (member.active && response === void 0) {
17080
- await this.waitForMember(member);
17081
- if (!member.active || member.signal?.aborted) {
17082
- break;
17083
- }
17084
- for (const m of member.mailbox.receiveSync()) {
17085
- if (isShutdownRequest(m)) {
17086
- const reply = shutdownResponse(
17087
- member.name,
17088
- m.requestId ?? "",
17089
- true,
17090
- "acknowledged, shutting down"
17091
- );
17092
- await this.leaderMailbox.send(member.name, reply.text, reply);
17093
- member.active = false;
17094
- } else if (m.type === MSG_PLAN_APPROVAL_RESPONSE && m.from === LEADER_NAME && m.requestId === req.requestId) {
17095
- response = m;
17096
- } else {
17097
- held.push(m);
17098
- }
17099
- }
17100
- }
17101
- member.mailbox.requeue(held);
17102
- 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) {
17103
16789
  return null;
17104
16790
  }
17105
- if (approved(response) && member.checker) {
17106
- if (!member.readOnlyRole) {
17107
- member.checker.planModeLocked = false;
17108
- }
17109
- 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;
17110
16799
  }
17111
- return approved(response) ? "The Leader has approved your plan. Begin execution now." : `The Leader rejected your plan. Feedback: ${response.text}
17112
- 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.";
17113
16803
  }
17114
16804
  getMember(name) {
17115
16805
  return this.members.get(name);
@@ -17141,7 +16831,7 @@ Please revise the plan accordingly and resubmit.`;
17141
16831
  );
17142
16832
  }
17143
16833
  } catch (error) {
17144
- log28.error(
16834
+ log27.error(
17145
16835
  { error, member: member.name },
17146
16836
  "failed to release teammate tasks"
17147
16837
  );
@@ -17175,66 +16865,26 @@ Please revise the plan accordingly and resubmit.`;
17175
16865
  );
17176
16866
  this.persist();
17177
16867
  }
17178
- /**
17179
- * Stops a single teammate: marks it inactive, updates UI state, and
17180
- * unregisters the name so SendMessage can no longer resolve it.
17181
- * External teammates get a grace window after the shutdown notice — they
17182
- * poll their mailbox every ~2 s, so waiting one poll interval lets the
17183
- * common (idle) case exit gracefully before the pane is force-killed.
17184
- * In-process teammates are stopped via cancel (abort) alone; `done` is then
17185
- * awaited so the loop has fully exited (external members have no promise).
17186
- */
17187
16868
  stopOne(member) {
17188
16869
  member.stopping ??= this.stopMemberRuntime(member);
17189
16870
  return member.stopping;
17190
16871
  }
17191
16872
  async stopMemberRuntime(member) {
17192
- const wasActive = member.active;
17193
16873
  member.active = false;
17194
16874
  if (member.uiState?.status === "running" || member.uiState?.status === "idle") {
17195
16875
  member.uiState.status = "stopped";
17196
16876
  }
17197
16877
  getNameRegistry().unregister(member.name);
17198
- if (member.external && wasActive) {
17199
- try {
17200
- await member.mailbox.send(LEADER_NAME, `${_Team.SHUTDOWN_PREFIX} stop`);
17201
- await new Promise((r) => setTimeout(r, _Team.STOP_GRACE_MS));
17202
- } catch {
17203
- }
17204
- }
17205
- if (member.external && member.backendType === "iterm") {
17206
- const pid = readTeamFile(this.cwd, this.name)?.members.find(
17207
- (entry) => entry.name === member.name
17208
- )?.workerPid;
17209
- if (pid && pid !== process.pid && isProcessAlive(pid)) {
17210
- try {
17211
- process.kill(pid, "SIGTERM");
17212
- const deadline = Date.now() + 2500;
17213
- while (isProcessAlive(pid) && Date.now() < deadline) {
17214
- await new Promise((resolve11) => setTimeout(resolve11, 50));
17215
- }
17216
- if (isProcessAlive(pid)) {
17217
- process.kill(pid, "SIGKILL");
17218
- }
17219
- } catch (error) {
17220
- log28.error(
17221
- { error, member: member.name },
17222
- "external teammate termination failed"
17223
- );
17224
- }
17225
- }
17226
- }
17227
16878
  try {
17228
16879
  member.cancel?.();
17229
16880
  } catch (error) {
17230
- log28.error({ error, member: member.name }, "teammate cancellation failed");
16881
+ log27.error({ error, member: member.name }, "teammate cancellation failed");
17231
16882
  }
17232
16883
  await member.done;
17233
16884
  this.releaseMemberTasks(member);
17234
16885
  member.cancel = void 0;
17235
16886
  member.checker = void 0;
17236
16887
  member.signal = void 0;
17237
- member.workerPid = void 0;
17238
16888
  member.done = void 0;
17239
16889
  this.pruneTerminatedMembers();
17240
16890
  }
@@ -17242,52 +16892,10 @@ Please revise the plan accordingly and resubmit.`;
17242
16892
  return [...this.members.values()];
17243
16893
  }
17244
16894
  getTeammateStates() {
17245
- this.refreshExternalMembers();
17246
16895
  return this.listMembers().flatMap(
17247
16896
  (member) => member.uiState ? [member.uiState] : []
17248
16897
  );
17249
16898
  }
17250
- refreshExternalMembers() {
17251
- const now = Date.now();
17252
- if (now - this.lastLivenessCheck < 2e3) {
17253
- return;
17254
- }
17255
- this.lastLivenessCheck = now;
17256
- const config = readTeamFile(this.cwd, this.name);
17257
- for (const member of this.members.values()) {
17258
- if (!member.external || !member.active) {
17259
- continue;
17260
- }
17261
- member.workerPid = config?.members.find((entry) => entry.name === member.name)?.workerPid ?? member.workerPid;
17262
- if (!member.workerPid && member.backendType === "iterm" && now - (member.uiState?.startTime ?? now) < 1e4) {
17263
- continue;
17264
- }
17265
- if (isTeammateAlive(
17266
- member.backendType ?? this.mode,
17267
- member.paneId,
17268
- member.workerPid
17269
- )) {
17270
- continue;
17271
- }
17272
- member.active = false;
17273
- member.cancel = void 0;
17274
- member.checker = void 0;
17275
- member.workerPid = void 0;
17276
- getNameRegistry().unregister(member.name);
17277
- if (member.uiState) {
17278
- member.uiState.status = "failed";
17279
- member.uiState.lastMessage = "Teammate process exited unexpectedly";
17280
- clearActiveTools(member.uiState.progress);
17281
- }
17282
- this.releaseMemberTasks(member);
17283
- this.leaderMailbox.sendSync(
17284
- member.name,
17285
- `[idle] ${member.name} (reason: failed): teammate process exited unexpectedly`
17286
- );
17287
- this.persist();
17288
- }
17289
- this.pruneTerminatedMembers();
17290
- }
17291
16899
  pruneTerminatedMembers() {
17292
16900
  const terminal = this.listMembers().filter(
17293
16901
  (member) => !member.active && !member.done && !member.cancel && member.uiState && ["completed", "failed", "stopped"].includes(member.uiState.status)
@@ -17314,15 +16922,13 @@ var TeamManager = class {
17314
16922
  /** Teams keyed by their canonical disk slug; Team.name remains the display name. */
17315
16923
  teams = /* @__PURE__ */ new Map();
17316
16924
  cwd;
17317
- claimLeadership;
17318
16925
  permissionChecker;
17319
16926
  unsubscribePermissions;
17320
16927
  // One shared task store per canonical team identity.
17321
16928
  taskStores = /* @__PURE__ */ new Map();
17322
16929
  listeners = /* @__PURE__ */ new Set();
17323
- constructor(cwd2, opts = {}) {
16930
+ constructor(cwd2) {
17324
16931
  this.cwd = canonicalPath(cwd2);
17325
- this.claimLeadership = opts.claimLeadership ?? true;
17326
16932
  }
17327
16933
  subscribe(listener) {
17328
16934
  this.listeners.add(listener);
@@ -17335,7 +16941,7 @@ var TeamManager = class {
17335
16941
  try {
17336
16942
  listener();
17337
16943
  } catch (error) {
17338
- log28.error({ error }, "team subscriber failed");
16944
+ log27.error({ error }, "team subscriber failed");
17339
16945
  }
17340
16946
  }
17341
16947
  }
@@ -17347,7 +16953,7 @@ var TeamManager = class {
17347
16953
  this.permissionChecker = checker;
17348
16954
  const sync = () => {
17349
16955
  for (const team of this.teams.values()) {
17350
- team.permissionMode = checker.delegatedMode;
16956
+ team.permissionMode = checker.mode;
17351
16957
  team.persist();
17352
16958
  }
17353
16959
  };
@@ -17360,19 +16966,16 @@ var TeamManager = class {
17360
16966
  teamDir(name) {
17361
16967
  return teamDir(this.cwd, name);
17362
16968
  }
17363
- create(name, mode2 = detectBackend(), opts = {}) {
16969
+ create(name, opts = {}) {
17364
16970
  const existing = this.get(name);
17365
16971
  if (existing) {
17366
16972
  return existing;
17367
16973
  }
17368
16974
  const key = this.teamKey(name);
17369
- const team = new Team(name, mode2, this.cwd);
17370
- team.permissionMode = this.permissionChecker?.delegatedMode ?? "default";
16975
+ const team = new Team(name, this.cwd);
16976
+ team.permissionMode = this.permissionChecker?.mode ?? "default";
17371
16977
  team.leaderAgentId = opts.leaderAgentId ?? "";
17372
16978
  team.description = opts.description;
17373
- if (this.claimLeadership) {
17374
- team.leaderPid = process.pid;
17375
- }
17376
16979
  this.teams.set(key, team);
17377
16980
  const store = new SharedTaskStore(join19(this.teamDir(name), "tasks.json"));
17378
16981
  store.initEmpty();
@@ -17381,67 +16984,45 @@ var TeamManager = class {
17381
16984
  this.emitChange();
17382
16985
  return team;
17383
16986
  }
17384
- /**
17385
- * Checks the in-memory cache first; on miss, hydrates config.json without
17386
- * incremental member writes. Active members regain their runtime-facing UI,
17387
- * registry, and external cancellation metadata. A leader claims leadership
17388
- * with one final snapshot; teammate processes leave the file byte-identical.
17389
- */
17390
16987
  get(name) {
17391
16988
  const key = this.teamKey(name);
17392
16989
  const cached = this.teams.get(key);
17393
- if (cached && this.claimLeadership) {
16990
+ if (cached) {
17394
16991
  return cached;
17395
16992
  }
17396
16993
  const tf = readTeamFile(this.cwd, name);
17397
16994
  if (!tf) {
17398
- if (!this.claimLeadership) {
17399
- this.teams.delete(key);
17400
- }
17401
16995
  return void 0;
17402
16996
  }
17403
- const team = new Team(tf.name, tf.mode, this.cwd);
16997
+ const team = new Team(tf.name, this.cwd);
17404
16998
  team.leaderAgentId = tf.leaderAgentId;
17405
- team.permissionMode = this.permissionChecker?.delegatedMode ?? tf.permissionMode;
16999
+ team.permissionMode = this.permissionChecker?.mode ?? tf.permissionMode;
17406
17000
  team.description = tf.description;
17407
17001
  team.createdAt = tf.createdAt;
17408
- team.leaderPid = tf.leaderPid ?? 0;
17409
17002
  for (const member of tf.members) {
17410
17003
  const hydrated = team.hydrateMember(member);
17411
- if (this.claimLeadership && !hydrated.active) {
17412
- hydrated.uiState = {
17413
- name: hydrated.name,
17414
- teamName: team.name,
17415
- status: member.isActive ? "failed" : "stopped",
17416
- progress: createProgress(),
17417
- startTime: member.joinedAt * 1e3,
17418
- spinnerVerb: "Working"
17419
- };
17420
- team.releaseMemberTasks(hydrated);
17421
- }
17422
- }
17423
- if (this.claimLeadership) {
17424
- team.leaderPid = process.pid;
17425
- team.persist();
17426
- 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);
17427
17013
  }
17014
+ team.persist();
17015
+ team.pruneTerminatedMembers();
17428
17016
  this.teams.set(key, team);
17429
- if (this.claimLeadership) {
17430
- this.emitChange();
17431
- }
17017
+ this.emitChange();
17432
17018
  return team;
17433
17019
  }
17434
- /**
17435
- * Loads every team found on disk into the manager. Called on leader startup
17436
- * so teams (and their leader mailboxes) survive a leader restart: external
17437
- * teammates keep running, and their notifications are drained again.
17438
- */
17439
17020
  restoreFromDisk() {
17440
17021
  for (const name of listTeamNames(this.cwd)) {
17441
17022
  this.get(name);
17442
17023
  }
17443
17024
  }
17444
- /** 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. */
17445
17026
  getTaskStore(teamName) {
17446
17027
  const key = this.teamKey(teamName);
17447
17028
  const cached = this.taskStores.get(key);
@@ -17455,11 +17036,6 @@ var TeamManager = class {
17455
17036
  return store;
17456
17037
  }
17457
17038
  list() {
17458
- if (!this.claimLeadership) {
17459
- for (const name of [...this.teams.values()].map((team) => team.name)) {
17460
- this.get(name);
17461
- }
17462
- }
17463
17039
  return [...this.teams.values()];
17464
17040
  }
17465
17041
  async stopAll() {
@@ -17509,9 +17085,6 @@ var TeamManager = class {
17509
17085
  return this.list().flatMap((t) => t.getTeammateStates());
17510
17086
  }
17511
17087
  hasLeaderNotifications() {
17512
- for (const team of this.list()) {
17513
- team.refreshExternalMembers();
17514
- }
17515
17088
  return this.list().some((team) => team.leaderMailbox.unreadCount() > 0);
17516
17089
  }
17517
17090
  /**
@@ -17529,29 +17102,6 @@ var TeamManager = class {
17529
17102
  const lines = [];
17530
17103
  lines.push(`<task-notification team="${team.name}">`);
17531
17104
  for (const msg of msgs) {
17532
- const member = team.getMember(msg.from);
17533
- if (member?.external && member.uiState && msg.text.startsWith("[idle]")) {
17534
- const failed = msg.text.includes(" failed:") || msg.text.includes("reason: failed");
17535
- const stopped = msg.text.includes("reason: stopped");
17536
- if (Date.parse(msg.timestamp) < member.uiState.startTime) {
17537
- continue;
17538
- }
17539
- if (!member.active && !failed && !stopped) {
17540
- continue;
17541
- }
17542
- member.uiState.status = failed ? "failed" : stopped ? "stopped" : "idle";
17543
- clearActiveTools(member.uiState.progress);
17544
- if (failed || stopped) {
17545
- member.active = false;
17546
- getNameRegistry().unregister(member.name);
17547
- team.releaseMemberTasks(member);
17548
- member.cancel = void 0;
17549
- member.checker = void 0;
17550
- member.workerPid = void 0;
17551
- team.persist();
17552
- team.pruneTerminatedMembers();
17553
- }
17554
- }
17555
17105
  const metadata = [
17556
17106
  msg.type ? `type=${msg.type}` : "",
17557
17107
  msg.requestId ? `requestId=${msg.requestId}` : "",
@@ -17567,9 +17117,6 @@ var TeamManager = class {
17567
17117
  return out;
17568
17118
  }
17569
17119
  };
17570
- function isTeamMode(mode2) {
17571
- return mode2 === "in-process" || mode2 === "tmux" || mode2 === "iterm";
17572
- }
17573
17120
 
17574
17121
  // src/tools/ask-user.ts
17575
17122
  var ask_user_exports = {};
@@ -17807,10 +17354,10 @@ var SyntheticOutputTool = class {
17807
17354
  };
17808
17355
 
17809
17356
  // src/websocket-security.ts
17810
- import { randomBytes as randomBytes5, timingSafeEqual } from "crypto";
17357
+ import { randomBytes as randomBytes4, timingSafeEqual } from "crypto";
17811
17358
  var WEBSOCKET_TOKEN_PARAM = "token";
17812
17359
  function createWebSocketAccessToken() {
17813
- return randomBytes5(32).toString("base64url");
17360
+ return randomBytes4(32).toString("base64url");
17814
17361
  }
17815
17362
  function tokensEqual(expected, provided) {
17816
17363
  if (!provided) {
@@ -17867,7 +17414,7 @@ function addWebSocketToken(url, accessToken) {
17867
17414
  }
17868
17415
 
17869
17416
  // src/remote/server.ts
17870
- var log29 = createChildLogger({ module: "remote" });
17417
+ var log28 = createChildLogger({ module: "remote" });
17871
17418
  var requestCounter = 0;
17872
17419
  function nextRequestId(prefix) {
17873
17420
  requestCounter += 1;
@@ -17903,10 +17450,10 @@ var CodeReviewStartSchema = z19.object({
17903
17450
  commit: z19.string().optional(),
17904
17451
  excludePatterns: z19.array(z19.string()).optional()
17905
17452
  });
17906
- var FE_DIST = [
17907
- join20(import.meta.dirname, "fe", "dist"),
17908
- join20(import.meta.dirname, "..", "fe", "dist")
17909
- ].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));
17910
17457
  var MIME_TYPES = {
17911
17458
  ".html": "text/html; charset=utf-8",
17912
17459
  ".js": "application/javascript; charset=utf-8",
@@ -17918,15 +17465,15 @@ var MIME_TYPES = {
17918
17465
  ".woff2": "font/woff2"
17919
17466
  };
17920
17467
  function serveStatic(path) {
17921
- if (!FE_DIST) {
17468
+ if (!BROWSER_DIST) {
17922
17469
  return null;
17923
17470
  }
17924
17471
  const cleanPath = normalize(path).replace(/^(\.\.[/\\])+/, "");
17925
- const fullPath = join20(FE_DIST, cleanPath);
17926
- if (!fullPath.startsWith(FE_DIST)) {
17472
+ const fullPath = join20(BROWSER_DIST, cleanPath);
17473
+ if (!fullPath.startsWith(BROWSER_DIST)) {
17927
17474
  return null;
17928
17475
  }
17929
- if (!existsSync14(fullPath) || !statSync10(fullPath).isFile()) {
17476
+ if (!existsSync13(fullPath) || !statSync10(fullPath).isFile()) {
17930
17477
  return null;
17931
17478
  }
17932
17479
  const body = readFileSync12(fullPath);
@@ -18230,6 +17777,7 @@ async function createRemoteAgent(opts) {
18230
17777
  {
18231
17778
  abortSignal,
18232
17779
  backgroundTasks: false,
17780
+ agentName: options?.agentName,
18233
17781
  conversation,
18234
17782
  onPermissionRequest: options?.onPermissionRequest
18235
17783
  }
@@ -18281,6 +17829,7 @@ async function createRemoteAgent(opts) {
18281
17829
  forkConv.addUserMessage(prompt);
18282
17830
  const forkTaskManager = new TaskManager();
18283
17831
  const agent2 = new Agent({
17832
+ agentName: "fork",
18284
17833
  client: forkClient,
18285
17834
  registry: forkRegistry,
18286
17835
  checker,
@@ -18343,7 +17892,7 @@ async function createRemoteAgent(opts) {
18343
17892
  }
18344
17893
  }
18345
17894
  for (const { serverName, error } of result.errors) {
18346
- log29.error({ serverName, error }, "MCP server connection error");
17895
+ log28.error({ serverName, error }, "MCP server connection error");
18347
17896
  }
18348
17897
  if (result.tools.length > 0) {
18349
17898
  decideAndApply(
@@ -18430,7 +17979,7 @@ var RemoteServer = class {
18430
17979
  compactController = null;
18431
17980
  reviewController = null;
18432
17981
  turnCount = 0;
18433
- eventLogger = new AgentEventLogger(log29);
17982
+ eventLogger = new AgentEventLogger(log28);
18434
17983
  /** Resolves run() once stop() has completed; run() blocks on it. */
18435
17984
  stoppedResolve = null;
18436
17985
  /** Last pong timestamp per client; drives the heartbeat sweep. */
@@ -18524,12 +18073,12 @@ var RemoteServer = class {
18524
18073
  try {
18525
18074
  raw = JSON.parse(data.toString("utf-8"));
18526
18075
  } catch {
18527
- log29.warn("received non-JSON WebSocket message");
18076
+ log28.warn("received non-JSON WebSocket message");
18528
18077
  return;
18529
18078
  }
18530
18079
  const parsed = WsInboundSchema.safeParse(raw);
18531
18080
  if (!parsed.success) {
18532
- log29.warn("received malformed WS message");
18081
+ log28.warn("received malformed WS message");
18533
18082
  return;
18534
18083
  }
18535
18084
  void this.handleWsMessage(ws, parsed.data);
@@ -18583,7 +18132,7 @@ var RemoteServer = class {
18583
18132
  await this.handleUserMessage(parsed.data.content);
18584
18133
  }
18585
18134
  } else {
18586
- log29.warn("dropping malformed user_message");
18135
+ log28.warn("dropping malformed user_message");
18587
18136
  }
18588
18137
  break;
18589
18138
  }
@@ -18595,7 +18144,7 @@ var RemoteServer = class {
18595
18144
  parsed.data.feedback
18596
18145
  );
18597
18146
  } else {
18598
- log29.warn({ issues: parsed.error.issues }, "malformed plan approval");
18147
+ log28.warn({ issues: parsed.error.issues }, "malformed plan approval");
18599
18148
  }
18600
18149
  break;
18601
18150
  }
@@ -18604,7 +18153,7 @@ var RemoteServer = class {
18604
18153
  if (parsed.success) {
18605
18154
  await this.handleCodeReviewStart(parsed.data);
18606
18155
  } else {
18607
- log29.warn(
18156
+ log28.warn(
18608
18157
  { issues: parsed.error.issues },
18609
18158
  "malformed code review request"
18610
18159
  );
@@ -18642,7 +18191,7 @@ var RemoteServer = class {
18642
18191
  break;
18643
18192
  }
18644
18193
  default:
18645
- log29.warn({ type: msg.type }, "unknown WS message type");
18194
+ log28.warn({ type: msg.type }, "unknown WS message type");
18646
18195
  }
18647
18196
  }
18648
18197
  /**
@@ -18694,7 +18243,7 @@ var RemoteServer = class {
18694
18243
  this.broadcast({ type: "commands", data: this.buildCommandList() });
18695
18244
  return handle;
18696
18245
  } catch (err) {
18697
- log29.error({ err }, "failed to initialize agent");
18246
+ log28.error({ err }, "failed to initialize agent");
18698
18247
  this.broadcast({
18699
18248
  type: "error",
18700
18249
  data: {
@@ -18758,7 +18307,7 @@ var RemoteServer = class {
18758
18307
  }
18759
18308
  }
18760
18309
  } catch (err) {
18761
- log29.error({ err }, "agent stream error");
18310
+ log28.error({ err }, "agent stream error");
18762
18311
  this.broadcast({
18763
18312
  type: "error",
18764
18313
  data: { message: err instanceof Error ? err.message : String(err) }
@@ -18991,7 +18540,7 @@ var RemoteServer = class {
18991
18540
  });
18992
18541
  }
18993
18542
  } catch (err) {
18994
- log29.error({ err }, "agent stream error in prompt command");
18543
+ log28.error({ err }, "agent stream error in prompt command");
18995
18544
  this.broadcast({
18996
18545
  type: "error",
18997
18546
  data: { message: err instanceof Error ? err.message : String(err) }
@@ -19271,7 +18820,7 @@ Investigate and design your approach. The agent will call ExitPlanMode when the
19271
18820
  });
19272
18821
  }
19273
18822
  } catch (err) {
19274
- log29.error({ err }, "agent stream error in plan command");
18823
+ log28.error({ err }, "agent stream error in plan command");
19275
18824
  this.broadcast({
19276
18825
  type: "error",
19277
18826
  data: { message: err instanceof Error ? err.message : String(err) }
@@ -19316,7 +18865,7 @@ Investigate and design your approach. The agent will call ExitPlanMode when the
19316
18865
  const planPath = getOrCreatePlanPath(handle);
19317
18866
  let planContent = "";
19318
18867
  try {
19319
- if (existsSync14(planPath)) {
18868
+ if (existsSync13(planPath)) {
19320
18869
  planContent = readFileSync12(planPath, "utf-8");
19321
18870
  }
19322
18871
  } catch {
@@ -19372,7 +18921,7 @@ Investigate and design your approach. The agent will call ExitPlanMode when the
19372
18921
  const planPath = getOrCreatePlanPath(handle);
19373
18922
  let planContent = "";
19374
18923
  try {
19375
- if (existsSync14(planPath)) {
18924
+ if (existsSync13(planPath)) {
19376
18925
  planContent = readFileSync12(planPath, "utf-8");
19377
18926
  }
19378
18927
  } catch {
@@ -19505,7 +19054,7 @@ ${report}
19505
19054
  }
19506
19055
  });
19507
19056
  } catch (err) {
19508
- log29.error({ err }, "code review failed");
19057
+ log28.error({ err }, "code review failed");
19509
19058
  this.broadcast({
19510
19059
  type: "error",
19511
19060
  data: { message: err instanceof Error ? err.message : String(err) }
@@ -19666,9 +19215,12 @@ ${report}
19666
19215
  }
19667
19216
  /** Creates the onPermissionRequest callback for agent runs. */
19668
19217
  createPermissionCallback() {
19669
- return async (toolName, args, decision, _toolCallId, signal) => {
19218
+ return async (toolName, args, decision, _toolCallId, signal, source) => {
19670
19219
  const id = nextRequestId("perm");
19671
- const desc = formatPermissionDesc(args, decision);
19220
+ const desc = [
19221
+ source ? `${source.agentName} \xB7 ${source.cwd}` : "",
19222
+ formatPermissionDesc(args, decision)
19223
+ ].filter(Boolean).join("\n");
19672
19224
  this.broadcast({
19673
19225
  type: "permission_request",
19674
19226
  data: { id, toolName, description: desc }
@@ -19779,7 +19331,7 @@ ${report}
19779
19331
  memoryEnabled: this.opts.memoryEnabled !== false
19780
19332
  });
19781
19333
  } catch (err) {
19782
- log29.warn({ err }, "agent init deferred -- will retry on first message");
19334
+ log28.warn({ err }, "agent init deferred -- will retry on first message");
19783
19335
  this.agentHandle = null;
19784
19336
  }
19785
19337
  const stopped = new Promise((resolve11) => {
@@ -19858,7 +19410,7 @@ ${report}
19858
19410
  try {
19859
19411
  await this.agentHandle.registry.dispose();
19860
19412
  } catch (error) {
19861
- log29.error({ error }, "remote tool cleanup failed");
19413
+ log28.error({ error }, "remote tool cleanup failed");
19862
19414
  }
19863
19415
  }
19864
19416
  const resolveStopped = this.stoppedResolve;
@@ -20227,7 +19779,7 @@ var YukinoA2aExecutor = class {
20227
19779
  const taskId = run2.taskId;
20228
19780
  const contextId = session.contextId;
20229
19781
  const events = run2.runtime.run(text, {
20230
- onPermissionRequest: (toolName, args, decision, toolCallId, signal) => this.requestPermission(
19782
+ onPermissionRequest: (toolName, args, decision, toolCallId, signal, source) => this.requestPermission(
20231
19783
  run2,
20232
19784
  taskId,
20233
19785
  contextId,
@@ -20235,7 +19787,8 @@ var YukinoA2aExecutor = class {
20235
19787
  args,
20236
19788
  decision,
20237
19789
  toolCallId,
20238
- signal
19790
+ signal,
19791
+ source
20239
19792
  )
20240
19793
  });
20241
19794
  void (async () => {
@@ -20256,7 +19809,7 @@ var YukinoA2aExecutor = class {
20256
19809
  this.finishRun(session, run2, taskId, contextId, failure);
20257
19810
  })();
20258
19811
  }
20259
- requestPermission(run2, taskId, contextId, toolName, args, decision, toolCallId, signal) {
19812
+ requestPermission(run2, taskId, contextId, toolName, args, decision, toolCallId, signal, source) {
20260
19813
  if (signal?.aborted || run2.canceled || run2.finished) {
20261
19814
  return Promise.resolve("deny");
20262
19815
  }
@@ -20267,7 +19820,10 @@ var YukinoA2aExecutor = class {
20267
19820
  permissionId,
20268
19821
  toolCallId,
20269
19822
  toolName,
20270
- reason: decision.reason,
19823
+ reason: [
19824
+ source ? `${source.agentName} \xB7 ${source.cwd}` : "",
19825
+ decision.reason
19826
+ ].filter(Boolean).join("\n"),
20271
19827
  args
20272
19828
  };
20273
19829
  return new Promise((resolve11) => {
@@ -20542,7 +20098,7 @@ __export(agent_exports2, {
20542
20098
  YukinoAcpAgent: () => YukinoAcpAgent,
20543
20099
  createYukinoAcpApp: () => createYukinoAcpApp
20544
20100
  });
20545
- import { existsSync as existsSync15 } from "fs";
20101
+ import { existsSync as existsSync14 } from "fs";
20546
20102
  import { isAbsolute as isAbsolute5 } from "path";
20547
20103
  import * as acp from "@agentclientprotocol/sdk";
20548
20104
 
@@ -20901,7 +20457,7 @@ var YukinoAcpAgent = class {
20901
20457
  return {};
20902
20458
  }
20903
20459
  const saved = loadSession(params.cwd, params.sessionId);
20904
- if (!session && !existsSync15(getSessionFilePath(params.cwd, params.sessionId))) {
20460
+ if (!session && !existsSync14(getSessionFilePath(params.cwd, params.sessionId))) {
20905
20461
  throw acp.RequestError.resourceNotFound(params.sessionId);
20906
20462
  }
20907
20463
  if (!session) {
@@ -21037,7 +20593,7 @@ var YukinoAcpAgent = class {
21037
20593
  let sawUsage = false;
21038
20594
  let usage = emptyUsage();
21039
20595
  for await (const event of session.runtime.run(text, {
21040
- onPermissionRequest: async (toolName, args, decision, toolCallId, requestSignal) => {
20596
+ onPermissionRequest: async (toolName, args, decision, toolCallId, requestSignal, source) => {
21041
20597
  const permissionSignal = requestSignal ?? signal;
21042
20598
  const permission = context2.client.request(
21043
20599
  acp.methods.client.session.requestPermission,
@@ -21045,17 +20601,20 @@ var YukinoAcpAgent = class {
21045
20601
  sessionId,
21046
20602
  toolCall: {
21047
20603
  toolCallId,
21048
- title: `${toolName}: ${decision.reason}`,
20604
+ title: `${source ? `${source.agentName} \xB7 ${source.cwd} \xB7 ` : ""}${toolName}: ${decision.reason}`,
21049
20605
  kind: toolKind(toolName),
21050
20606
  status: "pending",
21051
20607
  rawInput: args,
21052
- locations: toolLocations(args, session.runtime.cwd)
20608
+ locations: toolLocations(
20609
+ args,
20610
+ source?.cwd ?? session.runtime.cwd
20611
+ )
21053
20612
  },
21054
20613
  options: [
21055
20614
  { optionId: "allow", name: "Allow once", kind: "allow_once" },
21056
20615
  {
21057
20616
  optionId: "allowAlways",
21058
- name: "Always allow",
20617
+ name: "Allow pattern for all project agents",
21059
20618
  kind: "allow_always"
21060
20619
  },
21061
20620
  { optionId: "deny", name: "Reject", kind: "reject_once" }
@@ -21522,10 +21081,10 @@ var usage_tracker_exports = {};
21522
21081
  __export(usage_tracker_exports, {
21523
21082
  CommandUsageTracker: () => CommandUsageTracker
21524
21083
  });
21525
- import { readFileSync as readFileSync13, writeFileSync as writeFileSync10, mkdirSync as mkdirSync11, existsSync as existsSync16 } from "fs";
21526
- 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";
21527
21086
  import { safeParse as safeParse6, z as z21 } from "zod";
21528
- var log30 = createChildLogger({ module: "commands" });
21087
+ var log29 = createChildLogger({ module: "commands" });
21529
21088
  var UsageEntrySchema = z21.object({
21530
21089
  usageCount: z21.coerce.number(),
21531
21090
  lastUsedAt: z21.coerce.number()
@@ -21536,7 +21095,7 @@ var CommandUsageTracker = class {
21536
21095
  constructor() {
21537
21096
  const dir = getYukinoDir();
21538
21097
  this.filePath = join21(dir, "command_usage.json");
21539
- if (!existsSync16(dir)) {
21098
+ if (!existsSync15(dir)) {
21540
21099
  mkdirSync11(dir, { recursive: true });
21541
21100
  }
21542
21101
  this.load();
@@ -21578,13 +21137,13 @@ var CommandUsageTracker = class {
21578
21137
  }
21579
21138
  save() {
21580
21139
  try {
21581
- mkdirSync11(dirname9(this.filePath), { recursive: true });
21140
+ mkdirSync11(dirname8(this.filePath), { recursive: true });
21582
21141
  writeFileSync10(
21583
21142
  this.filePath,
21584
21143
  JSON.stringify(Object.fromEntries(this.usage), null, 2)
21585
21144
  );
21586
21145
  } catch (err) {
21587
- log30.error({ err }, "commands operation failed");
21146
+ log29.error({ err }, "commands operation failed");
21588
21147
  }
21589
21148
  }
21590
21149
  };
@@ -21605,7 +21164,7 @@ __export(history_exports, {
21605
21164
  load: () => load
21606
21165
  });
21607
21166
  import {
21608
- existsSync as existsSync17,
21167
+ existsSync as existsSync16,
21609
21168
  mkdirSync as mkdirSync12,
21610
21169
  readFileSync as readFileSync14,
21611
21170
  renameSync as renameSync6,
@@ -21613,13 +21172,13 @@ import {
21613
21172
  writeFileSync as writeFileSync11
21614
21173
  } from "fs";
21615
21174
  import { parse as parse6, z as z22 } from "zod";
21616
- var log31 = createChildLogger({ module: "history" });
21175
+ var log30 = createChildLogger({ module: "history" });
21617
21176
  var MAX_HISTORY_ENTRIES = 1e4;
21618
21177
  var FILENAME = "prompt_history.jsonl";
21619
21178
  var JSONLSchema = z22.looseObject({ text: z22.string() });
21620
21179
  function load() {
21621
21180
  const filePath = yukinoPath(FILENAME);
21622
- if (!existsSync17(filePath)) {
21181
+ if (!existsSync16(filePath)) {
21623
21182
  return [];
21624
21183
  }
21625
21184
  try {
@@ -21630,12 +21189,12 @@ function load() {
21630
21189
  const { text } = parse6(JSONLSchema, entry);
21631
21190
  return text;
21632
21191
  } catch (err) {
21633
- log31.error({ err }, "parse history line failed");
21192
+ log30.error({ err }, "parse history line failed");
21634
21193
  return "";
21635
21194
  }
21636
21195
  }).filter(Boolean).slice(-MAX_HISTORY_ENTRIES);
21637
21196
  } catch (err2) {
21638
- log31.error({ err: err2 }, "load history failed");
21197
+ log30.error({ err: err2 }, "load history failed");
21639
21198
  return [];
21640
21199
  }
21641
21200
  }
@@ -21883,7 +21442,7 @@ import {
21883
21442
  import { homedir as homedir2 } from "os";
21884
21443
  import { join as join22, resolve as resolve9 } from "path";
21885
21444
  import yaml4 from "js-yaml";
21886
- var log32 = createChildLogger({ module: "skills" });
21445
+ var log31 = createChildLogger({ module: "skills" });
21887
21446
  var MAX_SKILL_DOWNLOAD_BYTES = 1024 * 1024;
21888
21447
  async function readSkillResponse(response, signal) {
21889
21448
  const contentLength = Number(response.headers.get("content-length"));
@@ -22057,7 +21616,7 @@ ${parsed.body}
22057
21616
  isError: false
22058
21617
  };
22059
21618
  } catch (err) {
22060
- log32.error({ err }, "skills operation failed");
21619
+ log31.error({ err }, "skills operation failed");
22061
21620
  return {
22062
21621
  output: `Error installing skill: ${asErrorString(err)}`,
22063
21622
  isError: true
@@ -22089,6 +21648,7 @@ __export(tools_exports3, {
22089
21648
  EditFile: () => edit_file_exports,
22090
21649
  EditFileDiagnostics: () => edit_file_diagnostics_exports,
22091
21650
  EnterWorktree: () => enter_worktree_exports,
21651
+ ExecutionCoordinator: () => execution_coordinator_exports,
22092
21652
  ExitCodeHints: () => exit_code_hints_exports,
22093
21653
  ExitPlanMode: () => exit_plan_mode_exports,
22094
21654
  ExitWorktree: () => exit_worktree_exports,
@@ -22143,7 +21703,7 @@ __export(install_exports, {
22143
21703
  });
22144
21704
  import { execFile as execFile4, spawn as spawn6 } from "child_process";
22145
21705
  import { readFileSync as readFileSync16, realpathSync as realpathSync2 } from "fs";
22146
- 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";
22147
21707
  import { fileURLToPath } from "url";
22148
21708
  import { z as z25 } from "zod";
22149
21709
 
@@ -22256,7 +21816,7 @@ function packageManagerInvocation(command, args, platform2 = process.platform) {
22256
21816
  };
22257
21817
  }
22258
21818
  function getPackageDirectory() {
22259
- let directory = dirname10(fileURLToPath(import.meta.url));
21819
+ let directory = dirname9(fileURLToPath(import.meta.url));
22260
21820
  while (true) {
22261
21821
  try {
22262
21822
  const data = JSON.parse(
@@ -22267,7 +21827,7 @@ function getPackageDirectory() {
22267
21827
  }
22268
21828
  } catch {
22269
21829
  }
22270
- const parent = dirname10(directory);
21830
+ const parent = dirname9(directory);
22271
21831
  if (parent === directory) {
22272
21832
  throw new Error("Could not locate the Yukino installation.");
22273
21833
  }
@@ -22311,11 +21871,11 @@ async function getSelfUpdateCommand(latest, packageDirectory = getPackageDirecto
22311
21871
  });
22312
21872
  } catch {
22313
21873
  }
22314
- const npmRoot = dirname10(dirname10(packageDirectory));
22315
- 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;
22316
21876
  const roots = [globalRoot, ...inferredNpmPrefix ? [npmRoot] : []];
22317
21877
  if (command === "pnpm" && globalRoot) {
22318
- roots.push(dirname10(globalRoot));
21878
+ roots.push(dirname9(globalRoot));
22319
21879
  }
22320
21880
  if (!roots.some((root) => root && isInside(packageDirectory, root))) {
22321
21881
  throw new Error(
@@ -22446,7 +22006,7 @@ import { readdir, readFile as readFile8 } from "fs/promises";
22446
22006
  import { homedir as homedir3 } from "os";
22447
22007
  import { join as join24, resolve as resolve10, sep as sep4 } from "path";
22448
22008
  import { z as z26 } from "zod";
22449
- var log33 = createChildLogger({ module: "vscode" });
22009
+ var log32 = createChildLogger({ module: "vscode" });
22450
22010
  var LockfileSchema = z26.object({
22451
22011
  workspaceFolders: z26.array(z26.string()).optional(),
22452
22012
  pid: z26.number().optional(),
@@ -22488,7 +22048,7 @@ async function readLockfile(dir, filename) {
22488
22048
  pid: parsed.pid
22489
22049
  };
22490
22050
  } catch (err) {
22491
- log33.error({ err, filename }, "failed to read IDE lockfile");
22051
+ log32.error({ err, filename }, "failed to read IDE lockfile");
22492
22052
  return null;
22493
22053
  }
22494
22054
  }
@@ -22612,7 +22172,7 @@ var WebSocketTransport = class {
22612
22172
  };
22613
22173
 
22614
22174
  // src/vscode/ide-client.ts
22615
- var log34 = createChildLogger({ module: "vscode" });
22175
+ var log33 = createChildLogger({ module: "vscode" });
22616
22176
  var AtMentionedSchema = z27.object({
22617
22177
  method: z27.literal("at_mentioned"),
22618
22178
  params: z27.object({
@@ -22654,7 +22214,7 @@ async function connectToIde(opts) {
22654
22214
  } catch (err) {
22655
22215
  await client.close().catch(() => void 0);
22656
22216
  if (!opts.signal?.aborted) {
22657
- log34.error({ err, url: ide.url }, "failed to connect to IDE extension");
22217
+ log33.error({ err, url: ide.url }, "failed to connect to IDE extension");
22658
22218
  }
22659
22219
  return null;
22660
22220
  }
@@ -22680,7 +22240,7 @@ async function connectToIde(opts) {
22680
22240
  params: { pid: process.pid }
22681
22241
  });
22682
22242
  } catch (err) {
22683
- log34.error({ err }, "failed to send ide_connected notification");
22243
+ log33.error({ err }, "failed to send ide_connected notification");
22684
22244
  }
22685
22245
  return {
22686
22246
  ideName: ide.ideName,
@@ -22689,7 +22249,7 @@ async function connectToIde(opts) {
22689
22249
  try {
22690
22250
  await client.close();
22691
22251
  } catch (err) {
22692
- log34.error({ err }, "failed to close IDE client");
22252
+ log33.error({ err }, "failed to close IDE client");
22693
22253
  }
22694
22254
  }
22695
22255
  };
@@ -22851,6 +22411,7 @@ async function runPrintMode(args) {
22851
22411
  modelOverride,
22852
22412
  context2?.permissionChecker,
22853
22413
  {
22414
+ agentName: "fork",
22854
22415
  conversation,
22855
22416
  abortSignal: context2?.abortSignal,
22856
22417
  onPermissionRequest: context2?.onPermissionRequest
@@ -22875,7 +22436,13 @@ async function runPrintMode(args) {
22875
22436
  options?.modelOverride,
22876
22437
  teamChecker,
22877
22438
  // Teammates stay purely foreground: see SubagentRunOptions.backgroundTasks.
22878
- { abortSignal, backgroundTasks: false, conversation }
22439
+ {
22440
+ abortSignal,
22441
+ backgroundTasks: false,
22442
+ conversation,
22443
+ agentName: options?.agentName,
22444
+ onPermissionRequest: options?.onPermissionRequest
22445
+ }
22879
22446
  );
22880
22447
  }
22881
22448
  );
@@ -23190,430 +22757,6 @@ function recover() {
23190
22757
  recordExit(code);
23191
22758
  });
23192
22759
  }
23193
-
23194
- // src/teammate.ts
23195
- var teammate_exports = {};
23196
- __export(teammate_exports, {
23197
- buildTeammateRegistry: () => buildTeammateRegistry,
23198
- parseTeammateFlags: () => parseTeammateFlags,
23199
- runTeammate: () => runTeammate
23200
- });
23201
- import { basename as basename6, dirname as dirname11, join as join25 } from "path";
23202
- function parseTeammateFlags(args) {
23203
- if (!args.includes("--teammate")) {
23204
- return null;
23205
- }
23206
- let teamDir2 = "";
23207
- let teamCwd;
23208
- let teamName = "";
23209
- let memberName = "";
23210
- let initialTask = "";
23211
- let providerIndex;
23212
- let permissionMode;
23213
- let agentType;
23214
- let model;
23215
- for (let i = 0; i < args.length; i++) {
23216
- if (args[i] === "--team-dir" && args[i + 1]) {
23217
- teamDir2 = args[++i];
23218
- } else if (args[i] === "--team-cwd" && args[i + 1]) {
23219
- teamCwd = args[++i];
23220
- } else if (args[i] === "--agent-type" && args[i + 1]) {
23221
- agentType = args[++i];
23222
- } else if (args[i] === "--model" && args[i + 1]) {
23223
- model = args[++i];
23224
- } else if (args[i] === "--team-name" && args[i + 1]) {
23225
- teamName = args[++i];
23226
- } else if (args[i] === "--member-name" && args[i + 1]) {
23227
- memberName = args[++i];
23228
- } else if (args[i] === "--task" && args[i + 1]) {
23229
- initialTask = args[++i];
23230
- } else if (args[i] === "--provider-index" && args[i + 1]) {
23231
- providerIndex = Number(args[++i]);
23232
- } else if (args[i] === "--permission-mode") {
23233
- const mode2 = args[++i];
23234
- if (mode2 !== "default" && mode2 !== "acceptEdits" && mode2 !== "plan" && mode2 !== "bypassPermissions") {
23235
- throw new Error("Invalid teammate --permission-mode.");
23236
- }
23237
- permissionMode = mode2;
23238
- }
23239
- }
23240
- if (!permissionMode) {
23241
- throw new Error("Teammate --permission-mode is required.");
23242
- }
23243
- if (!teamName) {
23244
- const leaf = basename6(teamDir2);
23245
- teamName = leaf === "inboxes" ? basename6(dirname11(teamDir2)) : leaf;
23246
- }
23247
- return {
23248
- teamDir: teamDir2,
23249
- ...teamCwd ? { teamCwd } : {},
23250
- ...agentType ? { agentType } : {},
23251
- ...model ? { model } : {},
23252
- teamName,
23253
- memberName,
23254
- initialTask,
23255
- providerIndex,
23256
- permissionMode
23257
- };
23258
- }
23259
- var LEADER_LOST_EXIT_MS = 6e4;
23260
- var log35 = createChildLogger({ module: "teammate" });
23261
- function isPidAlive2(pid) {
23262
- try {
23263
- process.kill(pid, 0);
23264
- return true;
23265
- } catch (err) {
23266
- return err instanceof Error && "code" in err && err.code === "EPERM";
23267
- }
23268
- }
23269
- function createIdleNotification(memberName) {
23270
- return `[idle] ${memberName} has completed their task and is waiting for new instructions.`;
23271
- }
23272
- async function buildTeammateRegistry(opts) {
23273
- const mcpServers = opts.mcpServers ?? [];
23274
- const mgr = opts.mcpManager;
23275
- if (mcpServers.length > 0 && !mgr) {
23276
- throw new Error(
23277
- "A teammate host must own the MCP manager and disconnect it on exit"
23278
- );
23279
- }
23280
- const registry = createToolRegistry(opts.cwd, new TaskList(), {
23281
- interactionMode: "interactive",
23282
- lspServers: opts.lspServers
23283
- });
23284
- await configureBashSandbox(registry, opts.cwd, opts.sandboxConfig);
23285
- registry.register(new SyntheticOutputTool());
23286
- registry.register(new LoadSkillTool(opts.catalog, opts.skillHost));
23287
- registry.register(new InstallSkillTool(opts.cwd, opts.catalog));
23288
- const teamManager = new TeamManager(opts.teamCwd ?? opts.cwd, {
23289
- // This process is a teammate, not the leader: leave the recorded
23290
- // leaderPid in config.json alone so other teammates (and this one) can
23291
- // keep using it for liveness checks.
23292
- claimLeadership: false
23293
- });
23294
- teamManager.get(opts.teamName);
23295
- registry.register(new SendMessageTool(teamManager, opts.memberName));
23296
- registry.register(
23297
- new TeamTaskCreateTool(teamManager, opts.teamName, opts.memberName)
23298
- );
23299
- registry.register(new TeamTaskGetTool(teamManager, opts.teamName));
23300
- registry.register(new TeamTaskListTool(teamManager, opts.teamName));
23301
- registry.register(
23302
- new TeamTaskUpdateTool(teamManager, opts.teamName, opts.memberName)
23303
- );
23304
- if (mcpServers.length > 0 && mgr) {
23305
- try {
23306
- const result = await mgr.connectAll(mcpServers);
23307
- for (const { serverName, tool } of result.tools) {
23308
- const client = mgr.getClient(serverName);
23309
- if (client) {
23310
- registry.register(new MCPToolWrapper(client, serverName, tool));
23311
- }
23312
- }
23313
- for (const { serverName, error } of result.errors) {
23314
- log35.error({ serverName, error }, "MCP connection error");
23315
- }
23316
- if (result.tools.length > 0 && opts.contextWindow) {
23317
- decideAndApply(
23318
- registry,
23319
- opts.baseUrl ?? "",
23320
- opts.protocol ?? "anthropic",
23321
- opts.contextWindow
23322
- );
23323
- }
23324
- } catch (err) {
23325
- log35.error({ err }, "MCP setup failed");
23326
- }
23327
- }
23328
- const filtered = filterToolsForAgent(
23329
- registry,
23330
- opts.definition?.tools,
23331
- opts.definition?.disallowedTools,
23332
- false
23333
- );
23334
- for (const name of [
23335
- "SendMessage",
23336
- "TaskCreate",
23337
- "TaskGet",
23338
- "TaskList",
23339
- "TaskUpdate"
23340
- ]) {
23341
- const tool = registry.get(name);
23342
- if (tool) {
23343
- filtered.register(tool);
23344
- }
23345
- }
23346
- filtered.takeOwnershipFrom(registry);
23347
- await registry.dispose();
23348
- return filtered;
23349
- }
23350
- async function runTeammate(args) {
23351
- const safeMemberName = sanitizeNameSegment(args.memberName);
23352
- initLogger({
23353
- sessionId: `teammate-${safeMemberName}-${Date.now().toString(36)}`,
23354
- mode: "teammate",
23355
- logDir: join25(dirname11(args.teamDir), "logs"),
23356
- skipCleanup: true
23357
- });
23358
- process.on("exit", closeLogger);
23359
- let mcpManager;
23360
- let registry;
23361
- let controlTimer;
23362
- let shutdownReply;
23363
- let failureReported = false;
23364
- let failure;
23365
- const configPath = join25(dirname11(args.teamDir), "config.json");
23366
- let hadTeamConfig = readTeamFileAtPath(configPath) !== null;
23367
- const controller = new AbortController();
23368
- const abort = () => {
23369
- controller.abort();
23370
- };
23371
- process.on("SIGINT", abort);
23372
- process.on("SIGTERM", abort);
23373
- process.on("SIGHUP", abort);
23374
- try {
23375
- registerTeammateProcess(
23376
- join25(dirname11(args.teamDir), "config.json"),
23377
- args.memberName,
23378
- process.pid
23379
- );
23380
- const cwd2 = process.cwd();
23381
- const cfg = withProjectMcpServers(loadConfig(), cwd2);
23382
- const configuredProvider = args.providerIndex === void 0 ? resolveDefaultProvider(cfg.providers, cfg.default_provider) : cfg.providers[args.providerIndex];
23383
- if (!configuredProvider) {
23384
- throw new Error(
23385
- `Provider at index ${args.providerIndex} is not configured.`
23386
- );
23387
- }
23388
- const definition = loadAgentDefinitions().find(
23389
- (entry) => entry.name === (args.agentType ?? "general-purpose")
23390
- );
23391
- if (!definition) {
23392
- throw new Error(`Unknown teammate agent type '${args.agentType}'.`);
23393
- }
23394
- const provider = {
23395
- ...configuredProvider,
23396
- model: args.model ?? definition.model ?? configuredProvider.model
23397
- };
23398
- const conversation = new ConversationManager();
23399
- conversation.addSystemReminder(buildSubagentInstructions(definition));
23400
- const catalog = new SkillCatalog();
23401
- catalog.load(cwd2);
23402
- const skillHost = {
23403
- activateSkill: (name, body) => {
23404
- conversation.addSystemReminder(
23405
- `<skill-name>${name}</skill-name>
23406
- ${body}`
23407
- );
23408
- }
23409
- };
23410
- const env = detectEnvironment(cwd2);
23411
- env.model = provider.model;
23412
- const systemPrompt = definition.systemPromptOverride ?? buildSystemPrompt(env);
23413
- const client = await createClient(provider, systemPrompt);
23414
- if (cfg.mcp_servers?.length) {
23415
- mcpManager = new MCPManager();
23416
- }
23417
- registry = await buildTeammateRegistry({
23418
- cwd: cwd2,
23419
- teamCwd: args.teamCwd,
23420
- definition,
23421
- teamName: args.teamName,
23422
- memberName: args.memberName,
23423
- catalog,
23424
- skillHost,
23425
- mcpServers: cfg.mcp_servers,
23426
- lspServers: cfg.lsp_servers,
23427
- sandboxConfig: cfg.sandbox,
23428
- mcpManager,
23429
- baseUrl: provider.base_url,
23430
- protocol: provider.protocol,
23431
- contextWindow: getContextWindow(provider)
23432
- });
23433
- const checker = new PermissionChecker(
23434
- cwd2,
23435
- args.permissionMode,
23436
- () => readTeamFileAtPath(join25(dirname11(args.teamDir), "config.json"))?.permissionMode ?? args.permissionMode
23437
- );
23438
- checker.teammate = true;
23439
- checker.sandboxEnabled = cfg.sandbox?.enabled ?? false;
23440
- checker.sandboxAutoAllow = cfg.sandbox?.auto_allow ?? false;
23441
- checker.planModeLocked = definition.permissionMode === "plan";
23442
- const agent2 = new Agent({
23443
- client,
23444
- registry,
23445
- checker,
23446
- conversation,
23447
- cwd: cwd2,
23448
- fileStateCache: new FileStateCache(),
23449
- skillSection: buildSkillSection(catalog),
23450
- instructions: loadInstructions(cwd2),
23451
- contextWindow: getContextWindow(provider),
23452
- maxOutput: getMaxOutputTokens(provider),
23453
- maxIterations: definition.maxTurns ?? 200,
23454
- abortSignal: controller.signal
23455
- });
23456
- conversation.addUserMessage(
23457
- buildTeammatePrompt(args.teamName, args.memberName, args.initialTask)
23458
- );
23459
- const mailbox = new FileMailbox(args.teamDir, args.memberName);
23460
- const leaderMailbox = new FileMailbox(args.teamDir, LEADER_NAME);
23461
- let leaderDeadSince = 0;
23462
- controlTimer = setInterval(() => {
23463
- try {
23464
- const shutdown2 = mailbox.receiveMatchingSync(isShutdownRequest)[0];
23465
- if (shutdown2) {
23466
- const response = shutdownResponse(
23467
- args.memberName,
23468
- shutdown2.requestId ?? "",
23469
- true,
23470
- "acknowledged, shutting down"
23471
- );
23472
- shutdownReply = leaderMailbox.send(
23473
- args.memberName,
23474
- response.text,
23475
- response
23476
- );
23477
- controller.abort();
23478
- return;
23479
- }
23480
- const config = readTeamFileAtPath(configPath);
23481
- if (config) {
23482
- hadTeamConfig = true;
23483
- }
23484
- const lost = hadTeamConfig && !config || config?.leaderPid && !isPidAlive2(config.leaderPid);
23485
- if (lost) {
23486
- if (!leaderDeadSince) {
23487
- leaderDeadSince = Date.now();
23488
- }
23489
- if (!config || Date.now() - leaderDeadSince > LEADER_LOST_EXIT_MS) {
23490
- controller.abort();
23491
- }
23492
- } else {
23493
- leaderDeadSince = 0;
23494
- }
23495
- } catch (err) {
23496
- log35.error({ err }, "teammate control poll failed");
23497
- }
23498
- }, 2e3);
23499
- const notifyIdle = () => leaderMailbox.send(
23500
- args.memberName,
23501
- createIdleNotification(args.memberName)
23502
- );
23503
- const notifyFailed = (err) => {
23504
- failureReported = true;
23505
- failure = err;
23506
- return Promise.resolve();
23507
- };
23508
- for await (const event of agent2.run()) {
23509
- switch (event.type) {
23510
- case "stream_text":
23511
- process.stdout.write(event.text);
23512
- break;
23513
- case "tool_result":
23514
- console.log(
23515
- `[${event.toolName}] ${event.isError ? "ERROR" : "OK"} (${event.elapsed.toFixed(1)}s)`
23516
- );
23517
- break;
23518
- case "loop_complete":
23519
- console.log("--- Task complete ---");
23520
- break;
23521
- case "error":
23522
- log35.error({ err: event.error }, "agent error");
23523
- await notifyFailed(event.error);
23524
- throw event.error;
23525
- }
23526
- }
23527
- if (controller.signal.aborted) {
23528
- return;
23529
- }
23530
- await notifyIdle();
23531
- polling: while (!controller.signal.aborted) {
23532
- const batch = await mailbox.receive();
23533
- for (const [i, msg] of batch.entries()) {
23534
- if (isShutdownRequest(msg)) {
23535
- mailbox.requeue(batch.slice(i + 1));
23536
- const response = shutdownResponse(
23537
- args.memberName,
23538
- msg.requestId ?? "",
23539
- true,
23540
- "acknowledged, shutting down"
23541
- );
23542
- await leaderMailbox.send(args.memberName, response.text, response);
23543
- console.log(`Shutdown requested, ${args.memberName} exiting.`);
23544
- break polling;
23545
- }
23546
- console.log(`Message from ${msg.from}: ${msg.text}`);
23547
- conversation.addUserMessage(`From ${msg.from}: ${msg.text}`);
23548
- for await (const event of agent2.run()) {
23549
- if (event.type === "stream_text") {
23550
- process.stdout.write(event.text);
23551
- } else if (event.type === "error") {
23552
- log35.error({ err: event.error }, "agent error");
23553
- await notifyFailed(event.error);
23554
- throw event.error;
23555
- }
23556
- }
23557
- if (controller.signal.aborted) {
23558
- mailbox.requeue(batch.slice(i + 1));
23559
- break polling;
23560
- }
23561
- const moreMessages = batch.length > i + 1;
23562
- if (!moreMessages && mailbox.unreadCount() === 0) {
23563
- await notifyIdle();
23564
- }
23565
- }
23566
- await new Promise((r) => setTimeout(r, 2e3));
23567
- }
23568
- } catch (error) {
23569
- failureReported = true;
23570
- failure = error;
23571
- throw error;
23572
- } finally {
23573
- clearInterval(controlTimer);
23574
- controller.abort();
23575
- const results = await Promise.allSettled([
23576
- shutdownReply,
23577
- registry?.dispose(),
23578
- mcpManager?.disconnectAll()
23579
- ]);
23580
- for (const result of results) {
23581
- if (result.status === "rejected") {
23582
- log35.error({ err: result.reason }, "teammate resource cleanup failed");
23583
- }
23584
- }
23585
- try {
23586
- const configExists = readTeamFileAtPath(configPath) !== null;
23587
- if (configExists || !hadTeamConfig) {
23588
- let releaseSummary = "";
23589
- if (configExists) {
23590
- try {
23591
- const released = new SharedTaskStore(
23592
- join25(dirname11(args.teamDir), "tasks.json")
23593
- ).releaseOwner(args.memberName);
23594
- if (released.length) {
23595
- releaseSummary = `; unassigned tasks: ${released.map((task) => `#${task.id}`).join(", ")}`;
23596
- }
23597
- } catch (error) {
23598
- log35.error({ error }, "teammate task release failed");
23599
- releaseSummary = "; task release failed: inspect the shared board before reassignment";
23600
- }
23601
- }
23602
- await new FileMailbox(args.teamDir, LEADER_NAME).send(
23603
- args.memberName,
23604
- `${failureReported ? `[idle] ${args.memberName} failed: ${failure instanceof Error ? failure.message : String(failure)}` : `[idle] ${args.memberName} (reason: stopped)`}${releaseSummary}`
23605
- );
23606
- }
23607
- } catch (error) {
23608
- log35.error({ error }, "teammate exit notification failed");
23609
- }
23610
- process.off("SIGINT", abort);
23611
- process.off("SIGTERM", abort);
23612
- process.off("SIGHUP", abort);
23613
- process.off("exit", closeLogger);
23614
- closeLogger();
23615
- }
23616
- }
23617
22760
  export {
23618
22761
  a2a_exports as A2a,
23619
22762
  acp_exports as Acp,
@@ -23644,7 +22787,6 @@ export {
23644
22787
  session_exports as Session,
23645
22788
  skills_exports as Skills,
23646
22789
  subagent_exports as Subagent,
23647
- teammate_exports as Teammate,
23648
22790
  teams_exports as Teams,
23649
22791
  telemetry_exports as Telemetry,
23650
22792
  todo_exports as Todo,