@rulvar/core 1.244.0 → 1.246.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +2739 -1844
- package/dist/index.js +1543 -78
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -3252,7 +3252,7 @@ const MAX_TIMER_DELAY_MS = 2147483647;
|
|
|
3252
3252
|
* century-long suspension journals as a perfectly valid date.
|
|
3253
3253
|
*/
|
|
3254
3254
|
const MAX_DEADLINE_MS = 315576e7;
|
|
3255
|
-
function refuse$
|
|
3255
|
+
function refuse$2(site, requirement, value) {
|
|
3256
3256
|
throw new ConfigError(`${site} must be ${requirement}; got ${String(value)}`);
|
|
3257
3257
|
}
|
|
3258
3258
|
/**
|
|
@@ -3269,26 +3269,26 @@ function requireDeadlineMs(value, site) {
|
|
|
3269
3269
|
}
|
|
3270
3270
|
/** An integer >= 1 (counts, caps, and depths). */
|
|
3271
3271
|
function requirePositiveInteger$2(value, site) {
|
|
3272
|
-
if (typeof value !== "number" || !Number.isInteger(value) || value < 1) refuse$
|
|
3272
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 1) refuse$2(site, "a positive integer", value);
|
|
3273
3273
|
}
|
|
3274
3274
|
/** An integer >= 0 (caps where zero means "none allowed"). */
|
|
3275
3275
|
function requireNonNegativeInteger(value, site) {
|
|
3276
|
-
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) refuse$
|
|
3276
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 0) refuse$2(site, "a nonnegative integer", value);
|
|
3277
3277
|
}
|
|
3278
3278
|
/** A finite number >= 0 (USD amounts and reserves). */
|
|
3279
3279
|
function requireNonNegativeNumber(value, site) {
|
|
3280
|
-
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) refuse$
|
|
3280
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) refuse$2(site, "a finite nonnegative number", value);
|
|
3281
3281
|
}
|
|
3282
3282
|
/** A finite fraction in (0, 1]. */
|
|
3283
3283
|
function requireFraction(value, site) {
|
|
3284
|
-
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0 || value > 1) refuse$
|
|
3284
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0 || value > 1) refuse$2(site, "a fraction in (0, 1]", value);
|
|
3285
3285
|
}
|
|
3286
3286
|
/**
|
|
3287
3287
|
* A relative delay handed to setTimeout as-is: an integer within the
|
|
3288
3288
|
* Node timer maximum, mirroring validateRetryPolicy's bound.
|
|
3289
3289
|
*/
|
|
3290
3290
|
function requireTimerDelayMs(value, site) {
|
|
3291
|
-
if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 2147483647) refuse$
|
|
3291
|
+
if (typeof value !== "number" || !Number.isInteger(value) || value < 1 || value > 2147483647) refuse$2(site, "an integer between 1 and 2147483647 ms (the Node timer maximum)", value);
|
|
3292
3292
|
}
|
|
3293
3293
|
/**
|
|
3294
3294
|
* A declared evidence contract (RV303, enforcement RV507): minEntries
|
|
@@ -4483,6 +4483,19 @@ function mcp(cfg) {
|
|
|
4483
4483
|
};
|
|
4484
4484
|
return {
|
|
4485
4485
|
id: sourceIdOf(cfg),
|
|
4486
|
+
describeRegulatedPosture: () => ({
|
|
4487
|
+
regulatedPosture: 1,
|
|
4488
|
+
kind: "mcp-source",
|
|
4489
|
+
name: sourceIdOf(cfg),
|
|
4490
|
+
drift: cfg.drift ?? "rekey",
|
|
4491
|
+
bounds: {
|
|
4492
|
+
declared: cfg.maxTools !== void 0 && cfg.maxPages !== void 0 && cfg.maxSchemaBytes !== void 0 && cfg.timeouts?.discoveryMs !== void 0,
|
|
4493
|
+
...cfg.maxTools === void 0 ? {} : { maxTools: cfg.maxTools },
|
|
4494
|
+
...cfg.maxPages === void 0 ? {} : { maxPages: cfg.maxPages },
|
|
4495
|
+
...cfg.maxSchemaBytes === void 0 ? {} : { maxSchemaBytes: cfg.maxSchemaBytes },
|
|
4496
|
+
...cfg.timeouts?.discoveryMs === void 0 ? {} : { discoveryMs: cfg.timeouts.discoveryMs }
|
|
4497
|
+
}
|
|
4498
|
+
}),
|
|
4486
4499
|
tools: async () => {
|
|
4487
4500
|
if (poisoned) throw new ConfigError(`mcp: the tool list of '${sourceIdOf(cfg)}' changed after import (listChanged) and drift policy 'refuse' holds the source closed; close() and re-create the source (and re-record any toolset attestation) to import the changed list deliberately`);
|
|
4488
4501
|
if (cache !== void 0) return cache;
|
|
@@ -8313,11 +8326,13 @@ var EscalationDecisionAbortedError = class extends Error {
|
|
|
8313
8326
|
* Normalizes a resolution value into an ApprovalDecision. Anything that
|
|
8314
8327
|
* is not an explicit allow is a deny: an approval never fails open.
|
|
8315
8328
|
*/
|
|
8316
|
-
function toApprovalDecision(value) {
|
|
8329
|
+
function toApprovalDecision(value, entryRef) {
|
|
8317
8330
|
const record = value ?? {};
|
|
8318
8331
|
return {
|
|
8319
8332
|
decision: record.decision === "allow" ? "allow" : "deny",
|
|
8320
|
-
...typeof record.reason === "string" ? { reason: record.reason } : {}
|
|
8333
|
+
...typeof record.reason === "string" ? { reason: record.reason } : {},
|
|
8334
|
+
...typeof record.expiresAt === "string" ? { expiresAt: record.expiresAt } : {},
|
|
8335
|
+
...entryRef === void 0 ? {} : { entryRef }
|
|
8321
8336
|
};
|
|
8322
8337
|
}
|
|
8323
8338
|
/**
|
|
@@ -8352,7 +8367,9 @@ function detachedApprovalFlavor(entry) {
|
|
|
8352
8367
|
async function validatePayloadArms(kind, key, value, schemaSpec) {
|
|
8353
8368
|
if (kind === "approval") {
|
|
8354
8369
|
const decision = value?.decision;
|
|
8355
|
-
if (decision !== "allow" && decision !== "deny") throw new InvalidResolutionError(`approval '${key}' resolves with { decision: 'allow' | 'deny', reason? }`);
|
|
8370
|
+
if (decision !== "allow" && decision !== "deny") throw new InvalidResolutionError(`approval '${key}' resolves with { decision: 'allow' | 'deny', reason?, expiresAt? }`);
|
|
8371
|
+
const expiresAt = value?.expiresAt;
|
|
8372
|
+
if (expiresAt !== void 0 && (typeof expiresAt !== "string" || Number.isNaN(Date.parse(expiresAt)))) throw new InvalidResolutionError(`approval '${key}' expiresAt must be an ISO 8601 date string; got ` + JSON.stringify(expiresAt));
|
|
8356
8373
|
}
|
|
8357
8374
|
if (kind === "decision") {
|
|
8358
8375
|
const decisionKind = value?.kind;
|
|
@@ -8572,7 +8589,7 @@ var ExternalRegistry = class ExternalRegistry {
|
|
|
8572
8589
|
entry = matched.running;
|
|
8573
8590
|
replayed = true;
|
|
8574
8591
|
const state = this.replayer.suspensionState(entry.seq);
|
|
8575
|
-
if (state.state === "resolved") return toApprovalDecision(state.value);
|
|
8592
|
+
if (state.state === "resolved") return toApprovalDecision(state.value, entry.seq);
|
|
8576
8593
|
if (state.state === "abandoned") {
|
|
8577
8594
|
this.suspendActivity();
|
|
8578
8595
|
return new Promise(() => void 0);
|
|
@@ -8604,7 +8621,7 @@ var ExternalRegistry = class ExternalRegistry {
|
|
|
8604
8621
|
prompt: `approve tool '${options.toolName}'`,
|
|
8605
8622
|
resolve: (value) => {
|
|
8606
8623
|
resumeActivity();
|
|
8607
|
-
resolve(toApprovalDecision(value));
|
|
8624
|
+
resolve(toApprovalDecision(value, entry.seq));
|
|
8608
8625
|
}
|
|
8609
8626
|
};
|
|
8610
8627
|
if (entry.deadlineAt !== void 0) waiter.timer = setLongTimeout(() => {
|
|
@@ -8792,6 +8809,62 @@ var ExternalRegistry = class ExternalRegistry {
|
|
|
8792
8809
|
* resolvable this way only once the segment settled (closed registry),
|
|
8793
8810
|
* with the exact live-path validation and no wake.
|
|
8794
8811
|
*/
|
|
8812
|
+
/**
|
|
8813
|
+
* Revokes a tool approval (RV4008). A still-open approval is denied
|
|
8814
|
+
* through the ordinary first-closing-wins arbitration (a race with
|
|
8815
|
+
* a live allow stays deterministic by the journal). A RECORDED
|
|
8816
|
+
* allow cannot be unwritten (history is immutable): the revocation
|
|
8817
|
+
* appends an `approval_revoked` decision that beats the allow at
|
|
8818
|
+
* the consumption recheck, so an allow granted, crashed over, and
|
|
8819
|
+
* revoked never dispatches its tool on resume. A denied or
|
|
8820
|
+
* abandoned approval has nothing to revoke.
|
|
8821
|
+
*/
|
|
8822
|
+
async revokeApproval(key, options) {
|
|
8823
|
+
if (typeof options.principal !== "string" || options.principal.length === 0) throw new InvalidResolutionError("revokeApproval principal must be a non empty string");
|
|
8824
|
+
if (typeof options.reason !== "string" || options.reason.length === 0) throw new InvalidResolutionError("revokeApproval reason must be a non empty string");
|
|
8825
|
+
const candidates = this.replayer.snapshot().filter((entry) => ExternalRegistry.suspensionKeyOf(entry) === key && entry.kind === "approval");
|
|
8826
|
+
const target = candidates[candidates.length - 1];
|
|
8827
|
+
if (target === void 0) throw new InvalidResolutionError(`no approval suspension with key '${key}' in this run`);
|
|
8828
|
+
const state = this.replayer.suspensionState(target.seq);
|
|
8829
|
+
if (state.state === "suspended") {
|
|
8830
|
+
await this.resolveExternal(key, {
|
|
8831
|
+
decision: "deny",
|
|
8832
|
+
reason: `revoked by ${options.principal}: ${options.reason}`
|
|
8833
|
+
});
|
|
8834
|
+
return {
|
|
8835
|
+
state: "denied-pending",
|
|
8836
|
+
entryRef: target.seq
|
|
8837
|
+
};
|
|
8838
|
+
}
|
|
8839
|
+
if (state.state === "resolved" && state.value?.decision === "allow") {
|
|
8840
|
+
if (this.replayer.snapshot().some((entry) => entry.kind === "decision" && entry.value?.decisionType === "approval_revoked" && entry.value.targetRef === target.seq)) return {
|
|
8841
|
+
state: "already-revoked",
|
|
8842
|
+
entryRef: target.seq
|
|
8843
|
+
};
|
|
8844
|
+
await this.replayer.appendSinglePhase({
|
|
8845
|
+
scope: target.scope,
|
|
8846
|
+
key: `approval-revoked:${String(target.seq)}`,
|
|
8847
|
+
kind: "decision",
|
|
8848
|
+
status: "ok",
|
|
8849
|
+
spanId: target.spanId ?? "",
|
|
8850
|
+
site: "approval-revocation",
|
|
8851
|
+
value: {
|
|
8852
|
+
decisionType: "approval_revoked",
|
|
8853
|
+
targetRef: target.seq,
|
|
8854
|
+
principal: options.principal,
|
|
8855
|
+
reason: options.reason
|
|
8856
|
+
}
|
|
8857
|
+
});
|
|
8858
|
+
return {
|
|
8859
|
+
state: "revoked-allow",
|
|
8860
|
+
entryRef: target.seq
|
|
8861
|
+
};
|
|
8862
|
+
}
|
|
8863
|
+
return {
|
|
8864
|
+
state: "already-closed",
|
|
8865
|
+
entryRef: target.seq
|
|
8866
|
+
};
|
|
8867
|
+
}
|
|
8795
8868
|
async resolveDetached(key, value) {
|
|
8796
8869
|
const candidates = this.replayer.snapshot().filter((entry) => ExternalRegistry.suspensionKeyOf(entry) === key);
|
|
8797
8870
|
const open = candidates.find((entry) => this.replayer.suspensionState(entry.seq).state === "suspended");
|
|
@@ -9870,6 +9943,141 @@ function criticalPathFromJournal(entries) {
|
|
|
9870
9943
|
return path;
|
|
9871
9944
|
}
|
|
9872
9945
|
//#endregion
|
|
9946
|
+
//#region src/stores/repair-ledger.ts
|
|
9947
|
+
const failedNamesOf = (failed) => {
|
|
9948
|
+
if (!Array.isArray(failed)) return [];
|
|
9949
|
+
return failed.map((row) => typeof row.name === "string" ? String(row.name) : void 0).filter((name) => name !== void 0);
|
|
9950
|
+
};
|
|
9951
|
+
const sectionsOf = (sections) => {
|
|
9952
|
+
if (!Array.isArray(sections) || sections.length === 0) return;
|
|
9953
|
+
const markers = sections.filter((marker) => typeof marker === "string");
|
|
9954
|
+
return markers.length === 0 ? void 0 : markers;
|
|
9955
|
+
};
|
|
9956
|
+
/**
|
|
9957
|
+
* Folds the workflow-wide repair ledger from a journal (RV4002). Pure
|
|
9958
|
+
* over the entries, so the acceptance envelope's live aggregate
|
|
9959
|
+
* (computed from the run's own snapshot at assembly) and a post-hoc
|
|
9960
|
+
* fold over the persisted journal agree by construction on every
|
|
9961
|
+
* count and row identity; `wireRef`/`costUsd` enrich rows exactly when
|
|
9962
|
+
* the asynchronous billing lane covered them.
|
|
9963
|
+
*/
|
|
9964
|
+
function repairLedgerFromJournal(entries, priceUsd) {
|
|
9965
|
+
const ordered = [...entries].sort((a, b) => a.seq - b.seq);
|
|
9966
|
+
const rounds = [];
|
|
9967
|
+
const rowScopes = /* @__PURE__ */ new Map();
|
|
9968
|
+
let draft = 0;
|
|
9969
|
+
let composition = 0;
|
|
9970
|
+
let semantic = 0;
|
|
9971
|
+
let unstagedVerdicts = 0;
|
|
9972
|
+
/** Sectional acceptances by scope, to pair sections onto the rejection they healed. */
|
|
9973
|
+
const draftAccepts = [];
|
|
9974
|
+
const wireRows = [];
|
|
9975
|
+
for (const entry of ordered) {
|
|
9976
|
+
if (entry.kind === "agent" && entry.status !== "running" && entry.status !== "suspended") {
|
|
9977
|
+
if (entry.costAttribution?.label === "final-composition" && entry.costAttribution.phase === "repair") {
|
|
9978
|
+
semantic += 1;
|
|
9979
|
+
const trigger = entry.costAttribution.repairTrigger;
|
|
9980
|
+
const semanticRow = {
|
|
9981
|
+
stage: "semantic",
|
|
9982
|
+
seq: entry.seq,
|
|
9983
|
+
failedValidators: [],
|
|
9984
|
+
...trigger === "claim" || trigger === "citation" ? { trigger } : {}
|
|
9985
|
+
};
|
|
9986
|
+
rounds.push(semanticRow);
|
|
9987
|
+
rowScopes.set(semanticRow, entry.scope);
|
|
9988
|
+
}
|
|
9989
|
+
continue;
|
|
9990
|
+
}
|
|
9991
|
+
if (entry.kind !== "decision") continue;
|
|
9992
|
+
const value = entry.value;
|
|
9993
|
+
if (value === void 0) continue;
|
|
9994
|
+
if (value.decisionType === "provider-call") {
|
|
9995
|
+
const row = entry.value;
|
|
9996
|
+
if (row.record?.phase === "repair") wireRows.push({
|
|
9997
|
+
seq: entry.seq,
|
|
9998
|
+
scope: entry.scope,
|
|
9999
|
+
record: row.record
|
|
10000
|
+
});
|
|
10001
|
+
continue;
|
|
10002
|
+
}
|
|
10003
|
+
if (value.decisionType === "orchestrator_draft_gate") {
|
|
10004
|
+
if (value.verdict === "rejected") {
|
|
10005
|
+
draft += 1;
|
|
10006
|
+
const row = {
|
|
10007
|
+
stage: "draft",
|
|
10008
|
+
seq: entry.seq,
|
|
10009
|
+
...typeof value.callId === "string" ? { callId: value.callId } : {},
|
|
10010
|
+
failedValidators: failedNamesOf(value.failed)
|
|
10011
|
+
};
|
|
10012
|
+
rounds.push(row);
|
|
10013
|
+
rowScopes.set(row, entry.scope);
|
|
10014
|
+
} else if (value.verdict === "accepted" && value.spliced === true) {
|
|
10015
|
+
const sections = sectionsOf(value.sections);
|
|
10016
|
+
if (sections !== void 0) draftAccepts.push({
|
|
10017
|
+
seq: entry.seq,
|
|
10018
|
+
scope: entry.scope,
|
|
10019
|
+
sections
|
|
10020
|
+
});
|
|
10021
|
+
}
|
|
10022
|
+
continue;
|
|
10023
|
+
}
|
|
10024
|
+
if (value.decisionType === "orchestrator_finish_validation" && value.verdict === "repair") {
|
|
10025
|
+
if (value.stage !== "composition" && value.stage !== "round") {
|
|
10026
|
+
unstagedVerdicts += 1;
|
|
10027
|
+
continue;
|
|
10028
|
+
}
|
|
10029
|
+
composition += 1;
|
|
10030
|
+
const sections = sectionsOf(value.sections);
|
|
10031
|
+
const row = {
|
|
10032
|
+
stage: value.stage,
|
|
10033
|
+
seq: entry.seq,
|
|
10034
|
+
...typeof value.callId === "string" ? { callId: value.callId } : {},
|
|
10035
|
+
failedValidators: failedNamesOf(value.failed),
|
|
10036
|
+
...sections === void 0 ? {} : { sections }
|
|
10037
|
+
};
|
|
10038
|
+
rounds.push(row);
|
|
10039
|
+
rowScopes.set(row, entry.scope);
|
|
10040
|
+
continue;
|
|
10041
|
+
}
|
|
10042
|
+
if (value.decisionType === "orchestrator_finish_validation" && value.verdict === "accepted" && value.spliced === true) {
|
|
10043
|
+
const sections = sectionsOf(value.sections);
|
|
10044
|
+
if (sections !== void 0) draftAccepts.push({
|
|
10045
|
+
seq: entry.seq,
|
|
10046
|
+
scope: entry.scope,
|
|
10047
|
+
sections
|
|
10048
|
+
});
|
|
10049
|
+
}
|
|
10050
|
+
}
|
|
10051
|
+
for (const accept of draftAccepts) for (let index = rounds.length - 1; index >= 0; index -= 1) {
|
|
10052
|
+
const row = rounds[index];
|
|
10053
|
+
if (row === void 0 || row.seq >= accept.seq || row.sections !== void 0 || rowScopes.get(row) !== accept.scope) continue;
|
|
10054
|
+
row.sections = accept.sections;
|
|
10055
|
+
break;
|
|
10056
|
+
}
|
|
10057
|
+
for (const wire of wireRows) {
|
|
10058
|
+
let nearest;
|
|
10059
|
+
for (const row of rounds) {
|
|
10060
|
+
if (row.seq >= wire.seq || rowScopes.get(row) !== wire.scope) continue;
|
|
10061
|
+
nearest = row;
|
|
10062
|
+
}
|
|
10063
|
+
if (nearest === void 0 || nearest.wireRef !== void 0) continue;
|
|
10064
|
+
nearest.wireRef = wire.seq;
|
|
10065
|
+
if (priceUsd !== void 0 && wire.record.servedBy !== void 0) {
|
|
10066
|
+
const usd = priceUsd(wire.record.servedBy, wire.record.usage);
|
|
10067
|
+
if (usd !== void 0 && Number.isFinite(usd) && usd >= 0) nearest.costUsd = usd;
|
|
10068
|
+
}
|
|
10069
|
+
}
|
|
10070
|
+
rounds.sort((a, b) => a.seq - b.seq);
|
|
10071
|
+
return {
|
|
10072
|
+
draft,
|
|
10073
|
+
composition,
|
|
10074
|
+
semantic,
|
|
10075
|
+
total: draft + composition + semantic,
|
|
10076
|
+
rounds,
|
|
10077
|
+
unstagedVerdicts
|
|
10078
|
+
};
|
|
10079
|
+
}
|
|
10080
|
+
//#endregion
|
|
9873
10081
|
//#region src/stores/synthesis-candidates.ts
|
|
9874
10082
|
const parse = (at) => {
|
|
9875
10083
|
if (at === void 0) return;
|
|
@@ -10098,9 +10306,17 @@ function toolCalibrationFromJournal(entries) {
|
|
|
10098
10306
|
const budgetOnly = [];
|
|
10099
10307
|
let dispatches = 0;
|
|
10100
10308
|
let unobserved = 0;
|
|
10309
|
+
let coordinationDispatches = 0;
|
|
10310
|
+
let coordinationToolCalls = 0;
|
|
10101
10311
|
for (const entry of ordered) {
|
|
10102
10312
|
if (entry.kind !== "agent" || entry.ref === void 0 || entry.status === "running") continue;
|
|
10103
10313
|
dispatches += 1;
|
|
10314
|
+
const role = entry.costAttribution?.role;
|
|
10315
|
+
if ((role === "orchestrate" || role === "synthesize") && entry.toolBudget !== void 0 && entry.evidence === void 0) {
|
|
10316
|
+
coordinationDispatches += 1;
|
|
10317
|
+
coordinationToolCalls += entry.toolBudget.used;
|
|
10318
|
+
continue;
|
|
10319
|
+
}
|
|
10104
10320
|
const named = {
|
|
10105
10321
|
scope: entry.scope,
|
|
10106
10322
|
handle: entry.ref,
|
|
@@ -10123,7 +10339,11 @@ function toolCalibrationFromJournal(entries) {
|
|
|
10123
10339
|
observed,
|
|
10124
10340
|
evidenceOnly,
|
|
10125
10341
|
budgetOnly,
|
|
10126
|
-
unobserved
|
|
10342
|
+
unobserved,
|
|
10343
|
+
...coordinationDispatches > 0 ? { coordination: {
|
|
10344
|
+
dispatches: coordinationDispatches,
|
|
10345
|
+
toolCallsUsed: coordinationToolCalls
|
|
10346
|
+
} } : {}
|
|
10127
10347
|
};
|
|
10128
10348
|
if (observed.length > 0) {
|
|
10129
10349
|
const toolCallsUsed = observed.reduce((sum, row) => sum + row.toolCallsUsed, 0);
|
|
@@ -10939,6 +11159,19 @@ function fallbackTriggerOf(outcome) {
|
|
|
10939
11159
|
}
|
|
10940
11160
|
//#endregion
|
|
10941
11161
|
//#region src/model/projector.ts
|
|
11162
|
+
/**
|
|
11163
|
+
* The RETENTION identity of an adapter (RV4007): the provider family,
|
|
11164
|
+
* composed with the adapter's declared `scopeKey` when one exists, so
|
|
11165
|
+
* two adapters of one family serving different accounts stop sharing
|
|
11166
|
+
* provider-raw blocks (cache handles, thinking blocks: provider-side
|
|
11167
|
+
* identifiers minted under one account are not portable to another).
|
|
11168
|
+
* Adapters without a scopeKey keep the family alone, byte for byte
|
|
11169
|
+
* the historical sharing.
|
|
11170
|
+
*/
|
|
11171
|
+
function retentionKeyOf(adapter) {
|
|
11172
|
+
const family = providerOf(adapter);
|
|
11173
|
+
return adapter.scopeKey === void 0 ? family : `${family}#${adapter.scopeKey}`;
|
|
11174
|
+
}
|
|
10942
11175
|
/** The provider family of an adapter: `provider` when set, else `id`. */
|
|
10943
11176
|
function providerOf(adapter) {
|
|
10944
11177
|
return adapter.provider ?? adapter.id;
|
|
@@ -10975,7 +11208,7 @@ function liftRetainedParts(providerMetadata, adapter) {
|
|
|
10975
11208
|
const retained = namespace.retainedParts;
|
|
10976
11209
|
if (!Array.isArray(retained)) return [];
|
|
10977
11210
|
const blocks = retained;
|
|
10978
|
-
const provider =
|
|
11211
|
+
const provider = retentionKeyOf(adapter);
|
|
10979
11212
|
return blocks.map((block) => ({
|
|
10980
11213
|
type: "provider-raw",
|
|
10981
11214
|
provider,
|
|
@@ -13632,6 +13865,13 @@ async function runAgent(options) {
|
|
|
13632
13865
|
reservationId = decision.reservationId;
|
|
13633
13866
|
const abandoned = await abortedAfterReserve(quota, decision.reservationId);
|
|
13634
13867
|
if (abandoned !== void 0) return abandoned;
|
|
13868
|
+
if (options.billing?.onProviderIntent !== void 0) await options.billing.onProviderIntent({
|
|
13869
|
+
ordinal: providerCalls.length + 1,
|
|
13870
|
+
role: site.role,
|
|
13871
|
+
servedBy: target.resolved.ref,
|
|
13872
|
+
attempt: tries + 1,
|
|
13873
|
+
request: req
|
|
13874
|
+
});
|
|
13635
13875
|
if (quota.reserveContinuations !== true) return streamTurn(target.adapter, req, meteredOptionsFor(target));
|
|
13636
13876
|
const hooks = { onContinuationSegment: async () => {
|
|
13637
13877
|
let segmentDecision;
|
|
@@ -13688,6 +13928,14 @@ async function runAgent(options) {
|
|
|
13688
13928
|
if (options.quota === void 0) {
|
|
13689
13929
|
const req = site.requestFor(target);
|
|
13690
13930
|
admitExposure(req);
|
|
13931
|
+
const intentHook = options.billing?.onProviderIntent;
|
|
13932
|
+
if (intentHook !== void 0) return Promise.resolve(intentHook({
|
|
13933
|
+
ordinal: providerCalls.length + 1,
|
|
13934
|
+
role: site.role,
|
|
13935
|
+
servedBy: target.resolved.ref,
|
|
13936
|
+
attempt: tries + 1,
|
|
13937
|
+
request: req
|
|
13938
|
+
})).then(() => streamTurn(target.adapter, req, meteredOptionsFor(target)));
|
|
13691
13939
|
return streamTurn(target.adapter, req, meteredOptionsFor(target));
|
|
13692
13940
|
}
|
|
13693
13941
|
return dispatchWithQuota(options.quota);
|
|
@@ -13781,6 +14029,7 @@ async function runAgent(options) {
|
|
|
13781
14029
|
outcome: outcome.aborted !== void 0 ? "aborted" : outcome.wireError !== void 0 ? "error" : "ok",
|
|
13782
14030
|
usage: accounted
|
|
13783
14031
|
};
|
|
14032
|
+
if (site.phase !== void 0) record.phase = site.phase;
|
|
13784
14033
|
if (typeof namespace?.responseId === "string") record.responseId = namespace.responseId;
|
|
13785
14034
|
else if (typeof namespace?.response?.id === "string") record.responseId = namespace.response.id;
|
|
13786
14035
|
const wire = namespace?.wireRequests;
|
|
@@ -13936,7 +14185,7 @@ async function runAgent(options) {
|
|
|
13936
14185
|
chain: loopChain,
|
|
13937
14186
|
cursor: loopCursor,
|
|
13938
14187
|
requestFor: (target) => {
|
|
13939
|
-
let req = buildRequest(target.resolved, projectHistory(drainMessages,
|
|
14188
|
+
let req = buildRequest(target.resolved, projectHistory(drainMessages, retentionKeyOf(target.adapter)), limits, toolsRide ? allowedTools : void 0);
|
|
13940
14189
|
const reserveMax = limits.finalizationReserve?.maxOutputTokens;
|
|
13941
14190
|
if (reserveMax !== void 0) req = {
|
|
13942
14191
|
...req,
|
|
@@ -14015,16 +14264,19 @@ async function runAgent(options) {
|
|
|
14015
14264
|
break;
|
|
14016
14265
|
}
|
|
14017
14266
|
turns += 1;
|
|
14267
|
+
const lastWindowMessage = messages[messages.length - 1];
|
|
14268
|
+
const repairTurnWire = options.terminalTool !== void 0 && lastWindowMessage !== void 0 && lastWindowMessage.parts.some((part) => part.type === "tool-result" && part.name === options.terminalTool?.name && part.isError === true);
|
|
14018
14269
|
const signals = [];
|
|
14019
14270
|
if (options.signal !== void 0) signals.push(options.signal);
|
|
14020
14271
|
let loopDispatch;
|
|
14021
14272
|
try {
|
|
14022
14273
|
loopDispatch = await dispatchPhase({
|
|
14023
14274
|
role: primaryRole,
|
|
14275
|
+
...repairTurnWire ? { phase: "repair" } : {},
|
|
14024
14276
|
chain: loopChain,
|
|
14025
14277
|
cursor: loopCursor,
|
|
14026
14278
|
requestFor: (target) => {
|
|
14027
|
-
let req = buildRequest(target.resolved, projectHistory(messages,
|
|
14279
|
+
let req = buildRequest(target.resolved, projectHistory(messages, retentionKeyOf(target.adapter)), limits, options.tools?.contracts);
|
|
14028
14280
|
if (options.schema !== void 0 && options.canonicalSchema !== void 0 && !separateExtract) req = applyStructuredOutputTier(req, rideTierFor(target), options.canonicalSchema);
|
|
14029
14281
|
req = applyCachePolicy(req, target, options.cache);
|
|
14030
14282
|
return applyOutputBudget(req, target, options.budget);
|
|
@@ -14248,7 +14500,7 @@ async function runAgent(options) {
|
|
|
14248
14500
|
}, ...options.summarize.fallbacks ?? []],
|
|
14249
14501
|
cursor: { index: 0 },
|
|
14250
14502
|
requestFor: (target) => {
|
|
14251
|
-
let req = buildRequest(target.resolved, [...projectHistory(messages,
|
|
14503
|
+
let req = buildRequest(target.resolved, [...projectHistory(messages, retentionKeyOf(target.adapter)), summarizeInstruction()], limits, options.tools?.contracts);
|
|
14252
14504
|
if (req.tools !== void 0) req = {
|
|
14253
14505
|
...req,
|
|
14254
14506
|
toolChoice: "none"
|
|
@@ -14435,7 +14687,7 @@ async function runAgent(options) {
|
|
|
14435
14687
|
chain: loopChain,
|
|
14436
14688
|
cursor: loopCursor,
|
|
14437
14689
|
requestFor: (target) => {
|
|
14438
|
-
let req = buildRequest(target.resolved, projectHistory(reserveMessages,
|
|
14690
|
+
let req = buildRequest(target.resolved, projectHistory(reserveMessages, retentionKeyOf(target.adapter)), limits, options.tools?.contracts);
|
|
14439
14691
|
if (options.schema !== void 0 && options.canonicalSchema !== void 0 && !separateExtract) req = applyStructuredOutputTier(req, rideTierFor(target), options.canonicalSchema);
|
|
14440
14692
|
if (req.tools !== void 0) req = {
|
|
14441
14693
|
...req,
|
|
@@ -14571,7 +14823,7 @@ async function runAgent(options) {
|
|
|
14571
14823
|
}, ...options.finalize.fallbacks ?? []],
|
|
14572
14824
|
cursor: { index: 0 },
|
|
14573
14825
|
requestFor: (target) => applyOutputBudget({
|
|
14574
|
-
...buildRequest(target.resolved, projectHistory(synthesisMessages,
|
|
14826
|
+
...buildRequest(target.resolved, projectHistory(synthesisMessages, retentionKeyOf(target.adapter)), limits, options.tools?.contracts),
|
|
14575
14827
|
toolChoice: "none"
|
|
14576
14828
|
}, target, options.budget),
|
|
14577
14829
|
streamOptionsFor: (target) => {
|
|
@@ -14690,7 +14942,7 @@ async function runAgent(options) {
|
|
|
14690
14942
|
cursor: extractCursor,
|
|
14691
14943
|
requestFor: (target) => {
|
|
14692
14944
|
const targetTier = extractTierFor(target);
|
|
14693
|
-
let req = buildRequest(target.resolved, projectHistory(extractMessages,
|
|
14945
|
+
let req = buildRequest(target.resolved, projectHistory(extractMessages, retentionKeyOf(target.adapter)), limits, options.tools?.contracts);
|
|
14694
14946
|
if (req.tools !== void 0 && targetTier !== "forced-tool") req = {
|
|
14695
14947
|
...req,
|
|
14696
14948
|
toolChoice: "none"
|
|
@@ -16072,7 +16324,12 @@ function costReportFromJournal(entries, priceUsd) {
|
|
|
16072
16324
|
if (entry.usageApprox === true) usageApprox = true;
|
|
16073
16325
|
const facts = entry.costAttribution;
|
|
16074
16326
|
const phase = attributionBucket(facts?.phase);
|
|
16075
|
-
|
|
16327
|
+
let phaseUsd = priced.usd;
|
|
16328
|
+
for (const unit of priced.units) if (unit.source === "call" && unit.record?.phase === "repair") {
|
|
16329
|
+
byPhase.repair = (byPhase.repair ?? 0) + unit.usd;
|
|
16330
|
+
phaseUsd -= unit.usd;
|
|
16331
|
+
}
|
|
16332
|
+
byPhase[phase] = (byPhase[phase] ?? 0) + phaseUsd;
|
|
16076
16333
|
const agentType = attributionBucket(facts?.agentType);
|
|
16077
16334
|
byAgentType[agentType] = (byAgentType[agentType] ?? 0) + priced.usd;
|
|
16078
16335
|
const scope = scopeBucket(entry.scope);
|
|
@@ -16361,6 +16618,48 @@ function rowUsd(priceUsd, servedBy, usage, seq) {
|
|
|
16361
16618
|
return usd !== void 0 && Number.isFinite(usd) && usd >= 0 ? usd : void 0;
|
|
16362
16619
|
}
|
|
16363
16620
|
/**
|
|
16621
|
+
* The open provider wire intents of a journal (RV4006): every
|
|
16622
|
+
* `provider-intent` decision with neither a `provider-call` receipt
|
|
16623
|
+
* row nor a settled terminal record covering its (agentRef, ordinal,
|
|
16624
|
+
* attempt). ONE pairing rule, shared by the invoice's `openIntents`
|
|
16625
|
+
* lane and the resume refusal, the dispatchProjectionReserveUsd
|
|
16626
|
+
* precedent: the linter and the gate cannot drift.
|
|
16627
|
+
*/
|
|
16628
|
+
function openWireIntentsOf(entries) {
|
|
16629
|
+
const terminals = /* @__PURE__ */ new Map();
|
|
16630
|
+
const receipts = /* @__PURE__ */ new Set();
|
|
16631
|
+
const intents = [];
|
|
16632
|
+
for (const entry of entries) {
|
|
16633
|
+
if (entry.kind === "agent" && entry.status !== "running" && typeof entry.ref === "number") {
|
|
16634
|
+
terminals.set(entry.ref, entry);
|
|
16635
|
+
continue;
|
|
16636
|
+
}
|
|
16637
|
+
if (entry.kind !== "decision") continue;
|
|
16638
|
+
const value = entry.value;
|
|
16639
|
+
if (value?.decisionType === "provider-call" && typeof value.agentRef === "number") {
|
|
16640
|
+
const ordinal = value.record?.ordinal;
|
|
16641
|
+
const attempt = typeof value.record?.attempt === "number" ? value.record.attempt : 1;
|
|
16642
|
+
if (typeof ordinal === "number") receipts.add(`${String(value.agentRef)}:${String(ordinal)}:${String(attempt)}`);
|
|
16643
|
+
continue;
|
|
16644
|
+
}
|
|
16645
|
+
if (value?.decisionType === "provider-intent" && typeof value.agentRef === "number" && typeof value.ordinal === "number" && typeof value.attempt === "number" && typeof value.servedBy === "string") intents.push({
|
|
16646
|
+
seq: entry.seq,
|
|
16647
|
+
scope: entry.scope,
|
|
16648
|
+
agentRef: value.agentRef,
|
|
16649
|
+
ordinal: value.ordinal,
|
|
16650
|
+
attempt: value.attempt,
|
|
16651
|
+
servedBy: value.servedBy,
|
|
16652
|
+
...typeof value.requestFingerprint === "string" ? { requestFingerprint: value.requestFingerprint } : {}
|
|
16653
|
+
});
|
|
16654
|
+
}
|
|
16655
|
+
return intents.filter((intent) => {
|
|
16656
|
+
if (receipts.has(`${String(intent.agentRef)}:${String(intent.ordinal)}:${String(intent.attempt)}`)) return false;
|
|
16657
|
+
const terminal = terminals.get(intent.agentRef);
|
|
16658
|
+
if (terminal === void 0) return true;
|
|
16659
|
+
return !(terminal.providerCalls ?? []).some((call) => call.ordinal === intent.ordinal && call.attempt === intent.attempt);
|
|
16660
|
+
});
|
|
16661
|
+
}
|
|
16662
|
+
/**
|
|
16364
16663
|
* The pure invoice fold. Pass the same entries and price table you
|
|
16365
16664
|
* would pass `costReportFromJournal`; the totals are that report's
|
|
16366
16665
|
* gross/net split verbatim. To make the export historically stable
|
|
@@ -16526,6 +16825,21 @@ function invoiceFromJournal(entries, priceUsd, options) {
|
|
|
16526
16825
|
cardinality: cardinalityOf(rows),
|
|
16527
16826
|
...unsettled === void 0 ? {} : { unsettled },
|
|
16528
16827
|
...orphanedReceipts === void 0 ? {} : { orphanedReceipts },
|
|
16828
|
+
...(() => {
|
|
16829
|
+
for (const entry of entries) {
|
|
16830
|
+
if (entry.kind !== "decision") continue;
|
|
16831
|
+
const value = entry.value;
|
|
16832
|
+
if (value?.decisionType === "execution_scope" && typeof value.scope === "object") return { executionScope: value.scope };
|
|
16833
|
+
}
|
|
16834
|
+
return {};
|
|
16835
|
+
})(),
|
|
16836
|
+
...(() => {
|
|
16837
|
+
const open = openWireIntentsOf(entries);
|
|
16838
|
+
return open.length === 0 ? {} : { openIntents: {
|
|
16839
|
+
count: open.length,
|
|
16840
|
+
rows: open
|
|
16841
|
+
} };
|
|
16842
|
+
})(),
|
|
16529
16843
|
...(() => {
|
|
16530
16844
|
const count = rows.filter((row) => row.usageUnknown === true).length;
|
|
16531
16845
|
return count === 0 ? {} : { usageUnknownRows: count };
|
|
@@ -17134,7 +17448,7 @@ const TERMINAL_STATUSES = /* @__PURE__ */ new Set([
|
|
|
17134
17448
|
"exhausted",
|
|
17135
17449
|
"suspended"
|
|
17136
17450
|
]);
|
|
17137
|
-
function refuse(reason, message = REFUSAL_MESSAGES[reason]) {
|
|
17451
|
+
function refuse$1(reason, message = REFUSAL_MESSAGES[reason]) {
|
|
17138
17452
|
return {
|
|
17139
17453
|
available: false,
|
|
17140
17454
|
reason,
|
|
@@ -17150,17 +17464,17 @@ function refuse(reason, message = REFUSAL_MESSAGES[reason]) {
|
|
|
17150
17464
|
*/
|
|
17151
17465
|
function persistedTerminalEnvelope(input) {
|
|
17152
17466
|
const settle = lastRunSettle(input.entries);
|
|
17153
|
-
if (settle === void 0) return refuse("unsettled");
|
|
17154
|
-
if (!TERMINAL_STATUSES.has(settle.runStatus)) return refuse("not-terminal");
|
|
17467
|
+
if (settle === void 0) return refuse$1("unsettled");
|
|
17468
|
+
if (!TERMINAL_STATUSES.has(settle.runStatus)) return refuse$1("not-terminal");
|
|
17155
17469
|
const tail = input.entries.filter((entry) => entry.seq > settle.seq).length;
|
|
17156
|
-
if (tail > 0) return refuse("not-terminal", `the journal continued ${String(tail)} entr${tail === 1 ? "y" : "ies"} past the settle at seq ${String(settle.seq)}: the latest segment is not settled`);
|
|
17470
|
+
if (tail > 0) return refuse$1("not-terminal", `the journal continued ${String(tail)} entr${tail === 1 ? "y" : "ies"} past the settle at seq ${String(settle.seq)}: the latest segment is not settled`);
|
|
17157
17471
|
const workflow = input.meta?.workflowName;
|
|
17158
|
-
if (workflow === void 0) return refuse("unknown-workflow");
|
|
17472
|
+
if (workflow === void 0) return refuse$1("unknown-workflow");
|
|
17159
17473
|
try {
|
|
17160
17474
|
return assemble(input, workflow, settle);
|
|
17161
17475
|
} catch (error) {
|
|
17162
17476
|
const detail = error instanceof Error ? error.message : String(error);
|
|
17163
|
-
return refuse("malformed-envelope", `${REFUSAL_MESSAGES["malformed-envelope"]}: ${detail}`);
|
|
17477
|
+
return refuse$1("malformed-envelope", `${REFUSAL_MESSAGES["malformed-envelope"]}: ${detail}`);
|
|
17164
17478
|
}
|
|
17165
17479
|
}
|
|
17166
17480
|
function assemble(input, workflow, settle) {
|
|
@@ -17784,6 +18098,117 @@ function dispatchProjectionReserveUsd(spec, flatReserveUsd) {
|
|
|
17784
18098
|
const base = spec.estCostUsd ?? flatReserveUsd;
|
|
17785
18099
|
return spec.budgetUsd === void 0 ? base : Math.min(base, spec.budgetUsd);
|
|
17786
18100
|
}
|
|
18101
|
+
/**
|
|
18102
|
+
* Worst-case claim judge dispatches of a declared posture
|
|
18103
|
+
* (RV3402/RV4001): `'both'` dispatches the judge at the draft AND the
|
|
18104
|
+
* final, and an armed repair round (`onFound: 'repair'`, which intake
|
|
18105
|
+
* refuses at stage 'draft') rejudges the repaired composition once
|
|
18106
|
+
* more. Absent declarations read as the historical one pass.
|
|
18107
|
+
*/
|
|
18108
|
+
function acceptanceJudgePasses(stage, onFound) {
|
|
18109
|
+
const resolvedStage = stage ?? "draft";
|
|
18110
|
+
return (resolvedStage === "both" ? 2 : 1) + ((onFound ?? "report") === "repair" && resolvedStage !== "draft" ? 1 : 0);
|
|
18111
|
+
}
|
|
18112
|
+
/**
|
|
18113
|
+
* The ONE acceptance-tail formula (RV4001, the fifth comparison
|
|
18114
|
+
* experiment): what the effective cap must cover, at exact fill or
|
|
18115
|
+
* better, so the acceptance machinery the host declared is funded and
|
|
18116
|
+
* not started on luck. The RV3907 runtime gate landed WITHOUT a
|
|
18117
|
+
* preflight twin: preflight kept its own advisory arithmetic on
|
|
18118
|
+
* different terms, passed the experiment's plan green at a $4.54 cap,
|
|
18119
|
+
* and the runtime then refused the same plan typed at $4.82 before the
|
|
18120
|
+
* first wire; worse, the runtime undercounted the judge passes of
|
|
18121
|
+
* `stage: 'both'` (one where the worst case dispatches two) while
|
|
18122
|
+
* preflight counted them right, so the two calculators disagreed in
|
|
18123
|
+
* BOTH directions. The gate and the preflight `acceptanceReserve`
|
|
18124
|
+
* report block now both call this function, exactly the
|
|
18125
|
+
* {@link dispatchProjectionReserveUsd} precedent: one formula, so the
|
|
18126
|
+
* linter and the runtime cannot drift. Undeclared estimates contribute
|
|
18127
|
+
* zero: the tail binds exactly what the host declared. The armed
|
|
18128
|
+
* repair round (`onFound: 'repair'`, never at stage 'draft', which
|
|
18129
|
+
* intake refuses) adds one judge pass and one composition priced at
|
|
18130
|
+
* the declared `synthesis.estCost`.
|
|
18131
|
+
*/
|
|
18132
|
+
function acceptanceTailRequiredUsd(spec) {
|
|
18133
|
+
const stage = spec.claimStage ?? "draft";
|
|
18134
|
+
const onFound = spec.claimOnFound ?? "report";
|
|
18135
|
+
const citationDeclared = spec.citationJudgeEstCostUsd !== void 0 || spec.citationOnFound !== void 0;
|
|
18136
|
+
const citationRoundArmed = spec.citationOnFound === "repair";
|
|
18137
|
+
const roundArmed = onFound === "repair" && stage !== "draft" || citationRoundArmed;
|
|
18138
|
+
const judgePasses = acceptanceJudgePasses(spec.claimStage, spec.claimOnFound) + (citationRoundArmed && spec.claimConfigured === true && stage !== "draft" ? 1 : 0);
|
|
18139
|
+
const citationJudgePasses = citationDeclared ? 1 + (citationRoundArmed ? 1 : 0) : 0;
|
|
18140
|
+
const citationJudgeEstUsd = spec.citationJudgeEstCostUsd ?? 0;
|
|
18141
|
+
const terms = {
|
|
18142
|
+
synthesisReserveUsd: spec.synthesisReserveUsd ?? 0,
|
|
18143
|
+
judgeEstUsd: spec.claimJudgeEstCostUsd ?? 0,
|
|
18144
|
+
judgePasses,
|
|
18145
|
+
estRepairCostUsd: spec.finishEstRepairCostUsd ?? 0,
|
|
18146
|
+
roundCompositionUsd: roundArmed ? spec.synthesisEstCostUsd ?? 0 : 0,
|
|
18147
|
+
...citationDeclared ? {
|
|
18148
|
+
citationJudgeEstUsd,
|
|
18149
|
+
citationJudgePasses
|
|
18150
|
+
} : {},
|
|
18151
|
+
workingRoomUsd: spec.workingRoomUsd
|
|
18152
|
+
};
|
|
18153
|
+
return {
|
|
18154
|
+
requiredUsd: terms.synthesisReserveUsd + terms.judgeEstUsd * terms.judgePasses + terms.estRepairCostUsd + terms.roundCompositionUsd + citationJudgeEstUsd * citationJudgePasses + terms.workingRoomUsd,
|
|
18155
|
+
terms
|
|
18156
|
+
};
|
|
18157
|
+
}
|
|
18158
|
+
/**
|
|
18159
|
+
* The one rendering of the tail arithmetic (RV4001): the runtime
|
|
18160
|
+
* refusal message and the preflight finding print this same string, so
|
|
18161
|
+
* an operator can diff them by eye and a test can assert them equal.
|
|
18162
|
+
*/
|
|
18163
|
+
function formatAcceptanceTailTerms(terms) {
|
|
18164
|
+
const citationUsd = (terms.citationJudgeEstUsd ?? 0) * (terms.citationJudgePasses ?? 0);
|
|
18165
|
+
const requiredUsd = terms.synthesisReserveUsd + terms.judgeEstUsd * terms.judgePasses + terms.estRepairCostUsd + terms.roundCompositionUsd + citationUsd + terms.workingRoomUsd;
|
|
18166
|
+
return `synthesisReserveUsd ${terms.synthesisReserveUsd.toFixed(4)} + judge ${terms.judgeEstUsd.toFixed(4)} x ${String(terms.judgePasses)} pass(es) + estRepairCostUsd ${terms.estRepairCostUsd.toFixed(4)} + round composition ${terms.roundCompositionUsd.toFixed(4)} + ` + (terms.citationJudgePasses === void 0 || terms.citationJudgePasses === 0 ? "" : `citation judge ${(terms.citationJudgeEstUsd ?? 0).toFixed(4)} x ${String(terms.citationJudgePasses)} pass(es) + `) + `working room ${terms.workingRoomUsd.toFixed(4)} = ${requiredUsd.toFixed(4)} USD`;
|
|
18167
|
+
}
|
|
18168
|
+
/**
|
|
18169
|
+
* The wire capacity of a declared orchestration plan (RV4005, the
|
|
18170
|
+
* fifth comparison experiment): base wires by declaration, the armed
|
|
18171
|
+
* repair round's delta, and the round's overhead share, from ONE
|
|
18172
|
+
* exported function so an answer about the runtime's own economics
|
|
18173
|
+
* has a source instead of an improvisation. The experiment's terminal
|
|
18174
|
+
* answer wrote "34 wires without repair, 35 with" and multiplied
|
|
18175
|
+
* retry share as `1 + r`: the round is TWO wires (its composition
|
|
18176
|
+
* plus the rejudge, `orchestrate.ts`'s own doctrine), so 34 becomes
|
|
18177
|
+
* 36 at 5.88 percent overhead, and r retries over a base of B
|
|
18178
|
+
* multiply wires by `1 + r/B` ({@link retryWireMultiplier}), not by
|
|
18179
|
+
* `1 + r`.
|
|
18180
|
+
*/
|
|
18181
|
+
function wireCapacityEstimate(spec) {
|
|
18182
|
+
requireNonNegativeNumber(spec.childWires, "wireCapacityEstimate childWires");
|
|
18183
|
+
const coordinationWires = spec.coordinationWires ?? 0;
|
|
18184
|
+
const synthesisWires = spec.synthesisWires ?? 0;
|
|
18185
|
+
const judgeWires = spec.judgeWires ?? 0;
|
|
18186
|
+
const extractWires = spec.extractWires ?? 0;
|
|
18187
|
+
requireNonNegativeNumber(coordinationWires, "wireCapacityEstimate coordinationWires");
|
|
18188
|
+
requireNonNegativeNumber(synthesisWires, "wireCapacityEstimate synthesisWires");
|
|
18189
|
+
requireNonNegativeNumber(judgeWires, "wireCapacityEstimate judgeWires");
|
|
18190
|
+
requireNonNegativeNumber(extractWires, "wireCapacityEstimate extractWires");
|
|
18191
|
+
const baseWires = spec.childWires + coordinationWires + synthesisWires + judgeWires + extractWires;
|
|
18192
|
+
const repairRoundDeltaWires = 2;
|
|
18193
|
+
return {
|
|
18194
|
+
baseWires,
|
|
18195
|
+
repairRoundDeltaWires,
|
|
18196
|
+
mechanicalRepairDeltaWires: 1,
|
|
18197
|
+
wiresWithRound: baseWires + repairRoundDeltaWires,
|
|
18198
|
+
roundOverheadShare: baseWires === 0 ? 0 : repairRoundDeltaWires / baseWires
|
|
18199
|
+
};
|
|
18200
|
+
}
|
|
18201
|
+
/**
|
|
18202
|
+
* The retry share of a wire plan (RV4005): r retries over a base of B
|
|
18203
|
+
* wires re-dispatch r of the B, so totals scale by `1 + r/B`. The
|
|
18204
|
+
* fifth comparison run's answer multiplied by `1 + r`, reading every
|
|
18205
|
+
* retry as a whole extra plan.
|
|
18206
|
+
*/
|
|
18207
|
+
function retryWireMultiplier(baseWires, retries) {
|
|
18208
|
+
requireNonNegativeNumber(retries, "retryWireMultiplier retries");
|
|
18209
|
+
if (!Number.isFinite(baseWires) || baseWires <= 0) throw new ConfigError(`retryWireMultiplier baseWires must be a positive finite number; got ${String(baseWires)}`);
|
|
18210
|
+
return 1 + retries / baseWires;
|
|
18211
|
+
}
|
|
17787
18212
|
/** Nesting depth of a child scope: its workflow, agent, and plan-node segments. */
|
|
17788
18213
|
function spawnDepthOf(childScope) {
|
|
17789
18214
|
return parseScopePath(childScope).filter((segment) => segment.kind === "workflow" || segment.kind === "agent" || segment.kind === "plan-node").length;
|
|
@@ -19214,7 +19639,12 @@ function createCtx(internals, rootWorkflow) {
|
|
|
19214
19639
|
model: slice.servedBy,
|
|
19215
19640
|
usage: slice.usage
|
|
19216
19641
|
});
|
|
19217
|
-
|
|
19642
|
+
let replayPhaseUsd = costUsd;
|
|
19643
|
+
for (const unit of replayPriced?.units ?? []) if (unit.source === "call" && unit.record?.phase === "repair") {
|
|
19644
|
+
bump(internals.cost.byPhase, "repair", unit.usd);
|
|
19645
|
+
replayPhaseUsd -= unit.usd;
|
|
19646
|
+
}
|
|
19647
|
+
bump(internals.cost.byPhase, state.phase ?? "", replayPhaseUsd);
|
|
19218
19648
|
bump(internals.cost.byAgentType, agentType, costUsd);
|
|
19219
19649
|
bump(internals.cost.byScope, state.scope, costUsd);
|
|
19220
19650
|
internals.cost.byRole.set(primaryRole, (internals.cost.byRole.get(primaryRole) ?? 0) + costUsd);
|
|
@@ -19528,7 +19958,7 @@ function createCtx(internals, rootWorkflow) {
|
|
|
19528
19958
|
suspend: async () => {
|
|
19529
19959
|
if (internals.external === void 0) throw new ConfigError("tool approvals require the engine run context (createEngine)");
|
|
19530
19960
|
const approvalDeadlineMs = chain.approvalDeadlineMs;
|
|
19531
|
-
|
|
19961
|
+
const decision = await internals.external.awaitApproval({
|
|
19532
19962
|
scope: agentScope(state.scope, running.seq),
|
|
19533
19963
|
spanId: internals.spans.mint(spanId),
|
|
19534
19964
|
toolName: call.name,
|
|
@@ -19541,6 +19971,22 @@ function createCtx(internals, rootWorkflow) {
|
|
|
19541
19971
|
entryRef: entry.seq
|
|
19542
19972
|
}, spanId, replayed)
|
|
19543
19973
|
});
|
|
19974
|
+
if (decision.decision !== "allow") return decision;
|
|
19975
|
+
if (decision.entryRef !== void 0) {
|
|
19976
|
+
const revocation = internals.replayer.snapshot().find((entry) => entry.kind === "decision" && entry.value?.decisionType === "approval_revoked" && entry.value.targetRef === decision.entryRef);
|
|
19977
|
+
if (revocation !== void 0) {
|
|
19978
|
+
const why = revocation.value ?? {};
|
|
19979
|
+
return {
|
|
19980
|
+
decision: "deny",
|
|
19981
|
+
reason: `the recorded allow was revoked by ${typeof why.principal === "string" ? why.principal : "unknown"}: ${typeof why.reason === "string" ? why.reason : "no reason recorded"}`
|
|
19982
|
+
};
|
|
19983
|
+
}
|
|
19984
|
+
}
|
|
19985
|
+
if (decision.expiresAt !== void 0 && !(Date.parse(decision.expiresAt) >= internals.now())) return {
|
|
19986
|
+
decision: "deny",
|
|
19987
|
+
reason: `the recorded allow expired at ${decision.expiresAt}`
|
|
19988
|
+
};
|
|
19989
|
+
return decision;
|
|
19544
19990
|
}
|
|
19545
19991
|
};
|
|
19546
19992
|
}
|
|
@@ -19628,28 +20074,47 @@ function createCtx(internals, rootWorkflow) {
|
|
|
19628
20074
|
const cachePolicy = opts.cache ?? profile?.cache ?? internals.defaults.cache;
|
|
19629
20075
|
if (cachePolicy !== void 0) runAgentOptions.cache = cachePolicy;
|
|
19630
20076
|
}
|
|
19631
|
-
runAgentOptions.billing = {
|
|
19632
|
-
|
|
20077
|
+
runAgentOptions.billing = {
|
|
20078
|
+
onProviderCall: (record) => {
|
|
20079
|
+
const append = internals.replayer.appendSinglePhase({
|
|
20080
|
+
scope: state.scope,
|
|
20081
|
+
key: `pc:${String(running.seq)}:${String(record.ordinal)}`,
|
|
20082
|
+
kind: "decision",
|
|
20083
|
+
status: "ok",
|
|
20084
|
+
spanId,
|
|
20085
|
+
site: "provider-call",
|
|
20086
|
+
value: {
|
|
20087
|
+
decisionType: "provider-call",
|
|
20088
|
+
agentRef: running.seq,
|
|
20089
|
+
record
|
|
20090
|
+
}
|
|
20091
|
+
}).then(() => void 0).catch((thrown) => {
|
|
20092
|
+
internals.events.emit({
|
|
20093
|
+
type: "log",
|
|
20094
|
+
level: "warn",
|
|
20095
|
+
msg: `incremental billing row failed to append; the terminal entry remains the canonical record (${thrown instanceof Error ? thrown.message : String(thrown)})`
|
|
20096
|
+
}, spanId);
|
|
20097
|
+
});
|
|
20098
|
+
if (internals.defaults.billingReceipts === "awaited" || internals.defaults.billingReceipts === "intent") return append;
|
|
20099
|
+
},
|
|
20100
|
+
...internals.defaults.billingReceipts === "intent" ? { onProviderIntent: (intent) => internals.replayer.appendSinglePhase({
|
|
19633
20101
|
scope: state.scope,
|
|
19634
|
-
key: `
|
|
20102
|
+
key: `pi:${String(running.seq)}:${String(intent.ordinal)}:${String(intent.attempt)}`,
|
|
19635
20103
|
kind: "decision",
|
|
19636
20104
|
status: "ok",
|
|
19637
20105
|
spanId,
|
|
19638
|
-
site: "provider-
|
|
20106
|
+
site: "provider-intent",
|
|
19639
20107
|
value: {
|
|
19640
|
-
decisionType: "provider-
|
|
20108
|
+
decisionType: "provider-intent",
|
|
19641
20109
|
agentRef: running.seq,
|
|
19642
|
-
|
|
20110
|
+
ordinal: intent.ordinal,
|
|
20111
|
+
role: intent.role,
|
|
20112
|
+
servedBy: intent.servedBy,
|
|
20113
|
+
attempt: intent.attempt,
|
|
20114
|
+
requestFingerprint: createHash("sha256").update(jcsSerialize(intent.request.messages), "utf8").digest("hex")
|
|
19643
20115
|
}
|
|
19644
|
-
}).then(() => void 0)
|
|
19645
|
-
|
|
19646
|
-
type: "log",
|
|
19647
|
-
level: "warn",
|
|
19648
|
-
msg: `incremental billing row failed to append; the terminal entry remains the canonical record (${thrown instanceof Error ? thrown.message : String(thrown)})`
|
|
19649
|
-
}, spanId);
|
|
19650
|
-
});
|
|
19651
|
-
if (internals.defaults.billingReceipts === "awaited") return append;
|
|
19652
|
-
} };
|
|
20116
|
+
}).then(() => void 0) } : {}
|
|
20117
|
+
};
|
|
19653
20118
|
runAgentOptions.summarize = summarize;
|
|
19654
20119
|
if (profile?.compaction !== void 0) runAgentOptions.compaction = profile.compaction;
|
|
19655
20120
|
if (profile?.evidenceContract !== void 0) runAgentOptions.evidenceContract = profile.evidenceContract;
|
|
@@ -19888,6 +20353,7 @@ function createCtx(internals, rootWorkflow) {
|
|
|
19888
20353
|
...result.providerCalls === void 0 ? {} : { providerCalls: result.providerCalls },
|
|
19889
20354
|
costAttribution: {
|
|
19890
20355
|
...state.phase === void 0 ? {} : { phase: state.phase },
|
|
20356
|
+
...state.repairTrigger === void 0 ? {} : { repairTrigger: state.repairTrigger },
|
|
19891
20357
|
agentType,
|
|
19892
20358
|
role: primaryRole,
|
|
19893
20359
|
budgetAccount: state.budgetScope ?? "run",
|
|
@@ -19990,7 +20456,15 @@ function createCtx(internals, rootWorkflow) {
|
|
|
19990
20456
|
const sliceRole = slice.role ?? primaryRole;
|
|
19991
20457
|
internals.cost.byRole.set(sliceRole, (internals.cost.byRole.get(sliceRole) ?? 0) + priced);
|
|
19992
20458
|
}
|
|
19993
|
-
|
|
20459
|
+
let livePhaseUsd = usd;
|
|
20460
|
+
for (const record of result.providerCalls ?? []) {
|
|
20461
|
+
if (record.phase !== "repair") continue;
|
|
20462
|
+
const recordUsd = internals.priceUsd(record.servedBy, record.usage);
|
|
20463
|
+
if (recordUsd === void 0 || !Number.isFinite(recordUsd) || recordUsd < 0) continue;
|
|
20464
|
+
bump(internals.cost.byPhase, "repair", recordUsd);
|
|
20465
|
+
livePhaseUsd -= recordUsd;
|
|
20466
|
+
}
|
|
20467
|
+
bump(internals.cost.byPhase, state.phase ?? "", livePhaseUsd);
|
|
19994
20468
|
bump(internals.cost.byAgentType, agentType, usd);
|
|
19995
20469
|
bump(internals.cost.byScope, state.scope, usd);
|
|
19996
20470
|
if (result.error?.kind === "budget" || internals.budget.exhausted && result.status !== "ok") {
|
|
@@ -22223,6 +22697,212 @@ function renderContractRequirements(manifest) {
|
|
|
22223
22697
|
return lines.join("\n");
|
|
22224
22698
|
}
|
|
22225
22699
|
//#endregion
|
|
22700
|
+
//#region src/orchestrator/citation-audit.ts
|
|
22701
|
+
const DEFAULT_CITATION_SAMPLE_PER_SECTION = 2;
|
|
22702
|
+
const DEFAULT_CITATION_MAX_SAMPLED = 24;
|
|
22703
|
+
const DEFAULT_CITATION_EXCERPT_WINDOW = 3;
|
|
22704
|
+
/** Excerpt bounds, the claim-pass excerpt discipline. */
|
|
22705
|
+
const MAX_CITATION_EXCERPT_LINES = 12;
|
|
22706
|
+
const MAX_CITATION_EXCERPT_CHARS = 800;
|
|
22707
|
+
/** A citation with an optional `-end` range tail on the line half. */
|
|
22708
|
+
const citationWithRange = (pattern) => new RegExp(pattern, "gu");
|
|
22709
|
+
const RANGE_TAIL = /^(.*):(\d+)(?:-(\d+))?$/u;
|
|
22710
|
+
/**
|
|
22711
|
+
* Validates the declared plan numbers; returns the resolved bounds.
|
|
22712
|
+
* Garbage throws like every malformed intake.
|
|
22713
|
+
*/
|
|
22714
|
+
function resolveCitationAuditPlan(options) {
|
|
22715
|
+
const samplePerSection = options.samplePerSection ?? 2;
|
|
22716
|
+
if (!Number.isInteger(samplePerSection) || samplePerSection < 1) throw new ConfigError(`citationAudit.samplePerSection must be a positive integer; got ${String(options.samplePerSection)}`);
|
|
22717
|
+
const maxSampled = options.maxSampled ?? 24;
|
|
22718
|
+
if (!Number.isInteger(maxSampled) || maxSampled < 1) throw new ConfigError(`citationAudit.maxSampled must be a positive integer; got ${String(options.maxSampled)}`);
|
|
22719
|
+
const window = options.window ?? 3;
|
|
22720
|
+
if (!Number.isInteger(window) || window < 0) throw new ConfigError(`citationAudit.window must be a non negative integer; got ${String(options.window)}`);
|
|
22721
|
+
const pattern = options.pattern ?? "[\\w./-]+\\.\\w+:\\d+";
|
|
22722
|
+
let probe;
|
|
22723
|
+
try {
|
|
22724
|
+
probe = new RegExp(pattern, "gu");
|
|
22725
|
+
} catch (thrown) {
|
|
22726
|
+
throw new ConfigError(`citationAudit.pattern does not compile: ${thrown instanceof Error ? thrown.message : String(thrown)}`);
|
|
22727
|
+
}
|
|
22728
|
+
if (probe.test("")) throw new ConfigError("citationAudit.pattern matches the empty string: it would flood the sample instead of anchoring it");
|
|
22729
|
+
return {
|
|
22730
|
+
pattern,
|
|
22731
|
+
samplePerSection,
|
|
22732
|
+
maxSampled,
|
|
22733
|
+
window
|
|
22734
|
+
};
|
|
22735
|
+
}
|
|
22736
|
+
/** Splits a document into (section marker, body) runs in order. */
|
|
22737
|
+
function sectionsOfDocument(document) {
|
|
22738
|
+
const lines = document.split("\n");
|
|
22739
|
+
const runs = [{
|
|
22740
|
+
marker: "",
|
|
22741
|
+
body: []
|
|
22742
|
+
}];
|
|
22743
|
+
for (const line of lines) {
|
|
22744
|
+
if (/^##\s+\S/u.test(line) && !line.startsWith("###")) {
|
|
22745
|
+
runs.push({
|
|
22746
|
+
marker: line.trim(),
|
|
22747
|
+
body: []
|
|
22748
|
+
});
|
|
22749
|
+
continue;
|
|
22750
|
+
}
|
|
22751
|
+
runs.at(-1)?.body.push(line);
|
|
22752
|
+
}
|
|
22753
|
+
return runs.map((run) => ({
|
|
22754
|
+
marker: run.marker,
|
|
22755
|
+
body: run.body.join("\n")
|
|
22756
|
+
})).filter((run) => run.body.trim().length > 0);
|
|
22757
|
+
}
|
|
22758
|
+
/** The deterministic per-section pick: seeded index selection without replacement. */
|
|
22759
|
+
function pickIndexes(count, k, seedInput) {
|
|
22760
|
+
const indexes = Array.from({ length: count }, (_, index) => index);
|
|
22761
|
+
const picked = [];
|
|
22762
|
+
for (let round = 0; round < Math.min(k, count); round += 1) {
|
|
22763
|
+
const index = createHash("sha256").update(`${seedInput}:${String(round)}`).digest().readUInt32BE(0) % indexes.length;
|
|
22764
|
+
const chosen = indexes.splice(index, 1)[0];
|
|
22765
|
+
if (chosen !== void 0) picked.push(chosen);
|
|
22766
|
+
}
|
|
22767
|
+
return picked.sort((a, b) => a - b);
|
|
22768
|
+
}
|
|
22769
|
+
/**
|
|
22770
|
+
* The deterministic stratified sample (RV4004): per H2 section, up to
|
|
22771
|
+
* `samplePerSection` citing sentences, selected by a hash chain seeded
|
|
22772
|
+
* from the audited document's own hash, so the same candidate always
|
|
22773
|
+
* yields the same sample (replay-stable, no clock, no randomness) and
|
|
22774
|
+
* a repaired candidate re-samples afresh from its new hash. The whole
|
|
22775
|
+
* sample is capped at `maxSampled` by pick rank across sections (every
|
|
22776
|
+
* section's first pick seats before any section's second), so a
|
|
22777
|
+
* many-section document degrades to one citation per section instead
|
|
22778
|
+
* of auditing the first sections only.
|
|
22779
|
+
*/
|
|
22780
|
+
function sampleCitationRows(document, plan, seed) {
|
|
22781
|
+
const perSection = [];
|
|
22782
|
+
for (const { marker, body } of sectionsOfDocument(document)) {
|
|
22783
|
+
const candidates = [];
|
|
22784
|
+
for (const sentence of sentencesOf(body)) {
|
|
22785
|
+
const match = citationWithRange(plan.pattern).exec(sentence);
|
|
22786
|
+
if (match === null) continue;
|
|
22787
|
+
const anchorText = new RegExp(`${match[0].replace(/[.*+?^${}()|[\]\\]/gu, "\\$&")}(?:-(\\d+))?`, "u").exec(sentence)?.[0] ?? match[0];
|
|
22788
|
+
const parsed = RANGE_TAIL.exec(anchorText);
|
|
22789
|
+
if (parsed === null) continue;
|
|
22790
|
+
const path = parsed[1] ?? "";
|
|
22791
|
+
const line = Number(parsed[2]);
|
|
22792
|
+
const endLine = parsed[3] === void 0 ? void 0 : Number(parsed[3]);
|
|
22793
|
+
if (path === "" || !Number.isInteger(line) || line < 1) continue;
|
|
22794
|
+
candidates.push({
|
|
22795
|
+
sentence,
|
|
22796
|
+
anchor: anchorText,
|
|
22797
|
+
path,
|
|
22798
|
+
line,
|
|
22799
|
+
...endLine !== void 0 && Number.isInteger(endLine) && endLine >= line ? { endLine } : {}
|
|
22800
|
+
});
|
|
22801
|
+
}
|
|
22802
|
+
if (candidates.length === 0) continue;
|
|
22803
|
+
const picks = pickIndexes(candidates.length, plan.samplePerSection, `${seed}:${marker}`).map((index) => candidates[index]).filter((candidate) => candidate !== void 0);
|
|
22804
|
+
perSection.push({
|
|
22805
|
+
section: marker,
|
|
22806
|
+
picks
|
|
22807
|
+
});
|
|
22808
|
+
}
|
|
22809
|
+
const rows = [];
|
|
22810
|
+
for (let rank = 0; rows.length < plan.maxSampled; rank += 1) {
|
|
22811
|
+
let any = false;
|
|
22812
|
+
for (const bucket of perSection) {
|
|
22813
|
+
const pick = bucket.picks[rank];
|
|
22814
|
+
if (pick === void 0) continue;
|
|
22815
|
+
any = true;
|
|
22816
|
+
if (rows.length >= plan.maxSampled) break;
|
|
22817
|
+
rows.push({
|
|
22818
|
+
row: rows.length,
|
|
22819
|
+
section: bucket.section,
|
|
22820
|
+
...pick
|
|
22821
|
+
});
|
|
22822
|
+
}
|
|
22823
|
+
if (!any) break;
|
|
22824
|
+
}
|
|
22825
|
+
return rows;
|
|
22826
|
+
}
|
|
22827
|
+
/**
|
|
22828
|
+
* Resolves one sampled citation's excerpt through the host's pure
|
|
22829
|
+
* snapshot resolver. The FIRST cited line failing to resolve returns
|
|
22830
|
+
* undefined (an unsupported citation by doctrine); later lines simply
|
|
22831
|
+
* end the excerpt (a range past the file's end reads as far as the
|
|
22832
|
+
* snapshot goes).
|
|
22833
|
+
*/
|
|
22834
|
+
function citationExcerptOf(resolve, row, window) {
|
|
22835
|
+
const last = Math.min(row.endLine ?? row.line + window, row.line + 12 - 1);
|
|
22836
|
+
const lines = [];
|
|
22837
|
+
for (let line = row.line; line <= last; line += 1) {
|
|
22838
|
+
const text = resolve({
|
|
22839
|
+
path: row.path,
|
|
22840
|
+
line
|
|
22841
|
+
});
|
|
22842
|
+
if (text === void 0) {
|
|
22843
|
+
if (line === row.line) return;
|
|
22844
|
+
break;
|
|
22845
|
+
}
|
|
22846
|
+
lines.push(`L${String(line)}: ${text}`);
|
|
22847
|
+
}
|
|
22848
|
+
const excerpt = lines.join("\n");
|
|
22849
|
+
return excerpt.length > 800 ? `${excerpt.slice(0, 800)}…` : excerpt;
|
|
22850
|
+
}
|
|
22851
|
+
/** The audit judge's structured verdict schema (mirrors the claim judge). */
|
|
22852
|
+
const CITATION_JUDGE_SCHEMA = {
|
|
22853
|
+
type: "object",
|
|
22854
|
+
properties: { verdicts: {
|
|
22855
|
+
type: "array",
|
|
22856
|
+
items: {
|
|
22857
|
+
type: "object",
|
|
22858
|
+
properties: {
|
|
22859
|
+
row: { type: "integer" },
|
|
22860
|
+
verdict: {
|
|
22861
|
+
type: "string",
|
|
22862
|
+
enum: [
|
|
22863
|
+
"supported",
|
|
22864
|
+
"partial",
|
|
22865
|
+
"unsupported"
|
|
22866
|
+
]
|
|
22867
|
+
},
|
|
22868
|
+
reason: { type: "string" }
|
|
22869
|
+
},
|
|
22870
|
+
required: [
|
|
22871
|
+
"row",
|
|
22872
|
+
"verdict",
|
|
22873
|
+
"reason"
|
|
22874
|
+
],
|
|
22875
|
+
additionalProperties: false
|
|
22876
|
+
}
|
|
22877
|
+
} },
|
|
22878
|
+
required: ["verdicts"],
|
|
22879
|
+
additionalProperties: false
|
|
22880
|
+
};
|
|
22881
|
+
/**
|
|
22882
|
+
* Parses the judge output strictly: one verdict per judged row, no
|
|
22883
|
+
* duplicates, verdicts from the closed vocabulary. Anything else returns
|
|
22884
|
+
* undefined and the caller treats the invocation as a failed judge
|
|
22885
|
+
* (nothing was judged; partial verdicts over a partial parse would
|
|
22886
|
+
* claim more than the judge said).
|
|
22887
|
+
*/
|
|
22888
|
+
function parseCitationVerdicts(output, rowIndexes) {
|
|
22889
|
+
const shaped = output;
|
|
22890
|
+
if (shaped === null || shaped === void 0 || !Array.isArray(shaped.verdicts)) return;
|
|
22891
|
+
const parsed = /* @__PURE__ */ new Map();
|
|
22892
|
+
for (const entry of shaped.verdicts) {
|
|
22893
|
+
const row = entry.row;
|
|
22894
|
+
const verdict = entry.verdict;
|
|
22895
|
+
const reason = entry.reason;
|
|
22896
|
+
if (typeof row !== "number" || verdict !== "supported" && verdict !== "partial" && verdict !== "unsupported" || typeof reason !== "string" || parsed.has(row)) return;
|
|
22897
|
+
parsed.set(row, {
|
|
22898
|
+
verdict,
|
|
22899
|
+
reason
|
|
22900
|
+
});
|
|
22901
|
+
}
|
|
22902
|
+
for (const index of rowIndexes) if (!parsed.has(index)) return;
|
|
22903
|
+
return parsed;
|
|
22904
|
+
}
|
|
22905
|
+
//#endregion
|
|
22226
22906
|
//#region src/orchestrator/contradictions.ts
|
|
22227
22907
|
/**
|
|
22228
22908
|
* The bounded contradiction pass, pure half (RV1301, the sixteenth
|
|
@@ -23487,6 +24167,18 @@ function validateOrchestrateOptions(opts) {
|
|
|
23487
24167
|
if (consistency.runFactCoverageRatio !== void 0 && consistency.runFacts !== true) throw new ConfigError("orchestrate claimConsistency.runFactCoverageRatio rides the runFacts pass; set claimConsistency.runFacts true");
|
|
23488
24168
|
if (consistency.onLowCoverage !== void 0 && consistency.onLowCoverage !== "report" && consistency.onLowCoverage !== "fail") throw new ConfigError("orchestrate claimConsistency.onLowCoverage must be 'report' or 'fail'; got " + JSON.stringify(consistency.onLowCoverage));
|
|
23489
24169
|
if (consistency.onLowCoverage !== void 0 && consistency.minimumCoverageRatio === void 0 && consistency.runFactCoverageRatio === void 0 && consistency.coverageTarget === void 0) throw new ConfigError("orchestrate claimConsistency.onLowCoverage needs a declared floor; set minimumCoverageRatio, runFactCoverageRatio, or coverageTarget");
|
|
24170
|
+
const coveragePolicy = consistency.coveragePolicy;
|
|
24171
|
+
if (coveragePolicy !== void 0 && coveragePolicy !== "observed" && coveragePolicy !== "strict-final") throw new ConfigError(`orchestrate claimConsistency.coveragePolicy must be 'observed' or 'strict-final'; got ${JSON.stringify(coveragePolicy)}`);
|
|
24172
|
+
if (coveragePolicy === "strict-final" && stage === "draft") throw new ConfigError("orchestrate claimConsistency.coveragePolicy 'strict-final' needs stage 'final' or 'both': a draft-only pass grades no final document, so the policy would gate on nothing");
|
|
24173
|
+
const waiver = consistency.waiver;
|
|
24174
|
+
if (waiver !== void 0) {
|
|
24175
|
+
if (coveragePolicy !== "strict-final") throw new ConfigError("orchestrate claimConsistency.waiver requires coveragePolicy 'strict-final': a waiver over an unenforced grade is a signature over nothing");
|
|
24176
|
+
if (typeof waiver !== "object" || waiver === null || Array.isArray(waiver)) throw new ConfigError(`orchestrate claimConsistency.waiver must be an object; got ${JSON.stringify(waiver)}`);
|
|
24177
|
+
const shaped = waiver;
|
|
24178
|
+
if (typeof shaped.principal !== "string" || shaped.principal.length === 0) throw new ConfigError("orchestrate claimConsistency.waiver.principal must be a non empty string; got " + JSON.stringify(shaped.principal));
|
|
24179
|
+
if (typeof shaped.reason !== "string" || shaped.reason.length === 0) throw new ConfigError("orchestrate claimConsistency.waiver.reason must be a non empty string; got " + JSON.stringify(shaped.reason));
|
|
24180
|
+
if (shaped.expiresAt !== void 0 && (typeof shaped.expiresAt !== "string" || Number.isNaN(Date.parse(shaped.expiresAt)))) throw new ConfigError(`orchestrate claimConsistency.waiver.expiresAt must be an ISO 8601 date string; got ${JSON.stringify(shaped.expiresAt)}`);
|
|
24181
|
+
}
|
|
23490
24182
|
if (consistency.judge !== void 0) {
|
|
23491
24183
|
const judge = consistency.judge;
|
|
23492
24184
|
if (typeof judge !== "object" || judge === null || Array.isArray(judge)) throw new ConfigError(`orchestrate claimConsistency.judge must be an object; got ${JSON.stringify(consistency.judge)}`);
|
|
@@ -23502,6 +24194,18 @@ function validateOrchestrateOptions(opts) {
|
|
|
23502
24194
|
}
|
|
23503
24195
|
}
|
|
23504
24196
|
if (opts.executionFacts !== void 0 && typeof opts.executionFacts !== "boolean") throw new ConfigError(`orchestrate executionFacts must be a boolean; got ${typeof opts.executionFacts}`);
|
|
24197
|
+
const audit = opts?.citationAudit;
|
|
24198
|
+
if (audit !== void 0) {
|
|
24199
|
+
if (typeof audit !== "object" || audit === null || Array.isArray(audit)) throw new ConfigError(`orchestrate citationAudit must be an object; got ${JSON.stringify(audit)}`);
|
|
24200
|
+
if (typeof audit.resolve !== "function") throw new ConfigError("orchestrate citationAudit.resolve must be a function: the pure host snapshot reader is the whole evidence channel of the audit");
|
|
24201
|
+
resolveCitationAuditPlan(audit);
|
|
24202
|
+
if (audit.onFound !== void 0 && audit.onFound !== "report" && audit.onFound !== "repair" && audit.onFound !== "fail") throw new ConfigError(`orchestrate citationAudit.onFound must be 'report', 'repair' or 'fail'; got ${String(audit.onFound)}`);
|
|
24203
|
+
if (audit.judge?.estCost !== void 0) requireNonNegativeNumber(audit.judge.estCost, "orchestrate citationAudit.judge.estCost");
|
|
24204
|
+
if (audit.onFound === "repair") {
|
|
24205
|
+
if (opts?.synthesis === void 0) throw new ConfigError("orchestrate citationAudit.onFound 'repair' requires synthesis: the bounded round is one more composition, and without one there is nothing to repair with");
|
|
24206
|
+
if (opts?.claimConsistency?.onFound === "repair") throw new ConfigError("orchestrate citationAudit.onFound 'repair' cannot pair with claimConsistency.onFound 'repair': the run grants ONE bounded repair round (RV3307), so arm one consumer and give the other 'report' or 'fail'");
|
|
24207
|
+
}
|
|
24208
|
+
}
|
|
23505
24209
|
const spec = opts.budget;
|
|
23506
24210
|
if (spec === void 0) return;
|
|
23507
24211
|
if (spec.capUsd !== void 0) requireNonNegativeNumber(spec.capUsd, "orchestrate budget.capUsd");
|
|
@@ -23712,19 +24416,21 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
23712
24416
|
}
|
|
23713
24417
|
}
|
|
23714
24418
|
if (opts?.budget?.acceptanceReserve === "require") {
|
|
23715
|
-
const
|
|
23716
|
-
|
|
23717
|
-
|
|
23718
|
-
|
|
23719
|
-
|
|
23720
|
-
|
|
23721
|
-
|
|
23722
|
-
|
|
23723
|
-
|
|
23724
|
-
|
|
24419
|
+
const { requiredUsd, terms } = acceptanceTailRequiredUsd({
|
|
24420
|
+
...opts.budget.synthesisReserveUsd === void 0 ? {} : { synthesisReserveUsd: opts.budget.synthesisReserveUsd },
|
|
24421
|
+
...opts?.claimConsistency?.stage === void 0 ? {} : { claimStage: opts.claimConsistency.stage },
|
|
24422
|
+
...opts?.claimConsistency?.onFound === void 0 ? {} : { claimOnFound: opts.claimConsistency.onFound },
|
|
24423
|
+
...opts?.claimConsistency?.judge?.estCost === void 0 ? {} : { claimJudgeEstCostUsd: opts.claimConsistency.judge.estCost },
|
|
24424
|
+
...opts?.finishValidation?.estRepairCostUsd === void 0 ? {} : { finishEstRepairCostUsd: opts.finishValidation.estRepairCostUsd },
|
|
24425
|
+
...opts?.synthesis?.estCost === void 0 ? {} : { synthesisEstCostUsd: opts.synthesis.estCost },
|
|
24426
|
+
...opts?.citationAudit?.judge?.estCost === void 0 ? {} : { citationJudgeEstCostUsd: opts.citationAudit.judge.estCost },
|
|
24427
|
+
...opts?.citationAudit?.onFound === void 0 ? {} : { citationOnFound: opts.citationAudit.onFound },
|
|
24428
|
+
...opts?.claimConsistency === void 0 ? {} : { claimConfigured: true },
|
|
24429
|
+
workingRoomUsd: capState?.turnEstimateUsd ?? internals.flatReserveUsd ?? .5
|
|
24430
|
+
});
|
|
23725
24431
|
const capUsd = capState?.effectiveCapUsd;
|
|
23726
24432
|
if (capUsd === void 0 || capUsd < requiredUsd) {
|
|
23727
|
-
const
|
|
24433
|
+
const termsLine = formatAcceptanceTailTerms(terms);
|
|
23728
24434
|
await internals.replayer.appendSinglePhase({
|
|
23729
24435
|
scope: callingState.scope,
|
|
23730
24436
|
key: deriverV2.deriveKey({ kind: "acceptance-reserve-refused" }),
|
|
@@ -23736,15 +24442,19 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
23736
24442
|
decisionType: "acceptance_reserve_refused",
|
|
23737
24443
|
requiredUsd,
|
|
23738
24444
|
effectiveCapUsd: capUsd ?? null,
|
|
23739
|
-
synthesisReserveUsd:
|
|
23740
|
-
judgeEstUsd,
|
|
23741
|
-
judgePasses,
|
|
23742
|
-
estRepairCostUsd:
|
|
23743
|
-
roundCompositionUsd,
|
|
23744
|
-
|
|
24445
|
+
synthesisReserveUsd: terms.synthesisReserveUsd,
|
|
24446
|
+
judgeEstUsd: terms.judgeEstUsd,
|
|
24447
|
+
judgePasses: terms.judgePasses,
|
|
24448
|
+
estRepairCostUsd: terms.estRepairCostUsd,
|
|
24449
|
+
roundCompositionUsd: terms.roundCompositionUsd,
|
|
24450
|
+
...terms.citationJudgePasses === void 0 ? {} : {
|
|
24451
|
+
citationJudgeEstUsd: terms.citationJudgeEstUsd ?? 0,
|
|
24452
|
+
citationJudgePasses: terms.citationJudgePasses
|
|
24453
|
+
},
|
|
24454
|
+
workingRoomUsd: terms.workingRoomUsd
|
|
23745
24455
|
}
|
|
23746
24456
|
});
|
|
23747
|
-
throw new OrchestratorCapConfigError(capUsd === void 0 ? `budget.acceptanceReserve 'require' needs a resolved effective cap to hold the declared acceptance tail against (${
|
|
24457
|
+
throw new OrchestratorCapConfigError(capUsd === void 0 ? `budget.acceptanceReserve 'require' needs a resolved effective cap to hold the declared acceptance tail against (${termsLine}); declare budget.capUsd or a run ceiling` : `budget.acceptanceReserve 'require': the declared acceptance tail does not fit the effective cap ${capUsd.toFixed(4)} USD (${termsLine}); raise the cap or lower the declared tail`);
|
|
23748
24458
|
}
|
|
23749
24459
|
}
|
|
23750
24460
|
const records = /* @__PURE__ */ new Map();
|
|
@@ -24700,6 +25410,20 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
24700
25410
|
*/
|
|
24701
25411
|
let validationInvocationStart = 0;
|
|
24702
25412
|
/**
|
|
25413
|
+
* The stage a finish-validation verdict is rendered under (RV4002,
|
|
25414
|
+
* the fifth comparison experiment): 'composition' for the initial
|
|
25415
|
+
* composition invocation, the no-synthesis coordination finish,
|
|
25416
|
+
* and the reserved finalizer wake; 'round' from the moment the
|
|
25417
|
+
* RV3307 claim repair round's own composition dispatches. Written
|
|
25418
|
+
* onto every `orchestrator_finish_validation` decision so the
|
|
25419
|
+
* workflow-wide repair ledger is a pure journal fold instead of a
|
|
25420
|
+
* positional reconstruction (the experiment's judge rebuilt the
|
|
25421
|
+
* one draft repair from the raw transcript). Live state on the
|
|
25422
|
+
* RV808b doctrine: replay re-delivers the journaled decisions and
|
|
25423
|
+
* never re-runs validateFinish.
|
|
25424
|
+
*/
|
|
25425
|
+
let finishValidationStage = "composition";
|
|
25426
|
+
/**
|
|
24703
25427
|
* The staged release of the round's mechanical money leg (RV3802),
|
|
24704
25428
|
* armed by the bounded claim repair round right before its
|
|
24705
25429
|
* composition dispatches and fired at the round invocation's FIRST
|
|
@@ -24887,7 +25611,8 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
24887
25611
|
};
|
|
24888
25612
|
return {
|
|
24889
25613
|
kind: "spliced",
|
|
24890
|
-
result: spliceSections(retained, declared, patch)
|
|
25614
|
+
result: spliceSections(retained, declared, patch),
|
|
25615
|
+
markers
|
|
24891
25616
|
};
|
|
24892
25617
|
}
|
|
24893
25618
|
};
|
|
@@ -24898,6 +25623,7 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
24898
25623
|
if (validationSpec === void 0) return { ok: true };
|
|
24899
25624
|
let effective = call.result ?? null;
|
|
24900
25625
|
let spliced = false;
|
|
25626
|
+
let splicedMarkers;
|
|
24901
25627
|
if (sectionalRoundContext !== void 0) {
|
|
24902
25628
|
const round = sectionalRoundContext;
|
|
24903
25629
|
const args = call.args ?? {};
|
|
@@ -24935,6 +25661,7 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
24935
25661
|
};
|
|
24936
25662
|
effective = spliceSections(round.base, round.sections, patch);
|
|
24937
25663
|
spliced = true;
|
|
25664
|
+
splicedMarkers = markers;
|
|
24938
25665
|
}
|
|
24939
25666
|
} else if (finishSectional !== void 0) {
|
|
24940
25667
|
const resolution = finishSectional.resolve(call);
|
|
@@ -24944,6 +25671,7 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
24944
25671
|
};
|
|
24945
25672
|
effective = resolution.result ?? null;
|
|
24946
25673
|
spliced = resolution.kind === "spliced";
|
|
25674
|
+
if (resolution.kind === "spliced") splicedMarkers = resolution.markers;
|
|
24947
25675
|
}
|
|
24948
25676
|
const maxRepairs = validationSpec.maxRepairs ?? 1;
|
|
24949
25677
|
const known = validationDecisions();
|
|
@@ -25053,6 +25781,11 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
25053
25781
|
decisionType: "orchestrator_finish_validation",
|
|
25054
25782
|
callId: call.id,
|
|
25055
25783
|
verdict: failed.length === 0 || deterministicRepair?.outcome === "accepted" ? "accepted" : repairsUsed < maxRepairs ? "repair" : "rejected",
|
|
25784
|
+
stage: finishValidationStage,
|
|
25785
|
+
...spliced && splicedMarkers !== void 0 ? {
|
|
25786
|
+
spliced: true,
|
|
25787
|
+
sections: [...splicedMarkers]
|
|
25788
|
+
} : {},
|
|
25056
25789
|
failed: deterministicRepair?.outcome === "accepted" ? [] : failed,
|
|
25057
25790
|
repairsUsed,
|
|
25058
25791
|
maxRepairs,
|
|
@@ -25128,6 +25861,7 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
25128
25861
|
if (policy === void 0) return Promise.resolve({ ok: true });
|
|
25129
25862
|
let effective = call.result ?? null;
|
|
25130
25863
|
let spliced = false;
|
|
25864
|
+
let splicedMarkers;
|
|
25131
25865
|
if (draftSectional !== void 0) {
|
|
25132
25866
|
const resolution = draftSectional.resolve(call);
|
|
25133
25867
|
if (resolution.kind === "refused") return Promise.resolve({
|
|
@@ -25136,22 +25870,54 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
25136
25870
|
});
|
|
25137
25871
|
effective = resolution.result ?? null;
|
|
25138
25872
|
spliced = resolution.kind === "spliced";
|
|
25873
|
+
if (resolution.kind === "spliced") splicedMarkers = resolution.markers;
|
|
25139
25874
|
}
|
|
25140
25875
|
const result = effective;
|
|
25141
25876
|
const text = typeof result === "string" ? result : JSON.stringify(result);
|
|
25142
|
-
const accept = () =>
|
|
25143
|
-
|
|
25144
|
-
|
|
25145
|
-
|
|
25146
|
-
|
|
25877
|
+
const accept = async () => {
|
|
25878
|
+
if (spliced && splicedMarkers !== void 0) await internals.replayer.appendSinglePhase({
|
|
25879
|
+
scope: callingState.scope,
|
|
25880
|
+
key: `draft-gate-accept:${call.id}`,
|
|
25881
|
+
kind: "decision",
|
|
25882
|
+
status: "ok",
|
|
25883
|
+
spanId: internals.spans.mint(callingState.spanId),
|
|
25884
|
+
site: "orchestrator-draft-gate",
|
|
25885
|
+
value: {
|
|
25886
|
+
decisionType: "orchestrator_draft_gate",
|
|
25887
|
+
callId: call.id,
|
|
25888
|
+
verdict: "accepted",
|
|
25889
|
+
spliced: true,
|
|
25890
|
+
sections: [...splicedMarkers]
|
|
25891
|
+
}
|
|
25892
|
+
});
|
|
25893
|
+
return spliced ? {
|
|
25894
|
+
ok: true,
|
|
25895
|
+
resolved: { result }
|
|
25896
|
+
} : { ok: true };
|
|
25897
|
+
};
|
|
25898
|
+
const reject = async (feedback, failed) => {
|
|
25147
25899
|
draftSectional?.retain(result);
|
|
25148
|
-
|
|
25900
|
+
await internals.replayer.appendSinglePhase({
|
|
25901
|
+
scope: callingState.scope,
|
|
25902
|
+
key: `draft-gate:${call.id}`,
|
|
25903
|
+
kind: "decision",
|
|
25904
|
+
status: "ok",
|
|
25905
|
+
spanId: internals.spans.mint(callingState.spanId),
|
|
25906
|
+
site: "orchestrator-draft-gate",
|
|
25907
|
+
value: {
|
|
25908
|
+
decisionType: "orchestrator_draft_gate",
|
|
25909
|
+
callId: call.id,
|
|
25910
|
+
verdict: "rejected",
|
|
25911
|
+
failed
|
|
25912
|
+
}
|
|
25913
|
+
});
|
|
25914
|
+
return {
|
|
25149
25915
|
ok: false,
|
|
25150
25916
|
feedback: {
|
|
25151
25917
|
...feedback,
|
|
25152
25918
|
...draftSectional === void 0 ? {} : { sectionalRepair: draftSectional.guidance() }
|
|
25153
25919
|
}
|
|
25154
|
-
}
|
|
25920
|
+
};
|
|
25155
25921
|
};
|
|
25156
25922
|
if (policy === "contract") {
|
|
25157
25923
|
const failed = [];
|
|
@@ -25177,7 +25943,7 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
25177
25943
|
return reject({
|
|
25178
25944
|
error: "the coordination draft failed the declared finish contract; repair the draft and call finish again: a contract-valid draft skips the synthesis invocation entirely, and every gap left here is paid for again downstream",
|
|
25179
25945
|
failed
|
|
25180
|
-
});
|
|
25946
|
+
}, failed);
|
|
25181
25947
|
}
|
|
25182
25948
|
const reasons = [];
|
|
25183
25949
|
if (policy.minWords !== void 0) {
|
|
@@ -25190,7 +25956,10 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
25190
25956
|
return reject({
|
|
25191
25957
|
error: "the coordination draft failed the draft policy; repair the draft and call finish again: the synthesis invocation composes the FINAL result from this draft, and a collapsed draft starves it of the evidence the validators demand",
|
|
25192
25958
|
reasons
|
|
25193
|
-
}
|
|
25959
|
+
}, [{
|
|
25960
|
+
name: "draft-policy",
|
|
25961
|
+
reasons
|
|
25962
|
+
}]);
|
|
25194
25963
|
};
|
|
25195
25964
|
/**
|
|
25196
25965
|
* The extension finish gate (RV3202, the 2026-08-11 experiment's
|
|
@@ -25632,6 +26401,12 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
25632
26401
|
*/
|
|
25633
26402
|
let claimFindingsFound;
|
|
25634
26403
|
/**
|
|
26404
|
+
* The citation findings riding the armed audit round's prompt
|
|
26405
|
+
* (RV4004): set exactly while that round's composition dispatches,
|
|
26406
|
+
* so every other synthesis prompt keeps its bytes.
|
|
26407
|
+
*/
|
|
26408
|
+
let carriedCitationFindings;
|
|
26409
|
+
/**
|
|
25635
26410
|
* The observed price of this run's own latest post draft claim
|
|
25636
26411
|
* judge pass (RV3701): the fallback sizing of the repair round's
|
|
25637
26412
|
* convergence hold when the host declared no `judge.estCost`. By
|
|
@@ -26006,7 +26781,204 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
26006
26781
|
...snapshot ?? {}
|
|
26007
26782
|
} });
|
|
26008
26783
|
};
|
|
26009
|
-
|
|
26784
|
+
/**
|
|
26785
|
+
* The citation entailment audit's terminal state (RV4004):
|
|
26786
|
+
* undefined until the pass ran (or when it is not configured),
|
|
26787
|
+
* the meta plus the findings once it did. `citationFindingsFound`
|
|
26788
|
+
* carries every non-supported sampled citation (mechanically
|
|
26789
|
+
* unresolved rows included); `[]` is the judge's claim that every
|
|
26790
|
+
* sampled citation is supported.
|
|
26791
|
+
*/
|
|
26792
|
+
let citationAuditMeta;
|
|
26793
|
+
let citationFindingsFound;
|
|
26794
|
+
/**
|
|
26795
|
+
* The citation entailment audit (RV4004): a deterministic
|
|
26796
|
+
* stratified sample of the document's citing sentences, excerpts
|
|
26797
|
+
* through the host's pure snapshot resolver, one bounded judge
|
|
26798
|
+
* invocation. Mirrors the claim judge's dispatch discipline
|
|
26799
|
+
* (declined admissions degrade typed and journaled, dead judges
|
|
26800
|
+
* stamp the meta, armed postures refuse to pass silently); the
|
|
26801
|
+
* POSTURE consequences of findings ('fail', the RV3307 round)
|
|
26802
|
+
* belong to the call site.
|
|
26803
|
+
*/
|
|
26804
|
+
const runCitationAudit = async (document, pass) => {
|
|
26805
|
+
const auditSpec = opts?.citationAudit;
|
|
26806
|
+
if (auditSpec === void 0) return;
|
|
26807
|
+
const plan = resolveCitationAuditPlan(auditSpec);
|
|
26808
|
+
const auditedHash = createHash("sha256").update(jcsSerialize(document ?? null), "utf8").digest("hex");
|
|
26809
|
+
const rows = sampleCitationRows(typeof document === "string" ? document : JSON.stringify(document ?? null), plan, auditedHash).map((row) => {
|
|
26810
|
+
const excerpt = citationExcerptOf(auditSpec.resolve, row, plan.window);
|
|
26811
|
+
return excerpt === void 0 ? row : {
|
|
26812
|
+
...row,
|
|
26813
|
+
excerpt
|
|
26814
|
+
};
|
|
26815
|
+
});
|
|
26816
|
+
const perSection = {};
|
|
26817
|
+
const bucketOf = (section) => perSection[section] ??= {
|
|
26818
|
+
sampled: 0,
|
|
26819
|
+
supported: 0,
|
|
26820
|
+
partial: 0,
|
|
26821
|
+
unsupported: 0
|
|
26822
|
+
};
|
|
26823
|
+
for (const row of rows) bucketOf(row.section).sampled += 1;
|
|
26824
|
+
const mechanical = rows.filter((row) => row.excerpt === void 0).map((row) => ({
|
|
26825
|
+
row: row.row,
|
|
26826
|
+
section: row.section,
|
|
26827
|
+
sentence: row.sentence,
|
|
26828
|
+
anchor: row.anchor,
|
|
26829
|
+
verdict: "unsupported",
|
|
26830
|
+
reason: "the cited location does not resolve in the host snapshot"
|
|
26831
|
+
}));
|
|
26832
|
+
for (const finding of mechanical) bucketOf(finding.section).unsupported += 1;
|
|
26833
|
+
const judgeRows = rows.filter((row) => row.excerpt !== void 0);
|
|
26834
|
+
const metaBase = {
|
|
26835
|
+
sampled: rows.length,
|
|
26836
|
+
supported: 0,
|
|
26837
|
+
partial: 0,
|
|
26838
|
+
unsupported: mechanical.length,
|
|
26839
|
+
unresolved: mechanical.length,
|
|
26840
|
+
perSection,
|
|
26841
|
+
auditedHash,
|
|
26842
|
+
samplePerSection: plan.samplePerSection,
|
|
26843
|
+
maxSampled: plan.maxSampled
|
|
26844
|
+
};
|
|
26845
|
+
const onFound = auditSpec.onFound ?? "report";
|
|
26846
|
+
if (judgeRows.length === 0) {
|
|
26847
|
+
citationAuditMeta = {
|
|
26848
|
+
...metaBase,
|
|
26849
|
+
judgeInvoked: false
|
|
26850
|
+
};
|
|
26851
|
+
citationFindingsFound = mechanical;
|
|
26852
|
+
return;
|
|
26853
|
+
}
|
|
26854
|
+
const judgePrompt = ["You audit CITATIONS for entailment. Each row below carries one sentence from a composed document, the source location it cites, and the resolved text of the cited lines. Judge whether the cited text ENTAILS what the sentence claims about it: 'supported' when the lines carry the claimed meaning, 'partial' when they carry some of it but not the load-bearing part, 'unsupported' when they are about something else entirely, however plausible the sentence reads. Judge the MEANING, not the mechanics: the location resolving, or sharing words with the sentence, is not entailment. Answer with { verdicts: [{ row, verdict, reason }] }, one verdict per row, reason one short sentence.", `ROWS: ${JSON.stringify(judgeRows.map((row) => ({
|
|
26855
|
+
row: row.row,
|
|
26856
|
+
section: row.section,
|
|
26857
|
+
sentence: row.sentence,
|
|
26858
|
+
anchor: row.anchor,
|
|
26859
|
+
excerpt: row.excerpt
|
|
26860
|
+
})))}`].join("\n");
|
|
26861
|
+
const auditJudgeState = { ...callingState };
|
|
26862
|
+
if (orchestratorAccount !== void 0) auditJudgeState.budgetScope = orchestratorAccount;
|
|
26863
|
+
auditJudgeState.phase = auditJudgeState.phase ?? "judge";
|
|
26864
|
+
const judgeOpts = {
|
|
26865
|
+
role: "synthesize",
|
|
26866
|
+
result: "full",
|
|
26867
|
+
label: pass === "round" ? "citation-entailment-judge-round" : "citation-entailment-judge",
|
|
26868
|
+
schema: CITATION_JUDGE_SCHEMA,
|
|
26869
|
+
limits: auditSpec.judge?.limits ?? { maxTurns: 3 },
|
|
26870
|
+
...auditSpec.judge?.model === void 0 ? {} : { model: auditSpec.judge.model },
|
|
26871
|
+
...auditSpec.judge?.effort === void 0 ? {} : { effort: auditSpec.judge.effort },
|
|
26872
|
+
...auditSpec.judge?.estCost === void 0 ? {} : { estCost: auditSpec.judge.estCost }
|
|
26873
|
+
};
|
|
26874
|
+
let judged;
|
|
26875
|
+
try {
|
|
26876
|
+
judged = await runtime.runInScope(auditJudgeState, () => ctx.agent(judgePrompt, judgeOpts));
|
|
26877
|
+
noteInternalSettle(judged);
|
|
26878
|
+
} catch (declined) {
|
|
26879
|
+
if (!(declined instanceof BudgetExhaustedError)) throw declined;
|
|
26880
|
+
citationAuditMeta = {
|
|
26881
|
+
...metaBase,
|
|
26882
|
+
judgeInvoked: false,
|
|
26883
|
+
judgeDeclined: true
|
|
26884
|
+
};
|
|
26885
|
+
citationFindingsFound = void 0;
|
|
26886
|
+
const declineKey = deriverV2.deriveKey({ kind: pass === "round" ? "orchestrator-citation-judge-declined-round" : "orchestrator-citation-judge-declined" });
|
|
26887
|
+
if (!internals.replayer.snapshot().some((entry) => entry.kind === "decision" && entry.key === declineKey)) await internals.replayer.appendSinglePhase({
|
|
26888
|
+
scope: callingState.scope,
|
|
26889
|
+
key: declineKey,
|
|
26890
|
+
kind: "decision",
|
|
26891
|
+
status: "ok",
|
|
26892
|
+
spanId: internals.spans.mint(callingState.spanId),
|
|
26893
|
+
site: "orchestrator-budget",
|
|
26894
|
+
value: {
|
|
26895
|
+
decisionType: "orchestrator_citation_judge_declined",
|
|
26896
|
+
reason: declined.message.slice(0, 300),
|
|
26897
|
+
remainingUsd: internals.budget.remainingUsd(orchestratorAccount ?? "run") ?? null
|
|
26898
|
+
}
|
|
26899
|
+
});
|
|
26900
|
+
internals.events.emit({
|
|
26901
|
+
type: "log",
|
|
26902
|
+
level: "warn",
|
|
26903
|
+
msg: "orchestrator citation audit judge declined by admission",
|
|
26904
|
+
data: { reason: declined.message.slice(0, 300) }
|
|
26905
|
+
}, callingState.spanId);
|
|
26906
|
+
if (onFound === "fail" || onFound === "repair") throw new FailRunError(`the citation audit judge could not be admitted within the orchestrator account, so the armed ${onFound} posture cannot pass the document: ` + declined.message.slice(0, 300), { data: {
|
|
26907
|
+
source: "orchestrator_citation_audit",
|
|
26908
|
+
citationAuditMeta
|
|
26909
|
+
} });
|
|
26910
|
+
return;
|
|
26911
|
+
}
|
|
26912
|
+
const verdicts = judged.status === "ok" ? parseCitationVerdicts(judged.output, judgeRows.map((row) => row.row)) : void 0;
|
|
26913
|
+
if (verdicts === void 0) {
|
|
26914
|
+
citationAuditMeta = {
|
|
26915
|
+
...metaBase,
|
|
26916
|
+
judgeInvoked: true,
|
|
26917
|
+
judgeFailed: true
|
|
26918
|
+
};
|
|
26919
|
+
citationFindingsFound = void 0;
|
|
26920
|
+
internals.events.emit({
|
|
26921
|
+
type: "log",
|
|
26922
|
+
level: "warn",
|
|
26923
|
+
msg: "orchestrator citation audit judge failed",
|
|
26924
|
+
data: { status: judged.status }
|
|
26925
|
+
}, callingState.spanId);
|
|
26926
|
+
if (onFound === "fail" || onFound === "repair") throw new FailRunError(`the citation audit judge did not produce a usable verdict, so the armed ${onFound} posture cannot pass the document`, { data: {
|
|
26927
|
+
source: "orchestrator_citation_audit",
|
|
26928
|
+
citationAuditMeta
|
|
26929
|
+
} });
|
|
26930
|
+
return;
|
|
26931
|
+
}
|
|
26932
|
+
const findings = [...mechanical];
|
|
26933
|
+
let supported = 0;
|
|
26934
|
+
let partial = 0;
|
|
26935
|
+
let unsupported = mechanical.length;
|
|
26936
|
+
for (const row of judgeRows) {
|
|
26937
|
+
const verdict = verdicts.get(row.row);
|
|
26938
|
+
if (verdict === void 0) continue;
|
|
26939
|
+
if (verdict.verdict === "supported") {
|
|
26940
|
+
supported += 1;
|
|
26941
|
+
bucketOf(row.section).supported += 1;
|
|
26942
|
+
continue;
|
|
26943
|
+
}
|
|
26944
|
+
if (verdict.verdict === "partial") {
|
|
26945
|
+
partial += 1;
|
|
26946
|
+
bucketOf(row.section).partial += 1;
|
|
26947
|
+
} else {
|
|
26948
|
+
unsupported += 1;
|
|
26949
|
+
bucketOf(row.section).unsupported += 1;
|
|
26950
|
+
}
|
|
26951
|
+
findings.push({
|
|
26952
|
+
row: row.row,
|
|
26953
|
+
section: row.section,
|
|
26954
|
+
sentence: row.sentence,
|
|
26955
|
+
anchor: row.anchor,
|
|
26956
|
+
verdict: verdict.verdict,
|
|
26957
|
+
reason: verdict.reason
|
|
26958
|
+
});
|
|
26959
|
+
}
|
|
26960
|
+
citationAuditMeta = {
|
|
26961
|
+
...metaBase,
|
|
26962
|
+
supported,
|
|
26963
|
+
partial,
|
|
26964
|
+
unsupported,
|
|
26965
|
+
judgeInvoked: true
|
|
26966
|
+
};
|
|
26967
|
+
citationFindingsFound = findings;
|
|
26968
|
+
internals.events.emit({
|
|
26969
|
+
type: "log",
|
|
26970
|
+
level: findings.length === 0 ? "debug" : "info",
|
|
26971
|
+
msg: "orchestrator citation entailment audit",
|
|
26972
|
+
data: {
|
|
26973
|
+
sampled: rows.length,
|
|
26974
|
+
supported,
|
|
26975
|
+
partial,
|
|
26976
|
+
unsupported,
|
|
26977
|
+
pass
|
|
26978
|
+
}
|
|
26979
|
+
}, callingState.spanId);
|
|
26980
|
+
};
|
|
26981
|
+
const runSynthesis = async (draft, stagePhase = "composition", repairTrigger) => {
|
|
26010
26982
|
const spec = opts?.synthesis;
|
|
26011
26983
|
if (spec === void 0) return draft;
|
|
26012
26984
|
await recoveryDone;
|
|
@@ -26258,6 +27230,7 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
26258
27230
|
...opts?.contradictions?.onFound !== "carry" || contradictionsFound === void 0 || contradictionsFound.length === 0 ? [] : ["CHILD CONTRADICTIONS: the settled children read these cited locations differently; resolve each one EXPLICITLY in the final result (say which reading holds and why it does) instead of silently picking one. " + JSON.stringify(contradictionsFound)],
|
|
26259
27231
|
...opts?.claimConsistency?.onFound !== "carry" && opts?.claimConsistency?.onFound !== "repair" || claimFindingsFound === void 0 || claimFindingsFound.length === 0 ? [] : ["CLAIM CONTRADICTIONS: the composed draft contradicts the settled child pool at these cited locations; resolve each one EXPLICITLY in the final result (say which reading holds and why) instead of keeping the inverted claim. " + JSON.stringify(claimFindingsFound)],
|
|
26260
27232
|
...opts?.claimConsistency?.onFound !== "carry" && opts?.claimConsistency?.onFound !== "repair" || claimFindingsFound === void 0 || claimFindingsFound.length === 0 ? [] : hostValidationLessons(),
|
|
27233
|
+
...carriedCitationFindings === void 0 || carriedCitationFindings.length === 0 ? [] : ["CITATION AUDIT FINDINGS: these sampled citations were judged NOT entailed by their cited lines; for each, either fix the citation to the lines that actually carry the claim or rewrite the sentence to claim what the cited lines say, and keep every other sentence byte identical. " + JSON.stringify(carriedCitationFindings)],
|
|
26261
27234
|
...sectionalRoundContext === void 0 ? [] : [
|
|
26262
27235
|
`RETAINED FINAL: ${JSON.stringify(sectionalRoundContext.base)}`,
|
|
26263
27236
|
"SECTIONAL ROUND: the accepted document above is RETAINED; repair ONLY the sections owning the contradicted claims by calling finish({ sections: { \"<marker>\": \"<new section body>\" } }). Unchanged sections are spliced from the retained document byte for byte and the spliced whole is validated and judged. Target sections: " + JSON.stringify(sectionalRoundContext.targets) + ". Declared markers: " + JSON.stringify(sectionalRoundContext.sections) + ". Resubmit the full document as result only when a targeted repair is impossible.",
|
|
@@ -26364,6 +27337,7 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
26364
27337
|
const heldReserveUsd = orchestratorAccount === void 0 ? 0 : internals.budget.accountView(orchestratorAccount)?.synthesisReserveUsd ?? 0;
|
|
26365
27338
|
const synthesisState = { ...callingState };
|
|
26366
27339
|
synthesisState.phase = synthesisState.phase ?? stagePhase;
|
|
27340
|
+
if (repairTrigger !== void 0) synthesisState.repairTrigger = repairTrigger;
|
|
26367
27341
|
if (orchestratorAccount !== void 0) {
|
|
26368
27342
|
synthesisState.budgetScope = orchestratorAccount;
|
|
26369
27343
|
internals.budget.releaseSynthesisReserve(orchestratorAccount);
|
|
@@ -26390,6 +27364,7 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
26390
27364
|
}
|
|
26391
27365
|
};
|
|
26392
27366
|
validationInvocationStart = validationDecisions().length;
|
|
27367
|
+
finishValidationStage = stagePhase === "repair" ? "round" : "composition";
|
|
26393
27368
|
const synthesized = await runtime.runInScope(synthesisState, () => ctx.agent(prompt, synthesisOpts));
|
|
26394
27369
|
noteInternalSettle(synthesized);
|
|
26395
27370
|
synthesisSchemaRejectedExchanges = synthesized.schemaRejectedTerminalExchanges ?? 0;
|
|
@@ -27147,7 +28122,7 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
27147
28122
|
}, callingState.spanId);
|
|
27148
28123
|
}
|
|
27149
28124
|
try {
|
|
27150
|
-
synthesizedFinal = await runSynthesis(result.output, "repair");
|
|
28125
|
+
synthesizedFinal = await runSynthesis(result.output, "repair", "claim");
|
|
27151
28126
|
} catch (thrown) {
|
|
27152
28127
|
await journalSynthesisAdmissionDecline(thrown);
|
|
27153
28128
|
const hostRejection = thrown instanceof FailRunError && typeof thrown.data === "object" && thrown.data !== null && !Array.isArray(thrown.data) && thrown.data.source === "orchestrator_finish_validation" ? thrown.data : void 0;
|
|
@@ -27211,6 +28186,93 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
27211
28186
|
} });
|
|
27212
28187
|
}
|
|
27213
28188
|
}
|
|
28189
|
+
if (opts?.citationAudit !== void 0) {
|
|
28190
|
+
const hashOfDocument = (value) => createHash("sha256").update(jcsSerialize(value ?? null), "utf8").digest("hex");
|
|
28191
|
+
await runCitationAudit(synthesizedFinal, "first");
|
|
28192
|
+
const auditOnFound = opts.citationAudit.onFound ?? "report";
|
|
28193
|
+
const unsupportedOf = () => (citationFindingsFound ?? []).filter((finding) => finding.verdict === "unsupported");
|
|
28194
|
+
const firstUnsupported = unsupportedOf();
|
|
28195
|
+
if (auditOnFound === "fail" && firstUnsupported.length > 0) throw new FailRunError(`the citation audit judged ${String(firstUnsupported.length)} sampled citation${firstUnsupported.length === 1 ? "" : "s"} UNSUPPORTED by the cited lines, and the armed fail posture cannot pass the document`, { data: {
|
|
28196
|
+
source: "orchestrator_citation_audit",
|
|
28197
|
+
citationFindings: citationFindingsFound,
|
|
28198
|
+
citationAuditMeta,
|
|
28199
|
+
...acceptanceSnapshot
|
|
28200
|
+
} });
|
|
28201
|
+
if (auditOnFound === "repair" && citationAuditMeta !== void 0) {
|
|
28202
|
+
citationAuditMeta.passes = 1;
|
|
28203
|
+
citationAuditMeta.citationRepairRounds = 0;
|
|
28204
|
+
}
|
|
28205
|
+
if (auditOnFound === "repair" && firstUnsupported.length > 0) {
|
|
28206
|
+
const preRepairHash = hashOfDocument(synthesizedFinal);
|
|
28207
|
+
const carried = firstUnsupported;
|
|
28208
|
+
const auditConvergenceHoldUsd = opts.citationAudit.judge?.estCost ?? 0;
|
|
28209
|
+
const auditHoldScope = orchestratorAccount ?? "run";
|
|
28210
|
+
if (auditConvergenceHoldUsd > 0) internals.budget.commitConvergenceReserve(auditHoldScope, auditConvergenceHoldUsd);
|
|
28211
|
+
const auditRepairHoldUsd = validationSpec === void 0 ? 0 : validationSpec.estRepairCostUsd ?? lastMechanicalRepairCostUsd(internals.replayer.snapshot(), (servedBy, usage) => internals.priceUsd(servedBy, usage)) ?? 0;
|
|
28212
|
+
if (auditRepairHoldUsd > 0) {
|
|
28213
|
+
internals.budget.commitRepairReserve(auditHoldScope, auditRepairHoldUsd);
|
|
28214
|
+
releaseRepairLeg = () => {
|
|
28215
|
+
releaseRepairLeg = void 0;
|
|
28216
|
+
internals.budget.releaseRepairReserve(auditHoldScope);
|
|
28217
|
+
};
|
|
28218
|
+
}
|
|
28219
|
+
const auditRoundPlan = validationSpec !== void 0 && typeof synthesizedFinal === "string" ? sectionalRoundPlan(synthesizedFinal, carried.map((finding) => finding.sentence)) : void 0;
|
|
28220
|
+
if (auditRoundPlan !== void 0) {
|
|
28221
|
+
sectionalRoundContext = {
|
|
28222
|
+
base: synthesizedFinal,
|
|
28223
|
+
...auditRoundPlan
|
|
28224
|
+
};
|
|
28225
|
+
internals.events.emit({
|
|
28226
|
+
type: "log",
|
|
28227
|
+
level: "debug",
|
|
28228
|
+
msg: "orchestrator sectional round armed",
|
|
28229
|
+
data: {
|
|
28230
|
+
targets: auditRoundPlan.targets,
|
|
28231
|
+
sections: auditRoundPlan.sections.length
|
|
28232
|
+
}
|
|
28233
|
+
}, callingState.spanId);
|
|
28234
|
+
}
|
|
28235
|
+
carriedCitationFindings = carried;
|
|
28236
|
+
try {
|
|
28237
|
+
synthesizedFinal = await runSynthesis(result.output, "repair", "citation");
|
|
28238
|
+
} catch (thrown) {
|
|
28239
|
+
await journalSynthesisAdmissionDecline(thrown);
|
|
28240
|
+
const auditHostRejection = (thrown instanceof FailRunError && typeof thrown.data === "object" && thrown.data !== null && !Array.isArray(thrown.data) ? thrown.data.source : void 0) === "orchestrator_finish_validation" ? thrown.data : void 0;
|
|
28241
|
+
throw new FailRunError(auditHostRejection !== void 0 ? `the citation audit repair round dispatched and its repaired candidate failed host validation (${thrown instanceof Error ? thrown.message.slice(0, 300) : String(thrown)}); ${String(carried.length)} unsupported citation${carried.length === 1 ? "" : "s"} stand unconsumed and a gate armed to repair must not pass silently` : `the citation audit repair round could not dispatch (${thrown instanceof Error ? thrown.message.slice(0, 300) : String(thrown)}); ${String(carried.length)} unsupported citation${carried.length === 1 ? "" : "s"} stand unconsumed and a gate armed to repair must not pass silently`, { data: {
|
|
28242
|
+
source: "orchestrator_citation_audit",
|
|
28243
|
+
citationFindings: carried,
|
|
28244
|
+
citationAuditMeta,
|
|
28245
|
+
repairsUsed: auditHostRejection !== void 0 ? 1 : 0,
|
|
28246
|
+
roundDispatched: auditHostRejection !== void 0,
|
|
28247
|
+
preRepairHash,
|
|
28248
|
+
...acceptanceSnapshot
|
|
28249
|
+
} });
|
|
28250
|
+
} finally {
|
|
28251
|
+
carriedCitationFindings = void 0;
|
|
28252
|
+
sectionalRoundContext = void 0;
|
|
28253
|
+
releaseRepairLeg = void 0;
|
|
28254
|
+
if (auditRepairHoldUsd > 0) internals.budget.releaseRepairReserve(auditHoldScope);
|
|
28255
|
+
if (auditConvergenceHoldUsd > 0) internals.budget.releaseConvergenceReserve(auditHoldScope);
|
|
28256
|
+
}
|
|
28257
|
+
await runCitationAudit(synthesizedFinal, "round");
|
|
28258
|
+
if (citationAuditMeta !== void 0) {
|
|
28259
|
+
citationAuditMeta.passes = 2;
|
|
28260
|
+
citationAuditMeta.firstPassFindings = carried.length;
|
|
28261
|
+
citationAuditMeta.citationRepairRounds = 1;
|
|
28262
|
+
}
|
|
28263
|
+
if (opts?.claimConsistency !== void 0 && claimStage !== "draft") await runClaimConsistencyPass(synthesizedFinal, acceptanceSnapshot, "final");
|
|
28264
|
+
const survivors = unsupportedOf();
|
|
28265
|
+
if (survivors.length > 0) throw new FailRunError(`the citation audit still judged ${String(survivors.length)} sampled citation${survivors.length === 1 ? "" : "s"} UNSUPPORTED after the bounded repair round: the repaired document keeps citing lines that do not carry its claims`, { data: {
|
|
28266
|
+
source: "orchestrator_citation_audit",
|
|
28267
|
+
citationFindings: citationFindingsFound,
|
|
28268
|
+
citationAuditMeta,
|
|
28269
|
+
repairsUsed: 1,
|
|
28270
|
+
preRepairHash,
|
|
28271
|
+
repairedHash: hashOfDocument(synthesizedFinal),
|
|
28272
|
+
...acceptanceSnapshot
|
|
28273
|
+
} });
|
|
28274
|
+
}
|
|
28275
|
+
}
|
|
27214
28276
|
const envelopeSchemaRecovered = (result.schemaRecoveredTerminalExchanges ?? 0) + synthesisSchemaRecoveredExchanges;
|
|
27215
28277
|
const deliverable = deliverableVerdict(synthesizedFinal);
|
|
27216
28278
|
const draftToFinal = opts?.synthesis === void 0 ? void 0 : (() => {
|
|
@@ -27233,6 +28295,56 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
27233
28295
|
lastBeforeHash: lastAcceptedRepair.beforeHash,
|
|
27234
28296
|
lastAfterHash: lastAcceptedRepair.afterHash
|
|
27235
28297
|
};
|
|
28298
|
+
const repairLedger = validationSpec !== void 0 || (opts?.claimConsistency?.onFound ?? "report") === "repair" || opts?.citationAudit?.onFound === "repair" ? repairLedgerFromJournal(internals.replayer.snapshot(), (servedBy, usage) => internals.priceUsd(servedBy, usage)) : void 0;
|
|
28299
|
+
let claimCoverageWaiver;
|
|
28300
|
+
if (opts?.claimConsistency?.coveragePolicy === "strict-final") {
|
|
28301
|
+
const grade = claimConsistencyMeta?.coverage ?? "not-judged";
|
|
28302
|
+
if (grade !== "full") {
|
|
28303
|
+
const priorWaiveDecision = internals.replayer.snapshot().find((entry) => {
|
|
28304
|
+
if (entry.kind !== "decision" || entry.scope !== callingState.scope) return false;
|
|
28305
|
+
const value = entry.value;
|
|
28306
|
+
return value?.decisionType === "claim_coverage_waived" && (value.judgedHash === void 0 || value.judgedHash === claimConsistencyMeta?.judgedHash);
|
|
28307
|
+
});
|
|
28308
|
+
if (priorWaiveDecision !== void 0) {
|
|
28309
|
+
const frozen = priorWaiveDecision.value;
|
|
28310
|
+
claimCoverageWaiver = {
|
|
28311
|
+
principal: frozen.principal,
|
|
28312
|
+
reason: frozen.reason,
|
|
28313
|
+
...frozen.expiresAt === void 0 ? {} : { expiresAt: frozen.expiresAt },
|
|
28314
|
+
coverage: frozen.coverage
|
|
28315
|
+
};
|
|
28316
|
+
} else {
|
|
28317
|
+
const waiverSpec = opts.claimConsistency.waiver;
|
|
28318
|
+
const expired = waiverSpec?.expiresAt !== void 0 && Date.parse(waiverSpec.expiresAt) < internals.now();
|
|
28319
|
+
if (waiverSpec === void 0 || expired) throw new FailRunError(`claimConsistency.coveragePolicy 'strict-final': the final coverage grade is '${grade}', not 'full', and ` + (waiverSpec === void 0 ? "no waiver is declared" : `the declared waiver expired at ${String(waiverSpec.expiresAt)}`) + "; raise the coverage (pairs, targets, critical anchors) or record a waiver naming who accepts the gap and why", { data: {
|
|
28320
|
+
source: "orchestrator_claim_consistency",
|
|
28321
|
+
coveragePolicy: "strict-final",
|
|
28322
|
+
coverage: grade,
|
|
28323
|
+
...waiverSpec === void 0 ? {} : { waiverExpiredAt: waiverSpec.expiresAt ?? null },
|
|
28324
|
+
...claimConsistencyMeta === void 0 ? {} : { claimConsistencyMeta }
|
|
28325
|
+
} });
|
|
28326
|
+
claimCoverageWaiver = {
|
|
28327
|
+
principal: waiverSpec.principal,
|
|
28328
|
+
reason: waiverSpec.reason,
|
|
28329
|
+
...waiverSpec.expiresAt === void 0 ? {} : { expiresAt: waiverSpec.expiresAt },
|
|
28330
|
+
coverage: grade
|
|
28331
|
+
};
|
|
28332
|
+
await internals.replayer.appendSinglePhase({
|
|
28333
|
+
scope: callingState.scope,
|
|
28334
|
+
key: deriverV2.deriveKey({ kind: "claim-coverage-waived" }),
|
|
28335
|
+
kind: "decision",
|
|
28336
|
+
status: "ok",
|
|
28337
|
+
spanId: internals.spans.mint(callingState.spanId),
|
|
28338
|
+
site: "orchestrator-claim-coverage",
|
|
28339
|
+
value: {
|
|
28340
|
+
decisionType: "claim_coverage_waived",
|
|
28341
|
+
...claimCoverageWaiver,
|
|
28342
|
+
...claimConsistencyMeta?.judgedHash === void 0 ? {} : { judgedHash: claimConsistencyMeta.judgedHash }
|
|
28343
|
+
}
|
|
28344
|
+
});
|
|
28345
|
+
}
|
|
28346
|
+
}
|
|
28347
|
+
}
|
|
27236
28348
|
return {
|
|
27237
28349
|
result: synthesizedFinal,
|
|
27238
28350
|
completion: decision.completion,
|
|
@@ -27241,6 +28353,12 @@ function makeOrchestratorWorkflow(goal, opts) {
|
|
|
27241
28353
|
...deliverable.acceptedArtifactRef === void 0 ? {} : { acceptedArtifactRef: deliverable.acceptedArtifactRef },
|
|
27242
28354
|
...envelopeRejectedCandidates.length === 0 ? {} : { rejectedFinishCandidates: envelopeRejectedCandidates },
|
|
27243
28355
|
...deterministicPatches === void 0 ? {} : { deterministicPatches },
|
|
28356
|
+
...repairLedger === void 0 ? {} : { repairs: repairLedger },
|
|
28357
|
+
...claimCoverageWaiver === void 0 ? {} : { claimCoverageWaiver },
|
|
28358
|
+
...citationAuditMeta === void 0 ? {} : {
|
|
28359
|
+
...citationFindingsFound === void 0 ? {} : { citationFindings: citationFindingsFound },
|
|
28360
|
+
citationAuditMeta
|
|
28361
|
+
},
|
|
27244
28362
|
childStatusCounts: decision.childStatusCounts,
|
|
27245
28363
|
degradedReasons: decision.degradedReasons,
|
|
27246
28364
|
...decision.salvagedPartialChildren === void 0 ? {} : { salvagedPartialChildren: decision.salvagedPartialChildren },
|
|
@@ -27515,6 +28633,15 @@ function preflightEstimate(input) {
|
|
|
27515
28633
|
});
|
|
27516
28634
|
}
|
|
27517
28635
|
const spec = input.orchestrator.budget;
|
|
28636
|
+
if (spec?.acceptanceReserve !== void 0 && spec.acceptanceReserve !== "warn" && spec.acceptanceReserve !== "require") throw new ConfigError("preflight.orchestrator.budget.acceptanceReserve must be 'warn' or 'require'; got " + JSON.stringify(spec.acceptanceReserve));
|
|
28637
|
+
if (input.orchestrator.synthesis?.estCost !== void 0) requireNonNegativeNumber(input.orchestrator.synthesis.estCost, "preflight.orchestrator.synthesis.estCost");
|
|
28638
|
+
if (input.finishValidation?.estRepairCostUsd !== void 0) requireNonNegativeNumber(input.finishValidation.estRepairCostUsd, "preflight.finishValidation.estRepairCostUsd");
|
|
28639
|
+
if (input.orchestrator.citationAudit?.judge?.estCost !== void 0) requireNonNegativeNumber(input.orchestrator.citationAudit.judge.estCost, "preflight.orchestrator.citationAudit.judge.estCost");
|
|
28640
|
+
if (input.orchestrator.citationAudit?.onFound !== void 0 && ![
|
|
28641
|
+
"report",
|
|
28642
|
+
"repair",
|
|
28643
|
+
"fail"
|
|
28644
|
+
].includes(input.orchestrator.citationAudit.onFound)) throw new ConfigError(`preflight.orchestrator.citationAudit.onFound must be 'report', 'repair' or 'fail'; got ${JSON.stringify(input.orchestrator.citationAudit.onFound)}`);
|
|
27518
28645
|
const fraction = spec?.capFraction ?? .2;
|
|
27519
28646
|
const fromFraction = ceilingUsd === void 0 ? void 0 : fraction * ceilingUsd;
|
|
27520
28647
|
const bounds = [spec?.capUsd, fromFraction].filter((bound) => bound !== void 0);
|
|
@@ -27542,6 +28669,36 @@ function preflightEstimate(input) {
|
|
|
27542
28669
|
code: "orchestrator-cap-below-finalize-reserve",
|
|
27543
28670
|
message: `effectiveCap ${effectiveCapUsd.toFixed(4)} USD is below the finalize reserve ${finalizeReserveUsd.toFixed(4)} USD: the run would refuse to start`
|
|
27544
28671
|
});
|
|
28672
|
+
if (spec?.acceptanceReserve !== void 0) {
|
|
28673
|
+
const { requiredUsd, terms } = acceptanceTailRequiredUsd({
|
|
28674
|
+
...spec.synthesisReserveUsd === void 0 ? {} : { synthesisReserveUsd: spec.synthesisReserveUsd },
|
|
28675
|
+
...input.orchestrator.claimConsistency?.stage === void 0 ? {} : { claimStage: input.orchestrator.claimConsistency.stage },
|
|
28676
|
+
...input.orchestrator.claimConsistency?.onFound === void 0 ? {} : { claimOnFound: input.orchestrator.claimConsistency.onFound },
|
|
28677
|
+
...input.orchestrator.claimConsistency?.judge?.estCost === void 0 ? {} : { claimJudgeEstCostUsd: input.orchestrator.claimConsistency.judge.estCost },
|
|
28678
|
+
...input.finishValidation?.estRepairCostUsd === void 0 ? {} : { finishEstRepairCostUsd: input.finishValidation.estRepairCostUsd },
|
|
28679
|
+
...input.orchestrator.synthesis?.estCost === void 0 ? {} : { synthesisEstCostUsd: input.orchestrator.synthesis.estCost },
|
|
28680
|
+
...input.orchestrator.citationAudit?.judge?.estCost === void 0 ? {} : { citationJudgeEstCostUsd: input.orchestrator.citationAudit.judge.estCost },
|
|
28681
|
+
...input.orchestrator.citationAudit?.onFound === void 0 ? {} : { citationOnFound: input.orchestrator.citationAudit.onFound },
|
|
28682
|
+
...input.orchestrator.claimConsistency === void 0 ? {} : { claimConfigured: true },
|
|
28683
|
+
workingRoomUsd: flatReserveUsd
|
|
28684
|
+
});
|
|
28685
|
+
const fits = effectiveCapUsd !== void 0 && effectiveCapUsd >= requiredUsd;
|
|
28686
|
+
orchestratorEcho.acceptanceReserve = {
|
|
28687
|
+
declared: spec.acceptanceReserve,
|
|
28688
|
+
requiredUsd,
|
|
28689
|
+
...effectiveCapUsd === void 0 ? {} : { effectiveCapUsd },
|
|
28690
|
+
fits,
|
|
28691
|
+
terms
|
|
28692
|
+
};
|
|
28693
|
+
if (!fits) {
|
|
28694
|
+
const termsLine = formatAcceptanceTailTerms(terms);
|
|
28695
|
+
say({
|
|
28696
|
+
severity: spec.acceptanceReserve === "require" ? "error" : "warning",
|
|
28697
|
+
code: "acceptance-reserve-unfit",
|
|
28698
|
+
message: (effectiveCapUsd === void 0 ? `budget.acceptanceReserve '${spec.acceptanceReserve}': no effective cap resolves to hold the declared acceptance tail against (${termsLine})` : `budget.acceptanceReserve '${spec.acceptanceReserve}': the declared acceptance tail does not fit the effective cap ${effectiveCapUsd.toFixed(4)} USD (${termsLine})`) + (spec.acceptanceReserve === "require" ? "; the run would refuse to start before its first wire (RV3907): raise the cap or lower the declared tail" : "; the run would start with its acceptance machinery funded by luck: raise the cap, lower the declared tail, or declare 'require' to refuse instead")
|
|
28699
|
+
});
|
|
28700
|
+
}
|
|
28701
|
+
}
|
|
27545
28702
|
}
|
|
27546
28703
|
const spawnSpecs = input.spawns ?? [];
|
|
27547
28704
|
spawnSpecs.forEach(validateSpawnSpec);
|
|
@@ -28085,8 +29242,8 @@ function preflightEstimate(input) {
|
|
|
28085
29242
|
message: `the ceiling headroom is ${(ceilingHeadroomShare * 100).toFixed(2)} percent of the ceiling (${(ceilingHeadroomUsd ?? 0).toFixed(4)} USD over the required minimum ${(requiredMinimumCeilingUsd ?? 0).toFixed(4)} USD), below the declared ${(minCeilingHeadroomShare * 100).toFixed(2)} percent floor: a small pricing or context drift refuses the whole wave at admission; raise the ceiling or slim the wave`
|
|
28086
29243
|
});
|
|
28087
29244
|
const claimPosture = input.orchestrator?.claimConsistency;
|
|
28088
|
-
const repairArmed = claimPosture?.onFound === "repair";
|
|
28089
|
-
const worstJudgePasses = (
|
|
29245
|
+
const repairArmed = claimPosture?.onFound === "repair" && (claimPosture?.stage ?? "draft") !== "draft";
|
|
29246
|
+
const worstJudgePasses = acceptanceJudgePasses(claimPosture?.stage, claimPosture?.onFound);
|
|
28090
29247
|
{
|
|
28091
29248
|
const judgeEstUsd = input.orchestrator?.claimConsistency?.judge?.estCost;
|
|
28092
29249
|
if (judgeEstUsd !== void 0 && effectiveCapUsd !== void 0 && synthesisHoldUsd > 0) {
|
|
@@ -28911,6 +30068,34 @@ function parseDeadlineAt(value) {
|
|
|
28911
30068
|
if (month < 1 || month > 12 || day < 1 || day > daysInMonth) refuse();
|
|
28912
30069
|
return parsed;
|
|
28913
30070
|
}
|
|
30071
|
+
const SCOPE_FIELDS = [
|
|
30072
|
+
"tenant",
|
|
30073
|
+
"account",
|
|
30074
|
+
"project"
|
|
30075
|
+
];
|
|
30076
|
+
/**
|
|
30077
|
+
* Validates and copies a declared scope (RV4007): own properties only
|
|
30078
|
+
* (the RV1205 doctrine: a prototype member must never resolve),
|
|
30079
|
+
* non-empty strings of at most 256 chars, at least one field, and the
|
|
30080
|
+
* copy is what gets recorded, so later host mutation of the passed
|
|
30081
|
+
* object cannot move the recorded identity.
|
|
30082
|
+
*/
|
|
30083
|
+
function normalizeExecutionScope(value, site) {
|
|
30084
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new ConfigError(`${site} must be an object; got ${JSON.stringify(value)}`);
|
|
30085
|
+
const copy = {};
|
|
30086
|
+
for (const field of SCOPE_FIELDS) {
|
|
30087
|
+
if (!Object.hasOwn(value, field)) continue;
|
|
30088
|
+
const declared = value[field];
|
|
30089
|
+
if (typeof declared !== "string" || declared.length === 0 || declared.length > 256) throw new ConfigError(`${site}.${field} must be a non-empty string of at most 256 characters; got ` + JSON.stringify(declared));
|
|
30090
|
+
copy[field] = declared;
|
|
30091
|
+
}
|
|
30092
|
+
if (Object.keys(copy).length === 0) throw new ConfigError(`${site} must declare at least one of tenant, account, project; an empty scope records nothing and asserts nothing`);
|
|
30093
|
+
return copy;
|
|
30094
|
+
}
|
|
30095
|
+
/** The canonical identity string of a scope (RV4007): JCS bytes, total and deterministic. */
|
|
30096
|
+
function executionScopeKey(scope) {
|
|
30097
|
+
return jcsSerialize(scope);
|
|
30098
|
+
}
|
|
28914
30099
|
/** Validates a declared config fingerprint (RV3210): a non-empty string of at most 512 chars. */
|
|
28915
30100
|
function requireConfigFingerprint(value, site) {
|
|
28916
30101
|
if (typeof value !== "string" || value.length === 0 || value.length > 512) throw new ConfigError(`${site} must be a non-empty string of at most 512 characters; got ` + (typeof value === "string" ? `${String(value.length)} characters` : JSON.stringify(value)));
|
|
@@ -29190,7 +30375,11 @@ function createEngine(options) {
|
|
|
29190
30375
|
if (profile.countTokens !== void 0 && !["allow", "deny"].includes(profile.countTokens)) throw new ConfigError(`createEngine defaults.profiles['${name}'].countTokens must be 'allow' or 'deny'`);
|
|
29191
30376
|
}
|
|
29192
30377
|
if (options.defaults?.countTokens !== void 0 && !["allow", "deny"].includes(options.defaults.countTokens)) throw new ConfigError("createEngine defaults.countTokens must be 'allow' or 'deny'");
|
|
29193
|
-
if (options.defaults?.billingReceipts !== void 0 && ![
|
|
30378
|
+
if (options.defaults?.billingReceipts !== void 0 && ![
|
|
30379
|
+
"async",
|
|
30380
|
+
"awaited",
|
|
30381
|
+
"intent"
|
|
30382
|
+
].includes(options.defaults.billingReceipts)) throw new ConfigError("createEngine defaults.billingReceipts must be 'async', 'awaited' or 'intent'");
|
|
29194
30383
|
if (options.telemetry?.quotaDeniedAgentError !== void 0 && typeof options.telemetry.quotaDeniedAgentError !== "boolean") throw new ConfigError("createEngine telemetry.quotaDeniedAgentError must be a boolean");
|
|
29195
30384
|
validateDeterminismConfig(options.determinism);
|
|
29196
30385
|
validateEngineQuotaConfig(options.quota);
|
|
@@ -29228,6 +30417,7 @@ function createEngine(options) {
|
|
|
29228
30417
|
if (opts?.clampTurnToExposure !== void 0 && typeof opts.clampTurnToExposure !== "boolean") throw new ConfigError("RunOptions.clampTurnToExposure must be a boolean; got " + JSON.stringify(opts.clampTurnToExposure));
|
|
29229
30418
|
if (opts?.strictPricing !== void 0 && typeof opts.strictPricing !== "boolean" && (typeof opts.strictPricing !== "object" || opts.strictPricing === null || Array.isArray(opts.strictPricing))) throw new ConfigError("RunOptions.strictPricing must be a boolean or an options object; got " + JSON.stringify(opts.strictPricing));
|
|
29230
30419
|
if (opts?.budgetPolicy !== void 0 && opts.budgetPolicy !== "segment" && opts.budgetPolicy !== "immutable-lifetime") throw new ConfigError("RunOptions.budgetPolicy must be 'segment' or 'immutable-lifetime'; got " + JSON.stringify(opts.budgetPolicy));
|
|
30420
|
+
const declaredScope = opts?.scope === void 0 ? void 0 : normalizeExecutionScope(opts.scope, "RunOptions.scope");
|
|
29231
30421
|
if (opts?.limits !== void 0) validateUsageLimits(opts.limits, "RunOptions.limits");
|
|
29232
30422
|
const deadlineAtMs = opts?.deadlineAt === void 0 ? void 0 : parseDeadlineAt(opts.deadlineAt);
|
|
29233
30423
|
const compiled = wf.kind === "compiled-workflow" ? wf : void 0;
|
|
@@ -29263,6 +30453,7 @@ function createEngine(options) {
|
|
|
29263
30453
|
};
|
|
29264
30454
|
const configFingerprint = opts?.configFingerprint ?? resumeCtx?.configFingerprint;
|
|
29265
30455
|
const budgetPolicy = opts?.budgetPolicy ?? resumeCtx?.budgetPolicy;
|
|
30456
|
+
const executionScope = declaredScope ?? resumeCtx?.scope;
|
|
29266
30457
|
const makeBudget = () => new RunBudget({
|
|
29267
30458
|
...ceilingUsd === void 0 ? {} : { ceilingUsd },
|
|
29268
30459
|
...exposureCapUsd === void 0 ? {} : { maxInFlightExposureUsd: exposureCapUsd },
|
|
@@ -29447,6 +30638,7 @@ function createEngine(options) {
|
|
|
29447
30638
|
...strictPricing === void 0 ? {} : { strictPricing },
|
|
29448
30639
|
...budgetPolicy === "immutable-lifetime" ? { budgetPolicy } : {},
|
|
29449
30640
|
...configFingerprint === void 0 ? {} : { configFingerprint },
|
|
30641
|
+
...executionScope === void 0 ? {} : { scope: executionScope },
|
|
29450
30642
|
...argsBinding.argsProvided === void 0 ? {} : { argsProvided: argsBinding.argsProvided },
|
|
29451
30643
|
...argsBinding.argsHash === void 0 ? {} : { argsHash: argsBinding.argsHash },
|
|
29452
30644
|
...genesis === void 0 ? {} : { genesis },
|
|
@@ -29538,6 +30730,34 @@ function createEngine(options) {
|
|
|
29538
30730
|
}
|
|
29539
30731
|
});
|
|
29540
30732
|
}
|
|
30733
|
+
if (executionScope !== void 0 && resumeCtx === void 0) await replayer.appendSinglePhase({
|
|
30734
|
+
scope: "",
|
|
30735
|
+
key: deriverV2.deriveKey({ kind: "execution-scope" }),
|
|
30736
|
+
kind: "decision",
|
|
30737
|
+
status: "ok",
|
|
30738
|
+
spanId: rootSpanId,
|
|
30739
|
+
site: "execution-scope",
|
|
30740
|
+
value: {
|
|
30741
|
+
decisionType: "execution_scope",
|
|
30742
|
+
scope: executionScope
|
|
30743
|
+
}
|
|
30744
|
+
});
|
|
30745
|
+
if (resumeCtx?.acknowledgedOpenWireIntents !== void 0 && resumeCtx.acknowledgedOpenWireIntents > 0 && resumeCtx.strict !== true) await replayer.appendSinglePhase({
|
|
30746
|
+
scope: "",
|
|
30747
|
+
key: deriverV2.deriveKey({
|
|
30748
|
+
kind: "open-wire-intents-acknowledged",
|
|
30749
|
+
segment: segmentsBefore + 1
|
|
30750
|
+
}),
|
|
30751
|
+
kind: "decision",
|
|
30752
|
+
status: "ok",
|
|
30753
|
+
spanId: rootSpanId,
|
|
30754
|
+
site: "resume-acknowledgment",
|
|
30755
|
+
value: {
|
|
30756
|
+
decisionType: "open_wire_intents_acknowledged",
|
|
30757
|
+
segment: segmentsBefore + 1,
|
|
30758
|
+
count: resumeCtx.acknowledgedOpenWireIntents
|
|
30759
|
+
}
|
|
30760
|
+
});
|
|
29541
30761
|
await putMeta("running");
|
|
29542
30762
|
bus.emit({
|
|
29543
30763
|
type: "run:start",
|
|
@@ -29795,6 +31015,7 @@ function createEngine(options) {
|
|
|
29795
31015
|
events: bus.iterate(),
|
|
29796
31016
|
on: (type, cb) => bus.on(type, cb),
|
|
29797
31017
|
resolveExternal: (key, value) => external.resolveExternal(key, value),
|
|
31018
|
+
revokeApproval: (key, options) => external.revokeApproval(key, options),
|
|
29798
31019
|
cancel: async (reason) => {
|
|
29799
31020
|
requestCancel(reason ?? "cancelled by host");
|
|
29800
31021
|
await result.then(() => void 0, () => void 0);
|
|
@@ -29862,6 +31083,15 @@ function createEngine(options) {
|
|
|
29862
31083
|
type: "RulvarWarning"
|
|
29863
31084
|
});
|
|
29864
31085
|
}
|
|
31086
|
+
{
|
|
31087
|
+
const supplied = resumeOptions?.scope === void 0 ? void 0 : normalizeExecutionScope(resumeOptions.scope, "ResumeOptions.scope");
|
|
31088
|
+
const recorded = typeof meta?.scope === "object" && meta.scope !== null ? meta.scope : void 0;
|
|
31089
|
+
if (supplied !== void 0 && recorded !== void 0 && executionScopeKey(supplied) !== executionScopeKey(recorded)) throw new ConfigError(`resume: the supplied scope does not match the one run '${runId}' recorded at genesis; the execution scope is immutable for the life of the run, and the host declared exactly this check`);
|
|
31090
|
+
if (supplied !== void 0 && recorded === void 0) process.emitWarning(`resume: a scope was supplied but run '${runId}' never recorded one; the assertion cannot be verified (absence means NOT RECORDED)`, {
|
|
31091
|
+
code: "RULVAR_RESUME_SCOPE_UNRECORDED",
|
|
31092
|
+
type: "RulvarWarning"
|
|
31093
|
+
});
|
|
31094
|
+
}
|
|
29865
31095
|
const priorEntries = (await journal.load(runId)).map((entry) => normalizeEntry(entry));
|
|
29866
31096
|
scanJournalCompatibility(runId, priorEntries, buildDeriverRegistry(options.extraDerivers));
|
|
29867
31097
|
if (priorEntries.some((entry) => entry.usageSemantics === void 0 && (entry.servedBy?.startsWith("openai:") === true && (entry.usage?.cacheWriteTokens ?? 0) > 0 || (entry.usageByModel?.some((slice) => slice.servedBy.startsWith("openai:") && slice.usage.cacheWriteTokens > 0) ?? false)))) process.emitWarning(`resume: run '${runId}' contains OpenAI cache-write usage recorded without a usage-semantics stamp. Entries written by rulvar v1.19.0 double-counted cache writes into inputTokens, so their recorded cost and budget debits are OVERSTATED; unstamped entries from v1.20.0 are correct. Resuming keeps the recorded debits. Audit procedure: https://docs.rulvar.com/guide/providers#openai-legacy-cache-journals`, {
|
|
@@ -29874,7 +31104,13 @@ function createEngine(options) {
|
|
|
29874
31104
|
...runOverride.maxInFlightExposureUsd === void 0 ? {} : { maxInFlightExposureUsd: runOverride.maxInFlightExposureUsd }
|
|
29875
31105
|
};
|
|
29876
31106
|
if (budgetOverride !== void 0 && meta?.budgetPolicy === "immutable-lifetime") throw new ConfigError(`run '${runId}' was started with budgetPolicy 'immutable-lifetime': the recorded ceilings are immutable for the whole life of the run and ResumeOptions.run is refused, raising and lowering alike; cancel the run (or start a new one) instead of editing its ceilings`);
|
|
31107
|
+
const openIntents = openWireIntentsOf(priorEntries);
|
|
31108
|
+
if (openIntents.length > 0 && resumeOptions?.acknowledgeOpenWireIntents !== true) {
|
|
31109
|
+
const preview = openIntents.slice(0, 3).map((intent) => `agent ${String(intent.agentRef)} ordinal ${String(intent.ordinal)} attempt ${String(intent.attempt)} (${intent.servedBy})`).join("; ");
|
|
31110
|
+
throw new ConfigError(`resume: run '${runId}' holds ${String(openIntents.length)} provider wire intent(s) with unknown outcome (${preview}${openIntents.length > 3 ? "; …" : ""}): an intent was journaled before dispatch and neither a receipt nor a terminal record covers it, so the provider may have billed a wire this process never heard back from, and a blind retry could pay twice. Reconcile the invoice's openIntents lane (cost-audit prints it) against the provider statement, then resume with ResumeOptions.acknowledgeOpenWireIntents: true; the acknowledgment is journaled`);
|
|
31111
|
+
}
|
|
29877
31112
|
return run(bound, resumeOptions?.args, void 0, {
|
|
31113
|
+
...openIntents.length > 0 && resumeOptions?.acknowledgeOpenWireIntents === true ? { acknowledgedOpenWireIntents: openIntents.length } : {},
|
|
29878
31114
|
runId,
|
|
29879
31115
|
priorEntries,
|
|
29880
31116
|
strict: resumeOptions?.dryRun ?? false,
|
|
@@ -29884,6 +31120,7 @@ function createEngine(options) {
|
|
|
29884
31120
|
...typeof meta?.budgetUsd === "number" ? { budgetUsd: meta.budgetUsd } : {},
|
|
29885
31121
|
...typeof meta?.maxInFlightExposureUsd === "number" ? { maxInFlightExposureUsd: meta.maxInFlightExposureUsd } : {},
|
|
29886
31122
|
...typeof meta?.strictPricing === "object" && meta.strictPricing !== null ? { strictPricing: meta.strictPricing } : {},
|
|
31123
|
+
...typeof meta?.scope === "object" && meta.scope !== null ? { scope: meta.scope } : {},
|
|
29887
31124
|
...meta?.budgetPolicy === "immutable-lifetime" ? { budgetPolicy: meta.budgetPolicy } : {},
|
|
29888
31125
|
segmentsBefore: typeof meta?.segments === "number" && meta.segments > 0 ? Math.floor(meta.segments) : 1,
|
|
29889
31126
|
...typeof meta?.argsProvided === "boolean" ? { argsProvided: meta.argsProvided } : {},
|
|
@@ -29914,6 +31151,9 @@ function createEngine(options) {
|
|
|
29914
31151
|
resolveExternal: async (key, value) => {
|
|
29915
31152
|
return (await handlePromise).resolveExternal(key, value);
|
|
29916
31153
|
},
|
|
31154
|
+
revokeApproval: async (key, options) => {
|
|
31155
|
+
return (await handlePromise).revokeApproval(key, options);
|
|
31156
|
+
},
|
|
29917
31157
|
cancel: async (reason) => {
|
|
29918
31158
|
await (await handlePromise).cancel(reason);
|
|
29919
31159
|
},
|
|
@@ -30072,6 +31312,231 @@ function createEngine(options) {
|
|
|
30072
31312
|
};
|
|
30073
31313
|
}
|
|
30074
31314
|
//#endregion
|
|
31315
|
+
//#region src/engine/regulated-profile.ts
|
|
31316
|
+
/**
|
|
31317
|
+
* The regulated run profile (RV4009, the fifth comparison experiment;
|
|
31318
|
+
* previously gated behind its own word and confirmed with plan 40).
|
|
31319
|
+
*
|
|
31320
|
+
* Every assurance posture this codebase grew across the comparison
|
|
31321
|
+
* arcs is an OPT-IN knob, which is correct for a library and lethal
|
|
31322
|
+
* for an unreviewed config: the 2026-08-12 run armed every gate to
|
|
31323
|
+
* observe, and the fifth run's harness gated on error findings alone.
|
|
31324
|
+
* `compileRegulatedProfile` is the one-call composition: it takes the
|
|
31325
|
+
* host's ordinary options, REFUSES any field that loosens the
|
|
31326
|
+
* regulated floor (typed, naming the field), fills what is absent,
|
|
31327
|
+
* and returns the compiled options plus a profile hash over the
|
|
31328
|
+
* enforced posture. The hash rides RunOptions.configFingerprint, so
|
|
31329
|
+
* the existing genesis recording and resume assertion machinery
|
|
31330
|
+
* (RV3210) pin it with zero new meta surface.
|
|
31331
|
+
*
|
|
31332
|
+
* DATA, not engine semantics (the M5-T07 doctrine): the engine gains
|
|
31333
|
+
* no strategy enum and no behavioral branch; a host that wants the
|
|
31334
|
+
* posture applies the compiled options like any others. The floor
|
|
31335
|
+
* binds what flows through CreateEngineOptions / RunOptions /
|
|
31336
|
+
* OrchestrateOptions, and since RV4101 it also walks the
|
|
31337
|
+
* CONSTRUCTIONS those options reach (adapters, tool sources in named
|
|
31338
|
+
* toolsets and profiles). A construction exposing
|
|
31339
|
+
* `describeRegulatedPosture()` has its posture judged by field name
|
|
31340
|
+
* (an MCP source's drift must be 'refuse' with every discovery bound
|
|
31341
|
+
* declared; the AI SDK bridge must keep providerExecutedTools
|
|
31342
|
+
* 'deny'), the sorted descriptors enter the hashed map under
|
|
31343
|
+
* `construction`, and constructions exposing nothing are COUNTED
|
|
31344
|
+
* there as `unrecognized`, so the hash names its own blind spot
|
|
31345
|
+
* instead of implying totality (the RV4009 rule "a hash must not
|
|
31346
|
+
* imply what it cannot verify", now with the verifiable part
|
|
31347
|
+
* verified). The between-compile-and-use window is held as well
|
|
31348
|
+
* (RV4102): the compiled options carry re-asserting wrappers whose
|
|
31349
|
+
* risk seams re-judge the descriptor on every use, and the
|
|
31350
|
+
* cross-process half was always held by the RV3210 fingerprint
|
|
31351
|
+
* assertion.
|
|
31352
|
+
*/
|
|
31353
|
+
const REGULATED_VERSION = 2;
|
|
31354
|
+
function refuse(field, requirement) {
|
|
31355
|
+
throw new ConfigError(`compileRegulatedProfile: ${field} ${requirement}; the regulated floor is non-loosenable, so drop the field to inherit the floor or meet it explicitly`);
|
|
31356
|
+
}
|
|
31357
|
+
/**
|
|
31358
|
+
* Judges one construction's descriptor against the floor (RV4101) and
|
|
31359
|
+
* returns the normalized shape that enters the hashed posture map.
|
|
31360
|
+
* Shared by the compile walk and the use-time re-assertion (RV4102),
|
|
31361
|
+
* so a posture that loosens AFTER compile refuses with the same
|
|
31362
|
+
* field-named error it would have refused with at compile time.
|
|
31363
|
+
*/
|
|
31364
|
+
function judgeDescriptor(raw) {
|
|
31365
|
+
const descriptor = raw;
|
|
31366
|
+
if (descriptor === null || typeof descriptor !== "object" || descriptor.regulatedPosture !== 1 || typeof descriptor.name !== "string" || descriptor.name === "") refuse("construction", "exposes describeRegulatedPosture() with an unrecognized shape (need regulatedPosture: 1, a non-empty string name, and a known kind)");
|
|
31367
|
+
if (descriptor.kind === "mcp-source") {
|
|
31368
|
+
const mcpPosture = descriptor;
|
|
31369
|
+
if (mcpPosture.drift !== "refuse") refuse(`construction['${descriptor.name}'].drift`, "must be 'refuse' (RV1516): under a rekey posture a listChanged notification imports a changed tool list beneath the regulated run");
|
|
31370
|
+
const bounds = mcpPosture.bounds;
|
|
31371
|
+
if (bounds === void 0 || bounds.declared !== true) refuse(`construction['${descriptor.name}'].bounds`, "must declare every discovery bound (maxTools, maxPages, maxSchemaBytes, timeouts.discoveryMs; RV1808): an unbounded sweep against a remote registry is an availability decision someone should have made on purpose");
|
|
31372
|
+
return {
|
|
31373
|
+
regulatedPosture: 1,
|
|
31374
|
+
kind: "mcp-source",
|
|
31375
|
+
name: descriptor.name,
|
|
31376
|
+
drift: "refuse",
|
|
31377
|
+
bounds: {
|
|
31378
|
+
declared: true,
|
|
31379
|
+
...typeof bounds.maxTools === "number" ? { maxTools: bounds.maxTools } : {},
|
|
31380
|
+
...typeof bounds.maxPages === "number" ? { maxPages: bounds.maxPages } : {},
|
|
31381
|
+
...typeof bounds.maxSchemaBytes === "number" ? { maxSchemaBytes: bounds.maxSchemaBytes } : {},
|
|
31382
|
+
...typeof bounds.discoveryMs === "number" ? { discoveryMs: bounds.discoveryMs } : {}
|
|
31383
|
+
}
|
|
31384
|
+
};
|
|
31385
|
+
}
|
|
31386
|
+
if (descriptor.kind === "ai-sdk-bridge") {
|
|
31387
|
+
if (descriptor.providerExecutedTools !== "deny") refuse(`construction['${descriptor.name}'].providerExecutedTools`, "must be 'deny': a provider-executed tool runs outside the permission chain and the journal");
|
|
31388
|
+
return {
|
|
31389
|
+
regulatedPosture: 1,
|
|
31390
|
+
kind: "ai-sdk-bridge",
|
|
31391
|
+
name: descriptor.name,
|
|
31392
|
+
providerExecutedTools: "deny"
|
|
31393
|
+
};
|
|
31394
|
+
}
|
|
31395
|
+
refuse(`construction['${descriptor.name}']`, `attests an unrecognized kind '${String(descriptor.kind)}'; this floor can judge 'mcp-source' and 'ai-sdk-bridge'`);
|
|
31396
|
+
}
|
|
31397
|
+
/**
|
|
31398
|
+
* The use-time re-assertion (RV4102, the RV1608 template). The
|
|
31399
|
+
* descriptor is a snapshot, and the window between compile and use is
|
|
31400
|
+
* where a construction mutated in-process could walk a moved posture
|
|
31401
|
+
* beneath the hash. The compiled options therefore carry this proxy
|
|
31402
|
+
* in the original's place: every use of the risk seam (`tools` on a
|
|
31403
|
+
* source, `stream` on an adapter) re-reads and re-judges the
|
|
31404
|
+
* descriptor first. A loosening refuses with the compile-time
|
|
31405
|
+
* field-named error; any other movement (a rename, a bound change, a
|
|
31406
|
+
* vanished descriptor) refuses naming the drift. Everything else
|
|
31407
|
+
* passes through untouched, so `close()`, `caps()`, and identity
|
|
31408
|
+
* fields behave exactly as before. The cross-process half of the
|
|
31409
|
+
* window needs no proxy: a mutated construction compiles to a
|
|
31410
|
+
* different profile hash, and the RV3210 resume assertion refuses it.
|
|
31411
|
+
*/
|
|
31412
|
+
function wrapReasserting(construction, frozen) {
|
|
31413
|
+
const guard = (seam, original) => (...args) => {
|
|
31414
|
+
const probe = construction.describeRegulatedPosture;
|
|
31415
|
+
const fresh = typeof probe === "function" ? jcsSerialize(judgeDescriptor(probe.call(construction))) : void 0;
|
|
31416
|
+
if (fresh !== frozen) throw new ConfigError(`compileRegulatedProfile: the construction posture moved between compile time and ${seam}() (RV4102): the compiled profile licensed ${frozen}, the construction now reports ${fresh ?? "no describeRegulatedPosture() at all"}. Recompile the profile deliberately instead of mutating a construction beneath it.`);
|
|
31417
|
+
return original.apply(construction, args);
|
|
31418
|
+
};
|
|
31419
|
+
return new Proxy(construction, { get(target, prop) {
|
|
31420
|
+
const value = Reflect.get(target, prop, target);
|
|
31421
|
+
if ((prop === "tools" || prop === "stream") && typeof value === "function") return guard(String(prop), value);
|
|
31422
|
+
return value;
|
|
31423
|
+
} });
|
|
31424
|
+
}
|
|
31425
|
+
function compileRegulatedProfile(input) {
|
|
31426
|
+
const engine = {
|
|
31427
|
+
...input.engine,
|
|
31428
|
+
defaults: { ...input.engine.defaults }
|
|
31429
|
+
};
|
|
31430
|
+
const run = { ...input.run };
|
|
31431
|
+
const orchestrate = input.orchestrate === void 0 ? void 0 : { ...input.orchestrate };
|
|
31432
|
+
const defaults = engine.defaults ?? {};
|
|
31433
|
+
const permissions = { ...defaults.permissions ?? {} };
|
|
31434
|
+
if (permissions.strictApprovals === false) refuse("defaults.permissions.strictApprovals", "must not be false (RV1507 monotonic mode)");
|
|
31435
|
+
permissions.strictApprovals = true;
|
|
31436
|
+
defaults.permissions = permissions;
|
|
31437
|
+
if (defaults.billingReceipts !== void 0 && defaults.billingReceipts !== "intent") refuse("defaults.billingReceipts", "must be 'intent' (RV4006 pre-wire intents)");
|
|
31438
|
+
defaults.billingReceipts = "intent";
|
|
31439
|
+
engine.defaults = defaults;
|
|
31440
|
+
const determinism = { ...engine.determinism ?? {} };
|
|
31441
|
+
if (determinism.mode !== void 0 && determinism.mode !== "error") refuse("determinism.mode", "must be 'error'");
|
|
31442
|
+
determinism.mode = "error";
|
|
31443
|
+
engine.determinism = determinism;
|
|
31444
|
+
for (const [name, profile] of Object.entries(defaults.profiles ?? {})) {
|
|
31445
|
+
if (profile.permissions?.strictApprovals === false) refuse(`defaults.profiles.${name}.permissions.strictApprovals`, "must not be false");
|
|
31446
|
+
if (profile.tools !== void 0 && profile.toolsetAttestation === void 0) refuse(`defaults.profiles.${name}`, "declares tools without a toolsetAttestation (pin the resolved hashes)");
|
|
31447
|
+
}
|
|
31448
|
+
const walked = /* @__PURE__ */ new Set();
|
|
31449
|
+
const attested = [];
|
|
31450
|
+
const reasserted = /* @__PURE__ */ new Map();
|
|
31451
|
+
let unrecognized = 0;
|
|
31452
|
+
const visit = (construction) => {
|
|
31453
|
+
if (construction === null || typeof construction !== "object" || walked.has(construction)) return;
|
|
31454
|
+
walked.add(construction);
|
|
31455
|
+
const probe = construction.describeRegulatedPosture;
|
|
31456
|
+
if (typeof probe !== "function") {
|
|
31457
|
+
unrecognized += 1;
|
|
31458
|
+
return;
|
|
31459
|
+
}
|
|
31460
|
+
const judged = judgeDescriptor(probe.call(construction));
|
|
31461
|
+
attested.push(judged);
|
|
31462
|
+
reasserted.set(construction, wrapReasserting(construction, jcsSerialize(judged)));
|
|
31463
|
+
};
|
|
31464
|
+
for (const adapter of engine.adapters ?? []) visit(adapter);
|
|
31465
|
+
const visitTools = (tools) => {
|
|
31466
|
+
for (const entry of tools ?? []) {
|
|
31467
|
+
if (typeof entry === "string" || entry.kind === "tool") continue;
|
|
31468
|
+
visit(entry);
|
|
31469
|
+
}
|
|
31470
|
+
};
|
|
31471
|
+
for (const toolset of Object.values(defaults.toolsets ?? {})) visitTools(toolset);
|
|
31472
|
+
for (const profile of Object.values(defaults.profiles ?? {})) visitTools(profile.tools);
|
|
31473
|
+
const swap = (value) => typeof value === "object" && value !== null && reasserted.has(value) ? reasserted.get(value) : value;
|
|
31474
|
+
if (reasserted.size > 0) {
|
|
31475
|
+
if (engine.adapters !== void 0) engine.adapters = engine.adapters.map(swap);
|
|
31476
|
+
if (defaults.toolsets !== void 0) defaults.toolsets = Object.fromEntries(Object.entries(defaults.toolsets).map(([name, tools]) => [name, tools.map(swap)]));
|
|
31477
|
+
if (defaults.profiles !== void 0) defaults.profiles = Object.fromEntries(Object.entries(defaults.profiles).map(([name, profile]) => [name, profile.tools === void 0 ? profile : {
|
|
31478
|
+
...profile,
|
|
31479
|
+
tools: profile.tools.map(swap)
|
|
31480
|
+
}]));
|
|
31481
|
+
}
|
|
31482
|
+
const postureKeyOf = (entry) => `${entry.kind} ${entry.name}`;
|
|
31483
|
+
attested.sort((a, b) => postureKeyOf(a) < postureKeyOf(b) ? -1 : postureKeyOf(a) > postureKeyOf(b) ? 1 : 0);
|
|
31484
|
+
if (typeof run.budgetUsd !== "number" || !Number.isFinite(run.budgetUsd) || run.budgetUsd <= 0) refuse("run.budgetUsd", "must declare a positive finite USD ceiling (RV4107): NaN and Infinity are not ceilings, and a non-positive one is a run that cannot pay for its own floor");
|
|
31485
|
+
if (run.strictPricing === false) refuse("run.strictPricing", "must not be false");
|
|
31486
|
+
run.strictPricing = run.strictPricing ?? true;
|
|
31487
|
+
if (run.budgetPolicy !== void 0 && run.budgetPolicy !== "immutable-lifetime") refuse("run.budgetPolicy", "must be 'immutable-lifetime' (RV3902)");
|
|
31488
|
+
run.budgetPolicy = "immutable-lifetime";
|
|
31489
|
+
if (run.scope === void 0) refuse("run.scope", "must name the execution scope (RV4007): a regulated run has an owner");
|
|
31490
|
+
run.scope = normalizeExecutionScope(run.scope, "compileRegulatedProfile run.scope");
|
|
31491
|
+
if (orchestrate !== void 0) {
|
|
31492
|
+
const budget = { ...orchestrate.budget ?? {} };
|
|
31493
|
+
if (budget.acceptanceReserve !== void 0 && budget.acceptanceReserve !== "require") refuse("orchestrate.budget.acceptanceReserve", "must be 'require' (RV3907/RV4001)");
|
|
31494
|
+
budget.acceptanceReserve = "require";
|
|
31495
|
+
orchestrate.budget = budget;
|
|
31496
|
+
if (orchestrate.citationAudit === void 0) refuse("orchestrate.citationAudit", "must be declared with the host snapshot resolver (RV4004): entailment is the regulated posture, not an option");
|
|
31497
|
+
if (typeof orchestrate.citationAudit.resolve !== "function") refuse("orchestrate.citationAudit.resolve", "must be the host snapshot resolver function (RV4004/RV4107)");
|
|
31498
|
+
if (orchestrate.claimConsistency === void 0) refuse("orchestrate.claimConsistency", "must be declared with stage 'final' or 'both' (RV4103): the claim machinery is the regulated posture, and omitting it entirely is the deepest loosening");
|
|
31499
|
+
if (orchestrate.claimConsistency !== void 0) {
|
|
31500
|
+
const claim = { ...orchestrate.claimConsistency };
|
|
31501
|
+
if (claim.coveragePolicy !== void 0 && claim.coveragePolicy !== "strict-final") refuse("orchestrate.claimConsistency.coveragePolicy", "must be 'strict-final' (RV4003)");
|
|
31502
|
+
if ((claim.stage ?? "draft") === "draft") refuse("orchestrate.claimConsistency.stage", "must be 'final' or 'both': the shipped document is what the pass must grade");
|
|
31503
|
+
claim.coveragePolicy = "strict-final";
|
|
31504
|
+
orchestrate.claimConsistency = claim;
|
|
31505
|
+
}
|
|
31506
|
+
}
|
|
31507
|
+
const posture = {
|
|
31508
|
+
regulated: REGULATED_VERSION,
|
|
31509
|
+
strictApprovals: true,
|
|
31510
|
+
billingReceipts: "intent",
|
|
31511
|
+
determinism: "error",
|
|
31512
|
+
construction: {
|
|
31513
|
+
attested,
|
|
31514
|
+
unrecognized
|
|
31515
|
+
},
|
|
31516
|
+
strictPricing: run.strictPricing === true ? true : run.strictPricing,
|
|
31517
|
+
budgetPolicy: "immutable-lifetime",
|
|
31518
|
+
budgetUsd: run.budgetUsd,
|
|
31519
|
+
scope: run.scope,
|
|
31520
|
+
...orchestrate === void 0 ? {} : {
|
|
31521
|
+
acceptanceReserve: "require",
|
|
31522
|
+
citationAudit: true,
|
|
31523
|
+
...orchestrate.claimConsistency === void 0 ? {} : {
|
|
31524
|
+
coveragePolicy: "strict-final",
|
|
31525
|
+
claimStage: orchestrate.claimConsistency.stage
|
|
31526
|
+
}
|
|
31527
|
+
},
|
|
31528
|
+
...run.configFingerprint === void 0 ? {} : { hostFingerprint: run.configFingerprint }
|
|
31529
|
+
};
|
|
31530
|
+
const profileHash = createHash("sha256").update(jcsSerialize(posture), "utf8").digest("hex");
|
|
31531
|
+
run.configFingerprint = `regulated:${String(REGULATED_VERSION)}:${profileHash}`;
|
|
31532
|
+
return {
|
|
31533
|
+
engine,
|
|
31534
|
+
run,
|
|
31535
|
+
...orchestrate === void 0 ? {} : { orchestrate },
|
|
31536
|
+
profileHash
|
|
31537
|
+
};
|
|
31538
|
+
}
|
|
31539
|
+
//#endregion
|
|
30075
31540
|
//#region src/runner/sandbox-bridge.ts
|
|
30076
31541
|
/**
|
|
30077
31542
|
* The host half of the worker sandbox contract (M6-T02).
|
|
@@ -30361,4 +31826,4 @@ function createSandboxBridge(ctx, options) {
|
|
|
30361
31826
|
};
|
|
30362
31827
|
}
|
|
30363
31828
|
//#endregion
|
|
30364
|
-
export { AWAIT_SCHEMA, AdmissionController, AdmissionRejectedError, AgentCallError, BUDGET_ABORT_REASON, BudgetExhaustedError, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CLAIM_JUDGE_LABEL, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, ConfigError, DECISION_CHAIN_KINDS, DEFAULT_ANCHOR_PATTERN, DEFAULT_ARTIFACT_PATTERN, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_PATTERN, DEFAULT_CITATION_SAMPLE, DEFAULT_CLAIM_JUDGE_MAX_TURNS, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_CALLS_PER_ENTRY, DEFAULT_EVIDENCE_GRADE_PHRASES, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_EVIDENCE_OVERHEAD_CALLS, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_CLAIM_PAIRS, DEFAULT_MAX_CONTRADICTIONS, DEFAULT_MAX_DEPTH, DEFAULT_MAX_EXCERPT_CHARS, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PAIR_EXCERPT_CHARS, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_POOL_PER_PAIR, DEFAULT_MAX_QUOTA_DENIALS, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_RUN_FACT_PAIRS, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_SYNTHESIS_MAX_TURNS, DEFAULT_SYNTHESIS_NOTE_MAX_TURNS, DedupIndex, DeterminismError, EMIT_RESULT_TOOL, EMPTY_AUTHORITY_HASH, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EXPOSURE_WAIT_SWEEP_MS, EscalationDecisionAbortedError, EventBus, ExternalRegistry, FINALIZE_SYNTHESIS_INSTRUCTION, FINAL_COMPOSITION_LABEL, FINISH_LESSON_CAP_CHARS, FINISH_SCHEMA, FINISH_SECTIONAL_SCHEMA, FINISH_TOOL_NAME, FUTURE_RATES_TOLERANCE_MS, FailRunError, FileModelKnowledgeStore, FileTranscriptStore, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, GET_SETTLED_CHILD_RESULTS_SCHEMA, GET_SETTLED_CHILD_RESULTS_TOOL_NAME, GitWorktreeProvider, IMPLEMENTATION_PROFILE_LIMITS, INBOX_PROPOSAL_TTL_DAYS, IN_FLIGHT_EXPOSURE_REFUSAL_PREFIX, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, JOURNAL_ENVELOPE_MARKER, JournalCompatibilityError, JournalIntegrityError, JournalMatcher, JournalMissError, JournalOrderViolation, JournalSealedError, JsonlFileStore, KB_ACTIVE_CLAIMS_CAP, KB_CARD_RENDER_BUDGET_CHARS, KeyedLimiter, KnowledgeCasError, LARGE_VALUE_WARN_BYTES, LEGACY_LTID_PREFIX, LEGACY_SIGNATURE_INPUTS, LINEAGE_SIG_VERSION, LeaseHeldError, LineageIndex, MASKED_SECRET, MAX_CHILD_RESULT_PAGE_CHARS, MAX_CRITICAL_UNCOVERED, MAX_DEPTH_CEILING, MAX_RUN_FACTS_SHEET_CHARS, MAX_RUN_ID_LENGTH, MAX_TIMER_DELAY_MS, ModelRetry, NoProgressDetector, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OrchestratorCapConfigError, PARALLEL_AGENTS_SCHEMA, PROGRESS_REPORT_TOOL_NAME, ParallelSiteCounter, PlanInvariantError, QUOTA_WINDOW_MS, READ_CHILD_ARTIFACT_SCHEMA, READ_CHILD_ARTIFACT_TOOL_NAME, RESEARCH_PROFILE_LIMITS, REVIEW_PROFILE_LIMITS, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_FACTS_ANCHOR, RUN_PROFILES, RUN_SETTLE_DECISION_TYPE, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionFold, RulvarError, RunBudget, SANDBOX_AGENT_OPT_KEYS, SPAWN_ADMISSION_DECISION_TYPE, SPAWN_AGENT_SCHEMA, SYNTHESIS_NOTE_LABEL, SandboxError, ScriptRejected, Semaphore, SettlementError, SpanRegistry, SupersededError, TERMINAL_TELEMETRY_SCOPE, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, accountSpendFromJournal, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyFinishRepairHints, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, assertSafeRunId, atCompactionThreshold, attestToolset, attributionBucket, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, childRostersFromJournal, citationTargetsValidator, citedValueValidator, claimCoverageOf, claimExpired, claimExpiry, claimIssues, claimJudgeStageOf, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compareRates, compilePermissionChain, compilePermissionPreset, compileSecretMasker, compileVerifiedLayer, constantTimeEqual, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createEnvelopeEncryption, createSandboxBridge, criticalPathFromJournal, currentOnlyKeyRing, decodeCheckpoint, dedupeRepeatedClaims, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispatchProjectionReserveUsd, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, enforceToolsetAttestation, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidenceGradeValidator, evidencePreservedValidator, executeWorkflow, executionFactsOf, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, findContradictions, finishContract, foldLedger, foldTermination, formatCharacterValidator, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashRunOutput, hashWorkflowBody, hashWorkflowSource, headingStructureValidator, identityJcs, implementationAgentProfile, insertRunIdIntoSentence, invoiceFromJournal, isClaimJudgeLabel, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, journalPricingSnapshot, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastMechanicalRepairCostUsd, lastRunSettle, latestProgressReport, lexShellCommand, liftRetainedParts, lineageWeightOf, localKeyProvider, logicalRunTelemetry, makeOrchestratorWorkflow, manifestValidators, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, memoryQuotaLimiter, mergeQuotaDenial, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeFallbacks, orchestrate, orchestratorAdmissionEstCostUsd, pairDraftClaims, pairRunFactClaims, parallelScope, parseModelRef, parseScopePath, parseTerminalEnvelope, persistedTerminalEnvelope, phiInitialOf, pilotAgentProfile, pipelineScope, planNodeScope, preflightEstimate, priceComponentsOf, priceEntryBilling, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualRequestsDelta, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleKey, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reconcileStatement, reduceAuditTrail, reduceCriticalPath, reduceDecisionChain, reduceInvocationTable, registryKeyRing, remeasureQueue, renderContractRequirements, replayDisposition, repositoryResearchToolset, requiredFieldsValidator, requiredMentionsValidator, requiredSectionsValidator, researchAgentProfile, resolveModelInvocation, resolvePricing, resolveToolset, retryClassOf, retryDelayMs, reviewAgentProfile, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, scopeBucket, sectionCitationsValidator, sectionPatternCountValidator, sectionalRoundPlan, selectStructuredOutputTier, selfTestFinishValidation, shouldCompact, snapshotQuotaRules, snapshotUsage, spawnDepthOf, spliceSections, statementFromRows, statementRowsFromDelimited, stripFencedBlocks, sumUsage, summarizeInstruction, summarizeOutput, synthesisCandidatesFromJournal, terminalEnvelopeOf, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolAuthority, toolCalibrationFromJournal, toolContract, toolContractHash, toolsetAuthorityHash, toolsetHash, ttlState, unionOfIntervalsMs, usageViolations, validateDetachedResolution, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateToolsetAttestation, validateUsageLimits, wordCountValidator, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
|
|
31829
|
+
export { AWAIT_SCHEMA, AdmissionController, AdmissionRejectedError, AgentCallError, BUDGET_ABORT_REASON, BudgetExhaustedError, CANCEL_AGENT_SCHEMA, CHECKPOINT_FORMAT_V1, CITATION_JUDGE_SCHEMA, CLAIM_JUDGE_LABEL, CLAIM_STATEMENT_MAX_CHARS, CLAIM_TTL_DAYS, COMPACTION_SUMMARY_PREFIX, CURRENT_HASH_VERSION, ConfigError, DECISION_CHAIN_KINDS, DEFAULT_ANCHOR_PATTERN, DEFAULT_ARTIFACT_PATTERN, DEFAULT_CHILD_BUDGET_FRACTION, DEFAULT_CHILD_RESULT_PAGE_CHARS, DEFAULT_CITATION_EXCERPT_WINDOW, DEFAULT_CITATION_MAX_SAMPLED, DEFAULT_CITATION_PATTERN, DEFAULT_CITATION_SAMPLE, DEFAULT_CITATION_SAMPLE_PER_SECTION, DEFAULT_CLAIM_JUDGE_MAX_TURNS, DEFAULT_COMPACTION_THRESHOLD, DEFAULT_ESCALATION_LIMITS, DEFAULT_EVIDENCE_CALLS_PER_ENTRY, DEFAULT_EVIDENCE_GRADE_PHRASES, DEFAULT_EVIDENCE_MIN_SHARE, DEFAULT_EVIDENCE_OVERHEAD_CALLS, DEFAULT_FINISH_MAX_REPAIRS, DEFAULT_FLAT_RESERVE_USD, DEFAULT_MAX_CHILDREN_PER_NODE, DEFAULT_MAX_CLAIM_PAIRS, DEFAULT_MAX_CONTRADICTIONS, DEFAULT_MAX_DEPTH, DEFAULT_MAX_EXCERPT_CHARS, DEFAULT_MAX_OSCILLATIONS_PER_KEY, DEFAULT_MAX_PAIR_EXCERPT_CHARS, DEFAULT_MAX_PINNED_WORKTREES, DEFAULT_MAX_POOL_PER_PAIR, DEFAULT_MAX_QUOTA_DENIALS, DEFAULT_MAX_REVISIONS_PER_RUN, DEFAULT_MAX_RUN_FACT_PAIRS, DEFAULT_MAX_TOTAL_SPAWNS, DEFAULT_MAX_TURNS, DEFAULT_MODEL_RETRY_ATTEMPTS, DEFAULT_NO_PROGRESS_TURNS, DEFAULT_PER_RUN_CONCURRENCY, DEFAULT_RETRY_POLICY, DEFAULT_STREAM_IDLE_TIMEOUT_MS, DEFAULT_SYNTHESIS_MAX_TURNS, DEFAULT_SYNTHESIS_NOTE_MAX_TURNS, DedupIndex, DeterminismError, EMIT_RESULT_TOOL, EMPTY_AUTHORITY_HASH, EMPTY_SCHEMA_HASH, EMPTY_TOOLSET_HASH, ESCALATE_TOOL_NAME, ESCALATION_REPORT_SCHEMA, ESCALATION_REQUEST_SCHEMA, EVENT_SEGMENT_STRIDE, EXPOSURE_WAIT_SWEEP_MS, EscalationDecisionAbortedError, EventBus, ExternalRegistry, FINALIZE_SYNTHESIS_INSTRUCTION, FINAL_COMPOSITION_LABEL, FINISH_LESSON_CAP_CHARS, FINISH_SCHEMA, FINISH_SECTIONAL_SCHEMA, FINISH_TOOL_NAME, FUTURE_RATES_TOLERANCE_MS, FailRunError, FileModelKnowledgeStore, FileTranscriptStore, GET_CHILD_RESULT_SCHEMA, GET_CHILD_RESULT_TOOL_NAME, GET_SETTLED_CHILD_RESULTS_SCHEMA, GET_SETTLED_CHILD_RESULTS_TOOL_NAME, GitWorktreeProvider, IMPLEMENTATION_PROFILE_LIMITS, INBOX_PROPOSAL_TTL_DAYS, IN_FLIGHT_EXPOSURE_REFUSAL_PREFIX, InMemoryStore, InMemoryTranscriptStore, InProcessRunner, InvalidResolutionError, JOURNAL_ENVELOPE_MARKER, JournalCompatibilityError, JournalIntegrityError, JournalMatcher, JournalMissError, JournalOrderViolation, JournalSealedError, JsonlFileStore, KB_ACTIVE_CLAIMS_CAP, KB_CARD_RENDER_BUDGET_CHARS, KeyedLimiter, KnowledgeCasError, LARGE_VALUE_WARN_BYTES, LEGACY_LTID_PREFIX, LEGACY_SIGNATURE_INPUTS, LINEAGE_SIG_VERSION, LeaseHeldError, LineageIndex, MASKED_SECRET, MAX_CHILD_RESULT_PAGE_CHARS, MAX_CITATION_EXCERPT_CHARS, MAX_CITATION_EXCERPT_LINES, MAX_CRITICAL_UNCOVERED, MAX_DEPTH_CEILING, MAX_RUN_FACTS_SHEET_CHARS, MAX_RUN_ID_LENGTH, MAX_TIMER_DELAY_MS, ModelRetry, NoProgressDetector, NonSerializableValueError, ORCHESTRATE_WORKFLOW_NAME, OrchestratorCapConfigError, PARALLEL_AGENTS_SCHEMA, PROGRESS_REPORT_TOOL_NAME, ParallelSiteCounter, PlanInvariantError, QUOTA_WINDOW_MS, READ_CHILD_ARTIFACT_SCHEMA, READ_CHILD_ARTIFACT_TOOL_NAME, RESEARCH_PROFILE_LIMITS, REVIEW_PROFILE_LIMITS, ROLE_EFFORT_DEFAULTS, ROOT_ACCOUNT, ROOT_SCOPE, RUN_FACTS_ANCHOR, RUN_PROFILES, RUN_SETTLE_DECISION_TYPE, ReplayPlanHashMismatch, Replayer, ResolutionArbiter, ResolutionFold, RulvarError, RunBudget, SANDBOX_AGENT_OPT_KEYS, SPAWN_ADMISSION_DECISION_TYPE, SPAWN_AGENT_SCHEMA, SYNTHESIS_NOTE_LABEL, SandboxError, ScriptRejected, Semaphore, SettlementError, SpanRegistry, SupersededError, TERMINAL_TELEMETRY_SCOPE, TOOL_NAME_PATTERN, TerminationAccount, WAIT_FOR_EVENTS_SCHEMA, WAIT_FOR_EVENTS_TOOL_NAME, WAKE_SUMMARY_RENDER_BUDGET_CHARS, acceptanceJudgePasses, acceptanceTailRequiredUsd, accountSpendFromJournal, admissionReserveUsd, affordableOutputTokens, agentErrorFromWire, agentErrorToWire, agentResultWire, agentScope, applyClaimOps, applyFinishRepairHints, applyStructuredOutputTier, approachSigCoarse, approachSigOf, archiveDeprecatedModelOps, assertFencedWrites, assertSafeRunId, atCompactionThreshold, attestToolset, attributionBucket, auditRun, auditRuns, buildAbandonFold, buildAdapterRegistry, buildCostReport, buildDeriverRegistry, buildOrchestratorTools, buildTerminationInitValue, buildToolContext, canRideLoopTurn, canonicalIsolationTag, canonicalizeLadder, canonicalizeSchema, capIssues, capsHashOf, checkFloors, checkpointRefFor, childCoveragePrefix, childRostersFromJournal, citationExcerptOf, citationTargetsValidator, citedValueValidator, claimCoverageOf, claimExpired, claimExpiry, claimIssues, claimJudgeStageOf, claimOpIssues, classifyAgentError, classifyAttemptOutcome, collectDeclaredLadders, compactMessages, compareRates, compilePermissionChain, compilePermissionPreset, compileRegulatedProfile, compileSecretMasker, compileVerifiedLayer, constantTimeEqual, costReportFromJournal, countsAgainstLimit, createCanonicalIdMinter, createCtx, createEngine, createEnvelopeEncryption, createSandboxBridge, criticalPathFromJournal, currentOnlyKeyRing, decodeCheckpoint, dedupeRepeatedClaims, defineWorkflow, deriveContentKey, deriverV1, deriverV2, digestOf, dispatchProjectionReserveUsd, dispositionHook, emptyDigestBlocks, emptyToolset, encodeCheckpoint, enforceToolsetAttestation, entryUsageSlices, escalateTool, evaluatePermission, evaluateReuse, evidenceGradeValidator, evidencePreservedValidator, executeWorkflow, executionFactsOf, executionScopeKey, exhaustionCodeOf, extractCandidate, failoverTriggerOf, fallbackTriggerOf, filterClaimsForRun, finalizeFires, findContradictions, finishContract, foldLedger, foldTermination, formatAcceptanceTailTerms, formatCharacterValidator, formatRePrompt, formatScopePath, hasFencedWrites, hasMetaLookup, hashRunArgs, hashRunOutput, hashWorkflowBody, hashWorkflowSource, headingStructureValidator, identityJcs, implementationAgentProfile, insertRunIdIntoSentence, invoiceFromJournal, isClaimJudgeLabel, isEscalated, isSchemaPairSpec, isStandardSchemaSpec, isStrictCompatibleSchema, journalPricingSnapshot, kMaxOf, knowledgeHash, ladderLengthOf, ladderRungChoice, lastMechanicalRepairCostUsd, lastRunSettle, latestProgressReport, lexShellCommand, liftRetainedParts, lineageWeightOf, localKeyProvider, logicalRunTelemetry, makeOrchestratorWorkflow, manifestValidators, maskSecrets, maskSecretsDeep, maskSecretsJson, matchArgvPattern, matchShellCommand, mcp, memoryQuotaLimiter, mergeQuotaDenial, mergeUsageLimits, metaMatchesFilter, minMatchesValidator, modelEpochOf, modelKnowledgeCard, modelSpecIdentity, needsSeparateExtract, nextFailover, nodeLinkKey, normalizeApproachTag, normalizeEntry, normalizeExecutionScope, normalizeFallbacks, openWireIntentsOf, orchestrate, orchestratorAdmissionEstCostUsd, pairDraftClaims, pairRunFactClaims, parallelScope, parseCitationVerdicts, parseModelRef, parseScopePath, parseTerminalEnvelope, persistedTerminalEnvelope, phiInitialOf, pilotAgentProfile, pipelineScope, planNodeScope, preflightEstimate, priceComponentsOf, priceEntryBilling, priceEntryUsage, priceUsdOf, profileCard, profileRegistrySnapshotHash, progressReportTool, projectHistory, projectIdentity, projectToJsonSchema, proposalStatement, providerOf, quotaActualRequestsDelta, quotaActualTokens, quotaEstimateTokens, quotaRuleAdmission, quotaRuleKey, quotaRuleMatches, readRunMeta, readTerminationInit, reconcileRunMeta, reconcileStatement, reduceAuditTrail, reduceCriticalPath, reduceDecisionChain, reduceInvocationTable, registryKeyRing, remeasureQueue, renderContractRequirements, repairLedgerFromJournal, replayDisposition, repositoryResearchToolset, requiredFieldsValidator, requiredMentionsValidator, requiredSectionsValidator, researchAgentProfile, resolveCitationAuditPlan, resolveModelInvocation, resolvePricing, resolveToolset, retentionKeyOf, retryClassOf, retryDelayMs, retryWireMultiplier, reviewAgentProfile, roleConfiguredInRouting, roundOneDisposition, runAgent, runProfile, sampleCitationRows, sanitizeTerminalText, sanitizeTokenCount, sanitizeUsage, sanitizeUsageDelta, scanJournalCompatibility, schemaHash, schemaHashOfSpec, scopeBucket, sectionCitationsValidator, sectionPatternCountValidator, sectionalRoundPlan, selectStructuredOutputTier, selfTestFinishValidation, shouldCompact, snapshotQuotaRules, snapshotUsage, spawnDepthOf, spliceSections, statementFromRows, statementRowsFromDelimited, stripFencedBlocks, sumUsage, summarizeInstruction, summarizeOutput, synthesisCandidatesFromJournal, terminalEnvelopeOf, terminationConfigDrift, tierWithinCaps, toApprovalDecision, toJournalValue, tool, toolAuthority, toolCalibrationFromJournal, toolContract, toolContractHash, toolsetAuthorityHash, toolsetHash, ttlState, unionOfIntervalsMs, usageViolations, validateDetachedResolution, validateEditorialCommit, validateEngineQuotaConfig, validateEntryShape, validateEscalationLimits, validateEscalationReport, validateQuotaRules, validateRetryPolicy, validateSchemaSpec, validateTerminationLimits, validateToolsetAttestation, validateUsageLimits, wireCapacityEstimate, wordCountValidator, workflowScope, workflowSourceRef, wrapJournalStore, wrapTranscriptStore };
|