@henryqw/pi-subagent 27.14.2 → 27.15.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/README.md CHANGED
@@ -142,7 +142,7 @@ Staging, validation, and promotion require clean, unchanged Main. After a defini
142
142
 
143
143
  ### Inspect work
144
144
 
145
- Open `/subagent` to browse direct work on this session branch and isolated requests in the current canonical Git checkout, including other sessions. Rows are grouped under **Direct**, **Isolated**, and **Orphaned · parent checkout removed**. Before the menu opens, and after each **Refresh**, a **Current subagent work** report shows which subagents are working. Without interactive UI, `/subagent` sends the report and the request list, including history.
145
+ Open `/subagent` to browse direct work on this session branch and isolated requests in the current canonical Git checkout, including other sessions. Rows are grouped under **Direct**, **Isolated**, and **Orphaned · parent checkout removed**. Before the menu opens, and after each **Refresh**, a **Current subagent work** report shows which subagents are working. Without interactive UI, `/subagent` sends the report and the request list, including history. In the terminal, the menu replaces the editor and uses at most half the terminal height. It does not overlay the report or the transcript.
146
146
 
147
147
  Each row starts with a status symbol: `●` active, `✓` completed, `⚠` needs attention, `✗` failed. Terminal requests stay hidden until you select **Completed / history**; this filter deletes no records. `/subagent` reports show as transcript entries that the model does not get.
148
148
 
@@ -190,6 +190,12 @@ The built-in reviewer answers exactly `PASS` or gives prioritized findings in th
190
190
 
191
191
  The built-in reviewer and scout include `git_read`; existing user reviewers and scouts must add it to `tools`. No additional extension or Bash access is necessary. See [Reviewer Git inspection](./docs/orchestration.md#reviewer-git-inspection) for operations, parameters, limits, and Git requirements.
192
192
 
193
+ When a direct or isolated worker starts with a configured fallback, Pi Subagent warns in the parent session that created it. The warning names the profile, selected `provider/model`, and thinking level. It uses the user interface (UI) when available. Without a UI, it adds a displayed parent-session message that does not start a turn.
194
+
195
+ The same profile and fallback route warn once in the active parent session. A session change resets these warnings. A different fallback model or thinking level gets a new warning. Dry runs, preflight, unused launch preparation, and cancelled or replaced sessions do not consume warnings. Isolated text and judgment workers report fallback use on their first child activity.
196
+
197
+ Route selection does not change. An available primary produces no fallback warning. A direct `model` override produces no fallback warning because it replaces the configured model. It still keeps the resolved thinking level.
198
+
193
199
  Children load only declared resources and required adapters. Roles must list their model provider extension. `codemode` requires both `builtin:codemode` in `extensions` and `codemode` in `tools`. Missing Skills, tools, MCP servers, Roles, or routes fail before productive work. Main-only delegation/recovery tools and `ask_question` stay unavailable to children.
194
200
 
195
201
  Read [Role and resource policy](./docs/orchestration.md#role-and-resource-policy) for extension exposure, MCP validation, OAuth constraints, and child budgets. Project MCP overrides cannot change a Role's global allowlist or exposure.
@@ -200,7 +206,7 @@ Read [Role and resource policy](./docs/orchestration.md#role-and-resource-policy
200
206
  | --- | --- | --- |
201
207
  | `loadRoleCatalog`, `findRole`, `parseRoleName`, `parseRoleDefaults` | functions | Load, validate, and select Roles with shared defaults and per-file errors. |
202
208
  | `registerRoleDefaultsReporting(pi, agentDir?)` | function | Report problems at session start, once per session. Returns `report(ctx)`; call before a lazy `loadRoleCatalog`. |
203
- | `resolveRoleSkills`, `resolveRoleLaunch`, `resolveConfiguredRoleLaunch` | functions | Resolve effective Pi resources and model routes. |
209
+ | `resolveRoleSkills`, `resolveRoleLaunch`, `resolveConfiguredRoleLaunch` | functions | Resolve effective Pi resources and model routes. Role launch results include optional `fallback` identity without a notification. |
204
210
  | `prepareRoleLaunch`, `finalizeRoleLaunch` | functions | Prepare Role prompts, arguments, and tool policy. |
205
211
  | `createEphemeralSubagentExecutor` | function | Run bounded no-session Pi children through a FIFO pool. |
206
212
  | `createChildWorktree`, `finalizeChildWorktree` | functions | Create and conservatively finalize child worktrees. |
@@ -226,6 +232,8 @@ Role extensions and MCP servers are trusted executable code, not a sandbox. Sele
226
232
 
227
233
  For uncertain direct termination, open `/subagent`, select the exact workflow, and choose **Close/cancel-and-release ALL owned workers in this workflow**. This stops all owned workers, not only the selected one. Resolve reported blockers and repeat the action. Recorded-only tasks cannot release admission. Restarting Pi does not prove termination. Inspect partial changes before new writes; never blindly repeat commits or delete work.
228
234
 
235
+ After Close/cancel-and-release proves pane absence, it terminates the processes that hold the exact private process lease of an owned worker (`SIGTERM`, then `SIGKILL`). Automatic completion, continuation, and Subagent Collection never send signals.
236
+
229
237
  Unverified tab allocations retain evidence but offer no Close action. Reconcile them manually against Herdr; do not recreate tabs, guess IDs, or restart to bypass admission. See [Direct contract](./docs/orchestration.md#direct-contract).
230
238
 
231
239
  After coordinator interruption, restart Pi and run `/subagent recover` in the canonical repository. Use `subagent_status` for exact evidence; never take over a live productive lease or replay uncertain prompts, merges, or promotion. For aborted requests with retained resources, resolve blockers and repeat `subagent_abort`. See [Recover after interruption](./docs/orchestration.md#recover-after-interruption) and [Recovery and state](./docs/orchestration.md#recovery-and-state).
@@ -88,6 +88,7 @@ export function createExactJudgmentExecutor(executor) {
88
88
  };
89
89
  const result = await executor.run({
90
90
  signal: context.signal,
91
+ onActivity: input.launch.onFallbackUse,
91
92
  prepare: async () => ({ launch, task, cwd: input.cwd }),
92
93
  });
93
94
  context.signal.throwIfAborted();
@@ -59,13 +59,15 @@ export declare class DirectAllocationError extends Error {
59
59
  readonly allocation: DirectAllocation;
60
60
  constructor(allocation: DirectAllocation, cause: unknown);
61
61
  }
62
- export declare function createDirectHerdr(pi: Pick<ExtensionAPI, "exec">, cwd: string, idleMs: number): {
62
+ export declare function createDirectHerdr(pi: Pick<ExtensionAPI, "exec">, cwd: string, idleMs: number, kill?: (pid: number, signal: NodeJS.Signals) => void): {
63
63
  workspaceId: string;
64
64
  cwd: string;
65
65
  /** Close only an exact owned pane, then prove it and its leased children stopped.
66
66
  * A task result or Ctrl-C acknowledgement is not termination evidence.
67
- * `settledOnly` refuses to close a listed agent that is not idle or done. */
68
- stop(tab: Pick<DirectTab, "name" | "tabId" | "paneId" | "leasePath">, current?: () => boolean, settledOnly?: boolean): Promise<void>;
67
+ * `settled` refuses to close a listed agent that is not idle or done. Only an explicit
68
+ * user stop or Close uses `terminate`: after pane absence it signals each holder that a
69
+ * per-PID scan still proves holds the exact lease. Other callers only prove. */
70
+ stop(tab: Pick<DirectTab, "name" | "tabId" | "paneId" | "leasePath">, current?: () => boolean, mode?: "proof" | "settled" | "terminate"): Promise<void>;
69
71
  /** Collection preserves the saved conversation and private lease for continuation and recovery. */
70
72
  collect(tab: DirectTab, current: () => boolean): Promise<boolean>;
71
73
  /** `resume` reuses a stopped worker's saved session and private lease instead of a new temp directory. */
@@ -278,7 +278,7 @@ export class DirectAllocationError extends Error {
278
278
  this.allocation = allocation;
279
279
  }
280
280
  }
281
- export function createDirectHerdr(pi, cwd, idleMs) {
281
+ export function createDirectHerdr(pi, cwd, idleMs, kill = (pid, signal) => process.kill(pid, signal)) {
282
282
  if (process.env.HERDR_ENV !== "1")
283
283
  throw new Error("Direct delegation requires a Herdr-managed Pi pane (HERDR_ENV=1).");
284
284
  const workspaceId = field(process.env.HERDR_WORKSPACE_ID, "HERDR_WORKSPACE_ID");
@@ -299,8 +299,10 @@ export function createDirectHerdr(pi, cwd, idleMs) {
299
299
  cwd: workingDir,
300
300
  /** Close only an exact owned pane, then prove it and its leased children stopped.
301
301
  * A task result or Ctrl-C acknowledgement is not termination evidence.
302
- * `settledOnly` refuses to close a listed agent that is not idle or done. */
303
- async stop(tab, current = () => true, settledOnly = false) {
302
+ * `settled` refuses to close a listed agent that is not idle or done. Only an explicit
303
+ * user stop or Close uses `terminate`: after pane absence it signals each holder that a
304
+ * per-PID scan still proves holds the exact lease. Other callers only prove. */
305
+ async stop(tab, current = () => true, mode = "proof") {
304
306
  const requireCurrent = () => { if (!current())
305
307
  throw new Error("Direct task scope changed; reopen /subagent."); };
306
308
  requireCurrent();
@@ -333,7 +335,7 @@ export function createDirectHerdr(pi, cwd, idleMs) {
333
335
  || agent.tab_id !== tab.tabId || agent.workspace_id !== workspaceId || agent.cwd !== workingDir
334
336
  || tab.paneId === callerPane)
335
337
  throw new Error("Worker termination requires one exact owned agent, workspace, checkout, tab and pane match.");
336
- if (settledOnly && agent.agent_status !== "idle" && agent.agent_status !== "done") {
338
+ if (mode === "settled" && agent.agent_status !== "idle" && agent.agent_status !== "done") {
337
339
  throw new Error(`Herdr agent ${tab.name} is ${String(agent.agent_status)}, not idle or done; it was not closed`);
338
340
  }
339
341
  requireCurrent();
@@ -342,13 +344,36 @@ export function createDirectHerdr(pi, cwd, idleMs) {
342
344
  if ((await panes()).some((pane) => pane.pane_id === tab.paneId || pane.tab_id === tab.tabId)) {
343
345
  throw new Error(`Owned pane ${tab.paneId} is still present; termination is unproved.`);
344
346
  }
345
- for (let scan = 0; scan < 2; scan++) {
346
- const holders = await scanProcessLease(tab.leasePath, (args) => pi.exec("lsof", args, { cwd: workingDir, timeout: 3_000 }));
347
+ const scan = (pid) => scanProcessLease(tab.leasePath, (args) => pi.exec("lsof", args, { cwd: workingDir, timeout: 3_000 }), pid);
348
+ let holders = await scan();
349
+ if (mode === "terminate") {
350
+ for (const [signal, wait] of [["SIGTERM", 250], ["SIGKILL", 100]]) {
351
+ if (!holders.length)
352
+ break;
353
+ for (const pid of holders) {
354
+ requireCurrent();
355
+ if (!(await scan(pid)).includes(pid))
356
+ continue;
357
+ requireCurrent();
358
+ try {
359
+ kill(pid, signal);
360
+ }
361
+ catch (error) {
362
+ if (error.code !== "ESRCH")
363
+ throw error;
364
+ }
365
+ }
366
+ await sleep(wait);
367
+ holders = await scan();
368
+ }
347
369
  if (holders.length)
348
- throw new Error(`Owned process lease ${tab.leasePath} still has holders: ${holders.join(", ")}. Stop those owned processes, then retry Close/cancel-and-release.`);
349
- if (scan === 0)
350
- await sleep(50);
370
+ throw new Error(`Owned process lease ${tab.leasePath} still has holders after SIGTERM and SIGKILL: ${holders.join(", ")}. Inspect those processes before retrying Close/cancel-and-release.`);
351
371
  }
372
+ if (holders.length)
373
+ throw new Error(`Owned process lease ${tab.leasePath} still has holders: ${holders.join(", ")}. Stop those owned processes, or use /subagent Stop or Close/cancel-and-release of the owning workflow to terminate them.`);
374
+ await sleep(50);
375
+ if ((await scan()).length)
376
+ throw new Error(`Owned process lease ${tab.leasePath} did not remain empty for two consecutive scans.`);
352
377
  requireCurrent();
353
378
  },
354
379
  /** Collection preserves the saved conversation and private lease for continuation and recovery. */
@@ -365,7 +390,7 @@ export function createDirectHerdr(pi, cwd, idleMs) {
365
390
  throw new Error("Direct collection tab identity or pane count changed.");
366
391
  }
367
392
  await assertSettledDirectSession(tab.sessionFile, tab.turn);
368
- await this.stop(tab, current, true);
393
+ await this.stop(tab, current, "settled");
369
394
  const response = await herdr.exec(["tab", "get", tab.tabId], options());
370
395
  if (!response.killed && hasHerdrErrorCode(response, "tab_not_found"))
371
396
  return true;
@@ -882,11 +882,12 @@ export class HerdrHostRuntime {
882
882
  const agent = parseAgent(parseJsonObject(response.stdout, "Herdr agent start response"), allocation, ["agent_started"]);
883
883
  if (!agent.interactiveReady || agent.status !== "idle")
884
884
  throw new Error("Started Herdr agent is not exactly ready and idle.");
885
- return { kind: "agent", outcome: "owned" };
886
885
  }
887
886
  catch (error) {
888
887
  return { kind: "agent", outcome: "unknown", failure: safeText(error), possibleResources: [allocation.agentName, allocation.paneId] };
889
888
  }
889
+ launch.onFallbackUse?.();
890
+ return { kind: "agent", outcome: "owned" };
890
891
  });
891
892
  }
892
893
  async reconcileDeliveredPrompt(input, allocation, context, prompt, promptMayBeInFlight = true) {
package/dist/index.d.ts CHANGED
@@ -59,10 +59,16 @@ export interface PiLaunch {
59
59
  env: Record<string, string>;
60
60
  args: string[];
61
61
  }
62
+ export type TaskModelFallback = Readonly<{
63
+ profileName: ProfileName;
64
+ model: string;
65
+ thinkingLevel: ThinkingLevel;
66
+ }>;
62
67
  export interface ResolvedRoleLaunch extends PiLaunch {
63
68
  model: AvailableModel;
64
69
  thinkingLevel: ThinkingLevel;
65
70
  missingSkills: string[];
71
+ fallback?: TaskModelFallback;
66
72
  }
67
73
  export interface PreparedRoleLaunch extends ResolvedRoleLaunch {
68
74
  role: RoleName;
@@ -143,7 +149,7 @@ export declare function loadRoleCatalog(agentDir?: string): RoleCatalog;
143
149
  export declare function findRole(catalog: RoleCatalog, name: RoleName): Role;
144
150
  type TaskRouteContext = Parameters<typeof resolveTaskModelRoute>[0];
145
151
  type RoleLaunchContext = TaskRouteContext & Pick<ExtensionContext, "isProjectTrusted">;
146
- export declare function resolveTaskRoute(ctx: TaskRouteContext, profileName: ProfileName, agentDir?: string): ResolvedTaskRoute;
152
+ export declare function resolveTaskRoute(ctx: TaskRouteContext, profileName: ProfileName, agentDir?: string, onFallback?: (profileName: ProfileName, route: ResolvedTaskRoute) => void): ResolvedTaskRoute;
147
153
  export declare function resolveRoleSkills(pi: Pick<ExtensionAPI, "getCommands">, role: Role): ResolvedRoleSkills;
148
154
  /** Resolve all enabled package resources selected by one Role's extension sources. */
149
155
  export declare function resolveRolePackageResources(role: Role, ctx: Pick<ExtensionContext, "cwd" | "isProjectTrusted">): Promise<{
package/dist/index.js CHANGED
@@ -397,18 +397,21 @@ export function findRole(catalog, name) {
397
397
  throw new Error(`Subagent role ${name} is unavailable: ${invalid.map(({ message }) => message).join("; ")}`);
398
398
  throw new Error(`Unknown Subagent role: ${name}. Available roles: ${catalog.roles.map((candidate) => candidate.name).join(", ") || "none"}.${catalog.errors.length ? ` ${catalog.errors.length} invalid Role file(s); run /subagent roles.` : ""}`);
399
399
  }
400
- export function resolveTaskRoute(ctx, profileName, agentDir = getAgentDir()) {
400
+ export function resolveTaskRoute(ctx, profileName, agentDir = getAgentDir(), onFallback) {
401
401
  // A disabled config throws with the path and the problems.
402
402
  const config = loadTaskModelsConfig(agentDir).value;
403
- return resolveConfiguredRoute(ctx, profileName, config.profiles[profileName]);
403
+ return resolveConfiguredRoute(ctx, profileName, config.profiles[profileName], onFallback);
404
404
  }
405
- function resolveConfiguredRoute(ctx, profileName, profile) {
405
+ function resolveConfiguredRoute(ctx, profileName, profile, onFallback) {
406
406
  if (!profile)
407
407
  throw new Error(`No ${profileName} task model profile is configured. Run /task-models.`);
408
408
  for (const route of orderedProfileRoutes(profile)) {
409
409
  const resolved = resolveTaskModelRoute(ctx, route);
410
- if (resolved)
410
+ if (resolved) {
411
+ if (route === profile.fallback)
412
+ onFallback?.(profileName, resolved);
411
413
  return resolved;
414
+ }
412
415
  }
413
416
  throw new Error(`No usable ${profileName} task model route. Run /task-models.`);
414
417
  }
@@ -509,12 +512,17 @@ function prepareRoleLaunchFromSkills(ctx, input, skills) {
509
512
  function prepareResolvedRoleLaunch(pi, ctx, input) {
510
513
  const { task, modelClass, agentDir, ...launchInput } = input;
511
514
  const selectedClass = modelClass ?? input.role.modelClass;
512
- return prepareRoleLaunchFromSkills(ctx, {
515
+ let fallback;
516
+ const onFallback = (profileName, route) => {
517
+ fallback = { profileName, model: modelReference(route.model), thinkingLevel: route.thinkingLevel };
518
+ };
519
+ const prepared = prepareRoleLaunchFromSkills(ctx, {
513
520
  ...launchInput,
514
521
  route: selectedClass === undefined
515
- ? resolveConfiguredTaskRoute(ctx, task, agentDir)
516
- : resolveTaskRoute(ctx, selectedClass, agentDir),
522
+ ? resolveConfiguredTaskRoute(ctx, task, agentDir, undefined, onFallback)
523
+ : resolveTaskRoute(ctx, selectedClass, agentDir, onFallback),
517
524
  }, resolveRoleSkills(pi, input.role));
525
+ return { ...prepared, ...(fallback ? { fallback } : {}) };
518
526
  }
519
527
  export function resolveRoleLaunch(pi, ctx, input) {
520
528
  return finalizeRoleLaunch(prepareResolvedRoleLaunch(pi, ctx, input));
@@ -552,9 +560,12 @@ export async function resolveConfiguredRoleLaunch(pi, ctx, input) {
552
560
  ...namedSkills,
553
561
  paths: [...new Set([...namedSkills.paths, ...resources.skills])],
554
562
  };
563
+ let fallback;
555
564
  const prepared = prepareRoleLaunchFromSkills(ctx, {
556
565
  role: effectiveRole,
557
- route: resolveTaskRoute(ctx, input.modelClass),
566
+ route: resolveTaskRoute(ctx, input.modelClass, undefined, (profileName, route) => {
567
+ fallback = { profileName, model: modelReference(route.model), thinkingLevel: route.thinkingLevel };
568
+ }),
558
569
  }, skills);
559
570
  assertNoMissingRoleSkills(effectiveRole, prepared);
560
571
  const args = [
@@ -564,7 +575,7 @@ export async function resolveConfiguredRoleLaunch(pi, ctx, input) {
564
575
  ...resources.prompts.flatMap((path) => ["--prompt-template", path]),
565
576
  ...resources.themes.flatMap((path) => ["--theme", path]),
566
577
  ];
567
- return { ...prepared, args, promptArgIndex: args.length };
578
+ return { ...prepared, args, promptArgIndex: args.length, ...(fallback ? { fallback } : {}) };
568
579
  }
569
580
  /** Insert the system prompt pair after a caller has prepared its launch argv. */
570
581
  export function finalizeRoleLaunch(prepared) {
@@ -576,6 +587,7 @@ export function finalizeRoleLaunch(prepared) {
576
587
  model: prepared.model,
577
588
  thinkingLevel: prepared.thinkingLevel,
578
589
  missingSkills: prepared.missingSkills,
590
+ ...(prepared.fallback ? { fallback: prepared.fallback } : {}),
579
591
  };
580
592
  }
581
593
  export * from "./composition.js";
@@ -1,4 +1,5 @@
1
1
  import { type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { type TaskModelFallback } from "./index.ts";
2
3
  import type { CoordinatorRuntime, OperationContext, ResolvedRoute, TransientLaunchHandle, VerifiedLaunch } from "./runner.ts";
3
4
  import { type ExecuteRequest, type ModelClass, type WorkspaceIdentity } from "./schema.ts";
4
5
  export declare const ISOLATED_MODEL_TASK: {
@@ -11,6 +12,7 @@ type LaunchPi = Pick<ExtensionAPI, "events" | "getCommands">;
11
12
  export interface LaunchRuntimeOptions {
12
13
  pi: LaunchPi;
13
14
  context(): ExtensionContext;
15
+ captureFallbackWarning?(signal: AbortSignal): (fallback: TaskModelFallback) => void;
14
16
  resolveRoot(cwd: string, context: OperationContext): Promise<string>;
15
17
  preflightHost?(input: {
16
18
  request: ExecuteRequest;
@@ -117,6 +117,7 @@ export class RoleLaunchRuntime {
117
117
  async prepareLaunch(role, modelClass, context) {
118
118
  context.signal?.throwIfAborted();
119
119
  const prepared = await resolveConfiguredRoleLaunch(this.options.pi, this.options.context(), { role, modelClass });
120
+ context.signal.throwIfAborted();
120
121
  return Object.freeze({
121
122
  launch: Object.freeze({
122
123
  role: prepared.role,
@@ -129,6 +130,7 @@ export class RoleLaunchRuntime {
129
130
  }),
130
131
  prompt: prepared.systemPrompt,
131
132
  promptArgIndex: prepared.promptArgIndex,
133
+ ...(prepared.fallback ? { fallback: prepared.fallback } : {}),
132
134
  });
133
135
  }
134
136
  async preflight(input, context) {
@@ -172,7 +174,15 @@ export class RoleLaunchRuntime {
172
174
  return { root, main, routes };
173
175
  }
174
176
  async acquireLaunch(role, modelClass, context) {
177
+ context.signal.throwIfAborted();
178
+ const reportFallback = this.options.captureFallbackWarning?.(context.signal);
175
179
  const prepared = await this.prepareLaunch(role, modelClass, context);
176
- return await materializeTransientLaunch(prepared, context.signal);
180
+ const fallback = prepared.fallback;
181
+ const launch = fallback && reportFallback ? Object.freeze({
182
+ ...prepared.launch,
183
+ onFallbackUse: () => { if (!context.signal.aborted)
184
+ reportFallback(fallback); },
185
+ }) : prepared.launch;
186
+ return await materializeTransientLaunch({ ...prepared, launch }, context.signal);
177
187
  }
178
188
  }
package/dist/runner.d.ts CHANGED
@@ -95,6 +95,8 @@ export interface VerifiedLaunch {
95
95
  readonly args: readonly string[];
96
96
  readonly env: Readonly<Record<string, string>>;
97
97
  readonly tools: readonly string[];
98
+ /** Parent-owned notice; call only after the child starts productive work. */
99
+ readonly onFallbackUse?: () => void;
98
100
  }
99
101
  export type ResolvedRoute = Pick<VerifiedLaunch, "role" | "modelClass" | "model" | "thinkingLevel">;
100
102
  /** A dry-run result: the normalized request and the resolved routes; no state exists for it. */
package/dist/runner.js CHANGED
@@ -2473,6 +2473,7 @@ export class IsolatedRunner {
2473
2473
  const launch = { args: [...verifiedLaunch.args], env: { ...verifiedLaunch.env } };
2474
2474
  return await this.textExecutor.run({
2475
2475
  signal: context.signal,
2476
+ onActivity: verifiedLaunch.onFallbackUse,
2476
2477
  prepare: async () => ({ launch, task: prompt, cwd: isolated.cwd }),
2477
2478
  });
2478
2479
  });
@@ -97,11 +97,11 @@ A write request runs its tasks in sequence. It holds checkout admission after th
97
97
 
98
98
  A failure in a write request stops further dispatch, but a worker with an uncertain state can still run. Chains replace each literal `{previous}` with the preceding successful answer and stop on failure. Task outcome and worker termination are separate.
99
99
 
100
- After settlement, the coordinator closes exact owned writer panes. It releases admission only after pane absence and two empty private process-lease scans. This proof requires native `lsof`. The coordinator removes no Git files, commits, or saved sessions. A failure stays a failure even when the coordinator releases admission.
100
+ After settlement, the coordinator closes exact owned writer panes. It releases admission only after pane absence and two empty private process-lease scans. This proof requires native `lsof`. This automatic step sends no signals, so a background process that the worker started and that holds its lease keeps admission held. The coordinator removes no Git files, commits, or saved sessions. A failure stays a failure even when the coordinator releases admission.
101
101
 
102
102
  Admission stays held if the close fails, identity changes, a leased child survives, or inspection is uncertain. In that case, open `/subagent`. Select the exact direct workflow. Then choose **Close/cancel-and-release ALL owned workers in this workflow** to cancel dispatch and try termination again. This action stops every owned worker of that workflow, not one selected worker.
103
103
 
104
- The action checks session, branch, epoch, and live ownership. Recorded-only tasks cannot unlock anything. Resolve the reported blocker, including any surviving owned process. Then do the same action again. A restart of Pi is not termination proof.
104
+ The action checks session, branch, epoch, and live ownership. Recorded-only tasks cannot unlock anything. After it proves pane absence, it sends `SIGTERM` to each process that holds the exact private lease of an owned worker. Then it sends `SIGKILL` to each process that survives. Before each signal, it scans the lease again for that PID, and it does not signal a PID that no longer holds the lease. If a holder survives, a scan fails, or ownership changes, admission stays held. Resolve the reported blocker, then do the same action again. A restart of Pi is not termination proof.
105
105
 
106
106
  Inspect partial changes before new writes. To recover, never retry a commit or delete work without inspection.
107
107
 
@@ -127,11 +127,11 @@ Before launch, the request fails if the reference is unknown or matches more tha
127
127
 
128
128
  If Herdr still lists the old agent, the agent must match the recorded name, pane, tab, workspace, and checkout. It must also be idle or done. The extension never closes a working or blocked agent. The extension closes the old pane, then proves pane absence and two empty lease scans.
129
129
 
130
- An absent old agent still requires two empty lease scans.
130
+ An absent old agent still requires two empty lease scans. Continuation and Subagent Collection never send signals to lease holders.
131
131
 
132
132
  Records saved before 27.0.0 have no turn identity. The extension cannot continue them. For these records, start a new task.
133
133
 
134
- In a running workflow that has only `read` tasks, `/subagent` shows **Stop this worker** for each running worker. It aborts only that worker, sends Ctrl-C, closes its exact pane, and proves pane absence and two empty lease scans. The result of the worker becomes a failure, `Stopped by user from /subagent`, and keeps any partial output. Other workers continue, but a chain stops its later steps.
134
+ In a running workflow that has only `read` tasks, `/subagent` shows **Stop this worker** for each running worker. It aborts only that worker, sends Ctrl-C, closes its exact pane, and proves pane absence. Then it terminates the remaining lease holders of that worker as Close does, and proves two empty lease scans. The result of the worker becomes a failure, `Stopped by user from /subagent`, and keeps any partial output. Other workers continue, but a chain stops its later steps.
135
135
 
136
136
  If the extension cannot prove termination of the stopped worker, the workflow keeps local ownership. So **Close/cancel-and-release** stays available. Main receives one result when the workflow finishes. A workflow with a `write` task offers only **Close/cancel-and-release ALL owned workers in this workflow**. Both actions check session, branch, and epoch, so a stale dialog cannot act.
137
137
 
@@ -39,6 +39,7 @@ import {
39
39
  } from "../dist/schema.js";
40
40
  import { FileRunStore } from "../dist/store.js";
41
41
  import { workerOutputForMain } from "./result-transport.ts";
42
+ import { captureFallbackWarning } from "./task-model-fallback.ts";
42
43
  import type { CleanupReport, IsolatedInventory, IsolatedRequest, PrunePlan } from "./subagent-command.ts";
43
44
  import type { DiscardPlan } from "../dist/discard.js";
44
45
 
@@ -58,6 +59,7 @@ export interface IsolatedExtensionComponents {
58
59
  export type CreateIsolatedComponents = (options: {
59
60
  pi: ExtensionAPI;
60
61
  context(): ExtensionContext;
62
+ captureFallbackWarning?: LaunchRuntimeOptions["captureFallbackWarning"];
61
63
  executor: EphemeralSubagentExecutor;
62
64
  policy: ExecutionPolicySnapshot;
63
65
  currentPolicy(): ExecutionPolicySnapshot;
@@ -66,7 +68,7 @@ export type CreateIsolatedComponents = (options: {
66
68
 
67
69
  /** Construct the checked runtime while reusing the unified productive-assignment executor. */
68
70
  export const createIsolatedComponents: CreateIsolatedComponents = ({
69
- pi, context, executor, policy, currentPolicy, onStateSaved,
71
+ pi, context, captureFallbackWarning, executor, policy, currentPolicy, onStateSaved,
70
72
  }) => {
71
73
  const runProcess: DirectProcessRunner = async (command, args, options) => options.stdin === undefined
72
74
  ? await pi.exec(command, args, { cwd: options.cwd, signal: options.signal, timeout: options.timeoutMs })
@@ -82,6 +84,7 @@ export const createIsolatedComponents: CreateIsolatedComponents = ({
82
84
  const coordinator = new RoleLaunchRuntime({
83
85
  pi,
84
86
  context,
87
+ captureFallbackWarning,
85
88
  resolveRoot,
86
89
  preflightHost: async ({ root }, operation) => await host.preflightHost({ root }, operation),
87
90
  inspectMainBase: async (input, operation) => await git.inspectMainBase(input, operation),
@@ -568,6 +571,13 @@ export function registerIsolatedExtension(pi: ExtensionAPI, options: RegisterIso
568
571
  options.beforeRoleLaunch?.(ctx);
569
572
  return ctx;
570
573
  },
574
+ captureFallbackWarning: (signal) => {
575
+ const ctx = latestContext();
576
+ const epoch = sessionEpoch;
577
+ const sessionId = ctx.sessionManager.getSessionId();
578
+ return captureFallbackWarning(pi, ctx, () => !sessionClosed && sessionEpoch === epoch
579
+ && latestCtx?.sessionManager.getSessionId() === sessionId, signal);
580
+ },
571
581
  executor: options.executor,
572
582
  policy: options.policy,
573
583
  currentPolicy: options.currentPolicy,
@@ -344,9 +344,11 @@ async function choose<T>(ctx: ExtensionContext, title: string, items: readonly C
344
344
  }
345
345
  return ctx.ui.custom<T | undefined>((tui, theme, _keys, done) => {
346
346
  const rows = labels.map((label, index) => ({ label, value: String(index) }));
347
+ // The menu replaces the editor, not the screen; cap its height to leave room for other content.
348
+ const menuHeight = () => Math.max(1, Math.floor(tui.terminal.rows / 2));
347
349
  const createList = () => {
348
- // Reserve title, key hints, and the native scroll indicator. Very short terminals show only the list.
349
- const height = tui.terminal.rows;
350
+ // Reserve title, key hints, and the native scroll indicator. Very short menus show only the list.
351
+ const height = menuHeight();
350
352
  const list = new SelectList(rows, Math.max(1, height - (height >= 4 ? 3 : 1)), getSelectListTheme());
351
353
  list.setSelectedIndex(selectedIndex);
352
354
  list.onSelectionChange = ({ value }) => { selectedIndex = Number(value); };
@@ -359,7 +361,7 @@ async function choose<T>(ctx: ExtensionContext, title: string, items: readonly C
359
361
  render(width) {
360
362
  list = createList();
361
363
  const lines = list.render(width);
362
- if (tui.terminal.rows < 4) return lines.slice(0, tui.terminal.rows);
364
+ if (menuHeight() < 4) return lines.slice(0, menuHeight());
363
365
  return [truncateToWidth(theme.fg("accent", title), width), ...lines,
364
366
  truncateToWidth([`${keyText("tui.select.up")}/${keyText("tui.select.down")} scroll`,
365
367
  keyHint("tui.select.confirm", "select"), keyHint("tui.select.cancel", "cancel")].join(" · "), width)];
@@ -367,7 +369,7 @@ async function choose<T>(ctx: ExtensionContext, title: string, items: readonly C
367
369
  handleInput(data) { list.handleInput(data); tui.requestRender(); },
368
370
  invalidate() { list.invalidate(); },
369
371
  };
370
- }, { overlay: true, overlayOptions: { width: "100%", maxHeight: "100%", margin: 0 } });
372
+ });
371
373
  }
372
374
 
373
375
  /** Multi-select on single-choice menus: each pick toggles one row until Continue. Returns chosen values in
@@ -5,6 +5,7 @@ import { availableTaskModels, loadTaskModelsConfig, modelReference, type Profile
5
5
  import { registerConfigReporting } from "@henryqw/pi-config-store";
6
6
  import { capEphemeralSubagentOutput as capOutput, createEphemeralSubagentExecutor, createSubagentConfigStore, DEFAULT_SUBAGENT_CONFIG, DELEGATE_TASK, findRole, formatDuration, loadRoleCatalog, prepareRoleLaunch, resolveRolePackageResources, resolveTaskRoute, ROLE_TOOL_POLICY_FLAG, type ExecutionPolicySnapshot, type Role } from "@henryqw/pi-subagent";
7
7
  import { resolveExecutionPolicy } from "./config.ts";
8
+ import { captureFallbackWarning } from "./task-model-fallback.ts";
8
9
  import { registerCheckoutAdmission } from "./admission.ts";
9
10
  import { registerIsolatedExtension } from "./isolated.ts";
10
11
  import { directRef, registerSubagentCommand, type DirectDisplay, type DirectTask } from "./subagent-command.ts";
@@ -259,7 +260,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
259
260
  const directTasks = new Map<string, {
260
261
  controller: AbortController; settled: Promise<void>; handles: DirectHandle[]; tabs: DirectTabRecord[];
261
262
  pendingResult?: (sessionId: string) => boolean;
262
- close?: (current: () => boolean) => Promise<void>; closeScope?: () => boolean; allocation?: DirectAllocationRecord; recovery?: string;
263
+ close?: (current: () => boolean, terminate?: boolean) => Promise<void>; closeScope?: () => boolean; allocation?: DirectAllocationRecord; recovery?: string;
263
264
  /** Saved sessions this task continues; claimed before any await so a second request cannot reuse them. */
264
265
  continues?: ReadonlySet<string>;
265
266
  /** Read workflows only: stop one running worker while siblings continue. */
@@ -406,7 +407,8 @@ export default function subagentExtension(pi: ExtensionAPI): void {
406
407
  await local.settled;
407
408
  // Automatic settlement may already have proved termination and released it.
408
409
  if (!current()) throw new Error("Direct task scope changed; reopen /subagent.");
409
- if (directTasks.has(task.id)) await local.close(owned);
410
+ // Only this explicit Close may signal exact lease holders; automatic settlement only proves.
411
+ if (directTasks.has(task.id)) await local.close(owned, true);
410
412
  return "All owned workers in this workflow stopped; checkout admission released. Dirty files, commits and session evidence preserved. Inspect changes before retrying work.";
411
413
  },
412
414
  async stopDirect(task, entryId, current) {
@@ -432,9 +434,10 @@ export default function subagentExtension(pi: ExtensionAPI): void {
432
434
  if (Buffer.byteLength(snapshot, "utf8") > 32_000) throw new Error("Status exceeds the 32 KiB inspection limit; use subagent_status for exact evidence.");
433
435
  reportConfig(ctx);
434
436
  const role = findRole(loadRoleCatalog(), "scout");
437
+ const controller = new AbortController();
438
+ const reportFallback = captureFallbackWarning(pi, ctx, current, controller.signal);
435
439
  const prepared = await prepareDirectLaunch(role, ctx, { modelClass: "fast" });
436
440
  const herdr = createDirectHerdr(pi, ctx.cwd, currentPolicy().childIdleMs);
437
- const controller = new AbortController();
438
441
  const taskId = `inspect-${id}-${randomUUID()}`;
439
442
  const display: DirectDisplay = { workflow: nextWorkflow(ctx), worker: 1, workers: 1, title: `Inspect ${id}`, role: role.name };
440
443
  const recordEpoch = directRecordEpoch;
@@ -465,6 +468,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
465
468
  await handle.cancel();
466
469
  throw new Error(`Session changed during inspection launch; inspect Herdr tab ${handle.tabId}.`);
467
470
  }
471
+ if (prepared.fallback) reportFallback(prepared.fallback);
468
472
  return { ref: directRef(display), tabId: handle.tabId, name: handle.name, sessionFile: handle.sessionFile };
469
473
  } finally {
470
474
  directTasks.delete(taskId);
@@ -873,17 +877,17 @@ export default function subagentExtension(pi: ExtensionAPI): void {
873
877
  const proof = (async () => {
874
878
  entryControllers.get(entryId)!.abort();
875
879
  await handle.cancel().catch(() => undefined);
876
- await herdr.stop(tab, inScope);
880
+ await herdr.stop(tab, inScope, "terminate");
877
881
  })();
878
882
  stopProofs.set(entryId, proof);
879
883
  return proof;
880
884
  },
881
885
  };
882
- local.close = async (current) => {
886
+ local.close = async (current, terminate = false) => {
883
887
  const inScope = () => current() && (local.closeScope?.() ?? true);
884
888
  try {
885
889
  if (local.allocation) throw new Error(local.allocation.failure);
886
- for (const tab of tabs) await herdr.stop(tab, inScope);
890
+ for (const tab of tabs) await herdr.stop(tab, inScope, terminate ? "terminate" : "proof");
887
891
  if (!inScope()) throw new Error("Direct task scope changed; reopen /subagent.");
888
892
  releaseAdmission();
889
893
  directTasks.delete(taskId);
@@ -897,12 +901,15 @@ export default function subagentExtension(pi: ExtensionAPI): void {
897
901
  const answerBytes = Math.floor(40 * 1024 / entries.length);
898
902
  const launch = async (entry: WorkflowEntry, activeSignal: AbortSignal) => {
899
903
  activeSignal.throwIfAborted();
904
+ const reportFallback = captureFallbackWarning(pi, ctx, () => launchEpoch === sessionEpoch
905
+ && (latestCtx ?? ctx).sessionManager.getSessionId() === launchSessionId, activeSignal);
900
906
  // A later worker launches after earlier ones finish; report and revalidate config edits made meanwhile.
901
907
  beforeRoleLaunch(latestCtx ?? ctx);
902
908
  const role = findRole(loadRoleCatalog(), entry.delegation.role);
903
909
  const { modelClass, model } = entry.delegation;
904
910
  const prepared = await prepareDirectLaunch(role, latestCtx ?? ctx, {
905
911
  ...(modelClass === undefined ? {} : { modelClass }), ...(model === undefined ? {} : { model }) });
912
+ activeSignal.throwIfAborted();
906
913
  states.set(entry.id, { ...states.get(entry.id)!, model: modelReference(prepared.model), thinkingLevel: prepared.thinkingLevel, status: "running", assistantOutput: "" });
907
914
  startedAt.set(entry.id, Date.now());
908
915
  const display = displayOf(entry);
@@ -933,6 +940,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
933
940
  handles.push(handle);
934
941
  handleByEntry.set(entry.id, handle);
935
942
  if (widgetItems.has(entry.id)) tokenHandles.set(entry.id, handle);
943
+ if (prepared.fallback) reportFallback(prepared.fallback);
936
944
  if (launchEpoch === sessionEpoch) automaticCollection(ctx);
937
945
  return handle;
938
946
  };
@@ -946,7 +954,7 @@ export default function subagentExtension(pi: ExtensionAPI): void {
946
954
  try {
947
955
  await assertSettledDirectSession(source.sessionFile, source.turn);
948
956
  // Close only an idle or done exact agent; an absent one still needs two empty lease scans.
949
- await herdr.stop(source, () => launchEpoch === sessionEpoch && !controller.signal.aborted, true);
957
+ await herdr.stop(source, () => launchEpoch === sessionEpoch && !controller.signal.aborted, "settled");
950
958
  } catch (error) {
951
959
  throw new Error(`Cannot continue ${workflow.delegations[index]!.continueFrom}: ${error instanceof Error ? error.message : String(error)}.`, { cause: error });
952
960
  }
@@ -0,0 +1,29 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { TaskModelFallback } from "../dist/index.js";
3
+
4
+ // Keep one warning per parent session and route, including after extension reloads.
5
+ const FALLBACK_WARNINGS = Symbol.for("pi-subagent/task-model-fallback-warnings");
6
+
7
+ export function captureFallbackWarning(
8
+ pi: Pick<ExtensionAPI, "sendMessage">,
9
+ ctx: ExtensionContext,
10
+ current: () => boolean,
11
+ signal: AbortSignal,
12
+ ): (fallback: TaskModelFallback) => void {
13
+ const sessionId = ctx.sessionManager.getSessionId();
14
+ return ({ profileName, model, thinkingLevel }) => {
15
+ if (signal.aborted || !current() || ctx.sessionManager.getSessionId() !== sessionId) return;
16
+ const message = `Task model profile ${profileName}: primary route is unavailable; selected fallback ${JSON.stringify(model)} (thinking ${thinkingLevel}).`;
17
+ const state = globalThis as { [FALLBACK_WARNINGS]?: WeakMap<object, { sessionId: string; shown: Set<string> }> };
18
+ const sessions = state[FALLBACK_WARNINGS] ??= new WeakMap();
19
+ let warnings = sessions.get(ctx.sessionManager);
20
+ if (warnings?.sessionId !== sessionId) {
21
+ warnings = { sessionId, shown: new Set() };
22
+ sessions.set(ctx.sessionManager, warnings);
23
+ }
24
+ if (warnings.shown.has(message)) return;
25
+ if (ctx.hasUI) ctx.ui.notify(message, "warning");
26
+ else pi.sendMessage({ customType: "pi-subagent-model-fallback", content: message, display: true }, { triggerTurn: false, deliverAs: "followUp" });
27
+ warnings.shown.add(message);
28
+ };
29
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@henryqw/pi-subagent",
3
- "version": "27.14.2",
3
+ "version": "27.15.0",
4
4
  "description": "Delegate bounded direct work or durable checked isolated task graphs to Pi roles.",
5
5
  "keywords": [
6
6
  "pi-package",
@@ -74,7 +74,7 @@
74
74
  "@henryqw/pi-herdr": "^0.6.0",
75
75
  "@henryqw/pi-multi-codex": "^3.0.0",
76
76
  "@henryqw/pi-process": "^0.2.0",
77
- "@henryqw/pi-task-models": "^9.0.0",
77
+ "@henryqw/pi-task-models": "^9.2.0",
78
78
  "proper-lockfile": "^4.1.2"
79
79
  },
80
80
  "devDependencies": {