@vicary/pi-subagents 0.87.0 → 0.88.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.
Files changed (108) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +3 -3
  4. package/bundle/{chunk-3CVOAS77.js → chunk-2DIEL4WG.js} +2 -2
  5. package/bundle/{chunk-75LVXBSA.js → chunk-2HKPEANZ.js} +114 -49
  6. package/bundle/{chunk-ESWW6XSX.js → chunk-47ZN7NKR.js} +1 -1
  7. package/bundle/{chunk-C3KWLXDH.js → chunk-4MVDMA5C.js} +9 -1
  8. package/bundle/{chunk-XV7RTWTS.js → chunk-4ZQBZDF3.js} +21 -6
  9. package/bundle/{chunk-LZKVUWIY.js → chunk-5EMPFFO4.js} +30 -5
  10. package/bundle/{chunk-OOE3R7IQ.js → chunk-6CG2VAG4.js} +2 -2
  11. package/bundle/{chunk-HDICKROY.js → chunk-7OX6O7DQ.js} +31 -14
  12. package/bundle/{chunk-Z4TR7MK6.js → chunk-AZPP3G4N.js} +14 -5
  13. package/bundle/{chunk-PUSTU4Q7.js → chunk-BKISQ5CJ.js} +130 -49
  14. package/bundle/{chunk-NMYBVCGP.js → chunk-CGWNA6EJ.js} +75 -44
  15. package/bundle/{chunk-PGU4TZV3.js → chunk-CPSUJHZE.js} +417 -455
  16. package/bundle/{chunk-W52LJANO.js → chunk-CYKNHFXB.js} +1 -1
  17. package/bundle/{chunk-SIAQXPJ4.js → chunk-D32H53HM.js} +21 -9
  18. package/bundle/{chunk-YEXKJJVS.js → chunk-DSHQWGHO.js} +4 -4
  19. package/bundle/{chunk-6O7YH2QV.js → chunk-GDR2ILWY.js} +1 -1
  20. package/bundle/{chunk-O7A26O6B.js → chunk-IYT7X46U.js} +6 -4
  21. package/bundle/{chunk-NJTSXIMG.js → chunk-JQTHG2ID.js} +12 -12
  22. package/bundle/{chunk-C5QWQSSM.js → chunk-KXW62VBU.js} +1 -1
  23. package/bundle/{chunk-BFF6YDK6.js → chunk-L4YY2TOE.js} +1 -1
  24. package/bundle/{chunk-2NY5PCKQ.js → chunk-LV3CPYXJ.js} +4 -4
  25. package/bundle/{chunk-2D2DQGC2.js → chunk-PYKBTBY6.js} +27 -10
  26. package/bundle/{chunk-M2VBGET6.js → chunk-RMZAAXIR.js} +7 -2
  27. package/bundle/{chunk-HTI7DD5D.js → chunk-V7SZMS6W.js} +2 -2
  28. package/bundle/{chunk-VFUFOZBU.js → chunk-W6HIYD2Z.js} +1 -1
  29. package/bundle/{chunk-USRX7QXD.js → chunk-XIA5GSEU.js} +2 -2
  30. package/bundle/{chunk-CTPAE36Y.js → chunk-YARY7JWU.js} +22 -0
  31. package/bundle/chunk-YDZ7BZD5.js +523 -0
  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 +9 -9
  36. package/bundle/project-panes.js +3 -3
  37. package/bundle/required-child-extensions.js +1 -1
  38. package/docs/agents.md +4 -2
  39. package/docs/configuration.md +4 -2
  40. package/docs/observability.md +2 -0
  41. package/docs/tool-reference.md +4 -1
  42. package/docs/workflows.md +3 -1
  43. package/package.json +3 -3
  44. package/skills/pi-subagents/SKILL.md +8 -2
  45. package/src/agents/agent-management.d.ts +1 -0
  46. package/src/agents/agent-management.js +12 -4
  47. package/src/agents/agents.d.ts +1 -0
  48. package/src/agents/agents.js +2 -2
  49. package/src/extension/config.d.ts +9 -0
  50. package/src/extension/config.js +13 -0
  51. package/src/extension/index.d.ts +1 -1
  52. package/src/extension/index.js +47 -23
  53. package/src/extension/schemas.d.ts +2 -0
  54. package/src/extension/schemas.js +1 -0
  55. package/src/extension/subagent-launch-tool.d.ts +6 -2
  56. package/src/extension/subagent-launch-tool.js +13 -9
  57. package/src/extension/tool-activation.js +20 -3
  58. package/src/runs/background/async-resume.js +2 -1
  59. package/src/runs/background/async-retention.d.ts +0 -2
  60. package/src/runs/background/async-retention.js +11 -5
  61. package/src/runs/background/async-status.d.ts +2 -0
  62. package/src/runs/background/async-status.js +4 -0
  63. package/src/runs/background/run-child-session.d.ts +2 -2
  64. package/src/runs/background/run-child-session.js +4 -7
  65. package/src/runs/background/stale-run-reconciler.js +17 -8
  66. package/src/runs/background/steering.d.ts +2 -11
  67. package/src/runs/background/steering.js +11 -6
  68. package/src/runs/background/subagent-runner.d.ts +0 -2
  69. package/src/runs/background/subagent-runner.js +73 -58
  70. package/src/runs/foreground/async-steering-action.js +24 -9
  71. package/src/runs/foreground/execution.js +32 -15
  72. package/src/runs/foreground/prompt-audit.js +1 -0
  73. package/src/runs/foreground/subagent-executor.d.ts +1 -8
  74. package/src/runs/foreground/subagent-executor.js +17 -21
  75. package/src/runs/shared/async-status-projection.d.ts +2 -0
  76. package/src/runs/shared/async-status-projection.js +10 -0
  77. package/src/runs/shared/child-launch.js +6 -3
  78. package/src/runs/shared/child-session.d.ts +1 -1
  79. package/src/runs/shared/child-session.js +24 -30
  80. package/src/runs/shared/mcp-config-sources.d.ts +2 -0
  81. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +5 -5
  82. package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -15
  83. package/src/runs/shared/subagent-prompt-runtime.js +14 -2
  84. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  85. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  86. package/src/shared/artifacts.d.ts +1 -0
  87. package/src/shared/artifacts.js +107 -9
  88. package/src/shared/compaction-interruption.d.ts +9 -0
  89. package/src/shared/compaction-interruption.js +47 -0
  90. package/src/shared/parent-wake.d.ts +3 -2
  91. package/src/shared/parent-wake.js +14 -3
  92. package/src/shared/reported-progress.d.ts +1 -0
  93. package/src/shared/reported-progress.js +12 -0
  94. package/src/shared/required-child-extensions.d.ts +2 -0
  95. package/src/shared/required-child-extensions.js +27 -0
  96. package/src/shared/status-format.d.ts +1 -0
  97. package/src/shared/status-format.js +1 -1
  98. package/src/shared/types.d.ts +9 -0
  99. package/src/shared/utils.d.ts +3 -1
  100. package/src/shared/utils.js +4 -0
  101. package/src/tui/fleet.d.ts +7 -2
  102. package/src/tui/fleet.js +22 -0
  103. package/src/tui/render.js +33 -2
  104. package/src/watchdog/permission-arbiter.js +1 -0
  105. package/src/watchdog/review.d.ts +0 -5
  106. package/src/watchdog/review.js +2 -1
  107. package/src/workflows/workflow-script-worker.js +3 -1
  108. package/bundle/chunk-XSDYTXHF.js +0 -242
@@ -1,5 +1,5 @@
1
1
  import { type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import { type Component, type MarkdownTheme, type TuiMouseEvent, type TuiMouseEventResult } from "@earendil-works/pi-tui";
2
+ import { type Component, type Focusable, type MarkdownTheme, type TuiMouseEvent, type TuiMouseEventResult } from "@earendil-works/pi-tui";
3
3
  import { type ExternalRun } from "../api/external-runs.ts";
4
4
  import { type FleetKeybindingAction, type FleetKeybindingsConfig, type ForegroundChildControl, type ForegroundResumeChild, type ForegroundResumeRun, type ForegroundRunControl, type SubagentState } from "../shared/types.ts";
5
5
  import { type AsyncRunSummary } from "../runs/background/async-status.ts";
@@ -14,6 +14,7 @@ type FleetTui = {
14
14
  rows: number;
15
15
  };
16
16
  requestRender(): void;
17
+ getFocusedComponent?(): Component | null;
17
18
  };
18
19
  type AsyncStep = AsyncRunSummary["steps"][number];
19
20
  export type FleetItem = ({
@@ -108,7 +109,7 @@ export declare function collectFleetSnapshot(state: SubagentState, options?: {
108
109
  resultsDir?: string;
109
110
  limit?: number;
110
111
  }): FleetSnapshot;
111
- export declare class SubagentFleetComponent implements Component {
112
+ export declare class SubagentFleetComponent implements Component, Focusable {
112
113
  private snapshot;
113
114
  private selected;
114
115
  private selectedKey;
@@ -125,6 +126,8 @@ export declare class SubagentFleetComponent implements Component {
125
126
  private actionBusy;
126
127
  private transcriptCache;
127
128
  private disposed;
129
+ private hasFocus;
130
+ private readonly openedOver;
128
131
  private refreshTimer;
129
132
  private readonly refreshMs;
130
133
  private readonly tui;
@@ -154,6 +157,8 @@ export declare class SubagentFleetComponent implements Component {
154
157
  private setActionNotice;
155
158
  private runAction;
156
159
  private scrollDetail;
160
+ get focused(): boolean;
161
+ set focused(value: boolean);
157
162
  handleMouse(event: TuiMouseEvent): TuiMouseEventResult | undefined;
158
163
  handleInput(data: string): void;
159
164
  private rosterLines;
package/src/tui/fleet.js CHANGED
@@ -770,6 +770,10 @@ export class SubagentFleetComponent {
770
770
  actionBusy = false;
771
771
  transcriptCache;
772
772
  disposed = false;
773
+ // Undefined until a TUI first focuses the overlay, so a fleet rendered outside one still draws.
774
+ hasFocus;
775
+ // The component focused when the fleet opened (the overlay's preFocus).
776
+ openedOver;
773
777
  refreshTimer;
774
778
  refreshMs;
775
779
  tui;
@@ -781,6 +785,7 @@ export class SubagentFleetComponent {
781
785
  keybindings;
782
786
  constructor(tui, theme, state, done, options = {}) {
783
787
  this.tui = tui;
788
+ this.openedOver = tui.getFocusedComponent?.();
784
789
  this.viewport = new FleetViewport(() => this.tui.requestRender());
785
790
  this.theme = theme;
786
791
  this.markdownTheme = options.markdownTheme ?? getMarkdownTheme();
@@ -984,6 +989,15 @@ export class SubagentFleetComponent {
984
989
  scrollDetail(delta) {
985
990
  this.viewport.scroll.scrollBy(delta);
986
991
  }
992
+ get focused() {
993
+ return this.hasFocus === true;
994
+ }
995
+ set focused(value) {
996
+ if (value === this.hasFocus)
997
+ return;
998
+ this.hasFocus = value;
999
+ this.tui.requestRender();
1000
+ }
987
1001
  handleMouse(event) {
988
1002
  // Block pointer fallback as well as inspector actions while a text/confirmation modal owns input.
989
1003
  if (this.steerDraft !== undefined || this.redoGuidanceDraft !== undefined || this.stopConfirming || this.actionBusy) {
@@ -1339,6 +1353,14 @@ export class SubagentFleetComponent {
1339
1353
  return { header: [], body: this.withActionLines(lines) };
1340
1354
  }
1341
1355
  render(width) {
1356
+ // An inline dialog that took focus (a permission prompt, select, confirm) sits under this overlay and
1357
+ // would be covered while it owns the keys. Hiding the overlay through its handle would cancel the
1358
+ // TUI's focus restore, so draw nothing until the TUI gives focus back. Focus moving to the component the
1359
+ // fleet opened over (a fullscreen click on the editor) shows no dialog, and the next key returns to the fleet.
1360
+ if (this.hasFocus === false && this.tui.getFocusedComponent?.() !== this.openedOver) {
1361
+ this.renderedLayout = undefined;
1362
+ return [];
1363
+ }
1342
1364
  const layout = fleetLayout(width, this.tui.terminal?.rows ?? 32, this.selected, this.snapshot.items);
1343
1365
  this.renderedLayout = layout;
1344
1366
  if (!layout)
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
- };