@arcships/aimux 0.3.0 → 0.5.0

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.
Files changed (39) hide show
  1. package/dist/error.d.ts +93 -25
  2. package/dist/error.js +51 -110
  3. package/dist/index.d.ts +55 -28
  4. package/dist/index.js +152 -103
  5. package/dist/native.d.ts +2 -0
  6. package/dist/native.js +46 -0
  7. package/dist/types/AiMuxError.d.ts +28 -10
  8. package/dist/types/ApiCallError.d.ts +26 -16
  9. package/dist/types/ApiCallError.js +0 -1
  10. package/dist/types/CallOptions.d.ts +1 -1
  11. package/dist/types/ContentPart.d.ts +6 -0
  12. package/dist/types/EmbeddingCallOptions.d.ts +9 -0
  13. package/dist/types/GenerateContent.d.ts +12 -1
  14. package/dist/types/HttpExchange.d.ts +12 -1
  15. package/dist/types/ImageCallOptions.d.ts +9 -0
  16. package/dist/types/OutcomeRecord.d.ts +5 -0
  17. package/dist/types/RawToolCall.d.ts +16 -0
  18. package/dist/types/RawToolCall.js +2 -0
  19. package/dist/types/RerankingCallOptions.d.ts +9 -0
  20. package/dist/types/RetryError.d.ts +9 -0
  21. package/dist/types/RetryError.js +2 -0
  22. package/dist/types/RetryErrorReason.d.ts +4 -0
  23. package/dist/types/RetryErrorReason.js +3 -0
  24. package/dist/types/SearchCallOptions.d.ts +9 -0
  25. package/dist/types/SpeechCallOptions.d.ts +9 -0
  26. package/dist/types/StreamPart.d.ts +12 -0
  27. package/dist/types/TimeoutConfiguration.d.ts +9 -0
  28. package/dist/types/ToolCall.d.ts +16 -1
  29. package/dist/types/ToolCallRepairReply.d.ts +19 -0
  30. package/dist/types/ToolCallRepairReply.js +2 -0
  31. package/dist/types/TranscriptionCallOptions.d.ts +9 -0
  32. package/dist/types/VideoCallOptions.d.ts +16 -1
  33. package/dist/types/VideoPollOptions.d.ts +13 -0
  34. package/dist/types/VideoPollOptions.js +3 -0
  35. package/dist/types/VideoResult.d.ts +1 -1
  36. package/dist/types.d.ts +5 -0
  37. package/index.d.ts +83 -7
  38. package/index.js +59 -54
  39. package/package.json +12 -12
package/dist/index.js CHANGED
@@ -10,8 +10,8 @@
10
10
  // `./types.ts` (ts-rs exports directly into `./types/` — single source of
11
11
  // truth in the Rust core, packaged with the npm tarball).
12
12
  //
13
- // The raw napi API (`index.js` / `index.d.ts`, auto-generated) is untouched.
14
- // This is purely an extra TypeScript layer on top.
13
+ // The generated napi loader stays untouched. `native.ts` registers the canonical
14
+ // JS Error constructors; this file adds the typed JSON layer on top.
15
15
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
16
16
  if (k2 === undefined) k2 = k;
17
17
  var desc = Object.getOwnPropertyDescriptor(m, k);
@@ -46,7 +46,7 @@ var __importStar = (this && this.__importStar) || (function () {
46
46
  };
47
47
  })();
48
48
  Object.defineProperty(exports, "__esModule", { value: true });
49
- exports.ProviderHandleTyped = exports.ProviderName = exports.provider = exports.azure = exports.anthropicAws = exports.vertex = exports.bedrock = exports.xai = exports.mistral = exports.cohere = exports.google = exports.deepseek = exports.anthropic = exports.openai = exports.moa = exports.router = exports.mockReplay = exports.listSessions = exports.sessionCalls = exports.initSessionInfer = exports.initSessionStore = exports.initLogging = exports.AbortBridge = exports.StreamTextGenerator = exports.Model = exports.withAimuxError = exports.OtherError = exports.RequestAbortedError = exports.TimeoutError = exports.NoSuchProviderError = exports.NoSuchModelError = exports.UnsupportedFunctionalityError = exports.TokenExpiredError = exports.InvalidPromptError = exports.InvalidArgumentError = exports.ToolError = exports.InvalidResponseDataError = exports.JSONParseError = exports.APICallError = exports.AimuxError = void 0;
49
+ exports.ProviderHandleTyped = exports.ProviderName = exports.initRecording = exports.recordingTryFlush = exports.provider = exports.azure = exports.anthropicAws = exports.vertex = exports.bedrock = exports.xai = exports.mistral = exports.cohere = exports.google = exports.deepseek = exports.anthropic = exports.openai = exports.moa = exports.router = exports.initRecordingRing = exports.mockReplay = exports.listSessions = exports.sessionCalls = exports.initSessionInfer = exports.initSessionStore = exports.recordingStop = exports.recordingFlush = exports.initLogging = exports.AbortBridge = exports.StreamTextGenerator = exports.Model = exports.RecordingError = exports.OtherError = exports.RequestAbortedError = exports.TimeoutError = exports.NoSuchProviderError = exports.NoSuchModelError = exports.UnsupportedFunctionalityError = exports.TokenExpiredError = exports.InvalidPromptError = exports.InvalidArgumentError = exports.ToolCallRepairError = exports.InvalidToolInputError = exports.NoSuchToolError = exports.InvalidResponseDataError = exports.JSONParseError = exports.RetryError = exports.APICallError = exports.AimuxError = void 0;
50
50
  exports.generateText = generateText;
51
51
  exports.streamText = streamText;
52
52
  exports.getSessionCalls = getSessionCalls;
@@ -55,15 +55,18 @@ exports.generateTextAsOpenai = generateTextAsOpenai;
55
55
  exports.streamTextAsOpenai = streamTextAsOpenai;
56
56
  exports.createProvider = createProvider;
57
57
  exports.getModelSpecs = getModelSpecs;
58
- const native = __importStar(require("../index.js"));
59
- const index_js_1 = require("../index.js");
58
+ const native = __importStar(require("./native.js"));
59
+ const native_ts_1 = require("./native.js");
60
60
  // Error hierarchy (throw/catch). Wire payload type `AiMuxError` lives under StreamPart only.
61
61
  var error_ts_1 = require("./error.js");
62
62
  Object.defineProperty(exports, "AimuxError", { enumerable: true, get: function () { return error_ts_1.AimuxError; } });
63
63
  Object.defineProperty(exports, "APICallError", { enumerable: true, get: function () { return error_ts_1.APICallError; } });
64
+ Object.defineProperty(exports, "RetryError", { enumerable: true, get: function () { return error_ts_1.RetryError; } });
64
65
  Object.defineProperty(exports, "JSONParseError", { enumerable: true, get: function () { return error_ts_1.JSONParseError; } });
65
66
  Object.defineProperty(exports, "InvalidResponseDataError", { enumerable: true, get: function () { return error_ts_1.InvalidResponseDataError; } });
66
- Object.defineProperty(exports, "ToolError", { enumerable: true, get: function () { return error_ts_1.ToolError; } });
67
+ Object.defineProperty(exports, "NoSuchToolError", { enumerable: true, get: function () { return error_ts_1.NoSuchToolError; } });
68
+ Object.defineProperty(exports, "InvalidToolInputError", { enumerable: true, get: function () { return error_ts_1.InvalidToolInputError; } });
69
+ Object.defineProperty(exports, "ToolCallRepairError", { enumerable: true, get: function () { return error_ts_1.ToolCallRepairError; } });
67
70
  Object.defineProperty(exports, "InvalidArgumentError", { enumerable: true, get: function () { return error_ts_1.InvalidArgumentError; } });
68
71
  Object.defineProperty(exports, "InvalidPromptError", { enumerable: true, get: function () { return error_ts_1.InvalidPromptError; } });
69
72
  Object.defineProperty(exports, "TokenExpiredError", { enumerable: true, get: function () { return error_ts_1.TokenExpiredError; } });
@@ -73,66 +76,113 @@ Object.defineProperty(exports, "NoSuchProviderError", { enumerable: true, get: f
73
76
  Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function () { return error_ts_1.TimeoutError; } });
74
77
  Object.defineProperty(exports, "RequestAbortedError", { enumerable: true, get: function () { return error_ts_1.RequestAbortedError; } });
75
78
  Object.defineProperty(exports, "OtherError", { enumerable: true, get: function () { return error_ts_1.OtherError; } });
76
- Object.defineProperty(exports, "withAimuxError", { enumerable: true, get: function () { return error_ts_1.withAimuxError; } });
77
- const error_ts_2 = require("./error.js");
79
+ Object.defineProperty(exports, "RecordingError", { enumerable: true, get: function () { return error_ts_1.RecordingError; } });
78
80
  // Re-export the raw napi constructors/factories so consumers can do everything
79
81
  // from a single import: `import { openai, generateText } from 'aimux'`.
80
82
  // Rust fn names are snake_case; napi-rs exposes them camelCased (like
81
83
  // `init_logging` → `initLogging`).
82
84
  //
83
- // Infallible items (classes + void initializers) pass through untouched.
84
- var index_js_2 = require("../index.js");
85
- Object.defineProperty(exports, "Model", { enumerable: true, get: function () { return index_js_2.Model; } });
86
- Object.defineProperty(exports, "StreamTextGenerator", { enumerable: true, get: function () { return index_js_2.StreamTextGenerator; } });
87
- Object.defineProperty(exports, "AbortBridge", { enumerable: true, get: function () { return index_js_2.AbortBridge; } });
88
- Object.defineProperty(exports, "initLogging", { enumerable: true, get: function () { return index_js_2.initLogging; } });
89
- Object.defineProperty(exports, "initSessionStore", { enumerable: true, get: function () { return index_js_2.initSessionStore; } });
90
- Object.defineProperty(exports, "initSessionInfer", { enumerable: true, get: function () { return index_js_2.initSessionInfer; } });
91
- // Fallible raw functions are wrapped so their throws are typed `AimuxError`
92
- // subclasses (`instanceof` works); generic wrappers preserve the signatures.
93
- function wrapSync(fn) {
94
- return (...args) => {
95
- try {
96
- return fn(...args);
97
- }
98
- catch (e) {
99
- throw error_ts_2.AimuxError.fromNative(e);
100
- }
101
- };
102
- }
103
- function wrapAsync(fn) {
104
- return (...args) => (0, error_ts_2.withAimuxError)(() => fn(...args));
105
- }
106
- exports.sessionCalls = wrapSync(native.sessionCalls);
107
- exports.listSessions = wrapSync(native.listSessions);
108
- exports.mockReplay = wrapSync(native.mockReplay);
109
- exports.router = wrapSync(native.router);
110
- exports.moa = wrapSync(native.moa);
111
- exports.openai = wrapAsync(native.openai);
112
- exports.anthropic = wrapAsync(native.anthropic);
113
- exports.deepseek = wrapAsync(native.deepseek);
114
- exports.google = wrapAsync(native.google);
115
- exports.cohere = wrapAsync(native.cohere);
116
- exports.mistral = wrapAsync(native.mistral);
117
- exports.xai = wrapAsync(native.xai);
118
- exports.bedrock = wrapAsync(native.bedrock);
119
- exports.vertex = wrapAsync(native.vertex);
120
- exports.anthropicAws = wrapAsync(native.anthropicAws);
121
- exports.azure = wrapAsync(native.azure);
122
- exports.provider = wrapAsync(native.provider);
85
+ // Native functions pass through unchanged: Rust already constructs the
86
+ // registered JavaScript error subclasses before throwing.
87
+ var native_ts_2 = require("./native.js");
88
+ Object.defineProperty(exports, "Model", { enumerable: true, get: function () { return native_ts_2.Model; } });
89
+ Object.defineProperty(exports, "StreamTextGenerator", { enumerable: true, get: function () { return native_ts_2.StreamTextGenerator; } });
90
+ Object.defineProperty(exports, "AbortBridge", { enumerable: true, get: function () { return native_ts_2.AbortBridge; } });
91
+ Object.defineProperty(exports, "initLogging", { enumerable: true, get: function () { return native_ts_2.initLogging; } });
92
+ Object.defineProperty(exports, "recordingFlush", { enumerable: true, get: function () { return native_ts_2.recordingFlush; } });
93
+ Object.defineProperty(exports, "recordingStop", { enumerable: true, get: function () { return native_ts_2.recordingStop; } });
94
+ Object.defineProperty(exports, "initSessionStore", { enumerable: true, get: function () { return native_ts_2.initSessionStore; } });
95
+ Object.defineProperty(exports, "initSessionInfer", { enumerable: true, get: function () { return native_ts_2.initSessionInfer; } });
96
+ Object.defineProperty(exports, "sessionCalls", { enumerable: true, get: function () { return native_ts_2.sessionCalls; } });
97
+ Object.defineProperty(exports, "listSessions", { enumerable: true, get: function () { return native_ts_2.listSessions; } });
98
+ Object.defineProperty(exports, "mockReplay", { enumerable: true, get: function () { return native_ts_2.mockReplay; } });
99
+ Object.defineProperty(exports, "initRecordingRing", { enumerable: true, get: function () { return native_ts_2.initRecordingRing; } });
100
+ Object.defineProperty(exports, "router", { enumerable: true, get: function () { return native_ts_2.router; } });
101
+ Object.defineProperty(exports, "moa", { enumerable: true, get: function () { return native_ts_2.moa; } });
102
+ Object.defineProperty(exports, "openai", { enumerable: true, get: function () { return native_ts_2.openai; } });
103
+ Object.defineProperty(exports, "anthropic", { enumerable: true, get: function () { return native_ts_2.anthropic; } });
104
+ Object.defineProperty(exports, "deepseek", { enumerable: true, get: function () { return native_ts_2.deepseek; } });
105
+ Object.defineProperty(exports, "google", { enumerable: true, get: function () { return native_ts_2.google; } });
106
+ Object.defineProperty(exports, "cohere", { enumerable: true, get: function () { return native_ts_2.cohere; } });
107
+ Object.defineProperty(exports, "mistral", { enumerable: true, get: function () { return native_ts_2.mistral; } });
108
+ Object.defineProperty(exports, "xai", { enumerable: true, get: function () { return native_ts_2.xai; } });
109
+ Object.defineProperty(exports, "bedrock", { enumerable: true, get: function () { return native_ts_2.bedrock; } });
110
+ Object.defineProperty(exports, "vertex", { enumerable: true, get: function () { return native_ts_2.vertex; } });
111
+ Object.defineProperty(exports, "anthropicAws", { enumerable: true, get: function () { return native_ts_2.anthropicAws; } });
112
+ Object.defineProperty(exports, "azure", { enumerable: true, get: function () { return native_ts_2.azure; } });
113
+ Object.defineProperty(exports, "provider", { enumerable: true, get: function () { return native_ts_2.provider; } });
114
+ // Spell these as `void` in the public wrapper instead of leaking the generated
115
+ // `AimuxResult<undefined>` implementation type.
116
+ exports.recordingTryFlush = native.recordingTryFlush;
117
+ exports.initRecording = native.initRecording;
123
118
  // Both meanings: the `ProviderName` const object (runtime, for `ProviderName.groq`)
124
119
  // and the derived string-union type. A value export resolves at runtime, so the
125
120
  // specifier needs the real `.ts` extension for Node's type-stripping test runs;
126
121
  // tsc rewrites it to `.js` on emit (rewriteRelativeImportExtensions).
127
122
  var ProviderName_ts_1 = require("./types/ProviderName.js");
128
123
  Object.defineProperty(exports, "ProviderName", { enumerable: true, get: function () { return ProviderName_ts_1.ProviderName; } });
124
+ /**
125
+ * The AI SDK's `getErrorMessage`, so a thrown value renders exactly as it
126
+ * would in the SDK's own `ToolCallRepairError` message: strings verbatim,
127
+ * `Error` instances via `toString()` (name included), anything else as JSON.
128
+ */
129
+ function errorMessage(e) {
130
+ if (e == null)
131
+ return 'unknown error';
132
+ if (typeof e === 'string')
133
+ return e;
134
+ if (e instanceof Error)
135
+ return e.toString();
136
+ return JSON.stringify(e);
137
+ }
138
+ /**
139
+ * Run the user's repair function for one invalid call and turn its outcome
140
+ * into the wire reply. Returns `null` when the call is not repairable at all
141
+ * (no tool set — the AI SDK rule, decided in core).
142
+ */
143
+ async function repairReplyFor(call, promptJson, optsJson, repair) {
144
+ const context = JSON.parse((0, native_ts_1.toolCallRepairContext)(JSON.stringify(call), promptJson, optsJson));
145
+ if (context === null)
146
+ return null;
147
+ let reply;
148
+ try {
149
+ const replacement = await repair(context);
150
+ reply = replacement ? { type: 'repaired', tool_call: replacement } : { type: 'unchanged' };
151
+ }
152
+ catch (e) {
153
+ reply = { type: 'failed', message: errorMessage(e) };
154
+ }
155
+ return JSON.stringify(reply);
156
+ }
157
+ /**
158
+ * Repair every invalid call in a serialized result, before it is decoded.
159
+ * `tool_calls` sits at the top level of a generate-text result and under `raw`
160
+ * in a generate-object one.
161
+ */
162
+ async function repairResultJson(resultJson, promptJson, optsJson, repair) {
163
+ const result = JSON.parse(resultJson);
164
+ const calls = result.tool_calls ?? result.raw?.tool_calls ?? [];
165
+ let patched = resultJson;
166
+ for (const call of calls) {
167
+ if (call.invalid !== true)
168
+ continue;
169
+ const reply = await repairReplyFor(call, promptJson, optsJson, repair);
170
+ if (reply === null)
171
+ continue;
172
+ patched = (0, native_ts_1.applyToolCallRepairToResult)(patched, optsJson, call.tool_call_id, reply);
173
+ }
174
+ return patched;
175
+ }
129
176
  /**
130
177
  * Generate text (non-streaming). Returns a typed {@link GenerateTextResult}.
131
178
  *
132
179
  * @param model - A raw model instance from `openai()`, `anthropic()`, etc.
133
180
  * @param prompt - A plain string or an array of typed chat messages.
134
181
  * @param options - Optional typed generation options (tools, tool_choice,
135
- * temperature, response_format, …).
182
+ * temperature, response_format, …). Invalid tool calls arrive
183
+ * with `invalid`/`error` set on the tool call; pass
184
+ * {@link RepairToolCall | `repairToolCall`} to fix them up
185
+ * before the result is decoded.
136
186
  * @param signal - Optional `AbortSignal`; aborting it cancels the call.
137
187
  *
138
188
  * Internally calls the raw
@@ -148,12 +198,14 @@ Object.defineProperty(exports, "ProviderName", { enumerable: true, get: function
148
198
  * ```
149
199
  */
150
200
  async function generateText(model, prompt, options, signal) {
151
- return (0, error_ts_2.withAimuxError)(async () => {
152
- const optsJson = options ? JSON.stringify(options) : undefined;
153
- const bridge = signal ? new index_js_1.AbortBridge(signal) : undefined;
154
- const resultJson = await model.generateText(JSON.stringify(prompt), optsJson, bridge);
155
- return JSON.parse(resultJson);
156
- });
201
+ const promptJson = JSON.stringify(prompt);
202
+ const optsJson = options ? JSON.stringify(options) : undefined;
203
+ const bridge = signal ? new native_ts_1.AbortBridge(signal) : undefined;
204
+ let resultJson = await model.generateText(promptJson, optsJson, bridge);
205
+ if (options?.repairToolCall) {
206
+ resultJson = await repairResultJson(resultJson, promptJson, optsJson, options.repairToolCall);
207
+ }
208
+ return JSON.parse(resultJson);
157
209
  }
158
210
  /**
159
211
  * Stream text from a model. Yields typed {@link StreamPart}s.
@@ -177,16 +229,25 @@ async function generateText(model, prompt, options, signal) {
177
229
  * ```
178
230
  */
179
231
  async function* streamText(model, prompt, options, signal) {
180
- try {
181
- const optsJson = options ? JSON.stringify(options) : undefined;
182
- const bridge = signal ? new index_js_1.AbortBridge(signal) : undefined;
183
- const gen = await model.streamText(JSON.stringify(prompt), optsJson, bridge);
184
- for await (const json of gen) {
185
- yield JSON.parse(json);
232
+ const promptJson = JSON.stringify(prompt);
233
+ const optsJson = options ? JSON.stringify(options) : undefined;
234
+ const bridge = signal ? new native_ts_1.AbortBridge(signal) : undefined;
235
+ const repair = options?.repairToolCall;
236
+ const gen = await model.streamText(promptJson, optsJson, bridge);
237
+ for await (const json of gen) {
238
+ const part = JSON.parse(json);
239
+ // Only the settled ToolCall part is repairable; ToolInputDelta parts are
240
+ // the provider's raw text and pass through immediately (AI SDK behaviour).
241
+ if (repair && 'ToolCall' in part && part.ToolCall.invalid === true) {
242
+ const reply = await repairReplyFor(part.ToolCall, promptJson, optsJson, repair);
243
+ if (reply !== null) {
244
+ yield {
245
+ ToolCall: JSON.parse((0, native_ts_1.applyToolCallRepair)(JSON.stringify(part.ToolCall), optsJson, reply)),
246
+ };
247
+ continue;
248
+ }
186
249
  }
187
- }
188
- catch (e) {
189
- throw error_ts_2.AimuxError.fromNative(e);
250
+ yield part;
190
251
  }
191
252
  }
192
253
  /**
@@ -197,23 +258,13 @@ async function* streamText(model, prompt, options, signal) {
197
258
  * above) must be called first to register the store / opt-in inferer.
198
259
  */
199
260
  function getSessionCalls(sessionId) {
200
- try {
201
- return JSON.parse(native.sessionCalls(sessionId));
202
- }
203
- catch (e) {
204
- throw error_ts_2.AimuxError.fromNative(e);
205
- }
261
+ return JSON.parse(native.sessionCalls(sessionId));
206
262
  }
207
263
  /**
208
264
  * All known sessions (RFC-0024).
209
265
  */
210
266
  function getSessions() {
211
- try {
212
- return JSON.parse(native.listSessions());
213
- }
214
- catch (e) {
215
- throw error_ts_2.AimuxError.fromNative(e);
216
- }
267
+ return JSON.parse(native.listSessions());
217
268
  }
218
269
  /**
219
270
  * Generate text and return an OpenAI Chat Completion (non-streaming).
@@ -221,6 +272,11 @@ function getSessions() {
221
272
  * Works with **any** provider — the result is always a standard OpenAI
222
273
  * `ChatCompletion` object.
223
274
  *
275
+ * With {@link RepairToolCall | `repairToolCall`}, invalid calls are repaired
276
+ * on the native result first and the completion is converted from it, so its
277
+ * `tool_calls` carry the repaired arguments (a `ChatCompletion` has no
278
+ * `invalid` marker to repair from).
279
+ *
224
280
  * @example
225
281
  * ```ts
226
282
  * import { openai, generateTextAsOpenai } from 'aimux'
@@ -230,12 +286,16 @@ function getSessions() {
230
286
  * ```
231
287
  */
232
288
  async function generateTextAsOpenai(model, prompt, options, signal) {
233
- return (0, error_ts_2.withAimuxError)(async () => {
234
- const optsJson = options ? JSON.stringify(options) : undefined;
235
- const bridge = signal ? new index_js_1.AbortBridge(signal) : undefined;
236
- const resultJson = await model.generateTextAsOpenai(JSON.stringify(prompt), optsJson, bridge);
237
- return JSON.parse(resultJson);
238
- });
289
+ const promptJson = JSON.stringify(prompt);
290
+ const optsJson = options ? JSON.stringify(options) : undefined;
291
+ const bridge = signal ? new native_ts_1.AbortBridge(signal) : undefined;
292
+ if (options?.repairToolCall) {
293
+ let resultJson = await model.generateText(promptJson, optsJson, bridge);
294
+ resultJson = await repairResultJson(resultJson, promptJson, optsJson, options.repairToolCall);
295
+ return JSON.parse(model.generateTextResultAsOpenai(resultJson));
296
+ }
297
+ const resultJson = await model.generateTextAsOpenai(promptJson, optsJson, bridge);
298
+ return JSON.parse(resultJson);
239
299
  }
240
300
  /**
241
301
  * Stream text as OpenAI Chat Completion chunks.
@@ -255,16 +315,11 @@ async function generateTextAsOpenai(model, prompt, options, signal) {
255
315
  * ```
256
316
  */
257
317
  async function* streamTextAsOpenai(model, prompt, options, signal) {
258
- try {
259
- const optsJson = options ? JSON.stringify(options) : undefined;
260
- const bridge = signal ? new index_js_1.AbortBridge(signal) : undefined;
261
- const gen = await model.streamTextAsOpenai(JSON.stringify(prompt), optsJson, bridge);
262
- for await (const json of gen) {
263
- yield JSON.parse(json);
264
- }
265
- }
266
- catch (e) {
267
- throw error_ts_2.AimuxError.fromNative(e);
318
+ const optsJson = options ? JSON.stringify(options) : undefined;
319
+ const bridge = signal ? new native_ts_1.AbortBridge(signal) : undefined;
320
+ const gen = await model.streamTextAsOpenai(JSON.stringify(prompt), optsJson, bridge);
321
+ for await (const json of gen) {
322
+ yield JSON.parse(json);
268
323
  }
269
324
  }
270
325
  // ─────────────────────────────────────────────────────────────────────────────
@@ -290,13 +345,11 @@ class ProviderHandleTyped {
290
345
  }
291
346
  /** List models available on this provider (runtime discovery + anya2a spec). */
292
347
  async listModels() {
293
- return (0, error_ts_2.withAimuxError)(async () => {
294
- return JSON.parse(await this.raw.listModels());
295
- });
348
+ return JSON.parse(await this.raw.listModels());
296
349
  }
297
350
  /** Build a language model from a discovered model id. */
298
351
  async model(modelId) {
299
- return (0, error_ts_2.withAimuxError)(() => this.raw.model(modelId));
352
+ return this.raw.model(modelId);
300
353
  }
301
354
  }
302
355
  exports.ProviderHandleTyped = ProviderHandleTyped;
@@ -320,10 +373,8 @@ exports.ProviderHandleTyped = ProviderHandleTyped;
320
373
  * ```
321
374
  */
322
375
  async function createProvider(name, apiKey, config) {
323
- return (0, error_ts_2.withAimuxError)(async () => {
324
- const raw = await (0, index_js_1.createProvider)(name, apiKey ?? null, config ?? null);
325
- return new ProviderHandleTyped(raw);
326
- });
376
+ const raw = await (0, native_ts_1.createProvider)(name, apiKey ?? null, config ?? null);
377
+ return new ProviderHandleTyped(raw);
327
378
  }
328
379
  /**
329
380
  * Fetch the community model catalogue (anya2a). Returns a `Catalogue` object
@@ -345,7 +396,5 @@ async function createProvider(name, apiKey, config) {
345
396
  * ```
346
397
  */
347
398
  async function getModelSpecs(sourceUrl) {
348
- return (0, error_ts_2.withAimuxError)(async () => {
349
- return JSON.parse(await (0, index_js_1.getModelSpecs)(sourceUrl ?? null));
350
- });
399
+ return JSON.parse(await (0, native_ts_1.getModelSpecs)(sourceUrl ?? null));
351
400
  }
@@ -0,0 +1,2 @@
1
+ export * from '../index.js';
2
+ export * from './error.ts';
package/dist/native.js ADDED
@@ -0,0 +1,46 @@
1
+ "use strict";
2
+ // Native napi surface with the package's canonical JavaScript Error classes.
3
+ // Rust constructs these classes directly, so native throws and promise
4
+ // rejections preserve their prototype chain.
5
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = { enumerable: true, get: function() { return m[k]; } };
10
+ }
11
+ Object.defineProperty(o, k2, desc);
12
+ }) : (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ o[k2] = m[k];
15
+ }));
16
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
18
+ }) : function(o, v) {
19
+ o["default"] = v;
20
+ });
21
+ var __importStar = (this && this.__importStar) || (function () {
22
+ var ownKeys = function(o) {
23
+ ownKeys = Object.getOwnPropertyNames || function (o) {
24
+ var ar = [];
25
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
26
+ return ar;
27
+ };
28
+ return ownKeys(o);
29
+ };
30
+ return function (mod) {
31
+ if (mod && mod.__esModule) return mod;
32
+ var result = {};
33
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
34
+ __setModuleDefault(result, mod);
35
+ return result;
36
+ };
37
+ })();
38
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
39
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
40
+ };
41
+ Object.defineProperty(exports, "__esModule", { value: true });
42
+ const native = __importStar(require("../index.js"));
43
+ const errors = __importStar(require("./error.js"));
44
+ native.__registerErrorClasses(errors);
45
+ __exportStar(require("../index.js"), exports);
46
+ __exportStar(require("./error.js"), exports);
@@ -1,25 +1,41 @@
1
1
  import type { ApiCallError } from "./ApiCallError";
2
+ import type { RetryError } from "./RetryError";
2
3
  /**
3
4
  * Unified error type for all aimux operations.
4
5
  *
5
6
  * Variants are cut by *what the caller does about it*, not by where the
6
- * failure came from. `ApiCall` carries the [`ApiCallError`] detail inline
7
- * (unboxed, like async-openai's `ApiError(ApiError)`); the size guard in
8
- * `error_value_golden_test` keeps the enum under clippy's
9
- * `result_large_err` threshold.
10
- *
11
- * Constructed as a named struct literal everywhere
12
- * (`ApiCallError { status_code: .., ..Default::default() }`), the same
13
- * shape as the AI SDK's named-options constructor.
7
+ * failure came from. `ApiCallError` is boxed only to keep the Rust enum
8
+ * compact; serde and every binding still observe the same object shape.
14
9
  */
15
10
  export type AiMuxError = {
16
11
  "ApiCall": ApiCallError;
12
+ } | {
13
+ "Retry": RetryError;
17
14
  } | {
18
15
  "JsonParse": string;
19
16
  } | {
20
17
  "InvalidResponseData": string;
21
18
  } | {
22
- "Tool": string;
19
+ "NoSuchTool": {
20
+ tool_name: string;
21
+ available_tools?: Array<string> | null;
22
+ /**
23
+ * Original argument text, when supplied by the provider. Absent in
24
+ * older serialized errors and errors constructed without a call.
25
+ */
26
+ tool_input?: string | null;
27
+ };
28
+ } | {
29
+ "InvalidToolInput": {
30
+ tool_name: string;
31
+ tool_input: string;
32
+ cause: string;
33
+ };
34
+ } | {
35
+ "ToolCallRepair": {
36
+ original_error: AiMuxError;
37
+ cause: AiMuxError;
38
+ };
23
39
  } | {
24
40
  "InvalidArgument": string;
25
41
  } | {
@@ -43,6 +59,8 @@ export type AiMuxError = {
43
59
  };
44
60
  } | {
45
61
  "Timeout": string;
46
- } | "Aborted" | {
62
+ } | {
63
+ "Aborted": string;
64
+ } | {
47
65
  "Other": string;
48
66
  };
@@ -1,3 +1,4 @@
1
+ import type { JsonValue } from "./serde_json/JsonValue";
1
2
  /**
2
3
  * What a failed API call observed — the field set of the AI SDK's
3
4
  * `APICallError` (`statusCode` / `responseBody`), which this project's error
@@ -10,17 +11,25 @@
10
11
  * body read) are `ApiCall` errors too — no response arrived, so
11
12
  * `status_code` is `None` and `is_retryable` is `true`, exactly as the AI
12
13
  * SDK's `handleFetchError` builds an `APICallError` with no `statusCode`
13
- * and `isRetryable: true`. `message` holds the provider's text **only** —
14
- * the status is a field, never baked into the string; `Display` composes
15
- * the human-readable form from the fields at print time, so nothing
16
- * downstream has to parse it back out.
14
+ * and `isRetryable: true`. `message` holds the provider's text verbatim when
15
+ * one is available; transport and parsing failures use a library message
16
+ * with the source detail appended. The HTTP status is always a field, never
17
+ * baked into the string; `Display` composes the human-readable form from the
18
+ * fields at print time, so nothing downstream has to parse it back out.
17
19
  *
18
- * `APICallError` fields not carried in this round: `url` /
19
- * `requestBodyValues` / `responseHeaders` (the request context is not
20
- * available at the error-construction sites today; all fields are
21
- * `#[serde(default)]`, so adding them later is not a breaking change).
20
+ * Every producer must provide the sanitized request URL and request values.
21
+ * This keeps transport and response failures self-contained and matches the
22
+ * AI SDK's `APICallError` contract.
22
23
  */
23
24
  export type ApiCallError = {
25
+ /**
26
+ * Sanitized request URL. Required for every API-derived failure.
27
+ */
28
+ url: string;
29
+ /**
30
+ * Sanitized request values used to create the API request.
31
+ */
32
+ request_body_values: JsonValue;
24
33
  /**
25
34
  * HTTP status of the response, when it came from one
26
35
  * (`APICallError.statusCode`). Always the *observed* status: the HTTP
@@ -35,7 +44,9 @@ export type ApiCallError = {
35
44
  */
36
45
  provider_code: string | null;
37
46
  /**
38
- * The provider's message, verbatim. No status prefix.
47
+ * Human-readable failure text. Provider text is verbatim when available;
48
+ * locally detected transport/parse failures include their source detail.
49
+ * Never includes an HTTP status prefix.
39
50
  */
40
51
  message: string;
41
52
  /**
@@ -45,16 +56,15 @@ export type ApiCallError = {
45
56
  */
46
57
  response_body: string | null;
47
58
  /**
48
- * Provider-assigned request id, from the `x-request-id` / `request-id`
49
- * response header when one was sent. Filled by the shared HTTP layer.
59
+ * Sanitized response headers.
50
60
  */
51
- request_id: string | null;
61
+ response_headers: {
62
+ [key in string]: string;
63
+ } | null;
52
64
  /**
53
- * Retry hint in milliseconds, distilled from the `retry-after-ms` /
54
- * `retry-after` response headers on a 429. The classification lives in
55
- * `status_code`; this is the matching action input.
65
+ * Parsed provider error data.
56
66
  */
57
- retry_after_ms: number | null;
67
+ data: JsonValue | null;
58
68
  /**
59
69
  * Whether retrying can help (`APICallError.isRetryable`) — stored at
60
70
  * construction, exactly like the AI SDK: the response path computes it
@@ -1,3 +1,2 @@
1
1
  "use strict";
2
- // This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
3
2
  Object.defineProperty(exports, "__esModule", { value: true });
@@ -86,7 +86,7 @@ export type CallOptions = {
86
86
  body_overrides: JsonValue | null;
87
87
  /**
88
88
  * Per-call retry count override. `None` uses the provider's configured
89
- * `RetryConfig.max_retries`. `Some(0)` disables retries.
89
+ * Core operation retry. `Some(0)` disables retries.
90
90
  */
91
91
  max_retries: number | null;
92
92
  /**
@@ -57,6 +57,12 @@ export type ContentPart = {
57
57
  * Arguments as a JSON value (usually an object).
58
58
  */
59
59
  input: JsonValue;
60
+ /**
61
+ * Whether the tool call is executed by the provider rather than by
62
+ * the client. This is part of the prompt contract because providers
63
+ * need it to replay server tool calls on a later turn.
64
+ */
65
+ provider_executed?: boolean | null;
60
66
  /**
61
67
  * Provider-assigned thought signature (e.g. Google Gemini
62
68
  * `thoughtSignature`). Must be echoed back verbatim on the follow-up
@@ -1,3 +1,4 @@
1
+ import type { TimeoutConfiguration } from "./TimeoutConfiguration";
1
2
  import type { JsonValue } from "./serde_json/JsonValue";
2
3
  /**
3
4
  * Options passed to [`EmbeddingModel::do_embed`].
@@ -9,6 +10,14 @@ export type EmbeddingCallOptions = {
9
10
  * List of text values to generate embeddings for.
10
11
  */
11
12
  values: Array<string>;
13
+ /**
14
+ * Per-call retry override. `None` uses the model default.
15
+ */
16
+ max_retries: number | null;
17
+ /**
18
+ * Per-call operation timeout.
19
+ */
20
+ timeout: TimeoutConfiguration | null;
12
21
  /**
13
22
  * Additional provider-specific options, keyed by provider name.
14
23
  */
@@ -12,7 +12,18 @@ export type GenerateContent = {
12
12
  "ToolCall": {
13
13
  tool_call_id: string;
14
14
  tool_name: string;
15
- input: JsonValue;
15
+ /**
16
+ * The model's raw argument text, exactly as the provider delivered
17
+ * it (possibly malformed). Providers never parse it — `generate_text`
18
+ * owns parsing, schema validation, and repair.
19
+ *
20
+ * Always serializes as a JSON string. Deserializes a JSON string
21
+ * (the current wire shape) unchanged, and also re-serializes the
22
+ * pre-refactor shape — an already-parsed JSON value — to its compact
23
+ * JSON text, so a `GenerateResult` persisted before this field
24
+ * became a `String` keeps loading. See docs/api/gaps.md §9.
25
+ */
26
+ input: string;
16
27
  /**
17
28
  * Whether the tool call will be executed by the provider.
18
29
  * If false/unset, the tool call is executed by the client.