pi-better-subagents 0.28.2 → 0.29.1

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
  }
@@ -2018,6 +2082,7 @@ export default function (pi: ExtensionAPI) {
2018
2082
  let catalogModelRegistry: ExtensionContext["modelRegistry"] | undefined;
2019
2083
  let delegationOverride: DelegationMode | undefined;
2020
2084
  let capOverride: number | undefined;
2085
+ let timingOverride: { toolWaitMinutes?: number; stuckMinutes?: number } = {};
2021
2086
  interface SkillSelection { mode: SkillExposureMode; paths: string[] }
2022
2087
  let skillsOverride: SkillSelection | undefined;
2023
2088
  const savedSkills = (): SkillSelection & { source: "config" | "default"; error?: string } => {
@@ -2062,11 +2127,60 @@ export default function (pi: ExtensionAPI) {
2062
2127
  return { value: skillsOverride.mode === "none" ? [] : [...skillsOverride.paths] };
2063
2128
  };
2064
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
+ };
2065
2174
  const changeCap = (cap: number): void => {
2066
2175
  if (!isConcurrencyCap(cap)) throw new Error("Concurrent subagents must be a positive whole number.");
2067
2176
  capOverride = cap;
2068
2177
  pi.appendEntry("pi-better-subagents-cap", { version: 1, maxConcurrent: cap });
2069
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
+ };
2070
2184
  const changeMode = (mode: DelegationMode): void => {
2071
2185
  delegationOverride = mode;
2072
2186
  pi.appendEntry("pi-better-subagents-delegation", { version: 1, mode });
@@ -2074,9 +2188,11 @@ export default function (pi: ExtensionAPI) {
2074
2188
  const resetSettings = (): void => {
2075
2189
  capOverride = undefined;
2076
2190
  delegationOverride = undefined;
2191
+ timingOverride = {};
2077
2192
  skillsOverride = undefined;
2078
2193
  pi.appendEntry("pi-better-subagents-cap", { version: 1, maxConcurrent: null });
2079
2194
  pi.appendEntry("pi-better-subagents-delegation", { version: 1, mode: null });
2195
+ pi.appendEntry("pi-better-subagents-timing", { version: 1, toolWaitMinutes: null, stuckMinutes: null });
2080
2196
  pi.appendEntry("pi-better-subagents-skills", { version: 1, mode: null });
2081
2197
  };
2082
2198
  const activeDelegationMode = (): DelegationMode => delegationOverride ?? normalizeDelegationMode(loadConfig().delegationMode);
@@ -2104,11 +2220,19 @@ export default function (pi: ExtensionAPI) {
2104
2220
  .finally(() => syncHealthTicker());
2105
2221
  return true;
2106
2222
  };
2107
- const effectiveSettings = () => effectiveSubagentSettings({
2108
- delegationMode: activeDelegationMode(), maxConcurrent: activeConcurrencyCap(),
2109
- sources: { delegationMode: delegationOverride ? "session" : "config",
2110
- maxConcurrent: capOverride !== undefined ? "session" : "config" },
2111
- }, 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
+ };
2112
2236
  const saveSettings = (): { ok: boolean; message: string } => {
2113
2237
  try {
2114
2238
  const skills = activeSkills();
@@ -2125,11 +2249,26 @@ export default function (pi: ExtensionAPI) {
2125
2249
  // Saving mode and cap must not write a skill key into a config that
2126
2250
  // never had one. Discovery only replaces a saved choice when a saved
2127
2251
  // skill value already exists.
2128
- const savedSkillValue = loadConfig().defaultSkills;
2252
+ const cfg = loadConfig();
2253
+ const savedSkillValue = cfg.defaultSkills;
2129
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
+ }
2130
2268
  writeSubagentSettings({
2131
2269
  delegationMode: activeDelegationMode(),
2132
2270
  maxConcurrent: activeConcurrencyCap(),
2271
+ ...savedTiming,
2133
2272
  ...(skills.mode === "inherit" && !hasSavedSkillChoice ? {} : {
2134
2273
  // null is an explicit discovery choice; it must override a saved path list.
2135
2274
  defaultSkills: skills.mode === "inherit" ? null : [...skills.paths],
@@ -2163,6 +2302,7 @@ export default function (pi: ExtensionAPI) {
2163
2302
  const restoreDelegationMode = (ctx: ExtensionContext): void => {
2164
2303
  delegationOverride = undefined;
2165
2304
  capOverride = undefined;
2305
+ timingOverride = {};
2166
2306
  skillsOverride = undefined;
2167
2307
  const branch = ctx.sessionManager?.getBranch?.();
2168
2308
  if (!Array.isArray(branch)) return;
@@ -2187,6 +2327,17 @@ export default function (pi: ExtensionAPI) {
2187
2327
  }
2188
2328
  continue;
2189
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
+ }
2190
2341
  if (entry.type !== "custom" || entry.customType !== "pi-better-subagents-delegation") continue;
2191
2342
  const data = entry.data as { version?: unknown; mode?: unknown } | null;
2192
2343
  if (data?.version !== 1) continue;
@@ -2386,8 +2537,8 @@ export default function (pi: ExtensionAPI) {
2386
2537
  );
2387
2538
  }
2388
2539
  const cfg = loadConfig();
2389
- // Harness-owned timing (soft deadline, ceiling, stuck window); validated before any side effect.
2390
- 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 });
2391
2542
  let model: string | undefined;
2392
2543
  let thinking: ThinkingLevel | undefined;
2393
2544
  if (resume) {
@@ -2784,7 +2935,7 @@ export default function (pi: ExtensionAPI) {
2784
2935
  authorityReference: "",
2785
2936
  // The assignment deadline the attempt was admitted with; a
2786
2937
  // continuation must not silently extend it.
2787
- 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,
2788
2939
  taskPolicy: taskRuntime?.policy ?? null,
2789
2940
  });
2790
2941
  const authorityReference = `worker-policy:${createHash("sha256")
@@ -2923,7 +3074,7 @@ export default function (pi: ExtensionAPI) {
2923
3074
  tools: bridgePlan.tools,
2924
3075
  },
2925
3076
  } : {}),
2926
- timing: resolveRunTiming({ params: p, settings: cfg, env: process.env, startedAt }),
3077
+ timing: resolveRunTiming({ params: p, settings: timingSettingsFor(cfg), env: process.env, startedAt }),
2927
3078
  };
2928
3079
  // This instance holds the exit observer for a run it actually
2929
3080
  // started; only it can finalize on the exit event (#625).
@@ -3173,6 +3324,7 @@ export default function (pi: ExtensionAPI) {
3173
3324
  ...(timing.deadlineAt !== undefined ? { deadline_minutes: minutes(timing.deadlineAt) } : {}),
3174
3325
  ...(timing.ceilingAt !== undefined ? { max_minutes: minutes(timing.ceilingAt) } : {}),
3175
3326
  ...(timing.graceMs !== undefined ? { grace_minutes: timing.graceMs / 60_000 } : {}),
3327
+ ...(timing.toolWaitMs !== undefined ? { tool_wait_minutes: timing.toolWaitMs / 60_000 } : {}),
3176
3328
  ...(timing.stuckMs !== undefined ? { stuck_minutes: timing.stuckMs / 60_000 } : {}),
3177
3329
  };
3178
3330
  }
@@ -3263,7 +3415,7 @@ export default function (pi: ExtensionAPI) {
3263
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.",
3264
3416
  ...CATALOG_GUIDELINES,
3265
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.",
3266
- "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.",
3267
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.",
3268
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.",
3269
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.",
@@ -3333,6 +3485,7 @@ export default function (pi: ExtensionAPI) {
3333
3485
  deadline_minutes: p.deadline_minutes,
3334
3486
  grace_minutes: p.grace_minutes,
3335
3487
  max_minutes: p.max_minutes,
3488
+ tool_wait_minutes: p.tool_wait_minutes,
3336
3489
  stuck_minutes: p.stuck_minutes,
3337
3490
  };
3338
3491
  const { id, spawned, runtime, warn, sandboxDir, modelNote } = await spawnSubagentRun(
@@ -3758,17 +3911,24 @@ export default function (pi: ExtensionAPI) {
3758
3911
  get: () => {
3759
3912
  const settings = effectiveSettings();
3760
3913
  const skills = activeSkills();
3914
+ const timing = timingState();
3761
3915
  return {
3762
3916
  mode: settings.delegationMode, maxConcurrent: settings.maxConcurrent,
3763
3917
  modeSource: settings.sources.delegationMode,
3764
3918
  capSource: settings.sources.maxConcurrent,
3765
3919
  defaultMode: normalizeDelegationMode(loadConfig().delegationMode),
3766
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 } : {}),
3767
3927
  skillsMode: skills.mode, skillsPaths: skills.paths, skillsSource: skills.source,
3768
3928
  skillsError: skills.error,
3769
3929
  };
3770
3930
  },
3771
- changeMode, changeCap, changeSkills, save: saveSettings, reset: resetSettings,
3931
+ changeMode, changeCap, changeTiming, changeSkills, save: saveSettings, reset: resetSettings,
3772
3932
  discoverSkills: () => discoveredSkillsFromContext(ctx),
3773
3933
  // Close this page first; the catalog opens after ui.custom resolves.
3774
3934
  openAgents: () => done("agents"),
@@ -3778,7 +3938,10 @@ export default function (pi: ExtensionAPI) {
3778
3938
  const skills = activeSkills();
3779
3939
  const skillChoice = skills.mode === "inherit" ? "discovery"
3780
3940
  : skills.mode === "none" ? "no skills" : `${skills.paths.length} selected skills`;
3781
- 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");
3782
3945
  }
3783
3946
  };
3784
3947
  const contribution = { id: "subagents", label: "Subagents", command: "/subagents settings", open: openSettings };
@@ -3793,7 +3956,7 @@ export default function (pi: ExtensionAPI) {
3793
3956
  if (typeof pi.registerCommand === "function") {
3794
3957
  agentOperations.registerCommands(pi);
3795
3958
  pi.registerCommand("subagents", {
3796
- 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",
3797
3960
  getArgumentCompletions: subagentsArgumentCompletions,
3798
3961
  async handler(args, ctx) {
3799
3962
  const tokens = args.trim().split(/\s+/).filter(Boolean);
@@ -3810,7 +3973,10 @@ export default function (pi: ExtensionAPI) {
3810
3973
  }
3811
3974
  const skillChoice = skills.mode === "inherit" ? "skill discovery"
3812
3975
  : skills.mode === "none" ? "no skills" : `${skills.paths.length} selected skills`;
3813
- 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}.`))) {
3814
3980
  ctx.ui.notify("Subagent defaults unchanged.", "info");
3815
3981
  return;
3816
3982
  }
@@ -3830,8 +3996,19 @@ export default function (pi: ExtensionAPI) {
3830
3996
  }
3831
3997
  changeCap(cap);
3832
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");
3833
4010
  } else {
3834
- 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");
3835
4012
  }
3836
4013
  refreshBackgroundWorkNavigator(ctx);
3837
4014
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-subagents",
3
- "version": "0.28.2",
3
+ "version": "0.29.1",
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;
package/settings-page.ts CHANGED
@@ -4,6 +4,9 @@ import { isConcurrencyCap } from "./config.ts";
4
4
  import { DELEGATION_MODES, type DelegationMode } from "./delegation.ts";
5
5
  import type { SkillExposureMode } from "./skills.ts";
6
6
  import { createSkillPicker, type DiscoveredSkill } from "./skill-picker.ts";
7
+ import { validatedTimingMinutes } from "./timing.ts";
8
+
9
+ export type TimingSettingKey = "toolWaitMinutes" | "stuckMinutes";
7
10
 
8
11
  export interface SubagentSettingsSnapshot {
9
12
  mode: DelegationMode;
@@ -12,6 +15,14 @@ export interface SubagentSettingsSnapshot {
12
15
  capSource: "session" | "config";
13
16
  defaultMode: DelegationMode;
14
17
  defaultCap: number;
18
+ toolWaitMinutes: number;
19
+ stuckMinutes: number;
20
+ toolWaitSource: "environment" | "session" | "config" | "default";
21
+ stuckSource: "environment" | "session" | "config" | "default";
22
+ defaultToolWaitMinutes: number;
23
+ defaultStuckMinutes: number;
24
+ /** A saved timing value the launcher cannot read, kept visible rather than hidden. */
25
+ timingError?: string;
15
26
  /** Session draft, or the saved global default when this session has no override. */
16
27
  skillsMode: SkillExposureMode;
17
28
  skillsPaths: readonly string[];
@@ -24,6 +35,7 @@ export interface SubagentSettingsHandlers {
24
35
  get(): SubagentSettingsSnapshot;
25
36
  changeMode(mode: DelegationMode): void;
26
37
  changeCap(cap: number): void;
38
+ changeTiming(key: TimingSettingKey, minutes: number): void;
27
39
  changeSkills(mode: SkillExposureMode, paths: readonly string[]): void;
28
40
  /** Loaded Pi skill metadata for the checkbox picker. Absent means manual paths only. */
29
41
  discoverSkills?(): readonly DiscoveredSkill[];
@@ -33,11 +45,13 @@ export interface SubagentSettingsHandlers {
33
45
  openAgents?(): void;
34
46
  }
35
47
 
36
- type EditTarget = { kind: "cap" };
48
+ type EditTarget = { kind: "cap" } | { kind: "toolWait" } | { kind: "stuck" };
37
49
 
38
50
  type Row =
39
51
  | { kind: "mode" }
40
52
  | { kind: "cap" }
53
+ | { kind: "toolWait" }
54
+ | { kind: "stuck" }
41
55
  | { kind: "skills" }
42
56
  | { kind: "choose" }
43
57
  | { kind: "agents" }
@@ -95,7 +109,10 @@ export function createSubagentSettingsPage(
95
109
  }
96
110
 
97
111
  function rowsOf(settings: SubagentSettingsSnapshot): Row[] {
98
- const rows: Row[] = [{ kind: "mode" }, { kind: "cap" }, { kind: "skills" }, { kind: "choose" }];
112
+ const rows: Row[] = [
113
+ { kind: "mode" }, { kind: "cap" }, { kind: "toolWait" }, { kind: "stuck" },
114
+ { kind: "skills" }, { kind: "choose" },
115
+ ];
99
116
  rows.push({ kind: "agents" }, { kind: "reset" });
100
117
  return rows;
101
118
  }
@@ -157,6 +174,10 @@ export function createSubagentSettingsPage(
157
174
  report("Session mode updated.");
158
175
  } else if (selected.kind === "cap") {
159
176
  startEditing({ kind: "cap" }, String(settings.maxConcurrent));
177
+ } else if (selected.kind === "toolWait") {
178
+ startEditing({ kind: "toolWait" }, String(settings.toolWaitMinutes));
179
+ } else if (selected.kind === "stuck") {
180
+ startEditing({ kind: "stuck" }, String(settings.stuckMinutes));
160
181
  } else if (selected.kind === "skills") {
161
182
  if (settings.skillsMode === "explicit") rememberedSkillPaths = [...settings.skillsPaths];
162
183
  const next = cycleSkillMode(settings.skillsMode);
@@ -198,6 +219,14 @@ export function createSubagentSettingsPage(
198
219
  }
199
220
  return;
200
221
  }
222
+ const key = target.kind === "toolWait" ? "toolWaitMinutes" : "stuckMinutes";
223
+ try {
224
+ const minutes = validatedTimingMinutes(value.trim(), key);
225
+ handlers.changeTiming(key, minutes);
226
+ finishEditing(`${target.kind === "toolWait" ? "Tool-wait" : "No-progress"} alert updated.`);
227
+ } catch (cause) {
228
+ report(cause instanceof Error ? cause.message : String(cause), true);
229
+ }
201
230
  };
202
231
 
203
232
  input.onSubmit = submit;
@@ -273,13 +302,21 @@ export function createSubagentSettingsPage(
273
302
  rows.forEach((entry, index) => {
274
303
  const selected = index === row;
275
304
  if (selected) selectedStart = lines.length;
276
- if (entry.kind === "mode" || entry.kind === "cap") {
277
- const label = entry.kind === "mode" ? "Delegation mode" : "Concurrent subagents";
278
- const value = entry.kind === "mode" ? settings.mode : String(settings.maxConcurrent);
279
- const active = editing?.kind === "cap" && entry.kind === "cap"
305
+ if (entry.kind === "mode" || entry.kind === "cap" || entry.kind === "toolWait" || entry.kind === "stuck") {
306
+ const label = entry.kind === "mode" ? "Delegation mode"
307
+ : entry.kind === "cap" ? "Concurrent subagents"
308
+ : entry.kind === "toolWait" ? "Tool-wait alert" : "No-progress alert";
309
+ const value = entry.kind === "mode" ? settings.mode
310
+ : entry.kind === "cap" ? String(settings.maxConcurrent)
311
+ : `${entry.kind === "toolWait" ? settings.toolWaitMinutes : settings.stuckMinutes} min`;
312
+ const active = editing?.kind === entry.kind
280
313
  ? input.render(compact ? Math.max(1, w - 2) : valueWidth)[0]!
281
314
  : value;
282
315
  pushSetting(label, value, selected, active);
316
+ if (entry.kind === "stuck" && settings.timingError) {
317
+ const sourceLine = compact ? " " + settings.timingError : " ".repeat(LABEL_WIDTH) + " " + settings.timingError;
318
+ lines.push(theme.fg("error", Tui.truncateToWidth(sourceLine, w, "")));
319
+ }
283
320
  } else if (entry.kind === "skills") {
284
321
  pushSetting("Skill exposure", skillLabel(settings.skillsMode), selected, skillLabel(settings.skillsMode));
285
322
  const sourceLine = compact ? " " + source : " ".repeat(LABEL_WIDTH) + " " + source;
@@ -342,6 +342,11 @@ export function listOperations(
342
342
  ): OperationRecord[] {
343
343
  const clauses: string[] = [];
344
344
  const params: Array<string | number> = [];
345
+ if (filter.ownerScope) {
346
+ const owner = normalizeOwner("ownerScope", filter.ownerScope);
347
+ clauses.push("owner_kind = ? AND owner_session_id = ? AND owner_workspace = ?");
348
+ params.push(owner.kind, owner.sessionId, owner.workspace);
349
+ }
345
350
  if (filter.owner) {
346
351
  const owner = normalizeOwner("owner", filter.owner);
347
352
  clauses.push(
@@ -204,6 +204,8 @@ export interface RecordTerminalOutcomeResult {
204
204
  /** Filter for `listOperations`. */
205
205
  export interface OperationFilter {
206
206
  owner?: OwnerIdentity;
207
+ /** Session/workspace scope spanning all branches and goals. */
208
+ ownerScope?: Pick<OwnerIdentity, "kind" | "sessionId" | "workspace">;
207
209
  phase?: OperationPhase;
208
210
  taskId?: string;
209
211
  }