@parcha/agentrun-jev 0.1.0-beta.3 → 0.1.0-beta.31
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 +110 -39
- package/dist/index.d.ts +56 -5
- package/dist/index.js +338 -87
- package/package.json +3 -3
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 22.19 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`, 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,32 @@ 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`. Requests over about 32 KB of state run in the provider's slower long-context mode.
|
|
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
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.
|
|
56
123
|
|
|
57
124
|
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
125
|
|
|
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.
|
|
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.
|
|
60
127
|
|
|
61
128
|
Optional `responseDiagnostic.reason` identifies a fixed response invariant, such
|
|
62
129
|
as `answer_keys`, `probability_mass`, or `token_usage`. An explicitly structured
|
|
@@ -64,48 +131,52 @@ capacity rejection can report `max_tokens_exceeded`; arbitrary provider messages
|
|
|
64
131
|
are never parsed for a reason. These details do not change validation, retry
|
|
65
132
|
policy, or the submitted evidence. Unknown causes remain unspecified.
|
|
66
133
|
|
|
67
|
-
Successful results retain `answers`, reported `model`, reported token `usage`, and a SHA-256 of the submitted request. `cost_usd` is `
|
|
68
|
-
|
|
69
|
-
## Offline tests
|
|
134
|
+
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.
|
|
70
135
|
|
|
71
|
-
|
|
136
|
+
## Images and Box questions
|
|
72
137
|
|
|
73
|
-
|
|
74
|
-
import assert from 'node:assert/strict';
|
|
75
|
-
import { createJevRunner } from '@parcha/agentrun-jev';
|
|
138
|
+
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.
|
|
76
139
|
|
|
77
|
-
|
|
78
|
-
|
|
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
|
-
});
|
|
140
|
+
```ts
|
|
141
|
+
import { createJevRunner, type JevJudge } from '@parcha/agentrun-jev';
|
|
89
142
|
|
|
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
|
-
},
|
|
143
|
+
const judge: JevJudge = createJevRunner({ model: 'jev-1.14.0' });
|
|
144
|
+
const { answers, usage, cost_usd } = await judge({
|
|
145
|
+
label: 'door', kind: 'judge',
|
|
146
|
+
state: 'The camera shows <photo>.',
|
|
97
147
|
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
|
-
},
|
|
148
|
+
open: { type: 'noul', instructions: 'Is the door in <photo> open?' },
|
|
149
|
+
door: { type: 'box', instructions: 'the door in <photo>' },
|
|
102
150
|
},
|
|
151
|
+
assets: { '<photo>': { bytes: pngOrJpegFileBytes, mime: 'image/png' } }, // PNG or JPEG file bytes
|
|
103
152
|
});
|
|
104
|
-
|
|
105
|
-
console.log(result.answers.answersQuestion);
|
|
153
|
+
// answers.door = { type: 'box', box: { top, bottom, left, right }, confidence } — edges are fractions of the image's height and width
|
|
106
154
|
```
|
|
107
155
|
|
|
108
|
-
|
|
156
|
+
- `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.
|
|
157
|
+
- 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.
|
|
158
|
+
- 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.
|
|
159
|
+
- 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.
|
|
160
|
+
- 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`.
|
|
161
|
+
- `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.
|
|
162
|
+
- 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"`.
|
|
163
|
+
- Request bodies are sent uncompressed; the SDK's default compresses them with zstd.
|
|
164
|
+
- Box is a preview: Jev's page says its request format, answers and limits can change between releases.
|
|
165
|
+
|
|
166
|
+
## As a DecisionProvider
|
|
167
|
+
|
|
168
|
+
`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`:
|
|
169
|
+
|
|
170
|
+
```ts
|
|
171
|
+
import { judgeFromProvider, runWorkflow } from '@parcha/agentrun-dsl';
|
|
172
|
+
import { jevProvider } from '@parcha/agentrun-jev';
|
|
173
|
+
|
|
174
|
+
const result = await runWorkflow(workflow, input, { runJudge: judgeFromProvider(jevProvider()) });
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
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`).
|
|
178
|
+
|
|
179
|
+
## Testing your own host
|
|
109
180
|
|
|
110
181
|
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
182
|
|
package/dist/index.d.ts
CHANGED
|
@@ -1,10 +1,44 @@
|
|
|
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 } 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
|
+
/** The longest side, in pixels, Jev takes an image at: TypeSafe answers HTTP 400 "Invalid image dimensions." past it, on its
|
|
37
|
+
* own API and through OpenRouter alike (live, 2026-10-30: 1568x400 answered, 1569x400 refused, area no factor). */
|
|
38
|
+
export declare const JEV_MAX_IMAGE_SIDE_PX = 1568;
|
|
7
39
|
export interface JevOptions {
|
|
40
|
+
/** `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`. */
|
|
41
|
+
provider?: JevProvider;
|
|
8
42
|
apiKey?: string;
|
|
9
43
|
/** API root, without /v1/systemone; useful for an explicitly configured gateway. */
|
|
10
44
|
baseURL?: string;
|
|
@@ -17,16 +51,22 @@ export interface JevOptions {
|
|
|
17
51
|
timeoutMs?: number | null;
|
|
18
52
|
/** Optional host guard on serialized UTF-8 JSON state; null or omission disables it. */
|
|
19
53
|
maxStateBytes?: number | null;
|
|
54
|
+
/** Attempts for a request that never reached Jev, or a 429 that says when to retry (default 3). */
|
|
20
55
|
maxAttempts?: number;
|
|
56
|
+
/** Also retry a 408, a 5xx and a connection lost after the request was sent, as earlier versions did. Such a retry can
|
|
57
|
+
* re-send a request Jev answered and billed. Off by default: those fail `outcome_unknown` after one attempt. */
|
|
58
|
+
retryAfterSend?: boolean;
|
|
21
59
|
retryBaseMs?: number;
|
|
22
60
|
retryMaxMs?: number;
|
|
23
|
-
/** Explicit estimate; unknown prices are never silently treated as free. */
|
|
61
|
+
/** Explicit estimate, used when the provider reports no cost; unknown prices are never silently treated as free. */
|
|
24
62
|
pricing?: {
|
|
25
63
|
inputUsdPerMillionTokens: number;
|
|
26
64
|
outputUsdPerMillionTokens: number;
|
|
27
65
|
};
|
|
28
66
|
}
|
|
29
|
-
|
|
67
|
+
/** `outcome_unknown`: the request was sent and its outcome is not known (a 408, a 5xx, a connection lost after sending). It
|
|
68
|
+
* may have been answered and billed, so it is not sent again, and its cost is unknown. */
|
|
69
|
+
export type JevErrorCode = "configuration" | "invalid_request" | "invalid_response" | "http" | "connection" | "aborted" | "timeout" | "outcome_unknown";
|
|
30
70
|
declare const adapterResponseReasons: readonly ["response_shape", "token_usage", "model_identifier", "cost_range", "answer_validation", "max_tokens_exceeded"];
|
|
31
71
|
export type JevResponseReason = SystemOneResponseReason | typeof adapterResponseReasons[number];
|
|
32
72
|
export declare function isJevResponseReason(value: unknown): value is JevResponseReason;
|
|
@@ -34,7 +74,7 @@ export type JevResponseDiagnostic = {
|
|
|
34
74
|
reason: JevResponseReason;
|
|
35
75
|
};
|
|
36
76
|
export type JevRequestDiagnostic = {
|
|
37
|
-
reason: "invalid_state" | "state_too_large" | "invalid_questions";
|
|
77
|
+
reason: "invalid_state" | "state_too_large" | "invalid_questions" | "invalid_assets" | "unsupported_model" | "unsupported_provider";
|
|
38
78
|
label?: string;
|
|
39
79
|
stateBytes?: number;
|
|
40
80
|
maxStateBytes?: number;
|
|
@@ -48,5 +88,16 @@ export declare class JevError extends Error {
|
|
|
48
88
|
readonly responseDiagnostic?: JevResponseDiagnostic;
|
|
49
89
|
constructor(code: JevErrorCode, message: string, attempts?: number, status?: number | undefined, requestDiagnostic?: JevRequestDiagnostic | undefined, responseDiagnostic?: JevResponseDiagnostic);
|
|
50
90
|
}
|
|
51
|
-
export declare function createJevRunner(options?: JevOptions):
|
|
91
|
+
export declare function createJevRunner(options?: JevOptions): JevJudge;
|
|
92
|
+
/** Jev as a DecisionProvider: `createJevRunner(options)` behind the DSL's provider seam, for a host that runs every
|
|
93
|
+
* decision model through `judgeFromProvider`. A paid request is never sent twice: only a 429 with Retry-After or a
|
|
94
|
+
* connect error before sending is sent again (up to `maxAttempts`, default 3), and a 408, a 5xx or a connection lost
|
|
95
|
+
* after sending is `outcome_unknown`, at an unknown cost, and so is the cost of an `invalid_response` (a 200 that breaks
|
|
96
|
+
* the response rules was still answered); so is a deadline that ends the request in flight (the host's, or the runner's
|
|
97
|
+
* own `timeoutMs`). Only the host's own cancel is `aborted`. On TypeSafe's route it takes image input: a request's images
|
|
98
|
+
* go as Jev assets under their tokens, with the `TypeSafe-Danger-Zone-Images` header. Its other errors become
|
|
99
|
+
* DecisionProviderErrors with the same message. A cost the response reports is booked "reported"; else the counted
|
|
100
|
+
* tokens are priced at `pricing`, by default TypeSafe's published price on the TypeSafe route (none on OpenRouter's),
|
|
101
|
+
* and booked "estimate"; else the cost is unknown (null, never 0). */
|
|
102
|
+
export declare function jevProvider(options?: JevOptions): DecisionProvider;
|
|
52
103
|
export {};
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
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
|
+
const MAX_IMAGE_BYTES = 16 * 1024 * 1024;
|
|
18
|
+
/** The longest side, in pixels, Jev takes an image at: TypeSafe answers HTTP 400 "Invalid image dimensions." past it, on its
|
|
19
|
+
* own API and through OpenRouter alike (live, 2026-10-30: 1568x400 answered, 1569x400 refused, area no factor). */
|
|
20
|
+
export const JEV_MAX_IMAGE_SIDE_PX = 1568;
|
|
21
|
+
const MAX_REFERENCE_BYTES = 1024;
|
|
22
|
+
/** The longest delay a Node timer accepts. */
|
|
23
|
+
const MAX_TIMER_MS = 2_147_483_647;
|
|
24
|
+
const BOX_MODEL = "jev-1.14.0";
|
|
25
|
+
/** 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. */
|
|
26
|
+
function answersBox(model) {
|
|
27
|
+
if (model === "jev-preview")
|
|
28
|
+
return true;
|
|
29
|
+
const version = /^jev-(\d+)\.(\d+)(?:\.\d+)?$/.exec(model);
|
|
30
|
+
return version !== null && (Number(version[1]) > 1 || (Number(version[1]) === 1 && Number(version[2]) >= 14));
|
|
31
|
+
}
|
|
32
|
+
/** Every string value of a JSON value, not its keys. */
|
|
33
|
+
function* stringValues(value) {
|
|
34
|
+
if (typeof value === "string")
|
|
35
|
+
yield value;
|
|
36
|
+
else if (Array.isArray(value))
|
|
37
|
+
for (const each of value)
|
|
38
|
+
yield* stringValues(each);
|
|
39
|
+
else if (isRecord(value))
|
|
40
|
+
for (const each of Object.values(value))
|
|
41
|
+
yield* stringValues(each);
|
|
42
|
+
}
|
|
43
|
+
const startsWith = (bytes, prefix) => prefix.every((byte, index) => bytes[index] === byte);
|
|
44
|
+
const imageMagic = { "image/png": [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], "image/jpeg": [0xff, 0xd8, 0xff] };
|
|
4
45
|
const adapterResponseReasons = ["response_shape", "token_usage", "model_identifier", "cost_range", "answer_validation", "max_tokens_exceeded"];
|
|
5
46
|
export function isJevResponseReason(value) {
|
|
6
47
|
return isSystemOneResponseReason(value) || typeof value === "string" && adapterResponseReasons.includes(value);
|
|
@@ -23,13 +64,27 @@ export class JevError extends Error {
|
|
|
23
64
|
this.responseDiagnostic = { reason: responseDiagnostic.reason };
|
|
24
65
|
}
|
|
25
66
|
}
|
|
26
|
-
|
|
67
|
+
/** Failures a request meets before it is sent: no DNS answer, no connection, no TLS handshake. Any other is after. */
|
|
68
|
+
const BEFORE_SENDING = new Set(["ENOTFOUND", "EAI_AGAIN", "ECONNREFUSED", "ENETUNREACH", "EHOSTUNREACH", "UND_ERR_CONNECT_TIMEOUT",
|
|
69
|
+
"CERT_HAS_EXPIRED", "DEPTH_ZERO_SELF_SIGNED_CERT", "SELF_SIGNED_CERT_IN_CHAIN", "UNABLE_TO_VERIFY_LEAF_SIGNATURE", "ERR_TLS_CERT_ALTNAME_INVALID"]);
|
|
70
|
+
/** Whether a transport failure provably happened before the request was sent, read from its causes. */
|
|
71
|
+
function neverSent(error) {
|
|
72
|
+
for (let cause = error, depth = 0; isRecord(cause) || cause instanceof Error; cause = cause.cause, depth++) {
|
|
73
|
+
const code = cause.code;
|
|
74
|
+
if (typeof code === "string" && BEFORE_SENDING.has(code))
|
|
75
|
+
return true;
|
|
76
|
+
if (depth >= 4)
|
|
77
|
+
break;
|
|
78
|
+
}
|
|
79
|
+
return false;
|
|
80
|
+
}
|
|
81
|
+
const requireConfig = (condition, message) => {
|
|
27
82
|
if (!condition)
|
|
28
83
|
throw new JevError("configuration", message);
|
|
29
84
|
};
|
|
30
|
-
const
|
|
31
|
-
const
|
|
32
|
-
const
|
|
85
|
+
const isTimerMs = (n, allowZero = false) => Number.isSafeInteger(n) && n >= (allowZero ? 0 : 1) && n <= MAX_TIMER_MS;
|
|
86
|
+
const isRecord = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
|
|
87
|
+
const isTokenCount = (n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0;
|
|
33
88
|
function abortable(promise, signal, error) {
|
|
34
89
|
return new Promise((resolve, reject) => {
|
|
35
90
|
const abort = () => { signal.removeEventListener("abort", abort); reject(error()); };
|
|
@@ -42,41 +97,180 @@ function abortable(promise, signal, error) {
|
|
|
42
97
|
abort();
|
|
43
98
|
});
|
|
44
99
|
}
|
|
45
|
-
function wait(ms, signal, error) {
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
100
|
+
async function wait(ms, signal, error) {
|
|
101
|
+
try {
|
|
102
|
+
await sleep(ms, undefined, { signal });
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
throw error();
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
/** A server's Retry-After in milliseconds from now, given as delta-seconds or an HTTP date; undefined when absent or unparseable. */
|
|
109
|
+
function retryAfterMs(headers) {
|
|
110
|
+
const value = headers instanceof Headers ? headers.get("retry-after")?.trim() : undefined;
|
|
111
|
+
if (!value)
|
|
112
|
+
return undefined;
|
|
113
|
+
if (/^\d+$/.test(value))
|
|
114
|
+
return Number(value) * 1000;
|
|
115
|
+
const date = Date.parse(value);
|
|
116
|
+
return Number.isNaN(date) ? undefined : Math.max(0, date - Date.now());
|
|
117
|
+
}
|
|
118
|
+
/** 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
|
+
* 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) {
|
|
121
|
+
let body;
|
|
122
|
+
let request;
|
|
123
|
+
const invalid = (reason, message, stateBytes) => new JevError("invalid_request", message, 0, undefined, { reason,
|
|
124
|
+
...(typeof params.label === "string" ? { label: params.label.slice(0, 200) } : {}),
|
|
125
|
+
...(stateBytes === undefined || maxStateBytes === null ? {} : { stateBytes, maxStateBytes }) });
|
|
126
|
+
const state = params.state;
|
|
127
|
+
let serializedState;
|
|
128
|
+
try {
|
|
129
|
+
// The SDK refuses a request with no state, so a null or missing state is refused here, before anything is sent.
|
|
130
|
+
if (typeof state !== "string" && (typeof state !== "object" || state === null))
|
|
131
|
+
throw new Error();
|
|
132
|
+
serializedState = JSON.stringify(state);
|
|
133
|
+
if (typeof serializedState !== "string")
|
|
134
|
+
throw new Error();
|
|
135
|
+
}
|
|
136
|
+
catch {
|
|
137
|
+
throw invalid("invalid_state", "Jev state must be JSON-serializable text, an object or an array.");
|
|
138
|
+
}
|
|
139
|
+
const stateBytes = Buffer.byteLength(serializedState, "utf8");
|
|
140
|
+
if (maxStateBytes !== null && stateBytes > maxStateBytes)
|
|
141
|
+
throw invalid("state_too_large", `Jev assembled state is ${stateBytes} UTF-8 bytes; configured host limit is ${maxStateBytes} bytes. No request was sent.`, stateBytes);
|
|
142
|
+
const callModel = params.model ?? model;
|
|
143
|
+
if (typeof callModel !== "string" || callModel.trim().length === 0)
|
|
144
|
+
throw invalid("unsupported_model", "model must be a nonempty string; no request was sent.");
|
|
145
|
+
try {
|
|
146
|
+
body = JSON.stringify({ state: JSON.parse(serializedState), model: callModel, questions: params.questions });
|
|
147
|
+
request = JSON.parse(body);
|
|
148
|
+
if (!isRecord(request.questions) || Object.keys(request.questions).length === 0)
|
|
149
|
+
throw new Error();
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
throw invalid("invalid_questions", "Jev requires a nonempty JSON question map; no request was sent.");
|
|
153
|
+
}
|
|
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
|
+
const given = params.assets ?? {};
|
|
157
|
+
if (!isRecord(given))
|
|
158
|
+
throw invalid("invalid_assets", "assets must map each reference to an image; no request was sent.");
|
|
159
|
+
const references = Object.keys(given);
|
|
160
|
+
const carriesImage = references.length > 0;
|
|
161
|
+
if ((carriesImage || hasBox) && provider !== "typesafe")
|
|
162
|
+
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.");
|
|
163
|
+
if (hasBox && !answersBox(callModel))
|
|
164
|
+
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.`);
|
|
165
|
+
if (hasBox && !carriesImage)
|
|
166
|
+
throw invalid("invalid_assets", "A Box question locates something in an image, and the request carries none. No request was sent.");
|
|
167
|
+
let assets;
|
|
168
|
+
let assetDigests;
|
|
169
|
+
if (carriesImage) {
|
|
170
|
+
// 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)] : [])];
|
|
172
|
+
assets = Object.create(null);
|
|
173
|
+
assetDigests = Object.create(null);
|
|
174
|
+
for (const reference of references) {
|
|
175
|
+
const image = given[reference];
|
|
176
|
+
const sound = reference.length > 0 && Buffer.byteLength(reference, "utf8") <= MAX_REFERENCE_BYTES && !/["\\\u0000-\u001f]/.test(reference)
|
|
177
|
+
&& isRecord(image) && image.bytes instanceof Uint8Array && (image.mime === "image/png" || image.mime === "image/jpeg")
|
|
178
|
+
&& image.bytes.byteLength > 0 && image.bytes.byteLength <= MAX_IMAGE_BYTES && startsWith(image.bytes, imageMagic[image.mime]);
|
|
179
|
+
if (!sound)
|
|
180
|
+
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)))
|
|
182
|
+
throw invalid("invalid_assets", "Every image reference must appear in the state or a question. No request was sent.");
|
|
183
|
+
const size = imageDimensions(image.bytes);
|
|
184
|
+
if (size === null)
|
|
185
|
+
throw invalid("invalid_assets", `The image ${reference} has no width and height its header can be read from. No request was sent.`);
|
|
186
|
+
if (size.width > JEV_MAX_IMAGE_SIDE_PX || size.height > JEV_MAX_IMAGE_SIDE_PX)
|
|
187
|
+
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.`);
|
|
188
|
+
assets[reference] = new Image(image.bytes);
|
|
189
|
+
assetDigests[reference] = { sha256: createHash("sha256").update(image.bytes).digest("hex"), mime: image.mime, bytes: image.bytes.byteLength };
|
|
190
|
+
}
|
|
191
|
+
// 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 });
|
|
193
|
+
request = { ...request, assets };
|
|
194
|
+
}
|
|
195
|
+
const headers = carriesImage || hasBox ? { [IMAGE_HEADER]: "true" } : undefined;
|
|
196
|
+
return { request, body, ...(headers ? { headers } : {}) };
|
|
197
|
+
}
|
|
198
|
+
/** The runner's result from what the client returned at `attempt`, or the `invalid_response` JevError for the first rule it breaks.
|
|
199
|
+
* `questions` are the questions as they were sent. */
|
|
200
|
+
function readResponse(result, questions, body, pricing, attempt) {
|
|
201
|
+
const invalid = (reason, message) => new JevError("invalid_response", message, attempt, undefined, undefined, { reason });
|
|
202
|
+
if (!isRecord(result))
|
|
203
|
+
throw invalid("response_shape", "Jev returned an invalid response.");
|
|
204
|
+
const answers = result.answers;
|
|
205
|
+
// Checked against the questions as they were sent: a value JSON cannot carry (an undefined criterion) was never asked.
|
|
206
|
+
try {
|
|
207
|
+
validateAnswers(questions, answers);
|
|
208
|
+
}
|
|
209
|
+
catch (error) {
|
|
210
|
+
throw invalid(error instanceof SystemOneError && isSystemOneResponseReason(error.responseReason) ? error.responseReason : "answer_validation", "Jev returned invalid answers or probability distributions.");
|
|
211
|
+
}
|
|
212
|
+
const usage = result.usage;
|
|
213
|
+
// Usage carries token counts, a provider-reported cost (USD), or both; a half pair of counts or a bad cost is invalid.
|
|
214
|
+
const counted = isRecord(usage) && isTokenCount(usage.input_tokens) && isTokenCount(usage.output_tokens);
|
|
215
|
+
const reported = isRecord(usage) && usage.cost !== undefined && usage.cost !== null;
|
|
216
|
+
const reportedCost = reported && typeof usage.cost === "number" && Number.isFinite(usage.cost) && usage.cost >= 0 ? usage.cost : undefined;
|
|
217
|
+
const noCounts = isRecord(usage) && usage.input_tokens === undefined && usage.output_tokens === undefined;
|
|
218
|
+
// Accepted: no usage; both counts; or a valid cost with both counts or with neither.
|
|
219
|
+
const usageValid = usage == null || (isRecord(usage) && (reported ? reportedCost !== undefined && (counted || noCounts) : counted));
|
|
220
|
+
if (!usageValid)
|
|
221
|
+
throw invalid("token_usage", "Jev returned invalid token usage.");
|
|
222
|
+
if (result.model != null && (typeof result.model !== "string" || !result.model.trim())) {
|
|
223
|
+
throw invalid("model_identifier", "Jev returned an invalid model identifier.");
|
|
224
|
+
}
|
|
225
|
+
const metering = counted ? { input_tokens: usage.input_tokens, output_tokens: usage.output_tokens } : null;
|
|
226
|
+
// The provider's own cost wins; else the configured estimate; else unknown (null), never 0.
|
|
227
|
+
const cost = reportedCost !== undefined ? reportedCost : pricing && metering ? (metering.input_tokens * pricing.inputUsdPerMillionTokens + metering.output_tokens * pricing.outputUsdPerMillionTokens) / 1_000_000 : null;
|
|
228
|
+
if (cost !== null && !Number.isFinite(cost))
|
|
229
|
+
throw invalid("cost_range", "Jev cost estimate exceeded the numeric range.");
|
|
230
|
+
return {
|
|
231
|
+
answers, model: typeof result.model === "string" ? result.model : null,
|
|
232
|
+
usage: metering, cost_usd: cost,
|
|
233
|
+
request_sha256: createHash("sha256").update(body).digest("hex"),
|
|
234
|
+
};
|
|
53
235
|
}
|
|
54
236
|
export function createJevRunner(options = {}) {
|
|
55
237
|
const timeoutMs = options.timeoutMs === null ? null : (options.timeoutMs ?? 30_000);
|
|
56
238
|
const maxStateBytes = options.maxStateBytes ?? null;
|
|
57
239
|
const maxAttempts = options.maxAttempts ?? 3;
|
|
240
|
+
const retryAfterSend = options.retryAfterSend === true;
|
|
58
241
|
const retryBaseMs = options.retryBaseMs ?? 500;
|
|
59
242
|
const retryMaxMs = options.retryMaxMs ?? 5_000;
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
243
|
+
// A JavaScript caller's `client: null` is no client, the same as an absent one.
|
|
244
|
+
const hostClient = options.client ?? undefined;
|
|
245
|
+
requireConfig(timeoutMs === null || isTimerMs(timeoutMs), `timeoutMs must be null or a positive integer of at most ${MAX_TIMER_MS}.`);
|
|
246
|
+
requireConfig(maxStateBytes === null || (Number.isSafeInteger(maxStateBytes) && maxStateBytes > 0), "maxStateBytes must be null or a positive safe integer.");
|
|
247
|
+
requireConfig(timeoutMs !== null || hostClient !== undefined, "The TypeSafe SDK requires a finite timeout. For timeoutMs: null, supply a cancellation-only host client.");
|
|
248
|
+
requireConfig(Number.isInteger(maxAttempts) && maxAttempts >= 1 && maxAttempts <= 10, "maxAttempts must be an integer from 1 to 10.");
|
|
249
|
+
requireConfig(isTimerMs(retryBaseMs, true) && isTimerMs(retryMaxMs, true) && retryBaseMs <= retryMaxMs, "Retry delays must be nonnegative integers; retryBaseMs cannot exceed retryMaxMs.");
|
|
250
|
+
requireConfig(hostClient === undefined || (options.apiKey === undefined && options.baseURL === undefined && options.fetch === undefined && options.provider === undefined), "Supply either client or transport options, not both.");
|
|
251
|
+
const provider = options.provider ?? "typesafe";
|
|
252
|
+
requireConfig(provider === "typesafe" || provider === "openrouter", "provider must be typesafe or openrouter.");
|
|
66
253
|
const pricing = options.pricing ? { ...options.pricing } : undefined;
|
|
67
254
|
if (pricing)
|
|
68
|
-
|
|
69
|
-
const model = options.model ?? "jev-latest";
|
|
70
|
-
|
|
255
|
+
requireConfig([pricing.inputUsdPerMillionTokens, pricing.outputUsdPerMillionTokens].every(n => Number.isFinite(n) && n >= 0), "Configured token prices must be finite nonnegative numbers.");
|
|
256
|
+
const model = options.model ?? (provider === "openrouter" ? OPENROUTER_DEFAULT_MODEL : "jev-latest");
|
|
257
|
+
requireConfig(typeof model === "string" && model.trim().length > 0, "model must be a nonempty string.");
|
|
71
258
|
let client;
|
|
72
259
|
try {
|
|
73
|
-
|
|
74
|
-
|
|
260
|
+
const key = options.apiKey ?? (provider === "openrouter" ? process.env[keyVariable.openrouter] : undefined);
|
|
261
|
+
// 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
|
|
262
|
+
// TYPESAFE_API_KEY, so for OpenRouter an absent key is refused too: that would send one provider's key to another.
|
|
263
|
+
if ((key !== undefined || provider === "openrouter") && (typeof key !== "string" || key.trim().length === 0))
|
|
264
|
+
throw new Error("no key");
|
|
265
|
+
client = hostClient ?? new TypeSafeClient({
|
|
266
|
+
apiKey: key, baseURL: options.baseURL ?? (provider === "openrouter" ? OPENROUTER_BASE_URL : undefined), fetch: options.fetch,
|
|
75
267
|
defaultModel: model, retry: { maxRetries: 0 }, timeout: timeoutMs ?? undefined, logLevel: "off",
|
|
268
|
+
// Bodies go as they always have: uncompressed JSON, which a host's own fetch, a gateway and OpenRouter all read.
|
|
269
|
+
compression: false,
|
|
76
270
|
});
|
|
77
271
|
}
|
|
78
272
|
catch {
|
|
79
|
-
throw new JevError("configuration",
|
|
273
|
+
throw new JevError("configuration", `Could not configure Jev. Supply apiKey or set ${keyVariable[provider]}, and check transport options.`);
|
|
80
274
|
}
|
|
81
275
|
const runnerSignal = options.signal;
|
|
82
276
|
return async (params) => {
|
|
@@ -92,88 +286,73 @@ export function createJevRunner(options = {}) {
|
|
|
92
286
|
const timer = timeoutMs === null ? undefined : setTimeout(() => deadline.abort(), timeoutMs);
|
|
93
287
|
const started = Date.now();
|
|
94
288
|
try {
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
...(typeof params.label === "string" ? { label: params.label.slice(0, 200) } : {}),
|
|
99
|
-
...(stateBytes === undefined || maxStateBytes === null ? {} : { stateBytes, maxStateBytes }) });
|
|
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
|
-
}
|
|
289
|
+
const { request, body, headers } = prepareRequest(params, model, maxStateBytes, provider);
|
|
290
|
+
// 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
|
+
let billable;
|
|
124
292
|
for (attempt = 1;; attempt++) {
|
|
125
293
|
if (signal.aborted)
|
|
126
294
|
throw abortError();
|
|
127
295
|
let result;
|
|
128
296
|
try {
|
|
129
297
|
result = await abortable(client.systemOne(request, {
|
|
130
|
-
signal, ...(timeoutMs === null ? {} : { timeout: Math.max(1, timeoutMs - (Date.now() - started)) }), retry: { maxRetries: 0 },
|
|
298
|
+
signal, ...(timeoutMs === null ? {} : { timeout: Math.max(1, timeoutMs - (Date.now() - started)) }), retry: { maxRetries: 0 }, ...(headers ? { headers } : {}),
|
|
131
299
|
}), signal, abortError);
|
|
132
300
|
}
|
|
133
301
|
catch (error) {
|
|
134
|
-
|
|
302
|
+
// Each attempt's timeout is the call's remaining budget, so the client's timer and the deadline end together: whichever fires first,
|
|
303
|
+
// the deadline ended the call. A timed-out request may have been billed, and its code is what says so.
|
|
304
|
+
if (signal.aborted || (timeoutMs !== null && error instanceof APITimeoutError))
|
|
135
305
|
throw abortError();
|
|
136
306
|
const status = error instanceof APIError ? error.status : undefined;
|
|
137
|
-
const
|
|
307
|
+
const before = error instanceof APIConnectionError && neverSent(error);
|
|
308
|
+
// A request that was sent may have been answered and billed: unless the host asked for retries after sending, it is not sent again.
|
|
309
|
+
if (!retryAfterSend && (status === 408 || (status !== undefined && status >= 500 && status <= 599) || (error instanceof APIConnectionError && !before))) {
|
|
310
|
+
const safeStatus = status !== undefined && Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
|
|
311
|
+
const capacity = error instanceof APIError && isRecord(error.body) && isRecord(error.body.detail) && error.body.detail.error_type === "max_tokens_exceeded";
|
|
312
|
+
const what = safeStatus === undefined ? "Jev's connection was lost" : `Jev returned HTTP ${safeStatus}`;
|
|
313
|
+
// Only the structured reason is named, as on any HTTP failure; the provider's body text never reaches the message.
|
|
314
|
+
throw new JevError("outcome_unknown", capacity
|
|
315
|
+
? `${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.`
|
|
316
|
+
: `${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);
|
|
317
|
+
}
|
|
318
|
+
const toldWhen = status === 429 && error instanceof APIError && retryAfterMs(error.headers) !== undefined;
|
|
319
|
+
const retryable = retryAfterSend
|
|
320
|
+
? status === 408 || status === 429 || (status !== undefined && status >= 500 && status <= 599) || error instanceof APIConnectionError
|
|
321
|
+
: before || toldWhen;
|
|
322
|
+
// A request that never reached Jev was not billed, and a 429 was refused unanswered: neither is the billable attempt.
|
|
323
|
+
if (retryable && status !== 429 && !before && billable === undefined)
|
|
324
|
+
billable = status === undefined ? {} : { status };
|
|
138
325
|
if (retryable && attempt < maxAttempts) {
|
|
139
|
-
|
|
140
|
-
|
|
326
|
+
const backoff = Math.min(retryMaxMs, retryBaseMs * 2 ** (attempt - 1));
|
|
327
|
+
const asked = error instanceof APIError && (status === 429 || status === 503) ? retryAfterMs(error.headers) : undefined;
|
|
328
|
+
const delay = asked === undefined ? backoff : Math.max(asked, backoff);
|
|
329
|
+
// 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
|
|
330
|
+
// 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
|
|
331
|
+
// cost no one knows). A backoff wait is not checked here: the deadline ends it.
|
|
332
|
+
const left = timeoutMs === null ? MAX_TIMER_MS : timeoutMs - (Date.now() - started);
|
|
333
|
+
if (asked === undefined || delay < left) {
|
|
334
|
+
await wait(delay, signal, abortError);
|
|
335
|
+
continue;
|
|
336
|
+
}
|
|
141
337
|
}
|
|
338
|
+
// HTTP 429 means every attempt was refused unanswered; after one that may have been billed, the give-up names that one instead.
|
|
339
|
+
if (status === 429 && billable)
|
|
340
|
+
throw billable.status === undefined ? new JevError("connection", "Jev transport failed.", attempt) : new JevError("http", `Jev returned HTTP ${billable.status}.`, attempt, billable.status);
|
|
142
341
|
if (status !== undefined) {
|
|
143
342
|
const safeStatus = Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
|
|
144
|
-
const capacity = error instanceof APIError &&
|
|
343
|
+
const capacity = error instanceof APIError && isRecord(error.body) && isRecord(error.body.detail)
|
|
145
344
|
&& error.body.detail.error_type === "max_tokens_exceeded";
|
|
146
|
-
|
|
345
|
+
// Only the structured reason is named; the provider's body text never reaches the message.
|
|
346
|
+
const returned = safeStatus === undefined ? "Jev returned an HTTP failure" : `Jev returned HTTP ${safeStatus}`;
|
|
347
|
+
throw new JevError("http", capacity
|
|
348
|
+
? `${returned}: the request exceeds the model's token budget (max_tokens_exceeded). Send fewer or shorter items per request.`
|
|
349
|
+
: `${returned}.`, attempt, safeStatus, undefined, capacity ? { reason: "max_tokens_exceeded" } : undefined);
|
|
147
350
|
}
|
|
148
351
|
if (error instanceof APIConnectionError)
|
|
149
352
|
throw new JevError("connection", "Jev transport failed.", attempt);
|
|
150
353
|
throw new JevError("invalid_request", "Jev could not process the request. Check question and transport configuration.", attempt);
|
|
151
354
|
}
|
|
152
|
-
|
|
153
|
-
throw new JevError("invalid_response", "Jev returned an invalid response.", attempt, undefined, undefined, { reason: "response_shape" });
|
|
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
|
-
};
|
|
355
|
+
return readResponse(result, request.questions, body, pricing, attempt);
|
|
177
356
|
}
|
|
178
357
|
}
|
|
179
358
|
finally {
|
|
@@ -181,3 +360,75 @@ export function createJevRunner(options = {}) {
|
|
|
181
360
|
}
|
|
182
361
|
};
|
|
183
362
|
}
|
|
363
|
+
/** Jev as a DecisionProvider: `createJevRunner(options)` behind the DSL's provider seam, for a host that runs every
|
|
364
|
+
* decision model through `judgeFromProvider`. A paid request is never sent twice: only a 429 with Retry-After or a
|
|
365
|
+
* connect error before sending is sent again (up to `maxAttempts`, default 3), and a 408, a 5xx or a connection lost
|
|
366
|
+
* after sending is `outcome_unknown`, at an unknown cost, and so is the cost of an `invalid_response` (a 200 that breaks
|
|
367
|
+
* the response rules was still answered); so is a deadline that ends the request in flight (the host's, or the runner's
|
|
368
|
+
* own `timeoutMs`). Only the host's own cancel is `aborted`. On TypeSafe's route it takes image input: a request's images
|
|
369
|
+
* go as Jev assets under their tokens, with the `TypeSafe-Danger-Zone-Images` header. Its other errors become
|
|
370
|
+
* DecisionProviderErrors with the same message. A cost the response reports is booked "reported"; else the counted
|
|
371
|
+
* tokens are priced at `pricing`, by default TypeSafe's published price on the TypeSafe route (none on OpenRouter's),
|
|
372
|
+
* and booked "estimate"; else the cost is unknown (null, never 0). */
|
|
373
|
+
export function jevProvider(options = {}) {
|
|
374
|
+
const provider = options.provider ?? "typesafe";
|
|
375
|
+
if (options.pricing)
|
|
376
|
+
requireConfig([options.pricing.inputUsdPerMillionTokens, options.pricing.outputUsdPerMillionTokens].every(n => Number.isFinite(n) && n >= 0), "Configured token prices must be finite nonnegative numbers.");
|
|
377
|
+
const pricing = options.pricing ?? (provider === "typesafe" ? JEV_PUBLISHED_PRICING : undefined);
|
|
378
|
+
// Priced here rather than by the runner, so a cost the response reports keeps its own basis.
|
|
379
|
+
const judge = createJevRunner({ ...options, pricing: undefined, retryAfterSend: false });
|
|
380
|
+
const capabilities = {
|
|
381
|
+
// No box question: no workflow node asks one. Images only on TypeSafe's own API, the one route verified for them.
|
|
382
|
+
types: ["noul", "choice", "score"], inputs: provider === "typesafe" ? ["text", "json", "image"] : ["text", "json"], evidence: "none", probability: "model", grounding: false,
|
|
383
|
+
replay: "never", maxQuestions: null, maxStateBytes: options.maxStateBytes ?? null,
|
|
384
|
+
};
|
|
385
|
+
return {
|
|
386
|
+
id: "jev", needs: [keyVariable[provider] ?? keyVariable.typesafe], capabilities,
|
|
387
|
+
async decide(request, ctx) {
|
|
388
|
+
checkCapabilities(capabilities, request);
|
|
389
|
+
const deadline = ctx.deadlineMs === null ? undefined : AbortSignal.timeout(ctx.deadlineMs);
|
|
390
|
+
const signal = deadline ? AbortSignal.any([ctx.signal, deadline]) : ctx.signal;
|
|
391
|
+
try {
|
|
392
|
+
const { images, ...asked } = request;
|
|
393
|
+
const assets = images && Object.keys(images).length
|
|
394
|
+
? Object.fromEntries(Object.entries(images).map(([token, image]) => [token, { bytes: image.bytes, mime: image.mime }])) : undefined;
|
|
395
|
+
const result = await judge({ ...asked, signal, decisionId: ctx.decisionId, ...(assets ? { assets } : {}) });
|
|
396
|
+
const reported = typeof result.cost_usd === "number" ? result.cost_usd : null;
|
|
397
|
+
const estimate = reported === null && pricing && result.usage
|
|
398
|
+
? (result.usage.input_tokens * pricing.inputUsdPerMillionTokens + result.usage.output_tokens * pricing.outputUsdPerMillionTokens) / 1_000_000 : null;
|
|
399
|
+
return {
|
|
400
|
+
answers: result.answers, evidence: [], model: result.model ?? null, usage: result.usage ?? null, cost_usd: reported ?? estimate,
|
|
401
|
+
cost_basis: reported !== null ? "reported" : estimate !== null ? "estimate" : "unknown", provider_request_id: null,
|
|
402
|
+
};
|
|
403
|
+
}
|
|
404
|
+
catch (error) {
|
|
405
|
+
if (!(error instanceof JevError))
|
|
406
|
+
throw new DecisionProviderError("http", "Jev request failed.");
|
|
407
|
+
const timedOut = Boolean(deadline?.aborted) && !ctx.signal.aborted;
|
|
408
|
+
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 });
|
|
410
|
+
}
|
|
411
|
+
},
|
|
412
|
+
};
|
|
413
|
+
}
|
|
414
|
+
function jevErrorCode(error, timedOut, cancelled) {
|
|
415
|
+
// 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.
|
|
416
|
+
if (error.code === "aborted")
|
|
417
|
+
return timedOut ? "outcome_unknown" : "aborted";
|
|
418
|
+
if (error.code === "timeout")
|
|
419
|
+
return cancelled ? "aborted" : "outcome_unknown";
|
|
420
|
+
// The runner gives up as `connection` only on a request that never reached Jev; one lost after sending is outcome_unknown.
|
|
421
|
+
if (error.code === "connection")
|
|
422
|
+
return "connection";
|
|
423
|
+
if (error.code !== "http")
|
|
424
|
+
return error.code;
|
|
425
|
+
if (error.status === 408 || (error.status !== undefined && error.status >= 500))
|
|
426
|
+
return "outcome_unknown";
|
|
427
|
+
if (error.status === 401 || error.status === 403)
|
|
428
|
+
return "auth";
|
|
429
|
+
if (error.status === 429)
|
|
430
|
+
return "rate_limited";
|
|
431
|
+
if (error.status === 400 || error.status === 422)
|
|
432
|
+
return "invalid_request";
|
|
433
|
+
return "http";
|
|
434
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@parcha/agentrun-jev",
|
|
3
|
-
"version": "0.1.0-beta.
|
|
3
|
+
"version": "0.1.0-beta.31",
|
|
4
4
|
"description": "Optional Jev system one decisions for AgentRun workflows",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -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.31",
|
|
31
|
+
"@typesafe-ai/sdk": "0.7.0"
|
|
32
32
|
},
|
|
33
33
|
"repository": {
|
|
34
34
|
"type": "git",
|