@parcha/agentrun-jev 0.1.0-beta.5 → 0.1.0-beta.50
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +2 -0
- package/README.md +122 -40
- package/dist/index.d.ts +80 -5
- package/dist/index.js +473 -87
- package/package.json +4 -4
package/NOTICE
CHANGED
package/README.md
CHANGED
|
@@ -2,14 +2,62 @@
|
|
|
2
2
|
|
|
3
3
|
Optional [TypeSafe Jev](https://docs.typesafe.ai/) support for AgentRun DSL. Jev answers focused questions with typed values and probability distributions. The workflow decides how to use them.
|
|
4
4
|
|
|
5
|
-
Beta
|
|
5
|
+
Beta, on npm under the `latest` dist-tag (`npm view @parcha/agentrun-jev dist-tags`). Requires Node.js 24.22.3 or later.
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
npm install @parcha/agentrun-dsl@latest @parcha/agentrun-jev@latest
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## Offline tests
|
|
12
|
+
|
|
13
|
+
To exercise the real adapter with no key and no network request, inject a client. After installing the packages, save this as `offline-jev.mjs` and run `node offline-jev.mjs`:
|
|
14
|
+
|
|
15
|
+
```js
|
|
16
|
+
import assert from 'node:assert/strict';
|
|
17
|
+
import { createJevRunner } from '@parcha/agentrun-jev';
|
|
18
|
+
|
|
19
|
+
const runJudge = createJevRunner({
|
|
20
|
+
maxAttempts: 1,
|
|
21
|
+
client: {
|
|
22
|
+
async systemOne(request, options) {
|
|
23
|
+
options.signal?.throwIfAborted();
|
|
24
|
+
assert.deepEqual(Object.keys(request.questions), ['answersQuestion']);
|
|
25
|
+
return {
|
|
26
|
+
answers: { answersQuestion: { type: 'noul', noul: 0.95 } },
|
|
27
|
+
};
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
const result = await runJudge({
|
|
33
|
+
label: 'screen-evidence',
|
|
34
|
+
kind: 'judge',
|
|
35
|
+
state: {
|
|
36
|
+
question: 'Can emergency documentation fixes bypass prior approval?',
|
|
37
|
+
passage: 'During an incident, the on-call engineer may merge a fix immediately; a second person reviews it the next working day.',
|
|
38
|
+
},
|
|
39
|
+
questions: {
|
|
40
|
+
answersQuestion: {
|
|
41
|
+
type: 'noul',
|
|
42
|
+
instructions: 'Does the passage contain a specific rule or exception answering the question? Retain conditional and contrary evidence; reject topic mentions and promotional claims.',
|
|
43
|
+
},
|
|
44
|
+
},
|
|
45
|
+
});
|
|
46
|
+
assert.equal(result.answers.answersQuestion.noul, 0.95);
|
|
47
|
+
console.log(result.answers.answersQuestion);
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
This prints `{ type: 'noul', noul: 0.95 }`. The answer is **scripted**; it does not evaluate the passage or adapt to prompt changes. Answer IDs must match the requested question IDs. Noul returns a probability, not a boolean. Reported model and token usage may be omitted; the adapter preserves missing usage/cost as unknown instead of inventing measurements.
|
|
51
|
+
|
|
52
|
+
## Call Jev
|
|
53
|
+
|
|
54
|
+
A live call needs a key. Set it, then run the sample below as `live-jev.mjs` (`node live-jev.mjs`). The samples that follow are written in TypeScript; run them with a TypeScript runner such as `npx tsx`, or drop the `type` imports and annotations to run them as `.mjs`.
|
|
6
55
|
|
|
7
56
|
```sh
|
|
8
|
-
npm install @parcha/agentrun-dsl@beta @parcha/agentrun-jev@beta
|
|
9
57
|
export TYPESAFE_API_KEY="your-key"
|
|
10
58
|
```
|
|
11
59
|
|
|
12
|
-
```
|
|
60
|
+
```js
|
|
13
61
|
import { createJevRunner } from '@parcha/agentrun-jev';
|
|
14
62
|
|
|
15
63
|
const runJudge = createJevRunner();
|
|
@@ -29,11 +77,13 @@ const result = await runJudge({
|
|
|
29
77
|
console.log(result.answers.team);
|
|
30
78
|
```
|
|
31
79
|
|
|
80
|
+
Without a key, or with an `apiKey` that is blank, `createJevRunner()` throws `JevError` (code `configuration`: "Could not configure Jev. Supply apiKey or set TYPESAFE_API_KEY, and check transport options.") on that line, before any request is made. The same holds for `provider: "openrouter"` without `OPENROUTER_API_KEY`.
|
|
81
|
+
|
|
32
82
|
`judge`, `pick`, `sift`, `route`, semantic predicates, and judgment verification use the same `runJudge` adapter. Choice, Noul, and Score answers retain their raw probabilities. The core validates answer IDs, probability keys and normalization, score rubrics, and value ranges before consuming a result. A typed answer records the model's decision. It does not prove that a real-world claim is true.
|
|
33
83
|
|
|
34
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.
|
|
35
85
|
|
|
36
|
-
The public adapter API
|
|
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`.
|
|
37
87
|
|
|
38
88
|
## Configuration
|
|
39
89
|
|
|
@@ -48,15 +98,43 @@ const runJudge = createJevRunner({
|
|
|
48
98
|
});
|
|
49
99
|
```
|
|
50
100
|
|
|
101
|
+
### Through OpenRouter
|
|
102
|
+
|
|
103
|
+
Jev is also served by OpenRouter's System One path, on the same request shape. Choose it with `provider`:
|
|
104
|
+
|
|
105
|
+
```ts
|
|
106
|
+
import { createJevRunner, jevProviderFromEnv } from "@parcha/agentrun-jev";
|
|
107
|
+
|
|
108
|
+
const runJudge = createJevRunner({ provider: "openrouter" }); // key: apiKey, else OPENROUTER_API_KEY
|
|
109
|
+
const byEnv = createJevRunner({ provider: jevProviderFromEnv(process.env) }); // OpenRouter only when only OPENROUTER_API_KEY is set
|
|
110
|
+
```
|
|
111
|
+
|
|
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
|
+
|
|
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
|
+
|
|
51
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.
|
|
52
117
|
|
|
53
|
-
|
|
118
|
+
A Jev request is paid once it is sent, so the adapter never sends it again unasked. It retries, with bounded exponential delays, only a request that provably never reached Jev (no DNS answer, no connection, no TLS handshake) and a 429 with a `Retry-After` (seconds or an HTTP date). It waits the larger of that and its own delay, and gives up at once, with attempts left, when that wait would not end before the timeout. A 429 without `Retry-After` is an `http` error at once. A 408, a 5xx or a connection lost after sending is sent once and fails with code `outcome_unknown` (and the HTTP `status` when there is one): it may have been answered and billed, and its cost is unknown.
|
|
119
|
+
|
|
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.
|
|
54
121
|
|
|
55
|
-
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.
|
|
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`.
|
|
56
134
|
|
|
57
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.
|
|
58
136
|
|
|
59
|
-
`JevError` provides a stable `code`, `attempts`, and optional HTTP `status`. 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.
|
|
60
138
|
|
|
61
139
|
Optional `responseDiagnostic.reason` identifies a fixed response invariant, such
|
|
62
140
|
as `answer_keys`, `probability_mass`, or `token_usage`. An explicitly structured
|
|
@@ -64,48 +142,52 @@ capacity rejection can report `max_tokens_exceeded`; arbitrary provider messages
|
|
|
64
142
|
are never parsed for a reason. These details do not change validation, retry
|
|
65
143
|
policy, or the submitted evidence. Unknown causes remain unspecified.
|
|
66
144
|
|
|
67
|
-
Successful results retain `answers`, reported `model`, reported token `usage`, and a SHA-256 of the submitted request. `cost_usd` is `
|
|
145
|
+
Successful results retain `answers`, reported `model`, reported token `usage`, and a SHA-256 of the submitted request. `cost_usd` is the response's reported `usage.cost` when it has one, else an estimate from the counted tokens and an explicit `pricing: { inputUsdPerMillionTokens, outputUsdPerMillionTokens }`, else `null`. Configured prices produce an estimate for the successful response; costs from unsuccessful or interrupted attempts are unknown.
|
|
68
146
|
|
|
69
|
-
##
|
|
147
|
+
## Images and Box questions
|
|
70
148
|
|
|
71
|
-
|
|
149
|
+
Jev 1.13 and 1.14 read still images, and Jev 1.14 can answer a Box question: where in an image something is. TypeSafe leaves both off unless a request says it carries one, and the runner says so for you: it sends `TypeSafe-Danger-Zone-Images: true` on every request that carries an image or a Box question and on no other.
|
|
72
150
|
|
|
73
|
-
```
|
|
74
|
-
import
|
|
75
|
-
import { createJevRunner } from '@parcha/agentrun-jev';
|
|
76
|
-
|
|
77
|
-
const runJudge = createJevRunner({
|
|
78
|
-
maxAttempts: 1,
|
|
79
|
-
client: {
|
|
80
|
-
async systemOne(request, options) {
|
|
81
|
-
options.signal?.throwIfAborted();
|
|
82
|
-
assert.deepEqual(Object.keys(request.questions), ['answersQuestion']);
|
|
83
|
-
return {
|
|
84
|
-
answers: { answersQuestion: { type: 'noul', noul: 0.95 } },
|
|
85
|
-
};
|
|
86
|
-
},
|
|
87
|
-
},
|
|
88
|
-
});
|
|
151
|
+
```ts
|
|
152
|
+
import { createJevRunner, type JevJudge } from '@parcha/agentrun-jev';
|
|
89
153
|
|
|
90
|
-
const
|
|
91
|
-
|
|
92
|
-
kind: 'judge',
|
|
93
|
-
state:
|
|
94
|
-
question: 'Can emergency documentation fixes bypass prior approval?',
|
|
95
|
-
passage: 'During an incident, the on-call engineer may merge a fix immediately; a second person reviews it the next working day.',
|
|
96
|
-
},
|
|
154
|
+
const judge: JevJudge = createJevRunner({ model: 'jev-1.14.0' });
|
|
155
|
+
const { answers, usage, cost_usd } = await judge({
|
|
156
|
+
label: 'door', kind: 'judge',
|
|
157
|
+
state: 'The camera shows <photo>.',
|
|
97
158
|
questions: {
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
instructions: 'Does the passage contain a specific rule or exception answering the question? Retain conditional and contrary evidence; reject topic mentions and promotional claims.',
|
|
101
|
-
},
|
|
159
|
+
open: { type: 'noul', instructions: 'Is the door in <photo> open?' },
|
|
160
|
+
door: { type: 'box', instructions: 'the door in <photo>' },
|
|
102
161
|
},
|
|
162
|
+
assets: { '<photo>': { bytes: pngOrJpegFileBytes, mime: 'image/png' } }, // PNG or JPEG file bytes
|
|
103
163
|
});
|
|
104
|
-
|
|
105
|
-
console.log(result.answers.answersQuestion);
|
|
164
|
+
// answers.door = { type: 'box', box: { top, bottom, left, right }, confidence } — edges are fractions of the image's height and width
|
|
106
165
|
```
|
|
107
166
|
|
|
108
|
-
|
|
167
|
+
- `assets` maps each reference, a string that appears literally in `state` or in a question's `instructions` or `criteria`, to the image. The runner builds the SDK's image from the bytes and sends it as a multipart file part. Each reference must appear inside a string value of the state, an instruction or a criterion (a question id or an option name does not count), or the request is refused.
|
|
168
|
+
- A Box question needs a model named for it: `model: 'jev-1.14.0'`, a later version, or `'jev-preview'`. The runner checks the name, so it refuses a Box on `jev-latest` whatever version that alias points at. A Box on any other model, or a Box with no image, is refused with `JevError` code `invalid_request` before any request. `model` can also be named per call.
|
|
169
|
+
- Before any request, the runner also refuses what Jev would reject: a file that is not PNG or JPEG (the bytes are checked against `mime`), an empty file, a file over 16 MiB, a reference nothing uses. It does not check pixel dimensions (each side 280 to 1568, total 78,400 to 2,458,624 pixels) or the 32 MiB request limit; Jev rejects those with a 400 or 413, which surfaces as a typed `http` error.
|
|
170
|
+
- Images are billed as input tokens at the text price, and `usage.input_tokens` counts them. `cost_usd` is as for text: the provider's reported cost, else your `pricing` applied to the counted tokens, else `null`. `request_sha256` names each image by its own SHA-256, so the same request hashes the same and a different image does not.
|
|
171
|
+
- A Box answer is always a box (there is no "not found"): ask a noul question in the same request to check presence. Edges and confidence are checked to lie in [0, 1] and the box to run forward (`top <= bottom`, `left <= right`); a confidence the provider omits is `null`.
|
|
172
|
+
- `JevJudge`, `JevJudgeParams`, `JevJudgeResult` and `JevImage` are the types of this call. A package that asks Jev about images takes a `JevJudge` from its host and never imports the SDK.
|
|
173
|
+
- Images and Box go to TypeSafe's own API only. The OpenRouter path is not verified for them, so a request that carries either is refused with `provider: "openrouter"`.
|
|
174
|
+
- Request bodies are sent uncompressed; the SDK's default compresses them with zstd.
|
|
175
|
+
- Box is a preview: Jev's page says its request format, answers and limits can change between releases.
|
|
176
|
+
|
|
177
|
+
## As a DecisionProvider
|
|
178
|
+
|
|
179
|
+
`jevProvider(options)` is Jev behind the DSL's provider seam, for a host that runs every decision model the same way. It takes `createJevRunner`'s options, and `judgeFromProvider(jevProvider())` is a `runJudge`:
|
|
180
|
+
|
|
181
|
+
```ts
|
|
182
|
+
import { judgeFromProvider, runWorkflow } from '@parcha/agentrun-dsl';
|
|
183
|
+
import { jevProvider } from '@parcha/agentrun-jev';
|
|
184
|
+
|
|
185
|
+
const result = await runWorkflow(workflow, input, { runJudge: judgeFromProvider(jevProvider()) });
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
It sends each decision once, since a paid request is never re-sent unasked: it runs `createJevRunner` with `maxAttempts: 1`, whatever `maxAttempts` you pass. A 408, a 5xx or a connection error (the SDK cannot tell one before sending from one after) is `outcome_unknown` at an unknown cost, and the run escalates the decision as interrupted. It declares noul, choice and score questions from text or JSON (a box question needs an image, which the seam does not carry yet), no evidence, and the key it reads by name (`TYPESAFE_API_KEY`, or `OPENROUTER_API_KEY` with `provider: "openrouter"`). Its other errors are `DecisionProviderError`s with Jev's message: an HTTP 401 or 403 is `auth`, a 429 `rate_limited`, and a 400 or 422 `invalid_request`. A deadline that ends the request in flight (the host's, or the runner's own `timeoutMs`) is `outcome_unknown` too, since it may have been answered; only the host's own cancel is `aborted`. A cost the response reports is booked `reported`. Otherwise its counted tokens are priced at `pricing`, by default TypeSafe's published price (`JEV_PUBLISHED_PRICING`: $0.042 per million input tokens, output tokens free, from [the models page](https://docs.typesafe.ai/models)) on the TypeSafe route and none on OpenRouter's, and booked `estimate`. With neither, and for a call that failed or may have been billed, the cost is unknown: `null`, never 0. It passes the conformance suite in `@parcha/agentrun-dsl/testing` (`test/decision-provider.test.mjs`).
|
|
189
|
+
|
|
190
|
+
## Testing your own host
|
|
109
191
|
|
|
110
192
|
The [standalone TypeScript starter](https://github.com/Parcha-ai/agentrun/tree/main/examples/starter#readme) includes npm installation, a complete search-and-screen workflow, and tests for missing evidence and the screening step alone. Its injected client answers every named question generated by `sift`.
|
|
111
193
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,54 @@
|
|
|
1
1
|
import type { Fetch, RequestOptions, SystemOneRequest } from "@typesafe-ai/sdk";
|
|
2
|
-
import type { WorkflowDeps, SystemOneResponseReason } 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>;
|
|
6
6
|
}
|
|
7
|
+
/** Where Jev is reached: TypeSafe's own API (default) or OpenRouter's System One path. */
|
|
8
|
+
export type JevProvider = "typesafe" | "openrouter";
|
|
9
|
+
/** TypeSafe's published price for Jev, per https://docs.typesafe.ai/models (read 2026-10-29): $0.042 per million input
|
|
10
|
+
* tokens for jev-1.13 and jev-1.14, and output tokens are free. jevProvider books a TypeSafe call at it as an estimate. */
|
|
11
|
+
export declare const JEV_PUBLISHED_PRICING: Readonly<{
|
|
12
|
+
inputUsdPerMillionTokens: 0.042;
|
|
13
|
+
outputUsdPerMillionTokens: 0;
|
|
14
|
+
}>;
|
|
15
|
+
/** The provider an environment's keys select: OpenRouter only when `OPENROUTER_API_KEY` is set and `TYPESAFE_API_KEY` is not. The runner itself never reads this. */
|
|
16
|
+
export declare function jevProviderFromEnv(env?: Record<string, string | undefined>): JevProvider;
|
|
17
|
+
/** A still image a request carries: PNG or JPEG file bytes and the type they are. The runner builds the SDK's image from it and sends it as a multipart file part. */
|
|
18
|
+
export interface JevImage {
|
|
19
|
+
bytes: Uint8Array;
|
|
20
|
+
mime: "image/png" | "image/jpeg";
|
|
21
|
+
}
|
|
22
|
+
type RunJudge = NonNullable<WorkflowDeps["runJudge"]>;
|
|
23
|
+
/** What one call to the runner takes: the interpreter's `runJudge` parameters, plus the images the request carries and an optional model for this call.
|
|
24
|
+
* `assets` maps each reference, a string that appears literally in `state` or in a question's `instructions` or `criteria` (`"<photo>"`), to its image;
|
|
25
|
+
* every reference must appear, and a Box question needs at least one image. */
|
|
26
|
+
export type JevJudgeParams = Parameters<RunJudge>[0] & {
|
|
27
|
+
assets?: Record<string, JevImage>;
|
|
28
|
+
/** Names the model for this call, over the runner's `model`. A Box question needs `jev-1.14.0` (or later) or `jev-preview` by name; the default `jev-latest` is refused for it whatever version that alias points at. */
|
|
29
|
+
model?: string;
|
|
30
|
+
};
|
|
31
|
+
/** The typed answers (choice, noul, score with their probabilities; box with its edges and confidence), the model that answered, its token usage, and
|
|
32
|
+
* the cost: the provider's reported cost, else the host's configured price applied to the counted tokens, else null. */
|
|
33
|
+
export type JevJudgeResult = Awaited<ReturnType<RunJudge>>;
|
|
34
|
+
/** The judge `createJevRunner` returns, and the port a host passes to a package that asks Jev about images without importing the SDK. */
|
|
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]";
|
|
46
|
+
/** The longest side, in pixels, Jev takes an image at: TypeSafe answers HTTP 400 "Invalid image dimensions." past it, on its
|
|
47
|
+
* own API and through OpenRouter alike (live, 2026-10-30: 1568x400 answered, 1569x400 refused, area no factor). */
|
|
48
|
+
export declare const JEV_MAX_IMAGE_SIDE_PX = 1568;
|
|
7
49
|
export interface JevOptions {
|
|
50
|
+
/** `typesafe` (default) or `openrouter`. OpenRouter sets the API root and the default model (`~typesafe/jev-latest`); its key is `apiKey` or `OPENROUTER_API_KEY`. Cannot be combined with `client`. */
|
|
51
|
+
provider?: JevProvider;
|
|
8
52
|
apiKey?: string;
|
|
9
53
|
/** API root, without /v1/systemone; useful for an explicitly configured gateway. */
|
|
10
54
|
baseURL?: string;
|
|
@@ -17,16 +61,26 @@ export interface JevOptions {
|
|
|
17
61
|
timeoutMs?: number | null;
|
|
18
62
|
/** Optional host guard on serialized UTF-8 JSON state; null or omission disables it. */
|
|
19
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;
|
|
68
|
+
/** Attempts for a request that never reached Jev, or a 429 that says when to retry (default 3). */
|
|
20
69
|
maxAttempts?: number;
|
|
70
|
+
/** Also retry a 408, a 5xx and a connection lost after the request was sent, as earlier versions did. Such a retry can
|
|
71
|
+
* re-send a request Jev answered and billed. Off by default: those fail `outcome_unknown` after one attempt. */
|
|
72
|
+
retryAfterSend?: boolean;
|
|
21
73
|
retryBaseMs?: number;
|
|
22
74
|
retryMaxMs?: number;
|
|
23
|
-
/** Explicit estimate; unknown prices are never silently treated as free. */
|
|
75
|
+
/** Explicit estimate, used when the provider reports no cost; unknown prices are never silently treated as free. */
|
|
24
76
|
pricing?: {
|
|
25
77
|
inputUsdPerMillionTokens: number;
|
|
26
78
|
outputUsdPerMillionTokens: number;
|
|
27
79
|
};
|
|
28
80
|
}
|
|
29
|
-
|
|
81
|
+
/** `outcome_unknown`: the request was sent and its outcome is not known (a 408, a 5xx, a connection lost after sending). It
|
|
82
|
+
* may have been answered and billed, so it is not sent again, and its cost is unknown. */
|
|
83
|
+
export type JevErrorCode = "configuration" | "invalid_request" | "invalid_response" | "http" | "connection" | "aborted" | "timeout" | "outcome_unknown";
|
|
30
84
|
declare const adapterResponseReasons: readonly ["response_shape", "token_usage", "model_identifier", "cost_range", "answer_validation", "max_tokens_exceeded"];
|
|
31
85
|
export type JevResponseReason = SystemOneResponseReason | typeof adapterResponseReasons[number];
|
|
32
86
|
export declare function isJevResponseReason(value: unknown): value is JevResponseReason;
|
|
@@ -34,7 +88,7 @@ export type JevResponseDiagnostic = {
|
|
|
34
88
|
reason: JevResponseReason;
|
|
35
89
|
};
|
|
36
90
|
export type JevRequestDiagnostic = {
|
|
37
|
-
reason: "invalid_state" | "state_too_large" | "invalid_questions";
|
|
91
|
+
reason: "invalid_state" | "state_too_large" | "invalid_questions" | "invalid_assets" | "unsupported_model" | "unsupported_provider" | "over_context";
|
|
38
92
|
label?: string;
|
|
39
93
|
stateBytes?: number;
|
|
40
94
|
maxStateBytes?: number;
|
|
@@ -46,7 +100,28 @@ export declare class JevError extends Error {
|
|
|
46
100
|
readonly status?: number | undefined;
|
|
47
101
|
readonly requestDiagnostic?: JevRequestDiagnostic | undefined;
|
|
48
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;
|
|
49
106
|
constructor(code: JevErrorCode, message: string, attempts?: number, status?: number | undefined, requestDiagnostic?: JevRequestDiagnostic | undefined, responseDiagnostic?: JevResponseDiagnostic);
|
|
50
107
|
}
|
|
51
|
-
|
|
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;
|
|
115
|
+
export declare function createJevRunner(options?: JevOptions): JevJudge;
|
|
116
|
+
/** Jev as a DecisionProvider: `createJevRunner(options)` behind the DSL's provider seam, for a host that runs every
|
|
117
|
+
* decision model through `judgeFromProvider`. A paid request is never sent twice: only a 429 with Retry-After or a
|
|
118
|
+
* connect error before sending is sent again (up to `maxAttempts`, default 3), and a 408, a 5xx or a connection lost
|
|
119
|
+
* after sending is `outcome_unknown`, at an unknown cost, and so is the cost of an `invalid_response` (a 200 that breaks
|
|
120
|
+
* the response rules was still answered); so is a deadline that ends the request in flight (the host's, or the runner's
|
|
121
|
+
* own `timeoutMs`). Only the host's own cancel is `aborted`. On TypeSafe's route it takes image input: a request's images
|
|
122
|
+
* go as Jev assets under their tokens, with the `TypeSafe-Danger-Zone-Images` header. Its other errors become
|
|
123
|
+
* DecisionProviderErrors with the same message. A cost the response reports is booked "reported"; else the counted
|
|
124
|
+
* tokens are priced at `pricing`, by default TypeSafe's published price on the TypeSafe route (none on OpenRouter's),
|
|
125
|
+
* and booked "estimate"; else the cost is unknown (null, never 0). */
|
|
126
|
+
export declare function jevProvider(options?: JevOptions): DecisionProvider;
|
|
52
127
|
export {};
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
3
|
+
import { APIConnectionError, APIError, APITimeoutError, Image, TypeSafeClient } from "@typesafe-ai/sdk";
|
|
4
|
+
import { validateAnswers, SystemOneError, isSystemOneResponseReason, checkCapabilities, DecisionProviderError, imageDimensions } from "@parcha/agentrun-dsl";
|
|
5
|
+
const keyVariable = { typesafe: "TYPESAFE_API_KEY", openrouter: "OPENROUTER_API_KEY" };
|
|
6
|
+
const OPENROUTER_BASE_URL = "https://openrouter.ai/api";
|
|
7
|
+
/** TypeSafe's published price for Jev, per https://docs.typesafe.ai/models (read 2026-10-29): $0.042 per million input
|
|
8
|
+
* tokens for jev-1.13 and jev-1.14, and output tokens are free. jevProvider books a TypeSafe call at it as an estimate. */
|
|
9
|
+
export const JEV_PUBLISHED_PRICING = Object.freeze({ inputUsdPerMillionTokens: 0.042, outputUsdPerMillionTokens: 0 });
|
|
10
|
+
const OPENROUTER_DEFAULT_MODEL = "~typesafe/jev-latest";
|
|
11
|
+
/** The provider an environment's keys select: OpenRouter only when `OPENROUTER_API_KEY` is set and `TYPESAFE_API_KEY` is not. The runner itself never reads this. */
|
|
12
|
+
export function jevProviderFromEnv(env = process.env) {
|
|
13
|
+
const isSet = (name) => typeof env[name] === "string" && env[name].trim().length > 0;
|
|
14
|
+
return isSet(keyVariable.openrouter) && !isSet(keyVariable.typesafe) ? "openrouter" : "typesafe";
|
|
15
|
+
}
|
|
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]";
|
|
26
|
+
const MAX_IMAGE_BYTES = 16 * 1024 * 1024;
|
|
27
|
+
/** The longest side, in pixels, Jev takes an image at: TypeSafe answers HTTP 400 "Invalid image dimensions." past it, on its
|
|
28
|
+
* own API and through OpenRouter alike (live, 2026-10-30: 1568x400 answered, 1569x400 refused, area no factor). */
|
|
29
|
+
export const JEV_MAX_IMAGE_SIDE_PX = 1568;
|
|
30
|
+
const MAX_REFERENCE_BYTES = 1024;
|
|
31
|
+
/** The longest delay a Node timer accepts. */
|
|
32
|
+
const MAX_TIMER_MS = 2_147_483_647;
|
|
33
|
+
const BOX_MODEL = "jev-1.14.0";
|
|
34
|
+
/** Models that answer a Box question: Jev 1.14 and later by name, and the preview alias. The check is by name, so `jev-latest` is refused whatever version it points at. */
|
|
35
|
+
function answersBox(model) {
|
|
36
|
+
if (model === "jev-preview")
|
|
37
|
+
return true;
|
|
38
|
+
const version = /^jev-(\d+)\.(\d+)(?:\.\d+)?$/.exec(model);
|
|
39
|
+
return version !== null && (Number(version[1]) > 1 || (Number(version[1]) === 1 && Number(version[2]) >= 14));
|
|
40
|
+
}
|
|
41
|
+
/** Every string value of a JSON value, not its keys. */
|
|
42
|
+
function* stringValues(value) {
|
|
43
|
+
if (typeof value === "string")
|
|
44
|
+
yield value;
|
|
45
|
+
else if (Array.isArray(value))
|
|
46
|
+
for (const each of value)
|
|
47
|
+
yield* stringValues(each);
|
|
48
|
+
else if (isRecord(value))
|
|
49
|
+
for (const each of Object.values(value))
|
|
50
|
+
yield* stringValues(each);
|
|
51
|
+
}
|
|
52
|
+
const startsWith = (bytes, prefix) => prefix.every((byte, index) => bytes[index] === byte);
|
|
53
|
+
const imageMagic = { "image/png": [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], "image/jpeg": [0xff, 0xd8, 0xff] };
|
|
4
54
|
const adapterResponseReasons = ["response_shape", "token_usage", "model_identifier", "cost_range", "answer_validation", "max_tokens_exceeded"];
|
|
5
55
|
export function isJevResponseReason(value) {
|
|
6
56
|
return isSystemOneResponseReason(value) || typeof value === "string" && adapterResponseReasons.includes(value);
|
|
@@ -12,6 +62,9 @@ export class JevError extends Error {
|
|
|
12
62
|
status;
|
|
13
63
|
requestDiagnostic;
|
|
14
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;
|
|
15
68
|
constructor(code, message, attempts = 0, status, requestDiagnostic, responseDiagnostic) {
|
|
16
69
|
super(message);
|
|
17
70
|
this.code = code;
|
|
@@ -23,13 +76,27 @@ export class JevError extends Error {
|
|
|
23
76
|
this.responseDiagnostic = { reason: responseDiagnostic.reason };
|
|
24
77
|
}
|
|
25
78
|
}
|
|
26
|
-
|
|
79
|
+
/** Failures a request meets before it is sent: no DNS answer, no connection, no TLS handshake. Any other is after. */
|
|
80
|
+
const BEFORE_SENDING = new Set(["ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED", "ENETUNREACH", "EHOSTUNREACH", "UND_ERR_CONNECT_TIMEOUT",
|
|
81
|
+
"CERT_HAS_EXPIRED", "DEPTH_ZERO_SELF_SIGNED_CERT", "SELF_SIGNED_CERT_IN_CHAIN", "UNABLE_TO_VERIFY_LEAF_SIGNATURE", "ERR_TLS_CERT_ALTNAME_INVALID"]);
|
|
82
|
+
/** Whether a transport failure provably happened before the request was sent, read from its causes. */
|
|
83
|
+
function neverSent(error) {
|
|
84
|
+
for (let cause = error, depth = 0; isRecord(cause) || cause instanceof Error; cause = cause.cause, depth++) {
|
|
85
|
+
const code = cause.code;
|
|
86
|
+
if (typeof code === "string" && BEFORE_SENDING.has(code))
|
|
87
|
+
return true;
|
|
88
|
+
if (depth >= 4)
|
|
89
|
+
break;
|
|
90
|
+
}
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
const requireConfig = (condition, message) => {
|
|
27
94
|
if (!condition)
|
|
28
95
|
throw new JevError("configuration", message);
|
|
29
96
|
};
|
|
30
|
-
const
|
|
31
|
-
const
|
|
32
|
-
const
|
|
97
|
+
const isTimerMs = (n, allowZero = false) => Number.isSafeInteger(n) && n >= (allowZero ? 0 : 1) && n <= MAX_TIMER_MS;
|
|
98
|
+
const isRecord = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
99
|
+
const isTokenCount = (n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0;
|
|
33
100
|
function abortable(promise, signal, error) {
|
|
34
101
|
return new Promise((resolve, reject) => {
|
|
35
102
|
const abort = () => { signal.removeEventListener("abort", abort); reject(error()); };
|
|
@@ -42,41 +109,291 @@ function abortable(promise, signal, error) {
|
|
|
42
109
|
abort();
|
|
43
110
|
});
|
|
44
111
|
}
|
|
45
|
-
function wait(ms, signal, error) {
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
112
|
+
async function wait(ms, signal, error) {
|
|
113
|
+
try {
|
|
114
|
+
await sleep(ms, undefined, { signal });
|
|
115
|
+
}
|
|
116
|
+
catch {
|
|
117
|
+
throw error();
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
/** A server's Retry-After in milliseconds from now, given as delta-seconds or an HTTP date; undefined when absent or unparseable. */
|
|
121
|
+
function retryAfterMs(headers) {
|
|
122
|
+
const value = headers instanceof Headers ? headers.get("retry-after")?.trim() : undefined;
|
|
123
|
+
if (!value)
|
|
124
|
+
return undefined;
|
|
125
|
+
if (/^\d+$/.test(value))
|
|
126
|
+
return Number(value) * 1000;
|
|
127
|
+
const date = Date.parse(value);
|
|
128
|
+
return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());
|
|
129
|
+
}
|
|
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
|
|
131
|
+
* checked before anything is sent: a request that cannot be valid throws the `invalid_request` JevError that names why. */
|
|
132
|
+
function prepareRequest(params, model, maxStateBytes, provider, longContext) {
|
|
133
|
+
let body;
|
|
134
|
+
let request;
|
|
135
|
+
const invalid = (reason, message, stateBytes) => new JevError("invalid_request", message, 0, undefined, { reason,
|
|
136
|
+
...(typeof params.label === "string" ? { label: params.label.slice(0, 200) } : {}),
|
|
137
|
+
...(stateBytes === undefined || maxStateBytes === null ? {} : { stateBytes, maxStateBytes }) });
|
|
138
|
+
const state = params.state;
|
|
139
|
+
let serializedState;
|
|
140
|
+
try {
|
|
141
|
+
// The SDK refuses a request with no state, so a null or missing state is refused here, before anything is sent.
|
|
142
|
+
if (typeof state !== "string" && (typeof state !== "object" || state === null))
|
|
143
|
+
throw new Error();
|
|
144
|
+
serializedState = JSON.stringify(state);
|
|
145
|
+
if (typeof serializedState !== "string")
|
|
146
|
+
throw new Error();
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
throw invalid("invalid_state", "Jev state must be JSON-serializable text, an object or an array.");
|
|
150
|
+
}
|
|
151
|
+
const stateBytes = Buffer.byteLength(serializedState, "utf8");
|
|
152
|
+
if (maxStateBytes !== null && stateBytes > maxStateBytes)
|
|
153
|
+
throw invalid("state_too_large", `Jev assembled state is ${stateBytes} UTF-8 bytes; configured host limit is ${maxStateBytes} bytes. No request was sent.`, stateBytes);
|
|
154
|
+
const callModel = params.model ?? model;
|
|
155
|
+
if (typeof callModel !== "string" || callModel.trim().length === 0)
|
|
156
|
+
throw invalid("unsupported_model", "model must be a nonempty string; no request was sent.");
|
|
157
|
+
try {
|
|
158
|
+
body = JSON.stringify({ state: JSON.parse(serializedState), model: callModel, questions: params.questions });
|
|
159
|
+
request = JSON.parse(body);
|
|
160
|
+
if (!isRecord(request.questions) || Object.keys(request.questions).length === 0)
|
|
161
|
+
throw new Error();
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
throw invalid("invalid_questions", "Jev requires a nonempty JSON question map; no request was sent.");
|
|
165
|
+
}
|
|
166
|
+
const given = params.assets ?? {};
|
|
167
|
+
if (!isRecord(given))
|
|
168
|
+
throw invalid("invalid_assets", "assets must map each reference to an image; no request was sent.");
|
|
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");
|
|
172
|
+
const carriesImage = references.length > 0;
|
|
173
|
+
if ((carriesImage || hasBox) && provider !== "typesafe")
|
|
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.");
|
|
175
|
+
if (hasBox && !answersBox(callModel))
|
|
176
|
+
throw invalid("unsupported_model", `A Box question needs a model that answers it, by name: ${BOX_MODEL} or later, or jev-preview; jev-latest is refused whatever version it points at. No request was sent.`);
|
|
177
|
+
if (hasBox && !carriesImage)
|
|
178
|
+
throw invalid("invalid_assets", "A Box question locates something in an image, and the request carries none. No request was sent.");
|
|
179
|
+
let assets;
|
|
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) };
|
|
185
|
+
if (carriesImage) {
|
|
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.
|
|
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;
|
|
192
|
+
assets = Object.create(null);
|
|
193
|
+
assetDigests = Object.create(null);
|
|
194
|
+
for (const reference of references) {
|
|
195
|
+
const image = given[reference];
|
|
196
|
+
const sound = reference.length > 0 && Buffer.byteLength(reference, "utf8") <= MAX_REFERENCE_BYTES && !/["\\\u0000-\u001f]/.test(reference)
|
|
197
|
+
&& isRecord(image) && image.bytes instanceof Uint8Array && (image.mime === "image/png" || image.mime === "image/jpeg")
|
|
198
|
+
&& image.bytes.byteLength > 0 && image.bytes.byteLength <= MAX_IMAGE_BYTES && startsWith(image.bytes, imageMagic[image.mime]);
|
|
199
|
+
if (!sound)
|
|
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.`);
|
|
201
|
+
const stateUses = usesIn(stateTexts, reference);
|
|
202
|
+
const uses = stateUses + questionTexts.reduce((count, [, texts]) => count + usesIn(texts, reference), 0);
|
|
203
|
+
if (uses === 0)
|
|
204
|
+
throw invalid("invalid_assets", "Every image reference must appear in the state or a question. No request was sent.");
|
|
205
|
+
const size = imageDimensions(image.bytes);
|
|
206
|
+
if (size === null)
|
|
207
|
+
throw invalid("invalid_assets", `The image ${reference} has no width and height its header can be read from. No request was sent.`);
|
|
208
|
+
if (size.width > JEV_MAX_IMAGE_SIDE_PX || size.height > JEV_MAX_IMAGE_SIDE_PX)
|
|
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;
|
|
216
|
+
assets[reference] = new Image(image.bytes);
|
|
217
|
+
assetDigests[reference] = { sha256: createHash("sha256").update(image.bytes).digest("hex"), mime: image.mime, bytes: image.bytes.byteLength };
|
|
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) {
|
|
236
|
+
// The hash names the images by their own digests, so it identifies the request that was sent without holding the bytes.
|
|
237
|
+
body = JSON.stringify({ ...request, ...long, assets: assetDigests });
|
|
238
|
+
request = { ...request, assets };
|
|
239
|
+
}
|
|
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}`;
|
|
317
|
+
}
|
|
318
|
+
/** The runner's result from what the client returned at `attempt`, or the `invalid_response` JevError for the first rule it breaks.
|
|
319
|
+
* `questions` are the questions as they were sent. */
|
|
320
|
+
function readResponse(result, questions, body, pricing, attempt) {
|
|
321
|
+
const invalid = (reason, message) => new JevError("invalid_response", message, attempt, undefined, undefined, { reason });
|
|
322
|
+
if (!isRecord(result))
|
|
323
|
+
throw invalid("response_shape", "Jev returned an invalid response.");
|
|
324
|
+
const answers = result.answers;
|
|
325
|
+
// Checked against the questions as they were sent: a value JSON cannot carry (an undefined criterion) was never asked.
|
|
326
|
+
try {
|
|
327
|
+
validateAnswers(questions, answers);
|
|
328
|
+
}
|
|
329
|
+
catch (error) {
|
|
330
|
+
throw invalid(error instanceof SystemOneError && isSystemOneResponseReason(error.responseReason) ? error.responseReason : "answer_validation", "Jev returned invalid answers or probability distributions.");
|
|
331
|
+
}
|
|
332
|
+
const usage = result.usage;
|
|
333
|
+
// Usage carries token counts, a provider-reported cost (USD), or both; a half pair of counts or a bad cost is invalid.
|
|
334
|
+
const counted = isRecord(usage) && isTokenCount(usage.input_tokens) && isTokenCount(usage.output_tokens);
|
|
335
|
+
const reported = isRecord(usage) && usage.cost !== undefined && usage.cost !== null;
|
|
336
|
+
const reportedCost = reported && typeof usage.cost === "number" && Number.isFinite(usage.cost) && usage.cost >= 0 ? usage.cost : undefined;
|
|
337
|
+
const noCounts = isRecord(usage) && usage.input_tokens === undefined && usage.output_tokens === undefined;
|
|
338
|
+
// Accepted: no usage; both counts; or a valid cost with both counts or with neither.
|
|
339
|
+
const usageValid = usage == null || (isRecord(usage) && (reported ? reportedCost !== undefined && (counted || noCounts) : counted));
|
|
340
|
+
if (!usageValid)
|
|
341
|
+
throw invalid("token_usage", "Jev returned invalid token usage.");
|
|
342
|
+
if (result.model != null && (typeof result.model !== "string" || !result.model.trim())) {
|
|
343
|
+
throw invalid("model_identifier", "Jev returned an invalid model identifier.");
|
|
344
|
+
}
|
|
345
|
+
const metering = counted ? { input_tokens: usage.input_tokens, output_tokens: usage.output_tokens } : null;
|
|
346
|
+
// The provider's own cost wins; else the configured estimate; else unknown (null), never 0.
|
|
347
|
+
const cost = reportedCost !== undefined ? reportedCost : pricing && metering ? (metering.input_tokens * pricing.inputUsdPerMillionTokens + metering.output_tokens * pricing.outputUsdPerMillionTokens) / 1_000_000 : null;
|
|
348
|
+
if (cost !== null && !Number.isFinite(cost))
|
|
349
|
+
throw invalid("cost_range", "Jev cost estimate exceeded the numeric range.");
|
|
350
|
+
return {
|
|
351
|
+
answers, model: typeof result.model === "string" ? result.model : null,
|
|
352
|
+
usage: metering, cost_usd: cost,
|
|
353
|
+
request_sha256: createHash("sha256").update(body).digest("hex"),
|
|
354
|
+
};
|
|
53
355
|
}
|
|
54
356
|
export function createJevRunner(options = {}) {
|
|
55
357
|
const timeoutMs = options.timeoutMs === null ? null : (options.timeoutMs ?? 30_000);
|
|
56
358
|
const maxStateBytes = options.maxStateBytes ?? null;
|
|
57
359
|
const maxAttempts = options.maxAttempts ?? 3;
|
|
360
|
+
const retryAfterSend = options.retryAfterSend === true;
|
|
58
361
|
const retryBaseMs = options.retryBaseMs ?? 500;
|
|
59
362
|
const retryMaxMs = options.retryMaxMs ?? 5_000;
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
363
|
+
// A JavaScript caller's `client: null` is no client, the same as an absent one.
|
|
364
|
+
const hostClient = options.client ?? undefined;
|
|
365
|
+
requireConfig(timeoutMs === null || isTimerMs(timeoutMs), `timeoutMs must be null or a positive integer of at most ${MAX_TIMER_MS}.`);
|
|
366
|
+
requireConfig(maxStateBytes === null || (Number.isSafeInteger(maxStateBytes) && maxStateBytes > 0), "maxStateBytes must be null or a positive safe integer.");
|
|
367
|
+
requireConfig(timeoutMs !== null || hostClient !== undefined, "The TypeSafe SDK requires a finite timeout. For timeoutMs: null, supply a cancellation-only host client.");
|
|
368
|
+
requireConfig(Number.isInteger(maxAttempts) && maxAttempts >= 1 && maxAttempts <= 10, "maxAttempts must be an integer from 1 to 10.");
|
|
369
|
+
requireConfig(isTimerMs(retryBaseMs, true) && isTimerMs(retryMaxMs, true) && retryBaseMs <= retryMaxMs, "Retry delays must be nonnegative integers; retryBaseMs cannot exceed retryMaxMs.");
|
|
370
|
+
requireConfig(hostClient === undefined || (options.apiKey === undefined && options.baseURL === undefined && options.fetch === undefined && options.provider === undefined), "Supply either client or transport options, not both.");
|
|
371
|
+
const provider = options.provider ?? "typesafe";
|
|
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";
|
|
66
376
|
const pricing = options.pricing ? { ...options.pricing } : undefined;
|
|
67
377
|
if (pricing)
|
|
68
|
-
|
|
69
|
-
const model = options.model ?? "jev-latest";
|
|
70
|
-
|
|
378
|
+
requireConfig([pricing.inputUsdPerMillionTokens, pricing.outputUsdPerMillionTokens].every(n => Number.isFinite(n) && n >= 0), "Configured token prices must be finite nonnegative numbers.");
|
|
379
|
+
const model = options.model ?? (provider === "openrouter" ? OPENROUTER_DEFAULT_MODEL : "jev-latest");
|
|
380
|
+
requireConfig(typeof model === "string" && model.trim().length > 0, "model must be a nonempty string.");
|
|
71
381
|
let client;
|
|
72
382
|
try {
|
|
73
|
-
|
|
74
|
-
|
|
383
|
+
const key = options.apiKey ?? (provider === "openrouter" ? process.env[keyVariable.openrouter] : undefined);
|
|
384
|
+
// A blank key is refused on either provider: the SDK would send it as an empty bearer token. Given no key, the SDK falls back to
|
|
385
|
+
// TYPESAFE_API_KEY, so for OpenRouter an absent key is refused too: that would send one provider's key to another.
|
|
386
|
+
if ((key !== undefined || provider === "openrouter") && (typeof key !== "string" || key.trim().length === 0))
|
|
387
|
+
throw new Error("no key");
|
|
388
|
+
client = hostClient ?? new TypeSafeClient({
|
|
389
|
+
apiKey: key, baseURL: options.baseURL ?? (provider === "openrouter" ? OPENROUTER_BASE_URL : undefined), fetch: options.fetch,
|
|
75
390
|
defaultModel: model, retry: { maxRetries: 0 }, timeout: timeoutMs ?? undefined, logLevel: "off",
|
|
391
|
+
// Bodies go as they always have: uncompressed JSON, which a host's own fetch, a gateway and OpenRouter all read.
|
|
392
|
+
compression: false,
|
|
76
393
|
});
|
|
77
394
|
}
|
|
78
395
|
catch {
|
|
79
|
-
throw new JevError("configuration",
|
|
396
|
+
throw new JevError("configuration", `Could not configure Jev. Supply apiKey or set ${keyVariable[provider]}, and check transport options.`);
|
|
80
397
|
}
|
|
81
398
|
const runnerSignal = options.signal;
|
|
82
399
|
return async (params) => {
|
|
@@ -91,93 +408,162 @@ export function createJevRunner(options = {}) {
|
|
|
91
408
|
throw abortError();
|
|
92
409
|
const timer = timeoutMs === null ? undefined : setTimeout(() => deadline.abort(), timeoutMs);
|
|
93
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;
|
|
94
413
|
try {
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
const state = params.state ?? null;
|
|
101
|
-
let serializedState;
|
|
102
|
-
try {
|
|
103
|
-
if (typeof state !== "string" && state !== null && typeof state !== "object")
|
|
104
|
-
throw new Error();
|
|
105
|
-
serializedState = JSON.stringify(state);
|
|
106
|
-
if (typeof serializedState !== "string")
|
|
107
|
-
throw new Error();
|
|
108
|
-
}
|
|
109
|
-
catch {
|
|
110
|
-
throw invalid("invalid_state", "Jev state must be JSON-serializable text, an object, an array or null.");
|
|
111
|
-
}
|
|
112
|
-
const stateBytes = Buffer.byteLength(serializedState, "utf8");
|
|
113
|
-
if (maxStateBytes !== null && stateBytes > maxStateBytes)
|
|
114
|
-
throw invalid("state_too_large", `Jev assembled state is ${stateBytes} UTF-8 bytes; configured host limit is ${maxStateBytes} bytes. No request was sent.`, stateBytes);
|
|
115
|
-
try {
|
|
116
|
-
body = JSON.stringify({ state: JSON.parse(serializedState), model, questions: params.questions });
|
|
117
|
-
request = JSON.parse(body);
|
|
118
|
-
if (!record(request.questions) || Object.keys(request.questions).length === 0)
|
|
119
|
-
throw new Error();
|
|
120
|
-
}
|
|
121
|
-
catch {
|
|
122
|
-
throw invalid("invalid_questions", "Jev requires a nonempty JSON question map; no request was sent.");
|
|
123
|
-
}
|
|
414
|
+
const prepared = prepareRequest(params, model, maxStateBytes, provider, longContext);
|
|
415
|
+
const { request, body, headers } = prepared;
|
|
416
|
+
sent = prepared.sent;
|
|
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.
|
|
418
|
+
let billable;
|
|
124
419
|
for (attempt = 1;; attempt++) {
|
|
125
420
|
if (signal.aborted)
|
|
126
421
|
throw abortError();
|
|
127
422
|
let result;
|
|
128
423
|
try {
|
|
129
424
|
result = await abortable(client.systemOne(request, {
|
|
130
|
-
signal, ...(timeoutMs === null ? {} : { timeout: Math.max(1, timeoutMs - (Date.now() - started)) }), retry: { maxRetries: 0 },
|
|
425
|
+
signal, ...(timeoutMs === null ? {} : { timeout: Math.max(1, timeoutMs - (Date.now() - started)) }), retry: { maxRetries: 0 }, ...(headers ? { headers } : {}),
|
|
131
426
|
}), signal, abortError);
|
|
132
427
|
}
|
|
133
428
|
catch (error) {
|
|
134
|
-
|
|
429
|
+
// Each attempt's timeout is the call's remaining budget, so the client's timer and the deadline end together: whichever fires first,
|
|
430
|
+
// the deadline ended the call. A timed-out request may have been billed, and its code is what says so.
|
|
431
|
+
if (signal.aborted || (timeoutMs !== null && error instanceof APITimeoutError))
|
|
135
432
|
throw abortError();
|
|
136
433
|
const status = error instanceof APIError ? error.status : undefined;
|
|
137
|
-
const
|
|
434
|
+
const before = error instanceof APIConnectionError && neverSent(error);
|
|
435
|
+
// A request that was sent may have been answered and billed: unless the host asked for retries after sending, it is not sent again.
|
|
436
|
+
if (!retryAfterSend && (status === 408 || (status !== undefined && status >= 500 && status <= 599) || (error instanceof APIConnectionError && !before))) {
|
|
437
|
+
const safeStatus = status !== undefined && Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
|
|
438
|
+
const capacity = error instanceof APIError && isRecord(error.body) && isRecord(error.body.detail) && error.body.detail.error_type === "max_tokens_exceeded";
|
|
439
|
+
const what = safeStatus === undefined ? "Jev's connection was lost" : `Jev returned HTTP ${safeStatus}`;
|
|
440
|
+
// Only the structured reason is named, as on any HTTP failure; the provider's body text never reaches the message.
|
|
441
|
+
throw new JevError("outcome_unknown", capacity
|
|
442
|
+
? `${what}: the request exceeds the model's token budget (max_tokens_exceeded). Send fewer or shorter items per request. It was sent once and is not sent again.`
|
|
443
|
+
: `${what} after the request was sent; it may have been answered, and is not sent again.`, attempt, safeStatus, undefined, capacity ? { reason: "max_tokens_exceeded" } : undefined);
|
|
444
|
+
}
|
|
445
|
+
const toldWhen = status === 429 && error instanceof APIError && retryAfterMs(error.headers) !== undefined;
|
|
446
|
+
const retryable = retryAfterSend
|
|
447
|
+
? status === 408 || status === 429 || (status !== undefined && status >= 500 && status <= 599) || error instanceof APIConnectionError
|
|
448
|
+
: before || toldWhen;
|
|
449
|
+
// A request that never reached Jev was not billed, and a 429 was refused unanswered: neither is the billable attempt.
|
|
450
|
+
if (retryable && status !== 429 && !before && billable === undefined)
|
|
451
|
+
billable = status === undefined ? {} : { status };
|
|
138
452
|
if (retryable && attempt < maxAttempts) {
|
|
139
|
-
|
|
140
|
-
|
|
453
|
+
const backoff = Math.min(retryMaxMs, retryBaseMs * 2 ** (attempt - 1));
|
|
454
|
+
const asked = error instanceof APIError && (status === 429 || status === 503) ? retryAfterMs(error.headers) : undefined;
|
|
455
|
+
const delay = asked === undefined ? backoff : Math.max(asked, backoff);
|
|
456
|
+
// A server's Retry-After wait is kept in full or the loop gives up now: a wait that would not end before the deadline (or within the longest
|
|
457
|
+
// timer, when there is none) is never started, since the retry after it would have no time left to answer (a request that times out has a
|
|
458
|
+
// cost no one knows). A backoff wait is not checked here: the deadline ends it.
|
|
459
|
+
const left = timeoutMs === null ? MAX_TIMER_MS : timeoutMs - (Date.now() - started);
|
|
460
|
+
if (asked === undefined || delay < left) {
|
|
461
|
+
await wait(delay, signal, abortError);
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
141
464
|
}
|
|
465
|
+
// HTTP 429 means every attempt was refused unanswered; after one that may have been billed, the give-up names that one instead.
|
|
466
|
+
if (status === 429 && billable)
|
|
467
|
+
throw billable.status === undefined ? new JevError("connection", "Jev transport failed.", attempt) : new JevError("http", `Jev returned HTTP ${billable.status}.`, attempt, billable.status);
|
|
142
468
|
if (status !== undefined) {
|
|
143
469
|
const safeStatus = Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
|
|
144
|
-
const capacity = error instanceof APIError &&
|
|
470
|
+
const capacity = error instanceof APIError && isRecord(error.body) && isRecord(error.body.detail)
|
|
145
471
|
&& error.body.detail.error_type === "max_tokens_exceeded";
|
|
146
|
-
|
|
472
|
+
// Only the structured reason is named; the provider's body text never reaches the message.
|
|
473
|
+
const returned = safeStatus === undefined ? "Jev returned an HTTP failure" : `Jev returned HTTP ${safeStatus}`;
|
|
474
|
+
throw new JevError("http", capacity
|
|
475
|
+
? `${returned}: the request exceeds the model's token budget (max_tokens_exceeded). Send fewer or shorter items per request.`
|
|
476
|
+
: `${returned}.`, attempt, safeStatus, undefined, capacity ? { reason: "max_tokens_exceeded" } : undefined);
|
|
147
477
|
}
|
|
148
478
|
if (error instanceof APIConnectionError)
|
|
149
479
|
throw new JevError("connection", "Jev transport failed.", attempt);
|
|
150
480
|
throw new JevError("invalid_request", "Jev could not process the request. Check question and transport configuration.", attempt);
|
|
151
481
|
}
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
const answers = result.answers;
|
|
155
|
-
try {
|
|
156
|
-
validateAnswers(params.questions, answers);
|
|
157
|
-
}
|
|
158
|
-
catch (error) {
|
|
159
|
-
throw new JevError("invalid_response", "Jev returned invalid answers or probability distributions.", attempt, undefined, undefined, { reason: error instanceof SystemOneError && isSystemOneResponseReason(error.responseReason) ? error.responseReason : "answer_validation" });
|
|
160
|
-
}
|
|
161
|
-
const usage = result.usage;
|
|
162
|
-
if (usage != null && (!record(usage) || !tokens(usage.input_tokens) || !tokens(usage.output_tokens))) {
|
|
163
|
-
throw new JevError("invalid_response", "Jev returned invalid token usage.", attempt, undefined, undefined, { reason: "token_usage" });
|
|
164
|
-
}
|
|
165
|
-
if (result.model != null && (typeof result.model !== "string" || !result.model.trim())) {
|
|
166
|
-
throw new JevError("invalid_response", "Jev returned an invalid model identifier.", attempt, undefined, undefined, { reason: "model_identifier" });
|
|
167
|
-
}
|
|
168
|
-
const metering = record(usage) ? { input_tokens: usage.input_tokens, output_tokens: usage.output_tokens } : null;
|
|
169
|
-
const cost = pricing && metering ? (metering.input_tokens * pricing.inputUsdPerMillionTokens + metering.output_tokens * pricing.outputUsdPerMillionTokens) / 1_000_000 : null;
|
|
170
|
-
if (cost !== null && !Number.isFinite(cost))
|
|
171
|
-
throw new JevError("invalid_response", "Jev cost estimate exceeded the numeric range.", attempt, undefined, undefined, { reason: "cost_range" });
|
|
172
|
-
return {
|
|
173
|
-
answers, model: typeof result.model === "string" ? result.model : null,
|
|
174
|
-
usage: metering, cost_usd: cost,
|
|
175
|
-
request_sha256: createHash("sha256").update(body).digest("hex"),
|
|
176
|
-
};
|
|
482
|
+
const answered = readResponse(result, request.questions, body, pricing, attempt);
|
|
483
|
+
return sent ? { ...answered, state_sent: sent } : answered;
|
|
177
484
|
}
|
|
178
485
|
}
|
|
486
|
+
catch (error) {
|
|
487
|
+
if (sent && error instanceof JevError)
|
|
488
|
+
error.stateSent = sent;
|
|
489
|
+
throw error;
|
|
490
|
+
}
|
|
179
491
|
finally {
|
|
180
492
|
clearTimeout(timer);
|
|
181
493
|
}
|
|
182
494
|
};
|
|
183
495
|
}
|
|
496
|
+
/** Jev as a DecisionProvider: `createJevRunner(options)` behind the DSL's provider seam, for a host that runs every
|
|
497
|
+
* decision model through `judgeFromProvider`. A paid request is never sent twice: only a 429 with Retry-After or a
|
|
498
|
+
* connect error before sending is sent again (up to `maxAttempts`, default 3), and a 408, a 5xx or a connection lost
|
|
499
|
+
* after sending is `outcome_unknown`, at an unknown cost, and so is the cost of an `invalid_response` (a 200 that breaks
|
|
500
|
+
* the response rules was still answered); so is a deadline that ends the request in flight (the host's, or the runner's
|
|
501
|
+
* own `timeoutMs`). Only the host's own cancel is `aborted`. On TypeSafe's route it takes image input: a request's images
|
|
502
|
+
* go as Jev assets under their tokens, with the `TypeSafe-Danger-Zone-Images` header. Its other errors become
|
|
503
|
+
* DecisionProviderErrors with the same message. A cost the response reports is booked "reported"; else the counted
|
|
504
|
+
* tokens are priced at `pricing`, by default TypeSafe's published price on the TypeSafe route (none on OpenRouter's),
|
|
505
|
+
* and booked "estimate"; else the cost is unknown (null, never 0). */
|
|
506
|
+
export function jevProvider(options = {}) {
|
|
507
|
+
const provider = options.provider ?? "typesafe";
|
|
508
|
+
if (options.pricing)
|
|
509
|
+
requireConfig([options.pricing.inputUsdPerMillionTokens, options.pricing.outputUsdPerMillionTokens].every(n => Number.isFinite(n) && n >= 0), "Configured token prices must be finite nonnegative numbers.");
|
|
510
|
+
const pricing = options.pricing ?? (provider === "typesafe" ? JEV_PUBLISHED_PRICING : undefined);
|
|
511
|
+
// Priced here rather than by the runner, so a cost the response reports keeps its own basis.
|
|
512
|
+
const judge = createJevRunner({ ...options, pricing: undefined, retryAfterSend: false });
|
|
513
|
+
const capabilities = {
|
|
514
|
+
// No box question: no workflow node asks one. Images only on TypeSafe's own API, the one route verified for them.
|
|
515
|
+
types: ["noul", "choice", "score"], inputs: provider === "typesafe" ? ["text", "json", "image"] : ["text", "json"], evidence: "none", probability: "model", grounding: false,
|
|
516
|
+
replay: "never", maxQuestions: null, maxStateBytes: options.maxStateBytes ?? null,
|
|
517
|
+
};
|
|
518
|
+
return {
|
|
519
|
+
id: "jev", needs: [keyVariable[provider] ?? keyVariable.typesafe], capabilities,
|
|
520
|
+
async decide(request, ctx) {
|
|
521
|
+
checkCapabilities(capabilities, request);
|
|
522
|
+
const deadline = ctx.deadlineMs === null ? undefined : AbortSignal.timeout(ctx.deadlineMs);
|
|
523
|
+
const signal = deadline ? AbortSignal.any([ctx.signal, deadline]) : ctx.signal;
|
|
524
|
+
try {
|
|
525
|
+
const { images, ...asked } = request;
|
|
526
|
+
const assets = images && Object.keys(images).length
|
|
527
|
+
? Object.fromEntries(Object.entries(images).map(([token, image]) => [token, { bytes: image.bytes, mime: image.mime }])) : undefined;
|
|
528
|
+
const result = await judge({ ...asked, signal, decisionId: ctx.decisionId, ...(assets ? { assets } : {}) });
|
|
529
|
+
const reported = typeof result.cost_usd === "number" ? result.cost_usd : null;
|
|
530
|
+
const estimate = reported === null && pricing && result.usage
|
|
531
|
+
? (result.usage.input_tokens * pricing.inputUsdPerMillionTokens + result.usage.output_tokens * pricing.outputUsdPerMillionTokens) / 1_000_000 : null;
|
|
532
|
+
return {
|
|
533
|
+
answers: result.answers, evidence: [], model: result.model ?? null, usage: result.usage ?? null, cost_usd: reported ?? estimate,
|
|
534
|
+
cost_basis: reported !== null ? "reported" : estimate !== null ? "estimate" : "unknown", provider_request_id: null,
|
|
535
|
+
...(result.state_sent ? { state_sent: result.state_sent } : {}),
|
|
536
|
+
};
|
|
537
|
+
}
|
|
538
|
+
catch (error) {
|
|
539
|
+
if (!(error instanceof JevError))
|
|
540
|
+
throw new DecisionProviderError("http", "Jev request failed.");
|
|
541
|
+
const timedOut = Boolean(deadline?.aborted) && !ctx.signal.aborted;
|
|
542
|
+
const code = jevErrorCode(error, timedOut, ctx.signal.aborted);
|
|
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 });
|
|
545
|
+
}
|
|
546
|
+
},
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
function jevErrorCode(error, timedOut, cancelled) {
|
|
550
|
+
// The one request is in flight when a deadline ends it (the host's, or the runner's own timeout): it may have been answered.
|
|
551
|
+
if (error.code === "aborted")
|
|
552
|
+
return timedOut ? "outcome_unknown" : "aborted";
|
|
553
|
+
if (error.code === "timeout")
|
|
554
|
+
return cancelled ? "aborted" : "outcome_unknown";
|
|
555
|
+
// The runner gives up as `connection` only on a request that never reached Jev; one lost after sending is outcome_unknown.
|
|
556
|
+
if (error.code === "connection")
|
|
557
|
+
return "connection";
|
|
558
|
+
if (error.code !== "http")
|
|
559
|
+
return error.code;
|
|
560
|
+
if (error.status === 408 || (error.status !== undefined && error.status >= 500))
|
|
561
|
+
return "outcome_unknown";
|
|
562
|
+
if (error.status === 401 || error.status === 403)
|
|
563
|
+
return "auth";
|
|
564
|
+
if (error.status === 429)
|
|
565
|
+
return "rate_limited";
|
|
566
|
+
if (error.status === 400 || error.status === 422)
|
|
567
|
+
return "invalid_request";
|
|
568
|
+
return "http";
|
|
569
|
+
}
|
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@parcha/agentrun-jev",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.50",
|
|
4
4
|
"description": "Optional Jev system one decisions for AgentRun workflows",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
7
7
|
"engines": {
|
|
8
|
-
"node": ">=22.
|
|
8
|
+
"node": ">=24.22.3"
|
|
9
9
|
},
|
|
10
10
|
"exports": {
|
|
11
11
|
".": {
|
|
@@ -27,8 +27,8 @@
|
|
|
27
27
|
"test": "node --test test/*.test.mjs"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@parcha/agentrun-dsl": "0.1.0-beta.
|
|
31
|
-
"@typesafe-ai/sdk": "0.
|
|
30
|
+
"@parcha/agentrun-dsl": "0.1.0-beta.50",
|
|
31
|
+
"@typesafe-ai/sdk": "0.7.0"
|
|
32
32
|
},
|
|
33
33
|
"repository": {
|
|
34
34
|
"type": "git",
|