@botlearn-course/daemon 0.0.27 → 0.0.28-beta.1
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/README.md +1 -0
- package/dist/agent-service-sandbox.js +2 -0
- package/dist/runtime-capabilities.js +1 -1
- package/dist/runtime-env.js +10 -4
- package/dist/runtime-skills.d.ts +1 -1
- package/dist/runtimes/engine.d.ts +2 -1
- package/dist/runtimes/engine.js +3 -0
- package/dist/runtimes/index.js +2 -0
- package/dist/runtimes/pi-agent.d.ts +21 -0
- package/dist/runtimes/pi-agent.js +256 -0
- package/dist/runtimes/pi-managed.d.ts +9 -0
- package/dist/runtimes/pi-managed.js +80 -0
- package/dist/sandbox-supervisor.js +1 -0
- package/dist/types.d.ts +8 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -67,6 +67,7 @@ run 的 `runtime.id` 决定用哪个 adapter 执行;未指定时默认 `codex`
|
|
|
67
67
|
| `kimi-cli` | Kimi CLI | `kimi` | `BOTLEARN_KIMI_CLI_BIN` | |
|
|
68
68
|
| `deepseek-tui` | DeepSeek TUI | `deepseek` | `BOTLEARN_DEEPSEEK_TUI_BIN` | Linux/macOS 本地 server 会保留现有 MCP 配置并注入零依赖 `report_progress`;`botlearn` 是保留 server key。Windows 因固定 runtime 无法保证 MCP clean-env,首版 fail closed、不注入 progress |
|
|
69
69
|
| `hermes-agent` | Hermes Agent | `hermes-acp` | `BOTLEARN_HERMES_AGENT_BIN` | ACP stdio 协议 |
|
|
70
|
+
| `pi-agent` | Pi Agent | `pi` | `BOTLEARN_PI_AGENT_BIN` | 固定 `@earendil-works/pi-coding-agent@0.85.1`,要求 Node.js >=22.19.0;每轮使用独立 RPC(远程过程调用)进程 |
|
|
70
71
|
| `openclaw-acp` | OpenClaw (ACP) | `openclaw` | `BOTLEARN_OPENCLAW_BIN` | 还需配置 `BOTLEARN_OPENCLAW_URL`(可选 `BOTLEARN_OPENCLAW_TOKEN` / `BOTLEARN_OPENCLAW_AGENT`),二进制或 URL 缺失时 doctor 标记不可用 |
|
|
71
72
|
| `fake` | 假 runtime | 无 | — | 仅测试/演示用:产出确定性文本与一个 `draft.md`。默认隐藏,只有 `BOTLEARN_DAEMON_ENABLE_FAKE_RUNTIME=1` 时才注册并上报 |
|
|
72
73
|
|
|
@@ -416,6 +416,8 @@ export class AgentServiceSandboxClient {
|
|
|
416
416
|
const runtimeEnv = runtimeChildEnv(process.env);
|
|
417
417
|
delete runtimeEnv.DEEPSEEK_API_KEY;
|
|
418
418
|
delete runtimeEnv.DEEPSEEK_BASE_URL;
|
|
419
|
+
delete runtimeEnv.BOTLEARN_MODEL_API_KEY;
|
|
420
|
+
delete runtimeEnv.BOTLEARN_MODEL_BASE_URL;
|
|
419
421
|
Object.assign(runtimeEnv, activation.runtimeEnv);
|
|
420
422
|
runtimeEnv.BOTLEARN_AGENT_SERVICE_ACTIVATION_ID = scope.activationId;
|
|
421
423
|
validateRuntimePrompt(payload.runtime_prompt, activation.skillProvider?.catalog.map((entry) => entry.ref) ?? []);
|
|
@@ -9,7 +9,7 @@ const WEB_SEARCH_RUNTIMES = new Set([
|
|
|
9
9
|
"hermes-agent",
|
|
10
10
|
"fake",
|
|
11
11
|
]);
|
|
12
|
-
const COURSE_SKILL_RUNTIMES = new Set(["deepseek-tui"]);
|
|
12
|
+
const COURSE_SKILL_RUNTIMES = new Set(["deepseek-tui", "pi-agent"]);
|
|
13
13
|
export function runtimeSupportsCourseSkills(runtimeId) {
|
|
14
14
|
return COURSE_SKILL_RUNTIMES.has(runtimeId);
|
|
15
15
|
}
|
package/dist/runtime-env.js
CHANGED
|
@@ -26,11 +26,14 @@ const ACTIVATION_RUNTIME_ENV_KEYS = new Set([
|
|
|
26
26
|
"DEEPSEEK_API_KEY",
|
|
27
27
|
"DEEPSEEK_BASE_URL",
|
|
28
28
|
"BOTLEARN_DEEPSEEK_VISION_MODEL",
|
|
29
|
+
"BOTLEARN_MODEL_API_KEY",
|
|
30
|
+
"BOTLEARN_MODEL_BASE_URL",
|
|
29
31
|
]);
|
|
30
32
|
const RUNTIME_USER_PATTERN = /^[a-z_][a-z0-9_-]{0,31}$/;
|
|
31
33
|
const RUNTIME_SUDO_BINARY = "/usr/bin/sudo";
|
|
32
34
|
const MANAGED_RUNTIME_LAUNCHER = "/opt/botlearn/bin/botlearn-runtime-launcher";
|
|
33
35
|
const MANAGED_RUNTIME_BINARY = "/opt/deepseek-tui/0.8.39/bin/deepseek";
|
|
36
|
+
const MANAGED_PI_BINARY = "/opt/pi-agent/0.85.1/bin/pi";
|
|
34
37
|
const MANAGED_RUNTIME_UID = 1001;
|
|
35
38
|
const MANAGED_RUNTIME_GID = 2000;
|
|
36
39
|
/** Remove Course control-plane coordinates before any model/runtime child is created. */
|
|
@@ -76,8 +79,11 @@ export function activationRuntimeEnv(value) {
|
|
|
76
79
|
result[key] = item;
|
|
77
80
|
}
|
|
78
81
|
if (Object.keys(result).length > 0 &&
|
|
79
|
-
(
|
|
80
|
-
|
|
82
|
+
!((result.DEEPSEEK_API_KEY && result.DEEPSEEK_BASE_URL
|
|
83
|
+
&& !result.BOTLEARN_MODEL_API_KEY && !result.BOTLEARN_MODEL_BASE_URL)
|
|
84
|
+
|| (result.BOTLEARN_MODEL_API_KEY && result.BOTLEARN_MODEL_BASE_URL
|
|
85
|
+
&& !result.DEEPSEEK_API_KEY && !result.DEEPSEEK_BASE_URL && !result.BOTLEARN_DEEPSEEK_VISION_MODEL))) {
|
|
86
|
+
throw new Error("activation runtime env requires exactly one model key and base URL pair");
|
|
81
87
|
}
|
|
82
88
|
return result;
|
|
83
89
|
}
|
|
@@ -108,7 +114,7 @@ export function runtimeChildLaunch(binary, args, env = process.env, options = {}
|
|
|
108
114
|
if (currentUid !== 0) {
|
|
109
115
|
throw new Error("direct managed runtime launch requires a root supervisor daemon");
|
|
110
116
|
}
|
|
111
|
-
if (binary !== MANAGED_RUNTIME_BINARY) {
|
|
117
|
+
if (binary !== MANAGED_RUNTIME_BINARY && binary !== MANAGED_PI_BINARY) {
|
|
112
118
|
throw new Error("invalid supervisor-provided runtime binary");
|
|
113
119
|
}
|
|
114
120
|
const identity = runtimeChildIdentity(env);
|
|
@@ -141,7 +147,7 @@ export function runtimeChildLaunch(binary, args, env = process.env, options = {}
|
|
|
141
147
|
if (env.BOTLEARN_RUNTIME_LAUNCHER !== MANAGED_RUNTIME_LAUNCHER) {
|
|
142
148
|
throw new Error("invalid supervisor-provided runtime launcher");
|
|
143
149
|
}
|
|
144
|
-
if (binary !== MANAGED_RUNTIME_BINARY) {
|
|
150
|
+
if (binary !== MANAGED_RUNTIME_BINARY && binary !== MANAGED_PI_BINARY) {
|
|
145
151
|
throw new Error("invalid supervisor-provided runtime binary");
|
|
146
152
|
}
|
|
147
153
|
return {
|
package/dist/runtime-skills.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type CourseRuntime, type RuntimeCompletionReason, type RuntimeFailureSummary, type RuntimeProgressDispositions, type RuntimeUsage } from "../types.js";
|
|
1
|
+
import { type CourseRuntime, type RuntimeCompletionReason, type RuntimeFailureSummary, type RuntimeProgressDispositions, type RuntimeUsage, type RunStartPayload } from "../types.js";
|
|
2
2
|
import type { Logger } from "../log.js";
|
|
3
3
|
import type { ProgressReport } from "../mcp/report-progress.js";
|
|
4
4
|
import type { PreparedRuntimeSkillProvider, RuntimeSkillEvent } from "../runtime-skills.js";
|
|
@@ -46,6 +46,7 @@ export interface EngineRunOptions {
|
|
|
46
46
|
runtimeStateDir?: string;
|
|
47
47
|
signal: AbortSignal;
|
|
48
48
|
extraArgs?: string[];
|
|
49
|
+
modelContract?: RunStartPayload["runtime"]["model_contract"];
|
|
49
50
|
systemContext?: string;
|
|
50
51
|
/** Final backend-owned prompt for managed execution; applied verbatim. */
|
|
51
52
|
systemPrompt?: string;
|
package/dist/runtimes/engine.js
CHANGED
|
@@ -94,6 +94,8 @@ function runtimeSelectionArgs(id, payload) {
|
|
|
94
94
|
}
|
|
95
95
|
if (id === "deepseek-tui")
|
|
96
96
|
args.push("--reasoning-effort", effort.trim());
|
|
97
|
+
if (id === "pi-agent")
|
|
98
|
+
args.push("--thinking", effort.trim());
|
|
97
99
|
}
|
|
98
100
|
if (id === "kimi-cli" && typeof payload.runtime.thinking === "boolean") {
|
|
99
101
|
args.push(payload.runtime.thinking ? "--thinking" : "--no-thinking");
|
|
@@ -217,6 +219,7 @@ export function wrapEngineAdapter(id, engine, opts) {
|
|
|
217
219
|
try {
|
|
218
220
|
result = await engine.run({
|
|
219
221
|
text,
|
|
222
|
+
...(payload.runtime.model_contract ? { modelContract: payload.runtime.model_contract } : {}),
|
|
220
223
|
...(payload.input.locale ? { locale: payload.input.locale } : {}),
|
|
221
224
|
...(recoveryText !== undefined ? { recoveryText } : {}),
|
|
222
225
|
sessionId: run.nativeSessionId ?? null,
|
package/dist/runtimes/index.js
CHANGED
|
@@ -6,6 +6,7 @@ import { geminiModule } from "./gemini.js";
|
|
|
6
6
|
import { hermesAgentModule } from "./hermes-agent.js";
|
|
7
7
|
import { kimiCliModule } from "./kimi.js";
|
|
8
8
|
import { openclawAcpModule } from "./openclaw-acp.js";
|
|
9
|
+
import { piAgentModule } from "./pi-agent.js";
|
|
9
10
|
export const DEFAULT_RUNTIME_ID = "codex";
|
|
10
11
|
export const RUNTIME_MODULES = [
|
|
11
12
|
codexModule,
|
|
@@ -15,6 +16,7 @@ export const RUNTIME_MODULES = [
|
|
|
15
16
|
kimiCliModule,
|
|
16
17
|
deepseekTuiModule,
|
|
17
18
|
hermesAgentModule,
|
|
19
|
+
piAgentModule,
|
|
18
20
|
fakeModule,
|
|
19
21
|
];
|
|
20
22
|
const BY_ID = new Map(RUNTIME_MODULES.map((m) => [m.id, m]));
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { RuntimeModule, RuntimeProbe } from "../types.js";
|
|
2
|
+
import { type EngineAdapter, type EngineRunOptions, type EngineRunResult } from "./engine.js";
|
|
3
|
+
import { type ProbeDeps } from "./probe.js";
|
|
4
|
+
/** Tested protocol baseline; older packages do not share the settled/delta contract. */
|
|
5
|
+
export declare const PI_AGENT_VERSION = "0.85.1";
|
|
6
|
+
export declare function probePiAgent(deps?: ProbeDeps): RuntimeProbe;
|
|
7
|
+
/**
|
|
8
|
+
* Runtime baseline: one ephemeral RPC process per Course turn. The wrapper rebuilds
|
|
9
|
+
* history from Course facts; Pi's session files are deliberately not a second memory store.
|
|
10
|
+
* Managed execution uses the fixed launcher, scoped model proxy and explicit course Skills.
|
|
11
|
+
*/
|
|
12
|
+
export declare class PiAgentAdapter implements EngineAdapter {
|
|
13
|
+
private readonly options;
|
|
14
|
+
readonly id = "pi-agent";
|
|
15
|
+
constructor(options?: {
|
|
16
|
+
binary?: string;
|
|
17
|
+
});
|
|
18
|
+
run(opts: EngineRunOptions): Promise<EngineRunResult>;
|
|
19
|
+
private execute;
|
|
20
|
+
}
|
|
21
|
+
export declare const piAgentModule: RuntimeModule;
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { runtimeChildEnv, runtimeChildLaunch } from "../runtime-env.js";
|
|
3
|
+
import { MANAGED_PI_BINARY, managedPiVersion, prepareManagedPi } from "./pi-managed.js";
|
|
4
|
+
import { sanitizeRuntimeFailureText } from "../redaction.js";
|
|
5
|
+
import { wrapEngineAdapter } from "./engine.js";
|
|
6
|
+
import { readCommandVersion, resolveCommandOnPath } from "./probe.js";
|
|
7
|
+
/** Tested protocol baseline; older packages do not share the settled/delta contract. */
|
|
8
|
+
export const PI_AGENT_VERSION = "0.85.1";
|
|
9
|
+
const MAX_RECORD_BYTES = 4 * 1024 * 1024;
|
|
10
|
+
const MAX_TEXT_BYTES = 1024 * 1024;
|
|
11
|
+
const KILL_GRACE_MS = 5_000;
|
|
12
|
+
function piEnv(env) {
|
|
13
|
+
return { ...runtimeChildEnv(env), PI_OFFLINE: "1", PI_TELEMETRY: "0", NO_COLOR: "1" };
|
|
14
|
+
}
|
|
15
|
+
export function probePiAgent(deps = {}) {
|
|
16
|
+
const env = piEnv(deps.env ?? process.env);
|
|
17
|
+
const command = env.BOTLEARN_PI_AGENT_BIN || resolveCommandOnPath("pi", { ...deps, env });
|
|
18
|
+
if (!command)
|
|
19
|
+
return { available: false };
|
|
20
|
+
const version = command === MANAGED_PI_BINARY ? managedPiVersion()
|
|
21
|
+
: readCommandVersion(command, [], { ...deps, env });
|
|
22
|
+
return { available: version === PI_AGENT_VERSION, path: command, ...(version ? { version } : {}) };
|
|
23
|
+
}
|
|
24
|
+
function record(value) {
|
|
25
|
+
return value !== null && typeof value === "object" && !Array.isArray(value)
|
|
26
|
+
? value : {};
|
|
27
|
+
}
|
|
28
|
+
function count(value) {
|
|
29
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : 0;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Runtime baseline: one ephemeral RPC process per Course turn. The wrapper rebuilds
|
|
33
|
+
* history from Course facts; Pi's session files are deliberately not a second memory store.
|
|
34
|
+
* Managed execution uses the fixed launcher, scoped model proxy and explicit course Skills.
|
|
35
|
+
*/
|
|
36
|
+
export class PiAgentAdapter {
|
|
37
|
+
options;
|
|
38
|
+
id = "pi-agent";
|
|
39
|
+
constructor(options = {}) {
|
|
40
|
+
this.options = options;
|
|
41
|
+
}
|
|
42
|
+
async run(opts) {
|
|
43
|
+
const managed = Boolean(opts.runtimeStateDir || process.env.BOTLEARN_RUNTIME_LAUNCH_MODE);
|
|
44
|
+
if (!managed)
|
|
45
|
+
return this.execute(opts);
|
|
46
|
+
const prepared = await prepareManagedPi(opts);
|
|
47
|
+
try {
|
|
48
|
+
return await this.execute({ ...opts, env: prepared.env }, prepared.skillsDir, true);
|
|
49
|
+
}
|
|
50
|
+
finally {
|
|
51
|
+
prepared.cleanup();
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
async execute(opts, skillsDir, managed = false) {
|
|
55
|
+
opts.signal.throwIfAborted();
|
|
56
|
+
const sourceEnv = opts.env ?? process.env;
|
|
57
|
+
if (!managed && (opts.skillProvider || [sourceEnv, process.env].some((env) => env.BOTLEARN_RUNTIME_LAUNCH_MODE || env.BOTLEARN_RUNTIME_USER || env.BOTLEARN_RUNTIME_UID))) {
|
|
58
|
+
throw new Error("pi-agent managed sandbox execution is not configured");
|
|
59
|
+
}
|
|
60
|
+
const env = piEnv(sourceEnv);
|
|
61
|
+
const binary = managed ? MANAGED_PI_BINARY
|
|
62
|
+
: this.options.binary || env.BOTLEARN_PI_AGENT_BIN || resolveCommandOnPath("pi", { env });
|
|
63
|
+
if (!binary || (managed ? managedPiVersion() : readCommandVersion(binary, [], { env })) !== PI_AGENT_VERSION) {
|
|
64
|
+
throw new Error(`pi-agent requires @earendil-works/pi-coding-agent@${PI_AGENT_VERSION}`);
|
|
65
|
+
}
|
|
66
|
+
const args = [
|
|
67
|
+
"--mode", "rpc", "--no-session", "--no-approve", "--no-extensions", "--no-skills",
|
|
68
|
+
"--no-prompt-templates", "--no-themes", "--no-context-files",
|
|
69
|
+
];
|
|
70
|
+
// Selection comes from the typed runtime payload, never arbitrary executable options.
|
|
71
|
+
const extra = opts.extraArgs ?? [];
|
|
72
|
+
for (let i = 0; i < extra.length; i += 2) {
|
|
73
|
+
if (!["--model", "--thinking"].includes(extra[i]) || !extra[i + 1]?.trim()) {
|
|
74
|
+
throw new Error("pi-agent received unsupported selection arguments");
|
|
75
|
+
}
|
|
76
|
+
args.push(extra[i], managed && extra[i] === "--model"
|
|
77
|
+
? `botlearn/${extra[i + 1]}` : extra[i + 1]);
|
|
78
|
+
}
|
|
79
|
+
const system = opts.systemPrompt ?? opts.systemContext;
|
|
80
|
+
if (system !== undefined)
|
|
81
|
+
args.push("--system-prompt", system);
|
|
82
|
+
if (skillsDir)
|
|
83
|
+
args.push("--skill", skillsDir);
|
|
84
|
+
opts.signal.throwIfAborted();
|
|
85
|
+
const launch = runtimeChildLaunch(binary, args, managed ? process.env : sourceEnv);
|
|
86
|
+
const child = spawn(launch.binary, launch.args, {
|
|
87
|
+
cwd: opts.cwd, env, ...launch.identity, stdio: ["pipe", "pipe", "pipe"],
|
|
88
|
+
});
|
|
89
|
+
let error;
|
|
90
|
+
let finalText = "";
|
|
91
|
+
let model;
|
|
92
|
+
let lastStopReason;
|
|
93
|
+
let settled = false;
|
|
94
|
+
let seq = 0;
|
|
95
|
+
let textBytes = 0;
|
|
96
|
+
let buffer = "";
|
|
97
|
+
let stderrTail = "";
|
|
98
|
+
let killTimer;
|
|
99
|
+
let abortTimer;
|
|
100
|
+
let hasUsage = false;
|
|
101
|
+
const usage = { input_tokens: 0, output_tokens: 0, total_tokens: 0,
|
|
102
|
+
cached_input_tokens: 0, cost_usd: 0 };
|
|
103
|
+
const stop = () => {
|
|
104
|
+
if (killTimer || child.exitCode !== null || child.signalCode !== null)
|
|
105
|
+
return;
|
|
106
|
+
child.kill("SIGTERM");
|
|
107
|
+
killTimer = setTimeout(() => {
|
|
108
|
+
if (child.exitCode === null && child.signalCode === null)
|
|
109
|
+
child.kill("SIGKILL");
|
|
110
|
+
}, KILL_GRACE_MS);
|
|
111
|
+
killTimer.unref();
|
|
112
|
+
};
|
|
113
|
+
const fail = (message) => {
|
|
114
|
+
error ??= message;
|
|
115
|
+
stop();
|
|
116
|
+
};
|
|
117
|
+
const onAbort = () => {
|
|
118
|
+
// Pi aborts its active tool before termination; escalation bounds an unresponsive process.
|
|
119
|
+
if (child.stdin.writable) {
|
|
120
|
+
child.stdin.write('{"id":"abort","type":"abort"}\n');
|
|
121
|
+
abortTimer = setTimeout(stop, KILL_GRACE_MS);
|
|
122
|
+
abortTimer.unref();
|
|
123
|
+
}
|
|
124
|
+
else
|
|
125
|
+
stop();
|
|
126
|
+
};
|
|
127
|
+
opts.signal.addEventListener("abort", onAbort, { once: true });
|
|
128
|
+
if (opts.signal.aborted)
|
|
129
|
+
onAbort();
|
|
130
|
+
const emit = (kind, data) => {
|
|
131
|
+
if (opts.signal.aborted || error || settled)
|
|
132
|
+
return;
|
|
133
|
+
textBytes += Buffer.byteLength(data.text ?? "");
|
|
134
|
+
if (textBytes > MAX_TEXT_BYTES)
|
|
135
|
+
return fail("pi-agent text exceeded the turn limit");
|
|
136
|
+
opts.onBlock?.({ kind, seq: ++seq, raw: data.raw ?? null, ...data });
|
|
137
|
+
};
|
|
138
|
+
const onEvent = (event) => {
|
|
139
|
+
if (opts.signal.aborted && event.type === "response" && event.id === "abort") {
|
|
140
|
+
stop();
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
if (settled || error || opts.signal.aborted)
|
|
144
|
+
return;
|
|
145
|
+
if (event.type === "response" && event.success === false) {
|
|
146
|
+
// Error payloads may echo prompts or credentials. Keep only the protocol failure here.
|
|
147
|
+
return fail("pi-agent rejected the RPC command");
|
|
148
|
+
}
|
|
149
|
+
if (event.type === "message_update") {
|
|
150
|
+
const delta = record(event.assistantMessageEvent);
|
|
151
|
+
if (typeof delta.delta === "string" && ["text_delta", "thinking_delta"].includes(String(delta.type))) {
|
|
152
|
+
emit(delta.type === "text_delta" ? "assistant_text" : "thinking", { text: delta.delta });
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
else if (event.type === "message_end") {
|
|
156
|
+
const message = record(event.message);
|
|
157
|
+
if (message.role !== "assistant")
|
|
158
|
+
return;
|
|
159
|
+
const content = Array.isArray(message.content) ? message.content.map(record) : [];
|
|
160
|
+
finalText = content.filter((item) => item.type === "text" && typeof item.text === "string")
|
|
161
|
+
.map((item) => item.text).join("");
|
|
162
|
+
if (Buffer.byteLength(finalText) > MAX_TEXT_BYTES)
|
|
163
|
+
return fail("pi-agent final text exceeded the turn limit");
|
|
164
|
+
lastStopReason = typeof message.stopReason === "string" ? message.stopReason : undefined;
|
|
165
|
+
if (typeof message.model === "string")
|
|
166
|
+
model = message.model;
|
|
167
|
+
const current = record(message.usage);
|
|
168
|
+
if (Object.keys(current).length > 0)
|
|
169
|
+
hasUsage = true;
|
|
170
|
+
// Pi input excludes cache tokens. BotLearn input includes them.
|
|
171
|
+
usage.input_tokens += count(current.input) + count(current.cacheRead) + count(current.cacheWrite);
|
|
172
|
+
usage.output_tokens += count(current.output);
|
|
173
|
+
usage.total_tokens += count(current.input) + count(current.cacheRead) + count(current.cacheWrite) + count(current.output);
|
|
174
|
+
usage.cached_input_tokens += count(current.cacheRead);
|
|
175
|
+
usage.cost_usd += count(record(current.cost).total);
|
|
176
|
+
}
|
|
177
|
+
else if (event.type === "tool_execution_start" || event.type === "tool_execution_end") {
|
|
178
|
+
const name = typeof event.toolName === "string" ? event.toolName : "tool";
|
|
179
|
+
const ending = event.type === "tool_execution_end";
|
|
180
|
+
emit(ending ? "tool_result" : "tool_use", {
|
|
181
|
+
name,
|
|
182
|
+
...(ending ? { status: event.isError === true ? "error" : "completed" } : {}),
|
|
183
|
+
// Feed only the existing audit projection, excluding arbitrary provider envelope fields.
|
|
184
|
+
raw: { id: event.toolCallId, name, ...(ending ? { output: event.result } : { input: event.args }) },
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
else if (event.type === "agent_settled") {
|
|
188
|
+
// agent_end may precede automatic retry/compaction. Only settled is terminal.
|
|
189
|
+
settled = true;
|
|
190
|
+
if (lastStopReason !== "stop" || !finalText.trim()) {
|
|
191
|
+
error = "pi-agent settled without a successful final assistant message";
|
|
192
|
+
}
|
|
193
|
+
stop();
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
child.stdout.setEncoding("utf8");
|
|
197
|
+
child.stdout.on("data", (chunk) => {
|
|
198
|
+
if (error || settled)
|
|
199
|
+
return;
|
|
200
|
+
buffer += chunk;
|
|
201
|
+
let newline;
|
|
202
|
+
while ((newline = buffer.indexOf("\n")) >= 0) {
|
|
203
|
+
const line = buffer.slice(0, newline);
|
|
204
|
+
buffer = buffer.slice(newline + 1);
|
|
205
|
+
if (Buffer.byteLength(line) > MAX_RECORD_BYTES)
|
|
206
|
+
return fail("pi-agent RPC record exceeded the limit");
|
|
207
|
+
if (!line.trim())
|
|
208
|
+
continue;
|
|
209
|
+
try {
|
|
210
|
+
onEvent(record(JSON.parse(line)));
|
|
211
|
+
}
|
|
212
|
+
catch {
|
|
213
|
+
return fail("pi-agent invalid RPC event or event consumer failure");
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (Buffer.byteLength(buffer) > MAX_RECORD_BYTES)
|
|
217
|
+
fail("pi-agent RPC record exceeded the limit");
|
|
218
|
+
});
|
|
219
|
+
child.stderr.setEncoding("utf8");
|
|
220
|
+
child.stderr.on("data", (chunk) => {
|
|
221
|
+
stderrTail = sanitizeRuntimeFailureText(stderrTail + chunk, 2048);
|
|
222
|
+
});
|
|
223
|
+
child.stdin.on("error", () => { if (!settled && !opts.signal.aborted)
|
|
224
|
+
fail("pi-agent RPC input failed"); });
|
|
225
|
+
try {
|
|
226
|
+
const exit = new Promise((resolve) => {
|
|
227
|
+
child.once("error", () => { fail("pi-agent process could not start"); resolve(); });
|
|
228
|
+
child.once("close", () => resolve());
|
|
229
|
+
});
|
|
230
|
+
if (!opts.signal.aborted)
|
|
231
|
+
child.stdin.write(JSON.stringify({ id: "prompt", type: "prompt", message: opts.text }) + "\n");
|
|
232
|
+
await exit;
|
|
233
|
+
}
|
|
234
|
+
finally {
|
|
235
|
+
opts.signal.removeEventListener("abort", onAbort);
|
|
236
|
+
if (killTimer)
|
|
237
|
+
clearTimeout(killTimer);
|
|
238
|
+
if (abortTimer)
|
|
239
|
+
clearTimeout(abortTimer);
|
|
240
|
+
}
|
|
241
|
+
opts.signal.throwIfAborted();
|
|
242
|
+
if (!settled)
|
|
243
|
+
error ??= "pi-agent exited before agent_settled";
|
|
244
|
+
return {
|
|
245
|
+
text: error ? "" : finalText, newSessionId: "", ...(hasUsage ? { usage } : {}), ...(model ? { model } : {}),
|
|
246
|
+
...(error ? { error, runtimeFailure: { runtime: this.id, exit_code: child.exitCode,
|
|
247
|
+
signal: child.signalCode, stderr_tail: stderrTail } } : {}),
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
export const piAgentModule = {
|
|
252
|
+
id: "pi-agent", displayName: "Pi Agent", binary: "pi", envVar: "BOTLEARN_PI_AGENT_BIN",
|
|
253
|
+
installHint: `npm install -g @earendil-works/pi-coding-agent@${PI_AGENT_VERSION} (Node.js >=22.19.0)`,
|
|
254
|
+
probe: async () => probePiAgent(),
|
|
255
|
+
create: () => wrapEngineAdapter("pi-agent", new PiAgentAdapter()),
|
|
256
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { EngineRunOptions } from "./engine.js";
|
|
2
|
+
export declare const MANAGED_PI_BINARY = "/opt/pi-agent/0.85.1/bin/pi";
|
|
3
|
+
/** The image verifies the CLI once; per-turn probes read immutable installed metadata. */
|
|
4
|
+
export declare function managedPiVersion(): string | null;
|
|
5
|
+
export declare function prepareManagedPi(opts: EngineRunOptions): Promise<{
|
|
6
|
+
env: NodeJS.ProcessEnv;
|
|
7
|
+
skillsDir?: string;
|
|
8
|
+
cleanup(): void;
|
|
9
|
+
}>;
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { runtimeChildEnv } from "../runtime-env.js";
|
|
4
|
+
import { materializeCourseSkills } from "../runtime-skill-materialization.js";
|
|
5
|
+
export const MANAGED_PI_BINARY = "/opt/pi-agent/0.85.1/bin/pi";
|
|
6
|
+
/** The image verifies the CLI once; per-turn probes read immutable installed metadata. */
|
|
7
|
+
export function managedPiVersion() {
|
|
8
|
+
try {
|
|
9
|
+
if (!existsSync(MANAGED_PI_BINARY))
|
|
10
|
+
return null;
|
|
11
|
+
const pkg = JSON.parse(readFileSync("/opt/pi-agent/0.85.1/node_modules/@earendil-works/pi-coding-agent/package.json", "utf8"));
|
|
12
|
+
return pkg.name === "@earendil-works/pi-coding-agent" ? pkg.version : null;
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export async function prepareManagedPi(opts) {
|
|
19
|
+
const supervisor = process.env;
|
|
20
|
+
const source = runtimeChildEnv(opts.env ?? supervisor);
|
|
21
|
+
const profileRoot = supervisor.BOTLEARN_AGENT_SERVICE_PROFILE_ROOT;
|
|
22
|
+
if (!opts.runtimeStateDir || !supervisor.BOTLEARN_RUNTIME_LAUNCH_MODE || !profileRoot
|
|
23
|
+
|| !source.BOTLEARN_MODEL_API_KEY || !source.BOTLEARN_MODEL_BASE_URL
|
|
24
|
+
|| !source.BOTLEARN_RUNTIME_ACTIVATION_SCOPE || opts.systemPrompt === undefined) {
|
|
25
|
+
throw new Error("pi-agent managed sandbox configuration is incomplete");
|
|
26
|
+
}
|
|
27
|
+
const home = mkdtempSync(path.join(profileRoot, "pi-"));
|
|
28
|
+
// Parent is supervisor-owned and searchable by the fixed runtime group.
|
|
29
|
+
chmodSync(home, 0o1770);
|
|
30
|
+
const cleanup = () => rmSync(home, { recursive: true, force: true });
|
|
31
|
+
try {
|
|
32
|
+
const agentDir = path.join(home, ".pi", "agent");
|
|
33
|
+
mkdirSync(agentDir, { recursive: true, mode: 0o750 });
|
|
34
|
+
chmodSync(path.dirname(agentDir), 0o750);
|
|
35
|
+
// Pi opens its credential-store file even with an environment-backed provider.
|
|
36
|
+
// Sticky group-write permits that state without replacing root-owned models.json.
|
|
37
|
+
chmodSync(agentDir, 0o1770);
|
|
38
|
+
const modelArg = opts.extraArgs?.indexOf("--model") ?? -1;
|
|
39
|
+
const model = modelArg >= 0 ? opts.extraArgs[modelArg + 1] : undefined;
|
|
40
|
+
const contract = opts.modelContract;
|
|
41
|
+
if (!model || !contract || contract.adapter !== "newapi-deepseek-thinking"
|
|
42
|
+
|| contract.runtime_model !== model
|
|
43
|
+
|| !Number.isSafeInteger(contract.context_window) || contract.context_window <= 0
|
|
44
|
+
|| !Number.isSafeInteger(contract.max_output_tokens) || contract.max_output_tokens <= 0
|
|
45
|
+
|| !Number.isSafeInteger(contract.max_output_tokens_limit) || contract.max_output_tokens_limit <= 0
|
|
46
|
+
|| contract.max_output_tokens > contract.max_output_tokens_limit
|
|
47
|
+
|| contract.max_output_tokens_limit > contract.context_window) {
|
|
48
|
+
throw new Error("pi-agent managed model selection is invalid");
|
|
49
|
+
}
|
|
50
|
+
writeFileSync(path.join(agentDir, "models.json"), JSON.stringify({ providers: {
|
|
51
|
+
botlearn: {
|
|
52
|
+
baseUrl: source.BOTLEARN_MODEL_BASE_URL, api: "openai-completions",
|
|
53
|
+
// Pi resolves a named environment variable; no credential bytes are written.
|
|
54
|
+
apiKey: "BOTLEARN_MODEL_API_KEY",
|
|
55
|
+
models: [{ id: model, name: model, reasoning: true, input: ["text"],
|
|
56
|
+
contextWindow: contract.context_window, maxTokens: contract.max_output_tokens,
|
|
57
|
+
compat: { supportsDeveloperRole: false, maxTokensField: "max_tokens",
|
|
58
|
+
supportsReasoningEffort: true, supportsStore: false, supportsStrictMode: false,
|
|
59
|
+
thinkingFormat: "deepseek", requiresReasoningContentOnAssistantMessages: true } }],
|
|
60
|
+
},
|
|
61
|
+
} }), { mode: 0o640 });
|
|
62
|
+
let skillsDir;
|
|
63
|
+
if (opts.skillProvider) {
|
|
64
|
+
const materialized = await materializeCourseSkills({
|
|
65
|
+
prepared: opts.skillProvider, profileRoot: home, managed: true,
|
|
66
|
+
});
|
|
67
|
+
if (materialized.skills.length)
|
|
68
|
+
skillsDir = materialized.skillsDir;
|
|
69
|
+
for (const entry of opts.skillProvider.catalog) {
|
|
70
|
+
await opts.onSkillEvent?.({ schema_version: "agent-skill-event/0.1", kind: "skill_event",
|
|
71
|
+
state: "applied", ref: entry.ref, digest: entry.digest, load_mode: "native" });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return { env: { ...source, HOME: home, PI_CODING_AGENT_DIR: agentDir }, skillsDir, cleanup };
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
cleanup();
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
@@ -179,6 +179,7 @@ export async function runSandboxSupervisor(argv) {
|
|
|
179
179
|
BOTLEARN_RUNTIME_HOME: "/home/user",
|
|
180
180
|
...launchPlan.runtimeLaunchEnv,
|
|
181
181
|
BOTLEARN_DEEPSEEK_TUI_BIN: DEEPSEEK_BINARY,
|
|
182
|
+
BOTLEARN_PI_AGENT_BIN: "/opt/pi-agent/0.85.1/bin/pi",
|
|
182
183
|
BOTLEARN_AGENT_SERVICE_WORKSPACE_ROOT: WORKSPACE,
|
|
183
184
|
BOTLEARN_AGENT_SERVICE_PROFILE_ROOT: RUNTIME_PROFILE_ROOT,
|
|
184
185
|
},
|
package/dist/types.d.ts
CHANGED
|
@@ -30,6 +30,14 @@ export interface RunStartPayload {
|
|
|
30
30
|
id?: string;
|
|
31
31
|
model?: string;
|
|
32
32
|
reasoning_effort?: string;
|
|
33
|
+
model_contract?: {
|
|
34
|
+
adapter: string;
|
|
35
|
+
runtime_model: string;
|
|
36
|
+
context_window: number;
|
|
37
|
+
max_output_tokens: number;
|
|
38
|
+
max_output_tokens_limit: number;
|
|
39
|
+
reasoning_efforts: string[];
|
|
40
|
+
};
|
|
33
41
|
thinking?: boolean;
|
|
34
42
|
web_search?: boolean;
|
|
35
43
|
[key: string]: unknown;
|
package/package.json
CHANGED