@parcha/agentrun-dsl 0.1.0-beta.33 → 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.
@@ -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
- }>;