@vicary/pi-subagents 0.86.0 → 0.88.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.
Files changed (122) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-PYOAIN3V.js → chunk-2DIEL4WG.js} +2 -2
  5. package/bundle/{chunk-GJGTMLPE.js → chunk-3DT5X2QC.js} +483 -477
  6. package/bundle/{chunk-374MZFF4.js → chunk-3MFYKBKI.js} +23 -13
  7. package/bundle/{chunk-77ASNIEM.js → chunk-47ZN7NKR.js} +1 -1
  8. package/bundle/{chunk-QGO6HXHG.js → chunk-4MVDMA5C.js} +88 -64
  9. package/bundle/{chunk-3RKFH2UZ.js → chunk-6EUQPQY7.js} +31 -14
  10. package/bundle/{chunk-6VD7BGIC.js → chunk-6PR44R7E.js} +7 -2
  11. package/bundle/{chunk-DD22RXYJ.js → chunk-AOSILI5R.js} +200 -64
  12. package/bundle/{chunk-WHC2XHGF.js → chunk-BW5JLKIU.js} +174 -56
  13. package/bundle/{chunk-7ZUFN6ME.js → chunk-CKLZ5FGU.js} +2 -2
  14. package/bundle/{chunk-ZPY5QZCS.js → chunk-CYKNHFXB.js} +1 -1
  15. package/bundle/{chunk-YK3QYNLE.js → chunk-GDR2ILWY.js} +1 -1
  16. package/bundle/{chunk-7QA7ZA46.js → chunk-IZEKQEY4.js} +9 -9
  17. package/bundle/{chunk-CJHFDQFJ.js → chunk-JYHTDTOZ.js} +10 -6
  18. package/bundle/{chunk-NAFLUJ26.js → chunk-KXW62VBU.js} +1 -1
  19. package/bundle/{chunk-S2Q75LP3.js → chunk-L4YY2TOE.js} +1 -1
  20. package/bundle/{chunk-2DITXA3H.js → chunk-NVGQE2H2.js} +12 -12
  21. package/bundle/{chunk-BU6PFPVX.js → chunk-PJSOS2Q4.js} +12 -7
  22. package/bundle/{chunk-UR7OW5S7.js → chunk-RHYVKQQL.js} +11 -5
  23. package/bundle/{chunk-BGXEAYUM.js → chunk-SVIXQDIV.js} +20 -5
  24. package/bundle/{chunk-GLVJMI6R.js → chunk-TDJKY2NE.js} +14 -5
  25. package/bundle/{chunk-XOFYXQKZ.js → chunk-V7SZMS6W.js} +2 -2
  26. package/bundle/{chunk-NF7IEKBH.js → chunk-W2BZS6UC.js} +27 -13
  27. package/bundle/{chunk-5H4BICQZ.js → chunk-W6HIYD2Z.js} +1 -1
  28. package/bundle/{chunk-LGINOOY5.js → chunk-XIA5GSEU.js} +2 -2
  29. package/bundle/{chunk-QFLPV64W.js → chunk-XZXYPZUT.js} +46 -32
  30. package/bundle/chunk-YDZ7BZD5.js +523 -0
  31. package/bundle/{chunk-WN2E5XHN.js → chunk-YZPVALSQ.js} +30 -5
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +12 -10
  36. package/bundle/project-panes.js +3 -3
  37. package/bundle/workflow-resources.js +1 -1
  38. package/docs/agents.md +4 -4
  39. package/docs/configuration.md +14 -4
  40. package/docs/extension-api.md +2 -0
  41. package/docs/models.md +6 -2
  42. package/docs/observability.md +2 -0
  43. package/docs/tool-reference.md +5 -1
  44. package/package.json +3 -3
  45. package/skills/pi-subagents/SKILL.md +15 -6
  46. package/skills/pi-subagents/references/prompting-and-roles.md +1 -0
  47. package/src/agents/agent-management.d.ts +1 -0
  48. package/src/agents/agent-management.js +22 -10
  49. package/src/agents/agent-serializer.d.ts +2 -0
  50. package/src/agents/agent-serializer.js +1 -1
  51. package/src/agents/agents.d.ts +1 -0
  52. package/src/agents/agents.js +39 -14
  53. package/src/api/preflight.d.ts +3 -1
  54. package/src/api/preflight.js +2 -0
  55. package/src/extension/config.d.ts +9 -0
  56. package/src/extension/config.js +13 -0
  57. package/src/extension/index.js +8 -5
  58. package/src/extension/schemas.d.ts +4 -0
  59. package/src/extension/schemas.js +2 -0
  60. package/src/extension/tool-activation.js +20 -3
  61. package/src/runs/background/async-execution.d.ts +2 -1
  62. package/src/runs/background/async-execution.js +4 -2
  63. package/src/runs/background/async-resume.js +2 -1
  64. package/src/runs/background/async-retention.d.ts +0 -2
  65. package/src/runs/background/async-retention.js +11 -5
  66. package/src/runs/background/async-status.d.ts +2 -0
  67. package/src/runs/background/async-status.js +4 -0
  68. package/src/runs/background/run-child-session.d.ts +2 -2
  69. package/src/runs/background/run-child-session.js +4 -7
  70. package/src/runs/background/runner-aliases.js +15 -0
  71. package/src/runs/background/steering.d.ts +2 -11
  72. package/src/runs/background/steering.js +11 -6
  73. package/src/runs/background/subagent-runner.d.ts +0 -2
  74. package/src/runs/background/subagent-runner.js +73 -58
  75. package/src/runs/background/wait-subscriptions.js +124 -12
  76. package/src/runs/foreground/async-steering-action.js +24 -9
  77. package/src/runs/foreground/async-stop-action.d.ts +1 -1
  78. package/src/runs/foreground/async-stop-action.js +9 -1
  79. package/src/runs/foreground/execution.js +33 -15
  80. package/src/runs/foreground/prompt-audit.js +1 -0
  81. package/src/runs/foreground/subagent-executor.d.ts +2 -8
  82. package/src/runs/foreground/subagent-executor.js +57 -23
  83. package/src/runs/shared/async-status-projection.d.ts +2 -0
  84. package/src/runs/shared/async-status-projection.js +10 -0
  85. package/src/runs/shared/child-session.d.ts +5 -4
  86. package/src/runs/shared/child-session.js +64 -36
  87. package/src/runs/shared/herdr-placed-run.js +3 -2
  88. package/src/runs/shared/mcp-config-sources.d.ts +4 -1
  89. package/src/runs/shared/mcp-config-sources.js +1 -1
  90. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -3
  91. package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -17
  92. package/src/runs/shared/model-resolution.d.ts +19 -4
  93. package/src/runs/shared/model-resolution.js +50 -51
  94. package/src/runs/shared/subagent-prompt-runtime.js +14 -2
  95. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  96. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  97. package/src/shared/artifacts.d.ts +1 -0
  98. package/src/shared/artifacts.js +132 -22
  99. package/src/shared/pruned-fork.js +2 -2
  100. package/src/shared/reported-progress.d.ts +1 -0
  101. package/src/shared/reported-progress.js +12 -0
  102. package/src/shared/status-format.d.ts +1 -0
  103. package/src/shared/status-format.js +1 -1
  104. package/src/shared/types.d.ts +23 -0
  105. package/src/shared/utils.d.ts +3 -1
  106. package/src/shared/utils.js +4 -0
  107. package/src/tui/render.js +33 -2
  108. package/src/watchdog/model-selection.js +2 -2
  109. package/src/watchdog/permission-arbiter.js +1 -0
  110. package/src/watchdog/review.d.ts +0 -5
  111. package/src/watchdog/review.js +4 -3
  112. package/src/workflows/scripted-workflow.d.ts +2 -0
  113. package/src/workflows/scripted-workflow.js +103 -39
  114. package/src/workflows/structured-workflow-scripts.d.ts +4 -3
  115. package/src/workflows/structured-workflow-scripts.js +32 -11
  116. package/src/workflows/workflow-resources.js +4 -4
  117. package/src/workflows/workflow-resume-claim.d.ts +2 -0
  118. package/src/workflows/workflow-resume-claim.js +1 -1
  119. package/src/workflows/workflow-resume.d.ts +1 -1
  120. package/src/workflows/workflow-resume.js +3 -1
  121. package/src/workflows/workflow-script-worker.js +3 -1
  122. package/bundle/chunk-GRJHIXYF.js +0 -235
@@ -1,8 +1,14 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
- import { CHAIN_RUNS_DIR, TEMP_ARTIFACTS_DIR } from "./types.js";
4
- import { getAgentDir } from "./utils.js";
3
+ import { CHAIN_RUNS_DIR, DIRS, TEMP_ARTIFACTS_DIR } from "./types.js";
4
+ import { getAgentDir, readStatus } from "./utils.js";
5
+ import { acquireSessionLease } from "../runs/shared/session-lease.js";
5
6
  const CLEANUP_MARKER_FILE = ".last-cleanup";
7
+ // Pi lists only directories under its sessions root, so a marker file there is invisible to it.
8
+ const FORK_CLEANUP_MARKER_FILE = ".pi-subagents-fork-cleanup";
9
+ const DAY_MS = 24 * 60 * 60 * 1000;
10
+ // Kept worktrees can outlive cleanupDays; their handoff record and the patches it points to must stay with them.
11
+ const RETAINED_ARTIFACT_DIRS = new Set(["handoffs", "worktree-diffs"]);
6
12
  export const PROJECT_SUBAGENTS_RELATIVE_DIR = ".pi/subagents";
7
13
  const PROJECT_ARTIFACT_PATHS = [
8
14
  `${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/output.md`,
@@ -221,30 +227,36 @@ export function cleanupOldArtifacts(dir, maxAgeDays) {
221
227
  return;
222
228
  const markerPath = path.join(dir, CLEANUP_MARKER_FILE);
223
229
  const now = Date.now();
224
- if (fs.existsSync(markerPath)) {
225
- const stat = fs.statSync(markerPath);
226
- if (now - stat.mtimeMs < 24 * 60 * 60 * 1000)
227
- return;
228
- }
229
- const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1000;
230
- const cutoff = now - maxAgeMs;
231
- for (const file of fs.readdirSync(dir)) {
232
- if (file === CLEANUP_MARKER_FILE)
230
+ if (ranWithinDay(markerPath, now))
231
+ return;
232
+ const cutoff = now - maxAgeDays * DAY_MS;
233
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
234
+ if (entry.name === CLEANUP_MARKER_FILE || (entry.isDirectory() && RETAINED_ARTIFACT_DIRS.has(entry.name)))
233
235
  continue;
234
- const filePath = path.join(dir, file);
235
- try {
236
- const stat = fs.statSync(filePath);
237
- if (stat.mtimeMs < cutoff) {
238
- fs.unlinkSync(filePath);
239
- }
240
- }
241
- catch {
242
- // Artifact cleanup is best-effort housekeeping. Skip files that disappear
243
- // or become unreadable while scanning so one bad entry does not block the rest.
244
- }
236
+ removeOldEntry(path.join(dir, entry.name), cutoff);
245
237
  }
246
238
  fs.writeFileSync(markerPath, String(now));
247
239
  }
240
+ function removeOldEntry(entryPath, cutoff) {
241
+ try {
242
+ const stat = fs.lstatSync(entryPath);
243
+ // Read the folder's age before emptying it: removing its files makes it look new.
244
+ const old = stat.mtimeMs < cutoff;
245
+ if (!stat.isDirectory()) {
246
+ if (old)
247
+ fs.unlinkSync(entryPath);
248
+ return;
249
+ }
250
+ for (const name of fs.readdirSync(entryPath))
251
+ removeOldEntry(path.join(entryPath, name), cutoff);
252
+ if (old && fs.readdirSync(entryPath).length === 0)
253
+ fs.rmdirSync(entryPath);
254
+ }
255
+ catch {
256
+ // Artifact cleanup is best-effort housekeeping. Skip entries that disappear
257
+ // or become unreadable while scanning so one bad entry does not block the rest.
258
+ }
259
+ }
248
260
  export function cleanupAllArtifactDirs(maxAgeDays) {
249
261
  cleanupOldArtifacts(TEMP_ARTIFACTS_DIR, maxAgeDays);
250
262
  const sessionsBase = path.join(getAgentDir(), "sessions");
@@ -259,6 +271,9 @@ export function cleanupAllArtifactDirs(maxAgeDays) {
259
271
  // skip cleanup instead of failing extension startup.
260
272
  return;
261
273
  }
274
+ const forkMarkerPath = path.join(sessionsBase, FORK_CLEANUP_MARKER_FILE);
275
+ const now = Date.now();
276
+ const pruneForks = maxAgeDays > 0 && !ranWithinDay(forkMarkerPath, now);
262
277
  for (const dir of dirs) {
263
278
  const artifactsDir = path.join(sessionsBase, dir, "subagent-artifacts");
264
279
  try {
@@ -268,5 +283,100 @@ export function cleanupAllArtifactDirs(maxAgeDays) {
268
283
  // Session cleanup is best-effort. Keep going so one unreadable session dir
269
284
  // does not block cleanup for the rest.
270
285
  }
286
+ if (pruneForks)
287
+ removeOldForkCopies(path.join(sessionsBase, dir), now - maxAgeDays * DAY_MS);
288
+ }
289
+ if (!pruneForks)
290
+ return;
291
+ try {
292
+ fs.writeFileSync(forkMarkerPath, String(now));
293
+ }
294
+ catch {
295
+ // Without the marker the next load scans again; cleanup must not fail startup.
296
+ }
297
+ }
298
+ function ranWithinDay(markerPath, now) {
299
+ try {
300
+ return now - fs.statSync(markerPath).mtimeMs < DAY_MS;
271
301
  }
302
+ catch {
303
+ return false;
304
+ }
305
+ }
306
+ function removeOldForkCopies(projectDir, cutoff) {
307
+ let sessions;
308
+ try {
309
+ sessions = fs.readdirSync(projectDir, { withFileTypes: true });
310
+ }
311
+ catch {
312
+ return;
313
+ }
314
+ for (const session of sessions) {
315
+ if (!session.isDirectory())
316
+ continue;
317
+ const forksDir = path.join(projectDir, session.name, "forks");
318
+ let runIds;
319
+ try {
320
+ // Never follow a symlinked forks folder: the deletes below would land in its target.
321
+ if (!fs.lstatSync(forksDir).isDirectory())
322
+ continue;
323
+ runIds = fs.readdirSync(forksDir);
324
+ }
325
+ catch {
326
+ continue;
327
+ }
328
+ for (const runId of runIds) {
329
+ const runDir = path.join(forksDir, runId);
330
+ const leases = [];
331
+ try {
332
+ const sessionFiles = idleSessionFiles(runDir, cutoff);
333
+ if (!sessionFiles || asyncRunActive(runId))
334
+ continue;
335
+ // A resumed run writes into its old copy under a new run id and holds that file's session lease.
336
+ // Holding the leases while deleting means a resume elsewhere finds either the lease taken or the file gone.
337
+ for (const file of sessionFiles)
338
+ leases.push(acquireSessionLease({ sessionFile: file, runId: "fork-cleanup", sourceRunId: runId }));
339
+ fs.rmSync(runDir, { recursive: true, force: true });
340
+ }
341
+ catch {
342
+ // Best-effort like artifact cleanup: a leased copy, or an entry that vanishes or can't be read, is left for the next pass.
343
+ }
344
+ finally {
345
+ for (const lease of leases)
346
+ lease.release();
347
+ }
348
+ }
349
+ }
350
+ }
351
+ // Undefined when anything inside, including a nested fork's copy, was written since cutoff: that keeps the whole folder.
352
+ function idleSessionFiles(entryPath, cutoff, files = []) {
353
+ const stat = fs.lstatSync(entryPath);
354
+ if (stat.mtimeMs >= cutoff)
355
+ return undefined;
356
+ if (!stat.isDirectory()) {
357
+ if (stat.isFile() && entryPath.endsWith(".jsonl"))
358
+ files.push(entryPath);
359
+ return files;
360
+ }
361
+ for (const name of fs.readdirSync(entryPath)) {
362
+ if (!idleSessionFiles(path.join(entryPath, name), cutoff, files))
363
+ return undefined;
364
+ }
365
+ return files;
366
+ }
367
+ // An async run waiting on a long tool call or a reply can leave its session file untouched for a long time.
368
+ function asyncRunActive(runId) {
369
+ try {
370
+ const state = readStatus(path.join(DIRS.async, runId))?.state;
371
+ return state === "queued" || state === "running";
372
+ }
373
+ catch {
374
+ // A status that can't be read may still belong to a live run.
375
+ return true;
376
+ }
377
+ }
378
+ export function missingForkCopyNote(sessionFile) {
379
+ if (path.basename(path.dirname(path.dirname(sessionFile))) !== "forks")
380
+ return "";
381
+ return ". It was a forked child's copy of the parent session; such copies are deleted once nothing has written to them for artifactConfig.cleanupDays days (default 7).";
272
382
  }
@@ -2,7 +2,7 @@ import { Buffer } from "node:buffer";
2
2
  import { createHash } from "node:crypto";
3
3
  import * as fs from "node:fs";
4
4
  import * as path from "node:path";
5
- import { resolveModelCandidate } from "../runs/shared/model-resolution.js";
5
+ import { knownModelProviders, resolveModelCandidate } from "../runs/shared/model-resolution.js";
6
6
  import { splitKnownThinkingSuffix, toModelInfo } from "./model-info.js";
7
7
  import { opencodeSessionHeaders } from "./opencode-session-headers.js";
8
8
  const MAX_INHERITED_SESSION_BYTES = 64 * 1024;
@@ -392,7 +392,7 @@ export async function createPrunedForkSessionWriter(ctx, config, signal) {
392
392
  if (!config.model?.trim())
393
393
  throw new Error("Pruned fork context requires config.forkContext.model.");
394
394
  const available = ctx.modelRegistry.getAvailable();
395
- const resolved = resolveModelCandidate(config.model.trim(), available.map(toModelInfo), ctx.model?.provider);
395
+ const resolved = resolveModelCandidate(config.model.trim(), available.map(toModelInfo), ctx.model?.provider, knownModelProviders(ctx.modelRegistry));
396
396
  if (!resolved)
397
397
  throw new Error(`Pruned fork model '${config.model}' did not match exactly one available model.`);
398
398
  const { baseModel } = splitKnownThinkingSuffix(resolved);
@@ -0,0 +1 @@
1
+ export declare function extractReportedProgress(toolName: string, args: unknown): string | undefined;
@@ -0,0 +1,12 @@
1
+ import { sanitizeDisplayText } from "./display-text.js";
2
+ const MAX_REPORTED_PROGRESS_LENGTH = 512;
3
+ export function extractReportedProgress(toolName, args) {
4
+ if (toolName !== "contact_supervisor" || typeof args !== "object" || args === null)
5
+ return undefined;
6
+ const call = args;
7
+ if (call.reason !== "progress_update" || typeof call.message !== "string")
8
+ return undefined;
9
+ const firstLine = call.message.split(/\r?\n/, 1)[0] ?? "";
10
+ const sanitized = sanitizeDisplayText(firstLine).replace(/^(?:progress|update):\s*/i, "");
11
+ return sanitized ? sanitized.slice(0, MAX_REPORTED_PROGRESS_LENGTH) : undefined;
12
+ }
@@ -1,5 +1,6 @@
1
1
  import type { ActivityState, AsyncJobStep } from "./types.ts";
2
2
  type StepStatusLike = Pick<AsyncJobStep, "status">;
3
+ export declare function formatActivityAge(ms: number): string;
3
4
  export declare function formatActivityLabel(lastActivityAt: number | undefined, activityState?: ActivityState, now?: number): string | undefined;
4
5
  export declare function aggregateStepStatus(steps: StepStatusLike[]): AsyncJobStep["status"];
5
6
  export declare function formatAgentRunningLabel(count: number): string;
@@ -1,4 +1,4 @@
1
- function formatActivityAge(ms) {
1
+ export function formatActivityAge(ms) {
2
2
  if (ms < 1000)
3
3
  return "now";
4
4
  if (ms < 60000)
@@ -668,6 +668,7 @@ export interface ScheduleOrigin {
668
668
  }
669
669
  export type SteeringActionState = "delivered" | "scheduled" | "pending" | "partial" | "recovered" | "failed";
670
670
  export type SteeringTargetState = "scheduled" | "pending" | "routed" | "queued" | "delivered" | "late" | "failed" | "recovered";
671
+ export type SteeringFailureKind = "rejected" | "unconsumed";
671
672
  export interface SteeringTargetStatus {
672
673
  index: number;
673
674
  state: SteeringTargetState;
@@ -676,6 +677,7 @@ export interface SteeringTargetStatus {
676
677
  lateDeliveredAt?: number;
677
678
  failedAt?: number;
678
679
  recoveredAt?: number;
680
+ failureKind?: SteeringFailureKind;
679
681
  reason?: string;
680
682
  replacementRunId?: string;
681
683
  }
@@ -700,6 +702,7 @@ export interface SteeringStatus {
700
702
  export interface SteerActionTarget {
701
703
  index: number;
702
704
  state: SteeringTargetState;
705
+ failureKind?: SteeringFailureKind;
703
706
  deliveredAt?: number;
704
707
  lateDeliveredAt?: number;
705
708
  reason?: string;
@@ -887,6 +890,8 @@ export interface AgentProgress {
887
890
  /** Human-readable display name for the child's session, when derived at launch. */
888
891
  sessionName?: string;
889
892
  status: "pending" | "running" | "completed" | "failed" | "detached";
893
+ progressText?: string;
894
+ progressUpdatedAt?: number;
890
895
  activityState?: ActivityState;
891
896
  task: string;
892
897
  skills?: string[];
@@ -1457,6 +1462,8 @@ export interface Details {
1457
1462
  sourceRunId: string;
1458
1463
  attempt: number;
1459
1464
  };
1465
+ /** When `stop` with `drain` was requested (epoch ms). A drained run is never resumed. */
1466
+ drainRequestedAt?: number;
1460
1467
  resource?: WorkflowResourceProvenance;
1461
1468
  preflightWarnings?: string[];
1462
1469
  trace: Array<{
@@ -1541,6 +1548,8 @@ export interface NestedStepSummary {
1541
1548
  /** Human-readable display name for the child session, when derived at launch. */
1542
1549
  sessionName?: string;
1543
1550
  status: "pending" | "running" | "complete" | "completed" | "failed" | "partial" | "paused" | "stopped" | "rejected";
1551
+ progressText?: string;
1552
+ progressUpdatedAt?: number;
1544
1553
  model?: string;
1545
1554
  thinking?: string;
1546
1555
  sessionFile?: string;
@@ -1993,6 +2002,8 @@ export interface AsyncStatus {
1993
2002
  endMs: number;
1994
2003
  }>;
1995
2004
  recentOutput?: string[];
2005
+ progressText?: string;
2006
+ progressUpdatedAt?: number;
1996
2007
  turnCount?: number;
1997
2008
  toolCount?: number;
1998
2009
  startedAt?: number;
@@ -2285,6 +2296,10 @@ export interface WaitSubscriptionRecord {
2285
2296
  version: 1;
2286
2297
  token: string;
2287
2298
  sessionId: string;
2299
+ /** Completion owner of the process that armed the record. A record without it stays scoped to the session. */
2300
+ completionOwnerId?: string;
2301
+ /** The Pi process behind `completionOwnerId`. Once it is dead, the next process on the session takes the wake. */
2302
+ completionOwnerProcess?: RecordedPid;
2288
2303
  targetKind: "async" | "foreground";
2289
2304
  runId: string;
2290
2305
  requestedId: string;
@@ -2374,6 +2389,13 @@ export interface SubagentState {
2374
2389
  workflowControllers?: Map<string, AbortController>;
2375
2390
  /** Live in-process workflow child stoppers keyed by parent workflow run id. */
2376
2391
  workflowChildStops?: Map<string, (childId: string, message?: string) => boolean>;
2392
+ /** Live in-process workflow drains keyed by workflow run id; `ok: false` means the drain request could not be saved and nothing was stopped. */
2393
+ workflowDrains?: Map<string, () => {
2394
+ ok: true;
2395
+ started: number;
2396
+ } | {
2397
+ ok: false;
2398
+ }>;
2377
2399
  /** Background children awaited by a blocking workflow call: their parent cannot answer supervisor asks. */
2378
2400
  blockingWorkflowChildren?: Set<string>;
2379
2401
  }
@@ -2562,6 +2584,7 @@ export interface RunSyncOptions {
2562
2584
  fullId: string;
2563
2585
  contextWindow?: number;
2564
2586
  }>;
2587
+ knownProviders?: import("../runs/shared/model-resolution.ts").KnownProviders;
2565
2588
  modelResponseAliases?: Record<string, string[]>;
2566
2589
  /** Current parent-session provider to prefer for ambiguous bare model ids */
2567
2590
  preferredModelProvider?: string;
@@ -1,4 +1,4 @@
1
- import type { Message, Usage as PiUsage } from "@earendil-works/pi-ai";
1
+ import type { Message, StopReason, Usage as PiUsage } from "@earendil-works/pi-ai";
2
2
  import type { AgentProgress, AsyncStatus, Details, DisplayItem, ErrorInfo, SingleResult, ToolCallSummary, Usage } from "./types.ts";
3
3
  export declare const PI_CODING_AGENT_PACKAGE_ROOT_ENV = "PI_SUBAGENTS_PI_CODING_AGENT_PACKAGE_ROOT";
4
4
  export declare const PROMPT_REDACTED = "[prompt redacted]";
@@ -27,6 +27,8 @@ export declare function assistantMessageError(message: {
27
27
  }): string | undefined;
28
28
  export declare function getFinalOutput(messages: Message[]): string;
29
29
  export declare function getSingleResultOutput(result: Pick<SingleResult, "finalOutput" | "messages">): string;
30
+ export declare const TRUNCATED_RESPONSE_ERROR = "Response was truncated: the model reached its maximum output length.";
31
+ export declare function getTerminalAssistantStopReason(messages: Message[]): StopReason | undefined;
30
32
  export declare function getDisplayItems(messages: Message[] | undefined): DisplayItem[];
31
33
  export declare function sumResultsUsage(results: SingleResult[]): Usage;
32
34
  export declare function toAgentToolUsage(usage: Usage): PiUsage;
@@ -288,6 +288,10 @@ export function getFinalOutput(messages) {
288
288
  export function getSingleResultOutput(result) {
289
289
  return result.finalOutput ?? getFinalOutput(result.messages ?? []);
290
290
  }
291
+ export const TRUNCATED_RESPONSE_ERROR = "Response was truncated: the model reached its maximum output length.";
292
+ export function getTerminalAssistantStopReason(messages) {
293
+ return messages.findLast((message) => message.role === "assistant")?.stopReason;
294
+ }
291
295
  export function getDisplayItems(messages) {
292
296
  if (!messages || messages.length === 0)
293
297
  return [];
package/src/tui/render.js CHANGED
@@ -10,7 +10,7 @@ import { formatContextUsage, formatTokens, formatUsage, formatDuration, formatMo
10
10
  import { getDisplayItems, getSingleResultOutput, PROMPT_REDACTED } from "../shared/utils.js";
11
11
  import { flatToLogicalStepIndex } from "../runs/background/parallel-groups.js";
12
12
  import { formatNestedAggregate } from "../runs/shared/nested-render.js";
13
- import { aggregateStepStatus, formatActivityLabel, formatAgentRunningLabel, formatParallelOutcome } from "../shared/status-format.js";
13
+ import { aggregateStepStatus, formatActivityAge, formatActivityLabel, formatAgentRunningLabel, formatParallelOutcome } from "../shared/status-format.js";
14
14
  import { contextModeBadge, contextModePrefix } from "../runs/shared/context-mode.js";
15
15
  import { shouldSuppressSingleStep, stripRepeatedAgentPrefix, withDuplicateLabelDiscriminators } from "./render-helpers.js";
16
16
  import { runningTone } from "./running-tone.js";
@@ -619,6 +619,17 @@ function workflowLabelForResult(details, resultIndex) {
619
619
  };
620
620
  return details.workflowGraph ? visit(details.workflowGraph.nodes) : undefined;
621
621
  }
622
+ function reportedProgressRow(progress, theme, indent, width) {
623
+ const text = progress.progressText?.trim();
624
+ if (!text)
625
+ return undefined;
626
+ let updated = "";
627
+ if (progress.progressUpdatedAt !== undefined) {
628
+ const age = formatActivityAge(Math.max(0, Date.now() - progress.progressUpdatedAt));
629
+ updated = age === "now" ? " · updated now" : ` · updated ${age} ago`;
630
+ }
631
+ return truncLine(theme.fg("dim", `${indent}progress: ${sanitizeDisplayText(text)}${updated}`), width);
632
+ }
622
633
  function foregroundProgressForResult(details, resultIndex) {
623
634
  const result = details.results[resultIndex];
624
635
  if (result?.progress)
@@ -961,6 +972,8 @@ function widgetStepRenderKey(step, index, expanded = false) {
961
972
  step.workflowKey,
962
973
  step.phase,
963
974
  step.label,
975
+ step.progressText,
976
+ step.progressUpdatedAt,
964
977
  step.status,
965
978
  step.activityState,
966
979
  step.lastActivityAt,
@@ -2295,6 +2308,9 @@ options) {
2295
2308
  lines.push(`${detailIndent}${theme.fg("dim", line)}`);
2296
2309
  if (task)
2297
2310
  lines.push(`${detailIndent}${theme.fg("dim", `task: ${task}`)}`);
2311
+ const progressRow = step.status === "running" ? reportedProgressRow(step, theme, detailIndent, width - 4) : undefined;
2312
+ if (progressRow)
2313
+ lines.push(progressRow);
2298
2314
  const activity = widgetStepActivityLine(step, width, expanded, job.updatedAt);
2299
2315
  const currentPath = options?.includeCurrentPath && step.currentPath ? shortenPath(step.currentPath) : undefined;
2300
2316
  const activityWithPath = currentPath && activity && !activity.includes(currentPath)
@@ -2445,12 +2461,15 @@ function compactSingleWidgetLines(job, theme, width, frame, projection = buildWo
2445
2461
  const status = widgetStepStatus(step.status, theme, thinking);
2446
2462
  const activity = widgetStepActivityLine(step, width, false, job.updatedAt);
2447
2463
  const stepStats = widgetStepStats(theme, step, job.updatedAt);
2448
- const activitySuffix = activity ? ` ${theme.fg("dim", "·")} ${theme.fg("dim", activity)}` : "";
2449
2464
  const modelDisplay = modelThinkingBadge(theme, step.model, step.thinking);
2450
2465
  const task = compactTaskText(step.description, step.label);
2451
2466
  const taskSuffix = task ? ` ${theme.fg("dim", "·")} ${theme.fg("dim", `task: ${task}`)}` : "";
2467
+ const activitySuffix = activity ? ` ${theme.fg("dim", "·")} ${theme.fg("dim", activity)}` : "";
2452
2468
  const marker = rowIndex === rows.length - 1 && rowIndex >= group.total - 1 ? "└─" : "├─";
2453
2469
  lines.push(` ${marker} ${widgetStepGlyph(step.status, theme, widgetStepRunningSeed(step, row.index), frame, thinking)} ${themeBold(theme, row.rowLabel)}${contextModeBadge(theme, step.context)} ${theme.fg("dim", "·")} ${status}${modelDisplay}${taskSuffix}${activitySuffix}${stepStats ? ` ${theme.fg("dim", "·")} ${stepStats}` : ""}`);
2470
+ const progressRow = step.status === "running" ? reportedProgressRow(step, theme, " ", width) : undefined;
2471
+ if (progressRow)
2472
+ lines.push(progressRow);
2454
2473
  const lane = projectAsyncLane(job, step);
2455
2474
  if (lane)
2456
2475
  lines.push(...formatLaneProjectionLines(lane, theme, " "));
@@ -3142,6 +3161,9 @@ function renderSingleCompact(d, r, theme, layout, frame, foregroundDetachShortcu
3142
3161
  const task = compactTaskText(r.task);
3143
3162
  if (task)
3144
3163
  c.addChild(new Text(truncLine(theme.fg("dim", `${detailIndent}task: ${task}`), width), 0, 0));
3164
+ const reportedRow = reportedProgressRow(r.progress, theme, detailIndent, width);
3165
+ if (reportedRow)
3166
+ c.addChild(new Text(reportedRow, 0, 0));
3145
3167
  const progressSnapshotNow = snapshotNowForProgress(r.progress);
3146
3168
  const activity = compactCurrentActivity(r.progress);
3147
3169
  c.addChild(new Text(truncLine(theme.fg("dim", `${detailIndent}⎿ ${activity}`), width), 0, 0));
@@ -3424,6 +3446,9 @@ function renderMultiCompact(d, theme, layout, frame) {
3424
3446
  if (task)
3425
3447
  c.addChild(new Text(truncLine(theme.fg("dim", `${detailIndent}task: ${task}`), width), 0, 0));
3426
3448
  }
3449
+ const reportedRow = rRunning && progressFromArray ? reportedProgressRow(progressFromArray, theme, detailIndent, width) : undefined;
3450
+ if (reportedRow)
3451
+ c.addChild(new Text(reportedRow, 0, 0));
3427
3452
  if (rRunning && rProg && "status" in rProg) {
3428
3453
  const liveProgress = rProg;
3429
3454
  const activity = compactCurrentActivity(liveProgress);
@@ -3546,6 +3571,9 @@ export function renderSubagentResult(result, options, theme, frame, rendererConf
3546
3571
  c.addChild(new Text(fit(theme.fg(r.exitCode !== 0 ? "error" : "dim", ` ⎿ ${resultStatusLine(r, output)}`)), 0, 0));
3547
3572
  }
3548
3573
  if (isRunning && r.progress) {
3574
+ const reportedRow = reportedProgressRow(r.progress, theme, " ", w);
3575
+ if (reportedRow)
3576
+ c.addChild(new Text(fit(reportedRow), 0, 0));
3549
3577
  const progressSnapshotNow = snapshotNowForProgress(r.progress);
3550
3578
  for (const nestedLine of formatNestedWidgetLines(r.children, theme, w, true, progressSnapshotNow, 12)) {
3551
3579
  c.addChild(new Text(fit(` ${nestedLine}`), 0, 0));
@@ -3733,6 +3761,9 @@ export function renderSubagentResult(result, options, theme, frame, rendererConf
3733
3761
  ? r.task
3734
3762
  : `${r.task.slice(0, taskMaxLen)}...`;
3735
3763
  c.addChild(new Text(fit(theme.fg("dim", ` task: ${taskPreview}`)), 0, 0));
3764
+ const reportedRow = rRunning && progressFromArray ? reportedProgressRow(progressFromArray, theme, " ", w) : undefined;
3765
+ if (reportedRow)
3766
+ c.addChild(new Text(fit(reportedRow), 0, 0));
3736
3767
  const outputTarget = extractOutputTarget(r.task);
3737
3768
  if (outputTarget) {
3738
3769
  c.addChild(new Text(fit(theme.fg("dim", ` output: ${outputTarget}`)), 0, 0));
@@ -1,4 +1,4 @@
1
- import { normalizeModelSegment, resolveModelCandidate } from "../runs/shared/model-resolution.js";
1
+ import { knownModelProviders, normalizeModelSegment, resolveModelCandidate } from "../runs/shared/model-resolution.js";
2
2
  import { getSupportedThinkingLevels, splitKnownThinkingSuffix, THINKING_LEVELS, toModelInfo, } from "../shared/model-info.js";
3
3
  export const STRONG_WATCHDOG_THINKING = "high";
4
4
  const STRONG_WATCHDOG_MODELS = {
@@ -53,7 +53,7 @@ export function resolveWatchdogModelInput(ctx, rawModel) {
53
53
  throw new Error("Watchdog model must be a non-empty provider/model value.");
54
54
  const availableModels = modelRegistryEntries(ctx);
55
55
  const preferredProvider = typeof ctx.model?.provider === "string" ? ctx.model.provider : undefined;
56
- const resolved = resolveModelCandidate(trimmed, availableModels, preferredProvider) ?? trimmed;
56
+ const resolved = resolveModelCandidate(trimmed, availableModels, preferredProvider, knownModelProviders(ctx.modelRegistry)) ?? trimmed;
57
57
  const { baseModel, thinkingSuffix } = splitKnownThinkingSuffix(resolved);
58
58
  const named = splitProviderModel(baseModel);
59
59
  if (!named)
@@ -90,6 +90,7 @@ export function createWatchdogPermissionArbiter(options = {}) {
90
90
  ].join("\n");
91
91
  const tools = [tool];
92
92
  agent = new Agent({
93
+ sessionId,
93
94
  initialState: {
94
95
  systemPrompt,
95
96
  model: selection.model,
@@ -27,10 +27,5 @@ export declare function resolveWatchdogReviewModel(ctx: ExtensionContext, config
27
27
  currentThinkingLevel?: ThinkingLevel;
28
28
  }): Promise<WatchdogReviewModelSelection>;
29
29
  export declare function formatWatchdogCwdSection(cwd: string): string;
30
- export declare function buildWatchdogSystemPrompt(ctx: Pick<ExtensionContext, "cwd">, options?: {
31
- hasScope?: boolean;
32
- guidance?: string;
33
- hasDiff?: boolean;
34
- }): string;
35
30
  export declare function createMainWatchdogReview(provider: WatchdogContextProvider, options?: CreateMainWatchdogReviewOptions): WatchdogReviewFunction;
36
31
  export {};
@@ -1,7 +1,7 @@
1
1
  import { Agent } from "@earendil-works/pi-agent-core";
2
2
  import { createReadOnlyTools, convertToLlm } from "@earendil-works/pi-coding-agent";
3
3
  import { Type } from "typebox";
4
- import { resolveModelCandidate } from "../runs/shared/model-resolution.js";
4
+ import { knownModelProviders, resolveModelCandidate } from "../runs/shared/model-resolution.js";
5
5
  import { agentStreamOptions } from "../shared/agent-stream-options.js";
6
6
  import { opencodeSessionHeaders } from "../shared/opencode-session-headers.js";
7
7
  import { resolveEffectiveThinking, splitKnownThinkingSuffix, THINKING_LEVELS, toModelInfo } from "../shared/model-info.js";
@@ -54,7 +54,7 @@ function resolveReviewThinking(input) {
54
54
  function resolveConfiguredModel(ctx, rawModel) {
55
55
  const availableModels = ctx.modelRegistry.getAvailable().map(toModelInfo);
56
56
  const preferredProvider = typeof ctx.model?.provider === "string" ? ctx.model.provider : undefined;
57
- const resolved = resolveModelCandidate(rawModel, availableModels, preferredProvider);
57
+ const resolved = resolveModelCandidate(rawModel, availableModels, preferredProvider, knownModelProviders(ctx.modelRegistry));
58
58
  if (!resolved) {
59
59
  throw new Error(`Configured watchdog model '${rawModel}' did not match exactly one authenticated available model. Use provider/model or configure credentials for the intended provider.`);
60
60
  }
@@ -170,7 +170,7 @@ export function formatWatchdogCwdSection(cwd) {
170
170
  throw new Error("Watchdog cwd cannot contain control, line-separator, or angle-bracket characters.");
171
171
  return `<cwd>\n${cwd}\n</cwd>`;
172
172
  }
173
- export function buildWatchdogSystemPrompt(ctx, options = {}) {
173
+ function buildWatchdogSystemPrompt(ctx, options = {}) {
174
174
  const guidance = options.guidance?.trim();
175
175
  return [
176
176
  "You are the main-session subagent watchdog for Pi.",
@@ -278,6 +278,7 @@ async function runWatchdogAttempt(ctx, request, options) {
278
278
  hasDiff: diffBaseline !== undefined,
279
279
  });
280
280
  const agent = new Agent({
281
+ sessionId,
281
282
  initialState: {
282
283
  systemPrompt,
283
284
  model: selection.model,
@@ -184,6 +184,8 @@ export interface RunWorkflowScriptOptions {
184
184
  set: (key: string, value: unknown) => void | Promise<void>;
185
185
  };
186
186
  registerStopChild?: (stop: ((key: string, message?: string) => boolean) | undefined) => void;
187
+ /** Drain: stop children that have not started, refuse new launches, and call `onDrained` once every started child has a result. Returns the started-child count. */
188
+ registerDrain?: (drain: ((onDrained: () => void) => number) | undefined) => void;
187
189
  onTrace?: (trace: WorkflowScriptTraceEntry[]) => void;
188
190
  onLanePlan?: (lanes: WorkflowLanePlan[]) => void;
189
191
  onEmit?: (emits: unknown[]) => void;