@botlearn-course/daemon 0.0.29-beta.2 → 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 (55) 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 +73 -10
  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 -0
  20. package/dist/runtimes/pi-managed.js +57 -2
  21. package/dist/runtimes/probe.d.ts +0 -5
  22. package/dist/runtimes/probe.js +0 -16
  23. package/dist/runtimes/tool-semantics.js +1 -0
  24. package/dist/types.d.ts +10 -73
  25. package/dist/workspace.d.ts +0 -2
  26. package/dist/workspace.js +0 -10
  27. package/package.json +2 -2
  28. package/dist/course-client.d.ts +0 -46
  29. package/dist/course-client.js +0 -158
  30. package/dist/doctor.d.ts +0 -15
  31. package/dist/doctor.js +0 -85
  32. package/dist/runtime-profile.d.ts +0 -8
  33. package/dist/runtime-profile.js +0 -236
  34. package/dist/runtimes/acp-stream.d.ts +0 -96
  35. package/dist/runtimes/acp-stream.js +0 -490
  36. package/dist/runtimes/claude-code.d.ts +0 -41
  37. package/dist/runtimes/claude-code.js +0 -364
  38. package/dist/runtimes/codex.d.ts +0 -44
  39. package/dist/runtimes/codex.js +0 -348
  40. package/dist/runtimes/gemini.d.ts +0 -39
  41. package/dist/runtimes/gemini.js +0 -264
  42. package/dist/runtimes/hermes-agent.d.ts +0 -61
  43. package/dist/runtimes/hermes-agent.js +0 -191
  44. package/dist/runtimes/kimi.d.ts +0 -35
  45. package/dist/runtimes/kimi.js +0 -343
  46. package/dist/runtimes/native-tool-blocks.d.ts +0 -3
  47. package/dist/runtimes/native-tool-blocks.js +0 -98
  48. package/dist/runtimes/ndjson-stream.d.ts +0 -48
  49. package/dist/runtimes/ndjson-stream.js +0 -210
  50. package/dist/runtimes/openclaw-acp.d.ts +0 -52
  51. package/dist/runtimes/openclaw-acp.js +0 -893
  52. package/dist/runtimes/runtime-errors.d.ts +0 -20
  53. package/dist/runtimes/runtime-errors.js +0 -95
  54. package/dist/runtimes/text-cap.d.ts +0 -7
  55. package/dist/runtimes/text-cap.js +0 -25
@@ -4,8 +4,9 @@ import { existsSync } from "node:fs";
4
4
  import { fileURLToPath } from "node:url";
5
5
  import { startCourseSkillsMcpServer } from "../mcp/course-skills-server.js";
6
6
  import { runtimeChildEnv, runtimeChildLaunch } from "../runtime-env.js";
7
- import { MANAGED_PI_BINARY, MANAGED_PI_WEB_ACCESS_EXTENSION, managedPiVersion, prepareManagedPi, } from "./pi-managed.js";
7
+ import { MANAGED_PI_BINARY, MANAGED_PI_SUBAGENT_EXTENSION, MANAGED_PI_WEB_ACCESS_EXTENSION, managedPiVersion, prepareManagedPi, writeManagedPiDelegation, } from "./pi-managed.js";
8
8
  import { piSessionHandle, preparePiSession } from "./pi-session.js";
9
+ import { forgetManagedProcessGroup, managedProcessGroupStart, signalManagedProcessGroup } from "./pi-managed-launch.js";
9
10
  import { sanitizeRuntimeFailureText } from "../redaction.js";
10
11
  import { wrapEngineAdapter } from "./engine.js";
11
12
  import { readCommandVersion, resolveCommandOnPath } from "./probe.js";
@@ -33,6 +34,31 @@ function record(value) {
33
34
  function count(value) {
34
35
  return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
35
36
  }
37
+ /**
38
+ * Subagents run as separate Pi processes, so their `message_end` usage never reaches this
39
+ * RPC stream. The delegation tool reports each child's totals in its result details; fold
40
+ * them into this turn using the same cache-inclusive input convention as the parent.
41
+ */
42
+ function addSubagentUsage(usage, result) {
43
+ const results = record(record(result).details).results;
44
+ if (!Array.isArray(results))
45
+ return false;
46
+ let counted = false;
47
+ for (const entry of results) {
48
+ const child = record(record(entry).usage);
49
+ if (Object.keys(child).length === 0)
50
+ continue;
51
+ counted = true;
52
+ const cached = count(child.cacheRead);
53
+ const input = count(child.input) + cached + count(child.cacheWrite);
54
+ usage.input_tokens += input;
55
+ usage.output_tokens += count(child.output);
56
+ usage.total_tokens += input + count(child.output);
57
+ usage.cached_input_tokens += cached;
58
+ usage.cost_usd += count(child.cost);
59
+ }
60
+ return counted;
61
+ }
36
62
  /**
37
63
  * One RPC process per Course turn, resuming a workspace-scoped native session cache.
38
64
  * Course facts bootstrap new/missing sessions; healthy sessions receive only this turn.
@@ -54,7 +80,8 @@ export class PiAgentAdapter {
54
80
  skills = await startCourseSkillsMcpServer({ prepared: opts.skillProvider,
55
81
  onEvent: opts.onSkillEvent ?? (async () => { }) });
56
82
  await skills.markApplied();
57
- return await this.execute({ ...opts, env: prepared.env }, skills.socketPath, true);
83
+ const delegation = writeManagedPiDelegation(prepared.delegationDir, opts, skills.socketPath);
84
+ return await this.execute({ ...opts, env: prepared.env }, skills.socketPath, true, delegation);
58
85
  }
59
86
  finally {
60
87
  try {
@@ -65,7 +92,7 @@ export class PiAgentAdapter {
65
92
  }
66
93
  }
67
94
  }
68
- async execute(opts, skillsSocket, managed = false) {
95
+ async execute(opts, skillsSocket, managed = false, delegation) {
69
96
  opts.signal.throwIfAborted();
70
97
  const sourceEnv = opts.env ?? process.env;
71
98
  if (!managed && (opts.skillProvider || [sourceEnv, process.env].some((env) => env.BOTLEARN_RUNTIME_LAUNCH_MODE || env.BOTLEARN_RUNTIME_USER || env.BOTLEARN_RUNTIME_UID))) {
@@ -97,13 +124,21 @@ export class PiAgentAdapter {
97
124
  args.push("--system-prompt", system);
98
125
  if (skillsSocket)
99
126
  args.push("--extension", fileURLToPath(new URL("./pi-course-skills-extension.js", import.meta.url)), "--botlearn-course-skills-socket", skillsSocket);
100
- // Web access ships in the image; a missing file means the build dropped it, so fail
101
- // instead of silently running a turn without the search tools the course expects.
127
+ // Both extensions ship in the image; a missing file means the build dropped it, so fail
128
+ // instead of silently running a turn without the tools the course expects.
102
129
  if (managed) {
103
- if (!existsSync(MANAGED_PI_WEB_ACCESS_EXTENSION)) {
104
- throw new Error("pi-agent web access extension is missing from the sandbox image");
130
+ for (const [extension, missing] of [
131
+ [MANAGED_PI_WEB_ACCESS_EXTENSION, "web access"],
132
+ [MANAGED_PI_SUBAGENT_EXTENSION, "subagent"],
133
+ ]) {
134
+ if (!existsSync(extension)) {
135
+ throw new Error(`pi-agent ${missing} extension is missing from the sandbox image`);
136
+ }
137
+ args.push("--extension", extension);
105
138
  }
106
- args.push("--extension", MANAGED_PI_WEB_ACCESS_EXTENSION);
139
+ if (!delegation)
140
+ throw new Error("pi-agent managed delegation is missing");
141
+ args.push("--botlearn-delegation-manifest", delegation);
107
142
  }
108
143
  const session = await preparePiSession(opts);
109
144
  args.push("--session-dir", session.dir);
@@ -113,7 +148,10 @@ export class PiAgentAdapter {
113
148
  const launch = runtimeChildLaunch(binary, args, managed ? process.env : sourceEnv);
114
149
  const child = spawn(launch.binary, launch.args, {
115
150
  cwd: opts.cwd, env, ...launch.identity, stdio: ["pipe", "pipe", "pipe"],
151
+ detached: managed && process.platform !== "win32",
116
152
  });
153
+ const groupStart = managed && process.platform === "linux" && child.pid
154
+ ? managedProcessGroupStart(child.pid) : null;
117
155
  let error;
118
156
  let finalText = "";
119
157
  let model;
@@ -128,14 +166,29 @@ export class PiAgentAdapter {
128
166
  let killTimer;
129
167
  let abortTimer;
130
168
  let hasUsage = false;
169
+ const countedDelegations = new Set();
170
+ let treeCleanup = false;
131
171
  const usage = { input_tokens: 0, output_tokens: 0, total_tokens: 0,
132
172
  cached_input_tokens: 0, cost_usd: 0 };
173
+ const signalTree = (signal) => {
174
+ if (managed && child.pid && process.platform === "linux" && groupStart) {
175
+ signalManagedProcessGroup(child.pid, groupStart, signal);
176
+ }
177
+ else if (child.exitCode === null && child.signalCode === null)
178
+ child.kill(signal);
179
+ };
133
180
  const stop = () => {
181
+ treeCleanup ||= managed && Boolean(error || opts.signal.aborted || !settled);
134
182
  if (killTimer || child.exitCode !== null || child.signalCode !== null)
135
183
  return;
136
- child.kill("SIGTERM");
184
+ if (treeCleanup)
185
+ signalTree("SIGTERM");
186
+ else
187
+ child.kill("SIGTERM");
137
188
  killTimer = setTimeout(() => {
138
- if (child.exitCode === null && child.signalCode === null)
189
+ if (treeCleanup)
190
+ signalTree("SIGKILL");
191
+ else if (child.exitCode === null && child.signalCode === null)
139
192
  child.kill("SIGKILL");
140
193
  }, KILL_GRACE_MS);
141
194
  killTimer.unref();
@@ -224,6 +277,12 @@ export class PiAgentAdapter {
224
277
  else if (event.type === "tool_execution_start" || event.type === "tool_execution_end") {
225
278
  const name = typeof event.toolName === "string" ? event.toolName : "tool";
226
279
  const ending = event.type === "tool_execution_end";
280
+ if (ending && name === "subagent" && typeof event.toolCallId === "string"
281
+ && !countedDelegations.has(event.toolCallId)) {
282
+ countedDelegations.add(event.toolCallId);
283
+ if (addSubagentUsage(usage, event.result))
284
+ hasUsage = true;
285
+ }
227
286
  emit(ending ? "tool_result" : "tool_use", {
228
287
  name,
229
288
  ...(ending ? { status: event.isError === true ? "error" : "completed" } : {}),
@@ -279,6 +338,10 @@ export class PiAgentAdapter {
279
338
  await exit;
280
339
  }
281
340
  finally {
341
+ if (opts.signal.aborted || treeCleanup)
342
+ signalTree("SIGKILL");
343
+ if (child.pid && groupStart)
344
+ forgetManagedProcessGroup(child.pid, groupStart);
282
345
  opts.signal.removeEventListener("abort", onAbort);
283
346
  if (killTimer)
284
347
  clearTimeout(killTimer);
@@ -0,0 +1,5 @@
1
+ /** Record the independent Linux process group created for one managed Pi turn. */
2
+ export declare function managedProcessGroupStart(pid: number): string | null;
3
+ /** A recycled leader PID must never target a new process group. */
4
+ export declare function signalManagedProcessGroup(pid: number, start: string, signal: NodeJS.Signals): boolean;
5
+ export declare function forgetManagedProcessGroup(pid: number, start: string): void;
@@ -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,9 +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
+ 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
+ }
4
17
  /** The image verifies the CLI once; per-turn probes read immutable installed metadata. */
5
18
  export declare function managedPiVersion(): string | null;
6
19
  export declare function prepareManagedPi(opts: EngineRunOptions): Promise<{
7
20
  env: NodeJS.ProcessEnv;
21
+ delegationDir: string;
8
22
  cleanup(): void;
9
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;