@te-river/opencode-team-mode 1.5.0 → 1.5.2
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 +157 -53
- package/README.zh-CN.md +137 -53
- package/dist/agents.d.ts.map +1 -1
- package/dist/agents.js +128 -26
- package/dist/agents.js.map +1 -1
- package/dist/approval-gate.d.ts +147 -0
- package/dist/approval-gate.d.ts.map +1 -0
- package/dist/approval-gate.js +471 -0
- package/dist/approval-gate.js.map +1 -0
- package/dist/commands.js +3 -3
- package/dist/commands.js.map +1 -1
- package/dist/envprotect.d.ts +234 -0
- package/dist/envprotect.d.ts.map +1 -0
- package/dist/envprotect.js +820 -0
- package/dist/envprotect.js.map +1 -0
- package/dist/index.d.ts +5 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +112 -1
- package/dist/index.js.map +1 -1
- package/dist/tm/config.d.ts +105 -0
- package/dist/tm/config.d.ts.map +1 -0
- package/dist/tm/config.js +118 -0
- package/dist/tm/config.js.map +1 -0
- package/dist/tm/guard.d.ts +56 -0
- package/dist/tm/guard.d.ts.map +1 -0
- package/dist/tm/guard.js +249 -0
- package/dist/tm/guard.js.map +1 -0
- package/dist/tm/index.d.ts +41 -0
- package/dist/tm/index.d.ts.map +1 -0
- package/dist/tm/index.js +93 -0
- package/dist/tm/index.js.map +1 -0
- package/dist/tm/preview.d.ts +46 -0
- package/dist/tm/preview.d.ts.map +1 -0
- package/dist/tm/preview.js +354 -0
- package/dist/tm/preview.js.map +1 -0
- package/dist/tm/ptc.d.ts +279 -0
- package/dist/tm/ptc.d.ts.map +1 -0
- package/dist/tm/ptc.js +839 -0
- package/dist/tm/ptc.js.map +1 -0
- package/dist/tm/refs.d.ts +37 -0
- package/dist/tm/refs.d.ts.map +1 -0
- package/dist/tm/refs.js +58 -0
- package/dist/tm/refs.js.map +1 -0
- package/dist/tm/store.d.ts +95 -0
- package/dist/tm/store.d.ts.map +1 -0
- package/dist/tm/store.js +222 -0
- package/dist/tm/store.js.map +1 -0
- package/dist/tm/tools.d.ts +84 -0
- package/dist/tm/tools.d.ts.map +1 -0
- package/dist/tm/tools.js +710 -0
- package/dist/tm/tools.js.map +1 -0
- package/dist/types.d.ts +155 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +3 -2
package/dist/tm/ptc.js
ADDED
|
@@ -0,0 +1,839 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* tm_ptc_run — M1 contract + aggregation skeleton (NO sandbox).
|
|
3
|
+
*
|
|
4
|
+
* Design: .git/opencode-team/.../ptc-run/02-architect-ptc-run-design.md §2/§3/§4/§6.
|
|
5
|
+
* Milestone split (design §10): this is **M1 only** — args schema, the engine
|
|
6
|
+
* RPC seam frozen for M2, the StepGate failure governance (error / call /
|
|
7
|
+
* time budgets, ≤1 retry on idempotent phases, produced-output preservation),
|
|
8
|
+
* the five-state status enum, the char-pinned aggregation summary, composite
|
|
9
|
+
* step numbers (`sXXXX.kNN`) and the trajectory event shapes.
|
|
10
|
+
*
|
|
11
|
+
* Deliberately NOT here in M1 (deferred):
|
|
12
|
+
* - the worker/RPC engine + inline-VM sandbox (M2 — the `PtcEngine` seam
|
|
13
|
+
* below is frozen so M2 adds an engine without touching this contract);
|
|
14
|
+
* - the program-source static pre-scan is WRITTEN but NOT wired into the run
|
|
15
|
+
* path (M2 attaches it) — `staticPscan`, marked unused here;
|
|
16
|
+
* - registering `tm_ptc_run` into the tm_* tool set (M3 role/whitelist
|
|
17
|
+
* wiring) — `buildPtcRunTool` exists and is fully exercised by tests, but
|
|
18
|
+
* index.ts does NOT merge it into `tools` yet.
|
|
19
|
+
*
|
|
20
|
+
* Governance is REUSED, never forked (D6 lock): the inline bridge calls the
|
|
21
|
+
* exact four exported pipelines (`buildPipelines`), so threshold offload,
|
|
22
|
+
* P2/P3, R6 and handle/TTL semantics apply to every bridged call verbatim.
|
|
23
|
+
* PTC is NOT a bypass layer.
|
|
24
|
+
*/
|
|
25
|
+
import * as crypto from "node:crypto";
|
|
26
|
+
import * as vm from "node:vm";
|
|
27
|
+
import { estimateTokens, shouldOffload, shorten } from "./config.js";
|
|
28
|
+
import { buildRef } from "./refs.js";
|
|
29
|
+
import { detectContentType } from "./preview.js";
|
|
30
|
+
import { tmError } from "./tools.js";
|
|
31
|
+
// ---------- public contract types (frozen for M2's RPC surface) ----------
|
|
32
|
+
/** The five PTC run statuses (design §2). */
|
|
33
|
+
export const PTC_STATUS_VALUES = [
|
|
34
|
+
"ok",
|
|
35
|
+
"stopped-error-budget",
|
|
36
|
+
"stopped-call-budget",
|
|
37
|
+
"timeout",
|
|
38
|
+
"engine-error",
|
|
39
|
+
];
|
|
40
|
+
/** Bridge allow set — read-only; tm_ptc_run itself is excluded (no nesting). */
|
|
41
|
+
export const BRIDGE_ALLOW = ["tm_read", "tm_grep", "tm_bash", "tm_fetch"];
|
|
42
|
+
/** Phases safe to retry once (idempotent read-only bridges; design §4.2). */
|
|
43
|
+
export const RETRYABLE_PHASES = ["client", "execute", "store"];
|
|
44
|
+
/**
|
|
45
|
+
* Clamp a caller-supplied budget against the resolved env ceiling. Absent ->
|
|
46
|
+
* the env ceiling; above the ceiling -> clamped DOWN (cannot loosen); below
|
|
47
|
+
* the hard floor -> clamped UP to the floor. Non-finite is ignored (ceiling).
|
|
48
|
+
*/
|
|
49
|
+
function clampBudget(raw, ceiling, floor) {
|
|
50
|
+
const n = typeof raw === "number" ? raw : raw == null ? NaN : Number(raw);
|
|
51
|
+
if (!Number.isFinite(n))
|
|
52
|
+
return ceiling;
|
|
53
|
+
const i = Math.trunc(n);
|
|
54
|
+
if (i > ceiling)
|
|
55
|
+
return ceiling;
|
|
56
|
+
if (i < floor)
|
|
57
|
+
return floor;
|
|
58
|
+
return i;
|
|
59
|
+
}
|
|
60
|
+
export function resolvePtcBudgets(cfg, budgets) {
|
|
61
|
+
const b = budgets && typeof budgets === "object" ? budgets : {};
|
|
62
|
+
return {
|
|
63
|
+
maxCalls: clampBudget(b.max_calls, cfg.ptcMaxCalls, PTC_BUDGET_BOUNDS_FLOOR.maxCalls),
|
|
64
|
+
maxErrors: clampBudget(b.max_errors, cfg.ptcMaxErrors, PTC_BUDGET_BOUNDS_FLOOR.maxErrors),
|
|
65
|
+
timeoutMs: clampBudget(b.timeout_ms, cfg.ptcTimeoutMs, PTC_BUDGET_BOUNDS_FLOOR.timeoutMs),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
// floors mirror config.ts PTC_BUDGET_BOUNDS (kept here so this module stays
|
|
69
|
+
// self-contained for clamp tests without importing config internals).
|
|
70
|
+
const PTC_BUDGET_BOUNDS_FLOOR = { maxCalls: 1, maxErrors: 1, timeoutMs: 5000 };
|
|
71
|
+
// ---------- arg schema + validation ----------
|
|
72
|
+
export const PTC_LABEL_MAX = 80;
|
|
73
|
+
/**
|
|
74
|
+
* Validate + normalize tm_ptc_run args. `program` over the length cap is a
|
|
75
|
+
* hard args error (a program cannot be meaningfully truncated); `label` over
|
|
76
|
+
* 80 is truncated; `budgets` are clamped toward the env ceilings.
|
|
77
|
+
*/
|
|
78
|
+
export function parsePtcArgs(raw, cfg) {
|
|
79
|
+
const a = raw ?? {};
|
|
80
|
+
const program = typeof a.program === "string" ? a.program : "";
|
|
81
|
+
if (!program.trim()) {
|
|
82
|
+
return { ok: false, error: tmError("tm_ptc_run", "args", "缺少 program 参数(async 函数体,可用 tm.read/tm.grep/tm.bash/tm.fetch)") };
|
|
83
|
+
}
|
|
84
|
+
if (program.length > cfg.ptcMaxProgramChars) {
|
|
85
|
+
return {
|
|
86
|
+
ok: false,
|
|
87
|
+
error: tmError("tm_ptc_run", "args", `program 超过长度上限 ${cfg.ptcMaxProgramChars} 字符(实际 ${program.length})。请拆分批次或调高 TM_PTC_MAX_PROGRAM_CHARS。`),
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
let label = typeof a.label === "string" && a.label.trim() ? a.label.trim() : "ptc-run";
|
|
91
|
+
if (label.length > PTC_LABEL_MAX)
|
|
92
|
+
label = label.slice(0, PTC_LABEL_MAX);
|
|
93
|
+
const budgets = resolvePtcBudgets(cfg, a.budgets);
|
|
94
|
+
return { ok: true, args: { program, label, budgets } };
|
|
95
|
+
}
|
|
96
|
+
// ---------- static pre-scan (WRITTEN, NOT enabled in M1 — M2 wires it) ------
|
|
97
|
+
/** Banned identifier tokens for the program source (auxiliary guard, not a
|
|
98
|
+
* security boundary — see design §3 trust model). */
|
|
99
|
+
const PSCAN_PATTERNS = [
|
|
100
|
+
/\brequire\b/,
|
|
101
|
+
/\bimport\b/,
|
|
102
|
+
/\bprocess\b/,
|
|
103
|
+
/\bglobalThis\b/,
|
|
104
|
+
/\bDeno\b/,
|
|
105
|
+
/\bBun\b/,
|
|
106
|
+
/\bfs\b/,
|
|
107
|
+
/\bnet\b/,
|
|
108
|
+
/\bchild_process\b/,
|
|
109
|
+
];
|
|
110
|
+
/** Static scan of a program string. M1 EXPOSES + tests this but does NOT call
|
|
111
|
+
* it in the run path (the sandbox that needs it lands in M2). */
|
|
112
|
+
export function staticPscan(program) {
|
|
113
|
+
const tokens = [];
|
|
114
|
+
for (const re of PSCAN_PATTERNS) {
|
|
115
|
+
if (re.test(program))
|
|
116
|
+
tokens.push(re.source.replace(/\\b/g, "").replace(/\b/g, ""));
|
|
117
|
+
}
|
|
118
|
+
return { rejected: tokens.length > 0, tokens };
|
|
119
|
+
}
|
|
120
|
+
// ---------- the inline sequential engine (M1's only engine) ----------------
|
|
121
|
+
class PtcStopSignal extends Error {
|
|
122
|
+
reason;
|
|
123
|
+
constructor(reason) {
|
|
124
|
+
super(`ptc-stop:${reason}`);
|
|
125
|
+
this.reason = reason;
|
|
126
|
+
this.name = "PtcStopSignal";
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
function makeFacade(bridge) {
|
|
130
|
+
const one = (tool) => (args) => bridge.call(tool, args && typeof args === "object" ? args : {});
|
|
131
|
+
return { read: one("tm_read"), grep: one("tm_grep"), bash: one("tm_bash"), fetch: one("tm_fetch") };
|
|
132
|
+
}
|
|
133
|
+
/** Best-effort line extraction from a program-side thrown error stack. */
|
|
134
|
+
function extractLine(err) {
|
|
135
|
+
const s = err instanceof Error ? err.stack ?? "" : String(err ?? "");
|
|
136
|
+
const m = /:(\d+):/.exec(s);
|
|
137
|
+
if (m) {
|
|
138
|
+
const n = Number(m[1]);
|
|
139
|
+
if (Number.isFinite(n))
|
|
140
|
+
return n;
|
|
141
|
+
}
|
|
142
|
+
const m2 = /line[:#]?\s*(\d+)/i.exec(s);
|
|
143
|
+
return m2 ? Number(m2[1]) : undefined;
|
|
144
|
+
}
|
|
145
|
+
export class InlineSequentialEngine {
|
|
146
|
+
name = "inline";
|
|
147
|
+
async run(program, bridge, signal) {
|
|
148
|
+
// M1 = "no sandbox": the program is a trusted async function body (only our
|
|
149
|
+
// implementer/tester agents author it, temp 0.2). M2 replaces this with the
|
|
150
|
+
// worker/VM engines behind the SAME seam; nothing else in this file changes.
|
|
151
|
+
const AsyncFunction = Object.getPrototypeOf(async function () { }).constructor;
|
|
152
|
+
const tm = makeFacade(bridge);
|
|
153
|
+
let abortHandler;
|
|
154
|
+
const abortP = new Promise((_, rej) => {
|
|
155
|
+
// The driver only aborts on wall-clock timeout (budget stops flow through
|
|
156
|
+
// the gate as PtcStopSignal). M2's worker engine adds terminate here.
|
|
157
|
+
abortHandler = () => rej(new PtcStopSignal("timeout"));
|
|
158
|
+
if (signal.aborted)
|
|
159
|
+
abortHandler();
|
|
160
|
+
else
|
|
161
|
+
signal.addEventListener("abort", abortHandler, { once: true });
|
|
162
|
+
});
|
|
163
|
+
try {
|
|
164
|
+
const fn = new AsyncFunction("tm", `"use strict";\n${program}`);
|
|
165
|
+
return await Promise.race([fn(tm), abortP]);
|
|
166
|
+
}
|
|
167
|
+
finally {
|
|
168
|
+
if (abortHandler)
|
|
169
|
+
signal.removeEventListener("abort", abortHandler);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
// ---------- M2: worker engine (MessagePort RPC over worker_threads) ----------
|
|
174
|
+
/**
|
|
175
|
+
* Worker engine — runs the program in a dedicated `worker_threads.Worker`
|
|
176
|
+
* with `env:{}` (process.env emptied), `resourceLimits`, and `terminate()`
|
|
177
|
+
* for hard timeout kills. The bootstrap source is a build-time template
|
|
178
|
+
* string constant (zero runtime file IO, zero new deps, passes tsc).
|
|
179
|
+
*
|
|
180
|
+
* Probe result (P1, %TEMP%): ALL-GREEN on Node 24 / win32 — eval bootstrap,
|
|
181
|
+
* postMessage bidirectional, terminate (9 ms), resourceLimits, env:{} all
|
|
182
|
+
* verified. Auto chain = worker-first, inline fallback.
|
|
183
|
+
*/
|
|
184
|
+
export class WorkerEngine {
|
|
185
|
+
name = "worker";
|
|
186
|
+
async run(program, bridge, signal) {
|
|
187
|
+
const { Worker } = await import("node:worker_threads");
|
|
188
|
+
// Build the worker bootstrap source as a regular string (ts-safe).
|
|
189
|
+
// The worker receives {program, startDeadlineMs} via its first message,
|
|
190
|
+
// creates the tm facade, runs the program, and sends RPC call requests
|
|
191
|
+
// back to the driver which executes them through the gate bridge.
|
|
192
|
+
const src = [
|
|
193
|
+
'"use strict";',
|
|
194
|
+
'const { parentPort } = require("node:worker_threads");',
|
|
195
|
+
"parentPort.on(" + JSON.stringify("message") + ", async function onMsg(msg) {",
|
|
196
|
+
" if (msg && msg.t === " + JSON.stringify("run") + ") {",
|
|
197
|
+
" const program = msg.program;",
|
|
198
|
+
" const AsyncFunction = Object.getPrototypeOf(async function(){}).constructor;",
|
|
199
|
+
" const callMap = new Map();",
|
|
200
|
+
" let nextId = 0;",
|
|
201
|
+
' const one = function(tool) { return function(args) { return new Promise(function(resolve, reject) {',
|
|
202
|
+
" const id = nextId++;",
|
|
203
|
+
" callMap.set(id, { resolve: resolve, reject: reject });",
|
|
204
|
+
' parentPort.postMessage({ t: "call", id: id, tool: tool, args: args || {} });',
|
|
205
|
+
" }); }; };",
|
|
206
|
+
" var tm = { read: one(" + JSON.stringify("tm_read") + "), grep: one(" + JSON.stringify("tm_grep") + "), bash: one(" + JSON.stringify("tm_bash") + "), fetch: one(" + JSON.stringify("tm_fetch") + ") };",
|
|
207
|
+
' parentPort.on("message", function(inner) {',
|
|
208
|
+
' if (inner && inner.t === "result" && callMap.has(inner.id)) {',
|
|
209
|
+
" callMap.get(inner.id).resolve(inner.r);",
|
|
210
|
+
" callMap.delete(inner.id);",
|
|
211
|
+
' } else if (inner && inner.t === "abort") {',
|
|
212
|
+
" for (const e of callMap.values()) e.reject(new Error(" + JSON.stringify("ptc-stop:") + " + inner.reason));",
|
|
213
|
+
" callMap.clear();",
|
|
214
|
+
" }",
|
|
215
|
+
" });",
|
|
216
|
+
" try {",
|
|
217
|
+
" var fn = new AsyncFunction(" + JSON.stringify("tm") + ", program);",
|
|
218
|
+
" var result = await fn(tm);",
|
|
219
|
+
' parentPort.postMessage({ t: "done", result: result });',
|
|
220
|
+
" } catch (err) {",
|
|
221
|
+
' parentPort.postMessage({ t: "error", message: err instanceof Error ? err.message : String(err), stack: err instanceof Error ? err.stack : undefined });',
|
|
222
|
+
" }",
|
|
223
|
+
" }",
|
|
224
|
+
"});",
|
|
225
|
+
].join("\n");
|
|
226
|
+
return new Promise((resolve, reject) => {
|
|
227
|
+
let settled = false;
|
|
228
|
+
const w = new Worker(src, {
|
|
229
|
+
eval: true,
|
|
230
|
+
env: {},
|
|
231
|
+
resourceLimits: { maxOldGenerationSizeMb: 128, maxYoungGenerationSizeMb: 16 },
|
|
232
|
+
});
|
|
233
|
+
function settle(fn) {
|
|
234
|
+
if (settled)
|
|
235
|
+
return;
|
|
236
|
+
settled = true;
|
|
237
|
+
fn();
|
|
238
|
+
}
|
|
239
|
+
w.on("message", (msg) => {
|
|
240
|
+
if (!msg || settled)
|
|
241
|
+
return;
|
|
242
|
+
if (msg.t === "done") {
|
|
243
|
+
settle(() => {
|
|
244
|
+
w.terminate();
|
|
245
|
+
resolve(msg.result);
|
|
246
|
+
});
|
|
247
|
+
}
|
|
248
|
+
else if (msg.t === "error") {
|
|
249
|
+
settle(() => {
|
|
250
|
+
w.terminate();
|
|
251
|
+
const err = new Error(typeof msg.message === "string" ? msg.message : "worker error");
|
|
252
|
+
if (typeof msg.stack === "string")
|
|
253
|
+
err.stack = msg.stack;
|
|
254
|
+
reject(err);
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
else if (msg.t === "call") {
|
|
258
|
+
// Driver executes the bridge call through the gate and replies.
|
|
259
|
+
const req = msg;
|
|
260
|
+
bridge
|
|
261
|
+
.call(req.tool, req.args)
|
|
262
|
+
.then((r) => {
|
|
263
|
+
if (!settled) {
|
|
264
|
+
w.postMessage({ t: "result", id: req.id, r });
|
|
265
|
+
}
|
|
266
|
+
})
|
|
267
|
+
.catch(() => {
|
|
268
|
+
if (!settled) {
|
|
269
|
+
w.postMessage({
|
|
270
|
+
t: "result",
|
|
271
|
+
id: req.id,
|
|
272
|
+
r: { ok: false, error: { tool: req.tool, phase: "execute", message: "bridge call failed" } },
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
w.on("error", (err) => {
|
|
279
|
+
settle(() => reject(err instanceof Error ? err : new Error(String(err))));
|
|
280
|
+
});
|
|
281
|
+
// Wire signal abort → terminate the worker.
|
|
282
|
+
const onAbort = () => {
|
|
283
|
+
settle(() => {
|
|
284
|
+
w.terminate().then(() => reject(new PtcStopSignal("timeout")));
|
|
285
|
+
});
|
|
286
|
+
};
|
|
287
|
+
if (signal.aborted)
|
|
288
|
+
onAbort();
|
|
289
|
+
else
|
|
290
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
291
|
+
// Send the run request.
|
|
292
|
+
w.postMessage({ t: "run", program });
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
// ---------- M2: inline-vm fallback engine (node:vm with timeout) ----------
|
|
297
|
+
/**
|
|
298
|
+
* Inline-vm engine — runs the program inside `node:vm` with a compile
|
|
299
|
+
* timeout for synchronous busy-loops. Same `PtcEngine` seam as
|
|
300
|
+
* `InlineSequentialEngine` (M1) and `WorkerEngine` (M2).
|
|
301
|
+
*
|
|
302
|
+
* KNOWN RESIDUAL RISK (design §3, declared): `vm.compileFunction`'s
|
|
303
|
+
* `timeout` only kills synchronous CPU-bound loops. An `await` yields
|
|
304
|
+
* back to the event loop, so a pure-JS busy-wait between awaits can only
|
|
305
|
+
* be caught by the next bridge call's step-budget pre-check. This is the
|
|
306
|
+
* accepted trade-off for the inline fallback; the primary worker engine
|
|
307
|
+
* does not share this limitation (`worker.terminate()` is wall-clock).
|
|
308
|
+
*/
|
|
309
|
+
export class InlineVmEngine {
|
|
310
|
+
name = "inline";
|
|
311
|
+
async run(program, bridge, signal) {
|
|
312
|
+
const tm = makeFacade(bridge);
|
|
313
|
+
let abortHandler;
|
|
314
|
+
const abortP = new Promise((_, rej) => {
|
|
315
|
+
abortHandler = () => rej(new PtcStopSignal("timeout"));
|
|
316
|
+
if (signal.aborted)
|
|
317
|
+
abortHandler();
|
|
318
|
+
else
|
|
319
|
+
signal.addEventListener("abort", abortHandler, { once: true });
|
|
320
|
+
});
|
|
321
|
+
try {
|
|
322
|
+
// compileFunction's timeout kills synchronous busy-loops; the `await`
|
|
323
|
+
// gap residual is documented (design §3) and accepted for the fallback.
|
|
324
|
+
const fn = vm.compileFunction(`"use strict";\n${program}`, ["tm"], { timeout: 30_000 });
|
|
325
|
+
return await Promise.race([fn(tm), abortP]);
|
|
326
|
+
}
|
|
327
|
+
finally {
|
|
328
|
+
if (abortHandler)
|
|
329
|
+
signal.removeEventListener("abort", abortHandler);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Wrap a raw bridge with the StepGate. Every call: enforce time/call budget
|
|
335
|
+
* (throw a stop that unwinds the program), assign a composite step id
|
|
336
|
+
* `parent.kNN`, retry ≤1 on idempotent phases, record + persist errors, and
|
|
337
|
+
* trip the error budget. The gate lives ONLY here (outside the engine), per
|
|
338
|
+
* design §3 ("决策进代码").
|
|
339
|
+
*/
|
|
340
|
+
export function createGateBridge(raw, parent, budgets, state, opts) {
|
|
341
|
+
const { now, deadlineAt, store } = opts;
|
|
342
|
+
const ptcTag = opts.trajectoryParent ?? parent;
|
|
343
|
+
let seq = 0;
|
|
344
|
+
const traj = (e) => store?.appendTrajectory(e);
|
|
345
|
+
return {
|
|
346
|
+
async call(tool, args) {
|
|
347
|
+
if (state.stopReason)
|
|
348
|
+
throw new PtcStopSignal(state.stopReason);
|
|
349
|
+
// time budget checked BEFORE the call so a run cannot start a call it
|
|
350
|
+
// has no time left for.
|
|
351
|
+
if (now() >= deadlineAt) {
|
|
352
|
+
state.stopReason = "timeout";
|
|
353
|
+
throw new PtcStopSignal("timeout");
|
|
354
|
+
}
|
|
355
|
+
// call budget: only `maxCalls` bridged calls may be dispatched.
|
|
356
|
+
if (state.calls >= budgets.maxCalls) {
|
|
357
|
+
state.stopReason = "call-budget";
|
|
358
|
+
throw new PtcStopSignal("call-budget");
|
|
359
|
+
}
|
|
360
|
+
state.calls++;
|
|
361
|
+
seq++;
|
|
362
|
+
const composite = `${parent}.k${String(seq).padStart(2, "0")}`;
|
|
363
|
+
traj({ tool, step_id: composite, event: "call", ptc: ptcTag });
|
|
364
|
+
const t0 = now();
|
|
365
|
+
let res = await raw.call(tool, args);
|
|
366
|
+
let retried = false;
|
|
367
|
+
if (!res.ok && RETRYABLE_PHASES.includes(res.error.phase)) {
|
|
368
|
+
retried = true;
|
|
369
|
+
state.retries++;
|
|
370
|
+
res = await raw.call(tool, args);
|
|
371
|
+
}
|
|
372
|
+
const ms = now() - t0;
|
|
373
|
+
if (res.ok) {
|
|
374
|
+
const { tokens, dest, ref } = describeOk(res.data);
|
|
375
|
+
state.steps.push({ n: seq, tool, ok: true, ms, tokens, dest, ref });
|
|
376
|
+
traj({
|
|
377
|
+
tool,
|
|
378
|
+
step_id: composite,
|
|
379
|
+
event: "result",
|
|
380
|
+
offloaded: Boolean(ref),
|
|
381
|
+
tokens,
|
|
382
|
+
ptc: ptcTag,
|
|
383
|
+
...(ref ? { ref } : {}),
|
|
384
|
+
});
|
|
385
|
+
return res;
|
|
386
|
+
}
|
|
387
|
+
// error path — full text persists to steps/sXXXX.kNN/ (design §4.1)
|
|
388
|
+
state.errors++;
|
|
389
|
+
const err = res.error;
|
|
390
|
+
let errorRef;
|
|
391
|
+
if (store) {
|
|
392
|
+
try {
|
|
393
|
+
store.writeResult(composite, {
|
|
394
|
+
tool,
|
|
395
|
+
content: JSON.stringify({ error: err }, null, 2),
|
|
396
|
+
tokens: estimateTokens(JSON.stringify(err)),
|
|
397
|
+
contentType: "json",
|
|
398
|
+
preview: shorten(err.message, 120),
|
|
399
|
+
expireAt: Date.now() + 24 * 60 * 60 * 1000,
|
|
400
|
+
});
|
|
401
|
+
errorRef = buildRef(store.runId, composite);
|
|
402
|
+
}
|
|
403
|
+
catch {
|
|
404
|
+
/* error persistence is best-effort; never mask the original error */
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
state.steps.push({
|
|
408
|
+
n: seq,
|
|
409
|
+
tool,
|
|
410
|
+
ok: false,
|
|
411
|
+
ms,
|
|
412
|
+
tokens: 0,
|
|
413
|
+
dest: "err",
|
|
414
|
+
phase: err.phase,
|
|
415
|
+
line: err.line,
|
|
416
|
+
retry: retried,
|
|
417
|
+
message: err.message,
|
|
418
|
+
errorRef,
|
|
419
|
+
});
|
|
420
|
+
traj({
|
|
421
|
+
tool,
|
|
422
|
+
step_id: composite,
|
|
423
|
+
event: "error",
|
|
424
|
+
phase: err.phase,
|
|
425
|
+
...(typeof err.line === "number" ? { line: err.line } : {}),
|
|
426
|
+
retry: retried,
|
|
427
|
+
ptc: ptcTag,
|
|
428
|
+
...(errorRef ? { ref: errorRef } : {}),
|
|
429
|
+
});
|
|
430
|
+
if (state.errors >= budgets.maxErrors) {
|
|
431
|
+
state.stopReason = "error-budget";
|
|
432
|
+
throw new PtcStopSignal("error-budget");
|
|
433
|
+
}
|
|
434
|
+
return res;
|
|
435
|
+
},
|
|
436
|
+
};
|
|
437
|
+
}
|
|
438
|
+
/** Describe an ok bridge result for the success table (inline vs handle). */
|
|
439
|
+
function describeOk(data) {
|
|
440
|
+
if (data && typeof data === "object" && data.offloaded === true) {
|
|
441
|
+
const o = data;
|
|
442
|
+
const ref = typeof o.ref === "string" ? o.ref : null;
|
|
443
|
+
return {
|
|
444
|
+
tokens: typeof o.tokens === "number" ? o.tokens : 0,
|
|
445
|
+
dest: ref ? `ref:${shortRefCode(ref)}` : "ref",
|
|
446
|
+
ref,
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
const text = typeof data === "string" ? data : JSON.stringify(data ?? "");
|
|
450
|
+
return { tokens: estimateTokens(text), dest: "inline", ref: null };
|
|
451
|
+
}
|
|
452
|
+
/** Short display code for a ref: the `steps/<id>` step segment. */
|
|
453
|
+
function shortRefCode(ref) {
|
|
454
|
+
const m = /\/steps\/([^/]+)\/result/.exec(ref);
|
|
455
|
+
return m ? m[1] : shorten(ref, 24);
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Select the PTC engine based on the TM_PTC_ENGINE mode.
|
|
459
|
+
* - "worker": WorkerEngine only (throws on failure → engine-error status).
|
|
460
|
+
* - "inline": InlineVmEngine only (vm timeout for sync busy-loops).
|
|
461
|
+
* - "auto" (default): try WorkerEngine first; on failure → InlineVmEngine
|
|
462
|
+
* with `degraded=true` (marked `degraded-engine` in the summary).
|
|
463
|
+
*
|
|
464
|
+
* Probe result (P1, %TEMP%): ALL-GREEN on Node 24/win32 — auto chain =
|
|
465
|
+
* worker-first, inline fallback. Design §3 table.
|
|
466
|
+
*/
|
|
467
|
+
export function selectEngine(mode, bridge) {
|
|
468
|
+
if (mode === "inline") {
|
|
469
|
+
return { engine: new InlineVmEngine(), degraded: false };
|
|
470
|
+
}
|
|
471
|
+
if (mode === "worker") {
|
|
472
|
+
return { engine: new WorkerEngine(), degraded: false };
|
|
473
|
+
}
|
|
474
|
+
// auto: try worker first, degrade to inline on any failure.
|
|
475
|
+
try {
|
|
476
|
+
// WorkerEngine construction is cheap (no spawn until run()).
|
|
477
|
+
return { engine: new WorkerEngine(), degraded: false };
|
|
478
|
+
}
|
|
479
|
+
catch {
|
|
480
|
+
return { engine: new InlineVmEngine(), degraded: true };
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
export async function runPtc(o) {
|
|
484
|
+
const now = o.now ?? Date.now;
|
|
485
|
+
const start = now();
|
|
486
|
+
const deadlineAt = start + o.budgets.timeoutMs;
|
|
487
|
+
// M2: engine selection — explicit override or auto/worker/inline from config.
|
|
488
|
+
let engine;
|
|
489
|
+
let degraded = false;
|
|
490
|
+
if (o.engine) {
|
|
491
|
+
engine = o.engine;
|
|
492
|
+
}
|
|
493
|
+
else {
|
|
494
|
+
const sel = selectEngine(o.cfg.ptcEngine, o.bridge);
|
|
495
|
+
engine = sel.engine;
|
|
496
|
+
degraded = sel.degraded;
|
|
497
|
+
}
|
|
498
|
+
// M2: static pre-scan — reject programs with banned tokens before any
|
|
499
|
+
// engine runs. Shape: engine-error with the pscan tokens listed.
|
|
500
|
+
// (Design §3: "辅助手段,声明不作安全边界".)
|
|
501
|
+
const pscan = staticPscan(o.program);
|
|
502
|
+
if (pscan.rejected) {
|
|
503
|
+
return {
|
|
504
|
+
label: o.label,
|
|
505
|
+
status: "engine-error",
|
|
506
|
+
steps: [],
|
|
507
|
+
okCount: 0,
|
|
508
|
+
errCount: 0,
|
|
509
|
+
retries: 0,
|
|
510
|
+
calls: 0,
|
|
511
|
+
ms: 0,
|
|
512
|
+
engine: engine.name,
|
|
513
|
+
degraded,
|
|
514
|
+
returnValue: undefined,
|
|
515
|
+
returned: false,
|
|
516
|
+
engineError: {
|
|
517
|
+
tool: "tm_ptc_run",
|
|
518
|
+
phase: "args",
|
|
519
|
+
message: `程序包含禁止标识符(${pscan.tokens.join(", ")}),已拒绝执行。`,
|
|
520
|
+
},
|
|
521
|
+
parentStepId: o.parentStepId,
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
// Auto-degrade: if the selected engine throws (not a PtcStopSignal),
|
|
525
|
+
// and we're in auto mode with no explicit override, retry with InlineVmEngine.
|
|
526
|
+
const tryRun = async (eng) => {
|
|
527
|
+
const state = { calls: 0, errors: 0, retries: 0, steps: [] };
|
|
528
|
+
const gate = createGateBridge(o.bridge, o.parentStepId, o.budgets, state, {
|
|
529
|
+
now,
|
|
530
|
+
deadlineAt,
|
|
531
|
+
store: o.store,
|
|
532
|
+
});
|
|
533
|
+
// parent call event (design §6)
|
|
534
|
+
o.store?.appendTrajectory({
|
|
535
|
+
tool: "tm_ptc_run",
|
|
536
|
+
step_id: o.parentStepId,
|
|
537
|
+
event: "call",
|
|
538
|
+
label: o.label,
|
|
539
|
+
program_sha256: crypto.createHash("sha256").update(o.program).digest("hex"),
|
|
540
|
+
budgets: o.budgets,
|
|
541
|
+
});
|
|
542
|
+
const ac = new AbortController();
|
|
543
|
+
const remaining = Math.max(0, deadlineAt - now());
|
|
544
|
+
const timer = setTimeout(() => ac.abort(), remaining);
|
|
545
|
+
let status;
|
|
546
|
+
let returnValue;
|
|
547
|
+
let returned = false;
|
|
548
|
+
let engineError;
|
|
549
|
+
try {
|
|
550
|
+
returnValue = await eng.run(o.program, gate, ac.signal);
|
|
551
|
+
returned = true;
|
|
552
|
+
status = state.stopReason ? mapStop(state.stopReason) : "ok";
|
|
553
|
+
}
|
|
554
|
+
catch (err) {
|
|
555
|
+
if (err instanceof PtcStopSignal) {
|
|
556
|
+
status = mapStop(err.reason);
|
|
557
|
+
}
|
|
558
|
+
else {
|
|
559
|
+
status = "engine-error";
|
|
560
|
+
const line = extractLine(err);
|
|
561
|
+
engineError = {
|
|
562
|
+
tool: "tm_ptc_run",
|
|
563
|
+
phase: "execute",
|
|
564
|
+
message: err instanceof Error ? err.message : String(err ?? "engine error"),
|
|
565
|
+
...(line != null ? { line } : {}),
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
finally {
|
|
570
|
+
clearTimeout(timer);
|
|
571
|
+
}
|
|
572
|
+
const ms = now() - start;
|
|
573
|
+
const outcome = {
|
|
574
|
+
label: o.label,
|
|
575
|
+
status,
|
|
576
|
+
steps: state.steps,
|
|
577
|
+
okCount: state.steps.filter((s) => s.ok).length,
|
|
578
|
+
errCount: state.steps.filter((s) => !s.ok).length,
|
|
579
|
+
retries: state.retries,
|
|
580
|
+
calls: state.calls,
|
|
581
|
+
ms,
|
|
582
|
+
engine: eng.name,
|
|
583
|
+
degraded,
|
|
584
|
+
returnValue,
|
|
585
|
+
returned,
|
|
586
|
+
...(engineError ? { engineError } : {}),
|
|
587
|
+
parentStepId: o.parentStepId,
|
|
588
|
+
};
|
|
589
|
+
o.store?.appendTrajectory({
|
|
590
|
+
tool: "tm_ptc_run",
|
|
591
|
+
step_id: o.parentStepId,
|
|
592
|
+
event: "finish",
|
|
593
|
+
status: outcome.status,
|
|
594
|
+
calls: outcome.calls,
|
|
595
|
+
errors: outcome.errCount,
|
|
596
|
+
retries: outcome.retries,
|
|
597
|
+
ms: outcome.ms,
|
|
598
|
+
});
|
|
599
|
+
return outcome;
|
|
600
|
+
};
|
|
601
|
+
// Auto mode: try worker first; on engine-error → degrade to inline.
|
|
602
|
+
if (!o.engine && o.cfg.ptcEngine === "auto" && engine.name === "worker") {
|
|
603
|
+
const result = await tryRun(engine);
|
|
604
|
+
if (result.status === "engine-error") {
|
|
605
|
+
// Degrade to inline-vm and re-run.
|
|
606
|
+
const inlineEngine = new InlineVmEngine();
|
|
607
|
+
const fallback = await tryRun(inlineEngine);
|
|
608
|
+
fallback.degraded = true;
|
|
609
|
+
fallback.engine = "inline";
|
|
610
|
+
return fallback;
|
|
611
|
+
}
|
|
612
|
+
return result;
|
|
613
|
+
}
|
|
614
|
+
return tryRun(engine);
|
|
615
|
+
}
|
|
616
|
+
function mapStop(reason) {
|
|
617
|
+
if (reason === "timeout")
|
|
618
|
+
return "timeout";
|
|
619
|
+
if (reason === "error-budget")
|
|
620
|
+
return "stopped-error-budget";
|
|
621
|
+
return "stopped-call-budget";
|
|
622
|
+
}
|
|
623
|
+
// ---------- aggregation summary (design §2 — char-pinned headers) ----------
|
|
624
|
+
export const PTC_SUMMARY_HEADER = "PTC 摘要";
|
|
625
|
+
export const PTC_OK_SECTION = "-- 成功分部(≤8 行,超出整表卸载)";
|
|
626
|
+
export const PTC_OK_HEADER = " # tool ms tokens 落点(inline|ref 短码)";
|
|
627
|
+
export const PTC_ERR_SECTION = "-- 错误分部(全量错误已落 run store)";
|
|
628
|
+
export const PTC_ERR_HEADER = " # tool phase line retry message(截断)";
|
|
629
|
+
export const PTC_RETURN_PREFIX = "返回值: ";
|
|
630
|
+
export const PTC_ERRORFULL_PREFIX = "错误全文: ";
|
|
631
|
+
const OK_ROWS_INLINE_MAX = 8;
|
|
632
|
+
const RETURN_VALUE_MAX = 2000;
|
|
633
|
+
function engineLabel(o) {
|
|
634
|
+
if (o.engine === "worker")
|
|
635
|
+
return "worker";
|
|
636
|
+
return o.degraded ? "inline(degraded)" : "inline";
|
|
637
|
+
}
|
|
638
|
+
/** Render the fixed-shape aggregation summary. `offload` is used to route an
|
|
639
|
+
* oversized success/error table (or return value) to a run-store handle. */
|
|
640
|
+
export function renderPtcSummary(o, offload) {
|
|
641
|
+
const lines = [];
|
|
642
|
+
lines.push(`${PTC_SUMMARY_HEADER} · ${o.label} · status=${o.status}`);
|
|
643
|
+
lines.push(`steps=${o.okCount + o.errCount} ok=${o.okCount} err=${o.errCount} retries=${o.retries} ms=${o.ms} engine=${engineLabel(o)}`);
|
|
644
|
+
const okSteps = o.steps.filter((s) => s.ok);
|
|
645
|
+
const errSteps = o.steps.filter((s) => !s.ok);
|
|
646
|
+
lines.push(PTC_OK_SECTION);
|
|
647
|
+
lines.push(PTC_OK_HEADER);
|
|
648
|
+
if (okSteps.length > OK_ROWS_INLINE_MAX && offload) {
|
|
649
|
+
const table = okSteps.map(okRow).join("\n");
|
|
650
|
+
lines.push(`(成功 ${okSteps.length} 行,超 ${OK_ROWS_INLINE_MAX},整表卸载)`);
|
|
651
|
+
lines.push(offload(table, "ok"));
|
|
652
|
+
}
|
|
653
|
+
else {
|
|
654
|
+
for (const s of okSteps)
|
|
655
|
+
lines.push(okRow(s));
|
|
656
|
+
}
|
|
657
|
+
lines.push(PTC_ERR_SECTION);
|
|
658
|
+
lines.push(PTC_ERR_HEADER);
|
|
659
|
+
for (const s of errSteps)
|
|
660
|
+
lines.push(errRow(s));
|
|
661
|
+
if (o.engineError) {
|
|
662
|
+
lines.push(errRow({
|
|
663
|
+
n: 0,
|
|
664
|
+
tool: "tm_ptc_run",
|
|
665
|
+
phase: o.engineError.phase,
|
|
666
|
+
line: o.engineError.line,
|
|
667
|
+
retry: false,
|
|
668
|
+
message: `程序抛出:${o.engineError.message}`,
|
|
669
|
+
}));
|
|
670
|
+
}
|
|
671
|
+
if (errSteps.length === 0 && !o.engineError)
|
|
672
|
+
lines.push(" (无)");
|
|
673
|
+
// return value (JSON-serialized, capped; oversized → offload handle)
|
|
674
|
+
if (o.returned) {
|
|
675
|
+
const json = safeStringify(o.returnValue);
|
|
676
|
+
if (json.length > RETURN_VALUE_MAX && offload) {
|
|
677
|
+
lines.push(PTC_RETURN_PREFIX + "(超 2000 字符,卸载为句柄)");
|
|
678
|
+
lines.push(offload(json, "return"));
|
|
679
|
+
}
|
|
680
|
+
else {
|
|
681
|
+
lines.push(PTC_RETURN_PREFIX + json);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
else {
|
|
685
|
+
lines.push(PTC_RETURN_PREFIX + "(无:程序未正常 return)");
|
|
686
|
+
}
|
|
687
|
+
// error full-text refs (aggregate handle when many)
|
|
688
|
+
const refs = o.steps.filter((s) => s.errorRef).map((s) => s.errorRef);
|
|
689
|
+
if (refs.length === 0) {
|
|
690
|
+
lines.push(PTC_ERRORFULL_PREFIX + "(无错误落盘)");
|
|
691
|
+
}
|
|
692
|
+
else if (refs.length > 8 && offload) {
|
|
693
|
+
lines.push(PTC_ERRORFULL_PREFIX + offload(refs.join("\n"), "errrefs"));
|
|
694
|
+
}
|
|
695
|
+
else {
|
|
696
|
+
lines.push(PTC_ERRORFULL_PREFIX + refs.map((r) => `tm://…/${shortRefCode(r)}`).join(" "));
|
|
697
|
+
}
|
|
698
|
+
return lines.join("\n");
|
|
699
|
+
}
|
|
700
|
+
function okRow(s) {
|
|
701
|
+
return ` ${s.n} ${pad(s.tool, 8)}${String(s.ms)}ms ${s.tokens} ${s.dest}`;
|
|
702
|
+
}
|
|
703
|
+
function errRow(s) {
|
|
704
|
+
const phase = s.phase ?? "-";
|
|
705
|
+
const line = typeof s.line === "number" ? String(s.line) : "-";
|
|
706
|
+
const retry = s.retry ? "yes" : "no";
|
|
707
|
+
const msg = shorten(s.message ?? "", 60);
|
|
708
|
+
return ` ${s.n} ${pad(s.tool, 8)}${pad(phase, 11)}${pad(line, 5)}${pad(retry, 5)}${msg}`;
|
|
709
|
+
}
|
|
710
|
+
function pad(v, w) {
|
|
711
|
+
const s = String(v);
|
|
712
|
+
return s.length >= w ? s + " " : s + " ".repeat(w - s.length);
|
|
713
|
+
}
|
|
714
|
+
function safeStringify(v) {
|
|
715
|
+
try {
|
|
716
|
+
const s = JSON.stringify(v);
|
|
717
|
+
return s === undefined ? "null" : s;
|
|
718
|
+
}
|
|
719
|
+
catch {
|
|
720
|
+
return String(v);
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
// ---------- bridge over the real governed pipelines ------------------------
|
|
724
|
+
/**
|
|
725
|
+
* Real M1 bridge: delegate each call to the corresponding exported pipeline,
|
|
726
|
+
* `ctx` passed through untouched, and normalize the pipeline's `unknown`
|
|
727
|
+
* result into `PtcCallResult` (TmErrorBody -> ok:false; anything else -> the
|
|
728
|
+
* already-governed data). Governance is entirely the pipelines'.
|
|
729
|
+
*/
|
|
730
|
+
export function pipelineBridge(pipelines, ctx) {
|
|
731
|
+
const pick = (tool) => tool === "tm_read"
|
|
732
|
+
? pipelines.tmRead
|
|
733
|
+
: tool === "tm_grep"
|
|
734
|
+
? pipelines.tmGrep
|
|
735
|
+
: tool === "tm_bash"
|
|
736
|
+
? pipelines.tmBash
|
|
737
|
+
: pipelines.tmFetch;
|
|
738
|
+
return {
|
|
739
|
+
async call(tool, args) {
|
|
740
|
+
if (!BRIDGE_ALLOW.includes(tool)) {
|
|
741
|
+
return { ok: false, error: tmError(tool, "args", "工具不在桥接白名单内").error };
|
|
742
|
+
}
|
|
743
|
+
const res = await pick(tool)(args ?? {}, ctx);
|
|
744
|
+
if (res && typeof res === "object" && "error" in res) {
|
|
745
|
+
return { ok: false, error: res.error };
|
|
746
|
+
}
|
|
747
|
+
return { ok: true, data: res };
|
|
748
|
+
},
|
|
749
|
+
};
|
|
750
|
+
}
|
|
751
|
+
// ---------- the tool definition (BUILT here, REGISTERED in M3) -------------
|
|
752
|
+
const PTC_RUN_DESCRIPTION = `Program-mode batch orchestration over the four governed tm_* tools. One program, N bridged calls, zero LLM round-trips during the run; only an aggregation summary returns to context.
|
|
753
|
+
|
|
754
|
+
- program: an async function body. Available: \`tm.read(args)\`, \`tm.grep(args)\`, \`tm.bash(args)\`, \`tm.fetch(args)\` — same args as the tm_* four. Each returns \`{ok:true, data}\` (data is already governed: inline text, or an offload handle you can tm.fetch again) or \`{ok:false, error:{tool,phase,line?,message}}\`. \`return\` a value; it is JSON-serialized into the summary (capped 2000 chars, oversized → handle).
|
|
755
|
+
- budgets (optional, tighten-only; clamped to TM_PTC_* ceilings): max_calls, max_errors, timeout_ms. Hitting any budget stops the whole run (produced output is NOT lost). Errors are retried at most once and only on idempotent phases (client/execute/store).
|
|
756
|
+
- Governance is NOT bypassed: every bridged call runs the full tm_* pipeline (P2 path scope, P3 allowlist, R6, threshold offload + handles, TTL). Status is one of ok | stopped-error-budget | stopped-call-budget | timeout | engine-error.
|
|
757
|
+
- Programs containing require/import/process/globalThis/Deno/Bun/fs/net/child_process are rejected before execution (static pre-scan, auxiliary guard).
|
|
758
|
+
- Engine: TM_PTC_ENGINE=auto|worker|inline (auto tries worker first, falls back to inline with degraded-engine mark).`;
|
|
759
|
+
/** Build the tm_ptc_run ToolDefinition. Registered in the tool segment
|
|
760
|
+
* when the agent's whitelist grants tm_ptc_run (M3). */
|
|
761
|
+
export function buildPtcRunTool(deps) {
|
|
762
|
+
const { cfg, store, nextStepId, ctx, accessToken } = deps;
|
|
763
|
+
const baseBridge = deps.bridge ?? (deps.pipelines ? pipelineBridge(deps.pipelines, ctx) : undefined);
|
|
764
|
+
const expireAt = () => Date.now() + cfg.blackboardTtlDays * 24 * 60 * 60 * 1000;
|
|
765
|
+
return {
|
|
766
|
+
description: PTC_RUN_DESCRIPTION,
|
|
767
|
+
args: {
|
|
768
|
+
program: { descriptor: "program: string (required, async fn body, ≤TM_PTC_MAX_PROGRAM_CHARS)" },
|
|
769
|
+
label: { descriptor: "label: string (optional, ≤80 chars)" },
|
|
770
|
+
budgets: { descriptor: "budgets: { max_calls?, max_errors?, timeout_ms? } (optional, tighten-only)" },
|
|
771
|
+
},
|
|
772
|
+
execute: async (rawArgs) => {
|
|
773
|
+
const parsed = parsePtcArgs(rawArgs ?? {}, cfg);
|
|
774
|
+
if (!parsed.ok) {
|
|
775
|
+
return { output: `[${parsed.error.error.tool} 失败 · phase=${parsed.error.error.phase}]\n${parsed.error.error.message}` };
|
|
776
|
+
}
|
|
777
|
+
// M2: static pre-scan — reject programs with banned tokens before any engine runs.
|
|
778
|
+
const pscan = staticPscan(parsed.args.program);
|
|
779
|
+
if (pscan.rejected) {
|
|
780
|
+
return {
|
|
781
|
+
output: `[tm_ptc_run 失败 · phase=args]\n程序包含禁止标识符(${pscan.tokens.join(", ")}),已拒绝执行。PTC 桥接仅暴露 tm.read/tm.grep/tm.bash/tm.fetch;require/import/process 等不在桥接白名单内。`,
|
|
782
|
+
};
|
|
783
|
+
}
|
|
784
|
+
if (!baseBridge) {
|
|
785
|
+
return {
|
|
786
|
+
output: "[tm_ptc_run 失败 · phase=client]\n桥接管线未提供。",
|
|
787
|
+
};
|
|
788
|
+
}
|
|
789
|
+
// Generate a fresh parent step ID per call.
|
|
790
|
+
const parentStepId = nextStepId();
|
|
791
|
+
// Per-call offload helper: persist `text` under a PTC sub-step and
|
|
792
|
+
// render a handle block matching the four tools' visible shape.
|
|
793
|
+
const offloadBlock = (text, kind) => {
|
|
794
|
+
const tokens = estimateTokens(text);
|
|
795
|
+
try {
|
|
796
|
+
const stored = store.writeResult(`${parentStepId}.${kind}`, {
|
|
797
|
+
tool: "tm_ptc_run",
|
|
798
|
+
content: text,
|
|
799
|
+
tokens,
|
|
800
|
+
contentType: detectContentType(text),
|
|
801
|
+
preview: shorten(text, 120),
|
|
802
|
+
expireAt: expireAt(),
|
|
803
|
+
});
|
|
804
|
+
return [
|
|
805
|
+
`ref: ${stored.ref}`,
|
|
806
|
+
`access_token: ${accessToken}`,
|
|
807
|
+
`expire_at: ${stored.expireAt}`,
|
|
808
|
+
`tokens: ${tokens}`,
|
|
809
|
+
`(用 tm_fetch(ref, access_token) 取回;大载荷先试 mode:"structure")`,
|
|
810
|
+
].join("\n");
|
|
811
|
+
}
|
|
812
|
+
catch {
|
|
813
|
+
return text.slice(0, 2000);
|
|
814
|
+
}
|
|
815
|
+
};
|
|
816
|
+
const outcome = await runPtc({
|
|
817
|
+
program: parsed.args.program,
|
|
818
|
+
label: parsed.args.label,
|
|
819
|
+
budgets: parsed.args.budgets,
|
|
820
|
+
parentStepId,
|
|
821
|
+
cfg,
|
|
822
|
+
store,
|
|
823
|
+
bridge: baseBridge,
|
|
824
|
+
...(deps.engine ? { engine: deps.engine } : {}),
|
|
825
|
+
});
|
|
826
|
+
const content = renderPtcSummary(outcome, offloadBlock);
|
|
827
|
+
// whole-summary offload if it still exceeds the threshold.
|
|
828
|
+
if (shouldOffload(estimateTokens(content), cfg.offloadThreshold)) {
|
|
829
|
+
return {
|
|
830
|
+
output: `PTC 摘要过大(≈${estimateTokens(content)} tokens),已整体卸载为句柄,短摘要随后:\n` +
|
|
831
|
+
offloadBlock(content, "rpt") +
|
|
832
|
+
`\n--- 摘要前 1200 字符 ---\n${content.slice(0, 1200)}`,
|
|
833
|
+
};
|
|
834
|
+
}
|
|
835
|
+
return { output: content };
|
|
836
|
+
},
|
|
837
|
+
};
|
|
838
|
+
}
|
|
839
|
+
//# sourceMappingURL=ptc.js.map
|