@theoremjs/agents 0.3.4-next.570.gfda95a3 → 0.3.4-next.586.ga59d695

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.
@@ -5,7 +5,7 @@ import { defineProtocol, } from '../../kernel/protocols/mod.js';
5
5
  import { turnStopFromOpenAiFinishReason } from '../../kernel/stop.js';
6
6
  import { base64ToBytes, bytesToBase64 } from '../../kernel/util/base64.js';
7
7
  import { mimeEssence } from '../../kernel/util/mime.js';
8
- import { buildChatMessages, resolveResponseFormat, wireTools, } from '../openrouter/openai/compat.js';
8
+ import { buildChatMessages, httpError, resolveResponseFormat, statedError, wireTools, } from '../openrouter/openai/compat.js';
9
9
  import { openAiResponse, openAiUsageTokens } from '../openrouter/openai/usage.js';
10
10
  import { pcmFormatFromMime, wrapPcmAsWav } from '../shared/pcm.js';
11
11
  import { asProtocolEvent } from '../shared/protocol-events.js';
@@ -42,8 +42,7 @@ function errorRow(row) {
42
42
  if (!error)
43
43
  return;
44
44
  const status = typeof error.code === 'number' ? error.code : 502;
45
- const message = typeof error.message === 'string' ? error.message : JSON.stringify(error);
46
- throw new TheoremError(kindOfHttpStatus(status), message);
45
+ throw new TheoremError(kindOfHttpStatus(status), statedError(row) ?? JSON.stringify(error));
47
46
  }
48
47
  function citations(part, reply) {
49
48
  const sources = (Array.isArray(part.annotations) ? part.annotations : []).flatMap((item) => {
@@ -176,6 +175,7 @@ export const openAi = defineProtocol({
176
175
  description: 'The Chat Completions shape that OpenAI and most compatible servers speak.', // labels-exempt: builder field description, read by the studio and docs
177
176
  endpoints: { text: '/chat/completions', speech: '/audio/speech' },
178
177
  options: z.strictObject({}),
178
+ error: (failure) => httpError(failure, 'Chat Completions'),
179
179
  create(context) {
180
180
  return {
181
181
  async *complete(request) {
@@ -1,6 +1,15 @@
1
- import { type ProducedError } from '../../../guardrails/error.js';
1
+ import { type ProducedError, TheoremError } from '../../../guardrails/error.js';
2
2
  import type { InteractionPart, ModelRequest, ResolvedStructured, WireFunctionTool } from '../../../kernel/types.js';
3
- /** The detail is the body's `error.message` (or raw text), so the upstream reason reaches traces. */
3
+ /**
4
+ * Why a Chat Completions body says the call failed: its `error.message`, then the provider's own
5
+ * fields (OpenRouter's `metadata.raw` names the upstream reason), else the raw body.
6
+ */
7
+ declare function statedError(body: unknown): string | undefined;
8
+ /** A refused Chat Completions call, its kind from the status and its stated reason in the message. */
9
+ declare function httpError(failure: {
10
+ status: number;
11
+ body: unknown;
12
+ }, label: string): TheoremError;
4
13
  declare function httpErrorEvent(res: Response, label: string): Promise<ProducedError>;
5
14
  interface GatewayHeaderConfig {
6
15
  siteUrl?: string;
@@ -16,4 +25,4 @@ declare function wireTools(wireTools?: WireFunctionTool[]): Record<string, unkno
16
25
  declare function resolveResponseFormat(structured: ResolvedStructured | null): Record<string, unknown> | undefined;
17
26
  declare function openAiGatewayHeaders(config: GatewayHeaderConfig): Record<string, string> | undefined;
18
27
  export type { GatewayHeaderConfig };
19
- export { buildChatMessages, httpErrorEvent, openAiGatewayHeaders, resolveResponseFormat, wireTools, };
28
+ export { buildChatMessages, httpError, httpErrorEvent, openAiGatewayHeaders, resolveResponseFormat, statedError, wireTools, };
@@ -3,20 +3,39 @@ import { asRecord } from '../../../kernel/engine/record.js';
3
3
  import { historyMessageParts, isMediaRefPart } from '../../../kernel/interaction-parts.js';
4
4
  import { withCarriedToolFiles } from '../../shared/carried-tool-files.js';
5
5
  import { historyToolIdentity } from '../../shared/tool-args.js';
6
- /** The detail is the body's `error.message` (or raw text), so the upstream reason reaches traces. */
6
+ /** The fields Chat Completions gives every error; any other field is the provider's own detail. */
7
+ const STANDARD_ERROR_FIELDS = new Set(['message', 'type', 'param', 'code']);
8
+ /**
9
+ * Why a Chat Completions body says the call failed: its `error.message`, then the provider's own
10
+ * fields (OpenRouter's `metadata.raw` names the upstream reason), else the raw body.
11
+ */
12
+ function statedError(body) {
13
+ if (typeof body === 'string')
14
+ return body.trim() || undefined;
15
+ const error = asRecord(asRecord(body)?.error);
16
+ if (!error)
17
+ return body === undefined || body === null ? undefined : JSON.stringify(body);
18
+ const own = Object.fromEntries(Object.entries(error).filter(([key]) => !STANDARD_ERROR_FIELDS.has(key)));
19
+ const said = typeof error.message === 'string' && error.message ? [error.message] : [];
20
+ const more = Object.keys(own).length > 0 ? [JSON.stringify(own)] : [];
21
+ return [...said, ...more].join(' ') || JSON.stringify(error);
22
+ }
23
+ /** A refused Chat Completions call, its kind from the status and its stated reason in the message. */
24
+ function httpError(failure, label) {
25
+ const detail = statedError(failure.body);
26
+ const head = `${label} HTTP ${String(failure.status)}`;
27
+ return new TheoremError(kindOfHttpStatus(failure.status), detail ? `${head}: ${detail}` : head);
28
+ }
7
29
  async function httpErrorEvent(res, label) {
8
30
  const text = (await res.text()).trim();
9
- let detail = text;
31
+ let body = text;
10
32
  try {
11
- const message = asRecord(asRecord(JSON.parse(text))?.error)?.message;
12
- if (typeof message === 'string' && message)
13
- detail = message;
33
+ body = JSON.parse(text);
14
34
  }
15
35
  catch {
16
36
  // why: Not JSON: the raw body is the detail.
17
37
  }
18
- const head = `${label} HTTP ${String(res.status)}`;
19
- return toErrorEvent(new TheoremError(kindOfHttpStatus(res.status), detail ? `${head}: ${detail}` : head));
38
+ return toErrorEvent(httpError({ status: res.status, body }, label));
20
39
  }
21
40
  function rejectMediaRef(part) {
22
41
  if (isMediaRefPart(part)) {
@@ -159,4 +178,4 @@ function openAiGatewayHeaders(config) {
159
178
  }
160
179
  return Object.keys(headers).length > 0 ? headers : undefined;
161
180
  }
162
- export { buildChatMessages, httpErrorEvent, openAiGatewayHeaders, resolveResponseFormat, wireTools, };
181
+ export { buildChatMessages, httpError, httpErrorEvent, openAiGatewayHeaders, resolveResponseFormat, statedError, wireTools, };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@theoremjs/agents",
3
- "version": "0.3.4-next.570.gfda95a3",
3
+ "version": "0.3.4-next.586.ga59d695",
4
4
  "description": "A flat TypeScript agent kernel for typed profiles, deterministic turn execution, registered tools, provider adapters, guardrails, and host-injected traces.",
5
5
  "keywords": [
6
6
  "agent",