pi-subagents 0.87.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 (91) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-3CVOAS77.js → chunk-2DIEL4WG.js} +2 -2
  5. package/bundle/{chunk-PGU4TZV3.js → chunk-3DT5X2QC.js} +406 -447
  6. package/bundle/{chunk-SIAQXPJ4.js → chunk-3MFYKBKI.js} +18 -6
  7. package/bundle/{chunk-AIL46SZU.js → chunk-47GJDBIK.js} +6 -4
  8. package/bundle/{chunk-ESWW6XSX.js → chunk-47ZN7NKR.js} +1 -1
  9. package/bundle/{chunk-C3KWLXDH.js → chunk-4MVDMA5C.js} +9 -1
  10. package/bundle/{chunk-DGTZKYIE.js → chunk-4PM6RDE5.js} +42 -29
  11. package/bundle/{chunk-EYGBK6CE.js → chunk-4UGWHREQ.js} +45 -15
  12. package/bundle/{chunk-HDICKROY.js → chunk-6EUQPQY7.js} +31 -14
  13. package/bundle/{chunk-LFKMM3UH.js → chunk-6OWNDN7R.js} +2 -2
  14. package/bundle/{chunk-M2VBGET6.js → chunk-6PR44R7E.js} +7 -2
  15. package/bundle/{chunk-OOE3R7IQ.js → chunk-CKLZ5FGU.js} +2 -2
  16. package/bundle/{chunk-W52LJANO.js → chunk-CYKNHFXB.js} +1 -1
  17. package/bundle/{chunk-6O7YH2QV.js → chunk-GDR2ILWY.js} +1 -1
  18. package/bundle/{chunk-2D2DQGC2.js → chunk-IZEKQEY4.js} +9 -9
  19. package/bundle/{chunk-C5QWQSSM.js → chunk-KXW62VBU.js} +1 -1
  20. package/bundle/{chunk-BFF6YDK6.js → chunk-L4YY2TOE.js} +1 -1
  21. package/bundle/{chunk-JLDQ6YUR.js → chunk-MTPICU4A.js} +11 -11
  22. package/bundle/{chunk-YEXKJJVS.js → chunk-PJSOS2Q4.js} +4 -4
  23. package/bundle/{chunk-2NY5PCKQ.js → chunk-RHYVKQQL.js} +4 -4
  24. package/bundle/{chunk-XV7RTWTS.js → chunk-SVIXQDIV.js} +20 -5
  25. package/bundle/{chunk-OTLDAYEQ.js → chunk-UVDLJXL6.js} +14 -5
  26. package/bundle/{chunk-VFUFOZBU.js → chunk-W6HIYD2Z.js} +1 -1
  27. package/bundle/{chunk-OZCPYJEY.js → chunk-XAOHLFJO.js} +118 -42
  28. package/bundle/{chunk-USRX7QXD.js → chunk-XIA5GSEU.js} +2 -2
  29. package/bundle/chunk-YDZ7BZD5.js +523 -0
  30. package/bundle/{chunk-LZKVUWIY.js → chunk-YZPVALSQ.js} +30 -5
  31. package/bundle/control-channel.js +2 -2
  32. package/bundle/index.js +1 -1
  33. package/bundle/intercom-bridge.js +2 -2
  34. package/bundle/preflight.js +8 -8
  35. package/bundle/project-panes.js +3 -3
  36. package/docs/agents.md +1 -1
  37. package/docs/configuration.md +7 -3
  38. package/docs/observability.md +2 -0
  39. package/docs/tool-reference.md +4 -1
  40. package/package.json +2 -2
  41. package/skills/pi-subagents/SKILL.md +8 -2
  42. package/src/agents/agent-management.d.ts +1 -0
  43. package/src/agents/agent-management.js +12 -4
  44. package/src/agents/agents.d.ts +1 -0
  45. package/src/agents/agents.js +2 -2
  46. package/src/extension/config.d.ts +1 -0
  47. package/src/extension/config.js +6 -0
  48. package/src/extension/index.js +4 -3
  49. package/src/extension/schemas.d.ts +2 -0
  50. package/src/extension/schemas.js +1 -0
  51. package/src/extension/tool-activation.js +20 -3
  52. package/src/runs/background/async-resume.js +2 -1
  53. package/src/runs/background/async-retention.d.ts +0 -2
  54. package/src/runs/background/async-retention.js +11 -5
  55. package/src/runs/background/async-status.d.ts +2 -0
  56. package/src/runs/background/async-status.js +4 -0
  57. package/src/runs/background/run-child-session.d.ts +2 -2
  58. package/src/runs/background/run-child-session.js +4 -7
  59. package/src/runs/background/steering.d.ts +2 -11
  60. package/src/runs/background/steering.js +11 -6
  61. package/src/runs/background/subagent-runner.d.ts +0 -2
  62. package/src/runs/background/subagent-runner.js +73 -58
  63. package/src/runs/foreground/async-steering-action.js +24 -9
  64. package/src/runs/foreground/execution.js +32 -15
  65. package/src/runs/foreground/prompt-audit.js +1 -0
  66. package/src/runs/foreground/subagent-executor.d.ts +1 -8
  67. package/src/runs/foreground/subagent-executor.js +6 -15
  68. package/src/runs/shared/async-status-projection.d.ts +2 -0
  69. package/src/runs/shared/async-status-projection.js +10 -0
  70. package/src/runs/shared/child-session.js +21 -3
  71. package/src/runs/shared/mcp-config-sources.d.ts +2 -0
  72. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -2
  73. package/src/runs/shared/mcp-direct-tool-allowlist.js +21 -11
  74. package/src/runs/shared/subagent-prompt-runtime.js +14 -2
  75. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  76. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  77. package/src/shared/artifacts.d.ts +1 -0
  78. package/src/shared/artifacts.js +107 -9
  79. package/src/shared/reported-progress.d.ts +1 -0
  80. package/src/shared/reported-progress.js +12 -0
  81. package/src/shared/status-format.d.ts +1 -0
  82. package/src/shared/status-format.js +1 -1
  83. package/src/shared/types.d.ts +9 -0
  84. package/src/shared/utils.d.ts +3 -1
  85. package/src/shared/utils.js +4 -0
  86. package/src/tui/render.js +33 -2
  87. package/src/watchdog/permission-arbiter.js +1 -0
  88. package/src/watchdog/review.d.ts +0 -5
  89. package/src/watchdog/review.js +2 -1
  90. package/src/workflows/workflow-script-worker.js +3 -1
  91. package/bundle/chunk-XSDYTXHF.js +0 -242
@@ -1,8 +1,12 @@
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;
6
10
  // Kept worktrees can outlive cleanupDays; their handoff record and the patches it points to must stay with them.
7
11
  const RETAINED_ARTIFACT_DIRS = new Set(["handoffs", "worktree-diffs"]);
8
12
  export const PROJECT_SUBAGENTS_RELATIVE_DIR = ".pi/subagents";
@@ -223,13 +227,9 @@ export function cleanupOldArtifacts(dir, maxAgeDays) {
223
227
  return;
224
228
  const markerPath = path.join(dir, CLEANUP_MARKER_FILE);
225
229
  const now = Date.now();
226
- if (fs.existsSync(markerPath)) {
227
- const stat = fs.statSync(markerPath);
228
- if (now - stat.mtimeMs < 24 * 60 * 60 * 1000)
229
- return;
230
- }
231
- const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1000;
232
- const cutoff = now - maxAgeMs;
230
+ if (ranWithinDay(markerPath, now))
231
+ return;
232
+ const cutoff = now - maxAgeDays * DAY_MS;
233
233
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
234
234
  if (entry.name === CLEANUP_MARKER_FILE || (entry.isDirectory() && RETAINED_ARTIFACT_DIRS.has(entry.name)))
235
235
  continue;
@@ -271,6 +271,9 @@ export function cleanupAllArtifactDirs(maxAgeDays) {
271
271
  // skip cleanup instead of failing extension startup.
272
272
  return;
273
273
  }
274
+ const forkMarkerPath = path.join(sessionsBase, FORK_CLEANUP_MARKER_FILE);
275
+ const now = Date.now();
276
+ const pruneForks = maxAgeDays > 0 && !ranWithinDay(forkMarkerPath, now);
274
277
  for (const dir of dirs) {
275
278
  const artifactsDir = path.join(sessionsBase, dir, "subagent-artifacts");
276
279
  try {
@@ -280,5 +283,100 @@ export function cleanupAllArtifactDirs(maxAgeDays) {
280
283
  // Session cleanup is best-effort. Keep going so one unreadable session dir
281
284
  // does not block cleanup for the rest.
282
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;
283
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).";
284
382
  }
@@ -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[];
@@ -1543,6 +1548,8 @@ export interface NestedStepSummary {
1543
1548
  /** Human-readable display name for the child session, when derived at launch. */
1544
1549
  sessionName?: string;
1545
1550
  status: "pending" | "running" | "complete" | "completed" | "failed" | "partial" | "paused" | "stopped" | "rejected";
1551
+ progressText?: string;
1552
+ progressUpdatedAt?: number;
1546
1553
  model?: string;
1547
1554
  thinking?: string;
1548
1555
  sessionFile?: string;
@@ -1995,6 +2002,8 @@ export interface AsyncStatus {
1995
2002
  endMs: number;
1996
2003
  }>;
1997
2004
  recentOutput?: string[];
2005
+ progressText?: string;
2006
+ progressUpdatedAt?: number;
1998
2007
  turnCount?: number;
1999
2008
  toolCount?: number;
2000
2009
  startedAt?: number;
@@ -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));
@@ -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 {};
@@ -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,
@@ -14,7 +14,9 @@ export class WorkflowScriptProcess extends EventEmitter {
14
14
  constructor(acornPath) {
15
15
  super();
16
16
  const acorn = realpathSync(acornPath);
17
- this.child = fork(WORKFLOW_PROCESS_URL, [acorn], {
17
+ // Fork a path, not the URL. A host that runs Pi on Electron does not strip execArgv from a child started
18
+ // from a file URL, so the flags below would arrive in the child's argv ahead of the script.
19
+ this.child = fork(fileURLToPath(WORKFLOW_PROCESS_URL), [acorn], {
18
20
  // Under --permission, Node lets worker threads read everything under the process cwd, so the cwd must
19
21
  // hold only public files: acorn's own directory. It also never holds a caller's cwd open on Windows.
20
22
  cwd: dirname(acorn),
@@ -1,242 +0,0 @@
1
- import {
2
- getAgentDir
3
- } from "./chunk-C3KWLXDH.js";
4
- import {
5
- TEMP_ARTIFACTS_DIR
6
- } from "./chunk-JEZOSEWG.js";
7
-
8
- // src/shared/artifacts.ts
9
- import * as fs from "node:fs";
10
- import * as path from "node:path";
11
- var CLEANUP_MARKER_FILE = ".last-cleanup";
12
- var RETAINED_ARTIFACT_DIRS = /* @__PURE__ */ new Set(["handoffs", "worktree-diffs"]);
13
- var PROJECT_SUBAGENTS_RELATIVE_DIR = ".pi/subagents";
14
- var PROJECT_ARTIFACT_PATHS = [
15
- `${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/output.md`,
16
- `${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/run_worker_input.md`,
17
- `${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/run_worker_output.md`,
18
- `${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/run_worker.jsonl`,
19
- `${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/run_worker_transcript.jsonl`,
20
- `${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/run_worker_meta.json`,
21
- `${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/progress/run/progress.md`,
22
- `${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/outputs/output.md`,
23
- `${PROJECT_SUBAGENTS_RELATIVE_DIR}/artifacts/outputs/run/output.md`,
24
- `${PROJECT_SUBAGENTS_RELATIVE_DIR}/chain-runs/run.json`
25
- ];
26
- function globMatchesPath(pattern, filePath) {
27
- let expression = "^";
28
- for (let index = 0; index < pattern.length; index += 1) {
29
- const character = pattern[index];
30
- if (character === void 0) break;
31
- if (character === "*" && pattern[index + 1] === "*") {
32
- index += 1;
33
- if (pattern[index + 1] === "/") {
34
- index += 1;
35
- expression += "(?:.*/)?";
36
- } else {
37
- expression += ".*";
38
- }
39
- } else if (character === "*") {
40
- expression += "[^/]*";
41
- } else if (character === "?") {
42
- expression += "[^/]";
43
- } else if (character === "[") {
44
- const end = pattern.indexOf("]", index + 1);
45
- if (end === -1) expression += "\\[";
46
- else {
47
- expression += pattern.slice(index, end + 1);
48
- index = end;
49
- }
50
- } else {
51
- expression += character.replace(/[|\\{}()[\]^$+?.]/g, "\\$&");
52
- }
53
- }
54
- try {
55
- return new RegExp(`${expression}$`).test(filePath);
56
- } catch {
57
- return false;
58
- }
59
- }
60
- function normalizePattern(pattern) {
61
- return pattern.replace(/^\.\//, "").replace(/^\//, "").replace(/\/+$/, "");
62
- }
63
- function patternMatchesArtifactPath(pattern, artifactPath) {
64
- const normalized = normalizePattern(pattern);
65
- return normalized === PROJECT_SUBAGENTS_RELATIVE_DIR || normalized === "*" || artifactPath.startsWith(`${normalized}/`) || globMatchesPath(normalized, artifactPath);
66
- }
67
- function ignoreFileExcludesProjectArtifacts(filePath) {
68
- if (!fs.existsSync(filePath)) return false;
69
- try {
70
- const excluded = /* @__PURE__ */ new Set();
71
- for (const rawLine of fs.readFileSync(filePath, "utf-8").split(/\r?\n/)) {
72
- const line = rawLine.trim();
73
- if (!line || line.startsWith("#")) continue;
74
- const negated = line.startsWith("!");
75
- const pattern = negated ? line.slice(1) : line;
76
- for (const artifactPath of PROJECT_ARTIFACT_PATHS) {
77
- if (!patternMatchesArtifactPath(pattern, artifactPath)) continue;
78
- if (negated) excluded.delete(artifactPath);
79
- else excluded.add(artifactPath);
80
- }
81
- }
82
- return excluded.size === PROJECT_ARTIFACT_PATHS.length;
83
- } catch {
84
- return false;
85
- }
86
- }
87
- function filesIncludeProjectArtifacts(files) {
88
- if (!Array.isArray(files)) return void 0;
89
- const included = /* @__PURE__ */ new Set();
90
- for (const entry of files) {
91
- if (typeof entry !== "string") continue;
92
- const negated = entry.startsWith("!");
93
- const pattern = negated ? entry.slice(1) : entry;
94
- for (const artifactPath of PROJECT_ARTIFACT_PATHS) {
95
- if (!patternMatchesArtifactPath(pattern, artifactPath)) continue;
96
- if (negated) included.delete(artifactPath);
97
- else included.add(artifactPath);
98
- }
99
- }
100
- return included.size > 0;
101
- }
102
- function getProjectArtifactPackagingWarning(cwd) {
103
- const packagePath = path.join(cwd, "package.json");
104
- if (!fs.existsSync(packagePath)) return void 0;
105
- let packageJson;
106
- try {
107
- const parsed = JSON.parse(fs.readFileSync(packagePath, "utf-8"));
108
- if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return void 0;
109
- packageJson = parsed;
110
- } catch {
111
- return void 0;
112
- }
113
- const filesIncludeArtifacts = filesIncludeProjectArtifacts(packageJson.files);
114
- if (filesIncludeArtifacts === false) return void 0;
115
- const npmIgnorePath = path.join(cwd, ".npmignore");
116
- const ignorePath = fs.existsSync(npmIgnorePath) ? npmIgnorePath : path.join(cwd, ".gitignore");
117
- if (filesIncludeArtifacts === void 0 && ignoreFileExcludesProjectArtifacts(ignorePath)) return void 0;
118
- return "Project-scoped subagent artifacts can be included when this package is published. Add '.pi/subagents/' to .npmignore, restrict package.json files, or set artifactDir to 'session' or 'temp'.";
119
- }
120
- function getProjectSubagentsDir(cwd) {
121
- return path.join(cwd, PROJECT_SUBAGENTS_RELATIVE_DIR);
122
- }
123
- function getProjectArtifactsDir(cwd) {
124
- return path.join(getProjectSubagentsDir(cwd), "artifacts");
125
- }
126
- function getArtifactsDir(sessionFile, projectCwd, dirPreference = "session") {
127
- switch (dirPreference) {
128
- case "session":
129
- if (sessionFile) {
130
- const sessionDir = path.dirname(sessionFile);
131
- return path.join(sessionDir, "subagent-artifacts");
132
- }
133
- return TEMP_ARTIFACTS_DIR;
134
- case "temp":
135
- return TEMP_ARTIFACTS_DIR;
136
- case "project":
137
- if (projectCwd) return getProjectArtifactsDir(projectCwd);
138
- if (sessionFile) {
139
- const sessionDir = path.dirname(sessionFile);
140
- return path.join(sessionDir, "subagent-artifacts");
141
- }
142
- return TEMP_ARTIFACTS_DIR;
143
- default:
144
- throw new Error(`Unsupported artifactDir ${JSON.stringify(dirPreference)}; expected "project", "session", or "temp".`);
145
- }
146
- }
147
- function getArtifactPaths(artifactsDir, runId, agent, index) {
148
- const suffix = index !== void 0 ? `_${index}` : "";
149
- const safeAgent = agent.replace(/[^\w.-]/g, "_");
150
- const base = `${runId}_${safeAgent}${suffix}`;
151
- return {
152
- inputPath: path.join(artifactsDir, `${base}_input.md`),
153
- outputPath: path.join(artifactsDir, `${base}_output.md`),
154
- jsonlPath: path.join(artifactsDir, `${base}.jsonl`),
155
- transcriptPath: path.join(artifactsDir, `${base}_transcript.jsonl`),
156
- metadataPath: path.join(artifactsDir, `${base}_meta.json`)
157
- };
158
- }
159
- function ensureArtifactsDir(dir) {
160
- fs.mkdirSync(dir, { recursive: true });
161
- }
162
- function writeArtifact(filePath, content) {
163
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
164
- fs.writeFileSync(filePath, content, "utf-8");
165
- }
166
- function formatOutputArtifactContent(input) {
167
- if (input.output.trim() || !input.error) return input.output;
168
- const lines = ["Subagent run failed before producing output.", "", "Error:", input.error];
169
- if (input.transcriptPath) lines.push("", `Transcript: ${input.transcriptPath}`);
170
- if (input.metadataPath) lines.push(`Metadata: ${input.metadataPath}`);
171
- return lines.join("\n");
172
- }
173
- function writeMetadata(filePath, metadata) {
174
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
175
- fs.writeFileSync(filePath, JSON.stringify(metadata, null, 2), "utf-8");
176
- }
177
- function appendJsonl(filePath, line) {
178
- fs.appendFileSync(filePath, `${line}
179
- `);
180
- }
181
- function cleanupOldArtifacts(dir, maxAgeDays) {
182
- if (maxAgeDays <= 0 || !fs.existsSync(dir)) return;
183
- const markerPath = path.join(dir, CLEANUP_MARKER_FILE);
184
- const now = Date.now();
185
- if (fs.existsSync(markerPath)) {
186
- const stat = fs.statSync(markerPath);
187
- if (now - stat.mtimeMs < 24 * 60 * 60 * 1e3) return;
188
- }
189
- const maxAgeMs = maxAgeDays * 24 * 60 * 60 * 1e3;
190
- const cutoff = now - maxAgeMs;
191
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
192
- if (entry.name === CLEANUP_MARKER_FILE || entry.isDirectory() && RETAINED_ARTIFACT_DIRS.has(entry.name)) continue;
193
- removeOldEntry(path.join(dir, entry.name), cutoff);
194
- }
195
- fs.writeFileSync(markerPath, String(now));
196
- }
197
- function removeOldEntry(entryPath, cutoff) {
198
- try {
199
- const stat = fs.lstatSync(entryPath);
200
- const old = stat.mtimeMs < cutoff;
201
- if (!stat.isDirectory()) {
202
- if (old) fs.unlinkSync(entryPath);
203
- return;
204
- }
205
- for (const name of fs.readdirSync(entryPath)) removeOldEntry(path.join(entryPath, name), cutoff);
206
- if (old && fs.readdirSync(entryPath).length === 0) fs.rmdirSync(entryPath);
207
- } catch {
208
- }
209
- }
210
- function cleanupAllArtifactDirs(maxAgeDays) {
211
- cleanupOldArtifacts(TEMP_ARTIFACTS_DIR, maxAgeDays);
212
- const sessionsBase = path.join(getAgentDir(), "sessions");
213
- if (!fs.existsSync(sessionsBase)) return;
214
- let dirs;
215
- try {
216
- dirs = fs.readdirSync(sessionsBase);
217
- } catch {
218
- return;
219
- }
220
- for (const dir of dirs) {
221
- const artifactsDir = path.join(sessionsBase, dir, "subagent-artifacts");
222
- try {
223
- cleanupOldArtifacts(artifactsDir, maxAgeDays);
224
- } catch {
225
- }
226
- }
227
- }
228
-
229
- export {
230
- PROJECT_SUBAGENTS_RELATIVE_DIR,
231
- getProjectArtifactPackagingWarning,
232
- getProjectSubagentsDir,
233
- getArtifactsDir,
234
- getArtifactPaths,
235
- ensureArtifactsDir,
236
- writeArtifact,
237
- formatOutputArtifactContent,
238
- writeMetadata,
239
- appendJsonl,
240
- cleanupOldArtifacts,
241
- cleanupAllArtifactDirs
242
- };