pi-better-subagents 0.28.1 → 0.29.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
@@ -43,14 +43,22 @@ import { STEER_FILE_ENV, readSteerReceipt } from "./child-steer.ts";
43
43
  import {
44
44
  decideTiming,
45
45
  describeTiming,
46
+ DEFAULT_TIMING_MINUTES,
46
47
  emptyProgress,
47
48
  foldProgress,
48
49
  formatTimingLimits,
50
+ isTimingMinutes,
49
51
  isProgressRelevantLine,
50
52
  resolveRunTiming,
51
53
  steerText,
54
+ stuckAlertText,
55
+ TIMING_ENV,
52
56
  timingParameterSchemas,
57
+ toolWaitAlertText,
58
+ validatedTimingMinutes,
59
+ type OpenCallRecord,
53
60
  type ProgressState,
61
+ type TimingSettings,
54
62
  type TimingParams,
55
63
  type TimingStopReason,
56
64
  } from "./timing.ts";
@@ -222,13 +230,15 @@ import { defaultUserRoot, type CatalogSnapshot } from "./catalog-store.ts";
222
230
  import { restrictContextFilesToWorktree } from "./shared-worktree-context.ts";
223
231
 
224
232
  const SUBAGENT_MODE_ACTIONS: readonly AutocompleteItem[] = [
225
- { value: "settings", label: "settings", description: "Open delegation mode and concurrency settings" },
233
+ { value: "settings", label: "settings", description: "Open delegation, concurrency, and timing settings" },
226
234
  { value: "cap", label: "cap <number>", description: "Set a positive concurrent subagent limit for this session" },
227
- { value: "reset", label: "reset", description: "Reset session mode and cap to saved defaults" },
235
+ { value: "tool-wait", label: "tool-wait <minutes>", description: "Set the session tool-wait alert time; 0 turns it off" },
236
+ { value: "stuck", label: "stuck <minutes>", description: "Set the session no-progress alert time; 0 turns it off" },
237
+ { value: "reset", label: "reset", description: "Reset session mode, cap, and timing alerts to saved defaults" },
228
238
  { value: "mode manual", label: "mode manual", description: "Delegate only when explicitly requested" },
229
239
  { value: "mode adaptive", label: "mode adaptive", description: "Delegate substantial independent work" },
230
240
  { value: "mode coordinator", label: "mode coordinator", description: "Delegate role-owned work by default" },
231
- { value: "save", label: "save", description: "Save the current mode and cap as defaults" },
241
+ { value: "save", label: "save", description: "Save the current mode, cap, and timing alerts as defaults" },
232
242
  ];
233
243
 
234
244
  export function subagentsArgumentCompletions(argumentPrefix: string): AutocompleteItem[] | null {
@@ -827,7 +837,9 @@ function readProgress(meta: RunMeta): ProgressState {
827
837
  const read = readAppendedLines(logPathFor(meta.id), entry?.cursor);
828
838
  // A fresh (or restarted) fold may have lost the start of a call that is still
829
839
  // running: seed it from the durable record rather than reporting silence.
830
- if (!entry || read.restarted) entry = { state: emptyProgress(meta.startedAt, meta.timing?.inFlight) };
840
+ if (!entry || read.restarted) {
841
+ entry = { state: emptyProgress(meta.startedAt, meta.timing?.openCalls ?? meta.timing?.inFlight) };
842
+ }
831
843
  if (read.error === undefined) entry.cursor = read.cursor;
832
844
  for (const line of read.lines) {
833
845
  if (!isProgressRelevantLine(line)) continue;
@@ -867,11 +879,19 @@ function fmtWindow(ms: number): string {
867
879
  return minutes >= 1 ? `${minutes}m` : `${Math.max(1, Math.round(ms / 1000))}s`;
868
880
  }
869
881
 
882
+ function sameOpenCalls(a: readonly OpenCallRecord[] | undefined, b: readonly OpenCallRecord[]): boolean {
883
+ return a !== undefined && a.length === b.length && a.every((call, index) => {
884
+ const next = b[index];
885
+ return next !== undefined && call.id === next.id && call.since === next.since
886
+ && call.name === next.name && call.command === next.command;
887
+ });
888
+ }
889
+
870
890
  /**
871
891
  * One parent wake for a timing event. The marker records a handoff (or an
872
892
  * intentional suppression), so reloads and later ticks never repeat it.
873
893
  */
874
- function deliverTimingWake(pi: ExtensionAPI | undefined, meta: RunMeta, kind: "deadline" | "stuck", key: string,
894
+ function deliverTimingWake(pi: ExtensionAPI | undefined, meta: RunMeta, kind: "deadline" | "stuck" | "tool-wait", key: string,
875
895
  content: string, isHandled: (current: RunMeta) => boolean, markHandled: (at: number) => void): void {
876
896
  if (!callbackSuppressionReason(meta)) {
877
897
  try { uiCtx?.ui.notify(content, "warning"); } catch { /* ignore */ }
@@ -942,23 +962,40 @@ function enforceTiming(pi: ExtensionAPI | undefined, meta: RunMeta, now: number)
942
962
  return timing.ceilingAt !== undefined && now >= timing.ceilingAt ? stopForTiming(pi, meta.id, "ceiling", now) : false;
943
963
  }
944
964
  if (meta.status !== "running") return false;
945
- // Progress is folded whenever a control can use it: the stuck window, or a deadline whose
946
- // steer must be held behind a running call (the record of that call must exist before the
947
- // deadline, not only after it).
948
- const needsProgress = timing.stuckMs !== undefined || timing.deadlineAt !== undefined;
965
+ // Progress is folded whenever a control can use it: the stuck or tool-wait
966
+ // window, or a deadline whose steer must be held behind a running call (the
967
+ // record of that call must exist before the deadline, not only after it).
968
+ const needsProgress = timing.stuckMs !== undefined || timing.toolWaitMs !== undefined || timing.deadlineAt !== undefined;
949
969
  const progress = needsProgress ? readProgress(meta) : undefined;
950
970
  const patch: Partial<NonNullable<RunMeta["timing"]>> = {};
951
971
  if (progress?.lastProgressAt !== undefined && progress.lastProgressAt > (timing.lastProgressAt ?? 0)) patch.lastProgressAt = progress.lastProgressAt;
952
972
  if (progress) {
953
- // Durable still-alive evidence: the call the child is waiting on. Survives a
954
- // reload whose bounded log read no longer contains the call's start (#620).
955
- const openId = progress.open.keys().next().value as string | undefined;
956
- const since = progress.inFlightSince ?? progress.lastEventAt ?? meta.startedAt;
973
+ const openCalls: OpenCallRecord[] = [...progress.open.entries()].map(([id, call]) => ({
974
+ id, since: call.startedAt,
975
+ ...(call.name ? { name: call.name } : {}),
976
+ ...(call.command !== undefined ? { command: call.command.slice(0, 200) } : {}),
977
+ }));
978
+ const first = openCalls[0];
979
+ const openId = first?.id;
980
+ const since = progress.inFlightSince ?? first?.since ?? progress.lastEventAt ?? meta.startedAt;
981
+ // Durable still-alive evidence: every call the child is waiting on. Survives a
982
+ // reload whose bounded log read no longer contains a call's start (#620).
983
+ if (openCalls.length > 0) {
984
+ if (!sameOpenCalls(timing.openCalls, openCalls)) patch.openCalls = openCalls;
985
+ } else if (timing.openCalls !== undefined) {
986
+ patch.openCalls = undefined;
987
+ }
957
988
  if (openId === undefined) {
958
989
  if (timing.inFlight !== undefined) patch.inFlight = undefined;
959
990
  } else if (timing.inFlight?.id !== openId || timing.inFlight.since !== since) {
960
991
  patch.inFlight = { id: openId, since };
961
992
  }
993
+ // A finished call needs no marker. Keeping only live call ids bounds the record.
994
+ const openIds = new Set(openCalls.map((call) => call.id));
995
+ const alerted = (timing.toolWaitAlerted ?? []).filter((id) => openIds.has(id));
996
+ if (alerted.length !== (timing.toolWaitAlerted ?? []).length) {
997
+ patch.toolWaitAlerted = alerted.length > 0 ? alerted : undefined;
998
+ }
962
999
  }
963
1000
  if (timing.steerRequestedAt !== undefined && timing.steerDeliveredAt === undefined) {
964
1001
  // The child's receipt for this run's steer; clamped so a skewed clock cannot move grace earlier than the request.
@@ -980,17 +1017,44 @@ function enforceTiming(pi: ExtensionAPI | undefined, meta: RunMeta, now: number)
980
1017
  deliverTimingWake(pi, meta, "deadline", "deadline",
981
1018
  `Subagent ${timingLabel(meta)} reached its ${limit} soft deadline. The harness told it to stop starting new work, ` +
982
1019
  `commit what is done, and report. The message reaches it after its current tool call; if it has not finished ${fmtWindow(t.graceMs)} after that, ` +
983
- `the harness stops it (reason: deadline). ` +
984
- `Its completion or stop is reported here; no action is needed now.`,
1020
+ `the harness stops it (reason: deadline).`,
985
1021
  (current) => current.timing?.deadlineWakeSentAt !== undefined,
986
1022
  (at) => { patchTiming(meta.id, { deadlineWakeSentAt: at }); });
987
1023
  }
1024
+ for (const wake of actions.toolWaitWakes ?? []) {
1025
+ const lastProgressAt = Math.max(progress?.lastProgressAt ?? 0, meta.timing?.lastProgressAt ?? 0) || undefined;
1026
+ const content = toolWaitAlertText({
1027
+ id: meta.id,
1028
+ label: timingLabel(meta),
1029
+ callId: wake.callId,
1030
+ toolName: wake.name ?? "",
1031
+ ...(wake.command !== undefined ? { command: wake.command } : {}),
1032
+ openMs: wake.ageMs,
1033
+ thresholdMs: meta.timing?.toolWaitMs ?? wake.ageMs,
1034
+ now,
1035
+ ...(lastProgressAt !== undefined ? { lastProgressAt } : {}),
1036
+ logPath: meta.logPath,
1037
+ });
1038
+ deliverTimingWake(pi, meta, "tool-wait", `tool-wait:${wake.callId}`, content,
1039
+ (current) => (current.timing?.toolWaitAlerted ?? []).includes(wake.callId),
1040
+ () => {
1041
+ const current = readMeta(meta.id);
1042
+ const alerted = current?.timing?.toolWaitAlerted ?? [];
1043
+ if (!alerted.includes(wake.callId)) {
1044
+ patchTiming(meta.id, { toolWaitAlerted: [...alerted, wake.callId] });
1045
+ }
1046
+ });
1047
+ }
988
1048
  if (actions.stuckWake) {
989
1049
  const { anchorAt, ageMs } = actions.stuckWake;
1050
+ const lastProgressAt = Math.max(progress?.lastProgressAt ?? 0, meta.timing?.lastProgressAt ?? 0) || undefined;
990
1051
  deliverTimingWake(pi, meta, "stuck", `stuck:${anchorAt}`,
991
- `Subagent ${timingLabel(meta)} looks stuck: no progress for ${fmtWindow(ageMs)}. Its successful tool calls, if any, only repeated earlier calls ` +
992
- `(same tool, same arguments), for example re-reading the same file or re-running the same command; time inside running tool calls is not counted. ` +
993
- `It is still running and will not be stopped for this; this is reported once. Inspect it with subagent_output before deciding to stop it.`,
1052
+ stuckAlertText({
1053
+ id: meta.id, label: timingLabel(meta), ageMs,
1054
+ windowMs: meta.timing?.stuckMs ?? ageMs, now,
1055
+ ...(lastProgressAt !== undefined ? { lastProgressAt } : {}),
1056
+ logPath: meta.logPath,
1057
+ }),
994
1058
  (current) => current.timing?.stuckWakeSentAt !== undefined && (current.timing.stuckAnchorAt ?? 0) >= anchorAt,
995
1059
  (at) => { patchTiming(meta.id, { stuckWakeSentAt: at, stuckAnchorAt: anchorAt }); });
996
1060
  }
@@ -1625,10 +1689,10 @@ function returnWidgetNavToInput(): void {
1625
1689
  exitWidgetNav();
1626
1690
  }
1627
1691
 
1628
- function viewWidgetNavSelection(ctx: ExtensionContext): void {
1692
+ function viewWidgetNavSelection(ctx: ExtensionContext, owner?: symbol): void {
1629
1693
  const selected = selectedWidgetNavRun();
1630
1694
  if (!selected) return;
1631
- openNavigator(ctx, selected.id);
1695
+ openNavigator(ctx, selected.id, owner);
1632
1696
  }
1633
1697
 
1634
1698
  function stopWidgetNavSelection(ctx: ExtensionContext): void {
@@ -1640,9 +1704,9 @@ function stopWidgetNavSelection(ctx: ExtensionContext): void {
1640
1704
  }
1641
1705
 
1642
1706
  /** Open the focused navigator overlay. No-op without a UI or visible runs. */
1643
- function openNavigator(ctx: ExtensionContext, initialDetailId?: string): void {
1707
+ function openNavigator(ctx: ExtensionContext, initialDetailId?: string, owner?: symbol): void {
1644
1708
  void initialDetailId;
1645
- ensureNavigator(ctx);
1709
+ ensureNavigator(ctx, owner);
1646
1710
  }
1647
1711
 
1648
1712
  /** Refresh the shared navigator after run changes. */
@@ -1651,7 +1715,7 @@ function updateNavigatorFooter(ctx: ExtensionContext | undefined): void {
1651
1715
  }
1652
1716
 
1653
1717
  /** Install the empty-editor ← wrapper once per UI (reload-safe, composable). */
1654
- function ensureNavigator(ctx: ExtensionContext): void {
1718
+ function ensureNavigator(ctx: ExtensionContext, owner?: symbol): void {
1655
1719
  if (!isNavigatorUiAvailable(ctx)) return;
1656
1720
  try {
1657
1721
  ensureSubagentProvider();
@@ -1662,7 +1726,7 @@ function ensureNavigator(ctx: ExtensionContext): void {
1662
1726
  matchKey: (data: string, keyId: string) => matchesKey(data, keyId),
1663
1727
  truncate: truncateToWidth,
1664
1728
  createTranscriptComponent: createSubagentTranscriptComponent,
1665
- });
1729
+ }, owner);
1666
1730
  } catch { /* ignore */ }
1667
1731
  }
1668
1732
 
@@ -2012,10 +2076,13 @@ export default function (pi: ExtensionAPI) {
2012
2076
  restrictContextFilesToWorktree(event.systemPromptOptions, PiCodingAgent.getAgentDir());
2013
2077
  });
2014
2078
  initializeNavigatorPanels(pi);
2079
+ // Each cached factory instance owns the navigator it installs (#460).
2080
+ const navigatorOwner = Symbol("subagents navigator factory");
2015
2081
  const agentSessionSettings = createAgentSessionSettings(pi);
2016
2082
  let catalogModelRegistry: ExtensionContext["modelRegistry"] | undefined;
2017
2083
  let delegationOverride: DelegationMode | undefined;
2018
2084
  let capOverride: number | undefined;
2085
+ let timingOverride: { toolWaitMinutes?: number; stuckMinutes?: number } = {};
2019
2086
  interface SkillSelection { mode: SkillExposureMode; paths: string[] }
2020
2087
  let skillsOverride: SkillSelection | undefined;
2021
2088
  const savedSkills = (): SkillSelection & { source: "config" | "default"; error?: string } => {
@@ -2060,11 +2127,60 @@ export default function (pi: ExtensionAPI) {
2060
2127
  return { value: skillsOverride.mode === "none" ? [] : [...skillsOverride.paths] };
2061
2128
  };
2062
2129
  const activeConcurrencyCap = (): number => capOverride ?? normalizeConcurrencyCap(loadConfig().maxConcurrent);
2130
+ const timingSettingsFor = (cfg = loadConfig()): TimingSettings => ({ ...cfg, ...timingOverride });
2131
+ interface TimingMinutesState {
2132
+ toolWaitMinutes: number;
2133
+ stuckMinutes: number;
2134
+ toolWaitSource: "environment" | "session" | "config" | "default";
2135
+ stuckSource: "environment" | "session" | "config" | "default";
2136
+ defaultToolWaitMinutes: number;
2137
+ defaultStuckMinutes: number;
2138
+ timingError?: string;
2139
+ }
2140
+ const timingState = (): TimingMinutesState => {
2141
+ const cfg = loadConfig();
2142
+ const envFor = (key: "toolWaitMinutes" | "stuckMinutes"): string | undefined => {
2143
+ const raw = key === "toolWaitMinutes" ? process.env[TIMING_ENV.toolWait] : process.env[TIMING_ENV.stuck];
2144
+ return raw !== undefined && raw.trim() !== "" ? raw : undefined;
2145
+ };
2146
+ const sourceFor = (key: "toolWaitMinutes" | "stuckMinutes"): "environment" | "session" | "config" | "default" =>
2147
+ envFor(key) !== undefined ? "environment"
2148
+ : timingOverride[key] !== undefined ? "session"
2149
+ : cfg[key] !== undefined && cfg[key] !== null ? "config" : "default";
2150
+ try {
2151
+ const effective = resolveRunTiming({ settings: timingSettingsFor(cfg), env: process.env, startedAt: 0 });
2152
+ const defaults = resolveRunTiming({ settings: cfg, env: process.env, startedAt: 0 });
2153
+ const minutes = (ms: number | undefined): number => ms === undefined ? 0 : ms / 60_000;
2154
+ return {
2155
+ toolWaitMinutes: minutes(effective.toolWaitMs),
2156
+ stuckMinutes: minutes(effective.stuckMs),
2157
+ toolWaitSource: sourceFor("toolWaitMinutes"),
2158
+ stuckSource: sourceFor("stuckMinutes"),
2159
+ defaultToolWaitMinutes: minutes(defaults.toolWaitMs),
2160
+ defaultStuckMinutes: minutes(defaults.stuckMs),
2161
+ };
2162
+ } catch (error) {
2163
+ return {
2164
+ toolWaitMinutes: DEFAULT_TIMING_MINUTES.toolWait,
2165
+ stuckMinutes: DEFAULT_TIMING_MINUTES.stuck,
2166
+ toolWaitSource: sourceFor("toolWaitMinutes"),
2167
+ stuckSource: sourceFor("stuckMinutes"),
2168
+ defaultToolWaitMinutes: DEFAULT_TIMING_MINUTES.toolWait,
2169
+ defaultStuckMinutes: DEFAULT_TIMING_MINUTES.stuck,
2170
+ timingError: error instanceof Error ? error.message : String(error),
2171
+ };
2172
+ }
2173
+ };
2063
2174
  const changeCap = (cap: number): void => {
2064
2175
  if (!isConcurrencyCap(cap)) throw new Error("Concurrent subagents must be a positive whole number.");
2065
2176
  capOverride = cap;
2066
2177
  pi.appendEntry("pi-better-subagents-cap", { version: 1, maxConcurrent: cap });
2067
2178
  };
2179
+ const changeTiming = (key: "toolWaitMinutes" | "stuckMinutes", minutes: number): void => {
2180
+ const value = validatedTimingMinutes(minutes, key);
2181
+ timingOverride = { ...timingOverride, [key]: value };
2182
+ pi.appendEntry("pi-better-subagents-timing", { version: 1, ...timingOverride });
2183
+ };
2068
2184
  const changeMode = (mode: DelegationMode): void => {
2069
2185
  delegationOverride = mode;
2070
2186
  pi.appendEntry("pi-better-subagents-delegation", { version: 1, mode });
@@ -2072,9 +2188,11 @@ export default function (pi: ExtensionAPI) {
2072
2188
  const resetSettings = (): void => {
2073
2189
  capOverride = undefined;
2074
2190
  delegationOverride = undefined;
2191
+ timingOverride = {};
2075
2192
  skillsOverride = undefined;
2076
2193
  pi.appendEntry("pi-better-subagents-cap", { version: 1, maxConcurrent: null });
2077
2194
  pi.appendEntry("pi-better-subagents-delegation", { version: 1, mode: null });
2195
+ pi.appendEntry("pi-better-subagents-timing", { version: 1, toolWaitMinutes: null, stuckMinutes: null });
2078
2196
  pi.appendEntry("pi-better-subagents-skills", { version: 1, mode: null });
2079
2197
  };
2080
2198
  const activeDelegationMode = (): DelegationMode => delegationOverride ?? normalizeDelegationMode(loadConfig().delegationMode);
@@ -2102,11 +2220,19 @@ export default function (pi: ExtensionAPI) {
2102
2220
  .finally(() => syncHealthTicker());
2103
2221
  return true;
2104
2222
  };
2105
- const effectiveSettings = () => effectiveSubagentSettings({
2106
- delegationMode: activeDelegationMode(), maxConcurrent: activeConcurrencyCap(),
2107
- sources: { delegationMode: delegationOverride ? "session" : "config",
2108
- maxConcurrent: capOverride !== undefined ? "session" : "config" },
2109
- }, countRunning(), getSharedCapacityGate(countRunning).pending);
2223
+ const effectiveSettings = () => {
2224
+ const timing = timingState();
2225
+ return effectiveSubagentSettings({
2226
+ delegationMode: activeDelegationMode(), maxConcurrent: activeConcurrencyCap(),
2227
+ sources: { delegationMode: delegationOverride ? "session" : "config",
2228
+ maxConcurrent: capOverride !== undefined ? "session" : "config" },
2229
+ timing: {
2230
+ toolWaitMinutes: timing.toolWaitMinutes, stuckMinutes: timing.stuckMinutes,
2231
+ sources: { toolWaitMinutes: timing.toolWaitSource, stuckMinutes: timing.stuckSource },
2232
+ ...(timing.timingError ? { error: timing.timingError } : {}),
2233
+ },
2234
+ }, countRunning(), getSharedCapacityGate(countRunning).pending);
2235
+ };
2110
2236
  const saveSettings = (): { ok: boolean; message: string } => {
2111
2237
  try {
2112
2238
  const skills = activeSkills();
@@ -2123,11 +2249,26 @@ export default function (pi: ExtensionAPI) {
2123
2249
  // Saving mode and cap must not write a skill key into a config that
2124
2250
  // never had one. Discovery only replaces a saved choice when a saved
2125
2251
  // skill value already exists.
2126
- const savedSkillValue = loadConfig().defaultSkills;
2252
+ const cfg = loadConfig();
2253
+ const savedSkillValue = cfg.defaultSkills;
2127
2254
  const hasSavedSkillChoice = savedSkillValue !== undefined && savedSkillValue !== null;
2255
+ // Like skills, only save a timing key this session overrides or the
2256
+ // config already carries; built-in defaults need no stored copy.
2257
+ const savedTiming: { toolWaitMinutes?: number; stuckMinutes?: number } = {};
2258
+ if (timingOverride.toolWaitMinutes !== undefined) {
2259
+ savedTiming.toolWaitMinutes = timingOverride.toolWaitMinutes;
2260
+ } else if (isTimingMinutes(cfg.toolWaitMinutes)) {
2261
+ savedTiming.toolWaitMinutes = cfg.toolWaitMinutes;
2262
+ }
2263
+ if (timingOverride.stuckMinutes !== undefined) {
2264
+ savedTiming.stuckMinutes = timingOverride.stuckMinutes;
2265
+ } else if (isTimingMinutes(cfg.stuckMinutes)) {
2266
+ savedTiming.stuckMinutes = cfg.stuckMinutes;
2267
+ }
2128
2268
  writeSubagentSettings({
2129
2269
  delegationMode: activeDelegationMode(),
2130
2270
  maxConcurrent: activeConcurrencyCap(),
2271
+ ...savedTiming,
2131
2272
  ...(skills.mode === "inherit" && !hasSavedSkillChoice ? {} : {
2132
2273
  // null is an explicit discovery choice; it must override a saved path list.
2133
2274
  defaultSkills: skills.mode === "inherit" ? null : [...skills.paths],
@@ -2161,6 +2302,7 @@ export default function (pi: ExtensionAPI) {
2161
2302
  const restoreDelegationMode = (ctx: ExtensionContext): void => {
2162
2303
  delegationOverride = undefined;
2163
2304
  capOverride = undefined;
2305
+ timingOverride = {};
2164
2306
  skillsOverride = undefined;
2165
2307
  const branch = ctx.sessionManager?.getBranch?.();
2166
2308
  if (!Array.isArray(branch)) return;
@@ -2185,6 +2327,17 @@ export default function (pi: ExtensionAPI) {
2185
2327
  }
2186
2328
  continue;
2187
2329
  }
2330
+ if (entry.type === "custom" && entry.customType === "pi-better-subagents-timing") {
2331
+ const data = entry.data as {
2332
+ version?: unknown; toolWaitMinutes?: unknown; stuckMinutes?: unknown;
2333
+ } | null;
2334
+ if (data?.version !== 1) continue;
2335
+ const next: { toolWaitMinutes?: number; stuckMinutes?: number } = {};
2336
+ if (isTimingMinutes(data.toolWaitMinutes)) next.toolWaitMinutes = data.toolWaitMinutes;
2337
+ if (isTimingMinutes(data.stuckMinutes)) next.stuckMinutes = data.stuckMinutes;
2338
+ timingOverride = next;
2339
+ continue;
2340
+ }
2188
2341
  if (entry.type !== "custom" || entry.customType !== "pi-better-subagents-delegation") continue;
2189
2342
  const data = entry.data as { version?: unknown; mode?: unknown } | null;
2190
2343
  if (data?.version !== 1) continue;
@@ -2384,8 +2537,8 @@ export default function (pi: ExtensionAPI) {
2384
2537
  );
2385
2538
  }
2386
2539
  const cfg = loadConfig();
2387
- // Harness-owned timing (soft deadline, ceiling, stuck window); validated before any side effect.
2388
- resolveRunTiming({ params: p, settings: cfg, env: process.env, startedAt: 0 });
2540
+ // Harness-owned timing (soft deadline, ceiling, tool-wait and stuck windows); validated before any side effect.
2541
+ resolveRunTiming({ params: p, settings: timingSettingsFor(cfg), env: process.env, startedAt: 0 });
2389
2542
  let model: string | undefined;
2390
2543
  let thinking: ThinkingLevel | undefined;
2391
2544
  if (resume) {
@@ -2782,7 +2935,7 @@ export default function (pi: ExtensionAPI) {
2782
2935
  authorityReference: "",
2783
2936
  // The assignment deadline the attempt was admitted with; a
2784
2937
  // continuation must not silently extend it.
2785
- deadlineAt: resolveRunTiming({ params: p, settings: cfg, env: process.env, startedAt: Date.now() }).deadlineAt ?? null,
2938
+ deadlineAt: resolveRunTiming({ params: p, settings: timingSettingsFor(cfg), env: process.env, startedAt: Date.now() }).deadlineAt ?? null,
2786
2939
  taskPolicy: taskRuntime?.policy ?? null,
2787
2940
  });
2788
2941
  const authorityReference = `worker-policy:${createHash("sha256")
@@ -2921,7 +3074,7 @@ export default function (pi: ExtensionAPI) {
2921
3074
  tools: bridgePlan.tools,
2922
3075
  },
2923
3076
  } : {}),
2924
- timing: resolveRunTiming({ params: p, settings: cfg, env: process.env, startedAt }),
3077
+ timing: resolveRunTiming({ params: p, settings: timingSettingsFor(cfg), env: process.env, startedAt }),
2925
3078
  };
2926
3079
  // This instance holds the exit observer for a run it actually
2927
3080
  // started; only it can finalize on the exit event (#625).
@@ -3171,6 +3324,7 @@ export default function (pi: ExtensionAPI) {
3171
3324
  ...(timing.deadlineAt !== undefined ? { deadline_minutes: minutes(timing.deadlineAt) } : {}),
3172
3325
  ...(timing.ceilingAt !== undefined ? { max_minutes: minutes(timing.ceilingAt) } : {}),
3173
3326
  ...(timing.graceMs !== undefined ? { grace_minutes: timing.graceMs / 60_000 } : {}),
3327
+ ...(timing.toolWaitMs !== undefined ? { tool_wait_minutes: timing.toolWaitMs / 60_000 } : {}),
3174
3328
  ...(timing.stuckMs !== undefined ? { stuck_minutes: timing.stuckMs / 60_000 } : {}),
3175
3329
  };
3176
3330
  }
@@ -3261,7 +3415,7 @@ export default function (pi: ExtensionAPI) {
3261
3415
  "The tools param is both the tool allowlist AND what determines which extensions load in the child (e.g. tools='read,bash,web_fetch' loads only the web-tools package). Ask for the tools the task needs and nothing more; clean:true gives a built-ins-only child. When the task already names its SKILL.md by path, pass skills with those absolute paths (or [] for none) so the child does not advertise the whole skills catalog. Without an agent or role, pick a model with the model param (e.g. 'xai/grok-4.5@high'); providerless model patterns are resolved by Pi, while provider/model is deterministic and loads mapped provider extensions.",
3262
3416
  ...CATALOG_GUIDELINES,
3263
3417
  "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.",
3264
- "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.",
3418
+ "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. A tool call still open for tool_wait_minutes (default 5) or no progress for stuck_minutes (default 10) sends one factual alert; these alerts never stop, cancel, or restart the run. Elapsed-time limits are opt-in for work with a real wall-clock bound: deadline_minutes steers the child to wrap up and later stops it after grace_minutes, while max_minutes stops it without grace.",
3265
3419
  "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.",
3266
3420
  "Saved conversations persist automatically. To continue a completed or stopped 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.",
3267
3421
  "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, skills, 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.",
@@ -3331,6 +3485,7 @@ export default function (pi: ExtensionAPI) {
3331
3485
  deadline_minutes: p.deadline_minutes,
3332
3486
  grace_minutes: p.grace_minutes,
3333
3487
  max_minutes: p.max_minutes,
3488
+ tool_wait_minutes: p.tool_wait_minutes,
3334
3489
  stuck_minutes: p.stuck_minutes,
3335
3490
  };
3336
3491
  const { id, spawned, runtime, warn, sandboxDir, modelNote } = await spawnSubagentRun(
@@ -3756,17 +3911,24 @@ export default function (pi: ExtensionAPI) {
3756
3911
  get: () => {
3757
3912
  const settings = effectiveSettings();
3758
3913
  const skills = activeSkills();
3914
+ const timing = timingState();
3759
3915
  return {
3760
3916
  mode: settings.delegationMode, maxConcurrent: settings.maxConcurrent,
3761
3917
  modeSource: settings.sources.delegationMode,
3762
3918
  capSource: settings.sources.maxConcurrent,
3763
3919
  defaultMode: normalizeDelegationMode(loadConfig().delegationMode),
3764
3920
  defaultCap: normalizeConcurrencyCap(loadConfig().maxConcurrent),
3921
+ toolWaitMinutes: settings.toolWaitMinutes, stuckMinutes: settings.stuckMinutes,
3922
+ toolWaitSource: settings.timingSources.toolWaitMinutes,
3923
+ stuckSource: settings.timingSources.stuckMinutes,
3924
+ defaultToolWaitMinutes: timing.defaultToolWaitMinutes,
3925
+ defaultStuckMinutes: timing.defaultStuckMinutes,
3926
+ ...(settings.timingError ? { timingError: settings.timingError } : {}),
3765
3927
  skillsMode: skills.mode, skillsPaths: skills.paths, skillsSource: skills.source,
3766
3928
  skillsError: skills.error,
3767
3929
  };
3768
3930
  },
3769
- changeMode, changeCap, changeSkills, save: saveSettings, reset: resetSettings,
3931
+ changeMode, changeCap, changeTiming, changeSkills, save: saveSettings, reset: resetSettings,
3770
3932
  discoverSkills: () => discoveredSkillsFromContext(ctx),
3771
3933
  // Close this page first; the catalog opens after ui.custom resolves.
3772
3934
  openAgents: () => done("agents"),
@@ -3776,7 +3938,10 @@ export default function (pi: ExtensionAPI) {
3776
3938
  const skills = activeSkills();
3777
3939
  const skillChoice = skills.mode === "inherit" ? "discovery"
3778
3940
  : skills.mode === "none" ? "no skills" : `${skills.paths.length} selected skills`;
3779
- ctx.ui.notify(`Delegation mode: ${activeDelegationMode()}. Concurrent subagents: ${activeConcurrencyCap()}. Skills: ${skillChoice}. Use /subagents mode <mode>, cap <number>, or settings; /subagents save persists them.`, "info");
3941
+ const timing = timingState();
3942
+ ctx.ui.notify(`Delegation mode: ${activeDelegationMode()}. Concurrent subagents: ${activeConcurrencyCap()}. ` +
3943
+ `Tool-wait alert: ${timing.toolWaitMinutes} min. No-progress alert: ${timing.stuckMinutes} min. Skills: ${skillChoice}. ` +
3944
+ `Use /subagents mode <mode>, cap <number>, tool-wait <minutes>, stuck <minutes>, or settings; /subagents save persists them.`, "info");
3780
3945
  }
3781
3946
  };
3782
3947
  const contribution = { id: "subagents", label: "Subagents", command: "/subagents settings", open: openSettings };
@@ -3791,7 +3956,7 @@ export default function (pi: ExtensionAPI) {
3791
3956
  if (typeof pi.registerCommand === "function") {
3792
3957
  agentOperations.registerCommands(pi);
3793
3958
  pi.registerCommand("subagents", {
3794
- description: "[settings|mode manual|adaptive|coordinator|cap <number>|save|reset] — Subagent settings",
3959
+ description: "[settings|mode manual|adaptive|coordinator|cap <number>|tool-wait <minutes>|stuck <minutes>|save|reset] — Subagent settings",
3795
3960
  getArgumentCompletions: subagentsArgumentCompletions,
3796
3961
  async handler(args, ctx) {
3797
3962
  const tokens = args.trim().split(/\s+/).filter(Boolean);
@@ -3808,7 +3973,10 @@ export default function (pi: ExtensionAPI) {
3808
3973
  }
3809
3974
  const skillChoice = skills.mode === "inherit" ? "skill discovery"
3810
3975
  : skills.mode === "none" ? "no skills" : `${skills.paths.length} selected skills`;
3811
- if (ctx.hasUI && !(await ctx.ui.confirm("Save subagent defaults?", `Future sessions will start in ${activeDelegationMode()} with a cap of ${activeConcurrencyCap()} and ${skillChoice}.`))) {
3976
+ const timing = timingState();
3977
+ if (ctx.hasUI && !(await ctx.ui.confirm("Save subagent defaults?",
3978
+ `Future sessions will start in ${activeDelegationMode()} with a cap of ${activeConcurrencyCap()}, ` +
3979
+ `tool-wait alert ${timing.toolWaitMinutes} min, no-progress alert ${timing.stuckMinutes} min, and ${skillChoice}.`))) {
3812
3980
  ctx.ui.notify("Subagent defaults unchanged.", "info");
3813
3981
  return;
3814
3982
  }
@@ -3828,8 +3996,19 @@ export default function (pi: ExtensionAPI) {
3828
3996
  }
3829
3997
  changeCap(cap);
3830
3998
  ctx.ui.notify(`Concurrent subagents: ${cap} (current session). Running subagents are unchanged.`, "info");
3999
+ } else if (tokens.length === 2 && (tokens[0] === "tool-wait" || tokens[0] === "stuck")) {
4000
+ const key = tokens[0] === "tool-wait" ? "toolWaitMinutes" : "stuckMinutes";
4001
+ let minutes: number;
4002
+ try {
4003
+ minutes = validatedTimingMinutes(requested, key);
4004
+ } catch (error) {
4005
+ ctx.ui.notify(`${error instanceof Error ? error.message : String(error)} Nothing changed.`, "warning");
4006
+ return;
4007
+ }
4008
+ changeTiming(key, minutes);
4009
+ ctx.ui.notify(`${tokens[0] === "tool-wait" ? "Tool-wait" : "No-progress"} alert: ${minutes} min (current session). Running subagents are unchanged.`, "info");
3831
4010
  } else {
3832
- ctx.ui.notify("Usage: /subagents [settings|mode manual|adaptive|coordinator|cap <number>|save|reset]", "warning");
4011
+ ctx.ui.notify("Usage: /subagents [settings|mode manual|adaptive|coordinator|cap <number>|tool-wait <minutes>|stuck <minutes>|save|reset]", "warning");
3833
4012
  }
3834
4013
  refreshBackgroundWorkNavigator(ctx);
3835
4014
  },
@@ -3932,10 +4111,10 @@ export default function (pi: ExtensionAPI) {
3932
4111
  // Adopt records left non-terminal by a pi that died without a clean
3933
4112
  // shutdown, so the age sweep can eventually retire them.
3934
4113
  reconcileAbandonedRuns();
3935
- disposeBackgroundWorkNavigator(ctx);
4114
+ disposeBackgroundWorkNavigator(ctx, navigatorOwner);
3936
4115
  widgetNavActive = false;
3937
4116
  widgetNavSelectedId = undefined;
3938
- ensureNavigator(ctx);
4117
+ ensureNavigator(ctx, navigatorOwner);
3939
4118
  publishAcceptanceHooks();
3940
4119
  updateNavigatorFooter(ctx);
3941
4120
  // Clear the retired legacy widget so the shared navigator is the only
@@ -3956,7 +4135,9 @@ export default function (pi: ExtensionAPI) {
3956
4135
  cancelCallbackBatch(pi);
3957
4136
  mainAgentStartedAt = undefined;
3958
4137
  mainAgentTools.clear();
3959
- disposeBackgroundWorkNavigator();
4138
+ // Owned disposal only: a headless child or a stale factory must not clear
4139
+ // the parent's navigator by omitting the context and owner.
4140
+ disposeBackgroundWorkNavigator(undefined, navigatorOwner);
3960
4141
  });
3961
4142
 
3962
4143
  // Tear down the timer and clear the widget when the session ends.
@@ -4008,7 +4189,7 @@ export default function (pi: ExtensionAPI) {
4008
4189
  resetParseRunCursor();
4009
4190
  // Always dispose navigator detail timers (no UI call — just clearInterval).
4010
4191
  // Safe in every mode; the dispose hook is only set when a TUI overlay opened.
4011
- disposeBackgroundWorkNavigator(ctx);
4192
+ disposeBackgroundWorkNavigator(ctx, navigatorOwner);
4012
4193
  // Widget clear is intentional in every mode that exposes ui, including RPC.
4013
4194
  try { ctx.ui.setWidget("subagents", WIDGET_CLEAR); } catch { /* ignore */ }
4014
4195
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-subagents",
3
- "version": "0.28.1",
3
+ "version": "0.29.0",
4
4
  "description": "Pi extension for detached, sandboxed subagent runs that keep the foreground session free.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/registry.ts CHANGED
@@ -277,7 +277,8 @@ export interface RunMeta {
277
277
  operations?: RunOperationsBinding;
278
278
  /**
279
279
  * Harness-owned timing policy and one-shot markers (soft deadline, grace,
280
- * hard ceiling, stuck window). Written at launch so /reload keeps it.
280
+ * hard ceiling, tool-wait and stuck windows). Written at launch so /reload
281
+ * keeps it.
281
282
  * Additive: runs launched before it have none and are never timed.
282
283
  */
283
284
  timing?: RunTiming;