stitchkit 0.68.3 → 0.68.5

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.
Files changed (58) hide show
  1. package/README.md +4 -1
  2. package/dist/agent-runtime/context-refusal.d.ts +13 -0
  3. package/dist/agent-runtime/context-refusal.d.ts.map +1 -0
  4. package/dist/agent-runtime/event-schema.d.ts +1341 -0
  5. package/dist/agent-runtime/event-schema.d.ts.map +1 -0
  6. package/dist/agent-runtime/events.d.ts +2 -1347
  7. package/dist/agent-runtime/events.d.ts.map +1 -1
  8. package/dist/agent-runtime/run-execution.d.ts +2 -0
  9. package/dist/agent-runtime/run-execution.d.ts.map +1 -1
  10. package/dist/agent-runtime/runtime.d.ts +6 -0
  11. package/dist/agent-runtime/runtime.d.ts.map +1 -1
  12. package/dist/agent-runtime/store-driver.d.ts.map +1 -1
  13. package/dist/agent-runtime/store.d.ts +4 -6
  14. package/dist/agent-runtime/store.d.ts.map +1 -1
  15. package/dist/agent-runtime-browser.d.ts +4 -0
  16. package/dist/agent-runtime-browser.d.ts.map +1 -0
  17. package/dist/agent-runtime-browser.js +420 -0
  18. package/dist/agent-runtime.d.ts +1 -0
  19. package/dist/agent-runtime.d.ts.map +1 -1
  20. package/dist/agent-runtime.js +149 -97
  21. package/dist/browser/cancellation.d.ts.map +1 -1
  22. package/dist/browser/contract-stream.d.ts.map +1 -1
  23. package/dist/browser/stream.d.ts +3 -0
  24. package/dist/browser/stream.d.ts.map +1 -1
  25. package/dist/cli.js +5 -5
  26. package/dist/contract/define.d.ts +39 -6
  27. package/dist/contract/define.d.ts.map +1 -1
  28. package/dist/contract/index.d.ts +1 -1
  29. package/dist/contract/index.d.ts.map +1 -1
  30. package/dist/contract/index.js +1 -1
  31. package/dist/{index-cz32amcb.js → index-04agqrs8.js} +2 -2
  32. package/dist/{index-cszjsxy5.js → index-1bmpkhj2.js} +3 -3
  33. package/dist/{index-wqyrvhzz.js → index-3ydx9j01.js} +2 -2
  34. package/dist/{index-69m2278y.js → index-51a19y3v.js} +1 -1
  35. package/dist/{index-3vq6we8m.js → index-6tqys26z.js} +16 -6
  36. package/dist/{index-7etq650s.js → index-88yyydag.js} +1 -1
  37. package/dist/{index-g2j2m6vv.js → index-9t2tdk1x.js} +2 -2
  38. package/dist/{index-9ky9hhg3.js → index-bmmtz6r9.js} +14 -0
  39. package/dist/{index-dafax5md.js → index-hmfpjnh7.js} +1 -1
  40. package/dist/{index-cq9q73nf.js → index-j2nq04z6.js} +14 -0
  41. package/dist/{index-2ve29dzn.js → index-n34x0q5e.js} +49 -26
  42. package/dist/{index-v5bayx1z.js → index-r5s4wqb5.js} +7 -3
  43. package/dist/{index-pr0qsmjy.js → index-z575awm9.js} +1 -1
  44. package/dist/index.js +54 -27
  45. package/dist/internal/bounded-lines.d.ts +1 -1
  46. package/dist/internal/bounded-lines.d.ts.map +1 -1
  47. package/dist/node.js +4 -4
  48. package/dist/observability/index.js +3 -3
  49. package/dist/remote.js +3 -3
  50. package/dist/server/contract-stream.d.ts.map +1 -1
  51. package/dist/server/index.js +10 -7
  52. package/dist/server/openapi.d.ts.map +1 -1
  53. package/dist/testing/agent-store-conformance.d.ts.map +1 -1
  54. package/dist/testing.js +29 -7
  55. package/dist/tool-invoker.js +5 -5
  56. package/dist/tools.js +9 -9
  57. package/llms-full.txt +119 -8
  58. package/package.json +6 -2
@@ -13,7 +13,7 @@ import {
13
13
  sseRoute,
14
14
  streamingRoute,
15
15
  webSocketLane
16
- } from "../index-3vq6we8m.js";
16
+ } from "../index-6tqys26z.js";
17
17
  import {
18
18
  composeAuthHooks,
19
19
  createAuthHook,
@@ -26,7 +26,7 @@ import {
26
26
  signJwt,
27
27
  verifyJwt,
28
28
  verifyPkce
29
- } from "../index-wqyrvhzz.js";
29
+ } from "../index-3ydx9j01.js";
30
30
  import {
31
31
  DEFAULT_CORS_ALLOW_HEADERS,
32
32
  DEFAULT_CORS_EXPOSE_HEADERS,
@@ -40,7 +40,7 @@ import {
40
40
  defineMultipartStream,
41
41
  implement,
42
42
  implementRegistry
43
- } from "../index-pr0qsmjy.js";
43
+ } from "../index-z575awm9.js";
44
44
  import {
45
45
  extractIp,
46
46
  generateTraceId,
@@ -48,7 +48,7 @@ import {
48
48
  getTraceId,
49
49
  resolveSocketIp,
50
50
  resolveTraceId
51
- } from "../index-69m2278y.js";
51
+ } from "../index-51a19y3v.js";
52
52
  import {
53
53
  isWithinDir,
54
54
  realPathWithinDir
@@ -69,7 +69,7 @@ import {
69
69
  inputIsQuery,
70
70
  parseSSE,
71
71
  streamSSE
72
- } from "../index-v5bayx1z.js";
72
+ } from "../index-r5s4wqb5.js";
73
73
  import {
74
74
  DEFAULT_CONTRACT_STREAM_FRAME_BYTES,
75
75
  errorCode,
@@ -78,7 +78,7 @@ import {
78
78
  normalizeError,
79
79
  parseTrailingWildcard,
80
80
  zodIssues
81
- } from "../index-9ky9hhg3.js";
81
+ } from "../index-bmmtz6r9.js";
82
82
  import {
83
83
  isRecord
84
84
  } from "../index-smpbdg6k.js";
@@ -799,7 +799,10 @@ function generateOpenApiDocument(config) {
799
799
  schema: { type: "string" },
800
800
  "x-stitchkit-item-schema": safeJson(method.stream.item, "output"),
801
801
  "x-stitchkit-max-frame-bytes": method.stream.maxFrameBytes ?? DEFAULT_CONTRACT_STREAM_FRAME_BYTES,
802
- "x-stitchkit-terminal-required": Boolean(method.stream.terminal)
802
+ "x-stitchkit-terminal-required": Boolean(method.stream.terminal),
803
+ "x-stitchkit-stream-framing": method.stream.framing ?? "envelope",
804
+ "x-stitchkit-stream-completion": method.stream.completion ?? "stream-end",
805
+ "x-stitchkit-final-line": method.stream.finalLine ?? "allow"
803
806
  }
804
807
  }
805
808
  };
@@ -1 +1 @@
1
- {"version":3,"file":"openapi.d.ts","sourceRoot":"","sources":["../../src/server/openapi.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAOH,OAAO,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,UAAU,EAAE,M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M,wBAAwB,CAAC;AAEhE;;;;;;;;;GASG;AACH,MAAM,WAAW,4BAA4B;IAC3C;;;;OAIG;IACH,QAAQ,CAAC,eAAe,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7C;AAED,MAAM,WAAW,2BAA2B;IAC1C;;;;OAIG;IACH,WAAW,CACT,OAAO,EAAE,4BAA4B,GACpC,iBAAiB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;IAClD;;;;;;;;OAQG;IACH,OAAO,CAAC,CAAC,OAAO,EAAE,4BAA4B,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACvE;AAwCD,gFAAgF;AAChF,wBAAsB,wBAAwB,CAC5C,MAAM,EAAE,2BAA2B,GAClC,OAAO,CAAC,IAAI,CAAC,CA2Bf"}
1
+ {"version":3,"file":"agent-store-conformance.d.ts","sourceRoot":"","sources":["../../src/testing/agent-store-conformance.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAEhE;;;;;;;;;GASG;AACH,MAAM,WAAW,4BAA4B;IAC3C;;;;OAIG;IACH,QAAQ,CAAC,eAAe,EAAE,SAAS,MAAM,EAAE,CAAC;CAC7C;AAED,MAAM,WAAW,2BAA2B;IAC1C;;;;OAIG;IACH,WAAW,CACT,OAAO,EAAE,4BAA4B,GACpC,iBAAiB,GAAG,OAAO,CAAC,iBAAiB,CAAC,CAAC;IAClD;;;;;;;;OAQG;IACH,OAAO,CAAC,CAAC,OAAO,EAAE,4BAA4B,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACvE;AAwCD,gFAAgF;AAChF,wBAAsB,wBAAwB,CAC5C,MAAM,EAAE,2BAA2B,GAClC,OAAO,CAAC,IAAI,CAAC,CAiCf"}
package/dist/testing.js CHANGED
@@ -25,11 +25,11 @@ import {
25
25
  import {
26
26
  createClient,
27
27
  createClients
28
- } from "./index-2ve29dzn.js";
29
- import"./index-v5bayx1z.js";
28
+ } from "./index-n34x0q5e.js";
29
+ import"./index-r5s4wqb5.js";
30
30
  import {
31
31
  joinRoutePath
32
- } from "./index-9ky9hhg3.js";
32
+ } from "./index-bmmtz6r9.js";
33
33
  import {
34
34
  isRecord
35
35
  } from "./index-smpbdg6k.js";
@@ -145,7 +145,13 @@ function requireOutcome(actual, expected) {
145
145
  async function runAgentStoreConformance(config) {
146
146
  const run = `conformance-${crypto.randomUUID()}`;
147
147
  const context = {
148
- conversationIds: [run, `${run}-recovery`, `${run}-absorb`, `${run}-causal-history`]
148
+ conversationIds: [
149
+ run,
150
+ `${run}-recovery`,
151
+ `${run}-absorb`,
152
+ `${run}-causal-history`,
153
+ `${run}-causal-active`
154
+ ]
149
155
  };
150
156
  const store = await config.createStore(context);
151
157
  let failure;
@@ -169,10 +175,11 @@ async function conformanceScenario(store, conversationIds) {
169
175
  conversationId,
170
176
  recoveryConversationId,
171
177
  absorbConversationId,
172
- causalHistoryConversationId
178
+ causalHistoryConversationId,
179
+ causalActiveConversationId
173
180
  ] = conversationIds;
174
- if (!conversationId || !recoveryConversationId || !absorbConversationId || !causalHistoryConversationId) {
175
- throw new Error("Agent store conformance requires four conversation identities");
181
+ if (!conversationId || !recoveryConversationId || !absorbConversationId || !causalHistoryConversationId || !causalActiveConversationId) {
182
+ throw new Error("Agent store conformance requires five conversation identities");
176
183
  }
177
184
  const absentConversationId = `${conversationId}-absent`;
178
185
  const firstInput = userMessage(conversationId, "input-1");
@@ -554,8 +561,23 @@ async function conformanceScenario(store, conversationIds) {
554
561
  throw new Error("Abandon recovery did not atomically terminalize its assistant record");
555
562
  }
556
563
  await assertCausalHistoryOrder(store, causalHistoryConversationId);
564
+ await assertActiveRunCausalOrder(store, causalActiveConversationId);
557
565
  await assertAbsorptionIsAtomic(store, absorbConversationId);
558
566
  }
567
+ async function assertActiveRunCausalOrder(store, conversationId) {
568
+ for (const id of ["z-causal-run", "a-causal-run"]) {
569
+ const input = userMessage(conversationId, `${id}-input`);
570
+ requireOutcome(await store.acceptInputAndAssignRun({
571
+ idempotencyKey: id,
572
+ input,
573
+ run: queuedRun(conversationId, input.id, id)
574
+ }), "applied");
575
+ }
576
+ const active = await store.listActiveRuns(conversationId);
577
+ if (active.map((run) => run.id).join(",") !== "z-causal-run,a-causal-run") {
578
+ throw new Error("listActiveRuns must preserve causal history order for timestamp ties");
579
+ }
580
+ }
559
581
  async function assertCausalHistoryOrder(store, conversationId) {
560
582
  const leadInput = userMessage(conversationId, "causal-input-1");
561
583
  const leadRun = queuedRun(conversationId, leadInput.id, "causal-run-1");
@@ -1,13 +1,13 @@
1
1
  import {
2
2
  createToolInvoker
3
- } from "./index-g2j2m6vv.js";
4
- import"./index-7etq650s.js";
5
- import"./index-cz32amcb.js";
6
- import"./index-69m2278y.js";
3
+ } from "./index-9t2tdk1x.js";
4
+ import"./index-88yyydag.js";
5
+ import"./index-04agqrs8.js";
6
+ import"./index-51a19y3v.js";
7
7
  import"./index-vkk06pv1.js";
8
8
  import"./index-6djpbnda.js";
9
9
  import"./index-cby4ar3v.js";
10
- import"./index-9ky9hhg3.js";
10
+ import"./index-bmmtz6r9.js";
11
11
  import"./index-smpbdg6k.js";
12
12
  import"./index-0w9abg87.js";
13
13
  import"./index-6k1937bx.js";
package/dist/tools.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  redact
3
- } from "./index-dafax5md.js";
3
+ } from "./index-hmfpjnh7.js";
4
4
  import {
5
5
  signJwt,
6
6
  verifyPkce
7
- } from "./index-wqyrvhzz.js";
7
+ } from "./index-3ydx9j01.js";
8
8
  import {
9
9
  DEFAULT_CORS_ALLOW_HEADERS,
10
10
  DEFAULT_PROCESS_SIGNALS,
@@ -12,10 +12,10 @@ import {
12
12
  defaultSignalSource,
13
13
  guardSignalCallback,
14
14
  reportSignalError
15
- } from "./index-pr0qsmjy.js";
15
+ } from "./index-z575awm9.js";
16
16
  import {
17
17
  createToolInvoker
18
- } from "./index-g2j2m6vv.js";
18
+ } from "./index-9t2tdk1x.js";
19
19
  import {
20
20
  WaitTimeoutError,
21
21
  collectToolSurface,
@@ -27,24 +27,24 @@ import {
27
27
  fetchPinnedDocument,
28
28
  readCapped,
29
29
  runWaitOperation
30
- } from "./index-cszjsxy5.js";
30
+ } from "./index-1bmpkhj2.js";
31
31
  import {
32
32
  collectTools,
33
33
  createToolRunner,
34
34
  formatToolError
35
- } from "./index-7etq650s.js";
35
+ } from "./index-88yyydag.js";
36
36
  import {
37
37
  ToolExecutionControlError,
38
38
  coerceJsonArgs,
39
39
  executeToolMethod,
40
40
  isToolExecutionControlError,
41
41
  toolResultFromError
42
- } from "./index-cz32amcb.js";
42
+ } from "./index-04agqrs8.js";
43
43
  import {
44
44
  getRequestContext,
45
45
  getTraceId,
46
46
  runWithRequestContext
47
- } from "./index-69m2278y.js";
47
+ } from "./index-51a19y3v.js";
48
48
  import {
49
49
  ManagedFileError
50
50
  } from "./index-bfcpjw20.js";
@@ -66,7 +66,7 @@ import {
66
66
  defineContract,
67
67
  normalizeError,
68
68
  resolvePropagationContext
69
- } from "./index-9ky9hhg3.js";
69
+ } from "./index-bmmtz6r9.js";
70
70
  import {
71
71
  isRecord
72
72
  } from "./index-smpbdg6k.js";
package/llms-full.txt CHANGED
@@ -61,6 +61,7 @@ own, recorded as an ADR.
61
61
  | `stitchkit/react` | browser | stable | `createCursorQuery`, `createCacheBridge` |
62
62
  | `stitchkit/agent-runtime` | server | evolving<br>_redefined in 9 of the 13 minors since 0.56.2, most recently 0.66.0_ | optional durable conversation/run loop, history, models, prompts, fencing and events |
63
63
  | `stitchkit/agent-runtime/openrouter` | server | evolving | isolated OpenRouter language-model adapter |
64
+ | `stitchkit/agent-runtime/browser` | browser + server | evolving | canonical agent records, events and reconnect cursor without execution or sinks |
64
65
  | `stitchkit/application` | server | evolving<br>_redefined in 3 of the 13 minors since 0.56.2, most recently 0.67.0_ | managed resource graph, readiness, admission, schedules and bounded shutdown |
65
66
  | `stitchkit/application/grammy` | server | evolving | isolated grammY polling and webhook lifecycle adapters |
66
67
  | `stitchkit/application/opentelemetry` | server | evolving | maps application snapshots onto an injected OpenTelemetry `Meter` |
@@ -1574,6 +1575,27 @@ multipart or tool exposure. They do not provide replay, cursors or durable
1574
1575
  subscriptions. Keep using `streamingRoute` for an application-owned protocol and
1575
1576
  `rawResponse` for arbitrary response bodies. → ADR 0117.
1576
1577
 
1578
+ For an existing schema-owned NDJSON protocol, opt into direct item frames and
1579
+ terminal-owned completion:
1580
+
1581
+ ```ts
1582
+ stream: {
1583
+ item: Item,
1584
+ framing: 'item',
1585
+ completion: 'terminal',
1586
+ terminal: z.object({ kind: z.literal('complete') }).loose(),
1587
+ finalLine: 'require-newline',
1588
+ }
1589
+ ```
1590
+
1591
+ `item` framing is NDJSON-only and requires terminal completion. The server
1592
+ writes each validated item directly, stops the source after the terminal and
1593
+ never reads trailing producer values. Because this wire has no framework error
1594
+ envelope, any producer/lifetime failure before terminal closes the response;
1595
+ the typed client reports `STREAM_TERMINAL_MISSING`. The terminal item therefore
1596
+ proves success without weakening safe post-header failure semantics. Existing
1597
+ streams retain the envelope and explicit end frame by default. → ADR 0126.
1598
+
1577
1599
  ### SSE streaming
1578
1600
 
1579
1601
  `streamSSE` returns a `Response`, so its endpoint declares
@@ -2407,6 +2429,33 @@ wire `end` frame and, when declared, at least one matching terminal item; EOF is
2407
2429
  converge on the request operation. See the
2408
2430
  [server half](./server.md#contract-first-streams). → ADR 0117.
2409
2431
 
2432
+ The request deadline bounds the wait for response headers. Once headers arrive,
2433
+ that timer is cleared, while the caller signal remains attached to the response
2434
+ body until it ends or is cancelled. This is the same for a Fetch-config client,
2435
+ `createHttpClient`, the Bun-only `unix` convenience and an injected portable
2436
+ Unix transport. Cancelling a quiet stream therefore releases its server source
2437
+ and transport connection instead of only settling the local iterator.
2438
+
2439
+ An established NDJSON protocol may keep its item schema as the complete wire
2440
+ frame. This mode requires a terminal item because an unwrapped response has no
2441
+ separate safe error/end envelope:
2442
+
2443
+ ```ts
2444
+ stream: {
2445
+ item: Progress,
2446
+ framing: 'item',
2447
+ completion: 'terminal',
2448
+ terminal: z.object({ kind: z.literal('complete') }).loose(),
2449
+ finalLine: 'require-newline',
2450
+ }
2451
+ ```
2452
+
2453
+ The matching terminal item ends the operation. Before `next()` returns that
2454
+ item, the client aborts the owned request and cancels its body reader; trailing
2455
+ frames are not read. EOF first is `STREAM_TERMINAL_MISSING`. The defaults remain
2456
+ `framing: 'envelope'`, `completion: 'stream-end'` and `finalLine: 'allow'`.
2457
+ → ADR 0126.
2458
+
2410
2459
  ## SSE
2411
2460
 
2412
2461
  For a streaming endpoint, consume the response with `parseSSE`:
@@ -2460,6 +2509,10 @@ implementations. One line is bounded by `maxLineBytes` (default 1 MiB), UTF-8 is
2460
2509
  decoded strictly and malformed input throws. Passing `onParseError` explicitly
2461
2510
  selects tolerant skip-and-report behaviour.
2462
2511
 
2512
+ Set `finalLine: 'require-newline'` when the final newline is part of the
2513
+ protocol's truncation proof. The default `allow` continues to accept one valid
2514
+ final JSON document without a newline.
2515
+
2463
2516
 
2464
2517
  ==============================================================================
2465
2518
  # Guide: MCP & agents (docs/guide/mcp-and-agents.md)
@@ -3697,6 +3750,21 @@ If the application already owns that loop, continue importing `mountAgent` from
3697
3750
  this entrypoint uses the tool executor from it, but pulls no MCP peer, so
3698
3751
  choosing `mountAgent` alone costs you nothing from here.
3699
3752
 
3753
+ UI and shared DTO code must import canonical records and delivery validation from
3754
+ `stitchkit/agent-runtime/browser`, not from the server runtime barrel:
3755
+
3756
+ ```ts
3757
+ import {
3758
+ AgentRunSchema,
3759
+ AgentRuntimeEventSchema,
3760
+ advanceAgentRuntimeEventCursor,
3761
+ } from 'stitchkit/agent-runtime/browser'
3762
+ ```
3763
+
3764
+ This browser-safe entrypoint re-exports the same schemas and inferred types used
3765
+ by the runtime. It intentionally excludes model construction, execution,
3766
+ persistence, event sinks and every Node context dependency.
3767
+
3700
3768
  ## Install
3701
3769
 
3702
3770
  ```sh
@@ -3721,6 +3789,7 @@ bun add @openrouter/ai-sdk-provider
3721
3789
  ```ts
3722
3790
  import { z } from 'zod'
3723
3791
  import {
3792
+ AgentContextOverflowError,
3724
3793
  composeAgentPrompt,
3725
3794
  createAgentRuntime,
3726
3795
  createMemoryAgentRuntimeStore,
@@ -4144,12 +4213,18 @@ checkpoint/terminal CAS and tool context, so a distributed adapter can reject an
4144
4213
  an owner label is reused. Lease expiry and renewal remain application-owned.
4145
4214
 
4146
4215
  On startup, `runtime.recover({ resolveContext })` consumes bounded lightweight
4147
- pages. Its safe default resumes queued runs and reports acquired or
4216
+ pages, then restores each conversation's canonical causal order before any run
4217
+ acquires. Scan identifiers and page boundaries therefore never become queue
4218
+ order. Its safe default resumes queued runs and reports acquired or
4148
4219
  `interrupt_requested` runs as skipped. A policy may requeue acquired work only
4149
4220
  with explicit replay-safe evidence, or abandon it only with stale-owner
4150
- evidence. Each attempted run returns its own outcome/error; `pageSize`,
4151
- `maxRuns`, and `signal` bound the pass. `runtime.resume(...)` remains available
4152
- for one known queued record.
4221
+ evidence. Each attempted run returns its own outcome/error; a `resumed` or
4222
+ `requeued` outcome also exposes the terminal `result` promise. The outcome is
4223
+ reported only after durable acquisition, so a lost acquisition is `failed`
4224
+ rather than a successful-looking handoff. `pageSize`, `maxRuns`, and `signal`
4225
+ bound the pass. `runtime.resume(...)` remains available for one known queued
4226
+ record; its `accepted` promise likewise means that the recovered run acquired
4227
+ durable ownership, while `result` carries terminal completion.
4153
4228
 
4154
4229
  Canonical records currently write `schemaVersion: 1`. A durable adapter owns
4155
4230
  read-time migration of older rows: migrate to the current shape at its storage
@@ -4199,6 +4274,25 @@ is the reserved built-in policy name. `loop.prepareStep` is the controlled AI
4199
4274
  SDK step boundary for changing active tools, model, instructions or messages.
4200
4275
  It cannot replace the managed tool set or bypass its lifecycle fence.
4201
4276
 
4277
+ Context can grow between steps as tool results and deferred schemas enter the
4278
+ provider prompt. When application budgeting can prove that the next assembled
4279
+ step exceeds the selected model window, refuse it by type before that provider
4280
+ call:
4281
+
4282
+ ```ts
4283
+ prepareStep: (step) => {
4284
+ if (wouldExceedSelectedModelWindow(step)) {
4285
+ throw new AgentContextOverflowError('Prepared step exceeds the selected model window')
4286
+ }
4287
+ return chooseProductStepOptions(step)
4288
+ }
4289
+ ```
4290
+
4291
+ That deliberate refusal ends the run as `context_overflow` on the durable
4292
+ record, delivery terminal and operator event. Stitchkit does not inspect error
4293
+ messages: every other `prepareStep` or provider error remains
4294
+ `provider_failure`, and operator-only observability retains its original cause.
4295
+
4202
4296
  Completion validity belongs to the protocol and is checked before the terminal
4203
4297
  CAS. Protocols that require a visible answer opt in explicitly:
4204
4298
 
@@ -10909,8 +11003,10 @@ The browser-and-server entrypoint. Re-exports everything from
10909
11003
  | `bindRealtimeClient` | function | bind contract validation and typed acknowledgements to an existing Stitchkit client transport without owning its lifecycle |
10910
11004
  | `createRetainedTopics` | function | retained last-value store for sticky events — [guide](../guide/realtime.md#sticky-events) |
10911
11005
  | `parseSSE` | function | parse an SSE `Response` into an async generator — [guide](../guide/client.md#sse) |
10912
- | `parseNDJSON` | function | parse an NDJSON `Response`; blank keep-alive lines are skipped — [guide](../guide/client.md#ndjson) |
10913
- | `ContractStreamFrameSchema` / `ContractStreamFrame` | schema / _type_ | internal-on-the-wire `data` / safe `error` / `end` envelope of a contract-first stream |
11006
+ | `parseNDJSON` | function | parse bounded fatal-UTF-8 NDJSON; blank keep-alives are skipped and `finalLine: 'require-newline'` can make the delimiter mandatory — [guide](../guide/client.md#ndjson) |
11007
+ | `ContractStreamFrameSchema` / `ContractStreamFrame` | schema / _type_ | default on-the-wire `data` / safe `error` / `end` envelope of a contract-first stream |
11008
+ | `ContractStreamFraming` / `ContractStreamCompletion` | _types_ | opt-in item-vs-envelope framing and terminal-vs-stream-end completion policies |
11009
+ | `StreamFinalLinePolicy` | _type_ | permissive or newline-required final NDJSON line policy |
10914
11010
  | `DEFAULT_CONTRACT_STREAM_FRAME_BYTES` | const | default maximum encoded contract-stream frame: 256 KiB |
10915
11011
  | `SocketIOClient` | _type_ | low-level client handle; `emit` reports disconnected drops and `emitWithAck` exposes the native Promise primitive used by validated `request()` |
10916
11012
  | `SocketIOClientPeerLoaders` | _type_ | inject `socket.io-client` so a bundler can put it in a self-contained artifact |
@@ -10987,7 +11083,7 @@ from the root `stitchkit`.
10987
11083
  | `ContractDef` | _type_ | a defined contract |
10988
11084
  | `ContractMeta` | _type_ | a contract's `prefix` + optional `scope` and `meta` (a default every endpoint shallow-merges over) |
10989
11085
  | `EndpointDef` | _type_ | a single endpoint definition; `output` declares JSON response presence (`null` is data, `undefined` is invalid) |
10990
- | `EndpointStreamDescriptor` | _type_ | HTTP-only schema-derived stream declaration: item schema, NDJSON/SSE framing, frame/lifetime/heartbeat/idle bounds and optional terminal predicate — [guide](../guide/server.md#contract-first-streams) |
11086
+ | `EndpointStreamDescriptor` | _type_ | HTTP-only schema-derived stream declaration: item schema, envelope/item framing, stream-end/terminal completion, NDJSON/SSE encoding and frame/lifetime/heartbeat/idle bounds — [guide](../guide/server.md#contract-first-streams) |
10991
11087
  | `HeadEndpointDef` | _type_ | explicit HTTP-only, bodyless `HEAD` endpoint definition |
10992
11088
  | `EndpointResponseMeta` | _type_ | static success metadata declared by an HTTP-only typed-data endpoint |
10993
11089
  | `ResponseMetadata` | _type_ | per-request outbound collector exposed as `ctx.response` only for a `responseMeta` endpoint |
@@ -11444,11 +11540,12 @@ Server-only optional application runtime. See the
11444
11540
  | `createAgentSessionCoordinator` | function | strict process-local queue/interrupt/supersede lifecycle |
11445
11541
  | `AgentRuntimeStopPolicy` | _type_ | named custom AI SDK stop condition persisted and published on policy stop |
11446
11542
  | `AgentRuntimePrepareStep` | _type_ | per-run controlled step callback with typed domain context and managed run signal/fence |
11543
+ | `AgentContextOverflowError` | class | deliberate application budget refusal thrown from `loop.prepareStep`; terminalizes as `context_overflow` without classifying arbitrary error text |
11447
11544
  | `AgentRuntimeRecordIds` | _type_ | optional caller-provided input, run and assistant IDs for stable application records |
11448
11545
  | `AgentRuntimeAdmission` | _type_ | canonical committed input, assigned run, pending assistant projection, compatibility IDs and snapshot version |
11449
11546
  | `AgentAdmissionEventSchema` | schema | post-commit admission projection; removes store rereads but does not imply exactly-once delivery |
11450
11547
  | `AgentRunMetricsSchema` | schema | optional provenance-aware usage and timings; `partial` says the provider never reported the run finished, so the figure beside it is not a confirmed total |
11451
- | `AgentRuntimeRecoverOptions` | _type_ | bounded paged startup recovery with context resolver and explicit evidence policy |
11548
+ | `AgentRuntimeRecoverOptions` | _type_ | bounded paged startup recovery with causal per-conversation scheduling, context resolver and explicit evidence policy |
11452
11549
  | `AgentRuntimeConflictError` | class | thrown when a store mutation loses to a concurrent writer — catchable by type from `stitchkit/agent-runtime` |
11453
11550
  | `AgentSessionCloseOptions` | _type_ | `gracePeriodMs` for natural settlement, then abort, then `forceTimeoutMs` for bounded settlement after it |
11454
11551
  | `AgentSessionCloseResult` | _type_ | what `close()` achieved: `settled`, or `timedOut` with `remaining` runs still in flight. Only omitting `forceTimeoutMs` guarantees nothing is in flight on return |
@@ -11561,6 +11658,20 @@ Managed effects and operator telemetry additionally export `AgentToolFenceConfig
11561
11658
  may accompany checkpoint/terminal writes and tool context; internal causes are redacted unless an
11562
11659
  operator-only observability sink explicitly opts in.
11563
11660
 
11661
+ ## `stitchkit/agent-runtime/browser`
11662
+
11663
+ Browser-safe canonical agent data. It re-exports the run, message, part, usage,
11664
+ terminal and provider-envelope schemas/types listed under
11665
+ `stitchkit/agent-runtime`, together with all runtime delivery event schemas,
11666
+ `AgentRuntimeEventCursorSchema`, `advanceAgentRuntimeEventCursor` and
11667
+ `agentDurableEventId`. It imports no model provider, executor, store, event sink
11668
+ or Node context module.
11669
+
11670
+ Use this entrypoint from client components and shared DTO packages. The full
11671
+ `stitchkit/agent-runtime` entrypoint remains server-only.
11672
+
11673
+ ---
11674
+
11564
11675
  ## `stitchkit/agent-runtime/openrouter`
11565
11676
 
11566
11677
  | Export | Kind | Summary |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "stitchkit",
3
- "version": "0.68.3",
3
+ "version": "0.68.5",
4
4
  "description": "Contract-first backend framework — one defineContract() into an HTTP API, MCP tools, AI-agent tools and a typed client. Bun and Node.",
5
5
  "keywords": [
6
6
  "bun",
@@ -84,6 +84,10 @@
84
84
  "types": "./dist/agent-runtime.d.ts",
85
85
  "import": "./dist/agent-runtime.js"
86
86
  },
87
+ "./agent-runtime/browser": {
88
+ "types": "./dist/agent-runtime-browser.d.ts",
89
+ "import": "./dist/agent-runtime-browser.js"
90
+ },
87
91
  "./agent-runtime/openrouter": {
88
92
  "types": "./dist/agent-runtime-openrouter.d.ts",
89
93
  "import": "./dist/agent-runtime-openrouter.js"
@@ -122,7 +126,7 @@
122
126
  },
123
127
  "scripts": {
124
128
  "check": "bun x tsc --noEmit",
125
- "build:browser": "bun build src/index.ts src/react.ts src/contract/index.ts src/declaration.ts --outdir dist --target node --packages external --splitting --root src",
129
+ "build:browser": "bun build src/index.ts src/react.ts src/contract/index.ts src/declaration.ts src/agent-runtime-browser.ts --outdir dist --target node --packages external --splitting --root src",
126
130
  "build:server": "bun build src/server/index.ts src/node.ts src/tools.ts src/tool-invoker.ts src/cli.ts src/remote.ts src/files.ts src/testing.ts src/observability/index.ts src/agent-runtime.ts src/agent-runtime-openrouter.ts src/application.ts src/application-grammy.ts src/application-opentelemetry.ts --outdir dist --target node --packages external --splitting --root src",
127
131
  "build:js": "bun run build:browser && bun run build:server && bun scripts/preserve-webpack-ignore.mjs",
128
132
  "build:types": "bun x tsc -p tsconfig.build.json --emitDeclarationOnly && bun scripts/rewrite-declaration-specifiers.mjs",