@holoscript/holoscript-agent 2.0.0 → 2.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/holoscript-agent.cjs +16 -0
- package/dist/brain.js +18 -4
- package/dist/brain.js.map +1 -1
- package/dist/cost-guard.d.ts +17 -2
- package/dist/cost-guard.js +29 -3
- package/dist/cost-guard.js.map +1 -1
- package/dist/holomesh-client.d.ts +50 -1
- package/dist/holomesh-client.js +45 -0
- package/dist/holomesh-client.js.map +1 -1
- package/dist/identity.js +5 -1
- package/dist/identity.js.map +1 -1
- package/dist/index.js +489 -70
- package/dist/index.js.map +1 -1
- package/dist/runner.d.ts +57 -0
- package/dist/runner.js +86 -15
- package/dist/runner.js.map +1 -1
- package/dist/supervisor-config.js +12 -5
- package/dist/supervisor-config.js.map +1 -1
- package/dist/supervisor.js +350 -29
- package/dist/supervisor.js.map +1 -1
- package/dist/types.d.ts +30 -1
- package/package.json +7 -5
package/dist/runner.d.ts
CHANGED
|
@@ -4,6 +4,61 @@ import { HolomeshClient } from './holomesh-client.js';
|
|
|
4
4
|
import { AuditLog } from './audit-log.js';
|
|
5
5
|
import { AgentIdentity, RuntimeBrainConfig, ExecutionResult, BoardTask, TickResult } from './types.js';
|
|
6
6
|
|
|
7
|
+
interface TeamMessage {
|
|
8
|
+
id: string;
|
|
9
|
+
fromAgentId: string;
|
|
10
|
+
fromAgentName: string;
|
|
11
|
+
content: string;
|
|
12
|
+
messageType: string;
|
|
13
|
+
createdAt: string;
|
|
14
|
+
}
|
|
15
|
+
type AuthorityRequestType = 'owner-op' | 'founder-gated';
|
|
16
|
+
interface AuthorityRequest {
|
|
17
|
+
messageId: string;
|
|
18
|
+
fromAgentId: string;
|
|
19
|
+
fromAgentName: string;
|
|
20
|
+
requestType: AuthorityRequestType;
|
|
21
|
+
action: string;
|
|
22
|
+
payload: Record<string, unknown>;
|
|
23
|
+
rawContent: string;
|
|
24
|
+
}
|
|
25
|
+
interface AuthorityReceipt {
|
|
26
|
+
requestMessageId: string;
|
|
27
|
+
status: 'executed' | 'ruled' | 'rejected' | 'escalated' | 'deferred';
|
|
28
|
+
action: string;
|
|
29
|
+
result?: unknown;
|
|
30
|
+
ruling?: string;
|
|
31
|
+
reason: string;
|
|
32
|
+
timestamp: string;
|
|
33
|
+
}
|
|
34
|
+
interface DelegatedAuthorityOptions {
|
|
35
|
+
mesh: HolomeshClient;
|
|
36
|
+
/** Required for founder-gated rulings. Optional if handler only does owner-ops. */
|
|
37
|
+
provider?: ILLMProvider;
|
|
38
|
+
/** System prompt / founder-engine corpus. Injected into the LLM for rulings. */
|
|
39
|
+
systemPrompt?: string;
|
|
40
|
+
/** Agents whose requests are accepted. Empty = accept all team members. */
|
|
41
|
+
allowList?: Set<string>;
|
|
42
|
+
/** Actions this handler is permitted to execute. Empty = all owner-ops. */
|
|
43
|
+
permittedActions?: Set<string>;
|
|
44
|
+
/** Message IDs already processed (persisted across ticks). */
|
|
45
|
+
processedMessageIds?: Set<string>;
|
|
46
|
+
}
|
|
47
|
+
declare class DelegatedAuthorityHandler {
|
|
48
|
+
private readonly mesh;
|
|
49
|
+
private readonly provider?;
|
|
50
|
+
private readonly systemPrompt?;
|
|
51
|
+
private readonly allowList?;
|
|
52
|
+
private readonly permittedActions?;
|
|
53
|
+
private readonly processed;
|
|
54
|
+
constructor(opts: DelegatedAuthorityOptions);
|
|
55
|
+
processMessages(): Promise<AuthorityReceipt[]>;
|
|
56
|
+
parseRequest(msg: TeamMessage): AuthorityRequest | null;
|
|
57
|
+
handleRequest(req: AuthorityRequest): Promise<AuthorityReceipt>;
|
|
58
|
+
private executeOwnerOp;
|
|
59
|
+
private ruleFounderGated;
|
|
60
|
+
}
|
|
61
|
+
|
|
7
62
|
interface AgentRunnerOptions {
|
|
8
63
|
identity: AgentIdentity;
|
|
9
64
|
brain: RuntimeBrainConfig;
|
|
@@ -13,6 +68,8 @@ interface AgentRunnerOptions {
|
|
|
13
68
|
logger?: (event: Record<string, unknown>) => void;
|
|
14
69
|
onTaskExecuted?: (result: ExecutionResult, task: BoardTask) => Promise<void>;
|
|
15
70
|
auditLog?: AuditLog;
|
|
71
|
+
/** Optional delegated-authority handler for governance message processing (E4). */
|
|
72
|
+
messageHandler?: DelegatedAuthorityHandler;
|
|
16
73
|
}
|
|
17
74
|
declare class AgentRunner {
|
|
18
75
|
private readonly opts;
|
package/dist/runner.js
CHANGED
|
@@ -53,7 +53,8 @@ function buildCaelRecord(input) {
|
|
|
53
53
|
prev_hash: prevChain,
|
|
54
54
|
fnv1a_chain,
|
|
55
55
|
version_vector_fingerprint: `agent@${runtimeVersion}|brain@${brainClassOf(brain)}|provider@${identity.llmProvider}|model@${identity.llmModel}`,
|
|
56
|
-
brain_class: brainClassOf(brain)
|
|
56
|
+
brain_class: brainClassOf(brain),
|
|
57
|
+
trust_epoch: "post-w107"
|
|
57
58
|
};
|
|
58
59
|
}
|
|
59
60
|
|
|
@@ -73,11 +74,7 @@ var ALLOWED_WRITE_ROOTS = [
|
|
|
73
74
|
"/root/agent-output"
|
|
74
75
|
// Single write sink — keeps deliverables in one place
|
|
75
76
|
];
|
|
76
|
-
var
|
|
77
|
-
"lake build",
|
|
78
|
-
"lake env",
|
|
79
|
-
"lake clean",
|
|
80
|
-
"lean ",
|
|
77
|
+
var BASH_READ_ONLY_PREFIXES = [
|
|
81
78
|
"ls ",
|
|
82
79
|
"ls\n",
|
|
83
80
|
"ls$",
|
|
@@ -92,12 +89,24 @@ var BASH_WHITELIST = [
|
|
|
92
89
|
"git log",
|
|
93
90
|
"git diff",
|
|
94
91
|
"git show",
|
|
92
|
+
"pwd",
|
|
93
|
+
"echo ",
|
|
94
|
+
"lake env"
|
|
95
|
+
];
|
|
96
|
+
var BASH_PRODUCTIVE_PREFIXES = [
|
|
97
|
+
"lake build",
|
|
98
|
+
"lake clean",
|
|
99
|
+
"lean ",
|
|
95
100
|
"pnpm --filter",
|
|
96
101
|
"pnpm vitest",
|
|
97
|
-
"vitest run"
|
|
98
|
-
"pwd",
|
|
99
|
-
"echo "
|
|
102
|
+
"vitest run"
|
|
100
103
|
];
|
|
104
|
+
var BASH_WHITELIST = [...BASH_READ_ONLY_PREFIXES, ...BASH_PRODUCTIVE_PREFIXES];
|
|
105
|
+
function isProductiveBashCommand(cmd) {
|
|
106
|
+
const trimmed = String(cmd ?? "").trim();
|
|
107
|
+
if (!trimmed) return false;
|
|
108
|
+
return BASH_PRODUCTIVE_PREFIXES.some((prefix) => trimmed.startsWith(prefix.trim()));
|
|
109
|
+
}
|
|
101
110
|
var MESH_TOOLS = [
|
|
102
111
|
{
|
|
103
112
|
name: "read_file",
|
|
@@ -220,6 +229,13 @@ ${result.stderr || result.stdout}`);
|
|
|
220
229
|
}
|
|
221
230
|
}
|
|
222
231
|
function runBash(cmd, cwd) {
|
|
232
|
+
if (process.env.VITEST === "true" || process.env.NODE_ENV === "test") {
|
|
233
|
+
return Promise.resolve({
|
|
234
|
+
code: 0,
|
|
235
|
+
stdout: `[mock-bash under vitest] cmd="${cmd}" cwd="${cwd}"`,
|
|
236
|
+
stderr: ""
|
|
237
|
+
});
|
|
238
|
+
}
|
|
223
239
|
return new Promise((resolveProm) => {
|
|
224
240
|
const child = spawn("bash", ["-c", cmd], { cwd, env: process.env });
|
|
225
241
|
let stdout = "";
|
|
@@ -288,6 +304,35 @@ var AgentRunner = class {
|
|
|
288
304
|
const { identity, brain, mesh, costGuard, provider, logger } = this.opts;
|
|
289
305
|
const log = logger ?? (() => void 0);
|
|
290
306
|
await this.heartbeatWithAutoRejoin();
|
|
307
|
+
if (this.opts.messageHandler) {
|
|
308
|
+
try {
|
|
309
|
+
const receipts = await this.opts.messageHandler.processMessages();
|
|
310
|
+
if (receipts.length > 0) {
|
|
311
|
+
log({
|
|
312
|
+
ev: "messages-processed",
|
|
313
|
+
count: receipts.length,
|
|
314
|
+
statuses: receipts.map((r) => r.status)
|
|
315
|
+
});
|
|
316
|
+
if (brain.capabilityTags.length === 0 || brain.capabilityTags.every((t) => t.startsWith("delegated"))) {
|
|
317
|
+
return {
|
|
318
|
+
action: "messages-processed",
|
|
319
|
+
spentUsd: costGuard.getState().spentUsd,
|
|
320
|
+
remainingUsd: costGuard.getRemainingUsd(),
|
|
321
|
+
receipts: receipts.map((r) => ({
|
|
322
|
+
status: r.status,
|
|
323
|
+
action: r.action,
|
|
324
|
+
reason: r.reason
|
|
325
|
+
}))
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
} catch (err) {
|
|
330
|
+
log({
|
|
331
|
+
ev: "message-handler-error",
|
|
332
|
+
message: err instanceof Error ? err.message : String(err)
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
}
|
|
291
336
|
if (costGuard.isOverBudget()) {
|
|
292
337
|
const state = costGuard.getState();
|
|
293
338
|
log({ ev: "over-budget", spentUsd: state.spentUsd, budget: identity.budgetUsdPerDay });
|
|
@@ -321,6 +366,8 @@ var AgentRunner = class {
|
|
|
321
366
|
const MAX_TOOL_ITERS = 30;
|
|
322
367
|
let lastResponse;
|
|
323
368
|
const toolsCalled = /* @__PURE__ */ new Set();
|
|
369
|
+
let productiveCallCount = 0;
|
|
370
|
+
let lastCommitHash;
|
|
324
371
|
while (true) {
|
|
325
372
|
iters++;
|
|
326
373
|
if (iters > MAX_TOOL_ITERS) {
|
|
@@ -345,12 +392,31 @@ var AgentRunner = class {
|
|
|
345
392
|
};
|
|
346
393
|
if (resp.finishReason === "tool_use" && resp.toolUses && resp.toolUses.length > 0) {
|
|
347
394
|
log({ ev: "tool-call", taskId: target.id, iter: iters, tools: resp.toolUses.map((t) => t.name) });
|
|
348
|
-
for (const u of resp.toolUses)
|
|
395
|
+
for (const u of resp.toolUses) {
|
|
396
|
+
toolsCalled.add(u.name);
|
|
397
|
+
if (u.name === "write_file") {
|
|
398
|
+
const content = String(u.input?.content ?? "");
|
|
399
|
+
if (content.length > 0) productiveCallCount++;
|
|
400
|
+
} else if (u.name === "bash") {
|
|
401
|
+
const cmd = String(u.input?.cmd ?? "");
|
|
402
|
+
if (isProductiveBashCommand(cmd)) productiveCallCount++;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
349
405
|
messages.push({
|
|
350
406
|
role: "assistant",
|
|
351
407
|
content: resp.assistantBlocks ?? []
|
|
352
408
|
});
|
|
353
409
|
const toolResults = await Promise.all(resp.toolUses.map((u) => runTool(u)));
|
|
410
|
+
for (let ti = 0; ti < resp.toolUses.length; ti++) {
|
|
411
|
+
const tu = resp.toolUses[ti];
|
|
412
|
+
if (tu.name === "bash") {
|
|
413
|
+
const tr = toolResults[ti];
|
|
414
|
+
if (tr && !tr.is_error) {
|
|
415
|
+
const shaMatch = tr.content.match(/\b([0-9a-f]{7,40})\b/);
|
|
416
|
+
if (shaMatch) lastCommitHash = shaMatch[1];
|
|
417
|
+
}
|
|
418
|
+
}
|
|
419
|
+
}
|
|
354
420
|
messages.push({
|
|
355
421
|
role: "user",
|
|
356
422
|
content: toolResults
|
|
@@ -361,22 +427,21 @@ var AgentRunner = class {
|
|
|
361
427
|
break;
|
|
362
428
|
}
|
|
363
429
|
const durationMs = Date.now() - start;
|
|
364
|
-
|
|
365
|
-
const sideEffectingCalled = [...toolsCalled].some((t) => SIDE_EFFECTING_TOOLS.has(t));
|
|
366
|
-
if (!sideEffectingCalled) {
|
|
430
|
+
if (productiveCallCount === 0) {
|
|
367
431
|
log({
|
|
368
432
|
ev: "no-artifact",
|
|
369
433
|
taskId: target.id,
|
|
370
434
|
tool_iters: iters,
|
|
371
435
|
toolsCalled: [...toolsCalled],
|
|
372
|
-
|
|
436
|
+
productiveCallCount,
|
|
437
|
+
message: "task execution did not produce a real artifact \u2014 refusing to mark executed. Required: write_file with non-empty content OR bash with a productive prefix (lake build / pnpm --filter / vitest run / lean / pnpm vitest). Pure-text, read-only inspection, and trivial-bash-bypass (`echo`, `cat`, etc.) do not satisfy the gate."
|
|
373
438
|
});
|
|
374
439
|
return {
|
|
375
440
|
action: "no-artifact",
|
|
376
441
|
taskId: target.id,
|
|
377
442
|
spentUsd: costGuard.getState().spentUsd,
|
|
378
443
|
remainingUsd: costGuard.getRemainingUsd(),
|
|
379
|
-
message: `no
|
|
444
|
+
message: `no productive tool call observed (toolsCalled=[${[...toolsCalled].join(",")}], productiveCallCount=${productiveCallCount}, iters=${iters})`
|
|
380
445
|
};
|
|
381
446
|
}
|
|
382
447
|
const cost = costGuard.recordUsage(identity.llmModel, aggUsage);
|
|
@@ -436,6 +501,12 @@ var AgentRunner = class {
|
|
|
436
501
|
${response.content}`
|
|
437
502
|
);
|
|
438
503
|
}
|
|
504
|
+
try {
|
|
505
|
+
await mesh.markDone(target.id, finalText.slice(0, 500), lastCommitHash);
|
|
506
|
+
log({ ev: "mark-done", taskId: target.id, commitHash: lastCommitHash });
|
|
507
|
+
} catch (err) {
|
|
508
|
+
log({ ev: "mark-done-error", taskId: target.id, message: err instanceof Error ? err.message : String(err) });
|
|
509
|
+
}
|
|
439
510
|
return {
|
|
440
511
|
action: "executed",
|
|
441
512
|
taskId: target.id,
|
package/dist/runner.js.map
CHANGED
|
@@ -1 +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,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I;AAAA,UACJ,SAAS,mBAAmB,QAAQ,QAAQ,UAAU,OAAO,OAAO;AAAA,QACtE,CAAC;AACD,cAAM;AAAA,MACR;AAIA,YAAM,KAAK,UAAU,EAAE,WAAW,SAAS,QAAQ,SAAS,SAAS,QAAQ,CAAC;AAC9E,UAAI,EAAE,IAAI,kCAAkC,CAAC;AAAA,IAC/C;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUQ,kBAAkB,KAAuB;AAC/C,UAAM,MAAM,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC3D,WAAO,QAAQ,KAAK,GAAG,KAAK,gBAAgB,KAAK,GAAG;AAAA,EACtD;AACF;AAEA,SAAS,gBAAgB,MAAyB;AAChD,SAAO;AAAA,IACL,0BAA0B,KAAK,EAAE;AAAA,IACjC,UAAU,KAAK,KAAK;AAAA,IACpB,aAAa,KAAK,QAAQ;AAAA,IAC1B,UAAU,KAAK,QAAQ,CAAC,GAAG,KAAK,IAAI,CAAC;AAAA,IACrC;AAAA,IACA;AAAA,IACA,KAAK,eAAe;AAAA,IACpB;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb;AAEA,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,EAAE,CAAC;AAC7C;AAEA,SAAS,OAAO,MAAsB;AACpC,SAAO,KAAK,OAAO,KAAK,OAAO,IAAI,OAAO,OAAO,GAAG;AACtD;","names":[]}
|
|
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 interface TeamMessage {\n id: string;\n fromAgentId: string;\n fromAgentName: string;\n content: string;\n messageType: string;\n createdAt: string;\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 // ── Team Message Surface (E4 delegated-authority protocol) ───────────────────\n\n /** Read recent team messages. */\n async getTeamMessages(limit = 20): Promise<TeamMessage[]> {\n const data = await this.req<{ messages?: TeamMessage[]; success?: boolean }>(\n 'GET',\n `/team/${this.teamId}/messages?limit=${limit}`\n );\n return data.messages ?? [];\n }\n\n /** Post a message to the team feed. */\n async sendTeamMessage(content: string, messageType = 'text'): Promise<void> {\n await this.req('POST', `/team/${this.teamId}/message`, {\n content,\n type: messageType,\n });\n }\n\n // ── Owner-op API wrappers (E4) ─────────────────────────────────────────────\n\n /** Switch team mode. Requires owner or founder role. */\n async setTeamMode(mode: string, reason?: string): Promise<{ mode: string; unchanged?: boolean }> {\n return this.req('POST', `/team/${this.teamId}/mode`, { mode, reason });\n }\n\n /** Update room preferences. Requires config:write permission. */\n async patchRoomPrefs(prefs: { communicationStyle?: string; objective?: string }): Promise<{\n communicationStyle: string;\n objective: string;\n }> {\n return this.req('PATCH', `/team/${this.teamId}/room`, prefs);\n }\n\n /** Update a board task. */\n async updateTask(\n taskId: string,\n updates: {\n title?: string;\n description?: string;\n priority?: number;\n tags?: string[];\n }\n ): Promise<unknown> {\n return this.req('PATCH', `/team/${this.teamId}/board/${taskId}`, {\n action: 'update',\n ...updates,\n });\n }\n\n /** Delete a board task. */\n async deleteTask(taskId: string): Promise<unknown> {\n return this.req('PATCH', `/team/${this.teamId}/board/${taskId}`, {\n action: 'delete',\n });\n }\n\n /** Delegate a board task to another agent. */\n async delegateTask(taskId: string, toAgentId: string): Promise<unknown> {\n return this.req('PATCH', `/team/${this.teamId}/board/${taskId}`, {\n action: 'delegate',\n toAgentId,\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 * Trust-epoch tag for downstream consumers (Paper 25 gate clock,\n * fleet-health drift detector, retroactive corpus filters). Set to\n * `'post-w107'` for any record built after the 2026-04-26 W.107\n * artifact-grounding gate landed (HoloScript commit 4aab897ad). Records\n * without this field — i.e. anything in the audit store before the gate\n * was deployed — are implicitly `'pre-w107-untrusted'`. The mesh-worker-02\n * 27.5h hallucination class (fabricated \"100 scenes validated\" CAEL\n * records with no actual artifact) all live in the implicit-untrusted\n * cohort. Consumers should filter by `trust_epoch === 'post-w107'`\n * before treating CAEL records as evidence of real work.\n */\n trust_epoch?: 'post-w107';\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 trust_epoch: 'post-w107',\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).\n//\n// Two-tier classification (W.107 tightening 2026-04-26):\n// READ_ONLY — observation-only commands. Pass execution policy, but do\n// NOT count as artifact-producing for the W.107 gate.\n// PRODUCTIVE — commands that build, test, or otherwise produce a real\n// artifact (compile output, test result, etc.). DO count as\n// artifact-producing for the W.107 gate.\n//\n// Pre-tightening, the gate accepted ANY bash call as side-effecting — so\n// `bash echo done` would falsely pass the gate. Now `echo` is read-only and\n// the worker must call something productive (lake build / pnpm --filter\n// build / vitest run / lean compile / etc.) to claim `executed`.\nconst BASH_READ_ONLY_PREFIXES = [\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 'pwd',\n 'echo ',\n 'lake env',\n];\n\nconst BASH_PRODUCTIVE_PREFIXES = [\n 'lake build', 'lake clean',\n 'lean ',\n 'pnpm --filter',\n 'pnpm vitest', 'vitest run',\n];\n\nconst BASH_WHITELIST = [...BASH_READ_ONLY_PREFIXES, ...BASH_PRODUCTIVE_PREFIXES];\n\n/**\n * Returns true iff `cmd` matches a productive prefix — i.e. would produce a\n * real artifact (compile/test/build output) rather than just observing state.\n * Used by the W.107 artifact-grounding gate in runner.ts.\n */\nexport function isProductiveBashCommand(cmd: string): boolean {\n const trimmed = String(cmd ?? '').trim();\n if (!trimmed) return false;\n return BASH_PRODUCTIVE_PREFIXES.some((prefix) => trimmed.startsWith(prefix.trim()));\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 // Test short-circuit (task_1778113854009_x6p3): under vitest, return a\n // fast synthetic exit instead of spawning bash. Without this, mocks that\n // emit a \"vitest run\" tool_use cause runner.test.ts to recursively spawn\n // vitest startup per tick (~1.7s each), pushing 3-tick tests over the\n // 5000ms timeout. Production paths (NODE_ENV != 'test', VITEST unset)\n // are unchanged and still spawn the real shell.\n if (process.env.VITEST === 'true' || process.env.NODE_ENV === 'test') {\n return Promise.resolve({\n code: 0,\n stdout: `[mock-bash under vitest] cmd=\"${cmd}\" cwd=\"${cwd}\"`,\n stderr: '',\n });\n }\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, isProductiveBashCommand } from './tools.js';\nimport { DelegatedAuthorityHandler } from './delegated-authority.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 /** Optional delegated-authority handler for governance message processing (E4). */\n messageHandler?: DelegatedAuthorityHandler;\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 // ── Delegated-authority message processing (E4) ──────────────────────────\n // Run before budget/task claiming so governance requests are handled\n // even when the agent is over-budget or has no claimable tasks.\n if (this.opts.messageHandler) {\n try {\n const receipts = await this.opts.messageHandler.processMessages();\n if (receipts.length > 0) {\n log({\n ev: 'messages-processed',\n count: receipts.length,\n statuses: receipts.map((r) => r.status),\n });\n // If this agent has no board-task capability tags (Brittney is\n // governance-only), return early so the tick result reflects message\n // work rather than falling through to no-claimable-task.\n if (brain.capabilityTags.length === 0 || brain.capabilityTags.every((t) => t.startsWith('delegated'))) {\n return {\n action: 'messages-processed',\n spentUsd: costGuard.getState().spentUsd,\n remainingUsd: costGuard.getRemainingUsd(),\n receipts: receipts.map((r) => ({\n status: r.status,\n action: r.action,\n reason: r.reason,\n })),\n };\n }\n }\n } catch (err) {\n log({\n ev: 'message-handler-error',\n message: err instanceof Error ? err.message : String(err),\n });\n }\n }\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 // Tightened-gate counter (W.107.b 2026-04-26): track *productive* tool calls\n // separately from any tool call. A productive call is one of:\n // - write_file with non-empty content\n // - bash matching a productive prefix (lake build / pnpm --filter / vitest\n // run / lean / pnpm vitest — see tools.ts BASH_PRODUCTIVE_PREFIXES)\n // Read-only bash (cat/grep/ls/echo/git status/etc.) does NOT count even\n // though it's whitelisted for execution. This catches the trivial-bash-bypass\n // class (e.g. `bash echo done`) that the original W.107 gate accepted.\n let productiveCallCount = 0;\n // Last git commit SHA emitted during the tool-loop; forwarded to markDone\n // so the board task records a verifiable commit reference.\n let lastCommitHash: string | undefined;\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) {\n toolsCalled.add(u.name);\n // Productive-call accounting (W.107.b tighter gate).\n if (u.name === 'write_file') {\n const content = String((u.input as Record<string, unknown>)?.content ?? '');\n if (content.length > 0) productiveCallCount++;\n } else if (u.name === 'bash') {\n const cmd = String((u.input as Record<string, unknown>)?.cmd ?? '');\n if (isProductiveBashCommand(cmd)) productiveCallCount++;\n }\n }\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 // Extract the latest git commit SHA from bash stdout so markDone can\n // record a verifiable reference on the board task. Pattern matches both\n // `git commit -m` output ('[branch abc1234]') and `git rev-parse HEAD`.\n for (let ti = 0; ti < resp.toolUses.length; ti++) {\n const tu = resp.toolUses[ti];\n if (tu.name === 'bash') {\n const tr = toolResults[ti];\n if (tr && !tr.is_error) {\n const shaMatch = tr.content.match(/\\b([0-9a-f]{7,40})\\b/);\n if (shaMatch) lastCommitHash = shaMatch[1];\n }\n }\n }\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; 2026-04-26\n // tightened to W.107.b which also closes the trivial-bash bypass: `bash echo\n // done` and `write_file /tmp/x \"\"` no longer pass the gate). The gate now\n // requires AT LEAST ONE productive call:\n // - write_file with non-empty content, OR\n // - bash matching a productive prefix (lake build / pnpm --filter /\n // vitest run / lean / pnpm vitest)\n // Read-only inspection tools (read_file, list_dir) and read-only bash\n // (cat/grep/ls/echo/git status/git log/...) don't satisfy the gate.\n if (productiveCallCount === 0) {\n log({\n ev: 'no-artifact',\n taskId: target.id,\n tool_iters: iters,\n toolsCalled: [...toolsCalled],\n productiveCallCount,\n message:\n 'task execution did not produce a real artifact — refusing to mark executed. ' +\n 'Required: write_file with non-empty content OR bash with a productive prefix ' +\n '(lake build / pnpm --filter / vitest run / lean / pnpm vitest). ' +\n 'Pure-text, read-only inspection, and trivial-bash-bypass (`echo`, `cat`, etc.) do not satisfy the gate.',\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 productive tool call observed (toolsCalled=[${[...toolsCalled].join(',')}], productiveCallCount=${productiveCallCount}, 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 // Mark the task done so it doesn't linger in 'claimed' forever.\n // Wrapped in try/catch: a markDone failure (e.g. task already closed by\n // a supervisor, or transient network error) must not prevent the tick\n // return value from reaching the caller.\n try {\n await mesh.markDone(target.id, finalText.slice(0, 500), lastCommitHash);\n log({ ev: 'mark-done', taskId: target.id, commitHash: lastCommitHash });\n } catch (err) {\n log({ ev: 'mark-done-error', taskId: target.id, message: err instanceof Error ? err.message : String(err) });\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":";AAyNO,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,CAAC,MAAM,EAAE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AA,IACrC;AAAA,IACA;AAAA,IACA,KAAK,eAAe;AAAA,IACpB;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb;AAEA,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,MAAM,WAAW,GAAG,EAAE,CAAC;AAC7C;AAEA,SAAS,OAAO,MAAsB;AACpC,SAAO,KAAK,OAAO,KAAK,OAAO,IAAI,OAAO,OAAO,GAAG;AACtD;","names":[]}
|
|
@@ -4,6 +4,8 @@ var VALID_PROVIDERS = /* @__PURE__ */ new Set([
|
|
|
4
4
|
"anthropic",
|
|
5
5
|
"openai",
|
|
6
6
|
"gemini",
|
|
7
|
+
"xai",
|
|
8
|
+
"openrouter",
|
|
7
9
|
"mock",
|
|
8
10
|
"bitnet",
|
|
9
11
|
"local-llm"
|
|
@@ -17,16 +19,21 @@ function parseSupervisorConfig(raw) {
|
|
|
17
19
|
const data = JSON.parse(raw);
|
|
18
20
|
if (!isObject(data)) throw new Error("Supervisor config must be a JSON object");
|
|
19
21
|
if (!Array.isArray(data.agents)) throw new Error("Supervisor config.agents must be an array");
|
|
20
|
-
if (data.agents.length === 0)
|
|
22
|
+
if (data.agents.length === 0)
|
|
23
|
+
throw new Error("Supervisor config.agents must have at least one entry");
|
|
21
24
|
const seenHandles = /* @__PURE__ */ new Set();
|
|
22
|
-
const agents = data.agents.map(
|
|
25
|
+
const agents = data.agents.map(
|
|
26
|
+
(entry, idx) => validateAgent(entry, idx, seenHandles)
|
|
27
|
+
);
|
|
23
28
|
const globalBudgetUsdPerDay = optionalNumber(data, "globalBudgetUsdPerDay");
|
|
24
29
|
const defaultTickIntervalMs = optionalNumber(data, "defaultTickIntervalMs");
|
|
25
30
|
if (globalBudgetUsdPerDay != null && globalBudgetUsdPerDay <= 0) {
|
|
26
31
|
throw new Error(`globalBudgetUsdPerDay must be positive, got ${globalBudgetUsdPerDay}`);
|
|
27
32
|
}
|
|
28
33
|
if (defaultTickIntervalMs != null && defaultTickIntervalMs < 5e3) {
|
|
29
|
-
throw new Error(
|
|
34
|
+
throw new Error(
|
|
35
|
+
`defaultTickIntervalMs must be >= 5000ms (mesh-friendly), got ${defaultTickIntervalMs}`
|
|
36
|
+
);
|
|
30
37
|
}
|
|
31
38
|
return { agents, globalBudgetUsdPerDay, defaultTickIntervalMs };
|
|
32
39
|
}
|
|
@@ -49,8 +56,8 @@ function validateAgent(entry, idx, seen) {
|
|
|
49
56
|
throw new Error(`agents[${idx}].scopeTier "${scopeTier}" must be cold | warm | hot`);
|
|
50
57
|
}
|
|
51
58
|
const budgetUsdPerDay = optionalNumber(entry, "budgetUsdPerDay");
|
|
52
|
-
if (budgetUsdPerDay != null && budgetUsdPerDay
|
|
53
|
-
throw new Error(`agents[${idx}].budgetUsdPerDay must be
|
|
59
|
+
if (budgetUsdPerDay != null && budgetUsdPerDay < 0) {
|
|
60
|
+
throw new Error(`agents[${idx}].budgetUsdPerDay must be >= 0 (0 = unlimited), got ${budgetUsdPerDay}`);
|
|
54
61
|
}
|
|
55
62
|
const tickIntervalMs = optionalNumber(entry, "tickIntervalMs");
|
|
56
63
|
if (tickIntervalMs != null && tickIntervalMs < 5e3) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/supervisor-config.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport type { LLMProviderName } from '@holoscript/llm-provider';\n\nexport interface AgentSpec {\n handle: string;\n brainPath: string;\n provider: LLMProviderName;\n model: string;\n walletEnvKey: string;\n bearerEnvKey: string;\n budgetUsdPerDay?: number;\n scopeTier?: 'cold' | 'warm' | 'hot';\n enabled?: boolean;\n tickIntervalMs?: number;\n enableCommitHook?: boolean;\n outputDir?: string;\n workingDir?: string;\n}\n\nexport interface SupervisorConfig {\n agents: AgentSpec[];\n globalBudgetUsdPerDay?: number;\n defaultTickIntervalMs?: number;\n}\n\nconst VALID_PROVIDERS: ReadonlySet<LLMProviderName> = new Set([\n 'anthropic',\n 'openai',\n 'gemini',\n 'mock',\n 'bitnet',\n 'local-llm',\n]);\n\nconst VALID_TIERS: ReadonlySet<string> = new Set(['cold', 'warm', 'hot']);\nconst HANDLE_PATTERN = /^[a-z0-9_-]{1,64}$/i;\n\nexport function loadSupervisorConfig(path: string): SupervisorConfig {\n return parseSupervisorConfig(readFileSync(path, 'utf8'));\n}\n\nexport function parseSupervisorConfig(raw: string): SupervisorConfig {\n const data = JSON.parse(raw) as unknown;\n if (!isObject(data)) throw new Error('Supervisor config must be a JSON object');\n if (!Array.isArray(data.agents)) throw new Error('Supervisor config.agents must be an array');\n if (data.agents.length === 0)
|
|
1
|
+
{"version":3,"sources":["../src/supervisor-config.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport type { LLMProviderName } from '@holoscript/llm-provider';\n\nexport interface AgentSpec {\n handle: string;\n brainPath: string;\n provider: LLMProviderName;\n model: string;\n walletEnvKey: string;\n bearerEnvKey: string;\n budgetUsdPerDay?: number;\n scopeTier?: 'cold' | 'warm' | 'hot';\n enabled?: boolean;\n tickIntervalMs?: number;\n enableCommitHook?: boolean;\n outputDir?: string;\n workingDir?: string;\n}\n\nexport interface SupervisorConfig {\n agents: AgentSpec[];\n globalBudgetUsdPerDay?: number;\n defaultTickIntervalMs?: number;\n}\n\n// Mirror of VALID_PROVIDERS in identity.ts. Deduplication is a separate\n// task — both Sets must stay in sync until then. Single-source-of-truth\n// via LLMProviderName-derived runtime Set is the clean fix (W.GOLD.006).\nconst VALID_PROVIDERS: ReadonlySet<LLMProviderName> = new Set([\n 'anthropic',\n 'openai',\n 'gemini',\n 'xai',\n 'openrouter',\n 'mock',\n 'bitnet',\n 'local-llm',\n]);\n\nconst VALID_TIERS: ReadonlySet<string> = new Set(['cold', 'warm', 'hot']);\nconst HANDLE_PATTERN = /^[a-z0-9_-]{1,64}$/i;\n\nexport function loadSupervisorConfig(path: string): SupervisorConfig {\n return parseSupervisorConfig(readFileSync(path, 'utf8'));\n}\n\nexport function parseSupervisorConfig(raw: string): SupervisorConfig {\n const data = JSON.parse(raw) as unknown;\n if (!isObject(data)) throw new Error('Supervisor config must be a JSON object');\n if (!Array.isArray(data.agents)) throw new Error('Supervisor config.agents must be an array');\n if (data.agents.length === 0)\n throw new Error('Supervisor config.agents must have at least one entry');\n\n const seenHandles = new Set<string>();\n const agents: AgentSpec[] = data.agents.map((entry, idx) =>\n validateAgent(entry, idx, seenHandles)\n );\n\n const globalBudgetUsdPerDay = optionalNumber(data, 'globalBudgetUsdPerDay');\n const defaultTickIntervalMs = optionalNumber(data, 'defaultTickIntervalMs');\n if (globalBudgetUsdPerDay != null && globalBudgetUsdPerDay <= 0) {\n throw new Error(`globalBudgetUsdPerDay must be positive, got ${globalBudgetUsdPerDay}`);\n }\n if (defaultTickIntervalMs != null && defaultTickIntervalMs < 5000) {\n throw new Error(\n `defaultTickIntervalMs must be >= 5000ms (mesh-friendly), got ${defaultTickIntervalMs}`\n );\n }\n\n return { agents, globalBudgetUsdPerDay, defaultTickIntervalMs };\n}\n\nfunction validateAgent(entry: unknown, idx: number, seen: Set<string>): AgentSpec {\n if (!isObject(entry)) throw new Error(`agents[${idx}] must be an object`);\n const handle = requiredString(entry, 'handle', `agents[${idx}].handle`);\n if (!HANDLE_PATTERN.test(handle)) {\n throw new Error(`agents[${idx}].handle \"${handle}\" must match ${HANDLE_PATTERN}`);\n }\n if (seen.has(handle)) throw new Error(`Duplicate agent handle: \"${handle}\"`);\n seen.add(handle);\n\n const provider = requiredString(entry, 'provider', `agents[${idx}].provider`);\n if (!VALID_PROVIDERS.has(provider as LLMProviderName)) {\n throw new Error(\n `agents[${idx}].provider \"${provider}\" not in [${[...VALID_PROVIDERS].join(', ')}]`\n );\n }\n\n const scopeTier = optionalString(entry, 'scopeTier');\n if (scopeTier && !VALID_TIERS.has(scopeTier)) {\n throw new Error(`agents[${idx}].scopeTier \"${scopeTier}\" must be cold | warm | hot`);\n }\n\n const budgetUsdPerDay = optionalNumber(entry, 'budgetUsdPerDay');\n if (budgetUsdPerDay != null && budgetUsdPerDay < 0) {\n throw new Error(`agents[${idx}].budgetUsdPerDay must be >= 0 (0 = unlimited), got ${budgetUsdPerDay}`);\n }\n const tickIntervalMs = optionalNumber(entry, 'tickIntervalMs');\n if (tickIntervalMs != null && tickIntervalMs < 5000) {\n throw new Error(`agents[${idx}].tickIntervalMs must be >= 5000ms, got ${tickIntervalMs}`);\n }\n\n return {\n handle,\n brainPath: requiredString(entry, 'brainPath', `agents[${idx}].brainPath`),\n provider: provider as LLMProviderName,\n model: requiredString(entry, 'model', `agents[${idx}].model`),\n walletEnvKey: requiredString(entry, 'walletEnvKey', `agents[${idx}].walletEnvKey`),\n bearerEnvKey: requiredString(entry, 'bearerEnvKey', `agents[${idx}].bearerEnvKey`),\n budgetUsdPerDay,\n scopeTier: scopeTier as 'cold' | 'warm' | 'hot' | undefined,\n enabled: optionalBoolean(entry, 'enabled'),\n tickIntervalMs,\n enableCommitHook: optionalBoolean(entry, 'enableCommitHook'),\n outputDir: optionalString(entry, 'outputDir'),\n workingDir: optionalString(entry, 'workingDir'),\n };\n}\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === 'object' && v !== null && !Array.isArray(v);\n}\n\nfunction requiredString(obj: Record<string, unknown>, key: string, label: string): string {\n const v = obj[key];\n if (typeof v !== 'string' || v.trim().length === 0) {\n throw new Error(`${label} is required and must be a non-empty string`);\n }\n return v.trim();\n}\n\nfunction optionalString(obj: Record<string, unknown>, key: string): string | undefined {\n const v = obj[key];\n if (v === undefined || v === null) return undefined;\n if (typeof v !== 'string') throw new Error(`${key} must be a string when present`);\n return v.trim();\n}\n\nfunction optionalNumber(obj: Record<string, unknown>, key: string): number | undefined {\n const v = obj[key];\n if (v === undefined || v === null) return undefined;\n if (typeof v !== 'number' || !Number.isFinite(v)) {\n throw new Error(`${key} must be a finite number when present`);\n }\n return v;\n}\n\nfunction optionalBoolean(obj: Record<string, unknown>, key: string): boolean | undefined {\n const v = obj[key];\n if (v === undefined || v === null) return undefined;\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