@demicodes/provider 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,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,20 @@
1
+ # @demicodes/provider
2
+
3
+ The provider contract for Demi: one inference interface the runtime talks to, so
4
+ backends (APIs or CLIs) stay decoupled. Also ships the shared building blocks for
5
+ writing providers.
6
+
7
+ - **Contract** — `Provider`, `AgentProvider` (`run()` → `ProviderRun` of
8
+ `ProviderEvent`s), `ProviderSelection`, `ProviderModelList`; `defineProvider`,
9
+ `providerRuntime`, `applyModelPolicy`.
10
+ - **Catalog** — `modelSelectionFromCatalog`, `thinkingCapabilitiesFromProviderModel`,
11
+ `withProviderId`.
12
+ - **HTTP helpers** — `redactSecretText`, `httpErrorCode`, `normalizeErrorCode`,
13
+ `providerErrorFromUnknown`, `authStatusFromKey`, `httpRequestFailedEvent`.
14
+
15
+ ```ts
16
+ import { defineProvider, zeroUsage } from '@demicodes/provider'
17
+ ```
18
+
19
+ See [Add a Provider](../../docs/guides/add-a-provider.md). Part of
20
+ [Demi](../../README.md). Apache-2.0.
@@ -0,0 +1,57 @@
1
+ import { _ as ProviderSelection, a as ModelPolicy, c as ProviderAuthState, d as ProviderModel, f as ProviderModelCost, g as ProviderRuntimeState, h as ProviderRuntimeFactory, i as InferenceSteer, l as ProviderEvent, m as ProviderRun, n as InferenceItem, o as Provider, p as ProviderModelList, r as InferenceRequest, s as ProviderAuth, t as AgentProvider, u as ProviderFactoryDefinition, v as ProviderServiceTier, y as ToolDefinition } from "./types-CGXGUfNJ.mjs";
2
+ import { FileExtension, ModelSelection, ThinkingCapability, ThinkingConfig } from "@demicodes/core";
3
+
4
+ //#region src/provider.d.ts
5
+ declare function defineProvider(definition: ProviderFactoryDefinition): Provider;
6
+ declare function providerRuntime(provider: Provider, selection: ProviderSelection): Promise<AgentProvider> | AgentProvider;
7
+ declare function applyModelPolicy(list: ProviderModelList, providerId: string, policy: ModelPolicy | undefined): ProviderModelList;
8
+ //#endregion
9
+ //#region src/model-selection.d.ts
10
+ /** Stamps `providerId` onto a model catalog and every model in it. */
11
+ declare function withProviderId(list: ProviderModelList, providerId: string): ProviderModelList;
12
+ /** Attachment file types a model is offered when it reports attachment support. */
13
+ declare const DEFAULT_ATTACHMENT_EXTENSIONS: readonly FileExtension[];
14
+ /** Derive the thinking capabilities a UI can offer from a catalog model. */
15
+ declare function thinkingCapabilitiesFromProviderModel(model: ProviderModel | null): ThinkingCapability[];
16
+ interface ModelSelectionFromCatalogOptions {
17
+ /** Override the model id (defaults to `model.id`); useful before the catalog has loaded. */
18
+ modelId?: string;
19
+ /** Active thinking configuration, if any. */
20
+ thinking?: ThinkingConfig | null;
21
+ /** Active service tier, if the model exposes tiers. */
22
+ serviceTierId?: string | null;
23
+ /** Attachment types to accept when the model supports attachments. */
24
+ acceptedExtensions?: readonly FileExtension[];
25
+ /** Display name to use when the catalog entry is absent. */
26
+ fallbackName?: string;
27
+ }
28
+ /**
29
+ * Build a `ModelSelection` from a catalog `ProviderModel`. Pass `model: null`
30
+ * (with `modelId`) to construct a selection before the catalog has been fetched.
31
+ */
32
+ declare function modelSelectionFromCatalog(providerId: string, model: ProviderModel | null, options?: ModelSelectionFromCatalogOptions): ModelSelection;
33
+ //#endregion
34
+ //#region src/http.d.ts
35
+ type SecretResolver = () => string | Promise<string> | null | undefined;
36
+ type HeadersResolver = () => Record<string, string> | Promise<Record<string, string>>;
37
+ /**
38
+ * Clamps a session identifier to the 64-character limit the OpenAI Responses
39
+ * API enforces on `prompt_cache_key` (and on the headers it derives it from).
40
+ */
41
+ declare function clampPromptCacheKey(value: string): string;
42
+ /** Replaces every occurrence of `secret` in `value` with a redaction marker. */
43
+ declare function redactSecretText(value: string, secret: string | null | undefined): string;
44
+ /** Maps an HTTP status (and response text) to a coarse provider error code. */
45
+ declare function httpErrorCode(status: number, message: string): string | null;
46
+ /** Classifies a provider error code/message into a coarse category, falling back to `code`. */
47
+ declare function normalizeErrorCode(code: string | null, message: string): string | null;
48
+ /** Builds a provider `error` event from an unknown thrown value, redacting `secret`. */
49
+ declare function providerErrorFromUnknown(error: unknown, secret: string | null | undefined): ProviderEvent;
50
+ /** Resolves auth state from an API key or a matching custom auth header. */
51
+ declare function authStatusFromKey(resolveKey: SecretResolver, resolveHeaders: HeadersResolver | undefined, authHeader: string, providerLabel: string): Promise<ProviderAuthState>;
52
+ /** Parses a Retry-After header (delta-seconds or HTTP-date) into milliseconds. */
53
+ declare function retryAfterMsFromHeader(value: string | null): number | undefined;
54
+ /** Builds a redacted provider `error` event from a failed HTTP response. */
55
+ declare function httpRequestFailedEvent(response: Response, secret: string | null | undefined, providerLabel: string): Promise<ProviderEvent>;
56
+ //#endregion
57
+ export { AgentProvider, DEFAULT_ATTACHMENT_EXTENSIONS, InferenceItem, InferenceRequest, InferenceSteer, ModelPolicy, type ModelSelectionFromCatalogOptions, Provider, ProviderAuth, ProviderAuthState, ProviderEvent, ProviderFactoryDefinition, ProviderModel, ProviderModelCost, ProviderModelList, ProviderRun, ProviderRuntimeFactory, ProviderRuntimeState, ProviderSelection, ProviderServiceTier, ToolDefinition, applyModelPolicy, authStatusFromKey, clampPromptCacheKey, defineProvider, httpErrorCode, httpRequestFailedEvent, modelSelectionFromCatalog, normalizeErrorCode, providerErrorFromUnknown, providerRuntime, redactSecretText, retryAfterMsFromHeader, thinkingCapabilitiesFromProviderModel, withProviderId };
package/dist/index.mjs ADDED
@@ -0,0 +1,167 @@
1
+ import { shortHash } from "@demicodes/utils";
2
+ //#region src/provider.ts
3
+ const runtimeFactorySymbol = Symbol("demi.provider.runtimeFactory");
4
+ function defineProvider(definition) {
5
+ const { createRuntime, ...publicProvider } = definition;
6
+ return Object.freeze(Object.defineProperty(publicProvider, runtimeFactorySymbol, {
7
+ value: { createRuntime },
8
+ enumerable: false,
9
+ configurable: false,
10
+ writable: false
11
+ }));
12
+ }
13
+ function providerRuntime(provider, selection) {
14
+ const factory = provider[runtimeFactorySymbol];
15
+ if (!factory) throw new Error(`Provider "${provider.id}" does not expose a runtime factory`);
16
+ return factory.createRuntime(selection);
17
+ }
18
+ function applyModelPolicy(list, providerId, policy) {
19
+ const include = policy?.include ? new Set(policy.include) : null;
20
+ const exclude = policy?.exclude ? new Set(policy.exclude) : null;
21
+ const models = list.models.filter((model) => (!include || include.has(model.id)) && (!exclude || !exclude.has(model.id))).map((model) => withProviderId$1(model, providerId));
22
+ const defaultModelId = policy?.default && models.some((model) => model.id === policy.default) ? policy.default : list.defaultModelId && models.some((model) => model.id === list.defaultModelId) ? list.defaultModelId : null;
23
+ return {
24
+ ...list,
25
+ providerId,
26
+ models,
27
+ defaultModelId
28
+ };
29
+ }
30
+ function withProviderId$1(model, providerId) {
31
+ return model.providerId === providerId ? model : {
32
+ ...model,
33
+ providerId
34
+ };
35
+ }
36
+ //#endregion
37
+ //#region src/model-selection.ts
38
+ /** Stamps `providerId` onto a model catalog and every model in it. */
39
+ function withProviderId(list, providerId) {
40
+ return {
41
+ ...list,
42
+ providerId,
43
+ models: list.models.map((model) => ({
44
+ ...model,
45
+ providerId
46
+ }))
47
+ };
48
+ }
49
+ /** Attachment file types a model is offered when it reports attachment support. */
50
+ const DEFAULT_ATTACHMENT_EXTENSIONS = [
51
+ "png",
52
+ "jpg",
53
+ "jpeg",
54
+ "gif",
55
+ "webp",
56
+ "pdf"
57
+ ];
58
+ /** Derive the thinking capabilities a UI can offer from a catalog model. */
59
+ function thinkingCapabilitiesFromProviderModel(model) {
60
+ if (!model) return [];
61
+ if (model.supportsReasoning === false) return [{ type: "disabled" }];
62
+ if (!model.supportedThinkingEfforts || model.supportedThinkingEfforts.length === 0) return [];
63
+ return [{
64
+ type: "effort",
65
+ efforts: model.supportedThinkingEfforts,
66
+ defaultEffort: null,
67
+ summaries: [
68
+ "auto",
69
+ "concise",
70
+ "detailed",
71
+ "off",
72
+ "on"
73
+ ],
74
+ defaultSummary: null
75
+ }];
76
+ }
77
+ /**
78
+ * Build a `ModelSelection` from a catalog `ProviderModel`. Pass `model: null`
79
+ * (with `modelId`) to construct a selection before the catalog has been fetched.
80
+ */
81
+ function modelSelectionFromCatalog(providerId, model, options = {}) {
82
+ const modelId = options.modelId ?? model?.id ?? "";
83
+ const accepted = options.acceptedExtensions ?? DEFAULT_ATTACHMENT_EXTENSIONS;
84
+ return {
85
+ providerId,
86
+ model: {
87
+ id: modelId,
88
+ name: model?.displayName ?? options.fallbackName ?? modelId,
89
+ contextWindow: model?.contextWindow ?? 0,
90
+ inputLimit: null,
91
+ thinking: thinkingCapabilitiesFromProviderModel(model),
92
+ acceptedExtensions: model?.supportsAttachments ? [...accepted] : []
93
+ },
94
+ thinking: options.thinking ?? null,
95
+ serviceTierId: options.serviceTierId ?? null
96
+ };
97
+ }
98
+ //#endregion
99
+ //#region src/http.ts
100
+ /**
101
+ * Clamps a session identifier to the 64-character limit the OpenAI Responses
102
+ * API enforces on `prompt_cache_key` (and on the headers it derives it from).
103
+ */
104
+ function clampPromptCacheKey(value) {
105
+ return value.length <= 64 ? value : `session_${shortHash(value)}`;
106
+ }
107
+ /** Replaces every occurrence of `secret` in `value` with a redaction marker. */
108
+ function redactSecretText(value, secret) {
109
+ return secret ? value.split(secret).join("[redacted]") : value;
110
+ }
111
+ /** Maps an HTTP status (and response text) to a coarse provider error code. */
112
+ function httpErrorCode(status, message) {
113
+ if (status === 401 || status === 403) return "auth_expired";
114
+ if (status === 408 || status === 409 || status === 425 || status === 429 || status >= 500) return "rate_limit";
115
+ if (status === 400 && /context|too long|token/i.test(message)) return "context_length_exceeded";
116
+ return null;
117
+ }
118
+ /** Classifies a provider error code/message into a coarse category, falling back to `code`. */
119
+ function normalizeErrorCode(code, message) {
120
+ const value = `${code ?? ""} ${message}`.toLowerCase();
121
+ if (/context|too long|max.*token/.test(value)) return "context_length_exceeded";
122
+ if (/rate|quota|billing|limit/.test(value)) return "rate_limit";
123
+ if (/auth|unauth|invalid.*key|expired/.test(value)) return "auth_expired";
124
+ if (/overload|unavailable|timeout/.test(value)) return "overloaded";
125
+ return code;
126
+ }
127
+ /** Builds a provider `error` event from an unknown thrown value, redacting `secret`. */
128
+ function providerErrorFromUnknown(error, secret) {
129
+ const message = error instanceof Error ? error.message : String(error);
130
+ return {
131
+ type: "error",
132
+ message: redactSecretText(message, secret),
133
+ code: normalizeErrorCode(null, message)
134
+ };
135
+ }
136
+ /** Resolves auth state from an API key or a matching custom auth header. */
137
+ async function authStatusFromKey(resolveKey, resolveHeaders, authHeader, providerLabel) {
138
+ const [key, headers] = await Promise.all([resolveKey(), resolveHeaders?.()]);
139
+ if (key || headers && Object.keys(headers).some((name) => name.toLowerCase() === authHeader)) return { status: "authenticated" };
140
+ return {
141
+ status: "unauthenticated",
142
+ message: `${providerLabel} API key is missing`
143
+ };
144
+ }
145
+ /** Parses a Retry-After header (delta-seconds or HTTP-date) into milliseconds. */
146
+ function retryAfterMsFromHeader(value) {
147
+ if (!value) return void 0;
148
+ const seconds = Number(value);
149
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.floor(seconds * 1e3);
150
+ const dateMs = Date.parse(value);
151
+ if (Number.isFinite(dateMs)) return Math.max(0, dateMs - Date.now());
152
+ }
153
+ /** Builds a redacted provider `error` event from a failed HTTP response. */
154
+ async function httpRequestFailedEvent(response, secret, providerLabel) {
155
+ const text = await response.text().catch(() => "");
156
+ const message = redactSecretText(`${providerLabel} API request failed with HTTP ${response.status}${text ? `: ${text}` : ""}`, secret);
157
+ const retryAfterMs = retryAfterMsFromHeader(response.headers.get("retry-after"));
158
+ const event = {
159
+ type: "error",
160
+ message,
161
+ code: httpErrorCode(response.status, message)
162
+ };
163
+ if (retryAfterMs !== void 0) event.retryAfterMs = retryAfterMs;
164
+ return event;
165
+ }
166
+ //#endregion
167
+ export { DEFAULT_ATTACHMENT_EXTENSIONS, applyModelPolicy, authStatusFromKey, clampPromptCacheKey, defineProvider, httpErrorCode, httpRequestFailedEvent, modelSelectionFromCatalog, normalizeErrorCode, providerErrorFromUnknown, providerRuntime, redactSecretText, retryAfterMsFromHeader, thinkingCapabilitiesFromProviderModel, withProviderId };
@@ -0,0 +1,45 @@
1
+ import { i as InferenceSteer, l as ProviderEvent, m as ProviderRun, r as InferenceRequest, t as AgentProvider } from "./types-CGXGUfNJ.mjs";
2
+
3
+ //#region src/testing.d.ts
4
+ /**
5
+ * Scripted provider for testing. Each "turn" is a list of events to yield.
6
+ *
7
+ * The provider advances through turns sequentially: each `run()` call
8
+ * consumes the next turn's events. This lets tests script multi-turn
9
+ * flows like "respond with text -> request a tool call -> receive tool
10
+ * result -> respond with follow-up text".
11
+ *
12
+ * Tool call round-trip: a turn yields `tool_call_requested`. AgentSession
13
+ * executes the tool, then calls `run()` again with the tool result in
14
+ * `items`. The next turn's events are then yielded.
15
+ *
16
+ * Turn scripts can also be functions of the incoming request, so a test
17
+ * can inspect the items it received (e.g. assert tool_result present).
18
+ */
19
+ declare class StubProvider implements AgentProvider {
20
+ private turns;
21
+ private cursor;
22
+ constructor(turns: TurnScript[]);
23
+ run(request: InferenceRequest): AsyncIterable<ProviderEvent>;
24
+ /** Number of turns consumed so far. Useful for assertions. */
25
+ get consumedTurns(): number;
26
+ }
27
+ type TurnScript = ProviderEvent[] | ((request: InferenceRequest) => ProviderEvent[]);
28
+ declare function createProviderRun(output: Iterable<ProviderEvent> | AsyncIterable<ProviderEvent>, options?: {
29
+ steer?: (input: InferenceSteer) => Promise<void> | void;
30
+ }): ProviderRun;
31
+ declare const events: {
32
+ text: (text: string) => ProviderEvent;
33
+ response: (usage?: Partial<UsageLike>) => ProviderEvent;
34
+ toolCall: (toolUseId: string, toolName: string, input: unknown) => ProviderEvent;
35
+ error: (message: string, code?: string) => ProviderEvent;
36
+ abort: () => ProviderEvent;
37
+ };
38
+ interface UsageLike {
39
+ inputTokens: number;
40
+ outputTokens: number;
41
+ cacheReadTokens: number;
42
+ cacheWriteTokens: number;
43
+ }
44
+ //#endregion
45
+ export { StubProvider, createProviderRun, events };
@@ -0,0 +1,74 @@
1
+ //#region src/testing.ts
2
+ /**
3
+ * Scripted provider for testing. Each "turn" is a list of events to yield.
4
+ *
5
+ * The provider advances through turns sequentially: each `run()` call
6
+ * consumes the next turn's events. This lets tests script multi-turn
7
+ * flows like "respond with text -> request a tool call -> receive tool
8
+ * result -> respond with follow-up text".
9
+ *
10
+ * Tool call round-trip: a turn yields `tool_call_requested`. AgentSession
11
+ * executes the tool, then calls `run()` again with the tool result in
12
+ * `items`. The next turn's events are then yielded.
13
+ *
14
+ * Turn scripts can also be functions of the incoming request, so a test
15
+ * can inspect the items it received (e.g. assert tool_result present).
16
+ */
17
+ var StubProvider = class {
18
+ turns;
19
+ cursor = 0;
20
+ constructor(turns) {
21
+ this.turns = turns;
22
+ }
23
+ async *run(request) {
24
+ const turn = this.turns[this.cursor];
25
+ this.cursor += 1;
26
+ if (turn === void 0) throw new Error(`StubProvider: no turn scripted for call #${this.cursor} (ran out of turns)`);
27
+ const events = typeof turn === "function" ? turn(request) : turn;
28
+ for (const event of events) yield event;
29
+ }
30
+ /** Number of turns consumed so far. Useful for assertions. */
31
+ get consumedTurns() {
32
+ return this.cursor;
33
+ }
34
+ };
35
+ function createProviderRun(output, options = {}) {
36
+ const run = { [Symbol.asyncIterator]: () => toAsyncIterator(output) };
37
+ if (options.steer) run.steer = options.steer;
38
+ return run;
39
+ }
40
+ const events = {
41
+ text: (text) => ({
42
+ type: "text_delta",
43
+ text
44
+ }),
45
+ response: (usage) => ({
46
+ type: "response",
47
+ usage: {
48
+ inputTokens: usage?.inputTokens ?? 0,
49
+ outputTokens: usage?.outputTokens ?? 0,
50
+ cacheReadTokens: usage?.cacheReadTokens ?? 0,
51
+ cacheWriteTokens: usage?.cacheWriteTokens ?? 0
52
+ }
53
+ }),
54
+ toolCall: (toolUseId, toolName, input) => ({
55
+ type: "tool_call_requested",
56
+ toolUseId,
57
+ toolName,
58
+ input
59
+ }),
60
+ error: (message, code) => ({
61
+ type: "error",
62
+ message,
63
+ code: code ?? null
64
+ }),
65
+ abort: () => ({ type: "abort" })
66
+ };
67
+ function toAsyncIterator(output) {
68
+ if (Symbol.asyncIterator in output) return output[Symbol.asyncIterator]();
69
+ return (async function* () {
70
+ for (const event of output) yield event;
71
+ })();
72
+ }
73
+ //#endregion
74
+ export { StubProvider, createProviderRun, events };
@@ -0,0 +1,198 @@
1
+ import { ModelSelection, ThinkingConfig, ThinkingEffort, TokenUsage, ToolResultContentBlock, UserContentBlock } from "@demicodes/core";
2
+
3
+ //#region src/types.d.ts
4
+ interface ToolDefinition {
5
+ name: string;
6
+ description: string;
7
+ /** JSON Schema describing the tool input. */
8
+ inputSchema: Record<string, unknown>;
9
+ }
10
+ type InferenceItem = {
11
+ type: 'user_message';
12
+ content: UserContentBlock[];
13
+ } | {
14
+ type: 'user_steer';
15
+ turnId: string;
16
+ content: UserContentBlock[];
17
+ } | {
18
+ type: 'assistant_text';
19
+ modelId: string;
20
+ text: string;
21
+ } | {
22
+ type: 'assistant_thinking';
23
+ modelId: string;
24
+ text: string;
25
+ signature: string | null;
26
+ } | {
27
+ type: 'assistant_redacted_thinking';
28
+ modelId: string;
29
+ data: string;
30
+ } | {
31
+ type: 'tool_use';
32
+ modelId: string;
33
+ toolUseId: string;
34
+ toolName: string;
35
+ input: unknown;
36
+ } | {
37
+ type: 'tool_result';
38
+ toolUseId: string;
39
+ output: ToolResultContentBlock[];
40
+ isError: boolean;
41
+ };
42
+ interface InferenceRequest {
43
+ /** Stable id for the owning agent session. */
44
+ sessionId: string;
45
+ /** Stable id for the active user/maintenance turn; shared by provider continuations inside that turn. */
46
+ turnId: string;
47
+ /** Unique id for this concrete provider request. */
48
+ requestId: string;
49
+ modelId: string;
50
+ systemPrompt: string;
51
+ cwd: string;
52
+ items: InferenceItem[];
53
+ tools: ToolDefinition[];
54
+ thinking: ThinkingConfig | null;
55
+ serviceTierId?: string | null;
56
+ cancel: AbortSignal;
57
+ }
58
+ type ProviderEvent = {
59
+ type: 'thinking_start';
60
+ } | {
61
+ type: 'thinking_delta';
62
+ text: string;
63
+ } | {
64
+ type: 'thinking_signature';
65
+ signature: string;
66
+ } | {
67
+ type: 'redacted_thinking';
68
+ data: string;
69
+ } | {
70
+ type: 'text_delta';
71
+ text: string;
72
+ } | {
73
+ type: 'tool_call_requested';
74
+ toolUseId: string;
75
+ toolName: string;
76
+ input: unknown;
77
+ } | {
78
+ type: 'response';
79
+ usage: TokenUsage;
80
+ } | {
81
+ type: 'error';
82
+ message: string;
83
+ code: string | null; /** Server-suggested retry delay (e.g. from a Retry-After header), if any. */
84
+ retryAfterMs?: number;
85
+ } | {
86
+ type: 'abort';
87
+ };
88
+ interface InferenceSteer {
89
+ id: string;
90
+ sessionId: string;
91
+ turnId: string;
92
+ content: UserContentBlock[];
93
+ }
94
+ interface ProviderRun extends AsyncIterable<ProviderEvent> {
95
+ steer?(input: InferenceSteer): Promise<void> | void;
96
+ }
97
+ interface AgentProvider {
98
+ run(request: InferenceRequest): ProviderRun;
99
+ /**
100
+ * Releases any resources the provider holds open across turns — e.g. a long-lived CLI
101
+ * subprocess kept alive for a whole session. Called once when the owning session closes.
102
+ */
103
+ dispose?(): Promise<void> | void;
104
+ }
105
+ interface ProviderSelection {
106
+ providerId: string;
107
+ model: ModelSelection;
108
+ }
109
+ type ProviderAuthState = {
110
+ status: 'unknown';
111
+ message?: string;
112
+ } | {
113
+ status: 'authenticated';
114
+ accountLabel?: string;
115
+ } | {
116
+ status: 'unauthenticated';
117
+ message?: string;
118
+ } | {
119
+ status: 'error';
120
+ message: string;
121
+ };
122
+ interface ProviderAuth {
123
+ status(): Promise<ProviderAuthState> | ProviderAuthState;
124
+ }
125
+ type ProviderRuntimeState = {
126
+ status: 'unknown';
127
+ message?: string;
128
+ } | {
129
+ status: 'ready';
130
+ message?: string;
131
+ } | {
132
+ status: 'unavailable';
133
+ message: string;
134
+ } | {
135
+ status: 'error';
136
+ message: string;
137
+ };
138
+ interface Provider {
139
+ id: string;
140
+ displayName: string;
141
+ auth?: ProviderAuth;
142
+ state?(): Promise<ProviderRuntimeState> | ProviderRuntimeState;
143
+ listModels?(): Promise<ProviderModelList> | ProviderModelList;
144
+ }
145
+ interface ProviderRuntimeFactory {
146
+ createRuntime(selection: ProviderSelection): Promise<AgentProvider> | AgentProvider;
147
+ }
148
+ interface ProviderFactoryDefinition extends Provider {
149
+ createRuntime(selection: ProviderSelection): Promise<AgentProvider> | AgentProvider;
150
+ }
151
+ interface ProviderModelCost {
152
+ input: number | null;
153
+ output: number | null;
154
+ cacheRead: number | null;
155
+ cacheWrite: number | null;
156
+ }
157
+ interface ProviderServiceTier {
158
+ id: string;
159
+ label: string;
160
+ description?: string;
161
+ }
162
+ interface ProviderModel {
163
+ providerId: string;
164
+ id: string;
165
+ displayName: string;
166
+ description?: string;
167
+ contextWindow: number | null;
168
+ outputLimit: number | null;
169
+ supportsTools: boolean | null;
170
+ supportsAttachments: boolean | null;
171
+ supportsReasoning: boolean | null;
172
+ supportedThinkingEfforts: ThinkingEffort[] | null;
173
+ defaultThinkingEffort: ThinkingEffort | null;
174
+ /** Whether thinking can be turned off entirely. Some transports (e.g. the Claude Code CLI, whose
175
+ * `--effort` flag only accepts low|medium|high|xhigh|max) can level thinking but never disable it,
176
+ * so the UI must not offer a "no reasoning" option. Defaults to true (optional) when unset. */
177
+ canDisableThinking?: boolean | null;
178
+ serviceTiers?: ProviderServiceTier[] | null;
179
+ defaultServiceTierId?: string | null;
180
+ cost?: ProviderModelCost;
181
+ sourceFetchedAt: string;
182
+ stale: boolean;
183
+ }
184
+ interface ProviderModelList {
185
+ providerId: string;
186
+ models: ProviderModel[];
187
+ defaultModelId: string | null;
188
+ warnings: string[];
189
+ sourceFetchedAt: string;
190
+ stale: boolean;
191
+ }
192
+ type ModelPolicy = {
193
+ include?: string[];
194
+ exclude?: string[];
195
+ default?: string;
196
+ };
197
+ //#endregion
198
+ export { ProviderSelection as _, ModelPolicy as a, ProviderAuthState as c, ProviderModel as d, ProviderModelCost as f, ProviderRuntimeState as g, ProviderRuntimeFactory as h, InferenceSteer as i, ProviderEvent as l, ProviderRun as m, InferenceItem as n, Provider as o, ProviderModelList as p, InferenceRequest as r, ProviderAuth as s, AgentProvider as t, ProviderFactoryDefinition as u, ProviderServiceTier as v, ToolDefinition as y };
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@demicodes/provider",
3
+ "description": "Provider contract and shared building blocks for Demi inference adapters.",
4
+ "version": "0.1.0",
5
+ "private": false,
6
+ "type": "module",
7
+ "exports": {
8
+ ".": {
9
+ "development": "./src/index.ts",
10
+ "types": "./dist/index.d.mts",
11
+ "import": "./dist/index.mjs"
12
+ },
13
+ "./testing": {
14
+ "development": "./src/testing.ts",
15
+ "types": "./dist/testing.d.mts",
16
+ "import": "./dist/testing.mjs"
17
+ }
18
+ },
19
+ "dependencies": {
20
+ "@demicodes/core": "workspace:*",
21
+ "@demicodes/utils": "workspace:*"
22
+ },
23
+ "license": "Apache-2.0",
24
+ "main": "./dist/index.mjs",
25
+ "module": "./dist/index.mjs",
26
+ "types": "./dist/index.d.mts",
27
+ "files": [
28
+ "dist"
29
+ ],
30
+ "scripts": {
31
+ "build": "tsdown"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/wspl/demi.git",
39
+ "directory": "packages/provider"
40
+ },
41
+ "homepage": "https://github.com/wspl/demi/tree/main/packages/provider#readme",
42
+ "bugs": "https://github.com/wspl/demi/issues"
43
+ }