@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,1452 @@
1
+ /**
2
+ * Extension loaded into sub-agents.
3
+ * - Shows agent identity + available tools as a styled widget above the editor (toggle with Alt+J)
4
+ * - Provides a `subagent_done` tool for autonomous agents to self-terminate
5
+ * - Replay discipline (PMR-ZJCP): child side-effect tools consult the durable
6
+ * effect memo (tool-effects/) and their own records (ask record, inbox,
7
+ * .exit payload) so an interrupted run replays the original askId/payload
8
+ * instead of duplicating the send
9
+ */
10
+
11
+ import { randomUUID } from 'node:crypto'
12
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
13
+ import type { ExtensionAPI } from '@mariozechner/pi-coding-agent'
14
+ import { Box, Text } from '@mariozechner/pi-tui'
15
+ import { Type } from '@sinclair/typebox'
16
+ import { createSubagentActivityRecorder } from './activity.ts'
17
+ import {
18
+ type AskRecord,
19
+ type AskReplyRecord,
20
+ readAskRecord,
21
+ readAskSidecar,
22
+ readReplyRecord,
23
+ removeAskRecord,
24
+ removeReplyRecord,
25
+ writeAskRecord,
26
+ writeAskSidecar,
27
+ } from './asks.ts'
28
+ import { loadSubagentsConfig } from './config.ts'
29
+ import {
30
+ type ControlAck,
31
+ type ControlRecord,
32
+ readControlRecord,
33
+ writeAckSidecar,
34
+ } from './control.ts'
35
+ import { ensureSubagentsDataDir } from './dataroot.ts'
36
+ import { hasDelivered, markDelivered } from './delivered.ts'
37
+ import { readOwnerInbox, sendOwnerMessage } from './inbox.ts'
38
+ import {
39
+ type PeerRecipientBinding,
40
+ readPeerBinding,
41
+ touchPeerBinding,
42
+ writePeerBinding,
43
+ } from './peer-bindings.ts'
44
+ import {
45
+ type ChildIdentity,
46
+ inboxDir,
47
+ listLivePeers,
48
+ presenceIsLive,
49
+ publishPresence,
50
+ readInbox,
51
+ readPresence,
52
+ removeInboxEntry,
53
+ resolvePeer,
54
+ sendPeerMessage,
55
+ } from './peers.ts'
56
+ import {
57
+ effectFingerprint,
58
+ readEffectMemo,
59
+ rewriteEffectMemo,
60
+ writeEffectMemo,
61
+ } from './tool-effects.ts'
62
+
63
+ // AIDEV-NOTE (PMR-ZJCP): parse the `.exit` sidecar defensively — a missing
64
+ // file or malformed JSON means "no prior payload" and callers proceed with the
65
+ // fresh-write path; only a well-formed payload can trigger replay/conflict.
66
+ function parseExitPayload(
67
+ exitFile: string,
68
+ ): { type: string; message?: string } | null {
69
+ if (!existsSync(exitFile)) {
70
+ return null
71
+ }
72
+ let parsed: unknown
73
+ try {
74
+ parsed = JSON.parse(readFileSync(exitFile, 'utf8'))
75
+ } catch {
76
+ return null
77
+ }
78
+ if (typeof parsed !== 'object' || parsed === null) {
79
+ return null
80
+ }
81
+ const record = parsed as Record<string, unknown>
82
+ if (typeof record.type !== 'string') {
83
+ return null
84
+ }
85
+ if (typeof record.message === 'string') {
86
+ return { type: record.type, message: record.message }
87
+ }
88
+ return { type: record.type }
89
+ }
90
+
91
+ export function shouldMarkUserTookOver(agentStarted: boolean): boolean {
92
+ return agentStarted
93
+ }
94
+
95
+ export function shouldAutoExitOnAgentEnd(
96
+ _userTookOver: boolean,
97
+ messages: any[] | undefined,
98
+ ): boolean {
99
+ // Manual input should not strand an auto-exit subagent. If the latest agent
100
+ // turn completed normally, close the session. Escape/abort still leaves it
101
+ // open for inspection or another prompt.
102
+ //
103
+ // stopReason: "error" (e.g. exhausted retries on a provider overload) also
104
+ // returns true — we want to shut down so the parent is woken up — but we
105
+ // pair this with findLatestAssistantError() so the parent learns it was an
106
+ // error, not a clean completion.
107
+ if (messages) {
108
+ for (let i = messages.length - 1; i >= 0; i--) {
109
+ const msg = messages[i]
110
+ if (msg?.role === 'assistant') {
111
+ return msg.stopReason !== 'aborted'
112
+ }
113
+ }
114
+ }
115
+
116
+ return true
117
+ }
118
+
119
+ /** Pure pump decision: should this reply be delivered into this child? */
120
+ export type ReplyPumpDecision = 'idle' | 'identity_mismatch' | 'deliver'
121
+
122
+ export function decideReplyDelivery(params: {
123
+ reply: AskReplyRecord | null
124
+ record: AskRecord | null
125
+ childId: string
126
+ sessionFile: string
127
+ }): ReplyPumpDecision {
128
+ if (!params.reply || !params.record) return 'idle'
129
+ if (params.record.childId !== params.childId) return 'identity_mismatch'
130
+ if (params.record.sessionFile !== params.sessionFile) {
131
+ return 'identity_mismatch'
132
+ }
133
+ if (params.record.askId !== params.reply.askId) return 'identity_mismatch'
134
+ return 'deliver'
135
+ }
136
+
137
+ export interface SubagentErrorInfo {
138
+ errorMessage: string
139
+ stopReason: 'error'
140
+ }
141
+
142
+ /**
143
+ * Payload the auto-exit path should write to the `.exit` sidecar: `{type:'error'}`
144
+ * when the turn ended with stopReason=error, `{type:'done'}` otherwise.
145
+ *
146
+ * AIDEV-NOTE: clean auto-exits previously wrote NO sidecar, so the parent's
147
+ * only completion signal was scraping the pane's last 5 visible rows for the
148
+ * `__SUBAGENT_DONE_` sentinel. The post-exit shell prompt (time report +
149
+ * multi-line prompt, more when lines wrap) pushes the sentinel out of that
150
+ * window and the parent never wakes. Always write the sidecar.
151
+ */
152
+ export function exitSidecarPayload(
153
+ messages: any[] | undefined,
154
+ ):
155
+ | { type: 'error'; errorMessage: string; stopReason: 'error' }
156
+ | { type: 'done' } {
157
+ const errorInfo = findLatestAssistantError(messages)
158
+ if (errorInfo) return { type: 'error', ...errorInfo }
159
+ return { type: 'done' }
160
+ }
161
+
162
+ /**
163
+ * If the last assistant message in the turn ended with `stopReason: "error"`
164
+ * (typically auto-retry exhausted on an overload / rate limit / server error),
165
+ * return its error info so the parent orchestrator can surface a clear
166
+ * failure instead of silently treating the run as completed.
167
+ *
168
+ * Returns `null` when the latest assistant turn completed normally or was
169
+ * aborted by the user (handled separately by shouldAutoExitOnAgentEnd).
170
+ */
171
+ export function findLatestAssistantError(
172
+ messages: any[] | undefined,
173
+ ): SubagentErrorInfo | null {
174
+ if (!messages) return null
175
+ for (let i = messages.length - 1; i >= 0; i--) {
176
+ const msg = messages[i]
177
+ if (msg?.role !== 'assistant') continue
178
+ if (msg.stopReason !== 'error') return null
179
+ const raw =
180
+ typeof msg.errorMessage === 'string' ? msg.errorMessage.trim() : ''
181
+ return {
182
+ errorMessage:
183
+ raw ||
184
+ 'Subagent agent loop ended with stopReason=error (no errorMessage field).',
185
+ stopReason: 'error',
186
+ }
187
+ }
188
+ return null
189
+ }
190
+
191
+ export function parseDeniedTools(rawValue: string | undefined): string[] {
192
+ return (rawValue ?? '')
193
+ .split(',')
194
+ .map((value) => value.trim())
195
+ .filter(Boolean)
196
+ }
197
+
198
+ /** stopReason of the latest assistant message, or null when none. */
199
+ export function findLastStopReason(messages: any[] | undefined): string | null {
200
+ if (!messages) return null
201
+ for (let i = messages.length - 1; i >= 0; i--) {
202
+ const msg = messages[i]
203
+ if (msg?.role !== 'assistant') continue
204
+ if (typeof msg.stopReason === 'string') return msg.stopReason
205
+ return null
206
+ }
207
+ return null
208
+ }
209
+
210
+ /**
211
+ * Pure ack decision for the parent→child interrupt handshake (PMR-DNPZ).
212
+ *
213
+ * AIDEV-NOTE: Escape is observed at the aborted turn boundary, not instantly —
214
+ * pi aborts the in-flight agent turn, which surfaces here as `agent_end` with
215
+ * `stopReason === 'aborted'`. That boundary is the earliest reliable signal
216
+ * that the interrupt took effect, so the ack lands there. A child that exits
217
+ * normally instead (the interrupt-raced-completion case) never acks; the
218
+ * parent sees `.exit` and the request times out harmlessly.
219
+ */
220
+ export function interruptAckPayload(
221
+ stopReason: string | undefined,
222
+ record: ControlRecord | null,
223
+ ): ControlAck | null {
224
+ if (stopReason !== 'aborted') return null
225
+ if (!record || record.kind !== 'interrupt') return null
226
+ return {
227
+ requestId: record.requestId,
228
+ accepted: true,
229
+ code: 'idle',
230
+ message: 'turn aborted by interrupt',
231
+ }
232
+ }
233
+
234
+ /**
235
+ * Pure one-shot intercept decision for threshold compaction (PMR-HVM8).
236
+ *
237
+ * AIDEV-NOTE: first threshold compaction on a gated child is cancelled so the
238
+ * child can converge (finish up, call subagent_done) instead of being
239
+ * summarized mid-flight. The SECOND threshold event must fall through to
240
+ * native compaction — canceling forever would loop-block the child against
241
+ * a context it can never shrink. Manual/emergency compaction is never
242
+ * touched (the user or pi asked for summarization explicitly).
243
+ */
244
+ export interface ThresholdInterceptDecision {
245
+ cancel: boolean
246
+ retire: boolean
247
+ }
248
+
249
+ export function decideThresholdIntercept(params: {
250
+ reason: string
251
+ enabled: boolean
252
+ isChild: boolean
253
+ interceptUsed: boolean
254
+ }): ThresholdInterceptDecision {
255
+ if (!params.enabled || !params.isChild)
256
+ return { cancel: false, retire: false }
257
+ if (params.interceptUsed) return { cancel: false, retire: false }
258
+ if (params.reason !== 'threshold') return { cancel: false, retire: false }
259
+ return { cancel: true, retire: true }
260
+ }
261
+
262
+ const CONVERGE_GUIDANCE =
263
+ 'Context retirement: this subagent session hit its compaction threshold. ' +
264
+ 'Compaction was cancelled once so you can converge instead of being ' +
265
+ 'summarized mid-task. Wrap up NOW: finish (or safely abandon) whatever you ' +
266
+ 'are doing and call the subagent_done tool with your final summary. Do not ' +
267
+ 'start new work. If this session hits the threshold again, native ' +
268
+ 'compaction will proceed and this guidance will not repeat.'
269
+
270
+ export default function (pi: ExtensionAPI) {
271
+ let toolNames: string[] = []
272
+ let denied: string[] = []
273
+ let expanded = false
274
+
275
+ // Read subagent identity from env vars (set by parent orchestrator)
276
+ const subagentName = process.env.PI_SUBAGENT_NAME ?? ''
277
+ const subagentAgent = process.env.PI_SUBAGENT_AGENT ?? ''
278
+ const deniedToolsValue = process.env.PI_DENY_TOOLS
279
+ const autoExit = process.env.PI_SUBAGENT_AUTO_EXIT === '1'
280
+ const recorder = createSubagentActivityRecorder({
281
+ runningChildId: process.env.PI_SUBAGENT_ID,
282
+ activityFile: process.env.PI_SUBAGENT_ACTIVITY_FILE,
283
+ })
284
+
285
+ function renderWidget(ctx: { ui: { setWidget: Function } }, _theme: any) {
286
+ ctx.ui.setWidget(
287
+ 'subagent-tools',
288
+ (_tui: any, theme: any) => {
289
+ const box = new Box(1, 0, (text: string) =>
290
+ theme.bg('toolSuccessBg', text),
291
+ )
292
+
293
+ const label = subagentAgent || subagentName
294
+ const agentTag = label
295
+ ? theme.bold(theme.fg('accent', `[${label}]`))
296
+ : ''
297
+
298
+ if (expanded) {
299
+ // Expanded: full tool list + denied
300
+ const countInfo = theme.fg('dim', ` — ${toolNames.length} available`)
301
+ const hint = theme.fg('muted', ' (Alt+J to collapse)')
302
+
303
+ const toolList = toolNames
304
+ .map((name: string) => theme.fg('dim', name))
305
+ .join(theme.fg('muted', ', '))
306
+
307
+ let deniedLine = ''
308
+ if (denied.length > 0) {
309
+ const deniedList = denied
310
+ .map((name: string) => theme.fg('error', name))
311
+ .join(theme.fg('muted', ', '))
312
+ deniedLine = `\n${theme.fg('muted', 'denied: ')}${deniedList}`
313
+ }
314
+
315
+ const content = new Text(
316
+ `${agentTag}${countInfo}${hint}\n${toolList}${deniedLine}`,
317
+ 0,
318
+ 0,
319
+ )
320
+ box.addChild(content)
321
+ } else {
322
+ // Collapsed: one-line summary
323
+ const countInfo = theme.fg('dim', ` — ${toolNames.length} tools`)
324
+ const deniedInfo =
325
+ denied.length > 0
326
+ ? theme.fg('dim', ' · ') +
327
+ theme.fg('error', `${denied.length} denied`)
328
+ : ''
329
+ const hint = theme.fg('muted', ' (Alt+J to expand)')
330
+
331
+ const content = new Text(
332
+ `${agentTag}${countInfo}${deniedInfo}${hint}`,
333
+ 0,
334
+ 0,
335
+ )
336
+ box.addChild(content)
337
+ }
338
+
339
+ return box
340
+ },
341
+ { placement: 'aboveEditor' },
342
+ )
343
+ }
344
+
345
+ let userTookOver = false
346
+ let agentStarted = false
347
+
348
+ // Show widget + status bar on session start
349
+ // AIDEV-NOTE: the ack correlates on the CURRENT control record's requestId;
350
+ // if the parent already superseded it, this ack is discarded parent-side by
351
+ // requestId correlation.
352
+ function tryAckInterrupt(stopReason: string): void {
353
+ const childId = process.env.PI_SUBAGENT_ID
354
+ const sessionFile = process.env.PI_SUBAGENT_SESSION
355
+ if (!childId || !sessionFile) return
356
+ const record = readControlRecord(childId)
357
+ const ack = interruptAckPayload(stopReason, record)
358
+ if (ack) writeAckSidecar(sessionFile, ack)
359
+ }
360
+
361
+ // ── Mailbox pump (PMR-WXG0 phase 5) ──
362
+ // Watches the parent-owned reply record for this child's pending ask and
363
+ // delivers the answer into THIS session as a normal user turn.
364
+ //
365
+ // AIDEV-NOTE: at-least-once window — the reply record is only deleted AFTER
366
+ // sendMessage succeeds and the ingestion ack is written. A pump failure (crash
367
+ // before sendMessage, failed ack write) leaves the record in place so the next
368
+ // pump tick (or a resumed session's first tick) re-delivers the same answer;
369
+ // worst case the child sees the answer twice. Identity is revalidated on every
370
+ // tick: the ask record must name THIS childId + sessionFile and the reply's
371
+ // askId must match — a stale/superseded reply is never delivered.
372
+ let pumpBusy = false
373
+
374
+ function pumpReplies(): void {
375
+ if (pumpBusy) return
376
+ const childId = process.env.PI_SUBAGENT_ID
377
+ const sessionFile = process.env.PI_SUBAGENT_SESSION
378
+ if (!childId || !sessionFile) return
379
+ pumpBusy = true
380
+ try {
381
+ const reply = readReplyRecord(childId)
382
+ const record = readAskRecord(childId)
383
+ if (
384
+ decideReplyDelivery({ reply, record, childId, sessionFile }) !==
385
+ 'deliver'
386
+ ) {
387
+ return
388
+ }
389
+ if (!reply || !record) return // unreachable per decideReplyDelivery
390
+ // AIDEV-NOTE (PMR-KY0E): exactly-once guard — a crash after sendMessage
391
+ // but before the record unlink would re-deliver the same answer; the
392
+ // delivered marker suppresses that. Window note: the marker is written
393
+ // AFTER sendMessage succeeds, so a crash in the send→mark gap can still
394
+ // duplicate (tiny); marking earlier would risk LOSING the answer on a
395
+ // failed send, which is worse than a rare duplicate.
396
+ if (hasDelivered(childId, reply.askId)) {
397
+ // Already injected — finish the idempotent cleanup only.
398
+ writeAckSidecar(sessionFile, {
399
+ requestId: reply.askId,
400
+ accepted: true,
401
+ code: 'idle',
402
+ message: 'answer already delivered (dedup)',
403
+ })
404
+ removeReplyRecord(childId)
405
+ removeAskRecord(childId)
406
+ return
407
+ }
408
+ pi.sendMessage(
409
+ {
410
+ customType: 'subagent-answer',
411
+ content:
412
+ `The owner answered your question (${reply.askId}):\n\n` +
413
+ reply.message,
414
+ display: true,
415
+ details: { askId: reply.askId },
416
+ },
417
+ { triggerTurn: true },
418
+ )
419
+ markDelivered(childId, reply.askId)
420
+ writeAckSidecar(sessionFile, {
421
+ requestId: reply.askId,
422
+ accepted: true,
423
+ code: 'idle',
424
+ message: 'answer ingested',
425
+ })
426
+ removeReplyRecord(childId)
427
+ removeAskRecord(childId)
428
+ } catch {
429
+ // Durable record stays — the next tick re-delivers (see AIDEV-NOTE above).
430
+ } finally {
431
+ pumpBusy = false
432
+ }
433
+ }
434
+
435
+ // Delivery cadence: 500ms pumpMailboxes interval (see AIDEV-NOTE below —
436
+ // fs.watch was removed after it wedged child startup).
437
+ // AIDEV-NOTE: no fs.watch here — a watcher whose listener runs the pump
438
+ // during pi's startup wedges the event loop before the first turn (found
439
+ // 2026-10-15 via integration repro: child pi spins at 100% CPU, never
440
+ // creates its session file; watch+noop listener is fine, interval-only is
441
+ // fine). Polling every 500ms is the documented delivery path and is
442
+ // sufficient — fs.watch bought sub-second latency at the cost of a
443
+ // startup-deadlock we never fully isolated. Do not re-add without a
444
+ // startup regression test.
445
+ function startReplyWatcher(): void {
446
+ const childId = process.env.PI_SUBAGENT_ID
447
+ if (!childId || !process.env.PI_SUBAGENT_SESSION) return
448
+ try {
449
+ ensureSubagentsDataDir('asks')
450
+ } catch {
451
+ // asks dir missing — the 500ms pump re-checks every tick anyway.
452
+ }
453
+ }
454
+
455
+ const isChildSession = Boolean(
456
+ process.env.PI_SUBAGENT_ID && process.env.PI_SUBAGENT_SESSION,
457
+ )
458
+
459
+ if (isChildSession) {
460
+ startReplyWatcher()
461
+ startPeerWatcher()
462
+ const pumpInterval = setInterval(pumpMailboxes, 500)
463
+ pumpInterval.unref()
464
+ }
465
+
466
+ // ── Context retirement, child side (PMR-HVM8) ──
467
+ // AIDEV-NOTE: one-shot intercept — see decideThresholdIntercept. The hook
468
+ // is only registered for gated children; non-child sessions and
469
+ // contextRetirement.enabled=false never see it.
470
+ const retirementEnabled =
471
+ loadSubagentsConfig(process.cwd()).config.contextRetirement?.enabled ===
472
+ true
473
+ if (isChildSession && retirementEnabled) {
474
+ let thresholdInterceptUsed = false
475
+ pi.on('session_before_compact', (event) => {
476
+ // pi's extension typings (0.65) omit `reason`; the runtime (0.84) always
477
+ // passes it. Narrow structurally instead of bumping types.
478
+ const reason = (event as { reason?: string }).reason ?? ''
479
+ const decision = decideThresholdIntercept({
480
+ reason,
481
+ enabled: retirementEnabled,
482
+ isChild: isChildSession,
483
+ interceptUsed: thresholdInterceptUsed,
484
+ })
485
+ if (decision.retire) {
486
+ thresholdInterceptUsed = true
487
+ recorder.retiring()
488
+ pi.sendMessage(
489
+ {
490
+ customType: 'subagent-converge',
491
+ content: CONVERGE_GUIDANCE,
492
+ display: true,
493
+ },
494
+ { triggerTurn: true },
495
+ )
496
+ }
497
+ if (decision.cancel) return { cancel: true }
498
+ })
499
+ }
500
+
501
+ // ── Peer inbox drain (PMR-98S6) ──
502
+ // AIDEV-NOTE: at-least-once — an inbox entry is unlinked only AFTER its
503
+ // sendMessage succeeds; a crash before that re-delivers the same peer
504
+ // message next tick (duplicate turn worst case). Mirrors pumpReplies.
505
+ let peerDrainBusy = false
506
+ let releasePresence: (() => void) | null = null
507
+
508
+ function childIdentity(): ChildIdentity | null {
509
+ const childId = process.env.PI_SUBAGENT_ID
510
+ const sessionFile = process.env.PI_SUBAGENT_SESSION
511
+ if (!childId || !sessionFile) return null
512
+ const identity: ChildIdentity = {
513
+ childId,
514
+ sessionFile,
515
+ name: subagentName || childId,
516
+ cwd: process.cwd(),
517
+ }
518
+ if (subagentAgent) identity.agent = subagentAgent
519
+ return identity
520
+ }
521
+
522
+ function pumpInbox(): void {
523
+ if (peerDrainBusy) return
524
+ const identity = childIdentity()
525
+ if (!identity) return
526
+ peerDrainBusy = true
527
+ try {
528
+ for (const entry of readInbox(identity.childId)) {
529
+ const from = entry.message.from
530
+ const who = from.name || from.childId
531
+ const details: Record<string, unknown> = {
532
+ messageId: entry.message.messageId,
533
+ }
534
+ if (entry.message.resultRef !== undefined) {
535
+ details.resultRef = entry.message.resultRef
536
+ }
537
+ // AIDEV-NOTE (PMR-KY0E): exactly-once guard, same pattern as
538
+ // pumpReplies — hasDelivered BEFORE the turn, markDelivered only
539
+ // after sendMessage succeeded.
540
+ if (hasDelivered(identity.childId, entry.message.messageId)) {
541
+ removeInboxEntry(entry.path)
542
+ continue
543
+ }
544
+ pi.sendMessage(
545
+ {
546
+ customType: 'subagent-peer-message',
547
+ content:
548
+ `Peer message from ${who} (${from.childId}):\n\n` +
549
+ entry.message.message,
550
+ display: true,
551
+ details,
552
+ },
553
+ { triggerTurn: true },
554
+ )
555
+ markDelivered(identity.childId, entry.message.messageId)
556
+ removeInboxEntry(entry.path)
557
+ }
558
+ } catch {
559
+ // Entries stay durable — next tick re-delivers (see AIDEV-NOTE above).
560
+ } finally {
561
+ peerDrainBusy = false
562
+ }
563
+ }
564
+
565
+ function pumpMailboxes(): void {
566
+ pumpReplies()
567
+ pumpInbox()
568
+ }
569
+
570
+ // AIDEV-NOTE: polling-only like startReplyWatcher (same startup-wedge
571
+ // reason, see that note). Kept as a named function so the pump structure
572
+ // stays symmetric.
573
+ function startPeerWatcher(): void {
574
+ const identity = childIdentity()
575
+ if (!identity) return
576
+ try {
577
+ ensureSubagentsDataDir('peers')
578
+ } catch {
579
+ // peers dir missing — the 500ms pump re-checks every tick anyway.
580
+ }
581
+ }
582
+
583
+ pi.registerTool({
584
+ name: 'list_peers',
585
+ label: 'List Peers',
586
+ description:
587
+ 'List other live subagents you can message. Returns yourself plus every ' +
588
+ 'currently-running peer (dead/stale peers are filtered). Use childId or name ' +
589
+ 'as the `peer` argument of message_peer.',
590
+ parameters: Type.Object({}),
591
+ async execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
592
+ const identity = childIdentity()
593
+ if (!identity) {
594
+ throw new Error(
595
+ 'list_peers is only available in subagent contexts. ' +
596
+ 'PI_SUBAGENT_ID/PI_SUBAGENT_SESSION environment variables are not set.',
597
+ )
598
+ }
599
+ const peers = listLivePeers(identity)
600
+ const lines: string[] = []
601
+ for (const p of peers) {
602
+ const agentTag = p.agent ? ` [${p.agent}]` : ''
603
+ const selfMark = p.self ? ' (you)' : ''
604
+ lines.push(`- ${p.name}${agentTag} childId=${p.childId}${selfMark}`)
605
+ }
606
+ let text = 'No live peers right now.'
607
+ if (lines.length > 0) {
608
+ text = `Live peers (including you):\n${lines.join('\n')}`
609
+ }
610
+ return {
611
+ content: [{ type: 'text', text }],
612
+ details: { peers },
613
+ }
614
+ },
615
+ })
616
+
617
+ pi.registerTool({
618
+ name: 'message_peer',
619
+ label: 'Message Peer',
620
+ description:
621
+ 'Send a durable message to another live subagent WITHOUT blocking: the message is ' +
622
+ 'delivered to the peer as a new turn in ITS session and you keep working immediately. ' +
623
+ 'Resolve recipients with list_peers first. Max 8 KiB per message.',
624
+ parameters: Type.Object({
625
+ peer: Type.String({
626
+ description: 'Recipient childId or name (from list_peers)',
627
+ }),
628
+ message: Type.String({ description: 'Message body' }),
629
+ resultRef: Type.Optional(
630
+ Type.String({
631
+ description:
632
+ 'Optional result ref (result:<name>#<n>) to forward so the peer can load it',
633
+ }),
634
+ ),
635
+ }),
636
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
637
+ const identity = childIdentity()
638
+ if (!identity) {
639
+ throw new Error(
640
+ 'message_peer is only available in subagent contexts. ' +
641
+ 'PI_SUBAGENT_ID/PI_SUBAGENT_SESSION environment variables are not set.',
642
+ )
643
+ }
644
+ // AIDEV-NOTE (PMR-ZJCP): the memo-hit path runs BEFORE resolvePeer, so
645
+ // it cannot name the peer — static text mirroring message_owner's.
646
+ const replayedSentText =
647
+ 'Message delivered to the peer. You can keep working — the peer ' +
648
+ 'will pick it up as its next turn.'
649
+ const fingerprint = effectFingerprint('message_peer', identity.childId, {
650
+ peer: params.peer,
651
+ message: params.message,
652
+ resultRef: params.resultRef,
653
+ })
654
+ // AIDEV-NOTE (PMR-ZJCP): replay-safety for message_peer. Memo hit → the
655
+ // earlier send already happened; replay the memoized messageId with NO
656
+ // send and NO inbox mutation — and no resolvePeer call, so a peer that
657
+ // has since gone offline still gets its memoized delivery. Malformed
658
+ // memo results fail closed by falling through to the inbox scan below.
659
+ const memo = readEffectMemo(identity.childId, 'message_peer', fingerprint)
660
+ if (
661
+ memo !== null &&
662
+ typeof memo.result.messageId === 'string' &&
663
+ typeof memo.result.path === 'string'
664
+ ) {
665
+ return {
666
+ content: [
667
+ {
668
+ type: 'text',
669
+ text: `[Replay of an interrupted call] ${replayedSentText}`,
670
+ },
671
+ ],
672
+ details: { messageId: memo.result.messageId, path: memo.result.path },
673
+ }
674
+ }
675
+ // AIDEV-NOTE (PMR-77KT): bind-before-send discipline. Every logical
676
+ // send is durably bound (first write wins) to the recipient resolved at
677
+ // bind time — childId + sessionFile. Replays never re-resolve the peer
678
+ // name: if the bound recipient has died or been superseded, the send
679
+ // fails closed (throw, no retarget) rather than delivering to a new
680
+ // generation under the same name. The inbox evidence scan is the
681
+ // send→memo crash-window recovery (PMR-ZJCP); the binding is the
682
+ // recipient-pinning mechanism that makes it safe across generations.
683
+ const boundRequestMatches = (binding: PeerRecipientBinding): boolean => {
684
+ const sameResultRef =
685
+ (binding.request.resultRef || undefined) ===
686
+ (params.resultRef || undefined)
687
+ return (
688
+ binding.request.peer === params.peer &&
689
+ binding.request.message === params.message &&
690
+ sameResultRef
691
+ )
692
+ }
693
+ const deliverViaBinding = (
694
+ binding: PeerRecipientBinding,
695
+ ): {
696
+ content: { type: 'text'; text: string }[]
697
+ details: { messageId: string; path: string }
698
+ } => {
699
+ if (binding.toChildId === identity.childId) {
700
+ throw new Error(
701
+ `Peer binding conflict: the binding record names yourself ` +
702
+ `(${binding.toChildId}) as the recipient, which is corrupt. ` +
703
+ `Message NOT delivered; no retarget — the binding is never ` +
704
+ `overwritten and must be investigated.`,
705
+ )
706
+ }
707
+ if (!boundRequestMatches(binding)) {
708
+ throw new Error(
709
+ `Peer binding conflict: this logical send is already bound to ` +
710
+ `${binding.toName} (${binding.toChildId}) with a different ` +
711
+ `request payload. Message NOT delivered; no retarget — the ` +
712
+ `binding is never overwritten.`,
713
+ )
714
+ }
715
+ // AIDEV-NOTE (PMR-ZJCP): W1 crash-window evidence scan — the inbox
716
+ // is the source of truth when a send happened but the memo write was
717
+ // interrupted. Matches sender childId + byte-exact message + exact
718
+ // resultRef (undefined never matches ''). The scan runs against the
719
+ // BOUND recipient's inbox, so prior delivery is provable even when
720
+ // the recipient has since died. Prior to the binding (PMR-77KT)
721
+ // this scanned whichever recipient the name re-resolved to.
722
+ const delivered = readInbox(binding.toChildId).find(
723
+ (entry) =>
724
+ entry.message.from.childId === identity.childId &&
725
+ entry.message.message === params.message &&
726
+ (entry.message.resultRef || undefined) ===
727
+ (params.resultRef || undefined),
728
+ )
729
+ if (delivered !== undefined) {
730
+ writeEffectMemo({
731
+ version: 1,
732
+ childId: identity.childId,
733
+ tool: 'message_peer',
734
+ fingerprint,
735
+ createdAt: new Date().toISOString(),
736
+ result: {
737
+ messageId: delivered.message.messageId,
738
+ path: delivered.path,
739
+ },
740
+ })
741
+ touchPeerBinding(binding)
742
+ return {
743
+ content: [
744
+ {
745
+ type: 'text',
746
+ text:
747
+ `An identical message was already delivered to ${binding.toName} ` +
748
+ `(${binding.toChildId}) earlier (messageId ` +
749
+ `${delivered.message.messageId}); no duplicate send was made.`,
750
+ },
751
+ ],
752
+ details: {
753
+ messageId: delivered.message.messageId,
754
+ path: delivered.path,
755
+ },
756
+ }
757
+ }
758
+ // Liveness gate on the BOUND identity — never resolvePeer. A dead or
759
+ // superseded recipient fails closed: no send, no inbox mutation, no
760
+ // retarget under a reused name.
761
+ const presence = readPresence(binding.toChildId)
762
+ const boundPeerIsLive =
763
+ presence !== null &&
764
+ presence.sessionFile === binding.toSessionFile &&
765
+ presenceIsLive(presence)
766
+ if (!boundPeerIsLive) {
767
+ throw new Error(
768
+ `Bound recipient ${binding.toName} (${binding.toChildId}, ` +
769
+ `session ${binding.toSessionFile}) is no longer live — it has ` +
770
+ `died or been superseded. Message NOT delivered; no retarget — ` +
771
+ `this logical send stays pinned to its original recipient.`,
772
+ )
773
+ }
774
+ const sent = sendPeerMessage({
775
+ toChildId: binding.toChildId,
776
+ from: identity,
777
+ message: params.message,
778
+ resultRef: params.resultRef,
779
+ })
780
+ // AIDEV-NOTE (PMR-ZJCP): mark-after-effect — memo written only after
781
+ // the send is durable, so a memo hit is trustworthy evidence. The
782
+ // send→memo crash window is covered by the bound-inbox evidence scan.
783
+ writeEffectMemo({
784
+ version: 1,
785
+ childId: identity.childId,
786
+ tool: 'message_peer',
787
+ fingerprint,
788
+ createdAt: new Date().toISOString(),
789
+ result: { messageId: sent.messageId, path: sent.path },
790
+ })
791
+ touchPeerBinding(binding)
792
+ return {
793
+ content: [
794
+ {
795
+ type: 'text',
796
+ text: `Message delivered to ${binding.toName} (${binding.toChildId}). You can keep working — the peer will pick it up as its next turn.`,
797
+ },
798
+ ],
799
+ details: { messageId: sent.messageId, path: sent.path },
800
+ }
801
+ }
802
+ const existingBinding = readPeerBinding(identity.childId, fingerprint)
803
+ if (existingBinding !== null) {
804
+ return deliverViaBinding(existingBinding)
805
+ }
806
+ const target = resolvePeer(params.peer, identity)
807
+ if (target.self) {
808
+ throw new Error('Cannot message yourself — just continue working.')
809
+ }
810
+ // AIDEV-NOTE (PMR-77KT): durable-first — the binding is written BEFORE
811
+ // any inbox scan or send. A send we cannot durably pin does not happen
812
+ // (write failures propagate). EEXIST means another writer (or a prior
813
+ // crashed attempt) won the bind: re-read and join the bound path with
814
+ // full request-identity validation instead of overwriting.
815
+ const now = new Date().toISOString()
816
+ const binding: PeerRecipientBinding = {
817
+ version: 1,
818
+ childId: identity.childId,
819
+ fingerprint,
820
+ toChildId: target.childId,
821
+ toSessionFile: target.sessionFile,
822
+ toName: target.name,
823
+ request: {
824
+ peer: params.peer,
825
+ message: params.message,
826
+ resultRef: params.resultRef,
827
+ },
828
+ createdAt: now,
829
+ lastActivityAt: now,
830
+ }
831
+ const wrote = writePeerBinding(binding)
832
+ if (!wrote) {
833
+ const winner = readPeerBinding(identity.childId, fingerprint)
834
+ if (winner === null) {
835
+ throw new Error(
836
+ `Peer binding write raced with an unreadable record for ` +
837
+ `fingerprint ${fingerprint}. Message NOT delivered; no retarget.`,
838
+ )
839
+ }
840
+ return deliverViaBinding(winner)
841
+ }
842
+ return deliverViaBinding(binding)
843
+ },
844
+ })
845
+
846
+ pi.on('session_start', (_event, ctx) => {
847
+ recorder.sessionStart()
848
+ // Publish peer presence (PMR-98S6): the record lives exactly as long as
849
+ // our process-lock claim; release removes it on shutdown.
850
+ const peerIdentity = childIdentity()
851
+ if (peerIdentity && !releasePresence) {
852
+ try {
853
+ releasePresence = publishPresence(peerIdentity)
854
+ } catch {
855
+ // Presence is best-effort — list_peers just won't include us.
856
+ }
857
+ }
858
+ const tools = pi.getAllTools()
859
+ toolNames = tools.map((t) => t.name).sort()
860
+ denied = parseDeniedTools(deniedToolsValue)
861
+
862
+ renderWidget(ctx, null)
863
+ })
864
+
865
+ pi.on('input', () => {
866
+ recorder.input()
867
+ // Ignore the initial task message that starts an autonomous subagent.
868
+ // Only inputs after the first agent run has started count as user takeover.
869
+ if (!shouldMarkUserTookOver(agentStarted)) return
870
+ userTookOver = true
871
+ })
872
+
873
+ pi.on('before_agent_start', () => {
874
+ recorder.beforeAgentStart()
875
+ })
876
+
877
+ pi.on('agent_start', () => {
878
+ agentStarted = true
879
+ recorder.agentStart()
880
+ })
881
+
882
+ pi.on('agent_end', (event, ctx) => {
883
+ const messages = (event as any).messages as any[] | undefined
884
+
885
+ // Request/ack handshake: if the parent just interrupted us, confirm via
886
+ // the `.ack` sidecar. Best effort — the parent falls back to
887
+ // fire-and-forget on timeout, so a failed ack write is never fatal.
888
+ const lastStopReason = findLastStopReason(messages)
889
+ if (lastStopReason) {
890
+ tryAckInterrupt(lastStopReason)
891
+ }
892
+
893
+ const shouldExit =
894
+ autoExit && shouldAutoExitOnAgentEnd(userTookOver, messages)
895
+
896
+ if (shouldExit) {
897
+ // Surface the exit via the `.exit` sidecar so the parent's pollForExit
898
+ // fast path fires for clean completions too — not just errors or explicit
899
+ // subagent_done calls. Without this the parent depends on the fragile
900
+ // screen-sentinel scrape (see exitSidecarPayload note).
901
+ const sessionFile = process.env.PI_SUBAGENT_SESSION
902
+ if (sessionFile) {
903
+ try {
904
+ const payload = exitSidecarPayload(messages)
905
+ // Never overwrite an existing sidecar — subagent_done/caller_ping may
906
+ // have already written their own payload before shutdown.
907
+ const exitFile = `${sessionFile}.exit`
908
+ if (payload.type === 'error' || !existsSync(exitFile)) {
909
+ writeFileSync(exitFile, JSON.stringify(payload))
910
+ }
911
+ } catch {
912
+ // Best effort — even without the sidecar, watcher's session-file
913
+ // fallback can still recover the errorMessage.
914
+ }
915
+ }
916
+
917
+ recorder.agentEndDone()
918
+ ctx.shutdown()
919
+ return
920
+ }
921
+
922
+ recorder.agentEndWaiting()
923
+ if (autoExit) {
924
+ // Reset any recorded manual input marker. Auto-exit is decided by whether
925
+ // the latest agent turn completed normally, not by who initiated it.
926
+ userTookOver = false
927
+ }
928
+ })
929
+
930
+ pi.on('turn_start', (event) => {
931
+ recorder.turnStart((event as any).turnIndex)
932
+ })
933
+
934
+ pi.on('turn_end', (event) => {
935
+ recorder.turnEnd((event as any).turnIndex)
936
+ })
937
+
938
+ pi.on('before_provider_request', () => {
939
+ recorder.beforeProviderRequest()
940
+ })
941
+
942
+ pi.on('after_provider_response', () => {
943
+ recorder.afterProviderResponse()
944
+ })
945
+
946
+ pi.on('message_update', (event) => {
947
+ recorder.messageUpdate((event as any).assistantMessageEvent?.type)
948
+ })
949
+
950
+ pi.on('tool_execution_start', (event) => {
951
+ recorder.toolExecutionStart(
952
+ (event as any).toolCallId,
953
+ (event as any).toolName,
954
+ )
955
+ })
956
+
957
+ pi.on('tool_call', (event) => {
958
+ recorder.toolCall((event as any).toolCallId, (event as any).toolName)
959
+ })
960
+
961
+ pi.on('tool_execution_update', (event) => {
962
+ recorder.toolExecutionUpdate(
963
+ (event as any).toolCallId,
964
+ (event as any).toolName,
965
+ )
966
+ })
967
+
968
+ pi.on('tool_result', (event) => {
969
+ recorder.toolResult((event as any).toolCallId, (event as any).toolName)
970
+ })
971
+
972
+ pi.on('tool_execution_end', (event) => {
973
+ recorder.toolExecutionEnd(
974
+ (event as any).toolCallId,
975
+ (event as any).toolName,
976
+ )
977
+ })
978
+
979
+ pi.on('session_shutdown', (event) => {
980
+ recorder.sessionShutdown((event as any).reason)
981
+ if (releasePresence) {
982
+ try {
983
+ releasePresence()
984
+ } catch {}
985
+ releasePresence = null
986
+ }
987
+ })
988
+
989
+ // Toggle expand/collapse with Alt+J
990
+ pi.registerShortcut('alt+j', {
991
+ description: 'Toggle subagent tools widget',
992
+ handler: (ctx) => {
993
+ expanded = !expanded
994
+ renderWidget(ctx, null)
995
+ },
996
+ })
997
+
998
+ pi.registerTool({
999
+ name: 'caller_ping',
1000
+ label: 'Caller Ping',
1001
+ description:
1002
+ 'Send a help request to the parent agent and exit this session. ' +
1003
+ 'The parent will be notified with your message and can resume this session with a response. ' +
1004
+ "Use when you're stuck, need clarification, or need the parent to take action.",
1005
+ parameters: Type.Object({
1006
+ message: Type.String({ description: 'What you need help with' }),
1007
+ }),
1008
+ async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1009
+ const sessionFile = process.env.PI_SUBAGENT_SESSION
1010
+ if (!sessionFile) {
1011
+ throw new Error(
1012
+ 'caller_ping is only available in subagent contexts. ' +
1013
+ 'PI_SUBAGENT_SESSION environment variable is not set.',
1014
+ )
1015
+ }
1016
+
1017
+ recorder.callerPing()
1018
+ // Memo identity falls back to the session file — caller_ping has never
1019
+ // required PI_SUBAGENT_ID, and availability is unchanged.
1020
+ const memoIdentity = process.env.PI_SUBAGENT_ID ?? sessionFile
1021
+ const fingerprint = effectFingerprint('caller_ping', memoIdentity, {
1022
+ message: params.message,
1023
+ })
1024
+ const exitFile = `${sessionFile}.exit`
1025
+ const parsed = parseExitPayload(exitFile)
1026
+
1027
+ if (parsed === null) {
1028
+ // AIDEV-NOTE (PMR-ZJCP): fresh path — no prior `.exit` payload, so
1029
+ // write it, memo the effect, and exit. Mirrors the auto-exit
1030
+ // never-overwrite convention (see agent_end handler): an existing
1031
+ // sidecar payload is never clobbered.
1032
+ const exitData = {
1033
+ type: 'ping' as const,
1034
+ name: process.env.PI_SUBAGENT_NAME ?? 'subagent',
1035
+ message: params.message,
1036
+ }
1037
+ writeFileSync(exitFile, JSON.stringify(exitData))
1038
+ writeEffectMemo({
1039
+ version: 1,
1040
+ childId: memoIdentity,
1041
+ tool: 'caller_ping',
1042
+ fingerprint,
1043
+ createdAt: new Date().toISOString(),
1044
+ result: {},
1045
+ })
1046
+ ctx.shutdown()
1047
+ return {
1048
+ content: [
1049
+ {
1050
+ type: 'text',
1051
+ text: 'Ping sent. Session will exit and parent will be notified.',
1052
+ },
1053
+ ],
1054
+ details: {},
1055
+ }
1056
+ }
1057
+
1058
+ if (parsed.type === 'ping' && parsed.message === params.message) {
1059
+ // AIDEV-NOTE (PMR-ZJCP): replay of an interrupted caller_ping — the
1060
+ // identical `.exit` payload IS the durable record of the earlier
1061
+ // ping (auto-exit never-overwrite convention). Leave the file
1062
+ // byte-identical; only ensure the effect memo exists.
1063
+ writeEffectMemo({
1064
+ version: 1,
1065
+ childId: memoIdentity,
1066
+ tool: 'caller_ping',
1067
+ fingerprint,
1068
+ createdAt: new Date().toISOString(),
1069
+ result: {},
1070
+ })
1071
+ ctx.shutdown()
1072
+ return {
1073
+ content: [
1074
+ {
1075
+ type: 'text',
1076
+ text:
1077
+ '[Replay of an interrupted call] Ping already recorded from ' +
1078
+ 'the previous run; exiting now.',
1079
+ },
1080
+ ],
1081
+ details: {},
1082
+ }
1083
+ }
1084
+
1085
+ // AIDEV-NOTE (PMR-ZJCP): conflict path — the `.exit` sidecar already
1086
+ // holds a different payload from an interrupted run. Per the auto-exit
1087
+ // never-overwrite convention we preserve it: overwriting would lose
1088
+ // that record. The session exits with the preserved payload and the
1089
+ // parent consumes it.
1090
+ ctx.shutdown()
1091
+ return {
1092
+ content: [
1093
+ {
1094
+ type: 'text',
1095
+ text:
1096
+ `The .exit sidecar already records a '${parsed.type}' payload ` +
1097
+ 'from an interrupted run; it was preserved (overwriting it ' +
1098
+ 'would lose that record). This session exits with it and the ' +
1099
+ 'parent will consume that payload.',
1100
+ },
1101
+ ],
1102
+ details: {},
1103
+ }
1104
+ },
1105
+ })
1106
+
1107
+ pi.registerTool({
1108
+ name: 'ask_owner',
1109
+ label: 'Ask Owner',
1110
+ description:
1111
+ 'Ask the parent agent a question WITHOUT ending this session. ' +
1112
+ 'The parent is woken immediately with your question and its answer arrives as your next user message; you continue the same session afterwards. ' +
1113
+ 'MUST be the only tool call in this turn and the last thing you do before ending the turn. ' +
1114
+ 'Only one outstanding ask at a time. Use for genuine blockers (missing decisions, unclear requirements); for final completion use subagent_done instead.',
1115
+ parameters: Type.Object({
1116
+ question: Type.String({ description: 'What you need from the owner' }),
1117
+ files: Type.Optional(
1118
+ Type.Array(Type.String(), {
1119
+ description: 'Relevant file paths, if any',
1120
+ }),
1121
+ ),
1122
+ }),
1123
+ // AIDEV-NOTE (PMR-WXG0): this extension is only loaded into Pi-backed
1124
+ // children, so Claude-CLI children can never call ask_owner — for them the
1125
+ // tool simply does not exist (their "unsupported" signal is the absent
1126
+ // tool; they finish with subagent_done semantics instead).
1127
+ // The sole+final rule is conveyed via description + the returned guidance
1128
+ // text; herdsman's harder eligibility gates do not transfer (multi-turn
1129
+ // resumable children).
1130
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
1131
+ const childId = process.env.PI_SUBAGENT_ID
1132
+ const sessionFile = process.env.PI_SUBAGENT_SESSION
1133
+ if (!childId || !sessionFile) {
1134
+ throw new Error(
1135
+ 'ask_owner is only available in subagent contexts. ' +
1136
+ 'PI_SUBAGENT_ID/PI_SUBAGENT_SESSION environment variables are not set.',
1137
+ )
1138
+ }
1139
+
1140
+ const guidanceText =
1141
+ 'Question delivered to the owner. End your turn NOW — do not ' +
1142
+ 'call any other tool. The answer will arrive as your next user ' +
1143
+ 'message and you continue this same session afterwards.'
1144
+
1145
+ const fingerprint = effectFingerprint('ask_owner', childId, {
1146
+ question: params.question,
1147
+ files: params.files,
1148
+ })
1149
+
1150
+ const live = readAskRecord(childId)
1151
+ const sidecar = readAskSidecar(sessionFile)
1152
+ let liveIsReplay = false
1153
+ if (
1154
+ live !== null &&
1155
+ live.sessionFile === sessionFile &&
1156
+ effectFingerprint('ask_owner', childId, {
1157
+ question: live.question,
1158
+ files: live.files,
1159
+ }) === fingerprint
1160
+ ) {
1161
+ liveIsReplay = true
1162
+ }
1163
+
1164
+ // AIDEV-NOTE (PMR-ZJCP): replay of an interrupted ask_owner — the live
1165
+ // ask record IS the evidence (written durably before the result could
1166
+ // persist). Return the original askId; never a second ask, never the
1167
+ // misleading outstanding-ask error. Sidecar heal writes the RECORD's
1168
+ // askId, never a new one.
1169
+ if (liveIsReplay && live !== null) {
1170
+ if (sidecar === null || sidecar.askId !== live.askId) {
1171
+ writeAskSidecar(sessionFile, live.askId)
1172
+ }
1173
+ writeEffectMemo({
1174
+ version: 1,
1175
+ childId,
1176
+ tool: 'ask_owner',
1177
+ fingerprint,
1178
+ createdAt: new Date().toISOString(),
1179
+ result: { askId: live.askId },
1180
+ })
1181
+ return {
1182
+ content: [
1183
+ {
1184
+ type: 'text',
1185
+ text: `[Replay of an interrupted call] ${guidanceText}`,
1186
+ },
1187
+ ],
1188
+ details: { askId: live.askId },
1189
+ }
1190
+ }
1191
+
1192
+ // One outstanding ask per child — fail closed on a second call.
1193
+ if (sidecar || live) {
1194
+ throw new Error(
1195
+ "You already have an outstanding ask. Wait for the owner's answer " +
1196
+ '(it arrives as your next user message) before asking again.',
1197
+ )
1198
+ }
1199
+
1200
+ const orphaned = readEffectMemo(childId, 'ask_owner', fingerprint)
1201
+
1202
+ const askId = randomUUID()
1203
+ const record = {
1204
+ askId,
1205
+ childId,
1206
+ name: process.env.PI_SUBAGENT_NAME,
1207
+ question: params.question,
1208
+ files: params.files,
1209
+ sessionFile,
1210
+ createdAt: new Date().toISOString(),
1211
+ }
1212
+ // Durable first, sidecar second: the parent's poller keys on the
1213
+ // sidecar, so it can only observe a fully-written record.
1214
+ writeAskRecord(record)
1215
+ writeAskSidecar(sessionFile, askId)
1216
+ // AIDEV-NOTE (PMR-ZJCP): orphan branch — an earlier identical ask ran
1217
+ // but its records were cleared by a formal resume, so its askId is dead.
1218
+ // Mark-after-effect: memo written only after the fresh ask is durable.
1219
+ // A stale memo from the wiped run is atomically replaced (rewrite).
1220
+ const memo = {
1221
+ version: 1 as const,
1222
+ childId,
1223
+ tool: 'ask_owner' as const,
1224
+ fingerprint,
1225
+ createdAt: new Date().toISOString(),
1226
+ result: { askId },
1227
+ }
1228
+ if (orphaned === null) {
1229
+ writeEffectMemo(memo)
1230
+ } else {
1231
+ rewriteEffectMemo(memo)
1232
+ }
1233
+ recorder.blockedAsking()
1234
+
1235
+ let text = guidanceText
1236
+ if (orphaned !== null) {
1237
+ // AIDEV-NOTE: PMR-TC54 — cause-neutral wording: the orphan branch
1238
+ // fires whenever a memo exists while live record/sidecar are gone,
1239
+ // which ALSO happens when an identical ask was answered+acked and
1240
+ // the child deliberately re-asks byte-identically — naming "resume"
1241
+ // as the cause could nudge the model to disregard that answer.
1242
+ const orphanNotice =
1243
+ `Note: an earlier ask_owner with this exact question already ran ` +
1244
+ `(askId ${orphaned.result.askId}) but is no longer live (its ` +
1245
+ 'records are gone); a fresh ask was created — treat this askId as ' +
1246
+ 'the active one. '
1247
+ text = `${orphanNotice}${guidanceText}`
1248
+ }
1249
+
1250
+ return {
1251
+ content: [
1252
+ {
1253
+ type: 'text',
1254
+ text,
1255
+ },
1256
+ ],
1257
+ details: { askId },
1258
+ }
1259
+ },
1260
+ })
1261
+
1262
+ pi.registerTool({
1263
+ // AIDEV-NOTE (PMR-QCVA): like ask_owner, this extension is only loaded
1264
+ // into Pi-backed children — Claude-CLI children never see message_owner
1265
+ // (absent tool is their unsupported signal). Fire-and-forget: the tool
1266
+ // writes a durable record and returns immediately; the parent drains it
1267
+ // on its 1s status loop. Never call ctx.shutdown or end the turn.
1268
+ name: 'message_owner',
1269
+ label: 'Message Owner',
1270
+ description:
1271
+ 'Send a durable message to the parent agent WITHOUT blocking and WITHOUT ' +
1272
+ 'ending the session: you keep working immediately and the parent picks it ' +
1273
+ 'up on its next refresh tick. Use for progress updates, findings, or ' +
1274
+ 'coordination that must not interrupt your run; for genuine blockers use ' +
1275
+ 'ask_owner, for final completion use subagent_done. Max 8 KiB per message.',
1276
+ parameters: Type.Object({
1277
+ message: Type.String({ description: 'Message body' }),
1278
+ }),
1279
+ async execute(_toolCallId, params, _signal, _onUpdate, _ctx) {
1280
+ const childId = process.env.PI_SUBAGENT_ID
1281
+ const parentSessionId = process.env.PI_SUBAGENT_PARENT_SESSION
1282
+ if (!childId || !parentSessionId) {
1283
+ throw new Error(
1284
+ 'message_owner is only available in subagent contexts. ' +
1285
+ 'PI_SUBAGENT_ID/PI_SUBAGENT_PARENT_SESSION environment variables are not set.',
1286
+ )
1287
+ }
1288
+ const deliveredText =
1289
+ 'Message delivered to the owner. Keep working — no response is ' +
1290
+ 'expected; the owner reads it on its next refresh tick.'
1291
+ const fingerprint = effectFingerprint('message_owner', childId, {
1292
+ message: params.message,
1293
+ })
1294
+ // AIDEV-NOTE (PMR-ZJCP): replay-safety for message_owner. Memo hit →
1295
+ // the earlier send already happened; replay the memoized messageId with
1296
+ // NO send and NO inbox mutation. Malformed memo results fail closed by
1297
+ // falling through to the inbox scan below.
1298
+ const memo = readEffectMemo(childId, 'message_owner', fingerprint)
1299
+ if (
1300
+ memo !== null &&
1301
+ typeof memo.result.messageId === 'string' &&
1302
+ typeof memo.result.path === 'string'
1303
+ ) {
1304
+ return {
1305
+ content: [
1306
+ {
1307
+ type: 'text',
1308
+ text: `[Replay of an interrupted call] ${deliveredText}`,
1309
+ },
1310
+ ],
1311
+ details: { messageId: memo.result.messageId, path: memo.result.path },
1312
+ }
1313
+ }
1314
+ // AIDEV-NOTE (PMR-ZJCP): W1 crash-window evidence scan — the inbox is
1315
+ // the source of truth when a send happened but the memo write was
1316
+ // interrupted. The scan matches on childId + exact content only
1317
+ // (OwnerMessage carries no resultRef); intentional byte-identical
1318
+ // resends are therefore suppressed — the documented cost of crash-safe
1319
+ // dedup.
1320
+ const delivered = readOwnerInbox(parentSessionId).find(
1321
+ (entry) =>
1322
+ entry.message.childId === childId &&
1323
+ entry.message.message === params.message,
1324
+ )
1325
+ if (delivered !== undefined) {
1326
+ writeEffectMemo({
1327
+ version: 1,
1328
+ childId,
1329
+ tool: 'message_owner',
1330
+ fingerprint,
1331
+ createdAt: new Date().toISOString(),
1332
+ result: {
1333
+ messageId: delivered.message.messageId,
1334
+ path: delivered.path,
1335
+ },
1336
+ })
1337
+ return {
1338
+ content: [
1339
+ {
1340
+ type: 'text',
1341
+ text:
1342
+ `An identical message was already delivered earlier ` +
1343
+ `(messageId ${delivered.message.messageId}); no duplicate ` +
1344
+ 'send was made.',
1345
+ },
1346
+ ],
1347
+ details: {
1348
+ messageId: delivered.message.messageId,
1349
+ path: delivered.path,
1350
+ },
1351
+ }
1352
+ }
1353
+ const sent = sendOwnerMessage({
1354
+ parentSessionId,
1355
+ childId,
1356
+ name: subagentName || childId,
1357
+ message: params.message,
1358
+ })
1359
+ // AIDEV-NOTE (PMR-ZJCP): mark-after-effect — memo written only after
1360
+ // the send is durable, so a memo hit is trustworthy evidence.
1361
+ writeEffectMemo({
1362
+ version: 1,
1363
+ childId,
1364
+ tool: 'message_owner',
1365
+ fingerprint,
1366
+ createdAt: new Date().toISOString(),
1367
+ result: { messageId: sent.messageId, path: sent.path },
1368
+ })
1369
+ return {
1370
+ content: [
1371
+ {
1372
+ type: 'text',
1373
+ text: deliveredText,
1374
+ },
1375
+ ],
1376
+ details: { messageId: sent.messageId, path: sent.path },
1377
+ }
1378
+ },
1379
+ })
1380
+
1381
+ pi.registerTool({
1382
+ name: 'subagent_done',
1383
+ label: 'Subagent Done',
1384
+ description:
1385
+ 'Call this tool when you have completed your task. ' +
1386
+ 'It will close this session and return your results to the main session. ' +
1387
+ 'Your LAST assistant message before calling this becomes the summary returned to the caller.',
1388
+ parameters: Type.Object({}),
1389
+ async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
1390
+ const sessionFile = process.env.PI_SUBAGENT_SESSION
1391
+ recorder.subagentDone()
1392
+ // AIDEV-NOTE (PMR-ZJCP): the result text reports the exit-effect
1393
+ // outcome explicitly (D5 — replay awareness returns results, never
1394
+ // throws); the fresh path keeps today's text verbatim.
1395
+ let text = 'Shutting down subagent session.'
1396
+ if (sessionFile) {
1397
+ // Memo identity falls back to the session file; params are empty for
1398
+ // this tool, so the fingerprint covers `{}`.
1399
+ const memoIdentity = process.env.PI_SUBAGENT_ID ?? sessionFile
1400
+ const fingerprint = effectFingerprint('subagent_done', memoIdentity, {})
1401
+ const exitFile = `${sessionFile}.exit`
1402
+ const parsed = parseExitPayload(exitFile)
1403
+
1404
+ if (parsed === null) {
1405
+ // AIDEV-NOTE (PMR-ZJCP): fresh path — no prior `.exit` payload;
1406
+ // write it and memo the effect (auto-exit never-overwrite
1407
+ // convention: an existing sidecar is never clobbered).
1408
+ writeFileSync(exitFile, JSON.stringify({ type: 'done' }))
1409
+ writeEffectMemo({
1410
+ version: 1,
1411
+ childId: memoIdentity,
1412
+ tool: 'subagent_done',
1413
+ fingerprint,
1414
+ createdAt: new Date().toISOString(),
1415
+ result: {},
1416
+ })
1417
+ } else if (parsed.type === 'done') {
1418
+ // AIDEV-NOTE (PMR-ZJCP): replay of an interrupted subagent_done —
1419
+ // the identical `.exit` payload IS the durable record of the
1420
+ // earlier done (auto-exit never-overwrite convention). Leave the
1421
+ // file byte-identical; only ensure the effect memo exists.
1422
+ writeEffectMemo({
1423
+ version: 1,
1424
+ childId: memoIdentity,
1425
+ tool: 'subagent_done',
1426
+ fingerprint,
1427
+ createdAt: new Date().toISOString(),
1428
+ result: {},
1429
+ })
1430
+ text =
1431
+ '[Replay of an interrupted call] Done already recorded from the ' +
1432
+ 'previous run; exiting now.'
1433
+ } else {
1434
+ // AIDEV-NOTE (PMR-ZJCP): conflict path — a different payload is
1435
+ // already recorded from an interrupted run; preserve it per the
1436
+ // auto-exit never-overwrite convention. The parent consumes that
1437
+ // payload when the session exits.
1438
+ text =
1439
+ `The .exit sidecar already records a '${parsed.type}' payload ` +
1440
+ 'from an interrupted run; it was preserved (overwriting it ' +
1441
+ 'would lose that record). This session exits with it and the ' +
1442
+ 'parent will consume that payload.'
1443
+ }
1444
+ }
1445
+ ctx.shutdown()
1446
+ return {
1447
+ content: [{ type: 'text', text }],
1448
+ details: {},
1449
+ }
1450
+ },
1451
+ })
1452
+ }