@parcha/agentrun-jev 0.1.0-beta.27 → 0.1.0-beta.29
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 +18 -3
- package/dist/index.d.ts +28 -2
- package/dist/index.js +117 -4
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -2,10 +2,10 @@
|
|
|
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, on npm under the `
|
|
5
|
+
Beta, on npm under the `latest` dist-tag (`npm view @parcha/agentrun-jev dist-tags`). Requires Node.js 22.19 or later.
|
|
6
6
|
|
|
7
7
|
```sh
|
|
8
|
-
npm install @parcha/agentrun-dsl@
|
|
8
|
+
npm install @parcha/agentrun-dsl@latest @parcha/agentrun-jev@latest
|
|
9
9
|
```
|
|
10
10
|
|
|
11
11
|
## Offline tests
|
|
@@ -115,7 +115,9 @@ Cost: when the response reports `usage.cost` (USD) it is `cost_usd`; otherwise a
|
|
|
115
115
|
|
|
116
116
|
The official `@typesafe-ai/sdk` resolves `TYPESAFE_API_KEY` and `TYPESAFE_BASE_URL`. Explicit `apiKey` and `baseURL` options take precedence. An API root ends before `/v1/systemone`. Set `fetch` for a custom transport, or supply a `client` with a `systemOne(request, options)` method. A custom client must honor the request signal and disable its own retries; it owns its credentials and cannot be combined with transport options.
|
|
117
117
|
|
|
118
|
-
|
|
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.
|
|
119
121
|
|
|
120
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.
|
|
121
123
|
|
|
@@ -161,6 +163,19 @@ const { answers, usage, cost_usd } = await judge({
|
|
|
161
163
|
- Request bodies are sent uncompressed; the SDK's default compresses them with zstd.
|
|
162
164
|
- Box is a preview: Jev's page says its request format, answers and limits can change between releases.
|
|
163
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
|
+
|
|
164
179
|
## Testing your own host
|
|
165
180
|
|
|
166
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`.
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,17 @@
|
|
|
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
7
|
/** Where Jev is reached: TypeSafe's own API (default) or OpenRouter's System One path. */
|
|
8
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
|
+
}>;
|
|
9
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. */
|
|
10
16
|
export declare function jevProviderFromEnv(env?: Record<string, string | undefined>): JevProvider;
|
|
11
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. */
|
|
@@ -27,6 +33,9 @@ export type JevJudgeParams = Parameters<RunJudge>[0] & {
|
|
|
27
33
|
export type JevJudgeResult = Awaited<ReturnType<RunJudge>>;
|
|
28
34
|
/** The judge `createJevRunner` returns, and the port a host passes to a package that asks Jev about images without importing the SDK. */
|
|
29
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;
|
|
30
39
|
export interface JevOptions {
|
|
31
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`. */
|
|
32
41
|
provider?: JevProvider;
|
|
@@ -42,7 +51,11 @@ export interface JevOptions {
|
|
|
42
51
|
timeoutMs?: number | null;
|
|
43
52
|
/** Optional host guard on serialized UTF-8 JSON state; null or omission disables it. */
|
|
44
53
|
maxStateBytes?: number | null;
|
|
54
|
+
/** Attempts for a request that never reached Jev, or a 429 that says when to retry (default 3). */
|
|
45
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;
|
|
46
59
|
retryBaseMs?: number;
|
|
47
60
|
retryMaxMs?: number;
|
|
48
61
|
/** Explicit estimate, used when the provider reports no cost; unknown prices are never silently treated as free. */
|
|
@@ -51,7 +64,9 @@ export interface JevOptions {
|
|
|
51
64
|
outputUsdPerMillionTokens: number;
|
|
52
65
|
};
|
|
53
66
|
}
|
|
54
|
-
|
|
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";
|
|
55
70
|
declare const adapterResponseReasons: readonly ["response_shape", "token_usage", "model_identifier", "cost_range", "answer_validation", "max_tokens_exceeded"];
|
|
56
71
|
export type JevResponseReason = SystemOneResponseReason | typeof adapterResponseReasons[number];
|
|
57
72
|
export declare function isJevResponseReason(value: unknown): value is JevResponseReason;
|
|
@@ -74,4 +89,15 @@ export declare class JevError extends Error {
|
|
|
74
89
|
constructor(code: JevErrorCode, message: string, attempts?: number, status?: number | undefined, requestDiagnostic?: JevRequestDiagnostic | undefined, responseDiagnostic?: JevResponseDiagnostic);
|
|
75
90
|
}
|
|
76
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;
|
|
77
103
|
export {};
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { setTimeout as sleep } from "node:timers/promises";
|
|
3
3
|
import { APIConnectionError, APIError, APITimeoutError, Image, TypeSafeClient } from "@typesafe-ai/sdk";
|
|
4
|
-
import { validateAnswers, SystemOneError, isSystemOneResponseReason } from "@parcha/agentrun-dsl";
|
|
4
|
+
import { validateAnswers, SystemOneError, isSystemOneResponseReason, checkCapabilities, DecisionProviderError, imageDimensions } from "@parcha/agentrun-dsl";
|
|
5
5
|
const keyVariable = { typesafe: "TYPESAFE_API_KEY", openrouter: "OPENROUTER_API_KEY" };
|
|
6
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 });
|
|
7
10
|
const OPENROUTER_DEFAULT_MODEL = "~typesafe/jev-latest";
|
|
8
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. */
|
|
9
12
|
export function jevProviderFromEnv(env = process.env) {
|
|
@@ -12,6 +15,9 @@ export function jevProviderFromEnv(env = process.env) {
|
|
|
12
15
|
}
|
|
13
16
|
const IMAGE_HEADER = "TypeSafe-Danger-Zone-Images";
|
|
14
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;
|
|
15
21
|
const MAX_REFERENCE_BYTES = 1024;
|
|
16
22
|
/** The longest delay a Node timer accepts. */
|
|
17
23
|
const MAX_TIMER_MS = 2_147_483_647;
|
|
@@ -58,6 +64,20 @@ export class JevError extends Error {
|
|
|
58
64
|
this.responseDiagnostic = { reason: responseDiagnostic.reason };
|
|
59
65
|
}
|
|
60
66
|
}
|
|
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
|
+
}
|
|
61
81
|
const requireConfig = (condition, message) => {
|
|
62
82
|
if (!condition)
|
|
63
83
|
throw new JevError("configuration", message);
|
|
@@ -139,7 +159,7 @@ function prepareRequest(params, model, maxStateBytes, provider) {
|
|
|
139
159
|
const references = Object.keys(given);
|
|
140
160
|
const carriesImage = references.length > 0;
|
|
141
161
|
if ((carriesImage || hasBox) && provider !== "typesafe")
|
|
142
|
-
throw invalid("unsupported_provider", "Images and Box questions are sent to TypeSafe's own API only
|
|
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.");
|
|
143
163
|
if (hasBox && !answersBox(callModel))
|
|
144
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.`);
|
|
145
165
|
if (hasBox && !carriesImage)
|
|
@@ -160,6 +180,11 @@ function prepareRequest(params, model, maxStateBytes, provider) {
|
|
|
160
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.`);
|
|
161
181
|
if (!texts.some(text => text.includes(reference)))
|
|
162
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.`);
|
|
163
188
|
assets[reference] = new Image(image.bytes);
|
|
164
189
|
assetDigests[reference] = { sha256: createHash("sha256").update(image.bytes).digest("hex"), mime: image.mime, bytes: image.bytes.byteLength };
|
|
165
190
|
}
|
|
@@ -212,6 +237,7 @@ export function createJevRunner(options = {}) {
|
|
|
212
237
|
const timeoutMs = options.timeoutMs === null ? null : (options.timeoutMs ?? 30_000);
|
|
213
238
|
const maxStateBytes = options.maxStateBytes ?? null;
|
|
214
239
|
const maxAttempts = options.maxAttempts ?? 3;
|
|
240
|
+
const retryAfterSend = options.retryAfterSend === true;
|
|
215
241
|
const retryBaseMs = options.retryBaseMs ?? 500;
|
|
216
242
|
const retryMaxMs = options.retryMaxMs ?? 5_000;
|
|
217
243
|
// A JavaScript caller's `client: null` is no client, the same as an absent one.
|
|
@@ -278,8 +304,23 @@ export function createJevRunner(options = {}) {
|
|
|
278
304
|
if (signal.aborted || (timeoutMs !== null && error instanceof APITimeoutError))
|
|
279
305
|
throw abortError();
|
|
280
306
|
const status = error instanceof APIError ? error.status : undefined;
|
|
281
|
-
const
|
|
282
|
-
|
|
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)
|
|
283
324
|
billable = status === undefined ? {} : { status };
|
|
284
325
|
if (retryable && attempt < maxAttempts) {
|
|
285
326
|
const backoff = Math.min(retryMaxMs, retryBaseMs * 2 ** (attempt - 1));
|
|
@@ -319,3 +360,75 @@ export function createJevRunner(options = {}) {
|
|
|
319
360
|
}
|
|
320
361
|
};
|
|
321
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.29",
|
|
4
4
|
"description": "Optional Jev system one decisions for AgentRun workflows",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
"test": "node --test test/*.test.mjs"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@parcha/agentrun-dsl": "0.1.0-beta.
|
|
30
|
+
"@parcha/agentrun-dsl": "0.1.0-beta.29",
|
|
31
31
|
"@typesafe-ai/sdk": "0.7.0"
|
|
32
32
|
},
|
|
33
33
|
"repository": {
|