@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,237 @@
|
|
|
1
|
+
import {
|
|
2
|
+
HerdrError,
|
|
3
|
+
herdrRunInPane,
|
|
4
|
+
herdrWaitOutput,
|
|
5
|
+
runHerdr,
|
|
6
|
+
runHerdrEnvelope,
|
|
7
|
+
} from './herdr.ts'
|
|
8
|
+
|
|
9
|
+
// AIDEV-NOTE: Tab spawn + rollback (PMR-TABUX). Spawn = background tab
|
|
10
|
+
// (`tab create --no-focus` — the user's focus never moves) → shell-readiness
|
|
11
|
+
// marker → `agent start` attaching pi/claude to the tab's root pane. Failure
|
|
12
|
+
// of `agent start` rolls back ONLY tabs this spawn created (asymmetric
|
|
13
|
+
// cleanup — herdsman's rule: never close a user's tab). Focus actions are
|
|
14
|
+
// separately verified via canFocusAgent before `agent focus` is sent.
|
|
15
|
+
|
|
16
|
+
// ── Tab + agent spawn verbs (PMR-TABUX) ──
|
|
17
|
+
|
|
18
|
+
export interface HerdrSpawnedTab {
|
|
19
|
+
paneId: string
|
|
20
|
+
tabId: string
|
|
21
|
+
workspaceId: string
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface HerdrPaneSummary {
|
|
25
|
+
pane_id?: string
|
|
26
|
+
tab_id?: string
|
|
27
|
+
workspace_id?: string
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Create a background tab: `tab create --workspace --cwd --label --env K=V
|
|
32
|
+
* --no-focus`. `--no-focus` is the background guarantee — the user's focus
|
|
33
|
+
* never moves. Returns the tab's root pane + tab ids for rollback bookkeeping.
|
|
34
|
+
* Flag shapes verified against the installed 0.9.0 binary.
|
|
35
|
+
*/
|
|
36
|
+
export function herdrTabCreate(options: {
|
|
37
|
+
workspaceId: string
|
|
38
|
+
cwd: string
|
|
39
|
+
label: string
|
|
40
|
+
env?: Record<string, string>
|
|
41
|
+
}): HerdrSpawnedTab {
|
|
42
|
+
const args = [
|
|
43
|
+
'tab',
|
|
44
|
+
'create',
|
|
45
|
+
'--workspace',
|
|
46
|
+
options.workspaceId,
|
|
47
|
+
'--cwd',
|
|
48
|
+
options.cwd,
|
|
49
|
+
'--label',
|
|
50
|
+
options.label,
|
|
51
|
+
'--no-focus',
|
|
52
|
+
]
|
|
53
|
+
for (const [key, value] of Object.entries(options.env ?? {})) {
|
|
54
|
+
args.push('--env', `${key}=${value}`)
|
|
55
|
+
}
|
|
56
|
+
const result = runHerdrEnvelope<{
|
|
57
|
+
root_pane?: HerdrPaneSummary
|
|
58
|
+
tab?: HerdrPaneSummary
|
|
59
|
+
}>(args)
|
|
60
|
+
const pane = result.root_pane
|
|
61
|
+
const tab = result.tab
|
|
62
|
+
if (!pane?.pane_id || !tab?.tab_id) {
|
|
63
|
+
throw new HerdrError(
|
|
64
|
+
`herdr tab create returned no root pane/tab: ${JSON.stringify(result).slice(0, 200)}`,
|
|
65
|
+
args,
|
|
66
|
+
)
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
paneId: pane.pane_id,
|
|
70
|
+
tabId: tab.tab_id,
|
|
71
|
+
workspaceId: tab.workspace_id ?? options.workspaceId,
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Close a tab (rollback path — only ever called on tabs WE created). */
|
|
76
|
+
export function herdrTabClose(tabId: string): void {
|
|
77
|
+
runHerdr(['tab', 'close', tabId])
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Start an agent in a shell-ready pane: `agent start <alias> --kind <kind>
|
|
82
|
+
* --pane <id> --timeout <ms> -- <argv>`. Blocks until herdr detects the
|
|
83
|
+
* agent's interactive readiness. Throws HerdrError on failure — caller owns
|
|
84
|
+
* rollback of the tab it created.
|
|
85
|
+
*/
|
|
86
|
+
export function herdrAgentStart(options: {
|
|
87
|
+
alias: string
|
|
88
|
+
kind: 'pi' | 'claude'
|
|
89
|
+
paneId: string
|
|
90
|
+
argv: readonly string[]
|
|
91
|
+
timeoutMs?: number
|
|
92
|
+
}): void {
|
|
93
|
+
const args = [
|
|
94
|
+
'agent',
|
|
95
|
+
'start',
|
|
96
|
+
options.alias,
|
|
97
|
+
'--kind',
|
|
98
|
+
options.kind,
|
|
99
|
+
'--pane',
|
|
100
|
+
options.paneId,
|
|
101
|
+
'--timeout',
|
|
102
|
+
// AIDEV-NOTE: keep this SHORT. herdr's readiness detection waits for an
|
|
103
|
+
// idle agent, but our children go busy immediately (positional task), so
|
|
104
|
+
// this timeout is a false-negative path — the caller (spawnAgentInTab)
|
|
105
|
+
// treats it as soft and confirms via the child session file. A long
|
|
106
|
+
// timeout blocks the subagent tool call itself (observed: 31s block made
|
|
107
|
+
// the parent miss a child's ask window).
|
|
108
|
+
String(options.timeoutMs ?? 10_000),
|
|
109
|
+
'--',
|
|
110
|
+
...options.argv,
|
|
111
|
+
]
|
|
112
|
+
runHerdr(args)
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Liveness probe: `pane get <id>`. True when the pane still exists. Errors
|
|
117
|
+
* (herdr unreachable) fail OPEN — the caller must not misclassify a live
|
|
118
|
+
* child as crashed just because a probe failed.
|
|
119
|
+
*
|
|
120
|
+
* AIDEV-NOTE (PMR-YFRB): the default timeoutMs bounds a hung `herdr` CLI.
|
|
121
|
+
* An execFileSync timeout throw fails OPEN by design — polarity is
|
|
122
|
+
* unchanged (probe errors are treated alive); the stall watchdog is the
|
|
123
|
+
* independent backstop for a child that is genuinely gone.
|
|
124
|
+
*/
|
|
125
|
+
export function herdrPaneAlive(paneId: string, timeoutMs = 10_000): boolean {
|
|
126
|
+
try {
|
|
127
|
+
runHerdr(['pane', 'get', paneId], timeoutMs)
|
|
128
|
+
return true
|
|
129
|
+
} catch (err) {
|
|
130
|
+
if (err instanceof HerdrError && err.exitCode === 1) return false
|
|
131
|
+
return true
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** List tabs in a workspace (used to verify a created tab still exists). */
|
|
136
|
+
export function herdrTabList(workspaceId: string): string[] {
|
|
137
|
+
const result = runHerdrEnvelope<{
|
|
138
|
+
tabs?: Array<{ tab_id?: string }>
|
|
139
|
+
}>(['tab', 'list', '--workspace', workspaceId])
|
|
140
|
+
return (result.tabs ?? [])
|
|
141
|
+
.map((t) => t.tab_id)
|
|
142
|
+
.filter((id): id is string => typeof id === 'string')
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const AGENT_PANE_BUSY_RETRY_MS = 2000
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Shell-readiness marker (herdsman's spawn hardening): echo a unique marker
|
|
149
|
+
* via `pane run`, then block on `pane wait-output --regex` until the fresh
|
|
150
|
+
* pane's shell prints it — proving the shell is interactive before any
|
|
151
|
+
* `agent start`. Retries once after ~2s on the fresh-shell busy race.
|
|
152
|
+
*
|
|
153
|
+
* Acceptance is regex-escaped — the marker is generated, not user input, but
|
|
154
|
+
* escape defensively anyway.
|
|
155
|
+
*/
|
|
156
|
+
export async function waitShellReady(
|
|
157
|
+
paneId: string,
|
|
158
|
+
options?: { timeoutMs?: number },
|
|
159
|
+
): Promise<void> {
|
|
160
|
+
const marker = `__READY_${crypto.randomUUID().replaceAll('-', '')}__`
|
|
161
|
+
const escaped = marker.replaceAll(/[.*+?^${}()|[\]\\]/g, '\\$&')
|
|
162
|
+
const timeoutMs = options?.timeoutMs ?? 10_000
|
|
163
|
+
|
|
164
|
+
try {
|
|
165
|
+
herdrRunInPane(paneId, ['echo', marker])
|
|
166
|
+
herdrWaitOutput(paneId, `^${escaped}$`, timeoutMs)
|
|
167
|
+
return
|
|
168
|
+
} catch (err) {
|
|
169
|
+
// Fresh-shell busy race: pane exists but its agent/shell isn't accepting
|
|
170
|
+
// input yet (`agent_pane_busy`). Wait ~2s and retry once.
|
|
171
|
+
if (!(err instanceof HerdrError)) throw err
|
|
172
|
+
await new Promise<void>((resolve) =>
|
|
173
|
+
setTimeout(resolve, AGENT_PANE_BUSY_RETRY_MS),
|
|
174
|
+
)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
herdrRunInPane(paneId, ['echo', marker])
|
|
178
|
+
herdrWaitOutput(paneId, `^${escaped}$`, timeoutMs)
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// ── Pure bookkeeping (unit-tested) ──
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Rollback selection: of the candidate tabs, close ONLY the ones this spawn
|
|
185
|
+
* created and that still exist. Never returns a tab absent from `createdTabIds`
|
|
186
|
+
* — user tabs are untouchable.
|
|
187
|
+
*/
|
|
188
|
+
export function pickRollbackTabs(
|
|
189
|
+
createdTabIds: readonly string[],
|
|
190
|
+
existingTabIds: readonly string[],
|
|
191
|
+
): string[] {
|
|
192
|
+
const created = new Set(createdTabIds)
|
|
193
|
+
return existingTabIds.filter((id) => created.has(id))
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/** What a focus click needs to know about the entry it targets. */
|
|
197
|
+
export interface FocusTargetRecord {
|
|
198
|
+
childId: string
|
|
199
|
+
sessionFile: string
|
|
200
|
+
paneId?: string
|
|
201
|
+
tabId?: string
|
|
202
|
+
workspaceId?: string
|
|
203
|
+
starting?: boolean
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Focus verification gate (herdsman's `focusTarget` discipline — status
|
|
208
|
+
* projection is never authorization): the recorded entry must be live (not
|
|
209
|
+
* starting), carry a paneId, and the herdr-reported agent must still sit on
|
|
210
|
+
* the same pane/tab/workspace. Any mismatch ⇒ inert.
|
|
211
|
+
*/
|
|
212
|
+
export function canFocusAgent(
|
|
213
|
+
target: FocusTargetRecord,
|
|
214
|
+
agent: {
|
|
215
|
+
pane_id?: string
|
|
216
|
+
tab_id?: string
|
|
217
|
+
workspace_id?: string
|
|
218
|
+
} | null,
|
|
219
|
+
): { ok: true; paneId: string } | { ok: false; reason: string } {
|
|
220
|
+
if (!target.paneId) return { ok: false, reason: 'no pane recorded' }
|
|
221
|
+
if (target.starting) return { ok: false, reason: 'still starting' }
|
|
222
|
+
if (!agent) return { ok: false, reason: 'agent gone from herdr' }
|
|
223
|
+
if (agent.pane_id !== target.paneId) {
|
|
224
|
+
return { ok: false, reason: 'pane identity changed' }
|
|
225
|
+
}
|
|
226
|
+
if (target.tabId && agent.tab_id && agent.tab_id !== target.tabId) {
|
|
227
|
+
return { ok: false, reason: 'tab identity changed' }
|
|
228
|
+
}
|
|
229
|
+
if (
|
|
230
|
+
target.workspaceId &&
|
|
231
|
+
agent.workspace_id &&
|
|
232
|
+
agent.workspace_id !== target.workspaceId
|
|
233
|
+
) {
|
|
234
|
+
return { ok: false, reason: 'workspace identity changed' }
|
|
235
|
+
}
|
|
236
|
+
return { ok: true, paneId: target.paneId }
|
|
237
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
// Replay-safe spawn identity (PMR-YKAC). Ported from pi-durable's
|
|
2
|
+
// `replay: "safe"` subagent tool: child creation is keyed on
|
|
3
|
+
// (parentSessionId, spawnSeq) so a rerun after a crash finds the same child
|
|
4
|
+
// instead of duplicating it.
|
|
5
|
+
//
|
|
6
|
+
// AIDEV-NOTE: the seq allocator is a marker-file set (delivered.ts
|
|
7
|
+
// precedent): seq N is claimed by exclusive-create of
|
|
8
|
+
// <dataRoot>/spawn-seq/<parentSessionId>/<N> — atomic by construction, so
|
|
9
|
+
// concurrent spawns in one parent session can never claim the same seq, and
|
|
10
|
+
// the counter survives a parent crash (no in-memory reset).
|
|
11
|
+
//
|
|
12
|
+
// Replay is scan-based (pi-durable's scanConversations({ownerTaskId})):
|
|
13
|
+
// before allocating, look up a 'starting' assignment record written by THIS
|
|
14
|
+
// parent for the SAME name+task — that is the spawn that crashed between
|
|
15
|
+
// record-write and tab-create. Reuse its childId/sessionFile/worktree
|
|
16
|
+
// instead of creating duplicates.
|
|
17
|
+
import { createHash } from 'node:crypto'
|
|
18
|
+
import { closeSync, fsyncSync, mkdirSync, openSync, writeSync } from 'node:fs'
|
|
19
|
+
import { join } from 'node:path'
|
|
20
|
+
import { type AssignmentRecord, findStartingAssignment } from './assignments.ts'
|
|
21
|
+
import { ensureSubagentsDataDir, subagentsDataRoot } from './dataroot.ts'
|
|
22
|
+
|
|
23
|
+
function sanitizeScope(scope: string): string {
|
|
24
|
+
const safe = scope.replace(/[^A-Za-z0-9._-]/g, '_')
|
|
25
|
+
if (safe === '' || safe === '.' || safe === '..') return '_'
|
|
26
|
+
return safe
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Deterministic childId: first 8 hex of sha256(parentSessionId:spawnSeq) —
|
|
31
|
+
* same shape as the legacy random id (`Math.random().toString(16)`), so
|
|
32
|
+
* every downstream consumer (session file naming, worktree branch suffix,
|
|
33
|
+
* PI_SUBAGENT_ID) is unaffected.
|
|
34
|
+
*/
|
|
35
|
+
export function deriveChildId(
|
|
36
|
+
parentSessionId: string,
|
|
37
|
+
spawnSeq: number,
|
|
38
|
+
): string {
|
|
39
|
+
return createHash('sha256')
|
|
40
|
+
.update(`${parentSessionId}:${spawnSeq}`)
|
|
41
|
+
.digest('hex')
|
|
42
|
+
.slice(0, 8)
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Claim the next spawn seq for this parent session. Durable and crash-safe:
|
|
47
|
+
* the marker persists, so a restarted parent never re-issues a seq whose
|
|
48
|
+
* assignment record may already exist.
|
|
49
|
+
*/
|
|
50
|
+
export function nextSpawnSeq(
|
|
51
|
+
parentSessionId: string,
|
|
52
|
+
root: string = subagentsDataRoot(),
|
|
53
|
+
): number {
|
|
54
|
+
const dir = join(
|
|
55
|
+
ensureSubagentsDataDir('spawn-seq', root),
|
|
56
|
+
sanitizeScope(parentSessionId),
|
|
57
|
+
)
|
|
58
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
59
|
+
for (let seq = 1; ; seq++) {
|
|
60
|
+
let fd: number
|
|
61
|
+
try {
|
|
62
|
+
fd = openSync(join(dir, String(seq)), 'wx', 0o600)
|
|
63
|
+
} catch (error) {
|
|
64
|
+
if ((error as NodeJS.ErrnoException).code === 'EEXIST') continue
|
|
65
|
+
throw error
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
writeSync(fd, '1')
|
|
69
|
+
fsyncSync(fd)
|
|
70
|
+
} finally {
|
|
71
|
+
closeSync(fd)
|
|
72
|
+
}
|
|
73
|
+
return seq
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface SpawnIdentity {
|
|
78
|
+
childId: string
|
|
79
|
+
/** The crashed spawn's record when this allocation is a replay. */
|
|
80
|
+
replay: AssignmentRecord | null
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Lookup-before-create (the replay: "safe" port): a matching 'starting'
|
|
85
|
+
* record from this parent means the previous spawn crashed after writing
|
|
86
|
+
* its record but before creating the tab — reuse it. Otherwise allocate a
|
|
87
|
+
* fresh deterministic childId. Without a parent session id (programmatic
|
|
88
|
+
* callers) fall back to the legacy random id.
|
|
89
|
+
*/
|
|
90
|
+
export function allocateSpawnIdentity(
|
|
91
|
+
options: {
|
|
92
|
+
parentSessionId: string | null
|
|
93
|
+
name: string
|
|
94
|
+
task: string
|
|
95
|
+
},
|
|
96
|
+
root?: string,
|
|
97
|
+
): SpawnIdentity {
|
|
98
|
+
const { parentSessionId, name, task } = options
|
|
99
|
+
if (!parentSessionId) {
|
|
100
|
+
return {
|
|
101
|
+
childId: Math.random().toString(16).slice(2, 10),
|
|
102
|
+
replay: null,
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const replay = findStartingAssignment({ parentSessionId, name, task }, root)
|
|
106
|
+
if (replay) {
|
|
107
|
+
return { childId: replay.childId, replay }
|
|
108
|
+
}
|
|
109
|
+
return {
|
|
110
|
+
childId: deriveChildId(
|
|
111
|
+
parentSessionId,
|
|
112
|
+
nextSpawnSeq(parentSessionId, root),
|
|
113
|
+
),
|
|
114
|
+
replay: null,
|
|
115
|
+
}
|
|
116
|
+
}
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
// AIDEV-NOTE (PMR-3QMY): public state-event contract for co-extensions.
|
|
2
|
+
//
|
|
3
|
+
// What this module is: the single source of truth for the
|
|
4
|
+
// `pi-my-rifle-subagents:state` channel payload. Pure module — no fs, no
|
|
5
|
+
// pi import, no globalThis. It only builds versioned event objects and
|
|
6
|
+
// hands them to an injected `{ emit }` bus; index.ts owns WHEN emissions
|
|
7
|
+
// happen (the durable/Map seams) and derives the entry list.
|
|
8
|
+
//
|
|
9
|
+
// Payload contract (HUMAN DECISION, Option A — minimal projection):
|
|
10
|
+
// each entry carries EXACTLY id / name / status, and the envelope carries
|
|
11
|
+
// EXACTLY type / version / incarnation / seq / emittedAt / agents. A
|
|
12
|
+
// key-set contract test pins this. Excluded from any payload: task prompt,
|
|
13
|
+
// message bodies, `cwd`, `sessionFile`, `activityFile`, `claim.pid`,
|
|
14
|
+
// paneId/tabId/workspaceId, worktree/branch paths, usage — anything
|
|
15
|
+
// beyond id/name/status per entry, and anything secret-ish or
|
|
16
|
+
// filesystem-detail-ish. Additive fields are a deliberate version-policy
|
|
17
|
+
// decision (v1 is additive-only: consumers MUST ignore unknown fields).
|
|
18
|
+
//
|
|
19
|
+
// Sequencer: `incarnation` is generated ONCE at module load and `seq` is a
|
|
20
|
+
// module-level 1-based counter. This is a DELIBERATE exception to the
|
|
21
|
+
// globalThis-survival pattern (RUNNING_KEY / flow-env.ts listener
|
|
22
|
+
// registry): we WANT a fresh incarnation per module load so `/reload`
|
|
23
|
+
// restarts the sequence. The sequencer must NOT move to globalThis. A
|
|
24
|
+
// cached module load continuing its incarnation is the safe direction —
|
|
25
|
+
// seq never reuses numbers within a live incarnation.
|
|
26
|
+
//
|
|
27
|
+
// Dual module instances: pi loads the extension entrypoint directly while
|
|
28
|
+
// co-extensions (pi-flow) import through the workspace package root — those
|
|
29
|
+
// can be distinct instances. Only the entrypoint instance wires emissions;
|
|
30
|
+
// consumers subscribe via `pi.events`, never via module imports.
|
|
31
|
+
|
|
32
|
+
import { randomUUID } from 'node:crypto'
|
|
33
|
+
|
|
34
|
+
/** Channel name for all subagent state events. */
|
|
35
|
+
export const SUBAGENT_STATE_CHANNEL = 'pi-my-rifle-subagents:state'
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Payload schema version. v1 is additive-only: consumers MUST ignore
|
|
39
|
+
* unknown fields; publishers MAY add fields without bumping. Breaking
|
|
40
|
+
* changes bump this constant.
|
|
41
|
+
*/
|
|
42
|
+
export const SUBAGENT_STATE_EVENT_VERSION = 1
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Mirror of `WidgetStateKind` (index.ts ~1000) / `AssignmentStatus`
|
|
46
|
+
* (assignments.ts:24). Keep in sync with both.
|
|
47
|
+
*
|
|
48
|
+
* AIDEV-NOTE (PMR-3QMY) sync contract: `'lost'` is RESERVED — a lost child
|
|
49
|
+
* is REMOVED from snapshots (settlement is the disappearance signal), so
|
|
50
|
+
* it is never carried as a live status. It stays in the union so consumer
|
|
51
|
+
* exhaustive switches are forward-stable.
|
|
52
|
+
*/
|
|
53
|
+
export type SubagentStateStatus =
|
|
54
|
+
| 'starting'
|
|
55
|
+
| 'working'
|
|
56
|
+
| 'blocked'
|
|
57
|
+
| 'waiting'
|
|
58
|
+
| 'stalled'
|
|
59
|
+
| 'lost'
|
|
60
|
+
|
|
61
|
+
/** Minimal public projection of one live subagent. */
|
|
62
|
+
export interface SubagentStateEntry {
|
|
63
|
+
/** childId */
|
|
64
|
+
id: string
|
|
65
|
+
name: string
|
|
66
|
+
status: SubagentStateStatus
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Envelope published on SUBAGENT_STATE_CHANNEL. */
|
|
70
|
+
export interface SubagentStateEvent {
|
|
71
|
+
type: 'snapshot' | 'stopped'
|
|
72
|
+
version: 1
|
|
73
|
+
/** UUID, per publisher module load. */
|
|
74
|
+
incarnation: string
|
|
75
|
+
/** 1-based, strictly monotonic within an incarnation. */
|
|
76
|
+
seq: number
|
|
77
|
+
/** ISO 8601. */
|
|
78
|
+
emittedAt: string
|
|
79
|
+
/** Snapshot entries sorted by id (the CALLER sorts); `[]` for 'stopped'. */
|
|
80
|
+
agents: SubagentStateEntry[]
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Minimal structural shape publishStateEvent needs from pi's EventBus. */
|
|
84
|
+
export interface StateEventBus {
|
|
85
|
+
emit(channel: string, data: unknown): void
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Module-level sequencer (see AIDEV-NOTE header — must NOT move to
|
|
89
|
+
// globalThis). One incarnation per module load; seq increments per event.
|
|
90
|
+
const incarnation: string = randomUUID()
|
|
91
|
+
let seqCounter = 0
|
|
92
|
+
|
|
93
|
+
/** Next envelope field values from the sequencer (1-based, monotonic). */
|
|
94
|
+
function nextEnvelope(
|
|
95
|
+
type: 'snapshot' | 'stopped',
|
|
96
|
+
now?: number,
|
|
97
|
+
): SubagentStateEvent {
|
|
98
|
+
seqCounter += 1
|
|
99
|
+
let timestamp: number
|
|
100
|
+
if (now === undefined) {
|
|
101
|
+
timestamp = Date.now()
|
|
102
|
+
} else {
|
|
103
|
+
timestamp = now
|
|
104
|
+
}
|
|
105
|
+
return {
|
|
106
|
+
type,
|
|
107
|
+
version: SUBAGENT_STATE_EVENT_VERSION,
|
|
108
|
+
incarnation,
|
|
109
|
+
seq: seqCounter,
|
|
110
|
+
emittedAt: new Date(timestamp).toISOString(),
|
|
111
|
+
agents: [],
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Build a full-snapshot event from the given entries.
|
|
117
|
+
*
|
|
118
|
+
* The entries are carried verbatim (same array reference and same element
|
|
119
|
+
* identities) — the builder does NOT re-sort or copy. Callers derive the
|
|
120
|
+
* list sorted by id (see `subagentStateEntries` in index.ts).
|
|
121
|
+
*/
|
|
122
|
+
export function buildSubagentStateSnapshot(
|
|
123
|
+
entries: SubagentStateEntry[],
|
|
124
|
+
now?: number,
|
|
125
|
+
): SubagentStateEvent {
|
|
126
|
+
const event = nextEnvelope('snapshot', now)
|
|
127
|
+
event.agents = entries
|
|
128
|
+
return event
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Build the terminal 'stopped' event (always `agents: []`). */
|
|
132
|
+
export function buildSubagentStateStopped(now?: number): SubagentStateEvent {
|
|
133
|
+
return nextEnvelope('stopped', now)
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Best-effort publish — a missing/stale bus or a throwing `emit` must never
|
|
138
|
+
* propagate into the status-maintenance path (spawn / tick / settle).
|
|
139
|
+
* pi's EventBus already catches throwing subscribers; the try/catch here
|
|
140
|
+
* additionally covers a stale bus object whose `emit` itself throws.
|
|
141
|
+
*/
|
|
142
|
+
export function publishStateEvent(
|
|
143
|
+
bus: StateEventBus | null | undefined,
|
|
144
|
+
event: SubagentStateEvent,
|
|
145
|
+
): void {
|
|
146
|
+
if (!bus) return
|
|
147
|
+
try {
|
|
148
|
+
bus.emit(SUBAGENT_STATE_CHANNEL, event)
|
|
149
|
+
} catch {
|
|
150
|
+
// Isolation by design: state observation must never break execution.
|
|
151
|
+
}
|
|
152
|
+
}
|