@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,323 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process'
|
|
2
|
+
|
|
3
|
+
// AIDEV-NOTE: Herdr verb layer (PMR-M48Y) — thin JSON-envelope wrappers over
|
|
4
|
+
// the `herdr` CLI, ported from pi-herdsman's runHerdr discipline. Every socket
|
|
5
|
+
// verb returns herdr's `{id, result}` envelope; raw-output verbs (pane read,
|
|
6
|
+
// pane send-*) return plain text. Verb/flag shapes verified against
|
|
7
|
+
// `herdr api schema --json` of the installed binary (0.9.0, protocol 22).
|
|
8
|
+
// 0.9.0 gaps noted inline; HERDR_MIN_VERSION gate protects users at runtime.
|
|
9
|
+
// ── Herdr verb layer ──
|
|
10
|
+
|
|
11
|
+
/** herdsman's baseline pin. Older servers fail preflight with an upgrade hint. */
|
|
12
|
+
export const HERDR_MIN_VERSION = '0.9.1'
|
|
13
|
+
|
|
14
|
+
/** Error from a failed herdr CLI invocation (nonzero exit or bad output). */
|
|
15
|
+
export class HerdrError extends Error {
|
|
16
|
+
readonly args: readonly string[]
|
|
17
|
+
readonly stderr: string
|
|
18
|
+
/** Process exit status when the CLI itself ran and failed, else null. */
|
|
19
|
+
readonly exitCode: number | null
|
|
20
|
+
|
|
21
|
+
constructor(
|
|
22
|
+
message: string,
|
|
23
|
+
args: readonly string[],
|
|
24
|
+
stderr = '',
|
|
25
|
+
exitCode: number | null = null,
|
|
26
|
+
) {
|
|
27
|
+
super(message)
|
|
28
|
+
this.name = 'HerdrError'
|
|
29
|
+
this.args = args
|
|
30
|
+
this.stderr = stderr
|
|
31
|
+
this.exitCode = exitCode
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
interface HerdrEnvelope<T> {
|
|
36
|
+
id?: unknown
|
|
37
|
+
result?: T
|
|
38
|
+
error?: { code?: string; message?: string }
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Run `herdr` with the given args and return trimmed stdout. Throws HerdrError
|
|
43
|
+
* on nonzero exit (stderr included) — never parses here.
|
|
44
|
+
*/
|
|
45
|
+
export function runHerdr(args: readonly string[], timeoutMs?: number): string {
|
|
46
|
+
// AIDEV-NOTE: stdio must be piped. execFileSync inherits stderr by default,
|
|
47
|
+
// so a CAUGHT herdr failure (tab close after pane close already removed the
|
|
48
|
+
// tab, pane-get liveness probes on dead panes) still printed herdr's raw
|
|
49
|
+
// {"error":{"code":"tab_not_found"...}} JSON into the parent TUI, and
|
|
50
|
+
// HerdrError.stderr stayed empty. Observed 2026-10-22, 8 tab.close + 8
|
|
51
|
+
// pane.get expected failures per day.
|
|
52
|
+
const opts: {
|
|
53
|
+
encoding: BufferEncoding
|
|
54
|
+
timeout?: number
|
|
55
|
+
stdio: 'pipe'
|
|
56
|
+
env: NodeJS.ProcessEnv
|
|
57
|
+
} = {
|
|
58
|
+
encoding: 'utf8',
|
|
59
|
+
stdio: 'pipe',
|
|
60
|
+
// AIDEV-NOTE: env must be explicit. Bun resolves bare command names from
|
|
61
|
+
// the STARTUP environ snapshot, ignoring process.env.PATH mutations, so
|
|
62
|
+
// test PATH shims never served the spawn; explicit env: process.env keeps
|
|
63
|
+
// Node semantics identical and makes PATH mutations effective.
|
|
64
|
+
env: process.env,
|
|
65
|
+
}
|
|
66
|
+
if (timeoutMs !== undefined) {
|
|
67
|
+
opts.timeout = timeoutMs
|
|
68
|
+
}
|
|
69
|
+
try {
|
|
70
|
+
return execFileSync('herdr', args, opts).trim()
|
|
71
|
+
} catch (err) {
|
|
72
|
+
const e = err as {
|
|
73
|
+
stderr?: string | Buffer
|
|
74
|
+
message: string
|
|
75
|
+
status?: number | null
|
|
76
|
+
}
|
|
77
|
+
let stderr = ''
|
|
78
|
+
if (typeof e.stderr === 'string') {
|
|
79
|
+
stderr = e.stderr
|
|
80
|
+
} else if (e.stderr !== undefined && e.stderr !== null) {
|
|
81
|
+
stderr = String(e.stderr)
|
|
82
|
+
}
|
|
83
|
+
throw new HerdrError(
|
|
84
|
+
`herdr ${args.join(' ')} failed: ${stderr.trim() || e.message}`,
|
|
85
|
+
args,
|
|
86
|
+
stderr,
|
|
87
|
+
typeof e.status === 'number' ? e.status : null,
|
|
88
|
+
)
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Parse herdr's `{id, result}` JSON envelope from raw stdout. Pure — exported
|
|
94
|
+
* for tests. Non-JSON output fails with a clear error (fail closed).
|
|
95
|
+
*/
|
|
96
|
+
export function parseHerdrEnvelope<T>(
|
|
97
|
+
args: readonly string[],
|
|
98
|
+
stdout: string,
|
|
99
|
+
): T {
|
|
100
|
+
let parsed: HerdrEnvelope<T>
|
|
101
|
+
try {
|
|
102
|
+
parsed = JSON.parse(stdout) as HerdrEnvelope<T>
|
|
103
|
+
} catch {
|
|
104
|
+
throw new HerdrError(
|
|
105
|
+
`herdr ${args.join(' ')} returned non-JSON output (expected {id, result} envelope): ${stdout.slice(0, 200)}`,
|
|
106
|
+
args,
|
|
107
|
+
)
|
|
108
|
+
}
|
|
109
|
+
if (parsed.error) {
|
|
110
|
+
throw new HerdrError(
|
|
111
|
+
`herdr ${args.join(' ')} error ${parsed.error.code ?? ''}: ${parsed.error.message ?? 'unknown'}`,
|
|
112
|
+
args,
|
|
113
|
+
)
|
|
114
|
+
}
|
|
115
|
+
if (parsed.id === undefined || parsed.result === undefined) {
|
|
116
|
+
throw new HerdrError(
|
|
117
|
+
`herdr ${args.join(' ')} returned unexpected JSON (missing id/result): ${stdout.slice(0, 200)}`,
|
|
118
|
+
args,
|
|
119
|
+
)
|
|
120
|
+
}
|
|
121
|
+
return parsed.result
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Run a herdr verb that returns the `{id, result}` JSON envelope and return
|
|
126
|
+
* `result`. Non-JSON output fails with a clear error (fail closed).
|
|
127
|
+
*/
|
|
128
|
+
export function runHerdrEnvelope<T>(
|
|
129
|
+
args: readonly string[],
|
|
130
|
+
timeoutMs?: number,
|
|
131
|
+
): T {
|
|
132
|
+
return parseHerdrEnvelope<T>(args, runHerdr(args, timeoutMs))
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** `herdr status --json` payload (CLI-level JSON, not an envelope). */
|
|
136
|
+
export interface HerdrStatus {
|
|
137
|
+
client?: { version?: string }
|
|
138
|
+
server?: { status?: string; running?: boolean; version?: string }
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** Compare dotted version strings; negative when a < b. */
|
|
142
|
+
export function compareVersions(a: string, b: string): number {
|
|
143
|
+
const pa = a.split('.').map((n) => Number.parseInt(n, 10) || 0)
|
|
144
|
+
const pb = b.split('.').map((n) => Number.parseInt(n, 10) || 0)
|
|
145
|
+
for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
|
|
146
|
+
const diff = (pa[i] ?? 0) - (pb[i] ?? 0)
|
|
147
|
+
if (diff !== 0) return diff
|
|
148
|
+
}
|
|
149
|
+
return 0
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Validate a raw `herdr status --json` payload and enforce the version gate.
|
|
154
|
+
* Throws with an actionable message on unreachable server or version < gate.
|
|
155
|
+
*/
|
|
156
|
+
export function parseHerdrStatus(raw: string): HerdrStatus {
|
|
157
|
+
let status: HerdrStatus
|
|
158
|
+
try {
|
|
159
|
+
status = JSON.parse(raw) as HerdrStatus
|
|
160
|
+
} catch {
|
|
161
|
+
throw new HerdrError(
|
|
162
|
+
'herdr status returned non-JSON output — is herdr installed correctly? See https://github.com/steipete/herdr',
|
|
163
|
+
['status', '--json'],
|
|
164
|
+
)
|
|
165
|
+
}
|
|
166
|
+
const running = status.server?.running === true
|
|
167
|
+
if (!running) {
|
|
168
|
+
throw new HerdrError(
|
|
169
|
+
'Herdr server is not running. Start it with `herdr` (or `herdr pi`), then retry.',
|
|
170
|
+
['status', '--json'],
|
|
171
|
+
)
|
|
172
|
+
}
|
|
173
|
+
const version = status.server?.version ?? status.client?.version
|
|
174
|
+
if (!version) {
|
|
175
|
+
throw new HerdrError(
|
|
176
|
+
'Could not determine herdr version from `herdr status --json` — refusing to proceed.',
|
|
177
|
+
['status', '--json'],
|
|
178
|
+
)
|
|
179
|
+
}
|
|
180
|
+
if (compareVersions(version, HERDR_MIN_VERSION) < 0) {
|
|
181
|
+
throw new HerdrError(
|
|
182
|
+
`herdr ${version} is too old; this extension requires >= ${HERDR_MIN_VERSION}. Upgrade with \`herdr upgrade\` (or reinstall from https://github.com/steipete/herdr) and restart the herdr server.`,
|
|
183
|
+
['status', '--json'],
|
|
184
|
+
)
|
|
185
|
+
}
|
|
186
|
+
return status
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Preflight: `herdr status --json`, server reachability, >= HERDR_MIN_VERSION.
|
|
191
|
+
* Call before any spawn. Throws HerdrError with an actionable message.
|
|
192
|
+
*/
|
|
193
|
+
export function herdrPreflight(): HerdrStatus {
|
|
194
|
+
return parseHerdrStatus(runHerdr(['status', '--json']))
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/** Send one Escape keypress (canonical `esc`, never raw byte 27). */
|
|
198
|
+
export function herdrSendEscape(paneId: string): void {
|
|
199
|
+
runHerdr(['pane', 'send-keys', paneId, 'esc'])
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Type text into a pane without submitting. */
|
|
203
|
+
export function herdrSendText(paneId: string, text: string): void {
|
|
204
|
+
runHerdr(['pane', 'send-text', paneId, text])
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Submit the pending input line (Enter). */
|
|
208
|
+
export function herdrSendReturn(paneId: string): void {
|
|
209
|
+
runHerdr(['pane', 'send-keys', paneId, 'return'])
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Script-file execution (herdsman's sendLongCommand correction): run a
|
|
214
|
+
* payload from a file instead of typing it into the pane — herdr rejects
|
|
215
|
+
* oversized input lines. Sends a short `bash <file>` line and submits it.
|
|
216
|
+
*/
|
|
217
|
+
export function herdrRunScriptFile(paneId: string, scriptPath: string): void {
|
|
218
|
+
herdrSendText(paneId, `bash ${scriptPath}`)
|
|
219
|
+
herdrSendReturn(paneId)
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** Run a short command in a pane via `herdr pane run` (no shell typing). */
|
|
223
|
+
export function herdrRunInPane(
|
|
224
|
+
paneId: string,
|
|
225
|
+
command: readonly string[],
|
|
226
|
+
): void {
|
|
227
|
+
runHerdr(['pane', 'run', paneId, ...command])
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export type HerdrReadSource =
|
|
231
|
+
| 'visible'
|
|
232
|
+
| 'recent'
|
|
233
|
+
| 'recent-unwrapped'
|
|
234
|
+
| 'detection'
|
|
235
|
+
|
|
236
|
+
/** Read pane terminal output. Defaults to `--source recent`. */
|
|
237
|
+
export function herdrReadPane(
|
|
238
|
+
paneId: string,
|
|
239
|
+
options?: { lines?: number; source?: HerdrReadSource },
|
|
240
|
+
): string {
|
|
241
|
+
const args = ['pane', 'read', paneId, '--source', options?.source ?? 'recent']
|
|
242
|
+
if (options?.lines !== undefined) {
|
|
243
|
+
args.push('--lines', String(options.lines))
|
|
244
|
+
}
|
|
245
|
+
return runHerdr(args)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Read an agent's terminal output: `agent read <target> --source
|
|
250
|
+
* recent-unwrapped --format text`. No `--lines` — avoids truncation and the
|
|
251
|
+
* alternate-screen paging guard herdsman works around. Only works for
|
|
252
|
+
* agent-reported panes (pane.report-agent); plain shell panes fail with
|
|
253
|
+
* `agent_not_found` — verified on 0.9.0.
|
|
254
|
+
*/
|
|
255
|
+
export function herdrReadAgent(target: string): string {
|
|
256
|
+
return runHerdr([
|
|
257
|
+
'agent',
|
|
258
|
+
'read',
|
|
259
|
+
target,
|
|
260
|
+
'--source',
|
|
261
|
+
'recent-unwrapped',
|
|
262
|
+
'--format',
|
|
263
|
+
'text',
|
|
264
|
+
])
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
export interface HerdrWaitOutputResult {
|
|
268
|
+
matched_line: string
|
|
269
|
+
pane_id: string
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Block until pane output matches a regex: `pane wait-output <pane> --regex
|
|
274
|
+
* <pattern> --timeout <ms>`. Throws HerdrError on timeout/nonzero exit.
|
|
275
|
+
*/
|
|
276
|
+
export function herdrWaitOutput(
|
|
277
|
+
paneId: string,
|
|
278
|
+
regex: string,
|
|
279
|
+
timeoutMs: number,
|
|
280
|
+
): HerdrWaitOutputResult {
|
|
281
|
+
return runHerdrEnvelope<HerdrWaitOutputResult>([
|
|
282
|
+
'pane',
|
|
283
|
+
'wait-output',
|
|
284
|
+
'--regex',
|
|
285
|
+
regex,
|
|
286
|
+
paneId,
|
|
287
|
+
'--timeout',
|
|
288
|
+
String(timeoutMs),
|
|
289
|
+
])
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
/** Result payload of `agent list` (envelope). */
|
|
293
|
+
export interface HerdrAgent {
|
|
294
|
+
agent: string
|
|
295
|
+
agent_status?: string
|
|
296
|
+
cwd?: string
|
|
297
|
+
focused?: boolean
|
|
298
|
+
pane_id: string
|
|
299
|
+
tab_id?: string
|
|
300
|
+
workspace_id?: string
|
|
301
|
+
agent_session?: { value?: string }
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** List herdr-known agents. NOTE: `agent list --json` does NOT exist on 0.9.0; the CLI prints the envelope by default. */
|
|
305
|
+
export function herdrAgentList(): HerdrAgent[] {
|
|
306
|
+
const result = runHerdrEnvelope<{ agents?: HerdrAgent[] }>(['agent', 'list'])
|
|
307
|
+
return result.agents ?? []
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** Get one agent by pane id / target. Returns null when herdr reports it gone. */
|
|
311
|
+
export function herdrAgentGet(target: string): HerdrAgent | null {
|
|
312
|
+
const result = runHerdrEnvelope<{ agent?: HerdrAgent | null }>([
|
|
313
|
+
'agent',
|
|
314
|
+
'get',
|
|
315
|
+
target,
|
|
316
|
+
])
|
|
317
|
+
return result.agent ?? null
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** Focus an agent's pane. */
|
|
321
|
+
export function herdrAgentFocus(target: string): void {
|
|
322
|
+
runHerdr(['agent', 'focus', target])
|
|
323
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
// Fire-and-forget child-to-owner messaging (PMR-QCVA).
|
|
2
|
+
// Durable records live at `<dataRoot>/inbox/<parentSessionId>/<childId>-<seq>.json`.
|
|
3
|
+
// The child's message_owner tool writes one and returns immediately; the
|
|
4
|
+
// parent's 1s status-refresh loop drains the inbox, coalesces all records
|
|
5
|
+
// from the tick into ONE `subagent_message` steer, and deletes each drained
|
|
6
|
+
// record afterwards.
|
|
7
|
+
//
|
|
8
|
+
// AIDEV-NOTE: at-least-once window — records are unlinked only AFTER the
|
|
9
|
+
// parent's sendMessage succeeds. A crash (or a stale pi instance after
|
|
10
|
+
// /reload) before the unlink re-delivers the same messages on the next tick
|
|
11
|
+
// (duplicate turn in the worst case). Mirrors the peers inbox discipline.
|
|
12
|
+
import { randomUUID } from 'node:crypto'
|
|
13
|
+
import {
|
|
14
|
+
closeSync,
|
|
15
|
+
fsyncSync,
|
|
16
|
+
mkdirSync,
|
|
17
|
+
openSync,
|
|
18
|
+
readdirSync,
|
|
19
|
+
readFileSync,
|
|
20
|
+
renameSync,
|
|
21
|
+
statSync,
|
|
22
|
+
unlinkSync,
|
|
23
|
+
writeSync,
|
|
24
|
+
} from 'node:fs'
|
|
25
|
+
import { join } from 'node:path'
|
|
26
|
+
import { ensureSubagentsDataDir, subagentsDataRoot } from './dataroot.ts'
|
|
27
|
+
import { capStatusLines } from './status.ts'
|
|
28
|
+
|
|
29
|
+
export const MESSAGE_VERSION = 1
|
|
30
|
+
export const OWNER_MESSAGE_MAX_BYTES = 8192
|
|
31
|
+
|
|
32
|
+
export interface OwnerMessage {
|
|
33
|
+
version: number
|
|
34
|
+
messageId: string
|
|
35
|
+
childId: string
|
|
36
|
+
name?: string
|
|
37
|
+
message: string
|
|
38
|
+
sentAt: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function sanitizeId(id: string): string {
|
|
42
|
+
const safe = id.replace(/[^A-Za-z0-9._-]/g, '_')
|
|
43
|
+
if (safe === '' || safe === '.' || safe === '..') return '_'
|
|
44
|
+
return safe
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function inboxBaseDir(root?: string): string {
|
|
48
|
+
return ensureSubagentsDataDir('inbox', root ?? subagentsDataRoot())
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function ownerInboxDir(parentSessionId: string, root?: string): string {
|
|
52
|
+
const dir = join(inboxBaseDir(root), sanitizeId(parentSessionId))
|
|
53
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 })
|
|
54
|
+
return dir
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function atomicWrite(path: string, contents: string): void {
|
|
58
|
+
const tmpPath = `${path}.${process.pid}.tmp`
|
|
59
|
+
const fd = openSync(tmpPath, 'w', 0o600)
|
|
60
|
+
try {
|
|
61
|
+
writeSync(fd, contents)
|
|
62
|
+
fsyncSync(fd)
|
|
63
|
+
} finally {
|
|
64
|
+
closeSync(fd)
|
|
65
|
+
}
|
|
66
|
+
renameSync(tmpPath, path)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function nextSeq(dir: string, childId: string): number {
|
|
70
|
+
const prefix = `${sanitizeId(childId)}-`
|
|
71
|
+
let max = 0
|
|
72
|
+
for (const entry of readdirSync(dir)) {
|
|
73
|
+
if (!entry.startsWith(prefix) || !entry.endsWith('.json')) continue
|
|
74
|
+
const match = /^(\d+)\.json$/.exec(entry.slice(prefix.length))
|
|
75
|
+
if (match) max = Math.max(max, Number.parseInt(match[1], 10))
|
|
76
|
+
}
|
|
77
|
+
return max + 1
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function messagePath(dir: string, childId: string, seq: number): string {
|
|
81
|
+
return join(
|
|
82
|
+
dir,
|
|
83
|
+
`${sanitizeId(childId)}-${String(seq).padStart(6, '0')}.json`,
|
|
84
|
+
)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Write a durable message to the owner's inbox. Exclusive-create with retry
|
|
89
|
+
* on the allocated seq so concurrent senders never overwrite each other.
|
|
90
|
+
* Throws a clear error above the 8 KiB cap.
|
|
91
|
+
*/
|
|
92
|
+
export function sendOwnerMessage(params: {
|
|
93
|
+
parentSessionId: string
|
|
94
|
+
childId: string
|
|
95
|
+
name?: string
|
|
96
|
+
message: string
|
|
97
|
+
root?: string
|
|
98
|
+
}): { path: string; messageId: string } {
|
|
99
|
+
const record: OwnerMessage = {
|
|
100
|
+
version: MESSAGE_VERSION,
|
|
101
|
+
messageId: randomUUID(),
|
|
102
|
+
childId: params.childId,
|
|
103
|
+
message: params.message,
|
|
104
|
+
sentAt: new Date().toISOString(),
|
|
105
|
+
}
|
|
106
|
+
if (params.name !== undefined) record.name = params.name
|
|
107
|
+
const payload = JSON.stringify(record)
|
|
108
|
+
const size = Buffer.byteLength(payload)
|
|
109
|
+
if (size > OWNER_MESSAGE_MAX_BYTES) {
|
|
110
|
+
throw new Error(
|
|
111
|
+
`message is ${size} bytes; the owner-inbox cap is ${OWNER_MESSAGE_MAX_BYTES} bytes. Split or shorten the message.`,
|
|
112
|
+
)
|
|
113
|
+
}
|
|
114
|
+
const dir = ownerInboxDir(params.parentSessionId, params.root)
|
|
115
|
+
// AIDEV-NOTE: seq allocation + exclusive create — a concurrent sender that
|
|
116
|
+
// wins the same seq bumps our attempt and we retry with the next number.
|
|
117
|
+
for (let attempt = 0; attempt < 5; attempt += 1) {
|
|
118
|
+
const seq = nextSeq(dir, params.childId)
|
|
119
|
+
const path = messagePath(dir, params.childId, seq)
|
|
120
|
+
let fd: number
|
|
121
|
+
try {
|
|
122
|
+
fd = openSync(path, 'wx', 0o600)
|
|
123
|
+
} catch (error) {
|
|
124
|
+
if ((error as NodeJS.ErrnoException).code === 'EEXIST') continue
|
|
125
|
+
throw error
|
|
126
|
+
}
|
|
127
|
+
try {
|
|
128
|
+
writeSync(fd, payload)
|
|
129
|
+
fsyncSync(fd)
|
|
130
|
+
} finally {
|
|
131
|
+
closeSync(fd)
|
|
132
|
+
}
|
|
133
|
+
return { path, messageId: record.messageId }
|
|
134
|
+
}
|
|
135
|
+
throw new Error('owner-inbox contention: could not allocate a message slot')
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** An inbox file plus its parsed message (only structurally valid ones). */
|
|
139
|
+
export interface OwnerInboxEntry {
|
|
140
|
+
path: string
|
|
141
|
+
message: OwnerMessage
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Read all valid owner-inbox messages, ordered by filename (seq). */
|
|
145
|
+
export function readOwnerInbox(
|
|
146
|
+
parentSessionId: string,
|
|
147
|
+
root?: string,
|
|
148
|
+
): OwnerInboxEntry[] {
|
|
149
|
+
let entries: string[]
|
|
150
|
+
const dir = ownerInboxDir(parentSessionId, root)
|
|
151
|
+
try {
|
|
152
|
+
entries = readdirSync(dir)
|
|
153
|
+
} catch {
|
|
154
|
+
return []
|
|
155
|
+
}
|
|
156
|
+
const result: OwnerInboxEntry[] = []
|
|
157
|
+
for (const entry of entries.sort()) {
|
|
158
|
+
if (!entry.endsWith('.json')) continue
|
|
159
|
+
const path = join(dir, entry)
|
|
160
|
+
try {
|
|
161
|
+
if (statSync(path).isDirectory()) continue
|
|
162
|
+
const parsed: unknown = JSON.parse(readFileSync(path, 'utf8'))
|
|
163
|
+
if (parsed == null || typeof parsed !== 'object') continue
|
|
164
|
+
const candidate = parsed as Record<string, unknown>
|
|
165
|
+
if (candidate.version !== MESSAGE_VERSION) continue
|
|
166
|
+
if (typeof candidate.messageId !== 'string') continue
|
|
167
|
+
if (typeof candidate.childId !== 'string') continue
|
|
168
|
+
if (typeof candidate.message !== 'string') continue
|
|
169
|
+
if (typeof candidate.sentAt !== 'string') continue
|
|
170
|
+
result.push({ path, message: parsed as OwnerMessage })
|
|
171
|
+
} catch {
|
|
172
|
+
// Malformed / partially visible — never surfaced.
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return result
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export function removeOwnerMessage(path: string): void {
|
|
179
|
+
try {
|
|
180
|
+
unlinkSync(path)
|
|
181
|
+
} catch {}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export interface CoalescedOwnerMessages {
|
|
185
|
+
lines: string[]
|
|
186
|
+
visibleLines: string[]
|
|
187
|
+
overflow: number
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* Pure coalescing + line-cap: one bullet per message, capped at lineLimit
|
|
192
|
+
* with an overflow count (capStatusLines precedent). Returns the full lines
|
|
193
|
+
* (for details) and the capped view.
|
|
194
|
+
*/
|
|
195
|
+
export function coalesceOwnerMessages(
|
|
196
|
+
entries: OwnerInboxEntry[],
|
|
197
|
+
lineLimit: number,
|
|
198
|
+
): CoalescedOwnerMessages {
|
|
199
|
+
const lines = entries.map((entry) => {
|
|
200
|
+
const who = entry.message.name || entry.message.childId
|
|
201
|
+
const firstLine = entry.message.message.split('\n')[0]
|
|
202
|
+
return `${who}: ${firstLine}`
|
|
203
|
+
})
|
|
204
|
+
const capped = capStatusLines(lines, lineLimit)
|
|
205
|
+
return {
|
|
206
|
+
lines,
|
|
207
|
+
visibleLines: capped.visibleLines,
|
|
208
|
+
overflow: capped.overflow,
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// AIDEV-NOTE: exported for tests — ids are filesystem path components.
|
|
213
|
+
export const __inboxInternals__ = { sanitizeId }
|