@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,191 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
|
|
2
|
+
import { dirname, join } from 'node:path'
|
|
3
|
+
import { CONFIG_DIR_NAME, getAgentDir } from '@mariozechner/pi-coding-agent'
|
|
4
|
+
import { type Static, Type } from '@sinclair/typebox'
|
|
5
|
+
import { Value } from '@sinclair/typebox/value'
|
|
6
|
+
|
|
7
|
+
// AIDEV-NOTE: extension-owned config per repo convention. Global:
|
|
8
|
+
// <agentDir>/pi-subagents/config.json. Project override:
|
|
9
|
+
// <cwd>/<CONFIG_DIR_NAME>/pi-subagents/config.json. Parsed at this boundary
|
|
10
|
+
// (JSON.parse → unknown → TypeBox) — never cast elsewhere.
|
|
11
|
+
export const SUBAGENTS_CONFIG_DIR = 'pi-subagents'
|
|
12
|
+
|
|
13
|
+
const SubagentsConfigSchema = Type.Object(
|
|
14
|
+
{
|
|
15
|
+
$schema: Type.Optional(Type.String()),
|
|
16
|
+
status: Type.Object(
|
|
17
|
+
{
|
|
18
|
+
enabled: Type.Boolean(),
|
|
19
|
+
// AIDEV-NOTE (PMR-AD0H): hide the "Subagents · N running" widget
|
|
20
|
+
// completely while no subagent exists. Default on — the persistent
|
|
21
|
+
// idle box is an opt-out (false keeps it visible at zero).
|
|
22
|
+
hideWhenIdle: Type.Optional(Type.Boolean()),
|
|
23
|
+
},
|
|
24
|
+
{ additionalProperties: false },
|
|
25
|
+
),
|
|
26
|
+
// AIDEV-NOTE (PMR-1EC3): off by default — context retirement changes what
|
|
27
|
+
// the model sees, so it is an explicit opt-in. Absent = disabled.
|
|
28
|
+
// AIDEV-NOTE (PMR-Y4PV): reserveTokens / keepRecentTokens /
|
|
29
|
+
// backgroundTokens are RESERVED, not yet implemented — accepted so tuning
|
|
30
|
+
// configs written against pi-durable's settings.compaction vocabulary
|
|
31
|
+
// ({ enabled, reserveTokens, keepRecentTokens, backgroundTokens }) stay
|
|
32
|
+
// valid. Semantics map onto our finish-and-hand-off retirement model
|
|
33
|
+
// (not squeeze-and-continue compaction): reserveTokens = headroom that
|
|
34
|
+
// triggers hand-off, keepRecentTokens = recent context preserved into
|
|
35
|
+
// the hand-off, backgroundTokens = budget for background pre-retirement
|
|
36
|
+
// summarization. When pi core lands native compaction settings,
|
|
37
|
+
// migrating is a rename, not a redesign.
|
|
38
|
+
contextRetirement: Type.Optional(
|
|
39
|
+
Type.Object(
|
|
40
|
+
{
|
|
41
|
+
enabled: Type.Boolean(),
|
|
42
|
+
reserveTokens: Type.Optional(Type.Number()),
|
|
43
|
+
keepRecentTokens: Type.Optional(Type.Number()),
|
|
44
|
+
backgroundTokens: Type.Optional(Type.Number()),
|
|
45
|
+
},
|
|
46
|
+
{ additionalProperties: false },
|
|
47
|
+
),
|
|
48
|
+
),
|
|
49
|
+
// AIDEV-NOTE (PMR-YFRB): dead-turn stall watchdog — opt-OUT, absent
|
|
50
|
+
// config = watchdog on. `enabled: false` restores the legacy never-age
|
|
51
|
+
// behavior (present+active snapshots never classify as stalled and the
|
|
52
|
+
// poll loop never escalates on the stall deadline).
|
|
53
|
+
// AIDEV-NOTE (PMR-KT90): opt-IN retention — absent config = legacy
|
|
54
|
+
// no-pruning behavior; setting a positive integer age enables pruning.
|
|
55
|
+
retentionDays: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
56
|
+
watchdog: Type.Optional(
|
|
57
|
+
Type.Object(
|
|
58
|
+
{
|
|
59
|
+
enabled: Type.Optional(Type.Boolean()),
|
|
60
|
+
streamStallAfterMs: Type.Optional(Type.Number()),
|
|
61
|
+
quietStallAfterMs: Type.Optional(Type.Number()),
|
|
62
|
+
},
|
|
63
|
+
{ additionalProperties: false },
|
|
64
|
+
),
|
|
65
|
+
),
|
|
66
|
+
},
|
|
67
|
+
{ additionalProperties: false },
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
export type SubagentsConfig = Static<typeof SubagentsConfigSchema>
|
|
71
|
+
|
|
72
|
+
export interface WatchdogConfig {
|
|
73
|
+
enabled: boolean
|
|
74
|
+
streamStallAfterMs: number
|
|
75
|
+
quietStallAfterMs: number
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export const DEFAULT_WATCHDOG_CONFIG: WatchdogConfig = {
|
|
79
|
+
enabled: true,
|
|
80
|
+
streamStallAfterMs: 150_000,
|
|
81
|
+
quietStallAfterMs: 1_800_000,
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export const DEFAULT_SUBAGENTS_CONFIG: SubagentsConfig = {
|
|
85
|
+
status: { enabled: true, hideWhenIdle: true },
|
|
86
|
+
contextRetirement: { enabled: false },
|
|
87
|
+
watchdog: DEFAULT_WATCHDOG_CONFIG,
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export function globalSubagentsConfigPath(
|
|
91
|
+
agentDir: string = getAgentDir(),
|
|
92
|
+
): string {
|
|
93
|
+
return join(agentDir, SUBAGENTS_CONFIG_DIR, 'config.json')
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function projectSubagentsConfigPath(cwd: string): string {
|
|
97
|
+
return join(cwd, CONFIG_DIR_NAME, SUBAGENTS_CONFIG_DIR, 'config.json')
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export function validateSubagentsConfig(
|
|
101
|
+
raw: unknown,
|
|
102
|
+
source: string,
|
|
103
|
+
): SubagentsConfig {
|
|
104
|
+
if (!Value.Check(SubagentsConfigSchema, raw)) {
|
|
105
|
+
let firstMessage = 'is invalid'
|
|
106
|
+
for (const error of Value.Errors(SubagentsConfigSchema, raw)) {
|
|
107
|
+
firstMessage = `${error.path === '' ? 'config' : error.path} ${error.message}`
|
|
108
|
+
break
|
|
109
|
+
}
|
|
110
|
+
throw new Error(`Invalid subagents config in ${source}: ${firstMessage}`)
|
|
111
|
+
}
|
|
112
|
+
// Reconstruct instead of returning raw so metadata keys like $schema never
|
|
113
|
+
// leak into the typed config value.
|
|
114
|
+
const config: SubagentsConfig = { status: raw.status }
|
|
115
|
+
if (raw.contextRetirement !== undefined) {
|
|
116
|
+
config.contextRetirement = raw.contextRetirement
|
|
117
|
+
}
|
|
118
|
+
if (raw.retentionDays !== undefined) {
|
|
119
|
+
config.retentionDays = raw.retentionDays
|
|
120
|
+
}
|
|
121
|
+
if (raw.watchdog !== undefined) {
|
|
122
|
+
config.watchdog = raw.watchdog
|
|
123
|
+
}
|
|
124
|
+
return config
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
function readSubagentsConfigFile(
|
|
128
|
+
path: string,
|
|
129
|
+
source: string,
|
|
130
|
+
): SubagentsConfig | undefined {
|
|
131
|
+
if (!existsSync(path)) return undefined
|
|
132
|
+
let parsed: unknown
|
|
133
|
+
try {
|
|
134
|
+
parsed = JSON.parse(readFileSync(path, 'utf8')) as unknown
|
|
135
|
+
} catch (error) {
|
|
136
|
+
const detail = error instanceof Error ? error.message : String(error)
|
|
137
|
+
throw new Error(`Invalid JSON in subagents config ${source}: ${detail}`)
|
|
138
|
+
}
|
|
139
|
+
return validateSubagentsConfig(parsed, source)
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Scaffold the default global config when (and only when) it is missing.
|
|
144
|
+
* Never touches an existing or malformed file — failures to parse surface
|
|
145
|
+
* from loadSubagentsConfig instead.
|
|
146
|
+
*/
|
|
147
|
+
export function scaffoldGlobalSubagentsConfig(
|
|
148
|
+
agentDir: string = getAgentDir(),
|
|
149
|
+
): string {
|
|
150
|
+
const path = globalSubagentsConfigPath(agentDir)
|
|
151
|
+
if (existsSync(path)) return path
|
|
152
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
153
|
+
writeFileSync(
|
|
154
|
+
path,
|
|
155
|
+
`${JSON.stringify(
|
|
156
|
+
{
|
|
157
|
+
$schema: 'https://json-schema.org/schema',
|
|
158
|
+
...DEFAULT_SUBAGENTS_CONFIG,
|
|
159
|
+
},
|
|
160
|
+
null,
|
|
161
|
+
2,
|
|
162
|
+
)}\n`,
|
|
163
|
+
{ mode: 0o600 },
|
|
164
|
+
)
|
|
165
|
+
return path
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
export interface LoadedSubagentsConfig {
|
|
169
|
+
config: SubagentsConfig
|
|
170
|
+
source: string
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Load the effective config: project override wins, otherwise the global
|
|
175
|
+
* config (scaffolded with defaults if missing). Throws on invalid JSON or
|
|
176
|
+
* invalid shape at either location.
|
|
177
|
+
*/
|
|
178
|
+
export function loadSubagentsConfig(
|
|
179
|
+
cwd?: string,
|
|
180
|
+
agentDir: string = getAgentDir(),
|
|
181
|
+
): LoadedSubagentsConfig {
|
|
182
|
+
if (cwd !== undefined) {
|
|
183
|
+
const projectPath = projectSubagentsConfigPath(cwd)
|
|
184
|
+
const project = readSubagentsConfigFile(projectPath, projectPath)
|
|
185
|
+
if (project !== undefined) return { config: project, source: projectPath }
|
|
186
|
+
}
|
|
187
|
+
const globalPath = scaffoldGlobalSubagentsConfig(agentDir)
|
|
188
|
+
const global = readSubagentsConfigFile(globalPath, globalPath)
|
|
189
|
+
if (global !== undefined) return { config: global, source: globalPath }
|
|
190
|
+
return { config: DEFAULT_SUBAGENTS_CONFIG, source: globalPath }
|
|
191
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
// Durable request/ack handshake for parent→child control ops (interrupt,
|
|
2
|
+
// answer). Ported from pi-herdsman's RequestRecord/lastAck discipline
|
|
3
|
+
// (Apache-2.0, mailbox.ts schema v5 essence), scoped down per plan PMR-DNPZ:
|
|
4
|
+
// the parent writes `<dataRoot>/asks/<childId>.control.json`, the child
|
|
5
|
+
// extension answers with an ack sidecar `<sessionFile>.ack`, and the parent's
|
|
6
|
+
// 1s status-refresh loop correlates the two.
|
|
7
|
+
//
|
|
8
|
+
// AIDEV-NOTE: at-least-once window — the escape keypress remains the actual
|
|
9
|
+
// delivery mechanism; the control record is durable INTENT so a future
|
|
10
|
+
// reattach (PMR-WXG0/Z5KR) can observe it. If the ack write is lost (child
|
|
11
|
+
// crash between abort and sidecar write), the parent expires the request and
|
|
12
|
+
// falls back to legacy fire-and-forget semantics — a stale record alone never
|
|
13
|
+
// re-applies a request today; any future re-apply path must correlate on
|
|
14
|
+
// requestId before acting.
|
|
15
|
+
import {
|
|
16
|
+
closeSync,
|
|
17
|
+
fsyncSync,
|
|
18
|
+
openSync,
|
|
19
|
+
readFileSync,
|
|
20
|
+
renameSync,
|
|
21
|
+
unlinkSync,
|
|
22
|
+
writeFileSync,
|
|
23
|
+
writeSync,
|
|
24
|
+
} from 'node:fs'
|
|
25
|
+
import { join } from 'node:path'
|
|
26
|
+
import { ensureSubagentsDataDir, subagentsDataRoot } from './dataroot.ts'
|
|
27
|
+
|
|
28
|
+
export type ControlRequestKind = 'interrupt' | 'answer'
|
|
29
|
+
|
|
30
|
+
// Typed rejection codes, ported from herdsman's ack vocabulary. The child
|
|
31
|
+
// currently only ever emits 'idle' (turn aborted cleanly); the rest exist so
|
|
32
|
+
// future child-side gates (busy mid-tool, identity mismatch, ...) share one
|
|
33
|
+
// wire format instead of inventing strings later.
|
|
34
|
+
export type AckCode =
|
|
35
|
+
| 'busy'
|
|
36
|
+
| 'idle'
|
|
37
|
+
| 'invalid'
|
|
38
|
+
| 'identity'
|
|
39
|
+
| 'ambiguous'
|
|
40
|
+
| 'incompatible'
|
|
41
|
+
|
|
42
|
+
export interface ControlRecord {
|
|
43
|
+
requestId: string
|
|
44
|
+
childId: string
|
|
45
|
+
sessionFile: string
|
|
46
|
+
kind: ControlRequestKind
|
|
47
|
+
payload: Record<string, unknown>
|
|
48
|
+
sentAt: string
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface ControlAck {
|
|
52
|
+
requestId: string
|
|
53
|
+
accepted: boolean
|
|
54
|
+
code: AckCode
|
|
55
|
+
message?: string
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function sanitizeChildId(childId: string): string {
|
|
59
|
+
const safe = childId.replace(/[^A-Za-z0-9._-]/g, '_')
|
|
60
|
+
if (safe === '' || safe === '.' || safe === '..') return '_'
|
|
61
|
+
return safe
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Durable control record path: `<dataRoot>/asks/<childId>.control.json`. */
|
|
65
|
+
export function controlRecordPath(childId: string, root?: string): string {
|
|
66
|
+
return join(
|
|
67
|
+
ensureSubagentsDataDir('asks', root ?? subagentsDataRoot()),
|
|
68
|
+
`${sanitizeChildId(childId)}.control.json`,
|
|
69
|
+
)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Ack sidecar path, colocated with the child session file. */
|
|
73
|
+
export function ackSidecarPath(sessionFile: string): string {
|
|
74
|
+
return `${sessionFile}.ack`
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// AIDEV-NOTE: atomic write (tmp + fsync + rename) so the parent's 1s poller
|
|
78
|
+
// never observes a partial record. Latest intent wins — a second request for
|
|
79
|
+
// the same child overwrites the first; the superseded requestId then fails
|
|
80
|
+
// ack correlation and times out on the parent side.
|
|
81
|
+
export function writeControlRecord(record: ControlRecord, root?: string): void {
|
|
82
|
+
const path = controlRecordPath(record.childId, root)
|
|
83
|
+
const tmpPath = `${path}.tmp`
|
|
84
|
+
const fd = openSync(tmpPath, 'w', 0o600)
|
|
85
|
+
try {
|
|
86
|
+
writeSync(fd, JSON.stringify(record))
|
|
87
|
+
fsyncSync(fd)
|
|
88
|
+
} finally {
|
|
89
|
+
closeSync(fd)
|
|
90
|
+
}
|
|
91
|
+
renameSync(tmpPath, path)
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** Read a control record; returns null when missing, malformed, or not an object. */
|
|
95
|
+
export function readControlRecord(
|
|
96
|
+
childId: string,
|
|
97
|
+
root?: string,
|
|
98
|
+
): ControlRecord | null {
|
|
99
|
+
let raw: string
|
|
100
|
+
try {
|
|
101
|
+
raw = readFileSync(controlRecordPath(childId, root), 'utf8')
|
|
102
|
+
} catch {
|
|
103
|
+
return null
|
|
104
|
+
}
|
|
105
|
+
try {
|
|
106
|
+
const parsed = JSON.parse(raw) as unknown
|
|
107
|
+
if (parsed == null || typeof parsed !== 'object') return null
|
|
108
|
+
const record = parsed as Record<string, unknown>
|
|
109
|
+
if (typeof record.requestId !== 'string') return null
|
|
110
|
+
return parsed as ControlRecord
|
|
111
|
+
} catch {
|
|
112
|
+
return null
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export function removeControlRecord(childId: string, root?: string): void {
|
|
117
|
+
try {
|
|
118
|
+
unlinkSync(controlRecordPath(childId, root))
|
|
119
|
+
} catch {}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Child side: write the ack sidecar. Best-effort callers wrap in try/catch. */
|
|
123
|
+
export function writeAckSidecar(sessionFile: string, ack: ControlAck): void {
|
|
124
|
+
writeFileSync(ackSidecarPath(sessionFile), JSON.stringify(ack))
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Parent side: read the ack sidecar; null when missing or malformed. */
|
|
128
|
+
export function readAckSidecar(sessionFile: string): ControlAck | null {
|
|
129
|
+
try {
|
|
130
|
+
const parsed = JSON.parse(
|
|
131
|
+
readFileSync(ackSidecarPath(sessionFile), 'utf8'),
|
|
132
|
+
) as unknown
|
|
133
|
+
if (parsed == null || typeof parsed !== 'object') return null
|
|
134
|
+
const ack = parsed as Record<string, unknown>
|
|
135
|
+
if (typeof ack.requestId !== 'string') return null
|
|
136
|
+
if (typeof ack.accepted !== 'boolean') return null
|
|
137
|
+
return parsed as ControlAck
|
|
138
|
+
} catch {
|
|
139
|
+
return null
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function removeAckSidecar(sessionFile: string): void {
|
|
144
|
+
try {
|
|
145
|
+
unlinkSync(ackSidecarPath(sessionFile))
|
|
146
|
+
} catch {}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* Identity revalidation before an ack is applied (herdsman discipline): the
|
|
151
|
+
* ack must carry the requestId we sent, and the control record must still
|
|
152
|
+
* name the childId + sessionFile we are polling. A mismatched or wrong-id ack
|
|
153
|
+
* is ignored, never guessed from.
|
|
154
|
+
*/
|
|
155
|
+
export function ackMatches(params: {
|
|
156
|
+
record: ControlRecord
|
|
157
|
+
ack: ControlAck
|
|
158
|
+
childId: string
|
|
159
|
+
sessionFile: string
|
|
160
|
+
}): boolean {
|
|
161
|
+
return (
|
|
162
|
+
params.record.requestId === params.ack.requestId &&
|
|
163
|
+
params.record.childId === params.childId &&
|
|
164
|
+
params.record.sessionFile === params.sessionFile
|
|
165
|
+
)
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// AIDEV-NOTE: completion ack = the existing `.exit` sidecar. A child that
|
|
169
|
+
// exits between request and ack needs no new machinery: the watcher observes
|
|
170
|
+
// `.exit`/`.code` as today and closes the entry; the pending request simply
|
|
171
|
+
// times out and any leftover control record is residue (single small file,
|
|
172
|
+
// harmless). Do not build a separate completion-ack protocol.
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { chmodSync, mkdirSync } from 'node:fs'
|
|
2
|
+
import { join } from 'node:path'
|
|
3
|
+
import { getAgentDir } from '@mariozechner/pi-coding-agent'
|
|
4
|
+
|
|
5
|
+
export type SubagentsDataDirName =
|
|
6
|
+
| 'results'
|
|
7
|
+
| 'result-ref-reservations'
|
|
8
|
+
| 'peers'
|
|
9
|
+
| 'asks'
|
|
10
|
+
| 'assignments'
|
|
11
|
+
| 'inbox'
|
|
12
|
+
| 'delivered'
|
|
13
|
+
| 'interrupts'
|
|
14
|
+
| 'spawn-seq'
|
|
15
|
+
| 'retired'
|
|
16
|
+
| 'tool-effects'
|
|
17
|
+
| 'peer-bindings'
|
|
18
|
+
|
|
19
|
+
export const SUBAGENTS_DATA_DIR_NAMES: readonly SubagentsDataDirName[] = [
|
|
20
|
+
'results',
|
|
21
|
+
'result-ref-reservations',
|
|
22
|
+
'peers',
|
|
23
|
+
'asks',
|
|
24
|
+
'assignments',
|
|
25
|
+
'inbox',
|
|
26
|
+
'delivered',
|
|
27
|
+
'interrupts',
|
|
28
|
+
'spawn-seq',
|
|
29
|
+
'retired',
|
|
30
|
+
'tool-effects',
|
|
31
|
+
'peer-bindings',
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
/** Durable data root for pi-interactive-subagents: <agentDir>/pi-subagents/. */
|
|
35
|
+
export function subagentsDataRoot(agentDir: string = getAgentDir()): string {
|
|
36
|
+
return join(agentDir, 'pi-subagents')
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// AIDEV-NOTE: lazily creates the named data subdir on first use. Private
|
|
40
|
+
// per-user data (subagent results, peer inboxes) — enforce 0700 explicitly
|
|
41
|
+
// because umask may weaken mkdir's mode.
|
|
42
|
+
export function ensureSubagentsDataDir(
|
|
43
|
+
name: SubagentsDataDirName,
|
|
44
|
+
root: string = subagentsDataRoot(),
|
|
45
|
+
): string {
|
|
46
|
+
mkdirSync(root, { recursive: true })
|
|
47
|
+
chmodSync(root, 0o700)
|
|
48
|
+
const dir = join(root, name)
|
|
49
|
+
mkdirSync(dir, { recursive: true })
|
|
50
|
+
chmodSync(dir, 0o700)
|
|
51
|
+
return dir
|
|
52
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// Exactly-once mailbox delivery dedup (PMR-KY0E).
|
|
2
|
+
//
|
|
3
|
+
// Each durable mailbox record (ask replies, owner-inbox messages, peer-inbox
|
|
4
|
+
// messages, control requests) carries a requestId. Drains consult this set
|
|
5
|
+
// BEFORE injecting the turn and mark the id after a successful send, so a
|
|
6
|
+
// crash between send and record-unlink suppresses the redelivery.
|
|
7
|
+
//
|
|
8
|
+
// AIDEV-NOTE: marker-file set (store.ts reservation precedent) — a delivered
|
|
9
|
+
// id is an exclusive-create marker under
|
|
10
|
+
// <dataRoot>/delivered/<scope>/<requestId>. Exclusive create is atomic by
|
|
11
|
+
// construction, so no read-modify-write discipline is needed. Markers are
|
|
12
|
+
// deliberately never cleaned up (same policy as result-ref-reservations).
|
|
13
|
+
// Legacy records: every record version currently validated by the readers
|
|
14
|
+
// (asks askId, inbox/peers messageId, control requestId) already carries an
|
|
15
|
+
// id, so there is no pre-dedup shape to migrate — a missing id fails closed
|
|
16
|
+
// in the readers as before.
|
|
17
|
+
import {
|
|
18
|
+
closeSync,
|
|
19
|
+
existsSync,
|
|
20
|
+
fsyncSync,
|
|
21
|
+
mkdirSync,
|
|
22
|
+
openSync,
|
|
23
|
+
writeSync,
|
|
24
|
+
} from 'node:fs'
|
|
25
|
+
import { join } from 'node:path'
|
|
26
|
+
import { ensureSubagentsDataDir, subagentsDataRoot } from './dataroot.ts'
|
|
27
|
+
|
|
28
|
+
function sanitizeScope(scope: string): string {
|
|
29
|
+
const safe = scope.replace(/[^A-Za-z0-9._-]/g, '_')
|
|
30
|
+
if (safe === '' || safe === '.' || safe === '..') return '_'
|
|
31
|
+
return safe
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Marker path for a delivered requestId within a scope. */
|
|
35
|
+
export function deliveredMarkerPath(
|
|
36
|
+
scope: string,
|
|
37
|
+
requestId: string,
|
|
38
|
+
root: string = subagentsDataRoot(),
|
|
39
|
+
): string {
|
|
40
|
+
return join(
|
|
41
|
+
ensureSubagentsDataDir('delivered', root),
|
|
42
|
+
sanitizeScope(scope),
|
|
43
|
+
sanitizeScope(requestId),
|
|
44
|
+
)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** True when this requestId was already marked delivered in this scope. */
|
|
48
|
+
export function hasDelivered(
|
|
49
|
+
scope: string,
|
|
50
|
+
requestId: string,
|
|
51
|
+
root: string = subagentsDataRoot(),
|
|
52
|
+
): boolean {
|
|
53
|
+
return existsSync(deliveredMarkerPath(scope, requestId, root))
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Mark a requestId delivered. Returns true when newly marked (deliver it),
|
|
58
|
+
* false when it was already marked (suppress the redelivery).
|
|
59
|
+
*/
|
|
60
|
+
export function markDelivered(
|
|
61
|
+
scope: string,
|
|
62
|
+
requestId: string,
|
|
63
|
+
root: string = subagentsDataRoot(),
|
|
64
|
+
): boolean {
|
|
65
|
+
const marker = deliveredMarkerPath(scope, requestId, root)
|
|
66
|
+
mkdirSync(join(marker, '..'), { recursive: true, mode: 0o700 })
|
|
67
|
+
let fd: number
|
|
68
|
+
try {
|
|
69
|
+
fd = openSync(marker, 'wx', 0o600)
|
|
70
|
+
} catch (error) {
|
|
71
|
+
if ((error as NodeJS.ErrnoException).code === 'EEXIST') return false
|
|
72
|
+
throw error
|
|
73
|
+
}
|
|
74
|
+
try {
|
|
75
|
+
writeSync(fd, '1')
|
|
76
|
+
fsyncSync(fd)
|
|
77
|
+
} finally {
|
|
78
|
+
closeSync(fd)
|
|
79
|
+
}
|
|
80
|
+
return true
|
|
81
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// AIDEV-NOTE (PMR-HFK1, pi-flow observability M1): flow attribution env
|
|
2
|
+
// forwarding. Pure module — no fs, no process reads inside the helpers; the
|
|
3
|
+
// spawn/resume sites pass the parent env explicitly so tests stay pure. The
|
|
4
|
+
// /flow loop (pi-flow package) stamps PI_FLOW_REF / PI_FLOW_PHASE /
|
|
5
|
+
// PI_FLOW_TRACEPARENT into the MAIN process env; this module copies them
|
|
6
|
+
// into each child's `tab create --env` block and adds PI_FLOW_SUBTASK when
|
|
7
|
+
// the spawn maps 1:1 to a plan task. Children therefore join the flow's
|
|
8
|
+
// trace tree and per-ticket / per-subtask cost becomes computable.
|
|
9
|
+
//
|
|
10
|
+
// Values are validated BEFORE they enter env (same safe-charset rule as
|
|
11
|
+
// pi-flow's runFileName — a ref that can never be a filename can never be
|
|
12
|
+
// an env value either). Invalid parent values are dropped fail-closed, never
|
|
13
|
+
// forwarded mangled.
|
|
14
|
+
|
|
15
|
+
/** Safe charset for flow refs / phases / subtask refs (runFileName rule). */
|
|
16
|
+
export const FLOW_VALUE_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/
|
|
17
|
+
|
|
18
|
+
/** W3C traceparent shape (version-traceid-spanid-flags, lowercase hex). */
|
|
19
|
+
export const TRACEPARENT_RE =
|
|
20
|
+
/^[0-9a-f]{2}-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$/
|
|
21
|
+
|
|
22
|
+
export function isValidFlowValue(value: string | undefined): boolean {
|
|
23
|
+
if (value === undefined) return false
|
|
24
|
+
return FLOW_VALUE_RE.test(value)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function isValidTraceparent(value: string | undefined): boolean {
|
|
28
|
+
if (value === undefined) return false
|
|
29
|
+
return TRACEPARENT_RE.test(value)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Copy the flow attribution vars from the parent env into a child env block.
|
|
34
|
+
* Pure: mutates only `env`, reads only `parentEnv`. Keys absent or invalid
|
|
35
|
+
* in the parent are simply not forwarded (fail-closed). `subtask` is the
|
|
36
|
+
* agent-supplied plan-task ref for a 1:1 worker spawn — omitted (or invalid)
|
|
37
|
+
* means the child is a scout/general worker and gets no subtask stamp.
|
|
38
|
+
*/
|
|
39
|
+
export function applyFlowEnv(
|
|
40
|
+
env: Record<string, string>,
|
|
41
|
+
parentEnv: Record<string, string | undefined>,
|
|
42
|
+
subtask?: string,
|
|
43
|
+
): void {
|
|
44
|
+
const ref = parentEnv.PI_FLOW_REF
|
|
45
|
+
if (isValidFlowValue(ref)) env.PI_FLOW_REF = ref as string
|
|
46
|
+
const phase = parentEnv.PI_FLOW_PHASE
|
|
47
|
+
if (isValidFlowValue(phase)) env.PI_FLOW_PHASE = phase as string
|
|
48
|
+
const traceparent = parentEnv.PI_FLOW_TRACEPARENT
|
|
49
|
+
if (isValidTraceparent(traceparent)) {
|
|
50
|
+
env.PI_FLOW_TRACEPARENT = traceparent as string
|
|
51
|
+
}
|
|
52
|
+
// AIDEV-NOTE: work/personal separation — the tracking ref (Jira key in work
|
|
53
|
+
// mode) and the mode ride along so worker telemetry shows the same ticket
|
|
54
|
+
// identity as the orchestrator. Both fail closed like the vars above.
|
|
55
|
+
const trackRef = parentEnv.PI_FLOW_TRACK_REF
|
|
56
|
+
if (isValidFlowValue(trackRef)) env.PI_FLOW_TRACK_REF = trackRef as string
|
|
57
|
+
const mode = parentEnv.PI_FLOW_MODE
|
|
58
|
+
if (mode === 'work' || mode === 'personal') env.PI_FLOW_MODE = mode
|
|
59
|
+
if (subtask !== undefined && isValidFlowValue(subtask)) {
|
|
60
|
+
env.PI_FLOW_SUBTASK = subtask
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** What the subagents package can tell a flow-aware caller about a spawn. */
|
|
65
|
+
export interface FlowSpawnInfo {
|
|
66
|
+
/** 'spawn' = fresh tab; 'resume'/'reattach' = takeover of existing work. */
|
|
67
|
+
kind: 'spawn' | 'resume' | 'reattach'
|
|
68
|
+
childId: string
|
|
69
|
+
name: string
|
|
70
|
+
/** Plan-task ref when the spawn maps 1:1 to one; absent for scouts. */
|
|
71
|
+
subtask?: string
|
|
72
|
+
/** Child session jsonl path (PMR-EA8X): journals it so /flow-cost can
|
|
73
|
+
* resolve sessions without guessing from the assignments dir. */
|
|
74
|
+
sessionFile?: string
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export type FlowSpawnListener = (info: FlowSpawnInfo) => void
|
|
78
|
+
|
|
79
|
+
// AIDEV-NOTE: the registry lives on globalThis (same pattern as
|
|
80
|
+
// RUNNING_KEY / POLL_ABORT_KEY in index.ts). Pi loads this package's
|
|
81
|
+
// extension entrypoint directly while pi-flow imports it through the
|
|
82
|
+
// workspace package root — under some loaders those are distinct module
|
|
83
|
+
// instances, so a module-level Set would NOT be shared. globalThis is the
|
|
84
|
+
// established cross-instance channel in this codebase.
|
|
85
|
+
const FLOW_SPAWN_LISTENERS_KEY = 'pi-subagents-flow-spawn-listeners'
|
|
86
|
+
|
|
87
|
+
function flowSpawnListeners(): Set<FlowSpawnListener> {
|
|
88
|
+
const holder = globalThis as Record<string, unknown>
|
|
89
|
+
const existing = holder[FLOW_SPAWN_LISTENERS_KEY]
|
|
90
|
+
if (existing instanceof Set) return existing as Set<FlowSpawnListener>
|
|
91
|
+
const created = new Set<FlowSpawnListener>()
|
|
92
|
+
holder[FLOW_SPAWN_LISTENERS_KEY] = created
|
|
93
|
+
return created
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Subscribe to spawn/resume/reattach events; returns an unsubscribe fn. */
|
|
97
|
+
export function onFlowSpawn(listener: FlowSpawnListener): () => void {
|
|
98
|
+
const set = flowSpawnListeners()
|
|
99
|
+
set.add(listener)
|
|
100
|
+
return () => {
|
|
101
|
+
set.delete(listener)
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Best-effort notify — a listener failure must never break a spawn. */
|
|
106
|
+
export function emitFlowSpawn(info: FlowSpawnInfo): void {
|
|
107
|
+
for (const listener of flowSpawnListeners()) {
|
|
108
|
+
try {
|
|
109
|
+
listener(info)
|
|
110
|
+
} catch {}
|
|
111
|
+
}
|
|
112
|
+
}
|