@parcha/agentrun-dsl 0.1.0-beta.18 → 0.1.0-beta.180
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/NOTICE +2 -0
- package/README.md +153 -16
- package/dist/author-references.d.ts +8 -0
- package/dist/author-references.js +8 -0
- package/dist/author.d.ts +4 -3
- package/dist/author.js +20 -11
- package/dist/authoring.js +5 -4
- package/dist/cli.js +19 -13
- package/dist/code-exec.d.ts +19 -0
- package/dist/code-exec.js +54 -5
- package/dist/decision-provider.d.ts +166 -0
- package/dist/decision-provider.js +238 -0
- package/dist/decision-receipts.d.ts +64 -3
- package/dist/decision-receipts.js +50 -8
- package/dist/dry-run.d.ts +35 -1
- package/dist/dry-run.js +131 -25
- package/dist/evidence.d.ts +19 -0
- package/dist/evidence.js +63 -0
- package/dist/graph.d.ts +107 -5
- package/dist/graph.js +284 -9
- package/dist/index.d.ts +17 -12
- package/dist/index.js +16 -10
- package/dist/inspection.d.ts +5 -0
- package/dist/inspection.js +14 -1
- package/dist/pattern-screen.d.ts +14 -0
- package/dist/pattern-screen.js +451 -0
- package/dist/predicates.d.ts +29 -0
- package/dist/predicates.js +62 -3
- package/dist/record.d.ts +4 -0
- package/dist/record.js +6 -0
- package/dist/recovery/binding.js +2 -1
- package/dist/recovery/call-key.d.ts +0 -4
- package/dist/recovery/call-key.js +0 -7
- package/dist/recovery/driver.d.ts +59 -24
- package/dist/recovery/driver.js +251 -73
- package/dist/recovery/frozen-snapshot.d.ts +54 -4
- package/dist/recovery/frozen-snapshot.js +44 -14
- package/dist/recovery/handoff-receipts.d.ts +0 -35
- package/dist/recovery/handoff-receipts.js +2 -44
- package/dist/recovery/index.d.ts +4 -8
- package/dist/recovery/index.js +4 -7
- package/dist/recovery/with-recovery.d.ts +9 -3
- package/dist/recovery/with-recovery.js +78 -18
- package/dist/submit-envelope.d.ts +9 -0
- package/dist/submit-envelope.js +44 -0
- package/dist/system-one.d.ts +21 -2
- package/dist/system-one.js +96 -18
- package/dist/testing/decision-provider.d.ts +32 -0
- package/dist/testing/decision-provider.js +183 -0
- package/dist/testing/index.d.ts +1 -0
- package/dist/testing/index.js +2 -0
- package/dist/vocabulary.d.ts +11 -3
- package/dist/vocabulary.js +19 -9
- package/dist/workflow-shape.d.ts +7 -0
- package/dist/workflow-shape.js +116 -70
- package/dist/workflow.d.ts +171 -19
- package/dist/workflow.js +1063 -399
- package/dist/zod-json-contract.js +6 -8
- package/package.json +12 -4
- package/schema/workflow.schema.json +366 -1
- package/skills/author/SKILL.md +6 -1
- package/skills/author/references/jev-decisions.md +50 -5
- package/skills/author/references/language.md +19 -14
- package/dist/recovery/effect-failure.d.ts +0 -34
- package/dist/recovery/effect-failure.js +0 -62
- package/dist/recovery/handoff-block.d.ts +0 -36
- package/dist/recovery/handoff-block.js +0 -148
- package/dist/recovery/handoff-digest.d.ts +0 -58
- package/dist/recovery/handoff-digest.js +0 -195
- package/dist/recovery/handoff-files.d.ts +0 -54
- package/dist/recovery/handoff-files.js +0 -162
- package/dist/recovery/handoff-redact.d.ts +0 -12
- package/dist/recovery/handoff-redact.js +0 -44
- package/dist/recovery/handoff.d.ts +0 -44
- package/dist/recovery/handoff.js +0 -46
|
@@ -8,33 +8,33 @@ Deliver the complete JSON document the way your host asks; never deliver prose,
|
|
|
8
8
|
## Document
|
|
9
9
|
|
|
10
10
|
A workflow is {"v":2,"name","schemas","input"?,"output","root"}.
|
|
11
|
-
- `schemas` maps ids to inline JSON Schema objects. Every schema id a node, `input` or `output` names must exist there. Inside a schema, reference a catalog schema or an inline definition only as {"$ref":"#/definitions/<id>"}.
|
|
11
|
+
- `schemas` maps ids to inline JSON Schema objects. Every schema id a node, `input` or `output` names must exist there. Inside a schema, reference a catalog schema or an inline definition only as {"$ref":"#/definitions/<id>"}. A `pattern` must not backtrack exponentially: no repeat or optional part inside a repeat that can match the same text (`(a+)+`, `(a?a?)+`, `(\w+\s?)*`), no unbounded repeat of alternatives that start alike (`(a|ab)*`), no backreference; validation refuses one.
|
|
12
12
|
- The input contract: the run starts from the input object and nothing else. `input.schemaId`, when present, is enforced before the first node. A node may read only input keys and keys an earlier node wrote.
|
|
13
13
|
- `output.schemaId` validates the final value; `output.path` selects it from state and must name an input key or a key an earlier node wrote.
|
|
14
14
|
- State is one object. Each step writes its result under one key: its `as`, or, for an agent, decide, extract or code node without `as`, its label. A report writes `report_markdown`. A code node without `as` that returns an object merges that object's top-level fields instead.
|
|
15
|
-
- Keys that
|
|
16
|
-
- `{dot.path}` placeholders are replaced from state in `state` maps (including `verify.state` and `ask.state`), call `args`, `input`, `env` and `produces`, a child workflow's `input`, and `escalate.summary`; `pick` and `sift` `describe` templates also see `{item...}`. A placeholder that is the whole string keeps its value's type. Every key a state map, call or child input interpolates must be produced upstream. `instructions`, `code` and `command` are literal and never interpolated.
|
|
15
|
+
- Keys that hold a `$` are engine-owned: `$host` (host state), `<as>$answers` (raw judge answers and confidences) and `<as>$verify` (verifier results). Read them; never write one. No `as` may hold a `$`, and neither may the label of an agent, decide, extract or code node without `as`.
|
|
16
|
+
- `{dot.path}` placeholders are replaced from state in `state` maps (including `verify.state` and `ask.state`), call `args`, `input`, `env` and `produces`, a child workflow's `input`, and `escalate.summary`; `pick` and `sift` `describe` templates also see `{item...}`. A placeholder that is the whole string keeps its value's type. Every key a state map, call or child input interpolates must be produced upstream, except through a whole-string placeholder marked optional, such as `"{draft?}"`: it is null while its path is absent (a loop's first pass, before the step that writes it ran), and the path's value once present. Only a whole string may be marked. `instructions`, `code` and `command` are literal and never interpolated.
|
|
17
17
|
|
|
18
18
|
## Node kinds
|
|
19
19
|
|
|
20
20
|
This is the complete set. Each kind accepts exactly these fields; any other field is an error.
|
|
21
21
|
- `chain`: `steps`
|
|
22
22
|
- `code`: `label`, `code`, `as`
|
|
23
|
-
- `agent`: `label`, `state`, `instructions`, `sopSection`, `out`, `as`, `requires`, `tools`, `effort`, `thinking`, `verify`, `tier`, `budget_usd`, `context`
|
|
23
|
+
- `agent`: `label`, `state`, `instructions`, `sopSection`, `out`, `as`, `requires`, `tools`, `effort`, `thinking`, `verify`, `tier`, `budget_usd`, `max_turns`, `context`
|
|
24
24
|
- `decide`: `label`, `state`, `instructions`, `sopSection`, `out`, `as`, `requires`, `tools`, `effort`, `thinking`, `verify`, `tier`
|
|
25
25
|
- `extract`: `label`, `state`, `instructions`, `sopSection`, `out`, `as`, `requires`, `tools`, `effort`, `thinking`, `verify`, `tier`
|
|
26
26
|
- `report`: `label`, `state`, `instructions`, `sopSection`, `requires`, `tools`, `effort`, `thinking`
|
|
27
27
|
- `artifact`: `label`, `state`, `type`, `path`, `instructions`, `sopSection`, `requires`, `tools`, `effort`, `thinking`
|
|
28
|
-
- `map`: `label`, `itemsPath`, `body`, `as`, `resultPath`, `maxConcurrency`
|
|
28
|
+
- `map`: `label`, `itemsPath`, `body`, `as`, `resultPath`, `maxConcurrency`, `onItemFailure`, `failedAs`
|
|
29
29
|
- `parallel`: `label`, `branches`
|
|
30
30
|
- `loop`: `label`, `body`, `until`, `maxIters`, `expect_iters`
|
|
31
31
|
- `escalate`: `label`, `when`, `kind`, `stage`, `summary`
|
|
32
32
|
- `call`: `label`, `via`, `tool`, `args`, `code`, `input`, `command`, `env`, `where`, `out`, `as`, `produces`, `deadline_s`, `retry`, `poll`, `requires`
|
|
33
33
|
- `workflow`: `label`, `workflow`, `input`, `out`, `as`
|
|
34
|
-
- `judge`: `label`, `state`, `out`, `as`, `requires`
|
|
35
|
-
- `pick`: `label`, `itemsPath`, `describe`, `instructions`, `state`, `allowNone`, `as`, `requires`
|
|
36
|
-
- `sift`: `label`, `itemsPath`, `describe`, `state`, `out`, `as`, `keep`, `requires`
|
|
37
|
-
- `route`: `label`, `state`, `instructions`, `branches`, `unsure`, `valuePath`, `otherwise`, `as`, `requires`
|
|
34
|
+
- `judge`: `label`, `state`, `out`, `as`, `requires`, `provider`, `model`, `evidence`, `timeoutMs`, `images`
|
|
35
|
+
- `pick`: `label`, `itemsPath`, `describe`, `instructions`, `state`, `allowNone`, `as`, `requires`, `provider`, `model`, `evidence`, `timeoutMs`, `images`
|
|
36
|
+
- `sift`: `label`, `itemsPath`, `describe`, `state`, `out`, `as`, `keep`, `requires`, `provider`, `model`, `evidence`, `timeoutMs`, `images`
|
|
37
|
+
- `route`: `label`, `state`, `instructions`, `branches`, `unsure`, `valuePath`, `otherwise`, `as`, `requires`, `provider`, `model`, `evidence`, `timeoutMs`, `images`
|
|
38
38
|
|
|
39
39
|
Every kind also accepts `metadata`, an object the host owns and the engine never reads; set only the keys the host addendum names.
|
|
40
40
|
|
|
@@ -51,8 +51,8 @@ Their fields:
|
|
|
51
51
|
- `out` names the schema the submission must satisfy; the value lands at `as`.
|
|
52
52
|
- `requires` lists state paths that must hold evidence before the node runs, each produced upstream: missing values, null, blank strings, empty arrays and empty objects stop the run; `false` and `0` pass.
|
|
53
53
|
- `tools` names tools the host offers. `[]` means no tools; omitting `tools` offers every tool the host allows. Never name a tool the host did not offer.
|
|
54
|
-
- `effort` is minimal|low|medium|high; `thinking` is low|medium|high (never off); `tier` is fast|default|strong. They are requests to the host: resource ceilings are the host's.
|
|
55
|
-
- An `agent` node may carry `budget_usd`, the most it asks to spend in dollars (above 0), which the host caps by what it has left, and `context`, fresh|fork: `fresh` (the default) sees only its instructions and state; `fork` asks the host to start it from the caller's transcript, which a host refuses where it has none.
|
|
54
|
+
- `effort` is minimal|low|medium|high; `thinking` is low|medium|high (never off); `tier` is fast|default|strong. They are requests to the host: resource ceilings are the host's. A node that names no `thinking` thinks at medium, unless its host sets another level.
|
|
55
|
+
- An `agent` node may carry `budget_usd`, the most it asks to spend in dollars (above 0), which the host caps by what it has left; `max_turns`, a positive integer, the most turns it asks its host for per attempt, which the host applies within its own cap and refuses above it (the engine enforces nothing, and naming it changes the workflow's digest); and `context`, fresh|fork: `fresh` (the default) sees only its instructions and state; `fork` asks the host to start it from the caller's transcript, which a host refuses where it has none.
|
|
56
56
|
- `sopSection` names one heading of the host's SOP, or a list of them, as the exact text after "## ". The node receives those sections verbatim.
|
|
57
57
|
- `verify` reviews a submission before it is accepted: {"out": a question schema with at least one boolean question, "state"?, "maxDrives"?: an integer >= 1 (default 2, no maximum), "override"?: {"below": a number in (0, 1), default 0.3}}. A boolean question named after a submission field doubts that field when its yes-probability is below `override.below`; any other boolean question is a requirement met at 0.5. A rejected submission returns to the same session with the reasons.
|
|
58
58
|
- When the workflow has a report, no decide or extract `out` schema carries `report_markdown`.
|
|
@@ -72,11 +72,13 @@ Typed questions answered by the host's judge in one request each: no tools, no s
|
|
|
72
72
|
- `sift`: `itemsPath`, `out` (a question schema asked of every item; the host splits the items across requests when they exceed its limits) and `as`. `keep` {path: a question id or <id>.confidence, never a choice, gte?} keeps passing items, in order, at `<as>.items`.
|
|
73
73
|
- `route` runs one of 2 or more named `branches`. Jev chooses: a non-empty `state` map, `instructions` (the one question) and up to 240 branches, each {criteria?, body}; `unsure` {branch, gte: a number in (0, 1]} takes that branch when the choice's confidence is below `gte`. Or the workflow already holds the choice: `valuePath` names the state string that is the branch, each branch is {body}, no question is asked, and `otherwise` (a branch) takes a missing or unknown name, which otherwise fails; a non-string fails. `as` records the choice.
|
|
74
74
|
- A decoded boolean is true at yes-probability 0.5. To hold a different threshold, read `<as>$answers.answers.<id>.noul` in a code node.
|
|
75
|
+
- `images` {token: reference} sends images with a decision (judge, pick, sift, a route Jev chooses, ask). Each token, such as "<page1>", must appear literally in the node's `state` or in a question's text; each reference is written as a state value is, such as "{item.pages.0.image}", and must resolve to an image path the host can read. Only a provider that takes image input answers such a node. Pass images by reference, never their bytes in state.
|
|
76
|
+
- Inside a `map` with `onItemFailure` `collect`, a decision whose provider fails (rate limit, HTTP error, invalid answer, timeout) fails that item, and one sent whose outcome was lost, or one the provider refused, ends the item as a row marked `needs_review`; the other items go on.
|
|
75
77
|
|
|
76
78
|
### Control nodes
|
|
77
79
|
|
|
78
80
|
- `chain`: non-empty `steps`, run in order.
|
|
79
|
-
- `map`: `itemsPath` (an upstream list), `body` and `as`. The body sees `item` and `item_index`; `maxConcurrency` is a positive integer (default 4); `resultPath` selects one path from each completed item's state. Without `resultPath`, and with no `as` in the body, each item's result is its whole state, the mapped list included: set `resultPath` (or an `as` in the body) for a large map; the validator warns.
|
|
81
|
+
- `map`: `itemsPath` (an upstream list), `body` and `as`. The body sees `item` and `item_index`; `maxConcurrency` is a positive integer (default 4); `resultPath` selects one path from each completed item's state. Without `resultPath`, and with no `as` in the body, each item's result is its whole state, the mapped list included: set `resultPath` (or an `as` in the body) for a large map; the validator warns. A map takes at most 10,000 items, and items × the state's JSON size at most 256 Mi characters (each item runs on its own copy of the state); past either it fails before any item runs. `onItemFailure` is `stop` (default: the first failing item stops the map and the run) or `collect`. With `collect`, an item whose node fails (a call that failed after its retries, an agent that delivered no record, output that does not match its schema, a failed check) ends as {item_index, label, code, message} in the list at `failedAs`, the other items finish, and `as` stays aligned with the items: `as[i]` is item i's result, or `null` when item i failed. Filter the nulls explicitly if only successes are wanted. Gate on `failedAs` with `escalate` or a code node; never let failures pass silently. A crash, a cancel, an `escalate` inside the item or an effect whose outcome is unknown is never collected.
|
|
80
82
|
- `parallel`: at least two `branches`, each starting from the state before the parallel node. Branches write disjoint keys and never read a sibling's writes.
|
|
81
83
|
- `loop`: `body`, `until` (a predicate) and an integer `maxIters` of at least 1 (no maximum), optionally an integer `expect_iters` of at least 1 (priced passes). At the bound the state passes through with `until` unmet; follow the loop with an escalate or gate on that condition.
|
|
82
84
|
- `escalate`: `when` (a predicate), and non-empty `kind`, `stage` and `summary`. When the predicate holds the run stops without output and returns the escalation with its interpolated summary.
|
|
@@ -92,7 +94,7 @@ Typed questions answered by the host's judge in one request each: no tools, no s
|
|
|
92
94
|
|
|
93
95
|
## Predicates
|
|
94
96
|
|
|
95
|
-
`loop.until` and `escalate.when` take one of these; `poll` takes only the first
|
|
97
|
+
`loop.until` and `escalate.when` take one of these; `poll` takes only the first 11. Each path or key reads a state value an input or an earlier node produced.
|
|
96
98
|
A predicate is one JSON object that names itself in its `predicate` field beside its own fields, for example `{"predicate": "field_true", "path": "review.approved"}`.
|
|
97
99
|
- `field_equals` {path, value}: holds when the value at `path` equals `value` (a string, number or boolean)
|
|
98
100
|
- `field_true` {path}: holds when the value at `path` is `true`
|
|
@@ -102,7 +104,10 @@ A predicate is one JSON object that names itself in its `predicate` field beside
|
|
|
102
104
|
- `lt` {path, n}: holds when the finite number at `path` is below `n`
|
|
103
105
|
- `empty` {path}: holds when the value at `path` is an empty array, an empty string, null or absent
|
|
104
106
|
- `no_new_items` {key}: takes `key`, not `path`; holds when that state key is an empty array or falsy
|
|
105
|
-
- `
|
|
107
|
+
- `field_type` {path, type}: holds when the value at `path` is of `type`, one of number, string, boolean, array, object, null; a number only when finite, and an absent value is of no type
|
|
108
|
+
- `quote_missing` {path, field, pages}: the quote check, in code: holds when a quote at `path` (a string, or a list of them; with `field`, a list of records each holding its quote at `field`) is in none of the pages at `pages` (state paths holding what this run's call steps fetched; every string under each is page text). Both sides are compared lowercased, with curly quotes straight, dashes as "-" and whitespace runs as one space, then once more as their letters and digits alone; a quote under 8 characters is not checked. `{"predicate": "quote_missing", "path": "answer.evidence", "field": "quote", "pages": ["page"]}` on an escalate hands back an answer quoting text no fetched page holds. Check quotes with it, never with a judge or an `ask`
|
|
109
|
+
- `not` {of}: holds when `of`, one mechanical predicate (never `ask`), does not; `{"predicate": "not", "of": {"predicate": "field_type", "path": "score", "type": "number"}}` holds when score is absent or not a finite number
|
|
110
|
+
- `ask` {instructions, state, criteria, gte, provider, model, evidence, timeoutMs, images}: a yes/no question for the host's judge: `instructions` is the question, `state` what it sees (default: the whole state), `criteria` optional {true, false} descriptions; holds when the yes-probability is at least `gte` (in (0.5, 1], default 0.6)
|
|
106
111
|
|
|
107
112
|
## Authority
|
|
108
113
|
|
|
@@ -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 writeFrozenEvidence 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
|
-
}
|