@agenticprimitives/orchestration 0.0.0-alpha.29 → 0.0.0-alpha.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +5 -0
- package/dist/approval.d.ts +20 -0
- package/dist/approval.d.ts.map +1 -0
- package/dist/approval.js +79 -0
- package/dist/approval.js.map +1 -0
- package/dist/authority.d.ts +137 -2
- package/dist/authority.d.ts.map +1 -1
- package/dist/derivation.d.ts +1 -1
- package/dist/derivation.d.ts.map +1 -1
- package/dist/derivation.js +14 -4
- package/dist/derivation.js.map +1 -1
- package/dist/index.d.ts +9 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +8 -2
- package/dist/index.js.map +1 -1
- package/dist/input.d.ts +52 -0
- package/dist/input.d.ts.map +1 -1
- package/dist/input.js +15 -0
- package/dist/input.js.map +1 -1
- package/dist/loop.d.ts +18 -1
- package/dist/loop.d.ts.map +1 -1
- package/dist/loop.js +554 -125
- package/dist/loop.js.map +1 -1
- package/dist/plan-digest.d.ts +10 -0
- package/dist/plan-digest.d.ts.map +1 -1
- package/dist/plan-digest.js +18 -0
- package/dist/plan-digest.js.map +1 -1
- package/dist/planner.d.ts.map +1 -1
- package/dist/planner.js +2 -1
- package/dist/planner.js.map +1 -1
- package/dist/provenance.d.ts +37 -0
- package/dist/provenance.d.ts.map +1 -0
- package/dist/provenance.js +127 -0
- package/dist/provenance.js.map +1 -0
- package/dist/reconcile.d.ts +10 -3
- package/dist/reconcile.d.ts.map +1 -1
- package/dist/reconcile.js +3 -3
- package/dist/reconcile.js.map +1 -1
- package/dist/step-lifecycle.d.ts +303 -0
- package/dist/step-lifecycle.d.ts.map +1 -0
- package/dist/step-lifecycle.js +304 -0
- package/dist/step-lifecycle.js.map +1 -0
- package/dist/types.d.ts +72 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -1
- package/package.json +2 -2
package/dist/loop.js
CHANGED
|
@@ -17,6 +17,9 @@
|
|
|
17
17
|
import { canonicalJson, compactObservations } from './artifacts.js';
|
|
18
18
|
import { VALUE_DIGEST_SCHEME, isValueDigest, sameValue, valueDigest } from './digest.js';
|
|
19
19
|
import { planDigest } from './plan-digest.js';
|
|
20
|
+
import { judgeApprovals } from './approval.js';
|
|
21
|
+
import { carriesThirdParty, intentForPlanner, isUntrustedContent, principalWordsOf } from './provenance.js';
|
|
22
|
+
import { MINIMUM_AUTHORITY } from '@agenticprimitives/tool-policy';
|
|
20
23
|
import { CONTINUE_STEP_ID, OrchestrationError, isEvaluationIntent } from './types.js';
|
|
21
24
|
import { frameUntrusted } from './planner.js';
|
|
22
25
|
import { statedOutcomeOf } from './conformance.js';
|
|
@@ -24,8 +27,9 @@ import { statedOutcomeOf } from './conformance.js';
|
|
|
24
27
|
* read the plan as the planner WORDED it and are not re-run against resolved values). */
|
|
25
28
|
const POINT_OF_USE_CODES = new Set(['OUTCOME_NOT_ENTAILED', 'OUTCOME_BOUND_EXCEEDED', 'OUTCOME_BOUND_UNREAD', 'OUTCOME_BOUND_PENDING', 'OUTCOME_DISCLOSURE']);
|
|
26
29
|
import { isToolInvocationResult } from './tool-invoker.js';
|
|
27
|
-
import { inputsFor, isInputRequired, receiptPending } from './input.js';
|
|
30
|
+
import { inputsFor, isInputRequired, isNotPerformed, receiptPending } from './input.js';
|
|
28
31
|
import { deriveArgs } from './derivation.js';
|
|
32
|
+
import { attemptTransition, answerBinding } from './step-lifecycle.js';
|
|
29
33
|
/** Read a dot/index path (e.g. `list.record_types.0.record_type`) out of the ref store. A bare name with no
|
|
30
34
|
* dots is a plain top-level lookup. A missing segment short-circuits to `undefined` (the tool then validates
|
|
31
35
|
* its own args — fail-closed, no path traversal / eval). */
|
|
@@ -89,7 +93,8 @@ function assertKnownTools(plan, toolIds) {
|
|
|
89
93
|
}
|
|
90
94
|
async function callPlanner(planner, input) {
|
|
91
95
|
try {
|
|
92
|
-
|
|
96
|
+
// Spec 448 rule 5 — the planner sees text the principal did not write framed as data, never as instruction.
|
|
97
|
+
return await planner.plan({ ...input, intent: intentForPlanner(input.intent) });
|
|
93
98
|
}
|
|
94
99
|
catch (e) {
|
|
95
100
|
if (e instanceof OrchestrationError)
|
|
@@ -106,6 +111,7 @@ function resolveStep(runRef, index, step, tool, args) {
|
|
|
106
111
|
const resourceRaw = cap?.resourceArg ? args[cap.resourceArg] : undefined;
|
|
107
112
|
const authorityRaw = cap?.authorityArg ? args[cap.authorityArg] : undefined;
|
|
108
113
|
const needsKey = risk === 'medium' || risk === 'high' || risk === 'critical';
|
|
114
|
+
const declaredKey = typeof step.idempotencyKey === 'string' && step.idempotencyKey !== '' ? step.idempotencyKey : undefined;
|
|
109
115
|
return {
|
|
110
116
|
runRef, stepRef, index, step, tool, args,
|
|
111
117
|
capability: cap
|
|
@@ -116,9 +122,27 @@ function resolveStep(runRef, index, step, tool, args) {
|
|
|
116
122
|
}
|
|
117
123
|
: { id: '', action: '' },
|
|
118
124
|
risk,
|
|
119
|
-
|
|
125
|
+
// Audit H-4 fix-up 2 — only a non-empty string is a declared key: "" is omitted from the signed plan (`planStepAsWritten`)
|
|
126
|
+
// and from the use ledger's step identity, so it is no key here either, never an empty `operationId`.
|
|
127
|
+
...(needsKey || declaredKey ? { idempotencyKey: declaredKey ?? `${runRef}:${stepRef}` } : {}),
|
|
120
128
|
};
|
|
121
129
|
}
|
|
130
|
+
/** Spec 448 rule 4 — why an attempt that began and recorded nothing cannot be resolved without the principal, in words. */
|
|
131
|
+
function uncertainWhy(why, reader) {
|
|
132
|
+
switch (why) {
|
|
133
|
+
case 'ledger-done-no-result': return 'the use ledger records its effect as done, and this run holds no result for it';
|
|
134
|
+
case 'no-reader': return 'no reader of its effect is bound';
|
|
135
|
+
case 'reader-unknown': return `the reader of its effect could not answer${reader?.status === 'indeterminate' ? `: ${reader.reason}` : ''}`;
|
|
136
|
+
case 'stale-read': return 'the reader was not asked about the attempt that holds the step';
|
|
137
|
+
case 'not-idempotent': return 'the reader found nothing, but the tool does not declare that it dedups a repeat by operation id, and the attempt may still be running';
|
|
138
|
+
case 'already-retried': return 'the one re-invocation an idempotent tool is allowed was already made';
|
|
139
|
+
case 'other-operation-id': return 'the reader found nothing, but the attempt that holds the step gave the downstream another operation id (or the ledger does not say which), so a repeat would not be deduplicated';
|
|
140
|
+
case 'lost-handover': return 'another attempt took the step first';
|
|
141
|
+
case 'retry-not-performed': return 'the re-invocation did not run, and the earlier attempt may have acted';
|
|
142
|
+
case 'ledger-unanswered': return 'the use ledger did not answer when this attempt asked to begin; it may hold the step for an attempt that performed nothing';
|
|
143
|
+
case 'release-failed': return 'the tool did not run, but the use ledger could not be told and still holds the step for that attempt';
|
|
144
|
+
}
|
|
145
|
+
}
|
|
122
146
|
/** Spec 413 — the stepRef of the declared pre-plan retrieval step. */
|
|
123
147
|
export const RETRIEVAL_STEP_REF = 'retrieve';
|
|
124
148
|
const randomRef = () => `run-${Math.random().toString(36).slice(2, 10)}${Date.now().toString(36)}`;
|
|
@@ -252,6 +276,8 @@ export async function runIntent(intent, opts) {
|
|
|
252
276
|
// Spec 421 W1 — the tools the PLANNER is offered: the agent's, plus the reserved continuation step when it is on.
|
|
253
277
|
const plannerTools = opts.continuation && opts.continuation.max > 0 ? [...opts.tools, CONTINUE_TOOL] : opts.tools;
|
|
254
278
|
const toolsById = new Map(plannerTools.map((t) => [t.id, t]));
|
|
279
|
+
/** Audit T4-3 — a tool whose results are the principal's own (`ToolSpec.firstPartyResult`): only its labels mark the run. */
|
|
280
|
+
const firstPartyTool = (toolId) => toolsById.get(toolId)?.firstPartyResult === true;
|
|
255
281
|
const toolIds = new Set(toolsById.keys());
|
|
256
282
|
/** The tools the AGENT exposes (never the reserved continuation step) — what a compensation may name (RUN-7). */
|
|
257
283
|
const exposedById = new Map(opts.tools.map((t) => [t.id, t]));
|
|
@@ -259,6 +285,9 @@ export async function runIntent(intent, opts) {
|
|
|
259
285
|
const receipts = [];
|
|
260
286
|
/** Executed steps whose tool declares a compensation, newest first — unwound on failure. */
|
|
261
287
|
const compensable = [];
|
|
288
|
+
/** Obligations whose tool no longer declares the compensation the step ran under (a deploy between two turns): they
|
|
289
|
+
* never block the forward path; if the run is unwound they are OWED (`declaration-changed`), not run. */
|
|
290
|
+
const lapsed = [];
|
|
262
291
|
const refs = {};
|
|
263
292
|
let executed = 0;
|
|
264
293
|
let replans = 0;
|
|
@@ -300,7 +329,7 @@ export async function runIntent(intent, opts) {
|
|
|
300
329
|
return {};
|
|
301
330
|
} })()),
|
|
302
331
|
// Spec 421 W2 — whose words each argument of an ACT came from (raw planner values against her goal and what was read).
|
|
303
|
-
...(rs.risk !== 'informational' ? (() => { const d = deriveArgs(rawArgsOf(rs), intent
|
|
332
|
+
...(rs.risk !== 'informational' ? (() => { const d = deriveArgs(rawArgsOf(rs), principalWordsOf(intent), allObservations, firstPartyTool); return Object.keys(d).length ? { derivation: d } : {}; })() : {}),
|
|
304
333
|
// Spec 367 §5 — the binding the step was admitted under, pinned by the harness that knows the
|
|
305
334
|
// intent, the principal and where each argument came from. Recorded on every receipt of the step.
|
|
306
335
|
...(() => { const b = opts.bindingFor?.(rs); return b ? { binding: b } : {}; })(),
|
|
@@ -315,6 +344,71 @@ export async function runIntent(intent, opts) {
|
|
|
315
344
|
: opts.selectPresentation
|
|
316
345
|
? opts.selectPresentation(rs, presentedAll)
|
|
317
346
|
: presentedAll[0];
|
|
347
|
+
/**
|
|
348
|
+
* THE OBLIGATION LADDER for one step (spec 448 rule 6 + §0): the decision's obligations, plus what policy adds, never
|
|
349
|
+
* fewer than the risk class's floor; each discharged only by approval records the ApprovalVerifier confirms from
|
|
350
|
+
* distinct approvers who hold a verified role. The mandated path and the self-authorized path both climb it: a session
|
|
351
|
+
* is the authority for WHO acts, never a discharge of an obligation (the principal's voice is not a signature).
|
|
352
|
+
*/
|
|
353
|
+
async function ladder(rs, startedAt, plan, req, decision, presentedRef) {
|
|
354
|
+
// Obligations: the verifier's, plus whatever policy adds for this risk class. Never fewer.
|
|
355
|
+
let obligations = [...decision.obligations];
|
|
356
|
+
if (ports.policyEvaluator) {
|
|
357
|
+
const extra = await ports.policyEvaluator.evaluate({ ...req, decision });
|
|
358
|
+
obligations = [...obligations, ...extra.obligations];
|
|
359
|
+
// Spec 448 rule 6 (audit H-9 fix-up) — a policy ADDS to the floor, never removes it: a policy that returns no
|
|
360
|
+
// obligation of a kind this risk class requires has not been bound to the ladder, and the step does not run.
|
|
361
|
+
const missing = MINIMUM_AUTHORITY[rs.risk].obligations.filter((kind) => !obligations.some((o) => o.kind === kind));
|
|
362
|
+
if (missing.length)
|
|
363
|
+
throw new OrchestrationError('no_policy_port', `step ${rs.stepRef} is ${rs.risk} risk, which requires ${missing.join(' + ')}, and the PolicyEvaluator returned no such obligation`);
|
|
364
|
+
}
|
|
365
|
+
else if (MINIMUM_AUTHORITY[rs.risk].obligations.length > 0) {
|
|
366
|
+
// Spec 448 rule 6 (audit T3-4) — a step whose risk class carries obligations does not run on the mandate alone
|
|
367
|
+
// because nobody bound the ladder: the missing port fails closed, as a missing verifier or approval port does.
|
|
368
|
+
throw new OrchestrationError('no_policy_port', `step ${rs.stepRef} is ${rs.risk} risk, which requires ${MINIMUM_AUTHORITY[rs.risk].obligations.join(' + ')}, and no PolicyEvaluator is configured`);
|
|
369
|
+
}
|
|
370
|
+
let approvalRecords = [];
|
|
371
|
+
let approvedBy = [];
|
|
372
|
+
if (obligations.length > 0) {
|
|
373
|
+
if (!ports.approvalPort)
|
|
374
|
+
throw new OrchestrationError('no_approval_port', `step ${rs.stepRef} carries ${obligations.length} obligation(s) and no ApprovalPort is configured`);
|
|
375
|
+
if (!ports.approvalVerifier)
|
|
376
|
+
throw new OrchestrationError('no_approval_verifier', `step ${rs.stepRef} carries ${obligations.length} obligation(s) and no ApprovalVerifier is configured — an approval nobody evaluates is not an approval`);
|
|
377
|
+
emit({ type: 'ApprovalRequested', runRef, stepRef: rs.stepRef, obligations });
|
|
378
|
+
const outcome = await ports.approvalPort.request({ runRef, stepRef: rs.stepRef, intent, step: rs, obligations, evidence: decision.evidence, planDigest: currentPlanDigest });
|
|
379
|
+
if (outcome.status === 'pending') {
|
|
380
|
+
emit({ type: 'RunSuspended', runRef, stepRef: rs.stepRef, resumeToken: outcome.resumeToken });
|
|
381
|
+
const prompt = outcome.prompt ? { ...outcome.prompt, stepRef: rs.stepRef, toolId: rs.tool.id } : undefined;
|
|
382
|
+
await record({
|
|
383
|
+
...(await base(rs, startedAt)), status: 'suspended',
|
|
384
|
+
authority: { presentedRef, decision, afterApproval: false },
|
|
385
|
+
...(prompt ? { pendingInput: receiptPending(prompt) } : {}),
|
|
386
|
+
completedAt: now(),
|
|
387
|
+
});
|
|
388
|
+
return { outcome: 'suspended', plan, ...parked(), steps: allObservations, receipts, runRef, resumeToken: outcome.resumeToken, ...(prompt ? { prompt } : {}) };
|
|
389
|
+
}
|
|
390
|
+
if (outcome.status === 'refused') {
|
|
391
|
+
emit({ type: 'ApprovalRefused', runRef, stepRef: rs.stepRef, ...(outcome.reason ? { reason: outcome.reason } : {}) });
|
|
392
|
+
const error = `approval refused${outcome.by ? ` by ${outcome.by}` : ''}${outcome.reason ? `: ${outcome.reason}` : ''}`;
|
|
393
|
+
await record({ ...(await base(rs, startedAt)), status: 'denied', authority: { presentedRef, decision, afterApproval: false }, completedAt: now(), error });
|
|
394
|
+
return { outcome: 'denied', plan, steps: allObservations, receipts, runRef, error };
|
|
395
|
+
}
|
|
396
|
+
// Spec 448 rule 6 (audit H-9) — THE RECORDS ARE JUDGED, NOT BELIEVED. Each is verified against this run, step,
|
|
397
|
+
// arguments, plan and obligation; each obligation needs its threshold of distinct, declared, role-holding
|
|
398
|
+
// approvers. An empty list, or records that do not verify, refuse the step.
|
|
399
|
+
const judged = await judgeApprovals({ obligations, records: outcome.records, step: rs, planDigest: currentPlanDigest, evidence: decision.evidence, verifier: ports.approvalVerifier });
|
|
400
|
+
if (!judged.ok) {
|
|
401
|
+
const error = `approval_not_satisfied: ${judged.reason}`;
|
|
402
|
+
emit({ type: 'ApprovalRefused', runRef, stepRef: rs.stepRef, reason: judged.reason });
|
|
403
|
+
await record({ ...(await base(rs, startedAt)), status: 'denied', authority: { presentedRef, decision, afterApproval: false }, completedAt: now(), error });
|
|
404
|
+
return { outcome: 'denied', plan, steps: allObservations, receipts, runRef, error };
|
|
405
|
+
}
|
|
406
|
+
approvedBy = judged.approved;
|
|
407
|
+
approvalRecords = approvedBy.map((a) => a.ref);
|
|
408
|
+
emit({ type: 'ApprovalDischarged', runRef, stepRef: rs.stepRef, records: approvalRecords });
|
|
409
|
+
}
|
|
410
|
+
return { obligations, approvalRecords, approvedBy };
|
|
411
|
+
}
|
|
318
412
|
/** The authority path for one step. Returns the decision to execute under, or a terminal RunResult. */
|
|
319
413
|
async function authorize(rs, startedAt, plan) {
|
|
320
414
|
if (!ports.mandateVerifier)
|
|
@@ -332,8 +426,8 @@ export async function runIntent(intent, opts) {
|
|
|
332
426
|
emit({ type: 'RunSuspended', runRef, stepRef: rs.stepRef, resumeToken: rs.stepRef });
|
|
333
427
|
await record({ ...(await base(rs, startedAt)), status: 'authority-required', completedAt: now() });
|
|
334
428
|
return {
|
|
335
|
-
outcome: 'authority-required', plan, steps: allObservations, receipts, runRef,
|
|
336
|
-
required: { stepRef: rs.stepRef, toolId: rs.tool.id, capability: rs.capability, risk: rs.risk, args: rs.args, ...(() => { const d = deriveArgs(rawArgsOf(rs), intent
|
|
429
|
+
outcome: 'authority-required', plan, ...parked(), steps: allObservations, receipts, runRef,
|
|
430
|
+
required: { stepRef: rs.stepRef, toolId: rs.tool.id, capability: rs.capability, risk: rs.risk, args: rs.args, ...(() => { const d = deriveArgs(rawArgsOf(rs), principalWordsOf(intent), allObservations, firstPartyTool); return Object.keys(d).length ? { derivation: d } : {}; })(), ...(rs.tool.carries ? { carries: rs.tool.carries } : {}) },
|
|
337
431
|
};
|
|
338
432
|
}
|
|
339
433
|
const req = { intent, presented, step: rs, afterApproval: false, planDigest: currentPlanDigest };
|
|
@@ -344,54 +438,180 @@ export async function runIntent(intent, opts) {
|
|
|
344
438
|
await record({ ...(await base(rs, startedAt)), status: 'denied', authority: { presentedRef: presented.ref, decision, afterApproval: false }, completedAt: now(), error: decision.reasons.map((r) => `${r.code}: ${r.message}`).join('; ') });
|
|
345
439
|
return { outcome: 'denied', plan, steps: allObservations, receipts, runRef, error: decision.reasons.map((r) => `${r.code}: ${r.message}`).join('; ') };
|
|
346
440
|
}
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
obligations = [...obligations, ...extra.obligations];
|
|
352
|
-
}
|
|
353
|
-
let approvalRecords = [];
|
|
441
|
+
const laddered = await ladder(rs, startedAt, plan, req, decision, presented.ref);
|
|
442
|
+
if ('outcome' in laddered)
|
|
443
|
+
return laddered;
|
|
444
|
+
const { obligations, approvalRecords, approvedBy } = laddered;
|
|
354
445
|
if (obligations.length > 0) {
|
|
355
|
-
if (!ports.approvalPort)
|
|
356
|
-
throw new OrchestrationError('no_approval_port', `step ${rs.stepRef} carries ${obligations.length} obligation(s) and no ApprovalPort is configured`);
|
|
357
|
-
emit({ type: 'ApprovalRequested', runRef, stepRef: rs.stepRef, obligations });
|
|
358
|
-
const outcome = await ports.approvalPort.request({ runRef, stepRef: rs.stepRef, intent, step: rs, obligations, evidence: decision.evidence });
|
|
359
|
-
if (outcome.status === 'pending') {
|
|
360
|
-
emit({ type: 'RunSuspended', runRef, stepRef: rs.stepRef, resumeToken: outcome.resumeToken });
|
|
361
|
-
const prompt = outcome.prompt ? { ...outcome.prompt, stepRef: rs.stepRef, toolId: rs.tool.id } : undefined;
|
|
362
|
-
await record({
|
|
363
|
-
...(await base(rs, startedAt)), status: 'suspended',
|
|
364
|
-
authority: { presentedRef: presented.ref, decision, afterApproval: false },
|
|
365
|
-
...(prompt ? { pendingInput: receiptPending(prompt) } : {}),
|
|
366
|
-
completedAt: now(),
|
|
367
|
-
});
|
|
368
|
-
return { outcome: 'suspended', plan, steps: allObservations, receipts, runRef, resumeToken: outcome.resumeToken, ...(prompt ? { prompt } : {}) };
|
|
369
|
-
}
|
|
370
|
-
if (outcome.status === 'refused') {
|
|
371
|
-
emit({ type: 'ApprovalRefused', runRef, stepRef: rs.stepRef, ...(outcome.reason ? { reason: outcome.reason } : {}) });
|
|
372
|
-
const error = `approval refused${outcome.by ? ` by ${outcome.by}` : ''}${outcome.reason ? `: ${outcome.reason}` : ''}`;
|
|
373
|
-
await record({ ...(await base(rs, startedAt)), status: 'denied', authority: { presentedRef: presented.ref, decision, afterApproval: false }, completedAt: now(), error });
|
|
374
|
-
return { outcome: 'denied', plan, steps: allObservations, receipts, runRef, error };
|
|
375
|
-
}
|
|
376
|
-
approvalRecords = outcome.records;
|
|
377
|
-
emit({ type: 'ApprovalDischarged', runRef, stepRef: rs.stepRef, records: approvalRecords });
|
|
378
446
|
// RE-VERIFY. An approval is an input to the verifier, not a bypass of it: the mandate may have been
|
|
379
|
-
// revoked while the approver was deciding.
|
|
380
|
-
decision = await ports.mandateVerifier.verify({ ...req, afterApproval: true });
|
|
447
|
+
// revoked while the approver was deciding. The verifier is told WHO approved.
|
|
448
|
+
decision = await ports.mandateVerifier.verify({ ...req, afterApproval: true, approvals: approvedBy });
|
|
381
449
|
emit({ type: 'MandateChecked', runRef, stepRef: rs.stepRef, decision: decision.decision, afterApproval: true });
|
|
382
450
|
if (decision.decision !== 'allow') {
|
|
383
451
|
const reasons = decision.decision === 'deny' ? decision.reasons : [{ code: 'still-obligated', message: 'obligations remain after approval' }];
|
|
384
452
|
emit({ type: 'MandateDenied', runRef, stepRef: rs.stepRef, reasons });
|
|
385
453
|
const error = reasons.map((r) => `${r.code}: ${r.message}`).join('; ');
|
|
386
|
-
await record({ ...(await base(rs, startedAt)), status: 'denied', authority: { presentedRef: presented.ref, decision, afterApproval: true }, approvalRecords, completedAt: now(), error });
|
|
454
|
+
await record({ ...(await base(rs, startedAt)), status: 'denied', authority: { presentedRef: presented.ref, decision, afterApproval: true }, approvalRecords, approvedBy, completedAt: now(), error });
|
|
387
455
|
return { outcome: 'denied', plan, steps: allObservations, receipts, runRef, error };
|
|
388
456
|
}
|
|
389
457
|
}
|
|
390
|
-
return { decision, approvalRecords, used: presented };
|
|
458
|
+
return { decision, approvalRecords, approvedBy, used: presented };
|
|
459
|
+
}
|
|
460
|
+
async function perform(p) {
|
|
461
|
+
const verifier = ports.mandateVerifier;
|
|
462
|
+
const mine = p.counted && verifier?.begin ? { ...p.counted, attempt: crypto.randomUUID() } : undefined;
|
|
463
|
+
const ctx = { attempt: mine?.attempt ?? '', retryAttempt: crypto.randomUUID(), operationId: p.operationId, idempotentByKey: p.tool.adapter?.retry === 'idempotent-by-key', counted: !!mine };
|
|
464
|
+
// A reader exists only where one is bound: no port (or an informational step) is `unbound`, never `absent`.
|
|
465
|
+
// A reader that asks the person a question raises it (caught below); one that fails any other way could not be asked.
|
|
466
|
+
const read = async () => {
|
|
467
|
+
if (!ports.reconcile || p.rs.risk === 'informational')
|
|
468
|
+
return { status: 'unbound' };
|
|
469
|
+
try {
|
|
470
|
+
return await ports.reconcile.reconcile({ operationId: p.operationId, runRef, stepRef: p.rs.stepRef, step: p.step, tool: p.tool, args: p.args, ...(p.binding ? { binding: p.binding } : {}) });
|
|
471
|
+
}
|
|
472
|
+
catch (e) {
|
|
473
|
+
if (isInputRequired(e))
|
|
474
|
+
throw e;
|
|
475
|
+
return { status: 'indeterminate', reason: e instanceof Error ? e.message : String(e) };
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
const said = (a) => (a.status === 'found' ? 'present' : a.status === 'absent' ? 'absent' : a.status === 'unbound' ? 'no-reader' : 'unknown');
|
|
479
|
+
/** A STORAGE CALL AND ITS ACKNOWLEDGEMENT. The same call is repeated once (the ledger's operations are idempotent for
|
|
480
|
+
* the attempt that makes them); a second failure is delivered to the machine as what it is — no answer. */
|
|
481
|
+
const twice = async (call) => {
|
|
482
|
+
for (let i = 0; i < 2; i++) {
|
|
483
|
+
try {
|
|
484
|
+
return { ok: true, value: await call() };
|
|
485
|
+
}
|
|
486
|
+
catch { /* asked again, then reported */ }
|
|
487
|
+
}
|
|
488
|
+
return { ok: false };
|
|
489
|
+
};
|
|
490
|
+
const asked = async (to, call) => {
|
|
491
|
+
const r = await twice(call);
|
|
492
|
+
return r.ok ? { type: 'slot-answered', to, answer: r.value } : { type: 'slot-unanswered', to };
|
|
493
|
+
};
|
|
494
|
+
let state = { phase: 'idle' };
|
|
495
|
+
let found;
|
|
496
|
+
let outcome;
|
|
497
|
+
let thrown;
|
|
498
|
+
let raw;
|
|
499
|
+
let usedOperationId = p.operationId;
|
|
500
|
+
/** What the last evidence was gathered about — the prompt a park raises is bound to it. */
|
|
501
|
+
let about;
|
|
502
|
+
// THE PRE-ACT READ (spec 410 §3): did this operation already happen? `found` ⇒ recorded, nothing is invoked.
|
|
503
|
+
try {
|
|
504
|
+
return await drive(await read());
|
|
505
|
+
}
|
|
506
|
+
catch (e) {
|
|
507
|
+
// A READER asked the person something. Nothing this attempt began is released by it: a slot another attempt holds
|
|
508
|
+
// is not this one's, and one this attempt holds after a throw may cover an effect.
|
|
509
|
+
if (isInputRequired(e))
|
|
510
|
+
return { kind: 'question', request: e.request };
|
|
511
|
+
throw e;
|
|
512
|
+
}
|
|
513
|
+
async function drive(pre) {
|
|
514
|
+
const queue = [];
|
|
515
|
+
if (pre.status === 'found') {
|
|
516
|
+
found = pre;
|
|
517
|
+
queue.push({ type: 'evidence', reader: 'present', uncertainty: '' });
|
|
518
|
+
}
|
|
519
|
+
else if (!mine)
|
|
520
|
+
queue.push({ type: 'slot-answered', to: 'begin', answer: { status: 'begun' } });
|
|
521
|
+
else
|
|
522
|
+
queue.push(await asked('begin', () => verifier.begin({ ...mine, operationId: p.operationId })));
|
|
523
|
+
while (queue.length) {
|
|
524
|
+
const t = attemptTransition(state, queue.shift(), ctx);
|
|
525
|
+
state = t.state;
|
|
526
|
+
for (const fx of t.effects) {
|
|
527
|
+
switch (fx.do) {
|
|
528
|
+
case 'invoke': {
|
|
529
|
+
// The store that would know whether a FIRST attempt's operation already happened could not be asked: no act
|
|
530
|
+
// this attempt (spec 410 §3) — the attempt performed nothing, and says so.
|
|
531
|
+
if (pre.status === 'indeterminate' && state.phase === 'acting' && !state.retry) {
|
|
532
|
+
thrown = new OrchestrationError('reconcile_indeterminate', `the store that would know whether this operation already happened could not be asked (${pre.reason}); nothing was done this attempt`);
|
|
533
|
+
queue.push({ type: 'not-performed', retry: false, question: false });
|
|
534
|
+
break;
|
|
535
|
+
}
|
|
536
|
+
usedOperationId = fx.operationId;
|
|
537
|
+
const retry = state.phase === 'acting' && state.retry;
|
|
538
|
+
try {
|
|
539
|
+
raw = await p.invoke(fx.operationId);
|
|
540
|
+
queue.push({ type: 'returned', retry });
|
|
541
|
+
}
|
|
542
|
+
catch (e) {
|
|
543
|
+
thrown = e;
|
|
544
|
+
queue.push(isInputRequired(e) ? { type: 'not-performed', retry, question: true } : isNotPerformed(e) ? { type: 'not-performed', retry, question: false } : { type: 'threw', retry });
|
|
545
|
+
}
|
|
546
|
+
break;
|
|
547
|
+
}
|
|
548
|
+
// The effect exists whether or not the ledger could be told: a `complete` that fails is delivered as such — the
|
|
549
|
+
// step is still recorded (never turned into a failure), its receipt says the ledger holds it, and any other
|
|
550
|
+
// runner of the step finds it held and parks for the principal.
|
|
551
|
+
case 'complete':
|
|
552
|
+
queue.push({ type: !verifier?.complete || (await twice(() => verifier.complete(mine))).ok ? 'completed' : 'complete-failed' });
|
|
553
|
+
break;
|
|
554
|
+
case 'release':
|
|
555
|
+
queue.push({ type: !verifier?.release || (await twice(() => verifier.release(mine))).ok ? 'released' : 'release-failed' });
|
|
556
|
+
break;
|
|
557
|
+
case 'gather-evidence': {
|
|
558
|
+
const slot = state.slot;
|
|
559
|
+
// Asked NOW — after the slot named the attempt that holds it — so the read is about that attempt.
|
|
560
|
+
const reader = await read();
|
|
561
|
+
if (reader.status === 'found')
|
|
562
|
+
found = reader;
|
|
563
|
+
const uncertainty = await valueDigest({ kind: 'effect-uncertain', runRef, stepRef: p.rs.stepRef, toolId: p.tool.id, operationId: (slot.status === 'held' ? slot.operationId : undefined) ?? p.operationId, ledger: slot.status, attempt: slot.status === 'held' ? slot.attempt : null, retried: slot.status === 'held' ? slot.retried : null });
|
|
564
|
+
about = { slot, uncertainty, reader };
|
|
565
|
+
// The principal's answer to THIS uncertainty (I6): one that names another park of this step is not read.
|
|
566
|
+
const answer = inputsFor(opts.supplied, p.rs.stepRef).filter((s) => s.effect !== undefined && s.answers === uncertainty).pop();
|
|
567
|
+
queue.push({ type: 'evidence', reader: said(reader), ...(fx.about !== undefined ? { readAbout: fx.about } : {}), uncertainty, ...(answer ? { principal: { effect: answer.effect, ...(answer.answers !== undefined ? { answers: answer.answers } : {}) } } : {}) });
|
|
568
|
+
break;
|
|
569
|
+
}
|
|
570
|
+
case 'hand-over':
|
|
571
|
+
queue.push(await asked('hand-over', () => verifier.begin({ ...mine, attempt: fx.as, retryOf: fx.retryOf, operationId: fx.operationId })));
|
|
572
|
+
break;
|
|
573
|
+
case 'record': {
|
|
574
|
+
const unwritten = fx.ledgerUnwritten ? { ledgerUnwritten: true } : {};
|
|
575
|
+
outcome = fx.by === 'tool' ? { kind: 'recorded', by: 'tool', raw, operationId: usedOperationId, ...unwritten }
|
|
576
|
+
: fx.by === 'reader' ? { kind: 'recorded', by: 'reader', found: found, operationId: usedOperationId, ...unwritten }
|
|
577
|
+
: { kind: 'recorded', by: 'principal', operationId: usedOperationId, ...unwritten };
|
|
578
|
+
break;
|
|
579
|
+
}
|
|
580
|
+
case 'park': {
|
|
581
|
+
// The prompt is bound to the slot as the NEXT runner will be told it. Where this attempt itself is (or may
|
|
582
|
+
// be) the holder, that is known here; otherwise it is the slot the evidence was gathered about.
|
|
583
|
+
const own = fx.why === 'ledger-unanswered' || fx.why === 'release-failed' || fx.why === 'retry-not-performed';
|
|
584
|
+
const slot = own
|
|
585
|
+
? { status: 'held', attempt: fx.heldAttempt ?? ctx.attempt, retried: fx.why === 'retry-not-performed', operationId: usedOperationId }
|
|
586
|
+
: about?.slot;
|
|
587
|
+
const heldKey = slot?.status === 'held' ? slot.operationId : undefined;
|
|
588
|
+
const uncertainty = !own && about ? about.uncertainty : await valueDigest({ kind: 'effect-uncertain', runRef, stepRef: p.rs.stepRef, toolId: p.tool.id, operationId: heldKey ?? p.operationId, ledger: fx.ledger, attempt: slot?.status === 'held' ? slot.attempt : null, retried: slot?.status === 'held' ? slot.retried : null });
|
|
589
|
+
const why = uncertainWhy(fx.why, own ? undefined : about?.reader);
|
|
590
|
+
outcome = { kind: 'parked', request: {
|
|
591
|
+
kind: 'effect-uncertain', stepRef: p.rs.stepRef, toolId: p.tool.id, operationId: heldKey ?? p.operationId, ledger: fx.ledger, why, reason: fx.why, uncertainty,
|
|
592
|
+
prompt: `${p.tool.id} began under its mandate and recorded no completion; nothing here shows whether it acted. It will not be performed again on its own. Does its effect exist? Answer with { effect: 'present'${fx.ledger === 'held' ? " | 'absent'" : ''}, answers: '${uncertainty}' }.`,
|
|
593
|
+
} };
|
|
594
|
+
break;
|
|
595
|
+
}
|
|
596
|
+
case 'surface-question':
|
|
597
|
+
outcome = { kind: 'question', request: thrown.request };
|
|
598
|
+
break;
|
|
599
|
+
case 'fail':
|
|
600
|
+
outcome = { kind: 'failed', error: thrown };
|
|
601
|
+
break;
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
// The machine is total and every path above ends in an outcome; a state with none is a defect, reported as uncertain
|
|
606
|
+
// (never as "nothing happened").
|
|
607
|
+
return outcome ?? { kind: 'failed', error: new OrchestrationError('max_steps', `step ${p.rs.stepRef}: the step lifecycle ended in '${state.phase}' with no outcome`) };
|
|
608
|
+
}
|
|
391
609
|
}
|
|
610
|
+
const compensationsOwed = [];
|
|
611
|
+
const withOwed = (r) => (compensationsOwed.length ? { ...r, compensationsOwed: [...compensationsOwed] } : r);
|
|
392
612
|
/**
|
|
393
|
-
* Unwind executed steps that declared compensation, newest first.
|
|
394
|
-
* recorded, not retried — the receipt is the honest record.
|
|
613
|
+
* Unwind executed steps that declared compensation, newest first. A compensation that fails before anything left is
|
|
614
|
+
* recorded as owed, not retried — the receipt is the honest record.
|
|
395
615
|
*
|
|
396
616
|
* RUN-7 (spec 445 W0) — A COMPENSATION IS A STEP. It runs only if it is a tool this run EXPOSES, and, when that tool
|
|
397
617
|
* exercises a capability, only under a verdict: the verifier judged it `allow` against a presented mandate that fits
|
|
@@ -400,11 +620,14 @@ export async function runIntent(intent, opts) {
|
|
|
400
620
|
* the last thing that may run unjudged. Anything else is NOT RUN: it is recorded on its own receipt and returned as
|
|
401
621
|
* `compensationsOwed`, naming the step, so the caller can obtain the authority and perform it — owed, never done
|
|
402
622
|
* unverified, never dropped.
|
|
623
|
+
*
|
|
624
|
+
* Returns the prompt of a compensation that is EFFECT-UNCERTAIN — the unwinding stops there and the
|
|
625
|
+
* run parks on it (I2: an uncertain compensation is answerable, never an owed entry on a finished run) — or null when
|
|
626
|
+
* every compensation is settled: performed, or owed for a reason the caller is told.
|
|
403
627
|
*/
|
|
404
|
-
const compensationsOwed = [];
|
|
405
|
-
const withOwed = (r) => (compensationsOwed.length ? { ...r, compensationsOwed: [...compensationsOwed] } : r);
|
|
406
628
|
async function compensate() {
|
|
407
|
-
|
|
629
|
+
while (compensable.length) {
|
|
630
|
+
const { resolved, result } = compensable[compensable.length - 1];
|
|
408
631
|
const comp = resolved.tool.compensation;
|
|
409
632
|
const compTool = exposedById.get(comp.toolId);
|
|
410
633
|
const startedAt = now();
|
|
@@ -412,16 +635,21 @@ export async function runIntent(intent, opts) {
|
|
|
412
635
|
const crs = compTool
|
|
413
636
|
? resolveStep(runRef, resolved.index, { toolId: comp.toolId, args, id: `${resolved.stepRef}:compensate` }, compTool, args)
|
|
414
637
|
: { ...resolved, stepRef: `${resolved.stepRef}:compensate`, step: { toolId: comp.toolId, args, id: `${resolved.stepRef}:compensate` }, tool: { id: comp.toolId, description: '' }, args, risk: 'informational', capability: { id: '', action: '' } };
|
|
638
|
+
const compDigest = await planDigest({ steps: [crs.step] });
|
|
415
639
|
let authority;
|
|
416
640
|
const notRun = async (reason, status, detail) => {
|
|
417
641
|
compensationsOwed.push({ stepRef: crs.stepRef, forStepRef: resolved.stepRef, toolId: comp.toolId, ...(crs.risk !== 'informational' ? { capability: crs.capability } : {}), risk: crs.risk, args, reason, detail });
|
|
418
642
|
emit({ type: 'StepCompensated', runRef, stepRef: resolved.stepRef, by: comp.toolId, ok: false });
|
|
419
643
|
await record({ ...(await base(crs, startedAt)), status, ...(authority ? { authority } : {}), completedAt: now(), error: `compensation owed (${reason}): ${detail}` });
|
|
644
|
+
compensable.pop();
|
|
420
645
|
};
|
|
421
646
|
if (!compTool) {
|
|
422
647
|
await notRun('tool-not-exposed', 'failed', `${resolved.tool.id} declares ${comp.toolId} as its compensation, which this run does not expose — refused, not run`);
|
|
423
648
|
continue;
|
|
424
649
|
}
|
|
650
|
+
/** A compensation under a verified mandate is performed once, by a named attempt, exactly as a forward step is. */
|
|
651
|
+
let compReq;
|
|
652
|
+
let done;
|
|
425
653
|
try {
|
|
426
654
|
if (crs.risk !== 'informational') {
|
|
427
655
|
const judgedAt = opts.authorityJudgedElsewhere ? opts.authorityJudgedElsewhere(crs) : null;
|
|
@@ -431,9 +659,18 @@ export async function runIntent(intent, opts) {
|
|
|
431
659
|
else if (compTool.selfAuthorized) {
|
|
432
660
|
if (holdSelfActs) {
|
|
433
661
|
await record({ ...(await base(crs, startedAt)), status: 'skipped', completedAt: now(), error: holdReason });
|
|
662
|
+
compensable.pop();
|
|
663
|
+
continue;
|
|
664
|
+
}
|
|
665
|
+
authority = { presentedRef: 'self', decision: { decision: 'allow', obligations: [], evidence: { mandateRef: 'self', intentDigest: await valueDigest(intent), evaluatedAt: now(), verdicts: [{ enforcer: 'self', allowed: true, reason: `the run's own principal owns what this touches; the session is the authority${opts.caller ? ` — the session of ${opts.caller.kind}${opts.caller.ref ? ` ${opts.caller.ref}` : ''}` : ''}` }], ...(opts.caller ? { caller: opts.caller } : {}) } }, afterApproval: false };
|
|
666
|
+
// Audit H-9 fix-up 2 — a session discharges no obligation, and an unwinding run asks for none: a self-acting
|
|
667
|
+
// compensation whose risk class or policy carries one is owed, exactly as a mandated one is.
|
|
668
|
+
const selfReq = { intent, presented: null, step: crs, afterApproval: false, planDigest: compDigest };
|
|
669
|
+
const extra = ports.policyEvaluator ? (await ports.policyEvaluator.evaluate({ ...selfReq, decision: authority.decision })).obligations : [];
|
|
670
|
+
if (extra.length + MINIMUM_AUTHORITY[crs.risk].obligations.length > 0) {
|
|
671
|
+
await notRun('approval-required', 'authority-required', `${comp.toolId} carries obligation(s) that an unwinding run does not discharge — the session is not an approval`);
|
|
434
672
|
continue;
|
|
435
673
|
}
|
|
436
|
-
authority = { presentedRef: 'self', decision: { decision: 'allow', obligations: [], evidence: { mandateRef: 'self', intentDigest: await valueDigest(intent), evaluatedAt: now(), verdicts: [{ enforcer: 'self', allowed: true, reason: 'the run\'s own principal owns what this touches; the session is the authority' }] } }, afterApproval: false };
|
|
437
674
|
}
|
|
438
675
|
else {
|
|
439
676
|
if (!ports.mandateVerifier) {
|
|
@@ -445,7 +682,9 @@ export async function runIntent(intent, opts) {
|
|
|
445
682
|
await notRun('no-mandate', 'authority-required', `${comp.toolId} exercises ${crs.capability.id} and no presented mandate covers it`);
|
|
446
683
|
continue;
|
|
447
684
|
}
|
|
448
|
-
|
|
685
|
+
// Audit H-4 fix-up — a compensation is not a step of the signed plan: its arguments come from a result. It is
|
|
686
|
+
// presented under ITS OWN digest, so a mandate bound to the forward plan never covers it.
|
|
687
|
+
const req = { intent, presented: compPresented, step: crs, afterApproval: false, planDigest: compDigest };
|
|
449
688
|
const d = await ports.mandateVerifier.verify(req);
|
|
450
689
|
emit({ type: 'MandateChecked', runRef, stepRef: crs.stepRef, decision: d.decision, afterApproval: false });
|
|
451
690
|
authority = { presentedRef: compPresented.ref, decision: d, afterApproval: false };
|
|
@@ -453,23 +692,61 @@ export async function runIntent(intent, opts) {
|
|
|
453
692
|
await notRun('not-authorized', 'denied', d.reasons.map((r) => `${r.code}: ${r.message}`).join('; '));
|
|
454
693
|
continue;
|
|
455
694
|
}
|
|
695
|
+
// Audit H-9 fix-up — the risk floor holds here too: a missing policy port is not an empty one, and an unwinding
|
|
696
|
+
// run discharges no obligation, so a compensation whose risk class carries one is owed, never run.
|
|
456
697
|
const extra = ports.policyEvaluator ? (await ports.policyEvaluator.evaluate({ ...req, decision: d })).obligations : [];
|
|
457
|
-
if (d.decision !== 'allow' || d.obligations.length + extra.length > 0) {
|
|
698
|
+
if (d.decision !== 'allow' || d.obligations.length + extra.length + MINIMUM_AUTHORITY[crs.risk].obligations.length > 0) {
|
|
458
699
|
await notRun('approval-required', 'authority-required', `${comp.toolId} carries obligation(s) that an unwinding run does not discharge — it needs its own approval`);
|
|
459
700
|
continue;
|
|
460
701
|
}
|
|
702
|
+
compReq = { ...req, decision: d };
|
|
461
703
|
}
|
|
462
704
|
}
|
|
463
|
-
|
|
705
|
+
const compOperationId = `${crs.idempotencyKey ?? `${runRef}:${crs.stepRef}`}:compensate`;
|
|
706
|
+
// Spec 448 rule 4 — A COMPENSATION IS A STEP: the same lifecycle, the same slot rules, the same park.
|
|
707
|
+
done = await perform({
|
|
708
|
+
rs: crs, tool: compTool, step: crs.step, args, operationId: compOperationId, ...(compReq ? { counted: compReq } : {}),
|
|
709
|
+
invoke: (opId) => opts.invoke(comp.toolId, args, { intent, step: crs.step, index: crs.index, ...(crs.idempotencyKey ? { idempotencyKey: crs.idempotencyKey } : {}), operationId: opId, planDigest: compDigest, untrustedSeen }),
|
|
710
|
+
});
|
|
464
711
|
}
|
|
465
712
|
catch (e) {
|
|
466
713
|
await notRun('failed', 'failed', e instanceof Error ? e.message : String(e));
|
|
467
714
|
continue;
|
|
468
715
|
}
|
|
716
|
+
if (done.kind === 'parked') {
|
|
717
|
+
// Nothing shows whether the compensation acted. The unwinding waits here for the principal (the step stays
|
|
718
|
+
// in the list: the resume asks again, with her answer).
|
|
719
|
+
await record({ ...(await base(crs, startedAt)), status: 'suspended', ...(authority ? { authority } : {}), pendingInput: receiptPending(done.request), completedAt: now(), error: `effect-uncertain: ${done.request.why}` });
|
|
720
|
+
return done.request;
|
|
721
|
+
}
|
|
722
|
+
if (done.kind === 'failed' || done.kind === 'question') {
|
|
723
|
+
await notRun('failed', 'failed', done.kind === 'question' ? `${comp.toolId} asked for input an unwinding run does not have` : done.error instanceof Error ? done.error.message : String(done.error));
|
|
724
|
+
continue;
|
|
725
|
+
}
|
|
469
726
|
emit({ type: 'StepCompensated', runRef, stepRef: resolved.stepRef, by: comp.toolId, ok: true });
|
|
470
|
-
await record({ ...(await base(crs, startedAt)), status: 'compensated', ...(authority ? { authority } : {}), completedAt: now() });
|
|
727
|
+
await record({ ...(await base(crs, startedAt)), status: 'compensated', ...(authority ? { authority } : {}), ...(done.by !== 'tool' ? { reconciled: true } : {}), completedAt: now() });
|
|
728
|
+
compensable.pop();
|
|
729
|
+
}
|
|
730
|
+
return null;
|
|
731
|
+
}
|
|
732
|
+
/** END THE RUN (denied or failed): unwind what ran, and finish — unless a compensation is effect-uncertain, in which
|
|
733
|
+
* case the run parks on it and carries WHY it was ending and what is already owed (`unwinding`), so the resume
|
|
734
|
+
* finishes the unwinding and then the run, whatever number of waits lie between (I3). */
|
|
735
|
+
async function endRun(r) {
|
|
736
|
+
// What ran under a compensation its tool no longer declares is owed, by name — never run under another declaration.
|
|
737
|
+
for (const o of lapsed.splice(0)) {
|
|
738
|
+
const compId = o.compensation?.toolId ?? `${o.toolId}:compensation`;
|
|
739
|
+
const crs = resolveStep(runRef, o.index, { toolId: compId, args: {}, id: `${o.stepRef}:compensate` }, { id: compId, description: '' }, {});
|
|
740
|
+
const detail = `${o.toolId} ran under a compensation it no longer declares${o.compensation ? ` (${o.compensation.toolId})` : ''} — it cannot be discharged automatically`;
|
|
741
|
+
compensationsOwed.push({ stepRef: crs.stepRef, forStepRef: o.stepRef, toolId: compId, risk: crs.risk, args: o.compensation?.args ?? {}, reason: 'declaration-changed', detail });
|
|
742
|
+
emit({ type: 'StepCompensated', runRef, stepRef: o.stepRef, by: compId, ok: false });
|
|
743
|
+
await record({ ...(await base(crs, now())), status: 'failed', completedAt: now(), error: `compensation owed (declaration-changed): ${detail}` });
|
|
471
744
|
}
|
|
472
|
-
|
|
745
|
+
const waiting = await compensate();
|
|
746
|
+
if (!waiting)
|
|
747
|
+
return withOwed(r);
|
|
748
|
+
emit({ type: 'RunSuspended', runRef, stepRef: waiting.stepRef, resumeToken: waiting.stepRef });
|
|
749
|
+
return withOwed({ outcome: 'suspended', plan: r.plan, ...parked(), steps: allObservations, receipts, runRef, resumeToken: waiting.stepRef, prompt: waiting, unwinding: { outcome: r.outcome === 'denied' ? 'denied' : 'failed', error: r.error ?? r.outcome, owed: [...compensationsOwed] } });
|
|
473
750
|
}
|
|
474
751
|
// Spec 438 §2.3 — stamped from an id the caller ALREADY HOLDS. No read, no round-trip, no await is added
|
|
475
752
|
// here: if attaching to work cost a lookup before the first step, every run would pay for a field most
|
|
@@ -480,17 +757,37 @@ export async function runIntent(intent, opts) {
|
|
|
480
757
|
// placeholder drop, a re-plan): what the verifier compares a plan-bound mandate against. A re-planned run
|
|
481
758
|
// is a different plan and a plan-bound mandate refuses it, which is the point.
|
|
482
759
|
let currentPlanDigest = '';
|
|
760
|
+
/** What a parked run hands back (audit H-4 / H-5 fix-up): the digest a remote signer binds a plan-bound mandate to — never
|
|
761
|
+
* one it recomputed from a plan it guessed — and whether the run had read text its principal did not write, which a
|
|
762
|
+
* resume must carry (`resume.untrustedSeen`): the observation that tainted it (a failed step's error) is not replayed. */
|
|
763
|
+
function parked() {
|
|
764
|
+
// I3 — WHAT MUST STILL BE UNWOUND BELONGS TO THE RUN. Every result that is not terminal hands back the steps that ran
|
|
765
|
+
// and declared a compensation, whichever version of the plan they ran under; the resume is seeded from them, so a
|
|
766
|
+
// re-plan, an admission refusal or a new plan between two waits cannot make the run forget one.
|
|
767
|
+
const obligations = [...lapsed, ...compensable.filter((c) => c.receipt).map((c) => ({ stepRef: c.resolved.stepRef, index: c.resolved.index, toolId: c.resolved.tool.id, ...(c.resolved.tool.compensation ? { compensation: c.declared ?? { toolId: c.resolved.tool.compensation.toolId, args: c.resolved.tool.compensation.args } } : {}), ...(c.result !== undefined ? { result: c.result } : {}), receipt: c.receipt }))];
|
|
768
|
+
return { planDigest: currentPlanDigest, ...(untrustedSeen ? { untrustedSeen: true } : {}), ...(obligations.length ? { obligations } : {}) };
|
|
769
|
+
}
|
|
483
770
|
// Spec 445 decision 8 (EVAL-13) — an EVALUATION's intent holds self-acting writes exactly as a comparison's dry run does.
|
|
484
771
|
const holdSelfActs = opts.dryRunSelfActs === true || isEvaluationIntent(intent);
|
|
485
772
|
const holdReason = isEvaluationIntent(intent) ? 'held: an evaluation run does not commit a self-acting write' : 'dry run: a comparison run does not commit a self-acting write';
|
|
486
773
|
// Spec 409 §4 — whether any observation so far carried untrusted content (see `InvokeContext.untrustedSeen`).
|
|
487
|
-
|
|
488
|
-
|
|
774
|
+
// Spec 448 rule 5 (audit H-5 / T4-1) — a run started from text its principal did not write has read untrusted content
|
|
775
|
+
// before its first step: the outbound gate trips on the intent exactly as it does on a tool result.
|
|
776
|
+
let untrustedSeen = carriesThirdParty(intent);
|
|
777
|
+
// Audit T4-3 — one test for untrusted content: text, lists and labels at any depth, judged per the tool's declaration.
|
|
778
|
+
const isUntrusted = (value, toolId) => isUntrustedContent(value, { firstParty: !!toolId && firstPartyTool(toolId) });
|
|
779
|
+
/** The intent as admission judges it: only the principal's own words are "the words" (a marked goal is not hers). */
|
|
780
|
+
const admissionIntent = intent.provenance?.goal ? { ...intent, goal: principalWordsOf(intent) } : intent;
|
|
489
781
|
const completedByRef = new Map((opts.resume?.completed ?? []).map((c) => [c.stepRef, c]));
|
|
490
782
|
// Spec 445 decision 8 — A REPLAYED UNTRUSTED OBSERVATION STILL MARKS THE RUN. The checkpoint carries what this run
|
|
491
783
|
// read before it parked; a resume is the same run, so what it read then counts from the first step now — not only
|
|
492
784
|
// once its replay is reached (and whether or not a host relays it on `ctx.untrustedSeen`).
|
|
493
|
-
if ((opts.resume?.completed ?? []).some((c) => isUntrusted(c.result)))
|
|
785
|
+
if ((opts.resume?.completed ?? []).some((c) => isUntrusted(c.result, c.receipt?.toolId)))
|
|
786
|
+
untrustedSeen = true;
|
|
787
|
+
// Audit H-5 fix-up — and what it read that left no completed step (an error a remote service wrote) is carried by the checkpoint.
|
|
788
|
+
// Audit H-5 fix-up 3 — and a resume that does not SAY it is clean is not: a checkpoint written before the bit existed
|
|
789
|
+
// cannot show that nothing tainted the run. `false` is the only clean answer.
|
|
790
|
+
if (opts.resume && opts.resume.untrustedSeen !== false)
|
|
494
791
|
untrustedSeen = true;
|
|
495
792
|
/** Spec 445 decision 8 — the `ref`s whose results are untrusted, or were threaded from one (transitively). */
|
|
496
793
|
const taintedRefs = new Set();
|
|
@@ -542,7 +839,7 @@ export async function runIntent(intent, opts) {
|
|
|
542
839
|
// stated outcome is judged AGAIN on its concrete arguments at the point of use (`judgeAtPointOfUse`, below) before
|
|
543
840
|
// the verifier, a signature request or the tool sees it.
|
|
544
841
|
const admit = async (candidate) => {
|
|
545
|
-
const v = await ports.planAdmission.admit({ intent, plan: candidate, tools: plannerTools });
|
|
842
|
+
const v = await ports.planAdmission.admit({ intent: admissionIntent, plan: candidate, tools: plannerTools });
|
|
546
843
|
if (v.admitted)
|
|
547
844
|
return v;
|
|
548
845
|
const rest = v.violations.filter((x) => x.recovery !== 'defer');
|
|
@@ -601,6 +898,37 @@ export async function runIntent(intent, opts) {
|
|
|
601
898
|
}
|
|
602
899
|
return { plan: p };
|
|
603
900
|
};
|
|
901
|
+
// ── I3: THE RUN'S COMPENSATION OBLIGATIONS, SEEDED BEFORE ANYTHING ELSE. They come from the checkpoint (`obligations`),
|
|
902
|
+
// not from the plan: the steps of an earlier plan version are in none of this turn's steps. A row written before the
|
|
903
|
+
// field existed is read from its completed steps' receipts (by the tool each receipt names). Each is checked against
|
|
904
|
+
// its receipt — a compensation's arguments come from the result — and one that does not check refuses the resume.
|
|
905
|
+
if (opts.resume) {
|
|
906
|
+
const owedFor = new Set((opts.resume.unwinding?.owed ?? []).map((o) => o.forStepRef));
|
|
907
|
+
const seed = opts.resume.obligations
|
|
908
|
+
?? opts.resume.completed.flatMap((c) => {
|
|
909
|
+
const r = c.receipt;
|
|
910
|
+
const t = r ? exposedById.get(r.toolId) : undefined;
|
|
911
|
+
return r && t?.compensation && t.capability && r.status === 'executed' && !r.reconciled ? [{ stepRef: c.stepRef, index: r.index, toolId: r.toolId, ...(c.result !== undefined ? { result: c.result } : {}), receipt: r }] : [];
|
|
912
|
+
});
|
|
913
|
+
for (const o of seed) {
|
|
914
|
+
if (owedFor.has(o.stepRef))
|
|
915
|
+
continue;
|
|
916
|
+
const t = exposedById.get(o.toolId);
|
|
917
|
+
const r = o.receipt;
|
|
918
|
+
if (!r || r.runRef !== runRef || r.stepRef !== o.stepRef || r.toolId !== o.toolId || r.status !== 'executed' || !isValueDigest(r.outputDigest) || r.outputDigest !== await valueDigest(o.result)) {
|
|
919
|
+
throw new OrchestrationError('resume_integrity', `step ${o.stepRef}: the checkpoint says it must still be unwound, but its result is not the one its receipt recorded — this run cannot be resumed with integrity`);
|
|
920
|
+
}
|
|
921
|
+
// TOOL DECLARATIONS CHANGE ACROSS DEPLOYS WHILE RUNS ARE PARKED. A step whose tool no longer declares the
|
|
922
|
+
// compensation it ran under (gone, or different) does not stop the run going FORWARD: the obligation is kept on the
|
|
923
|
+
// run as one that can no longer be discharged automatically, and is owed if an unwind is ever needed.
|
|
924
|
+
const now_ = t?.compensation ? { toolId: t.compensation.toolId, args: t.compensation.args } : undefined;
|
|
925
|
+
if (!t || !now_ || (o.compensation && canonicalJson(o.compensation) !== canonicalJson(now_))) {
|
|
926
|
+
lapsed.push(o);
|
|
927
|
+
continue;
|
|
928
|
+
}
|
|
929
|
+
compensable.push({ resolved: resolveStep(runRef, o.index, { id: o.stepRef, toolId: o.toolId, args: {} }, t, {}), result: o.result, receipt: r, ...(o.compensation ? { declared: o.compensation } : {}) });
|
|
930
|
+
}
|
|
931
|
+
}
|
|
604
932
|
try {
|
|
605
933
|
plan = opts.resume ? { ...opts.resume.plan, steps: [...opts.resume.plan.steps] } : await callPlanner(opts.planner, { intent, tools: plannerTools });
|
|
606
934
|
// ── PLAN ADMISSION (spec 367 W1) — is this the plan the sentence asked for? Deterministic, reads the
|
|
@@ -609,10 +937,12 @@ export async function runIntent(intent, opts) {
|
|
|
609
937
|
// but a wrong act they did not get. Admission runs BEFORE the known-tools guard so a rule set that
|
|
610
938
|
// includes `capabilitiesAvailable` turns a plan naming an unexposed tool into a re-plan rather than a
|
|
611
939
|
// raw `unknown_tool` throw (a game persona's planner that named calendar.events.list recovers here).
|
|
612
|
-
|
|
940
|
+
// (A run resumed mid-unwind executes nothing more of its plan: there is no plan to admit, only what ran to undo.)
|
|
941
|
+
// (A refusal here on a RESUME ends a run that has run things: it goes through `endRun`, which unwinds them.)
|
|
942
|
+
if (!opts.resume?.unwinding) {
|
|
613
943
|
const admitted = await admitPlan(plan);
|
|
614
944
|
if ('result' in admitted)
|
|
615
|
-
return admitted.result;
|
|
945
|
+
return endRun(admitted.result);
|
|
616
946
|
plan = admitted.plan;
|
|
617
947
|
}
|
|
618
948
|
assertKnownTools(plan, toolIds); // fail-closed (ADR-0013): a caller without `capabilitiesAvailable` still hard-fails on an unexposed tool.
|
|
@@ -631,6 +961,10 @@ export async function runIntent(intent, opts) {
|
|
|
631
961
|
/** Spec 445 W0 — consequential steps that have run in this run, with the arguments they ran with (see the point of use). */
|
|
632
962
|
const spent = [];
|
|
633
963
|
const concreteArgs = new Map();
|
|
964
|
+
// Audit H-9 fix-up 3 — A PARK IS NOT A FAILURE. A step waiting for an approval or a mandate resumes later, and the
|
|
965
|
+
// resume replays what already ran as done; unwinding it now would leave the resume skipping a prerequisite it undid.
|
|
966
|
+
// Only a run that ends (denied, failed) unwinds.
|
|
967
|
+
const unwinds = (r) => r.outcome === 'denied' || r.outcome === 'failed';
|
|
634
968
|
const attempt = async (i, step) => {
|
|
635
969
|
const tool = toolsById.get(step.toolId);
|
|
636
970
|
// ── ALREADY RAN (spec 370 P1) — replayed as evidence, never as permission. ────────────────
|
|
@@ -709,6 +1043,15 @@ export async function runIntent(intent, opts) {
|
|
|
709
1043
|
// Only names the TOOL declares are accepted: `supplied` arrives from a client, and a question we
|
|
710
1044
|
// asked is not a licence to set arguments we did not ask about.
|
|
711
1045
|
const declaredArgs = tool.inputSchema?.properties;
|
|
1046
|
+
// Spec 448 rule 4 (audit T4-5) — AN ANSWER IS PART OF THE PLAN, NOT A WAY AROUND IT. An answer that sets an
|
|
1047
|
+
// argument to anything other than what the plan states is written INTO the plan, and the plan digest is
|
|
1048
|
+
// recomputed: the mandate a person signs after answering binds the answer, and an answer supplied after she
|
|
1049
|
+
// signed — a session holder rewriting a message body, a memo, a record key — is `plan-mismatch` at the verifier,
|
|
1050
|
+
// never a silent substitution under the digest she approved.
|
|
1051
|
+
// Audit T4-5 fix-up — the answer is compared with the plan AS WRITTEN and the step runs with the folded plan's
|
|
1052
|
+
// arguments RESOLVED: an answer that restates a written value (a `$ref` included) changes nothing, and never hands
|
|
1053
|
+
// the tool the unresolved expression in place of the value it names.
|
|
1054
|
+
let foldedArgs = null;
|
|
712
1055
|
for (const answer of inputsFor(opts.supplied, step.id ?? `s${i}`)) {
|
|
713
1056
|
// A CONFIRMATION answers yes/no; its `data` (an outbound `disclosure` digest) binds the answer, never an argument.
|
|
714
1057
|
if (answer.confirmed !== undefined)
|
|
@@ -718,9 +1061,18 @@ export async function runIntent(intent, opts) {
|
|
|
718
1061
|
continue;
|
|
719
1062
|
if (declaredArgs && !(name in declaredArgs))
|
|
720
1063
|
continue;
|
|
721
|
-
|
|
1064
|
+
const written = (foldedArgs ?? step.args ?? {})[name];
|
|
1065
|
+
if (written === undefined || canonicalJson(written) !== canonicalJson(value))
|
|
1066
|
+
foldedArgs = { ...(foldedArgs ?? step.args ?? {}), [name]: value };
|
|
722
1067
|
}
|
|
723
1068
|
}
|
|
1069
|
+
if (foldedArgs) {
|
|
1070
|
+
const original = step;
|
|
1071
|
+
step = { ...step, args: foldedArgs };
|
|
1072
|
+
plan = { ...plan, steps: plan.steps.map((s, j) => (j === i && s === original ? step : s)) };
|
|
1073
|
+
currentPlanDigest = await planDigest(plan);
|
|
1074
|
+
args = resolveArgs(step.args, refs);
|
|
1075
|
+
}
|
|
724
1076
|
const startedAt = now();
|
|
725
1077
|
if (opts.normalizeArgs) {
|
|
726
1078
|
// Normalisation may not be able to finish alone: "send it to alice" names a person the substrate
|
|
@@ -742,7 +1094,7 @@ export async function runIntent(intent, opts) {
|
|
|
742
1094
|
const request = { ...e.request, stepRef: pending.stepRef, toolId: tool.id };
|
|
743
1095
|
emit({ type: 'RunSuspended', runRef, stepRef: pending.stepRef, resumeToken: pending.stepRef });
|
|
744
1096
|
await record({ ...(await base(pending, startedAt)), status: 'suspended', pendingInput: receiptPending(request), completedAt: now() });
|
|
745
|
-
return { kind: 'exit', result: { outcome: 'suspended', plan, steps: allObservations, receipts, runRef, resumeToken: pending.stepRef, prompt: request }, compensate: false };
|
|
1097
|
+
return { kind: 'exit', result: { outcome: 'suspended', plan, ...parked(), steps: allObservations, receipts, runRef, resumeToken: pending.stepRef, prompt: request }, compensate: false };
|
|
746
1098
|
}
|
|
747
1099
|
}
|
|
748
1100
|
const rs = resolveStep(runRef, i, step, tool, args);
|
|
@@ -755,7 +1107,7 @@ export async function runIntent(intent, opts) {
|
|
|
755
1107
|
// no tool is left to choose an amount nobody compared with what she said.
|
|
756
1108
|
if (ports.planAdmission && tool.capability && statedOutcomeOf(intent)) {
|
|
757
1109
|
const at = spent.length;
|
|
758
|
-
const verdict = await ports.planAdmission.admit({ intent, plan: { steps: [...spent, { toolId: step.toolId, args }] }, tools: plannerTools, concrete: true });
|
|
1110
|
+
const verdict = await ports.planAdmission.admit({ intent: admissionIntent, plan: { steps: [...spent, { toolId: step.toolId, args }] }, tools: plannerTools, concrete: true });
|
|
759
1111
|
const mine = verdict.admitted ? [] : verdict.violations.filter((v) => v.stepIndex === at && POINT_OF_USE_CODES.has(v.code));
|
|
760
1112
|
const refused = mine.filter((v) => v.recovery !== 'ask');
|
|
761
1113
|
if (refused.length) {
|
|
@@ -769,15 +1121,18 @@ export async function runIntent(intent, opts) {
|
|
|
769
1121
|
const request = { kind: 'data', stepRef: rs.stepRef, toolId: tool.id, prompt: asked.map((v) => v.message).join(' '), fields: asked.map((v) => ({ name: v.field, label: v.field, type: 'number', required: true })) };
|
|
770
1122
|
emit({ type: 'RunSuspended', runRef, stepRef: rs.stepRef, resumeToken: rs.stepRef });
|
|
771
1123
|
await record({ ...(await base(rs, startedAt)), status: 'suspended', pendingInput: receiptPending(request), completedAt: now() });
|
|
772
|
-
return { kind: 'exit', result: { outcome: 'suspended', plan, steps: allObservations, receipts, runRef, resumeToken: rs.stepRef, prompt: request }, compensate: false };
|
|
1124
|
+
return { kind: 'exit', result: { outcome: 'suspended', plan, ...parked(), steps: allObservations, receipts, runRef, resumeToken: rs.stepRef, prompt: request }, compensate: false };
|
|
773
1125
|
}
|
|
774
1126
|
concreteArgs.set(rs.stepRef, args);
|
|
775
1127
|
}
|
|
776
1128
|
// ── authority, for every step that exercises a capability ──
|
|
777
1129
|
let authority;
|
|
778
1130
|
let approvalRecords = [];
|
|
1131
|
+
let approvedBy = [];
|
|
779
1132
|
/** Spec 445 decision 8 — this step runs under a VERIFIED mandate (the effectful-step authority path). */
|
|
780
1133
|
let mandated = false;
|
|
1134
|
+
/** The request the allowing decision answered — what `MandateVerifier.begin` counts the attempt under. */
|
|
1135
|
+
let mandatedReq;
|
|
781
1136
|
// Spec 374 §1 — THE ASK IS ROUTED; THE MANDATE IS NOT. A step whose subject is another agent is
|
|
782
1137
|
// sent there (spec 366 R1), and THAT agent judges its authority under its own playbook, asks its own
|
|
783
1138
|
// steward, and answers. Judging it here would ask the asker for a mandate the subject never
|
|
@@ -810,7 +1165,7 @@ export async function runIntent(intent, opts) {
|
|
|
810
1165
|
const request = { ...e.request, stepRef: rs.stepRef, toolId: tool.id };
|
|
811
1166
|
emit({ type: 'RunSuspended', runRef, stepRef: rs.stepRef, resumeToken: rs.stepRef });
|
|
812
1167
|
await record({ ...(await base(rs, startedAt)), status: 'suspended', pendingInput: receiptPending(request), completedAt: now() });
|
|
813
|
-
return { kind: 'exit', result: { outcome: 'suspended', plan, steps: allObservations, receipts, runRef, resumeToken: rs.stepRef, prompt: request }, compensate: false };
|
|
1168
|
+
return { kind: 'exit', result: { outcome: 'suspended', plan, ...parked(), steps: allObservations, receipts, runRef, resumeToken: rs.stepRef, prompt: request }, compensate: false };
|
|
814
1169
|
}
|
|
815
1170
|
await record({ ...(await base(rs, startedAt)), status: 'failed', completedAt: now(), error: e instanceof Error ? e.message : String(e) });
|
|
816
1171
|
return { kind: 'done', obs: { step, ok: false, stepRef: rs.stepRef, error: e instanceof Error ? e.message : String(e) } };
|
|
@@ -836,18 +1191,31 @@ export async function runIntent(intent, opts) {
|
|
|
836
1191
|
decision: 'allow', obligations: [],
|
|
837
1192
|
// The evidence names the basis honestly — there is no mandate to reference, and inventing a
|
|
838
1193
|
// mandateRef would make a receipt claim a signature that never happened.
|
|
839
|
-
evidence: { mandateRef: 'self', intentDigest: await valueDigest(intent), evaluatedAt: now(), verdicts: [{ enforcer: 'self', allowed: true, reason:
|
|
1194
|
+
evidence: { mandateRef: 'self', intentDigest: await valueDigest(intent), evaluatedAt: now(), verdicts: [{ enforcer: 'self', allowed: true, reason: `the run's own principal owns what this touches; the session is the authority${opts.caller ? ` — the session of ${opts.caller.kind}${opts.caller.ref ? ` ${opts.caller.ref}` : ''}` : ''}` }], ...(opts.caller ? { caller: opts.caller } : {}) },
|
|
840
1195
|
},
|
|
841
1196
|
afterApproval: false,
|
|
842
1197
|
};
|
|
1198
|
+
// Spec 448 rule 6 + §0 (audit H-9 fix-up 2) — the session says WHO acts; it discharges no obligation. A step whose
|
|
1199
|
+
// risk class or declared policy carries one climbs the same ladder as a mandated step: with no declared policy one
|
|
1200
|
+
// verified steward's signature (the steward who asked included), a declared two-steward policy two of them.
|
|
1201
|
+
const selfDecision = authority.decision;
|
|
1202
|
+
const laddered = await ladder(rs, startedAt, plan, { intent, presented: null, step: rs, afterApproval: false, planDigest: currentPlanDigest }, selfDecision, 'self');
|
|
1203
|
+
if ('outcome' in laddered)
|
|
1204
|
+
return { kind: 'exit', result: laddered, compensate: unwinds(laddered) };
|
|
1205
|
+
approvalRecords = laddered.approvalRecords;
|
|
1206
|
+
approvedBy = laddered.approvedBy;
|
|
1207
|
+
if (approvedBy.length)
|
|
1208
|
+
authority = { ...authority, afterApproval: true };
|
|
843
1209
|
}
|
|
844
1210
|
else if (rs.risk !== 'informational') {
|
|
845
1211
|
const a = await authorize(rs, startedAt, plan);
|
|
846
1212
|
if ('outcome' in a)
|
|
847
|
-
return { kind: 'exit', result: a, compensate:
|
|
848
|
-
authority = { presentedRef: a.used.ref, decision: a.decision, afterApproval: a.
|
|
1213
|
+
return { kind: 'exit', result: a, compensate: unwinds(a) };
|
|
1214
|
+
authority = { presentedRef: a.used.ref, decision: a.decision, afterApproval: a.approvedBy.length > 0 };
|
|
849
1215
|
approvalRecords = a.approvalRecords;
|
|
1216
|
+
approvedBy = a.approvedBy;
|
|
850
1217
|
mandated = true;
|
|
1218
|
+
mandatedReq = { intent, presented: a.used, step: rs, afterApproval: a.approvedBy.length > 0, planDigest: currentPlanDigest, ...(a.approvedBy.length ? { approvals: a.approvedBy } : {}), decision: a.decision };
|
|
851
1219
|
}
|
|
852
1220
|
// ── OUTBOUND (spec 445 decision 8) — a tool that sends data to another party is not run silently once this run
|
|
853
1221
|
// has read untrusted content, nor when an argument is threaded from an untrusted result. A verified mandate is
|
|
@@ -866,7 +1234,8 @@ export async function runIntent(intent, opts) {
|
|
|
866
1234
|
await record({ ...(await base(rs, startedAt)), status: 'denied', completedAt: now(), error });
|
|
867
1235
|
return { kind: 'exit', result: { outcome: 'denied', plan, steps: allObservations, receipts, runRef, error }, compensate: true };
|
|
868
1236
|
}
|
|
869
|
-
|
|
1237
|
+
// I6 — a yes counts only for the disclosure it names: the one shown, which is the one these arguments produce.
|
|
1238
|
+
if (!answers.some((s) => s.confirmed === true && answerBinding(s) === disclosure)) {
|
|
870
1239
|
const request = {
|
|
871
1240
|
kind: 'confirmation', stepRef: rs.stepRef, toolId: tool.id,
|
|
872
1241
|
prompt: `This run has read content written by others. Send this to ${party}? Nothing leaves until you confirm exactly this.`,
|
|
@@ -874,7 +1243,7 @@ export async function runIntent(intent, opts) {
|
|
|
874
1243
|
};
|
|
875
1244
|
emit({ type: 'RunSuspended', runRef, stepRef: rs.stepRef, resumeToken: rs.stepRef });
|
|
876
1245
|
await record({ ...(await base(rs, startedAt)), status: 'suspended', ...(authority ? { authority } : {}), pendingInput: receiptPending(request), completedAt: now() });
|
|
877
|
-
return { kind: 'exit', result: { outcome: 'suspended', plan, steps: allObservations, receipts, runRef, resumeToken: rs.stepRef, prompt: request }, compensate: false };
|
|
1246
|
+
return { kind: 'exit', result: { outcome: 'suspended', plan, ...parked(), steps: allObservations, receipts, runRef, resumeToken: rs.stepRef, prompt: request }, compensate: false };
|
|
878
1247
|
}
|
|
879
1248
|
outboundConfirmed = disclosure;
|
|
880
1249
|
}
|
|
@@ -882,57 +1251,72 @@ export async function runIntent(intent, opts) {
|
|
|
882
1251
|
// ── execute ──
|
|
883
1252
|
const suppliedHere = inputsFor(opts.supplied, rs.stepRef);
|
|
884
1253
|
const binding = opts.bindingFor?.(rs);
|
|
885
|
-
const operationId = binding?.operationId
|
|
886
|
-
const ctx = { intent, step, index: i, ...(rs.idempotencyKey ? { idempotencyKey: rs.idempotencyKey } : {}), operationId, ...(suppliedHere.length ? { supplied: suppliedHere } : {}), planDigest: currentPlanDigest, untrustedSeen, ...(outboundConfirmed ? { outboundConfirmed } : {}) };
|
|
1254
|
+
const operationId = binding?.operationId || rs.idempotencyKey || `${runRef}:${rs.stepRef}`;
|
|
887
1255
|
executed++;
|
|
888
1256
|
let obs;
|
|
889
1257
|
let observation;
|
|
890
1258
|
let reconciled = false;
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
1259
|
+
/** The compensation obligation this step leaves, once its receipt exists. */
|
|
1260
|
+
let owes;
|
|
1261
|
+
// Spec 448 rule 4 — THE STEP'S EFFECT GOES THROUGH THE LIFECYCLE (`step-lifecycle.ts`, `perform` above): the pre-act
|
|
1262
|
+
// read, the use ledger's slot, the invocation, a lost response, a hand-over and the effect-uncertain park are one
|
|
1263
|
+
// machine. What comes back is what happened; this code only records it.
|
|
1264
|
+
const performed = await perform({
|
|
1265
|
+
rs, tool, step, args, operationId, ...(binding ? { binding } : {}), ...(mandatedReq ? { counted: mandatedReq } : {}),
|
|
1266
|
+
invoke: (opId) => opts.invoke(step.toolId, args, { intent, step, index: i, ...(rs.idempotencyKey ? { idempotencyKey: rs.idempotencyKey } : {}), operationId: opId, ...(suppliedHere.length ? { supplied: suppliedHere } : {}), planDigest: currentPlanDigest, untrustedSeen, ...(outboundConfirmed ? { outboundConfirmed } : {}) }),
|
|
1267
|
+
});
|
|
1268
|
+
if (performed.kind === 'parked') {
|
|
1269
|
+
// EFFECT-UNCERTAIN: the run waits here for the principal. Never a failure, never re-planned around, nothing unwound.
|
|
1270
|
+
emit({ type: 'RunSuspended', runRef, stepRef: rs.stepRef, resumeToken: rs.stepRef });
|
|
1271
|
+
await record({ ...(await base(rs, startedAt)), status: 'suspended', ...(authority ? { authority } : {}), ...(approvalRecords.length ? { approvalRecords } : {}), pendingInput: receiptPending(performed.request), completedAt: now(), error: `effect-uncertain: ${performed.request.why}` });
|
|
1272
|
+
return { kind: 'exit', result: { outcome: 'suspended', plan, ...parked(), steps: allObservations, receipts, runRef, resumeToken: rs.stepRef, prompt: performed.request }, compensate: false };
|
|
1273
|
+
}
|
|
1274
|
+
if (performed.kind === 'question') {
|
|
1275
|
+
// The tool asked the person for something (spec 350 §3.4). Not a failure — nothing is re-planned
|
|
1276
|
+
// around a question — and not a denial: authority was verified and stands. The run suspends with
|
|
1277
|
+
// the prompt; the resume re-runs the intent with the answers, through every gate again. Steps
|
|
1278
|
+
// already executed are NOT compensated: they stand, and the resume replays them.
|
|
1279
|
+
const request = { ...performed.request, stepRef: rs.stepRef, toolId: tool.id };
|
|
1280
|
+
emit({ type: 'RunSuspended', runRef, stepRef: rs.stepRef, resumeToken: rs.stepRef });
|
|
1281
|
+
await record({
|
|
1282
|
+
...(await base(rs, startedAt)),
|
|
1283
|
+
status: 'suspended',
|
|
1284
|
+
...(authority ? { authority } : {}),
|
|
1285
|
+
...(approvalRecords.length ? { approvalRecords } : {}),
|
|
1286
|
+
pendingInput: receiptPending(request),
|
|
1287
|
+
completedAt: now(),
|
|
1288
|
+
});
|
|
1289
|
+
return { kind: 'exit', result: { outcome: 'suspended', plan, ...parked(), steps: allObservations, receipts, runRef, resumeToken: rs.stepRef, prompt: request }, compensate: false };
|
|
1290
|
+
}
|
|
1291
|
+
if (performed.kind === 'failed') {
|
|
1292
|
+
obs = { step, ok: false, error: performed.error instanceof Error ? performed.error.message : String(performed.error), stepRef: rs.stepRef };
|
|
1293
|
+
}
|
|
1294
|
+
else {
|
|
1295
|
+
if (performed.by === 'tool') {
|
|
1296
|
+
const seen = observeInvocation(performed.raw, tool, now);
|
|
1297
|
+
observation = seen.observation;
|
|
1298
|
+
obs = { step, ok: true, result: seen.output, stepRef: rs.stepRef };
|
|
1299
|
+
}
|
|
1300
|
+
else if (performed.by === 'reader') {
|
|
901
1301
|
reconciled = true;
|
|
902
|
-
observation = { ...found.observation, outcome: found.observation.outcome ?? 'confirmed', evidence: [{ kind: 'reconcile', ref: `operation ${operationId} was already done; this attempt did not act` }, ...found.observation.evidence] };
|
|
903
|
-
obs = { step, ok: true, result: found.output, stepRef: rs.stepRef };
|
|
1302
|
+
observation = { ...performed.found.observation, outcome: performed.found.observation.outcome ?? 'confirmed', evidence: [{ kind: 'reconcile', ref: `operation ${performed.operationId} was already done; this attempt did not act` }, ...performed.found.observation.evidence] };
|
|
1303
|
+
obs = { step, ok: true, result: performed.found.output, stepRef: rs.stepRef };
|
|
904
1304
|
}
|
|
905
1305
|
else {
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
obs = { step, ok: true, result, stepRef: rs.stepRef };
|
|
1306
|
+
reconciled = true;
|
|
1307
|
+
observation = { outcome: 'committed', observedAt: new Date(now()).toISOString(), evidence: [{ kind: 'principal-attested', ref: `the principal said operation ${performed.operationId} took effect; this attempt did not act` }] };
|
|
1308
|
+
obs = { step, ok: true, stepRef: rs.stepRef };
|
|
910
1309
|
}
|
|
911
1310
|
if (step.ref)
|
|
912
1311
|
refs[step.ref] = obs.result;
|
|
913
1312
|
lastResult = obs.result;
|
|
914
|
-
if (tool.compensation && rs.risk !== 'informational' && !reconciled)
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
catch (e) {
|
|
918
|
-
if (isInputRequired(e)) {
|
|
919
|
-
// The tool asked the person for something (spec 350 §3.4). Not a failure — nothing is re-planned
|
|
920
|
-
// around a question — and not a denial: authority was verified and stands. The run suspends with
|
|
921
|
-
// the prompt; the resume re-runs the intent with the answers, through every gate again. Steps
|
|
922
|
-
// already executed are NOT compensated: they stand, and the resume re-invokes them idempotently.
|
|
923
|
-
const request = { ...e.request, stepRef: rs.stepRef, toolId: tool.id };
|
|
924
|
-
emit({ type: 'RunSuspended', runRef, stepRef: rs.stepRef, resumeToken: rs.stepRef });
|
|
925
|
-
await record({
|
|
926
|
-
...(await base(rs, startedAt)),
|
|
927
|
-
status: 'suspended',
|
|
928
|
-
...(authority ? { authority } : {}),
|
|
929
|
-
...(approvalRecords.length ? { approvalRecords } : {}),
|
|
930
|
-
pendingInput: receiptPending(request),
|
|
931
|
-
completedAt: now(),
|
|
932
|
-
});
|
|
933
|
-
return { kind: 'exit', result: { outcome: 'suspended', plan, steps: allObservations, receipts, runRef, resumeToken: rs.stepRef, prompt: request }, compensate: false };
|
|
1313
|
+
if (tool.compensation && rs.risk !== 'informational' && !reconciled) {
|
|
1314
|
+
owes = { resolved: rs, result: obs.result };
|
|
1315
|
+
compensable.push(owes);
|
|
934
1316
|
}
|
|
935
|
-
|
|
1317
|
+
// The effect exists and this run records it; the ledger could not be told, and the receipt says so.
|
|
1318
|
+
if (performed.ledgerUnwritten && observation)
|
|
1319
|
+
observation = { ...observation, evidence: [...observation.evidence, { kind: 'ledger-unwritten', ref: 'the use ledger could not be told this step completed; it still holds the step, and no other attempt performs it' }] };
|
|
936
1320
|
}
|
|
937
1321
|
emit({ type: 'ToolInvoked', runRef, stepRef: rs.stepRef, toolId: tool.id, ok: obs.ok });
|
|
938
1322
|
const decisions = opts.decisionsFor?.(tool.id, args) ?? [];
|
|
@@ -943,12 +1327,15 @@ export async function runIntent(intent, opts) {
|
|
|
943
1327
|
...(decisions.length ? { decisions: [...decisions] } : {}),
|
|
944
1328
|
...(authority ? { authority } : {}),
|
|
945
1329
|
...(approvalRecords.length ? { approvalRecords } : {}),
|
|
1330
|
+
...(approvedBy.length ? { approvedBy } : {}),
|
|
946
1331
|
...(obs.ok ? { outputDigest: await valueDigest(obs.result) } : { error: obs.error }),
|
|
947
1332
|
// Spec 410 §2 — what the adapter saw, and the one word the receipt attests.
|
|
948
1333
|
...(observation ? { observation, attests: observation.outcome } : {}),
|
|
949
1334
|
...(reconciled ? { reconciled: true } : {}),
|
|
950
1335
|
completedAt: now(),
|
|
951
1336
|
};
|
|
1337
|
+
if (owes)
|
|
1338
|
+
owes.receipt = stepReceipt;
|
|
952
1339
|
await record(stepReceipt);
|
|
953
1340
|
// ── DECLARED EFFECTS — spec 360. What the playbook promised FOLLOWS this act.
|
|
954
1341
|
//
|
|
@@ -994,6 +1381,33 @@ export async function runIntent(intent, opts) {
|
|
|
994
1381
|
}
|
|
995
1382
|
return { kind: 'done', obs };
|
|
996
1383
|
};
|
|
1384
|
+
// ── RESUMED MID-UNWIND (I3) — the run was ending when a compensation parked as effect-uncertain. What ran is read back
|
|
1385
|
+
// from the checkpoint (each result against its receipt: a compensation's arguments come from it), what is already owed
|
|
1386
|
+
// is carried, and the unwinding goes on from where it stopped. No step of the plan runs.
|
|
1387
|
+
if (opts.resume?.unwinding) {
|
|
1388
|
+
const u = opts.resume.unwinding;
|
|
1389
|
+
compensationsOwed.push(...u.owed);
|
|
1390
|
+
for (let i = 0; i < plan.steps.length; i++) {
|
|
1391
|
+
const st = plan.steps[i];
|
|
1392
|
+
const stepRef = st.id ?? `s${i}`;
|
|
1393
|
+
const was = completedByRef.get(stepRef);
|
|
1394
|
+
const tool = toolsById.get(st.toolId);
|
|
1395
|
+
if (!was || !tool)
|
|
1396
|
+
continue;
|
|
1397
|
+
const r = was.receipt;
|
|
1398
|
+
if (!r || r.runRef !== runRef || r.stepRef !== stepRef || r.toolId !== st.toolId || r.status !== 'executed' || !isValueDigest(r.outputDigest) || r.outputDigest !== await valueDigest(was.result)) {
|
|
1399
|
+
throw new OrchestrationError('resume_integrity', `step ${stepRef}: the checkpoint's result is not the one its receipt recorded — it cannot be unwound from`);
|
|
1400
|
+
}
|
|
1401
|
+
if (st.ref)
|
|
1402
|
+
refs[st.ref] = was.result;
|
|
1403
|
+
receipts.push(r);
|
|
1404
|
+
allObservations.push({ step: st, ok: true, result: was.result, stepRef, replayed: true });
|
|
1405
|
+
}
|
|
1406
|
+
const ended = await endRun({ outcome: u.outcome, plan, steps: allObservations, receipts, runRef, error: u.error });
|
|
1407
|
+
if (ended.outcome === 'failed')
|
|
1408
|
+
emit({ type: 'RunFailed', runRef, error: u.error });
|
|
1409
|
+
return ended;
|
|
1410
|
+
}
|
|
997
1411
|
for (;;) {
|
|
998
1412
|
let failedMidPlan = false;
|
|
999
1413
|
for (let i = 0; i < plan.steps.length;) {
|
|
@@ -1021,7 +1435,7 @@ export async function runIntent(intent, opts) {
|
|
|
1021
1435
|
const next = await callPlanner(opts.planner, { intent: toldOwed, tools: plannerTools, observations: forPlanner(allObservations), continuation: true });
|
|
1022
1436
|
const admitted = await admitPlan({ ...next, steps: [...done, ...next.steps] });
|
|
1023
1437
|
if ('result' in admitted)
|
|
1024
|
-
return admitted.result;
|
|
1438
|
+
return endRun(admitted.result);
|
|
1025
1439
|
plan = admitted.plan;
|
|
1026
1440
|
assertKnownTools(plan, toolIds); // fail-closed after admission's re-plan (ADR-0013).
|
|
1027
1441
|
currentPlanDigest = await planDigest(plan);
|
|
@@ -1075,18 +1489,21 @@ export async function runIntent(intent, opts) {
|
|
|
1075
1489
|
emit({ type: 'PlanCreated', runRef, steps: expanded.length, rationale: `fan-out of ${baseId} over <${relation}> into ${expanded.length} steps` });
|
|
1076
1490
|
maxSteps += Math.max(0, expanded.length - 1);
|
|
1077
1491
|
plan = { ...plan, steps: [...plan.steps.slice(0, i), ...expanded, ...plan.steps.slice(i + 1)] };
|
|
1492
|
+
// Audit H-4 fix-up — the steps that run are the EXPANDED ones (new ids, item arguments); the digest presented for
|
|
1493
|
+
// them is the expanded plan's, so a mandate signed over the template does not cover items it never named. A
|
|
1494
|
+
// parked run reports this digest and a resume (the expanded plan, no `forEach` left) reproduces it.
|
|
1495
|
+
currentPlanDigest = await planDigest(plan);
|
|
1078
1496
|
// RUNC-4 (spec 445 W0) — A BOUND STATED OVER THE PLAN IS JUDGED OVER THE EXPANDED PLAN. Admission saw ONE step
|
|
1079
1497
|
// where there are now N; "up to 20 in total" over three payees is only decidable here. The expanded plan goes
|
|
1080
1498
|
// back through the same admission port, and a violation no re-plan may cure (`refuse`) ends the run before
|
|
1081
1499
|
// any item runs. Other recoveries are not acted on here: the plan as written was already admitted, and an
|
|
1082
1500
|
// expansion is not a new plan to re-word.
|
|
1083
1501
|
if (ports.planAdmission && expanded.length > 0) {
|
|
1084
|
-
const verdict = await ports.planAdmission.admit({ intent, plan, tools: plannerTools });
|
|
1502
|
+
const verdict = await ports.planAdmission.admit({ intent: admissionIntent, plan, tools: plannerTools });
|
|
1085
1503
|
const refused = verdict.admitted ? [] : verdict.violations.filter((v) => v.recovery === 'refuse');
|
|
1086
1504
|
if (refused.length) {
|
|
1087
1505
|
emit({ type: 'PlanRefused', runRef, violations: refused, replanning: false });
|
|
1088
|
-
|
|
1089
|
-
return withOwed({ outcome: 'denied', plan, steps: allObservations, receipts, runRef, error: `plan_refused: ${refused.map((v) => v.message).join(' | ')}` });
|
|
1506
|
+
return endRun({ outcome: 'denied', plan, steps: allObservations, receipts, runRef, error: `plan_refused: ${refused.map((v) => v.message).join(' | ')}` });
|
|
1090
1507
|
}
|
|
1091
1508
|
}
|
|
1092
1509
|
if (expanded.length === 0)
|
|
@@ -1127,9 +1544,12 @@ export async function runIntent(intent, opts) {
|
|
|
1127
1544
|
}
|
|
1128
1545
|
spent.push({ toolId: o.obs.step.toolId, args: ran });
|
|
1129
1546
|
}
|
|
1130
|
-
if (o.obs.ok && isUntrusted(o.obs.result))
|
|
1547
|
+
if (o.obs.ok && isUntrusted(o.obs.result, o.obs.step.toolId))
|
|
1548
|
+
untrustedSeen = true;
|
|
1549
|
+
// Audit T4-3 — a failed step's error text reaches the re-planner (framed); it may be a remote service's words.
|
|
1550
|
+
if (!o.obs.ok && isUntrusted(o.obs.error))
|
|
1131
1551
|
untrustedSeen = true;
|
|
1132
|
-
if (o.obs.ok && o.obs.step.ref && (isUntrusted(o.obs.result) || [...refsUsed(o.obs.step.args)].some((r) => taintedRefs.has(r))))
|
|
1552
|
+
if (o.obs.ok && o.obs.step.ref && (isUntrusted(o.obs.result, o.obs.step.toolId) || [...refsUsed(o.obs.step.args)].some((r) => taintedRefs.has(r))))
|
|
1133
1553
|
taintedRefs.add(o.obs.step.ref);
|
|
1134
1554
|
opts.onObserve?.(o.obs);
|
|
1135
1555
|
if (o.obs.ok && !o.obs.skipped)
|
|
@@ -1141,9 +1561,11 @@ export async function runIntent(intent, opts) {
|
|
|
1141
1561
|
exit = o;
|
|
1142
1562
|
}
|
|
1143
1563
|
if (exit) {
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1564
|
+
// Audit T4-3 fix-up 2 — the exit was built when its step settled; a sibling that settled after it may have read
|
|
1565
|
+
// untrusted content. What a parked run hands its resume is read now, after the whole batch.
|
|
1566
|
+
if (untrustedSeen && (exit.result.outcome === 'suspended' || exit.result.outcome === 'authority-required'))
|
|
1567
|
+
exit.result = { ...exit.result, untrustedSeen: true };
|
|
1568
|
+
return exit.compensate ? endRun(exit.result) : withOwed(exit.result);
|
|
1147
1569
|
}
|
|
1148
1570
|
if (failedMidPlan)
|
|
1149
1571
|
break; // stop this plan; decide whether to re-plan below
|
|
@@ -1155,10 +1577,11 @@ export async function runIntent(intent, opts) {
|
|
|
1155
1577
|
}
|
|
1156
1578
|
if (replans >= maxReplans) {
|
|
1157
1579
|
const last = allObservations[allObservations.length - 1];
|
|
1158
|
-
await compensate();
|
|
1159
1580
|
const error = last?.error ?? 'step failed';
|
|
1160
|
-
|
|
1161
|
-
|
|
1581
|
+
const ended = await endRun({ outcome: 'failed', plan, steps: allObservations, receipts, runRef, error });
|
|
1582
|
+
if (ended.outcome === 'failed')
|
|
1583
|
+
emit({ type: 'RunFailed', runRef, error });
|
|
1584
|
+
return ended;
|
|
1162
1585
|
}
|
|
1163
1586
|
replans++;
|
|
1164
1587
|
// Spec 391 W2 — the planner sees what each prior step WAS and how big, not a 40 KB body in its prompt.
|
|
@@ -1169,10 +1592,8 @@ export async function runIntent(intent, opts) {
|
|
|
1169
1592
|
// just read an error string. Refused ⇒ the run ends there, and what already ran is unwound.
|
|
1170
1593
|
const replanned = await callPlanner(opts.planner, { intent, tools: plannerTools, observations: compactObservations(forPlanner(allObservations)) });
|
|
1171
1594
|
const readmitted = await admitPlan(replanned);
|
|
1172
|
-
if ('result' in readmitted)
|
|
1173
|
-
|
|
1174
|
-
return withOwed(readmitted.result);
|
|
1175
|
-
}
|
|
1595
|
+
if ('result' in readmitted)
|
|
1596
|
+
return endRun(readmitted.result);
|
|
1176
1597
|
plan = readmitted.plan;
|
|
1177
1598
|
assertKnownTools(plan, toolIds); // fail-closed after admission (ADR-0013).
|
|
1178
1599
|
currentPlanDigest = await planDigest(plan);
|
|
@@ -1181,9 +1602,17 @@ export async function runIntent(intent, opts) {
|
|
|
1181
1602
|
}
|
|
1182
1603
|
catch (e) {
|
|
1183
1604
|
const error = e instanceof OrchestrationError ? `${e.code}: ${e.message}` : e instanceof Error ? e.message : String(e);
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1605
|
+
// The unwinding is itself guarded: a throw inside it must not escape as an unhandled rejection with steps half-undone.
|
|
1606
|
+
let ended;
|
|
1607
|
+
try {
|
|
1608
|
+
ended = await endRun({ outcome: 'failed', plan, steps: allObservations, receipts, runRef, error });
|
|
1609
|
+
}
|
|
1610
|
+
catch (e2) {
|
|
1611
|
+
ended = withOwed({ outcome: 'failed', plan, steps: allObservations, receipts, runRef, error: `${error}; and unwinding failed: ${e2 instanceof Error ? e2.message : String(e2)}` });
|
|
1612
|
+
}
|
|
1613
|
+
if (ended.outcome === 'failed')
|
|
1614
|
+
emit({ type: 'RunFailed', runRef, error });
|
|
1615
|
+
return ended;
|
|
1187
1616
|
}
|
|
1188
1617
|
}
|
|
1189
1618
|
//# sourceMappingURL=loop.js.map
|