pi-better-subagents 0.25.0 → 0.26.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.ts CHANGED
@@ -34,6 +34,8 @@ import {
34
34
  import { spawnDetached, killProcessTree, type SpawnResult } from "./spawn.ts";
35
35
  import { parseRun, readRunTranscript, resetParseRunCursor, type Usage } from "./parse.ts";
36
36
  import { finalizeRun as finalizeRunCore } from "./finalization.ts";
37
+ import { selectSessionByName } from "./session-selection.ts";
38
+ import { isWithinWorkspace } from "./workspace-scope.ts";
37
39
  import { loadConfig, writeDelegationMode, writeSubagentSettings, isConcurrencyCap, normalizeConcurrencyCap, normalizeTools, resolveExtensionPath, selfDir, SAFE_DEFAULT_TOOLS, SAFE_CLEAN_TOOLS } from "./config.ts";
38
40
  import { createSubagentSettingsPage } from "./settings-page.ts";
39
41
  import { effectiveSubagentSettings, formatSubagentSettings, subagentSettingsTool, SUBAGENT_SETTINGS_CONTEXT } from "./effective-settings.ts";
@@ -152,11 +154,7 @@ import {
152
154
  acquireConversationLease,
153
155
  assertContinuationExtensions,
154
156
  buildLaunchRecipe,
155
- markRetentionReleased,
156
157
  planContinuation,
157
- planRetentionRelease,
158
- refreshRetentionForAttempt,
159
- retainConversation,
160
158
  type ContinuationPlan,
161
159
  type ConversationLease,
162
160
  } from "./continuation.ts";
@@ -201,8 +199,6 @@ export function subagentsArgumentCompletions(argumentPrefix: string): Autocomple
201
199
  const SUBAGENT_TOOLS = [
202
200
  "subagent_spawn",
203
201
  "subagent_spawn_batch",
204
- "subagent_resume",
205
- "subagent_release",
206
202
  "subagent_list",
207
203
  "subagent_settings",
208
204
  "subagent_output",
@@ -1486,7 +1482,7 @@ function revalidateContinuationUnderLease(
1486
1482
  if (!current) {
1487
1483
  throw new ContinuationError(
1488
1484
  `Cannot continue ${plan.prior.id}: its run record was removed while this launch was being prepared. ` +
1489
- `Retained history lives in temporary storage and can be removed; launch a new run instead.`,
1485
+ `Its saved history is missing; restore the original history or launch a new run instead.`,
1490
1486
  );
1491
1487
  }
1492
1488
  const fresh = planContinuation({
@@ -1503,6 +1499,131 @@ function revalidateContinuationUnderLease(
1503
1499
  }
1504
1500
  }
1505
1501
 
1502
+ /**
1503
+ * The removed launch flag, reported by name so an older caller is told what to
1504
+ * do instead of having its request silently dropped.
1505
+ */
1506
+ const RETAIN_SESSION_REMOVED =
1507
+ "retain_session was removed: every saved conversation persists automatically. " +
1508
+ "Omit it, and pass session_id to continue a saved conversation.";
1509
+
1510
+ function assertNoRetiredLaunchOptions(value: object | undefined, label = ""): void {
1511
+ if (value && (value as { retain_session?: unknown }).retain_session !== undefined) {
1512
+ throw new Error(`${label}${RETAIN_SESSION_REMOVED}`);
1513
+ }
1514
+ }
1515
+
1516
+ function sameLaunchPath(left: unknown, right: string | undefined): boolean {
1517
+ if (typeof left !== "string" || right === undefined) return false;
1518
+ if (left === right) return true;
1519
+ try { return canonicalizePath(left) === canonicalizePath(right); } catch { return false; }
1520
+ }
1521
+
1522
+ function sameLaunchTools(left: unknown, right: string): boolean {
1523
+ return typeof left === "string" && normalizeTools(left) === normalizeTools(right);
1524
+ }
1525
+
1526
+ function sameLaunchRoles(left: unknown, right: string | readonly string[] | undefined): boolean {
1527
+ if (typeof left === "string") return left === right;
1528
+ if (Array.isArray(left) && Array.isArray(right)) {
1529
+ return left.length === right.length && left.every((value, index) => value === right[index]);
1530
+ }
1531
+ return false;
1532
+ }
1533
+
1534
+ function continuationLaunchConflicts(
1535
+ job: Record<string, unknown>,
1536
+ recipe: ContinuationPlan["recipe"],
1537
+ options: { includeName: boolean },
1538
+ ): string[] {
1539
+ const conflicts: string[] = [];
1540
+ const check = (key: string, same: (value: unknown) => boolean) => {
1541
+ const value = job[key];
1542
+ if (value !== undefined && !same(value)) conflicts.push(key);
1543
+ };
1544
+ if (options.includeName) check("name", (value) => value === recipe.name);
1545
+ check("agent", (value) => value === recipe.agent);
1546
+ check("role", (value) => sameLaunchRoles(value, recipe.role));
1547
+ check("alias", (value) => value === recipe.alias);
1548
+ check("tools", (value) => sameLaunchTools(value, recipe.tools));
1549
+ check("exclude_tools", (value) => typeof value === "string" && normalizeTools(value) === normalizeTools(recipe.excludeTools ?? ""));
1550
+ check("clean", (value) => value === recipe.clean);
1551
+ check("sandbox", (value) => value === recipe.sandbox);
1552
+ check("sandbox_dir", (value) => sameLaunchPath(value, recipe.sandboxDir));
1553
+ check("cwd", (value) => sameLaunchPath(value, recipe.cwd));
1554
+ check("git_clone_workspace", (value) => value === recipe.gitCloneWorkspace);
1555
+ check("approve", (value) => value === recipe.approve);
1556
+ check("allow_nested", (value) => value === recipe.allowNested);
1557
+ return conflicts;
1558
+ }
1559
+
1560
+ /**
1561
+ * Refuse any launch-only option that does not reproduce the saved recipe.
1562
+ * Matching values are allowed (a caller that repeats its original launch call is
1563
+ * provably asking for the same thing); a missing option just keeps the recipe.
1564
+ */
1565
+ function assertContinuationLaunchOptions(
1566
+ job: Record<string, unknown>,
1567
+ recipe: ContinuationPlan["recipe"],
1568
+ label: string,
1569
+ options: { includeName: boolean } = { includeName: true },
1570
+ ): void {
1571
+ if (job.retain_session !== undefined) throw new ContinuationError(`${label}${RETAIN_SESSION_REMOVED}`);
1572
+ const conflicts = continuationLaunchConflicts(job, recipe, options);
1573
+ if (conflicts.length === 0) return;
1574
+ const named = conflicts.map((key) => `\`${key}\``).join(", ");
1575
+ const prefix = label || "Cannot continue this saved conversation: ";
1576
+ throw new ContinuationError(
1577
+ `${prefix}${named} ${conflicts.length === 1 ? "conflicts" : "conflict"} with the saved launch recipe. ` +
1578
+ `A continued conversation keeps the recipe it was launched with; omit ${conflicts.length === 1 ? "it" : "them"}. ` +
1579
+ `A continuation accepts prompt, session_id, and optional model, thinking, callback, and timing overrides.`,
1580
+ );
1581
+ }
1582
+
1583
+ /**
1584
+ * The attempt that currently owns a saved conversation: the LATEST attempt by
1585
+ * `startedAt` (then id, so ties stay deterministic). Never pick an older
1586
+ * completed sibling: that would branch history from a superseded attempt.
1587
+ */
1588
+ function latestConversationAttempt(sessionId: string, metas: readonly RunMeta[]): RunMeta | undefined {
1589
+ let latest: RunMeta | undefined;
1590
+ for (const meta of metas) {
1591
+ if (meta.sessionId !== sessionId) continue;
1592
+ if (!latest || meta.startedAt > latest.startedAt
1593
+ || (meta.startedAt === latest.startedAt && meta.id > latest.id)) latest = meta;
1594
+ }
1595
+ return latest;
1596
+ }
1597
+
1598
+ /**
1599
+ * Select a saved conversation by its exact native session id and validate it for
1600
+ * one more attempt. `planContinuation` owns the refusals (a running/orphaned
1601
+ * latest attempt, missing history or workspace, unsupported recipe), so a
1602
+ * missing session is the only error added here. Nothing is ever recreated.
1603
+ */
1604
+ function requestedSessionId(job: { session_id?: string; session_name?: string }, cwd: string): string | undefined {
1605
+ if (job.session_id !== undefined && job.session_name !== undefined) {
1606
+ throw new Error("Pass either session_id or session_name, not both.");
1607
+ }
1608
+ if (job.session_name !== undefined) {
1609
+ if (typeof job.session_name !== "string") throw new Error("session_name must be a non-empty name.");
1610
+ return selectSessionByName(listMetas(), job.session_name, (workspace) => isWithinWorkspace(workspace, cwd));
1611
+ }
1612
+ return job.session_id;
1613
+ }
1614
+
1615
+ function continuationPlanFor(sessionId: string, origin: RunCallbackOrigin | undefined): ContinuationPlan {
1616
+ const others = listMetas();
1617
+ const latest = latestConversationAttempt(sessionId, others);
1618
+ if (!latest) {
1619
+ throw new ContinuationError(
1620
+ `Cannot continue session ${sessionId}: no saved subagent conversation has that native session id. ` +
1621
+ `Check the session id reported by the launching attempt, or omit session_id to start a new conversation.`,
1622
+ );
1623
+ }
1624
+ return planContinuation({ id: latest.id, prior: latest, origin, others });
1625
+ }
1626
+
1506
1627
  function timingSchemaFields() {
1507
1628
  return timingParameterSchemas(Type);
1508
1629
  }
@@ -1698,8 +1819,13 @@ export default function (pi: ExtensionAPI) {
1698
1819
  git_clone_workspace?: boolean; approve?: boolean; allow_nested?: boolean;
1699
1820
  agent?: string; role?: string | readonly string[]; alias?: string;
1700
1821
  catalog?: CatalogRunRecord; catalogResolved?: boolean;
1701
- /** Keep the completed conversation and workspace out of cleanup for continuation. */
1702
- retain_session?: boolean;
1822
+ /**
1823
+ * Native session id of a saved conversation to continue. Omit for a
1824
+ * brand-new conversation; an attempt's own id is its session id only on
1825
+ * a fresh launch, so follow-ups use the session id the launch reported.
1826
+ */
1827
+ session_id?: string;
1828
+ session_name?: string;
1703
1829
  } & TimingParams;
1704
1830
 
1705
1831
  /**
@@ -1868,7 +1994,7 @@ export default function (pi: ExtensionAPI) {
1868
1994
  requested: allow.split(",").filter((name) => name && !requestedExcludes.has(name)),
1869
1995
  settings: permissionPlan.tools, network: permissionPlan.permissions?.network ?? true,
1870
1996
  processAccess: permissionPlan.permissions?.processAccess ?? "off",
1871
- builtins: TASK_BUILTINS, registered: pi.getAllTools?.() ?? [],
1997
+ builtins: [...TASK_BUILTINS, "codemode"], registered: pi.getAllTools?.() ?? [],
1872
1998
  toolExtensions: cfg.toolExtensions, resolvePath: resolveExtensionPath,
1873
1999
  }) : undefined;
1874
2000
  const resolution = resolveExtensions({
@@ -1882,10 +2008,12 @@ export default function (pi: ExtensionAPI) {
1882
2008
  .filter((path) => !resolvedExtArgs.includes(path)).flatMap((path) => ["--extension", path]);
1883
2009
  // Harness child controls ride along in every mode, including clean and unsandboxed runs.
1884
2010
  // They deliver deadline steers and keep external monitoring with the coordinator.
1885
- const extArgs = [...resolvedExtArgs, ...trustedExtArgs,
2011
+ const codemodeArgs = !sandboxEnabled && allow.split(",").includes("codemode") && !requestedExcludes.has("codemode")
2012
+ ? ["--extension", join(selfDir(), "child-codemode.ts")] : [];
2013
+ const extArgs = [...resolvedExtArgs, ...trustedExtArgs, ...codemodeArgs,
1886
2014
  "--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
1887
2015
  .map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value);
1888
- const baseExtensionArgs = [...resolvedExtArgs,
2016
+ const baseExtensionArgs = [...resolvedExtArgs, ...codemodeArgs,
1889
2017
  "--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
1890
2018
  .map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value);
1891
2019
  if (resume?.recipe.extensionArgs) {
@@ -1895,7 +2023,7 @@ export default function (pi: ExtensionAPI) {
1895
2023
  tools: sandboxEnabled ? allow.split(",").filter((name) => (SDK_BUILTIN_TOOLS as readonly string[]).includes(name)).join(",") : allow,
1896
2024
  model: resume.recipe.model, clean, allowNested: sandboxEnabled ? false : allowNested, config: cfg,
1897
2025
  });
1898
- const referenceArgs = [...extensionArgs(reference, resolveExtensionPath).args,
2026
+ const referenceArgs = [...extensionArgs(reference, resolveExtensionPath).args, ...codemodeArgs,
1899
2027
  ...(!resume.recipe.baseExtensionArgs ? trustedExtArgs : []),
1900
2028
  "--extension", childSteerExtensionPath(), "--extension", join(selfDir(), "child-ownership.ts")]
1901
2029
  .map((value, index, all) => sandboxEnabled && all[index - 1] === "--extension" ? canonicalizePath(value) : value);
@@ -1981,8 +2109,10 @@ export default function (pi: ExtensionAPI) {
1981
2109
  }
1982
2110
  // One writer per conversation, held across admission, child lifetime,
1983
2111
  // and finalization. A live duplicate continuation is refused instead of
1984
- // letting two processes rewrite one session file.
1985
- if (resume || p.retain_session === true) {
2112
+ // letting two processes rewrite one session file. A fresh launch has a
2113
+ // brand-new native session id, so it cannot contend with anyone and
2114
+ // needs no lease; every continuation does.
2115
+ if (resume) {
1986
2116
  lease = acquireConversationLease({ sessionId, attemptId: id });
1987
2117
  }
1988
2118
  // The lease is the first moment no other process can retire this
@@ -2056,7 +2186,7 @@ export default function (pi: ExtensionAPI) {
2056
2186
  timing: resolveRunTiming({ params: p, settings: cfg, env: process.env, startedAt }),
2057
2187
  };
2058
2188
  // Register exit supervision before any fallible post-spawn publication.
2059
- // A failed retention write must not strand a running child without a close
2189
+ // A failed metadata write must not strand a running child without a close
2060
2190
  // handler; the lease stays held until that child has actually exited.
2061
2191
  void spawned.exit.then((code) => {
2062
2192
  try { finalizeRun(pi, ctx, id, code); }
@@ -2064,13 +2194,6 @@ export default function (pi: ExtensionAPI) {
2064
2194
  });
2065
2195
  try {
2066
2196
  writeMeta(meta);
2067
- // Publish retention only after the attempt is discoverable. Later
2068
- // attempts refresh an existing promise without reviving a release.
2069
- if (resume) {
2070
- refreshRetentionForAttempt({ sessionId, attemptId: id });
2071
- } else if (p.retain_session === true) {
2072
- retainConversation({ sessionId, ownerRunId: rootRunId, workspace: cwd, ownerOrigin: callbackOrigin, attemptId: id });
2073
- }
2074
2197
  } catch (error) {
2075
2198
  killProcessTree(spawned.pid, "SIGKILL");
2076
2199
  throw error;
@@ -2102,6 +2225,15 @@ export default function (pi: ExtensionAPI) {
2102
2225
  }
2103
2226
 
2104
2227
  // ---- subagent_spawn -------------------------------------------------
2228
+ //
2229
+ // One tool launches both fresh work and a continuation of saved work. A
2230
+ // continuation is an ORDINARY attempt of the SAME saved conversation: a new
2231
+ // run id, the prior native session id, the exact saved session file, and the
2232
+ // frozen launch recipe. Old logs/results/callbacks/timing stay under their
2233
+ // own attempt id. Nothing stays alive between attempts, so a parked
2234
+ // conversation occupies zero capacity slots. `session_id` (not the run id)
2235
+ // selects the conversation, and the latest attempt is always the one that
2236
+ // owns it.
2105
2237
  const acceptanceSpawnTool = {
2106
2238
  name: "subagent_spawn",
2107
2239
  label: "Spawn Subagent",
@@ -2120,10 +2252,14 @@ export default function (pi: ExtensionAPI) {
2120
2252
  "Subagent sandboxing defaults to off. Human settings in /sandbox control file, credential-file, command, and network permissions; sandbox:false cannot override an enabled human profile. Set sandbox:true to request kernel confinement, including without published settings. Set callback:false to finish quietly — then read the result on demand via subagent_result.",
2121
2253
  "Every launch automatically joins one shared harness-owned watcher, including batch launches; it stops when the last active run ends. Do not start a separate heartbeat or background watcher for subagents. No progress for stuck_minutes (default 10) wakes you once without stopping the run. Elapsed-time limits are opt-in: deadline_minutes steers the child to wrap up and later stops it after grace_minutes, while max_minutes stops it without grace. Do not set elapsed-time limits merely because a task may take a while; use them only when the work needs a real wall-clock bound.",
2122
2254
  "Use git_clone_workspace:true when the subagent will mutate Git in a sandbox. The parent prepares a disposable, self-contained clone with a real .git/ directory inside the sandbox root, so linked-worktree metadata outside the sandbox cannot stall the child.",
2123
- "Set retain_session:true only when the run is expected to need follow-up: it keeps the completed conversation and workspace available for subagent_resume. It does not keep the child process alive and does not occupy a capacity slot. Release it with subagent_release when no more feedback is expected. Ordinary one-shot runs leave it off.",
2255
+ "Saved conversations persist automatically. To continue a completed worker in its own history, call subagent_spawn with session_id (the native session id reported for the saved conversation) and the new feedback as prompt. Omit session_id for a brand-new conversation.",
2256
+ "On a continuation, pass prompt, session_id, and only optional model, thinking, callback, or timing overrides. Launch-only options (name, agent, role, alias, tools, exclude_tools, clean, sandbox, sandbox_dir, cwd, git_clone_workspace, approve, allow_nested) keep the saved recipe; repeat them only with the same value, otherwise the launch is refused.",
2257
+ "Do not restate the original task or role when continuing: they already live in the saved conversation. A running or orphaned latest attempt blocks continuation until it stops, and missing saved history is refused rather than recreated.",
2124
2258
  ],
2125
2259
  parameters: Type.Object({
2126
- prompt: Type.String({ description: "The task for the subagent. This is the only context it gets — be self-contained." }),
2260
+ prompt: Type.String({ description: "The task for the subagent. This is the only context it gets — be self-contained. On a continuation this is the next user turn; the original task and role stay in saved history." }),
2261
+ session_name: Type.Optional(Type.String({ description: "Exact name of one saved conversation in the current folder and descendants. Alternative to session_id. Duplicate names report matching session ids instead of choosing a conversation." })),
2262
+ session_id: Type.Optional(Type.String({ description: "Native session id of a saved conversation to continue (reported for every launch and attempt). Omit to start a new conversation. A continuation gets a new run id but keeps this session id, history, workspace, and frozen launch recipe." })),
2127
2263
  name: Type.Optional(Type.String({ description: "Short label for the run (e.g. 'reviewer'). Ignored when agent or role is set, except as the direct-role alias when alias is omitted." })),
2128
2264
  agent: Type.Optional(Type.String({ description: "Named agent id (agent.<slug>). Mutually exclusive with role. The navigator shows the defined agent name." })),
2129
2265
  role: catalogRoleSchema("direct role launch"),
@@ -2140,13 +2276,20 @@ export default function (pi: ExtensionAPI) {
2140
2276
  git_clone_workspace: Type.Optional(Type.Boolean({ description: "Prepare a disposable Git clone workspace for sandboxed Git-mutating subagents. The clone has a real .git/ directory inside the sandbox writable root and is self-contained after setup." })),
2141
2277
  approve: Type.Optional(Type.Boolean({ description: "Trust project-local files in the child (default: false; headless runs cannot prompt for trust)." })),
2142
2278
  allow_nested: Type.Optional(Type.Boolean({ description: "Allow the child to spawn its own subagents (default: false). Loads this extension in the child and allowlists its tools." })),
2143
- retain_session: Type.Optional(Type.Boolean({ description: "Keep this completed conversation and its workspace available for subagent_resume until subagent_release. Default false: ordinary one-shot behavior. Retention uses existing temporary runtime storage, so it is bounded, not permanent." })),
2144
2279
  ...timingSchemaFields(),
2145
2280
  }),
2146
2281
 
2147
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
2148
- const p = params as SpawnParams;
2282
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx): Promise<{
2283
+ content: { type: "text"; text: string }[];
2284
+ details: Record<string, unknown>;
2285
+ }> {
2286
+ const p = { ...params } as SpawnParams;
2287
+ p.session_id = requestedSessionId(p, ctx.cwd);
2149
2288
  if (p.prompt.trim() === "") throw new Error("prompt is empty.");
2289
+ if (p.session_id !== undefined && (typeof p.session_id !== "string" || p.session_id.trim() === "")) {
2290
+ throw new Error("session_id must be a non-empty native session id.");
2291
+ }
2292
+ assertNoRetiredLaunchOptions(p as { retain_session?: unknown });
2150
2293
  // A present-but-blank role or agent is a mistake, not a request for a catalog-free child.
2151
2294
  const blankSelector = blankCatalogSelector(p);
2152
2295
  if (blankSelector) throw new Error(blankSelector);
@@ -2161,11 +2304,55 @@ export default function (pi: ExtensionAPI) {
2161
2304
 
2162
2305
  let reserved = 1;
2163
2306
  try {
2307
+ if (p.session_id !== undefined) {
2308
+ // Continue a saved conversation. The same capacity, permission,
2309
+ // lease, callback, and finalization path runs as for a fresh
2310
+ // launch; only the conversation and recipe are inherited. The
2311
+ // catalog is never re-resolved for a saved conversation.
2312
+ const plan = continuationPlanFor(p.session_id, verifiedOriginFromContext(ctx) ?? activeCallbackOrigin);
2313
+ assertContinuationLaunchOptions(p as unknown as Record<string, unknown>, plan.recipe, "");
2314
+ const continuation: SpawnParams = {
2315
+ prompt: p.prompt,
2316
+ model: p.model,
2317
+ thinking: p.thinking,
2318
+ callback: p.callback,
2319
+ deadline_minutes: p.deadline_minutes,
2320
+ grace_minutes: p.grace_minutes,
2321
+ max_minutes: p.max_minutes,
2322
+ stuck_minutes: p.stuck_minutes,
2323
+ };
2324
+ const { id, spawned, runtime, warn, sandboxDir, modelNote } = await spawnSubagentRun(
2325
+ ctx, continuation, undefined, plan,
2326
+ );
2327
+ gate.commit(1);
2328
+ reserved = 0;
2329
+ return {
2330
+ content: [{ type: "text" as const, text:
2331
+ `Subagent continued: ${plan.recipe.name ? `${plan.recipe.name} ` : ""}id=${id} (pid ${spawned.pid}) from ${plan.prior.id}.\n` +
2332
+ `Conversation: session ${plan.conversation.sessionId} — pass session_id=${plan.conversation.sessionId} for the next follow-up.\n` +
2333
+ (modelNote ? `${modelNote[0]!.toUpperCase()}${modelNote.slice(1)}.\n` : "") +
2334
+ (continuation.callback === false
2335
+ ? `Running in the background; the foreground is free. It will finish quietly — read the result with subagent_result id=${id}.\n`
2336
+ : `Running in the background; the foreground is free. Its result will be posted back here when it finishes.\n`) +
2337
+ (sandboxDir ? `Sandboxed: project root ${sandboxDir}; current launch permissions apply.\n` : "") +
2338
+ runtime + warn +
2339
+ `Log: ${logPathFor(id)}`,
2340
+ }],
2341
+ details: {
2342
+ status: "continued" as const,
2343
+ launched: true,
2344
+ priorId: plan.prior.id,
2345
+ runId: id,
2346
+ sessionId: plan.conversation.sessionId,
2347
+ rootRunId: plan.rootRunId,
2348
+ },
2349
+ };
2350
+ }
2164
2351
  const catalog = await admitCatalog(ctx, [p]);
2165
2352
  if (catalog.status === "clarification-needed") {
2166
2353
  gate.release(1);
2167
2354
  reserved = 0;
2168
- return catalogResult(catalog) as ReturnType<typeof text>;
2355
+ return catalogResult(catalog);
2169
2356
  }
2170
2357
  if (catalog.jobs.length > 1) {
2171
2358
  const extra = catalog.jobs.length - 1;
@@ -2182,22 +2369,29 @@ export default function (pi: ExtensionAPI) {
2182
2369
  reserved -= 1;
2183
2370
  launched.push({ name: job.name, id, modelNote });
2184
2371
  }
2185
- return text(launched.map((item) => `Subagent launched: ${item.name ? `${item.name} ` : ""}id=${item.id}.${item.modelNote ? ` ${item.modelNote}.` : ""}`).join("\n"));
2372
+ return {
2373
+ content: [{ type: "text" as const, text: launched.map((item) => `Subagent launched: ${item.name ? `${item.name} ` : ""}id=${item.id} (session ${item.id}).${item.modelNote ? ` ${item.modelNote}.` : ""}`).join("\n") }],
2374
+ details: { status: "launched" as const, launched: true, runIds: launched.map((item) => item.id) },
2375
+ };
2186
2376
  }
2187
2377
  Object.assign(p, catalog.jobs[0]);
2188
- const { id, spawned, runtime, warn, sandboxDir, modelNote } = await spawnSubagentRun(ctx, p);
2378
+ const { id, meta, spawned, runtime, warn, sandboxDir, modelNote } = await spawnSubagentRun(ctx, p);
2189
2379
  gate.commit(1);
2190
2380
  reserved = 0;
2191
- return text(
2192
- `Subagent launched: ${p.name ? `${p.name} ` : ""}id=${id} (pid ${spawned.pid}).\n` +
2193
- (modelNote ? `${modelNote[0]!.toUpperCase()}${modelNote.slice(1)}.\n` : "") +
2194
- (p.callback === false
2195
- ? `Running in the background; the foreground is free. It will finish quietly — read the result with subagent_result id=${id}.\n`
2196
- : `Running in the background; the foreground is free. Its result will be posted back here when it finishes.\n`) +
2197
- (sandboxDir ? `Sandboxed: project root ${sandboxDir}; launch permissions apply.\n` : "") +
2198
- runtime + warn +
2199
- `Log: ${logPathFor(id)}`,
2200
- );
2381
+ return {
2382
+ content: [{ type: "text" as const, text:
2383
+ `Subagent launched: ${p.name ? `${p.name} ` : ""}id=${id} (pid ${spawned.pid}).\n` +
2384
+ `Session: ${meta.sessionId} — pass it as session_id to continue this conversation.\n` +
2385
+ (modelNote ? `${modelNote[0]!.toUpperCase()}${modelNote.slice(1)}.\n` : "") +
2386
+ (p.callback === false
2387
+ ? `Running in the background; the foreground is free. It will finish quietly — read the result with subagent_result id=${id}.\n`
2388
+ : `Running in the background; the foreground is free. Its result will be posted back here when it finishes.\n`) +
2389
+ (sandboxDir ? `Sandboxed: project root ${sandboxDir}; launch permissions apply.\n` : "") +
2390
+ runtime + warn +
2391
+ `Log: ${logPathFor(id)}`,
2392
+ }],
2393
+ details: { status: "launched" as const, launched: true, runId: id, sessionId: meta.sessionId },
2394
+ };
2201
2395
  } catch (err) {
2202
2396
  if (reserved === 1) gate.release(1);
2203
2397
  else if (reserved > 0) gate.release(reserved);
@@ -2251,9 +2445,11 @@ export default function (pi: ExtensionAPI) {
2251
2445
  approve: Type.Optional(Type.Boolean({ description: "Trust project-local files in children." })),
2252
2446
  allow_nested: Type.Optional(Type.Boolean({ description: "Allow children to spawn their own subagents." })),
2253
2447
  ...timingSchemaFields(),
2254
- }, { description: "Options applied to every job; per-job values override these." })),
2448
+ }, { description: "Options applied to every job; per-job values override these. session_id is per job and is never inherited from shared, because one shared conversation would make every job compete for the same writer." })),
2255
2449
  jobs: Type.Array(Type.Object({
2256
- prompt: Type.String({ description: "The task for this job." }),
2450
+ prompt: Type.String({ description: "The task for this job. On a continuation this is the next user turn." }),
2451
+ session_name: Type.Optional(Type.String({ description: "Exact saved conversation name in the current folder and descendants. Per job only; alternative to session_id. Ambiguous names refuse with matching session ids." })),
2452
+ session_id: Type.Optional(Type.String({ description: "Native session id of a saved conversation this JOB continues. Per job only, never shared. Omit for a new conversation. A continuation keeps its saved history, workspace, and frozen recipe, and accepts only model/thinking/callback/timing overrides." })),
2257
2453
  name: Type.Optional(Type.String({ description: "Short label for this job. Direct-role alias when alias is omitted." })),
2258
2454
  agent: Type.Optional(Type.String({ description: "Named agent id for this job. Overrides shared agent and role." })),
2259
2455
  role: catalogRoleSchema("batch job"),
@@ -2292,6 +2488,15 @@ export default function (pi: ExtensionAPI) {
2292
2488
  // concurrent single spawn cannot take a slot the batch already admitted.
2293
2489
  const gate = getSharedCapacityGate(countRunning);
2294
2490
 
2491
+ // session_id selects one saved conversation, so it is per job: a shared
2492
+ // value would point every job at the same conversation writer.
2493
+ if (p.shared?.session_name !== undefined) throw new Error("session_name is per job, never shared.");
2494
+ if (p.shared?.session_id !== undefined) {
2495
+ throw new Error("session_id is per job: set jobs[i].session_id for the jobs that continue a saved conversation; shared has no session_id.");
2496
+ }
2497
+ assertNoRetiredLaunchOptions(p.shared, "shared: ");
2498
+ p.jobs.forEach((job, index) => assertNoRetiredLaunchOptions(job, `jobs[${index}]: `));
2499
+
2295
2500
  validateBatchPlan({ shared: p.shared, jobs: p.jobs, onCapacity: p.onCapacity, config: cfg });
2296
2501
  // A present-but-blank role or agent rejects the whole batch before any launch.
2297
2502
  const blankSelector = blankCatalogSelector(p.shared, "shared")
@@ -2300,7 +2505,9 @@ export default function (pi: ExtensionAPI) {
2300
2505
 
2301
2506
  let catalogSnapshot: CatalogSnapshot | undefined;
2302
2507
  let catalogHost: CatalogHost | undefined;
2303
- if (hasCatalogSelector(p.shared) || p.jobs.some((job) => hasCatalogSelector(job))) {
2508
+ const needsCatalog = p.jobs.some((job) => job.session_id === undefined && job.session_name === undefined
2509
+ && hasCatalogSelector(mergeJobOptions(p.shared, job)));
2510
+ if (needsCatalog) {
2304
2511
  catalogHost = catalogHostFrom(ctx);
2305
2512
  noteCatalogHost(catalogHost);
2306
2513
  catalogSnapshot = loadLaunchSnapshot(catalogHost);
@@ -2349,7 +2556,7 @@ export default function (pi: ExtensionAPI) {
2349
2556
 
2350
2557
  const names = assignBatchJobNames(p.jobs);
2351
2558
  const batchId = nextBatchId();
2352
- const launched: { job: number; name: string; id: string; modelNote?: string }[] = [];
2559
+ const launched: { job: number; name: string; id: string; sessionId: string; continuedFrom?: string; modelNote?: string }[] = [];
2353
2560
  const failed: { job: number; name: string; reason: string }[] = [];
2354
2561
  const skipped: { job: number; name: string }[] = [];
2355
2562
  // How many reject-mode reserved slots are still held (not yet committed/released).
@@ -2361,6 +2568,13 @@ export default function (pi: ExtensionAPI) {
2361
2568
  const job = p.jobs[i];
2362
2569
  let name = names[i];
2363
2570
  const merged = mergeJobOptions(p.shared, job);
2571
+ const isContinuation = job.session_id !== undefined || job.session_name !== undefined;
2572
+ // A continuation keeps its own frozen model and effort. shared.model
2573
+ // is a default for NEW conversations, so only a per-job value is an
2574
+ // explicit escalation of the saved recipe.
2575
+ const launch: Partial<SpawnParams> & { prompt: string; name: string } = !isContinuation
2576
+ ? { ...merged, name }
2577
+ : { ...merged, name, model: job.model, thinking: job.thinking };
2364
2578
 
2365
2579
  if (launchAvailable) {
2366
2580
  if (!gate.tryReserve(1, activeConcurrencyCap())) {
@@ -2372,7 +2586,9 @@ export default function (pi: ExtensionAPI) {
2372
2586
  }
2373
2587
 
2374
2588
  try {
2375
- if (catalogSnapshot && catalogHost && hasCatalogSelector(merged)) {
2589
+ const sessionId = requestedSessionId(job, ctx.cwd);
2590
+ // A saved conversation is never re-resolved against the catalog.
2591
+ if (sessionId === undefined && catalogSnapshot && catalogHost && hasCatalogSelector(merged)) {
2376
2592
  const explicitName = typeof job.name === "string" && job.name.trim() !== "" ? job.name : undefined;
2377
2593
  const prepared = await prepareCatalogJob(catalogSnapshot, {
2378
2594
  ...merged,
@@ -2381,16 +2597,27 @@ export default function (pi: ExtensionAPI) {
2381
2597
  }, catalogHost);
2382
2598
  if (prepared.status === "blocked") throw new Error(prepared.message);
2383
2599
  if (prepared.status === "ready") {
2384
- Object.assign(merged, prepared.assign);
2385
- if (prepared.assign.model === undefined) delete merged.model;
2386
- if (prepared.assign.thinking === undefined) delete merged.thinking;
2600
+ Object.assign(launch, prepared.assign);
2601
+ if (prepared.assign.model === undefined) delete launch.model;
2602
+ if (prepared.assign.thinking === undefined) delete launch.thinking;
2387
2603
  name = prepared.assign.name;
2388
2604
  }
2389
2605
  }
2390
- const { id, modelNote } = await spawnSubagentRun(ctx, { ...merged, name }, { batchId, batchName: p.batchName });
2606
+ let plan: ContinuationPlan | undefined;
2607
+ if (sessionId !== undefined) {
2608
+ plan = continuationPlanFor(sessionId, verifiedOriginFromContext(ctx) ?? activeCallbackOrigin);
2609
+ assertContinuationLaunchOptions(
2610
+ launch as unknown as Record<string, unknown>, plan.recipe, `Job ${i + 1}: `, { includeName: false },
2611
+ );
2612
+ }
2613
+ const { id, meta, modelNote } = await spawnSubagentRun(ctx, { ...launch, name }, { batchId, batchName: p.batchName }, plan);
2391
2614
  gate.commit(1);
2392
2615
  if (!launchAvailable) reservedRemaining -= 1;
2393
- launched.push({ job: i + 1, name, id, ...(modelNote ? { modelNote } : {}) });
2616
+ launched.push({
2617
+ job: i + 1, name, id, sessionId: meta.sessionId,
2618
+ ...(plan ? { continuedFrom: plan.prior.id } : {}),
2619
+ ...(modelNote ? { modelNote } : {}),
2620
+ });
2394
2621
  } catch (err) {
2395
2622
  gate.release(1);
2396
2623
  if (!launchAvailable) reservedRemaining -= 1;
@@ -2429,143 +2656,6 @@ export default function (pi: ExtensionAPI) {
2429
2656
  },
2430
2657
  });
2431
2658
 
2432
- // ---- subagent_resume / subagent_release ------------------------------
2433
- //
2434
- // A continuation is an ORDINARY attempt of the SAME saved conversation:
2435
- // a new run id, the prior native session id, the exact saved session file,
2436
- // and the frozen launch recipe. Old logs/results/callbacks/timing stay
2437
- // under their own attempt id. Nothing stays alive between attempts, so a
2438
- // parked owner occupies zero capacity slots.
2439
- type ResumeParams = {
2440
- id: string; prompt: string; model?: string; thinking?: ThinkingLevel; callback?: boolean;
2441
- } & TimingParams;
2442
-
2443
- const acceptanceResumeTool = {
2444
- name: "subagent_resume",
2445
- label: "Resume Subagent",
2446
- description:
2447
- "Continue a COMPLETED background subagent in its own saved conversation and return " +
2448
- "IMMEDIATELY with a new run id. The attempt is new (new log, result, timing, and " +
2449
- "capacity slot) while the native session and its full history stay the same. The " +
2450
- "foreground session stays free; completion is reported later, never polled.",
2451
- promptSnippet: "Send feedback to a completed subagent and continue its conversation",
2452
- promptGuidelines: [
2453
- "For repair work or feedback within the same assignment, subagent_resume continues the completed worker's conversation with the same role, workspace, and prior context.",
2454
- "subagent_resume takes the PRIOR run id and the new feedback as its prompt. Do not restate the original task or role instructions; they are already in the saved conversation.",
2455
- "Only a completed run owned by this foreground session can be resumed. A running or orphaned run must be stopped first, and a conversation whose saved history or workspace is gone cannot be resumed.",
2456
- "The prior attempt's result and logs are preserved under its own run id. The resumed attempt reports back like any other run and uses one capacity slot while it runs.",
2457
- "Preserve the original model and effort unless an explicit escalation is required for this attempt; pass model or thinking only for that reason.",
2458
- "Keep the implementation owner through repairs. For independent review, resume only an unfinished review on the same HEAD and scope; after a completed review use a fresh session for the next required round, carrying structured findings as evidence. Release retention once no further feedback is expected.",
2459
- ...SUBAGENT_ORCHESTRATION_GUIDELINES,
2460
- ],
2461
- parameters: Type.Object({
2462
- id: Type.String({ description: "Completed run id to continue (from subagent_spawn or a prior subagent_resume)." }),
2463
- prompt: Type.String({ description: "The new feedback for the existing conversation. This is the next user turn; the original task and role stay in saved history." }),
2464
- model: Type.Optional(Type.String({ description: "Explicit model for this attempt only (provider/id, optionally @effort). Omit to keep the saved launch recipe's model." })),
2465
- thinking: Type.Optional(Type.String({ description: "Explicit reasoning effort for this attempt only. Omit to keep the saved launch recipe's effort." })),
2466
- callback: Type.Optional(Type.Boolean({ description: "Default: the retained run's callback setting. Set false to finish this attempt quietly." })),
2467
- ...timingSchemaFields(),
2468
- }),
2469
-
2470
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
2471
- const p = params as ResumeParams;
2472
- if (typeof p.id !== "string" || p.id.trim() === "") throw new Error("id is required.");
2473
- if (typeof p.prompt !== "string" || p.prompt.trim() === "") throw new Error("prompt is empty.");
2474
- // The owner is the calling foreground session; an unreadable session
2475
- // identity stays unavailable instead of widening to the whole cwd.
2476
- const origin = verifiedOriginFromContext(ctx) ?? activeCallbackOrigin;
2477
- const maxConcurrent = activeConcurrencyCap();
2478
- const gate = getSharedCapacityGate(countRunning);
2479
- if (!gate.tryReserve(1, maxConcurrent)) {
2480
- throw new Error(`Max concurrent subagents (${maxConcurrent}) reached. Stop or let some finish first.`);
2481
- }
2482
- // Only the contract's fields cross into the launch path: the prior id
2483
- // selects the conversation, never a new run identity.
2484
- const job: SpawnParams = {
2485
- prompt: p.prompt,
2486
- model: p.model,
2487
- thinking: p.thinking,
2488
- callback: p.callback,
2489
- deadline_minutes: p.deadline_minutes,
2490
- grace_minutes: p.grace_minutes,
2491
- max_minutes: p.max_minutes,
2492
- stuck_minutes: p.stuck_minutes,
2493
- };
2494
- let reserved = 1;
2495
- try {
2496
- // Validation is synchronous and side-effect free: nothing is
2497
- // spawned and no history is created or replaced on a refusal.
2498
- const plan = planContinuation({ id: p.id, prior: readMeta(p.id), origin, others: listMetas() });
2499
- const { id, spawned, runtime, warn, sandboxDir, modelNote } = await spawnSubagentRun(
2500
- ctx, job, undefined, plan,
2501
- );
2502
- gate.commit(1);
2503
- reserved = 0;
2504
- const body =
2505
- `Subagent resumed: ${plan.recipe.name ? `${plan.recipe.name} ` : ""}id=${id} (pid ${spawned.pid}) from ${p.id}.\n` +
2506
- `Same conversation: session ${plan.conversation.sessionId}. The prior attempt ${p.id} is unchanged.\n` +
2507
- (modelNote ? `${modelNote[0]!.toUpperCase()}${modelNote.slice(1)}.\n` : "") +
2508
- `Running in the background; the foreground is free. Its result will be posted back here when it finishes.\n` +
2509
- (sandboxDir ? `Sandboxed: project root ${sandboxDir}; current launch permissions apply.\n` : "") +
2510
- runtime + warn +
2511
- `Log: ${logPathFor(id)}`;
2512
- return {
2513
- content: [{ type: "text" as const, text: body }],
2514
- details: {
2515
- status: "resumed",
2516
- launched: true,
2517
- priorId: p.id,
2518
- runId: id,
2519
- sessionId: plan.conversation.sessionId,
2520
- rootRunId: plan.rootRunId,
2521
- },
2522
- };
2523
- } catch (err) {
2524
- if (reserved) gate.release(reserved);
2525
- throw err;
2526
- }
2527
- },
2528
- } as Parameters<ExtensionAPI["registerTool"]>[0];
2529
- registerSpawnTool(acceptanceResumeTool);
2530
-
2531
- const acceptanceReleaseTool = {
2532
- name: "subagent_release",
2533
- label: "Release Subagent Retention",
2534
- description:
2535
- "Release explicit retain_session protection for a completed subagent conversation and its " +
2536
- "workspace. Nothing is deleted now and no completed result is rewritten; ordinary " +
2537
- "cleanup may remove the artifacts afterwards. Only the owning foreground session may release.",
2538
- promptSnippet: "Release a retained subagent conversation and workspace",
2539
- promptGuidelines: [
2540
- "Call subagent_release when no more subagent_resume feedback is expected, so retained temporary history and workspace can be reclaimed by normal cleanup.",
2541
- "Release does not delete anything immediately and does not change the run's result; the conversation becomes unavailable for a later resume once cleanup removes it.",
2542
- ],
2543
- parameters: Type.Object({
2544
- id: Type.String({ description: "Run id whose retained conversation should be released." }),
2545
- }),
2546
- async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
2547
- const p = params as { id: string };
2548
- if (typeof p.id !== "string" || p.id.trim() === "") throw new Error("id is required.");
2549
- const origin = verifiedOriginFromContext(ctx) ?? activeCallbackOrigin;
2550
- if (!origin?.sessionId) throw new Error(`Cannot release ${p.id}: the active foreground session identity is unavailable.`);
2551
- const record = planRetentionRelease({ id: p.id, prior: readMeta(p.id), origin, others: listMetas() });
2552
- const released = markRetentionReleased(record, origin);
2553
- return {
2554
- content: [{ type: "text" as const, text:
2555
- `Released retention for ${p.id}: session ${record.sessionId} and workspace ${record.workspace} ` +
2556
- `are no longer protected. Logs, results, and completed metadata are unchanged; normal cleanup may remove them later.`,
2557
- }],
2558
- details: {
2559
- status: "released",
2560
- id: p.id,
2561
- sessionId: record.sessionId,
2562
- releasedAt: released.releasedAt,
2563
- },
2564
- };
2565
- },
2566
- } as Parameters<ExtensionAPI["registerTool"]>[0];
2567
- pi.registerTool(acceptanceReleaseTool);
2568
-
2569
2659
  // ---- model-facing read/stop tools -----------------------------------
2570
2660
  // The definitions live in tools.ts; registration uses the exact objects
2571
2661
  // the factories return, so tests invoke the same execute handlers the