@holoscript/holoscript-agent 2.0.0
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/LICENSE +21 -0
- package/dist/ablation.d.ts +56 -0
- package/dist/ablation.js +183 -0
- package/dist/ablation.js.map +1 -0
- package/dist/audit-log.d.ts +99 -0
- package/dist/audit-log.js +123 -0
- package/dist/audit-log.js.map +1 -0
- package/dist/brain.d.ts +6 -0
- package/dist/brain.js +66 -0
- package/dist/brain.js.map +1 -0
- package/dist/commit-hook.d.ts +22 -0
- package/dist/commit-hook.js +103 -0
- package/dist/commit-hook.js.map +1 -0
- package/dist/cost-guard.d.ts +54 -0
- package/dist/cost-guard.js +92 -0
- package/dist/cost-guard.js.map +1 -0
- package/dist/holomesh-client.d.ts +63 -0
- package/dist/holomesh-client.js +117 -0
- package/dist/holomesh-client.js.map +1 -0
- package/dist/identity.d.ts +7 -0
- package/dist/identity.js +64 -0
- package/dist/identity.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2101 -0
- package/dist/index.js.map +1 -0
- package/dist/provision.d.ts +43 -0
- package/dist/provision.js +195 -0
- package/dist/provision.js.map +1 -0
- package/dist/runner.d.ts +62 -0
- package/dist/runner.js +543 -0
- package/dist/runner.js.map +1 -0
- package/dist/supervisor-config.d.ts +26 -0
- package/dist/supervisor-config.js +109 -0
- package/dist/supervisor-config.js.map +1 -0
- package/dist/supervisor.d.ts +53 -0
- package/dist/supervisor.js +1167 -0
- package/dist/supervisor.js.map +1 -0
- package/dist/types.d.ts +57 -0
- package/dist/types.js +1 -0
- package/dist/types.js.map +1 -0
- package/package.json +99 -0
package/dist/runner.js
ADDED
|
@@ -0,0 +1,543 @@
|
|
|
1
|
+
// src/holomesh-client.ts
|
|
2
|
+
function pickClaimableTask(tasks, brainCapabilityTags) {
|
|
3
|
+
const wanted = new Set(brainCapabilityTags.map((t) => t.toLowerCase()));
|
|
4
|
+
const open = tasks.filter((t) => t.status === "open" && !t.claimedBy);
|
|
5
|
+
const scored = open.map((t) => ({ task: t, score: scoreTask(t, wanted) })).filter((s) => s.score > 0).sort((a, b) => b.score - a.score || priority(a.task) - priority(b.task));
|
|
6
|
+
return scored[0]?.task;
|
|
7
|
+
}
|
|
8
|
+
function scoreTask(task, wanted) {
|
|
9
|
+
const tags = (task.tags ?? []).map((t) => t.toLowerCase());
|
|
10
|
+
const text = `${task.title} ${task.description ?? ""}`.toLowerCase();
|
|
11
|
+
let score = 0;
|
|
12
|
+
for (const tag of tags) if (wanted.has(tag)) score += 2;
|
|
13
|
+
for (const w of wanted) if (text.includes(w)) score += 1;
|
|
14
|
+
return score;
|
|
15
|
+
}
|
|
16
|
+
function priority(t) {
|
|
17
|
+
if (typeof t.priority === "number") return t.priority;
|
|
18
|
+
const map = { critical: 1, high: 2, medium: 4, low: 6 };
|
|
19
|
+
return map[String(t.priority).toLowerCase()] ?? 5;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// src/cael-builder.ts
|
|
23
|
+
import { createHash } from "crypto";
|
|
24
|
+
function sha(input) {
|
|
25
|
+
return createHash("sha256").update(input, "utf8").digest("hex");
|
|
26
|
+
}
|
|
27
|
+
function brainClassOf(brain) {
|
|
28
|
+
const p = String(brain.brainPath ?? "");
|
|
29
|
+
let m = p.match(/compositions[\\/]([\w-]+)-brain\.hsplus$/);
|
|
30
|
+
if (m) return m[1];
|
|
31
|
+
m = p.match(/([\w-]+)-brain\.hsplus$/);
|
|
32
|
+
if (m) return m[1];
|
|
33
|
+
m = p.match(/([\w-]+)\.hsplus$/);
|
|
34
|
+
if (m) return m[1];
|
|
35
|
+
const domain = String(brain.domain ?? "").trim();
|
|
36
|
+
if (domain && domain !== "unknown") return domain;
|
|
37
|
+
return "unknown";
|
|
38
|
+
}
|
|
39
|
+
function buildCaelRecord(input) {
|
|
40
|
+
const { identity, brain, task, messages, finalText, usage, costUsd, spentUsd, prevChain, runtimeVersion } = input;
|
|
41
|
+
const l0 = sha(brain.systemPrompt);
|
|
42
|
+
const l1 = sha(`${task.id}|${task.title}|${task.description ?? ""}`);
|
|
43
|
+
const l2 = sha(JSON.stringify(messages));
|
|
44
|
+
const l3 = sha(finalText);
|
|
45
|
+
const l4 = sha(JSON.stringify(usage));
|
|
46
|
+
const l5 = sha(`${costUsd.toFixed(6)}|${spentUsd.toFixed(6)}`);
|
|
47
|
+
const l6 = sha([l0, l1, l2, l3, l4, l5].join("|"));
|
|
48
|
+
const fnv1a_chain = sha(`${prevChain ?? ""}|${l6}`);
|
|
49
|
+
return {
|
|
50
|
+
tick_iso: (/* @__PURE__ */ new Date()).toISOString(),
|
|
51
|
+
layer_hashes: [l0, l1, l2, l3, l4, l5, l6],
|
|
52
|
+
operation: `task-executed:${task.id}`,
|
|
53
|
+
prev_hash: prevChain,
|
|
54
|
+
fnv1a_chain,
|
|
55
|
+
version_vector_fingerprint: `agent@${runtimeVersion}|brain@${brainClassOf(brain)}|provider@${identity.llmProvider}|model@${identity.llmModel}`,
|
|
56
|
+
brain_class: brainClassOf(brain)
|
|
57
|
+
};
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// src/tools.ts
|
|
61
|
+
import { readFile, writeFile, readdir, mkdir, stat } from "fs/promises";
|
|
62
|
+
import { resolve, dirname } from "path";
|
|
63
|
+
import { spawn } from "child_process";
|
|
64
|
+
var ALLOWED_READ_ROOTS = [
|
|
65
|
+
"/root/msc-paper-22",
|
|
66
|
+
// Paper 22 mechanization inputs (scp'd by deploy)
|
|
67
|
+
"/root/holoscript-mesh",
|
|
68
|
+
// Read-only repo view (clone path on instance)
|
|
69
|
+
"/root/agent-output"
|
|
70
|
+
// Read back what we wrote
|
|
71
|
+
];
|
|
72
|
+
var ALLOWED_WRITE_ROOTS = [
|
|
73
|
+
"/root/agent-output"
|
|
74
|
+
// Single write sink — keeps deliverables in one place
|
|
75
|
+
];
|
|
76
|
+
var BASH_WHITELIST = [
|
|
77
|
+
"lake build",
|
|
78
|
+
"lake env",
|
|
79
|
+
"lake clean",
|
|
80
|
+
"lean ",
|
|
81
|
+
"ls ",
|
|
82
|
+
"ls\n",
|
|
83
|
+
"ls$",
|
|
84
|
+
"cat ",
|
|
85
|
+
"grep ",
|
|
86
|
+
"rg ",
|
|
87
|
+
"find ",
|
|
88
|
+
"wc ",
|
|
89
|
+
"head ",
|
|
90
|
+
"tail ",
|
|
91
|
+
"git status",
|
|
92
|
+
"git log",
|
|
93
|
+
"git diff",
|
|
94
|
+
"git show",
|
|
95
|
+
"pnpm --filter",
|
|
96
|
+
"pnpm vitest",
|
|
97
|
+
"vitest run",
|
|
98
|
+
"pwd",
|
|
99
|
+
"echo "
|
|
100
|
+
];
|
|
101
|
+
var MESH_TOOLS = [
|
|
102
|
+
{
|
|
103
|
+
name: "read_file",
|
|
104
|
+
description: "Read a file from the agent sandbox. Allowed roots: /root/msc-paper-22, /root/holoscript-mesh, /root/agent-output. Returns the file content as text. Use this to inspect inputs scp'd to the instance (e.g. MSC/Invariants.lean).",
|
|
105
|
+
input_schema: {
|
|
106
|
+
type: "object",
|
|
107
|
+
properties: {
|
|
108
|
+
path: { type: "string", description: "Absolute path under an allowed read root" }
|
|
109
|
+
},
|
|
110
|
+
required: ["path"]
|
|
111
|
+
}
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
name: "list_dir",
|
|
115
|
+
description: "List entries in a directory under the agent sandbox. Same root restrictions as read_file. Returns a newline-separated list of entries.",
|
|
116
|
+
input_schema: {
|
|
117
|
+
type: "object",
|
|
118
|
+
properties: {
|
|
119
|
+
path: { type: "string", description: "Absolute path under an allowed read root" }
|
|
120
|
+
},
|
|
121
|
+
required: ["path"]
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
{
|
|
125
|
+
name: "write_file",
|
|
126
|
+
description: "Write a file to /root/agent-output/. This is the deliverable sink \u2014 anything you want to emit as task output (a Lean proof, a markdown report, a JSON dataset) goes here. Creates parent directories. Will refuse paths outside the write root.",
|
|
127
|
+
input_schema: {
|
|
128
|
+
type: "object",
|
|
129
|
+
properties: {
|
|
130
|
+
path: { type: "string", description: "Absolute path under /root/agent-output/" },
|
|
131
|
+
content: { type: "string", description: "File content to write (UTF-8)" }
|
|
132
|
+
},
|
|
133
|
+
required: ["path", "content"]
|
|
134
|
+
}
|
|
135
|
+
},
|
|
136
|
+
{
|
|
137
|
+
name: "bash",
|
|
138
|
+
description: "Run a shell command. Whitelisted prefixes only: lake build, lean, ls, cat, grep, find, wc, head, tail, git status/log/diff/show, pnpm --filter, vitest run, pwd, echo. Hard 60s wall timeout, 1MB stdout cap. Use for lake build / lean kernel-checks, git inspection, repo greps. Refuses rm, curl, ssh, sudo, eval.",
|
|
139
|
+
input_schema: {
|
|
140
|
+
type: "object",
|
|
141
|
+
properties: {
|
|
142
|
+
cmd: { type: "string", description: "Whitelisted shell command" },
|
|
143
|
+
cwd: { type: "string", description: "Optional working directory (defaults to /root)" }
|
|
144
|
+
},
|
|
145
|
+
required: ["cmd"]
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
];
|
|
149
|
+
function isUnderRoot(absPath, root) {
|
|
150
|
+
const resolved = resolve(absPath);
|
|
151
|
+
const rootResolved = resolve(root);
|
|
152
|
+
return resolved === rootResolved || resolved.startsWith(rootResolved + "/");
|
|
153
|
+
}
|
|
154
|
+
function checkReadAllowed(path) {
|
|
155
|
+
if (!path.startsWith("/")) return `path must be absolute, got "${path}"`;
|
|
156
|
+
for (const root of ALLOWED_READ_ROOTS) {
|
|
157
|
+
if (isUnderRoot(path, root)) return null;
|
|
158
|
+
}
|
|
159
|
+
return `read denied \u2014 path "${path}" not under allowed roots: ${ALLOWED_READ_ROOTS.join(", ")}`;
|
|
160
|
+
}
|
|
161
|
+
function checkWriteAllowed(path) {
|
|
162
|
+
if (!path.startsWith("/")) return `path must be absolute, got "${path}"`;
|
|
163
|
+
for (const root of ALLOWED_WRITE_ROOTS) {
|
|
164
|
+
if (isUnderRoot(path, root)) return null;
|
|
165
|
+
}
|
|
166
|
+
return `write denied \u2014 path "${path}" not under allowed roots: ${ALLOWED_WRITE_ROOTS.join(", ")}`;
|
|
167
|
+
}
|
|
168
|
+
function checkBashAllowed(cmd) {
|
|
169
|
+
const trimmed = cmd.trim();
|
|
170
|
+
if (trimmed.length === 0) return "empty command";
|
|
171
|
+
if (/[;&|`$<>]|>>|\|\||&&/.test(trimmed)) {
|
|
172
|
+
return `command contains shell metachars (; & | \` $ < > >> || &&) \u2014 not allowed for safety`;
|
|
173
|
+
}
|
|
174
|
+
for (const prefix of BASH_WHITELIST) {
|
|
175
|
+
if (trimmed.startsWith(prefix.trim())) return null;
|
|
176
|
+
}
|
|
177
|
+
return `command not on whitelist. Allowed prefixes: ${BASH_WHITELIST.join(" / ")}`;
|
|
178
|
+
}
|
|
179
|
+
async function runTool(use) {
|
|
180
|
+
try {
|
|
181
|
+
if (use.name === "read_file") {
|
|
182
|
+
const path = use.input.path;
|
|
183
|
+
const denied = checkReadAllowed(path);
|
|
184
|
+
if (denied) return errResult(use.id, denied);
|
|
185
|
+
const text = await readFile(path, "utf8");
|
|
186
|
+
const truncated = text.length > 2e5 ? text.slice(0, 2e5) + `
|
|
187
|
+
\u2026[truncated, full file is ${text.length} bytes]` : text;
|
|
188
|
+
return okResult(use.id, truncated);
|
|
189
|
+
}
|
|
190
|
+
if (use.name === "list_dir") {
|
|
191
|
+
const path = use.input.path;
|
|
192
|
+
const denied = checkReadAllowed(path);
|
|
193
|
+
if (denied) return errResult(use.id, denied);
|
|
194
|
+
const entries = await readdir(path, { withFileTypes: true });
|
|
195
|
+
const lines = entries.map((e) => `${e.isDirectory() ? "d" : "-"} ${e.name}`);
|
|
196
|
+
return okResult(use.id, lines.join("\n"));
|
|
197
|
+
}
|
|
198
|
+
if (use.name === "write_file") {
|
|
199
|
+
const path = use.input.path;
|
|
200
|
+
const content = use.input.content;
|
|
201
|
+
const denied = checkWriteAllowed(path);
|
|
202
|
+
if (denied) return errResult(use.id, denied);
|
|
203
|
+
await mkdir(dirname(path), { recursive: true });
|
|
204
|
+
await writeFile(path, content, "utf8");
|
|
205
|
+
const s = await stat(path);
|
|
206
|
+
return okResult(use.id, `wrote ${s.size} bytes to ${path}`);
|
|
207
|
+
}
|
|
208
|
+
if (use.name === "bash") {
|
|
209
|
+
const cmd = use.input.cmd;
|
|
210
|
+
const cwd = use.input.cwd ?? "/root";
|
|
211
|
+
const denied = checkBashAllowed(cmd);
|
|
212
|
+
if (denied) return errResult(use.id, denied);
|
|
213
|
+
const result = await runBash(cmd, cwd);
|
|
214
|
+
return result.code === 0 ? okResult(use.id, result.stdout) : errResult(use.id, `exit=${result.code}
|
|
215
|
+
${result.stderr || result.stdout}`);
|
|
216
|
+
}
|
|
217
|
+
return errResult(use.id, `unknown tool: ${use.name}`);
|
|
218
|
+
} catch (err) {
|
|
219
|
+
return errResult(use.id, err instanceof Error ? err.message : String(err));
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
function runBash(cmd, cwd) {
|
|
223
|
+
return new Promise((resolveProm) => {
|
|
224
|
+
const child = spawn("bash", ["-c", cmd], { cwd, env: process.env });
|
|
225
|
+
let stdout = "";
|
|
226
|
+
let stderr = "";
|
|
227
|
+
let killed = false;
|
|
228
|
+
const STDOUT_CAP = 1e6;
|
|
229
|
+
const TIMEOUT_MS = 6e4;
|
|
230
|
+
const killer = setTimeout(() => {
|
|
231
|
+
killed = true;
|
|
232
|
+
child.kill("SIGKILL");
|
|
233
|
+
}, TIMEOUT_MS);
|
|
234
|
+
child.stdout.on("data", (d) => {
|
|
235
|
+
if (stdout.length < STDOUT_CAP) stdout += d.toString("utf8");
|
|
236
|
+
});
|
|
237
|
+
child.stderr.on("data", (d) => {
|
|
238
|
+
if (stderr.length < STDOUT_CAP) stderr += d.toString("utf8");
|
|
239
|
+
});
|
|
240
|
+
child.on("error", (err) => {
|
|
241
|
+
clearTimeout(killer);
|
|
242
|
+
resolveProm({ code: 1, stdout, stderr: stderr + "\nspawn-error: " + err.message });
|
|
243
|
+
});
|
|
244
|
+
child.on("exit", (code) => {
|
|
245
|
+
clearTimeout(killer);
|
|
246
|
+
const finalStdout = stdout.length >= STDOUT_CAP ? stdout + `
|
|
247
|
+
\u2026[stdout truncated at ${STDOUT_CAP} bytes]` : stdout;
|
|
248
|
+
const note = killed ? `
|
|
249
|
+
[bash killed after ${TIMEOUT_MS}ms timeout]` : "";
|
|
250
|
+
resolveProm({ code: code ?? 1, stdout: finalStdout + note, stderr });
|
|
251
|
+
});
|
|
252
|
+
});
|
|
253
|
+
}
|
|
254
|
+
function okResult(id, content) {
|
|
255
|
+
return { type: "tool_result", tool_use_id: id, content };
|
|
256
|
+
}
|
|
257
|
+
function errResult(id, message) {
|
|
258
|
+
return { type: "tool_result", tool_use_id: id, content: message, is_error: true };
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// src/runner.ts
|
|
262
|
+
var RUNTIME_VERSION = "1.0.0";
|
|
263
|
+
var AgentRunner = class {
|
|
264
|
+
constructor(opts) {
|
|
265
|
+
this.opts = opts;
|
|
266
|
+
this.stopped = false;
|
|
267
|
+
// CAEL audit hash chain — survives across ticks within a single runner
|
|
268
|
+
// process. On process restart it resets to null; the first post-restart
|
|
269
|
+
// record breaks the chain, which is honest (the runner has no memory of
|
|
270
|
+
// its prior chain state and shouldn't fake continuity). prev_hash=null
|
|
271
|
+
// is a valid value the audit-store accepts.
|
|
272
|
+
this.prevCaelChain = null;
|
|
273
|
+
// Self-recovery flag for the auto-rejoin path (task_1777112258989_eeyp).
|
|
274
|
+
// When the heartbeat returns 403 "Not a member of this team" — typical of
|
|
275
|
+
// a fresh Vast.ai worker whose provisioning didn't atomically /join, or of
|
|
276
|
+
// a worker whose membership was reaped — the runner calls mesh.joinTeam()
|
|
277
|
+
// ONCE per process and retries the heartbeat. After a successful rejoin
|
|
278
|
+
// we set this flag so subsequent 403s on the same process don't loop back
|
|
279
|
+
// into joinTeam (avoiding a retry storm if the team-cap is full or the
|
|
280
|
+
// join itself is permanently rejected). On process restart the flag
|
|
281
|
+
// resets, which is the correct semantics: a fresh process gets one fresh
|
|
282
|
+
// chance to self-rejoin. Discovered 2026-04-25 SSH-probing 5 fleet
|
|
283
|
+
// workers stuck in indefinite 403→tick-error→sleep→retry loops; without
|
|
284
|
+
// this, a fresh-deploy of an unjoined agent stays silent forever.
|
|
285
|
+
this.joinedThisProcess = false;
|
|
286
|
+
}
|
|
287
|
+
async tick() {
|
|
288
|
+
const { identity, brain, mesh, costGuard, provider, logger } = this.opts;
|
|
289
|
+
const log = logger ?? (() => void 0);
|
|
290
|
+
await this.heartbeatWithAutoRejoin();
|
|
291
|
+
if (costGuard.isOverBudget()) {
|
|
292
|
+
const state = costGuard.getState();
|
|
293
|
+
log({ ev: "over-budget", spentUsd: state.spentUsd, budget: identity.budgetUsdPerDay });
|
|
294
|
+
return {
|
|
295
|
+
action: "over-budget",
|
|
296
|
+
spentUsd: state.spentUsd,
|
|
297
|
+
remainingUsd: 0,
|
|
298
|
+
message: `daily budget $${identity.budgetUsdPerDay} exhausted`
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
const tasks = await mesh.getOpenTasks();
|
|
302
|
+
const target = pickClaimableTask(tasks, brain.capabilityTags);
|
|
303
|
+
if (!target) {
|
|
304
|
+
log({ ev: "no-claimable-task", open: tasks.length });
|
|
305
|
+
return {
|
|
306
|
+
action: "no-claimable-task",
|
|
307
|
+
spentUsd: costGuard.getState().spentUsd,
|
|
308
|
+
remainingUsd: costGuard.getRemainingUsd()
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
log({ ev: "claim", taskId: target.id, title: target.title });
|
|
312
|
+
await mesh.claim(target.id);
|
|
313
|
+
const start = Date.now();
|
|
314
|
+
const messages = [
|
|
315
|
+
{ role: "system", content: brain.systemPrompt },
|
|
316
|
+
{ role: "user", content: buildTaskPrompt(target) }
|
|
317
|
+
];
|
|
318
|
+
let aggUsage = { promptTokens: 0, completionTokens: 0, totalTokens: 0 };
|
|
319
|
+
let finalText = "";
|
|
320
|
+
let iters = 0;
|
|
321
|
+
const MAX_TOOL_ITERS = 30;
|
|
322
|
+
let lastResponse;
|
|
323
|
+
const toolsCalled = /* @__PURE__ */ new Set();
|
|
324
|
+
while (true) {
|
|
325
|
+
iters++;
|
|
326
|
+
if (iters > MAX_TOOL_ITERS) {
|
|
327
|
+
log({ ev: "tool-loop-cap", taskId: target.id, iters });
|
|
328
|
+
finalText = finalText || `[tool-loop hit ${MAX_TOOL_ITERS}-iter cap before final text]`;
|
|
329
|
+
break;
|
|
330
|
+
}
|
|
331
|
+
const resp = await provider.complete(
|
|
332
|
+
{
|
|
333
|
+
messages,
|
|
334
|
+
maxTokens: 4096,
|
|
335
|
+
temperature: 0.4,
|
|
336
|
+
tools: MESH_TOOLS
|
|
337
|
+
},
|
|
338
|
+
identity.llmModel
|
|
339
|
+
);
|
|
340
|
+
lastResponse = resp;
|
|
341
|
+
aggUsage = {
|
|
342
|
+
promptTokens: aggUsage.promptTokens + resp.usage.promptTokens,
|
|
343
|
+
completionTokens: aggUsage.completionTokens + resp.usage.completionTokens,
|
|
344
|
+
totalTokens: aggUsage.totalTokens + resp.usage.totalTokens
|
|
345
|
+
};
|
|
346
|
+
if (resp.finishReason === "tool_use" && resp.toolUses && resp.toolUses.length > 0) {
|
|
347
|
+
log({ ev: "tool-call", taskId: target.id, iter: iters, tools: resp.toolUses.map((t) => t.name) });
|
|
348
|
+
for (const u of resp.toolUses) toolsCalled.add(u.name);
|
|
349
|
+
messages.push({
|
|
350
|
+
role: "assistant",
|
|
351
|
+
content: resp.assistantBlocks ?? []
|
|
352
|
+
});
|
|
353
|
+
const toolResults = await Promise.all(resp.toolUses.map((u) => runTool(u)));
|
|
354
|
+
messages.push({
|
|
355
|
+
role: "user",
|
|
356
|
+
content: toolResults
|
|
357
|
+
});
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
finalText = resp.content;
|
|
361
|
+
break;
|
|
362
|
+
}
|
|
363
|
+
const durationMs = Date.now() - start;
|
|
364
|
+
const SIDE_EFFECTING_TOOLS = /* @__PURE__ */ new Set(["write_file", "bash"]);
|
|
365
|
+
const sideEffectingCalled = [...toolsCalled].some((t) => SIDE_EFFECTING_TOOLS.has(t));
|
|
366
|
+
if (!sideEffectingCalled) {
|
|
367
|
+
log({
|
|
368
|
+
ev: "no-artifact",
|
|
369
|
+
taskId: target.id,
|
|
370
|
+
tool_iters: iters,
|
|
371
|
+
toolsCalled: [...toolsCalled],
|
|
372
|
+
message: "task execution called no side-effecting tool (write_file/bash) \u2014 refusing to mark executed. Likely a pure-text or read-only-inspection response. Task remains open for a grounded attempt."
|
|
373
|
+
});
|
|
374
|
+
return {
|
|
375
|
+
action: "no-artifact",
|
|
376
|
+
taskId: target.id,
|
|
377
|
+
spentUsd: costGuard.getState().spentUsd,
|
|
378
|
+
remainingUsd: costGuard.getRemainingUsd(),
|
|
379
|
+
message: `no side-effecting tool called (toolsCalled=[${[...toolsCalled].join(",")}], iters=${iters})`
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
const cost = costGuard.recordUsage(identity.llmModel, aggUsage);
|
|
383
|
+
log({
|
|
384
|
+
ev: "executed",
|
|
385
|
+
taskId: target.id,
|
|
386
|
+
costUsd: cost.costUsd.toFixed(4),
|
|
387
|
+
spentUsd: cost.spentUsd.toFixed(4),
|
|
388
|
+
tokens: aggUsage.totalTokens,
|
|
389
|
+
tool_iters: iters
|
|
390
|
+
});
|
|
391
|
+
const response = { ...lastResponse ?? { content: finalText, usage: aggUsage }, content: finalText, usage: aggUsage };
|
|
392
|
+
const execResult = {
|
|
393
|
+
taskId: target.id,
|
|
394
|
+
responseText: response.content,
|
|
395
|
+
usage: response.usage,
|
|
396
|
+
costUsd: cost.costUsd,
|
|
397
|
+
durationMs
|
|
398
|
+
};
|
|
399
|
+
if (this.opts.auditLog) {
|
|
400
|
+
try {
|
|
401
|
+
this.opts.auditLog.recordTaskExecuted({
|
|
402
|
+
identity,
|
|
403
|
+
task: target,
|
|
404
|
+
result: execResult
|
|
405
|
+
});
|
|
406
|
+
} catch (err) {
|
|
407
|
+
log({ ev: "audit-log-error", message: err instanceof Error ? err.message : String(err) });
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
try {
|
|
411
|
+
const caelRecord = buildCaelRecord({
|
|
412
|
+
identity,
|
|
413
|
+
brain,
|
|
414
|
+
task: target,
|
|
415
|
+
messages,
|
|
416
|
+
finalText,
|
|
417
|
+
usage: aggUsage,
|
|
418
|
+
costUsd: cost.costUsd,
|
|
419
|
+
spentUsd: cost.spentUsd,
|
|
420
|
+
prevChain: this.prevCaelChain,
|
|
421
|
+
runtimeVersion: RUNTIME_VERSION
|
|
422
|
+
});
|
|
423
|
+
const posted = await mesh.postAuditRecords(identity.handle, [caelRecord]);
|
|
424
|
+
this.prevCaelChain = caelRecord.fnv1a_chain;
|
|
425
|
+
log({ ev: "cael-posted", taskId: target.id, appended: posted.appended, rejected: posted.rejected });
|
|
426
|
+
} catch (err) {
|
|
427
|
+
log({ ev: "cael-post-error", message: err instanceof Error ? err.message : String(err) });
|
|
428
|
+
}
|
|
429
|
+
if (this.opts.onTaskExecuted) {
|
|
430
|
+
await this.opts.onTaskExecuted(execResult, target);
|
|
431
|
+
} else {
|
|
432
|
+
await mesh.sendMessageOnTask(
|
|
433
|
+
target.id,
|
|
434
|
+
`[${identity.handle}] response (${response.usage.totalTokens} tok, $${cost.costUsd.toFixed(4)}):
|
|
435
|
+
|
|
436
|
+
${response.content}`
|
|
437
|
+
);
|
|
438
|
+
}
|
|
439
|
+
return {
|
|
440
|
+
action: "executed",
|
|
441
|
+
taskId: target.id,
|
|
442
|
+
spentUsd: cost.spentUsd,
|
|
443
|
+
remainingUsd: cost.remainingUsd
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
async runForever(opts = {}) {
|
|
447
|
+
const interval = opts.tickIntervalMs ?? 6e4;
|
|
448
|
+
while (!this.stopped) {
|
|
449
|
+
try {
|
|
450
|
+
await this.tick();
|
|
451
|
+
} catch (err) {
|
|
452
|
+
const log = this.opts.logger ?? (() => void 0);
|
|
453
|
+
log({ ev: "tick-error", message: err instanceof Error ? err.message : String(err) });
|
|
454
|
+
}
|
|
455
|
+
await sleep(interval + jitter(interval));
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
stop() {
|
|
459
|
+
this.stopped = true;
|
|
460
|
+
}
|
|
461
|
+
/**
|
|
462
|
+
* Heartbeat with one-shot self-rejoin on 403 "Not a member of this team".
|
|
463
|
+
*
|
|
464
|
+
* Pairs with task_1777112258989_eeyp: fresh-deploy fleet workers whose
|
|
465
|
+
* provisioning didn't atomically call /join (or whose membership was
|
|
466
|
+
* reaped) hit 403 every tick and never recover. We detect the specific
|
|
467
|
+
* server error string (see packages/mcp-server/src/holomesh/routes/
|
|
468
|
+
* team-routes.ts:903 → `{ error: 'Not a member' }` for /presence), call
|
|
469
|
+
* mesh.joinTeam() ONCE per runner process, and retry the heartbeat.
|
|
470
|
+
*
|
|
471
|
+
* Strict scope:
|
|
472
|
+
* - Only retries on 403 + "Not a member" body. Any other 403 (insufficient
|
|
473
|
+
* permissions, signing failure) re-throws unchanged.
|
|
474
|
+
* - Only retries ONCE per process. If we already rejoined this process and
|
|
475
|
+
* the heartbeat is *still* 403, the team is rejecting us for a reason
|
|
476
|
+
* /join can't fix (e.g. capacity, ban) — surface the error.
|
|
477
|
+
* - If joinTeam() itself throws, we DO mark joinedThisProcess=true before
|
|
478
|
+
* re-throwing so we don't slam the join endpoint on every subsequent
|
|
479
|
+
* tick. The next tick will surface the same heartbeat 403 and the
|
|
480
|
+
* runner-level catch in runForever logs tick-error and sleeps. Operator
|
|
481
|
+
* inspection (SSH/log) is the recovery path at that point.
|
|
482
|
+
*/
|
|
483
|
+
async heartbeatWithAutoRejoin() {
|
|
484
|
+
const { identity, mesh, logger } = this.opts;
|
|
485
|
+
const log = logger ?? (() => void 0);
|
|
486
|
+
try {
|
|
487
|
+
await mesh.heartbeat({ agentName: identity.handle, surface: identity.surface });
|
|
488
|
+
} catch (err) {
|
|
489
|
+
if (!this.isNotAMemberError(err) || this.joinedThisProcess) {
|
|
490
|
+
throw err;
|
|
491
|
+
}
|
|
492
|
+
log({ ev: "auto-rejoin-attempt", reason: "heartbeat-403-not-a-member" });
|
|
493
|
+
this.joinedThisProcess = true;
|
|
494
|
+
try {
|
|
495
|
+
const joinResult = await mesh.joinTeam();
|
|
496
|
+
log({ ev: "auto-rejoin-success", role: joinResult.role, members: joinResult.members });
|
|
497
|
+
} catch (joinErr) {
|
|
498
|
+
log({
|
|
499
|
+
ev: "auto-rejoin-failed",
|
|
500
|
+
message: joinErr instanceof Error ? joinErr.message : String(joinErr)
|
|
501
|
+
});
|
|
502
|
+
throw joinErr;
|
|
503
|
+
}
|
|
504
|
+
await mesh.heartbeat({ agentName: identity.handle, surface: identity.surface });
|
|
505
|
+
log({ ev: "auto-rejoin-heartbeat-recovered" });
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
/**
|
|
509
|
+
* Detect the server's "Not a member" 403 error from HolomeshClient.req().
|
|
510
|
+
* The error message format is: `HoloMesh POST /team/<id>/presence 403: <body>`
|
|
511
|
+
* where body contains `{"error":"Not a member"}` (or "Not a member of this team").
|
|
512
|
+
* Match conservatively: BOTH a "403" status marker AND the "Not a member"
|
|
513
|
+
* substring must appear, so unrelated 403s (insufficient permissions,
|
|
514
|
+
* signing failures) do NOT trigger a rejoin.
|
|
515
|
+
*/
|
|
516
|
+
isNotAMemberError(err) {
|
|
517
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
518
|
+
return / 403:/.test(msg) && /Not a member/i.test(msg);
|
|
519
|
+
}
|
|
520
|
+
};
|
|
521
|
+
function buildTaskPrompt(task) {
|
|
522
|
+
return [
|
|
523
|
+
`Board task to execute: ${task.id}`,
|
|
524
|
+
`Title: ${task.title}`,
|
|
525
|
+
`Priority: ${task.priority}`,
|
|
526
|
+
`Tags: ${(task.tags ?? []).join(", ")}`,
|
|
527
|
+
"",
|
|
528
|
+
"Description:",
|
|
529
|
+
task.description ?? "(no description)",
|
|
530
|
+
"",
|
|
531
|
+
"Produce the deliverable described in the task. Apply your brain composition rules \u2014 anti-patterns, decision loop, and scope tier all bind. Return the response as plain text suitable for posting to /room as a message on this task."
|
|
532
|
+
].join("\n");
|
|
533
|
+
}
|
|
534
|
+
function sleep(ms) {
|
|
535
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
536
|
+
}
|
|
537
|
+
function jitter(base) {
|
|
538
|
+
return Math.floor((Math.random() - 0.5) * base * 0.2);
|
|
539
|
+
}
|
|
540
|
+
export {
|
|
541
|
+
AgentRunner
|
|
542
|
+
};
|
|
543
|
+
//# sourceMappingURL=runner.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/holomesh-client.ts","../src/cael-builder.ts","../src/tools.ts","../src/runner.ts"],"sourcesContent":["import type { BoardTask } from './types.js';\nimport type { CaelAuditRecord } from './cael-builder.js';\n\nexport interface HolomeshClientOptions {\n apiBase: string;\n bearer: string;\n teamId: string;\n fetchImpl?: typeof fetch;\n}\n\nexport class HolomeshClient {\n private readonly apiBase: string;\n private readonly bearer: string;\n private readonly teamId: string;\n private readonly fetchImpl: typeof fetch;\n\n constructor(opts: HolomeshClientOptions) {\n this.apiBase = opts.apiBase.replace(/\\/$/, '');\n this.bearer = opts.bearer;\n this.teamId = opts.teamId;\n this.fetchImpl = opts.fetchImpl ?? fetch;\n }\n\n async heartbeat(payload: { agentName: string; surface: string }): Promise<void> {\n await this.req('POST', `/team/${this.teamId}/presence`, payload);\n }\n\n async getOpenTasks(): Promise<BoardTask[]> {\n const data = await this.req<{ tasks?: BoardTask[]; open?: BoardTask[] }>(\n 'GET',\n `/team/${this.teamId}/board`\n );\n return data.tasks ?? data.open ?? [];\n }\n\n async claim(taskId: string): Promise<BoardTask> {\n return this.req<BoardTask>('PATCH', `/team/${this.teamId}/board/${taskId}`, { action: 'claim' });\n }\n\n async joinTeam(): Promise<{ success: boolean; role?: string; members?: number }> {\n return this.req<{ success: boolean; role?: string; members?: number }>(\n 'POST',\n `/team/${this.teamId}/join`,\n {}\n );\n }\n\n async sendMessageOnTask(taskId: string, body: string): Promise<void> {\n await this.req('POST', `/team/${this.teamId}/message`, {\n to: 'team',\n subject: `task:${taskId}`,\n content: body,\n });\n }\n\n async markDone(taskId: string, summary: string, commitHash?: string): Promise<void> {\n await this.req('PATCH', `/team/${this.teamId}/board/${taskId}`, {\n action: 'done',\n summary,\n commitHash,\n });\n }\n\n // POST CAEL audit records for this agent. Server validator at\n // packages/mcp-server/src/holomesh/routes/core-routes.ts:472-533 requires\n // bearer == handle owner OR founder; the per-surface x402 bearer is the\n // handle owner so this resolves correctly. Records that fail shape\n // validation (layer_hashes != 7 elements, missing tick_iso/operation/\n // fnv1a_chain) are silently dropped server-side, not rejected as a batch.\n async postAuditRecords(handle: string, records: CaelAuditRecord[]): Promise<{ appended: number; rejected: number }> {\n return this.req<{ appended: number; rejected: number }>(\n 'POST',\n `/agent/${encodeURIComponent(handle)}/audit`,\n { records }\n );\n }\n\n async whoAmI(): Promise<{ agentId: string; surface: string; wallet?: string }> {\n // GET /api/holomesh/me returns { agentId, name, wallet, isFounder, teamId, teams, permissions }\n // (see packages/mcp-server/src/holomesh/routes/core-routes.ts §/me handler).\n // It does NOT return a `surface` field — derive it from the seat name on the\n // client side. Seat naming convention (set by the provisioning admin path):\n // claudecode-claude-x402 → claude-code\n // cursor-claude-x402 → claude-cursor\n // gemini-antigravity → gemini-antigravity\n // copilot-vscode → copilot-vscode\n // Founder → unknown (shared key, no surface attribution)\n const raw = await this.req<{\n agentId: string;\n name?: string;\n wallet?: string;\n }>('GET', '/me');\n return {\n agentId: raw.agentId,\n surface: deriveSurface(raw.name),\n wallet: raw.wallet,\n };\n }\n\n private async req<T>(method: string, path: string, body?: unknown): Promise<T> {\n const url = `${this.apiBase}${path}`;\n // HoloMesh REST auth: server (packages/mcp-server/src/holomesh/auth-utils.ts\n // resolveRequestingAgent) accepts EITHER `Authorization: Bearer <token>`\n // (HTTP-standard, used here) OR `x-mcp-api-key: <token>` (orchestrator\n // convention). Both resolve through the same key-registry / agent-store /\n // env-fallback chain. Bearer is preferred for new code (W.087 vertex B,\n // task_1777073616424_klls).\n const res = await this.fetchImpl(url, {\n method,\n headers: {\n Authorization: `Bearer ${this.bearer}`,\n 'content-type': 'application/json',\n },\n body: body ? JSON.stringify(body) : undefined,\n });\n if (!res.ok) {\n const txt = await res.text().catch(() => '');\n throw new Error(`HoloMesh ${method} ${path} ${res.status}: ${txt.slice(0, 300)}`);\n }\n if (res.status === 204) return undefined as T;\n return (await res.json()) as T;\n }\n}\n\n/**\n * Derive a surface tag from a seat name returned by /me. Mirrors the surface\n * detection in scripts/probe-surface-bearers.mjs and hooks/lib/holomesh-env.mjs\n * so a single agent's surface attribution is consistent across read and write\n * paths. Returns 'unknown' when the seat name doesn't encode a surface\n * (e.g. shared-key resolution to \"Founder\").\n */\nexport function deriveSurface(seatName: string | undefined): string {\n if (!seatName) return 'unknown';\n const n = seatName.toLowerCase();\n if (n.startsWith('claudecode')) return 'claude-code';\n if (n.startsWith('cursor')) return 'claude-cursor';\n if (n.startsWith('claudedesktop')) return 'claude-desktop';\n if (n.startsWith('vscode-claude') || n.startsWith('claude-vscode')) return 'claude-vscode';\n if (n.startsWith('gemini')) return 'gemini-antigravity';\n if (n.startsWith('copilot')) return 'copilot-vscode';\n return 'unknown';\n}\n\nexport function pickClaimableTask(\n tasks: BoardTask[],\n brainCapabilityTags: string[]\n): BoardTask | undefined {\n const wanted = new Set(brainCapabilityTags.map((t) => t.toLowerCase()));\n const open = tasks.filter((t) => t.status === 'open' && !t.claimedBy);\n const scored = open\n .map((t) => ({ task: t, score: scoreTask(t, wanted) }))\n .filter((s) => s.score > 0)\n .sort((a, b) => b.score - a.score || priority(a.task) - priority(b.task));\n return scored[0]?.task;\n}\n\nfunction scoreTask(task: BoardTask, wanted: Set<string>): number {\n const tags = (task.tags ?? []).map((t) => t.toLowerCase());\n const text = `${task.title} ${task.description ?? ''}`.toLowerCase();\n let score = 0;\n for (const tag of tags) if (wanted.has(tag)) score += 2;\n for (const w of wanted) if (text.includes(w)) score += 1;\n return score;\n}\n\nfunction priority(t: BoardTask): number {\n if (typeof t.priority === 'number') return t.priority;\n const map: Record<string, number> = { critical: 1, high: 2, medium: 4, low: 6 };\n return map[String(t.priority).toLowerCase()] ?? 5;\n}\n","// CAEL audit record builder for the headless agent runtime.\n//\n// Phase 1: agent ticks emit a CaelAuditRecord shaped to satisfy the\n// HoloMesh audit endpoint validator at packages/mcp-server/src/holomesh/\n// routes/core-routes.ts:512-518 (7-element layer_hashes array, string\n// tick_iso/operation/fnv1a_chain). The 7 layers map to concrete tick\n// stages so a downstream consumer can verify any one layer in isolation:\n//\n// L0 brain_state — sha256(brain.systemPrompt)\n// L1 tick_input — sha256(taskId|title|description)\n// L2 messages — sha256(JSON of final message thread)\n// L3 response — sha256(finalText)\n// L4 usage — sha256(JSON of aggregated TokenUsage)\n// L5 cost — sha256(costUsd|spentUsd)\n// L6 composite — sha256(L0|L1|L2|L3|L4|L5)\n//\n// fnv1a_chain extends across records: chain_n = sha256(chain_{n-1} | L6_n).\n// First tick emits prev_hash=null; subsequent ticks chain from the\n// previous record's fnv1a_chain.\n\nimport { createHash } from 'node:crypto';\nimport type { LLMMessage, TokenUsage } from '@holoscript/llm-provider';\nimport type { AgentIdentity, BoardTask, ExecutionResult, RuntimeBrainConfig } from './types.js';\n\nexport interface CaelAuditRecord {\n tick_iso: string;\n layer_hashes: string[];\n operation: string;\n prev_hash: string | null;\n fnv1a_chain: string;\n version_vector_fingerprint: string;\n brain_class?: string;\n trial?: number;\n attack_class?: string;\n defense_state?: string;\n}\n\nexport interface BuildCaelRecordInput {\n identity: AgentIdentity;\n brain: RuntimeBrainConfig;\n task: BoardTask;\n messages: LLMMessage[];\n finalText: string;\n usage: TokenUsage;\n costUsd: number;\n spentUsd: number;\n prevChain: string | null;\n runtimeVersion: string;\n}\n\nfunction sha(input: string): string {\n return createHash('sha256').update(input, 'utf8').digest('hex');\n}\n\n/**\n * Extract the brain class from a runtime brain config. Tries multiple sources\n * because brainPath shape varies across deployment environments:\n * 1. compositions/<class>-brain.hsplus (canonical layout — caught 2026-04-24)\n * 2. <anything>/<class>-brain.hsplus (loose match — Vast.ai box layout)\n * 3. <class>-brain.hsplus basename only\n * 4. brain.domain (loaded from .hsplus identity block by loadBrain())\n * 5. 'unknown' if all sources fail\n *\n * Live evidence (2026-04-25 mesh-worker-01 record): the strict regex returned\n * 'unknown' against the production worker box's brainPath, leaving every CAEL\n * fingerprint useless for fleet attribution. This loosened version recovers\n * brain class even when path layout drifts from the compositions/-rooted form.\n */\nfunction brainClassOf(brain: { brainPath?: string; domain?: string }): string {\n const p = String(brain.brainPath ?? '');\n // Tier 1: canonical compositions/-rooted layout.\n let m = p.match(/compositions[\\\\/]([\\w-]+)-brain\\.hsplus$/);\n if (m) return m[1];\n // Tier 2: any path with `<class>-brain.hsplus` basename.\n m = p.match(/([\\w-]+)-brain\\.hsplus$/);\n if (m) return m[1];\n // Tier 3: bare basename.\n m = p.match(/([\\w-]+)\\.hsplus$/);\n if (m) return m[1];\n // Tier 4: domain field from the loaded brain composition's identity block.\n const domain = String(brain.domain ?? '').trim();\n if (domain && domain !== 'unknown') return domain;\n return 'unknown';\n}\n\nexport function buildCaelRecord(input: BuildCaelRecordInput): CaelAuditRecord {\n const { identity, brain, task, messages, finalText, usage, costUsd, spentUsd, prevChain, runtimeVersion } = input;\n\n const l0 = sha(brain.systemPrompt);\n const l1 = sha(`${task.id}|${task.title}|${task.description ?? ''}`);\n const l2 = sha(JSON.stringify(messages));\n const l3 = sha(finalText);\n const l4 = sha(JSON.stringify(usage));\n const l5 = sha(`${costUsd.toFixed(6)}|${spentUsd.toFixed(6)}`);\n const l6 = sha([l0, l1, l2, l3, l4, l5].join('|'));\n\n const fnv1a_chain = sha(`${prevChain ?? ''}|${l6}`);\n\n return {\n tick_iso: new Date().toISOString(),\n layer_hashes: [l0, l1, l2, l3, l4, l5, l6],\n operation: `task-executed:${task.id}`,\n prev_hash: prevChain,\n fnv1a_chain,\n version_vector_fingerprint: `agent@${runtimeVersion}|brain@${brainClassOf(brain)}|provider@${identity.llmProvider}|model@${identity.llmModel}`,\n brain_class: brainClassOf(brain),\n };\n}\n","/**\n * Tool runner for headless mesh agents.\n *\n * Provides a small, sandboxed set of tools that LLM agents can call during\n * task execution. Anthropic tool-use shape — these specs are passed to\n * `messages.stream({ tools: [...] })`, the model returns `tool_use` blocks,\n * the runner executes them via `runTool()` and feeds results back as\n * `tool_result` blocks until the model emits its final text response.\n *\n * Sandbox model:\n * - read_file / list_dir: restricted to ALLOWED_READ_ROOTS (task inputs +\n * read-only views of the cloned repo). No /etc, no /home, no /root/.ssh.\n * - write_file: restricted to ALLOWED_WRITE_ROOTS (just /root/agent-output/).\n * Creates dir if needed, refuses paths that escape via .. or symlinks.\n * - bash: ONLY whitelisted command prefixes (lake build, lean ..., ls, cat,\n * grep, find, wc, head, tail, git status/log/diff/show, pnpm --filter,\n * vitest run --no-coverage). Hard 60s wall timeout, 1MB stdout cap. Refuses\n * anything else (rm, curl, ssh, sudo, eval, etc.).\n *\n * The sandbox is best-effort host isolation — these instances are dedicated\n * to a single mesh-worker identity, so we trade some flexibility for a clear\n * \"what the LLM can do\" contract that audits cleanly.\n */\n\nimport { readFile, writeFile, readdir, mkdir, stat } from 'node:fs/promises';\nimport { resolve, dirname } from 'node:path';\nimport { spawn } from 'node:child_process';\nimport type { ToolSpec, ToolUseBlock, ToolResultBlock } from '@holoscript/llm-provider';\n\n// ---------------------------------------------------------------------------\n// Sandbox roots — keep narrow. Add only when a task needs more.\n// ---------------------------------------------------------------------------\nconst ALLOWED_READ_ROOTS = [\n '/root/msc-paper-22', // Paper 22 mechanization inputs (scp'd by deploy)\n '/root/holoscript-mesh', // Read-only repo view (clone path on instance)\n '/root/agent-output', // Read back what we wrote\n];\n\nconst ALLOWED_WRITE_ROOTS = [\n '/root/agent-output', // Single write sink — keeps deliverables in one place\n];\n\n// Command-prefix whitelist. Prefix-match is intentional — `lake build MSC`\n// matches `lake build`, `pnpm --filter @holoscript/core build` matches\n// `pnpm --filter`, etc. Refuses anything else (no sudo, rm, curl, ssh, eval).\nconst BASH_WHITELIST = [\n 'lake build', 'lake env', 'lake clean',\n 'lean ',\n 'ls ', 'ls\\n', 'ls$',\n 'cat ',\n 'grep ', 'rg ',\n 'find ',\n 'wc ',\n 'head ', 'tail ',\n 'git status', 'git log', 'git diff', 'git show',\n 'pnpm --filter',\n 'pnpm vitest', 'vitest run',\n 'pwd',\n 'echo ',\n];\n\n// ---------------------------------------------------------------------------\n// Tool specs surfaced to the LLM\n// ---------------------------------------------------------------------------\nexport const MESH_TOOLS: ToolSpec[] = [\n {\n name: 'read_file',\n description:\n 'Read a file from the agent sandbox. Allowed roots: /root/msc-paper-22, ' +\n '/root/holoscript-mesh, /root/agent-output. Returns the file content as text. ' +\n 'Use this to inspect inputs scp\\'d to the instance (e.g. MSC/Invariants.lean).',\n input_schema: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Absolute path under an allowed read root' },\n },\n required: ['path'],\n },\n },\n {\n name: 'list_dir',\n description:\n 'List entries in a directory under the agent sandbox. Same root restrictions ' +\n 'as read_file. Returns a newline-separated list of entries.',\n input_schema: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Absolute path under an allowed read root' },\n },\n required: ['path'],\n },\n },\n {\n name: 'write_file',\n description:\n 'Write a file to /root/agent-output/. This is the deliverable sink — anything ' +\n 'you want to emit as task output (a Lean proof, a markdown report, a JSON dataset) ' +\n 'goes here. Creates parent directories. Will refuse paths outside the write root.',\n input_schema: {\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Absolute path under /root/agent-output/' },\n content: { type: 'string', description: 'File content to write (UTF-8)' },\n },\n required: ['path', 'content'],\n },\n },\n {\n name: 'bash',\n description:\n 'Run a shell command. Whitelisted prefixes only: lake build, lean, ls, cat, ' +\n 'grep, find, wc, head, tail, git status/log/diff/show, pnpm --filter, vitest run, ' +\n 'pwd, echo. Hard 60s wall timeout, 1MB stdout cap. Use for lake build / lean ' +\n 'kernel-checks, git inspection, repo greps. Refuses rm, curl, ssh, sudo, eval.',\n input_schema: {\n type: 'object',\n properties: {\n cmd: { type: 'string', description: 'Whitelisted shell command' },\n cwd: { type: 'string', description: 'Optional working directory (defaults to /root)' },\n },\n required: ['cmd'],\n },\n },\n];\n\n// ---------------------------------------------------------------------------\n// Path-sandbox helpers\n// ---------------------------------------------------------------------------\nfunction isUnderRoot(absPath: string, root: string): boolean {\n const resolved = resolve(absPath);\n const rootResolved = resolve(root);\n return resolved === rootResolved || resolved.startsWith(rootResolved + '/');\n}\n\nfunction checkReadAllowed(path: string): string | null {\n if (!path.startsWith('/')) return `path must be absolute, got \"${path}\"`;\n for (const root of ALLOWED_READ_ROOTS) {\n if (isUnderRoot(path, root)) return null;\n }\n return `read denied — path \"${path}\" not under allowed roots: ${ALLOWED_READ_ROOTS.join(', ')}`;\n}\n\nfunction checkWriteAllowed(path: string): string | null {\n if (!path.startsWith('/')) return `path must be absolute, got \"${path}\"`;\n for (const root of ALLOWED_WRITE_ROOTS) {\n if (isUnderRoot(path, root)) return null;\n }\n return `write denied — path \"${path}\" not under allowed roots: ${ALLOWED_WRITE_ROOTS.join(', ')}`;\n}\n\nfunction checkBashAllowed(cmd: string): string | null {\n const trimmed = cmd.trim();\n if (trimmed.length === 0) return 'empty command';\n // Reject obvious shell-injection attempts. Whitelist below still applies.\n if (/[;&|`$<>]|>>|\\|\\||&&/.test(trimmed)) {\n return `command contains shell metachars (; & | \\` $ < > >> || &&) — not allowed for safety`;\n }\n for (const prefix of BASH_WHITELIST) {\n if (trimmed.startsWith(prefix.trim())) return null;\n }\n return `command not on whitelist. Allowed prefixes: ${BASH_WHITELIST.join(' / ')}`;\n}\n\n// ---------------------------------------------------------------------------\n// Tool implementations\n// ---------------------------------------------------------------------------\nexport async function runTool(use: ToolUseBlock): Promise<ToolResultBlock> {\n try {\n if (use.name === 'read_file') {\n const path = use.input.path as string;\n const denied = checkReadAllowed(path);\n if (denied) return errResult(use.id, denied);\n const text = await readFile(path, 'utf8');\n // Cap at 200KB to avoid context blowups\n const truncated = text.length > 200_000 ? text.slice(0, 200_000) + `\\n…[truncated, full file is ${text.length} bytes]` : text;\n return okResult(use.id, truncated);\n }\n\n if (use.name === 'list_dir') {\n const path = use.input.path as string;\n const denied = checkReadAllowed(path);\n if (denied) return errResult(use.id, denied);\n const entries = await readdir(path, { withFileTypes: true });\n const lines = entries.map((e) => `${e.isDirectory() ? 'd' : '-'} ${e.name}`);\n return okResult(use.id, lines.join('\\n'));\n }\n\n if (use.name === 'write_file') {\n const path = use.input.path as string;\n const content = use.input.content as string;\n const denied = checkWriteAllowed(path);\n if (denied) return errResult(use.id, denied);\n await mkdir(dirname(path), { recursive: true });\n await writeFile(path, content, 'utf8');\n const s = await stat(path);\n return okResult(use.id, `wrote ${s.size} bytes to ${path}`);\n }\n\n if (use.name === 'bash') {\n const cmd = use.input.cmd as string;\n const cwd = (use.input.cwd as string | undefined) ?? '/root';\n const denied = checkBashAllowed(cmd);\n if (denied) return errResult(use.id, denied);\n const result = await runBash(cmd, cwd);\n return result.code === 0\n ? okResult(use.id, result.stdout)\n : errResult(use.id, `exit=${result.code}\\n${result.stderr || result.stdout}`);\n }\n\n return errResult(use.id, `unknown tool: ${use.name}`);\n } catch (err) {\n return errResult(use.id, err instanceof Error ? err.message : String(err));\n }\n}\n\ninterface BashResult {\n code: number;\n stdout: string;\n stderr: string;\n}\n\nfunction runBash(cmd: string, cwd: string): Promise<BashResult> {\n return new Promise((resolveProm) => {\n const child = spawn('bash', ['-c', cmd], { cwd, env: process.env });\n let stdout = '';\n let stderr = '';\n let killed = false;\n const STDOUT_CAP = 1_000_000;\n const TIMEOUT_MS = 60_000;\n const killer = setTimeout(() => {\n killed = true;\n child.kill('SIGKILL');\n }, TIMEOUT_MS);\n child.stdout.on('data', (d: Buffer) => {\n if (stdout.length < STDOUT_CAP) stdout += d.toString('utf8');\n });\n child.stderr.on('data', (d: Buffer) => {\n if (stderr.length < STDOUT_CAP) stderr += d.toString('utf8');\n });\n child.on('error', (err) => {\n clearTimeout(killer);\n resolveProm({ code: 1, stdout, stderr: stderr + '\\nspawn-error: ' + err.message });\n });\n child.on('exit', (code) => {\n clearTimeout(killer);\n const finalStdout = stdout.length >= STDOUT_CAP ? stdout + `\\n…[stdout truncated at ${STDOUT_CAP} bytes]` : stdout;\n const note = killed ? `\\n[bash killed after ${TIMEOUT_MS}ms timeout]` : '';\n resolveProm({ code: code ?? 1, stdout: finalStdout + note, stderr });\n });\n });\n}\n\nfunction okResult(id: string, content: string): ToolResultBlock {\n return { type: 'tool_result', tool_use_id: id, content };\n}\n\nfunction errResult(id: string, message: string): ToolResultBlock {\n return { type: 'tool_result', tool_use_id: id, content: message, is_error: true };\n}\n","import type { ILLMProvider, LLMMessage, TokenUsage } from '@holoscript/llm-provider';\nimport type { CostGuard } from './cost-guard.js';\nimport type { HolomeshClient } from './holomesh-client.js';\nimport { pickClaimableTask } from './holomesh-client.js';\nimport type { AuditLog } from './audit-log.js';\nimport { buildCaelRecord } from './cael-builder.js';\nimport { MESH_TOOLS, runTool } from './tools.js';\nimport type {\n AgentIdentity,\n BoardTask,\n ExecutionResult,\n RuntimeBrainConfig,\n TickResult,\n} from './types.js';\n\n// Bumped when the CAEL record schema or layer-hash semantics change. Lives\n// in the version_vector_fingerprint of every emitted record so consumers\n// can partition the corpus by runtime version.\nconst RUNTIME_VERSION = '1.0.0';\n\nexport interface AgentRunnerOptions {\n identity: AgentIdentity;\n brain: RuntimeBrainConfig;\n provider: ILLMProvider;\n costGuard: CostGuard;\n mesh: HolomeshClient;\n logger?: (event: Record<string, unknown>) => void;\n onTaskExecuted?: (result: ExecutionResult, task: BoardTask) => Promise<void>;\n auditLog?: AuditLog;\n}\n\nexport class AgentRunner {\n private stopped = false;\n // CAEL audit hash chain — survives across ticks within a single runner\n // process. On process restart it resets to null; the first post-restart\n // record breaks the chain, which is honest (the runner has no memory of\n // its prior chain state and shouldn't fake continuity). prev_hash=null\n // is a valid value the audit-store accepts.\n private prevCaelChain: string | null = null;\n // Self-recovery flag for the auto-rejoin path (task_1777112258989_eeyp).\n // When the heartbeat returns 403 \"Not a member of this team\" — typical of\n // a fresh Vast.ai worker whose provisioning didn't atomically /join, or of\n // a worker whose membership was reaped — the runner calls mesh.joinTeam()\n // ONCE per process and retries the heartbeat. After a successful rejoin\n // we set this flag so subsequent 403s on the same process don't loop back\n // into joinTeam (avoiding a retry storm if the team-cap is full or the\n // join itself is permanently rejected). On process restart the flag\n // resets, which is the correct semantics: a fresh process gets one fresh\n // chance to self-rejoin. Discovered 2026-04-25 SSH-probing 5 fleet\n // workers stuck in indefinite 403→tick-error→sleep→retry loops; without\n // this, a fresh-deploy of an unjoined agent stays silent forever.\n private joinedThisProcess = false;\n\n constructor(private readonly opts: AgentRunnerOptions) {}\n\n async tick(): Promise<TickResult> {\n const { identity, brain, mesh, costGuard, provider, logger } = this.opts;\n const log = logger ?? (() => undefined);\n\n await this.heartbeatWithAutoRejoin();\n\n if (costGuard.isOverBudget()) {\n const state = costGuard.getState();\n log({ ev: 'over-budget', spentUsd: state.spentUsd, budget: identity.budgetUsdPerDay });\n return {\n action: 'over-budget',\n spentUsd: state.spentUsd,\n remainingUsd: 0,\n message: `daily budget $${identity.budgetUsdPerDay} exhausted`,\n };\n }\n\n const tasks = await mesh.getOpenTasks();\n const target = pickClaimableTask(tasks, brain.capabilityTags);\n if (!target) {\n log({ ev: 'no-claimable-task', open: tasks.length });\n return {\n action: 'no-claimable-task',\n spentUsd: costGuard.getState().spentUsd,\n remainingUsd: costGuard.getRemainingUsd(),\n };\n }\n\n log({ ev: 'claim', taskId: target.id, title: target.title });\n await mesh.claim(target.id);\n\n const start = Date.now();\n // Tool-use loop. The model gets MESH_TOOLS (read_file, list_dir,\n // write_file, bash) and can iterate read→reason→read→write until it\n // emits a final text response. Without this loop the model could only\n // reason from prompt+brain alone — no filesystem access, no kernel\n // checks, no inspection of inputs scp'd to the instance. With it,\n // lean-theorist can actually `cat MSC/Invariants.lean`, `lake build`,\n // and `write_file /root/agent-output/Invariants.lean` per its brain rules.\n const messages: LLMMessage[] = [\n { role: 'system', content: brain.systemPrompt },\n { role: 'user', content: buildTaskPrompt(target) },\n ];\n let aggUsage: TokenUsage = { promptTokens: 0, completionTokens: 0, totalTokens: 0 };\n let finalText = '';\n let iters = 0;\n // 30-iter cap: lean-theorist on Paper 22 needed 13 iters to read MSC files\n // + run lake build + iterate kernel checks. 12 was too tight (cap fired\n // before write_file deliverable). 30 allows ~3x that depth — anything\n // hitting 30 iters is almost certainly stuck and should bail.\n const MAX_TOOL_ITERS = 30;\n let lastResponse;\n // Track which tool names were called during this run so the artifact-grounding\n // gate below can refuse to mark \"executed\" on pure-text or read-only responses.\n // Discovered 2026-04-26 mesh-worker-02 audit: workers were posting CAEL records\n // with tool_iters:1 (zero tools called) declaring \"100 scenes validated\" with\n // no commit / no /room done — fabricated deliverables polluting trust. The\n // gate below short-circuits this class of hallucination at the runner edge.\n const toolsCalled = new Set<string>();\n while (true) {\n iters++;\n if (iters > MAX_TOOL_ITERS) {\n log({ ev: 'tool-loop-cap', taskId: target.id, iters });\n finalText = finalText || `[tool-loop hit ${MAX_TOOL_ITERS}-iter cap before final text]`;\n break;\n }\n const resp = await provider.complete(\n {\n messages,\n maxTokens: 4096,\n temperature: 0.4,\n tools: MESH_TOOLS,\n },\n identity.llmModel\n );\n lastResponse = resp;\n aggUsage = {\n promptTokens: aggUsage.promptTokens + resp.usage.promptTokens,\n completionTokens: aggUsage.completionTokens + resp.usage.completionTokens,\n totalTokens: aggUsage.totalTokens + resp.usage.totalTokens,\n };\n // If model called tools, execute them and feed results back.\n if (resp.finishReason === 'tool_use' && resp.toolUses && resp.toolUses.length > 0) {\n log({ ev: 'tool-call', taskId: target.id, iter: iters, tools: resp.toolUses.map((t) => t.name) });\n // Track tool names for the artifact-grounding gate.\n for (const u of resp.toolUses) toolsCalled.add(u.name);\n // Append the assistant turn (text + tool_use blocks) so the model\n // sees its own request when we send tool_result back.\n messages.push({\n role: 'assistant',\n content: (resp.assistantBlocks ?? []) as never,\n });\n // Run each tool and collect results.\n const toolResults = await Promise.all(resp.toolUses.map((u) => runTool(u)));\n messages.push({\n role: 'user',\n content: toolResults as never,\n });\n continue;\n }\n // Final text response.\n finalText = resp.content;\n break;\n }\n const durationMs = Date.now() - start;\n\n // Artifact-grounding gate (W.107 — fleet event-firing rate is not a productivity\n // metric; only side-effecting tool calls produce real artifacts). MESH_TOOLS\n // exposes 4 tools: read_file + list_dir (read-only inspection) and write_file +\n // bash (state-mutating). A task whose execution did NOT call write_file or\n // bash at least once produced no artifact and should NOT be marked executed.\n // We log a 'no-artifact' tick-error instead, skip CAEL/message posts, and\n // return so the task remains open for a real attempt.\n const SIDE_EFFECTING_TOOLS: ReadonlySet<string> = new Set(['write_file', 'bash']);\n const sideEffectingCalled = [...toolsCalled].some((t) => SIDE_EFFECTING_TOOLS.has(t));\n if (!sideEffectingCalled) {\n log({\n ev: 'no-artifact',\n taskId: target.id,\n tool_iters: iters,\n toolsCalled: [...toolsCalled],\n message:\n 'task execution called no side-effecting tool (write_file/bash) — refusing to mark executed. ' +\n 'Likely a pure-text or read-only-inspection response. Task remains open for a grounded attempt.',\n });\n // Best-effort: leave the task in claimed state so the supervisor can either\n // re-tick or release it via heartbeat-rejoin. We deliberately do NOT post\n // a \"fake-done\" message on the board, do NOT post a CAEL record, and do NOT\n // call the cost guard's recordUsage — the run produced no artifact and\n // should not bill the budget for a hallucinated tick.\n return {\n action: 'no-artifact',\n taskId: target.id,\n spentUsd: costGuard.getState().spentUsd,\n remainingUsd: costGuard.getRemainingUsd(),\n message: `no side-effecting tool called (toolsCalled=[${[...toolsCalled].join(',')}], iters=${iters})`,\n };\n }\n\n const cost = costGuard.recordUsage(identity.llmModel, aggUsage);\n log({\n ev: 'executed',\n taskId: target.id,\n costUsd: cost.costUsd.toFixed(4),\n spentUsd: cost.spentUsd.toFixed(4),\n tokens: aggUsage.totalTokens,\n tool_iters: iters,\n });\n const response = { ...(lastResponse ?? { content: finalText, usage: aggUsage }), content: finalText, usage: aggUsage };\n\n const execResult: ExecutionResult = {\n taskId: target.id,\n responseText: response.content,\n usage: response.usage,\n costUsd: cost.costUsd,\n durationMs,\n };\n\n if (this.opts.auditLog) {\n try {\n this.opts.auditLog.recordTaskExecuted({\n identity,\n task: target,\n result: execResult,\n });\n } catch (err) {\n log({ ev: 'audit-log-error', message: err instanceof Error ? err.message : String(err) });\n }\n }\n\n // Phase 1 CAEL audit: post to the HoloMesh audit store so the fleet\n // corpus collector at ai-ecosystem/scripts/fleet-corpus-collector.mjs\n // can read records via GET /api/holomesh/agent/{handle}/audit. Without\n // this POST, the local AuditLog above is the only durable record and\n // Paper 25's gate clock cannot start. See ai-ecosystem task\n // task_1777106535952_atug for the empty-audit investigation.\n try {\n const caelRecord = buildCaelRecord({\n identity,\n brain,\n task: target,\n messages,\n finalText,\n usage: aggUsage,\n costUsd: cost.costUsd,\n spentUsd: cost.spentUsd,\n prevChain: this.prevCaelChain,\n runtimeVersion: RUNTIME_VERSION,\n });\n const posted = await mesh.postAuditRecords(identity.handle, [caelRecord]);\n this.prevCaelChain = caelRecord.fnv1a_chain;\n log({ ev: 'cael-posted', taskId: target.id, appended: posted.appended, rejected: posted.rejected });\n } catch (err) {\n log({ ev: 'cael-post-error', message: err instanceof Error ? err.message : String(err) });\n }\n\n if (this.opts.onTaskExecuted) {\n await this.opts.onTaskExecuted(execResult, target);\n } else {\n await mesh.sendMessageOnTask(\n target.id,\n `[${identity.handle}] response (${response.usage.totalTokens} tok, $${cost.costUsd.toFixed(4)}):\\n\\n${response.content}`\n );\n }\n\n return {\n action: 'executed',\n taskId: target.id,\n spentUsd: cost.spentUsd,\n remainingUsd: cost.remainingUsd,\n };\n }\n\n async runForever(opts: { tickIntervalMs?: number } = {}): Promise<void> {\n const interval = opts.tickIntervalMs ?? 60_000;\n while (!this.stopped) {\n try {\n await this.tick();\n } catch (err) {\n const log = this.opts.logger ?? (() => undefined);\n log({ ev: 'tick-error', message: err instanceof Error ? err.message : String(err) });\n }\n await sleep(interval + jitter(interval));\n }\n }\n\n stop(): void {\n this.stopped = true;\n }\n\n /**\n * Heartbeat with one-shot self-rejoin on 403 \"Not a member of this team\".\n *\n * Pairs with task_1777112258989_eeyp: fresh-deploy fleet workers whose\n * provisioning didn't atomically call /join (or whose membership was\n * reaped) hit 403 every tick and never recover. We detect the specific\n * server error string (see packages/mcp-server/src/holomesh/routes/\n * team-routes.ts:903 → `{ error: 'Not a member' }` for /presence), call\n * mesh.joinTeam() ONCE per runner process, and retry the heartbeat.\n *\n * Strict scope:\n * - Only retries on 403 + \"Not a member\" body. Any other 403 (insufficient\n * permissions, signing failure) re-throws unchanged.\n * - Only retries ONCE per process. If we already rejoined this process and\n * the heartbeat is *still* 403, the team is rejecting us for a reason\n * /join can't fix (e.g. capacity, ban) — surface the error.\n * - If joinTeam() itself throws, we DO mark joinedThisProcess=true before\n * re-throwing so we don't slam the join endpoint on every subsequent\n * tick. The next tick will surface the same heartbeat 403 and the\n * runner-level catch in runForever logs tick-error and sleeps. Operator\n * inspection (SSH/log) is the recovery path at that point.\n */\n private async heartbeatWithAutoRejoin(): Promise<void> {\n const { identity, mesh, logger } = this.opts;\n const log = logger ?? (() => undefined);\n try {\n await mesh.heartbeat({ agentName: identity.handle, surface: identity.surface });\n } catch (err) {\n if (!this.isNotAMemberError(err) || this.joinedThisProcess) {\n throw err;\n }\n log({ ev: 'auto-rejoin-attempt', reason: 'heartbeat-403-not-a-member' });\n // Mark BEFORE the join call so a thrown joinTeam() can't loop us.\n this.joinedThisProcess = true;\n try {\n const joinResult = await mesh.joinTeam();\n log({ ev: 'auto-rejoin-success', role: joinResult.role, members: joinResult.members });\n } catch (joinErr) {\n log({\n ev: 'auto-rejoin-failed',\n message: joinErr instanceof Error ? joinErr.message : String(joinErr),\n });\n throw joinErr;\n }\n // Retry the heartbeat exactly once. If it still fails (including with\n // another 403), the new error propagates — joinedThisProcess is now\n // true so we won't retry-loop on the next tick.\n await mesh.heartbeat({ agentName: identity.handle, surface: identity.surface });\n log({ ev: 'auto-rejoin-heartbeat-recovered' });\n }\n }\n\n /**\n * Detect the server's \"Not a member\" 403 error from HolomeshClient.req().\n * The error message format is: `HoloMesh POST /team/<id>/presence 403: <body>`\n * where body contains `{\"error\":\"Not a member\"}` (or \"Not a member of this team\").\n * Match conservatively: BOTH a \"403\" status marker AND the \"Not a member\"\n * substring must appear, so unrelated 403s (insufficient permissions,\n * signing failures) do NOT trigger a rejoin.\n */\n private isNotAMemberError(err: unknown): boolean {\n const msg = err instanceof Error ? err.message : String(err);\n return / 403:/.test(msg) && /Not a member/i.test(msg);\n }\n}\n\nfunction buildTaskPrompt(task: BoardTask): string {\n return [\n `Board task to execute: ${task.id}`,\n `Title: ${task.title}`,\n `Priority: ${task.priority}`,\n `Tags: ${(task.tags ?? []).join(', ')}`,\n '',\n 'Description:',\n task.description ?? '(no description)',\n '',\n 'Produce the deliverable described in the task. Apply your brain composition rules — anti-patterns, decision loop, and scope tier all bind. Return the response as plain text suitable for posting to /room as a message on this task.',\n ].join('\\n');\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => setTimeout(r, ms));\n}\n\nfunction jitter(base: number): number {\n return Math.floor((Math.random() - 0.5) * base * 0.2);\n}\n"],"mappings":";AA+IO,SAAS,kBACd,OACA,qBACuB;AACvB,QAAM,SAAS,IAAI,IAAI,oBAAoB,IAAI,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;AACtE,QAAM,OAAO,MAAM,OAAO,CAAC,MAAM,EAAE,WAAW,UAAU,CAAC,EAAE,SAAS;AACpE,QAAM,SAAS,KACZ,IAAI,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,UAAU,GAAG,MAAM,EAAE,EAAE,EACrD,OAAO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