@tangle-network/agent-runtime 6.0.2 → 6.0.3
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/CHANGELOG.md +4 -0
- package/dist/{activation-BRfZOfwb.js → activation-DNqjZEo7.js} +4 -4
- package/dist/{activation-BRfZOfwb.js.map → activation-DNqjZEo7.js.map} +1 -1
- package/dist/agent.js +4 -4
- package/dist/{bundle-vFFiCigS.js → bundle-BET6gl5r.js} +2 -2
- package/dist/{bundle-vFFiCigS.js.map → bundle-BET6gl5r.js.map} +1 -1
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{coordination-manager-RSJg5GmY.js → coordination-manager-CYElgkMI.js} +7 -6
- package/dist/{coordination-manager-RSJg5GmY.js.map → coordination-manager-CYElgkMI.js.map} +1 -1
- package/dist/{coordination-map-routing-DVjW5Gx0.js → coordination-map-routing-CKRNZSaV.js} +2 -2
- package/dist/{coordination-map-routing-DVjW5Gx0.js.map → coordination-map-routing-CKRNZSaV.js.map} +1 -1
- package/dist/{delegate-C0cprMUN.js → delegate-dW2jsqFF.js} +2 -2
- package/dist/{delegate-C0cprMUN.js.map → delegate-dW2jsqFF.js.map} +1 -1
- package/dist/durable.js +12 -11
- package/dist/durable.js.map +1 -1
- package/dist/failure-cause-BzjUUsRz.js +3208 -0
- package/dist/failure-cause-BzjUUsRz.js.map +1 -0
- package/dist/{graph-cEg-gquv.js → graph-A7AvOP1I.js} +7 -6
- package/dist/{graph-cEg-gquv.js.map → graph-A7AvOP1I.js.map} +1 -1
- package/dist/{graph-registry-C-hjRx2t.js → graph-registry-C4ASeL2P.js} +1 -1
- package/dist/{graph-registry-B25FxBZN.js → graph-registry-DbCwfHMY.js} +3 -3
- package/dist/{graph-registry-B25FxBZN.js.map → graph-registry-DbCwfHMY.js.map} +1 -1
- package/dist/{improve-DNl4_6lP.js → improve-4qJclc9J.js} +10 -8
- package/dist/{improve-DNl4_6lP.js.map → improve-4qJclc9J.js.map} +1 -1
- package/dist/index.js +13 -11
- package/dist/index.js.map +1 -1
- package/dist/intelligence.js +8 -8
- package/dist/jsonl-file-BeUa5EDx.js +232 -0
- package/dist/jsonl-file-BeUa5EDx.js.map +1 -0
- package/dist/kernel.js +14 -13
- package/dist/{loop-runner-DQJjowz0.js → loop-runner-DZxVXLLU.js} +2 -2
- package/dist/{loop-runner-DQJjowz0.js.map → loop-runner-DZxVXLLU.js.map} +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.js +7 -7
- package/dist/mcp/memory-bin.js +1 -1
- package/dist/{prepare-B6SQA12v.js → prepare-O1HbzOqs.js} +4 -3
- package/dist/{prepare-B6SQA12v.js.map → prepare-O1HbzOqs.js.map} +1 -1
- package/dist/{profile-DN8Dw2Kp.js → profile-DcRoyryP.js} +2 -2
- package/dist/{profile-DN8Dw2Kp.js.map → profile-DcRoyryP.js.map} +1 -1
- package/dist/{provision-supervisor-CtAaJCUa.js → provision-supervisor-CBeTMpMY.js} +7 -6
- package/dist/{provision-supervisor-CtAaJCUa.js.map → provision-supervisor-CBeTMpMY.js.map} +1 -1
- package/dist/{run-cancellation-BCuu6khW.js → run-cancellation-ZmRSYLu5.js} +4 -3
- package/dist/{run-cancellation-BCuu6khW.js.map → run-cancellation-ZmRSYLu5.js.map} +1 -1
- package/dist/{run-state-ByHiAjUs.js → run-state-Dn2AIE5m.js} +6 -6
- package/dist/{run-state-ByHiAjUs.js.map → run-state-Dn2AIE5m.js.map} +1 -1
- package/dist/{runtime-9EYvBcHG.js → runtime-D5eL70Is.js} +20 -17
- package/dist/{runtime-9EYvBcHG.js.map → runtime-D5eL70Is.js.map} +1 -1
- package/dist/{scope-DzhBJrRN.js → scope-DSm2RW5I.js} +9 -3204
- package/dist/scope-DSm2RW5I.js.map +1 -0
- package/dist/{search-executor-BJRNavck.js → search-executor-1qaSeY70.js} +6 -4
- package/dist/{search-executor-BJRNavck.js.map → search-executor-1qaSeY70.js.map} +1 -1
- package/dist/{server-DH0P6OY_.js → server-Dp4JKuTZ.js} +5 -5
- package/dist/{server-DH0P6OY_.js.map → server-Dp4JKuTZ.js.map} +1 -1
- package/dist/{settle-record-BSDDf9Z4.js → settle-record-DTh0cvF-.js} +2 -2
- package/dist/{settle-record-BSDDf9Z4.js.map → settle-record-DTh0cvF-.js.map} +1 -1
- package/dist/snapshot-Cgj2Wzi6.js +210 -0
- package/dist/snapshot-Cgj2Wzi6.js.map +1 -0
- package/dist/{structural-rollout-DgvJLTO0.js → structural-rollout-BwyAIuww.js} +6 -4
- package/dist/{structural-rollout-DgvJLTO0.js.map → structural-rollout-BwyAIuww.js.map} +1 -1
- package/dist/{supervise-Cqhkb2Oj.js → supervise-C2Do7hEd.js} +11 -10
- package/dist/{supervise-Cqhkb2Oj.js.map → supervise-C2Do7hEd.js.map} +1 -1
- package/dist/{supervision-discovery-DI5GIFBJ.js → supervision-discovery-BNChDps7.js} +5 -4
- package/dist/{supervision-discovery-DI5GIFBJ.js.map → supervision-discovery-BNChDps7.js.map} +1 -1
- package/dist/{supervisor-B6sl14OR.js → supervisor-jXN2xXiU.js} +8 -5
- package/dist/{supervisor-B6sl14OR.js.map → supervisor-jXN2xXiU.js.map} +1 -1
- package/dist/testing.js +13 -13
- package/dist/{tool-server-CZWd_Opp.js → tool-server-B9q2dtnW.js} +11 -8
- package/dist/tool-server-B9q2dtnW.js.map +1 -0
- package/dist/{top-web-DGoXGxH8.js → top-web-CQNkrh_j.js} +7 -6
- package/dist/{top-web-DGoXGxH8.js.map → top-web-CQNkrh_j.js.map} +1 -1
- package/dist/tui/bin.js +3 -3
- package/dist/tui/index.js +2 -2
- package/dist/util-C_cdPNC4.js +653 -0
- package/dist/util-C_cdPNC4.js.map +1 -0
- package/dist/{workspace-streams-BqNM06y4.js → workspace-streams-uB9rRbms.js} +3 -652
- package/dist/workspace-streams-uB9rRbms.js.map +1 -0
- package/package.json +3 -3
- package/dist/jsonl-file-CeVYTIQJ.js +0 -439
- package/dist/jsonl-file-CeVYTIQJ.js.map +0 -1
- package/dist/scope-DzhBJrRN.js.map +0 -1
- package/dist/tool-server-CZWd_Opp.js.map +0 -1
- package/dist/workspace-streams-BqNM06y4.js.map +0 -1
package/dist/intelligence.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { In as createOtelExporter, Ln as flatOtelSpan, Mn as buildLoopOtelSpans, Pn as buildRuntimeEventOtelSpans, vr as authoredAgentIdentity } from "./scope-
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { _ as agentImprovementTargetProfileDiffs, a as reviewAgentImprovementProposal, b as isAgentProfileMeasuredSurface, c as verifyAgentImprovementProposal, d as attachOptimizationActivationReceipt, f as createOptimizationActivationReceipt, g as agentImprovementProfileSurfaceInput, h as agentImprovementProfileSurfaceDigest, i as executeAgentImprovementActivation, l as verifyAgentImprovementReview, m as agentImprovementProfileDiffs, n as createAgentImprovementActivationResult, o as verifyAgentImprovementActivation, p as optimizationActivationReceiptFromMetadata, r as createAgentImprovementProposal, s as verifyAgentImprovementActivationResult, t as createAgentImprovementActivation, u as assertNoCallerOptimizationReceipt, v as assertProfileImprovementTargetsShareIdentity, y as isAgentImprovementProfileSurface } from "./activation-
|
|
7
|
-
import { _ as parseAgentCandidateProfileActivation, a as applyExactAgentProfileDiff, d as createAgentCandidateProfileActivation, g as omitUndefinedObjectFields, m as materializeAgentCandidateProfilePlan, o as assertCandidateProfileBinding, v as parseExactAgentProfile } from "./profile-
|
|
1
|
+
import { In as createOtelExporter, Ln as flatOtelSpan, Mn as buildLoopOtelSpans, Pn as buildRuntimeEventOtelSpans, vr as authoredAgentIdentity } from "./scope-DSm2RW5I.js";
|
|
2
|
+
import { d as resolveRedactor, l as defaultRedactor } from "./snapshot-Cgj2Wzi6.js";
|
|
3
|
+
import { U as resolveAgentEnvironmentProvider } from "./supervisor-jXN2xXiU.js";
|
|
4
|
+
import { a as assertProfileTrainingIsHeldOut, f as addRuntimeUsage, l as rethrowAfterCleanup, m as isUsageAmount, p as createRuntimeUsageTotals, t as improve } from "./improve-4qJclc9J.js";
|
|
5
|
+
import { I as immutableCandidateValue, L as omitTopLevelDigest, M as canonicalCandidateDigest$1, N as canonicalCandidateDocument, j as canonicalCandidateBytes$1, z as verifyCanonicalCandidateDocument } from "./workspace-streams-uB9rRbms.js";
|
|
6
|
+
import { _ as agentImprovementTargetProfileDiffs, a as reviewAgentImprovementProposal, b as isAgentProfileMeasuredSurface, c as verifyAgentImprovementProposal, d as attachOptimizationActivationReceipt, f as createOptimizationActivationReceipt, g as agentImprovementProfileSurfaceInput, h as agentImprovementProfileSurfaceDigest, i as executeAgentImprovementActivation, l as verifyAgentImprovementReview, m as agentImprovementProfileDiffs, n as createAgentImprovementActivationResult, o as verifyAgentImprovementActivation, p as optimizationActivationReceiptFromMetadata, r as createAgentImprovementProposal, s as verifyAgentImprovementActivationResult, t as createAgentImprovementActivation, u as assertNoCallerOptimizationReceipt, v as assertProfileImprovementTargetsShareIdentity, y as isAgentImprovementProfileSurface } from "./activation-DNqjZEo7.js";
|
|
7
|
+
import { _ as parseAgentCandidateProfileActivation, a as applyExactAgentProfileDiff, d as createAgentCandidateProfileActivation, g as omitUndefinedObjectFields, m as materializeAgentCandidateProfilePlan, o as assertCandidateProfileBinding, v as parseExactAgentProfile } from "./profile-DcRoyryP.js";
|
|
8
8
|
import { t as runAnalystLoop } from "./analyst-loop-BZvXCDKy.js";
|
|
9
|
-
import { C as verifiedResourceTextByDigest, S as AGENT_CANDIDATE_EXECUTION_SUPPORT, n as executePreparedAgentCandidate, t as prepareAgentCandidateExecution, w as verifyAgentCandidateBundle, x as exactProcessProviderAsCandidateExecutor, y as createProtectedAgentCandidateModelPort } from "./prepare-
|
|
9
|
+
import { C as verifiedResourceTextByDigest, S as AGENT_CANDIDATE_EXECUTION_SUPPORT, n as executePreparedAgentCandidate, t as prepareAgentCandidateExecution, w as verifyAgentCandidateBundle, x as exactProcessProviderAsCandidateExecutor, y as createProtectedAgentCandidateModelPort } from "./prepare-O1HbzOqs.js";
|
|
10
10
|
import { ATTR, agentIdentityAttributes } from "@tangle-network/agent-trace-contract";
|
|
11
11
|
import { AGENT_IMPROVEMENT_SOURCE_METADATA_KEY, agentCandidateMaterializationReceiptSchema, agentCandidateRunReceiptSchema, agentImprovementSourceMetadata, agentImprovementSourceSchema, agentProfileImprovementArmSchema, applyAgentProfileDiff, candidateExecutionEvidenceSchema, numbersApproximatelyEqual } from "@tangle-network/agent-interface";
|
|
12
12
|
import { CostLedger, contentHash } from "@tangle-network/agent-eval";
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { s as fenceRunWrite } from "./durable-file-DstVeHcj.js";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { closeSync, fstatSync, fsync, fsyncSync, ftruncateSync, openSync, readSync, writeSync } from "node:fs";
|
|
4
|
+
import { promisify } from "node:util";
|
|
5
|
+
// src/content-digest.ts
|
|
6
|
+
function sha256(value) {
|
|
7
|
+
return createHash("sha256").update(value).digest("hex");
|
|
8
|
+
}
|
|
9
|
+
// src/durable/jsonl-append.ts
|
|
10
|
+
async function appendCommittedJsonLine(path, record, acknowledge) {
|
|
11
|
+
const encoded = JSON.stringify(record);
|
|
12
|
+
if (encoded === void 0) throw new TypeError("JSONL records must be JSON serializable");
|
|
13
|
+
let fd;
|
|
14
|
+
try {
|
|
15
|
+
const acknowledged = fenceRunWrite(() => {
|
|
16
|
+
const bytes = Buffer.from(`${prepareJsonlTail(path) ? "\n" : ""}${encoded}\n`);
|
|
17
|
+
fd = openSync(path, "a");
|
|
18
|
+
let offset = 0;
|
|
19
|
+
while (offset < bytes.length) {
|
|
20
|
+
const written = writeSync(fd, bytes, offset, bytes.length - offset);
|
|
21
|
+
if (written <= 0) throw new Error(`append-only file write made no progress at byte ${offset}`);
|
|
22
|
+
offset += written;
|
|
23
|
+
}
|
|
24
|
+
return acknowledge?.(fd);
|
|
25
|
+
});
|
|
26
|
+
await promisify(fsync)(fd);
|
|
27
|
+
return acknowledged;
|
|
28
|
+
} finally {
|
|
29
|
+
if (fd !== void 0) closeSync(fd);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/** Recover only an uncommitted tail. Caller holds the generation fence. @internal */
|
|
33
|
+
function prepareJsonlTail(path) {
|
|
34
|
+
let fd;
|
|
35
|
+
try {
|
|
36
|
+
fd = openSync(path, "r+");
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if (error.code === "ENOENT") return false;
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
try {
|
|
42
|
+
const size = fstatSync(fd).size;
|
|
43
|
+
if (size === 0) return false;
|
|
44
|
+
const last = Buffer.allocUnsafe(1);
|
|
45
|
+
readAt(fd, last, size - 1);
|
|
46
|
+
if (last[0] === 10) return false;
|
|
47
|
+
const chunks = [];
|
|
48
|
+
let end = size;
|
|
49
|
+
let tailStart = 0;
|
|
50
|
+
while (end > 0) {
|
|
51
|
+
const start = Math.max(0, end - 65536);
|
|
52
|
+
const chunk = Buffer.allocUnsafe(end - start);
|
|
53
|
+
readAt(fd, chunk, start);
|
|
54
|
+
const newline = chunk.lastIndexOf(10);
|
|
55
|
+
chunks.push(chunk.subarray(newline + 1));
|
|
56
|
+
if (newline >= 0) {
|
|
57
|
+
tailStart = start + newline + 1;
|
|
58
|
+
break;
|
|
59
|
+
}
|
|
60
|
+
end = start;
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
JSON.parse(Buffer.concat(chunks.reverse()).toString("utf8"));
|
|
64
|
+
return true;
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if (!(error instanceof SyntaxError)) throw error;
|
|
67
|
+
ftruncateSync(fd, tailStart);
|
|
68
|
+
fsyncSync(fd);
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
} finally {
|
|
72
|
+
closeSync(fd);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
function readAt(fd, buffer, position) {
|
|
76
|
+
let offset = 0;
|
|
77
|
+
while (offset < buffer.length) {
|
|
78
|
+
const read = readSync(fd, buffer, offset, buffer.length - offset, position + offset);
|
|
79
|
+
if (read === 0) throw new Error("journal changed while preparing its append tail");
|
|
80
|
+
offset += read;
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
// src/durable/jsonl-file.ts
|
|
84
|
+
/** Parse in-memory evidence with the same commit boundary as streamed journal reads. */
|
|
85
|
+
function parseCommittedJsonLines(text, source) {
|
|
86
|
+
const lines = text.split("\n");
|
|
87
|
+
const records = [];
|
|
88
|
+
for (const [index, line] of lines.entries()) {
|
|
89
|
+
const record = parseRecord(line, source, index + 1, index < lines.length - 1);
|
|
90
|
+
if (record !== void 0) records.push(record.value);
|
|
91
|
+
}
|
|
92
|
+
return records;
|
|
93
|
+
}
|
|
94
|
+
/** Read a fixed file prefix one record at a time, never allocating the whole journal as a string.
|
|
95
|
+
* A reader cannot chase concurrent appends forever. Missing files are empty only when requested;
|
|
96
|
+
* corruption, short reads, and other I/O errors remain failures. Closing the iterator closes the fd. */
|
|
97
|
+
async function* readCommittedJsonLines(path, options = {}) {
|
|
98
|
+
const fs = await import("node:fs/promises");
|
|
99
|
+
let handle;
|
|
100
|
+
try {
|
|
101
|
+
handle = options.handle ?? await fs.open(path, "r");
|
|
102
|
+
} catch (error) {
|
|
103
|
+
if (options.allowMissing && isNoEntError(error)) return;
|
|
104
|
+
throw error;
|
|
105
|
+
}
|
|
106
|
+
try {
|
|
107
|
+
const start = options.start ?? 0;
|
|
108
|
+
const end = options.end ?? (await handle.stat()).size;
|
|
109
|
+
if (end <= start) return;
|
|
110
|
+
const fragments = [];
|
|
111
|
+
let offset = start;
|
|
112
|
+
let lineNumber = 1;
|
|
113
|
+
const parse = (terminated) => {
|
|
114
|
+
const bytes = Buffer.concat(fragments);
|
|
115
|
+
let line;
|
|
116
|
+
try {
|
|
117
|
+
line = options.strictUtf8 ? new TextDecoder("utf-8", { fatal: true }).decode(bytes) : bytes.toString("utf8");
|
|
118
|
+
} catch (cause) {
|
|
119
|
+
if (!terminated) return void 0;
|
|
120
|
+
throw new Error(`${path}: malformed UTF-8 at line ${lineNumber}`, { cause });
|
|
121
|
+
}
|
|
122
|
+
return parseRecord(line, path, lineNumber++, terminated, options.allowWhitespaceLines);
|
|
123
|
+
};
|
|
124
|
+
let position = start;
|
|
125
|
+
while (position < end) {
|
|
126
|
+
const buffer = Buffer.alloc(Math.min(65536, end - position));
|
|
127
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, position);
|
|
128
|
+
if (bytesRead === 0) throw new Error(`${path}: journal changed while reading its committed prefix`);
|
|
129
|
+
position += bytesRead;
|
|
130
|
+
const bytes = buffer.subarray(0, bytesRead);
|
|
131
|
+
options.onBytes?.(bytes);
|
|
132
|
+
let start = 0;
|
|
133
|
+
for (let end = bytes.indexOf(10); end !== -1; end = bytes.indexOf(10, start)) {
|
|
134
|
+
fragments.push(bytes.subarray(start, end));
|
|
135
|
+
const record = parse(true);
|
|
136
|
+
offset += fragments.reduce((size, part) => size + part.length, 0) + 1;
|
|
137
|
+
fragments.length = 0;
|
|
138
|
+
options.onCommit?.(offset);
|
|
139
|
+
if (record !== void 0) yield record.value;
|
|
140
|
+
start = end + 1;
|
|
141
|
+
}
|
|
142
|
+
if (start < bytes.length) fragments.push(bytes.subarray(start));
|
|
143
|
+
}
|
|
144
|
+
const record = parse(false);
|
|
145
|
+
if (record !== void 0) {
|
|
146
|
+
options.onCommit?.(end);
|
|
147
|
+
yield record.value;
|
|
148
|
+
}
|
|
149
|
+
} finally {
|
|
150
|
+
if (options.handle === void 0) await handle.close();
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
/** An invalid unterminated tail may be a torn write; other parse failures are not evidence of one. */
|
|
154
|
+
function parseRecord(line, source, lineNumber, terminated, allowWhitespaceLines = false) {
|
|
155
|
+
if (line.length === 0 || allowWhitespaceLines && line.trim().length === 0) return void 0;
|
|
156
|
+
try {
|
|
157
|
+
return { value: JSON.parse(line) };
|
|
158
|
+
} catch (cause) {
|
|
159
|
+
if (!(cause instanceof SyntaxError)) throw cause;
|
|
160
|
+
if (!terminated) return void 0;
|
|
161
|
+
throw new Error(`${source}: malformed JSONL record at line ${lineNumber}`, { cause });
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
/** Serialize JSONL file updates across processes and aliases using Eval's existing file lock.
|
|
165
|
+
* The caller owns validation and the record format. The lock path names the canonical file,
|
|
166
|
+
* including its first write, so two directory aliases cannot acquire different write heads.
|
|
167
|
+
* @internal
|
|
168
|
+
*/
|
|
169
|
+
async function withJsonlFileLock(path, operation) {
|
|
170
|
+
const fs = await import("node:fs/promises");
|
|
171
|
+
const { dirname } = await import("node:path");
|
|
172
|
+
const { tryAcquireAtomicFileLock } = await import("@tangle-network/agent-eval/ledger-core");
|
|
173
|
+
await fs.mkdir(dirname(path), { recursive: true });
|
|
174
|
+
await (await fs.open(path, "a")).close();
|
|
175
|
+
const canonicalPath = await fs.realpath(path);
|
|
176
|
+
const deadline = Date.now() + 5e3;
|
|
177
|
+
for (;;) {
|
|
178
|
+
const acquisition = tryAcquireAtomicFileLock({ lockPath: `${canonicalPath}.lock` });
|
|
179
|
+
if (!acquisition.acquired) {
|
|
180
|
+
if (Date.now() >= deadline) throw new Error(`journal file lock unavailable after 5000ms: ${canonicalPath}`);
|
|
181
|
+
await new Promise((resolve) => setTimeout(resolve, 25));
|
|
182
|
+
continue;
|
|
183
|
+
}
|
|
184
|
+
try {
|
|
185
|
+
return await operation(canonicalPath);
|
|
186
|
+
} finally {
|
|
187
|
+
acquisition.lock.release();
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
/** Read one keyed registry snapshot without an extra whole-file text allocation.
|
|
192
|
+
* Historical registry files allow whitespace-only separators; append journals remain strict.
|
|
193
|
+
* @internal
|
|
194
|
+
*/
|
|
195
|
+
async function readCommittedJsonFile(path) {
|
|
196
|
+
const records = [];
|
|
197
|
+
for await (const record of readCommittedJsonLines(path, {
|
|
198
|
+
allowMissing: true,
|
|
199
|
+
allowWhitespaceLines: true
|
|
200
|
+
})) records.push(record);
|
|
201
|
+
return records;
|
|
202
|
+
}
|
|
203
|
+
/** Replace one keyed row and publish one durable snapshot. The caller holds the file lock.
|
|
204
|
+
* Keep unrelated rows in order and put the replacement last. No revision archive is retained.
|
|
205
|
+
* @internal
|
|
206
|
+
*/
|
|
207
|
+
async function upsertCommittedJsonLine(path, record, key) {
|
|
208
|
+
const encoded = JSON.stringify(record);
|
|
209
|
+
if (encoded === void 0) throw new Error("JSONL records must be JSON serializable");
|
|
210
|
+
const snapshot = JSON.parse(encoded);
|
|
211
|
+
const id = key(snapshot);
|
|
212
|
+
const updated = [];
|
|
213
|
+
for await (const prior of readCommittedJsonLines(path, {
|
|
214
|
+
allowMissing: true,
|
|
215
|
+
allowWhitespaceLines: true
|
|
216
|
+
})) if (key(prior) !== id) updated.push(prior);
|
|
217
|
+
updated.push(snapshot);
|
|
218
|
+
const { writeAtomicDurableFile } = await import("./durable-file-CksURHlH.js");
|
|
219
|
+
writeAtomicDurableFile(path, `${updated.map((row) => JSON.stringify(row)).join("\n")}\n`, { preserveMode: true });
|
|
220
|
+
}
|
|
221
|
+
/** Recover a torn tail under the same generation fence as durable publications. @internal */
|
|
222
|
+
async function prepareJsonlAppend(path) {
|
|
223
|
+
return fenceRunWrite(() => prepareJsonlTail(path));
|
|
224
|
+
}
|
|
225
|
+
/** True for a filesystem error meaning "the file is not there yet" — the one condition an
|
|
226
|
+
* append-only reader treats as an empty log rather than a fault. */
|
|
227
|
+
function isNoEntError(error) {
|
|
228
|
+
return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
|
|
229
|
+
}
|
|
230
|
+
export { readCommittedJsonLines as a, appendCommittedJsonLine as c, readCommittedJsonFile as i, sha256 as l, parseCommittedJsonLines as n, upsertCommittedJsonLine as o, prepareJsonlAppend as r, withJsonlFileLock as s, isNoEntError as t };
|
|
231
|
+
|
|
232
|
+
//# sourceMappingURL=jsonl-file-BeUa5EDx.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"jsonl-file-BeUa5EDx.js","names":[],"sources":["../src/content-digest.ts","../src/durable/jsonl-append.ts","../src/durable/jsonl-file.ts"],"sourcesContent":["import { createHash } from 'node:crypto'\n\nexport function sha256(value: string): string {\n return createHash('sha256').update(value).digest('hex')\n}\n","import {\n closeSync,\n fstatSync,\n fsync,\n fsyncSync,\n ftruncateSync,\n openSync,\n readSync,\n writeSync,\n} from 'node:fs'\nimport { promisify } from 'node:util'\nimport { fenceRunWrite } from './run-fence'\n\n/** Append one JSONL record under the caller's existing single-writer discipline.\n * The caller creates the parent directory. Recover only an uncommitted tail and handle short\n * writes under one generation fence; fsync after the fence, off the event loop (#2362), and\n * resolve only once the bytes are durable. An optional acknowledgement reads the same open\n * descriptor inside the fence (the spawn journal validates its file stamp here).\n * @internal\n */\nexport function appendCommittedJsonLine(path: string, record: unknown): Promise<void>\nexport function appendCommittedJsonLine<T>(\n path: string,\n record: unknown,\n acknowledge: (fd: number) => T,\n): Promise<T>\nexport async function appendCommittedJsonLine<T>(\n path: string,\n record: unknown,\n acknowledge?: (fd: number) => T,\n): Promise<T | undefined> {\n const encoded = JSON.stringify(record)\n if (encoded === undefined) throw new TypeError('JSONL records must be JSON serializable')\n let fd: number | undefined\n try {\n const acknowledged = fenceRunWrite(() => {\n const bytes = Buffer.from(`${prepareJsonlTail(path) ? '\\n' : ''}${encoded}\\n`)\n fd = openSync(path, 'a')\n let offset = 0\n while (offset < bytes.length) {\n const written = writeSync(fd, bytes, offset, bytes.length - offset)\n if (written <= 0)\n throw new Error(`append-only file write made no progress at byte ${offset}`)\n offset += written\n }\n return acknowledge?.(fd)\n })\n await promisify(fsync)(fd as number)\n return acknowledged\n } finally {\n if (fd !== undefined) closeSync(fd)\n }\n}\n\n/** Recover only an uncommitted tail. Caller holds the generation fence. @internal */\nexport function prepareJsonlTail(path: string): boolean {\n let fd: number\n try {\n fd = openSync(path, 'r+')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false\n throw error\n }\n try {\n const size = fstatSync(fd).size\n if (size === 0) return false\n const last = Buffer.allocUnsafe(1)\n readAt(fd, last, size - 1)\n if (last[0] === 0x0a) return false\n const chunks: Buffer[] = []\n let end = size\n let tailStart = 0\n while (end > 0) {\n const start = Math.max(0, end - 65_536)\n const chunk = Buffer.allocUnsafe(end - start)\n readAt(fd, chunk, start)\n const newline = chunk.lastIndexOf(0x0a)\n chunks.push(chunk.subarray(newline + 1))\n if (newline >= 0) {\n tailStart = start + newline + 1\n break\n }\n end = start\n }\n try {\n JSON.parse(Buffer.concat(chunks.reverse()).toString('utf8'))\n return true\n } catch (error) {\n if (!(error instanceof SyntaxError)) throw error\n ftruncateSync(fd, tailStart)\n fsyncSync(fd)\n return false\n }\n } finally {\n closeSync(fd)\n }\n}\n\nfunction readAt(fd: number, buffer: Buffer, position: number): void {\n let offset = 0\n while (offset < buffer.length) {\n const read = readSync(fd, buffer, offset, buffer.length - offset, position + offset)\n if (read === 0) throw new Error('journal changed while preparing its append tail')\n offset += read\n }\n}\n","import type { FileHandle } from 'node:fs/promises'\nimport { prepareJsonlTail } from './jsonl-append'\nimport { fenceRunWrite } from './run-fence'\n\n/** Parse in-memory evidence with the same commit boundary as streamed journal reads. */\nexport function parseCommittedJsonLines<T>(text: string, source: string): T[] {\n const lines = text.split('\\n')\n const records: T[] = []\n for (const [index, line] of lines.entries()) {\n const record = parseRecord<T>(line, source, index + 1, index < lines.length - 1)\n if (record !== undefined) records.push(record.value)\n }\n return records\n}\n\n/** Read a fixed file prefix one record at a time, never allocating the whole journal as a string.\n * A reader cannot chase concurrent appends forever. Missing files are empty only when requested;\n * corruption, short reads, and other I/O errors remain failures. Closing the iterator closes the fd. */\nexport async function* readCommittedJsonLines<T>(\n path: string,\n options: {\n allowMissing?: boolean\n allowWhitespaceLines?: boolean\n onBytes?: (bytes: Uint8Array) => void\n /** Internal fixed-prefix range. The caller supplies a record boundary and owns the handle. */\n handle?: FileHandle\n start?: number\n end?: number\n strictUtf8?: boolean\n onCommit?: (offset: number) => void\n } = {},\n): AsyncGenerator<T> {\n const fs = await import('node:fs/promises')\n let handle: FileHandle\n try {\n handle = options.handle ?? (await fs.open(path, 'r'))\n } catch (error) {\n if (options.allowMissing && isNoEntError(error)) return\n throw error\n }\n try {\n const start = options.start ?? 0\n const end = options.end ?? (await handle.stat()).size\n if (end <= start) return\n const fragments: Buffer[] = []\n let offset = start\n let lineNumber = 1\n const parse = (terminated: boolean): { value: T } | undefined => {\n const bytes = Buffer.concat(fragments)\n let line: string\n try {\n line = options.strictUtf8\n ? new TextDecoder('utf-8', { fatal: true }).decode(bytes)\n : bytes.toString('utf8')\n } catch (cause) {\n if (!terminated) return undefined\n throw new Error(`${path}: malformed UTF-8 at line ${lineNumber}`, { cause })\n }\n return parseRecord<T>(line, path, lineNumber++, terminated, options.allowWhitespaceLines)\n }\n let position = start\n while (position < end) {\n const buffer = Buffer.alloc(Math.min(65_536, end - position))\n const { bytesRead } = await handle.read(buffer, 0, buffer.length, position)\n if (bytesRead === 0) {\n throw new Error(`${path}: journal changed while reading its committed prefix`)\n }\n position += bytesRead\n const bytes = buffer.subarray(0, bytesRead)\n options.onBytes?.(bytes)\n let start = 0\n for (let end = bytes.indexOf(10); end !== -1; end = bytes.indexOf(10, start)) {\n fragments.push(bytes.subarray(start, end))\n const record = parse(true)\n offset += fragments.reduce((size, part) => size + part.length, 0) + 1\n fragments.length = 0\n options.onCommit?.(offset)\n if (record !== undefined) yield record.value\n start = end + 1\n }\n if (start < bytes.length) fragments.push(bytes.subarray(start))\n }\n const record = parse(false)\n if (record !== undefined) {\n options.onCommit?.(end)\n yield record.value\n }\n } finally {\n if (options.handle === undefined) await handle.close()\n }\n}\n\n/** An invalid unterminated tail may be a torn write; other parse failures are not evidence of one. */\nfunction parseRecord<T>(\n line: string,\n source: string,\n lineNumber: number,\n terminated: boolean,\n allowWhitespaceLines = false,\n): { value: T } | undefined {\n if (line.length === 0 || (allowWhitespaceLines && line.trim().length === 0)) return undefined\n try {\n return { value: JSON.parse(line) as T }\n } catch (cause) {\n if (!(cause instanceof SyntaxError)) throw cause\n if (!terminated) return undefined\n throw new Error(`${source}: malformed JSONL record at line ${lineNumber}`, { cause })\n }\n}\n\nexport { appendCommittedJsonLine } from './jsonl-append'\n\n/** Serialize JSONL file updates across processes and aliases using Eval's existing file lock.\n * The caller owns validation and the record format. The lock path names the canonical file,\n * including its first write, so two directory aliases cannot acquire different write heads.\n * @internal\n */\nexport async function withJsonlFileLock<T>(\n path: string,\n operation: (canonicalPath: string) => Promise<T>,\n): Promise<T> {\n const fs = await import('node:fs/promises')\n const { dirname } = await import('node:path')\n const { tryAcquireAtomicFileLock } = await import('@tangle-network/agent-eval/ledger-core')\n await fs.mkdir(dirname(path), { recursive: true })\n const file = await fs.open(path, 'a')\n await file.close()\n const canonicalPath = await fs.realpath(path)\n const deadline = Date.now() + 5000\n for (;;) {\n const acquisition = tryAcquireAtomicFileLock({ lockPath: `${canonicalPath}.lock` })\n if (!acquisition.acquired) {\n if (Date.now() >= deadline) {\n throw new Error(`journal file lock unavailable after 5000ms: ${canonicalPath}`)\n }\n await new Promise((resolve) => setTimeout(resolve, 25))\n continue\n }\n try {\n return await operation(canonicalPath)\n } finally {\n acquisition.lock.release()\n }\n }\n}\n\n/** Read one keyed registry snapshot without an extra whole-file text allocation.\n * Historical registry files allow whitespace-only separators; append journals remain strict.\n * @internal\n */\nexport async function readCommittedJsonFile<T>(path: string): Promise<T[]> {\n const records: T[] = []\n for await (const record of readCommittedJsonLines<T>(path, {\n allowMissing: true,\n allowWhitespaceLines: true,\n })) {\n records.push(record)\n }\n return records\n}\n\n/** Replace one keyed row and publish one durable snapshot. The caller holds the file lock.\n * Keep unrelated rows in order and put the replacement last. No revision archive is retained.\n * @internal\n */\nexport async function upsertCommittedJsonLine<T>(\n path: string,\n record: T,\n key: (record: T) => string,\n): Promise<void> {\n const encoded = JSON.stringify(record)\n if (encoded === undefined) throw new Error('JSONL records must be JSON serializable')\n const snapshot: T = JSON.parse(encoded)\n const id = key(snapshot)\n const updated: T[] = []\n for await (const prior of readCommittedJsonLines<T>(path, {\n allowMissing: true,\n allowWhitespaceLines: true,\n })) {\n if (key(prior) !== id) updated.push(prior)\n }\n updated.push(snapshot)\n // Reuse Runtime's file publication owner; this module owns JSONL framing, not another\n // durability implementation. Preserve the existing snapshot's permissions across rename.\n const { writeAtomicDurableFile } = await import('../runtime/supervise/durable-file')\n writeAtomicDurableFile(path, `${updated.map((row) => JSON.stringify(row)).join('\\n')}\\n`, {\n preserveMode: true,\n })\n}\n\n/** Recover a torn tail under the same generation fence as durable publications. @internal */\nexport async function prepareJsonlAppend(path: string): Promise<boolean> {\n return fenceRunWrite(() => prepareJsonlTail(path))\n}\n\n/** True for a filesystem error meaning \"the file is not there yet\" — the one condition an\n * append-only reader treats as an empty log rather than a fault. */\nexport function isNoEntError(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n 'code' in error &&\n (error as { code: unknown }).code === 'ENOENT'\n )\n}\n"],"mappings":"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"}
|
package/dist/kernel.js
CHANGED
|
@@ -1,15 +1,16 @@
|
|
|
1
|
-
import { $n as readBoundHarnessSessions, $t as FileResultBlobStore, B as FileSpawnJournal,
|
|
2
|
-
import { A as defaultAnalystInstruction, D as runAgentic, E as refine, F as collectAgentTurn, I as streamAgentTurn, M as renderReport, N as profileChatClient, O as sample, P as profileOptimizerModelCall, S as strategyAuthorSystemPrompt, T as depthStrategy, _ as defineStrategy, a as defaultStructuralRolloutPolicy, b as sampleThenRefine, c as officialChecksFromMeta, d as selectBestIndex, f as structuralRollout, g as authorStrategy, h as assertStrategyContract, i as defaultExtractCandidate, j as observe, k as ObservationError, l as resolveEntrySymbol, m as adaptiveRefine, n as compareCheckOutcomes, o as filterAuthoredAsserts, p as visibleCheckScore, r as composeCheckSources, s as modelAuthoredChecks, t as canDisplace, u as sandboxCheckRunner, w as breadthStrategy, x as strategyAuthorContract } from "./structural-rollout-
|
|
1
|
+
import { $n as readBoundHarnessSessions, $t as FileResultBlobStore, B as FileSpawnJournal, F as attachWorker, G as settledToIteration, Gn as captureBoundHarnessTranscript, I as readWorkerInteractiveBinding, In as createOtelExporter, J as freeSlots, Kn as captureHarnessTranscript, L as reconnectRetainedInteractiveRun, Qn as HARNESS_TRANSCRIPT_READ_LIMITS, R as recoverRetainedInteractiveRun, S as writeWorkerSteer, Wn as HARNESS_TRANSCRIPT_SETTLE_TIMEOUT_MS, X as rollingDispatch, Xn as persistHarnessTranscript, Y as queueOf, Yt as materializeTreeView, Zr as RunCancellationReason, _ as supervisorRunDir, ar as readWorkerProgress, b as workerInboxFileFromEventDir, c as cancelWorker, er as resolveHarnessTranscriptCapture, fn as reconnectRetainedRun, g as safeWorkerFile, h as readWorkerSteerRequests, hn as startRetainedRunInEnvironment, j as parseWorkerToolTraceArtifact, k as replaySpawnTree, m as readWorkerSteerAcknowledgement, mn as startRetainedRun, nr as DEFAULT_STALL_AFTER_MS, p as readWorkerCancellation, pn as recoverRetainedRun, pr as subscriptionUsageLimitSignal, qn as harnessTranscriptArtifact, qt as loadSpawnForest, rr as createActivityLog, t as createScope, tr as retainHarnessTranscript, u as legacySupervisorRunDir, v as supervisorRunsRoot, w as createWorkerSlots, z as startRetainedInteractiveRun } from "./scope-DSm2RW5I.js";
|
|
2
|
+
import { A as defaultAnalystInstruction, D as runAgentic, E as refine, F as collectAgentTurn, I as streamAgentTurn, M as renderReport, N as profileChatClient, O as sample, P as profileOptimizerModelCall, S as strategyAuthorSystemPrompt, T as depthStrategy, _ as defineStrategy, a as defaultStructuralRolloutPolicy, b as sampleThenRefine, c as officialChecksFromMeta, d as selectBestIndex, f as structuralRollout, g as authorStrategy, h as assertStrategyContract, i as defaultExtractCandidate, j as observe, k as ObservationError, l as resolveEntrySymbol, m as adaptiveRefine, n as compareCheckOutcomes, o as filterAuthoredAsserts, p as visibleCheckScore, r as composeCheckSources, s as modelAuthoredChecks, t as canDisplace, u as sandboxCheckRunner, w as breadthStrategy, x as strategyAuthorContract } from "./structural-rollout-BwyAIuww.js";
|
|
3
3
|
import { t as runTaskQueue } from "./task-queue-DbpZAp6C.js";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import { n as
|
|
11
|
-
import {
|
|
12
|
-
import { n as
|
|
13
|
-
import {
|
|
14
|
-
import { n as
|
|
4
|
+
import { A as TRACE_SUMMARY_SCHEMA, M as contentAddress, St as decodeHarnessUsage, Z as spendFromUsageEvents, ht as extractLlmCallEvent, k as TRACE_ROOT_SCHEMA, nt as mapSandboxEvent, q as createBudgetPool, rt as mapSandboxToolEvent, tt as createSandboxToolPartState, xt as sumSandboxUsage } from "./failure-cause-BzjUUsRz.js";
|
|
5
|
+
import { $ as DEFAULT_PEER_MAIL_LIMITS, C as createExecutor, Ct as admitContinuationPolicy, D as runAgentRounds, E as createSteerableSandboxSession, Ft as harnessUsageIsEmpty, H as createAgentEnvironmentProviderRegistry, It as readCodexRolloutSession, J as createInPlaceCliExecutor, K as providerAsSandboxClient, L as createCodeModeTools, Lt as createPushTraceSource, M as acquireSandbox, N as TERMINAL_DECISIONS, Nt as addHarnessUsage, P as defaultSelectWinner, Pt as createCodexRolloutStoreReader, Q as AUTHORITY_MARKERS, R as runCodeMode, T as DEFAULT_SANDBOX_STEERING_MAX_TURNS, U as resolveAgentEnvironmentProvider, W as providerAsExecutor, _t as CheckUnavailableError, at as peerMailVerbNames, b as createExecutorRegistry, bt as mapExecutorResult, et as PEER_MAIL_WIRE_KEY, i as RunParkedError, it as peerMailTools, j as createSandboxLineage, n as createSupervisor, nt as createPeerMailbox, p as createRootHandle, q as createWorktreeCliExecutor, qt as assertProfileMaterializes, rt as isPeerMailEnvelope, s as readRunParking, t as DEFAULT_MAX_DEPTH, tt as claimsAuthority, u as bestDelivered, v as InMemoryResultBlobStore, xt as verdictFromJudgeScore, y as InMemorySpawnJournal, yt as gateOnDeliverable } from "./supervisor-jXN2xXiU.js";
|
|
6
|
+
import { _ as sharedWorkerClientName, f as DEFAULT_SHARED_BOX_RESOURCES, g as sharedBoxRefusal, h as ROUTER_CLIENT_HEADER, m as sharedBoxPlacement, p as DEFAULT_SHARED_BOX_WORKERS } from "./search-executor-1qaSeY70.js";
|
|
7
|
+
import { i as readRunCancellation, n as cancelRun, r as readRunCancelRequest, v as FileCoordinationLog } from "./run-cancellation-ZmRSYLu5.js";
|
|
8
|
+
import { f as createFileRunContext, i as watchTrace, m as withRunContext, o as createEventBus, p as createInMemoryRunContext, r as defaultToolDetectors } from "./coordination-manager-CYElgkMI.js";
|
|
9
|
+
import { A as dumbContinuationPassPrompt, B as areaUnderCurve, C as defaultEdgeTraversalCap, D as createPromptRegistry, E as analyzesFindingsReportPrompt, F as allWorkersStalled, H as plateauLength, I as anyOf, L as noProgressFor, M as kernelPromptRegistry, N as naiveContinuationPrompt, O as delegatesWorkerBriefPrompt, P as promptHandle, R as plateau, U as renderAnytimeTable, V as bestSoFar, W as createSupervisorSpanRecorder, _ as GraphRouteError, d as composeReentryTask, f as serveCoordinationMcp, j as formatPromptHandle, k as dumbContinuationFailPrompt, l as runToolSpans, n as superviseFleetCapabilities, o as workerFromBackend, s as supervisorAgent, t as supervise, u as UNPROVEN_CONTINUITY, z as anytimeReport } from "./supervise-C2Do7hEd.js";
|
|
10
|
+
import { a as graphRegistry, b as graphRouteWhenSchema, c as loadGraph, d as recordGraphRun, f as recordStoredGraphRun, i as graphFromStored, l as lookupGraph, m as taskShapeDigest, n as graphCorpusSummary, o as graphRunsFor, p as storedGraphDigests, r as graphDigest, s as listGraphRuns, t as digestOfGraph, u as pickBestGraph, y as graphFileSchema } from "./graph-registry-DbCwfHMY.js";
|
|
11
|
+
import { n as readSpawnJournal, t as readRunState } from "./run-state-Dn2AIE5m.js";
|
|
12
|
+
import { $ as runBenchmark, $t as renderLeaderboardHtml, A as searchPresets, At as sanitizeMcpToolSchema, B as graphFromSessionFacts, Bt as assertDeclaredCheck, C as withUntrackedArtifacts, Ct as harvestCorpus, D as SEARCH_SPEC_CORRELATION_KEY, Dt as connectStdioMcp, E as createFencedSqlRunContext, Et as McpSpawnFault, F as loadProfile, Ft as secretEnvOfMcpServer, G as chatWorkerSeam, Gt as readDeclaredCheck, H as loadGraphFile, Ht as declaredCheckDeliverable, I as pickBestProfile, It as inlineSandboxClient, J as strategyTournament, Jt as deterministicCompletion, K as createChatSessionStore, Kt as runIsolatedCheck, L as profileRegistry, Lt as loopCampaignDispatch, M as connectRemoteSupervisor, Mt as mcpSecretEnvMetadataKey, N as connectRemoteSupervisorControl, Nt as resolveMcpServerLaunch, O as assertSearchSpec, Ot as materializeLocalMcp, P as bestProfileFor, Pt as resolveSecretEnv, Q as printBenchmarkReport, Qt as pairwiseSignificance, R as profileRunsForName, Rt as loopDispatch, S as copyUntrackedIntoClone, St as HarvestError, T as validateStoredGraph, Tt as resolveSandboxClient, U as graphDesignerExtraTools, Ut as declaredCheckDigest, V as GraphFileResolutionError, Vt as checkProgramDigest, W as chatTransportExecutor, Wt as declaredCheckJudge, X as openSandboxRun, Xt as stopSentinel, Y as SandboxRunAbortError, Yt as sentinelCompletion, Z as createS3PrivateCasStore, Zt as leaderboard, _ as NOTE_MAX_CHARS, _t as buildSteerContext, a as localShell, at as FileCorpus, b as composeWorkerEvidence, bt as observationFromRegistry, c as createVerifierEnvironment, ct as fanout, d as harvestSurfaceDiffs, dt as panel, en as renderLeaderboardMarkdown, et as createPrivateCasArtifactPort, f as analystsFromRegistry, ft as pipeline, g as EVIDENCE_MAX_CHARS, gt as assertTraceDerivedFindings, ht as widen, i as jjWorkspace, in as openSqlRunStore, it as runPersonified, j as searchSpecDigest, jt as envKeyProvider, k as compileSearchSpec, kt as createMcpEnvironment, l as boxSurfaceReader, lt as flatWidenGate, m as worktreeFanout, mt as verify, n as makeFinding, nn as renderPairwiseMarkdown, nt as trajectoryReport, o as runInWorkspace, ot as InMemoryCorpus, p as failuresAnalyst, pt as selectValidWinner, q as runStrategyEvolution, qt as completionAuthorizes, r as gitWorkspace, rn as SqlRunOwnershipError, rt as definePersona, s as createWaterfallCollector, st as renderCorpusToInstructions, t as computeFindingId, tn as renderLeaderboardSvg, tt as equalKOnCost, u as fsSurfaceReader, ut as loopUntil, v as VERIFY_TAIL_CHARS, vt as createScopeAnalyst, w as analyzeTrace, wt as defineLeaderboard, x as settledWorkerOut, xt as inProcessSandboxClient, y as closingWorkerNote, yt as registryScopeAnalyst, z as recordProfileRun, zt as superviseDispatch } from "./runtime-D5eL70Is.js";
|
|
13
|
+
import { n as workerFromInteractiveProvider, r as claimRetainedInteractiveControl, t as provisionSupervisor } from "./provision-supervisor-CBeTMpMY.js";
|
|
14
|
+
import { a as defaultProfileRichnessThresholds, i as assessAuthoredProfile, n as delegate, o as profileRichnessFinding, r as asAuthoredProfile, s as supervisorInstructions, t as defaultDelegateBudget } from "./delegate-dW2jsqFF.js";
|
|
15
|
+
import { n as runGraph, t as GraphEdgeCapError } from "./graph-A7AvOP1I.js";
|
|
15
16
|
export { AUTHORITY_MARKERS, CheckUnavailableError, DEFAULT_MAX_DEPTH, DEFAULT_PEER_MAIL_LIMITS, DEFAULT_SANDBOX_STEERING_MAX_TURNS, DEFAULT_SHARED_BOX_RESOURCES, DEFAULT_SHARED_BOX_WORKERS, DEFAULT_STALL_AFTER_MS, EVIDENCE_MAX_CHARS, FileCoordinationLog, FileCorpus, FileResultBlobStore, FileSpawnJournal, GraphEdgeCapError, GraphFileResolutionError, GraphRouteError, HARNESS_TRANSCRIPT_READ_LIMITS, HARNESS_TRANSCRIPT_SETTLE_TIMEOUT_MS, HarvestError, InMemoryCorpus, InMemoryResultBlobStore, InMemorySpawnJournal, McpSpawnFault, NOTE_MAX_CHARS, ObservationError, PEER_MAIL_WIRE_KEY, ROUTER_CLIENT_HEADER, RunCancellationReason, RunParkedError, SEARCH_SPEC_CORRELATION_KEY, SandboxRunAbortError, SqlRunOwnershipError, TERMINAL_DECISIONS, TRACE_ROOT_SCHEMA, TRACE_SUMMARY_SCHEMA, UNPROVEN_CONTINUITY, VERIFY_TAIL_CHARS, acquireSandbox, adaptiveRefine, addHarnessUsage, admitContinuationPolicy, allWorkersStalled, analystsFromRegistry, analyzeTrace, analyzesFindingsReportPrompt, anyOf, anytimeReport, areaUnderCurve, asAuthoredProfile, assertDeclaredCheck, assertProfileMaterializes, assertSearchSpec, assertStrategyContract, assertTraceDerivedFindings, assessAuthoredProfile, attachWorker, authorStrategy, bestDelivered, bestProfileFor, bestSoFar, boxSurfaceReader, breadthStrategy, buildSteerContext, canDisplace, cancelRun, cancelWorker, captureBoundHarnessTranscript, captureHarnessTranscript, chatTransportExecutor, chatWorkerSeam, checkProgramDigest, claimRetainedInteractiveControl, claimsAuthority, closingWorkerNote, collectAgentTurn, compareCheckOutcomes, compileSearchSpec, completionAuthorizes, composeCheckSources, composeReentryTask, composeWorkerEvidence, computeFindingId, connectRemoteSupervisor, connectRemoteSupervisorControl, connectStdioMcp, contentAddress, copyUntrackedIntoClone, createActivityLog, createAgentEnvironmentProviderRegistry, createBudgetPool, createChatSessionStore, createCodeModeTools, createCodexRolloutStoreReader, createEventBus, createExecutor, createExecutorRegistry, createFencedSqlRunContext, createFileRunContext, createInMemoryRunContext, createInPlaceCliExecutor, createMcpEnvironment, createOtelExporter, createPeerMailbox, createPrivateCasArtifactPort, createPromptRegistry, createPushTraceSource, createRootHandle, createS3PrivateCasStore, createSandboxLineage, createSandboxToolPartState, createScope, createScopeAnalyst, createSteerableSandboxSession, createSupervisor, createSupervisorSpanRecorder, createVerifierEnvironment, createWaterfallCollector, createWorkerSlots, createWorktreeCliExecutor, declaredCheckDeliverable, declaredCheckDigest, declaredCheckJudge, decodeHarnessUsage, defaultAnalystInstruction, defaultDelegateBudget, defaultEdgeTraversalCap, defaultExtractCandidate, defaultProfileRichnessThresholds, defaultSelectWinner, defaultStructuralRolloutPolicy, defaultToolDetectors, defineLeaderboard, definePersona, defineStrategy, delegate, delegatesWorkerBriefPrompt, depthStrategy, deterministicCompletion, digestOfGraph, dumbContinuationFailPrompt, dumbContinuationPassPrompt, envKeyProvider, equalKOnCost, extractLlmCallEvent, failuresAnalyst, fanout, filterAuthoredAsserts, flatWidenGate, formatPromptHandle, freeSlots, fsSurfaceReader, gateOnDeliverable, gitWorkspace, graphCorpusSummary, graphDesignerExtraTools, graphDigest, graphFileSchema, graphFromSessionFacts, graphFromStored, graphRegistry, graphRouteWhenSchema, graphRunsFor, harnessTranscriptArtifact, harnessUsageIsEmpty, harvestCorpus, harvestSurfaceDiffs, inProcessSandboxClient, inlineSandboxClient, isPeerMailEnvelope, jjWorkspace, kernelPromptRegistry, leaderboard, legacySupervisorRunDir, listGraphRuns, loadGraph, loadGraphFile, loadProfile, loadSpawnForest, localShell, lookupGraph, loopCampaignDispatch, loopDispatch, loopUntil, makeFinding, mapExecutorResult, mapSandboxEvent, mapSandboxToolEvent, materializeLocalMcp, materializeTreeView, mcpSecretEnvMetadataKey, modelAuthoredChecks, naiveContinuationPrompt, noProgressFor, observationFromRegistry, observe, officialChecksFromMeta, openSandboxRun, openSqlRunStore, pairwiseSignificance, panel, parseWorkerToolTraceArtifact, peerMailTools, peerMailVerbNames, persistHarnessTranscript, pickBestGraph, pickBestProfile, pipeline, plateau, plateauLength, printBenchmarkReport, profileChatClient, profileOptimizerModelCall, profileRegistry, profileRichnessFinding, profileRunsForName, promptHandle, providerAsExecutor, providerAsSandboxClient, provisionSupervisor, queueOf, readBoundHarnessSessions, readCodexRolloutSession, readDeclaredCheck, readRunCancelRequest, readRunCancellation, readRunParking, readRunState, readSpawnJournal, readWorkerCancellation, readWorkerInteractiveBinding, readWorkerProgress, readWorkerSteerAcknowledgement, readWorkerSteerRequests, reconnectRetainedInteractiveRun, reconnectRetainedRun, recordGraphRun, recordProfileRun, recordStoredGraphRun, recoverRetainedInteractiveRun, recoverRetainedRun, refine, registryScopeAnalyst, renderAnytimeTable, renderCorpusToInstructions, renderLeaderboardHtml, renderLeaderboardMarkdown, renderLeaderboardSvg, renderPairwiseMarkdown, renderReport, replaySpawnTree, resolveAgentEnvironmentProvider, resolveEntrySymbol, resolveHarnessTranscriptCapture, resolveMcpServerLaunch, resolveSandboxClient, resolveSecretEnv, retainHarnessTranscript, rollingDispatch, runAgentRounds, runAgentic, runBenchmark, runCodeMode, runGraph, runInWorkspace, runIsolatedCheck, runPersonified, runStrategyEvolution, runTaskQueue, runToolSpans, safeWorkerFile, sample, sampleThenRefine, sandboxCheckRunner, sanitizeMcpToolSchema, searchPresets, searchSpecDigest, secretEnvOfMcpServer, selectBestIndex, selectValidWinner, sentinelCompletion, serveCoordinationMcp, settledToIteration, settledWorkerOut, sharedBoxPlacement, sharedBoxRefusal, sharedWorkerClientName, spendFromUsageEvents, startRetainedInteractiveRun, startRetainedRun, startRetainedRunInEnvironment, stopSentinel, storedGraphDigests, strategyAuthorContract, strategyAuthorSystemPrompt, strategyTournament, streamAgentTurn, structuralRollout, subscriptionUsageLimitSignal, sumSandboxUsage, supervise, superviseDispatch, superviseFleetCapabilities, supervisorAgent, supervisorInstructions, supervisorRunDir, supervisorRunsRoot, taskShapeDigest, trajectoryReport, validateStoredGraph, verdictFromJudgeScore, verify, visibleCheckScore, watchTrace, widen, withRunContext, withUntrackedArtifacts, workerFromBackend, workerFromInteractiveProvider, workerInboxFileFromEventDir, worktreeFanout, writeWorkerSteer };
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { i as ConfigError } from "./errors-AzSuGI23.js";
|
|
2
2
|
import { t as runAnalystLoop } from "./analyst-loop-BZvXCDKy.js";
|
|
3
|
-
import "./runtime-
|
|
3
|
+
import "./runtime-D5eL70Is.js";
|
|
4
4
|
// src/loop-runner.ts
|
|
5
5
|
/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */
|
|
6
6
|
const DELEGATED_LOOP_MODES = [
|
|
@@ -55,4 +55,4 @@ function auditLoopRunner(options) {
|
|
|
55
55
|
}
|
|
56
56
|
export { runDelegatedLoop as i, auditLoopRunner as n, isDelegatedLoopMode as r, DELEGATED_LOOP_MODES as t };
|
|
57
57
|
|
|
58
|
-
//# sourceMappingURL=loop-runner-
|
|
58
|
+
//# sourceMappingURL=loop-runner-DZxVXLLU.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loop-runner-DQJjowz0.js","names":[],"sources":["../src/loop-runner.ts"],"sourcesContent":["/**\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → caller-registered `improve(profile, options)` run\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a `DelegatedLoopResult`. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\ninterface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\ninterface WorktreeLoopRunnerOptions {\n /** Exact profile carried by the personified root that owns this fanout. */\n rootProfile: AgentProfile\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: options.rootProfile, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\ninterface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\ninterface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n"],"mappings":";;;;;AAyCA,MAAa,uBAAuB;CAAC;CAAQ;CAAU;CAAY;CAAS;AAAc;;AAM1F,SAAgB,oBAAoB,OAA4C;CAC9E,OAAO,OAAO,UAAU,YAAa,qBAA2C,SAAS,KAAK;AAChG;;;;;;;;;;AAoCA,eAAsB,iBACpB,MACA,UACA,UAAmC,CAAC,GACH;CACjC,MAAM,SAAS,SAAS;CACxB,IAAI,CAAC,QACH,MAAM,IAAI,YACR,oDAAoD,KAAK,iBACvD,OAAO,KAAK,QAAQ,CAAC,CAAC,KAAK,IAAI,KAAK,OACrC,EACH;CAEF,MAAM,MAAM,QAAQ,OAAO,KAAK;CAChC,MAAM,SAAS,QAAQ,UAAU,IAAI,gBAAgB,CAAC,CAAC;CACvD,MAAM,QAAQ,IAAI;CAClB,IAAI;EAEF,OAAO;GAAE;GAAM,IAAI;GAAM,QAAA,MADJ,OAAO,MAAM;GACD,YAAY,IAAI,IAAI;EAAM;CAC7D,SAAS,KAAK;EACZ,OAAO;GACL;GACA,IAAI;GACJ,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;GACtD,YAAY,IAAI,IAAI;EACtB;CACF;AACF;;;;;;AAoKA,SAAgB,gBACd,SAC6D;CAC7D,OAAO,YAAY,eAAiC,OAAO;AAC7D"}
|
|
1
|
+
{"version":3,"file":"loop-runner-DZxVXLLU.js","names":[],"sources":["../src/loop-runner.ts"],"sourcesContent":["/**\n *\n * `runDelegatedLoop` — the configured delegated loop-runner.\n *\n * One typed entrypoint a worker agent (or a scheduled routine) calls to run a\n * disciplined loop in a chosen MODE, over agent-runtime's hardened engines:\n *\n * code → build-in-a-loop on the GENERIC recursive path (worktreeLoopRunner: author one\n * `AgentProfile` per harness → worktree-CLI leaves → `patchDelivered` gate)\n * review → caller-registered runner — a `code` runner with an approval gate over candidates\n * research → research-in-a-loop with valid-only KB growth (createKbGate)\n * audit → analyze trace/run data → findings (runAnalystLoop, caller-wired)\n * self-improve → caller-registered `improve(profile, options)` run\n *\n * It is intentionally a thin façade: the value is that EVERY product reuses the\n * one hardened engine instead of forking delegation logic. The dispatcher owns\n * mode routing, timing, fail-loud on an unregistered mode, and a uniform result\n * shape; each mode's engine is a pre-configured runner in the registry (build it\n * with the factories below, or inject your own / a stub).\n *\n * @experimental\n */\n\nimport type { AgentProfile } from '@tangle-network/agent-interface'\nimport { runAnalystLoop } from './analyst-loop'\nimport type { RunAnalystLoopOpts, RunAnalystLoopResult } from './analyst-loop/types'\nimport { ConfigError } from './errors'\nimport { type CreateKbGateOptions, createKbGate, type FactCandidate } from './mcp/kb-gate'\nimport {\n type AuthoredHarness,\n type Budget,\n createExecutorRegistry,\n definePersona,\n runPersonified,\n type WinnerStrategy,\n type WorktreeFanoutOptions,\n type WorktreePatchArtifact,\n worktreeFanout,\n} from './runtime'\n\n/** All valid delegated-loop mode names — used for validation and CLI surfaces. @experimental */\nexport const DELEGATED_LOOP_MODES = ['code', 'review', 'research', 'audit', 'self-improve'] as const\n\n/** @experimental */\nexport type DelegatedLoopMode = (typeof DELEGATED_LOOP_MODES)[number]\n\n/** Type guard — returns true when `value` is a valid `DelegatedLoopMode` string. @experimental */\nexport function isDelegatedLoopMode(value: unknown): value is DelegatedLoopMode {\n return typeof value === 'string' && (DELEGATED_LOOP_MODES as readonly string[]).includes(value)\n}\n\n/** @experimental A pre-configured loop for one mode. Returns the mode's raw\n * output; the dispatcher wraps it in a `DelegatedLoopResult`. */\nexport type DelegatedLoopRunner<T = unknown> = (signal: AbortSignal) => Promise<T>\n\n/** @experimental Mode → configured runner. Partial: only register the modes a\n * given product/routine actually uses. */\nexport type DelegatedLoopRegistry = Partial<Record<DelegatedLoopMode, DelegatedLoopRunner>>\n\n/** @experimental Uniform result — never throws from a registered runner; a\n * thrown engine becomes `{ ok: false, error }` so a routine can record + move on. */\nexport interface DelegatedLoopResult<T = unknown> {\n mode: DelegatedLoopMode\n ok: boolean\n output?: T\n error?: string\n durationMs: number\n}\n\n/** @experimental */\ninterface RunDelegatedLoopOptions {\n signal?: AbortSignal\n /** Clock override for deterministic tests. */\n now?: () => number\n}\n\n/**\n *\n * Dispatch a configured loop by mode. Fails loud (throws `ConfigError`) when no\n * runner is registered for the mode — a routine pointed at an unwired mode is a\n * config bug, not a silent no-op. A runner that throws is captured as\n * `{ ok: false }` so unattended runs record the failure rather than crash.\n *\n * @experimental\n */\nexport async function runDelegatedLoop<T = unknown>(\n mode: DelegatedLoopMode,\n registry: DelegatedLoopRegistry,\n options: RunDelegatedLoopOptions = {},\n): Promise<DelegatedLoopResult<T>> {\n const runner = registry[mode] as DelegatedLoopRunner<T> | undefined\n if (!runner) {\n throw new ConfigError(\n `runDelegatedLoop: no runner registered for mode '${mode}' (registered: ${\n Object.keys(registry).join(', ') || 'none'\n })`,\n )\n }\n const now = options.now ?? Date.now\n const signal = options.signal ?? new AbortController().signal\n const start = now()\n try {\n const output = await runner(signal)\n return { mode, ok: true, output, durationMs: now() - start }\n } catch (err) {\n return {\n mode,\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n durationMs: now() - start,\n }\n }\n}\n\n/** @experimental Options for the local-repo `code` runner over the GENERIC recursive path. */\ninterface WorktreeLoopRunnerOptions {\n /** Exact profile carried by the personified root that owns this fanout. */\n rootProfile: AgentProfile\n /** Absolute path to the local git checkout each worktree is cut from. */\n repoRoot: string\n /** The instruction handed to every authored harness (composed under each profile's systemPrompt). */\n taskPrompt: string\n /** The supervisor-authored harness profiles — one fanout item (one worktree-CLI leaf) each. */\n harnesses: ReadonlyArray<AuthoredHarness>\n /** Conserved budget pool bounding the fanout (equal-k holds by construction). */\n budget: Budget\n /** Shell command run in each worktree to derive the tests-PASS signal. */\n testCmd?: string\n /** Shell command run in each worktree to derive the typecheck-PASS signal. */\n typecheckCmd?: string\n /** Which verification signals the deliverable REQUIRES present-and-passing (default none). */\n require?: ReadonlyArray<'tests' | 'typecheck'>\n /** Diff-size cap (lines). */\n maxDiffLines?: number\n /** Literal path prefixes the patch must not touch (the secret-floor is always on regardless). */\n forbiddenPaths?: string[]\n /** Winner-selection strategy among gated candidates. Default `highest-score`. */\n winnerStrategy?: WinnerStrategy\n /** Test seams forwarded to the worktree-CLI leaves so the runner drives offline. */\n runGit?: WorktreeFanoutOptions['runGit']\n runHarness?: WorktreeFanoutOptions['runHarness']\n runCommand?: WorktreeFanoutOptions['runCommand']\n}\n\n/**\n *\n * `code` mode on the GENERIC recursive path: author one `AgentProfile` per harness, run them as a\n * `worktreeFanout` (N `createWorktreeCliExecutor` leaves, each `gateOnDeliverable`) through\n * `runPersonified` on the keystone Supervisor. The sandbox-session counterpart that drives the in-box\n * harness over a `SandboxClient` is `detachedSessionDelegate` (`./mcp/delegates`); here there is no\n * `runAgentRounds` driver, no role-coupled delegate — the harness list is the fanout, the gate is\n * `patchDelivered`,\n * the winner is the shared valid-only selector (NOT `defaultSelectWinner`, whose non-valid fallback\n * would surface an ungated patch). Equal-k holds by the conserved budget pool. Returns the winning\n * patch artifact, or throws when no candidate is delivered (fail loud, never a vacuous done).\n *\n * @experimental\n */\nexport function worktreeLoopRunner(\n options: WorktreeLoopRunnerOptions,\n): DelegatedLoopRunner<WorktreePatchArtifact> {\n const shape = worktreeFanout<string>({\n repoRoot: options.repoRoot,\n taskPrompt: options.taskPrompt,\n harnesses: options.harnesses,\n ...(options.testCmd !== undefined ? { testCmd: options.testCmd } : {}),\n ...(options.typecheckCmd !== undefined ? { typecheckCmd: options.typecheckCmd } : {}),\n ...(options.require !== undefined ? { require: options.require } : {}),\n ...(options.maxDiffLines !== undefined ? { maxDiffLines: options.maxDiffLines } : {}),\n ...(options.forbiddenPaths !== undefined ? { forbiddenPaths: options.forbiddenPaths } : {}),\n ...(options.winnerStrategy !== undefined ? { winnerStrategy: options.winnerStrategy } : {}),\n ...(options.runGit ? { runGit: options.runGit } : {}),\n ...(options.runHarness ? { runHarness: options.runHarness } : {}),\n ...(options.runCommand ? { runCommand: options.runCommand } : {}),\n })\n // The persona's only role here is to carry the fanout shape onto the Supervisor; each item's\n // executor is BYO (the gated worktree-CLI leaf), so the registry only needs to pass BYO through.\n const persona = definePersona<WorktreePatchArtifact>({\n name: 'worktree-coder',\n root: { profile: options.rootProfile, harness: null },\n directive: 'deliver a minimal validated patch on a fresh worktree',\n context: { role: 'coder' },\n executors: { registry: createExecutorRegistry() },\n })\n return async (signal) => {\n const result = await runPersonified<string, WorktreePatchArtifact>({\n persona,\n shape,\n task: options.taskPrompt,\n budget: options.budget,\n signal,\n })\n if (result.kind !== 'winner' || result.out.kind !== 'done') {\n const blockers =\n result.kind === 'winner' && result.out.kind === 'blocked'\n ? result.out.blockers.join('; ')\n : `supervisor settled ${result.kind}`\n throw new Error(`worktreeLoopRunner: no delivered patch (${blockers})`)\n }\n return result.out.deliverable\n }\n}\n\n/** @experimental A fact rejected at the KB gate — surfaced, never dropped. */\nexport interface VetoedFact {\n candidate: FactCandidate\n vetoedBy?: string\n reason?: string\n}\n\n/** @experimental */\ninterface ResearchLoopResult {\n /** Facts that passed the fail-closed gate — safe to write to the KB. */\n accepted: FactCandidate[]\n /** Facts the gate vetoed in the final round — escalate, do not silently drop. */\n vetoed: VetoedFact[]\n /** Research rounds actually run. */\n rounds: number\n}\n\n/** @experimental Options for the default `research` runner. */\ninterface ResearchLoopRunnerOptions {\n /**\n * The research engine (the consumer's web/doc searcher + extractor). Called\n * each round with the prior round's vetoes so it can re-research the gaps.\n * Returns fact candidates carrying their grounding (`verbatimPassage` +\n * `sourceText`).\n */\n research: (round: number, vetoed: VetoedFact[]) => Promise<FactCandidate[]>\n /** Gate config (extra judges, self-artifact kinds, …). The floor is always on. */\n gate?: CreateKbGateOptions\n /** Max research rounds (correct-on-veto remediation). Default 1. */\n maxRounds?: number\n}\n\n/**\n * `research` mode — research-in-a-loop with valid-only KB growth.\n *\n * Each round: research → gate every candidate (fail-closed; passage MUST be in\n * the source) → accept the clean ones → re-research the vetoed ones next round,\n * up to `maxRounds`. Vetoed facts in the final round are RETURNED (escalate,\n * never silently dropped) so the caller audits vs retries.\n *\n * @experimental\n */\nexport function researchLoopRunner(\n o: ResearchLoopRunnerOptions,\n): DelegatedLoopRunner<ResearchLoopResult> {\n const gate = createKbGate(o.gate)\n const maxRounds = Math.max(1, Math.trunc(o.maxRounds ?? 1))\n return async (signal) => {\n const accepted: FactCandidate[] = []\n let vetoed: VetoedFact[] = []\n let rounds = 0\n for (let round = 0; round < maxRounds; round += 1) {\n if (signal.aborted) break\n rounds += 1\n const candidates = await o.research(round, vetoed)\n if (candidates.length === 0) break\n vetoed = []\n for (const c of candidates) {\n const v = await gate(c)\n if (v.accepted) accepted.push(c)\n else vetoed.push({ candidate: c, vetoedBy: v.vetoedBy, reason: v.reason })\n }\n if (vetoed.length === 0) break\n }\n return { accepted, vetoed, rounds }\n }\n}\n\n/**\n * `audit` mode — analyst loop over captured trace/run data.\n *\n * @experimental\n */\nexport function auditLoopRunner<TProposal = unknown, TEdit = unknown>(\n options: RunAnalystLoopOpts,\n): DelegatedLoopRunner<RunAnalystLoopResult<TProposal, TEdit>> {\n return async () => runAnalystLoop<TProposal, TEdit>(options)\n}\n"],"mappings":";;;;;AAyCA,MAAa,uBAAuB;CAAC;CAAQ;CAAU;CAAY;CAAS;AAAc;;AAM1F,SAAgB,oBAAoB,OAA4C;CAC9E,OAAO,OAAO,UAAU,YAAa,qBAA2C,SAAS,KAAK;AAChG;;;;;;;;;;AAoCA,eAAsB,iBACpB,MACA,UACA,UAAmC,CAAC,GACH;CACjC,MAAM,SAAS,SAAS;CACxB,IAAI,CAAC,QACH,MAAM,IAAI,YACR,oDAAoD,KAAK,iBACvD,OAAO,KAAK,QAAQ,CAAC,CAAC,KAAK,IAAI,KAAK,OACrC,EACH;CAEF,MAAM,MAAM,QAAQ,OAAO,KAAK;CAChC,MAAM,SAAS,QAAQ,UAAU,IAAI,gBAAgB,CAAC,CAAC;CACvD,MAAM,QAAQ,IAAI;CAClB,IAAI;EAEF,OAAO;GAAE;GAAM,IAAI;GAAM,QAAA,MADJ,OAAO,MAAM;GACD,YAAY,IAAI,IAAI;EAAM;CAC7D,SAAS,KAAK;EACZ,OAAO;GACL;GACA,IAAI;GACJ,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;GACtD,YAAY,IAAI,IAAI;EACtB;CACF;AACF;;;;;;AAoKA,SAAgB,gBACd,SAC6D;CAC7D,OAAO,YAAY,eAAiC,OAAO;AAC7D"}
|
package/dist/loop-runner-bin.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { i as runDelegatedLoop, r as isDelegatedLoopMode, t as DELEGATED_LOOP_MODES } from "./loop-runner-
|
|
2
|
+
import { i as runDelegatedLoop, r as isDelegatedLoopMode, t as DELEGATED_LOOP_MODES } from "./loop-runner-DZxVXLLU.js";
|
|
3
3
|
// src/loop-runner-bin.ts
|
|
4
4
|
/**
|
|
5
5
|
*
|
package/dist/mcp/bin.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { Mt as coordinationProfileToolPrefix, bn as FileObserverJournal, jn as readTraceContextFromEnv } from "../scope-
|
|
2
|
+
import { Mt as coordinationProfileToolPrefix, bn as FileObserverJournal, jn as readTraceContextFromEnv } from "../scope-DSm2RW5I.js";
|
|
3
3
|
import { i as ConfigError } from "../errors-AzSuGI23.js";
|
|
4
|
-
import { s as supervisorInstructions } from "../delegate-
|
|
5
|
-
import { a as FileDelegationStore, i as DelegationTaskQueue, n as observerJournalEventSource, t as createMcpServer } from "../server-
|
|
4
|
+
import { s as supervisorInstructions } from "../delegate-dW2jsqFF.js";
|
|
5
|
+
import { a as FileDelegationStore, i as DelegationTaskQueue, n as observerJournalEventSource, t as createMcpServer } from "../server-Dp4JKuTZ.js";
|
|
6
6
|
import { isAbsolute } from "node:path";
|
|
7
7
|
// src/mcp/delegate-supervisor-provisioning.ts
|
|
8
8
|
function trimmed(value) {
|
package/dist/mcp/index.js
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
|
-
import { _t as environmentReader, jn as readTraceContextFromEnv, kn as createPropagatingTraceEmitter, vt as resolveSpawnResourcePaths } from "../scope-
|
|
1
|
+
import { _t as environmentReader, jn as readTraceContextFromEnv, kn as createPropagatingTraceEmitter, vt as resolveSpawnResourcePaths } from "../scope-DSm2RW5I.js";
|
|
2
2
|
import { i as ConfigError, m as ValidationError } from "../errors-AzSuGI23.js";
|
|
3
|
-
import {
|
|
4
|
-
import { A as createSandboxForSpec, D as runAgentRounds, Ht as runWorktreeHarness, O as assertBoxlessPromptOptions, Ut as LOCAL_HARNESSES } from "../supervisor-
|
|
3
|
+
import { s as deleteBoxSafe, v as sleep, x as throwIfAborted } from "../util-C_cdPNC4.js";
|
|
4
|
+
import { A as createSandboxForSpec, D as runAgentRounds, Ht as runWorktreeHarness, O as assertBoxlessPromptOptions, Ut as LOCAL_HARNESSES } from "../supervisor-jXN2xXiU.js";
|
|
5
5
|
import { t as assertExecutableAgentProfile } from "../model-policy-JOcg3NRs.js";
|
|
6
|
-
import { n as createStdioToolServer } from "../tool-server-
|
|
7
|
-
import { t as createCoordinationTools } from "../coordination-manager-
|
|
8
|
-
import { h as runCoderChecks, pt as selectValidWinner } from "../runtime-
|
|
9
|
-
import { a as FileDelegationStore, i as DelegationTaskQueue, o as composeLoopTraceEmitters, r as createDelegateHandler, t as createMcpServer } from "../server-
|
|
6
|
+
import { n as createStdioToolServer } from "../tool-server-B9q2dtnW.js";
|
|
7
|
+
import { t as createCoordinationTools } from "../coordination-manager-CYElgkMI.js";
|
|
8
|
+
import { h as runCoderChecks, pt as selectValidWinner } from "../runtime-D5eL70Is.js";
|
|
9
|
+
import { a as FileDelegationStore, i as DelegationTaskQueue, o as composeLoopTraceEmitters, r as createDelegateHandler, t as createMcpServer } from "../server-Dp4JKuTZ.js";
|
|
10
10
|
import { agentProfileSchema } from "@tangle-network/agent-interface";
|
|
11
11
|
import { isRecord } from "@tangle-network/agent-core";
|
|
12
12
|
import { randomUUID } from "node:crypto";
|
package/dist/mcp/memory-bin.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { m as ValidationError } from "../errors-AzSuGI23.js";
|
|
3
|
-
import { n as createStdioToolServer } from "../tool-server-
|
|
3
|
+
import { n as createStdioToolServer } from "../tool-server-B9q2dtnW.js";
|
|
4
4
|
import { appendFileSync, mkdirSync, readFileSync } from "node:fs";
|
|
5
5
|
import { dirname } from "node:path";
|
|
6
6
|
// src/mcp/memory-server.ts
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { c as errorMessage } from "./util-C_cdPNC4.js";
|
|
2
|
+
import { B as hasControlCharacter, C as readMaterializedWorkspaceFiles, D as verifyMaterializedWorkspace, E as verifyMaterializedProfileWorkspace, F as embeddedCandidateArtifact, I as immutableCandidateValue, L as omitTopLevelDigest, M as canonicalCandidateDigest$1, N as canonicalCandidateDocument, O as verifyWorkspaceSnapshotArtifacts, P as deepFreezeCandidate, R as sha256Bytes$1, T as verifyBytes, _ as assertExactObjectKeys, b as artifactCacheKey, d as verifyTaskCheckout, f as verifyTaskOutcomePatch, g as persistCandidateOutputArtifact, j as canonicalCandidateBytes$1, l as readCandidateGitHubResource, u as verifyCandidateCode, v as isWellFormedUnicode, w as readVerifiedArtifact } from "./workspace-streams-uB9rRbms.js";
|
|
3
|
+
import { _ as parseAgentCandidateProfileActivation, c as buildLaunch, f as exactProfileExecutorFiles, h as modelRoutes, l as candidateEntrypointReceipt, m as materializeAgentCandidateProfilePlan, n as PI_CANDIDATE_SESSION_DIR_ENV, r as absoluteExecutionCwd, s as assertCandidateProfileExecutionSupport, t as PI_CANDIDATE_AGENT_DIR_ENV, u as candidateProfileAgentPaths, x as requirePublicCandidateConfigValue } from "./profile-DcRoyryP.js";
|
|
3
4
|
import { i as redactProtectedValue, n as createProtectedRecordRedactor, r as redactProtectedReason, t as assertNoProtectedBytes } from "./protected-redaction-DilFZch5.js";
|
|
4
5
|
import { agentCandidateArtifactRefSchema, agentCandidateBenchmarkResultEvidenceSchema, agentCandidateBenchmarkSuiteSchema, agentCandidateBenchmarkTaskSchema, agentCandidateBundleSchema, agentCandidateContainerSchema, agentCandidateExecutionLimitsSchema, agentCandidateExecutionPlanEvidenceSchema, agentCandidateExecutionPlanMaterialSchema, agentCandidateMaterializationReceiptSchema, agentCandidateModelAccessNetworkSchema, agentCandidateModelSettlementEvidenceSchema, agentCandidateProfilePlanEvidenceSchema, agentCandidateResolvedModelSchema, agentCandidateRunCellSchema, agentCandidateRunReceiptSchema, agentCandidateTaskOutcomeEvidenceSchema, agentCandidateTaskOutcomeSpecSchema, agentCandidateTerminationSchema, agentCandidateWorkspaceManifestMaterialSchema, agentCandidateWorkspaceSnapshotEvidenceSchema, sha256DigestSchema } from "@tangle-network/agent-interface";
|
|
5
6
|
import { REDACTION_VERSION, isLlmSpan } from "@tangle-network/agent-eval";
|
|
@@ -4318,4 +4319,4 @@ async function cleanupFailedPreparation(held, error) {
|
|
|
4318
4319
|
}
|
|
4319
4320
|
export { verifiedResourceTextByDigest as C, AGENT_CANDIDATE_EXECUTION_SUPPORT as S, sealTerminalDigest as _, consumePreparedCandidateExecution as a, sealAgentCandidateModelSettlement as b, withinCandidateCleanupDeadline as c, assertTerminalMatchesClaim as d, assertTerminalMatchesStaged as f, requireStagedTerminal as g, rejectedStage as h, beginPreparedCandidateDisposal as i, assertRecoveryMatchesStaged as l, rejectedFinish as m, executePreparedAgentCandidate as n, candidateClaimFileInternals as o, recoveredTerminalRecord as p, assertPreparedCandidateIntegrity as r, candidateCleanupDeadline as s, prepareAgentCandidateExecution as t, assertTerminalAllowedInPhase as u, terminalRecord as v, verifyAgentCandidateBundle as w, exactProcessProviderAsCandidateExecutor as x, createProtectedAgentCandidateModelPort as y };
|
|
4320
4321
|
|
|
4321
|
-
//# sourceMappingURL=prepare-
|
|
4322
|
+
//# sourceMappingURL=prepare-O1HbzOqs.js.map
|