@maheidem/pi-delegate 0.1.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 +32 -0
- package/README.md +86 -0
- package/application.ts +507 -0
- package/commands.ts +159 -0
- package/config.ts +216 -0
- package/index.ts +669 -0
- package/mode.ts +327 -0
- package/package.json +68 -0
- package/roles/general.md +41 -0
- package/roles/research.md +46 -0
- package/roles.ts +93 -0
- package/rpc-jsonl.ts +172 -0
- package/run-store.ts +326 -0
- package/runner.ts +771 -0
- package/types.ts +365 -0
- package/ui/running-view.ts +85 -0
- package/ui/settings-panel.ts +393 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 maheidem
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
This project builds against and vendors patterns from works under the MIT
|
|
26
|
+
License, copyright their respective authors:
|
|
27
|
+
|
|
28
|
+
- @earendil-works/pi-coding-agent (pi coding agent), including the official
|
|
29
|
+
`subagent` and `plan-mode` extension examples and RPC documentation.
|
|
30
|
+
- @earendil-works/pi-tui.
|
|
31
|
+
- The local `/loop` extension (same workspace), from which
|
|
32
|
+
`ui/settings-panel.ts` is vendored.
|
package/README.md
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# @maheidem/pi-delegate
|
|
2
|
+
|
|
3
|
+
Foreground isolated delegation + strict coordinator mode for the
|
|
4
|
+
[pi coding agent](https://github.com/earendil-works/pi) (`pi-coding-agent`).
|
|
5
|
+
Implements `PI-DELEGATE-TS-001` (Part II normative).
|
|
6
|
+
|
|
7
|
+
`delegate` runs a bounded task in a **separate child pi process** over the
|
|
8
|
+
documented RPC stdio protocol, returns a **bounded handoff** (capped text +
|
|
9
|
+
structured metadata, full transcript on disk), and can put the parent session
|
|
10
|
+
into a **strict coordinator mode** where the parent may only delegate — the
|
|
11
|
+
gate is an allowlist and exceptions fail closed.
|
|
12
|
+
|
|
13
|
+
## Install (source of truth: this workspace)
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
# development: run from a pi session in this repo
|
|
17
|
+
pi # /delegate is auto-discovered from .pi/extensions or ~/.pi/agent/extensions
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Register globally by copying/symlinking `custom-extensions/delegate` into
|
|
21
|
+
`~/.pi/agent/extensions/delegate` and adding it to
|
|
22
|
+
`~/.pi/agent/settings.json → packages`, then `/reload`. No automated install
|
|
23
|
+
is performed by this package.
|
|
24
|
+
|
|
25
|
+
## Usage
|
|
26
|
+
|
|
27
|
+
```text
|
|
28
|
+
/delegate dashboard (TUI) / status (headless)
|
|
29
|
+
/delegate run general <task> foreground delegation (impl specialist)
|
|
30
|
+
/delegate research <task> foreground web research (read-only tools)
|
|
31
|
+
/delegate on enable strict coordinator mode (session,
|
|
32
|
+
tree-stable; active tool set becomes
|
|
33
|
+
['delegate'])
|
|
34
|
+
/delegate off disable strict coordinator mode
|
|
35
|
+
/delegate status mode, active/last run, tool registration
|
|
36
|
+
/delegate inspect [runId] metadata + bounded transcript/stderr
|
|
37
|
+
/delegate cancel [runId] cancel the active (or named) run
|
|
38
|
+
/delegate paths config/run-store locations
|
|
39
|
+
/delegate doctor honest environment checks
|
|
40
|
+
/delegate help syntax + examples
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Any unrecognized first word is shorthand for `run general …`.
|
|
44
|
+
|
|
45
|
+
Tool (`delegate`) is available to models: same semantics, JSON result with
|
|
46
|
+
`ok`/`handoff`/`details` (usage, paths, state) or structured `error`.
|
|
47
|
+
|
|
48
|
+
## Safety model (selected invariants)
|
|
49
|
+
|
|
50
|
+
- The delegated task travels over child **RPC stdin**, never argv.
|
|
51
|
+
- Children run with `PI_DELEGATE_CHILD=1`; the extension is inert in children
|
|
52
|
+
(no recursion, no nested delegation).
|
|
53
|
+
- `agent_settled` is the only normal completion signal; raw stdout records are
|
|
54
|
+
persisted **before** semantic processing; unknown events are persisted and
|
|
55
|
+
ignored, never dropped.
|
|
56
|
+
- Cancellation is idempotent (first wins): RPC abort → SIGTERM → SIGKILL;
|
|
57
|
+
every finalization reaps the child exactly once.
|
|
58
|
+
- Run-store is `0700` with `0600` receipt/transcript/stderr files; corrupt
|
|
59
|
+
config is preserved as evidence and defaults are loaded.
|
|
60
|
+
- Strict mode is session-scoped, replayed per branch (tree/resume/fork safe),
|
|
61
|
+
persisted via session custom entries; persistence failures degrade loudly
|
|
62
|
+
but never silently disable the gate.
|
|
63
|
+
- Research requires a Firecrawl-capable tool path in the parent session;
|
|
64
|
+
Reddit is supplementary.
|
|
65
|
+
|
|
66
|
+
## Development
|
|
67
|
+
|
|
68
|
+
```bash
|
|
69
|
+
npm run typecheck # strict tsc, no emit
|
|
70
|
+
npm test # unit + runner (real RPC children) + application + UI + load
|
|
71
|
+
npm run test:e2e # real pi session E2E (needs a working default model)
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Design: `types.ts`/`config.ts`/`mode.ts`/`run-store.ts`/`rpc-jsonl.ts`/
|
|
75
|
+
`runner.ts`/`application.ts` are Pi-free domain modules; `index.ts` is the
|
|
76
|
+
sole Pi adapter (loads through jiti exactly as pi loads extensions; registers
|
|
77
|
+
only `/delegate`, the `delegate` tool, and the `delegate-handoff` renderer).
|
|
78
|
+
|
|
79
|
+
## Provenance / attribution
|
|
80
|
+
|
|
81
|
+
Built against `@earendil-works/pi-coding-agent` 0.84.4 and its official
|
|
82
|
+
`subagent` and `plan-mode` extension examples (MIT). `ui/settings-panel.ts`
|
|
83
|
+
is vendored from the local `/loop` extension's control panel (same author,
|
|
84
|
+
same workspace; pi-extension-builder v0.1.0 template). RPC protocol shapes
|
|
85
|
+
follow the installed pi RPC documentation (`docs/rpc.md`) in
|
|
86
|
+
`@earendil-works/pi-coding-agent`.
|
package/application.ts
ADDED
|
@@ -0,0 +1,507 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* delegate — canonical application core (Pi-free).
|
|
3
|
+
*
|
|
4
|
+
* Tool and command paths MUST route through application.run(); neither
|
|
5
|
+
* constructs child arguments independently (§11). The application owns the
|
|
6
|
+
* single active-run reservation (FR-007/POL-005), role/trust/model
|
|
7
|
+
* validation, store access, runner lifecycle, retention, and diagnostics.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import * as fs from "node:fs";
|
|
11
|
+
import type {
|
|
12
|
+
CancelResult,
|
|
13
|
+
DelegateApplication,
|
|
14
|
+
DelegateApplicationPorts,
|
|
15
|
+
DelegateDetails,
|
|
16
|
+
DelegateErrorCode,
|
|
17
|
+
DelegatePaths,
|
|
18
|
+
DelegateRequest,
|
|
19
|
+
DelegateRunResult,
|
|
20
|
+
DelegateStatus,
|
|
21
|
+
DoctorCheck,
|
|
22
|
+
DoctorReport,
|
|
23
|
+
ModeResult,
|
|
24
|
+
ModeRuntime,
|
|
25
|
+
ModeTransitionContext,
|
|
26
|
+
RoleName,
|
|
27
|
+
RunAttemptResult,
|
|
28
|
+
RunHooks,
|
|
29
|
+
RunInspection,
|
|
30
|
+
RunMetadataV1,
|
|
31
|
+
RunnerOutcome,
|
|
32
|
+
SessionEntryLike,
|
|
33
|
+
} from "./types.ts";
|
|
34
|
+
import { normalizeConfig, saveConfig, type DelegateConfigV1 } from "./config.ts";
|
|
35
|
+
import { EMPTY_USAGE } from "./types.ts";
|
|
36
|
+
import { isRoleName, resolveRole, rolePromptExists, DELEGATE_ROLES } from "./roles.ts";
|
|
37
|
+
import {
|
|
38
|
+
replayModeEntries,
|
|
39
|
+
applyReplayToRuntime,
|
|
40
|
+
newModeRuntime,
|
|
41
|
+
enableStrict as modeEnableStrict,
|
|
42
|
+
disableStrict as modeDisableStrict,
|
|
43
|
+
gateToolCall,
|
|
44
|
+
} from "./mode.ts";
|
|
45
|
+
import {
|
|
46
|
+
openRun,
|
|
47
|
+
listRuns,
|
|
48
|
+
readRunMetadata,
|
|
49
|
+
markOrphanedRuns,
|
|
50
|
+
enforceRetention,
|
|
51
|
+
runPaths,
|
|
52
|
+
pathsForAgentDir,
|
|
53
|
+
} from "./run-store.ts";
|
|
54
|
+
import { DelegateRunner, resolvePiInvocation, type PiInvocationResolver } from "./runner.ts";
|
|
55
|
+
import { validateTask } from "./commands.ts";
|
|
56
|
+
|
|
57
|
+
interface ActiveRunReservation {
|
|
58
|
+
id: string;
|
|
59
|
+
role: RoleName;
|
|
60
|
+
runner: DelegateRunner;
|
|
61
|
+
startedAt: string;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function errorResult(
|
|
65
|
+
runId: string,
|
|
66
|
+
role: RoleName,
|
|
67
|
+
code: DelegateErrorCode,
|
|
68
|
+
message: string,
|
|
69
|
+
extra?: Partial<DelegateDetails>,
|
|
70
|
+
): DelegateRunResult {
|
|
71
|
+
const now = new Date().toISOString();
|
|
72
|
+
return {
|
|
73
|
+
ok: false,
|
|
74
|
+
handoff: "",
|
|
75
|
+
details: {
|
|
76
|
+
schemaVersion: 1,
|
|
77
|
+
runId,
|
|
78
|
+
role,
|
|
79
|
+
state: "failed",
|
|
80
|
+
startedAt: now,
|
|
81
|
+
finishedAt: now,
|
|
82
|
+
durationMs: 0,
|
|
83
|
+
model: "",
|
|
84
|
+
usage: { ...EMPTY_USAGE },
|
|
85
|
+
outputBytes: 0,
|
|
86
|
+
outputTruncated: false,
|
|
87
|
+
transcriptPath: "",
|
|
88
|
+
stderrPath: "",
|
|
89
|
+
displayItems: [],
|
|
90
|
+
...extra,
|
|
91
|
+
},
|
|
92
|
+
error: { code, message },
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export class DelegateApplicationImpl implements DelegateApplication {
|
|
97
|
+
private activeRun: ActiveRunReservation | null = null;
|
|
98
|
+
private readonly modeRuntime: ModeRuntime;
|
|
99
|
+
private readonly ports: DelegateApplicationPorts;
|
|
100
|
+
private liveConfig: DelegateConfigV1;
|
|
101
|
+
|
|
102
|
+
constructor(ports: DelegateApplicationPorts) {
|
|
103
|
+
this.ports = ports;
|
|
104
|
+
this.liveConfig = ports.config;
|
|
105
|
+
this.modeRuntime = newModeRuntime();
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Live-edit one numeric config knob with validation + atomic persistence
|
|
110
|
+
* (dashboard edits). Returns an error string or null.
|
|
111
|
+
*/
|
|
112
|
+
patchConfig(key: string, rawValue: string): string | null {
|
|
113
|
+
const current = this.liveConfig as unknown as Record<string, unknown>;
|
|
114
|
+
if (!(key in current)) return `Unknown setting '${key}'.`;
|
|
115
|
+
const num = Number(rawValue);
|
|
116
|
+
if (!Number.isFinite(num)) return "Value must be a number.";
|
|
117
|
+
try {
|
|
118
|
+
const { config } = normalizeConfig({ ...current, [key]: num });
|
|
119
|
+
saveConfig(this.ports.agentDir, config);
|
|
120
|
+
this.liveConfig = config;
|
|
121
|
+
return null;
|
|
122
|
+
} catch (error) {
|
|
123
|
+
return `Save failed: ${(error as Error).message}`;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// ── Mode ───────────────────────────────────────────────────────────────
|
|
128
|
+
|
|
129
|
+
isStrict(): boolean {
|
|
130
|
+
return this.modeRuntime.hydrated && this.modeRuntime.modeEnabled;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
getModeRuntime(): ModeRuntime {
|
|
134
|
+
return this.modeRuntime;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Hydrate mode from a session branch replay (called by the adapter). */
|
|
138
|
+
hydrateFromBranch(branch: SessionEntryLike[]): void {
|
|
139
|
+
const replay = replayModeEntries(branch);
|
|
140
|
+
applyReplayToRuntime(this.modeRuntime, replay);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
async enableStrict(ctx: ModeTransitionContext): Promise<ModeResult> {
|
|
144
|
+
return modeEnableStrict(this.modeRuntime, ctx);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
async disableStrict(ctx: ModeTransitionContext): Promise<ModeResult> {
|
|
148
|
+
return modeDisableStrict(this.modeRuntime, ctx);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Strict tool_call gate decision (allowlist; fail-closed). */
|
|
152
|
+
gate(toolName: unknown): { block: boolean; reason?: string } {
|
|
153
|
+
return gateToolCall(this.modeRuntime, toolName);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// ── Run ────────────────────────────────────────────────────────────────
|
|
157
|
+
|
|
158
|
+
getActiveRun(): { runId: string; role: RoleName; startedAt: string } | null {
|
|
159
|
+
if (!this.activeRun) return null;
|
|
160
|
+
return { runId: this.activeRun.id, role: this.activeRun.role, startedAt: this.activeRun.startedAt };
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Canonical run entry point shared by tool and command. Reservation is
|
|
165
|
+
* synchronous before the first await (POL-005).
|
|
166
|
+
*/
|
|
167
|
+
async run(request: DelegateRequest, hooks: RunHooks = {}): Promise<RunAttemptResult> {
|
|
168
|
+
// 1. Synchronous reservation BEFORE any await.
|
|
169
|
+
if (this.activeRun) {
|
|
170
|
+
return {
|
|
171
|
+
ok: false,
|
|
172
|
+
busy: true,
|
|
173
|
+
runId: this.activeRun.id,
|
|
174
|
+
role: this.activeRun.role,
|
|
175
|
+
message: `Delegation is busy with run ${this.activeRun.id} (${this.activeRun.role}).`,
|
|
176
|
+
error: {
|
|
177
|
+
code: "E_DELEGATE_BUSY",
|
|
178
|
+
message: `Active run ${this.activeRun.id} (${this.activeRun.role}). Inspect, cancel, or wait.`,
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
const cfg = this.liveConfig;
|
|
184
|
+
const agentDir = this.ports.agentDir;
|
|
185
|
+
|
|
186
|
+
// 2. Validate task (line endings, blank, byte limit).
|
|
187
|
+
const taskResult = validateTask(request.task, cfg.maxTaskBytes);
|
|
188
|
+
if (typeof taskResult !== "string") {
|
|
189
|
+
return errorResult("", isRoleName(request.role) ? request.role : "general", "E_INVALID_TASK", `Task invalid: ${taskResult.error}`);
|
|
190
|
+
}
|
|
191
|
+
const task = taskResult;
|
|
192
|
+
|
|
193
|
+
// 3. Role (closed catalogue).
|
|
194
|
+
if (!isRoleName(request.role)) {
|
|
195
|
+
return errorResult("", "general", "E_INVALID_ROLE", `Unknown role '${String(request.role)}'. Use 'general' or 'research'.`);
|
|
196
|
+
}
|
|
197
|
+
const role = resolveRole(request.role, cfg.defaultRole);
|
|
198
|
+
|
|
199
|
+
// 4. Project trust for the write-capable general role.
|
|
200
|
+
if (role.name === "general" && !request.projectTrusted) {
|
|
201
|
+
return errorResult("", role.name, "E_PROJECT_UNTRUSTED", "Project is not trusted; a write-capable child cannot run. Approve trust or use the research role.");
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// 5. Model inheritance.
|
|
205
|
+
const model = request.parentModel?.trim();
|
|
206
|
+
if (!model) {
|
|
207
|
+
return errorResult("", role.name, "E_MODEL_UNAVAILABLE", "No parent model available to inherit. Select or configure a model.");
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// 6. Role prompt readability.
|
|
211
|
+
if (!rolePromptExists(role)) {
|
|
212
|
+
return errorResult("", role.name, "E_STORE", `Role prompt asset is unreadable for role '${role.name}'.`);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// 7. Open run store entry (atomic, 0700/0600).
|
|
216
|
+
let opened;
|
|
217
|
+
try {
|
|
218
|
+
opened = openRun(agentDir, { ...request, task, role: role.name });
|
|
219
|
+
} catch (error) {
|
|
220
|
+
return errorResult("", role.name, "E_STORE", `Run store could not initialize: ${(error as Error).message}`);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// 8. Reservation NOW covers the child lifecycle.
|
|
224
|
+
const runner = new DelegateRunner(
|
|
225
|
+
opened,
|
|
226
|
+
{
|
|
227
|
+
agentDir,
|
|
228
|
+
role,
|
|
229
|
+
task,
|
|
230
|
+
runId: opened.metadata.runId,
|
|
231
|
+
parentModel: model,
|
|
232
|
+
thinkingLevel: request.thinkingLevel,
|
|
233
|
+
cwd: request.cwd,
|
|
234
|
+
projectTrusted: request.projectTrusted,
|
|
235
|
+
registeredTools: this.lastRegisteredTools,
|
|
236
|
+
},
|
|
237
|
+
cfg,
|
|
238
|
+
hooks,
|
|
239
|
+
this.ports.resolveInvocation ?? resolvePiInvocation,
|
|
240
|
+
);
|
|
241
|
+
const reservation: ActiveRunReservation = {
|
|
242
|
+
id: opened.metadata.runId,
|
|
243
|
+
role: role.name,
|
|
244
|
+
runner,
|
|
245
|
+
startedAt: opened.metadata.createdAt,
|
|
246
|
+
};
|
|
247
|
+
this.activeRun = reservation;
|
|
248
|
+
|
|
249
|
+
try {
|
|
250
|
+
const outcome = await runner.run();
|
|
251
|
+
this.activeRun = null;
|
|
252
|
+
// Retention after terminal finalization (best-effort).
|
|
253
|
+
try {
|
|
254
|
+
enforceRetention(agentDir, cfg.maxRuns, cfg.maxRunAgeDays, undefined);
|
|
255
|
+
} catch {
|
|
256
|
+
// cleanup failure is warning-only
|
|
257
|
+
}
|
|
258
|
+
return outcomeToRunResult(outcome, opened.metadata, role.name, model, request.thinkingLevel);
|
|
259
|
+
} catch (error) {
|
|
260
|
+
this.activeRun = null;
|
|
261
|
+
return errorResult(opened.metadata.runId, role.name, "E_CHILD_EXIT", `Delegation failed unexpectedly: ${(error as Error).message}`);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Cancel the active run (default) or an exact run ID. */
|
|
266
|
+
async cancel(runId?: string): Promise<CancelResult> {
|
|
267
|
+
const active = this.activeRun;
|
|
268
|
+
if (!active) {
|
|
269
|
+
return { ok: false, message: "No active delegation to cancel.", error: { code: "E_DELEGATE_BUSY", message: "No active run." } };
|
|
270
|
+
}
|
|
271
|
+
if (runId && runId !== active.id) {
|
|
272
|
+
return {
|
|
273
|
+
ok: false,
|
|
274
|
+
runId,
|
|
275
|
+
message: `Run ${runId} is not the active run (active: ${active.id}). Only the active run can be cancelled.`,
|
|
276
|
+
error: { code: "E_DELEGATE_BUSY", message: "Unrelated run ID; cancel applies to the active run only." },
|
|
277
|
+
};
|
|
278
|
+
}
|
|
279
|
+
active.runner.cancel("cancelled");
|
|
280
|
+
return { ok: true, runId: active.id, message: `Cancellation requested for ${active.id}.` };
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** Cancel the active run on shutdown paths (session_shutdown). */
|
|
284
|
+
cancelActiveOnShutdown(): void {
|
|
285
|
+
this.activeRun?.runner.cancel("cancelled");
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// ── Inspection ─────────────────────────────────────────────────────────
|
|
289
|
+
|
|
290
|
+
inspect(runId?: string, includeTranscript = false): RunInspection {
|
|
291
|
+
const agentDir = this.ports.agentDir;
|
|
292
|
+
const id = runId ?? this.mostRecentRunId();
|
|
293
|
+
if (!id) throw Object.assign(new Error("No delegation runs exist."), { code: "E_RUN_NOT_FOUND" });
|
|
294
|
+
const metadata = readRunMetadata(agentDir, id);
|
|
295
|
+
if (!metadata) throw Object.assign(new Error(`Unknown run id '${id}'.`), { code: "E_RUN_NOT_FOUND" });
|
|
296
|
+
const inspection: RunInspection = { metadata };
|
|
297
|
+
if (includeTranscript) {
|
|
298
|
+
inspection.transcriptPreview = boundedPreview(metadata.transcriptPath, 12000);
|
|
299
|
+
inspection.stderrPreview = boundedPreview(metadata.stderrPath, 4000);
|
|
300
|
+
}
|
|
301
|
+
return inspection;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
mostRecentRunId(): string | null {
|
|
305
|
+
const active = this.activeRun;
|
|
306
|
+
const runs = listRuns(this.ports.agentDir, 50);
|
|
307
|
+
if (active) return active.id;
|
|
308
|
+
return runs[0]?.runId ?? null;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
recentRunIds(limit = 8): string[] {
|
|
312
|
+
return listRuns(this.ports.agentDir, limit).map((r) => r.runId);
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// ── Status ─────────────────────────────────────────────────────────────
|
|
316
|
+
|
|
317
|
+
getStatus(activeTools: string[] | "degraded"): DelegateStatus {
|
|
318
|
+
const cfg = this.liveConfig;
|
|
319
|
+
const runs = listRuns(this.ports.agentDir, 10);
|
|
320
|
+
const active = this.activeRun;
|
|
321
|
+
const last = runs.find((r) => r.runId !== active?.id) ?? runs[0];
|
|
322
|
+
return {
|
|
323
|
+
modeEnabled: this.isStrict(),
|
|
324
|
+
activeTools: this.isStrict() ? ["delegate"] : activeTools,
|
|
325
|
+
activeRun: active ? { runId: active.id, role: active.role, startedAt: active.startedAt } : null,
|
|
326
|
+
lastRun: last ? { runId: last.runId, role: last.role, state: last.state, finishedAt: last.finishedAt, durationMs: last.durationMs } : null,
|
|
327
|
+
defaultRole: cfg.defaultRole,
|
|
328
|
+
store: pathsForAgentDir(this.ports.agentDir),
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
paths(): DelegatePaths {
|
|
333
|
+
return pathsForAgentDir(this.ports.agentDir);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// ── Doctor ─────────────────────────────────────────────────────────────
|
|
337
|
+
|
|
338
|
+
doctor(): DoctorReport {
|
|
339
|
+
const checks: DoctorCheck[] = [];
|
|
340
|
+
const cfg = this.liveConfig;
|
|
341
|
+
const agentDir = this.ports.agentDir;
|
|
342
|
+
|
|
343
|
+
// 1. Pi invocation resolution.
|
|
344
|
+
try {
|
|
345
|
+
const inv = (this.ports.resolveInvocation ?? resolvePiInvocation)();
|
|
346
|
+
const fsOk = inv.command === "pi" || fs.existsSync(inv.command);
|
|
347
|
+
checks.push({
|
|
348
|
+
name: "pi-invocation",
|
|
349
|
+
status: fsOk ? "ok" : "warning",
|
|
350
|
+
detail: `${inv.command} ${inv.args.join(" ")}`.trim(),
|
|
351
|
+
});
|
|
352
|
+
} catch (error) {
|
|
353
|
+
checks.push({ name: "pi-invocation", status: "error", detail: (error as Error).message });
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// 2. Model availability (last known request context).
|
|
357
|
+
const lastModel = this.lastModelSeen;
|
|
358
|
+
checks.push({
|
|
359
|
+
name: "model",
|
|
360
|
+
status: lastModel ? "ok" : "warning",
|
|
361
|
+
detail: lastModel ?? "no parent model captured yet",
|
|
362
|
+
});
|
|
363
|
+
|
|
364
|
+
// 3. Role prompt readability.
|
|
365
|
+
for (const roleName of ["general", "research"] as const) {
|
|
366
|
+
const role = DELEGATE_ROLES[roleName];
|
|
367
|
+
const ok = rolePromptExists(role);
|
|
368
|
+
checks.push({ name: `role-${roleName}-prompt`, status: ok ? "ok" : "error", detail: role.promptPath });
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// 4. Run store writability + permissions.
|
|
372
|
+
try {
|
|
373
|
+
const runsDir = runPaths(agentDir, "_probe").runsDir;
|
|
374
|
+
fs.mkdirSync(runsDir, { recursive: true, mode: 0o700 });
|
|
375
|
+
const probePath = runPaths(agentDir, "_probe").runsDir + "/.probe";
|
|
376
|
+
fs.writeFileSync(probePath, "x", { mode: 0o600 });
|
|
377
|
+
const mode = fs.statSync(probePath).mode & 0o777;
|
|
378
|
+
const dirMode = fs.statSync(runPaths(agentDir, "_probe").runsDir).mode & 0o777;
|
|
379
|
+
fs.unlinkSync(probePath);
|
|
380
|
+
checks.push({
|
|
381
|
+
name: "run-store",
|
|
382
|
+
status: mode === 0o600 && dirMode === 0o700 ? "ok" : "warning",
|
|
383
|
+
detail: `runs dir ${dirMode.toString(8)}, files ${mode.toString(8)}`,
|
|
384
|
+
});
|
|
385
|
+
} catch (error) {
|
|
386
|
+
checks.push({ name: "run-store", status: "error", detail: (error as Error).message });
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// 5. delegate active-tool registration.
|
|
390
|
+
const activeToolsNow = this.lastActiveTools;
|
|
391
|
+
checks.push({
|
|
392
|
+
name: "delegate-registration",
|
|
393
|
+
status: activeToolsNow.includes("delegate") ? "ok" : "error",
|
|
394
|
+
detail: activeToolsNow.includes("delegate") ? "delegate is registered" : "delegate is NOT in the active tool set",
|
|
395
|
+
});
|
|
396
|
+
|
|
397
|
+
// 6. Strict gate/mode consistency.
|
|
398
|
+
const strict = this.isStrict();
|
|
399
|
+
const consistencyOk = !strict || activeToolsNow.length === 0 || (activeToolsNow.length === 1 && activeToolsNow[0] === "delegate");
|
|
400
|
+
checks.push({
|
|
401
|
+
name: "strict-consistency",
|
|
402
|
+
status: !strict ? "ok" : consistencyOk ? "ok" : "warning",
|
|
403
|
+
detail: strict ? "strict enforced; gate is authoritative" : "normal mode",
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
// 7. Firecrawl research path.
|
|
407
|
+
const registered = this.lastRegisteredTools;
|
|
408
|
+
const hasFirecrawl = registered.some((t) => /firecrawl/i.test(t));
|
|
409
|
+
checks.push({
|
|
410
|
+
name: "research-firecrawl-path",
|
|
411
|
+
status: hasFirecrawl ? "ok" : "warning",
|
|
412
|
+
detail: hasFirecrawl ? "Firecrawl-capable tool path present" : "no Firecrawl tool registered in this session",
|
|
413
|
+
});
|
|
414
|
+
|
|
415
|
+
// 8. Reddit supplementary path (informational).
|
|
416
|
+
const hasReddit = registered.some((t) => /reddit/i.test(t));
|
|
417
|
+
checks.push({
|
|
418
|
+
name: "research-reddit-path",
|
|
419
|
+
status: hasReddit ? "ok" : "warning",
|
|
420
|
+
detail: hasReddit ? "Reddit tool path present" : "Reddit not available (supplemental)",
|
|
421
|
+
});
|
|
422
|
+
|
|
423
|
+
// 9. Stale nonterminal receipts.
|
|
424
|
+
const stale = listRuns(agentDir, 100).filter((r) => !isTerminal(r.state));
|
|
425
|
+
checks.push({
|
|
426
|
+
name: "stale-receipts",
|
|
427
|
+
status: stale.length === 0 ? "ok" : "warning",
|
|
428
|
+
detail: stale.length === 0 ? "none" : `${stale.length} nonterminal receipt(s) without owned child`,
|
|
429
|
+
});
|
|
430
|
+
|
|
431
|
+
// 10. Active child ownership.
|
|
432
|
+
const activeInfo = this.activeRun;
|
|
433
|
+
checks.push({
|
|
434
|
+
name: "active-child",
|
|
435
|
+
status: "ok",
|
|
436
|
+
detail: activeInfo ? `${activeInfo.id} owned by pid ${activeInfo.runner.childPid ?? "?"}` : "none",
|
|
437
|
+
});
|
|
438
|
+
|
|
439
|
+
return { checks, ok: checks.every((c) => c.status !== "error") };
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
// Adapter refreshes these snapshots for doctor() without Pi imports here.
|
|
443
|
+
private lastModelSeen: string | null = null;
|
|
444
|
+
private lastActiveTools: string[] = [];
|
|
445
|
+
private lastRegisteredTools: string[] = [];
|
|
446
|
+
|
|
447
|
+
refreshDoctorContext(info: { model?: string; activeTools?: string[]; registeredTools?: string[] }): void {
|
|
448
|
+
if (info.model) this.lastModelSeen = info.model;
|
|
449
|
+
if (info.activeTools) this.lastActiveTools = [...info.activeTools];
|
|
450
|
+
if (info.registeredTools) this.lastRegisteredTools = [...info.registeredTools];
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/** Startup: stale nonterminal receipts become crashed; never kills PIDs. */
|
|
454
|
+
markOrphansOnStartup(): string[] {
|
|
455
|
+
return markOrphanedRuns(this.ports.agentDir);
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function isTerminal(state: string): boolean {
|
|
460
|
+
return ["succeeded", "failed", "cancelled", "timed_out_idle", "timed_out_hard", "crashed"].includes(state);
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function boundedPreview(filePath: string, maxBytes: number): string {
|
|
464
|
+
try {
|
|
465
|
+
const buf = fs.readFileSync(filePath);
|
|
466
|
+
if (buf.length <= maxBytes) return buf.toString("utf8");
|
|
467
|
+
const head = buf.subarray(0, maxBytes).toString("utf8");
|
|
468
|
+
return `${head}\n… [truncated ${buf.length - maxBytes} more bytes]`;
|
|
469
|
+
} catch {
|
|
470
|
+
return "";
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
function outcomeToRunResult(
|
|
475
|
+
outcome: RunnerOutcome,
|
|
476
|
+
metadata: RunMetadataV1,
|
|
477
|
+
role: RoleName,
|
|
478
|
+
model: string,
|
|
479
|
+
thinkingLevel?: string,
|
|
480
|
+
): DelegateRunResult {
|
|
481
|
+
const ok = outcome.state === "succeeded";
|
|
482
|
+
const details: DelegateDetails = {
|
|
483
|
+
schemaVersion: 1,
|
|
484
|
+
runId: outcome.runId,
|
|
485
|
+
role,
|
|
486
|
+
state: outcome.state,
|
|
487
|
+
startedAt: outcome.startedAt || metadata.startedAt || metadata.createdAt,
|
|
488
|
+
finishedAt: outcome.finishedAt || metadata.finishedAt || new Date().toISOString(),
|
|
489
|
+
durationMs: outcome.durationMs,
|
|
490
|
+
model,
|
|
491
|
+
...(thinkingLevel ? { thinkingLevel } : {}),
|
|
492
|
+
exitCode: outcome.exitCode,
|
|
493
|
+
stopReason: outcome.stopReason,
|
|
494
|
+
usage: outcome.usage,
|
|
495
|
+
outputBytes: outcome.outputBytes,
|
|
496
|
+
outputTruncated: outcome.outputTruncated,
|
|
497
|
+
transcriptPath: outcome.transcriptPath,
|
|
498
|
+
stderrPath: outcome.stderrPath,
|
|
499
|
+
displayItems: outcome.displayItems,
|
|
500
|
+
};
|
|
501
|
+
return {
|
|
502
|
+
ok,
|
|
503
|
+
handoff: outcome.handoff,
|
|
504
|
+
details,
|
|
505
|
+
...(outcome.error ? { error: outcome.error } : {}),
|
|
506
|
+
};
|
|
507
|
+
}
|