@botlearn-course/daemon 0.0.32-beta.4 → 0.0.32-beta.5
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 +6 -0
- package/dist/runtimes/engine.js +1 -1
- package/dist/runtimes/md-review.d.ts +21 -0
- package/dist/runtimes/md-review.js +21 -14
- package/dist/runtimes/pi-agent.js +18 -5
- package/dist/runtimes/pi-managed-subagent-extension.d.ts +3 -1
- package/dist/runtimes/pi-managed-subagent-extension.js +22 -5
- package/dist/runtimes/pi-md-review-extension.d.ts +24 -0
- package/dist/runtimes/pi-md-review-extension.js +70 -0
- package/dist/runtimes/pi-md-review-guard.d.ts +15 -0
- package/dist/runtimes/pi-md-review-guard.js +21 -0
- package/dist/runtimes/pi-md-review-server.d.ts +10 -0
- package/dist/runtimes/pi-md-review-server.js +69 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -214,3 +214,9 @@ pnpm exec vitest run src/runtimes/__tests__/process-reuse-binaries.test.ts
|
|
|
214
214
|
每批最多 50 项、元数据数组最多 192 KiB,长文本预览按字节大小分批而不裁短;预览仍最多 4000 字符。
|
|
215
215
|
整个扫描后上报阶段默认最多等待 10 秒。每批服务端事务提交后确认,普通运行保留上报失败日志并完成。
|
|
216
216
|
详情与三组件配套发布要求见 `docs/specs/agent-service-sandbox-daemon-websocket.md` 第 12.3 节。
|
|
217
|
+
|
|
218
|
+
Pi 托管执行支持专用 `mdreview_review` 工具,与 Codewhale 共用固定 MD 事实审查模板和
|
|
219
|
+
控制进程准备的证据。Pi 子审查只读本次三份输入,不加载联网、技能或委派扩展;异常和报告超限
|
|
220
|
+
明确失败。`reviewed` 表示审查执行完成,不代表内容判为 clean,也不改变学习进度。
|
|
221
|
+
真实 Pi 本地模型替身验证见 `scripts/smoke-pi-md-review.mjs`,完整契约见
|
|
222
|
+
`docs/specs/course-agent-runtime-selection.md`「MD 事实审查的双运行时适配」。
|
package/dist/runtimes/engine.js
CHANGED
|
@@ -190,7 +190,7 @@ export function wrapEngineAdapter(id, engine, opts) {
|
|
|
190
190
|
try {
|
|
191
191
|
result = await engine.run({
|
|
192
192
|
text,
|
|
193
|
-
...(
|
|
193
|
+
...(["deepseek-tui", "pi-agent"].includes(id) ? { mdReviewEvidence: {
|
|
194
194
|
conversation: structuredClone(payload.context.conversation),
|
|
195
195
|
currentRequest: renderCurrentLearnerRequest(payload),
|
|
196
196
|
} } : {}),
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
export declare const MD_REVIEW_MAX_STEPS = 12;
|
|
2
|
+
export declare const MD_REVIEW_WALL_TIME_MS = 240000;
|
|
1
3
|
export declare const MD_REVIEW_TOOL: {
|
|
2
4
|
namespace: string;
|
|
3
5
|
name: string;
|
|
@@ -24,6 +26,21 @@ export interface ReviewEvidence {
|
|
|
24
26
|
conversation: unknown;
|
|
25
27
|
currentRequest: string;
|
|
26
28
|
}
|
|
29
|
+
export interface PreparedMdReview {
|
|
30
|
+
artifact: string;
|
|
31
|
+
artifactSha256: string;
|
|
32
|
+
beforeSha256: string;
|
|
33
|
+
historySha256: string;
|
|
34
|
+
templateVersion: string;
|
|
35
|
+
templateSha256: string;
|
|
36
|
+
evidenceDirectory: string;
|
|
37
|
+
files: {
|
|
38
|
+
artifact: string;
|
|
39
|
+
history: string;
|
|
40
|
+
before: string;
|
|
41
|
+
};
|
|
42
|
+
prompt: string;
|
|
43
|
+
}
|
|
27
44
|
type NativeResult = {
|
|
28
45
|
success: boolean;
|
|
29
46
|
content: {
|
|
@@ -53,7 +70,11 @@ export declare class MdReviewPreparation {
|
|
|
53
70
|
result: NativeResult;
|
|
54
71
|
} | null>;
|
|
55
72
|
private prepare;
|
|
73
|
+
/** Shared evidence only; each runtime owns its read-only child invocation. */
|
|
74
|
+
prepareEvidence(artifact: string): PreparedMdReview;
|
|
56
75
|
private history;
|
|
57
76
|
private readArtifact;
|
|
58
77
|
}
|
|
78
|
+
export declare class ReviewInputError extends Error {
|
|
79
|
+
}
|
|
59
80
|
export {};
|
|
@@ -6,6 +6,8 @@ import { MD_REVIEW_TEMPLATE, MD_REVIEW_TEMPLATE_VERSION } from "./md-review-temp
|
|
|
6
6
|
const MAX_ARTIFACT_BYTES = 64 * 1024;
|
|
7
7
|
const MAX_HISTORY_BYTES = 512 * 1024;
|
|
8
8
|
const MAX_PREPARATIONS = 12;
|
|
9
|
+
export const MD_REVIEW_MAX_STEPS = 12;
|
|
10
|
+
export const MD_REVIEW_WALL_TIME_MS = 240_000;
|
|
9
11
|
export const MD_REVIEW_TOOL = {
|
|
10
12
|
namespace: "mdreview", name: "mdreview_prepare",
|
|
11
13
|
description: "为已写入的学习成果 MD 准备事实审查。只传工作区相对路径;代码提供课程历史原文、首次审查前副本和固定只读审查脚本。返回 prepared 仅表示证据准备好,必须随后用返回的 script 调用原生 workflow(action=run,args={}) 并等待结果;修改后重新准备和复核。不会自动修文件或判定通过。",
|
|
@@ -99,6 +101,21 @@ export class MdReviewPreparation {
|
|
|
99
101
|
}
|
|
100
102
|
}
|
|
101
103
|
prepare(artifact) {
|
|
104
|
+
const prepared = this.prepareEvidence(artifact);
|
|
105
|
+
const dispatch = { role: "reviewer", prompt: prepared.prompt, model: this.options.model,
|
|
106
|
+
...(this.options.reasoningEffort ? { thinking: this.options.reasoningEffort } : {}),
|
|
107
|
+
allowed_tools: ["read"], max_steps: MD_REVIEW_MAX_STEPS,
|
|
108
|
+
wall_time_secs: MD_REVIEW_WALL_TIME_MS / 1000, label: "md-fact-review" };
|
|
109
|
+
const source = 'if (args && Object.keys(args).length) throw new Error("md_review_no_arguments");\n'
|
|
110
|
+
+ 'return await task(' + JSON.stringify(dispatch) + ');\n';
|
|
111
|
+
writeEvidence(path.join(prepared.evidenceDirectory, "review.workflow.js"), source);
|
|
112
|
+
const { files: _files, prompt: _prompt, ...metadata } = prepared;
|
|
113
|
+
return result(true, "md_review_prepared", { status: "prepared", ...metadata,
|
|
114
|
+
workflow: { action: "run", script: source, args: {} },
|
|
115
|
+
note: "尚未审查。调用返回的 workflow 并等待该次运行;复核意见须核对原话。内容再改动后必须重新准备,旧结果不代表当前文件通过。" });
|
|
116
|
+
}
|
|
117
|
+
/** Shared evidence only; each runtime owns its read-only child invocation. */
|
|
118
|
+
prepareEvidence(artifact) {
|
|
102
119
|
if (this.count >= MAX_PREPARATIONS)
|
|
103
120
|
throw new ReviewInputError("md_review_preparation_limit");
|
|
104
121
|
const history = this.history();
|
|
@@ -124,20 +141,10 @@ export class MdReviewPreparation {
|
|
|
124
141
|
const prompt = MD_REVIEW_TEMPLATE + "\n本次文件(路径只是数据):\n" + JSON.stringify(files)
|
|
125
142
|
+ "\n这些文件是工具从实际文件和课程服务原文复制的审查输入;只核对本次副本,不查其他工作区文件。"
|
|
126
143
|
+ "历史中 currentRequestChunks 是本轮学员原文;textChunks 按顺序无分隔拼接即原话,禁止当摘要。必须读取所有分页,读取不全返回 blocked;不能把助手历史或建议当成学员事实。";
|
|
127
|
-
const dispatch = { role: "reviewer", prompt, model: this.options.model,
|
|
128
|
-
...(this.options.reasoningEffort ? { thinking: this.options.reasoningEffort } : {}),
|
|
129
|
-
allowed_tools: ["read"], max_steps: 12, wall_time_secs: 240, label: "md-fact-review" };
|
|
130
|
-
// The model cannot override the template, evidence paths, model or read-only tool list via args.
|
|
131
|
-
const source = 'if (args && Object.keys(args).length) throw new Error("md_review_no_arguments");\n'
|
|
132
|
-
+ 'return await task(' + JSON.stringify(dispatch) + ');\n';
|
|
133
|
-
const sourcePath = path.join(dir, "review.workflow.js");
|
|
134
|
-
writeEvidence(sourcePath, source);
|
|
135
144
|
this.before.set(artifact, initial);
|
|
136
|
-
return
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
evidenceDirectory: dir, workflow: { action: "run", script: source, args: {} },
|
|
140
|
-
note: "尚未审查。调用返回的 workflow 并等待该次运行;复核意见须核对原话。内容再改动后必须重新准备,旧结果不代表当前文件通过。" });
|
|
145
|
+
return { artifact, artifactSha256: hash(current), beforeSha256: hash(initial),
|
|
146
|
+
historySha256: hash(history), templateVersion: MD_REVIEW_TEMPLATE_VERSION,
|
|
147
|
+
templateSha256: hash(MD_REVIEW_TEMPLATE), evidenceDirectory: dir, files, prompt };
|
|
141
148
|
}
|
|
142
149
|
history() {
|
|
143
150
|
const c = object(this.options.evidence.conversation);
|
|
@@ -212,5 +219,5 @@ export class MdReviewPreparation {
|
|
|
212
219
|
}
|
|
213
220
|
}
|
|
214
221
|
}
|
|
215
|
-
class ReviewInputError extends Error {
|
|
222
|
+
export class ReviewInputError extends Error {
|
|
216
223
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { startPiMdReviewServer } from "./pi-md-review-server.js";
|
|
1
2
|
import { ToolSemantics } from "./tool-semantics.js";
|
|
2
3
|
import { spawn } from "node:child_process";
|
|
3
4
|
import { existsSync } from "node:fs";
|
|
@@ -76,6 +77,7 @@ export class PiAgentAdapter {
|
|
|
76
77
|
return this.execute(opts);
|
|
77
78
|
const prepared = await prepareManagedPi(opts);
|
|
78
79
|
let skills;
|
|
80
|
+
let review;
|
|
79
81
|
try {
|
|
80
82
|
// Without an authorized Skill the turn gets no Skill tools: an empty catalog only
|
|
81
83
|
// invites the model to look it up and narrate the result to the learner.
|
|
@@ -84,19 +86,28 @@ export class PiAgentAdapter {
|
|
|
84
86
|
onEvent: opts.onSkillEvent ?? (async () => { }) });
|
|
85
87
|
await skills.markApplied();
|
|
86
88
|
}
|
|
89
|
+
if (opts.mdReviewEvidence)
|
|
90
|
+
review = await startPiMdReviewServer({
|
|
91
|
+
workspace: opts.cwd, evidence: opts.mdReviewEvidence, signal: opts.signal,
|
|
92
|
+
});
|
|
87
93
|
const delegation = writeManagedPiDelegation(prepared.delegationDir, opts, skills?.socketPath);
|
|
88
|
-
return await this.execute({ ...opts, env: prepared.env }, skills?.socketPath, true, delegation);
|
|
94
|
+
return await this.execute({ ...opts, env: prepared.env }, skills?.socketPath, true, delegation, review?.socketPath);
|
|
89
95
|
}
|
|
90
96
|
finally {
|
|
91
97
|
try {
|
|
92
|
-
await
|
|
98
|
+
await review?.close();
|
|
93
99
|
}
|
|
94
100
|
finally {
|
|
95
|
-
|
|
101
|
+
try {
|
|
102
|
+
await skills?.close();
|
|
103
|
+
}
|
|
104
|
+
finally {
|
|
105
|
+
prepared.cleanup();
|
|
106
|
+
}
|
|
96
107
|
}
|
|
97
108
|
}
|
|
98
109
|
}
|
|
99
|
-
async execute(opts, skillsSocket, managed = false, delegation) {
|
|
110
|
+
async execute(opts, skillsSocket, managed = false, delegation, reviewSocket) {
|
|
100
111
|
opts.signal.throwIfAborted();
|
|
101
112
|
const sourceEnv = opts.env ?? process.env;
|
|
102
113
|
if (!managed && (opts.skillProvider || [sourceEnv, process.env].some((env) => env.BOTLEARN_RUNTIME_LAUNCH_MODE || env.BOTLEARN_RUNTIME_USER || env.BOTLEARN_RUNTIME_UID))) {
|
|
@@ -144,6 +155,8 @@ export class PiAgentAdapter {
|
|
|
144
155
|
throw new Error("pi-agent managed delegation is missing");
|
|
145
156
|
args.push("--botlearn-delegation-manifest", delegation);
|
|
146
157
|
}
|
|
158
|
+
if (reviewSocket)
|
|
159
|
+
args.push("--extension", fileURLToPath(new URL("./pi-md-review-extension.js", import.meta.url)), "--botlearn-md-review-socket", reviewSocket, "--botlearn-md-review-manifest", delegation);
|
|
147
160
|
const session = await preparePiSession(opts);
|
|
148
161
|
args.push("--session-dir", session.dir);
|
|
149
162
|
if (session.file)
|
|
@@ -281,7 +294,7 @@ export class PiAgentAdapter {
|
|
|
281
294
|
else if (event.type === "tool_execution_start" || event.type === "tool_execution_end") {
|
|
282
295
|
const name = typeof event.toolName === "string" ? event.toolName : "tool";
|
|
283
296
|
const ending = event.type === "tool_execution_end";
|
|
284
|
-
if (ending &&
|
|
297
|
+
if (ending && ["subagent", "mdreview_review"].includes(name) && typeof event.toolCallId === "string"
|
|
285
298
|
&& !countedDelegations.has(event.toolCallId)) {
|
|
286
299
|
countedDelegations.add(event.toolCallId);
|
|
287
300
|
if (addSubagentUsage(usage, event.result))
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { PreparedMdReview } from "./md-review.js";
|
|
1
2
|
import type { ManagedPiDelegation } from "./pi-managed.js";
|
|
2
3
|
type Task = {
|
|
3
4
|
agent: "worker";
|
|
@@ -121,7 +122,8 @@ export declare const subagentParameters: {
|
|
|
121
122
|
export declare function readDelegation(file: unknown): ManagedPiDelegation;
|
|
122
123
|
/** Every Pi child receives the exact managed launch contract, including recursive delegation. */
|
|
123
124
|
export declare function childArgs(config: ManagedPiDelegation, manifestPath: string, task: string): string[];
|
|
124
|
-
export declare function
|
|
125
|
+
export declare function reviewChildArgs(config: ManagedPiDelegation, review: PreparedMdReview): string[];
|
|
126
|
+
export declare function runWorker(config: ManagedPiDelegation, manifestPath: string, cwd: string, task: string, signal?: AbortSignal, step?: number, review?: PreparedMdReview): Promise<Result>;
|
|
125
127
|
export declare function executeDelegation(config: ManagedPiDelegation, manifestPath: string, cwd: string, params: Params, signal?: AbortSignal): Promise<ToolResult>;
|
|
126
128
|
export default function managedSubagentExtension(pi: PiExtensionAPI): void;
|
|
127
129
|
export {};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { fileURLToPath } from "node:url";
|
|
1
2
|
import { spawn } from "node:child_process";
|
|
2
3
|
import { readFileSync, realpathSync } from "node:fs";
|
|
3
4
|
import path from "node:path";
|
|
@@ -84,6 +85,15 @@ export function childArgs(config, manifestPath, task) {
|
|
|
84
85
|
] : []), "--extension", config.webExtension, "--extension", config.subagentExtension, "--botlearn-delegation-manifest", manifestPath, `Task: ${task}`);
|
|
85
86
|
return args;
|
|
86
87
|
}
|
|
88
|
+
export function reviewChildArgs(config, review) {
|
|
89
|
+
return ["--mode", "json", "-p", "--no-session", "--no-approve", "--no-extensions",
|
|
90
|
+
"--no-skills", "--no-prompt-templates", "--no-themes", "--no-context-files",
|
|
91
|
+
"--tools", "read", "--model", config.model,
|
|
92
|
+
...(config.thinking ? ["--thinking", config.thinking] : []),
|
|
93
|
+
"--system-prompt", review.prompt,
|
|
94
|
+
"--extension", fileURLToPath(new URL("./pi-md-review-guard.js", import.meta.url)),
|
|
95
|
+
"请只读本次证据,执行审查并返回完整报告。"];
|
|
96
|
+
}
|
|
87
97
|
const active = new Set();
|
|
88
98
|
function terminate(child) {
|
|
89
99
|
if (child.exitCode !== null || child.signalCode !== null)
|
|
@@ -102,12 +112,13 @@ process.once("SIGTERM", () => {
|
|
|
102
112
|
for (const child of active)
|
|
103
113
|
terminate(child);
|
|
104
114
|
});
|
|
105
|
-
export async function runWorker(config, manifestPath, cwd, task, signal, step) {
|
|
115
|
+
export async function runWorker(config, manifestPath, cwd, task, signal, step, review) {
|
|
106
116
|
if (signal?.aborted)
|
|
107
117
|
throw new Error("Subagent was aborted");
|
|
108
118
|
if (Buffer.byteLength(task) > MAX_OUTPUT_BYTES)
|
|
109
119
|
throw new Error("Subagent task exceeded the limit");
|
|
110
|
-
const
|
|
120
|
+
const args = review ? reviewChildArgs(config, review) : childArgs(config, manifestPath, task);
|
|
121
|
+
const child = spawn(config.binary, args, {
|
|
111
122
|
cwd, env: process.env, shell: false, stdio: ["ignore", "pipe", "pipe"],
|
|
112
123
|
});
|
|
113
124
|
active.add(child);
|
|
@@ -140,8 +151,14 @@ export async function runWorker(config, manifestPath, cwd, task, signal, step) {
|
|
|
140
151
|
if (message.role !== "assistant")
|
|
141
152
|
return;
|
|
142
153
|
const parts = Array.isArray(message.content) ? message.content.map(object) : [];
|
|
143
|
-
|
|
144
|
-
.map((p) => p.text).join("")
|
|
154
|
+
const output = parts.filter((p) => p.type === "text" && typeof p.text === "string")
|
|
155
|
+
.map((p) => p.text).join("");
|
|
156
|
+
if (review && Buffer.byteLength(output) > MAX_OUTPUT_BYTES) {
|
|
157
|
+
parseFailure = true;
|
|
158
|
+
terminate(child);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
result.output = bounded(output);
|
|
145
162
|
result.stopReason = typeof message.stopReason === "string" ? message.stopReason : undefined;
|
|
146
163
|
result.model = typeof message.model === "string" ? message.model : undefined;
|
|
147
164
|
const own = object(message.usage);
|
|
@@ -190,7 +207,7 @@ export async function runWorker(config, manifestPath, cwd, task, signal, step) {
|
|
|
190
207
|
throw new Error("Subagent was aborted");
|
|
191
208
|
if (parseFailure)
|
|
192
209
|
throw new Error("Subagent emitted invalid or oversized JSON");
|
|
193
|
-
if (exitCode === 0 && result.stopReason !== "stop") {
|
|
210
|
+
if (exitCode === 0 && (result.stopReason !== "stop" || (review && !result.output.trim()))) {
|
|
194
211
|
result.exitCode = 1;
|
|
195
212
|
result.stderr = "Subagent exited without a successful assistant message";
|
|
196
213
|
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type PreparedMdReview } from "./md-review.js";
|
|
2
|
+
export declare const PI_MD_REVIEW_TOOL = "mdreview_review";
|
|
3
|
+
export declare const PI_MD_REVIEW_DESCRIPTION = "\u5BF9\u5DF2\u4FDD\u5B58\u7684\u5B66\u4E60\u6210\u679C MD \u6267\u884C\u53EA\u8BFB\u4E8B\u5B9E\u5BA1\u67E5\u3002\u53EA\u4F20\u5DE5\u4F5C\u533A\u76F8\u5BF9\u8DEF\u5F84 artifact\u3002\u4EE3\u7801\u63D0\u4F9B\u8BFE\u7A0B\u5386\u53F2\u3001\u9996\u6B21\u5BA1\u67E5\u526F\u672C\u53CA\u56FA\u5B9A\u6A21\u677F\uFF0C\u7B49\u5F85\u540E\u8FD4\u56DE\u5B8C\u6574\u62A5\u544A\u3002\u4FEE\u6539\u540E\u518D\u6B21\u8C03\u7528\u590D\u6838\uFF1Bblocked \u6216\u5931\u8D25\u4E0D\u4EE3\u8868\u5BA1\u67E5\u901A\u8FC7\u3002";
|
|
4
|
+
interface PiExtensionAPI {
|
|
5
|
+
registerFlag(name: string, options: {
|
|
6
|
+
description: string;
|
|
7
|
+
type: "string";
|
|
8
|
+
}): void;
|
|
9
|
+
getFlag(name: string): unknown;
|
|
10
|
+
registerTool(tool: {
|
|
11
|
+
name: string;
|
|
12
|
+
label: string;
|
|
13
|
+
description: string;
|
|
14
|
+
parameters: unknown;
|
|
15
|
+
execute(id: string, args: Record<string, unknown>, signal?: AbortSignal): Promise<unknown>;
|
|
16
|
+
}): void;
|
|
17
|
+
}
|
|
18
|
+
export declare function prepareReview(socketPath: string, args: Record<string, unknown>, signal?: AbortSignal): Promise<{
|
|
19
|
+
ok: boolean;
|
|
20
|
+
prepared?: PreparedMdReview;
|
|
21
|
+
code?: string;
|
|
22
|
+
}>;
|
|
23
|
+
export default function mdReviewExtension(pi: PiExtensionAPI): void;
|
|
24
|
+
export {};
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import net from "node:net";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { MD_REVIEW_TEMPLATE } from "./md-review-template.js";
|
|
4
|
+
import { MD_REVIEW_WALL_TIME_MS } from "./md-review.js";
|
|
5
|
+
import { readDelegation, runWorker } from "./pi-managed-subagent-extension.js";
|
|
6
|
+
export const PI_MD_REVIEW_TOOL = "mdreview_review";
|
|
7
|
+
export const PI_MD_REVIEW_DESCRIPTION = "对已保存的学习成果 MD 执行只读事实审查。只传工作区相对路径 artifact。代码提供课程历史、首次审查副本及固定模板,等待后返回完整报告。修改后再次调用复核;blocked 或失败不代表审查通过。";
|
|
8
|
+
export function prepareReview(socketPath, args, signal) {
|
|
9
|
+
return new Promise((resolve, reject) => {
|
|
10
|
+
const socket = net.createConnection(socketPath);
|
|
11
|
+
let buffer = "";
|
|
12
|
+
const fail = () => { socket.destroy(); reject(new Error("md_review_transport_failed")); };
|
|
13
|
+
socket.on("error", fail);
|
|
14
|
+
socket.once("close", () => { signal?.removeEventListener("abort", fail); fail(); });
|
|
15
|
+
socket.setTimeout(15_000, fail);
|
|
16
|
+
signal?.addEventListener("abort", fail, { once: true });
|
|
17
|
+
socket.setEncoding("utf8");
|
|
18
|
+
socket.on("data", chunk => {
|
|
19
|
+
buffer += chunk;
|
|
20
|
+
if (Buffer.byteLength(buffer) > 128 * 1024)
|
|
21
|
+
return fail();
|
|
22
|
+
const end = buffer.indexOf("\n");
|
|
23
|
+
if (end < 0)
|
|
24
|
+
return;
|
|
25
|
+
try {
|
|
26
|
+
resolve(JSON.parse(buffer.slice(0, end)));
|
|
27
|
+
socket.destroy();
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
fail();
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
socket.once("connect", () => socket.write(JSON.stringify(args) + "\n"));
|
|
34
|
+
if (signal?.aborted)
|
|
35
|
+
fail();
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
export default function mdReviewExtension(pi) {
|
|
39
|
+
pi.registerFlag("botlearn-md-review-socket", { description: "本轮事实审查证据套接字", type: "string" });
|
|
40
|
+
pi.registerFlag("botlearn-md-review-manifest", { description: "本轮只读审查启动配置", type: "string" });
|
|
41
|
+
pi.registerTool({ name: PI_MD_REVIEW_TOOL, label: "事实审查", description: PI_MD_REVIEW_DESCRIPTION,
|
|
42
|
+
parameters: { type: "object", additionalProperties: false, required: ["artifact"],
|
|
43
|
+
properties: { artifact: { type: "string", description: "工作区内成果 MD 相对路径" } } },
|
|
44
|
+
async execute(_id, args, signal) {
|
|
45
|
+
const socket = pi.getFlag("botlearn-md-review-socket");
|
|
46
|
+
if (typeof socket !== "string" || !path.isAbsolute(socket))
|
|
47
|
+
throw new Error("md_review_unavailable");
|
|
48
|
+
const response = await prepareReview(socket, args, signal);
|
|
49
|
+
if (!response.ok || !response.prepared)
|
|
50
|
+
return { isError: true,
|
|
51
|
+
content: [{ type: "text", text: JSON.stringify({ status: "blocked", code: response.code }) }], details: {} };
|
|
52
|
+
const prepared = response.prepared;
|
|
53
|
+
// Reject mismatched packages rather than asking a child to follow a different template.
|
|
54
|
+
if (!prepared.prompt.startsWith(MD_REVIEW_TEMPLATE))
|
|
55
|
+
throw new Error("md_review_template_mismatch");
|
|
56
|
+
const manifest = pi.getFlag("botlearn-md-review-manifest");
|
|
57
|
+
const config = readDelegation(manifest);
|
|
58
|
+
const deadline = AbortSignal.timeout(MD_REVIEW_WALL_TIME_MS);
|
|
59
|
+
const boundedSignal = signal ? AbortSignal.any([signal, deadline]) : deadline;
|
|
60
|
+
const result = await runWorker(config, manifest, prepared.evidenceDirectory, "核对指定证据并返回完整事实审查报告。", boundedSignal, undefined, prepared);
|
|
61
|
+
const failed = result.exitCode !== 0 || result.stopReason !== "stop";
|
|
62
|
+
const { prompt: _prompt, files: _files, ...metadata } = prepared;
|
|
63
|
+
// A completed child is advisory, never an automatic clean verdict or course completion.
|
|
64
|
+
return { ...(failed ? { isError: true } : {}), content: [{ type: "text", text: JSON.stringify({
|
|
65
|
+
status: failed ? "blocked" : "reviewed", ...metadata,
|
|
66
|
+
report: failed ? undefined : result.output, code: failed ? "md_review_child_failed" : undefined,
|
|
67
|
+
}) }], details: { results: [result] } };
|
|
68
|
+
},
|
|
69
|
+
});
|
|
70
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
interface PiExtensionAPI {
|
|
2
|
+
on(event: "tool_call", callback: (event: {
|
|
3
|
+
toolName: string;
|
|
4
|
+
input: Record<string, unknown>;
|
|
5
|
+
}, ctx: {
|
|
6
|
+
cwd: string;
|
|
7
|
+
}) => {
|
|
8
|
+
block: true;
|
|
9
|
+
reason: string;
|
|
10
|
+
terminate: true;
|
|
11
|
+
} | undefined): void;
|
|
12
|
+
}
|
|
13
|
+
/** The controller chooses cwd: only these immutable evidence files may be read. */
|
|
14
|
+
export default function reviewGuard(pi: PiExtensionAPI): void;
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { realpathSync } from "node:fs";
|
|
2
|
+
import path from "node:path";
|
|
3
|
+
import { MD_REVIEW_MAX_STEPS } from "./md-review.js";
|
|
4
|
+
/** The controller chooses cwd: only these immutable evidence files may be read. */
|
|
5
|
+
export default function reviewGuard(pi) {
|
|
6
|
+
let calls = 0;
|
|
7
|
+
pi.on("tool_call", (event, ctx) => {
|
|
8
|
+
const deny = () => ({ block: true, reason: "事实审查只允许读取本次三份证据,且不得超过读取次数上限。", terminate: true });
|
|
9
|
+
if (++calls > MD_REVIEW_MAX_STEPS || event.toolName !== "read" || typeof event.input.path !== "string")
|
|
10
|
+
return deny();
|
|
11
|
+
try {
|
|
12
|
+
const root = realpathSync(ctx.cwd);
|
|
13
|
+
const file = realpathSync(path.resolve(root, event.input.path));
|
|
14
|
+
if (!["artifact.md", "history.json", "before.md"].some(name => file === path.join(root, name)))
|
|
15
|
+
return deny();
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return deny();
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { type ReviewEvidence } from "./md-review.js";
|
|
2
|
+
/** Control-owned evidence; the runtime may request an artifact, never supply history/template. */
|
|
3
|
+
export declare function startPiMdReviewServer(options: {
|
|
4
|
+
workspace: string;
|
|
5
|
+
evidence: ReviewEvidence;
|
|
6
|
+
signal: AbortSignal;
|
|
7
|
+
}): Promise<{
|
|
8
|
+
socketPath: string;
|
|
9
|
+
close: () => Promise<void>;
|
|
10
|
+
}>;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { chmodSync, mkdtempSync, rmSync } from "node:fs";
|
|
2
|
+
import net from "node:net";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { MdReviewPreparation, prepareMdReviewDirectory, ReviewInputError } from "./md-review.js";
|
|
6
|
+
/** Control-owned evidence; the runtime may request an artifact, never supply history/template. */
|
|
7
|
+
export async function startPiMdReviewServer(options) {
|
|
8
|
+
const preparation = new MdReviewPreparation({ workspace: options.workspace,
|
|
9
|
+
stateDir: prepareMdReviewDirectory(options.workspace), evidence: structuredClone(options.evidence), model: "" });
|
|
10
|
+
const directory = mkdtempSync(path.join(os.tmpdir(), "pi-md-review-"));
|
|
11
|
+
chmodSync(directory, 0o750);
|
|
12
|
+
const socketPath = path.join(directory, "review.sock");
|
|
13
|
+
const sockets = new Set();
|
|
14
|
+
const server = net.createServer(socket => {
|
|
15
|
+
sockets.add(socket);
|
|
16
|
+
socket.once("close", () => sockets.delete(socket));
|
|
17
|
+
socket.on("error", () => socket.destroy());
|
|
18
|
+
socket.setTimeout(15_000, () => socket.destroy());
|
|
19
|
+
let buffer = "";
|
|
20
|
+
let handled = false;
|
|
21
|
+
socket.setEncoding("utf8");
|
|
22
|
+
socket.on("data", chunk => {
|
|
23
|
+
if (handled)
|
|
24
|
+
return;
|
|
25
|
+
buffer += chunk;
|
|
26
|
+
if (Buffer.byteLength(buffer) > 4096 || options.signal.aborted)
|
|
27
|
+
return socket.destroy();
|
|
28
|
+
if (!buffer.includes("\n"))
|
|
29
|
+
return;
|
|
30
|
+
handled = true;
|
|
31
|
+
try {
|
|
32
|
+
const args = JSON.parse(buffer.slice(0, buffer.indexOf("\n")));
|
|
33
|
+
if (!args || Object.keys(args).join(",") !== "artifact" || typeof args.artifact !== "string") {
|
|
34
|
+
throw new ReviewInputError("md_review_arguments_invalid");
|
|
35
|
+
}
|
|
36
|
+
socket.end(JSON.stringify({ ok: true, prepared: preparation.prepareEvidence(args.artifact) }) + "\n");
|
|
37
|
+
}
|
|
38
|
+
catch (error) {
|
|
39
|
+
socket.end(JSON.stringify({ ok: false, code: error instanceof ReviewInputError
|
|
40
|
+
? error.message : "md_review_preparation_failed", status: "blocked" }) + "\n");
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
let closing;
|
|
45
|
+
const close = () => closing ??= (async () => {
|
|
46
|
+
options.signal.removeEventListener("abort", abort);
|
|
47
|
+
for (const socket of sockets)
|
|
48
|
+
socket.destroy();
|
|
49
|
+
if (server.listening)
|
|
50
|
+
await new Promise(resolve => server.close(() => resolve()));
|
|
51
|
+
rmSync(directory, { recursive: true, force: true });
|
|
52
|
+
})();
|
|
53
|
+
const abort = () => { void close(); };
|
|
54
|
+
try {
|
|
55
|
+
options.signal.throwIfAborted();
|
|
56
|
+
await new Promise((resolve, reject) => {
|
|
57
|
+
server.once("error", reject);
|
|
58
|
+
server.listen(socketPath, () => { server.off("error", reject); resolve(); });
|
|
59
|
+
});
|
|
60
|
+
chmodSync(socketPath, 0o660);
|
|
61
|
+
options.signal.addEventListener("abort", abort, { once: true });
|
|
62
|
+
options.signal.throwIfAborted();
|
|
63
|
+
return { socketPath, close };
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
await close();
|
|
67
|
+
throw error;
|
|
68
|
+
}
|
|
69
|
+
}
|