@gtheys/pi-interactive-subagents 0.0.0-stage → 0.2.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 (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +462 -2
  3. package/agents/claude-code.md +23 -0
  4. package/agents/planner.md +569 -0
  5. package/agents/reviewer.md +152 -0
  6. package/agents/scout.md +112 -0
  7. package/agents/visual-tester.md +202 -0
  8. package/agents/worker.md +109 -0
  9. package/config.json.example +6 -0
  10. package/config.schema.json +71 -0
  11. package/package.json +59 -4
  12. package/pi-extension/subagents/activity.ts +730 -0
  13. package/pi-extension/subagents/asks.ts +234 -0
  14. package/pi-extension/subagents/assignments.ts +395 -0
  15. package/pi-extension/subagents/config.ts +191 -0
  16. package/pi-extension/subagents/control.ts +172 -0
  17. package/pi-extension/subagents/dataroot.ts +52 -0
  18. package/pi-extension/subagents/delivered.ts +81 -0
  19. package/pi-extension/subagents/flow-env.ts +112 -0
  20. package/pi-extension/subagents/herdr.ts +323 -0
  21. package/pi-extension/subagents/inbox.ts +213 -0
  22. package/pi-extension/subagents/index.ts +5003 -0
  23. package/pi-extension/subagents/lock.ts +318 -0
  24. package/pi-extension/subagents/peer-bindings.ts +175 -0
  25. package/pi-extension/subagents/peers.ts +401 -0
  26. package/pi-extension/subagents/plan-skill.md +219 -0
  27. package/pi-extension/subagents/plugin/.claude-plugin/plugin.json +5 -0
  28. package/pi-extension/subagents/plugin/hooks/hooks.json +15 -0
  29. package/pi-extension/subagents/plugin/hooks/on-stop.sh +68 -0
  30. package/pi-extension/subagents/retention.ts +918 -0
  31. package/pi-extension/subagents/retirement.ts +216 -0
  32. package/pi-extension/subagents/session.ts +194 -0
  33. package/pi-extension/subagents/snapshot.ts +151 -0
  34. package/pi-extension/subagents/spawn.ts +237 -0
  35. package/pi-extension/subagents/spawnseq.ts +116 -0
  36. package/pi-extension/subagents/state-events.ts +152 -0
  37. package/pi-extension/subagents/status.ts +886 -0
  38. package/pi-extension/subagents/store.ts +245 -0
  39. package/pi-extension/subagents/subagent-done.ts +1452 -0
  40. package/pi-extension/subagents/surface.ts +365 -0
  41. package/pi-extension/subagents/task-composition.ts +113 -0
  42. package/pi-extension/subagents/tool-effects.ts +203 -0
  43. package/pi-extension/subagents/usage.ts +330 -0
  44. package/pi-extension/subagents/watermark.ts +126 -0
  45. package/pi-extension/subagents/worktrees.ts +147 -0
  46. package/skills/subagent-orchestration/SKILL.md +57 -0
@@ -0,0 +1,886 @@
1
+ import { readFileSync } from 'node:fs'
2
+ import { dirname, join } from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+
5
+ export const SNAPSHOT_STALLED_AFTER_MS = 60_000
6
+
7
+ // AIDEV-NOTE (PMR-YFRB): parent-side dead-turn watchdog thresholds. The short
8
+ // bucket covers the scope where silence means the model turn died
9
+ // mid-generation (streaming); the long bucket covers legitimately quiet
10
+ // scopes (provider/tool/turn/unknown) and sustained snapshot loss. Provider
11
+ // is long-bucket (PMR-S1PT): the provider window includes pre-first-token
12
+ // silence (large-prompt processing, 429/529 retry backoff) that emits no
13
+ // events — a short deadline there false-kills healthy children.
14
+ // Configurable via the `watchdog` object in pi-subagents/config.json;
15
+ // `enabled: false` restores the legacy never-age behavior.
16
+ export const STREAM_STALL_AFTER_MS = 150_000
17
+ export const QUIET_STALL_AFTER_MS = 1_800_000
18
+
19
+ export interface StallThresholds {
20
+ enabled: boolean
21
+ streamStallAfterMs: number
22
+ quietStallAfterMs: number
23
+ }
24
+
25
+ export const DEFAULT_STALL_THRESHOLDS: StallThresholds = {
26
+ enabled: true,
27
+ streamStallAfterMs: STREAM_STALL_AFTER_MS,
28
+ quietStallAfterMs: QUIET_STALL_AFTER_MS,
29
+ }
30
+
31
+ export type TurnStallReason = 'dead-turn' | 'no-activity'
32
+
33
+ export interface TurnStallVerdict {
34
+ stalled: boolean
35
+ reason: TurnStallReason | null
36
+ activeScope: string | null
37
+ stalledForMs: number
38
+ }
39
+ export const DEFAULT_STATUS_LINE_LIMIT = 4
40
+ export const MAX_STATUS_NAME_LENGTH = 72
41
+ export const MAX_STATUS_LINE_LENGTH = 120
42
+
43
+ const PACKAGE_ROOT = join(dirname(fileURLToPath(import.meta.url)), '../..')
44
+ const DEFAULT_STATUS_CONFIG_PATH = join(PACKAGE_ROOT, 'config.json')
45
+ const STATUS_CONFIG_EXAMPLE_PATH = join(PACKAGE_ROOT, 'config.json.example')
46
+
47
+ export type SubagentStatusKind =
48
+ | 'starting'
49
+ | 'active'
50
+ | 'waiting'
51
+ | 'blocked'
52
+ | 'stalled'
53
+ | 'running'
54
+ export type SubagentStatusSource = 'pi' | 'claude'
55
+ export type SubagentStatusTransition = 'stalled' | 'recovered' | null
56
+ export type StatusSnapshotState =
57
+ | 'unseen'
58
+ | 'present'
59
+ | 'missing'
60
+ | 'invalid'
61
+ | 'wrong-id'
62
+ export type StatusActivityPhase =
63
+ | 'starting'
64
+ | 'active'
65
+ | 'waiting'
66
+ | 'blocked'
67
+ | 'retiring'
68
+ | 'done'
69
+
70
+ // AIDEV-NOTE: pending parent→child control request (PMR-DNPZ). Tracked on the
71
+ // status state so the 1s refresh loop can observe the `.ack` sidecar and
72
+ // transition the request to acked/timeout; survives observeStatus spreads.
73
+ export interface PendingControlRequest {
74
+ requestId: string
75
+ kind: 'interrupt' | 'answer'
76
+ sentAtMs: number
77
+ }
78
+
79
+ /** No ack within this window ⇒ expire and fall back to fire-and-forget. */
80
+ export const INTERRUPT_ACK_TIMEOUT_MS = 5_000
81
+
82
+ export interface StatusConfig {
83
+ enabled: boolean
84
+ lineLimit: number
85
+ /** AIDEV-NOTE (PMR-AD0H): optional — absent ⇒ hide-when-idle is on. */
86
+ hideWhenIdle?: boolean
87
+ }
88
+
89
+ export type StatusObservation =
90
+ | {
91
+ snapshot: 'present'
92
+ updatedAt: number
93
+ sequence: number
94
+ phase: StatusActivityPhase
95
+ active?: boolean
96
+ activeScope?: string
97
+ activeSince?: number
98
+ waitingSince?: number
99
+ blockedSince?: number
100
+ latestEvent?: string
101
+ activityLabel?: string
102
+ }
103
+ | {
104
+ snapshot: 'missing' | 'invalid' | 'wrong-id'
105
+ snapshotError?: string
106
+ }
107
+
108
+ export interface SubagentStatusState {
109
+ source: SubagentStatusSource
110
+ startTimeMs: number
111
+ firstObservationAtMs: number | null
112
+ lastActivityAtMs: number | null
113
+ lastActivitySequence: number | null
114
+ localOverrideAtMs: number | null
115
+ localOverrideSequence: number | null
116
+ activeNow: boolean
117
+ activeSinceMs: number | null
118
+ activeScope: string | null
119
+ waitingSinceMs: number | null
120
+ blockedSinceMs: number | null
121
+ phase: StatusActivityPhase | null
122
+ latestEvent: string | null
123
+ activityLabel: string | null
124
+ snapshotState: StatusSnapshotState
125
+ snapshotProblemSinceMs: number | null
126
+ snapshotError: string | null
127
+ currentKind: SubagentStatusKind
128
+ pendingRequest: PendingControlRequest | null
129
+ }
130
+
131
+ export interface StatusSnapshot {
132
+ kind: SubagentStatusKind
133
+ elapsedMs: number
134
+ elapsedText: string
135
+ activeSinceMs: number | null
136
+ activeDurationText: string | null
137
+ activeScope: string | null
138
+ waitingSinceMs: number | null
139
+ blockedSinceMs: number | null
140
+ waitingDurationText: string | null
141
+ blockedDurationText: string | null
142
+ latestEvent: string | null
143
+ activityLabel: string | null
144
+ snapshotState: StatusSnapshotState
145
+ snapshotError: string | null
146
+ snapshotProblemText: string | null
147
+ statusLabel: string | null
148
+ }
149
+
150
+ export interface CappedStatusLines {
151
+ visibleLines: string[]
152
+ overflow: number
153
+ }
154
+
155
+ function invalidStatusConfig(source: string, message: string): never {
156
+ throw new Error(`Invalid subagent status config in ${source}: ${message}`)
157
+ }
158
+
159
+ function requireObject(
160
+ value: unknown,
161
+ source: string,
162
+ fieldName: string,
163
+ ): Record<string, unknown> {
164
+ if (value == null || typeof value !== 'object' || Array.isArray(value)) {
165
+ invalidStatusConfig(source, `${fieldName} must be an object`)
166
+ }
167
+ return value as Record<string, unknown>
168
+ }
169
+
170
+ function requireBoolean(
171
+ value: unknown,
172
+ source: string,
173
+ fieldName: string,
174
+ ): boolean {
175
+ if (typeof value !== 'boolean') {
176
+ invalidStatusConfig(source, `${fieldName} must be a boolean`)
177
+ }
178
+ return value
179
+ }
180
+
181
+ function rejectUnsupportedKeys(
182
+ value: Record<string, unknown>,
183
+ allowedKeys: string[],
184
+ source: string,
185
+ fieldName: string,
186
+ ): void {
187
+ const unsupportedKeys = Object.keys(value).filter(
188
+ (key) => !allowedKeys.includes(key),
189
+ )
190
+ if (unsupportedKeys.length > 0) {
191
+ invalidStatusConfig(
192
+ source,
193
+ `${fieldName} has unsupported key(s): ${unsupportedKeys.join(', ')}`,
194
+ )
195
+ }
196
+ }
197
+
198
+ function truncateText(text: string, maxLength: number): string {
199
+ if (text.length <= maxLength) return text
200
+ if (maxLength <= 1) return text.slice(0, maxLength)
201
+ return `${text.slice(0, maxLength - 1)}…`
202
+ }
203
+
204
+ export function normalizeStatusName(name: string): string {
205
+ const collapsed = name.replace(/\s+/g, ' ').trim() || 'subagent'
206
+ return truncateText(collapsed, MAX_STATUS_NAME_LENGTH)
207
+ }
208
+
209
+ function boundStatusLine(line: string): string {
210
+ return truncateText(line.replace(/\s+/g, ' ').trim(), MAX_STATUS_LINE_LENGTH)
211
+ }
212
+
213
+ function snapshotProblemLabel(
214
+ snapshotState: StatusSnapshotState,
215
+ ): string | null {
216
+ if (snapshotState === 'wrong-id') return 'wrong activity id'
217
+ return null
218
+ }
219
+
220
+ function activityLabel(
221
+ snapshot: Pick<StatusSnapshot, 'activityLabel' | 'activeScope'>,
222
+ ): string | null {
223
+ return snapshot.activityLabel ?? snapshot.activeScope
224
+ }
225
+
226
+ export function parseStatusConfig(
227
+ rawConfig: unknown,
228
+ source = 'config.json',
229
+ ): StatusConfig {
230
+ const config = requireObject(rawConfig, source, 'root')
231
+ const status = requireObject(config.status, source, 'status')
232
+ rejectUnsupportedKeys(status, ['enabled'], source, 'status')
233
+ const enabled = requireBoolean(status.enabled, source, 'status.enabled')
234
+
235
+ return {
236
+ enabled,
237
+ lineLimit: DEFAULT_STATUS_LINE_LIMIT,
238
+ }
239
+ }
240
+
241
+ function readStatusConfigFile(
242
+ configPath: string,
243
+ examplePath: string,
244
+ ): { sourcePath: string; rawConfig: string } {
245
+ try {
246
+ return {
247
+ sourcePath: configPath,
248
+ rawConfig: readFileSync(configPath, 'utf8'),
249
+ }
250
+ } catch (error) {
251
+ const errno = error as NodeJS.ErrnoException
252
+ if (errno.code !== 'ENOENT') throw error
253
+ }
254
+
255
+ try {
256
+ return {
257
+ sourcePath: examplePath,
258
+ rawConfig: readFileSync(examplePath, 'utf8'),
259
+ }
260
+ } catch (error) {
261
+ const errno = error as NodeJS.ErrnoException
262
+ if (errno.code === 'ENOENT') {
263
+ throw new Error(
264
+ `Missing subagent status config. Expected ${configPath} or ${examplePath}.`,
265
+ )
266
+ }
267
+ throw error
268
+ }
269
+ }
270
+
271
+ // AIDEV-NOTE: SUPERSEDED — runtime config now loads via config.ts
272
+ // (loadSubagentsConfig) from <agentDir>/pi-subagents/config.json with a
273
+ // project override in CONFIG_DIR_NAME. loadStatusConfig/config.json.example
274
+ // remain only for backwards compatibility and tests.
275
+ export function loadStatusConfig(
276
+ configPath = DEFAULT_STATUS_CONFIG_PATH,
277
+ examplePath = STATUS_CONFIG_EXAMPLE_PATH,
278
+ ): StatusConfig {
279
+ const { sourcePath, rawConfig } = readStatusConfigFile(
280
+ configPath,
281
+ examplePath,
282
+ )
283
+
284
+ let parsed: unknown
285
+ try {
286
+ parsed = JSON.parse(rawConfig) as unknown
287
+ } catch (error) {
288
+ const detail = error instanceof Error ? error.message : String(error)
289
+ throw new Error(`Invalid JSON in subagent config ${sourcePath}: ${detail}`)
290
+ }
291
+
292
+ return parseStatusConfig(parsed, sourcePath)
293
+ }
294
+
295
+ export function formatElapsedDuration(ms: number): string {
296
+ const totalSeconds = Math.max(0, Math.floor(ms / 1000))
297
+ if (totalSeconds < 60) return `${totalSeconds}s`
298
+
299
+ const hours = Math.floor(totalSeconds / 3600)
300
+ const minutes = Math.floor((totalSeconds % 3600) / 60)
301
+ if (hours > 0) return `${hours}h ${minutes}m`
302
+
303
+ return `${minutes}m`
304
+ }
305
+
306
+ export function createStatusState(params: {
307
+ source: SubagentStatusSource
308
+ startTimeMs: number
309
+ }): SubagentStatusState {
310
+ const initialKind = params.source === 'claude' ? 'running' : 'starting'
311
+ return {
312
+ source: params.source,
313
+ startTimeMs: params.startTimeMs,
314
+ firstObservationAtMs: null,
315
+ lastActivityAtMs: null,
316
+ lastActivitySequence: null,
317
+ localOverrideAtMs: null,
318
+ localOverrideSequence: null,
319
+ activeNow: false,
320
+ activeSinceMs: null,
321
+ activeScope: null,
322
+ waitingSinceMs: null,
323
+ blockedSinceMs: null,
324
+ phase: null,
325
+ latestEvent: null,
326
+ activityLabel: null,
327
+ snapshotState: params.source === 'claude' ? 'unseen' : 'unseen',
328
+ snapshotProblemSinceMs: null,
329
+ snapshotError: null,
330
+ currentKind: initialKind,
331
+ pendingRequest: null,
332
+ }
333
+ }
334
+
335
+ export function observeStatus(
336
+ state: SubagentStatusState,
337
+ observation: StatusObservation,
338
+ now: number,
339
+ ): SubagentStatusState {
340
+ if (state.source === 'claude') return state
341
+
342
+ if (observation.snapshot !== 'present') {
343
+ return {
344
+ ...state,
345
+ firstObservationAtMs: state.firstObservationAtMs ?? now,
346
+ snapshotState: observation.snapshot,
347
+ snapshotProblemSinceMs: state.snapshotProblemSinceMs ?? now,
348
+ snapshotError: observation.snapshotError ?? null,
349
+ }
350
+ }
351
+
352
+ const updatedAt = observation.updatedAt
353
+ const sequence = observation.sequence
354
+ const lastActivityAtMs = state.lastActivityAtMs
355
+ const lastActivitySequence = state.lastActivitySequence
356
+ const olderThanLastActivity =
357
+ lastActivityAtMs != null &&
358
+ (updatedAt < lastActivityAtMs ||
359
+ (updatedAt === lastActivityAtMs &&
360
+ lastActivitySequence != null &&
361
+ sequence < lastActivitySequence))
362
+ if (olderThanLastActivity) return state
363
+
364
+ const blockedByLocalOverride =
365
+ state.localOverrideAtMs != null &&
366
+ (updatedAt < state.localOverrideAtMs ||
367
+ (updatedAt === state.localOverrideAtMs &&
368
+ state.localOverrideSequence != null &&
369
+ sequence <= state.localOverrideSequence))
370
+ if (blockedByLocalOverride) return state
371
+
372
+ const phase = observation.phase
373
+ const activeNow = phase === 'active' || observation.active === true
374
+ const activeSinceMs = activeNow
375
+ ? (observation.activeSince ?? state.activeSinceMs ?? updatedAt)
376
+ : null
377
+ const waitingSinceMs =
378
+ phase === 'waiting'
379
+ ? (observation.waitingSince ?? state.waitingSinceMs ?? updatedAt)
380
+ : null
381
+ // AIDEV-NOTE: blocked ≠ waiting (PMR-WXG0) — a child sitting in ask_owner
382
+ // keeps its own since-timestamp so the status line can show "blocked".
383
+ const blockedSinceMs =
384
+ phase === 'blocked'
385
+ ? (observation.blockedSince ?? state.blockedSinceMs ?? updatedAt)
386
+ : null
387
+
388
+ return {
389
+ ...state,
390
+ firstObservationAtMs: state.firstObservationAtMs ?? now,
391
+ lastActivityAtMs: updatedAt,
392
+ lastActivitySequence: sequence,
393
+ activeNow,
394
+ activeSinceMs,
395
+ activeScope: activeNow ? (observation.activeScope ?? null) : null,
396
+ waitingSinceMs,
397
+ blockedSinceMs,
398
+ phase,
399
+ latestEvent: observation.latestEvent ?? null,
400
+ activityLabel: observation.activityLabel ?? null,
401
+ snapshotState: 'present',
402
+ snapshotProblemSinceMs: null,
403
+ snapshotError: null,
404
+ localOverrideAtMs: null,
405
+ localOverrideSequence: null,
406
+ }
407
+ }
408
+
409
+ export function forceStatusAfterInterrupt(
410
+ state: SubagentStatusState,
411
+ now: number,
412
+ ): SubagentStatusState {
413
+ if (state.source === 'claude') return state
414
+
415
+ return {
416
+ ...state,
417
+ firstObservationAtMs: state.firstObservationAtMs ?? now,
418
+ lastActivityAtMs: now,
419
+ localOverrideAtMs: now,
420
+ localOverrideSequence: state.lastActivitySequence,
421
+ activeNow: false,
422
+ activeSinceMs: null,
423
+ activeScope: null,
424
+ waitingSinceMs: now,
425
+ blockedSinceMs: null,
426
+ phase: 'waiting',
427
+ latestEvent: 'interrupt_requested',
428
+ activityLabel: 'interrupted',
429
+ snapshotState: 'present',
430
+ snapshotProblemSinceMs: null,
431
+ snapshotError: null,
432
+ currentKind: 'waiting',
433
+ }
434
+ }
435
+
436
+ export function markPendingRequest(
437
+ state: SubagentStatusState,
438
+ pending: PendingControlRequest,
439
+ ): SubagentStatusState {
440
+ return { ...state, pendingRequest: pending }
441
+ }
442
+
443
+ export type PendingAckOutcome = 'acked' | 'ignored'
444
+
445
+ // AIDEV-NOTE: identity revalidation — only an ack carrying the exact requestId
446
+ // we sent is applied; wrong-id acks are ignored (state untouched) so a stale
447
+ // sidecar from a superseded request can never satisfy a newer one.
448
+ export function applyPendingAck(
449
+ state: SubagentStatusState,
450
+ ackRequestId: string,
451
+ ): { state: SubagentStatusState; outcome: PendingAckOutcome } {
452
+ const pending = state.pendingRequest
453
+ if (!pending || pending.requestId !== ackRequestId) {
454
+ return { state, outcome: 'ignored' }
455
+ }
456
+ return {
457
+ state: {
458
+ ...state,
459
+ pendingRequest: null,
460
+ latestEvent: 'interrupt_acked',
461
+ },
462
+ outcome: 'acked',
463
+ }
464
+ }
465
+
466
+ export type PendingExpiryOutcome = 'pending' | 'timeout'
467
+
468
+ /** Expire the pending request once the bounded ack window elapses. */
469
+ export function expirePendingRequest(
470
+ state: SubagentStatusState,
471
+ now: number,
472
+ timeoutMs: number = INTERRUPT_ACK_TIMEOUT_MS,
473
+ ): { state: SubagentStatusState; outcome: PendingExpiryOutcome } {
474
+ const pending = state.pendingRequest
475
+ if (!pending || now - pending.sentAtMs < timeoutMs) {
476
+ return { state, outcome: 'pending' }
477
+ }
478
+ return {
479
+ state: {
480
+ ...state,
481
+ pendingRequest: null,
482
+ latestEvent: 'interrupt_unacknowledged',
483
+ },
484
+ outcome: 'timeout',
485
+ }
486
+ }
487
+
488
+ function lastHealthyKindOf(state: SubagentStatusState): SubagentStatusKind {
489
+ if (state.activeNow) return 'active'
490
+ if (state.phase === 'blocked') return 'blocked'
491
+ if (state.waitingSinceMs != null || state.phase === 'done') return 'waiting'
492
+ if (state.currentKind === 'stalled') return 'starting'
493
+ return state.currentKind
494
+ }
495
+
496
+ // AIDEV-NOTE (PMR-SMHB): a 'wrong-id' read means the activity file exists and
497
+ // some live child is writing it, but its runningChildId disagrees with our
498
+ // bookkeeping (identity churn: resume/reload/re-key paths hand out a new id
499
+ // while the old writer keeps going, or vice versa). That is identity
500
+ // ambiguity, not inactivity — a writer being present is evidence of life, so
501
+ // the 60s problem-age escalation must NEVER claim 'stalled' for it (fail
502
+ // closed: a possibly-alive child is never reported dead). Hold the last
503
+ // healthy kind ('starting' when identity was never validated) and keep the
504
+ // diagnostic label so the mismatch stays visible.
505
+ function classifyProblemState(
506
+ state: SubagentStatusState,
507
+ now: number,
508
+ ): Pick<StatusSnapshot, 'kind' | 'statusLabel'> {
509
+ const problemLabel = snapshotProblemLabel(state.snapshotState)
510
+ const hasValidSnapshot = state.lastActivityAtMs != null
511
+
512
+ if (state.snapshotState === 'wrong-id') {
513
+ if (!hasValidSnapshot) {
514
+ return { kind: 'starting', statusLabel: problemLabel }
515
+ }
516
+ return { kind: lastHealthyKindOf(state), statusLabel: problemLabel }
517
+ }
518
+
519
+ if (!hasValidSnapshot) {
520
+ const referenceMs = state.firstObservationAtMs ?? state.startTimeMs
521
+ const elapsedMs = Math.max(0, now - referenceMs)
522
+ if (elapsedMs >= SNAPSHOT_STALLED_AFTER_MS) {
523
+ return { kind: 'stalled', statusLabel: problemLabel }
524
+ }
525
+ return { kind: 'starting', statusLabel: null }
526
+ }
527
+
528
+ const problemSinceMs = state.snapshotProblemSinceMs ?? now
529
+ const problemMs = Math.max(0, now - problemSinceMs)
530
+ if (problemMs >= SNAPSHOT_STALLED_AFTER_MS) {
531
+ return { kind: 'stalled', statusLabel: problemLabel }
532
+ }
533
+
534
+ return { kind: lastHealthyKindOf(state), statusLabel: problemLabel }
535
+ }
536
+
537
+ // AIDEV-NOTE (PMR-YFRB): pure, now-parameterized dead-turn watchdog verdict.
538
+ // Scope-aware aging of the last recorded activity: streaming gets the short
539
+ // bucket (silence there means the model turn died mid-generation);
540
+ // provider/tool/turn/null/unknown scopes get the long bucket (a 20-minute
541
+ // bash is legitimate, and pre-first-token provider silence — large prompt
542
+ // processing, 429/529 retry-with-backoff loops — emits no events at all, so
543
+ // a short provider deadline false-kills healthy children, PMR-S1PT). A
544
+ // missing/invalid/wrong-id snapshot sustained past the long bucket is
545
+ // 'no-activity' — the poll-loop escalation backstop for vanished panes.
546
+ // Blocked (PMR-WXG0), waiting, and claude sources never stall here.
547
+ export function classifyTurnStall(
548
+ state: SubagentStatusState,
549
+ now: number,
550
+ thresholds: StallThresholds = DEFAULT_STALL_THRESHOLDS,
551
+ ): TurnStallVerdict {
552
+ if (state.source === 'claude' || !thresholds.enabled) {
553
+ return { stalled: false, reason: null, activeScope: null, stalledForMs: 0 }
554
+ }
555
+
556
+ const snapshotPresent = state.snapshotState === 'present'
557
+ const isActive = state.phase === 'active' || state.activeNow
558
+
559
+ if (snapshotPresent && isActive) {
560
+ const lastActivityAtMs = state.lastActivityAtMs
561
+ if (lastActivityAtMs == null) {
562
+ return {
563
+ stalled: false,
564
+ reason: null,
565
+ activeScope: null,
566
+ stalledForMs: 0,
567
+ }
568
+ }
569
+ const scope = state.activeScope
570
+ // Provider rides the long bucket (PMR-S1PT): before_provider_request →
571
+ // first streamed delta can legitimately stay silent far beyond 150s
572
+ // (huge contexts, provider-side retry backoff), and a false verdict here
573
+ // escalates to a failed result and closeSurface kills a healthy child
574
+ // mid-request. A stream hanging MID-generation is still caught by the
575
+ // streaming short bucket.
576
+ const shortBucket = scope === 'streaming'
577
+ let deadline: number
578
+ if (shortBucket) {
579
+ deadline = thresholds.streamStallAfterMs
580
+ } else {
581
+ deadline = thresholds.quietStallAfterMs
582
+ }
583
+ const ageMs = now - lastActivityAtMs
584
+ if (ageMs < deadline) {
585
+ return {
586
+ stalled: false,
587
+ reason: null,
588
+ activeScope: scope,
589
+ stalledForMs: 0,
590
+ }
591
+ }
592
+ return {
593
+ stalled: true,
594
+ reason: 'dead-turn',
595
+ activeScope: scope,
596
+ stalledForMs: ageMs,
597
+ }
598
+ }
599
+
600
+ if (!snapshotPresent) {
601
+ const referenceMs =
602
+ state.snapshotProblemSinceMs ??
603
+ state.firstObservationAtMs ??
604
+ state.startTimeMs
605
+ const ageMs = now - referenceMs
606
+ if (ageMs < thresholds.quietStallAfterMs) {
607
+ return {
608
+ stalled: false,
609
+ reason: null,
610
+ activeScope: null,
611
+ stalledForMs: 0,
612
+ }
613
+ }
614
+ return {
615
+ stalled: true,
616
+ reason: 'no-activity',
617
+ activeScope: null,
618
+ stalledForMs: ageMs,
619
+ }
620
+ }
621
+
622
+ // Present snapshot, but blocked / waiting / done / fresh — never stalled.
623
+ return { stalled: false, reason: null, activeScope: null, stalledForMs: 0 }
624
+ }
625
+
626
+ function formatHumanDuration(ms: number): string {
627
+ return formatElapsedDuration(Math.max(0, ms))
628
+ }
629
+
630
+ /** Human-readable error message for an escalated stall (PMR-YFRB). */
631
+ export function stallErrorMessage(verdict: TurnStallVerdict): string {
632
+ if (verdict.reason === 'no-activity') {
633
+ return `Subagent turn stalled: no activity snapshot for ${formatHumanDuration(verdict.stalledForMs)} (snapshot missing).`
634
+ }
635
+ const scope = verdict.activeScope ?? 'unknown'
636
+ return `Subagent turn stalled: ${scope} inactive for ${formatHumanDuration(verdict.stalledForMs)}.`
637
+ }
638
+
639
+ export function classifyStatus(
640
+ state: SubagentStatusState,
641
+ now: number,
642
+ thresholds: StallThresholds = DEFAULT_STALL_THRESHOLDS,
643
+ ): StatusSnapshot {
644
+ const elapsedMs = Math.max(0, now - state.startTimeMs)
645
+ const elapsedText = formatElapsedDuration(elapsedMs)
646
+
647
+ if (state.source === 'claude') {
648
+ return {
649
+ kind: 'running',
650
+ elapsedMs,
651
+ elapsedText,
652
+ activeSinceMs: null,
653
+ activeDurationText: null,
654
+ activeScope: null,
655
+ waitingSinceMs: null,
656
+ blockedSinceMs: null,
657
+ waitingDurationText: null,
658
+ blockedDurationText: null,
659
+ latestEvent: null,
660
+ activityLabel: null,
661
+ snapshotState: state.snapshotState,
662
+ snapshotError: null,
663
+ snapshotProblemText: null,
664
+ statusLabel: null,
665
+ }
666
+ }
667
+
668
+ let kind: SubagentStatusKind
669
+ let statusLabel: string | null = null
670
+
671
+ if (state.snapshotState === 'present') {
672
+ if (state.phase === 'active' || state.activeNow) {
673
+ // AIDEV-NOTE (PMR-YFRB): a present+active snapshot can now age into a
674
+ // dead turn via the scope-aware watchdog verdict. With the default
675
+ // thresholds and fresh activity this is a no-op, so legacy behavior is
676
+ // unchanged for anything inside its deadline.
677
+ const verdict = classifyTurnStall(state, now, thresholds)
678
+ if (verdict.stalled && verdict.reason === 'dead-turn') {
679
+ kind = 'stalled'
680
+ statusLabel = 'dead turn'
681
+ } else {
682
+ kind = 'active'
683
+ }
684
+ } else if (state.phase === 'blocked') {
685
+ // AIDEV-NOTE: blocked ≠ stalled (PMR-WXG0) — a blocked-asking child is
686
+ // intentionally waiting for its owner and must never trip the 60s
687
+ // snapshot-staleness rule, no matter how quiet it goes at its prompt.
688
+ kind = 'blocked'
689
+ } else if (state.phase === 'waiting') {
690
+ kind = 'waiting'
691
+ } else if (state.phase === 'done') {
692
+ kind = 'waiting'
693
+ statusLabel = 'done'
694
+ } else {
695
+ const referenceMs = state.firstObservationAtMs ?? state.startTimeMs
696
+ const elapsedSinceObservationMs = Math.max(0, now - referenceMs)
697
+ kind =
698
+ elapsedSinceObservationMs >= SNAPSHOT_STALLED_AFTER_MS
699
+ ? 'stalled'
700
+ : 'starting'
701
+ statusLabel = null
702
+ }
703
+ } else {
704
+ const classified = classifyProblemState(state, now)
705
+ kind = classified.kind
706
+ statusLabel = classified.statusLabel
707
+ }
708
+
709
+ const activeDurationText =
710
+ state.activeSinceMs == null
711
+ ? null
712
+ : formatElapsedDuration(now - state.activeSinceMs)
713
+ const waitingDurationText =
714
+ state.waitingSinceMs == null
715
+ ? null
716
+ : formatElapsedDuration(now - state.waitingSinceMs)
717
+ const blockedDurationText =
718
+ state.blockedSinceMs == null
719
+ ? null
720
+ : formatElapsedDuration(now - state.blockedSinceMs)
721
+ const snapshotProblemText =
722
+ state.snapshotProblemSinceMs == null
723
+ ? null
724
+ : formatElapsedDuration(now - state.snapshotProblemSinceMs)
725
+
726
+ return {
727
+ kind,
728
+ elapsedMs,
729
+ elapsedText,
730
+ activeSinceMs: state.activeSinceMs,
731
+ activeDurationText,
732
+ activeScope: state.activeScope,
733
+ waitingSinceMs: state.waitingSinceMs,
734
+ blockedSinceMs: state.blockedSinceMs,
735
+ waitingDurationText,
736
+ blockedDurationText,
737
+ latestEvent: state.latestEvent,
738
+ activityLabel: state.activityLabel,
739
+ snapshotState: state.snapshotState,
740
+ snapshotError: state.snapshotError,
741
+ snapshotProblemText,
742
+ statusLabel,
743
+ }
744
+ }
745
+
746
+ export function advanceStatusState(
747
+ state: SubagentStatusState,
748
+ now: number,
749
+ thresholds: StallThresholds = DEFAULT_STALL_THRESHOLDS,
750
+ ): {
751
+ nextState: SubagentStatusState
752
+ snapshot: StatusSnapshot
753
+ transition: SubagentStatusTransition
754
+ } {
755
+ const snapshot = classifyStatus(state, now, thresholds)
756
+ const transition =
757
+ state.currentKind !== 'stalled' && snapshot.kind === 'stalled'
758
+ ? 'stalled'
759
+ : state.currentKind === 'stalled' &&
760
+ (snapshot.kind === 'active' || snapshot.kind === 'waiting')
761
+ ? 'recovered'
762
+ : null
763
+
764
+ return {
765
+ snapshot,
766
+ transition,
767
+ nextState: {
768
+ ...state,
769
+ currentKind: snapshot.kind,
770
+ },
771
+ }
772
+ }
773
+
774
+ function formatActiveDetail(snapshot: StatusSnapshot): string {
775
+ const label = activityLabel(snapshot)
776
+ if (!label) return 'active'
777
+ const duration = snapshot.activeDurationText
778
+ ? ` ${snapshot.activeDurationText}`
779
+ : ''
780
+ return `active (${label}${duration})`
781
+ }
782
+
783
+ function formatWaitingDetail(snapshot: StatusSnapshot): string {
784
+ const duration = snapshot.waitingDurationText
785
+ ? ` ${snapshot.waitingDurationText}`
786
+ : ''
787
+ return `waiting${duration}`
788
+ }
789
+
790
+ function formatStalledDetail(snapshot: StatusSnapshot): string {
791
+ const detail = snapshot.statusLabel ? ` (${snapshot.statusLabel})` : ''
792
+ const duration = snapshot.snapshotProblemText
793
+ ? ` ${snapshot.snapshotProblemText}`
794
+ : ''
795
+ return `stalled${duration}${detail}`
796
+ }
797
+
798
+ export function formatStatusLine(
799
+ name: string,
800
+ snapshot: StatusSnapshot,
801
+ ): string {
802
+ const boundedName = normalizeStatusName(name)
803
+
804
+ if (snapshot.kind === 'starting') {
805
+ const label = snapshot.statusLabel ? ` (${snapshot.statusLabel})` : ''
806
+ return boundStatusLine(
807
+ `${boundedName} running ${snapshot.elapsedText}, starting${label}.`,
808
+ )
809
+ }
810
+
811
+ if (snapshot.kind === 'running') {
812
+ return boundStatusLine(`${boundedName} running ${snapshot.elapsedText}.`)
813
+ }
814
+
815
+ if (snapshot.kind === 'active') {
816
+ return boundStatusLine(
817
+ `${boundedName} running ${snapshot.elapsedText}, ${formatActiveDetail(snapshot)}.`,
818
+ )
819
+ }
820
+
821
+ if (snapshot.kind === 'blocked') {
822
+ const duration = snapshot.blockedDurationText
823
+ ? ` ${snapshot.blockedDurationText}`
824
+ : ''
825
+ return boundStatusLine(
826
+ `${boundedName} running ${snapshot.elapsedText}, blocked (waiting for owner${duration}).`,
827
+ )
828
+ }
829
+
830
+ if (snapshot.kind === 'waiting') {
831
+ const problem =
832
+ snapshot.statusLabel && snapshot.statusLabel !== 'done'
833
+ ? ` (${snapshot.statusLabel})`
834
+ : snapshot.statusLabel === 'done'
835
+ ? ' (done)'
836
+ : ''
837
+ return boundStatusLine(
838
+ `${boundedName} running ${snapshot.elapsedText}, ${formatWaitingDetail(snapshot)}${problem}.`,
839
+ )
840
+ }
841
+
842
+ return boundStatusLine(
843
+ `${boundedName} running ${snapshot.elapsedText}, ${formatStalledDetail(snapshot)}.`,
844
+ )
845
+ }
846
+
847
+ export function formatTransitionLine(
848
+ name: string,
849
+ snapshot: StatusSnapshot,
850
+ transition: Exclude<SubagentStatusTransition, null>,
851
+ ): string {
852
+ const boundedName = normalizeStatusName(name)
853
+
854
+ if (transition === 'recovered') {
855
+ const detail =
856
+ snapshot.kind === 'waiting'
857
+ ? formatWaitingDetail(snapshot)
858
+ : formatActiveDetail(snapshot)
859
+ return boundStatusLine(
860
+ `${boundedName} running ${snapshot.elapsedText}, recovered; ${detail}.`,
861
+ )
862
+ }
863
+
864
+ return formatStatusLine(boundedName, snapshot)
865
+ }
866
+
867
+ export function capStatusLines(
868
+ lines: string[],
869
+ lineLimit: number,
870
+ ): CappedStatusLines {
871
+ const visibleLines = lines.slice(0, lineLimit)
872
+ return {
873
+ visibleLines,
874
+ overflow: Math.max(0, lines.length - visibleLines.length),
875
+ }
876
+ }
877
+
878
+ export function formatStatusAggregate(
879
+ lines: string[],
880
+ lineLimit: number,
881
+ ): string {
882
+ const { visibleLines, overflow } = capStatusLines(lines, lineLimit)
883
+ const bulletLines = visibleLines.map((line) => `• ${line}`)
884
+ if (overflow > 0) bulletLines.push(`• +${overflow} more running.`)
885
+ return `Subagent status:\n${bulletLines.join('\n')}`
886
+ }