pi-subagents 0.17.4 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,34 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [0.18.0] - 2026-04-23
6
+
7
+ ### Added
8
+ - Added subagent control notifications so `needs_attention` signals push structured parent events, persist async control events to `events.jsonl`, show visible transcript notices for the user and parent agent, include proactive `nudge`/`status`/`interrupt` commands when a child appears blocked, and show each visible notice at most once per child run and attention state.
9
+ - Added stable child intercom session names for controlled subagents so needs-attention pings can tell the orchestrator which agent needs attention and how to message it when intercom is available.
10
+
11
+ ### Changed
12
+ - Replaced the unreleased `starting`/`active`/`quiet`/`stalled`/`paused` activity labels with factual activity reporting and a single `needs_attention` control signal, keeping `paused` as lifecycle state only.
13
+ - Added `subagent({ action: "status", id })` and `subagent({ action: "status" })` as the control-surface status checks, replacing the separate `subagent_status(...)` tool.
14
+ - Adjusted bundled agent defaults: most builtins now use `openai-codex/gpt-5.5`, while `scout` uses `openai-codex/gpt-5.4-mini`.
15
+ - Removed the incomplete e2e suite and stale `@marcfargas/pi-test-harness` dev dependency; `test:all` now runs the maintained unit and integration suites.
16
+
17
+ ### Fixed
18
+ - Paused async runs now render `Background task paused` notifications instead of failed/completed copy, including after extension reloads with stale legacy listeners still present.
19
+ - Async status output no longer shows stale activity-age lines for paused or completed runs.
20
+
21
+ ## [0.17.5] - 2026-04-23
22
+
23
+ ### Added
24
+ - Added subagent control activity state for foreground and async runs, including `starting`/`active`/`quiet`/`stalled`/`paused` tracking, compact stalled/recovered/paused control events, and an in-tool `action: "interrupt"` soft interrupt that pauses the current child turn without adding another top-level tool.
25
+
26
+ ### Changed
27
+ - Updated bundled agents to use `openai-codex/gpt-5.5` defaults, with `scout` on `openai-codex/gpt-5.5-mini` and `oracle-executor` on `openai-codex/gpt-5.5:xhigh`.
28
+
29
+ ### Fixed
30
+ - Async/background status token reporting now falls back to in-memory model-attempt usage when detached runs do not produce session `.jsonl` files, which also preserves token totals across model fallback retries.
31
+ - Non-Windows subagent launches now use plain `pi` again instead of reusing the current CLI script path, avoiding runs that get confused by installed `dist/cli.js` entrypoints.
32
+
5
33
  ## [0.17.4] - 2026-04-22
6
34
 
7
35
  ### Added
package/README.md CHANGED
@@ -48,8 +48,8 @@ Use `agentScope` parameter to control discovery: `"user"`, `"project"`, or `"bot
48
48
 
49
49
  **Builtin agents:** The extension ships with ready-to-use agents — `scout`, `planner`, `worker`, `reviewer`, `context-builder`, `researcher`, `delegate`, `oracle`, and `oracle-executor`. They load at lowest priority so any user or project agent with the same name overrides them.
50
50
 
51
- - `oracle` is a high-context advisory reviewer on `openai-codex/gpt-5.4:high`. It critiques direction, surfaces hidden risks, and proposes a concrete execution prompt, but it does not edit files directly.
52
- - `oracle-executor` is a high-context implementation escalator on `openai-codex/gpt-5.3-codex:high`. It is intended to run only after the main agent explicitly approves a course of action.
51
+ - `oracle` is a high-context advisory reviewer on `openai-codex/gpt-5.5`. It critiques direction, surfaces hidden risks, and proposes a concrete execution prompt, but it does not edit files directly.
52
+ - `oracle-executor` is a high-context implementation escalator on `openai-codex/gpt-5.5`. It is intended to run only after the main agent explicitly approves a course of action.
53
53
 
54
54
  You can also override selected builtin fields without copying the whole agent. Builtin overrides are stored in settings under `subagents.agentOverrides`:
55
55
 
@@ -285,7 +285,7 @@ Add `--bg` at the end of any slash command to run in the background:
285
285
  /parallel scout "scan frontend" -> scout "scan backend" -> scout "scan infra" --bg
286
286
  ```
287
287
 
288
- Without `--bg`, the run is foreground: the tool call stays active and streams progress until completion. With `--bg`, the run is launched asynchronously: control returns immediately, and completion arrives later via notification. In both cases subagents run as separate processes. Check status with the `subagent_status` tool, or open the `/subagents-status` slash command for a read-only overlay listing active runs and recent completions.
288
+ Without `--bg`, the run is foreground: the tool call stays active and streams progress until completion. With `--bg`, the run is launched asynchronously: control returns immediately, and completion arrives later via notification. In both cases subagents run as separate processes. Check status with `subagent({ action: "status", id })`, or open the `/subagents-status` slash command for a read-only overlay listing active runs and recent completions.
289
289
 
290
290
  ### Forked Context Execution
291
291
 
@@ -649,16 +649,16 @@ These are the parameters the **LLM agent** passes when it calls the `subagent` t
649
649
  ], clarify: false, async: true }
650
650
  ```
651
651
 
652
- **subagent_status tool:**
652
+ **Programmatic status:**
653
653
  ```typescript
654
- { action: "list" } // active async runs only
655
- { id: "a53ebe46" } // inspect one run
656
- { dir: "<tmpdir>/pi-subagents-<scope>/async-subagent-runs/a53ebe46-..." }
654
+ subagent({ action: "status" }) // active async runs only
655
+ subagent({ action: "status", id: "a53ebe46" }) // inspect one run
656
+ subagent({ action: "status", dir: "<tmpdir>/pi-subagents-<scope>/async-subagent-runs/a53ebe46-..." })
657
657
  ```
658
658
 
659
659
  **/subagents-status slash command:**
660
660
 
661
- Opens a small read-only overlay that shows active async runs plus recent completed/failed runs. It auto-refreshes every 2 seconds while open, keeps the current run selected when possible, and uses `↑↓` to select a run plus `Esc` to close.
661
+ Opens a small read-only overlay that shows active async runs plus recent completed, failed, and paused runs. It auto-refreshes every 2 seconds while open, keeps the current run selected when possible, and uses `↑↓` to select a run plus `Esc` to close.
662
662
 
663
663
  ## Management Actions
664
664
 
@@ -798,11 +798,12 @@ Fallbacks are inherited from the selected agent for that step. There is no per-s
798
798
 
799
799
  Fallbacks are inherited from the selected agent for that task. There is no per-task `fallbackModels` override in v1.
800
800
 
801
- Status tool:
801
+ Status commands:
802
802
 
803
- | Tool | Description |
803
+ | Command | Description |
804
804
  |------|-------------|
805
- | `subagent_status` | List active async runs or inspect one run by id or dir |
805
+ | `subagent({ action: "status" })` | List active async runs |
806
+ | `subagent({ action: "status", id })` | Inspect a foreground or async run by id or prefix |
806
807
 
807
808
  ## Worktree Isolation
808
809
 
@@ -1167,20 +1168,20 @@ When fallback is used in async/background mode, `status.json` and the final resu
1167
1168
  For programmatic access:
1168
1169
 
1169
1170
  ```typescript
1170
- subagent_status({ action: "list" })
1171
- subagent_status({ id: "<id>" })
1172
- subagent_status({ dir: "<tmpdir>/pi-subagents-<scope>/async-subagent-runs/<id>" })
1171
+ subagent({ action: "status" })
1172
+ subagent({ action: "status", id: "<id>" })
1173
+ subagent({ action: "status", dir: "<tmpdir>/pi-subagents-<scope>/async-subagent-runs/<id>" })
1173
1174
  ```
1174
1175
 
1175
- For an interactive overview, run the `/subagents-status` slash command to open the overlay listing active runs and recent completed/failed runs. The overlay auto-refreshes every 2 seconds while it is open and focuses on summary/status information, including the current output/session paths when available.
1176
+ For an interactive overview, run the `/subagents-status` slash command to open the overlay listing active runs and recent completed, failed, and paused runs. The overlay auto-refreshes every 2 seconds while it is open and focuses on summary/status information, including the current output/session paths when available.
1176
1177
 
1177
1178
  ## Events
1178
1179
 
1179
1180
  Async events:
1180
- - `subagent:started`
1181
- - `subagent:complete`
1181
+ - `subagent:async-started`
1182
+ - `subagent:async-complete`
1182
1183
 
1183
- `notify.ts` consumes `subagent:complete` as the canonical completion channel.
1184
+ The result watcher emits `subagent:async-complete`; `index.ts` registers the notification handler that consumes it.
1184
1185
 
1185
1186
  ## Files
1186
1187
 
@@ -1227,7 +1228,6 @@ Async events:
1227
1228
  ├── run-history.ts # Per-agent run recording (JSONL)
1228
1229
  ├── test/unit/ # Fast unit tests for pure modules
1229
1230
  ├── test/integration/ # Loader-based execution/integration tests
1230
- ├── test/e2e/ # End-to-end sandbox tests
1231
1231
  ├── test/support/ # Shared test loader, helpers, and mock pi harness
1232
1232
  └── text-editor.ts # Shared text editor (word nav, paste)
1233
1233
  ```
@@ -2,7 +2,7 @@
2
2
  name: context-builder
3
3
  description: Analyzes requirements and codebase, generates context and meta-prompt
4
4
  tools: read, grep, find, ls, bash, write, web_search
5
- model: openai-codex/gpt-5.4
5
+ model: openai-codex/gpt-5.5
6
6
  systemPromptMode: replace
7
7
  inheritProjectContext: true
8
8
  inheritSkills: false
@@ -2,7 +2,7 @@
2
2
  name: oracle-executor
3
3
  description: High-context implementation agent that executes only after main-agent approval
4
4
  tools: read, grep, find, ls, bash, edit, write, intercom
5
- model: openai-codex/gpt-5.3-codex
5
+ model: openai-codex/gpt-5.5
6
6
  thinking: high
7
7
  systemPromptMode: replace
8
8
  inheritProjectContext: true
package/agents/oracle.md CHANGED
@@ -2,7 +2,7 @@
2
2
  name: oracle
3
3
  description: High-context decision-consistency oracle that protects inherited state and prevents drift
4
4
  tools: read, grep, find, ls, bash, intercom
5
- model: openai-codex/gpt-5.4
5
+ model: openai-codex/gpt-5.5
6
6
  thinking: high
7
7
  systemPromptMode: replace
8
8
  inheritProjectContext: true
package/agents/planner.md CHANGED
@@ -2,7 +2,7 @@
2
2
  name: planner
3
3
  description: Creates implementation plans from context and requirements
4
4
  tools: read, grep, find, ls, write
5
- model: openai-codex/gpt-5.4
5
+ model: openai-codex/gpt-5.5
6
6
  thinking: high
7
7
  systemPromptMode: replace
8
8
  inheritProjectContext: true
@@ -2,7 +2,7 @@
2
2
  name: researcher
3
3
  description: Autonomous web researcher — searches, evaluates, and synthesizes a focused research brief
4
4
  tools: read, write, web_search, fetch_content, get_search_content
5
- model: openai-codex/gpt-5.4
5
+ model: openai-codex/gpt-5.5
6
6
  systemPromptMode: replace
7
7
  inheritProjectContext: true
8
8
  inheritSkills: false
@@ -2,7 +2,7 @@
2
2
  name: reviewer
3
3
  description: Code review specialist that validates implementation and fixes issues
4
4
  tools: read, grep, find, ls, bash, edit, write
5
- model: openai-codex/gpt-5.3-codex
5
+ model: openai-codex/gpt-5.5
6
6
  thinking: high
7
7
  systemPromptMode: replace
8
8
  inheritProjectContext: true
package/agents/worker.md CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  name: worker
3
3
  description: General-purpose subagent with full capabilities
4
- model: openai-codex/gpt-5.4
4
+ model: openai-codex/gpt-5.5
5
5
  systemPromptMode: replace
6
6
  inheritProjectContext: true
7
7
  inheritSkills: false
@@ -22,8 +22,10 @@ import {
22
22
  type ArtifactConfig,
23
23
  type Details,
24
24
  type MaxOutputConfig,
25
+ type ResolvedControlConfig,
25
26
  ASYNC_DIR,
26
27
  RESULTS_DIR,
28
+ SUBAGENT_ASYNC_STARTED_EVENT,
27
29
  TEMP_ROOT_DIR,
28
30
  getAsyncConfigPath,
29
31
  resolveChildMaxSubagentDepth,
@@ -75,6 +77,9 @@ export interface AsyncChainParams {
75
77
  maxSubagentDepth: number;
76
78
  worktreeSetupHook?: string;
77
79
  worktreeSetupHookTimeoutMs?: number;
80
+ controlConfig?: ResolvedControlConfig;
81
+ controlIntercomTarget?: string;
82
+ childIntercomTarget?: (agent: string, index: number) => string | undefined;
78
83
  }
79
84
 
80
85
  export interface AsyncSingleParams {
@@ -96,6 +101,9 @@ export interface AsyncSingleParams {
96
101
  maxSubagentDepth: number;
97
102
  worktreeSetupHook?: string;
98
103
  worktreeSetupHookTimeoutMs?: number;
104
+ controlConfig?: ResolvedControlConfig;
105
+ controlIntercomTarget?: string;
106
+ childIntercomTarget?: (agent: string, index: number) => string | undefined;
99
107
  }
100
108
 
101
109
  export interface AsyncExecutionResult {
@@ -178,6 +186,9 @@ export function executeAsyncChain(
178
186
  maxSubagentDepth,
179
187
  worktreeSetupHook,
180
188
  worktreeSetupHookTimeoutMs,
189
+ controlConfig,
190
+ controlIntercomTarget,
191
+ childIntercomTarget,
181
192
  } = params;
182
193
  const chainSkills = params.chainSkills ?? [];
183
194
  const availableModels = params.availableModels;
@@ -276,6 +287,13 @@ export function executeAsyncChain(
276
287
  }
277
288
  return buildSeqStep(s as SequentialStep, nextSessionFile());
278
289
  });
290
+ let childTargetIndex = 0;
291
+ const childIntercomTargets = childIntercomTarget ? steps.flatMap((step) => {
292
+ if ("parallel" in step) {
293
+ return step.parallel.map((task) => childIntercomTarget(task.agent, childTargetIndex++));
294
+ }
295
+ return [childIntercomTarget(step.agent, childTargetIndex++)];
296
+ }) : undefined;
279
297
 
280
298
  let spawnResult: { pid?: number; error?: string } = {};
281
299
  try {
@@ -297,6 +315,9 @@ export function executeAsyncChain(
297
315
  piArgv1: process.argv[1],
298
316
  worktreeSetupHook,
299
317
  worktreeSetupHookTimeoutMs,
318
+ controlConfig,
319
+ controlIntercomTarget,
320
+ childIntercomTargets,
300
321
  },
301
322
  id,
302
323
  runnerCwd,
@@ -315,7 +336,7 @@ export function executeAsyncChain(
315
336
  const firstAgents = isParallelStep(firstStep)
316
337
  ? firstStep.parallel.map((t) => t.agent)
317
338
  : [(firstStep as SequentialStep).agent];
318
- ctx.pi.events.emit("subagent:started", {
339
+ ctx.pi.events.emit(SUBAGENT_ASYNC_STARTED_EVENT, {
319
340
  id,
320
341
  pid: spawnResult.pid,
321
342
  agent: firstAgents[0],
@@ -364,6 +385,9 @@ export function executeAsyncSingle(
364
385
  maxSubagentDepth,
365
386
  worktreeSetupHook,
366
387
  worktreeSetupHookTimeoutMs,
388
+ controlConfig,
389
+ controlIntercomTarget,
390
+ childIntercomTarget,
367
391
  } = params;
368
392
  const runnerCwd = resolveChildCwd(ctx.cwd, cwd);
369
393
  const skillNames = params.skills ?? agentConfig.skills ?? [];
@@ -430,6 +454,9 @@ export function executeAsyncSingle(
430
454
  piArgv1: process.argv[1],
431
455
  worktreeSetupHook,
432
456
  worktreeSetupHookTimeoutMs,
457
+ controlConfig,
458
+ controlIntercomTarget,
459
+ childIntercomTargets: childIntercomTarget ? [childIntercomTarget(agent, 0)] : undefined,
433
460
  },
434
461
  id,
435
462
  runnerCwd,
@@ -444,7 +471,7 @@ export function executeAsyncSingle(
444
471
  }
445
472
 
446
473
  if (spawnResult.pid) {
447
- ctx.pi.events.emit("subagent:started", {
474
+ ctx.pi.events.emit(SUBAGENT_ASYNC_STARTED_EVENT, {
448
475
  id,
449
476
  pid: spawnResult.pid,
450
477
  agent,
@@ -1,9 +1,15 @@
1
- import type { ExtensionContext } from "@mariozechner/pi-coding-agent";
1
+ import type { ExtensionAPI, ExtensionContext } from "@mariozechner/pi-coding-agent";
2
+ import * as fs from "node:fs";
2
3
  import * as path from "node:path";
3
4
  import { renderWidget } from "./render.ts";
5
+ import { formatControlNoticeMessage } from "./subagent-control.ts";
4
6
  import {
7
+ type AsyncJobState,
8
+ type ControlEvent,
5
9
  type SubagentState,
6
10
  POLL_INTERVAL_MS,
11
+ SUBAGENT_CONTROL_EVENT,
12
+ SUBAGENT_CONTROL_INTERCOM_EVENT,
7
13
  } from "./types.ts";
8
14
  import { readStatus } from "./utils.ts";
9
15
 
@@ -12,7 +18,7 @@ interface AsyncJobTrackerOptions {
12
18
  pollIntervalMs?: number;
13
19
  }
14
20
 
15
- export function createAsyncJobTracker(state: SubagentState, asyncDirRoot: string, options: AsyncJobTrackerOptions = {}): {
21
+ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: SubagentState, asyncDirRoot: string, options: AsyncJobTrackerOptions = {}): {
16
22
  ensurePoller: () => void;
17
23
  handleStarted: (data: unknown) => void;
18
24
  handleComplete: (data: unknown) => void;
@@ -36,13 +42,67 @@ export function createAsyncJobTracker(state: SubagentState, asyncDirRoot: string
36
42
  }, completionRetentionMs);
37
43
  state.cleanupTimers.set(asyncId, timer);
38
44
  };
45
+ const emitNewControlEvents = (job: AsyncJobState) => {
46
+ const eventsPath = path.join(job.asyncDir, "events.jsonl");
47
+ let fd: number;
48
+ try {
49
+ fd = fs.openSync(eventsPath, "r");
50
+ } catch (error) {
51
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return;
52
+ console.error(`Failed to open async control events for '${job.asyncDir}':`, error);
53
+ return;
54
+ }
55
+ try {
56
+ const stat = fs.fstatSync(fd);
57
+ const cursor = stat.size < (job.controlEventCursor ?? 0) ? 0 : (job.controlEventCursor ?? 0);
58
+ if (stat.size <= cursor) return;
59
+ const buffer = Buffer.alloc(stat.size - cursor);
60
+ fs.readSync(fd, buffer, 0, buffer.length, cursor);
61
+ const lastNewline = buffer.lastIndexOf(0x0a);
62
+ if (lastNewline === -1) return;
63
+ job.controlEventCursor = cursor + lastNewline + 1;
64
+ for (const line of buffer.subarray(0, lastNewline).toString("utf-8").split("\n")) {
65
+ if (!line.trim()) continue;
66
+ let parsed: unknown;
67
+ try {
68
+ parsed = JSON.parse(line);
69
+ } catch {
70
+ // Ignore malformed completed records but keep the poller alive for later events.
71
+ continue;
72
+ }
73
+ if (!parsed || typeof parsed !== "object" || (parsed as { type?: unknown }).type !== "subagent.control") continue;
74
+ const record = parsed as { event?: ControlEvent; channels?: string[]; childIntercomTarget?: string; noticeText?: string; intercom?: { to?: string; message?: string } };
75
+ if (!record.event || !Array.isArray(record.channels)) continue;
76
+ const payload = {
77
+ event: record.event,
78
+ source: "async" as const,
79
+ asyncDir: job.asyncDir,
80
+ childIntercomTarget: record.childIntercomTarget,
81
+ noticeText: record.noticeText ?? formatControlNoticeMessage(record.event, record.childIntercomTarget),
82
+ };
83
+ if (record.channels.includes("event")) {
84
+ pi.events.emit(SUBAGENT_CONTROL_EVENT, payload);
85
+ }
86
+ if (record.channels.includes("intercom") && record.intercom?.to && record.intercom.message) {
87
+ pi.events.emit(SUBAGENT_CONTROL_INTERCOM_EVENT, {
88
+ ...payload,
89
+ to: record.intercom.to,
90
+ message: record.intercom.message,
91
+ });
92
+ }
93
+ }
94
+ } catch (error) {
95
+ console.error(`Failed to read async control events for '${job.asyncDir}':`, error);
96
+ } finally {
97
+ fs.closeSync(fd);
98
+ }
99
+ };
39
100
 
40
101
  const ensurePoller = () => {
41
102
  if (state.poller) return;
42
103
  state.poller = setInterval(() => {
43
- if (!state.lastUiContext || !state.lastUiContext.hasUI) return;
44
104
  if (state.asyncJobs.size === 0) {
45
- rerenderWidget(state.lastUiContext, []);
105
+ if (state.lastUiContext?.hasUI) rerenderWidget(state.lastUiContext, []);
46
106
  if (state.poller) {
47
107
  clearInterval(state.poller);
48
108
  state.poller = null;
@@ -52,10 +112,15 @@ export function createAsyncJobTracker(state: SubagentState, asyncDirRoot: string
52
112
 
53
113
  for (const job of state.asyncJobs.values()) {
54
114
  try {
115
+ emitNewControlEvents(job);
55
116
  const status = readStatus(job.asyncDir);
56
117
  if (status) {
57
118
  const previousStatus = job.status;
58
119
  job.status = status.state;
120
+ job.activityState = status.activityState;
121
+ job.lastActivityAt = status.lastActivityAt ?? job.lastActivityAt;
122
+ job.currentTool = status.currentTool ?? job.currentTool;
123
+ job.currentToolStartedAt = status.currentToolStartedAt ?? job.currentToolStartedAt;
59
124
  job.mode = status.mode;
60
125
  job.currentStep = status.currentStep ?? job.currentStep;
61
126
  job.stepsTotal = status.steps?.length ?? job.stepsTotal;
@@ -68,7 +133,7 @@ export function createAsyncJobTracker(state: SubagentState, asyncDirRoot: string
68
133
  job.outputFile = status.outputFile ?? job.outputFile;
69
134
  job.totalTokens = status.totalTokens ?? job.totalTokens;
70
135
  job.sessionFile = status.sessionFile ?? job.sessionFile;
71
- if ((job.status === "complete" || job.status === "failed") && previousStatus !== job.status) {
136
+ if ((job.status === "complete" || job.status === "failed" || job.status === "paused") && previousStatus !== job.status) {
72
137
  scheduleCleanup(job.asyncId);
73
138
  }
74
139
  continue;
@@ -82,7 +147,7 @@ export function createAsyncJobTracker(state: SubagentState, asyncDirRoot: string
82
147
  }
83
148
  }
84
149
 
85
- rerenderWidget(state.lastUiContext);
150
+ if (state.lastUiContext?.hasUI) rerenderWidget(state.lastUiContext);
86
151
  }, pollIntervalMs);
87
152
  state.poller.unref?.();
88
153
  };
@@ -108,9 +173,9 @@ export function createAsyncJobTracker(state: SubagentState, asyncDirRoot: string
108
173
  startedAt: now,
109
174
  updatedAt: now,
110
175
  });
176
+ ensurePoller();
111
177
  if (state.lastUiContext) {
112
178
  rerenderWidget(state.lastUiContext);
113
- ensurePoller();
114
179
  }
115
180
  };
116
181
 
@@ -136,6 +201,8 @@ export function createAsyncJobTracker(state: SubagentState, asyncDirRoot: string
136
201
  }
137
202
  state.cleanupTimers.clear();
138
203
  state.asyncJobs.clear();
204
+ state.foregroundControls?.clear();
205
+ state.lastForegroundControlId = null;
139
206
  state.resultFileCoalescer.clear();
140
207
  if (ctx?.hasUI) {
141
208
  state.lastUiContext = ctx;
package/async-status.ts CHANGED
@@ -1,13 +1,18 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { formatDuration, formatTokens, shortenPath } from "./formatters.ts";
4
- import { type AsyncStatus, type TokenUsage } from "./types.ts";
4
+ import { type ActivityState, type AsyncStatus, type TokenUsage } from "./types.ts";
5
+ import { DEFAULT_CONTROL_CONFIG, deriveActivityState } from "./subagent-control.ts";
5
6
  import { readStatus } from "./utils.ts";
6
7
 
7
8
  export interface AsyncRunStepSummary {
8
9
  index: number;
9
10
  agent: string;
10
11
  status: string;
12
+ activityState?: ActivityState;
13
+ lastActivityAt?: number;
14
+ currentTool?: string;
15
+ currentToolStartedAt?: number;
11
16
  durationMs?: number;
12
17
  tokens?: TokenUsage;
13
18
  skills?: string[];
@@ -19,7 +24,11 @@ export interface AsyncRunStepSummary {
19
24
  export interface AsyncRunSummary {
20
25
  id: string;
21
26
  asyncDir: string;
22
- state: "queued" | "running" | "complete" | "failed";
27
+ state: "queued" | "running" | "complete" | "failed" | "paused";
28
+ activityState?: ActivityState;
29
+ lastActivityAt?: number;
30
+ currentTool?: string;
31
+ currentToolStartedAt?: number;
23
32
  mode: "single" | "chain";
24
33
  cwd?: string;
25
34
  startedAt: number;
@@ -66,28 +75,65 @@ function isAsyncRunDir(root: string, entry: string): boolean {
66
75
  }
67
76
  }
68
77
 
78
+ function outputFileMtime(outputFile: string | undefined): number | undefined {
79
+ if (!outputFile) return undefined;
80
+ try {
81
+ return fs.statSync(outputFile).mtimeMs;
82
+ } catch {
83
+ return undefined;
84
+ }
85
+ }
86
+
87
+ function deriveAsyncActivityState(asyncDir: string, status: AsyncStatus): { activityState?: ActivityState; lastActivityAt?: number } {
88
+ if (status.state !== "running") return { activityState: status.activityState, lastActivityAt: status.lastActivityAt };
89
+ const outputPath = status.outputFile ? (path.isAbsolute(status.outputFile) ? status.outputFile : path.join(asyncDir, status.outputFile)) : undefined;
90
+ const currentStep = typeof status.currentStep === "number" ? status.steps?.[status.currentStep] : undefined;
91
+ const lastActivityAt = status.lastActivityAt ?? outputFileMtime(outputPath) ?? currentStep?.lastActivityAt ?? currentStep?.startedAt ?? status.startedAt;
92
+ return {
93
+ lastActivityAt,
94
+ activityState: status.activityState ?? deriveActivityState({
95
+ config: DEFAULT_CONTROL_CONFIG,
96
+ startedAt: status.startedAt,
97
+ lastActivityAt,
98
+ }),
99
+ };
100
+ }
101
+
69
102
  function statusToSummary(asyncDir: string, status: AsyncStatus & { cwd?: string }): AsyncRunSummary {
103
+ const { activityState, lastActivityAt } = deriveAsyncActivityState(asyncDir, status);
70
104
  return {
71
105
  id: status.runId || path.basename(asyncDir),
72
106
  asyncDir,
73
107
  state: status.state,
108
+ activityState,
109
+ lastActivityAt,
110
+ currentTool: status.currentTool,
111
+ currentToolStartedAt: status.currentToolStartedAt,
74
112
  mode: status.mode,
75
113
  cwd: status.cwd,
76
114
  startedAt: status.startedAt,
77
115
  lastUpdate: status.lastUpdate,
78
116
  endedAt: status.endedAt,
79
117
  currentStep: status.currentStep,
80
- steps: (status.steps ?? []).map((step, index) => ({
81
- index,
82
- agent: step.agent,
83
- status: step.status,
84
- ...(step.durationMs !== undefined ? { durationMs: step.durationMs } : {}),
85
- ...(step.tokens ? { tokens: step.tokens } : {}),
86
- ...(step.skills ? { skills: step.skills } : {}),
87
- ...(step.model ? { model: step.model } : {}),
88
- ...(step.attemptedModels ? { attemptedModels: step.attemptedModels } : {}),
89
- ...(step.error ? { error: step.error } : {}),
90
- })),
118
+ steps: (status.steps ?? []).map((step, index) => {
119
+ const stepActivityState = step.activityState ?? (step.status === "running" ? activityState : undefined);
120
+ const stepLastActivityAt = step.lastActivityAt ?? (step.status === "running" ? lastActivityAt : undefined);
121
+ return {
122
+ index,
123
+ agent: step.agent,
124
+ status: step.status,
125
+ ...(stepActivityState ? { activityState: stepActivityState } : {}),
126
+ ...(stepLastActivityAt ? { lastActivityAt: stepLastActivityAt } : {}),
127
+ ...(step.currentTool ? { currentTool: step.currentTool } : {}),
128
+ ...(step.currentToolStartedAt ? { currentToolStartedAt: step.currentToolStartedAt } : {}),
129
+ ...(step.durationMs !== undefined ? { durationMs: step.durationMs } : {}),
130
+ ...(step.tokens ? { tokens: step.tokens } : {}),
131
+ ...(step.skills ? { skills: step.skills } : {}),
132
+ ...(step.model ? { model: step.model } : {}),
133
+ ...(step.attemptedModels ? { attemptedModels: step.attemptedModels } : {}),
134
+ ...(step.error ? { error: step.error } : {}),
135
+ };
136
+ }),
91
137
  ...(status.sessionDir ? { sessionDir: status.sessionDir } : {}),
92
138
  ...(status.outputFile ? { outputFile: status.outputFile } : {}),
93
139
  ...(status.totalTokens ? { totalTokens: status.totalTokens } : {}),
@@ -100,8 +146,9 @@ function sortRuns(runs: AsyncRunSummary[]): AsyncRunSummary[] {
100
146
  switch (state) {
101
147
  case "running": return 0;
102
148
  case "queued": return 1;
103
- case "failed": return 2;
104
- case "complete": return 3;
149
+ case "failed": return 2;
150
+ case "paused": return 2;
151
+ case "complete": return 3;
105
152
  }
106
153
  };
107
154
  return [...runs].sort((a, b) => {
@@ -142,7 +189,7 @@ export function listAsyncRuns(asyncDirRoot: string, options: AsyncRunListOptions
142
189
  export function listAsyncRunsForOverlay(asyncDirRoot: string, recentLimit = 5): AsyncRunOverlayData {
143
190
  const all = listAsyncRuns(asyncDirRoot);
144
191
  const recent = all
145
- .filter((run) => run.state === "complete" || run.state === "failed")
192
+ .filter((run) => run.state === "complete" || run.state === "failed" || run.state === "paused")
146
193
  .sort((a, b) => (b.lastUpdate ?? b.endedAt ?? b.startedAt) - (a.lastUpdate ?? a.endedAt ?? a.startedAt))
147
194
  .slice(0, recentLimit);
148
195
  return {
@@ -151,8 +198,17 @@ export function listAsyncRunsForOverlay(asyncDirRoot: string, recentLimit = 5):
151
198
  };
152
199
  }
153
200
 
201
+ function formatActivityFacts(input: { activityState?: ActivityState; lastActivityAt?: number; currentTool?: string; currentToolStartedAt?: number }): string | undefined {
202
+ if (input.currentTool && input.currentToolStartedAt) return `tool ${input.currentTool} ${formatDuration(Math.max(0, Date.now() - input.currentToolStartedAt))}`;
203
+ if (!input.lastActivityAt) return input.activityState === "needs_attention" ? "needs attention" : undefined;
204
+ const elapsed = formatDuration(Math.max(0, Date.now() - input.lastActivityAt));
205
+ return input.activityState === "needs_attention" ? `no activity for ${elapsed}` : `active ${elapsed} ago`;
206
+ }
207
+
154
208
  function formatStepLine(step: AsyncRunStepSummary): string {
155
209
  const parts = [`${step.index + 1}. ${step.agent}`, step.status];
210
+ const activity = formatActivityFacts(step);
211
+ if (activity) parts.push(activity);
156
212
  if (step.model) parts.push(step.model);
157
213
  if (step.durationMs !== undefined) parts.push(formatDuration(step.durationMs));
158
214
  if (step.tokens) parts.push(`${formatTokens(step.tokens.total)} tok`);
@@ -163,7 +219,8 @@ function formatRunHeader(run: AsyncRunSummary): string {
163
219
  const stepCount = run.steps.length || 1;
164
220
  const stepLabel = run.currentStep !== undefined ? `step ${run.currentStep + 1}/${stepCount}` : `steps ${stepCount}`;
165
221
  const cwd = run.cwd ? shortenPath(run.cwd) : shortenPath(run.asyncDir);
166
- return `${run.id} | ${run.state} | ${run.mode} | ${stepLabel} | ${cwd}`;
222
+ const activity = formatActivityFacts(run);
223
+ return `${run.id} | ${run.state}${activity ? ` | ${activity}` : ""} | ${run.mode} | ${stepLabel} | ${cwd}`;
167
224
  }
168
225
 
169
226
  export function formatAsyncRunList(runs: AsyncRunSummary[], heading = "Active async runs"): string {