@botlearn-course/daemon 0.0.29-beta.3 → 0.0.29-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/README.md +29 -89
  2. package/dist/auth-store.d.ts +1 -11
  3. package/dist/auth-store.js +2 -83
  4. package/dist/cli.d.ts +0 -15
  5. package/dist/cli.js +12 -204
  6. package/dist/index.d.ts +0 -3
  7. package/dist/index.js +0 -3
  8. package/dist/run-dispatcher.d.ts +1 -5
  9. package/dist/run-dispatcher.js +41 -116
  10. package/dist/runtime-capabilities.js +3 -11
  11. package/dist/runtimes/engine.js +15 -52
  12. package/dist/runtimes/index.d.ts +1 -7
  13. package/dist/runtimes/index.js +1 -45
  14. package/dist/runtimes/pi-agent.js +38 -7
  15. package/dist/runtimes/pi-managed-launch.d.ts +5 -0
  16. package/dist/runtimes/pi-managed-launch.js +41 -0
  17. package/dist/runtimes/pi-managed-subagent-extension.d.ts +127 -0
  18. package/dist/runtimes/pi-managed-subagent-extension.js +303 -0
  19. package/dist/runtimes/pi-managed.d.ts +16 -2
  20. package/dist/runtimes/pi-managed.js +38 -16
  21. package/dist/runtimes/probe.d.ts +0 -5
  22. package/dist/runtimes/probe.js +0 -16
  23. package/dist/types.d.ts +10 -73
  24. package/dist/workspace.d.ts +0 -2
  25. package/dist/workspace.js +0 -10
  26. package/package.json +2 -2
  27. package/dist/course-client.d.ts +0 -46
  28. package/dist/course-client.js +0 -158
  29. package/dist/doctor.d.ts +0 -15
  30. package/dist/doctor.js +0 -85
  31. package/dist/runtime-profile.d.ts +0 -8
  32. package/dist/runtime-profile.js +0 -236
  33. package/dist/runtimes/acp-stream.d.ts +0 -96
  34. package/dist/runtimes/acp-stream.js +0 -490
  35. package/dist/runtimes/claude-code.d.ts +0 -41
  36. package/dist/runtimes/claude-code.js +0 -364
  37. package/dist/runtimes/codex.d.ts +0 -44
  38. package/dist/runtimes/codex.js +0 -348
  39. package/dist/runtimes/gemini.d.ts +0 -39
  40. package/dist/runtimes/gemini.js +0 -264
  41. package/dist/runtimes/hermes-agent.d.ts +0 -61
  42. package/dist/runtimes/hermes-agent.js +0 -191
  43. package/dist/runtimes/kimi.d.ts +0 -35
  44. package/dist/runtimes/kimi.js +0 -343
  45. package/dist/runtimes/native-tool-blocks.d.ts +0 -3
  46. package/dist/runtimes/native-tool-blocks.js +0 -98
  47. package/dist/runtimes/ndjson-stream.d.ts +0 -48
  48. package/dist/runtimes/ndjson-stream.js +0 -210
  49. package/dist/runtimes/openclaw-acp.d.ts +0 -52
  50. package/dist/runtimes/openclaw-acp.js +0 -893
  51. package/dist/runtimes/runtime-errors.d.ts +0 -20
  52. package/dist/runtimes/runtime-errors.js +0 -95
  53. package/dist/runtimes/text-cap.d.ts +0 -7
  54. package/dist/runtimes/text-cap.js +0 -25
@@ -0,0 +1,41 @@
1
+ import { readFileSync } from "node:fs";
2
+ const ownedGroups = new Map();
3
+ function processStat(pid) {
4
+ try {
5
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
6
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
7
+ const group = Number(fields[2]);
8
+ const start = fields[19];
9
+ return Number.isInteger(group) && start ? { group, start } : null;
10
+ }
11
+ catch {
12
+ return null;
13
+ }
14
+ }
15
+ /** Record the independent Linux process group created for one managed Pi turn. */
16
+ export function managedProcessGroupStart(pid) {
17
+ const stat = processStat(pid);
18
+ if (stat?.group !== pid)
19
+ return null;
20
+ ownedGroups.set(pid, stat.start);
21
+ return stat.start;
22
+ }
23
+ /** A recycled leader PID must never target a new process group. */
24
+ export function signalManagedProcessGroup(pid, start, signal) {
25
+ if (ownedGroups.get(pid) !== start)
26
+ return false;
27
+ const current = processStat(pid);
28
+ if (current && (current.group !== pid || current.start !== start))
29
+ return false;
30
+ try {
31
+ process.kill(-pid, signal);
32
+ return true;
33
+ }
34
+ catch {
35
+ return false;
36
+ }
37
+ }
38
+ export function forgetManagedProcessGroup(pid, start) {
39
+ if (ownedGroups.get(pid) === start)
40
+ ownedGroups.delete(pid);
41
+ }
@@ -0,0 +1,127 @@
1
+ import type { ManagedPiDelegation } from "./pi-managed.js";
2
+ type Task = {
3
+ agent: "worker";
4
+ task: string;
5
+ cwd?: string;
6
+ };
7
+ type Params = {
8
+ agent?: string;
9
+ task?: string;
10
+ tasks?: Task[];
11
+ chain?: Task[];
12
+ agentScope?: string;
13
+ cwd?: string;
14
+ };
15
+ type Usage = {
16
+ input: number;
17
+ output: number;
18
+ cacheRead: number;
19
+ cacheWrite: number;
20
+ cost: number;
21
+ };
22
+ type Result = {
23
+ agent: "worker";
24
+ task: string;
25
+ exitCode: number;
26
+ output: string;
27
+ stderr: string;
28
+ usage: Usage;
29
+ stopReason?: string;
30
+ model?: string;
31
+ step?: number;
32
+ };
33
+ type ToolResult = {
34
+ content: Array<{
35
+ type: "text";
36
+ text: string;
37
+ }>;
38
+ details: {
39
+ mode: "single" | "parallel" | "chain";
40
+ agentScope: "user";
41
+ results: Result[];
42
+ };
43
+ isError?: boolean;
44
+ };
45
+ interface PiExtensionAPI {
46
+ registerFlag(name: string, options: {
47
+ description: string;
48
+ type: "string";
49
+ }): void;
50
+ getFlag(name: string): unknown;
51
+ registerTool(definition: {
52
+ name: string;
53
+ label: string;
54
+ description: string;
55
+ parameters: unknown;
56
+ execute(id: string, args: Params, signal?: AbortSignal, onUpdate?: (result: ToolResult) => void, ctx?: {
57
+ cwd: string;
58
+ }): Promise<ToolResult>;
59
+ }): void;
60
+ }
61
+ export declare const subagentParameters: {
62
+ type: string;
63
+ additionalProperties: boolean;
64
+ properties: {
65
+ agent: {
66
+ type: string;
67
+ enum: string[];
68
+ };
69
+ task: {
70
+ type: string;
71
+ };
72
+ tasks: {
73
+ type: string;
74
+ items: {
75
+ type: string;
76
+ additionalProperties: boolean;
77
+ required: string[];
78
+ properties: {
79
+ agent: {
80
+ type: string;
81
+ enum: string[];
82
+ };
83
+ task: {
84
+ type: string;
85
+ };
86
+ cwd: {
87
+ type: string;
88
+ };
89
+ };
90
+ };
91
+ };
92
+ chain: {
93
+ type: string;
94
+ items: {
95
+ type: string;
96
+ additionalProperties: boolean;
97
+ required: string[];
98
+ properties: {
99
+ agent: {
100
+ type: string;
101
+ enum: string[];
102
+ };
103
+ task: {
104
+ type: string;
105
+ };
106
+ cwd: {
107
+ type: string;
108
+ };
109
+ };
110
+ };
111
+ };
112
+ agentScope: {
113
+ type: string;
114
+ enum: string[];
115
+ };
116
+ cwd: {
117
+ type: string;
118
+ };
119
+ };
120
+ };
121
+ export declare function readDelegation(file: unknown): ManagedPiDelegation;
122
+ /** Every Pi child receives the exact managed launch contract, including recursive delegation. */
123
+ export declare function childArgs(config: ManagedPiDelegation, manifestPath: string, task: string): string[];
124
+ export declare function runWorker(config: ManagedPiDelegation, manifestPath: string, cwd: string, task: string, signal?: AbortSignal, step?: number): Promise<Result>;
125
+ export declare function executeDelegation(config: ManagedPiDelegation, manifestPath: string, cwd: string, params: Params, signal?: AbortSignal): Promise<ToolResult>;
126
+ export default function managedSubagentExtension(pi: PiExtensionAPI): void;
127
+ export {};
@@ -0,0 +1,303 @@
1
+ import { spawn } from "node:child_process";
2
+ import { readFileSync, realpathSync } from "node:fs";
3
+ import path from "node:path";
4
+ const MAX_PARALLEL_TASKS = 8;
5
+ const MAX_CONCURRENCY = 4;
6
+ const MAX_RECORD_BYTES = 4 * 1024 * 1024;
7
+ const MAX_OUTPUT_BYTES = 50 * 1024;
8
+ const KILL_GRACE_MS = 5_000;
9
+ const taskSchema = { type: "object", additionalProperties: false, required: ["agent", "task"],
10
+ properties: { agent: { type: "string", enum: ["worker"] }, task: { type: "string" },
11
+ cwd: { type: "string" } } };
12
+ export const subagentParameters = { type: "object", additionalProperties: false, properties: {
13
+ agent: { type: "string", enum: ["worker"] }, task: { type: "string" },
14
+ tasks: { type: "array", items: taskSchema }, chain: { type: "array", items: taskSchema },
15
+ agentScope: { type: "string", enum: ["user"] },
16
+ cwd: { type: "string" },
17
+ } };
18
+ function object(value) {
19
+ return value !== null && typeof value === "object" && !Array.isArray(value)
20
+ ? value : {};
21
+ }
22
+ function count(value) {
23
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
24
+ }
25
+ function usage() { return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0 }; }
26
+ function addUsage(total, value) {
27
+ const part = object(value);
28
+ total.input += count(part.input);
29
+ total.output += count(part.output);
30
+ total.cacheRead += count(part.cacheRead);
31
+ total.cacheWrite += count(part.cacheWrite);
32
+ total.cost += count(part.cost);
33
+ }
34
+ function bounded(text, limit = MAX_OUTPUT_BYTES) {
35
+ const bytes = Buffer.from(text);
36
+ if (bytes.length <= limit)
37
+ return text;
38
+ return `${bytes.subarray(0, limit).toString("utf8")}\n[output truncated]`;
39
+ }
40
+ function workingDirectory(workspace, current, requested) {
41
+ const root = realpathSync(workspace);
42
+ const base = realpathSync(current);
43
+ if (requested !== undefined && (typeof requested !== "string" || !requested.trim()
44
+ || requested.includes("\0"))) {
45
+ throw new Error("Invalid managed subagent working directory");
46
+ }
47
+ const selected = requested === undefined ? base : realpathSync(path.resolve(base, requested));
48
+ const relative = path.relative(root, selected);
49
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
50
+ throw new Error("Subagent working directory is outside the workspace");
51
+ }
52
+ return selected;
53
+ }
54
+ export function readDelegation(file) {
55
+ if (typeof file !== "string" || !path.isAbsolute(file))
56
+ throw new Error("Invalid managed delegation path");
57
+ const config = object(JSON.parse(readFileSync(file, "utf8")));
58
+ const keys = ["binary", "model", "workspaceDir", "systemPrompt", "workerPromptPath", "webExtension",
59
+ "skillsExtension", "skillsSocket", "subagentExtension"];
60
+ for (const key of keys) {
61
+ if (typeof config[key] !== "string" || !config[key])
62
+ throw new Error("Invalid managed delegation configuration");
63
+ }
64
+ if (config.thinking !== undefined && typeof config.thinking !== "string") {
65
+ throw new Error("Invalid managed delegation thinking level");
66
+ }
67
+ return config;
68
+ }
69
+ /** Every Pi child receives the exact managed launch contract, including recursive delegation. */
70
+ export function childArgs(config, manifestPath, task) {
71
+ const args = ["--mode", "json", "-p", "--no-session", "--no-approve", "--no-extensions",
72
+ "--no-skills", "--no-prompt-templates", "--no-themes", "--no-context-files",
73
+ "--model", config.model];
74
+ if (config.thinking)
75
+ args.push("--thinking", config.thinking);
76
+ args.push("--system-prompt", config.systemPrompt, "--append-system-prompt", config.workerPromptPath, "--extension", config.skillsExtension, "--botlearn-course-skills-socket", config.skillsSocket, "--extension", config.webExtension, "--extension", config.subagentExtension, "--botlearn-delegation-manifest", manifestPath, `Task: ${task}`);
77
+ return args;
78
+ }
79
+ const active = new Set();
80
+ function terminate(child) {
81
+ if (child.exitCode !== null || child.signalCode !== null)
82
+ return;
83
+ child.kill("SIGTERM");
84
+ const timer = setTimeout(() => {
85
+ if (child.exitCode === null && child.signalCode === null)
86
+ child.kill("SIGKILL");
87
+ }, KILL_GRACE_MS);
88
+ timer.unref();
89
+ child.once("close", () => clearTimeout(timer));
90
+ }
91
+ // Pi can be terminated by the outer runtime before its tool signal is delivered.
92
+ process.once("SIGTERM", () => {
93
+ for (const child of active)
94
+ terminate(child);
95
+ if (active.size === 0)
96
+ process.exit(143);
97
+ const timer = setTimeout(() => process.exit(143), KILL_GRACE_MS + 50);
98
+ timer.unref();
99
+ });
100
+ export async function runWorker(config, manifestPath, cwd, task, signal, step) {
101
+ if (signal?.aborted)
102
+ throw new Error("Subagent was aborted");
103
+ if (Buffer.byteLength(task) > MAX_OUTPUT_BYTES)
104
+ throw new Error("Subagent task exceeded the limit");
105
+ const child = spawn(config.binary, childArgs(config, manifestPath, task), {
106
+ cwd, env: process.env, shell: false, stdio: ["ignore", "pipe", "pipe"],
107
+ });
108
+ active.add(child);
109
+ const result = { agent: "worker", task, exitCode: 1, output: "", stderr: "", usage: usage(),
110
+ ...(step ? { step } : {}) };
111
+ let buffer = "";
112
+ let parseFailure = false;
113
+ const completedTools = new Set();
114
+ const line = (raw) => {
115
+ if (!raw.trim() || parseFailure)
116
+ return;
117
+ if (Buffer.byteLength(raw) > MAX_RECORD_BYTES) {
118
+ parseFailure = true;
119
+ buffer = "";
120
+ terminate(child);
121
+ return;
122
+ }
123
+ let event;
124
+ try {
125
+ event = object(JSON.parse(raw));
126
+ }
127
+ catch {
128
+ parseFailure = true;
129
+ buffer = "";
130
+ terminate(child);
131
+ return;
132
+ }
133
+ if (event.type === "message_end") {
134
+ const message = object(event.message);
135
+ if (message.role !== "assistant")
136
+ return;
137
+ const parts = Array.isArray(message.content) ? message.content.map(object) : [];
138
+ result.output = bounded(parts.filter((p) => p.type === "text" && typeof p.text === "string")
139
+ .map((p) => p.text).join(""));
140
+ result.stopReason = typeof message.stopReason === "string" ? message.stopReason : undefined;
141
+ result.model = typeof message.model === "string" ? message.model : undefined;
142
+ const own = object(message.usage);
143
+ addUsage(result.usage, { ...own, cost: object(own.cost).total });
144
+ }
145
+ else if (event.type === "tool_execution_end" && event.toolName === "subagent") {
146
+ const id = String(event.toolCallId ?? "");
147
+ if (!id || completedTools.has(id))
148
+ return;
149
+ completedTools.add(id);
150
+ const entries = object(object(event.result).details).results;
151
+ if (Array.isArray(entries))
152
+ for (const entry of entries)
153
+ addUsage(result.usage, object(entry).usage);
154
+ }
155
+ };
156
+ child.stdout?.on("data", (chunk) => {
157
+ if (parseFailure)
158
+ return;
159
+ buffer += chunk.toString("utf8");
160
+ let end;
161
+ while ((end = buffer.indexOf("\n")) >= 0) {
162
+ line(buffer.slice(0, end));
163
+ buffer = buffer.slice(end + 1);
164
+ }
165
+ if (Buffer.byteLength(buffer) > MAX_RECORD_BYTES) {
166
+ parseFailure = true;
167
+ buffer = "";
168
+ terminate(child);
169
+ }
170
+ });
171
+ child.stderr?.on("data", (chunk) => {
172
+ result.stderr = bounded(result.stderr + chunk.toString("utf8"), 2048);
173
+ });
174
+ const onAbort = () => terminate(child);
175
+ signal?.addEventListener("abort", onAbort, { once: true });
176
+ if (signal?.aborted)
177
+ onAbort();
178
+ try {
179
+ const exitCode = await new Promise((resolve) => {
180
+ child.once("error", () => resolve(1));
181
+ child.once("close", (code) => { line(buffer); resolve(code ?? 1); });
182
+ });
183
+ result.exitCode = exitCode;
184
+ if (signal?.aborted)
185
+ throw new Error("Subagent was aborted");
186
+ if (parseFailure)
187
+ throw new Error("Subagent emitted invalid or oversized JSON");
188
+ if (exitCode === 0 && result.stopReason !== "stop") {
189
+ result.exitCode = 1;
190
+ result.stderr = "Subagent exited without a successful assistant message";
191
+ }
192
+ return result;
193
+ }
194
+ finally {
195
+ active.delete(child);
196
+ signal?.removeEventListener("abort", onAbort);
197
+ }
198
+ }
199
+ function failed(result) { return result.exitCode !== 0 || result.stopReason !== "stop"; }
200
+ function toolResult(mode, results, text, isError = false) {
201
+ return { content: [{ type: "text", text: bounded(text) }],
202
+ details: { mode, agentScope: "user", results }, ...(isError ? { isError: true } : {}) };
203
+ }
204
+ export async function executeDelegation(config, manifestPath, cwd, params, signal) {
205
+ if (!params || typeof params !== "object" || Array.isArray(params)) {
206
+ throw new Error("Invalid managed subagent parameters");
207
+ }
208
+ const modeCount = Number(params.agent !== undefined || params.task !== undefined)
209
+ + Number(params.tasks !== undefined) + Number(params.chain !== undefined);
210
+ if (params.agentScope !== undefined && params.agentScope !== "user"
211
+ || "confirmProjectAgents" in params || "model" in params
212
+ || "tools" in params || "systemPrompt" in params || modeCount !== 1
213
+ || Object.keys(params).some((key) => !["agent", "task", "tasks", "chain", "agentScope", "cwd"].includes(key))) {
214
+ throw new Error("Invalid managed subagent parameters");
215
+ }
216
+ const valid = (item) => {
217
+ const value = object(item);
218
+ return value.agent === "worker" && typeof value.task === "string" && value.task.trim().length > 0
219
+ && Buffer.byteLength(value.task) <= MAX_OUTPUT_BYTES
220
+ && Object.keys(value).every((key) => key === "agent" || key === "task" || key === "cwd")
221
+ && (value.cwd === undefined || typeof value.cwd === "string");
222
+ };
223
+ const defaultCwd = workingDirectory(config.workspaceDir, cwd, params.cwd);
224
+ if (params.tasks !== undefined) {
225
+ if (!Array.isArray(params.tasks) || params.tasks.length < 1 || !params.tasks.every(valid)) {
226
+ throw new Error("Invalid parallel subagent tasks");
227
+ }
228
+ if (params.tasks.length > MAX_PARALLEL_TASKS) {
229
+ return toolResult("parallel", [], `Too many parallel tasks (${params.tasks.length}). Max is 8.`, true);
230
+ }
231
+ const directories = params.tasks.map((item) => workingDirectory(config.workspaceDir, cwd, item.cwd ?? params.cwd));
232
+ const results = new Array(params.tasks.length);
233
+ let next = 0;
234
+ let firstFailure;
235
+ const batch = new AbortController();
236
+ const onAbort = () => batch.abort(signal?.reason);
237
+ signal?.addEventListener("abort", onAbort, { once: true });
238
+ if (signal?.aborted)
239
+ onAbort();
240
+ const workers = Array.from({ length: Math.min(MAX_CONCURRENCY, params.tasks.length) }, async () => {
241
+ while (next < params.tasks.length && !batch.signal.aborted) {
242
+ const index = next++;
243
+ try {
244
+ results[index] = await runWorker(config, manifestPath, directories[index], params.tasks[index].task, batch.signal);
245
+ }
246
+ catch (error) {
247
+ if (firstFailure === undefined)
248
+ firstFailure = error;
249
+ batch.abort(error);
250
+ throw error;
251
+ }
252
+ }
253
+ });
254
+ const outcomes = await Promise.allSettled(workers);
255
+ signal?.removeEventListener("abort", onAbort);
256
+ if (firstFailure !== undefined)
257
+ throw firstFailure;
258
+ const failure = outcomes.find((item) => item.status === "rejected");
259
+ if (failure?.status === "rejected")
260
+ throw failure.reason;
261
+ if (batch.signal.aborted)
262
+ throw new Error("Subagent was aborted");
263
+ const success = results.filter((r) => !failed(r)).length;
264
+ return toolResult("parallel", results, `Parallel: ${success}/${results.length} succeeded\n\n${results.map((r) => `### [worker] ${failed(r) ? "failed" : "completed"}\n\n${r.output || r.stderr || "(no output)"}`)
265
+ .join("\n\n---\n\n")}`, success !== results.length);
266
+ }
267
+ if (params.chain !== undefined) {
268
+ if (!Array.isArray(params.chain) || params.chain.length < 1 || !params.chain.every(valid)) {
269
+ throw new Error("Invalid chain subagent tasks");
270
+ }
271
+ const directories = params.chain.map((item) => workingDirectory(config.workspaceDir, cwd, item.cwd ?? params.cwd));
272
+ const results = [];
273
+ let previous = "";
274
+ for (const [index, item] of params.chain.entries()) {
275
+ const task = item.task.replace(/\{previous\}/g, previous);
276
+ const result = await runWorker(config, manifestPath, directories[index], task, signal, index + 1);
277
+ results.push(result);
278
+ if (failed(result))
279
+ return toolResult("chain", results, `Chain stopped at step ${index + 1}: ${result.stderr || result.output || "(no output)"}`, true);
280
+ previous = result.output;
281
+ }
282
+ return toolResult("chain", results, previous || "(no output)");
283
+ }
284
+ if (!valid({ agent: params.agent, task: params.task }))
285
+ throw new Error("Invalid single subagent task");
286
+ const result = await runWorker(config, manifestPath, defaultCwd, params.task, signal);
287
+ return toolResult("single", [result], failed(result) ? result.stderr || result.output || "(no output)"
288
+ : result.output || "(no output)", failed(result));
289
+ }
290
+ export default function managedSubagentExtension(pi) {
291
+ pi.registerFlag("botlearn-delegation-manifest", {
292
+ description: "本次激活的受控委派清单", type: "string",
293
+ });
294
+ pi.registerTool({ name: "subagent", label: "Subagent",
295
+ description: "Delegate to the managed worker. Modes: single, parallel (up to 8, 4 concurrent), chain.",
296
+ parameters: subagentParameters,
297
+ async execute(_id, params, signal, _onUpdate, ctx) {
298
+ const file = pi.getFlag("botlearn-delegation-manifest");
299
+ const config = readDelegation(file);
300
+ return executeDelegation(config, file, ctx?.cwd ?? process.cwd(), params, signal);
301
+ },
302
+ });
303
+ }
@@ -1,11 +1,25 @@
1
1
  import type { EngineRunOptions } from "./engine.js";
2
2
  export declare const MANAGED_PI_BINARY = "/opt/pi-agent/0.85.1/bin/pi";
3
3
  export declare const MANAGED_PI_WEB_ACCESS_EXTENSION = "/opt/pi-agent/0.85.1/node_modules/pi-web-access/dist/index.js";
4
- /** Ships with the pinned Pi package; its `files` field publishes `examples`. */
5
- export declare const MANAGED_PI_SUBAGENT_EXTENSION = "/opt/pi-agent/0.85.1/node_modules/@earendil-works/pi-coding-agent/examples/extensions/subagent/index.ts";
4
+ export declare const MANAGED_PI_SUBAGENT_EXTENSION: string;
5
+ export interface ManagedPiDelegation {
6
+ binary: string;
7
+ model: string;
8
+ workspaceDir: string;
9
+ thinking?: string;
10
+ systemPrompt: string;
11
+ workerPromptPath: string;
12
+ webExtension: string;
13
+ skillsExtension: string;
14
+ skillsSocket: string;
15
+ subagentExtension: string;
16
+ }
6
17
  /** The image verifies the CLI once; per-turn probes read immutable installed metadata. */
7
18
  export declare function managedPiVersion(): string | null;
8
19
  export declare function prepareManagedPi(opts: EngineRunOptions): Promise<{
9
20
  env: NodeJS.ProcessEnv;
21
+ delegationDir: string;
10
22
  cleanup(): void;
11
23
  }>;
24
+ /** Called after the course Skills socket exists, before the first Pi process starts. */
25
+ export declare function writeManagedPiDelegation(dir: string, opts: EngineRunOptions, skillsSocket: string): string;
@@ -1,15 +1,13 @@
1
- import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
1
+ import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
2
2
  import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
3
4
  import { runtimeChildEnv } from "../runtime-env.js";
4
5
  export const MANAGED_PI_BINARY = "/opt/pi-agent/0.85.1/bin/pi";
5
6
  export const MANAGED_PI_WEB_ACCESS_EXTENSION = "/opt/pi-agent/0.85.1/node_modules/pi-web-access/dist/index.js";
6
- /** Ships with the pinned Pi package; its `files` field publishes `examples`. */
7
- export const MANAGED_PI_SUBAGENT_EXTENSION = "/opt/pi-agent/0.85.1/node_modules/@earendil-works/pi-coding-agent/examples/extensions/subagent/index.ts";
7
+ export const MANAGED_PI_SUBAGENT_EXTENSION = fileURLToPath(new URL("./pi-managed-subagent-extension.js", import.meta.url));
8
8
  /**
9
- * The only delegation role. The extension resolves roles by name from the controlled
10
- * agent directory and cannot take an inline profile, so task-specific detail travels in
11
- * the delegated task text. Declaring no `tools` or `model` makes each subagent inherit
12
- * this turn's model and thinking level.
9
+ * The only delegation role. The managed extension loads this root-owned prompt directly;
10
+ * workspace agent files are never discovered.
13
11
  */
14
12
  const SUBAGENT_WORKER_ROLE = `---
15
13
  name: worker
@@ -72,14 +70,6 @@ export async function prepareManagedPi(opts) {
72
70
  || contract.max_output_tokens_limit > contract.context_window) {
73
71
  throw new Error("pi-agent managed model selection is invalid");
74
72
  }
75
- // The extension discovers roles under the controlled agent directory only. The workspace
76
- // never participates, so course content cannot introduce a delegation role.
77
- const agentsDir = path.join(agentDir, "agents");
78
- mkdirSync(agentsDir, { recursive: true, mode: 0o750 });
79
- chmodSync(agentsDir, 0o750);
80
- const roleFile = path.join(agentsDir, "worker.md");
81
- writeFileSync(roleFile, SUBAGENT_WORKER_ROLE, { mode: 0o640 });
82
- chmodSync(roleFile, 0o640);
83
73
  const modelsFile = path.join(agentDir, "models.json");
84
74
  writeFileSync(modelsFile, JSON.stringify({ providers: {
85
75
  botlearn: {
@@ -96,10 +86,42 @@ export async function prepareManagedPi(opts) {
96
86
  // The supervisor inherits umask 0077 in veFaaS. Restore group-read after
97
87
  // creation so the separate runtime UID can load the immutable model contract.
98
88
  chmodSync(modelsFile, 0o640);
99
- return { env: { ...source, HOME: home, PI_CODING_AGENT_DIR: agentDir }, cleanup };
89
+ const delegationDir = path.join(home, "managed-delegation");
90
+ mkdirSync(delegationDir, { mode: 0o750 });
91
+ chmodSync(delegationDir, 0o750);
92
+ return { env: { ...source, HOME: home, PI_CODING_AGENT_DIR: agentDir }, delegationDir, cleanup };
100
93
  }
101
94
  catch (error) {
102
95
  cleanup();
103
96
  throw error;
104
97
  }
105
98
  }
99
+ /** Called after the course Skills socket exists, before the first Pi process starts. */
100
+ export function writeManagedPiDelegation(dir, opts, skillsSocket) {
101
+ const modelIndex = opts.extraArgs?.indexOf("--model") ?? -1;
102
+ const thinkingIndex = opts.extraArgs?.indexOf("--thinking") ?? -1;
103
+ const model = modelIndex >= 0 ? opts.extraArgs?.[modelIndex + 1] : undefined;
104
+ const thinking = thinkingIndex >= 0 ? opts.extraArgs?.[thinkingIndex + 1] : undefined;
105
+ if (!model || opts.systemPrompt === undefined || !skillsSocket.startsWith("/")) {
106
+ throw new Error("pi-agent managed delegation configuration is incomplete");
107
+ }
108
+ const workerPromptPath = path.join(dir, "worker.md");
109
+ writeFileSync(workerPromptPath, SUBAGENT_WORKER_ROLE, { mode: 0o640, flag: "wx" });
110
+ chmodSync(workerPromptPath, 0o640);
111
+ const manifest = {
112
+ binary: MANAGED_PI_BINARY,
113
+ model: `botlearn/${model}`,
114
+ workspaceDir: realpathSync(opts.cwd),
115
+ ...(thinking ? { thinking } : {}),
116
+ systemPrompt: opts.systemPrompt,
117
+ workerPromptPath,
118
+ webExtension: MANAGED_PI_WEB_ACCESS_EXTENSION,
119
+ skillsExtension: path.resolve(fileURLToPath(new URL("./pi-course-skills-extension.js", import.meta.url))),
120
+ skillsSocket,
121
+ subagentExtension: MANAGED_PI_SUBAGENT_EXTENSION,
122
+ };
123
+ const file = path.join(dir, "launch.json");
124
+ writeFileSync(file, JSON.stringify(manifest), { mode: 0o640, flag: "wx" });
125
+ chmodSync(file, 0o640);
126
+ return file;
127
+ }
@@ -3,15 +3,10 @@ import { execFileSync } from "node:child_process";
3
3
  export interface ProbeDeps {
4
4
  platform?: NodeJS.Platform;
5
5
  env?: NodeJS.ProcessEnv;
6
- homeDir?: string;
7
6
  execFileSyncFn?: typeof execFileSync;
8
7
  existsSyncFn?: (p: string) => boolean;
9
8
  }
10
9
  /** Resolve a command name on PATH via `which`/`where`; returns null when missing. */
11
10
  export declare function resolveCommandOnPath(command: string, deps?: ProbeDeps): string | null;
12
- /** Return the first path in `candidates` that exists on disk, or null. */
13
- export declare function firstExistingPath(candidates: string[], deps?: ProbeDeps): string | null;
14
11
  /** Run `<command> [...args] --version` and return the first output line, or null. */
15
12
  export declare function readCommandVersion(command: string, args?: string[], deps?: ProbeDeps): string | null;
16
- /** Join `relativePath` against HOME (falls back to empty when unset). */
17
- export declare function resolveHomePath(relativePath: string, deps?: ProbeDeps): string;
@@ -1,6 +1,4 @@
1
1
  import { execFileSync } from "node:child_process";
2
- import { existsSync } from "node:fs";
3
- import path from "node:path";
4
2
  function normalizeExecOutput(raw) {
5
3
  return Buffer.isBuffer(raw) ? raw.toString("utf8") : String(raw ?? "");
6
4
  }
@@ -22,15 +20,6 @@ export function resolveCommandOnPath(command, deps = {}) {
22
20
  return null;
23
21
  }
24
22
  }
25
- /** Return the first path in `candidates` that exists on disk, or null. */
26
- export function firstExistingPath(candidates, deps = {}) {
27
- const exists = deps.existsSyncFn ?? existsSync;
28
- for (const c of candidates) {
29
- if (exists(c))
30
- return c;
31
- }
32
- return null;
33
- }
34
23
  /** Run `<command> [...args] --version` and return the first output line, or null. */
35
24
  export function readCommandVersion(command, args = [], deps = {}) {
36
25
  const env = deps.env ?? process.env;
@@ -47,8 +36,3 @@ export function readCommandVersion(command, args = [], deps = {}) {
47
36
  return null;
48
37
  }
49
38
  }
50
- /** Join `relativePath` against HOME (falls back to empty when unset). */
51
- export function resolveHomePath(relativePath, deps = {}) {
52
- const home = deps.homeDir ?? deps.env?.HOME ?? process.env.HOME ?? "";
53
- return path.join(home, relativePath);
54
- }