@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,318 @@
1
+ // Ported from pi-herdsman (/tmp/pi-herdsman-scout/extension/lock.ts),
2
+ // Apache-2.0. Near-verbatim reimplementation of the {pid,id} claim-dir
3
+ // process lock: exclusive-create via rename, stale-PID takeover, claim
4
+ // generation, quarantine of stale claims.
5
+ import { createHash, randomUUID } from 'node:crypto'
6
+ import * as fs from 'node:fs'
7
+ import { tmpdir } from 'node:os'
8
+ import { basename, dirname, join } from 'node:path'
9
+
10
+ const UUID =
11
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
12
+
13
+ export class ProcessLockOccupiedError extends Error {
14
+ readonly code = 'PROCESS_LOCK_OCCUPIED'
15
+ }
16
+
17
+ export type ProcessLockClaim = { pid: number; id: string }
18
+
19
+ type ProcessLockLease = { claim: ProcessLockClaim; release: () => void }
20
+
21
+ type ProcessLockOptions = {
22
+ afterStaleOwnerRemoved?: () => void
23
+ name?: string
24
+ occupiedMessage?: string
25
+ }
26
+
27
+ /** Root for lock claim dirs in the OS temp dir. */
28
+ export function subagentsTempRoot(): string {
29
+ return join(tmpdir(), 'pi-subagents')
30
+ }
31
+
32
+ // AIDEV-NOTE: stable lock path for an arbitrary key (session path, agent id,
33
+ // ...). Hashing keeps filesystem-safe names and unbounded key length.
34
+ export function keyedProcessLockPath(key: string): string {
35
+ return join(
36
+ subagentsTempRoot(),
37
+ 'locks',
38
+ `lock-${createHash('sha256').update(key).digest('hex')}`,
39
+ )
40
+ }
41
+
42
+ export function isProcessLockClaim(value: unknown): value is ProcessLockClaim {
43
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return false
44
+ const claim = value as Record<string, unknown>
45
+ if (
46
+ Object.keys(claim).length !== 2 ||
47
+ !Object.hasOwn(claim, 'pid') ||
48
+ !Object.hasOwn(claim, 'id') ||
49
+ !Number.isInteger(claim.pid) ||
50
+ (claim.pid as number) <= 0 ||
51
+ typeof claim.id !== 'string' ||
52
+ !UUID.test(claim.id)
53
+ ) {
54
+ return false
55
+ }
56
+ return true
57
+ }
58
+
59
+ function readProcessLockClaim(path: string, owner: string): ProcessLockClaim {
60
+ const claim: unknown = JSON.parse(fs.readFileSync(join(path, owner), 'utf8'))
61
+ if (!isProcessLockClaim(claim) || owner !== `${claim.pid}-${claim.id}`) {
62
+ throw new Error('invalid process lock claim')
63
+ }
64
+ return claim
65
+ }
66
+
67
+ function processExists(pid: number): boolean {
68
+ try {
69
+ process.kill(pid, 0)
70
+ return true
71
+ } catch (error) {
72
+ if ((error as NodeJS.ErrnoException).code === 'ESRCH') return false
73
+ throw error
74
+ }
75
+ }
76
+
77
+ function publishClaim(
78
+ parent: string,
79
+ claimDir: string,
80
+ owner: string,
81
+ payload: string,
82
+ ): void {
83
+ // Publish the owner record before the canonical rename so observers never
84
+ // see an empty canonical lock.
85
+ const temporary = join(parent, `.${basename(claimDir)}.${randomUUID()}.tmp`)
86
+ fs.mkdirSync(temporary, 0o700)
87
+ const temporaryOwner = join(temporary, owner)
88
+ let fd: number | undefined
89
+ try {
90
+ fd = fs.openSync(temporaryOwner, 'wx', 0o600)
91
+ fs.writeSync(fd, payload)
92
+ fs.fsyncSync(fd)
93
+ fs.closeSync(fd)
94
+ fd = undefined
95
+ fs.chmodSync(temporaryOwner, 0o600)
96
+ fs.renameSync(temporary, claimDir)
97
+ } finally {
98
+ if (fd !== undefined) fs.closeSync(fd)
99
+ try {
100
+ fs.unlinkSync(temporaryOwner)
101
+ } catch (error) {
102
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
103
+ }
104
+ try {
105
+ fs.rmdirSync(temporary)
106
+ } catch (error) {
107
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
108
+ }
109
+ }
110
+ }
111
+
112
+ export function readLiveProcessLock(
113
+ path: string,
114
+ name = 'process lock',
115
+ ): ProcessLockClaim {
116
+ const { claim, live } = readProcessLockStatus(path, name)
117
+ if (!live) throw new Error(`Unable to verify ${name}`)
118
+ return claim
119
+ }
120
+
121
+ export function readProcessLockStatus(
122
+ path: string,
123
+ name = 'process lock',
124
+ ): { claim: ProcessLockClaim; live: boolean } {
125
+ const verifyMessage = `Unable to verify ${name}`
126
+ let entries: string[]
127
+ try {
128
+ entries = fs.readdirSync(path)
129
+ } catch (error) {
130
+ throw new Error(verifyMessage, { cause: error })
131
+ }
132
+ if (entries.length !== 1) throw new Error(verifyMessage)
133
+
134
+ const owner = entries[0]
135
+ try {
136
+ const claim = readProcessLockClaim(path, owner)
137
+ return { claim, live: processExists(claim.pid) }
138
+ } catch (error) {
139
+ throw new Error(verifyMessage, { cause: error })
140
+ }
141
+ }
142
+
143
+ export function acquireProcessLock(
144
+ path: string,
145
+ options: ProcessLockOptions = {},
146
+ ): ProcessLockLease {
147
+ const name = options.name ?? 'process lock'
148
+ const verifyMessage = `Unable to verify ${name}`
149
+ const occupiedMessage =
150
+ options.occupiedMessage ??
151
+ `${name[0].toUpperCase()}${name.slice(1)} is in progress`
152
+ const recoverMessage = `Unable to recover ${name}`
153
+ const parent = dirname(path)
154
+ fs.mkdirSync(parent, { recursive: true, mode: 0o700 })
155
+ fs.chmodSync(parent, 0o700)
156
+ const claimDir = path
157
+ const claim: ProcessLockClaim = { pid: process.pid, id: randomUUID() }
158
+ const owner = `${claim.pid}-${claim.id}`
159
+ const payload = JSON.stringify(claim)
160
+ const ownerPath = join(claimDir, owner)
161
+
162
+ // An empty canonical directory is ambiguous and must not be replaced.
163
+ try {
164
+ if (fs.readdirSync(claimDir).length === 0) throw new Error(verifyMessage)
165
+ } catch (error) {
166
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error
167
+ }
168
+
169
+ try {
170
+ // Publish the complete claim with one rename. In particular, never
171
+ // create the canonical directory before its owner record exists.
172
+ publishClaim(parent, claimDir, owner, payload)
173
+ } catch (error) {
174
+ const code = (error as NodeJS.ErrnoException).code
175
+ if (code !== 'EEXIST' && code !== 'ENOTEMPTY' && code !== 'EPERM') {
176
+ throw error
177
+ }
178
+ let entries: string[]
179
+ try {
180
+ entries = fs.readdirSync(claimDir)
181
+ } catch {
182
+ throw new Error(verifyMessage)
183
+ }
184
+ if (entries.length === 0) {
185
+ throw new Error(verifyMessage)
186
+ }
187
+ if (entries.length !== 1) throw new Error(verifyMessage)
188
+ const observedOwner = entries[0]
189
+ let staleClaim: ProcessLockClaim
190
+ try {
191
+ staleClaim = readProcessLockClaim(claimDir, observedOwner)
192
+ } catch {
193
+ throw new Error(verifyMessage)
194
+ }
195
+ try {
196
+ if (processExists(staleClaim.pid)) {
197
+ throw new ProcessLockOccupiedError(occupiedMessage)
198
+ }
199
+ } catch (err) {
200
+ if (err instanceof ProcessLockOccupiedError) throw err
201
+ throw new Error(verifyMessage, { cause: err })
202
+ }
203
+ // Move the complete, verified stale claim out of the canonical name in
204
+ // one operation. Never unlink the owner while leaving an empty
205
+ // canonical directory behind.
206
+ const quarantine = join(
207
+ parent,
208
+ `.${basename(claimDir)}.${randomUUID()}.stale`,
209
+ )
210
+ try {
211
+ const currentEntries = fs.readdirSync(claimDir)
212
+ if (currentEntries.length !== 1 || currentEntries[0] !== observedOwner) {
213
+ throw new ProcessLockOccupiedError(occupiedMessage)
214
+ }
215
+ const currentClaim = readProcessLockClaim(claimDir, observedOwner)
216
+ if (
217
+ currentClaim.pid !== staleClaim.pid ||
218
+ currentClaim.id !== staleClaim.id
219
+ ) {
220
+ throw new ProcessLockOccupiedError(occupiedMessage)
221
+ }
222
+ } catch (err) {
223
+ if (err instanceof ProcessLockOccupiedError) throw err
224
+ throw new Error(verifyMessage, { cause: err })
225
+ }
226
+ try {
227
+ fs.renameSync(claimDir, quarantine)
228
+ } catch (removeError) {
229
+ const code = (removeError as NodeJS.ErrnoException).code
230
+ if (code === 'ENOENT' || code === 'ENOTEMPTY' || code === 'EEXIST') {
231
+ throw new ProcessLockOccupiedError(occupiedMessage)
232
+ }
233
+ throw new Error(recoverMessage, { cause: removeError })
234
+ }
235
+
236
+ // A concurrent claimant may have won the canonical name while it was
237
+ // absent. Never clean up a quarantined directory unless it is still the
238
+ // exact stale claim that was verified above.
239
+ let quarantinedEntries: string[]
240
+ try {
241
+ quarantinedEntries = fs.readdirSync(quarantine)
242
+ } catch (err) {
243
+ throw new Error(recoverMessage, { cause: err })
244
+ }
245
+ if (
246
+ quarantinedEntries.length !== 1 ||
247
+ quarantinedEntries[0] !== observedOwner
248
+ ) {
249
+ throw new ProcessLockOccupiedError(occupiedMessage)
250
+ }
251
+ try {
252
+ const quarantinedClaim = readProcessLockClaim(quarantine, observedOwner)
253
+ if (
254
+ quarantinedClaim.pid !== staleClaim.pid ||
255
+ quarantinedClaim.id !== staleClaim.id
256
+ ) {
257
+ throw new ProcessLockOccupiedError(occupiedMessage)
258
+ }
259
+ } catch (err) {
260
+ if (err instanceof ProcessLockOccupiedError) throw err
261
+ throw new Error(verifyMessage, { cause: err })
262
+ }
263
+ options.afterStaleOwnerRemoved?.()
264
+ try {
265
+ fs.unlinkSync(join(quarantine, observedOwner))
266
+ fs.rmdirSync(quarantine)
267
+ } catch (cleanupError) {
268
+ throw new Error(recoverMessage, { cause: cleanupError })
269
+ }
270
+ try {
271
+ publishClaim(parent, claimDir, owner, payload)
272
+ } catch (err) {
273
+ const code = (err as NodeJS.ErrnoException).code
274
+ if (code === 'EEXIST' || code === 'ENOTEMPTY' || code === 'EPERM') {
275
+ throw new ProcessLockOccupiedError(occupiedMessage)
276
+ }
277
+ throw err
278
+ }
279
+ }
280
+ return {
281
+ claim,
282
+ release: () => releaseProcessLock(claimDir, ownerPath, claim, name),
283
+ }
284
+ }
285
+
286
+ export function claimProcessLock(
287
+ path: string,
288
+ options: ProcessLockOptions = {},
289
+ ): () => void {
290
+ return acquireProcessLock(path, options).release
291
+ }
292
+
293
+ function releaseProcessLock(
294
+ claimDir: string,
295
+ ownerPath: string,
296
+ claim: ProcessLockClaim,
297
+ name: string,
298
+ ): void {
299
+ let current: ProcessLockClaim
300
+ try {
301
+ current = readProcessLockClaim(claimDir, basename(ownerPath))
302
+ } catch (error) {
303
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return
304
+ throw new Error(`Unable to verify ${name} ownership`, { cause: error })
305
+ }
306
+ if (current.pid !== claim.pid || current.id !== claim.id) {
307
+ throw new Error(
308
+ `${name[0].toUpperCase()}${name.slice(1)} ownership changed`,
309
+ )
310
+ }
311
+ fs.unlinkSync(ownerPath)
312
+ try {
313
+ fs.rmdirSync(claimDir)
314
+ } catch (error) {
315
+ const code = (error as NodeJS.ErrnoException).code
316
+ if (code !== 'ENOENT' && code !== 'ENOTEMPTY') throw error
317
+ }
318
+ }
@@ -0,0 +1,175 @@
1
+ // Durable per-logical-send recipient binding for message_peer (PMR-77KT).
2
+ //
3
+ // Bind-before-send discipline: when a child resolves a peer name to a
4
+ // concrete recipient (childId + session file) and is about to deliver to
5
+ // its inbox, it first writes an exclusive-create binding record keyed by
6
+ // the SAME logical fingerprint the effect memo uses. On replay after an
7
+ // interrupted run, the binding pins the logical send to its original
8
+ // recipient: a replayed call can never re-resolve a reused peer name to a
9
+ // newer generation. If the bound recipient has died or been superseded,
10
+ // the handler fails closed (throws, no retarget) instead of delivering to
11
+ // a different child — the effect either already happened (provable from
12
+ // the bound inbox) or stays pinned to its original target forever.
13
+ //
14
+ // AIDEV-NOTE (PMR-77KT): writePeerBinding happens BEFORE the inbox write
15
+ // (durable-first, ask_owner record-before-sidecar precedent) and only the
16
+ // first write wins (EEXIST ⇒ replay takes the bound path). Records are
17
+ // never deleted — they are the durable record of which recipient a
18
+ // logical send belongs to, surviving the PMR-WXG0 resume wipe.
19
+ import {
20
+ closeSync,
21
+ fsyncSync,
22
+ mkdirSync,
23
+ openSync,
24
+ readFileSync,
25
+ renameSync,
26
+ writeSync,
27
+ } from 'node:fs'
28
+ import { join } from 'node:path'
29
+ import { ensureSubagentsDataDir, subagentsDataRoot } from './dataroot.ts'
30
+
31
+ export interface PeerRecipientBinding {
32
+ version: 1
33
+ childId: string // sender
34
+ fingerprint: string // logical send key (effectFingerprint('message_peer', ...))
35
+ toChildId: string // bound recipient generation
36
+ toSessionFile: string // bound recipient session file (supersession check)
37
+ toName: string // display name at bind time (result/error text)
38
+ request: { peer: string; message: string; resultRef?: string } // request identity
39
+ createdAt: string
40
+ lastActivityAt: string
41
+ }
42
+
43
+ function sanitizeChildId(childId: string): string {
44
+ const safe = childId.replace(/[^A-Za-z0-9._-]/g, '_')
45
+ if (safe === '' || safe === '.' || safe === '..') return '_'
46
+ return safe
47
+ }
48
+
49
+ /**
50
+ * Binding path:
51
+ * `<dataRoot>/peer-bindings/<senderChildId>/<fingerprint>.json`.
52
+ */
53
+ export function peerBindingPath(
54
+ childId: string,
55
+ fingerprint: string,
56
+ root: string = subagentsDataRoot(),
57
+ ): string {
58
+ return join(
59
+ ensureSubagentsDataDir('peer-bindings', root),
60
+ sanitizeChildId(childId),
61
+ `${fingerprint}.json`,
62
+ )
63
+ }
64
+
65
+ /** Hand-rolled structural validator (never TypeBox for durable records). */
66
+ export function isPeerRecipientBinding(
67
+ value: unknown,
68
+ ): value is PeerRecipientBinding {
69
+ if (value == null || typeof value !== 'object') return false
70
+ const record = value as Record<string, unknown>
71
+ if (record.version !== 1) return false
72
+ if (typeof record.childId !== 'string') return false
73
+ if (typeof record.fingerprint !== 'string') return false
74
+ if (typeof record.toChildId !== 'string') return false
75
+ if (typeof record.toSessionFile !== 'string') return false
76
+ if (typeof record.toName !== 'string') return false
77
+ if (record.request == null || typeof record.request !== 'object') return false
78
+ if (Array.isArray(record.request)) return false
79
+ const request = record.request as Record<string, unknown>
80
+ if (typeof request.peer !== 'string') return false
81
+ if (typeof request.message !== 'string') return false
82
+ if (
83
+ request.resultRef !== undefined &&
84
+ typeof request.resultRef !== 'string'
85
+ ) {
86
+ return false
87
+ }
88
+ if (typeof record.createdAt !== 'string') return false
89
+ if (typeof record.lastActivityAt !== 'string') return false
90
+ return true
91
+ }
92
+
93
+ /** Fail closed: null on missing or malformed (tool-effects readEffectMemo style). */
94
+ export function readPeerBinding(
95
+ childId: string,
96
+ fingerprint: string,
97
+ root?: string,
98
+ ): PeerRecipientBinding | null {
99
+ let raw: string
100
+ try {
101
+ raw = readFileSync(peerBindingPath(childId, fingerprint, root), 'utf8')
102
+ } catch {
103
+ return null
104
+ }
105
+ try {
106
+ const parsed = JSON.parse(raw) as unknown
107
+ if (!isPeerRecipientBinding(parsed)) return null
108
+ return parsed
109
+ } catch {
110
+ return null
111
+ }
112
+ }
113
+
114
+ /**
115
+ * Exclusive create (openSync 'wx', 0o600, write+fsync+close). Returns true
116
+ * when newly written, false when a binding already exists (EEXIST).
117
+ */
118
+ export function writePeerBinding(
119
+ binding: PeerRecipientBinding,
120
+ root?: string,
121
+ ): boolean {
122
+ const path = peerBindingPath(binding.childId, binding.fingerprint, root)
123
+ mkdirSync(join(path, '..'), { recursive: true, mode: 0o700 })
124
+ let fd: number
125
+ try {
126
+ fd = openSync(path, 'wx', 0o600)
127
+ } catch (error) {
128
+ if ((error as NodeJS.ErrnoException).code === 'EEXIST') return false
129
+ throw error
130
+ }
131
+ try {
132
+ writeSync(fd, JSON.stringify(binding))
133
+ fsyncSync(fd)
134
+ } finally {
135
+ closeSync(fd)
136
+ }
137
+ return true
138
+ }
139
+
140
+ function atomicWrite(path: string, contents: string): void {
141
+ const tmpPath = `${path}.${process.pid}.tmp`
142
+ const fd = openSync(tmpPath, 'w', 0o600)
143
+ try {
144
+ writeSync(fd, contents)
145
+ fsyncSync(fd)
146
+ } finally {
147
+ closeSync(fd)
148
+ }
149
+ renameSync(tmpPath, path)
150
+ }
151
+
152
+ // AIDEV-NOTE (PMR-77KT): atomic touch (tmp + fsync + rename, tool-effects
153
+ // atomicWrite shape) advancing ONLY lastActivityAt — every other field,
154
+ // including the bound recipient and request identity, stays byte-identical.
155
+ // Best-effort by contract: handlers call it AFTER writeEffectMemo, so a
156
+ // throwing touch would surface a tool error for an already-completed send.
157
+ // All failures (EACCES, ENOSPC, read-only fs) are swallowed here — a stale
158
+ // lastActivityAt never justifies breaking a send; a leftover .tmp sibling is
159
+ // harmless (same shape as the atomicWrite in peers.ts).
160
+ export function touchPeerBinding(
161
+ binding: PeerRecipientBinding,
162
+ root?: string,
163
+ ): void {
164
+ try {
165
+ const path = peerBindingPath(binding.childId, binding.fingerprint, root)
166
+ mkdirSync(join(path, '..'), { recursive: true, mode: 0o700 })
167
+ const touched: PeerRecipientBinding = {
168
+ ...binding,
169
+ lastActivityAt: new Date().toISOString(),
170
+ }
171
+ atomicWrite(path, JSON.stringify(touched))
172
+ } catch {
173
+ // Best-effort: see the AIDEV-NOTE above.
174
+ }
175
+ }