@alma-harness/providers 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,61 @@
1
+ # @alma-harness/providers
2
+
3
+ `ModelClient` adapters for [Alma](https://github.com/FabioFernandesCarneiro/alma):
4
+ Anthropic and OpenAI first-party, plus the OpenRouter gateway bridge, over one
5
+ neutral message format.
6
+
7
+ > **Status: pre-release.** Not yet published to npm.
8
+
9
+ ## What it owns
10
+
11
+ - `AnthropicModelClient` — Messages API, streaming, with explicit
12
+ `cache_control` breakpoints at the stable-system boundary and the
13
+ conversation tail.
14
+ - `OpenAIModelClient` — Responses API, streaming, automatic prefix caching.
15
+ - `OpenRouterModelClient` — the gateway bridge (chat completions). A gateway
16
+ does not answer "who processed this data?" by itself, so construction
17
+ REQUIRES a declared upstream allowlist, fallbacks are off by default, data
18
+ collection is denied by default, and `require_parameters` rides along
19
+ whenever the request carries tools. Opening the catalogue changes nothing
20
+ about what the routing policy permits — that stays a product/DPO decision.
21
+ - The translation between Alma's neutral `Msg`/`Block` format and each
22
+ provider's wire format, in both directions.
23
+
24
+ Routing decides *which* client runs; the adapter only speaks the protocol.
25
+
26
+ ```ts
27
+ import { OpenRouterModelClient } from "@alma-harness/providers";
28
+
29
+ const client = new OpenRouterModelClient({
30
+ upstreams: ["deepinfra", "together"], // the declared data-processing chain
31
+ });
32
+ ```
33
+
34
+ ## Credentials
35
+
36
+ The harness never owns credentials. Each client accepts an explicitly injected
37
+ key or falls back to the SDK's own environment resolution — configuration comes
38
+ from the hosting environment, never from a file this repo reads.
39
+
40
+ ```ts
41
+ import { AnthropicModelClient } from "@alma-harness/providers";
42
+
43
+ const client = new AnthropicModelClient(); // reads ANTHROPIC_API_KEY
44
+ const explicit = new AnthropicModelClient({ apiKey }); // or inject it
45
+ ```
46
+
47
+ ## What it must never do
48
+
49
+ - Decide routing, spend, or capability. Those are core, not adapter.
50
+ - Leak a provider type into the neutral format — the format is the boundary
51
+ that makes a second provider cheap.
52
+ - Swallow provider drift: a stream that ends without a stop event fails loudly
53
+ rather than looking like a successful empty turn.
54
+
55
+ ## Documentation
56
+
57
+ [Docs index](../../docs/README.md) · [Architecture §6.2](../../docs/architecture.md#6-contracts)
58
+ · [Anthropic adapter spec](../../docs/specs/002-anthropic-provider.md)
59
+ · [OpenAI adapter spec](../../docs/specs/003-openai-provider.md)
60
+
61
+ Apache-2.0
@@ -0,0 +1,172 @@
1
+ import { ModelClient, ModelRequest, ModelEvent } from '@alma-harness/core';
2
+ export { ModelClient, ModelEvent, ModelRef, ModelRequest, ProviderId } from '@alma-harness/core';
3
+ import Anthropic from '@anthropic-ai/sdk';
4
+ import OpenAI from 'openai';
5
+
6
+ interface AnthropicModelClientOptions {
7
+ /** Omit to use the SDK's environment resolution (ANTHROPIC_API_KEY, …). */
8
+ apiKey?: string;
9
+ baseURL?: string;
10
+ }
11
+ /**
12
+ * `ModelClient` adapter for the Anthropic Messages API — §6.2, spec 002.
13
+ * A thin shell: request/stream translation lives in ./translate (pure);
14
+ * this class only owns the SDK client. SDK typed errors propagate as-is.
15
+ */
16
+ declare class AnthropicModelClient implements ModelClient {
17
+ #private;
18
+ constructor(opts?: AnthropicModelClientOptions);
19
+ stream(req: ModelRequest, opts?: {
20
+ signal?: AbortSignal;
21
+ }): AsyncIterable<ModelEvent>;
22
+ }
23
+
24
+ /**
25
+ * Pure translation between Alma's neutral vocabulary (§6.2) and the Anthropic
26
+ * Messages API — spec 002. Everything here is side-effect-free so the wire
27
+ * mapping is testable without a network.
28
+ */
29
+ /** Raised when a request or stream cannot be represented faithfully. */
30
+ declare class AnthropicTranslationError extends Error {
31
+ constructor(message: string);
32
+ }
33
+ declare function toAnthropicParams(req: ModelRequest): Anthropic.MessageCreateParamsStreaming;
34
+ /**
35
+ * Raw SDK stream → neutral `ModelEvent`s. Tool inputs arrive as
36
+ * `input_json_delta` fragments; they are accumulated per content block and
37
+ * emitted as ONE `tool_call` with parsed input at `content_block_stop`.
38
+ * Usage is aggregated (input + cache fields from `message_start`, output from
39
+ * `message_delta`) and emitted once before the final `stop`.
40
+ */
41
+ declare function translateStream(events: AsyncIterable<Anthropic.RawMessageStreamEvent>): AsyncGenerator<ModelEvent>;
42
+
43
+ interface OpenAIModelClientOptions {
44
+ /** Omit to use the SDK's environment resolution (OPENAI_API_KEY). */
45
+ apiKey?: string;
46
+ baseURL?: string;
47
+ }
48
+ /**
49
+ * `ModelClient` adapter for the OpenAI Responses API — §6.2, spec 003.
50
+ * A thin shell: request/stream translation lives in ./translate (pure);
51
+ * this class only owns the SDK client. SDK typed errors propagate as-is.
52
+ */
53
+ declare class OpenAIModelClient implements ModelClient {
54
+ #private;
55
+ constructor(opts?: OpenAIModelClientOptions);
56
+ stream(req: ModelRequest, opts?: {
57
+ signal?: AbortSignal;
58
+ }): AsyncIterable<ModelEvent>;
59
+ }
60
+
61
+ /**
62
+ * Pure translation between Alma's neutral vocabulary (§6.2) and the OpenAI
63
+ * Responses API — spec 003. Side-effect-free; testable without a network.
64
+ */
65
+ declare class OpenAITranslationError extends Error {
66
+ constructor(message: string);
67
+ }
68
+ declare function toOpenAIParams(req: ModelRequest): OpenAI.Responses.ResponseCreateParamsStreaming;
69
+ /**
70
+ * Semantic stream events → neutral `ModelEvent`s. Function-call arguments
71
+ * arrive complete on `response.output_item.done`, so each call is emitted as
72
+ * ONE parsed `tool_call`. The terminal `response.completed` / `.incomplete`
73
+ * event carries usage; `tool_use` is inferred from having emitted tool calls
74
+ * (the Responses API has no finish_reason).
75
+ */
76
+ declare function translateOpenAIStream(events: AsyncIterable<OpenAI.Responses.ResponseStreamEvent>): AsyncGenerator<ModelEvent>;
77
+
78
+ /**
79
+ * Pure translation between Alma's neutral vocabulary (§6.2) and OpenRouter's
80
+ * chat-completions wire — spec 014. A SECOND translator over the neutral
81
+ * format, not a `baseURL` override: the first-party OpenAI adapter speaks the
82
+ * Responses API, and nothing in its translation is reusable here.
83
+ * Side-effect-free; testable without a network.
84
+ */
85
+ declare class OpenRouterTranslationError extends Error {
86
+ constructor(message: string);
87
+ }
88
+ /**
89
+ * The upstream routing policy — spec 014's core constraint: for a gateway,
90
+ * "who processed this data?" must be a DECLARED fact, not an observed one.
91
+ */
92
+ interface OpenRouterRouting {
93
+ /**
94
+ * OpenRouter provider slugs allowed to serve requests (→ `provider.only`).
95
+ * REQUIRED and non-empty: without it the data-processing chain has no
96
+ * answer, so the client refuses to construct.
97
+ */
98
+ upstreams: readonly string[];
99
+ /**
100
+ * Default false: a fallback is a silent change of data processor. Enabling
101
+ * it is a stated product choice, never a default.
102
+ */
103
+ allowFallbacks?: boolean;
104
+ /**
105
+ * Default "deny" — OpenRouter defaults to "allow", and a harness whose
106
+ * README says "operating on sensitive data" must not inherit the permissive
107
+ * default (spec 014 DECISION).
108
+ */
109
+ dataCollection?: "allow" | "deny";
110
+ /** Opt-in pass-through to OpenRouter's zero-data-retention guarantee. */
111
+ zeroDataRetention?: boolean;
112
+ }
113
+ /** The `provider` routing block OpenRouter accepts on every request. */
114
+ interface OpenRouterProviderBlock {
115
+ only: string[];
116
+ allow_fallbacks: boolean;
117
+ data_collection: "allow" | "deny";
118
+ zdr?: boolean;
119
+ require_parameters?: boolean;
120
+ }
121
+ type OpenRouterParams = OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming & {
122
+ provider: OpenRouterProviderBlock;
123
+ };
124
+ declare function toOpenRouterParams(req: ModelRequest, routing: OpenRouterRouting): OpenRouterParams;
125
+ /**
126
+ * Chat-completion chunks → neutral `ModelEvent`s. Tool-call arguments arrive
127
+ * as indexed fragments (id and name on the first fragment, argument pieces on
128
+ * the rest); they are accumulated per index and emitted as ONE parsed
129
+ * `tool_call` each when the choice finishes. The usage chunk arrives AFTER
130
+ * `finish_reason` (with `stream_options.include_usage`), so the terminal
131
+ * usage + stop pair is emitted at stream end — same order every adapter emits.
132
+ */
133
+ declare function translateOpenRouterStream(chunks: AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>): AsyncGenerator<ModelEvent>;
134
+
135
+ interface OpenRouterModelClientOptions extends OpenRouterRouting {
136
+ /** Omit to read OPENROUTER_API_KEY (the OpenAI SDK's own env resolution
137
+ * would read OPENAI_API_KEY — the wrong credential for this gateway). */
138
+ apiKey?: string;
139
+ /** Defaults to OpenRouter's public endpoint. */
140
+ baseURL?: string;
141
+ }
142
+ /**
143
+ * `ModelClient` adapter for OpenRouter — §6.2, spec 014 (the gateway bridge).
144
+ * Same thin-shell shape as the first-party adapters: translation lives in
145
+ * ./translate (pure); this class owns the SDK client and the DECLARED
146
+ * upstream policy. A gateway erases "who processed this data?" unless the
147
+ * chain is declared beforehand, so construction REFUSES to proceed without a
148
+ * non-empty upstream allowlist — deciding after the fact enforces nothing.
149
+ */
150
+ declare class OpenRouterModelClient implements ModelClient {
151
+ #private;
152
+ constructor(opts: OpenRouterModelClientOptions);
153
+ stream(req: ModelRequest, opts?: {
154
+ signal?: AbortSignal;
155
+ }): AsyncIterable<ModelEvent>;
156
+ }
157
+
158
+ /**
159
+ * @alma-harness/providers — `ModelClient` adapters (§6.2).
160
+ * Bi-provider from birth — `AnthropicModelClient` (spec 002) and
161
+ * `OpenAIModelClient` (spec 003) — plus the OpenRouter gateway bridge
162
+ * (spec 014), all over the same neutral surface.
163
+ */
164
+
165
+ /**
166
+ * First-party from birth (§3 principle 4), plus the gateway bridge —
167
+ * spec 014: `openrouter` names the EXIT, not the processor; its adapter
168
+ * requires a declared upstream allowlist for exactly that reason.
169
+ */
170
+ declare const SUPPORTED_PROVIDERS: readonly ["anthropic", "openai", "openrouter"];
171
+
172
+ export { AnthropicModelClient, type AnthropicModelClientOptions, AnthropicTranslationError, OpenAIModelClient, type OpenAIModelClientOptions, OpenAITranslationError, OpenRouterModelClient, type OpenRouterModelClientOptions, type OpenRouterParams, type OpenRouterRouting, OpenRouterTranslationError, SUPPORTED_PROVIDERS, toAnthropicParams, toOpenAIParams, toOpenRouterParams, translateOpenAIStream, translateOpenRouterStream, translateStream };
package/dist/index.js ADDED
@@ -0,0 +1,655 @@
1
+ // src/anthropic/client.ts
2
+ import Anthropic from "@anthropic-ai/sdk";
3
+
4
+ // src/anthropic/translate.ts
5
+ var AnthropicTranslationError = class extends Error {
6
+ constructor(message) {
7
+ super(message);
8
+ this.name = "AnthropicTranslationError";
9
+ }
10
+ };
11
+ function toAnthropicParams(req) {
12
+ if (req.model.provider !== "anthropic") {
13
+ throw new AnthropicTranslationError(
14
+ `AnthropicModelClient received a request for provider ${JSON.stringify(req.model.provider)}`
15
+ );
16
+ }
17
+ const params = {
18
+ model: req.model.id,
19
+ max_tokens: req.maxTokens,
20
+ stream: true,
21
+ system: toSystem(req.system),
22
+ messages: req.messages.map(toMessageParam)
23
+ };
24
+ if (req.tools.length > 0) params.tools = req.tools.map(toTool);
25
+ markConversationTail(params.messages);
26
+ return params;
27
+ }
28
+ function markConversationTail(messages) {
29
+ const last = messages.at(-1);
30
+ if (!last || typeof last.content === "string") return;
31
+ const block = last.content.at(-1);
32
+ if (block) block.cache_control = { type: "ephemeral" };
33
+ }
34
+ function toSystem(blocks) {
35
+ const lastStable = blocks.reduce(
36
+ (last, b, i) => b.volatility === "stable" ? i : last,
37
+ -1
38
+ );
39
+ return blocks.map((b, i) => {
40
+ const param = { type: "text", text: b.text };
41
+ if (i === lastStable) param.cache_control = { type: "ephemeral" };
42
+ return param;
43
+ });
44
+ }
45
+ function toMessageParam(msg) {
46
+ switch (msg.role) {
47
+ case "user":
48
+ return { role: "user", content: msg.blocks.map(toUserBlock) };
49
+ case "assistant":
50
+ return { role: "assistant", content: msg.blocks.map(toAssistantBlock) };
51
+ case "tool":
52
+ return { role: "user", content: msg.blocks.map(toToolResultBlock) };
53
+ }
54
+ }
55
+ function toUserBlock(block) {
56
+ switch (block.type) {
57
+ case "text":
58
+ return { type: "text", text: block.text };
59
+ case "media":
60
+ switch (block.kind) {
61
+ case "image":
62
+ return { type: "image", source: { type: "url", url: block.ref.uri } };
63
+ case "document":
64
+ return { type: "document", source: { type: "url", url: block.ref.uri } };
65
+ case "audio":
66
+ throw new AnthropicTranslationError("audio media is not supported by the Anthropic adapter");
67
+ }
68
+ default:
69
+ throw new AnthropicTranslationError(`block type ${JSON.stringify(block.type)} is not valid in a user message`);
70
+ }
71
+ }
72
+ function toAssistantBlock(block) {
73
+ switch (block.type) {
74
+ case "text":
75
+ return { type: "text", text: block.text };
76
+ case "tool_call":
77
+ return { type: "tool_use", id: block.id, name: block.name, input: block.input };
78
+ default:
79
+ throw new AnthropicTranslationError(
80
+ `block type ${JSON.stringify(block.type)} is not valid in an assistant message`
81
+ );
82
+ }
83
+ }
84
+ function toToolResultBlock(block) {
85
+ if (block.type !== "tool_result") {
86
+ throw new AnthropicTranslationError(
87
+ `block type ${JSON.stringify(block.type)} is not valid in a tool message`
88
+ );
89
+ }
90
+ const param = {
91
+ type: "tool_result",
92
+ tool_use_id: block.callId,
93
+ // JSON.stringify yields undefined (not a string) for undefined/functions;
94
+ // "null" keeps the content explicit for void tool outputs.
95
+ content: typeof block.output === "string" ? block.output : JSON.stringify(block.output) ?? "null"
96
+ };
97
+ if (block.isError) param.is_error = true;
98
+ return param;
99
+ }
100
+ function toTool(spec) {
101
+ return {
102
+ name: spec.name,
103
+ description: spec.description,
104
+ // The registry already derived a JSON Schema object (§6.4).
105
+ input_schema: spec.inputSchema
106
+ };
107
+ }
108
+ async function* translateStream(events) {
109
+ const usage = { inputTokens: 0, outputTokens: 0 };
110
+ let stopReason = null;
111
+ const pendingTools = /* @__PURE__ */ new Map();
112
+ for await (const event of events) {
113
+ switch (event.type) {
114
+ case "message_start": {
115
+ const u = event.message.usage;
116
+ usage.inputTokens = u.input_tokens;
117
+ if (u.cache_read_input_tokens != null) usage.cacheReadInputTokens = u.cache_read_input_tokens;
118
+ if (u.cache_creation_input_tokens != null) {
119
+ usage.cacheWriteInputTokens = u.cache_creation_input_tokens;
120
+ }
121
+ break;
122
+ }
123
+ case "content_block_start":
124
+ if (event.content_block.type === "tool_use") {
125
+ pendingTools.set(event.index, {
126
+ id: event.content_block.id,
127
+ name: event.content_block.name,
128
+ json: ""
129
+ });
130
+ }
131
+ break;
132
+ case "content_block_delta":
133
+ if (event.delta.type === "text_delta") {
134
+ yield { type: "text_delta", text: event.delta.text };
135
+ } else if (event.delta.type === "input_json_delta") {
136
+ const pending = pendingTools.get(event.index);
137
+ if (pending) pending.json += event.delta.partial_json;
138
+ }
139
+ break;
140
+ case "content_block_stop": {
141
+ const pending = pendingTools.get(event.index);
142
+ if (pending) {
143
+ pendingTools.delete(event.index);
144
+ yield {
145
+ type: "tool_call",
146
+ id: pending.id,
147
+ name: pending.name,
148
+ input: pending.json === "" ? {} : JSON.parse(pending.json)
149
+ };
150
+ }
151
+ break;
152
+ }
153
+ case "message_delta":
154
+ if (event.delta.stop_reason != null) stopReason = event.delta.stop_reason;
155
+ usage.outputTokens = event.usage.output_tokens;
156
+ break;
157
+ case "message_stop":
158
+ yield { type: "usage", usage: { ...usage } };
159
+ yield { type: "stop", reason: mapStopReason(stopReason) };
160
+ break;
161
+ }
162
+ }
163
+ }
164
+ function mapStopReason(reason) {
165
+ switch (reason) {
166
+ case "end_turn":
167
+ case "stop_sequence":
168
+ return "end_turn";
169
+ case "tool_use":
170
+ return "tool_use";
171
+ case "max_tokens":
172
+ return "max_tokens";
173
+ case "refusal":
174
+ return "refusal";
175
+ case "model_context_window_exceeded":
176
+ return "context_window_exceeded";
177
+ default:
178
+ throw new AnthropicTranslationError(
179
+ `Unmapped Anthropic stop_reason ${JSON.stringify(reason)} \u2014 provider drift?`
180
+ );
181
+ }
182
+ }
183
+
184
+ // src/anthropic/client.ts
185
+ var AnthropicModelClient = class {
186
+ #client;
187
+ constructor(opts = {}) {
188
+ const init = {};
189
+ if (opts.apiKey !== void 0) init.apiKey = opts.apiKey;
190
+ if (opts.baseURL !== void 0) init.baseURL = opts.baseURL;
191
+ this.#client = new Anthropic(init);
192
+ }
193
+ stream(req, opts) {
194
+ const params = toAnthropicParams(req);
195
+ return translateStream(this.#rawEvents(params, opts?.signal));
196
+ }
197
+ async *#rawEvents(params, signal) {
198
+ const stream = await this.#client.messages.create(
199
+ params,
200
+ signal !== void 0 ? { signal } : void 0
201
+ );
202
+ for await (const event of stream) yield event;
203
+ }
204
+ };
205
+
206
+ // src/openai/client.ts
207
+ import OpenAI from "openai";
208
+
209
+ // src/openai/translate.ts
210
+ var OpenAITranslationError = class extends Error {
211
+ constructor(message) {
212
+ super(message);
213
+ this.name = "OpenAITranslationError";
214
+ }
215
+ };
216
+ function toOpenAIParams(req) {
217
+ if (req.model.provider !== "openai") {
218
+ throw new OpenAITranslationError(
219
+ `OpenAIModelClient received a request for provider ${JSON.stringify(req.model.provider)}`
220
+ );
221
+ }
222
+ const params = {
223
+ model: req.model.id,
224
+ max_output_tokens: req.maxTokens,
225
+ stream: true,
226
+ // Privacy-first (§3, §10): the Responses API stores responses server-side
227
+ // by default; the harness never leaves conversation state at the provider.
228
+ store: false,
229
+ input: req.messages.flatMap(toInputItems)
230
+ };
231
+ const instructions = toInstructions(req.system);
232
+ if (instructions !== "") params.instructions = instructions;
233
+ if (req.tools.length > 0) params.tools = req.tools.map(toTool2);
234
+ return params;
235
+ }
236
+ function toInstructions(blocks) {
237
+ return blocks.map((b) => b.text).join("\n\n");
238
+ }
239
+ function toInputItems(msg) {
240
+ switch (msg.role) {
241
+ case "user":
242
+ return [{ role: "user", content: msg.blocks.map(toUserContentPart) }];
243
+ case "assistant":
244
+ return msg.blocks.map(toAssistantItem);
245
+ case "tool":
246
+ return msg.blocks.map(toFunctionCallOutput);
247
+ }
248
+ }
249
+ function toUserContentPart(block) {
250
+ switch (block.type) {
251
+ case "text":
252
+ return { type: "input_text", text: block.text };
253
+ case "media":
254
+ if (block.kind === "image") {
255
+ return { type: "input_image", detail: "auto", image_url: block.ref.uri };
256
+ }
257
+ throw new OpenAITranslationError(
258
+ `${block.kind} media is not supported by the OpenAI adapter`
259
+ );
260
+ default:
261
+ throw new OpenAITranslationError(
262
+ `block type ${JSON.stringify(block.type)} is not valid in a user message`
263
+ );
264
+ }
265
+ }
266
+ function toAssistantItem(block) {
267
+ switch (block.type) {
268
+ case "text":
269
+ return { role: "assistant", content: block.text };
270
+ case "tool_call":
271
+ return {
272
+ type: "function_call",
273
+ call_id: block.id,
274
+ name: block.name,
275
+ arguments: JSON.stringify(block.input)
276
+ };
277
+ default:
278
+ throw new OpenAITranslationError(
279
+ `block type ${JSON.stringify(block.type)} is not valid in an assistant message`
280
+ );
281
+ }
282
+ }
283
+ function toFunctionCallOutput(block) {
284
+ if (block.type !== "tool_result") {
285
+ throw new OpenAITranslationError(
286
+ `block type ${JSON.stringify(block.type)} is not valid in a tool message`
287
+ );
288
+ }
289
+ const serialized = typeof block.output === "string" ? block.output : JSON.stringify(block.output) ?? "null";
290
+ return {
291
+ type: "function_call_output",
292
+ call_id: block.callId,
293
+ // The Responses API has no is_error flag on function outputs — an
294
+ // explicit prefix keeps failures visible to the model (spec 003).
295
+ output: block.isError ? `ERROR: ${serialized}` : serialized
296
+ };
297
+ }
298
+ function toTool2(spec) {
299
+ return {
300
+ type: "function",
301
+ name: spec.name,
302
+ description: spec.description,
303
+ parameters: spec.inputSchema,
304
+ // Registry-derived schemas are not guaranteed strict-compatible; the
305
+ // structured-output surface is a follow-up slice (spec 003 decision).
306
+ strict: false
307
+ };
308
+ }
309
+ async function* translateOpenAIStream(events) {
310
+ let sawToolCall = false;
311
+ let sawRefusal = false;
312
+ for await (const event of events) {
313
+ switch (event.type) {
314
+ case "response.output_text.delta":
315
+ yield { type: "text_delta", text: event.delta };
316
+ break;
317
+ case "response.refusal.delta":
318
+ sawRefusal = true;
319
+ yield { type: "text_delta", text: event.delta };
320
+ break;
321
+ case "response.output_item.done":
322
+ if (event.item.type === "function_call") {
323
+ sawToolCall = true;
324
+ yield {
325
+ type: "tool_call",
326
+ id: event.item.call_id,
327
+ name: event.item.name,
328
+ input: event.item.arguments === "" ? {} : JSON.parse(event.item.arguments)
329
+ };
330
+ }
331
+ break;
332
+ case "response.completed":
333
+ yield usageEvent(event.response);
334
+ yield { type: "stop", reason: sawRefusal ? "refusal" : sawToolCall ? "tool_use" : "end_turn" };
335
+ break;
336
+ case "response.incomplete": {
337
+ yield usageEvent(event.response);
338
+ yield { type: "stop", reason: mapIncompleteReason(event.response) };
339
+ break;
340
+ }
341
+ case "response.failed": {
342
+ const err = event.response.error;
343
+ throw new OpenAITranslationError(
344
+ `OpenAI response failed: ${err ? `${err.code}: ${err.message}` : "unknown error"}`
345
+ );
346
+ }
347
+ case "error":
348
+ throw new OpenAITranslationError(`OpenAI stream error: ${event.message}`);
349
+ default:
350
+ break;
351
+ }
352
+ }
353
+ }
354
+ function usageEvent(response) {
355
+ const u = response.usage;
356
+ const cachedRead = u?.input_tokens_details?.cached_tokens ?? 0;
357
+ const usage = {
358
+ // Neutral semantics (spec 005): inputTokens EXCLUDES cache reads.
359
+ // OpenAI's input_tokens includes cached_tokens; subtract to normalize —
360
+ // otherwise the BudgetGuard would price the same conversation
361
+ // differently per provider.
362
+ inputTokens: Math.max(0, (u?.input_tokens ?? 0) - cachedRead),
363
+ outputTokens: u?.output_tokens ?? 0
364
+ };
365
+ if (cachedRead > 0) usage.cacheReadInputTokens = cachedRead;
366
+ const cacheWrite = u?.input_tokens_details?.cache_write_tokens;
367
+ if (cacheWrite !== void 0 && cacheWrite > 0) usage.cacheWriteInputTokens = cacheWrite;
368
+ return { type: "usage", usage };
369
+ }
370
+ function mapIncompleteReason(response) {
371
+ const reason = response.incomplete_details?.reason;
372
+ switch (reason) {
373
+ case "max_output_tokens":
374
+ return "max_tokens";
375
+ case "content_filter":
376
+ return "refusal";
377
+ default:
378
+ throw new OpenAITranslationError(
379
+ `Unmapped OpenAI incomplete reason ${JSON.stringify(reason)} \u2014 provider drift?`
380
+ );
381
+ }
382
+ }
383
+
384
+ // src/openai/client.ts
385
+ var OpenAIModelClient = class {
386
+ #client;
387
+ constructor(opts = {}) {
388
+ const init = {};
389
+ if (opts.apiKey !== void 0) init.apiKey = opts.apiKey;
390
+ if (opts.baseURL !== void 0) init.baseURL = opts.baseURL;
391
+ this.#client = new OpenAI(init);
392
+ }
393
+ stream(req, opts) {
394
+ const params = toOpenAIParams(req);
395
+ return translateOpenAIStream(this.#rawEvents(params, opts?.signal));
396
+ }
397
+ async *#rawEvents(params, signal) {
398
+ const stream = await this.#client.responses.create(
399
+ params,
400
+ signal !== void 0 ? { signal } : void 0
401
+ );
402
+ for await (const event of stream) yield event;
403
+ }
404
+ };
405
+
406
+ // src/openrouter/client.ts
407
+ import OpenAI2 from "openai";
408
+
409
+ // src/openrouter/translate.ts
410
+ var OpenRouterTranslationError = class extends Error {
411
+ constructor(message) {
412
+ super(message);
413
+ this.name = "OpenRouterTranslationError";
414
+ }
415
+ };
416
+ function toOpenRouterParams(req, routing) {
417
+ if (req.model.provider !== "openrouter") {
418
+ throw new OpenRouterTranslationError(
419
+ `OpenRouterModelClient received a request for provider ${JSON.stringify(req.model.provider)}`
420
+ );
421
+ }
422
+ const provider = {
423
+ only: [...routing.upstreams],
424
+ allow_fallbacks: routing.allowFallbacks ?? false,
425
+ data_collection: routing.dataCollection ?? "deny"
426
+ };
427
+ if (routing.zeroDataRetention === true) provider.zdr = true;
428
+ if (req.tools.length > 0) {
429
+ provider.require_parameters = true;
430
+ }
431
+ const params = {
432
+ model: req.model.id,
433
+ // The SDK deprecates this in favor of the OpenAI-specific
434
+ // max_completion_tokens; for a gateway fronting heterogeneous upstreams,
435
+ // max_tokens is the common denominator OpenRouter documents.
436
+ max_tokens: req.maxTokens,
437
+ stream: true,
438
+ // Review amendment (spec 014): streamed chat completions only carry usage
439
+ // when asked — without this the BudgetGuard never sees a usage event.
440
+ stream_options: { include_usage: true },
441
+ messages: [...systemMessages(req.system), ...req.messages.flatMap(toWireMessages)],
442
+ provider
443
+ };
444
+ if (req.tools.length > 0) params.tools = req.tools.map(toTool3);
445
+ return params;
446
+ }
447
+ function systemMessages(blocks) {
448
+ if (blocks.length === 0) return [];
449
+ return [{ role: "system", content: blocks.map((b) => b.text).join("\n\n") }];
450
+ }
451
+ function toWireMessages(msg) {
452
+ switch (msg.role) {
453
+ case "user":
454
+ return [{ role: "user", content: msg.blocks.map(toUserContentPart2) }];
455
+ case "assistant":
456
+ return [toAssistantMessage(msg.blocks)];
457
+ case "tool":
458
+ return msg.blocks.map(toToolMessage);
459
+ }
460
+ }
461
+ function toUserContentPart2(block) {
462
+ switch (block.type) {
463
+ case "text":
464
+ return { type: "text", text: block.text };
465
+ case "media":
466
+ if (block.kind === "image") {
467
+ return { type: "image_url", image_url: { url: block.ref.uri } };
468
+ }
469
+ throw new OpenRouterTranslationError(
470
+ `${block.kind} media is not supported by the OpenRouter adapter`
471
+ );
472
+ default:
473
+ throw new OpenRouterTranslationError(
474
+ `block type ${JSON.stringify(block.type)} is not valid in a user message`
475
+ );
476
+ }
477
+ }
478
+ function toAssistantMessage(blocks) {
479
+ let text = "";
480
+ const toolCalls = [];
481
+ for (const block of blocks) {
482
+ switch (block.type) {
483
+ case "text":
484
+ text += block.text;
485
+ break;
486
+ case "tool_call":
487
+ toolCalls.push({
488
+ id: block.id,
489
+ type: "function",
490
+ function: { name: block.name, arguments: JSON.stringify(block.input) }
491
+ });
492
+ break;
493
+ default:
494
+ throw new OpenRouterTranslationError(
495
+ `block type ${JSON.stringify(block.type)} is not valid in an assistant message`
496
+ );
497
+ }
498
+ }
499
+ const message = {
500
+ role: "assistant",
501
+ content: text === "" ? null : text
502
+ };
503
+ if (toolCalls.length > 0) message.tool_calls = toolCalls;
504
+ return message;
505
+ }
506
+ function toToolMessage(block) {
507
+ if (block.type !== "tool_result") {
508
+ throw new OpenRouterTranslationError(
509
+ `block type ${JSON.stringify(block.type)} is not valid in a tool message`
510
+ );
511
+ }
512
+ const serialized = typeof block.output === "string" ? block.output : JSON.stringify(block.output) ?? "null";
513
+ return {
514
+ role: "tool",
515
+ tool_call_id: block.callId,
516
+ // No is_error flag on this wire either — the explicit prefix keeps
517
+ // failures visible to the model (spec 003's precedent).
518
+ content: block.isError ? `ERROR: ${serialized}` : serialized
519
+ };
520
+ }
521
+ function toTool3(spec) {
522
+ return {
523
+ type: "function",
524
+ function: {
525
+ name: spec.name,
526
+ description: spec.description,
527
+ parameters: spec.inputSchema
528
+ }
529
+ };
530
+ }
531
+ async function* translateOpenRouterStream(chunks) {
532
+ const pendingTools = /* @__PURE__ */ new Map();
533
+ let finish = null;
534
+ let usage = null;
535
+ let toolsEmitted = false;
536
+ for await (const chunk of chunks) {
537
+ const choice = chunk.choices[0];
538
+ if (choice) {
539
+ if (choice.delta.content != null && choice.delta.content !== "") {
540
+ yield { type: "text_delta", text: choice.delta.content };
541
+ }
542
+ for (const fragment of choice.delta.tool_calls ?? []) {
543
+ const pending = pendingTools.get(fragment.index) ?? { id: "", name: "", json: "" };
544
+ if (fragment.id != null) pending.id = fragment.id;
545
+ if (fragment.function?.name != null) pending.name = fragment.function.name;
546
+ if (fragment.function?.arguments != null) pending.json += fragment.function.arguments;
547
+ pendingTools.set(fragment.index, pending);
548
+ }
549
+ if (choice.finish_reason != null) {
550
+ finish = choice.finish_reason;
551
+ if (!toolsEmitted) {
552
+ toolsEmitted = true;
553
+ for (const [, call] of [...pendingTools.entries()].sort(([a], [b]) => a - b)) {
554
+ yield {
555
+ type: "tool_call",
556
+ id: call.id,
557
+ name: call.name,
558
+ input: call.json === "" ? {} : JSON.parse(call.json)
559
+ };
560
+ }
561
+ pendingTools.clear();
562
+ }
563
+ }
564
+ }
565
+ if (chunk.usage != null) {
566
+ const cachedRead = chunk.usage.prompt_tokens_details?.cached_tokens ?? 0;
567
+ usage = {
568
+ // Neutral semantics (spec 005): inputTokens EXCLUDES cache reads —
569
+ // the wire's prompt_tokens includes them.
570
+ inputTokens: Math.max(0, chunk.usage.prompt_tokens - cachedRead),
571
+ outputTokens: chunk.usage.completion_tokens
572
+ };
573
+ if (cachedRead > 0) usage.cacheReadInputTokens = cachedRead;
574
+ }
575
+ }
576
+ if (finish === null) {
577
+ throw new OpenRouterTranslationError(
578
+ "OpenRouter stream ended without a finish_reason \u2014 provider drift?"
579
+ );
580
+ }
581
+ if (usage !== null) yield { type: "usage", usage };
582
+ yield { type: "stop", reason: mapFinishReason(finish) };
583
+ }
584
+ function mapFinishReason(reason) {
585
+ switch (reason) {
586
+ case "stop":
587
+ return "end_turn";
588
+ case "tool_calls":
589
+ return "tool_use";
590
+ case "length":
591
+ return "max_tokens";
592
+ case "content_filter":
593
+ return "refusal";
594
+ default:
595
+ throw new OpenRouterTranslationError(
596
+ `Unmapped OpenRouter finish_reason ${JSON.stringify(reason)} \u2014 provider drift?`
597
+ );
598
+ }
599
+ }
600
+
601
+ // src/openrouter/client.ts
602
+ var OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1";
603
+ var OpenRouterModelClient = class {
604
+ #client;
605
+ #routing;
606
+ constructor(opts) {
607
+ if (!Array.isArray(opts.upstreams) || opts.upstreams.length === 0) {
608
+ throw new Error(
609
+ "OpenRouterModelClient requires a non-empty `upstreams` allowlist \u2014 for a gateway, the data-processing chain must be a declared fact (spec 014)"
610
+ );
611
+ }
612
+ const routing = { upstreams: [...opts.upstreams] };
613
+ if (opts.allowFallbacks !== void 0) routing.allowFallbacks = opts.allowFallbacks;
614
+ if (opts.dataCollection !== void 0) routing.dataCollection = opts.dataCollection;
615
+ if (opts.zeroDataRetention !== void 0) routing.zeroDataRetention = opts.zeroDataRetention;
616
+ this.#routing = routing;
617
+ const apiKey = opts.apiKey ?? process.env["OPENROUTER_API_KEY"];
618
+ if (apiKey === void 0 || apiKey === "") {
619
+ throw new Error(
620
+ "OpenRouterModelClient needs an API key: pass `apiKey` or set OPENROUTER_API_KEY"
621
+ );
622
+ }
623
+ this.#client = new OpenAI2({ apiKey, baseURL: opts.baseURL ?? OPENROUTER_BASE_URL });
624
+ }
625
+ stream(req, opts) {
626
+ const params = toOpenRouterParams(req, this.#routing);
627
+ return translateOpenRouterStream(this.#rawChunks(params, opts?.signal));
628
+ }
629
+ async *#rawChunks(params, signal) {
630
+ const stream = await this.#client.chat.completions.create(
631
+ params,
632
+ signal !== void 0 ? { signal } : void 0
633
+ );
634
+ for await (const chunk of stream) yield chunk;
635
+ }
636
+ };
637
+
638
+ // src/index.ts
639
+ var SUPPORTED_PROVIDERS = ["anthropic", "openai", "openrouter"];
640
+ export {
641
+ AnthropicModelClient,
642
+ AnthropicTranslationError,
643
+ OpenAIModelClient,
644
+ OpenAITranslationError,
645
+ OpenRouterModelClient,
646
+ OpenRouterTranslationError,
647
+ SUPPORTED_PROVIDERS,
648
+ toAnthropicParams,
649
+ toOpenAIParams,
650
+ toOpenRouterParams,
651
+ translateOpenAIStream,
652
+ translateOpenRouterStream,
653
+ translateStream
654
+ };
655
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/anthropic/client.ts","../src/anthropic/translate.ts","../src/openai/client.ts","../src/openai/translate.ts","../src/openrouter/client.ts","../src/openrouter/translate.ts","../src/index.ts"],"sourcesContent":["import Anthropic from \"@anthropic-ai/sdk\";\nimport type { ModelClient, ModelEvent, ModelRequest } from \"@alma-harness/core\";\n\nimport { toAnthropicParams, translateStream } from \"./translate\";\n\nexport interface AnthropicModelClientOptions {\n /** Omit to use the SDK's environment resolution (ANTHROPIC_API_KEY, …). */\n apiKey?: string;\n baseURL?: string;\n}\n\n/**\n * `ModelClient` adapter for the Anthropic Messages API — §6.2, spec 002.\n * A thin shell: request/stream translation lives in ./translate (pure);\n * this class only owns the SDK client. SDK typed errors propagate as-is.\n */\nexport class AnthropicModelClient implements ModelClient {\n readonly #client: Anthropic;\n\n constructor(opts: AnthropicModelClientOptions = {}) {\n const init: ConstructorParameters<typeof Anthropic>[0] = {};\n if (opts.apiKey !== undefined) init.apiKey = opts.apiKey;\n if (opts.baseURL !== undefined) init.baseURL = opts.baseURL;\n this.#client = new Anthropic(init);\n }\n\n stream(req: ModelRequest, opts?: { signal?: AbortSignal }): AsyncIterable<ModelEvent> {\n // Translation throws synchronously (wrong provider, unsupported blocks)\n // before any network activity — spec 002 criterion 5.\n const params = toAnthropicParams(req);\n return translateStream(this.#rawEvents(params, opts?.signal));\n }\n\n async *#rawEvents(\n params: Anthropic.MessageCreateParamsStreaming,\n signal?: AbortSignal,\n ): AsyncGenerator<Anthropic.RawMessageStreamEvent> {\n const stream = await this.#client.messages.create(\n params,\n signal !== undefined ? { signal } : undefined,\n );\n for await (const event of stream) yield event;\n }\n}\n","import type Anthropic from \"@anthropic-ai/sdk\";\n\nimport type {\n Block,\n ModelEvent,\n ModelRequest,\n Msg,\n StopReason,\n SystemBlock,\n ToolSpec,\n Usage,\n} from \"@alma-harness/core\";\n\n/**\n * Pure translation between Alma's neutral vocabulary (§6.2) and the Anthropic\n * Messages API — spec 002. Everything here is side-effect-free so the wire\n * mapping is testable without a network.\n */\n\n/** Raised when a request or stream cannot be represented faithfully. */\nexport class AnthropicTranslationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AnthropicTranslationError\";\n }\n}\n\nexport function toAnthropicParams(req: ModelRequest): Anthropic.MessageCreateParamsStreaming {\n if (req.model.provider !== \"anthropic\") {\n throw new AnthropicTranslationError(\n `AnthropicModelClient received a request for provider ${JSON.stringify(req.model.provider)}`,\n );\n }\n const params: Anthropic.MessageCreateParamsStreaming = {\n model: req.model.id,\n max_tokens: req.maxTokens,\n stream: true,\n system: toSystem(req.system),\n messages: req.messages.map(toMessageParam),\n };\n if (req.tools.length > 0) params.tools = req.tools.map(toTool);\n markConversationTail(params.messages);\n return params;\n}\n\n/**\n * Cache continuation — spec 005: a second breakpoint on the conversation\n * tail lets multi-turn sessions pay incremental tokens instead of re-reading\n * the whole history every turn. (Budget: 2 of the 4 allowed breakpoints —\n * one at the stable-system boundary, one here.)\n */\nfunction markConversationTail(messages: Anthropic.MessageParam[]): void {\n const last = messages.at(-1);\n if (!last || typeof last.content === \"string\") return;\n const block = last.content.at(-1);\n if (block) (block as { cache_control?: Anthropic.CacheControlEphemeral }).cache_control = { type: \"ephemeral\" };\n}\n\n/**\n * The §6.9 stable/volatile boundary becomes the cache boundary: one\n * `cache_control` breakpoint on the LAST stable block, volatile blocks after\n * it. Order is preserved — callers must already emit stable-first.\n */\nfunction toSystem(blocks: SystemBlock[]): Anthropic.TextBlockParam[] {\n const lastStable = blocks.reduce(\n (last, b, i) => (b.volatility === \"stable\" ? i : last),\n -1,\n );\n return blocks.map((b, i) => {\n const param: Anthropic.TextBlockParam = { type: \"text\", text: b.text };\n if (i === lastStable) param.cache_control = { type: \"ephemeral\" };\n return param;\n });\n}\n\nfunction toMessageParam(msg: Msg): Anthropic.MessageParam {\n switch (msg.role) {\n case \"user\":\n return { role: \"user\", content: msg.blocks.map(toUserBlock) };\n case \"assistant\":\n return { role: \"assistant\", content: msg.blocks.map(toAssistantBlock) };\n case \"tool\":\n // Anthropic's wire shape: tool results travel in a user-role message.\n return { role: \"user\", content: msg.blocks.map(toToolResultBlock) };\n }\n}\n\nfunction toUserBlock(block: Block): Anthropic.ContentBlockParam {\n switch (block.type) {\n case \"text\":\n return { type: \"text\", text: block.text };\n case \"media\":\n switch (block.kind) {\n case \"image\":\n return { type: \"image\", source: { type: \"url\", url: block.ref.uri } };\n case \"document\":\n return { type: \"document\", source: { type: \"url\", url: block.ref.uri } };\n case \"audio\":\n // The Messages API takes no raw audio; products transcribe upstream.\n throw new AnthropicTranslationError(\"audio media is not supported by the Anthropic adapter\");\n }\n default:\n throw new AnthropicTranslationError(`block type ${JSON.stringify(block.type)} is not valid in a user message`);\n }\n}\n\nfunction toAssistantBlock(block: Block): Anthropic.ContentBlockParam {\n switch (block.type) {\n case \"text\":\n return { type: \"text\", text: block.text };\n case \"tool_call\":\n return { type: \"tool_use\", id: block.id, name: block.name, input: block.input };\n default:\n throw new AnthropicTranslationError(\n `block type ${JSON.stringify(block.type)} is not valid in an assistant message`,\n );\n }\n}\n\nfunction toToolResultBlock(block: Block): Anthropic.ToolResultBlockParam {\n if (block.type !== \"tool_result\") {\n throw new AnthropicTranslationError(\n `block type ${JSON.stringify(block.type)} is not valid in a tool message`,\n );\n }\n const param: Anthropic.ToolResultBlockParam = {\n type: \"tool_result\",\n tool_use_id: block.callId,\n // JSON.stringify yields undefined (not a string) for undefined/functions;\n // \"null\" keeps the content explicit for void tool outputs.\n content:\n typeof block.output === \"string\" ? block.output : (JSON.stringify(block.output) ?? \"null\"),\n };\n if (block.isError) param.is_error = true;\n return param;\n}\n\nfunction toTool(spec: ToolSpec): Anthropic.Tool {\n return {\n name: spec.name,\n description: spec.description,\n // The registry already derived a JSON Schema object (§6.4).\n input_schema: spec.inputSchema as Anthropic.Tool.InputSchema,\n };\n}\n\n/**\n * Raw SDK stream → neutral `ModelEvent`s. Tool inputs arrive as\n * `input_json_delta` fragments; they are accumulated per content block and\n * emitted as ONE `tool_call` with parsed input at `content_block_stop`.\n * Usage is aggregated (input + cache fields from `message_start`, output from\n * `message_delta`) and emitted once before the final `stop`.\n */\nexport async function* translateStream(\n events: AsyncIterable<Anthropic.RawMessageStreamEvent>,\n): AsyncGenerator<ModelEvent> {\n const usage: Usage = { inputTokens: 0, outputTokens: 0 };\n let stopReason: Anthropic.Message[\"stop_reason\"] = null;\n const pendingTools = new Map<number, { id: string; name: string; json: string }>();\n\n for await (const event of events) {\n switch (event.type) {\n case \"message_start\": {\n const u = event.message.usage;\n usage.inputTokens = u.input_tokens;\n if (u.cache_read_input_tokens != null) usage.cacheReadInputTokens = u.cache_read_input_tokens;\n if (u.cache_creation_input_tokens != null) {\n usage.cacheWriteInputTokens = u.cache_creation_input_tokens;\n }\n break;\n }\n case \"content_block_start\":\n if (event.content_block.type === \"tool_use\") {\n pendingTools.set(event.index, {\n id: event.content_block.id,\n name: event.content_block.name,\n json: \"\",\n });\n }\n break;\n case \"content_block_delta\":\n if (event.delta.type === \"text_delta\") {\n yield { type: \"text_delta\", text: event.delta.text };\n } else if (event.delta.type === \"input_json_delta\") {\n const pending = pendingTools.get(event.index);\n if (pending) pending.json += event.delta.partial_json;\n }\n break;\n case \"content_block_stop\": {\n const pending = pendingTools.get(event.index);\n if (pending) {\n pendingTools.delete(event.index);\n yield {\n type: \"tool_call\",\n id: pending.id,\n name: pending.name,\n input: pending.json === \"\" ? {} : (JSON.parse(pending.json) as unknown),\n };\n }\n break;\n }\n case \"message_delta\":\n if (event.delta.stop_reason != null) stopReason = event.delta.stop_reason;\n usage.outputTokens = event.usage.output_tokens;\n break;\n case \"message_stop\":\n yield { type: \"usage\", usage: { ...usage } };\n yield { type: \"stop\", reason: mapStopReason(stopReason) };\n break;\n }\n }\n}\n\nfunction mapStopReason(reason: Anthropic.Message[\"stop_reason\"]): StopReason {\n switch (reason) {\n case \"end_turn\":\n case \"stop_sequence\":\n return \"end_turn\";\n case \"tool_use\":\n return \"tool_use\";\n case \"max_tokens\":\n return \"max_tokens\";\n case \"refusal\":\n return \"refusal\";\n case \"model_context_window_exceeded\":\n return \"context_window_exceeded\";\n default:\n // pause_turn (server-side tools the harness never declares — spec 002\n // known deferral) or a reason newer than this adapter: refuse loudly\n // rather than silently truncate.\n throw new AnthropicTranslationError(\n `Unmapped Anthropic stop_reason ${JSON.stringify(reason)} — provider drift?`,\n );\n }\n}\n","import OpenAI from \"openai\";\nimport type { ModelClient, ModelEvent, ModelRequest } from \"@alma-harness/core\";\n\nimport { toOpenAIParams, translateOpenAIStream } from \"./translate\";\n\nexport interface OpenAIModelClientOptions {\n /** Omit to use the SDK's environment resolution (OPENAI_API_KEY). */\n apiKey?: string;\n baseURL?: string;\n}\n\n/**\n * `ModelClient` adapter for the OpenAI Responses API — §6.2, spec 003.\n * A thin shell: request/stream translation lives in ./translate (pure);\n * this class only owns the SDK client. SDK typed errors propagate as-is.\n */\nexport class OpenAIModelClient implements ModelClient {\n readonly #client: OpenAI;\n\n constructor(opts: OpenAIModelClientOptions = {}) {\n const init: ConstructorParameters<typeof OpenAI>[0] = {};\n if (opts.apiKey !== undefined) init.apiKey = opts.apiKey;\n if (opts.baseURL !== undefined) init.baseURL = opts.baseURL;\n this.#client = new OpenAI(init);\n }\n\n stream(req: ModelRequest, opts?: { signal?: AbortSignal }): AsyncIterable<ModelEvent> {\n // Translation throws synchronously (wrong provider, unsupported blocks)\n // before any network activity — spec 003 criterion 6.\n const params = toOpenAIParams(req);\n return translateOpenAIStream(this.#rawEvents(params, opts?.signal));\n }\n\n async *#rawEvents(\n params: OpenAI.Responses.ResponseCreateParamsStreaming,\n signal?: AbortSignal,\n ): AsyncGenerator<OpenAI.Responses.ResponseStreamEvent> {\n const stream = await this.#client.responses.create(\n params,\n signal !== undefined ? { signal } : undefined,\n );\n for await (const event of stream) yield event;\n }\n}\n","import type OpenAI from \"openai\";\n\nimport type {\n Block,\n ModelEvent,\n ModelRequest,\n Msg,\n StopReason,\n SystemBlock,\n ToolSpec,\n Usage,\n} from \"@alma-harness/core\";\n\n/**\n * Pure translation between Alma's neutral vocabulary (§6.2) and the OpenAI\n * Responses API — spec 003. Side-effect-free; testable without a network.\n */\n\nexport class OpenAITranslationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"OpenAITranslationError\";\n }\n}\n\nexport function toOpenAIParams(\n req: ModelRequest,\n): OpenAI.Responses.ResponseCreateParamsStreaming {\n if (req.model.provider !== \"openai\") {\n throw new OpenAITranslationError(\n `OpenAIModelClient received a request for provider ${JSON.stringify(req.model.provider)}`,\n );\n }\n const params: OpenAI.Responses.ResponseCreateParamsStreaming = {\n model: req.model.id,\n max_output_tokens: req.maxTokens,\n stream: true,\n // Privacy-first (§3, §10): the Responses API stores responses server-side\n // by default; the harness never leaves conversation state at the provider.\n store: false,\n input: req.messages.flatMap(toInputItems),\n };\n const instructions = toInstructions(req.system);\n if (instructions !== \"\") params.instructions = instructions;\n if (req.tools.length > 0) params.tools = req.tools.map(toTool);\n return params;\n}\n\n/**\n * OpenAI has no explicit cache breakpoint (prefix caching is automatic), so\n * the §6.9 stable/volatile discipline is preserved simply by keeping the\n * blocks' order — stable first — in one instructions string.\n */\nfunction toInstructions(blocks: SystemBlock[]): string {\n return blocks.map((b) => b.text).join(\"\\n\\n\");\n}\n\nfunction toInputItems(msg: Msg): OpenAI.Responses.ResponseInputItem[] {\n switch (msg.role) {\n case \"user\":\n return [{ role: \"user\", content: msg.blocks.map(toUserContentPart) }];\n case \"assistant\":\n // Text stays a message item; each tool_call becomes its own top-level\n // function_call item, preserving block order.\n return msg.blocks.map(toAssistantItem);\n case \"tool\":\n return msg.blocks.map(toFunctionCallOutput);\n }\n}\n\nfunction toUserContentPart(\n block: Block,\n): OpenAI.Responses.ResponseInputText | OpenAI.Responses.ResponseInputImage {\n switch (block.type) {\n case \"text\":\n return { type: \"input_text\", text: block.text };\n case \"media\":\n if (block.kind === \"image\") {\n return { type: \"input_image\", detail: \"auto\", image_url: block.ref.uri };\n }\n // Documents/audio on the Responses input surface are file-id-centric,\n // which breaks media-by-reference (§6.1) — fail loudly (spec 003):\n // the routing policy is the layer that picks capable providers.\n throw new OpenAITranslationError(\n `${block.kind} media is not supported by the OpenAI adapter`,\n );\n default:\n throw new OpenAITranslationError(\n `block type ${JSON.stringify(block.type)} is not valid in a user message`,\n );\n }\n}\n\nfunction toAssistantItem(block: Block): OpenAI.Responses.ResponseInputItem {\n switch (block.type) {\n case \"text\":\n return { role: \"assistant\", content: block.text };\n case \"tool_call\":\n return {\n type: \"function_call\",\n call_id: block.id,\n name: block.name,\n arguments: JSON.stringify(block.input),\n };\n default:\n throw new OpenAITranslationError(\n `block type ${JSON.stringify(block.type)} is not valid in an assistant message`,\n );\n }\n}\n\nfunction toFunctionCallOutput(block: Block): OpenAI.Responses.ResponseInputItem {\n if (block.type !== \"tool_result\") {\n throw new OpenAITranslationError(\n `block type ${JSON.stringify(block.type)} is not valid in a tool message`,\n );\n }\n const serialized =\n typeof block.output === \"string\" ? block.output : (JSON.stringify(block.output) ?? \"null\");\n return {\n type: \"function_call_output\",\n call_id: block.callId,\n // The Responses API has no is_error flag on function outputs — an\n // explicit prefix keeps failures visible to the model (spec 003).\n output: block.isError ? `ERROR: ${serialized}` : serialized,\n };\n}\n\nfunction toTool(spec: ToolSpec): OpenAI.Responses.FunctionTool {\n return {\n type: \"function\",\n name: spec.name,\n description: spec.description,\n parameters: spec.inputSchema,\n // Registry-derived schemas are not guaranteed strict-compatible; the\n // structured-output surface is a follow-up slice (spec 003 decision).\n strict: false,\n };\n}\n\n/**\n * Semantic stream events → neutral `ModelEvent`s. Function-call arguments\n * arrive complete on `response.output_item.done`, so each call is emitted as\n * ONE parsed `tool_call`. The terminal `response.completed` / `.incomplete`\n * event carries usage; `tool_use` is inferred from having emitted tool calls\n * (the Responses API has no finish_reason).\n */\nexport async function* translateOpenAIStream(\n events: AsyncIterable<OpenAI.Responses.ResponseStreamEvent>,\n): AsyncGenerator<ModelEvent> {\n let sawToolCall = false;\n let sawRefusal = false;\n\n for await (const event of events) {\n switch (event.type) {\n case \"response.output_text.delta\":\n yield { type: \"text_delta\", text: event.delta };\n break;\n case \"response.refusal.delta\":\n // Refusal content is user-visible text; the stop reason records the\n // refusal itself (spec 003).\n sawRefusal = true;\n yield { type: \"text_delta\", text: event.delta };\n break;\n case \"response.output_item.done\":\n if (event.item.type === \"function_call\") {\n sawToolCall = true;\n yield {\n type: \"tool_call\",\n id: event.item.call_id,\n name: event.item.name,\n input:\n event.item.arguments === \"\" ? {} : (JSON.parse(event.item.arguments) as unknown),\n };\n }\n break;\n case \"response.completed\":\n yield usageEvent(event.response);\n yield { type: \"stop\", reason: sawRefusal ? \"refusal\" : sawToolCall ? \"tool_use\" : \"end_turn\" };\n break;\n case \"response.incomplete\": {\n yield usageEvent(event.response);\n yield { type: \"stop\", reason: mapIncompleteReason(event.response) };\n break;\n }\n case \"response.failed\": {\n const err = event.response.error;\n throw new OpenAITranslationError(\n `OpenAI response failed: ${err ? `${err.code}: ${err.message}` : \"unknown error\"}`,\n );\n }\n case \"error\":\n throw new OpenAITranslationError(`OpenAI stream error: ${event.message}`);\n default:\n // created / in_progress / content parts / argument deltas etc. carry\n // no neutral information beyond the events handled above.\n break;\n }\n }\n}\n\nfunction usageEvent(response: OpenAI.Responses.Response): ModelEvent {\n const u = response.usage;\n const cachedRead = u?.input_tokens_details?.cached_tokens ?? 0;\n const usage: Usage = {\n // Neutral semantics (spec 005): inputTokens EXCLUDES cache reads.\n // OpenAI's input_tokens includes cached_tokens; subtract to normalize —\n // otherwise the BudgetGuard would price the same conversation\n // differently per provider.\n inputTokens: Math.max(0, (u?.input_tokens ?? 0) - cachedRead),\n outputTokens: u?.output_tokens ?? 0,\n };\n if (cachedRead > 0) usage.cacheReadInputTokens = cachedRead;\n const cacheWrite = u?.input_tokens_details?.cache_write_tokens;\n if (cacheWrite !== undefined && cacheWrite > 0) usage.cacheWriteInputTokens = cacheWrite;\n return { type: \"usage\", usage };\n}\n\nfunction mapIncompleteReason(response: OpenAI.Responses.Response): StopReason {\n const reason = response.incomplete_details?.reason;\n switch (reason) {\n case \"max_output_tokens\":\n // NOTE (spec 003 decision): OpenAI's wire conflates context-window\n // exhaustion into this reason (or a 400 before the stream), so the\n // neutral \"context_window_exceeded\" is unreachable on this adapter —\n // the long-context policy must watch provider errors instead.\n return \"max_tokens\";\n case \"content_filter\":\n return \"refusal\";\n default:\n throw new OpenAITranslationError(\n `Unmapped OpenAI incomplete reason ${JSON.stringify(reason)} — provider drift?`,\n );\n }\n}\n","import OpenAI from \"openai\";\nimport type { ModelClient, ModelEvent, ModelRequest } from \"@alma-harness/core\";\n\nimport {\n toOpenRouterParams,\n translateOpenRouterStream,\n type OpenRouterParams,\n type OpenRouterRouting,\n} from \"./translate\";\n\nexport interface OpenRouterModelClientOptions extends OpenRouterRouting {\n /** Omit to read OPENROUTER_API_KEY (the OpenAI SDK's own env resolution\n * would read OPENAI_API_KEY — the wrong credential for this gateway). */\n apiKey?: string;\n /** Defaults to OpenRouter's public endpoint. */\n baseURL?: string;\n}\n\nconst OPENROUTER_BASE_URL = \"https://openrouter.ai/api/v1\";\n\n/**\n * `ModelClient` adapter for OpenRouter — §6.2, spec 014 (the gateway bridge).\n * Same thin-shell shape as the first-party adapters: translation lives in\n * ./translate (pure); this class owns the SDK client and the DECLARED\n * upstream policy. A gateway erases \"who processed this data?\" unless the\n * chain is declared beforehand, so construction REFUSES to proceed without a\n * non-empty upstream allowlist — deciding after the fact enforces nothing.\n */\nexport class OpenRouterModelClient implements ModelClient {\n readonly #client: OpenAI;\n readonly #routing: OpenRouterRouting;\n\n constructor(opts: OpenRouterModelClientOptions) {\n if (!Array.isArray(opts.upstreams) || opts.upstreams.length === 0) {\n throw new Error(\n \"OpenRouterModelClient requires a non-empty `upstreams` allowlist — \" +\n \"for a gateway, the data-processing chain must be a declared fact (spec 014)\",\n );\n }\n const routing: OpenRouterRouting = { upstreams: [...opts.upstreams] };\n if (opts.allowFallbacks !== undefined) routing.allowFallbacks = opts.allowFallbacks;\n if (opts.dataCollection !== undefined) routing.dataCollection = opts.dataCollection;\n if (opts.zeroDataRetention !== undefined) routing.zeroDataRetention = opts.zeroDataRetention;\n this.#routing = routing;\n\n const apiKey = opts.apiKey ?? process.env[\"OPENROUTER_API_KEY\"];\n if (apiKey === undefined || apiKey === \"\") {\n throw new Error(\n \"OpenRouterModelClient needs an API key: pass `apiKey` or set OPENROUTER_API_KEY\",\n );\n }\n this.#client = new OpenAI({ apiKey, baseURL: opts.baseURL ?? OPENROUTER_BASE_URL });\n }\n\n stream(req: ModelRequest, opts?: { signal?: AbortSignal }): AsyncIterable<ModelEvent> {\n // Translation throws synchronously (wrong provider, unsupported blocks)\n // before any network activity, like every adapter in this package.\n const params = toOpenRouterParams(req, this.#routing);\n return translateOpenRouterStream(this.#rawChunks(params, opts?.signal));\n }\n\n async *#rawChunks(\n params: OpenRouterParams,\n signal?: AbortSignal,\n ): AsyncGenerator<OpenAI.Chat.Completions.ChatCompletionChunk> {\n const stream = await this.#client.chat.completions.create(\n params,\n signal !== undefined ? { signal } : undefined,\n );\n for await (const chunk of stream) yield chunk;\n }\n}\n","import type OpenAI from \"openai\";\n\nimport type {\n Block,\n ModelEvent,\n ModelRequest,\n Msg,\n StopReason,\n SystemBlock,\n ToolSpec,\n Usage,\n} from \"@alma-harness/core\";\n\n/**\n * Pure translation between Alma's neutral vocabulary (§6.2) and OpenRouter's\n * chat-completions wire — spec 014. A SECOND translator over the neutral\n * format, not a `baseURL` override: the first-party OpenAI adapter speaks the\n * Responses API, and nothing in its translation is reusable here.\n * Side-effect-free; testable without a network.\n */\n\nexport class OpenRouterTranslationError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"OpenRouterTranslationError\";\n }\n}\n\n/**\n * The upstream routing policy — spec 014's core constraint: for a gateway,\n * \"who processed this data?\" must be a DECLARED fact, not an observed one.\n */\nexport interface OpenRouterRouting {\n /**\n * OpenRouter provider slugs allowed to serve requests (→ `provider.only`).\n * REQUIRED and non-empty: without it the data-processing chain has no\n * answer, so the client refuses to construct.\n */\n upstreams: readonly string[];\n /**\n * Default false: a fallback is a silent change of data processor. Enabling\n * it is a stated product choice, never a default.\n */\n allowFallbacks?: boolean;\n /**\n * Default \"deny\" — OpenRouter defaults to \"allow\", and a harness whose\n * README says \"operating on sensitive data\" must not inherit the permissive\n * default (spec 014 DECISION).\n */\n dataCollection?: \"allow\" | \"deny\";\n /** Opt-in pass-through to OpenRouter's zero-data-retention guarantee. */\n zeroDataRetention?: boolean;\n}\n\n/** The `provider` routing block OpenRouter accepts on every request. */\ninterface OpenRouterProviderBlock {\n only: string[];\n allow_fallbacks: boolean;\n data_collection: \"allow\" | \"deny\";\n zdr?: boolean;\n require_parameters?: boolean;\n}\n\nexport type OpenRouterParams = OpenAI.Chat.Completions.ChatCompletionCreateParamsStreaming & {\n provider: OpenRouterProviderBlock;\n};\n\nexport function toOpenRouterParams(req: ModelRequest, routing: OpenRouterRouting): OpenRouterParams {\n if (req.model.provider !== \"openrouter\") {\n throw new OpenRouterTranslationError(\n `OpenRouterModelClient received a request for provider ${JSON.stringify(req.model.provider)}`,\n );\n }\n const provider: OpenRouterProviderBlock = {\n only: [...routing.upstreams],\n allow_fallbacks: routing.allowFallbacks ?? false,\n data_collection: routing.dataCollection ?? \"deny\",\n };\n if (routing.zeroDataRetention === true) provider.zdr = true;\n if (req.tools.length > 0) {\n // Not cosmetic (spec 014): tool support varies by upstream, and without\n // this a model can receive the request WITHOUT the tools it was supposed\n // to have — a silent capability failure for a loop whose control flow IS\n // tool calls.\n provider.require_parameters = true;\n }\n\n const params: OpenRouterParams = {\n model: req.model.id,\n // The SDK deprecates this in favor of the OpenAI-specific\n // max_completion_tokens; for a gateway fronting heterogeneous upstreams,\n // max_tokens is the common denominator OpenRouter documents.\n max_tokens: req.maxTokens,\n stream: true,\n // Review amendment (spec 014): streamed chat completions only carry usage\n // when asked — without this the BudgetGuard never sees a usage event.\n stream_options: { include_usage: true },\n messages: [...systemMessages(req.system), ...req.messages.flatMap(toWireMessages)],\n provider,\n };\n if (req.tools.length > 0) params.tools = req.tools.map(toTool);\n return params;\n}\n\n/**\n * Chat completions has no instructions field; system blocks become one system\n * message. The §6.9 stable/volatile discipline is preserved by keeping the\n * blocks' order — stable first — exactly as the OpenAI adapter does; whether\n * an upstream caches the prefix varies (spec 014's cache-hygiene note).\n */\nfunction systemMessages(\n blocks: SystemBlock[],\n): OpenAI.Chat.Completions.ChatCompletionMessageParam[] {\n if (blocks.length === 0) return [];\n return [{ role: \"system\", content: blocks.map((b) => b.text).join(\"\\n\\n\") }];\n}\n\nfunction toWireMessages(msg: Msg): OpenAI.Chat.Completions.ChatCompletionMessageParam[] {\n switch (msg.role) {\n case \"user\":\n return [{ role: \"user\", content: msg.blocks.map(toUserContentPart) }];\n case \"assistant\":\n return [toAssistantMessage(msg.blocks)];\n case \"tool\":\n // Chat completions wants one tool-role message PER result, keyed by\n // tool_call_id — unlike Anthropic's single user message of results.\n return msg.blocks.map(toToolMessage);\n }\n}\n\nfunction toUserContentPart(block: Block): OpenAI.Chat.Completions.ChatCompletionContentPart {\n switch (block.type) {\n case \"text\":\n return { type: \"text\", text: block.text };\n case \"media\":\n if (block.kind === \"image\") {\n return { type: \"image_url\", image_url: { url: block.ref.uri } };\n }\n // Document/audio support varies wildly by upstream and the wire shapes\n // are provider-specific — fail loudly (the routing policy is the layer\n // that picks capable providers, spec 003's precedent).\n throw new OpenRouterTranslationError(\n `${block.kind} media is not supported by the OpenRouter adapter`,\n );\n default:\n throw new OpenRouterTranslationError(\n `block type ${JSON.stringify(block.type)} is not valid in a user message`,\n );\n }\n}\n\nfunction toAssistantMessage(blocks: Block[]): OpenAI.Chat.Completions.ChatCompletionMessageParam {\n let text = \"\";\n const toolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];\n for (const block of blocks) {\n switch (block.type) {\n case \"text\":\n text += block.text;\n break;\n case \"tool_call\":\n toolCalls.push({\n id: block.id,\n type: \"function\",\n function: { name: block.name, arguments: JSON.stringify(block.input) },\n });\n break;\n default:\n throw new OpenRouterTranslationError(\n `block type ${JSON.stringify(block.type)} is not valid in an assistant message`,\n );\n }\n }\n const message: OpenAI.Chat.Completions.ChatCompletionAssistantMessageParam = {\n role: \"assistant\",\n content: text === \"\" ? null : text,\n };\n if (toolCalls.length > 0) message.tool_calls = toolCalls;\n return message;\n}\n\nfunction toToolMessage(block: Block): OpenAI.Chat.Completions.ChatCompletionMessageParam {\n if (block.type !== \"tool_result\") {\n throw new OpenRouterTranslationError(\n `block type ${JSON.stringify(block.type)} is not valid in a tool message`,\n );\n }\n const serialized =\n typeof block.output === \"string\" ? block.output : (JSON.stringify(block.output) ?? \"null\");\n return {\n role: \"tool\",\n tool_call_id: block.callId,\n // No is_error flag on this wire either — the explicit prefix keeps\n // failures visible to the model (spec 003's precedent).\n content: block.isError ? `ERROR: ${serialized}` : serialized,\n };\n}\n\nfunction toTool(spec: ToolSpec): OpenAI.Chat.Completions.ChatCompletionTool {\n return {\n type: \"function\",\n function: {\n name: spec.name,\n description: spec.description,\n parameters: spec.inputSchema,\n },\n };\n}\n\n/**\n * Chat-completion chunks → neutral `ModelEvent`s. Tool-call arguments arrive\n * as indexed fragments (id and name on the first fragment, argument pieces on\n * the rest); they are accumulated per index and emitted as ONE parsed\n * `tool_call` each when the choice finishes. The usage chunk arrives AFTER\n * `finish_reason` (with `stream_options.include_usage`), so the terminal\n * usage + stop pair is emitted at stream end — same order every adapter emits.\n */\nexport async function* translateOpenRouterStream(\n chunks: AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>,\n): AsyncGenerator<ModelEvent> {\n const pendingTools = new Map<number, { id: string; name: string; json: string }>();\n let finish: string | null = null;\n let usage: Usage | null = null;\n let toolsEmitted = false;\n\n for await (const chunk of chunks) {\n const choice = chunk.choices[0];\n if (choice) {\n if (choice.delta.content != null && choice.delta.content !== \"\") {\n yield { type: \"text_delta\", text: choice.delta.content };\n }\n for (const fragment of choice.delta.tool_calls ?? []) {\n const pending = pendingTools.get(fragment.index) ?? { id: \"\", name: \"\", json: \"\" };\n if (fragment.id != null) pending.id = fragment.id;\n if (fragment.function?.name != null) pending.name = fragment.function.name;\n if (fragment.function?.arguments != null) pending.json += fragment.function.arguments;\n pendingTools.set(fragment.index, pending);\n }\n if (choice.finish_reason != null) {\n finish = choice.finish_reason;\n if (!toolsEmitted) {\n toolsEmitted = true;\n for (const [, call] of [...pendingTools.entries()].sort(([a], [b]) => a - b)) {\n yield {\n type: \"tool_call\",\n id: call.id,\n name: call.name,\n input: call.json === \"\" ? {} : (JSON.parse(call.json) as unknown),\n };\n }\n pendingTools.clear();\n }\n }\n }\n if (chunk.usage != null) {\n const cachedRead = chunk.usage.prompt_tokens_details?.cached_tokens ?? 0;\n usage = {\n // Neutral semantics (spec 005): inputTokens EXCLUDES cache reads —\n // the wire's prompt_tokens includes them.\n inputTokens: Math.max(0, chunk.usage.prompt_tokens - cachedRead),\n outputTokens: chunk.usage.completion_tokens,\n };\n if (cachedRead > 0) usage.cacheReadInputTokens = cachedRead;\n // No cache-write signal exists on this wire; the field stays absent.\n }\n }\n\n if (finish === null) {\n throw new OpenRouterTranslationError(\n \"OpenRouter stream ended without a finish_reason — provider drift?\",\n );\n }\n if (usage !== null) yield { type: \"usage\", usage };\n yield { type: \"stop\", reason: mapFinishReason(finish) };\n}\n\nfunction mapFinishReason(reason: string): StopReason {\n switch (reason) {\n case \"stop\":\n return \"end_turn\";\n case \"tool_calls\":\n return \"tool_use\";\n case \"length\":\n return \"max_tokens\";\n case \"content_filter\":\n return \"refusal\";\n default:\n // \"error\", or a reason newer than this adapter: refuse loudly rather\n // than silently truncate. NOTE (spec 014 review amendment): context-\n // window overflow arrives as a 400 error before any stream, so the\n // neutral \"context_window_exceeded\" is unreachable on this wire — the\n // long-context policy must watch provider errors, as with the OpenAI\n // adapter.\n throw new OpenRouterTranslationError(\n `Unmapped OpenRouter finish_reason ${JSON.stringify(reason)} — provider drift?`,\n );\n }\n}\n","import type { ProviderId } from \"@alma-harness/core\";\n\n/**\n * @alma-harness/providers — `ModelClient` adapters (§6.2).\n * Bi-provider from birth — `AnthropicModelClient` (spec 002) and\n * `OpenAIModelClient` (spec 003) — plus the OpenRouter gateway bridge\n * (spec 014), all over the same neutral surface.\n */\n\nexport { AnthropicModelClient } from \"./anthropic/client\";\nexport type { AnthropicModelClientOptions } from \"./anthropic/client\";\nexport {\n AnthropicTranslationError,\n toAnthropicParams,\n translateStream,\n} from \"./anthropic/translate\";\n\nexport { OpenAIModelClient } from \"./openai/client\";\nexport type { OpenAIModelClientOptions } from \"./openai/client\";\nexport {\n OpenAITranslationError,\n toOpenAIParams,\n translateOpenAIStream,\n} from \"./openai/translate\";\n\nexport { OpenRouterModelClient } from \"./openrouter/client\";\nexport type { OpenRouterModelClientOptions } from \"./openrouter/client\";\nexport {\n OpenRouterTranslationError,\n toOpenRouterParams,\n translateOpenRouterStream,\n} from \"./openrouter/translate\";\nexport type { OpenRouterParams, OpenRouterRouting } from \"./openrouter/translate\";\n\nexport type { ModelClient, ModelEvent, ModelRef, ModelRequest, ProviderId } from \"@alma-harness/core\";\n\n/**\n * First-party from birth (§3 principle 4), plus the gateway bridge —\n * spec 014: `openrouter` names the EXIT, not the processor; its adapter\n * requires a declared upstream allowlist for exactly that reason.\n */\nexport const SUPPORTED_PROVIDERS = [\"anthropic\", \"openai\", \"openrouter\"] as const satisfies readonly ProviderId[];\n"],"mappings":";AAAA,OAAO,eAAe;;;ACoBf,IAAM,4BAAN,cAAwC,MAAM;AAAA,EACnD,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;AAEO,SAAS,kBAAkB,KAA2D;AAC3F,MAAI,IAAI,MAAM,aAAa,aAAa;AACtC,UAAM,IAAI;AAAA,MACR,wDAAwD,KAAK,UAAU,IAAI,MAAM,QAAQ,CAAC;AAAA,IAC5F;AAAA,EACF;AACA,QAAM,SAAiD;AAAA,IACrD,OAAO,IAAI,MAAM;AAAA,IACjB,YAAY,IAAI;AAAA,IAChB,QAAQ;AAAA,IACR,QAAQ,SAAS,IAAI,MAAM;AAAA,IAC3B,UAAU,IAAI,SAAS,IAAI,cAAc;AAAA,EAC3C;AACA,MAAI,IAAI,MAAM,SAAS,EAAG,QAAO,QAAQ,IAAI,MAAM,IAAI,MAAM;AAC7D,uBAAqB,OAAO,QAAQ;AACpC,SAAO;AACT;AAQA,SAAS,qBAAqB,UAA0C;AACtE,QAAM,OAAO,SAAS,GAAG,EAAE;AAC3B,MAAI,CAAC,QAAQ,OAAO,KAAK,YAAY,SAAU;AAC/C,QAAM,QAAQ,KAAK,QAAQ,GAAG,EAAE;AAChC,MAAI,MAAO,CAAC,MAA8D,gBAAgB,EAAE,MAAM,YAAY;AAChH;AAOA,SAAS,SAAS,QAAmD;AACnE,QAAM,aAAa,OAAO;AAAA,IACxB,CAAC,MAAM,GAAG,MAAO,EAAE,eAAe,WAAW,IAAI;AAAA,IACjD;AAAA,EACF;AACA,SAAO,OAAO,IAAI,CAAC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.json ADDED
@@ -0,0 +1,46 @@
1
+ {
2
+ "name": "@alma-harness/providers",
3
+ "version": "0.1.0",
4
+ "description": "ModelClient adapters for Anthropic and OpenAI over Alma's neutral message format.",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=22"
9
+ },
10
+ "exports": {
11
+ ".": {
12
+ "types": "./dist/index.d.ts",
13
+ "default": "./dist/index.js"
14
+ }
15
+ },
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "https://github.com/FabioFernandesCarneiro/alma.git",
19
+ "directory": "packages/providers"
20
+ },
21
+ "dependencies": {
22
+ "@anthropic-ai/sdk": "^0.117.1",
23
+ "openai": "^7.5.0"
24
+ },
25
+ "peerDependencies": {
26
+ "@alma-harness/core": "^0.1.0"
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^24.1.0",
30
+ "typescript": "^5.9.2",
31
+ "vitest": "^3.2.4"
32
+ },
33
+ "files": [
34
+ "dist"
35
+ ],
36
+ "publishConfig": {
37
+ "access": "public"
38
+ },
39
+ "scripts": {
40
+ "typecheck": "tsc --noEmit",
41
+ "test": "vitest run",
42
+ "build": "tsup"
43
+ },
44
+ "main": "./dist/index.js",
45
+ "types": "./dist/index.d.ts"
46
+ }