@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.
- package/LICENSE +21 -0
- package/README.md +462 -2
- package/agents/claude-code.md +23 -0
- package/agents/planner.md +569 -0
- package/agents/reviewer.md +152 -0
- package/agents/scout.md +112 -0
- package/agents/visual-tester.md +202 -0
- package/agents/worker.md +109 -0
- package/config.json.example +6 -0
- package/config.schema.json +71 -0
- package/package.json +59 -4
- package/pi-extension/subagents/activity.ts +730 -0
- package/pi-extension/subagents/asks.ts +234 -0
- package/pi-extension/subagents/assignments.ts +395 -0
- package/pi-extension/subagents/config.ts +191 -0
- package/pi-extension/subagents/control.ts +172 -0
- package/pi-extension/subagents/dataroot.ts +52 -0
- package/pi-extension/subagents/delivered.ts +81 -0
- package/pi-extension/subagents/flow-env.ts +112 -0
- package/pi-extension/subagents/herdr.ts +323 -0
- package/pi-extension/subagents/inbox.ts +213 -0
- package/pi-extension/subagents/index.ts +5003 -0
- package/pi-extension/subagents/lock.ts +318 -0
- package/pi-extension/subagents/peer-bindings.ts +175 -0
- package/pi-extension/subagents/peers.ts +401 -0
- package/pi-extension/subagents/plan-skill.md +219 -0
- package/pi-extension/subagents/plugin/.claude-plugin/plugin.json +5 -0
- package/pi-extension/subagents/plugin/hooks/hooks.json +15 -0
- package/pi-extension/subagents/plugin/hooks/on-stop.sh +68 -0
- package/pi-extension/subagents/retention.ts +918 -0
- package/pi-extension/subagents/retirement.ts +216 -0
- package/pi-extension/subagents/session.ts +194 -0
- package/pi-extension/subagents/snapshot.ts +151 -0
- package/pi-extension/subagents/spawn.ts +237 -0
- package/pi-extension/subagents/spawnseq.ts +116 -0
- package/pi-extension/subagents/state-events.ts +152 -0
- package/pi-extension/subagents/status.ts +886 -0
- package/pi-extension/subagents/store.ts +245 -0
- package/pi-extension/subagents/subagent-done.ts +1452 -0
- package/pi-extension/subagents/surface.ts +365 -0
- package/pi-extension/subagents/task-composition.ts +113 -0
- package/pi-extension/subagents/tool-effects.ts +203 -0
- package/pi-extension/subagents/usage.ts +330 -0
- package/pi-extension/subagents/watermark.ts +126 -0
- package/pi-extension/subagents/worktrees.ts +147 -0
- package/skills/subagent-orchestration/SKILL.md +57 -0
|
@@ -0,0 +1,330 @@
|
|
|
1
|
+
// Token/cost usage accounting (PMR-874G). Ported from pi-herdsman's
|
|
2
|
+
// project-usage rollup (Apache-2.0): usage is summed from Pi-native session
|
|
3
|
+
// jsonl entries (assistant messages, toolResult summaries, branch_summary /
|
|
4
|
+
// compaction entries) — the same attribution rules as pi's own
|
|
5
|
+
// core/usage-totals.js. The rollup is display-only; the session file stays
|
|
6
|
+
// the authority. COVERAGE DISCIPLINE: when a session's usage is unavailable
|
|
7
|
+
// (unreadable file, no usage blocks) we surface a coverage flag, never a
|
|
8
|
+
// guessed number.
|
|
9
|
+
//
|
|
10
|
+
// AIDEV-NOTE (PMR-8MQH): NODE-ONLY DAEMON SURFACE. This file is exported as
|
|
11
|
+
// the `@gtheys/pi-interactive-subagents/usage` subpath (see package.json
|
|
12
|
+
// `exports`) and is module-imported by the pi-flow daemon
|
|
13
|
+
// (packages/pi-flow/server/daemon.ts), which runs in its own process with no
|
|
14
|
+
// pi extension runtime. Keep it that way: node built-ins only, and never
|
|
15
|
+
// import the root extension index (`./index.ts`) from here. The import graph is
|
|
16
|
+
// locked by test/subpath-exports.test.ts.
|
|
17
|
+
import { closeSync, openSync, readSync, statSync } from 'node:fs'
|
|
18
|
+
|
|
19
|
+
/** Session-accumulated token + cost totals (cost in USD). */
|
|
20
|
+
export interface UsageTotals {
|
|
21
|
+
input: number
|
|
22
|
+
output: number
|
|
23
|
+
cacheRead: number
|
|
24
|
+
cacheWrite: number
|
|
25
|
+
cost: number
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface UsageSummary {
|
|
29
|
+
totals: UsageTotals
|
|
30
|
+
/** False when no entry carried a usage block — never show invented zeros. */
|
|
31
|
+
sawUsage: boolean
|
|
32
|
+
/**
|
|
33
|
+
* AIDEV-NOTE (PMR-NRH8): assistant models in first-seen order. Optional for
|
|
34
|
+
* legacy record-projected summaries; model-less push bodies stay byte-stable.
|
|
35
|
+
*/
|
|
36
|
+
models?: Set<string>
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function createUsageSummary(): UsageSummary {
|
|
40
|
+
return {
|
|
41
|
+
totals: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 },
|
|
42
|
+
sawUsage: false,
|
|
43
|
+
models: new Set<string>(),
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function totalTokens(totals: UsageTotals): number {
|
|
48
|
+
return totals.input + totals.output + totals.cacheRead + totals.cacheWrite
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function num(value: unknown): number {
|
|
52
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : 0
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// AIDEV-NOTE: mirrors pi's core/usage-totals.js attribution — assistant
|
|
56
|
+
// messages, toolResult summaries, and branch_summary/compaction entries can
|
|
57
|
+
// all carry usage. Anything else is ignored. Fail closed on malformed
|
|
58
|
+
// shapes: partial data still counts, a crash never does.
|
|
59
|
+
function addUsageBlock(summary: UsageSummary, usage: unknown): void {
|
|
60
|
+
if (usage == null || typeof usage !== 'object') return
|
|
61
|
+
const u = usage as Record<string, unknown>
|
|
62
|
+
const cost = u.cost as Record<string, unknown> | undefined
|
|
63
|
+
summary.totals.input += num(u.input)
|
|
64
|
+
summary.totals.output += num(u.output)
|
|
65
|
+
summary.totals.cacheRead += num(u.cacheRead)
|
|
66
|
+
summary.totals.cacheWrite += num(u.cacheWrite)
|
|
67
|
+
summary.totals.cost += num(cost?.total)
|
|
68
|
+
summary.sawUsage = true
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Add one parsed session entry's usage (if any) to the summary. Pure. */
|
|
72
|
+
export function addEntryUsage(summary: UsageSummary, entry: unknown): void {
|
|
73
|
+
if (entry == null || typeof entry !== 'object') return
|
|
74
|
+
const e = entry as Record<string, unknown>
|
|
75
|
+
if (e.type === 'message') {
|
|
76
|
+
const message = e.message as Record<string, unknown> | undefined
|
|
77
|
+
if (message == null) return
|
|
78
|
+
if (message.role === 'assistant' && typeof message.model === 'string') {
|
|
79
|
+
if (summary.models === undefined) summary.models = new Set<string>()
|
|
80
|
+
summary.models.add(message.model)
|
|
81
|
+
}
|
|
82
|
+
if (message.role === 'assistant' || message.role === 'toolResult') {
|
|
83
|
+
addUsageBlock(summary, message.usage)
|
|
84
|
+
}
|
|
85
|
+
return
|
|
86
|
+
}
|
|
87
|
+
if (e.type === 'branch_summary' || e.type === 'compaction') {
|
|
88
|
+
addUsageBlock(summary, e.usage)
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Pure summarizer over parsed session entries (unit-tested with fixtures). */
|
|
93
|
+
export function summarizeEntriesUsage(
|
|
94
|
+
entries: readonly unknown[],
|
|
95
|
+
): UsageSummary {
|
|
96
|
+
const summary = createUsageSummary()
|
|
97
|
+
for (const entry of entries) {
|
|
98
|
+
addEntryUsage(summary, entry)
|
|
99
|
+
}
|
|
100
|
+
return summary
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Full-file usage read for one session jsonl. Null when the file is missing
|
|
105
|
+
* or unreadable (coverage gap — caller shows the flag, not a zero).
|
|
106
|
+
*/
|
|
107
|
+
export function readSessionUsage(sessionFile: string): UsageSummary | null {
|
|
108
|
+
let size: number
|
|
109
|
+
try {
|
|
110
|
+
size = statSync(sessionFile).size
|
|
111
|
+
} catch {
|
|
112
|
+
return null
|
|
113
|
+
}
|
|
114
|
+
const tracker = createSessionUsageTracker()
|
|
115
|
+
updateSessionUsageTracker(tracker, sessionFile, size)
|
|
116
|
+
return tracker.summary
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Incremental append-only reader state. Session jsonl files only grow, so
|
|
121
|
+
* the 1s status loop reparses just the new bytes per tick instead of the
|
|
122
|
+
* whole file (same discipline as the activity-file reads).
|
|
123
|
+
*/
|
|
124
|
+
export interface SessionUsageTracker {
|
|
125
|
+
/** Byte offset of the first unparsed byte. */
|
|
126
|
+
offset: number
|
|
127
|
+
summary: UsageSummary
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function createSessionUsageTracker(): SessionUsageTracker {
|
|
131
|
+
return { offset: 0, summary: createUsageSummary() }
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// AIDEV-NOTE: only COMPLETE lines are consumed (offset stops after the last
|
|
135
|
+
// newline) — a mid-write line is picked up on the next tick, never parsed
|
|
136
|
+
// half-written. File shrink (truncate/rotate — not expected for session
|
|
137
|
+
// jsonl) resets the tracker rather than double-counting from a stale offset.
|
|
138
|
+
export function updateSessionUsageTracker(
|
|
139
|
+
tracker: SessionUsageTracker,
|
|
140
|
+
sessionFile: string,
|
|
141
|
+
knownSize?: number,
|
|
142
|
+
): void {
|
|
143
|
+
let size: number
|
|
144
|
+
if (knownSize !== undefined) {
|
|
145
|
+
size = knownSize
|
|
146
|
+
} else {
|
|
147
|
+
try {
|
|
148
|
+
size = statSync(sessionFile).size
|
|
149
|
+
} catch {
|
|
150
|
+
return
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (size < tracker.offset) {
|
|
154
|
+
tracker.offset = 0
|
|
155
|
+
tracker.summary = createUsageSummary()
|
|
156
|
+
}
|
|
157
|
+
if (size === tracker.offset) return
|
|
158
|
+
|
|
159
|
+
let chunk: string
|
|
160
|
+
let fd: number
|
|
161
|
+
try {
|
|
162
|
+
fd = openSync(sessionFile, 'r')
|
|
163
|
+
} catch {
|
|
164
|
+
return
|
|
165
|
+
}
|
|
166
|
+
try {
|
|
167
|
+
const buffer = Buffer.alloc(size - tracker.offset)
|
|
168
|
+
const bytesRead = readSync(fd, buffer, 0, buffer.length, tracker.offset)
|
|
169
|
+
chunk = buffer.toString('utf8', 0, bytesRead)
|
|
170
|
+
} catch {
|
|
171
|
+
return
|
|
172
|
+
} finally {
|
|
173
|
+
closeSync(fd)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const lastNewline = chunk.lastIndexOf('\n')
|
|
177
|
+
if (lastNewline === -1) return
|
|
178
|
+
const complete = chunk.slice(0, lastNewline)
|
|
179
|
+
tracker.offset += Buffer.byteLength(complete, 'utf8') + 1
|
|
180
|
+
for (const line of complete.split('\n')) {
|
|
181
|
+
if (!line.trim()) continue
|
|
182
|
+
try {
|
|
183
|
+
addEntryUsage(tracker.summary, JSON.parse(line))
|
|
184
|
+
} catch {
|
|
185
|
+
// AIDEV-NOTE: one malformed line must not lose the whole chunk —
|
|
186
|
+
// skip it (coverage is already best-effort display data).
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** Compact one-liner, e.g. `12.3k tok $0.0420`. Cost omitted when zero. */
|
|
192
|
+
export function formatUsageCompact(totals: UsageTotals): string {
|
|
193
|
+
const tokens = totalTokens(totals)
|
|
194
|
+
let tok: string
|
|
195
|
+
if (tokens >= 1_000_000) {
|
|
196
|
+
tok = `${(tokens / 1_000_000).toFixed(1)}M`
|
|
197
|
+
} else if (tokens >= 1000) {
|
|
198
|
+
tok = `${(tokens / 1000).toFixed(1)}k`
|
|
199
|
+
} else {
|
|
200
|
+
tok = String(tokens)
|
|
201
|
+
}
|
|
202
|
+
if (totals.cost <= 0) return `${tok} tok`
|
|
203
|
+
let cost: string
|
|
204
|
+
if (totals.cost < 1) {
|
|
205
|
+
cost = totals.cost.toFixed(4)
|
|
206
|
+
} else {
|
|
207
|
+
cost = totals.cost.toFixed(2)
|
|
208
|
+
}
|
|
209
|
+
return `${tok} tok $${cost}`
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Parent session file from a session jsonl header (first line). Used to
|
|
214
|
+
* build the ownership graph for the transitive rollup (PMR-874G). Reads
|
|
215
|
+
* only the first chunk — session files grow to MBs. Null on any failure.
|
|
216
|
+
*/
|
|
217
|
+
export function readSessionParentFile(sessionFile: string): string | null {
|
|
218
|
+
let fd: number
|
|
219
|
+
try {
|
|
220
|
+
fd = openSync(sessionFile, 'r')
|
|
221
|
+
} catch {
|
|
222
|
+
return null
|
|
223
|
+
}
|
|
224
|
+
let firstLine: string
|
|
225
|
+
try {
|
|
226
|
+
const buffer = Buffer.alloc(8192)
|
|
227
|
+
const bytesRead = readSync(fd, buffer, 0, buffer.length, 0)
|
|
228
|
+
const chunk = buffer.toString('utf8', 0, bytesRead)
|
|
229
|
+
const newline = chunk.indexOf('\n')
|
|
230
|
+
if (newline === -1) return null
|
|
231
|
+
firstLine = chunk.slice(0, newline)
|
|
232
|
+
} catch {
|
|
233
|
+
return null
|
|
234
|
+
} finally {
|
|
235
|
+
closeSync(fd)
|
|
236
|
+
}
|
|
237
|
+
try {
|
|
238
|
+
const header = JSON.parse(firstLine) as Record<string, unknown>
|
|
239
|
+
if (header.type !== 'session') return null
|
|
240
|
+
if (typeof header.parentSession !== 'string') return null
|
|
241
|
+
return header.parentSession
|
|
242
|
+
} catch {
|
|
243
|
+
return null
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** One node of the ownership graph used for the transitive rollup. */
|
|
248
|
+
export interface UsageOwnershipNode {
|
|
249
|
+
childId: string
|
|
250
|
+
sessionFile: string
|
|
251
|
+
/** Parent session file from the child session header; null for roots. */
|
|
252
|
+
parentSessionFile: string | null
|
|
253
|
+
/** Null when this node's usage is unavailable (coverage gap). */
|
|
254
|
+
summary: UsageSummary | null
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
export interface UsageRollup {
|
|
258
|
+
/** Self + all transitive descendants. */
|
|
259
|
+
totals: UsageTotals
|
|
260
|
+
/** True when any node in the subtree lacked usage data. */
|
|
261
|
+
incomplete: boolean
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// AIDEV-NOTE: herdsman's project-usage rollup — walk the ownership graph
|
|
265
|
+
// (child session `parentSession` headers + assignment records), sum self +
|
|
266
|
+
// descendants. Cycle-guarded: a malformed graph (A parents B parents A)
|
|
267
|
+
// terminates with the subtree marked incomplete, never an infinite loop or
|
|
268
|
+
// double count.
|
|
269
|
+
export function rollupUsageByOwnership(
|
|
270
|
+
nodes: readonly UsageOwnershipNode[],
|
|
271
|
+
): Map<string, UsageRollup> {
|
|
272
|
+
const bySession = new Map<string, UsageOwnershipNode>()
|
|
273
|
+
for (const node of nodes) {
|
|
274
|
+
bySession.set(node.sessionFile, node)
|
|
275
|
+
}
|
|
276
|
+
const rollups = new Map<string, UsageRollup>()
|
|
277
|
+
|
|
278
|
+
function accumulate(
|
|
279
|
+
node: UsageOwnershipNode,
|
|
280
|
+
visiting: Set<string>,
|
|
281
|
+
): UsageRollup {
|
|
282
|
+
const cached = rollups.get(node.childId)
|
|
283
|
+
if (cached) return cached
|
|
284
|
+
if (visiting.has(node.sessionFile)) {
|
|
285
|
+
return {
|
|
286
|
+
totals: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 },
|
|
287
|
+
incomplete: true,
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
visiting.add(node.sessionFile)
|
|
291
|
+
const totals: UsageTotals = {
|
|
292
|
+
input: 0,
|
|
293
|
+
output: 0,
|
|
294
|
+
cacheRead: 0,
|
|
295
|
+
cacheWrite: 0,
|
|
296
|
+
cost: 0,
|
|
297
|
+
}
|
|
298
|
+
let incomplete = false
|
|
299
|
+
if (node.summary) {
|
|
300
|
+
totals.input += node.summary.totals.input
|
|
301
|
+
totals.output += node.summary.totals.output
|
|
302
|
+
totals.cacheRead += node.summary.totals.cacheRead
|
|
303
|
+
totals.cacheWrite += node.summary.totals.cacheWrite
|
|
304
|
+
totals.cost += node.summary.totals.cost
|
|
305
|
+
if (!node.summary.sawUsage) incomplete = true
|
|
306
|
+
} else {
|
|
307
|
+
incomplete = true
|
|
308
|
+
}
|
|
309
|
+
for (const child of nodes) {
|
|
310
|
+
if (child.parentSessionFile !== node.sessionFile) continue
|
|
311
|
+
if (child.childId === node.childId) continue
|
|
312
|
+
const sub = accumulate(child, visiting)
|
|
313
|
+
totals.input += sub.totals.input
|
|
314
|
+
totals.output += sub.totals.output
|
|
315
|
+
totals.cacheRead += sub.totals.cacheRead
|
|
316
|
+
totals.cacheWrite += sub.totals.cacheWrite
|
|
317
|
+
totals.cost += sub.totals.cost
|
|
318
|
+
if (sub.incomplete) incomplete = true
|
|
319
|
+
}
|
|
320
|
+
visiting.delete(node.sessionFile)
|
|
321
|
+
const rollup = { totals, incomplete }
|
|
322
|
+
rollups.set(node.childId, rollup)
|
|
323
|
+
return rollup
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
for (const node of nodes) {
|
|
327
|
+
accumulate(node, new Set())
|
|
328
|
+
}
|
|
329
|
+
return rollups
|
|
330
|
+
}
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
// Durable interrupt intent watermark (PMR-J3WY).
|
|
2
|
+
//
|
|
3
|
+
// `subagent_interrupt` is replay-sensitive: after a parent restart pi may
|
|
4
|
+
// re-execute the same logical tool call (same toolCallId) from session
|
|
5
|
+
// history. Without a durable watermark the replay would send a second Escape
|
|
6
|
+
// to whatever turn the child is running NOW and create a second pending
|
|
7
|
+
// control request.
|
|
8
|
+
//
|
|
9
|
+
// The watermark is keyed by the logical tool call id and records the identity
|
|
10
|
+
// (childId + sessionFile) plus the requestId of the control record the first
|
|
11
|
+
// execution wrote. It is claimed BEFORE the Escape keypress (mark-before-send)
|
|
12
|
+
// so the dangerous window — escape sent, result unrecorded, restart — closes:
|
|
13
|
+
// a replay observes the watermark and returns an idempotent result instead of
|
|
14
|
+
// re-sending.
|
|
15
|
+
//
|
|
16
|
+
// AIDEV-NOTE: fail-closed identity validation — a watermark naming a different
|
|
17
|
+
// childId/sessionFile than the resolved target means the same logical call now
|
|
18
|
+
// points at different work; the interrupt is refused, never re-targeted.
|
|
19
|
+
// AIDEV-NOTE: crash between claim and Escape suppresses the replay too (the
|
|
20
|
+
// intent is durable even when the send never happened) — we optimize for
|
|
21
|
+
// never double-sending over never missing a send.
|
|
22
|
+
// AIDEV-NOTE: markers are deliberately never cleaned up (same policy as
|
|
23
|
+
// delivered.ts); they are single small files keyed by a unique toolCallId.
|
|
24
|
+
import {
|
|
25
|
+
closeSync,
|
|
26
|
+
fsyncSync,
|
|
27
|
+
mkdirSync,
|
|
28
|
+
openSync,
|
|
29
|
+
readFileSync,
|
|
30
|
+
writeSync,
|
|
31
|
+
} from 'node:fs'
|
|
32
|
+
import { join } from 'node:path'
|
|
33
|
+
import { ensureSubagentsDataDir, subagentsDataRoot } from './dataroot.ts'
|
|
34
|
+
|
|
35
|
+
export interface InterruptWatermark {
|
|
36
|
+
toolCallId: string
|
|
37
|
+
childId: string
|
|
38
|
+
sessionFile: string
|
|
39
|
+
requestId: string
|
|
40
|
+
sentAt: string
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function sanitizeToolCallId(toolCallId: string): string {
|
|
44
|
+
const safe = toolCallId.replace(/[^A-Za-z0-9._-]/g, '_')
|
|
45
|
+
if (safe === '' || safe === '.' || safe === '..') return '_'
|
|
46
|
+
return safe
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Durable watermark path: `<dataRoot>/interrupts/<toolCallId>.json`. */
|
|
50
|
+
export function interruptWatermarkPath(
|
|
51
|
+
toolCallId: string,
|
|
52
|
+
root?: string,
|
|
53
|
+
): string {
|
|
54
|
+
return join(
|
|
55
|
+
ensureSubagentsDataDir('interrupts', root ?? subagentsDataRoot()),
|
|
56
|
+
`${sanitizeToolCallId(toolCallId)}.json`,
|
|
57
|
+
)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// AIDEV-NOTE: the watermark filename is a lossy sanitized key (non-
|
|
61
|
+
// [A-Za-z0-9._-] chars map to `_`, so distinct ids collide) — filename
|
|
62
|
+
// equality is NOT id equality. The stored toolCallId is the primary key and
|
|
63
|
+
// must match the requested id, otherwise the read fails closed (null).
|
|
64
|
+
/** Read a watermark; returns null when missing, malformed, not an object, or
|
|
65
|
+
* naming a different toolCallId than requested. */
|
|
66
|
+
export function readInterruptWatermark(
|
|
67
|
+
toolCallId: string,
|
|
68
|
+
root?: string,
|
|
69
|
+
): InterruptWatermark | null {
|
|
70
|
+
let raw: string
|
|
71
|
+
try {
|
|
72
|
+
raw = readFileSync(interruptWatermarkPath(toolCallId, root), 'utf8')
|
|
73
|
+
} catch {
|
|
74
|
+
return null
|
|
75
|
+
}
|
|
76
|
+
try {
|
|
77
|
+
const parsed = JSON.parse(raw) as unknown
|
|
78
|
+
if (parsed == null || typeof parsed !== 'object') return null
|
|
79
|
+
const record = parsed as Record<string, unknown>
|
|
80
|
+
if (typeof record.toolCallId !== 'string') return null
|
|
81
|
+
if (record.toolCallId !== toolCallId) return null
|
|
82
|
+
if (typeof record.childId !== 'string') return null
|
|
83
|
+
if (typeof record.sessionFile !== 'string') return null
|
|
84
|
+
if (typeof record.requestId !== 'string') return null
|
|
85
|
+
return parsed as InterruptWatermark
|
|
86
|
+
} catch {
|
|
87
|
+
return null
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** True when the watermark names this exact child and session file. */
|
|
92
|
+
export function interruptWatermarkMatches(
|
|
93
|
+
watermark: InterruptWatermark,
|
|
94
|
+
childId: string,
|
|
95
|
+
sessionFile: string,
|
|
96
|
+
): boolean {
|
|
97
|
+
return watermark.childId === childId && watermark.sessionFile === sessionFile
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Claim the watermark for a logical tool call. Exclusive create (atomic by
|
|
102
|
+
* construction — same discipline as delivered.ts markers): returns true when
|
|
103
|
+
* newly claimed (proceed with the send), false when it already exists (treat
|
|
104
|
+
* as a replay and re-read it).
|
|
105
|
+
*/
|
|
106
|
+
export function claimInterruptWatermark(
|
|
107
|
+
watermark: InterruptWatermark,
|
|
108
|
+
root?: string,
|
|
109
|
+
): boolean {
|
|
110
|
+
const marker = interruptWatermarkPath(watermark.toolCallId, root)
|
|
111
|
+
mkdirSync(join(marker, '..'), { recursive: true, mode: 0o700 })
|
|
112
|
+
let fd: number
|
|
113
|
+
try {
|
|
114
|
+
fd = openSync(marker, 'wx', 0o600)
|
|
115
|
+
} catch (error) {
|
|
116
|
+
if ((error as NodeJS.ErrnoException).code === 'EEXIST') return false
|
|
117
|
+
throw error
|
|
118
|
+
}
|
|
119
|
+
try {
|
|
120
|
+
writeSync(fd, JSON.stringify(watermark))
|
|
121
|
+
fsyncSync(fd)
|
|
122
|
+
} finally {
|
|
123
|
+
closeSync(fd)
|
|
124
|
+
}
|
|
125
|
+
return true
|
|
126
|
+
}
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process'
|
|
2
|
+
import { mkdirSync } from 'node:fs'
|
|
3
|
+
import { homedir } from 'node:os'
|
|
4
|
+
import { basename, dirname, join } from 'node:path'
|
|
5
|
+
|
|
6
|
+
// AIDEV-NOTE: Worktree placement for `subagent({worktree: true})` (PMR-11TD).
|
|
7
|
+
// Direct `git worktree add` — NO pi-flow/worktree import (cross-package runtime
|
|
8
|
+
// deps are repo-verboten), NO `herdr worktree` coupling. Creation is
|
|
9
|
+
// blocking+sync and runs BEFORE the tab spawn: a failed `git worktree add`
|
|
10
|
+
// means no tab, no partial state. Worktrees outlive their children — removal
|
|
11
|
+
// is manual (no auto-delete ever, per plan).
|
|
12
|
+
|
|
13
|
+
/** `worktree` param shape on the subagent tool: true or `{base?: string}`. */
|
|
14
|
+
export type WorktreeOption = boolean | { base?: string }
|
|
15
|
+
|
|
16
|
+
export interface CreatedWorktree {
|
|
17
|
+
path: string
|
|
18
|
+
branch: string
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Error from a failed git invocation during worktree setup. */
|
|
22
|
+
export class WorktreeError extends Error {
|
|
23
|
+
readonly stderr: string
|
|
24
|
+
|
|
25
|
+
constructor(message: string, stderr = '') {
|
|
26
|
+
super(message)
|
|
27
|
+
this.name = 'WorktreeError'
|
|
28
|
+
this.stderr = stderr
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
// AIDEV-NOTE: PMR-S6W3 — inside a git hook (e.g. lefthook pre-push) git
|
|
33
|
+
// exports repo-pointing vars (GIT_DIR, GIT_WORK_TREE, ...). This code
|
|
34
|
+
// resolves repos from explicit cwds via `git -C`, so those vars must never
|
|
35
|
+
// leak into child git calls — they override repo discovery and make every
|
|
36
|
+
// cwd look like a repo. Identity vars (GIT_AUTHOR_NAME etc.) are kept.
|
|
37
|
+
const GIT_REPO_ENV_VARS = [
|
|
38
|
+
'GIT_DIR',
|
|
39
|
+
'GIT_WORK_TREE',
|
|
40
|
+
'GIT_INDEX_FILE',
|
|
41
|
+
'GIT_COMMON_DIR',
|
|
42
|
+
'GIT_OBJECT_DIRECTORY',
|
|
43
|
+
'GIT_ALTERNATE_OBJECT_DIRECTORIES',
|
|
44
|
+
'GIT_NAMESPACE',
|
|
45
|
+
'GIT_PREFIX',
|
|
46
|
+
] as const
|
|
47
|
+
|
|
48
|
+
export function childGitEnv(): NodeJS.ProcessEnv {
|
|
49
|
+
const env: NodeJS.ProcessEnv = { ...process.env }
|
|
50
|
+
for (const name of GIT_REPO_ENV_VARS) {
|
|
51
|
+
delete env[name]
|
|
52
|
+
}
|
|
53
|
+
return env
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** Lowercase dash-slug; mirrors pi-flow/worktree's slugify rules (unexported). */
|
|
57
|
+
export function slugifyWorktree(text: string): string {
|
|
58
|
+
return text
|
|
59
|
+
.toLowerCase()
|
|
60
|
+
.replace(/[^a-z0-9\s-]/g, '')
|
|
61
|
+
.trim()
|
|
62
|
+
.replace(/[\s-]+/g, '-')
|
|
63
|
+
.replace(/^-+|-+$/g, '')
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Branch name for a worktree spawn: `subagent/<name-slug>-<ts>-<childId>`.
|
|
68
|
+
* The childId suffix guarantees uniqueness for same-second same-name spawns.
|
|
69
|
+
*/
|
|
70
|
+
export function deriveWorktreeBranch(
|
|
71
|
+
name: string,
|
|
72
|
+
childId: string,
|
|
73
|
+
now: Date = new Date(),
|
|
74
|
+
): string {
|
|
75
|
+
const pad = (n: number) => String(n).padStart(2, '0')
|
|
76
|
+
const ts =
|
|
77
|
+
`${now.getUTCFullYear()}${pad(now.getUTCMonth() + 1)}${pad(now.getUTCDate())}` +
|
|
78
|
+
`-${pad(now.getUTCHours())}${pad(now.getUTCMinutes())}${pad(now.getUTCSeconds())}`
|
|
79
|
+
const slug = slugifyWorktree(name).slice(0, 40) || 'agent'
|
|
80
|
+
return `subagent/${slug}-${ts}-${childId}`
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Worktree path convention: `$HOME/.herdr/worktrees/<repo-slug>/<branch-slug>`
|
|
85
|
+
* — the same layout herdr uses for its own workspaces, so manual cleanup and
|
|
86
|
+
* the pi-flow `worktree` tool's dashboard stay coherent. Branch slashes become dashes.
|
|
87
|
+
*/
|
|
88
|
+
export function worktreePathFor(mainRepoRoot: string, branch: string): string {
|
|
89
|
+
const repoSlug = basename(mainRepoRoot)
|
|
90
|
+
const branchSlug = branch.replace(/\//g, '-')
|
|
91
|
+
return join(homedir(), '.herdr', 'worktrees', repoSlug, branchSlug)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Absolute path of the MAIN checkout (not a linked worktree). Works when the
|
|
96
|
+
* caller itself runs inside a linked worktree: `--git-common-dir` always
|
|
97
|
+
* resolves to the main repo's `.git`.
|
|
98
|
+
*/
|
|
99
|
+
export function findMainRepoRoot(cwd: string): string {
|
|
100
|
+
let out: string
|
|
101
|
+
try {
|
|
102
|
+
out = execFileSync(
|
|
103
|
+
'git',
|
|
104
|
+
['-C', cwd, 'rev-parse', '--path-format=absolute', '--git-common-dir'],
|
|
105
|
+
{ encoding: 'utf8', env: childGitEnv() },
|
|
106
|
+
).trim()
|
|
107
|
+
} catch (err) {
|
|
108
|
+
const e = err as { stderr?: string | Buffer; message: string }
|
|
109
|
+
const stderr = e.stderr ? String(e.stderr).trim() : ''
|
|
110
|
+
throw new WorktreeError(
|
|
111
|
+
`not a git repository (cwd: ${cwd}): ${stderr || e.message}`,
|
|
112
|
+
stderr,
|
|
113
|
+
)
|
|
114
|
+
}
|
|
115
|
+
return dirname(out)
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Create a linked worktree + branch off the main checkout. Throws
|
|
120
|
+
* WorktreeError on any git failure — callers must treat this as fatal for
|
|
121
|
+
* the spawn (no tab, no partial state).
|
|
122
|
+
*/
|
|
123
|
+
export function createSubagentWorktree(options: {
|
|
124
|
+
cwd: string
|
|
125
|
+
branch: string
|
|
126
|
+
base?: string
|
|
127
|
+
}): CreatedWorktree {
|
|
128
|
+
const mainRoot = findMainRepoRoot(options.cwd)
|
|
129
|
+
const path = worktreePathFor(mainRoot, options.branch)
|
|
130
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
131
|
+
const args = ['-C', mainRoot, 'worktree', 'add', '-b', options.branch, path]
|
|
132
|
+
if (options.base) {
|
|
133
|
+
args.push(options.base)
|
|
134
|
+
}
|
|
135
|
+
try {
|
|
136
|
+
execFileSync('git', args, { encoding: 'utf8', env: childGitEnv() })
|
|
137
|
+
} catch (err) {
|
|
138
|
+
const e = err as { stderr?: string | Buffer; message: string }
|
|
139
|
+
const stderr = e.stderr ? String(e.stderr).trim() : ''
|
|
140
|
+
throw new WorktreeError(
|
|
141
|
+
`git worktree add failed (branch ${options.branch}, path ${path}): ` +
|
|
142
|
+
(stderr || e.message),
|
|
143
|
+
stderr,
|
|
144
|
+
)
|
|
145
|
+
}
|
|
146
|
+
return { path, branch: options.branch }
|
|
147
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: subagent-orchestration
|
|
3
|
+
description: Orchestrate background subagents effectively with pi-interactive-subagents. Use when a task benefits from parallel exploration, isolated implementation, long-running background work, or when you need to decide between ask_owner / caller_ping / message_owner, worktree:true, or resuming orphaned children. Trigger on "spawn agents", "parallel research", "background task", "delegate", "fan out", or when multiple independent investigations/implementations could run concurrently.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Subagent orchestration
|
|
7
|
+
|
|
8
|
+
The `subagent` tool returns immediately — children run in background herdr tabs.
|
|
9
|
+
The widget above the input shows live status, current activity, and token/cost
|
|
10
|
+
per child. Results steer back automatically; never poll or sleep waiting for
|
|
11
|
+
them — keep working or end your turn, the harness wakes you.
|
|
12
|
+
|
|
13
|
+
## When to spawn
|
|
14
|
+
|
|
15
|
+
- **Independent investigations** → fan out `scout` agents in parallel, one per
|
|
16
|
+
area. Synthesize when results steer back.
|
|
17
|
+
- AIDEV-NOTE: if the codegraph MCP is connected, run `codegraph sync` in
|
|
18
|
+
the target repo BEFORE fanning out scouts — parallel scouts never sync
|
|
19
|
+
(or init) the index themselves (lock races). If sync fails with
|
|
20
|
+
"CodeGraph not initialized", run `codegraph init -y` then sync. Name
|
|
21
|
+
`mcp__codegraph__codegraph_explore` in each scout task as the preferred
|
|
22
|
+
code-search tool.
|
|
23
|
+
- **Implementation while you continue** → `worker` in the background; review
|
|
24
|
+
when the result lands.
|
|
25
|
+
- **Any code-writing subagent in the main checkout** → `worktree: true` —
|
|
26
|
+
implementation ALWAYS runs in an isolated git worktree; the main checkout
|
|
27
|
+
is read-only for workers. Scout/investigation children are exempt.
|
|
28
|
+
- **Long-running watches** (test loops, deploy monitors) → background child +
|
|
29
|
+
`message_owner` updates.
|
|
30
|
+
|
|
31
|
+
## Choosing the communication channel
|
|
32
|
+
|
|
33
|
+
| Situation | Tool |
|
|
34
|
+
| --- | --- |
|
|
35
|
+
| Child needs an answer to proceed | `ask_owner` (blocks child; parent answers with `answer_subagent`; same session continues) |
|
|
36
|
+
| Child is done until further notice / stuck hard | `caller_ping` (child EXITS; parent resumes the session with guidance) |
|
|
37
|
+
| Progress note, no answer needed | `message_owner` (fire-and-forget) |
|
|
38
|
+
| Sibling coordination | `list_peers` + `message_peer` |
|
|
39
|
+
| Parent wants to stop a turn | `subagent_interrupt` (turn-level, ack-confirmed; session survives) |
|
|
40
|
+
|
|
41
|
+
## Rules of thumb
|
|
42
|
+
|
|
43
|
+
- Batch spawns: call `subagent` multiple times in one turn for true parallelism.
|
|
44
|
+
- Trust durable state, not screens: results, assignments, asks, and inboxes are
|
|
45
|
+
files under the extension data root; they survive parent restarts.
|
|
46
|
+
- After a parent restart, run `subagents_list` — orphaned children appear with
|
|
47
|
+
`subagent_resume` hints. Resume them instead of respawning from scratch.
|
|
48
|
+
- Respect `spawning` frontmatter: `manager-approval` agents can only be started
|
|
49
|
+
by the user via `/subagent <agent> <task>` — don't retry denied `subagent()`
|
|
50
|
+
calls; tell the user the command to run instead.
|
|
51
|
+
- ALWAYS pass `agent:` for role children — a display name like `Worker: X`
|
|
52
|
+
does NOT resolve the agent definition. The extension refuses the spawn with
|
|
53
|
+
a tool error telling you to pass `agent:` or rename without the role
|
|
54
|
+
prefix, because without `agent:` the child would get settings.json defaults
|
|
55
|
+
instead of the frontmatter model/skills/thinking.
|
|
56
|
+
- `fork: true` only when the child genuinely needs the parent's conversation
|
|
57
|
+
context — it costs tokens on every spawn.
|