@parcha/agentrun-jev 0.1.0-beta.39 → 0.1.0-beta.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -83,7 +83,7 @@ Without a key, or with an `apiKey` that is blank, `createJevRunner()` throws `Je
83
83
 
84
84
  `System One` is TypeSafe's typed-question interface, exposed by the SDK as `systemOne`. A Noul answer is a truth probability from 0 to 1; the DSL converts probabilities of at least 0.5 to `true` and retains the probability beside that value. Choice and Score confidence comes from the response. Jev does not return a separate confidence for Noul; the DSL derives its own gate-strength value from the distance from 0.5, scaled to the range 0 to 1. These numbers are useful gate inputs, not calibrated guarantees.
85
85
 
86
- The public adapter API is `createJevRunner`, `jevProviderFromEnv`, `JevError`, `isJevResponseReason`, and the types `JevOptions`, `JevClient`, `JevProvider`, `JevErrorCode`, `JevResponseReason`, `JevResponseDiagnostic`, `JevRequestDiagnostic`, `JevImage`, `JevJudge`, `JevJudgeParams` and `JevJudgeResult`. The shared question, answer and distribution helpers live in `@parcha/agentrun-dsl`.
86
+ The public adapter API is `createJevRunner`, `jevProviderFromEnv`, `JevError`, `isJevResponseReason`, `jevImageTokens`, the constants `JEV_CONTEXT_TOKENS` and `JEV_CUT_MARK`, and the types `JevOptions`, `JevClient`, `JevProvider`, `JevErrorCode`, `JevResponseReason`, `JevResponseDiagnostic`, `JevRequestDiagnostic`, `JevImage`, `JevJudge`, `JevJudgeParams` and `JevJudgeResult`. The shared question, answer and distribution helpers live in `@parcha/agentrun-dsl`.
87
87
 
88
88
  ## Configuration
89
89
 
@@ -111,7 +111,7 @@ const byEnv = createJevRunner({ provider: jevProviderFromEnv(process.env) }); //
111
111
 
112
112
  `provider: "openrouter"` sends to `https://openrouter.ai/api/v1/systemone` (an explicit `baseURL` wins) and defaults the model to `~typesafe/jev-latest`; pin `typesafe/jev-1.14` when a result must be reproducible. It never falls back to `TYPESAFE_API_KEY`: with no OpenRouter key it is a configuration error. The default provider is `typesafe` and nothing changes for it. `provider` cannot be combined with `client`.
113
113
 
114
- Cost: when the response reports `usage.cost` (USD) it is `cost_usd`; otherwise a configured `pricing` estimate is used; otherwise `cost_usd` is `null`, never 0. A `usage` with a cost and no token counts is accepted and returns `usage: null`. Requests over about 32 KB of state run in the provider's slower long-context mode.
114
+ Cost: when the response reports `usage.cost` (USD) it is `cost_usd`; otherwise a configured `pricing` estimate is used; otherwise `cost_usd` is `null`, never 0. A `usage` with a cost and no token counts is accepted and returns `usage: null`.
115
115
 
116
116
  The official `@typesafe-ai/sdk` resolves `TYPESAFE_API_KEY` and `TYPESAFE_BASE_URL`. Explicit `apiKey` and `baseURL` options take precedence. An API root ends before `/v1/systemone`. Set `fetch` for a custom transport, or supply a `client` with a `systemOne(request, options)` method. A custom client must honor the request signal and disable its own retries; it owns its credentials and cannot be combined with transport options.
117
117
 
@@ -119,11 +119,22 @@ A Jev request is paid once it is sent, so the adapter never sends it again unask
119
119
 
120
120
  `retryAfterSend: true` restores the retries of earlier versions, which can re-send a paid request. With it, the adapter also retries a 408, any 429, a 5xx and a lost connection; on a 503 with `Retry-After` it waits as above. When the attempts end on a 429 after an earlier 408, 5xx or lost connection, the error reports the first of those failures (its HTTP `status`, or code `connection`), since that attempt may have been billed; an `http` error with status 429 means every attempt was refused. SDK retries are disabled. Validation failures and other HTTP errors do not retry. The deadline and either the runner or per-call signal interrupt both requests and backoff. A call the deadline ends is `timeout`, whether the runner's timer or the SDK's per-attempt timer fired first, and is not retried. Cancellation bounds when the adapter returns; an uncooperative custom client can still continue its own work.
121
121
 
122
- Request state has no local byte cap by default. Set `maxStateBytes` to a positive safe integer to reject serialized UTF-8 JSON state exceeding that host-owned limit before transport; omission or `null` disables this guard. This is a byte guard, not a token estimate. [Provider model context limits](https://docs.typesafe.ai/models.md) still apply. The adapter never truncates or splits state or questions.
122
+ Request state has no local byte cap by default. Set `maxStateBytes` to a positive safe integer to reject serialized UTF-8 JSON state exceeding that host-owned limit before transport; omission or `null` disables this guard. This is a byte guard, not a token estimate.
123
+
124
+ ### Jev's context
125
+
126
+ [Jev's context](https://docs.typesafe.ai/models) is 32k tokens for the state plus any one question and 64k for the state plus all of them (`JEV_CONTEXT_TOKENS`); with the `TypeSafe-Danger-Zone-Long-Context: true` header both are 262k, at the same price, slower and less accurate. Past it Jev refuses the whole request (HTTP 400 `max_tokens_exceeded`). The runner never sends a request over it, measured by its UTF-8 JSON bytes, which bound its tokens from above (a token is at least one byte):
127
+
128
+ - Images count too: [each image's tokens count toward the context, and each use of its reference adds it again](https://docs.typesafe.ai/images). TypeSafe publishes no per-image figure yet, so the runner holds a bound, `jevImageTokens(width, height)`: one token per 14x14-pixel patch, 12,544 for a full-size 1568x1568 image, about four times what common vision encoders spend at that size. Every use of every image is held that room before the text is measured.
129
+ - A request that fits the default context goes as it is.
130
+ - One that may not fit it goes whole with the long-context header, on TypeSafe's route (`longContext`, on by default there). Its `request_sha256` covers that it was long.
131
+ - One that may not fit that either (or the default, with `longContext: false` or on OpenRouter, which documents no long context) has its longest state string values cut to one common length, each ending ` [cut]` (`JEV_CUT_MARK`), so Jev reads that it saw only the start and short values (a name, a URL) stay whole. A string holding an image reference is never cut. To keep every word, partition the evidence in the workflow (a `map` with a judge body) instead.
132
+ - A cut request's result says what was sent: `state_sent` holds the state as sent and `cut`, each value cut by its JSON Pointer `path`, its `bytes` as asked and its `sent_bytes`. A cut request that fails carries the same as the `JevError`'s `stateSent`. `jevProvider` passes both on, and the DSL's decision receipt records that state (`state`, `state_cut`), never the one asked.
133
+ - Questions and images too long for the context even with every value cut are refused before sending: `invalid_request` with reason `over_context`.
123
134
 
124
135
  The core allows up to 240 options per choice and 2–10 levels per score rubric. Adapter timeouts are positive integer milliseconds up to 2,147,483,647; retry delays may also be zero. `maxAttempts` is 1–10, with a default of 3.
125
136
 
126
- `JevError` provides a stable `code`, `attempts`, and optional HTTP `status`. A request the runner refuses before sending it has code `invalid_request`, `attempts` 0 and a `requestDiagnostic` (`JevRequestDiagnostic`): a `reason` (`invalid_state`, `state_too_large`, `invalid_questions`, `invalid_assets`, `unsupported_model` or `unsupported_provider`), the call's `label` (at most 200 characters) when it has one, and for a state over `maxStateBytes` its `stateBytes` and `maxStateBytes`. Errors deliberately omit raw service bodies, headers, input state, and causes. SDK logging is disabled. Custom clients and transports own their own logging. Do not expose credentials in browser code.
137
+ `JevError` provides a stable `code`, `attempts`, and optional HTTP `status`. A request the runner refuses before sending it has code `invalid_request`, `attempts` 0 and a `requestDiagnostic` (`JevRequestDiagnostic`): a `reason` (`invalid_state`, `state_too_large`, `invalid_questions`, `invalid_assets`, `unsupported_model`, `unsupported_provider` or `over_context`), the call's `label` (at most 200 characters) when it has one, and for a state over `maxStateBytes` its `stateBytes` and `maxStateBytes`. Errors deliberately omit raw service bodies, headers, input state, and causes. SDK logging is disabled. Custom clients and transports own their own logging. Do not expose credentials in browser code.
127
138
 
128
139
  Optional `responseDiagnostic.reason` identifies a fixed response invariant, such
129
140
  as `answer_keys`, `probability_mass`, or `token_usage`. An explicitly structured
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Fetch, RequestOptions, SystemOneRequest } from "@typesafe-ai/sdk";
2
- import type { WorkflowDeps, SystemOneResponseReason, DecisionProvider } from "@parcha/agentrun-dsl";
2
+ import type { WorkflowDeps, SystemOneResponseReason, DecisionProvider, DecisionStateSent } from "@parcha/agentrun-dsl";
3
3
  /** Injectable client boundary. Custom clients must honor signal and disable their own retries. */
4
4
  export interface JevClient {
5
5
  systemOne(request: SystemOneRequest, options: RequestOptions): PromiseLike<unknown>;
@@ -33,6 +33,16 @@ export type JevJudgeParams = Parameters<RunJudge>[0] & {
33
33
  export type JevJudgeResult = Awaited<ReturnType<RunJudge>>;
34
34
  /** The judge `createJevRunner` returns, and the port a host passes to a package that asks Jev about images without importing the SDK. */
35
35
  export type JevJudge = (params: JevJudgeParams) => Promise<JevJudgeResult>;
36
+ /** Jev's context, in tokens, per https://docs.typesafe.ai/models (read 2026-11-16), the same for Jev 1.13 and 1.14: the
37
+ * state plus any one question (`perQuestion`) and the state plus all its questions (`perRequest`). A request sent with
38
+ * the long-context header has `long` for both. Past them Jev answers HTTP 400 `max_tokens_exceeded`. */
39
+ export declare const JEV_CONTEXT_TOKENS: Readonly<{
40
+ perQuestion: 32000;
41
+ perRequest: 64000;
42
+ long: 262000;
43
+ }>;
44
+ /** What ends a state value cut to fit Jev's context, so Jev reads that it saw only the start. */
45
+ export declare const JEV_CUT_MARK = " [cut]";
36
46
  /** The longest side, in pixels, Jev takes an image at: TypeSafe answers HTTP 400 "Invalid image dimensions." past it, on its
37
47
  * own API and through OpenRouter alike (live, 2026-10-30: 1568x400 answered, 1569x400 refused, area no factor). */
38
48
  export declare const JEV_MAX_IMAGE_SIDE_PX = 1568;
@@ -51,6 +61,10 @@ export interface JevOptions {
51
61
  timeoutMs?: number | null;
52
62
  /** Optional host guard on serialized UTF-8 JSON state; null or omission disables it. */
53
63
  maxStateBytes?: number | null;
64
+ /** Send a request that may not fit Jev's default context with TypeSafe's long-context header (262k tokens), so it is
65
+ * answered whole. On by default on TypeSafe's route; OpenRouter documents no long context, so there it is off and
66
+ * cannot be turned on. Off, such a request's longest state values are cut to fit the default context. */
67
+ longContext?: boolean;
54
68
  /** Attempts for a request that never reached Jev, or a 429 that says when to retry (default 3). */
55
69
  maxAttempts?: number;
56
70
  /** Also retry a 408, a 5xx and a connection lost after the request was sent, as earlier versions did. Such a retry can
@@ -74,7 +88,7 @@ export type JevResponseDiagnostic = {
74
88
  reason: JevResponseReason;
75
89
  };
76
90
  export type JevRequestDiagnostic = {
77
- reason: "invalid_state" | "state_too_large" | "invalid_questions" | "invalid_assets" | "unsupported_model" | "unsupported_provider";
91
+ reason: "invalid_state" | "state_too_large" | "invalid_questions" | "invalid_assets" | "unsupported_model" | "unsupported_provider" | "over_context";
78
92
  label?: string;
79
93
  stateBytes?: number;
80
94
  maxStateBytes?: number;
@@ -86,8 +100,18 @@ export declare class JevError extends Error {
86
100
  readonly status?: number | undefined;
87
101
  readonly requestDiagnostic?: JevRequestDiagnostic | undefined;
88
102
  readonly responseDiagnostic?: JevResponseDiagnostic;
103
+ /** The state the request held as sent, and the values cut, when it was cut to fit Jev's context before sending: a
104
+ * decision receipt records it (jevProvider passes it on as the DecisionProviderError's `stateSent`). */
105
+ stateSent?: DecisionStateSent;
89
106
  constructor(code: JevErrorCode, message: string, attempts?: number, status?: number | undefined, requestDiagnostic?: JevRequestDiagnostic | undefined, responseDiagnostic?: JevResponseDiagnostic);
90
107
  }
108
+ /** The tokens a request's context is held for one use of a `width` x `height` image: one per 14x14-pixel patch, each side
109
+ * rounded up, so a full-size image (1568x1568) is held 12,544. TypeSafe publishes no figure (its images page, read
110
+ * 2026-11-16: "We'll be providing guidance on estimating image token usage soon"), only that image tokens count toward
111
+ * the context and each use of a reference adds the image again. So this is a bound, not an estimate: four times the
112
+ * tokens of a vision encoder that merges 2x2 patches of 14 pixels (28x28 pixels a token, as Qwen2-VL), and about 3.8
113
+ * times Claude's 750 square pixels a token at the same 1568-pixel side limit. */
114
+ export declare function jevImageTokens(width: number, height: number): number;
91
115
  export declare function createJevRunner(options?: JevOptions): JevJudge;
92
116
  /** Jev as a DecisionProvider: `createJevRunner(options)` behind the DSL's provider seam, for a host that runs every
93
117
  * decision model through `judgeFromProvider`. A paid request is never sent twice: only a 429 with Retry-After or a
package/dist/index.js CHANGED
@@ -14,6 +14,15 @@ export function jevProviderFromEnv(env = process.env) {
14
14
  return isSet(keyVariable.openrouter) && !isSet(keyVariable.typesafe) ? "openrouter" : "typesafe";
15
15
  }
16
16
  const IMAGE_HEADER = "TypeSafe-Danger-Zone-Images";
17
+ /** Jev's context, in tokens, per https://docs.typesafe.ai/models (read 2026-11-16), the same for Jev 1.13 and 1.14: the
18
+ * state plus any one question (`perQuestion`) and the state plus all its questions (`perRequest`). A request sent with
19
+ * the long-context header has `long` for both. Past them Jev answers HTTP 400 `max_tokens_exceeded`. */
20
+ export const JEV_CONTEXT_TOKENS = Object.freeze({ perQuestion: 32_000, perRequest: 64_000, long: 262_000 });
21
+ const LONG_CONTEXT_HEADER = "TypeSafe-Danger-Zone-Long-Context";
22
+ /** Tokens kept free under each limit for the words Jev frames a state and its questions in. */
23
+ const FRAME_TOKENS = 1_000;
24
+ /** What ends a state value cut to fit Jev's context, so Jev reads that it saw only the start. */
25
+ export const JEV_CUT_MARK = " [cut]";
17
26
  const MAX_IMAGE_BYTES = 16 * 1024 * 1024;
18
27
  /** The longest side, in pixels, Jev takes an image at: TypeSafe answers HTTP 400 "Invalid image dimensions." past it, on its
19
28
  * own API and through OpenRouter alike (live, 2026-10-30: 1568x400 answered, 1569x400 refused, area no factor). */
@@ -53,6 +62,9 @@ export class JevError extends Error {
53
62
  status;
54
63
  requestDiagnostic;
55
64
  responseDiagnostic;
65
+ /** The state the request held as sent, and the values cut, when it was cut to fit Jev's context before sending: a
66
+ * decision receipt records it (jevProvider passes it on as the DecisionProviderError's `stateSent`). */
67
+ stateSent;
56
68
  constructor(code, message, attempts = 0, status, requestDiagnostic, responseDiagnostic) {
57
69
  super(message);
58
70
  this.code = code;
@@ -117,7 +129,7 @@ function retryAfterMs(headers) {
117
129
  }
118
130
  /** What one call sends: the request, the body its hash is taken over, and the image header when it carries an image or a Box. All of it is
119
131
  * checked before anything is sent: a request that cannot be valid throws the `invalid_request` JevError that names why. */
120
- function prepareRequest(params, model, maxStateBytes, provider) {
132
+ function prepareRequest(params, model, maxStateBytes, provider, longContext) {
121
133
  let body;
122
134
  let request;
123
135
  const invalid = (reason, message, stateBytes) => new JevError("invalid_request", message, 0, undefined, { reason,
@@ -151,12 +163,12 @@ function prepareRequest(params, model, maxStateBytes, provider) {
151
163
  catch {
152
164
  throw invalid("invalid_questions", "Jev requires a nonempty JSON question map; no request was sent.");
153
165
  }
154
- // Images and Box questions: validated whole before any send; the header goes with exactly these requests.
155
- const hasBox = Object.values(request.questions).some(question => isRecord(question) && question.type === "box");
156
166
  const given = params.assets ?? {};
157
167
  if (!isRecord(given))
158
168
  throw invalid("invalid_assets", "assets must map each reference to an image; no request was sent.");
159
169
  const references = Object.keys(given);
170
+ // Images and Box questions: validated whole before any send; the header goes with exactly these requests.
171
+ const hasBox = Object.values(request.questions).some(question => isRecord(question) && question.type === "box");
160
172
  const carriesImage = references.length > 0;
161
173
  if ((carriesImage || hasBox) && provider !== "typesafe")
162
174
  throw invalid("unsupported_provider", "Images and Box questions are sent to TypeSafe's own API only: OpenRouter refuses the multipart body the TypeSafe SDK sends them in. For Jev with images through OpenRouter, use the openrouter decision provider with model typesafe/jev-1.14. No request was sent.");
@@ -166,9 +178,17 @@ function prepareRequest(params, model, maxStateBytes, provider) {
166
178
  throw invalid("invalid_assets", "A Box question locates something in an image, and the request carries none. No request was sent.");
167
179
  let assets;
168
180
  let assetDigests;
181
+ // The context the images take: each use of a reference adds its image again (https://docs.typesafe.ai/images).
182
+ let imageTokens = 0, imageUses = 0;
183
+ // No prototype: a question named __proto__ or constructor must read its own count, not an inherited object.
184
+ const held = { state: 0, questions: Object.create(null) };
169
185
  if (carriesImage) {
170
186
  // A reference is replaced where it sits inside a string value of the state, an instruction or a criterion; keys (question ids, option names) are never replaced.
171
- const texts = [...stringValues(request.state), ...Object.values(request.questions).flatMap(question => isRecord(question) ? [...stringValues(question.instructions), ...stringValues(question.criteria)] : [])];
187
+ const stateTexts = [...stringValues(request.state)];
188
+ const questionTexts = Object.entries(request.questions).map(([id, question]) => [id, isRecord(question) ? [...stringValues(question.instructions), ...stringValues(question.criteria)] : []]);
189
+ const usesIn = (texts, reference) => texts.reduce((count, text) => count + text.split(reference).length - 1, 0);
190
+ for (const [id] of questionTexts)
191
+ held.questions[id] = 0;
172
192
  assets = Object.create(null);
173
193
  assetDigests = Object.create(null);
174
194
  for (const reference of references) {
@@ -178,22 +198,122 @@ function prepareRequest(params, model, maxStateBytes, provider) {
178
198
  && image.bytes.byteLength > 0 && image.bytes.byteLength <= MAX_IMAGE_BYTES && startsWith(image.bytes, imageMagic[image.mime]);
179
199
  if (!sound)
180
200
  throw invalid("invalid_assets", `Each image is a PNG or JPEG file of at most ${MAX_IMAGE_BYTES / 1024 / 1024} MiB, with bytes that are that type and a plain reference. No request was sent.`);
181
- if (!texts.some(text => text.includes(reference)))
201
+ const stateUses = usesIn(stateTexts, reference);
202
+ const uses = stateUses + questionTexts.reduce((count, [, texts]) => count + usesIn(texts, reference), 0);
203
+ if (uses === 0)
182
204
  throw invalid("invalid_assets", "Every image reference must appear in the state or a question. No request was sent.");
183
205
  const size = imageDimensions(image.bytes);
184
206
  if (size === null)
185
207
  throw invalid("invalid_assets", `The image ${reference} has no width and height its header can be read from. No request was sent.`);
186
208
  if (size.width > JEV_MAX_IMAGE_SIDE_PX || size.height > JEV_MAX_IMAGE_SIDE_PX)
187
209
  throw invalid("invalid_assets", `The image ${reference} is ${size.width}x${size.height} px; Jev takes at most ${JEV_MAX_IMAGE_SIDE_PX} px on each side. Render it smaller (a letter page at 140 dpi is 1190x1540). No request was sent.`);
210
+ const each = jevImageTokens(size.width, size.height);
211
+ held.state += stateUses * each;
212
+ for (const [id, texts] of questionTexts)
213
+ held.questions[id] += usesIn(texts, reference) * each;
214
+ imageTokens += uses * each;
215
+ imageUses += uses;
188
216
  assets[reference] = new Image(image.bytes);
189
217
  assetDigests[reference] = { sha256: createHash("sha256").update(image.bytes).digest("hex"), mime: image.mime, bytes: image.bytes.byteLength };
190
218
  }
219
+ }
220
+ // Jev's context: a request that may not fit the default goes with the long-context header; one that may not fit that
221
+ // either has its longest state values cut. Never sent over it: Jev would refuse it whole (HTTP 400 max_tokens_exceeded).
222
+ const fit = fitContext(request.state, request.questions, longContext, references, held);
223
+ const context = longContext ? JEV_CONTEXT_TOKENS.long : JEV_CONTEXT_TOKENS.perQuestion;
224
+ if (fit === null)
225
+ throw invalid("over_context", imageTokens > 0
226
+ ? `Jev's questions and the request's ${imageUses} image use${imageUses === 1 ? "" : "s"} (held at ${imageTokens} tokens, each use of a reference adding its image again), with the state's names and shape, are over its ${context}-token context even with every state value cut; send fewer or smaller images, or ask fewer or shorter questions. No request was sent.`
227
+ : `Jev's questions, with the state's names and shape, are over its ${context}-token context even with every state value cut; ask fewer or shorter questions. No request was sent.`);
228
+ const sent = fit.cut.length ? { state: fit.state, cut: fit.cut } : undefined;
229
+ if (sent)
230
+ request = { ...request, state: fit.state };
231
+ // The hash names a long-context request as one: the same state and questions without the header are another request.
232
+ const long = fit.long ? { long_context: true } : {};
233
+ if (fit.long || sent)
234
+ body = JSON.stringify({ ...request, ...long });
235
+ if (carriesImage) {
191
236
  // The hash names the images by their own digests, so it identifies the request that was sent without holding the bytes.
192
- body = JSON.stringify({ ...request, assets: assetDigests });
237
+ body = JSON.stringify({ ...request, ...long, assets: assetDigests });
193
238
  request = { ...request, assets };
194
239
  }
195
- const headers = carriesImage || hasBox ? { [IMAGE_HEADER]: "true" } : undefined;
196
- return { request, body, ...(headers ? { headers } : {}) };
240
+ const headers = { ...(carriesImage || hasBox ? { [IMAGE_HEADER]: "true" } : {}), ...(fit.long ? { [LONG_CONTEXT_HEADER]: "true" } : {}) };
241
+ return { request, body, ...(Object.keys(headers).length ? { headers } : {}), ...(sent ? { sent } : {}) };
242
+ }
243
+ /** UTF-8 bytes of `value`'s JSON. A token is at least one byte of text, so a request's bytes bound its text's tokens from
244
+ * above. Images are held apart, by their pixels (jevImageTokens). */
245
+ const jsonBytes = (value) => Buffer.byteLength(JSON.stringify(value), "utf8");
246
+ /** The side of the pixel square a request's context is held one token for, in each image it carries. */
247
+ const IMAGE_PATCH_PX = 14;
248
+ /** The tokens a request's context is held for one use of a `width` x `height` image: one per 14x14-pixel patch, each side
249
+ * rounded up, so a full-size image (1568x1568) is held 12,544. TypeSafe publishes no figure (its images page, read
250
+ * 2026-11-16: "We'll be providing guidance on estimating image token usage soon"), only that image tokens count toward
251
+ * the context and each use of a reference adds the image again. So this is a bound, not an estimate: four times the
252
+ * tokens of a vision encoder that merges 2x2 patches of 14 pixels (28x28 pixels a token, as Qwen2-VL), and about 3.8
253
+ * times Claude's 750 square pixels a token at the same 1568-pixel side limit. */
254
+ export function jevImageTokens(width, height) {
255
+ return Math.ceil(width / IMAGE_PATCH_PX) * Math.ceil(height / IMAGE_PATCH_PX);
256
+ }
257
+ /** RFC 6901 JSON Pointer of a key path. */
258
+ const pointer = (path) => path.map(key => `/${String(key).replace(/~/g, "~0").replace(/\//g, "~1")}`).join("");
259
+ /** What a request sends for `state` and `questions` to stay inside Jev's context (JEV_CONTEXT_TOKENS), measured by the
260
+ * bytes that bound its text's tokens, with `imageTokens` (its images, every use) held apart: the state as is when it fits
261
+ * the default context; else, with `longContext`, as is under the long-context header (`long`) when it fits that; else its
262
+ * string values cut, longest first, to one common length each ends at (JEV_CUT_MARK), as long as the room left allows,
263
+ * each one cut named by its place, its bytes and its bytes as sent (`cut`). A string holding an image reference is never
264
+ * cut. Null when even every value cut would not fit: the questions and images alone are too long. */
265
+ function fitContext(state, questions, longContext, keep, images) {
266
+ const all = jsonBytes(questions);
267
+ const allImages = images.state + Object.values(images.questions).reduce((sum, tokens) => sum + tokens, 0);
268
+ // A question's request holds the state and that question, with the images either names; the whole request holds every use.
269
+ const tightest = (perQuestion) => Math.min(perQuestion, ...Object.entries(questions).map(([id, question]) => perQuestion - jsonBytes({ [id]: question }) - images.state - (images.questions[id] ?? 0)));
270
+ const room = (perQuestion, perRequest) => Math.min(tightest(perQuestion), perRequest - all - allImages) - FRAME_TOKENS;
271
+ const bytes = jsonBytes(state);
272
+ const normal = room(JEV_CONTEXT_TOKENS.perQuestion, JEV_CONTEXT_TOKENS.perRequest);
273
+ if (bytes <= normal)
274
+ return { state, long: false, cut: [] };
275
+ const limit = longContext ? room(JEV_CONTEXT_TOKENS.long, JEV_CONTEXT_TOKENS.long) : normal;
276
+ if (bytes <= limit)
277
+ return { state, long: longContext, cut: [] };
278
+ const cutAt = (cap, cuts) => {
279
+ const walk = (value, path) => {
280
+ if (typeof value === "string") {
281
+ const sent = cutText(value, cap, keep);
282
+ if (cuts && sent !== value)
283
+ cuts.push({ path: pointer(path), bytes: Buffer.byteLength(value, "utf8"), sent_bytes: Buffer.byteLength(sent, "utf8") });
284
+ return sent;
285
+ }
286
+ if (Array.isArray(value))
287
+ return value.map((each, index) => walk(each, [...path, index]));
288
+ if (isRecord(value))
289
+ return Object.fromEntries(Object.entries(value).map(([key, each]) => [key, walk(each, [...path, key])]));
290
+ return value;
291
+ };
292
+ return walk(state, []);
293
+ };
294
+ if (limit < 0 || jsonBytes(cutAt(0)) > limit)
295
+ return null;
296
+ // The longest cap that fits: every string longer than it ends at it, so the shortest values (a name, a line) stay whole.
297
+ let fits = 0, over = Math.max(0, ...[...stringValues(state)].map(text => Buffer.byteLength(text, "utf8")));
298
+ while (over - fits > 1) {
299
+ const cap = Math.floor((fits + over) / 2);
300
+ if (jsonBytes(cutAt(cap)) <= limit)
301
+ fits = cap;
302
+ else
303
+ over = cap;
304
+ }
305
+ const cut = [];
306
+ return { state: cutAt(fits, cut), long: longContext, cut };
307
+ }
308
+ /** `text`'s first `cap` UTF-8 bytes (never half a character) and JEV_CUT_MARK, when it is longer than that; else as is. */
309
+ function cutText(text, cap, keep) {
310
+ if (Buffer.byteLength(text, "utf8") <= cap + Buffer.byteLength(JEV_CUT_MARK, "utf8") || keep.some(reference => text.includes(reference)))
311
+ return text;
312
+ let start = Buffer.from(text, "utf8").subarray(0, cap).toString("utf8");
313
+ // A character the cap split decodes as U+FFFD: drop it, unless the text itself has one there.
314
+ if (start.endsWith("�") && !text.startsWith(start))
315
+ start = start.slice(0, -1);
316
+ return `${start}${JEV_CUT_MARK}`;
197
317
  }
198
318
  /** The runner's result from what the client returned at `attempt`, or the `invalid_response` JevError for the first rule it breaks.
199
319
  * `questions` are the questions as they were sent. */
@@ -250,6 +370,9 @@ export function createJevRunner(options = {}) {
250
370
  requireConfig(hostClient === undefined || (options.apiKey === undefined && options.baseURL === undefined && options.fetch === undefined && options.provider === undefined), "Supply either client or transport options, not both.");
251
371
  const provider = options.provider ?? "typesafe";
252
372
  requireConfig(provider === "typesafe" || provider === "openrouter", "provider must be typesafe or openrouter.");
373
+ requireConfig(options.longContext === undefined || typeof options.longContext === "boolean", "longContext must be true or false.");
374
+ requireConfig(!(options.longContext === true && provider === "openrouter"), "OpenRouter documents no long context for Jev; longContext is TypeSafe's route only.");
375
+ const longContext = options.longContext ?? provider === "typesafe";
253
376
  const pricing = options.pricing ? { ...options.pricing } : undefined;
254
377
  if (pricing)
255
378
  requireConfig([pricing.inputUsdPerMillionTokens, pricing.outputUsdPerMillionTokens].every(n => Number.isFinite(n) && n >= 0), "Configured token prices must be finite nonnegative numbers.");
@@ -285,8 +408,12 @@ export function createJevRunner(options = {}) {
285
408
  throw abortError();
286
409
  const timer = timeoutMs === null ? undefined : setTimeout(() => deadline.abort(), timeoutMs);
287
410
  const started = Date.now();
411
+ // The state as sent and the values cut, when the request was cut to fit Jev's context: its result, or its error, says so.
412
+ let sent;
288
413
  try {
289
- const { request, body, headers } = prepareRequest(params, model, maxStateBytes, provider);
414
+ const prepared = prepareRequest(params, model, maxStateBytes, provider, longContext);
415
+ const { request, body, headers } = prepared;
416
+ sent = prepared.sent;
290
417
  // The first attempt that failed in a way the server may have billed (a lost answer, a 408, a 5xx). A later 429 does not make the call free: the give-up reports this one.
291
418
  let billable;
292
419
  for (attempt = 1;; attempt++) {
@@ -352,9 +479,15 @@ export function createJevRunner(options = {}) {
352
479
  throw new JevError("connection", "Jev transport failed.", attempt);
353
480
  throw new JevError("invalid_request", "Jev could not process the request. Check question and transport configuration.", attempt);
354
481
  }
355
- return readResponse(result, request.questions, body, pricing, attempt);
482
+ const answered = readResponse(result, request.questions, body, pricing, attempt);
483
+ return sent ? { ...answered, state_sent: sent } : answered;
356
484
  }
357
485
  }
486
+ catch (error) {
487
+ if (sent && error instanceof JevError)
488
+ error.stateSent = sent;
489
+ throw error;
490
+ }
358
491
  finally {
359
492
  clearTimeout(timer);
360
493
  }
@@ -399,6 +532,7 @@ export function jevProvider(options = {}) {
399
532
  return {
400
533
  answers: result.answers, evidence: [], model: result.model ?? null, usage: result.usage ?? null, cost_usd: reported ?? estimate,
401
534
  cost_basis: reported !== null ? "reported" : estimate !== null ? "estimate" : "unknown", provider_request_id: null,
535
+ ...(result.state_sent ? { state_sent: result.state_sent } : {}),
402
536
  };
403
537
  }
404
538
  catch (error) {
@@ -406,7 +540,8 @@ export function jevProvider(options = {}) {
406
540
  throw new DecisionProviderError("http", "Jev request failed.");
407
541
  const timedOut = Boolean(deadline?.aborted) && !ctx.signal.aborted;
408
542
  const code = jevErrorCode(error, timedOut, ctx.signal.aborted);
409
- throw new DecisionProviderError(code, error.message, { ...(error.status !== undefined ? { status: error.status } : {}), attempts: error.attempts, ...(code === "outcome_unknown" || code === "invalid_response" ? { costUsd: null, costBasis: "unknown" } : {}), cause: error });
543
+ throw new DecisionProviderError(code, error.message, { ...(error.status !== undefined ? { status: error.status } : {}), attempts: error.attempts, ...(code === "outcome_unknown" || code === "invalid_response" ? { costUsd: null, costBasis: "unknown" } : {}),
544
+ ...(error.stateSent ? { stateSent: error.stateSent } : {}), cause: error });
410
545
  }
411
546
  },
412
547
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-jev",
3
- "version": "0.1.0-beta.39",
3
+ "version": "0.1.0-beta.40",
4
4
  "description": "Optional Jev system one decisions for AgentRun workflows",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",
@@ -27,7 +27,7 @@
27
27
  "test": "node --test test/*.test.mjs"
28
28
  },
29
29
  "dependencies": {
30
- "@parcha/agentrun-dsl": "0.1.0-beta.39",
30
+ "@parcha/agentrun-dsl": "0.1.0-beta.40",
31
31
  "@typesafe-ai/sdk": "0.7.0"
32
32
  },
33
33
  "repository": {