@parcha/agentrun-jev 0.1.0-beta.52 → 0.1.0-beta.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -83,7 +83,7 @@ Without a key, or with an `apiKey` that is blank, `createJevRunner()` throws `Je
83
83
 
84
84
  `System One` is TypeSafe's typed-question interface, exposed by the SDK as `systemOne`. A Noul answer is a truth probability from 0 to 1; the DSL converts probabilities of at least 0.5 to `true` and retains the probability beside that value. Choice and Score confidence comes from the response. Jev does not return a separate confidence for Noul; the DSL derives its own gate-strength value from the distance from 0.5, scaled to the range 0 to 1. These numbers are useful gate inputs, not calibrated guarantees.
85
85
 
86
- The public adapter API is `createJevRunner`, `jevProviderFromEnv`, `JevError`, `isJevResponseReason`, `jevImageTokens`, the constants `JEV_CONTEXT_TOKENS` and `JEV_CUT_MARK`, and the types `JevOptions`, `JevClient`, `JevProvider`, `JevErrorCode`, `JevResponseReason`, `JevResponseDiagnostic`, `JevRequestDiagnostic`, `JevImage`, `JevJudge`, `JevJudgeParams` and `JevJudgeResult`. The shared question, answer and distribution helpers live in `@parcha/agentrun-dsl`.
86
+ The public adapter API is `createJevRunner`, `jevProviderFromEnv`, `JevError`, `isJevResponseReason`, `jevImageTokens`, the constants `JEV_CONTEXT_TOKENS` and `JEV_CUT_MARK`, and the types `JevOptions`, `JevClient`, `JevProvider`, `JevErrorCode`, `JevResponseReason`, `JevResponseDiagnostic`, `JevRequestDiagnostic`, `JevProviderDiagnostic`, `JevImage`, `JevJudge`, `JevJudgeParams` and `JevJudgeResult`. The shared question, answer and distribution helpers live in `@parcha/agentrun-dsl`.
87
87
 
88
88
  ## Configuration
89
89
 
@@ -134,7 +134,7 @@ Request state has no local byte cap by default. Set `maxStateBytes` to a positiv
134
134
 
135
135
  The core allows up to 240 options per choice and 2–10 levels per score rubric. Adapter timeouts are positive integer milliseconds up to 2,147,483,647; retry delays may also be zero. `maxAttempts` is 1–10, with a default of 3.
136
136
 
137
- `JevError` provides a stable `code`, `attempts`, and optional HTTP `status`. A request the runner refuses before sending it has code `invalid_request`, `attempts` 0 and a `requestDiagnostic` (`JevRequestDiagnostic`): a `reason` (`invalid_state`, `state_too_large`, `invalid_questions`, `invalid_assets`, `unsupported_model`, `unsupported_provider` or `over_context`), the call's `label` (at most 200 characters) when it has one, and for a state over `maxStateBytes` its `stateBytes` and `maxStateBytes`. Errors deliberately omit raw service bodies, headers, input state, and causes. SDK logging is disabled. Custom clients and transports own their own logging. Do not expose credentials in browser code.
137
+ `JevError` provides a stable `code`, `attempts`, and optional HTTP `status`. A JSON HTTP error body's machine-readable `type`, `code` and `detail.error_type` values appear as `providerType`, `providerCode` and `providerErrorType` when they are at most 64 identifier characters, contain no URL separators or runner API key, and otherwise fit bounded token syntax; `type` and `code` are also read from the body's `error` object. If a broker wraps the vendor's JSON object in `message`, only its typed fields are read from that bounded object; message text is never exposed. A request the runner refuses before sending it has code `invalid_request`, `attempts` 0 and a `requestDiagnostic` (`JevRequestDiagnostic`): a `reason` (`invalid_state`, `state_too_large`, `invalid_questions`, `invalid_assets`, `unsupported_model`, `unsupported_provider` or `over_context`), the call's `label` (at most 200 characters) when it has one, and for a state over `maxStateBytes` its `stateBytes` and `maxStateBytes`. Errors deliberately omit raw service bodies, headers, input state, and causes. SDK logging is disabled. Custom clients and transports own their own logging. Do not expose credentials in browser code.
138
138
 
139
139
  Optional `responseDiagnostic.reason` identifies a fixed response invariant, such
140
140
  as `answer_keys`, `probability_mass`, or `token_usage`. An explicitly structured
package/dist/index.d.ts CHANGED
@@ -93,6 +93,12 @@ export type JevRequestDiagnostic = {
93
93
  stateBytes?: number;
94
94
  maxStateBytes?: number;
95
95
  };
96
+ /** The provider's machine-readable error fields. Message text is never read into them. */
97
+ export type JevProviderDiagnostic = {
98
+ type?: string;
99
+ code?: string;
100
+ errorType?: string;
101
+ };
96
102
  /** Deliberately excludes provider bodies, headers, input state, and underlying causes. */
97
103
  export declare class JevError extends Error {
98
104
  readonly code: JevErrorCode;
@@ -100,10 +106,13 @@ export declare class JevError extends Error {
100
106
  readonly status?: number | undefined;
101
107
  readonly requestDiagnostic?: JevRequestDiagnostic | undefined;
102
108
  readonly responseDiagnostic?: JevResponseDiagnostic;
109
+ readonly providerType?: string;
110
+ readonly providerCode?: string;
111
+ readonly providerErrorType?: string;
103
112
  /** The state the request held as sent, and the values cut, when it was cut to fit Jev's context before sending: a
104
113
  * decision receipt records it (jevProvider passes it on as the DecisionProviderError's `stateSent`). */
105
114
  stateSent?: DecisionStateSent;
106
- constructor(code: JevErrorCode, message: string, attempts?: number, status?: number | undefined, requestDiagnostic?: JevRequestDiagnostic | undefined, responseDiagnostic?: JevResponseDiagnostic);
115
+ constructor(code: JevErrorCode, message: string, attempts?: number, status?: number | undefined, requestDiagnostic?: JevRequestDiagnostic | undefined, responseDiagnostic?: JevResponseDiagnostic, providerDiagnostic?: JevProviderDiagnostic);
107
116
  }
108
117
  /** The tokens a request's context is held for one use of a `width` x `height` image: one per 14x14-pixel patch, each side
109
118
  * rounded up, so a full-size image (1568x1568) is held 12,544. TypeSafe publishes no figure (its images page, read
package/dist/index.js CHANGED
@@ -62,10 +62,13 @@ export class JevError extends Error {
62
62
  status;
63
63
  requestDiagnostic;
64
64
  responseDiagnostic;
65
+ providerType;
66
+ providerCode;
67
+ providerErrorType;
65
68
  /** The state the request held as sent, and the values cut, when it was cut to fit Jev's context before sending: a
66
69
  * decision receipt records it (jevProvider passes it on as the DecisionProviderError's `stateSent`). */
67
70
  stateSent;
68
- constructor(code, message, attempts = 0, status, requestDiagnostic, responseDiagnostic) {
71
+ constructor(code, message, attempts = 0, status, requestDiagnostic, responseDiagnostic, providerDiagnostic) {
69
72
  super(message);
70
73
  this.code = code;
71
74
  this.attempts = attempts;
@@ -74,6 +77,15 @@ export class JevError extends Error {
74
77
  this.name = "JevError";
75
78
  if (isJevResponseReason(responseDiagnostic?.reason))
76
79
  this.responseDiagnostic = { reason: responseDiagnostic.reason };
80
+ const providerType = providerToken(providerDiagnostic?.type);
81
+ const providerCode = providerToken(providerDiagnostic?.code);
82
+ const providerErrorType = providerToken(providerDiagnostic?.errorType, true);
83
+ if (providerType !== undefined)
84
+ this.providerType = providerType;
85
+ if (providerCode !== undefined)
86
+ this.providerCode = providerCode;
87
+ if (providerErrorType !== undefined)
88
+ this.providerErrorType = providerErrorType;
77
89
  }
78
90
  }
79
91
  /** Failures a request meets before it is sent: no DNS answer, no connection, no TLS handshake. Any other is after. */
@@ -97,6 +109,53 @@ const requireConfig = (condition, message) => {
97
109
  const isTimerMs = (n, allowZero = false) => Number.isSafeInteger(n) && n >= (allowZero ? 0 : 1) && n <= MAX_TIMER_MS;
98
110
  const isRecord = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
99
111
  const isTokenCount = (n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0;
112
+ /** A bounded machine token, never free text. Provider `error_type` values are lower-case identifiers. */
113
+ function providerToken(value, lowerCase = false, sensitiveValue) {
114
+ if (typeof value !== "string" || value.length === 0 || value.length > 64 ||
115
+ (sensitiveValue && value.includes(sensitiveValue)))
116
+ return undefined;
117
+ return (lowerCase ? /^[a-z][a-z0-9_.-]*$/ : /^[A-Za-z0-9][A-Za-z0-9_.-]*$/).test(value) ? value : undefined;
118
+ }
119
+ /** Read typed fields from one JSON object, without accepting free text as a field value. */
120
+ function providerFields(body, sensitiveValue) {
121
+ const nested = isRecord(body.error) ? body.error : undefined;
122
+ const detail = isRecord(body.detail) ? body.detail : undefined;
123
+ return {
124
+ type: providerToken(body.type ?? nested?.type, false, sensitiveValue),
125
+ code: providerToken(body.code ?? nested?.code, false, sensitiveValue),
126
+ errorType: providerToken(detail?.error_type, true, sensitiveValue),
127
+ };
128
+ }
129
+ /** A broker can put the vendor's JSON object in `message`; read only its typed fields, never the message itself. */
130
+ function wrappedProviderFields(message, sensitiveValue) {
131
+ if (typeof message !== "string" || message.length < 2 || message.length > 16_384)
132
+ return undefined;
133
+ try {
134
+ const body = JSON.parse(message);
135
+ return isRecord(body) ? providerFields(body, sensitiveValue) : undefined;
136
+ }
137
+ catch {
138
+ return undefined;
139
+ }
140
+ }
141
+ function directProviderErrorType(error, sensitiveValue) {
142
+ return isRecord(error.body) ? providerFields(error.body, sensitiveValue).errorType : undefined;
143
+ }
144
+ function providerDiagnostic(error, sensitiveValue) {
145
+ const body = error.body;
146
+ if (!isRecord(body))
147
+ return undefined;
148
+ const direct = providerFields(body, sensitiveValue);
149
+ const nested = isRecord(body.error) ? body.error : undefined;
150
+ const wrapped = wrappedProviderFields(nested?.message, sensitiveValue) ??
151
+ wrappedProviderFields(body.message, sensitiveValue);
152
+ const diagnostic = {
153
+ type: direct.type ?? wrapped?.type,
154
+ code: direct.code ?? wrapped?.code,
155
+ errorType: direct.errorType ?? wrapped?.errorType,
156
+ };
157
+ return diagnostic.type === undefined && diagnostic.code === undefined && diagnostic.errorType === undefined ? undefined : diagnostic;
158
+ }
100
159
  function abortable(promise, signal, error) {
101
160
  return new Promise((resolve, reject) => {
102
161
  const abort = () => { signal.removeEventListener("abort", abort); reject(error()); };
@@ -379,14 +438,16 @@ export function createJevRunner(options = {}) {
379
438
  const model = options.model ?? (provider === "openrouter" ? OPENROUTER_DEFAULT_MODEL : "jev-latest");
380
439
  requireConfig(typeof model === "string" && model.trim().length > 0, "model must be a nonempty string.");
381
440
  let client;
441
+ let apiKey;
382
442
  try {
383
- const key = options.apiKey ?? (provider === "openrouter" ? process.env[keyVariable.openrouter] : undefined);
384
- // A blank key is refused on either provider: the SDK would send it as an empty bearer token. Given no key, the SDK falls back to
385
- // TYPESAFE_API_KEY, so for OpenRouter an absent key is refused too: that would send one provider's key to another.
386
- if ((key !== undefined || provider === "openrouter") && (typeof key !== "string" || key.trim().length === 0))
443
+ // A host client owns its credentials. Do not let an ambient, blank SDK key reject an otherwise valid client.
444
+ apiKey = hostClient === undefined ? options.apiKey ?? process.env[keyVariable[provider]] : undefined;
445
+ // A blank SDK key is refused on either provider: the SDK would send it as an empty bearer token. The provider-specific lookup also
446
+ // keeps an OpenRouter request from falling back to TYPESAFE_API_KEY, and lets diagnostics redact whichever runner key is in use.
447
+ if (hostClient === undefined && (apiKey !== undefined || provider === "openrouter") && (typeof apiKey !== "string" || apiKey.trim().length === 0))
387
448
  throw new Error("no key");
388
449
  client = hostClient ?? new TypeSafeClient({
389
- apiKey: key, baseURL: options.baseURL ?? (provider === "openrouter" ? OPENROUTER_BASE_URL : undefined), fetch: options.fetch,
450
+ apiKey, baseURL: options.baseURL ?? (provider === "openrouter" ? OPENROUTER_BASE_URL : undefined), fetch: options.fetch,
390
451
  defaultModel: model, retry: { maxRetries: 0 }, timeout: timeoutMs ?? undefined, logLevel: "off",
391
452
  // Bodies go as they always have: uncompressed JSON, which a host's own fetch, a gateway and OpenRouter all read.
392
453
  compression: false,
@@ -431,16 +492,18 @@ export function createJevRunner(options = {}) {
431
492
  if (signal.aborted || (timeoutMs !== null && error instanceof APITimeoutError))
432
493
  throw abortError();
433
494
  const status = error instanceof APIError ? error.status : undefined;
495
+ const provider = error instanceof APIError ? providerDiagnostic(error, apiKey) : undefined;
496
+ const directErrorType = error instanceof APIError ? directProviderErrorType(error, apiKey) : undefined;
434
497
  const before = error instanceof APIConnectionError && neverSent(error);
435
498
  // A request that was sent may have been answered and billed: unless the host asked for retries after sending, it is not sent again.
436
499
  if (!retryAfterSend && (status === 408 || (status !== undefined && status >= 500 && status <= 599) || (error instanceof APIConnectionError && !before))) {
437
500
  const safeStatus = status !== undefined && Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
438
- const capacity = error instanceof APIError && isRecord(error.body) && isRecord(error.body.detail) && error.body.detail.error_type === "max_tokens_exceeded";
501
+ const capacity = directErrorType === "max_tokens_exceeded";
439
502
  const what = safeStatus === undefined ? "Jev's connection was lost" : `Jev returned HTTP ${safeStatus}`;
440
503
  // Only the structured reason is named, as on any HTTP failure; the provider's body text never reaches the message.
441
504
  throw new JevError("outcome_unknown", capacity
442
505
  ? `${what}: the request exceeds the model's token budget (max_tokens_exceeded). Send fewer or shorter items per request. It was sent once and is not sent again.`
443
- : `${what} after the request was sent; it may have been answered, and is not sent again.`, attempt, safeStatus, undefined, capacity ? { reason: "max_tokens_exceeded" } : undefined);
506
+ : `${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, provider);
444
507
  }
445
508
  const toldWhen = status === 429 && error instanceof APIError && retryAfterMs(error.headers) !== undefined;
446
509
  const retryable = retryAfterSend
@@ -448,7 +511,7 @@ export function createJevRunner(options = {}) {
448
511
  : before || toldWhen;
449
512
  // A request that never reached Jev was not billed, and a 429 was refused unanswered: neither is the billable attempt.
450
513
  if (retryable && status !== 429 && !before && billable === undefined)
451
- billable = status === undefined ? {} : { status };
514
+ billable = { ...(status === undefined ? {} : { status }), ...(provider ? { provider } : {}) };
452
515
  if (retryable && attempt < maxAttempts) {
453
516
  const backoff = Math.min(retryMaxMs, retryBaseMs * 2 ** (attempt - 1));
454
517
  const asked = error instanceof APIError && (status === 429 || status === 503) ? retryAfterMs(error.headers) : undefined;
@@ -464,16 +527,17 @@ export function createJevRunner(options = {}) {
464
527
  }
465
528
  // HTTP 429 means every attempt was refused unanswered; after one that may have been billed, the give-up names that one instead.
466
529
  if (status === 429 && billable)
467
- throw billable.status === undefined ? new JevError("connection", "Jev transport failed.", attempt) : new JevError("http", `Jev returned HTTP ${billable.status}.`, attempt, billable.status);
530
+ throw billable.status === undefined
531
+ ? new JevError("connection", "Jev transport failed.", attempt)
532
+ : new JevError("http", `Jev returned HTTP ${billable.status}.`, attempt, billable.status, undefined, undefined, billable.provider);
468
533
  if (status !== undefined) {
469
534
  const safeStatus = Number.isInteger(status) && status >= 100 && status <= 599 ? status : undefined;
470
- const capacity = error instanceof APIError && isRecord(error.body) && isRecord(error.body.detail)
471
- && error.body.detail.error_type === "max_tokens_exceeded";
535
+ const capacity = directErrorType === "max_tokens_exceeded";
472
536
  // Only the structured reason is named; the provider's body text never reaches the message.
473
537
  const returned = safeStatus === undefined ? "Jev returned an HTTP failure" : `Jev returned HTTP ${safeStatus}`;
474
538
  throw new JevError("http", capacity
475
539
  ? `${returned}: the request exceeds the model's token budget (max_tokens_exceeded). Send fewer or shorter items per request.`
476
- : `${returned}.`, attempt, safeStatus, undefined, capacity ? { reason: "max_tokens_exceeded" } : undefined);
540
+ : `${returned}.`, attempt, safeStatus, undefined, capacity ? { reason: "max_tokens_exceeded" } : undefined, provider);
477
541
  }
478
542
  if (error instanceof APIConnectionError)
479
543
  throw new JevError("connection", "Jev transport failed.", attempt);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@parcha/agentrun-jev",
3
- "version": "0.1.0-beta.52",
3
+ "version": "0.1.0-beta.53",
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.52",
30
+ "@parcha/agentrun-dsl": "0.1.0-beta.53",
31
31
  "@typesafe-ai/sdk": "0.7.0"
32
32
  },
33
33
  "repository": {