@parcha/agentrun-dsl 0.1.0-beta.34 → 0.1.0-beta.35

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 CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  Typed workflows that your agent writes. It drafts a workflow, checks it, dry-runs it for free, then runs it; `@parcha/agentrun-dsl/graph` turns the workflow into its graph. The core provides the v2 workflow types, validator, interpreter, events, schema, and an offline CLI. Supply agent, judgment, and effect functions only when a workflow needs them.
4
4
 
5
- Beta, on npm under the `latest` dist-tag (`npm view @parcha/agentrun-dsl dist-tags`). Requires Node 22.19+; TypeScript consumers require TypeScript 5.4+.
5
+ Beta, on npm under the `latest` dist-tag (`npm view @parcha/agentrun-dsl dist-tags`). Requires Node 24.22.3+; TypeScript consumers require TypeScript 5.4+.
6
6
 
7
7
  ```sh
8
8
  npm install @parcha/agentrun-dsl@latest
package/dist/index.d.ts CHANGED
@@ -15,7 +15,7 @@ export { evidenceOf, EVIDENCE_EXCERPT_MAX, EVIDENCE_EXCERPTS_PER_ITEM, EVIDENCE_
15
15
  export type { DecisionProvider, DecisionCapabilities, DecisionInput, DecisionRequest, DecisionContext, DecisionEvidence, DecisionOutcome, ProviderAnswer, CostBasis, DecisionProviderErrorCode, DecisionImage, LoadImage, JudgeFromProviderOptions, } from "./decision-provider.js";
16
16
  export { inspectWorkflow, formatWorkflowTree } from "./inspection.js";
17
17
  export type { WorkflowInspection, WorkflowInspectionNode } from "./inspection.js";
18
- export { runWorkflowSlice, assertWorkflowCapabilities, desugarWorkflow, stageSchemaForNode, submissionSchemaForNode, mergeStageDelta, REPORT_SCHEMA, SHELL_RESULT_SCHEMA, childSteps, declaredWrites, terminalArtifactType, artifactNodeIsProse, schemaProblems, HOST_STATE_KEY, buildReferenceContext, normalizeStringNullsForSchema, parseCsvRows, } from "./workflow.js";
18
+ export { runWorkflowSlice, assertWorkflowCapabilities, desugarWorkflow, stageSchemaForNode, submissionSchemaForNode, mergeStageDelta, REPORT_SCHEMA, SHELL_RESULT_SCHEMA, childSteps, declaredWrites, artifactNodeIsProse, schemaProblems, HOST_STATE_KEY, normalizeStringNullsForSchema, } from "./workflow.js";
19
19
  export { compileTransform, compileTransformSyntax, deniedGlobalReferences } from "./code-exec.js";
20
20
  export { resolveSchemaForWorkflow } from "./schema-references.js";
21
21
  export { submitParameters } from "./submit-envelope.js";
package/dist/index.js CHANGED
@@ -9,9 +9,9 @@ export { evidenceOf, EVIDENCE_EXCERPT_MAX, EVIDENCE_EXCERPTS_PER_ITEM, EVIDENCE_
9
9
  export { inspectWorkflow, formatWorkflowTree } from "./inspection.js";
10
10
  export { runWorkflowSlice, assertWorkflowCapabilities, desugarWorkflow, stageSchemaForNode, submissionSchemaForNode, mergeStageDelta, REPORT_SCHEMA, SHELL_RESULT_SCHEMA,
11
11
  // Document helpers a host facade needs to speak about a workflow without re-implementing the walk.
12
- childSteps, declaredWrites, terminalArtifactType, artifactNodeIsProse, schemaProblems, HOST_STATE_KEY,
13
- // Host-side data helpers the interpreter itself uses: the same normalization and reference shaping.
14
- buildReferenceContext, normalizeStringNullsForSchema, parseCsvRows, } from "./workflow.js";
12
+ childSteps, declaredWrites, artifactNodeIsProse, schemaProblems, HOST_STATE_KEY,
13
+ // The host-side normalization the interpreter itself uses.
14
+ normalizeStringNullsForSchema, } from "./workflow.js";
15
15
  export { compileTransform, compileTransformSyntax, deniedGlobalReferences } from "./code-exec.js";
16
16
  export { resolveSchemaForWorkflow } from "./schema-references.js";
17
17
  export { submitParameters } from "./submit-envelope.js";
@@ -7,7 +7,3 @@ export declare const CALL_KEY_BYTES = 256;
7
7
  * call always has the same key, and two different wide ids share a key only on a digest collision.
8
8
  * Only keys use it: what goes back to the provider is always the id it minted. */
9
9
  export declare function callKey(callId: string): string;
10
- /** The key a ledger holds a call under. Writes always use `callKey`; a read also accepts a row a
11
- * ledger already keys by the raw id (`holds` answers for the raw id), so a run whose ledger keyed a
12
- * wide id as it was resumes against its own receipts and never re-runs a recorded call. */
13
- export declare function heldCallKey(callId: string, holds: (rawKey: string) => boolean): string;
@@ -15,10 +15,3 @@ export function callKey(callId) {
15
15
  const prefix = callId.slice(0, PREFIX_CHARS).replace(/[^A-Za-z0-9_.-]/g, "_");
16
16
  return `${prefix}~${createHash("sha256").update(callId).digest("hex").slice(0, DIGEST_HEX)}`;
17
17
  }
18
- /** The key a ledger holds a call under. Writes always use `callKey`; a read also accepts a row a
19
- * ledger already keys by the raw id (`holds` answers for the raw id), so a run whose ledger keyed a
20
- * wide id as it was resumes against its own receipts and never re-runs a recorded call. */
21
- export function heldCallKey(callId, holds) {
22
- const key = callKey(callId);
23
- return key !== callId && holds(callId) ? callId : key;
24
- }
@@ -1,4 +1,4 @@
1
- import type { RecoveryEffect, RecoveryIntent } from "./store.js";
1
+ import type { RecoveryIntent } from "./store.js";
2
2
  /** A completed tool effect a continuation may answer an exact repeat from: the external call it paid for, and its value. */
3
3
  export type InheritedReceipt = {
4
4
  id: string;
@@ -21,18 +21,6 @@ export type InheritedUnknown = {
21
21
  * an object or as its JSON text. Such a value is not a paid result; the continuation may make the call again. Structural,
22
22
  * never prose. */
23
23
  export declare function returnedFailure(value: unknown): boolean;
24
- /** The receipts a journal hands to its continuation: completed effects whose receipt names the external call (tool
25
- * effects; shell and executor effects have no external call to repeat) and whose value is a result, not a returned
26
- * failure. */
27
- export declare function inheritableReceipts(effects: readonly RecoveryEffect[]): InheritedReceipt[];
28
- /** The effects a continuation must not dispatch again: every effect whose outcome is unknown, by the name and argument
29
- * hash its admission recorded, and by the external call it was admitted for when the journal holds one. A call the
30
- * continuation's own tools make is matched by `reuseReceipts` on either key. A session effect's name and hash are
31
- * already a tool's name and the hash of its arguments. A tool effect the driver admitted for a workflow node is named
32
- * by the node's label and hashed over the node's whole invocation, so it is matched by its intent (the tool and the
33
- * hash of its arguments, keyed as `gatewayIntentOf` keys a call); one a journal admitted before intents were recorded
34
- * has none, and is matched by name and hash only. */
35
- export declare function inheritableUnknowns(effects: readonly RecoveryEffect[]): InheritedUnknown[];
36
24
  /** The external call a model tool call stands for: the gateway tool and the hash of its arguments. Only a `fetch`
37
25
  * wrapper names the gateway tool in its arguments; every other tool is its own name, whatever its arguments look like.
38
26
  * The same key is computed for an effect from its receipt's intent. */
@@ -19,29 +19,6 @@ export function returnedFailure(value) {
19
19
  }
20
20
  return false;
21
21
  }
22
- /** The receipts a journal hands to its continuation: completed effects whose receipt names the external call (tool
23
- * effects; shell and executor effects have no external call to repeat) and whose value is a result, not a returned
24
- * failure. */
25
- export function inheritableReceipts(effects) {
26
- return effects.filter((e) => e.status === "completed" && e.result && typeof e.result === "object" && e.result.intent && typeof e.result.intent.tool === "string" && !returnedFailure(e.result.value))
27
- .map((e) => {
28
- const receipt = e.result;
29
- // Keyed as a continuation's own call is: a node that reached the gateway through the fetch wrapper paid for the tool the wrapper names.
30
- const { tool, argsHash } = gatewayIntentOf(receipt.intent.tool, receipt.intent.args ?? {});
31
- return { id: e.id, name: e.name, tool, argsHash, result: receipt.value, session: e.session };
32
- });
33
- }
34
- /** The effects a continuation must not dispatch again: every effect whose outcome is unknown, by the name and argument
35
- * hash its admission recorded, and by the external call it was admitted for when the journal holds one. A call the
36
- * continuation's own tools make is matched by `reuseReceipts` on either key. A session effect's name and hash are
37
- * already a tool's name and the hash of its arguments. A tool effect the driver admitted for a workflow node is named
38
- * by the node's label and hashed over the node's whole invocation, so it is matched by its intent (the tool and the
39
- * hash of its arguments, keyed as `gatewayIntentOf` keys a call); one a journal admitted before intents were recorded
40
- * has none, and is matched by name and hash only. */
41
- export function inheritableUnknowns(effects) {
42
- return effects.filter((e) => e.status === "unknown").map((e) => ({ id: e.id, name: e.name, argsHash: e.argsHash, session: e.session,
43
- ...(e.intent ? { intent: { tool: e.intent.tool, argsHash: e.intent.argsHash } } : {}) }));
44
- }
45
22
  /** The external call a model tool call stands for: the gateway tool and the hash of its arguments. Only a `fetch`
46
23
  * wrapper names the gateway tool in its arguments; every other tool is its own name, whatever its arguments look like.
47
24
  * The same key is computed for an effect from its receipt's intent. */
@@ -8,12 +8,8 @@ export { openJournal, type JournalBackend, type JournalRecord } from "./journal.
8
8
  export { RecoveryError, asRecoveryError, isRecoveryError, runStopOf, runStoppedError } from "./errors.js";
9
9
  export { bindingDigests, bindingMismatch, LEDGER_FORMAT } from "./binding.js";
10
10
  export { canonicalHash, canonicalSha256 } from "./canonical-hash.js";
11
- export { callKey, heldCallKey, CALL_KEY_BYTES } from "./call-key.js";
11
+ export { callKey, CALL_KEY_BYTES } from "./call-key.js";
12
12
  export { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, DECISION_REQUEST, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, stateDelta, applyStateDelta, itemState, partialResults, canonicalJson, frozenStepSessionId, frozenStepId, frozenEffectId, frozenEffectPath, admitFrozenStep, closeFrozenStepAttempt, frozenStop, type FrozenSnapshot, type FrozenSnapshotV4, type ItemRecord, type MapEntry, type StateDelta, type Sha256, type PartialSlot, type PathFrame, type RouteDecision, type DecisionRequest, type QuestionReceipts, type FrameTag, type StepRecord, type EscalationRow, type FrozenShape, } from "./frozen-snapshot.js";
13
13
  export { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, pathSegments, topLevelCompletion } from "./execution-path.js";
14
- export { TypedEffectFailure, EffectEnvelopeFailure, classifyEffectFailure } from "./effect-failure.js";
15
14
  export { effectRetryClass, transportFactOf, type TransportFact } from "./transport-facts.js";
16
- export { buildHandoff, handoffFirstTurn, type Handoff, type HandoffOptions } from "./handoff.js";
17
- export { gatewayIntentOf, inheritableReceipts, inheritableUnknowns, returnedFailure, type InheritedReceipt, type InheritedUnknown } from "./handoff-receipts.js";
18
- export { inputProvenance, judgedRecords, type InputProvenance } from "./handoff-files.js";
19
- export { type InheritedSession, type InheritedEffect, type TranscriptMessage } from "./handoff-digest.js";
15
+ export { gatewayIntentOf, returnedFailure, type InheritedReceipt, type InheritedUnknown } from "./handoff-receipts.js";
@@ -7,11 +7,8 @@ export { openJournal } from "./journal.js";
7
7
  export { RecoveryError, asRecoveryError, isRecoveryError, runStopOf, runStoppedError } from "./errors.js";
8
8
  export { bindingDigests, bindingMismatch, LEDGER_FORMAT } from "./binding.js";
9
9
  export { canonicalHash, canonicalSha256 } from "./canonical-hash.js";
10
- export { callKey, heldCallKey, CALL_KEY_BYTES } from "./call-key.js";
10
+ export { callKey, CALL_KEY_BYTES } from "./call-key.js";
11
11
  export { FROZEN_SNAPSHOT_SCHEMA, FROZEN_SNAPSHOT_SCHEMA_V4, DECISION_REQUEST, validateFrozenSnapshot, openedFrozenSnapshot, serializeFrozenSnapshot, emptyPathFrame, stateDelta, applyStateDelta, itemState, partialResults, canonicalJson, frozenStepSessionId, frozenStepId, frozenEffectId, frozenEffectPath, admitFrozenStep, closeFrozenStepAttempt, frozenStop, } from "./frozen-snapshot.js";
12
12
  export { chainStep, childrenOf, completedIteration, enclosingChains, enclosingIterations, isWithin, mapItemOf, nodeAt, pathSegments, topLevelCompletion } from "./execution-path.js";
13
- export { TypedEffectFailure, EffectEnvelopeFailure, classifyEffectFailure } from "./effect-failure.js";
14
13
  export { effectRetryClass, transportFactOf } from "./transport-facts.js";
15
- export { buildHandoff, handoffFirstTurn } from "./handoff.js";
16
- export { gatewayIntentOf, inheritableReceipts, inheritableUnknowns, returnedFailure } from "./handoff-receipts.js";
17
- export { inputProvenance, judgedRecords } from "./handoff-files.js";
14
+ export { gatewayIntentOf, returnedFailure } from "./handoff-receipts.js";
@@ -68,8 +68,10 @@ export function withRecovery(driver, deps, options = {}) {
68
68
  throw error;
69
69
  }
70
70
  // A cut call (a cancel, the run's failure) has no outcome: a later open finds it asked and unanswered. A call
71
- // that ended on its own failed, and the next process asks again.
72
- if (!driver.signal.aborted && !params.signal?.aborted)
71
+ // that ended on its own failed, and the next process asks again; so does one that never left (`unsent`, a host's
72
+ // refusal before it sent anything), whatever stopped the run meanwhile: nothing went out to answer.
73
+ const unsent = error instanceof DecisionProviderError && error.unsent === true;
74
+ if (unsent || (!driver.signal.aborted && !params.signal?.aborted))
73
75
  driver.decisionEnded(params.executionPath, decisionId, "failed", null);
74
76
  throw error;
75
77
  }
@@ -65,7 +65,6 @@ export declare const SYSTEM_ONE_LIMITS: {
65
65
  readonly minScoreLevels: 2;
66
66
  readonly maxScoreLevels: 10;
67
67
  };
68
- export declare const SYSTEM_ONE_DEFAULT_MODEL = "jev-latest";
69
68
  export type CompiledQuestions = Record<string, SystemOneQuestion>;
70
69
  export declare function compileQuestions(schema: Record<string, unknown>, definitions?: Record<string, unknown>): {
71
70
  ok: true;
@@ -1,5 +1,4 @@
1
1
  export const SYSTEM_ONE_LIMITS = { maxChoiceOptions: 240, minScoreLevels: 2, maxScoreLevels: 10 };
2
- export const SYSTEM_ONE_DEFAULT_MODEL = "jev-latest";
3
2
  const CRITERIA = "criteria";
4
3
  export function compileQuestions(schema, definitions = {}) {
5
4
  const errors = [];
@@ -320,7 +320,6 @@ export type ArtifactState = {
320
320
  };
321
321
  export declare function artifactNodeIsProse(node: ArtifactNode): boolean;
322
322
  export declare function desugarWorkflow(workflow: Workflow): Workflow;
323
- export declare function terminalArtifactType(workflow: Workflow): string | null;
324
323
  /** A predicate a `call` evaluates against ITS OWN RESULT: paths are result-relative. */
325
324
  export type CallPredicate = MechanicalPredicate;
326
325
  export type PollClause = {
@@ -667,14 +666,6 @@ export declare class EffectFailure extends Error {
667
666
  cause?: unknown;
668
667
  });
669
668
  }
670
- export declare function parseCsvRows(text: string): string[][];
671
- export declare function buildReferenceContext(files: Record<string, string>): {
672
- references: Record<string, string>;
673
- references_parsed: Record<string, {
674
- header: string[];
675
- rows: string[][];
676
- }>;
677
- };
678
669
  export declare function normalizeStringNullsForSchema(value: unknown, schema: Record<string, unknown> | undefined, depth?: number, root?: Record<string, unknown> | undefined): unknown;
679
670
  export declare function workflowSha256(workflow: Workflow): string;
680
671
  /** Bound the complete document before any recursive schema or semantic traversal. Shared
package/dist/workflow.js CHANGED
@@ -44,13 +44,6 @@ export function desugarWorkflow(workflow) {
44
44
  return workflow;
45
45
  return { ...workflow, root: visit(workflow.root) };
46
46
  }
47
- export function terminalArtifactType(workflow) {
48
- const steps = workflow?.root?.node === "chain" ? workflow.root.steps || [] : [workflow?.root];
49
- const last = steps[steps.length - 1];
50
- if (!last || last.node !== "artifact")
51
- return null;
52
- return last.type;
53
- }
54
47
  export const SHELL_RESULT_SCHEMA = {
55
48
  type: "object",
56
49
  required: ["code", "stdout", "stderr"],
@@ -269,63 +262,6 @@ function resultPathMissing(shape, dotted) {
269
262
  }
270
263
  return false;
271
264
  }
272
- export function parseCsvRows(text) {
273
- const rows = [];
274
- let field = "", row = [], inQuotes = false;
275
- for (let i = 0; i < text.length; i += 1) {
276
- const ch = text[i];
277
- if (inQuotes) {
278
- if (ch === '"' && text[i + 1] === '"') {
279
- field += '"';
280
- i += 1;
281
- }
282
- else if (ch === '"')
283
- inQuotes = false;
284
- else
285
- field += ch;
286
- }
287
- else if (ch === '"')
288
- inQuotes = true;
289
- else if (ch === ",") {
290
- row.push(field);
291
- field = "";
292
- }
293
- else if (ch === "\n" || ch === "\r") {
294
- if (ch === "\r" && text[i + 1] === "\n")
295
- i += 1;
296
- row.push(field);
297
- field = "";
298
- if (row.some((c) => c.trim() !== ""))
299
- rows.push(row);
300
- row = [];
301
- }
302
- else
303
- field += ch;
304
- }
305
- if (field !== "" || row.length) {
306
- row.push(field);
307
- if (row.some((c) => c.trim() !== ""))
308
- rows.push(row);
309
- }
310
- return rows;
311
- }
312
- export function buildReferenceContext(files) {
313
- // Null prototypes: reference filenames are external data. On a plain object a name like
314
- // "__proto__" hits the prototype SETTER on assignment — the file silently vanishes from
315
- // the map (and worse shapes pollute it). A null-prototype object stores it as an ordinary
316
- // own key, so every filename round-trips.
317
- const references = Object.create(null);
318
- const referencesParsed = Object.create(null);
319
- for (const [name, body] of Object.entries(files)) {
320
- references[name] = body;
321
- if (name.toLowerCase().endsWith(".csv")) {
322
- const rows = parseCsvRows(body);
323
- if (rows.length)
324
- referencesParsed[name] = { header: rows[0], rows: rows.slice(1) };
325
- }
326
- }
327
- return { references, references_parsed: referencesParsed };
328
- }
329
265
  /** Whether a field's schema lists the value itself: its own `const`, or a member of its own `enum`, or the same in the
330
266
  * schema a local `$ref` names in the root schema's `definitions` or `$defs`, or in any `anyOf` or `oneOf` branch, at any
331
267
  * depth. A schema's own listed values count beside its `$ref`, never in place of it. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-dsl",
3
- "version": "0.1.0-beta.34",
3
+ "version": "0.1.0-beta.35",
4
4
  "description": "Composable, typed workflows for agents",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -47,7 +47,7 @@
47
47
  "skills"
48
48
  ],
49
49
  "engines": {
50
- "node": ">=24.11.0"
50
+ "node": ">=24.22.3"
51
51
  },
52
52
  "scripts": {
53
53
  "build": "tsc -p tsconfig.json",
@@ -1,34 +0,0 @@
1
- import { EffectFailure, type CallRetryClass, type EffectFailureCode } from "../workflow.js";
2
- /** A failed effect: its closed code, the prose for the reader, and what the host observed
3
- * (`detail`: the deadline, the elapsed time, the output tail, the filed output) which the
4
- * interpreter writes onto the attempt's `effect.failed` event. The retry class is the transport's
5
- * when it gave one, else the code's. */
6
- export declare class TypedEffectFailure extends EffectFailure {
7
- readonly code: EffectFailureCode;
8
- constructor(code: EffectFailureCode, message: string, options?: {
9
- detail?: Record<string, unknown>;
10
- cause?: unknown;
11
- retryClass?: CallRetryClass | null;
12
- });
13
- }
14
- /** A dispatch that succeeded around a failed tool: the transport answered with the tool's own failure
15
- * envelope as its text. The envelope is the effect's failure, never its result. */
16
- export declare class EffectEnvelopeFailure extends Error {
17
- readonly tool: string;
18
- readonly envelope: string;
19
- constructor(tool: string, envelope: string);
20
- }
21
- /** A thrown error at an effect boundary, as a TypedEffectFailure. A TypedEffectFailure passes through; a
22
- * tool the host did not grant (`notGranted` names it) is effect_not_granted; an unknown transport
23
- * (`via` outside the interpreter's list) is effect_unknown_transport; a tool's failure envelope is
24
- * effect_transport; otherwise the error's typed transport facts decide: a deadline (a TimeoutError, an
25
- * AbortError, a 408, an idle cut, a timed-out connect) is effect_timeout, any other typed fact (a
26
- * status, a system code, an error class) is effect_transport with the retry class those facts earn
27
- * (effectRetryClass), and an error with no typed fact came through no transport that can be named:
28
- * effect_unknown_transport. The message is carried for the reader and never read. */
29
- export declare function classifyEffectFailure(error: unknown, at: {
30
- label: string;
31
- via: string;
32
- }, options?: {
33
- notGranted?: (error: unknown) => string | undefined;
34
- }): TypedEffectFailure;
@@ -1,62 +0,0 @@
1
- // An effect's failure, typed at every boundary. Every failure carries one closed code (EFFECT_FAILURE_CODES, the
2
- // interpreter's list, which `retry.on` names); the prose stays beside it as `message`, for the reader,
3
- // and is never the discriminator. This module holds the class a host's effect adapters throw, and the one
4
- // classifier that maps a thrown transport error to a code from its typed facts (the error's class, its
5
- // HTTP status, its system code), never from its text.
6
- import { CALL_TRANSPORTS } from "../vocabulary.js";
7
- import { EffectFailure } from "../workflow.js";
8
- import { effectRetryClass, transportFactOf } from "./transport-facts.js";
9
- /** The retry class a code implies when the failure's transport facts name none: a deadline is a
10
- * timeout and a non-zero exit is an exit, the two the interpreter's default retry list names; every
11
- * other code is not transient by nature. */
12
- const IMPLIED_RETRY_CLASS = { effect_timeout: "timeout", effect_exit: "exit" };
13
- /** A failed effect: its closed code, the prose for the reader, and what the host observed
14
- * (`detail`: the deadline, the elapsed time, the output tail, the filed output) which the
15
- * interpreter writes onto the attempt's `effect.failed` event. The retry class is the transport's
16
- * when it gave one, else the code's. */
17
- export class TypedEffectFailure extends EffectFailure {
18
- constructor(code, message, options = {}) {
19
- super(message, options.retryClass !== undefined ? options.retryClass : IMPLIED_RETRY_CLASS[code] ?? null, {
20
- code, ...(options.detail ? { detail: options.detail } : {}), ...(options.cause !== undefined ? { cause: options.cause } : {}),
21
- });
22
- }
23
- }
24
- /** A dispatch that succeeded around a failed tool: the transport answered with the tool's own failure
25
- * envelope as its text. The envelope is the effect's failure, never its result. */
26
- export class EffectEnvelopeFailure extends Error {
27
- tool;
28
- envelope;
29
- constructor(tool, envelope) {
30
- super(`tool "${tool}" returned a failure: ${envelope.slice(0, 500)}`);
31
- this.tool = tool;
32
- this.envelope = envelope;
33
- this.name = "EffectEnvelopeFailure";
34
- }
35
- }
36
- /** A thrown error at an effect boundary, as a TypedEffectFailure. A TypedEffectFailure passes through; a
37
- * tool the host did not grant (`notGranted` names it) is effect_not_granted; an unknown transport
38
- * (`via` outside the interpreter's list) is effect_unknown_transport; a tool's failure envelope is
39
- * effect_transport; otherwise the error's typed transport facts decide: a deadline (a TimeoutError, an
40
- * AbortError, a 408, an idle cut, a timed-out connect) is effect_timeout, any other typed fact (a
41
- * status, a system code, an error class) is effect_transport with the retry class those facts earn
42
- * (effectRetryClass), and an error with no typed fact came through no transport that can be named:
43
- * effect_unknown_transport. The message is carried for the reader and never read. */
44
- export function classifyEffectFailure(error, at, options = {}) {
45
- if (error instanceof TypedEffectFailure)
46
- return error;
47
- const text = error instanceof Error ? error.message : String(error);
48
- const message = `call node "${at.label}": ${text.slice(0, 500)}`;
49
- const refused = options.notGranted?.(error);
50
- if (refused !== undefined)
51
- return new TypedEffectFailure("effect_not_granted", message, { cause: error, detail: { tool: refused } });
52
- if (!CALL_TRANSPORTS.includes(at.via))
53
- return new TypedEffectFailure("effect_unknown_transport", message, { cause: error, detail: { transport: at.via } });
54
- if (error instanceof EffectEnvelopeFailure)
55
- return new TypedEffectFailure("effect_transport", message, { cause: error, retryClass: null });
56
- const fact = transportFactOf(error);
57
- const retryClass = effectRetryClass(fact);
58
- if (retryClass === "timeout" || fact.errorName === "AbortError")
59
- return new TypedEffectFailure("effect_timeout", message, { cause: error, retryClass });
60
- const typed = fact.status !== undefined || fact.causeCode !== undefined || fact.errorName !== undefined || fact.providerType !== undefined || fact.providerCode !== undefined;
61
- return new TypedEffectFailure(typed ? "effect_transport" : "effect_unknown_transport", message, { cause: error, retryClass });
62
- }
@@ -1,36 +0,0 @@
1
- import { type InputProvenance } from "./handoff-files.js";
2
- /** What the block says of the escalation. */
3
- export type HandoffBlockInput = {
4
- kind: string;
5
- stage: string;
6
- summary: string;
7
- step_label?: string | null;
8
- step_exec_id?: string | null;
9
- state?: Record<string, unknown> | null;
10
- workflow_sha_used?: string | null;
11
- cost_usd?: number | null;
12
- evidence_dir?: string | null;
13
- /** Where the attempt's report.md was moved, when one existed. */
14
- report_path?: string | null;
15
- /** Workspace-relative paths the attempt's files were written to. */
16
- files?: readonly string[] | null;
17
- /** Where each input the attempt started from came from, and its form. */
18
- inputs?: readonly InputProvenance[] | null;
19
- /** The host's sizes for the continuation, stated as one line. */
20
- budget?: {
21
- max_tool_calls?: number;
22
- max_seconds?: number;
23
- } | null;
24
- };
25
- /** The state at the gate is rendered whole up to this size; beyond it the block points at state.json. */
26
- export declare const STATE_LIMIT: number;
27
- /** Strings above the limit become a prefix plus a marker with the omitted length; nested values recurse. */
28
- export declare function boundedValue(value: unknown, limit?: number): unknown;
29
- /** One line per completed output in the state: the key the workflow wrote and the shape it holds. */
30
- export declare function stateShapes(state: Record<string, unknown> | null | undefined): string[];
31
- /** The one line that states the host's sizes for the continuation, or "" when the host sent none. */
32
- export declare function escalationBudgetLine(budget: HandoffBlockInput["budget"]): string;
33
- /** The block the continuation reads first. Deterministic for a given row; policy-agnostic. The reason is the
34
- * workflow's own text, whole; the state at the gate is whole up to STATE_LIMIT, and beyond it the
35
- * block points at the file that holds it. */
36
- export declare function escalationContextBlock(context: HandoffBlockInput): string;
@@ -1,148 +0,0 @@
1
- import path from "node:path";
2
- import { redactSensitiveValue, redactText } from "./handoff-redact.js";
3
- import { HANDOFF_FILES_DIR } from "./handoff-files.js";
4
- const VALUE_LIMIT = 400;
5
- const ARRAY_LIMIT = 20;
6
- /** The state at the gate is rendered whole up to this size; beyond it the block points at state.json. */
7
- export const STATE_LIMIT = 48 * 1024;
8
- /** The Files section lists this many paths, then counts the rest by directory. */
9
- const FILES_LIST_LIMIT = 200;
10
- const SHAPES_LIMIT = 3 * 1024;
11
- const SHAPE_LINE_LIMIT = 160;
12
- /** Strings above the limit become a prefix plus a marker with the omitted length; nested values recurse. */
13
- export function boundedValue(value, limit = VALUE_LIMIT) {
14
- if (typeof value === "string")
15
- return value.length > limit ? `${value.slice(0, limit)}<${value.length - limit} more chars>` : value;
16
- if (Array.isArray(value)) {
17
- const head = value.slice(0, ARRAY_LIMIT).map(v => boundedValue(v, limit));
18
- return value.length > ARRAY_LIMIT ? [...head, `<${value.length - ARRAY_LIMIT} more items>`] : head;
19
- }
20
- if (value && typeof value === "object")
21
- return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, boundedValue(v, limit)]));
22
- return value;
23
- }
24
- /** One line per completed output in the state: the key the workflow wrote and the shape it holds. */
25
- export function stateShapes(state) {
26
- if (!state || typeof state !== "object")
27
- return [];
28
- return Object.entries(state).map(([key, value]) => {
29
- let line;
30
- if (value === null || value === undefined)
31
- line = `- ${key}: empty`;
32
- else if (Array.isArray(value))
33
- line = `- ${key}: array of ${value.length}`;
34
- else if (typeof value === "object") {
35
- const keys = Object.keys(value);
36
- line = `- ${key}: object {${keys.slice(0, 12).join(", ")}${keys.length > 12 ? ", …" : ""}}`;
37
- }
38
- else if (typeof value === "string")
39
- line = `- ${key}: string (${value.length} chars)`;
40
- else
41
- line = `- ${key}: ${typeof value}`;
42
- return line.length > SHAPE_LINE_LIMIT ? `${line.slice(0, SHAPE_LINE_LIMIT)}…` : line;
43
- });
44
- }
45
- /** The shapes section under its own budget: whole lines until the budget is spent, then a count. */
46
- function shapesSection(shapes, budget) {
47
- if (!shapes.length)
48
- return ["- none"];
49
- const kept = [];
50
- let used = 0;
51
- for (const line of shapes) {
52
- if (used + line.length + 1 > budget)
53
- break;
54
- kept.push(line);
55
- used += line.length + 1;
56
- }
57
- if (kept.length < shapes.length)
58
- kept.push(`- …and ${shapes.length - kept.length} more keys (${shapes.length} in total)`);
59
- return kept;
60
- }
61
- /** The block lists this many inputs, then counts the rest; inputs.json lists every one. */
62
- const INPUT_LINE_LIMIT = 100;
63
- const INPUT_VALUE_LIMIT = 200;
64
- /** The inputs section: one line per input, its path, its form and its value (a long value by size). */
65
- function inputsSection(inputs, filed) {
66
- if (!inputs?.length)
67
- return [];
68
- const label = (form) => form === "email" ? "identifier (email address)" : form === "url" ? "identifier (URL)" : form === "text" ? "typed text" : form;
69
- return ["", `Inputs the run started from, as the dispatch carried them (path: form: value)${filed ? `; whole in \`${HANDOFF_FILES_DIR}/inputs.json\`` : ""}. An identifier is a value of a fixed form a source can be matched on; typed text is what was written in:`,
70
- ...inputs.slice(0, INPUT_LINE_LIMIT).map((input) => `- ${input.path}: ${label(input.form)}: ${input.value.length > INPUT_VALUE_LIMIT ? `(${input.value.length} chars)` : input.value.replace(/\s+/g, " ")}`),
71
- ...(inputs.length > INPUT_LINE_LIMIT ? [`- …${inputs.length - INPUT_LINE_LIMIT} more inputs (${inputs.length} in total)${filed ? `, each with its path and form in \`${HANDOFF_FILES_DIR}/inputs.json\`` : ""}`] : [])];
72
- }
73
- /** The one line that states the host's sizes for the continuation, or "" when the host sent none. */
74
- export function escalationBudgetLine(budget) {
75
- if (!budget)
76
- return "";
77
- const sizes = [
78
- ...(budget.max_tool_calls !== undefined ? [`${budget.max_tool_calls} external tool calls`] : []),
79
- ...(budget.max_seconds !== undefined ? [`${budget.max_seconds} seconds`] : []),
80
- ];
81
- return sizes.length ? `Budget for this continuation (set by the host): ${sizes.join(" and ")}.` : "";
82
- }
83
- /** The Files section: every path the attempt left for the continuation. */
84
- function filesSection(context) {
85
- const frozen = [...(context.files ?? [])];
86
- const lines = [];
87
- const described = {
88
- [`${HANDOFF_FILES_DIR}/state.json`]: "the workflow state at the gate, whole",
89
- [`${HANDOFF_FILES_DIR}/gate.json`]: "the gate: kind, stage, step, reason, its state and every committed route decision",
90
- [`${HANDOFF_FILES_DIR}/inputs.json`]: "the inputs the frozen attempt started from, with each one's path and form",
91
- };
92
- const shown = frozen.slice(0, FILES_LIST_LIMIT);
93
- for (const file of shown)
94
- lines.push(`- ${file}${described[file] ? `: ${described[file]}` : ""}`);
95
- if (frozen.length > shown.length) {
96
- const rest = new Map();
97
- for (const file of frozen.slice(shown.length)) {
98
- const dir = path.posix.dirname(file);
99
- rest.set(dir, (rest.get(dir) ?? 0) + 1);
100
- }
101
- for (const [dir, count] of rest)
102
- lines.push(`- …${count} more under ${dir}/`);
103
- }
104
- if (!lines.length)
105
- return [];
106
- const items = frozen.some((file) => file.startsWith(`${HANDOFF_FILES_DIR}/items/`));
107
- const effects = frozen.some((file) => file.startsWith(`${HANDOFF_FILES_DIR}/effects/`));
108
- return ["", "Files the frozen attempt left in the workspace (read them; they are whole where this text is not):",
109
- ...(items ? [`Each file under ${HANDOFF_FILES_DIR}/items/ is one record the workflow judged, with its text and its scores.`] : []),
110
- ...(effects ? [`Each file under ${HANDOFF_FILES_DIR}/effects/ is one paid call: its arguments and its full result.`] : []),
111
- ...lines];
112
- }
113
- /** The block the continuation reads first. Deterministic for a given row; policy-agnostic. The reason is the
114
- * workflow's own text, whole; the state at the gate is whole up to STATE_LIMIT, and beyond it the
115
- * block points at the file that holds it. */
116
- export function escalationContextBlock(context) {
117
- const step = context.step_label ?? context.stage;
118
- const summary = redactText(String(context.summary || "").trim()) || "(no summary recorded)";
119
- const budget = escalationBudgetLine(context.budget);
120
- const header = [
121
- "## YOU ARE CONTINUING A RUN THAT ESCALATED",
122
- "",
123
- `A reviewed workflow${context.workflow_sha_used ? ` (${String(context.workflow_sha_used).slice(0, 12)})` : ""} ran first and stopped at step \`${step}\`${context.step_exec_id ? ` (execution ${context.step_exec_id})` : ""}: ${context.kind}${context.stage && context.stage !== step ? ` at stage ${context.stage}` : ""}.`,
124
- "",
125
- "Why it stopped:",
126
- summary,
127
- ...(budget ? ["", budget] : []),
128
- "",
129
- ];
130
- const footer = [
131
- "",
132
- ...(context.evidence_dir ? [`Evidence gathered so far is under \`${context.evidence_dir}\`.`] : []),
133
- ...(context.report_path ? [`The frozen attempt's report was moved to \`${context.report_path}\`.`] : []),
134
- ...(typeof context.cost_usd === "number"
135
- ? [`The frozen attempt spent $${context.cost_usd.toFixed(4)}.`]
136
- : []),
137
- "",
138
- "Continue the job from this state. Do not redo completed work; build on it. When you explain what happened, cite this escalation (its step and reason) rather than inventing a cause.",
139
- ];
140
- const shapes = shapesSection(stateShapes(context.state), SHAPES_LIMIT);
141
- const stateFile = (context.files ?? []).includes(`${HANDOFF_FILES_DIR}/state.json`) ? `${HANDOFF_FILES_DIR}/state.json` : null;
142
- const stateJson = JSON.stringify(redactSensitiveValue(context.state ?? {}), null, 2);
143
- const state = stateJson.length <= STATE_LIMIT
144
- ? ["", `State at the gate (whole${stateFile ? `; also in \`${stateFile}\`` : ""}):`, "```json", stateJson, "```"]
145
- : ["", `State body is ${stateJson.length} chars (${Object.keys(context.state ?? {}).length} keys), beyond what this text carries; ${stateFile ? `read it whole in \`${stateFile}\`` : "the list above names every key with its type and size"}.`];
146
- const filedInputs = (context.files ?? []).includes(`${HANDOFF_FILES_DIR}/inputs.json`);
147
- return redactText([...header, "Completed outputs it left in the workflow state (do not redo this work):", ...shapes, ...state, ...inputsSection(context.inputs, filedInputs), ...filesSection(context), ...footer].join("\n"));
148
- }
@@ -1,58 +0,0 @@
1
- /** One step's transcript message, as a host's reader returns it. */
2
- export type TranscriptMessage = {
3
- role: "user" | "assistant" | "toolResult";
4
- content?: unknown;
5
- toolCallId?: string;
6
- toolName?: string;
7
- isError?: boolean;
8
- stopReason?: string;
9
- };
10
- export declare const DIGEST_STEP_LIMIT: number;
11
- export declare const DIGEST_LIMIT: number;
12
- /** A step's spend: `usd` is a floor when `state` is `partial` and unknown when null; a spend recorded without a state
13
- * (a recorded trace's `session.spent` row) is complete. */
14
- export type InheritedSession = {
15
- id: string;
16
- role: string;
17
- state: string;
18
- file: string | null;
19
- spend?: {
20
- usd: number | null;
21
- turns: number;
22
- state?: "complete" | "partial" | "unavailable";
23
- toolCalls?: number;
24
- };
25
- };
26
- export type InheritedEffect = {
27
- id: string;
28
- name: string;
29
- status: string;
30
- session?: string | null;
31
- result?: unknown;
32
- };
33
- export type InheritedJob = {
34
- runId: string;
35
- /** A step's transcript by its session id (the run's durable file holds them), or null when there is none. */
36
- transcriptOf: (sessionId: string) => readonly TranscriptMessage[] | null;
37
- cwd: string;
38
- evidenceDir?: string | null;
39
- sessions: InheritedSession[];
40
- effects: InheritedEffect[];
41
- /** Workspace-relative produced files with the sha256 the driver committed for them. */
42
- files: Record<string, string>;
43
- /** The file writeHandoffFiles wrote each effect's whole receipt to, by effect id. */
44
- effectFiles?: Record<string, string>;
45
- };
46
- /** The label a step's identity carries, distinct for every session the frozen driver admits. A step's
47
- * session is `<run>:<label>:<step|adapt>:<execution path>:a<attempt>` (the label as the
48
- * interpreter names the node: a child's step `invocation/step`, a plan's `adapt:<gate>/step`, and a
49
- * label may hold colons), read as the label with each map item index its path runs under as `[k]` and
50
- * each loop iteration as `#k`. */
51
- export declare function stepLabelOf(runId: string, sessionId: string): string | null;
52
- /** One completed LLM step, from its transcript (`transcriptOf`): what it was asked, what it called, what it concluded and
53
- * what it submitted. Bounded per step; a step whose transcript is absent or unreadable says so. */
54
- export declare function stepDigest(runId: string, session: InheritedSession, transcriptOf: (sessionId: string) => readonly TranscriptMessage[] | null): string;
55
- /** The digest the continuation reads after the escalation block: the completed
56
- * LLM steps' transcripts, the evidence gathered, the files produced with their receipts, and the
57
- * one rule that this is a continuation. Deterministic for a given ledger and workspace. */
58
- export declare function inheritedJobDigest(job: InheritedJob): string;
@@ -1,195 +0,0 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- import { redactSensitiveValue, redactText } from "./handoff-redact.js";
4
- import { HANDOFF_FILES_DIR } from "./handoff-files.js";
5
- import { boundedValue } from "./handoff-block.js";
6
- export const DIGEST_STEP_LIMIT = 3 * 1024;
7
- export const DIGEST_LIMIT = 24 * 1024;
8
- const DIGEST_ARGS_LIMIT = 240;
9
- const DIGEST_RESULT_LIMIT = 160;
10
- const DIGEST_TEXT_LIMIT = 600;
11
- const DIGEST_LIST_LIMIT = 40;
12
- const spendText = (spend) => spend.usd === null ? "cost unknown" : spend.state === "partial" ? `at least $${spend.usd.toFixed(4)}, some cost unknown` : `$${spend.usd.toFixed(4)}`;
13
- /** The label a step's identity carries, distinct for every session the frozen driver admits. A step's
14
- * session is `<run>:<label>:<step|adapt>:<execution path>:a<attempt>` (the label as the
15
- * interpreter names the node: a child's step `invocation/step`, a plan's `adapt:<gate>/step`, and a
16
- * label may hold colons), read as the label with each map item index its path runs under as `[k]` and
17
- * each loop iteration as `#k`. */
18
- export function stepLabelOf(runId, sessionId) {
19
- if (!sessionId.startsWith(`${runId}:`))
20
- return null;
21
- const match = /^(.+):(?:step|adapt):(\/root(?:\/.*)?):a\d+$/.exec(sessionId.slice(runId.length + 1));
22
- if (!match)
23
- return null;
24
- const [, label, at] = match;
25
- const marks = [...at.matchAll(/\/(items|iterations)\/(\d+)\/body(?=\/|$)/g)].map(([, kind, index]) => kind === "items" ? `[${index}]` : `#${index}`);
26
- return `${label}${marks.join("")}`;
27
- }
28
- const oneLine = (value, limit) => {
29
- const safe = redactSensitiveValue(value);
30
- const text = typeof safe === "string" ? safe : JSON.stringify(safe);
31
- const flat = String(text ?? "").replace(/\s+/g, " ").trim();
32
- return flat.length > limit ? `${flat.slice(0, limit)}<${flat.length - limit} more chars>` : flat;
33
- };
34
- const textOf = (content) => Array.isArray(content)
35
- ? content.filter((c) => c?.type === "text" && typeof c.text === "string").map((c) => c.text).join("\n")
36
- : typeof content === "string" ? content : "";
37
- /** One completed LLM step, from its transcript (`transcriptOf`): what it was asked, what it called, what it concluded and
38
- * what it submitted. Bounded per step; a step whose transcript is absent or unreadable says so. */
39
- export function stepDigest(runId, session, transcriptOf) {
40
- const label = stepLabelOf(runId, session.id) ?? session.id;
41
- const head = `### Step \`${label}\` (${session.state}${session.spend ? `, ${session.spend.turns} turn${session.spend.turns === 1 ? "" : "s"}, ${spendText(session.spend)}` : ""})`;
42
- let messages;
43
- try {
44
- messages = transcriptOf(session.id);
45
- }
46
- catch {
47
- return `${head}\n- transcript unreadable`;
48
- }
49
- if (!messages)
50
- return `${head}\n- transcript unavailable`;
51
- const lines = [head];
52
- const firstUser = messages.find(m => m.role === "user");
53
- if (firstUser)
54
- lines.push(`- asked: ${oneLine(textOf(firstUser.content), DIGEST_TEXT_LIMIT)}`);
55
- const results = new Map();
56
- for (const m of messages)
57
- if (m.role === "toolResult" && m.toolCallId)
58
- results.set(m.toolCallId, m);
59
- let submission;
60
- let lastText = "";
61
- const calls = [];
62
- for (const m of messages) {
63
- if (m.role !== "assistant" || !Array.isArray(m.content))
64
- continue;
65
- for (const block of m.content) {
66
- if (block?.type === "toolCall") {
67
- if (block.name === "submit") {
68
- submission = block.arguments;
69
- continue;
70
- }
71
- const result = results.get(block.id);
72
- const outcome = result ? (result.isError ? "error" : "ok") + (textOf(result.content) ? `: ${oneLine(textOf(result.content), DIGEST_RESULT_LIMIT)}` : "") : "no result";
73
- calls.push(`- called ${block.name}(${oneLine(block.arguments ?? {}, DIGEST_ARGS_LIMIT)}) → ${outcome}`);
74
- }
75
- else if (block?.type === "text" && typeof block.text === "string" && block.text.trim())
76
- lastText = block.text;
77
- }
78
- }
79
- const callLines = calls.length > DIGEST_LIST_LIMIT ? [...calls.slice(0, DIGEST_LIST_LIMIT), `- …${calls.length - DIGEST_LIST_LIMIT} more calls`] : calls;
80
- lines.push(...callLines);
81
- // Only what the step said and did crosses the boundary; its private reasoning never does.
82
- if (lastText)
83
- lines.push(`- concluded: ${oneLine(lastText, DIGEST_TEXT_LIMIT)}`);
84
- else
85
- lines.push("- ended without a text conclusion");
86
- if (submission !== undefined)
87
- lines.push(`- submitted: ${oneLine(boundedValue(submission), DIGEST_TEXT_LIMIT * 2)}`);
88
- // The step's own budget: whole lines, then a count. The head is never dropped.
89
- const kept = [lines[0]];
90
- let used = lines[0].length;
91
- for (const line of lines.slice(1)) {
92
- if (used + line.length + 1 > DIGEST_STEP_LIMIT) {
93
- kept.push(`- …${lines.length - kept.length} more lines omitted`);
94
- break;
95
- }
96
- kept.push(line);
97
- used += line.length + 1;
98
- }
99
- return redactText(kept.join("\n"));
100
- }
101
- const listDir = (dir, limit, skip = new Set()) => {
102
- if (!dir || !fs.existsSync(dir))
103
- return [];
104
- const out = [];
105
- const walk = (current, prefix) => {
106
- let entries = [];
107
- try {
108
- entries = fs.readdirSync(current, { withFileTypes: true });
109
- }
110
- catch {
111
- return;
112
- }
113
- for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
114
- if (out.length >= limit)
115
- return;
116
- const full = path.join(current, entry.name);
117
- if (skip.has(`${prefix}${entry.name}`))
118
- continue;
119
- if (entry.isDirectory())
120
- walk(full, `${prefix}${entry.name}/`);
121
- else {
122
- let size = 0;
123
- try {
124
- size = fs.statSync(full).size;
125
- }
126
- catch { /* listed without size */ }
127
- out.push(`- ${redactText(`${prefix}${entry.name}`)} (${size} bytes)`);
128
- }
129
- }
130
- };
131
- walk(dir, "");
132
- return out;
133
- };
134
- /** The digest the continuation reads after the escalation block: the completed
135
- * LLM steps' transcripts, the evidence gathered, the files produced with their receipts, and the
136
- * one rule that this is a continuation. Deterministic for a given ledger and workspace. */
137
- export function inheritedJobDigest(job) {
138
- const steps = job.sessions
139
- .filter(s => s.role === "step" && stepLabelOf(job.runId, s.id))
140
- .map(s => stepDigest(job.runId, s, job.transcriptOf));
141
- // The frozen attempt's own files are listed by the escalation block; this lists what the steps gathered.
142
- const evidence = job.evidenceDir ? listDir(job.evidenceDir, DIGEST_LIST_LIMIT, new Set([path.posix.basename(HANDOFF_FILES_DIR)])) : [];
143
- const effectsBy = new Map(job.effects.filter(e => e.status === "completed").map(e => [e.id, e]));
144
- const fileEntries = Object.entries(job.files).sort(([a], [b]) => a.localeCompare(b));
145
- const files = fileEntries.slice(0, DIGEST_LIST_LIMIT).map(([file, sha]) => {
146
- let size = null;
147
- try {
148
- size = fs.statSync(path.join(job.cwd, file)).size;
149
- }
150
- catch { /* the receipt still names it */ }
151
- return `- ${redactText(file)}${size === null ? " (missing on disk)" : ` (${size} bytes)`} sha256 ${sha.slice(0, 12)}`;
152
- });
153
- if (fileEntries.length > DIGEST_LIST_LIMIT)
154
- files.push(`- …${fileEntries.length - DIGEST_LIST_LIMIT} more`);
155
- const paid = [...effectsBy.values()].filter(e => e.name !== "submit" && !["read", "write", "edit", "grep", "find", "bash"].includes(e.name));
156
- const header = ["## THE JOB AS IT STANDS (inherited from the frozen attempt)", ""];
157
- const footer = ["", "You are continuing this job, not restarting it. Everything listed above is done and paid for: use it, do not redo it, and cite it (step labels, file names) when you explain what you did."];
158
- const effectLine = (e) => `- ${e.name} [${e.id}] completed${e.result === undefined ? "" : ` → ${oneLine(e.result, DIGEST_RESULT_LIMIT)}`}${job.effectFiles?.[e.id] ? ` (whole: ${job.effectFiles[e.id]})` : ""}`;
159
- // Display order: steps, effects, files, evidence. Budget order: the cheap ledger facts first, the
160
- // transcripts take what is left. A section that does not fit keeps its heading and as many whole
161
- // lines as fit, then a count.
162
- const sections = {
163
- steps: ["### LLM steps run so far (their transcripts, bounded; a step that did not submit shows how it ended)", ...(steps.length ? steps : ["- none"])],
164
- effects: [`### Paid effects already made (${paid.length})`,
165
- ...(paid.length ? ["These tool calls already ran; their results are previewed below, whole in the file each line names, and in the state above. Calling the same tool again buys the same answer twice.", ...paid.slice(0, DIGEST_LIST_LIMIT).map(effectLine)] : ["- none"]),
166
- ...(paid.length > DIGEST_LIST_LIMIT ? [`- …${paid.length - DIGEST_LIST_LIMIT} more`] : [])],
167
- files: ["### Files produced in the workspace (with the driver's receipts)", ...(files.length ? files : ["- none"])],
168
- evidence: [`### Evidence directory${job.evidenceDir ? ` (\`${job.evidenceDir}\`)` : ""}`, ...(evidence.length ? evidence : ["- empty"])],
169
- };
170
- let budget = DIGEST_LIMIT - [...header, ...footer].join("\n").length;
171
- const rendered = {};
172
- for (const name of ["effects", "files", "evidence", "steps"]) {
173
- const section = sections[name];
174
- const text = section.join("\n");
175
- if (text.length + 2 <= budget) {
176
- rendered[name] = text;
177
- budget -= text.length + 2;
178
- continue;
179
- }
180
- const kept = [section[0]];
181
- let used = section[0].length;
182
- for (const line of section.slice(1)) {
183
- if (used + line.length + 1 > budget - 48)
184
- break;
185
- kept.push(line);
186
- used += line.length + 1;
187
- }
188
- if (kept.length < section.length)
189
- kept.push(`- …${section.length - kept.length} more entries omitted`);
190
- rendered[name] = kept.join("\n");
191
- budget -= rendered[name].length + 2;
192
- }
193
- const body = ["steps", "effects", "files", "evidence"].flatMap(name => [rendered[name], ""]);
194
- return redactText([...header, ...body, ...footer].join("\n"));
195
- }
@@ -1,54 +0,0 @@
1
- /** Where the attempt's files live, relative to the workspace. */
2
- export declare const HANDOFF_FILES_DIR = "evidence/frozen";
3
- export declare const WALK_DEPTH = 8;
4
- /** What the files record of the escalation. */
5
- export type HandoffRow = {
6
- kind: string;
7
- stage: string;
8
- summary: string;
9
- step_label?: string | null;
10
- state?: Record<string, unknown> | null;
11
- };
12
- /** The journal facts the files are written from. */
13
- export type HandoffMemo = {
14
- effects?: ReadonlyArray<{
15
- id: string;
16
- name: string;
17
- status: string;
18
- result?: unknown;
19
- }>;
20
- /** The committed route decisions (the judge's answer, whole), by execution path. */
21
- routes?: Record<string, unknown> | null;
22
- } | null | undefined;
23
- /** One input as the dispatch carried it: its path in the run's input and the form of its value. `email` and `url` are
24
- * values of a fixed form (an identifier a source can be matched on); `text` is anything else that was typed. Form only:
25
- * which claim weighs more is the workflow's call. */
26
- export type InputProvenance = {
27
- path: string;
28
- form: "email" | "url" | "text" | "number" | "boolean";
29
- value: string;
30
- };
31
- /** Every scalar leaf of the run's input with its path and form, in input order. */
32
- export declare function inputProvenance(input: unknown): InputProvenance[];
33
- /** Every record in the state that carries an `id` and sits in an array: the records a workflow judges.
34
- * Structural only: no field name but `id` is read. A record seen twice with the same bytes is one. */
35
- export declare function judgedRecords(state: unknown): Array<Record<string, unknown> & {
36
- id: string | number;
37
- }>;
38
- /** One judged record as Markdown: short scalars (its numbers, flags and labels) as a list, then each
39
- * long text and nested value whole under its own heading. A text that is JSON is pretty-printed. */
40
- export declare function renderJudgedRecord(record: Record<string, unknown>): string;
41
- /** The workspace-relative file an effect's receipt is written to. */
42
- export declare const handoffEffectFile: (effect: {
43
- id: string;
44
- name: string;
45
- }) => string;
46
- /** Write the attempt into `<cwd>/evidence/frozen/`: state.json (the state at the gate), gate.json
47
- * (the gate and every committed route decision), inputs.json (what the attempt started from), one
48
- * effects/<id>-<name>.json per completed effect (its arguments and its full result) and one
49
- * items/<id>.md per judged record. The directory is replaced whole. Returns the paths written,
50
- * workspace-relative, sorted, and the file each effect went to. */
51
- export declare function writeHandoffFiles(cwd: string, row: HandoffRow, memo: HandoffMemo, input?: unknown): Promise<{
52
- files: string[];
53
- effectFiles: Record<string, string>;
54
- }>;
@@ -1,162 +0,0 @@
1
- import fs from "node:fs";
2
- import path from "node:path";
3
- import { isCredentialKey, redactSensitiveValue } from "./handoff-redact.js";
4
- // The attempt as files: what the continuation reads instead of a bounded rendering. Written once, before the continuation
5
- // starts, from the escalation row and the journal's effects alone, so a resumed continuation rewrites the same bytes.
6
- // Every value is redacted (secret-named keys and credential patterns) before it is written.
7
- /** Where the attempt's files live, relative to the workspace. */
8
- export const HANDOFF_FILES_DIR = "evidence/frozen";
9
- /** At most this many judged records become item files; the rest stay in state.json. */
10
- const ITEM_FILE_LIMIT = 1000;
11
- const ITEM_INLINE_LIMIT = 200;
12
- export const WALK_DEPTH = 8;
13
- const EMAIL_FORM = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$/;
14
- const URL_FORM = /^https?:\/\/\S+$/i;
15
- /** Every scalar leaf of the run's input with its path and form, in input order. */
16
- export function inputProvenance(input) {
17
- const out = [];
18
- const walk = (value, at, depth) => {
19
- if (depth > WALK_DEPTH || value === null || value === undefined)
20
- return;
21
- if (Array.isArray(value)) {
22
- value.forEach((item, i) => walk(item, `${at}[${i}]`, depth + 1));
23
- return;
24
- }
25
- if (typeof value === "object") {
26
- for (const [key, item] of Object.entries(value)) {
27
- const here = at ? `${at}.${key}` : key;
28
- // A credential-named field is one input whose value is never copied, whatever it holds.
29
- if (isCredentialKey(key)) {
30
- if (item !== null && item !== undefined)
31
- out.push({ path: here, form: "text", value: "<redacted>" });
32
- continue;
33
- }
34
- walk(item, here, depth + 1);
35
- }
36
- return;
37
- }
38
- if (typeof value === "number" || typeof value === "boolean") {
39
- out.push({ path: at, form: typeof value, value: String(value) });
40
- return;
41
- }
42
- const text = String(value).trim();
43
- if (!text)
44
- return;
45
- out.push({ path: at, form: EMAIL_FORM.test(text) ? "email" : URL_FORM.test(text) ? "url" : "text", value: text });
46
- };
47
- walk(input, "", 0);
48
- return out;
49
- }
50
- const safeName = (value) => String(value).replace(/[^A-Za-z0-9._-]+/g, "_").replace(/^[._-]+/, "").slice(0, 96) || "_";
51
- const isRecordWithId = (value) => !!value && typeof value === "object" && !Array.isArray(value) && (typeof value.id === "string" || typeof value.id === "number") && String(value.id).trim() !== "";
52
- /** Every record in the state that carries an `id` and sits in an array: the records a workflow judges.
53
- * Structural only: no field name but `id` is read. A record seen twice with the same bytes is one. */
54
- export function judgedRecords(state) {
55
- const found = new Map();
56
- const order = [];
57
- const walk = (value, depth) => {
58
- if (depth > WALK_DEPTH || order.length >= ITEM_FILE_LIMIT)
59
- return;
60
- if (Array.isArray(value)) {
61
- for (const item of value) {
62
- if (isRecordWithId(item)) {
63
- const key = `${item.id}\u0000${JSON.stringify(item)}`;
64
- if (!found.has(key)) {
65
- found.set(key, item);
66
- order.push(item);
67
- }
68
- }
69
- walk(item, depth + 1);
70
- }
71
- }
72
- else if (value && typeof value === "object")
73
- for (const item of Object.values(value))
74
- walk(item, depth + 1);
75
- };
76
- walk(state, 0);
77
- return order.slice(0, ITEM_FILE_LIMIT);
78
- }
79
- /** One judged record as Markdown: short scalars (its numbers, flags and labels) as a list, then each
80
- * long text and nested value whole under its own heading. A text that is JSON is pretty-printed. */
81
- export function renderJudgedRecord(record) {
82
- const safe = redactSensitiveValue(record);
83
- const lines = [`# ${String(safe.id)}`, ""];
84
- const long = [];
85
- for (const [key, value] of Object.entries(safe)) {
86
- if (key === "id")
87
- continue;
88
- if (value === null || typeof value === "number" || typeof value === "boolean" || (typeof value === "string" && value.length <= ITEM_INLINE_LIMIT && !value.includes("\n"))) {
89
- lines.push(`- ${key}: ${value === null ? "null" : String(value)}`);
90
- }
91
- else
92
- long.push([key, value]);
93
- }
94
- for (const [key, value] of long) {
95
- lines.push("", `## ${key}`, "");
96
- if (typeof value === "string") {
97
- let parsed;
98
- const trimmed = value.trim();
99
- if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
100
- try {
101
- parsed = JSON.parse(trimmed);
102
- }
103
- catch { /* plain text */ }
104
- }
105
- lines.push(parsed !== undefined ? ["```json", JSON.stringify(redactSensitiveValue(parsed), null, 2), "```"].join("\n") : value);
106
- }
107
- else
108
- lines.push("```json", JSON.stringify(value, null, 2), "```");
109
- }
110
- return `${lines.join("\n")}\n`;
111
- }
112
- /** The workspace-relative file an effect's receipt is written to. */
113
- export const handoffEffectFile = (effect) => `${HANDOFF_FILES_DIR}/effects/${safeName(effect.id)}-${safeName(effect.name)}.json`;
114
- /** Write the attempt into `<cwd>/evidence/frozen/`: state.json (the state at the gate), gate.json
115
- * (the gate and every committed route decision), inputs.json (what the attempt started from), one
116
- * effects/<id>-<name>.json per completed effect (its arguments and its full result) and one
117
- * items/<id>.md per judged record. The directory is replaced whole. Returns the paths written,
118
- * workspace-relative, sorted, and the file each effect went to. */
119
- export async function writeHandoffFiles(cwd, row, memo, input) {
120
- const root = path.join(cwd, HANDOFF_FILES_DIR);
121
- await fs.promises.rm(root, { recursive: true, force: true });
122
- await fs.promises.mkdir(root, { recursive: true });
123
- const written = [];
124
- const effectFiles = {};
125
- const put = async (relative, body) => {
126
- const full = path.join(cwd, relative);
127
- await fs.promises.mkdir(path.dirname(full), { recursive: true });
128
- await fs.promises.writeFile(full, body);
129
- written.push(relative);
130
- };
131
- const json = (value) => `${JSON.stringify(redactSensitiveValue(value ?? null), null, 2)}\n`;
132
- const state = row.state ?? {};
133
- await put(`${HANDOFF_FILES_DIR}/state.json`, json(state));
134
- await put(`${HANDOFF_FILES_DIR}/gate.json`, json({ kind: row.kind, stage: row.stage, step_label: row.step_label ?? null, summary: row.summary, state_at_gate: state, routes: memo?.routes ?? {} }));
135
- if (input !== undefined)
136
- await put(`${HANDOFF_FILES_DIR}/inputs.json`, json({ input, provenance: inputProvenance(input) }));
137
- const taken = new Set();
138
- const unique = (file) => {
139
- let candidate = file;
140
- for (let n = 2; taken.has(candidate); n++)
141
- candidate = file.replace(/(\.[a-z]+)$/, `-${n}$1`);
142
- taken.add(candidate);
143
- return candidate;
144
- };
145
- for (const effect of memo?.effects ?? []) {
146
- // A completed effect whose answer the journal does not hold has no file: a file with no answer listed as the call's full
147
- // result would be a lie.
148
- if (effect.status !== "completed" || effect.result === undefined || effect.result === null)
149
- continue;
150
- const receipt = effect.result && typeof effect.result === "object" ? effect.result : null;
151
- const intent = receipt?.intent && typeof receipt.intent === "object" ? receipt.intent : null;
152
- const file = unique(handoffEffectFile(effect));
153
- effectFiles[effect.id] = file;
154
- await put(file, json({ id: effect.id, name: effect.name, ...(intent?.tool ? { tool: intent.tool } : {}),
155
- args: intent ? intent.args ?? null : receipt?.args ?? null,
156
- result: receipt && "value" in receipt ? receipt.value : effect.result ?? null,
157
- ...(receipt?.files && Object.keys(receipt.files).length ? { files: receipt.files } : {}) }));
158
- }
159
- for (const record of judgedRecords(state))
160
- await put(unique(`${HANDOFF_FILES_DIR}/items/${safeName(record.id)}.md`), renderJudgedRecord(record));
161
- return { files: written.sort(), effectFiles };
162
- }
@@ -1,12 +0,0 @@
1
- /** Whether a key names a credential, by the explicit lists above. */
2
- export declare function isCredentialKey(key: string): boolean;
3
- /** Credential-shaped substrings of any text, each replaced by `<redacted>`: an HTTP `Bearer` credential, an environment
4
- * assignment (`NAME=value`) whose name is a credential key, a URL's userinfo, a JWT, and the prefixed keys providers
5
- * issue (`sk-`, GitHub `gh?_` and `github_pat_`, Slack `xox?-`, AWS `AKIA`, Google `AIza`). A SHA-256 or any other
6
- * unprefixed digest is not a credential. */
7
- export declare function redactCredentialText(value: unknown): string;
8
- /** A value with every credential-named key's value and every credential-shaped string redacted, objects and arrays walked. */
9
- export declare function redactSensitiveValue(value: unknown): unknown;
10
- /** Every string that reaches a continuation's first turn passes here: values redacted object-aware first, then the
11
- * finished text once more by pattern, and an email address by its form. */
12
- export declare const redactText: (text: string) => string;
@@ -1,44 +0,0 @@
1
- // Credentials, not substrings. A value is redacted when its key names a credential or when the value has a credential's
2
- // shape. Key names are compared as words (split on `_`, `-`, spaces and camelCase, lowercased): a key names a credential
3
- // when any of its words is a credential word, or any two adjacent words are a credential pair. `input_tokens` is the
4
- // words [input, tokens]; `tokens` is a count's word, never the credential word `token`, so counts and limits survive
5
- // while `access_token`, `token_value` and `api_key_id` do not.
6
- /** Words that name a credential wherever they stand in a key. */
7
- const CREDENTIAL_WORDS = new Set(["token", "secret", "password", "passwd", "passphrase", "authorization", "cookie", "credential", "credentials", "apikey"]);
8
- /** Adjacent word pairs that name a credential: `api_key`, `X-Api-Key`, `OPENAI_API_KEY`, `private_key`, `aws_secret_access_key`. */
9
- const CREDENTIAL_PAIRS = new Set(["api key", "private key", "secret key", "access key", "master key", "signing key", "session key", "auth key"]);
10
- const keyWords = (key) => key.replace(/([a-z0-9])([A-Z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter(Boolean);
11
- /** Whether a key names a credential, by the explicit lists above. */
12
- export function isCredentialKey(key) {
13
- const words = keyWords(key);
14
- return words.some((word, index) => CREDENTIAL_WORDS.has(word) || (index > 0 && CREDENTIAL_PAIRS.has(`${words[index - 1]} ${word}`)));
15
- }
16
- /** Credential-shaped substrings of any text, each replaced by `<redacted>`: an HTTP `Bearer` credential, an environment
17
- * assignment (`NAME=value`) whose name is a credential key, a URL's userinfo, a JWT, and the prefixed keys providers
18
- * issue (`sk-`, GitHub `gh?_` and `github_pat_`, Slack `xox?-`, AWS `AKIA`, Google `AIza`). A SHA-256 or any other
19
- * unprefixed digest is not a credential. */
20
- export function redactCredentialText(value) {
21
- return String(value ?? "")
22
- .replace(/\bBearer\s+[A-Za-z0-9._~+/=-]+/g, "Bearer <redacted>")
23
- .replace(/\b([A-Z][A-Z0-9_]*)=(\S+)/g, (whole, name) => (isCredentialKey(name) ? `${name}=<redacted>` : whole))
24
- .replace(/\b([a-z][a-z0-9+.-]*:\/\/)[^\s/?#@:]+(?::[^\s/?#@]*)?@/gi, "$1<redacted>@")
25
- .replace(/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g, "<redacted>")
26
- .replace(/\b(?:sk-[A-Za-z0-9_-]{16,}|crsr_[A-Za-z0-9_-]{16,}|gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|xox[abprs]-[A-Za-z0-9-]{10,}|AKIA[0-9A-Z]{16}|AIza[0-9A-Za-z_-]{35})/g, "<redacted>");
27
- }
28
- /** A value with every credential-named key's value and every credential-shaped string redacted, objects and arrays walked. */
29
- export function redactSensitiveValue(value) {
30
- if (typeof value === "string")
31
- return redactCredentialText(value);
32
- if (Array.isArray(value))
33
- return value.map((item) => redactSensitiveValue(item));
34
- if (value && typeof value === "object") {
35
- const out = {};
36
- for (const [key, item] of Object.entries(value))
37
- out[key] = isCredentialKey(key) ? "<redacted>" : redactSensitiveValue(item);
38
- return out;
39
- }
40
- return value;
41
- }
42
- /** Every string that reaches a continuation's first turn passes here: values redacted object-aware first, then the
43
- * finished text once more by pattern, and an email address by its form. */
44
- export const redactText = (text) => String(redactSensitiveValue(text)).replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, "<redacted email>");
@@ -1,44 +0,0 @@
1
- import { type InheritedSession, type TranscriptMessage } from "./handoff-digest.js";
2
- import { type InheritedReceipt, type InheritedUnknown } from "./handoff-receipts.js";
3
- import type { RecoveryJournal } from "./store.js";
4
- /** What a continuation inherits from a run that escalated. The package returns it; the host decides who continues. */
5
- export type Handoff = {
6
- /** What happened, the typed state, inputs and spend: bounded and redacted. */
7
- block: string;
8
- /** Each LLM step's transcript, each paid effect and result, files and evidence; null when it could not be built. */
9
- digest: string | null;
10
- /** The attempt written as files under the workspace, relative paths, sorted. */
11
- files: string[];
12
- /** Completed tool effects, keyed by tool and argument hash. */
13
- receipts: InheritedReceipt[];
14
- /** Effects the continuation must not send again. */
15
- unknown: InheritedUnknown[];
16
- /** Why the attempt files could not be written, when they could not: the block then points at files that are not there. */
17
- filesError?: string;
18
- /** Why the digest is null, when it is. */
19
- digestError?: string;
20
- };
21
- export type HandoffOptions = {
22
- /** The run's workspace: the attempt's files are written under it. */
23
- cwd: string;
24
- /** The run's identity as its step sessions are named (`<run>:<label>:step:...`). */
25
- runId: string;
26
- /** The input the run started from, as the dispatch carried it. */
27
- input?: unknown;
28
- /** Where the attempt's report was moved to, when the host set one aside. */
29
- reportPath?: string | null;
30
- /** The host's sizes for the continuation. */
31
- budget?: {
32
- max_tool_calls?: number;
33
- max_seconds?: number;
34
- } | null;
35
- /** The run's step sessions with their spend, from the host's own record of them. */
36
- sessions?: readonly InheritedSession[];
37
- /** A step's transcript by its session id, or null when there is none. */
38
- transcriptOf?: (sessionId: string) => readonly TranscriptMessage[] | null;
39
- };
40
- /** The one place a handoff is built: the escalation row and effects of an open journal, rendered as the continuation's
41
- * first turn. The row must be one the driver committed. Deterministic for a journal and a workspace. */
42
- export declare function buildHandoff(journal: Pick<RecoveryJournal, "state" | "effects">, options: HandoffOptions): Promise<Handoff>;
43
- /** The continuation's first turn: the escalation block, then the digest. Deterministic from its inputs. */
44
- export declare const handoffFirstTurn: (handoff: Pick<Handoff, "block" | "digest">) => string;
@@ -1,46 +0,0 @@
1
- import fs from "node:fs/promises";
2
- import path from "node:path";
3
- import { escalationContextBlock } from "./handoff-block.js";
4
- import { inheritedJobDigest } from "./handoff-digest.js";
5
- import { HANDOFF_FILES_DIR, inputProvenance, writeHandoffFiles } from "./handoff-files.js";
6
- import { inheritableReceipts, inheritableUnknowns } from "./handoff-receipts.js";
7
- /** The one place a handoff is built: the escalation row and effects of an open journal, rendered as the continuation's
8
- * first turn. The row must be one the driver committed. Deterministic for a journal and a workspace. */
9
- export async function buildHandoff(journal, options) {
10
- const snapshot = journal.state;
11
- const row = snapshot?.escalation;
12
- if (!row)
13
- throw new Error("A handoff is built from an escalation the driver committed");
14
- const effects = journal.effects();
15
- const routes = snapshot?.pin?.routes && typeof snapshot.pin.routes === "object" && !Array.isArray(snapshot.pin.routes) ? { ...snapshot.pin.routes } : {};
16
- let files = [];
17
- let effectFiles = {};
18
- let filesError;
19
- try {
20
- ({ files, effectFiles } = await writeHandoffFiles(options.cwd, row, { effects, routes }, options.input));
21
- }
22
- catch (error) {
23
- filesError = String(error?.message ?? error);
24
- }
25
- const evidenceDir = path.join(options.cwd, "evidence");
26
- const gathered = await fs.readdir(evidenceDir).then((names) => names.some((name) => name !== path.basename(HANDOFF_FILES_DIR)), () => false);
27
- const evidence = gathered ? (row.evidence_dir ?? evidenceDir) : null;
28
- const block = escalationContextBlock({ ...row, evidence_dir: evidence, report_path: options.reportPath ?? null, files,
29
- inputs: options.input === undefined ? [] : inputProvenance(options.input), budget: options.budget ?? null });
30
- let digest = null;
31
- let digestError;
32
- try {
33
- digest = inheritedJobDigest({
34
- runId: options.runId, transcriptOf: options.transcriptOf ?? (() => null), cwd: options.cwd, evidenceDir: evidence,
35
- sessions: [...(options.sessions ?? [])],
36
- effects: effects.map((e) => ({ id: e.id, name: e.name, status: e.status, ...(e.status === "completed" ? { result: e.result } : {}) })),
37
- files: snapshot?.files && typeof snapshot.files === "object" ? snapshot.files : {}, effectFiles,
38
- });
39
- }
40
- catch (error) {
41
- digestError = `digest unavailable: ${String(error?.message ?? error)}`;
42
- }
43
- return { block, digest, files, receipts: inheritableReceipts(effects), unknown: inheritableUnknowns(effects), ...(filesError ? { filesError } : {}), ...(digestError && digest === null ? { digestError } : {}) };
44
- }
45
- /** The continuation's first turn: the escalation block, then the digest. Deterministic from its inputs. */
46
- export const handoffFirstTurn = (handoff) => [handoff.block, handoff.digest].filter(Boolean).join("\n\n");