@arcships/aimux 0.2.1 → 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 (167) hide show
  1. package/dist/error.d.ts +139 -0
  2. package/dist/error.js +114 -0
  3. package/dist/index.d.ts +162 -8
  4. package/dist/index.js +334 -28
  5. package/dist/native.d.ts +2 -0
  6. package/dist/native.js +46 -0
  7. package/dist/types/AiMuxError.d.ts +45 -13
  8. package/dist/types/AiMuxError.js +0 -1
  9. package/dist/types/ApiCallError.d.ts +75 -0
  10. package/dist/types/ApiCallError.js +2 -0
  11. package/dist/types/BreakKind.d.ts +1 -0
  12. package/dist/types/BreakKind.js +3 -0
  13. package/dist/types/CallOptions.d.ts +28 -2
  14. package/dist/types/CatalogueSource.d.ts +4 -0
  15. package/dist/types/CatalogueSource.js +3 -0
  16. package/dist/types/ChatCompletion.d.ts +16 -0
  17. package/dist/types/ChatCompletion.js +2 -0
  18. package/dist/types/ChatCompletionChoice.d.ts +8 -0
  19. package/dist/types/ChatCompletionChoice.js +2 -0
  20. package/dist/types/ChatCompletionChunk.d.ts +15 -0
  21. package/dist/types/ChatCompletionChunk.js +2 -0
  22. package/dist/types/ChatCompletionChunkChoice.d.ts +8 -0
  23. package/dist/types/ChatCompletionChunkChoice.js +2 -0
  24. package/dist/types/ChatCompletionChunkFunction.d.ts +4 -0
  25. package/dist/types/ChatCompletionChunkFunction.js +3 -0
  26. package/dist/types/ChatCompletionChunkToolCall.d.ts +7 -0
  27. package/dist/types/ChatCompletionChunkToolCall.js +2 -0
  28. package/dist/types/ChatCompletionDelta.d.ts +7 -0
  29. package/dist/types/ChatCompletionDelta.js +2 -0
  30. package/dist/types/ChatCompletionFunction.d.ts +4 -0
  31. package/dist/types/ChatCompletionFunction.js +3 -0
  32. package/dist/types/ChatCompletionMessage.d.ts +9 -0
  33. package/dist/types/ChatCompletionMessage.js +2 -0
  34. package/dist/types/ChatCompletionToolCall.d.ts +6 -0
  35. package/dist/types/ChatCompletionToolCall.js +2 -0
  36. package/dist/types/ChatCompletionUsage.d.ts +9 -0
  37. package/dist/types/ChatCompletionUsage.js +2 -0
  38. package/dist/types/CompletionTokensDetails.d.ts +3 -0
  39. package/dist/types/CompletionTokensDetails.js +3 -0
  40. package/dist/types/ContentPart.d.ts +6 -0
  41. package/dist/types/EmbeddingCallOptions.d.ts +9 -0
  42. package/dist/types/FilePart.d.ts +8 -0
  43. package/dist/types/FilePart.js +2 -0
  44. package/dist/types/Fingerprint.d.ts +21 -0
  45. package/dist/types/Fingerprint.js +3 -0
  46. package/dist/types/GenerateContent.d.ts +12 -1
  47. package/dist/types/GenerateObjectResult.d.ts +48 -0
  48. package/dist/types/GenerateObjectResult.js +2 -0
  49. package/dist/types/GenerateTextOptions.d.ts +12 -1
  50. package/dist/types/GenerateTextResult.d.ts +47 -0
  51. package/dist/types/HttpExchange.d.ts +34 -0
  52. package/dist/types/HttpExchange.js +2 -0
  53. package/dist/types/HttpRecord.d.ts +12 -0
  54. package/dist/types/HttpRecord.js +3 -0
  55. package/dist/types/ImageCallOptions.d.ts +10 -1
  56. package/dist/types/InputRecord.d.ts +16 -0
  57. package/dist/types/InputRecord.js +2 -0
  58. package/dist/types/Modality.d.ts +4 -0
  59. package/dist/types/Modality.js +3 -0
  60. package/dist/types/ModelCapabilities.d.ts +21 -0
  61. package/dist/types/ModelCapabilities.js +3 -0
  62. package/dist/types/ModelCost.d.ts +10 -0
  63. package/dist/types/ModelCost.js +3 -0
  64. package/dist/types/ModelLimits.d.ts +17 -0
  65. package/dist/types/ModelLimits.js +3 -0
  66. package/dist/types/ModelModalities.d.ts +8 -0
  67. package/dist/types/ModelModalities.js +2 -0
  68. package/dist/types/ModelSpec.d.ts +33 -0
  69. package/dist/types/ModelSpec.js +2 -0
  70. package/dist/types/ModelType.d.ts +4 -0
  71. package/dist/types/ModelType.js +3 -0
  72. package/dist/types/OutcomeRecord.d.ts +19 -0
  73. package/dist/types/OutcomeRecord.js +2 -0
  74. package/dist/types/OutcomeStatus.d.ts +4 -0
  75. package/dist/types/OutcomeStatus.js +3 -0
  76. package/dist/types/PrefixBreak.d.ts +11 -0
  77. package/dist/types/PrefixBreak.js +2 -0
  78. package/dist/types/PromptTokensDetails.d.ts +4 -0
  79. package/dist/types/PromptTokensDetails.js +3 -0
  80. package/dist/types/ProviderAuditSpec.d.ts +33 -0
  81. package/dist/types/ProviderAuditSpec.js +2 -0
  82. package/dist/types/ProviderFamily.d.ts +5 -0
  83. package/dist/types/ProviderFamily.js +3 -0
  84. package/dist/types/ProviderRecord.d.ts +30 -0
  85. package/dist/types/ProviderRecord.js +2 -0
  86. package/dist/types/RawToolCall.d.ts +16 -0
  87. package/dist/types/RawToolCall.js +2 -0
  88. package/dist/types/ReasoningMode.d.ts +4 -0
  89. package/dist/types/ReasoningMode.js +3 -0
  90. package/dist/types/ReasoningPart.d.ts +9 -0
  91. package/dist/types/ReasoningPart.js +3 -0
  92. package/dist/types/ReasoningSpec.d.ts +39 -0
  93. package/dist/types/ReasoningSpec.js +2 -0
  94. package/dist/types/ReasoningVisibility.d.ts +4 -0
  95. package/dist/types/ReasoningVisibility.js +3 -0
  96. package/dist/types/Recording.d.ts +56 -0
  97. package/dist/types/Recording.js +2 -0
  98. package/dist/types/RequestCacheHints.d.ts +9 -0
  99. package/dist/types/RequestCacheHints.js +3 -0
  100. package/dist/types/RerankingCallOptions.d.ts +9 -0
  101. package/dist/types/ResponseRecord.d.ts +13 -0
  102. package/dist/types/ResponseRecord.js +3 -0
  103. package/dist/types/RetryError.d.ts +9 -0
  104. package/dist/types/RetryError.js +2 -0
  105. package/dist/types/RetryErrorReason.d.ts +4 -0
  106. package/dist/types/RetryErrorReason.js +3 -0
  107. package/dist/types/RuntimeModel.d.ts +22 -0
  108. package/dist/types/RuntimeModel.js +3 -0
  109. package/dist/types/SearchCallOptions.d.ts +9 -0
  110. package/dist/types/SessionCall.d.ts +20 -0
  111. package/dist/types/SessionCall.js +3 -0
  112. package/dist/types/SessionChainView.d.ts +10 -0
  113. package/dist/types/SessionChainView.js +2 -0
  114. package/dist/types/SessionSource.d.ts +4 -0
  115. package/dist/types/SessionSource.js +3 -0
  116. package/dist/types/SessionStepStat.d.ts +27 -0
  117. package/dist/types/SessionStepStat.js +2 -0
  118. package/dist/types/SessionView.d.ts +16 -0
  119. package/dist/types/SessionView.js +2 -0
  120. package/dist/types/SourcePart.d.ts +9 -0
  121. package/dist/types/SourcePart.js +3 -0
  122. package/dist/types/SpeechCallOptions.d.ts +9 -0
  123. package/dist/types/StreamPart.d.ts +12 -0
  124. package/dist/types/StreamTextResultAggregated.d.ts +74 -0
  125. package/dist/types/StreamTextResultAggregated.js +2 -0
  126. package/dist/types/TimeoutConfiguration.d.ts +19 -0
  127. package/dist/types/TimeoutConfiguration.js +1 -0
  128. package/dist/types/TimingRecord.d.ts +7 -0
  129. package/dist/types/TimingRecord.js +3 -0
  130. package/dist/types/ToolCall.d.ts +16 -1
  131. package/dist/types/ToolCallRepairReply.d.ts +19 -0
  132. package/dist/types/ToolCallRepairReply.js +2 -0
  133. package/dist/types/TraceFilter.d.ts +9 -0
  134. package/dist/types/TraceFilter.js +3 -0
  135. package/dist/types/TraceRecord.d.ts +54 -0
  136. package/dist/types/TraceRecord.js +2 -0
  137. package/dist/types/TraceStats.d.ts +20 -0
  138. package/dist/types/TraceStats.js +3 -0
  139. package/dist/types/TranscriptionCallOptions.d.ts +38 -0
  140. package/dist/types/TranscriptionCallOptions.js +2 -0
  141. package/dist/types/TranscriptionRequest.d.ts +9 -0
  142. package/dist/types/TranscriptionRequest.js +3 -0
  143. package/dist/types/TranscriptionResponse.d.ts +24 -0
  144. package/dist/types/TranscriptionResponse.js +2 -0
  145. package/dist/types/TranscriptionResult.d.ts +46 -0
  146. package/dist/types/TranscriptionResult.js +2 -0
  147. package/dist/types/TranscriptionSegment.d.ts +17 -0
  148. package/dist/types/TranscriptionSegment.js +3 -0
  149. package/dist/types/TranscriptionStreamPart.d.ts +70 -0
  150. package/dist/types/TranscriptionStreamPart.js +2 -0
  151. package/dist/types/UsageSnapshot.d.ts +18 -0
  152. package/dist/types/UsageSnapshot.js +2 -0
  153. package/dist/types/Verdict.d.ts +23 -0
  154. package/dist/types/Verdict.js +2 -0
  155. package/dist/types/VerdictConfidence.d.ts +4 -0
  156. package/dist/types/VerdictConfidence.js +3 -0
  157. package/dist/types/VerdictKind.d.ts +4 -0
  158. package/dist/types/VerdictKind.js +3 -0
  159. package/dist/types/VideoCallOptions.d.ts +17 -2
  160. package/dist/types/VideoPollOptions.d.ts +13 -0
  161. package/dist/types/VideoPollOptions.js +3 -0
  162. package/dist/types/VideoResult.d.ts +1 -1
  163. package/dist/types.d.ts +71 -1
  164. package/dist/types.js +3 -3
  165. package/index.d.ts +332 -25
  166. package/index.js +77 -54
  167. package/package.json +13 -12
package/dist/index.js CHANGED
@@ -7,42 +7,182 @@
7
7
  // Users would otherwise have to JSON.stringify every input and JSON.parse every
8
8
  // output, with no static types. This wrapper erases that JSON boundary: inputs
9
9
  // and outputs are typed objects, using the ts-rs generated types from
10
- // `./types.ts` (synced from `aimux-core/bindings` — single source of truth in
11
- // the Rust core, local copy packaged with the npm tarball).
10
+ // `./types.ts` (ts-rs exports directly into `./types/` — single source of
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
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
16
+ if (k2 === undefined) k2 = k;
17
+ var desc = Object.getOwnPropertyDescriptor(m, k);
18
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
19
+ desc = { enumerable: true, get: function() { return m[k]; } };
20
+ }
21
+ Object.defineProperty(o, k2, desc);
22
+ }) : (function(o, m, k, k2) {
23
+ if (k2 === undefined) k2 = k;
24
+ o[k2] = m[k];
25
+ }));
26
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
27
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
28
+ }) : function(o, v) {
29
+ o["default"] = v;
30
+ });
31
+ var __importStar = (this && this.__importStar) || (function () {
32
+ var ownKeys = function(o) {
33
+ ownKeys = Object.getOwnPropertyNames || function (o) {
34
+ var ar = [];
35
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
36
+ return ar;
37
+ };
38
+ return ownKeys(o);
39
+ };
40
+ return function (mod) {
41
+ if (mod && mod.__esModule) return mod;
42
+ var result = {};
43
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
44
+ __setModuleDefault(result, mod);
45
+ return result;
46
+ };
47
+ })();
15
48
  Object.defineProperty(exports, "__esModule", { value: true });
16
- 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.initLogging = exports.AbortBridge = exports.StreamTextGenerator = exports.Model = 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;
17
50
  exports.generateText = generateText;
18
51
  exports.streamText = streamText;
19
- const index_js_1 = require("../index.js");
52
+ exports.getSessionCalls = getSessionCalls;
53
+ exports.getSessions = getSessions;
54
+ exports.generateTextAsOpenai = generateTextAsOpenai;
55
+ exports.streamTextAsOpenai = streamTextAsOpenai;
56
+ exports.createProvider = createProvider;
57
+ exports.getModelSpecs = getModelSpecs;
58
+ const native = __importStar(require("./native.js"));
59
+ const native_ts_1 = require("./native.js");
60
+ // Error hierarchy (throw/catch). Wire payload type `AiMuxError` lives under StreamPart only.
61
+ var error_ts_1 = require("./error.js");
62
+ Object.defineProperty(exports, "AimuxError", { enumerable: true, get: function () { return error_ts_1.AimuxError; } });
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; } });
65
+ Object.defineProperty(exports, "JSONParseError", { enumerable: true, get: function () { return error_ts_1.JSONParseError; } });
66
+ Object.defineProperty(exports, "InvalidResponseDataError", { enumerable: true, get: function () { return error_ts_1.InvalidResponseDataError; } });
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; } });
70
+ Object.defineProperty(exports, "InvalidArgumentError", { enumerable: true, get: function () { return error_ts_1.InvalidArgumentError; } });
71
+ Object.defineProperty(exports, "InvalidPromptError", { enumerable: true, get: function () { return error_ts_1.InvalidPromptError; } });
72
+ Object.defineProperty(exports, "TokenExpiredError", { enumerable: true, get: function () { return error_ts_1.TokenExpiredError; } });
73
+ Object.defineProperty(exports, "UnsupportedFunctionalityError", { enumerable: true, get: function () { return error_ts_1.UnsupportedFunctionalityError; } });
74
+ Object.defineProperty(exports, "NoSuchModelError", { enumerable: true, get: function () { return error_ts_1.NoSuchModelError; } });
75
+ Object.defineProperty(exports, "NoSuchProviderError", { enumerable: true, get: function () { return error_ts_1.NoSuchProviderError; } });
76
+ Object.defineProperty(exports, "TimeoutError", { enumerable: true, get: function () { return error_ts_1.TimeoutError; } });
77
+ Object.defineProperty(exports, "RequestAbortedError", { enumerable: true, get: function () { return error_ts_1.RequestAbortedError; } });
78
+ Object.defineProperty(exports, "OtherError", { enumerable: true, get: function () { return error_ts_1.OtherError; } });
79
+ Object.defineProperty(exports, "RecordingError", { enumerable: true, get: function () { return error_ts_1.RecordingError; } });
20
80
  // Re-export the raw napi constructors/factories so consumers can do everything
21
81
  // from a single import: `import { openai, generateText } from 'aimux'`.
22
- var index_js_2 = require("../index.js");
23
- Object.defineProperty(exports, "Model", { enumerable: true, get: function () { return index_js_2.Model; } });
24
- Object.defineProperty(exports, "StreamTextGenerator", { enumerable: true, get: function () { return index_js_2.StreamTextGenerator; } });
25
- Object.defineProperty(exports, "AbortBridge", { enumerable: true, get: function () { return index_js_2.AbortBridge; } });
26
- Object.defineProperty(exports, "initLogging", { enumerable: true, get: function () { return index_js_2.initLogging; } });
27
- Object.defineProperty(exports, "openai", { enumerable: true, get: function () { return index_js_2.openai; } });
28
- Object.defineProperty(exports, "anthropic", { enumerable: true, get: function () { return index_js_2.anthropic; } });
29
- Object.defineProperty(exports, "deepseek", { enumerable: true, get: function () { return index_js_2.deepseek; } });
30
- Object.defineProperty(exports, "google", { enumerable: true, get: function () { return index_js_2.google; } });
31
- Object.defineProperty(exports, "cohere", { enumerable: true, get: function () { return index_js_2.cohere; } });
32
- Object.defineProperty(exports, "mistral", { enumerable: true, get: function () { return index_js_2.mistral; } });
33
- Object.defineProperty(exports, "xai", { enumerable: true, get: function () { return index_js_2.xai; } });
34
- Object.defineProperty(exports, "bedrock", { enumerable: true, get: function () { return index_js_2.bedrock; } });
35
- Object.defineProperty(exports, "vertex", { enumerable: true, get: function () { return index_js_2.vertex; } });
36
- Object.defineProperty(exports, "anthropicAws", { enumerable: true, get: function () { return index_js_2.anthropicAws; } });
37
- Object.defineProperty(exports, "azure", { enumerable: true, get: function () { return index_js_2.azure; } });
38
- Object.defineProperty(exports, "provider", { enumerable: true, get: function () { return index_js_2.provider; } });
82
+ // Rust fn names are snake_case; napi-rs exposes them camelCased (like
83
+ // `init_logging` → `initLogging`).
84
+ //
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;
118
+ // Both meanings: the `ProviderName` const object (runtime, for `ProviderName.groq`)
119
+ // and the derived string-union type. A value export resolves at runtime, so the
120
+ // specifier needs the real `.ts` extension for Node's type-stripping test runs;
121
+ // tsc rewrites it to `.js` on emit (rewriteRelativeImportExtensions).
122
+ var ProviderName_ts_1 = require("./types/ProviderName.js");
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
+ }
39
176
  /**
40
177
  * Generate text (non-streaming). Returns a typed {@link GenerateTextResult}.
41
178
  *
42
179
  * @param model - A raw model instance from `openai()`, `anthropic()`, etc.
43
180
  * @param prompt - A plain string or an array of typed chat messages.
44
181
  * @param options - Optional typed generation options (tools, tool_choice,
45
- * 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.
46
186
  * @param signal - Optional `AbortSignal`; aborting it cancels the call.
47
187
  *
48
188
  * Internally calls the raw
@@ -58,9 +198,13 @@ Object.defineProperty(exports, "provider", { enumerable: true, get: function ()
58
198
  * ```
59
199
  */
60
200
  async function generateText(model, prompt, options, signal) {
201
+ const promptJson = JSON.stringify(prompt);
61
202
  const optsJson = options ? JSON.stringify(options) : undefined;
62
- const bridge = signal ? new index_js_1.AbortBridge(signal) : undefined;
63
- const resultJson = await model.generateText(JSON.stringify(prompt), optsJson, bridge);
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
+ }
64
208
  return JSON.parse(resultJson);
65
209
  }
66
210
  /**
@@ -85,10 +229,172 @@ async function generateText(model, prompt, options, signal) {
85
229
  * ```
86
230
  */
87
231
  async function* streamText(model, prompt, options, signal) {
232
+ const promptJson = JSON.stringify(prompt);
88
233
  const optsJson = options ? JSON.stringify(options) : undefined;
89
- const bridge = signal ? new index_js_1.AbortBridge(signal) : undefined;
90
- const gen = await model.streamText(JSON.stringify(prompt), optsJson, bridge);
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
+ }
249
+ }
250
+ yield part;
251
+ }
252
+ }
253
+ /**
254
+ * All calls of a session, ordered by step (RFC-0024). Empty if the session
255
+ * is unknown or no store is registered.
256
+ *
257
+ * `initSessionStore()` / `initSessionInfer(enabled)` (raw napi, re-exported
258
+ * above) must be called first to register the store / opt-in inferer.
259
+ */
260
+ function getSessionCalls(sessionId) {
261
+ return JSON.parse(native.sessionCalls(sessionId));
262
+ }
263
+ /**
264
+ * All known sessions (RFC-0024).
265
+ */
266
+ function getSessions() {
267
+ return JSON.parse(native.listSessions());
268
+ }
269
+ /**
270
+ * Generate text and return an OpenAI Chat Completion (non-streaming).
271
+ *
272
+ * Works with **any** provider — the result is always a standard OpenAI
273
+ * `ChatCompletion` object.
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
+ *
280
+ * @example
281
+ * ```ts
282
+ * import { openai, generateTextAsOpenai } from 'aimux'
283
+ * const model = await openai(apiKey, 'gpt-4o')
284
+ * const completion = await generateTextAsOpenai(model, 'What is Rust?')
285
+ * console.log(completion.choices[0].message.content)
286
+ * ```
287
+ */
288
+ async function generateTextAsOpenai(model, prompt, options, signal) {
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);
299
+ }
300
+ /**
301
+ * Stream text as OpenAI Chat Completion chunks.
302
+ *
303
+ * Works with **any** provider — yields standard OpenAI `ChatCompletionChunk`
304
+ * objects. Pass `streamOptions` via `providerOptions.openai.stream_options`:
305
+ * `{ include_usage: true, include_reasoning: true }` (both default true).
306
+ *
307
+ * @example
308
+ * ```ts
309
+ * import { openai, streamTextAsOpenai } from 'aimux'
310
+ * const model = await openai(apiKey, 'gpt-4o')
311
+ * for await (const chunk of streamTextAsOpenai(model, 'Write a haiku.')) {
312
+ * const delta = chunk.choices[0]?.delta?.content
313
+ * if (delta) process.stdout.write(delta)
314
+ * }
315
+ * ```
316
+ */
317
+ async function* streamTextAsOpenai(model, prompt, options, signal) {
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);
91
321
  for await (const json of gen) {
92
322
  yield JSON.parse(json);
93
323
  }
94
324
  }
325
+ // ─────────────────────────────────────────────────────────────────────────────
326
+ // Provider handles (RFC-0027) — createProvider / listModels / model
327
+ // ─────────────────────────────────────────────────────────────────────────────
328
+ /**
329
+ * A typed wrapper around the raw napi `ProviderHandle` class. Created by
330
+ * {@link createProvider}, supports {@link ProviderHandleTyped.listModels} and
331
+ * {@link ProviderHandleTyped.model}.
332
+ *
333
+ * @example
334
+ * ```ts
335
+ * import { createProvider, generateText } from 'aimux'
336
+ * const p = await createProvider('deepseek', apiKey)
337
+ * const models = await p.listModels()
338
+ * const model = await p.model(models[0].id)
339
+ * const result = await generateText(model, 'Hello')
340
+ * ```
341
+ */
342
+ class ProviderHandleTyped {
343
+ constructor(raw) {
344
+ this.raw = raw;
345
+ }
346
+ /** List models available on this provider (runtime discovery + anya2a spec). */
347
+ async listModels() {
348
+ return JSON.parse(await this.raw.listModels());
349
+ }
350
+ /** Build a language model from a discovered model id. */
351
+ async model(modelId) {
352
+ return this.raw.model(modelId);
353
+ }
354
+ }
355
+ exports.ProviderHandleTyped = ProviderHandleTyped;
356
+ /**
357
+ * Create a **provider handle** (RFC-0027) for a registry-backed provider.
358
+ *
359
+ * Unlike `provider()` (which binds to a single modelId), this returns a handle
360
+ * that supports `listModels()` (runtime discovery) and `model()`.
361
+ *
362
+ * @param name - Provider name (e.g. `"deepseek"`, `"groq"`).
363
+ * @param apiKey - API key; omit/null to read the provider's env var.
364
+ * @param config - Optional provider config (baseUrl, headers, …).
365
+ *
366
+ * @example
367
+ * ```ts
368
+ * import { createProvider, generateText } from 'aimux'
369
+ * const p = await createProvider('deepseek', process.env.DEEPSEEK_API_KEY)
370
+ * const models = await p.listModels()
371
+ * const model = await p.model(models[0].id)
372
+ * const result = await generateText(model, 'Hello')
373
+ * ```
374
+ */
375
+ async function createProvider(name, apiKey, config) {
376
+ const raw = await (0, native_ts_1.createProvider)(name, apiKey ?? null, config ?? null);
377
+ return new ProviderHandleTyped(raw);
378
+ }
379
+ /**
380
+ * Fetch the community model catalogue (anya2a). Returns a `Catalogue` object
381
+ * with a `lookup(provider, modelId)` method. Thin fetch — no caching; the host
382
+ * decides how to persist/reuse the result.
383
+ *
384
+ * @param sourceUrl - Optional URL override (default = anya2a endpoint).
385
+ *
386
+ * @example
387
+ * ```ts
388
+ * import { createProvider, getModelSpecs, generateText } from 'aimux'
389
+ * const [p, catalogue] = await Promise.all([
390
+ * createProvider('deepseek', apiKey),
391
+ * getModelSpecs(),
392
+ * ])
393
+ * const models = await p.listModels()
394
+ * const model = await p.model(models[0].id)
395
+ * const spec = catalogue.specs?.['deepseek']?.[models[0].id] // community portrait
396
+ * ```
397
+ */
398
+ async function getModelSpecs(sourceUrl) {
399
+ return JSON.parse(await (0, native_ts_1.getModelSpecs)(sourceUrl ?? null));
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,34 +1,66 @@
1
+ import type { ApiCallError } from "./ApiCallError";
2
+ import type { RetryError } from "./RetryError";
1
3
  /**
2
4
  * Unified error type for all aimux operations.
5
+ *
6
+ * Variants are cut by *what the caller does about it*, not by where the
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.
3
9
  */
4
10
  export type AiMuxError = {
5
- "Provider": string;
11
+ "ApiCall": ApiCallError;
6
12
  } | {
7
- "Http": string;
13
+ "Retry": RetryError;
8
14
  } | {
9
- "Json": string;
15
+ "JsonParse": string;
10
16
  } | {
11
- "Stream": string;
17
+ "InvalidResponseData": string;
12
18
  } | {
13
- "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
+ };
14
39
  } | {
15
40
  "InvalidArgument": string;
16
41
  } | {
17
42
  "InvalidPrompt": string;
18
43
  } | {
19
- "RateLimited": {
20
- retry_after_ms: bigint;
21
- };
44
+ "TokenExpired": string;
22
45
  } | {
23
- "Auth": string;
46
+ "UnsupportedFunctionality": string;
24
47
  } | {
25
- "ModelNotFound": string;
48
+ "NoSuchModel": {
49
+ model_id: string;
50
+ /**
51
+ * What kind of model was requested (`"languageModel"`,
52
+ * `"imageModel"`, …), the AI SDK's `modelType`.
53
+ */
54
+ model_type: string;
55
+ };
26
56
  } | {
27
- "Unsupported": string;
57
+ "NoSuchProvider": {
58
+ provider_id: string;
59
+ };
28
60
  } | {
29
- "NoSuchModel": string;
61
+ "Timeout": string;
30
62
  } | {
31
- "ApiCall": string;
63
+ "Aborted": string;
32
64
  } | {
33
65
  "Other": string;
34
66
  };
@@ -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 });
@@ -0,0 +1,75 @@
1
+ import type { JsonValue } from "./serde_json/JsonValue";
2
+ /**
3
+ * What a failed API call observed — the field set of the AI SDK's
4
+ * `APICallError` (`statusCode` / `responseBody`), which this project's error
5
+ * taxonomy mirrors (docs/internal/vercel-research/07-kernel-infrastructure.md).
6
+ *
7
+ * Carried by [`AiMuxError::ApiCall`] alone. There are no per-status
8
+ * variants: a 401, 404 or 429 is an `ApiCall` error whose classification is
9
+ * read from `status_code`, exactly as the AI SDK reads
10
+ * `APICallError.statusCode`. Transport failures (connection reset, DNS,
11
+ * body read) are `ApiCall` errors too — no response arrived, so
12
+ * `status_code` is `None` and `is_retryable` is `true`, exactly as the AI
13
+ * SDK's `handleFetchError` builds an `APICallError` with no `statusCode`
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.
19
+ *
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.
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;
33
+ /**
34
+ * HTTP status of the response, when it came from one
35
+ * (`APICallError.statusCode`). Always the *observed* status: the HTTP
36
+ * layer fills it for every response-derived error; errors built without
37
+ * an HTTP exchange leave it `None`.
38
+ */
39
+ status_code: number | null;
40
+ /**
41
+ * Provider's machine-readable code (OpenAI's `code`/`type`,
42
+ * e.g. `"rate_limit_exceeded"` vs `"insufficient_quota"`). Never an HTTP
43
+ * status. Our normalized take on `APICallError.data`.
44
+ */
45
+ provider_code: string | null;
46
+ /**
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.
50
+ */
51
+ message: string;
52
+ /**
53
+ * The raw response body, verbatim (`APICallError.responseBody`) — the
54
+ * lossless evidence when `message`/`provider_code` are extractions.
55
+ * `None` when the error did not come from a response body.
56
+ */
57
+ response_body: string | null;
58
+ /**
59
+ * Sanitized response headers.
60
+ */
61
+ response_headers: {
62
+ [key in string]: string;
63
+ } | null;
64
+ /**
65
+ * Parsed provider error data.
66
+ */
67
+ data: JsonValue | null;
68
+ /**
69
+ * Whether retrying can help (`APICallError.isRetryable`) — stored at
70
+ * construction, exactly like the AI SDK: the response path computes it
71
+ * from the status (408/409/429 or 5xx), and the transport path (no response, so
72
+ * no status to compute from) sets it to `true` explicitly.
73
+ */
74
+ is_retryable: boolean;
75
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1 @@
1
+ export type BreakKind = "SystemChanged" | "ToolsChanged" | "ConversationReset" | "Unknown";
@@ -0,0 +1,3 @@
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
+ Object.defineProperty(exports, "__esModule", { value: true });