stitchkit 0.135.0 → 0.135.1
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/CHANGELOG.md +8 -0
- package/dist/agent-runtime/providers/openrouter-audio.d.ts +122 -0
- package/dist/agent-runtime/providers/openrouter-audio.d.ts.map +1 -0
- package/dist/agent-runtime/providers/openrouter-catalog-cache.d.ts.map +1 -1
- package/dist/agent-runtime/providers/openrouter-catalog.d.ts +2 -0
- package/dist/agent-runtime/providers/openrouter-catalog.d.ts.map +1 -1
- package/dist/agent-runtime/providers/openrouter-http.d.ts +100 -0
- package/dist/agent-runtime/providers/openrouter-http.d.ts.map +1 -0
- package/dist/agent-runtime/providers/openrouter-media.d.ts +160 -0
- package/dist/agent-runtime/providers/openrouter-media.d.ts.map +1 -0
- package/dist/agent-runtime/providers/openrouter-models.d.ts +1 -1
- package/dist/agent-runtime/providers/openrouter-models.d.ts.map +1 -1
- package/dist/agent-runtime/providers/openrouter-options.d.ts +2 -0
- package/dist/agent-runtime/providers/openrouter-options.d.ts.map +1 -1
- package/dist/agent-runtime/providers/openrouter-response.d.ts.map +1 -1
- package/dist/agent-runtime/providers/openrouter-retrieval.d.ts +114 -0
- package/dist/agent-runtime/providers/openrouter-retrieval.d.ts.map +1 -0
- package/dist/agent-runtime/providers/openrouter-spend.d.ts +5 -1
- package/dist/agent-runtime/providers/openrouter-spend.d.ts.map +1 -1
- package/dist/agent-runtime/providers/openrouter-stream.d.ts +29 -0
- package/dist/agent-runtime/providers/openrouter-stream.d.ts.map +1 -0
- package/dist/agent-runtime/providers/openrouter-systemone.d.ts +82 -0
- package/dist/agent-runtime/providers/openrouter-systemone.d.ts.map +1 -0
- package/dist/agent-runtime/providers/openrouter-url.d.ts +13 -0
- package/dist/agent-runtime/providers/openrouter-url.d.ts.map +1 -0
- package/dist/agent-runtime/providers/openrouter.d.ts +4 -1
- package/dist/agent-runtime/providers/openrouter.d.ts.map +1 -1
- package/dist/agent-runtime/providers/provider-http.d.ts +15 -1
- package/dist/agent-runtime/providers/provider-http.d.ts.map +1 -1
- package/dist/agent-runtime/stores/branch-observations.d.ts +42 -42
- package/dist/agent-runtime/testing/store-conformance-lifecycle.d.ts +20 -20
- package/dist/agent-runtime/testing/store-conformance-support.d.ts +10 -10
- package/dist/entrypoints/agent-runtime/anthropic.js +1 -1
- package/dist/entrypoints/agent-runtime/openai.js +1 -1
- package/dist/entrypoints/agent-runtime/openrouter.d.ts +7 -0
- package/dist/entrypoints/agent-runtime/openrouter.d.ts.map +1 -1
- package/dist/entrypoints/agent-runtime/openrouter.js +1444 -241
- package/dist/{index-zfrysr1e.js → index-ht71v1ag.js} +52 -32
- package/llms/agent-runtime-openrouter.txt +11 -3
- package/llms/agent-runtime.2.txt +333 -224
- package/llms/agent-runtime.3.txt +225 -380
- package/llms/agent-runtime.4.txt +381 -158
- package/llms/agent-runtime.5.txt +157 -152
- package/llms/agent-runtime.6.txt +164 -0
- package/llms/agent-runtime.txt +30 -332
- package/llms/spend.txt +17 -1
- package/llms-full.txt +54 -4
- package/llms.txt +3 -3
- package/package.json +1 -1
package/llms/agent-runtime.3.txt
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# stitchkit/agent-runtime — stitchkit docs slice, part 3 of
|
|
1
|
+
# stitchkit/agent-runtime — stitchkit docs slice, part 3 of 6
|
|
2
2
|
|
|
3
3
|
> Generated from the `docs/` tree by `bun run gen:llms`. The index of all slices is
|
|
4
4
|
> `llms.txt` in this package.
|
|
@@ -8,13 +8,235 @@ Parts of this slice:
|
|
|
8
8
|
- `llms/agent-runtime.txt`: Guide: Agent application runtime (docs/guide/agent-runtime.md)
|
|
9
9
|
- `llms/agent-runtime.2.txt`: Guide: Agent application runtime (docs/guide/agent-runtime.md)
|
|
10
10
|
- `llms/agent-runtime.3.txt`: Guide: Agent application runtime (docs/guide/agent-runtime.md)
|
|
11
|
-
- `llms/agent-runtime.4.txt`: Guide: Agent application runtime (docs/guide/agent-runtime.md)
|
|
12
|
-
- `llms/agent-runtime.5.txt`: API reference: `stitchkit/agent-runtime` (docs/api/reference.md)
|
|
11
|
+
- `llms/agent-runtime.4.txt`: Guide: Agent application runtime (docs/guide/agent-runtime.md)
|
|
12
|
+
- `llms/agent-runtime.5.txt`: API reference: `stitchkit/agent-runtime` (docs/api/reference.md)
|
|
13
|
+
- `llms/agent-runtime.6.txt`: API reference: `stitchkit/agent-runtime` (docs/api/reference.md) · API reference: `stitchkit-tui` (docs/api/reference.md)
|
|
13
14
|
|
|
14
15
|
==============================================================================
|
|
15
16
|
# Guide: Agent application runtime (docs/guide/agent-runtime.md) (continued)
|
|
16
17
|
==============================================================================
|
|
17
18
|
|
|
19
|
+
### Event ledger, projections and durable capabilities
|
|
20
|
+
|
|
21
|
+
`AgentRuntimeStore` exposes bounded `readEvents`, declared `appendEvent`, canonical
|
|
22
|
+
`exportConversation` and empty-target `importConversation`. Runtime transitions, exact provider
|
|
23
|
+
requests and completed provider response identities enter the same append-only ledger. A
|
|
24
|
+
`provider/response` payload binds `response: { id, provider? }` to its `runId`, retry `attempt` and
|
|
25
|
+
`stepNumber`; `step-finished.response` projects the same object to the operator sink. The optional
|
|
26
|
+
upstream name comes from the `AgentModelDriver` `finish.responseProvider` field (emitted directly by
|
|
27
|
+
`openRouterProvider`, or supplied via `FromAiSdkModelOptions.resolveResponseProvider` for AI SDK
|
|
28
|
+
models) so the runtime carries the fact without learning any gateway's metadata key. The normalized
|
|
29
|
+
head/run/message tables remain the fast operational projection.
|
|
30
|
+
|
|
31
|
+
For `runtime/transition` payload inspection, use `AgentStoreTransitionRecordSchema` and its
|
|
32
|
+
inferred `AgentStoreTransitionRecord` type. A checkpoint record may hold either the full assistant
|
|
33
|
+
message or `{ id, status: 'streaming', sha256?, sourceSha256?, parts: number, bytes: number }`;
|
|
34
|
+
exactly one digest is present. Numeric `parts` counts parts; it is not an array of message parts.
|
|
35
|
+
`sourceSha256` preserves a branch's historical source digest. These hash-only records are
|
|
36
|
+
observations, not executable checkpoint inputs. `AgentStoreTransitionSchema` describes full
|
|
37
|
+
store mutations. Shape inspection does not replace branch's complete replay/reference validation.
|
|
38
|
+
Schema v4 archives written by 0.109.4 use the same journal representation.
|
|
39
|
+
|
|
40
|
+
Use `defineAgentProjection` with `createAgentProjectionStore` for a
|
|
41
|
+
deterministic versioned fold. Every value reports `uptoSeq`, so a caller can
|
|
42
|
+
distinguish current data from a projection that still has events to consume.
|
|
43
|
+
Changing the projection version folds from sequence one.
|
|
44
|
+
|
|
45
|
+
The built-ins are `agentSummaryProjection`, `agentUsageProjection` and
|
|
46
|
+
`agentOutlineProjection`; focused card, state-slot and schedule projections are
|
|
47
|
+
also available. `list(projection)` reads all materialized conversation rows in
|
|
48
|
+
one SQLite query instead of reopening their event logs.
|
|
49
|
+
|
|
50
|
+
Durable state is declared once and injected on every provider request:
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
const goal = defineStateSlot({
|
|
54
|
+
name: 'goal',
|
|
55
|
+
schema: z.object({ objective: z.string(), status: z.string() }),
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
const slots = createAgentStateSlotStore({ store: sqlite.store, definitions: [goal] })
|
|
59
|
+
await slots.set({
|
|
60
|
+
conversationId,
|
|
61
|
+
name: 'goal',
|
|
62
|
+
value: { objective: 'finish migration', status: 'active' },
|
|
63
|
+
actor: 'human',
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
const runtime = createAgentRuntime({ ...config, store: sqlite.store, stateSlots: [goal] })
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
Every built-in tool factory below takes the run context `tools()` receives and acts
|
|
70
|
+
for that run's conversation; a context no runtime issued is refused, so the tools
|
|
71
|
+
are built per run:
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
createAgentRuntime({
|
|
75
|
+
...config,
|
|
76
|
+
tools: (run) =>
|
|
77
|
+
mountAgentTools({
|
|
78
|
+
access: { gate: run.toolFenceLifecycle },
|
|
79
|
+
runtimeTools: createAgentStateTools({ state, run }),
|
|
80
|
+
}),
|
|
81
|
+
})
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
`createAgentStateTools({ state, run })` binds `create_goal`, `update_goal`,
|
|
85
|
+
`get_goal` and `todo_write` to the conversation of the run it is given. Human changes call the same slot store with
|
|
86
|
+
`actor: 'human'`; they remain structured `state/set` facts rather than forged
|
|
87
|
+
chat messages.
|
|
88
|
+
|
|
89
|
+
`createAgentSpillStore` persists oversized output separately and records
|
|
90
|
+
its locator, hash, lifecycle and the tool call whose output it holds in the ledger. `read_output` and
|
|
91
|
+
`search_output` re-run both locator authorization and the originating tool
|
|
92
|
+
authorization before reading bytes. A reference the store does not hold is a
|
|
93
|
+
refusal like any other — `SPILL_REFERENCE_UNKNOWN` / 404, naming the reference
|
|
94
|
+
and pointing at the one the spilling command returned. The lookup is scoped by
|
|
95
|
+
conversation, so a reference belonging to another conversation is absent rather
|
|
96
|
+
than forbidden, and the refusal cannot tell a model that it exists elsewhere. The store's `conversationId`
|
|
97
|
+
and `runId` are the host's to name, as `root` is for the coding tools: the store also serves work outside a
|
|
98
|
+
run (retention `cleanup`, reading a branched copy), and the model never names a conversation, only a
|
|
99
|
+
reference. Inside a runtime, create it in `tools()` from the run context it receives —
|
|
100
|
+
`conversationId: runContext.run.conversationId, runId: runContext.run.id`. `createAgentEventSearch` returns the
|
|
101
|
+
exact conversation and event sequence; cross-conversation results are denied
|
|
102
|
+
unless `authorizeConversation` approves each target.
|
|
103
|
+
On the Postgres store the search keeps a `tsvector` (`simple`) per event in a
|
|
104
|
+
table of its own and indexes new events when a search needs them, never inside
|
|
105
|
+
`appendEvent`, so an event of any size is stored. It matches as SQLite does —
|
|
106
|
+
every word, in any order; a hyphenated word is found by its parts on both —
|
|
107
|
+
with two differences named in ADR 0315: diacritics are kept unless
|
|
108
|
+
`postgres: { diacritics: 'unaccent' }` (FTS5 removes them; `unaccent` needs the
|
|
109
|
+
extension and refuses without it), and the ranking and snippets come from
|
|
110
|
+
`ts_rank_cd` and `ts_headline` rather than `bm25` and `snippet`. `maxIndexedChars` (65 536) bounds the text indexed per
|
|
111
|
+
event; `maxSyncEvents` (10 000) bounds the indexing one search does — a search
|
|
112
|
+
further behind indexes that many and refuses with how far, and the next
|
|
113
|
+
continues.
|
|
114
|
+
`createAgentEventSearchTools({ run, search, store })` supplies `session_search`,
|
|
115
|
+
`session_trace` and `session_event` over the same bounded APIs, for the
|
|
116
|
+
conversation of the run it is given.
|
|
117
|
+
|
|
118
|
+
For credential-free failure tests, import `createFaultProviderServer` and
|
|
119
|
+
`createReplayAgentProvider` from `stitchkit/agent-runtime/testing`. Runtime
|
|
120
|
+
`loop.retry` applies an explicit `AgentRetryPolicy`: each decision is recorded
|
|
121
|
+
as `retry/scheduled`, each new attempt as `retry/started`, and an attempt that
|
|
122
|
+
has invoked a tool is never automatically replayed. Its `maxAttempts` is a
|
|
123
|
+
positive safe integer, refused otherwise when the runtime is created and when
|
|
124
|
+
`recordAgentRetryDecision` is given the policy (`TypeError`): `Infinity` would
|
|
125
|
+
retry a paid failure without end, `NaN` or `0` would silently mean never. The
|
|
126
|
+
Postgres store's `maxAttempts` follows the same rule.
|
|
127
|
+
|
|
128
|
+
`createAgentScheduleService` persists `at`, `after` and `every` input. It
|
|
129
|
+
requires `maxActivePerConversation` — the schedules one conversation may hold at
|
|
130
|
+
once, counted in the transaction that inserts — and `minIntervalMs`, the shortest
|
|
131
|
+
repeat; a request past either refuses with the limit in the message. Repeating
|
|
132
|
+
schedules require an explicit IANA time zone. Dispatch uses a stable
|
|
133
|
+
`schedule:<id>:<occurrence>` idempotency key, and restart lateness is recorded.
|
|
134
|
+
Resolve after durable admission; return `{ status: 'retry', reason }` for a
|
|
135
|
+
transient refusal or `{ status: 'terminal', reason }` to stop the entire schedule in
|
|
136
|
+
`failed` state. Only those two shapes are failures: any other returned value — a
|
|
137
|
+
queue length, a receipt — means the callback returned, so it delivered. Throws retry
|
|
138
|
+
too. `maxAttempts` (default 1000, about sixteen hours at the retry ceiling) bounds
|
|
139
|
+
one occurrence: a one-off schedule then becomes `failed`, a recurring one gives up
|
|
140
|
+
that occurrence (`schedule/failed` with `skipped: true` and the `nextAt` it moves
|
|
141
|
+
to) and keeps its cadence. A failure reason is kept to 1000 characters. Backoff is 1, 2, 4, 8, 16, 32, then 60 seconds,
|
|
142
|
+
capped at 60 seconds and persisted across restart. `retryAt`, `attempts` and `lastError`
|
|
143
|
+
show retry diagnostics; success resets them. `nextAt` and `lateByMs` retain the original
|
|
144
|
+
occurrence time. Recurring schedules fire once after an idle stretch and advance to the
|
|
145
|
+
next future slot on their original cadence.
|
|
146
|
+
|
|
147
|
+
Dispatch receives an `AbortSignal`, has a 30-second deadline and holds a unique
|
|
148
|
+
60-second lease. A late or cancelled attempt cannot settle or emit firing events.
|
|
149
|
+
Honor the signal and durably deduplicate the key: a crash after admission but before
|
|
150
|
+
settlement can replay delivery. This is at-least-once, not exactly-once.
|
|
151
|
+
Due selection is indexed, limited to 32 parallel deliveries per tick; one hung batch
|
|
152
|
+
can delay newly due work by at most its deadline. The service keeps one nearest-due
|
|
153
|
+
timer plus per-attempt deadline timers. Storage failures use a bounded recovery timer;
|
|
154
|
+
idle ticks do not write. SQLite v4 migration preserves due times and claims; stop older
|
|
155
|
+
scheduler processes before migration. See [ADR 0202](../decisions/0202-schedule-retries-preserve-occurrence-identity.md).
|
|
156
|
+
`createAgentScheduleTools({ service, run })` exposes the exact `schedule_after`,
|
|
157
|
+
`schedule_at`, `schedule_every`, `schedule_list` and `schedule_cancel` surface, bound to the
|
|
158
|
+
conversation of the run it is given: the model's input carries no conversation address, and
|
|
159
|
+
the service's limits are the only ones.
|
|
160
|
+
|
|
161
|
+
`createAgentChildManager` seeds a child from the parent's ledger through
|
|
162
|
+
an exact sequence, stores the graph, clamps requested limits to the parent
|
|
163
|
+
remainder `remainingBudget` returns (required; a dimension the model leaves out
|
|
164
|
+
takes it, a budget that names no limit or a spent dimension refuses), refuses a
|
|
165
|
+
child past `maxActiveChildren` (required; counted by the managing process, so two processes managing
|
|
166
|
+
one store each hold their own count) and stops budget overruns at the next step boundary as
|
|
167
|
+
`policy_stop`. That enforcement runs inside the child's own runtime: the host that spawns it gives the child
|
|
168
|
+
`loop.stopPolicies: [agentChildBudgetStopPolicy({ manager, childConversationId })]`, which
|
|
169
|
+
calls `recordStepUsage` at every step boundary using the resolved model's own `normalizeUsage` hook (the same path as `onStepSpend`, with no separate `cost` callback); `recordStepUsage` alone measures and decides,
|
|
170
|
+
and reports `enforced: false` when the deciding process holds no handle to stop; a budget stop the
|
|
171
|
+
host confirms records the child `stopped`, so it no longer holds a place under `maxActiveChildren`. Given to `createAgentRuntime` as `children`, the manager stops the parent's children after the parent's terminal is durable — interrupted, cancelled, timed out or shut down; a successful, policy-stopped, superseded or failed parent leaves them to the conversation (ADR 0175 carries the table); without `children` nothing cascades; an unreachable child is recorded
|
|
172
|
+
as `lost`, not misreported as a provider failure. Every stop — the cascade, `interruptChild`, the
|
|
173
|
+
cleanup of a spawn whose record failed — is asked of the host within one bound, and stops that meet on
|
|
174
|
+
one child while its host is answering share that one request; a stop it does not
|
|
175
|
+
confirm records `lost` with its `reason` (`stop-timeout`, `stop-failed`, `unreachable`). A spawn is
|
|
176
|
+
visible to the parent's stop from its first line: stopped before the host is asked to start the child,
|
|
177
|
+
`spawnChild` rejects and no child exists; stopped after, the child is stopped as soon as its handle is
|
|
178
|
+
held, and `spawnChild` returns the state that stop recorded. `waitChild` — and so the `subagent` tool —
|
|
179
|
+
resolves once a stop has recorded how the child ended, without waiting for a host that never reports. An
|
|
180
|
+
answer or a message that outlived the bound may still reach the host: until it settles, a second one is
|
|
181
|
+
refused rather than delivered twice, and one the host takes late is recorded when it lands. A message and a blocking answer are asked of
|
|
182
|
+
the host within the same bound: one it does not answer rejects, a blocking request stays pending to
|
|
183
|
+
answer again, and each parent's blocking requests queue on their own, so a silent host holds no other
|
|
184
|
+
parent's. A child
|
|
185
|
+
that finished while being stopped keeps `finished` and its result: a child leaves `spawned` or
|
|
186
|
+
`running` once, and each conversation journals one terminal state for it. `listChildBlocking`
|
|
187
|
+
returns `{ pending, unavailable }`: a live child that does not say in time what it has pending, or
|
|
188
|
+
whose answer fails, is listed in `unavailable`, not read as having nothing pending.
|
|
189
|
+
`createAgentChildTools({ manager, run })` adds `subagent`, `subagent_fork`,
|
|
190
|
+
`list_agents`, `send_message` and `interrupt_agent` for the parent conversation of the run it is given;
|
|
191
|
+
the model's input names no parent, and a child of another parent is refused. Final output stays
|
|
192
|
+
behind its bounded result locator.
|
|
193
|
+
|
|
194
|
+
### Per-step spend hook
|
|
195
|
+
|
|
196
|
+
`createAgentRuntime({ onStepSpend, onStepSpendError, stepSpendTimeoutMs })` delivers one validated
|
|
197
|
+
`AgentStepSpend & AgentRuntimeRunContext<CONTEXT>` fact for every billed model step
|
|
198
|
+
(`phase: 'step'`), billed retried attempt (`phase: 'abandoned-attempt'`), and compaction call
|
|
199
|
+
(`phase: 'compaction'`), after the `provider/response` ledger entry (which now persists `usage` in
|
|
200
|
+
the non-audited ledger too) is written. Step facts and `observe` `step-finished` events both carry
|
|
201
|
+
`finishReason`, `rawFinishReason`, `toolCallCount`, `costDetails` (`promptCostUsd`, `outputCostUsd`,
|
|
202
|
+
`isByok`), split `timings` (`ttftMs`, `responseTimeMs`, `toolExecutionMs`, `stepTimeMs`, plus
|
|
203
|
+
optional `chunkIntervalsMs` percentiles when a step streams two or more output deltas), and
|
|
204
|
+
`response.{id, provider, modelId, timestamp}`. The same fact feeds run totals.
|
|
205
|
+
|
|
206
|
+
`onStepSpend` is awaited up to `stepSpendTimeoutMs` (default `5_000` ms): the run does not start its
|
|
207
|
+
next step, or retry a discarded attempt, until the hook settles, so a slow hook adds its time to
|
|
208
|
+
every step. Because the provider call is already billed, a throw or timeout never fails the run; it
|
|
209
|
+
is isolated and reported to `onStepSpendError` and on the corresponding `step-finished`
|
|
210
|
+
observability event (`spendHookError: { code: 'hook_error' | 'hook_timeout', cause? }`, with `cause`
|
|
211
|
+
redacted unless `includeInternalCause: true`). `onStepSpendError` is awaited up to the same
|
|
212
|
+
`stepSpendTimeoutMs`; if it throws or times out as well, the event carries `reportFailed: true`:
|
|
213
|
+
it is then the only report of the failure.
|
|
214
|
+
|
|
215
|
+
The core intentionally carries no domain billing enum (`payment` / `subscription` / `key`)
|
|
216
|
+
([ADR 0002](../decisions/0002-generic-core.md),
|
|
217
|
+
[ADR 0110](../decisions/0110-a-reconciled-cost-belongs-to-the-application.md)): each
|
|
218
|
+
fact reports `provider: { key, upstream? }`, `usage.cost.provenance` (`provider-reported` vs
|
|
219
|
+
`unavailable`, never fabricated as `0`), and scope via `context` and `trace?.project`, so
|
|
220
|
+
applications attach their own workspace or payment-method rules to provider keys inside
|
|
221
|
+
`onStepSpend`.
|
|
222
|
+
|
|
223
|
+
## Durable order
|
|
224
|
+
|
|
225
|
+
`acceptInputAndAssignRun` is one atomic operation. It is followed by ownership
|
|
226
|
+
acquisition, revision-checked assistant checkpoints and one terminal CAS. The
|
|
227
|
+
process-local coordinator releases its lane only after terminal commit.
|
|
228
|
+
|
|
229
|
+
A queued admission is durable immediately, even if its predecessor is still awaiting ownership
|
|
230
|
+
or its first checkpoint. Snapshots expose causal turn order rather than physical append order:
|
|
231
|
+
the predecessor's assigned input(s) and assistant come before the successor input(s). Execution
|
|
232
|
+
uses the same run boundary, so neither `prompt({ snapshot })` nor default/custom history
|
|
233
|
+
projection can see inputs assigned to a later run. `inject` remains the explicit path that moves
|
|
234
|
+
a successor input into the run already in flight.
|
|
235
|
+
|
|
236
|
+
```text
|
|
237
|
+
input + queued run → running → execution settled → terminal CAS → successor
|
|
238
|
+
```
|
|
239
|
+
|
|
18
240
|
## What happens to a run when new input arrives
|
|
19
241
|
|
|
20
242
|
`runs.inputPolicy` decides. It takes five values, or a function returning one:
|
|
@@ -431,380 +653,3 @@ Their transaction must serialize `isPurged`, head/active-run checks, `remove`, a
|
|
|
431
653
|
for the same ID, including absent-ID admission. An optimistic head CAS alone is insufficient. `remove`
|
|
432
654
|
must delete every owned payload/index and preserve the tombstone; errors must roll back the entire
|
|
433
655
|
transaction. Drivers without this guarantee must leave the capability absent. See ADR 0138.
|
|
434
|
-
|
|
435
|
-
## Events and reconnect
|
|
436
|
-
|
|
437
|
-
A subscriber that switches over `event.type` handles one transient event
|
|
438
|
-
beyond deltas and reasoning: `attempt-reset`, published when `loop.retry`
|
|
439
|
-
starts a new attempt, meaning everything this run streamed before it is
|
|
440
|
-
withdrawn. `reduceAgentControlEvent` does that; a hand-written reducer must,
|
|
441
|
-
or it keeps the failed attempt's partial text on screen.
|
|
442
|
-
|
|
443
|
-
`publish` receives event classes with different guarantees:
|
|
444
|
-
|
|
445
|
-
- `admission` follows a successful acceptance CAS and carries the same complete
|
|
446
|
-
projection as `ticket.admission`;
|
|
447
|
-
|
|
448
|
-
- `assistant-delta` is transient and ordered by
|
|
449
|
-
`(runId, runtimeEpoch, sequence)`;
|
|
450
|
-
- `reasoning-start`, `reasoning-delta` and `reasoning-end` are transient and
|
|
451
|
-
ordered by the same identity; delta carries only the current text fragment,
|
|
452
|
-
while provider metadata stays inside a validated canonical envelope;
|
|
453
|
-
- `assistant-checkpoint` follows a successful checkpoint CAS;
|
|
454
|
-
- `run-state` follows durable queue/acquire/interrupt transitions;
|
|
455
|
-
- `run-operation` follows a successful operation CAS. Its `operation` is the
|
|
456
|
-
durable `AgentRun.lastOperation`: `model-request` or `compaction`, with
|
|
457
|
-
`started`, `first-output`, `completed`, `failed` or `cancelled` phase and the
|
|
458
|
-
original timestamps. Concrete models use SDK call identity in an awaited model
|
|
459
|
-
middleware; global provider IDs use a runtime-generated identity during awaited
|
|
460
|
-
step preparation. Both durably admit the request before entering `doStream`, so a failed
|
|
461
|
-
write prevents the provider call. This does not claim HTTP transmission is
|
|
462
|
-
measured. First output is a
|
|
463
|
-
non-empty text/reasoning/tool-argument delta or complete tool call; metadata,
|
|
464
|
-
usage, files and sources do not count;
|
|
465
|
-
- `tool-status` is durable lifecycle presentation with JSON-safe input on
|
|
466
|
-
start and output on completion: it follows the checkpoint that holds the call
|
|
467
|
-
(or its result) and carries that checkpoint's `eventId` and `snapshotVersion`. A mounted typed failure carries the same safe
|
|
468
|
-
`{ error, retryable, details?, _hint? }` envelope as the durable result; an unknown
|
|
469
|
-
internal cause remains generic and stays in local observability only;
|
|
470
|
-
- `tool-progress` is transient: what a running tool handler reported through
|
|
471
|
-
`ctx.reportProgress` — `message`, `progress` and `total`, the fields an MCP host
|
|
472
|
-
receives — with the call's `callId` and `toolName`. It never enters the
|
|
473
|
-
model's input or the durable history. A message longer than
|
|
474
|
-
`AGENT_TOOL_PROGRESS_MESSAGE_MAX` (280) is cut, reports of one call closer
|
|
475
|
-
than 250 ms apart are dropped, and a report after the call's terminal
|
|
476
|
-
`tool-status` or after its attempt was abandoned is dropped; the terminal
|
|
477
|
-
status carries the final word. `reduceAgentControlEvent` keeps the last
|
|
478
|
-
report of each running call in `transientByRun[runId].tools[callId]` and
|
|
479
|
-
removes it on that call's `completed`, `failed` or `interrupted`. The runtime
|
|
480
|
-
hands its reporter to a call through the SDK tool context, beside its step
|
|
481
|
-
ledger; a tool that declares its own `contextSchema` keeps that contract and
|
|
482
|
-
reports nowhere;
|
|
483
|
-
- `terminal` follows the winning terminal CAS.
|
|
484
|
-
|
|
485
|
-
`loop.checkpointEveryEvents` batches ordinary stream parts (default `20`) and
|
|
486
|
-
does not batch live event delivery. Tool call/result/error/denial, approval
|
|
487
|
-
request/response and step-finish boundaries force an assistant checkpoint and
|
|
488
|
-
reset that batch. The checkpoint is awaited after the managed loop observes the
|
|
489
|
-
normalized boundary. It does **not** promise persistence before a tool side
|
|
490
|
-
effect: tool fencing supplies the real ownership checks around execution, while
|
|
491
|
-
cross-crash effect idempotency stays application-owned. The following model
|
|
492
|
-
step waits for the previous step-finish checkpoint before its own durable
|
|
493
|
-
request admission and provider invocation. → ADR 0174.
|
|
494
|
-
|
|
495
|
-
`compaction` names invocation of the configured callback, including a
|
|
496
|
-
`not_needed` context-budget check; it does not by itself say that history was
|
|
497
|
-
summarized. Operation timestamps are retained wall-clock observations and may
|
|
498
|
-
move backwards after a clock correction. Do not subtract them for duration;
|
|
499
|
-
phase order comes from durable snapshot versions/event order.
|
|
500
|
-
|
|
501
|
-
These are post-commit notifications, not a transactional outbox: a process can
|
|
502
|
-
crash between the database commit and `publish`. Reconnect should load canonical
|
|
503
|
-
state. Exactly-once external delivery remains an application-owned outbox.
|
|
504
|
-
|
|
505
|
-
### External channel ingress and delivery
|
|
506
|
-
|
|
507
|
-
The executable
|
|
508
|
-
[`external-channel-harness.ts`](../../packages/core/examples/agent-runtime/external-channel-harness.ts)
|
|
509
|
-
is the reference composition for webhooks, polling transports and local-device
|
|
510
|
-
adapters. Its generic boundary injects a runtime, durable store and delivery
|
|
511
|
-
adapter; the optional
|
|
512
|
-
[`external-channel-grammy.ts`](../../packages/core/examples/agent-runtime/external-channel-grammy.ts)
|
|
513
|
-
attaches the same ingress function to grammY polling or webhook lifecycle
|
|
514
|
-
without putting provider types in the agent runtime.
|
|
515
|
-
|
|
516
|
-
Inbound update identity, principal resolution, conversation mapping and reply
|
|
517
|
-
target are application policy. Persist and deduplicate the update before
|
|
518
|
-
`runtime.submit`, use the stored idempotency key on crash recovery, then persist
|
|
519
|
-
the admitted `runId`. A duplicate arriving after restart resolves to that same
|
|
520
|
-
mapping instead of creating another model turn.
|
|
521
|
-
|
|
522
|
-
For output, choose `terminal-only` or `streaming` explicitly. Stable durable
|
|
523
|
-
`eventId` values and transient `(runtimeEpoch, sequence)` identities become
|
|
524
|
-
outbox keys; the application store assigns causal ordinals. A bounded channel
|
|
525
|
-
is only a process-local wakeup and never the durable authority. Before sending,
|
|
526
|
-
persist one of these states:
|
|
527
|
-
|
|
528
|
-
| State | Recovery action |
|
|
529
|
-
| --- | --- |
|
|
530
|
-
| `not-dispatched` | may dispatch once |
|
|
531
|
-
| `possibly-dispatched` | reconcile with the adapter or remain unresolved |
|
|
532
|
-
| `acknowledged` | deduplicate; delivery is complete |
|
|
533
|
-
|
|
534
|
-
The agent `terminal` event and the adapter's delivery receipt are intentionally
|
|
535
|
-
different records. A successful run does not prove that a reply reached its
|
|
536
|
-
channel, and a delivery failure never rewrites the canonical agent result.
|
|
537
|
-
Shutdown stops ingress, drains accepted process-local work and leaves ambiguous
|
|
538
|
-
outbox records visible for a later reconciliation pass. StitchKit does not own
|
|
539
|
-
a channel database, durable broker, provider payload schema or application
|
|
540
|
-
identity policy.
|
|
541
|
-
|
|
542
|
-
Durable event IDs are derived from run, event type and snapshot version. Use
|
|
543
|
-
`advanceAgentRuntimeEventCursor` to classify delivery.
|
|
544
|
-
|
|
545
|
-
**`gap` is reported for transient events only**, where `sequence` is a per-run
|
|
546
|
-
counter the runtime really does increment once per event. Durable events carry
|
|
547
|
-
the *conversation's* version, which advances on every mutation including the many
|
|
548
|
-
that publish nothing — checkpoints, compaction, an acceptance that has not
|
|
549
|
-
started — so two consecutive durable events are routinely several versions apart
|
|
550
|
-
and adjacency says nothing. A durable loss is not detectable from the cursor;
|
|
551
|
-
reload on reconnect, which is what a bounded fire-and-forget sink asks of you
|
|
552
|
-
anyway. `createAgentRuntimeEventSink` adds a bounded failure-isolated lifecycle and typed
|
|
553
|
-
projection/redaction hook. `onPublishError` records direct publisher failures without changing the
|
|
554
|
-
already committed run.
|
|
555
|
-
|
|
556
|
-
A named custom stop condition terminalizes with `policy_stop`; its `policyName`
|
|
557
|
-
is persisted on the run and included in the terminal event/result. `max-steps`
|
|
558
|
-
is the reserved built-in policy name. `loop.prepareStep` (and `prepareStep` on
|
|
559
|
-
`completeText` / `streamComplete` / `completeObject`) is the controlled step
|
|
560
|
-
boundary for changing active tools, driver, instructions or messages. It cannot
|
|
561
|
-
replace the managed tool set or bypass its lifecycle fence.
|
|
562
|
-
|
|
563
|
-
Override lifetimes in `prepareStep` follow two explicit rules:
|
|
564
|
-
|
|
565
|
-
- **`instructions` is sticky across the remaining steps of the current attempt**
|
|
566
|
-
(and resets to `initialInstructions` if a provider retry starts a fresh
|
|
567
|
-
attempt). Later steps receive the carried value in `instructions` alongside
|
|
568
|
-
the unchanged `initialInstructions`, so a step can explicitly revert with
|
|
569
|
-
`{ instructions: initialInstructions }`. One-shot `protocol.acceptTerminal`
|
|
570
|
-
continuation instructions apply only to that continuation step and do not
|
|
571
|
-
overwrite carried `prepareStep` instructions.
|
|
572
|
-
- **`driver` applies to that single step only** (matching `activeTools`,
|
|
573
|
-
`toolChoice`, `responseFormat`, `cacheControl`, `headers`, `providerOptions`
|
|
574
|
-
and call settings). Omitting `driver` on the next step reverts to the run's
|
|
575
|
-
resolved default driver (or `input.driver` in `completeText`), and
|
|
576
|
-
`prepareStep` always receives that default driver in `driver`.
|
|
577
|
-
|
|
578
|
-
Context can grow between steps as tool results and deferred schemas enter the
|
|
579
|
-
provider prompt. When application budgeting can prove that the next assembled
|
|
580
|
-
step exceeds the selected model window, refuse it by type before that provider
|
|
581
|
-
call:
|
|
582
|
-
|
|
583
|
-
```ts
|
|
584
|
-
prepareStep: (step) => {
|
|
585
|
-
if (wouldExceedSelectedModelWindow(step)) {
|
|
586
|
-
throw new AgentContextOverflowError('Prepared step exceeds the selected model window')
|
|
587
|
-
}
|
|
588
|
-
return chooseProductStepOptions(step)
|
|
589
|
-
}
|
|
590
|
-
```
|
|
591
|
-
|
|
592
|
-
That deliberate refusal ends the run as `context_overflow` on the durable
|
|
593
|
-
record, delivery terminal and operator event. StitchKit does not inspect error
|
|
594
|
-
messages — it recognises failures by identity, not by text. A store refusing an
|
|
595
|
-
owned mutation ends the run `storage_conflict`; `protocol.acceptTerminal`
|
|
596
|
-
refusing a finished message ends it `output_rejected`; a check the SDK runs on
|
|
597
|
-
what this runtime handed it ends it `runtime_failure`. Every error the runtime
|
|
598
|
-
cannot identify as its own remains `provider_failure`, and operator-only
|
|
599
|
-
observability retains its original cause in all of them.
|
|
600
|
-
|
|
601
|
-
Completion validity belongs to the protocol and is checked before the terminal
|
|
602
|
-
CAS. Protocols that require a visible answer opt in explicitly:
|
|
603
|
-
|
|
604
|
-
```ts
|
|
605
|
-
const protocol = defineAgentProtocol({
|
|
606
|
-
context: ContextSchema,
|
|
607
|
-
inputMetadata: InputMetadataSchema,
|
|
608
|
-
terminalAcceptance: 'require-output',
|
|
609
|
-
})
|
|
610
|
-
```
|
|
611
|
-
|
|
612
|
-
The built-in rule accepts non-blank text, generated files, structured provider
|
|
613
|
-
parts, and a named tool-only `policy_stop`. The default is `allow-empty` for
|
|
614
|
-
protocols where an empty acknowledgement is meaningful. Pass a callback when
|
|
615
|
-
the product has a narrower definition; it receives the candidate message,
|
|
616
|
-
terminal reason and optional policy name, and runs before persistence. A false
|
|
617
|
-
result fails the candidate instead of rewriting an already committed success.
|
|
618
|
-
|
|
619
|
-
`loop.idleTimeoutMs` measures provider silence. It starts immediately before the
|
|
620
|
-
provider call, resets on stream activity, and pauses while local tools execute.
|
|
621
|
-
Resource preparation, child waits and approval waiting do not spend this budget.
|
|
622
|
-
The host gives tools their own deadlines. A stalled provider still aborts with
|
|
623
|
-
durable reason `timeout`; caller interruption and shutdown reach tools directly.
|
|
624
|
-
|
|
625
|
-
Reconnect loads the durable snapshot. Missing transient deltas do not mean the
|
|
626
|
-
canonical result was lost. Exactly-once external delivery requires the
|
|
627
|
-
application's transactional outbox or stable-ID deduplication.
|
|
628
|
-
|
|
629
|
-
## Managed tools
|
|
630
|
-
|
|
631
|
-
Durable `step` bodies return lossless JSON: finite numbers (excluding negative zero),
|
|
632
|
-
strings, booleans, null, dense arrays and plain data objects. Return `null` explicitly
|
|
633
|
-
for effect-only bodies and convert Date values to strings. Unsupported values are
|
|
634
|
-
refused after the body, so external effects still require idempotency. First results
|
|
635
|
-
and replay are detached snapshots; mutating a returned object cannot rewrite a record.
|
|
636
|
-
The optional [sandbox coding profile](sandbox.md#coding-tool-integration) reuses the
|
|
637
|
-
same tool mounting, authorization and output handling for namespace-backed commands.
|
|
638
|
-
|
|
639
|
-
Always compose `toolFenceLifecycle` into `mountAgentTools`. It checks ownership
|
|
640
|
-
before a managed side effect and again before accepting its result. Fence loss
|
|
641
|
-
uses an internal control signal: it stops the old loop and is not sent to the
|
|
642
|
-
model as a tool error.
|
|
643
|
-
|
|
644
|
-
`mountAgentTools` throws `AgentToolError` for failed runner outcomes. AgentRuntime
|
|
645
|
-
persists them with `outcome: 'error'`, publishes the same safe envelope, and replays
|
|
646
|
-
them as an error result on later turns. Classification comes from the execution
|
|
647
|
-
channel, never from inspecting output fields: a valid successful result such as
|
|
648
|
-
`{ error: 'domain value' }` remains successful. Typed `AppError` codes and safe
|
|
649
|
-
details may reach the model; arbitrary thrown causes are retained for local hooks
|
|
650
|
-
and reduced to `INTERNAL_SERVER_ERROR` outside.
|
|
651
|
-
|
|
652
|
-
The framework cannot undo an already-started non-cooperative external effect.
|
|
653
|
-
Pass the stable call/run idempotency identity into business mutations when the
|
|
654
|
-
effect must be replay-safe.
|
|
655
|
-
|
|
656
|
-
## History, provider metadata and files
|
|
657
|
-
|
|
658
|
-
`projectAgentHistory` converts canonical engine records into provider-valid
|
|
659
|
-
`AgentModelMessage[]` and pairs tool calls/results in persisted causal order. Adjacent
|
|
660
|
-
parallel calls stay in one assistant round and their adjacent results stay in
|
|
661
|
-
one tool round; a dependent call after those results starts a new assistant
|
|
662
|
-
round, and trailing final text remains after the last tool result. Provider-required metadata is kept
|
|
663
|
-
in a versioned opaque envelope and omitted from product delivery by default.
|
|
664
|
-
`projectAgentHistoryDetailed` additionally returns one inspectable decision per canonical record;
|
|
665
|
-
leading assistant records, crash drafts and unmatched tool chronology are never silently passed to
|
|
666
|
-
the provider.
|
|
667
|
-
|
|
668
|
-
`selectAgentHistory` is the non-destructive context-window selector. It removes only whole oldest
|
|
669
|
-
complete turns, protects system/summary, incomplete and configured recent turns, and reports every
|
|
670
|
-
keep/remove reason with measured/estimated/unavailable token provenance. An oversized protected turn
|
|
671
|
-
returns `oversized`; unavailable accounting returns `unavailable` without invented arithmetic.
|
|
672
|
-
|
|
673
|
-
`ComposedAgentPrompt.instructions` accepts `AgentInstructions` (a string, one
|
|
674
|
-
`AgentModelSystemMessage`, or an ordered array of `AgentModelSystemMessage`).
|
|
675
|
-
Use `adaptInstructions` when a provider needs cache control or provider options on
|
|
676
|
-
the system message:
|
|
677
|
-
|
|
678
|
-
```ts
|
|
679
|
-
prompt({
|
|
680
|
-
context,
|
|
681
|
-
signal,
|
|
682
|
-
adaptInstructions: (content) => ({
|
|
683
|
-
role: 'system',
|
|
684
|
-
content,
|
|
685
|
-
cacheControl: { type: 'ephemeral' },
|
|
686
|
-
}),
|
|
687
|
-
})
|
|
688
|
-
```
|
|
689
|
-
|
|
690
|
-
Attachments and generated files remain application-owned. The runtime only
|
|
691
|
-
stores a reference returned by `persistGeneratedFile`; it never silently puts
|
|
692
|
-
base64 blobs into the neutral history store.
|
|
693
|
-
|
|
694
|
-
To send a stored attachment back to a multimodal model, configure
|
|
695
|
-
`history.resolveFile`. It maps the neutral file reference to tagged
|
|
696
|
-
`AgentModelFileData` (`{ type: 'data' | 'url' | 'reference' | 'text', ... }`). Without a resolver the
|
|
697
|
-
`unresolvedFile` policy applies, and it is **`omit`** by default: the file part
|
|
698
|
-
simply does not reach the provider. Choose `text` for a describing placeholder —
|
|
699
|
-
the filename or media type, never the storage reference, because that string is
|
|
700
|
-
an address inside your infrastructure and this content travels upstream — or
|
|
701
|
-
`error` to fail loudly. The `error` message does name the reference: it is
|
|
702
|
-
thrown into your process, where you are owed the whole story.
|
|
703
|
-
|
|
704
|
-
## Compaction
|
|
705
|
-
|
|
706
|
-
`structuredCompaction` summarizes complete provider-valid turn groups outside
|
|
707
|
-
the store lock, then calls `replaceCompactedRange` against the exact snapshot
|
|
708
|
-
version. A concurrent input produces `conflict`; the stale summary is not
|
|
709
|
-
applied. Summary records use the dedicated `summary` role and project to a
|
|
710
|
-
provider system message. The consumer supplies the structured summary schema
|
|
711
|
-
and prompt. Pass `previousSummary` for a direct call, or configure
|
|
712
|
-
`readPreviousSummary` for runtime-managed compaction, to merge and atomically
|
|
713
|
-
replace a leading summary on the next compaction.
|
|
714
|
-
Set `maxAttempts` to allow bounded conflict recovery. Every retry reloads the snapshot, reselects the
|
|
715
|
-
eligible range and recomputes the summary; the stale summary is never retried. Inside
|
|
716
|
-
`createAgentRuntime`, `history.compact` runs after `models.resolve` and receives the resolved
|
|
717
|
-
`model` descriptor (including `contextWindow`), `tools`, and `context`. `structuredCompaction`'s
|
|
718
|
-
`summarize` callback may return either the parsed summary directly or `{ summary, usage }` so
|
|
719
|
-
`structuredCompaction` accumulates `usage` across `maxAttempts` CAS retries and hands it directly to
|
|
720
|
-
run totals and `onStepSpend`.
|
|
721
|
-
|
|
722
|
-
### Recovering a prefix after a failed turn
|
|
723
|
-
|
|
724
|
-
The default evidence policy omits failed assistants. A failed turn therefore stops the
|
|
725
|
-
compactable prefix, including completed turns after it. A terminal failure is not an
|
|
726
|
-
unanswered tool call, but opting its partial evidence into a summary is an explicit host
|
|
727
|
-
decision. Use the existing `evidencePolicy: { failedAssistant: 'assistant-marked' }` on
|
|
728
|
-
`structuredCompaction` (or `selectCompactableHistory`) when that evidence is wanted.
|
|
729
|
-
The same policy belongs on the summarizer's history projection and on any corresponding
|
|
730
|
-
token-budget selection. Stored statuses remain unchanged.
|
|
731
|
-
|
|
732
|
-
The summarizer receives **raw** `eligibleMessages`, not provider messages and not an
|
|
733
|
-
automatic failure marker. Project them with the same policy before sending them to a
|
|
734
|
-
model, and preserve failed outcomes in the application's structured summary and prompt:
|
|
735
|
-
|
|
736
|
-
```ts
|
|
737
|
-
const evidencePolicy: AgentHistoryEvidencePolicy = {
|
|
738
|
-
failedAssistant: 'assistant-marked',
|
|
739
|
-
}
|
|
740
|
-
|
|
741
|
-
// Inside structuredCompaction({ evidencePolicy, ... }).summarize:
|
|
742
|
-
const projected = await projectAgentHistoryDetailed(eligibleMessages, {
|
|
743
|
-
evidencePolicy,
|
|
744
|
-
incompleteToolTurn: 'error',
|
|
745
|
-
})
|
|
746
|
-
const failedMessageIds = eligibleMessages
|
|
747
|
-
.filter(message => message.role === 'assistant' && message.status === 'failed')
|
|
748
|
-
.map(message => message.id)
|
|
749
|
-
// Pass projected.messages, projected.system and failedMessageIds to the host's
|
|
750
|
-
// summarizer. Its schema/prompt must retain failures and uncertain effects as
|
|
751
|
-
// such, merge previousSummary, and never describe partial output as success.
|
|
752
|
-
```
|
|
753
|
-
|
|
754
|
-
An opted-in failed assistant projects an explicit non-success marker even when it has
|
|
755
|
-
no text or only control parts. A dangling call, unresolved approval, invalid result
|
|
756
|
-
chronology or a user input with no assistant remains a barrier under either policy.
|
|
757
|
-
Raw whole-turn completeness does not guarantee that every record can be projected:
|
|
758
|
-
for example, a call and its result split across records may be rejected by the projector.
|
|
759
|
-
`incompleteToolTurn: 'error'` makes that rejection stop summarization; the original history
|
|
760
|
-
stays canonical. A host with such records must use a status-aware summarizer that explicitly
|
|
761
|
-
represents every relevant record, or retain the range. Do not silently summarize an omitted
|
|
762
|
-
exchange, filter the failed record out of the replacement range, rewrite its status or skip
|
|
763
|
-
over an incomplete turn. The replacement remains one contiguous prefix under snapshot CAS.
|
|
764
|
-
|
|
765
|
-
Provider chronology and external effect authority answer different questions (ADR 0269).
|
|
766
|
-
A matching `tool-result` with `outcome: 'error'` and an application code such as `UNKNOWN`
|
|
767
|
-
closes the provider exchange; it does **not** prove the external effect failed or succeeded.
|
|
768
|
-
Compaction changes the model-history projection, not the canonical event journal or the
|
|
769
|
-
retained terminal admission receipt. The `durability/effect` intent, accepted proof and
|
|
770
|
-
uncertain outcome remain available after compaction and archive restore. A reconstructed
|
|
771
|
-
`createLocalStepDurability` using the original `(conversationId, runId, effectName)` returns
|
|
772
|
-
the accepted proof, reconciles a bare intent, or returns `uncertain` without calling `run`
|
|
773
|
-
again. It does not deduplicate a new run or a newly named effect. Standalone effect callers
|
|
774
|
-
still own the exclusive execution lease; sharing a ledger is not an atomic claim.
|
|
775
|
-
An application-owned receipt outside that journal retains its own recovery rules and must
|
|
776
|
-
not be discarded because a history turn became compactable.
|
|
777
|
-
|
|
778
|
-
### Compacting without the store
|
|
779
|
-
|
|
780
|
-
The *selection* inside compaction needs no store, no version and no runtime, so
|
|
781
|
-
it is published on its own as `selectCompactableHistory` — for an application
|
|
782
|
-
that drives the model itself and keeps its own history (→ ADR 0142):
|
|
783
|
-
|
|
784
|
-
```ts
|
|
785
|
-
import { selectCompactableHistory } from 'stitchkit/agent-runtime'
|
|
786
|
-
|
|
787
|
-
const { leadingSummary, compactable, retained } = selectCompactableHistory({
|
|
788
|
-
messages,
|
|
789
|
-
keepRecentTurns: 3,
|
|
790
|
-
})
|
|
791
|
-
if (compactable.length > 0) {
|
|
792
|
-
const summary = await summarize(compactable, leadingSummary)
|
|
793
|
-
messages = [summary, ...retained] // replace the old summary, never stack one
|
|
794
|
-
}
|
|
795
|
-
```
|
|
796
|
-
|
|
797
|
-
`compactable` is the oldest **whole complete** turns and `retained` is
|
|
798
|
-
everything the model must still hear; together they are the input, in order. A
|
|
799
|
-
turn holding a tool call whose result never arrived is never eligible, and
|
|
800
|
-
neither is anything after it: half a turn hands the provider a call with no
|
|
801
|
-
result, which most of them refuse outright.
|
|
802
|
-
|
|
803
|
-
`structuredCompaction` calls this same function, so the published selection and
|
|
804
|
-
the runtime's cannot drift into two behaviours. What it adds is the part that
|
|
805
|
-
does need the store — writing the result back under a version check.
|
|
806
|
-
|
|
807
|
-
Deciding *when* to compact is yours: `AgentRuntimeRunContext.contextUsage`
|
|
808
|
-
carries the last step's prompt size beside the model's window, and dividing them
|
|
809
|
-
is one line where the threshold is decided. The core does not own that ratio, on
|
|
810
|
-
purpose — see ADR 0142 for what it publishes and what it declines to.
|