@molecule/api-ai 1.0.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,115 @@
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
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object
40
+ form, that is based on (or derived from) the Work and for which the
41
+ editorial revisions, annotations, elaborations, or other modifications
42
+ represent, as a whole, an original work of authorship.
43
+
44
+ "Contribution" shall mean any work of authorship, including the
45
+ original version of the Work and any modifications or additions
46
+ to that Work, that is intentionally submitted to the Licensor for
47
+ inclusion in the Work by the copyright owner or by an individual or
48
+ Legal Entity authorized to submit on behalf of the copyright owner.
49
+
50
+ "Contributor" shall mean Licensor and any individual or Legal Entity
51
+ on behalf of whom a Contribution has been received by the Licensor and
52
+ subsequently incorporated within the Work.
53
+
54
+ 2. Grant of Copyright License. Subject to the terms and conditions of
55
+ this License, each Contributor hereby grants to You a perpetual,
56
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
57
+ copyright license to reproduce, prepare Derivative Works of,
58
+ publicly display, publicly perform, sublicense, and distribute the
59
+ Work and such Derivative Works in Source or Object form.
60
+
61
+ 3. Grant of Patent License. Subject to the terms and conditions of
62
+ this License, each Contributor hereby grants to You a perpetual,
63
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
64
+ patent license to make, have made, use, offer to sell, sell, import,
65
+ and otherwise transfer the Work.
66
+
67
+ 4. Redistribution. You may reproduce and distribute copies of the
68
+ Work or Derivative Works thereof in any medium, with or without
69
+ modifications, and in Source or Object form, provided that You
70
+ meet the following conditions:
71
+
72
+ (a) You must give any other recipients of the Work or
73
+ Derivative Works a copy of this License; and
74
+
75
+ (b) You must cause any modified files to carry prominent notices
76
+ stating that You changed the files; and
77
+
78
+ (c) You must retain, in the Source form of any Derivative Works
79
+ that You distribute, all copyright, patent, trademark, and
80
+ attribution notices from the Source form of the Work,
81
+ excluding those notices that do not pertain to any part of
82
+ the Derivative Works; and
83
+
84
+ (d) If the Work includes a "NOTICE" text file as part of its
85
+ distribution, then any Derivative Works that You distribute must
86
+ include a readable copy of the attribution notices contained
87
+ within such NOTICE file.
88
+
89
+ 5. Submission of Contributions.
90
+
91
+ 6. Trademarks. This License does not grant permission to use the trade
92
+ names, trademarks, service marks, or product names of the Licensor.
93
+
94
+ 7. Disclaimer of Warranty. Unless required by applicable law or
95
+ agreed to in writing, Licensor provides the Work on an "AS IS" BASIS,
96
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
97
+
98
+ 8. Limitation of Liability. In no event and under no legal theory shall
99
+ any Contributor be liable to You for damages.
100
+
101
+ 9. Accepting Warranty or Additional Liability.
102
+
103
+ Copyright 2026 Molecule Dev, Inc.
104
+
105
+ Licensed under the Apache License, Version 2.0 (the "License");
106
+ you may not use this file except in compliance with the License.
107
+ You may obtain a copy of the License at
108
+
109
+ http://www.apache.org/licenses/LICENSE-2.0
110
+
111
+ Unless required by applicable law or agreed to in writing, software
112
+ distributed under the License is distributed on an "AS IS" BASIS,
113
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
114
+ See the License for the specific language governing permissions and
115
+ limitations under the License.
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=browser-guard.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"browser-guard.d.ts","sourceRoot":"","sources":["../src/browser-guard.ts"],"names":[],"mappings":"AAuBA,OAAO,EAAE,CAAA"}
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Browser guard — `@molecule/api-ai` is SERVER-ONLY.
3
+ *
4
+ * Generated by scripts/gen-browser-guards.mjs (workspace root) — edit THAT, not this.
5
+ * Evaluating a server package in a browser bundle is always an import-graph mistake
6
+ * (node APIs, secrets); without this guard it surfaces as a cryptic downstream crash
7
+ * ("Buffer is not defined") far from the culprit. Throwing here names the package and
8
+ * the fix at the exact moment the client bundle evaluates it. jsdom tests and SSR are
9
+ * unaffected: the throw requires browser globals AND the absence of a node runtime.
10
+ */
11
+ const g = globalThis;
12
+ if (g.window !== undefined && g.document !== undefined && !g.process?.versions?.node) {
13
+ throw new Error('@molecule/api-ai is SERVER-ONLY: it was bundled into browser/client code. Import it only ' +
14
+ 'from server code (a server route/function or your API), or dynamic-import it inside ' +
15
+ 'the server handler — never from components or shared client modules, and never ' +
16
+ 'polyfill Buffer/process to silence this.');
17
+ }
18
+ export {};
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Model-agnostic AI chat interface for molecule.dev.
3
+ *
4
+ * Defines the `AIProvider` interface that bond packages (Anthropic, OpenAI, etc.)
5
+ * implement, plus types for messages, streaming events, tool use, and token usage.
6
+ *
7
+ * @remarks
8
+ * The AI provider is a SERVER-side integration — a weak integration leaks the key, trusts
9
+ * the model, or gets billed:
10
+ *
11
+ * - **The provider API key is SERVER-ONLY.** Call `chat()` from YOUR API and stream results
12
+ * to the browser (SSE); NEVER put the AI key in the frontend or call the provider directly
13
+ * from the browser — the key would ship to every user.
14
+ * - **Never blindly trust model output.** Treat anything the model returns — code, SQL, a
15
+ * shell command, a URL, a tool-call argument — as UNTRUSTED input: validate/whitelist it,
16
+ * run it only in a sandbox, and re-check permissions server-side. User/content text in the
17
+ * prompt can hijack the model (prompt injection), so model output must never directly
18
+ * trigger a privileged action (delete, pay, email, exec) without your own authorization +
19
+ * validation.
20
+ * - **Gate + budget it.** Require auth and rate-limit AI endpoints and cap `maxTokens` — an
21
+ * open, unauthenticated AI route is an unbounded bill.
22
+ * - `chat()` returns an async iterable of `ChatEvent` (text chunks, tool calls, a final
23
+ * `done` with usage) — iterate it and forward chunks to the client.
24
+ * - **`setProvider(name, provider)` ambiguity:** the FIRST named provider you register also
25
+ * auto-promotes to the singleton (so plain `getProvider()`/`requireProvider()` work without
26
+ * the caller knowing the name) — but that promotion is a single-provider convenience, not a
27
+ * permanent pick. The moment a SECOND, differently-named provider is registered,
28
+ * `getProvider()` stops returning the first one and declines (`null`) instead —
29
+ * `requireProvider()` throws pointing at `getProviderByName(name)`. Call the explicit
30
+ * `setProvider(provider)` (no name) form if you want one provider to always win regardless of
31
+ * how many named providers you also register.
32
+ *
33
+ * @example
34
+ * ```typescript
35
+ * import { requireProvider } from '@molecule/api-ai'
36
+ * import type { ChatParams } from '@molecule/api-ai'
37
+ *
38
+ * const ai = requireProvider()
39
+ * const params: ChatParams = {
40
+ * messages: [{ role: 'user', content: 'Hello!' }],
41
+ * stream: true,
42
+ * }
43
+ * let reply = ''
44
+ * for await (const event of ai.chat(params)) {
45
+ * if (event.type === 'text') reply += event.content // or forward the chunk to the client (SSE)
46
+ * }
47
+ * console.log(reply)
48
+ * ```
49
+ *
50
+ * @e2e
51
+ * Integration checklist — drive the real UI (live preview, no mocks), adapt
52
+ * each item to this app's actual chat/AI screens, and check every box off one
53
+ * by one. A box you can't check is an integration bug to fix — not a skip. The
54
+ * sandbox HAS an AI provider bonded, so the flow runs live end-to-end; AI
55
+ * output is NON-DETERMINISTIC, so assert on STRUCTURE/behavior, not exact text:
56
+ * - [ ] A message sent through the real chat UI comes back as a RELEVANT AI
57
+ * reply — not an echo of the prompt, a hardcoded stub, or an empty bubble.
58
+ * Ask something with a checkable answer (e.g. "What is 2 + 2?") and confirm
59
+ * the response actually contains it ("4"), proving a live model answered.
60
+ * - [ ] If the app streams, tokens render INCREMENTALLY — text grows word by
61
+ * word in the UI, not one final blob dumped after a long frozen spinner. (A
62
+ * streamed `chat()` yields `text` chunks then a final `done`; a single late
63
+ * blob means the reply was awaited whole and streaming is broken.)
64
+ * - [ ] Multi-turn CONTEXT is preserved: a follow-up that refers back to the
65
+ * previous turn (e.g. after "2 + 2", ask "now double that" -> understood as
66
+ * 8) works — proving the full `messages` history is sent, not just the last
67
+ * line.
68
+ * - [ ] A provider failure (bad/missing key, rate limit, timeout) surfaces as
69
+ * a graceful in-UI error message, NOT a crash, blank screen, a spinner that
70
+ * never resolves, or an unhandled 500. Force one and watch the UI recover.
71
+ * - [ ] The provider key + the provider call are SERVER-side only: the key
72
+ * never reaches the browser (check the network tab, the JS bundle, and page
73
+ * globals), and no route proxies arbitrary prompts to the model without auth
74
+ * + a token cap — an open AI endpoint is an unbounded bill and abuse vector.
75
+ *
76
+ * @module
77
+ */
78
+ export * from './browser-guard.js';
79
+ export * from './provider.js';
80
+ export * from './types.js';
81
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4EG;AAEH,cAAc,oBAAoB,CAAA;AAClC,cAAc,eAAe,CAAA;AAC7B,cAAc,YAAY,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Model-agnostic AI chat interface for molecule.dev.
3
+ *
4
+ * Defines the `AIProvider` interface that bond packages (Anthropic, OpenAI, etc.)
5
+ * implement, plus types for messages, streaming events, tool use, and token usage.
6
+ *
7
+ * @remarks
8
+ * The AI provider is a SERVER-side integration — a weak integration leaks the key, trusts
9
+ * the model, or gets billed:
10
+ *
11
+ * - **The provider API key is SERVER-ONLY.** Call `chat()` from YOUR API and stream results
12
+ * to the browser (SSE); NEVER put the AI key in the frontend or call the provider directly
13
+ * from the browser — the key would ship to every user.
14
+ * - **Never blindly trust model output.** Treat anything the model returns — code, SQL, a
15
+ * shell command, a URL, a tool-call argument — as UNTRUSTED input: validate/whitelist it,
16
+ * run it only in a sandbox, and re-check permissions server-side. User/content text in the
17
+ * prompt can hijack the model (prompt injection), so model output must never directly
18
+ * trigger a privileged action (delete, pay, email, exec) without your own authorization +
19
+ * validation.
20
+ * - **Gate + budget it.** Require auth and rate-limit AI endpoints and cap `maxTokens` — an
21
+ * open, unauthenticated AI route is an unbounded bill.
22
+ * - `chat()` returns an async iterable of `ChatEvent` (text chunks, tool calls, a final
23
+ * `done` with usage) — iterate it and forward chunks to the client.
24
+ * - **`setProvider(name, provider)` ambiguity:** the FIRST named provider you register also
25
+ * auto-promotes to the singleton (so plain `getProvider()`/`requireProvider()` work without
26
+ * the caller knowing the name) — but that promotion is a single-provider convenience, not a
27
+ * permanent pick. The moment a SECOND, differently-named provider is registered,
28
+ * `getProvider()` stops returning the first one and declines (`null`) instead —
29
+ * `requireProvider()` throws pointing at `getProviderByName(name)`. Call the explicit
30
+ * `setProvider(provider)` (no name) form if you want one provider to always win regardless of
31
+ * how many named providers you also register.
32
+ *
33
+ * @example
34
+ * ```typescript
35
+ * import { requireProvider } from '@molecule/api-ai'
36
+ * import type { ChatParams } from '@molecule/api-ai'
37
+ *
38
+ * const ai = requireProvider()
39
+ * const params: ChatParams = {
40
+ * messages: [{ role: 'user', content: 'Hello!' }],
41
+ * stream: true,
42
+ * }
43
+ * let reply = ''
44
+ * for await (const event of ai.chat(params)) {
45
+ * if (event.type === 'text') reply += event.content // or forward the chunk to the client (SSE)
46
+ * }
47
+ * console.log(reply)
48
+ * ```
49
+ *
50
+ * @e2e
51
+ * Integration checklist — drive the real UI (live preview, no mocks), adapt
52
+ * each item to this app's actual chat/AI screens, and check every box off one
53
+ * by one. A box you can't check is an integration bug to fix — not a skip. The
54
+ * sandbox HAS an AI provider bonded, so the flow runs live end-to-end; AI
55
+ * output is NON-DETERMINISTIC, so assert on STRUCTURE/behavior, not exact text:
56
+ * - [ ] A message sent through the real chat UI comes back as a RELEVANT AI
57
+ * reply — not an echo of the prompt, a hardcoded stub, or an empty bubble.
58
+ * Ask something with a checkable answer (e.g. "What is 2 + 2?") and confirm
59
+ * the response actually contains it ("4"), proving a live model answered.
60
+ * - [ ] If the app streams, tokens render INCREMENTALLY — text grows word by
61
+ * word in the UI, not one final blob dumped after a long frozen spinner. (A
62
+ * streamed `chat()` yields `text` chunks then a final `done`; a single late
63
+ * blob means the reply was awaited whole and streaming is broken.)
64
+ * - [ ] Multi-turn CONTEXT is preserved: a follow-up that refers back to the
65
+ * previous turn (e.g. after "2 + 2", ask "now double that" -> understood as
66
+ * 8) works — proving the full `messages` history is sent, not just the last
67
+ * line.
68
+ * - [ ] A provider failure (bad/missing key, rate limit, timeout) surfaces as
69
+ * a graceful in-UI error message, NOT a crash, blank screen, a spinner that
70
+ * never resolves, or an unhandled 500. Force one and watch the UI recover.
71
+ * - [ ] The provider key + the provider call are SERVER-side only: the key
72
+ * never reaches the browser (check the network tab, the JS bundle, and page
73
+ * globals), and no route proxies arbitrary prompts to the model without auth
74
+ * + a token cap — an open AI endpoint is an unbounded bill and abuse vector.
75
+ *
76
+ * @module
77
+ */
78
+ export * from './browser-guard.js';
79
+ export * from './provider.js';
80
+ export * from './types.js';
@@ -0,0 +1,97 @@
1
+ /**
2
+ * AI provider bond accessor.
3
+ *
4
+ * Supports both singleton and named providers. Singleton mode bonds a single
5
+ * AI provider for simple apps. Named mode (`setProvider('anthropic', provider)`)
6
+ * allows multiple providers to coexist — the consumer picks the right one based
7
+ * on the model's provider ID.
8
+ *
9
+ * @module
10
+ */
11
+ import type { AIProvider } from './types.js';
12
+ /**
13
+ * Registers an AI provider in singleton mode.
14
+ *
15
+ * - **Singleton**: `setProvider(provider)` — bonds a single default provider.
16
+ *
17
+ * @param provider - The default provider implementation for this process.
18
+ */
19
+ export declare function setProvider(provider: AIProvider): void;
20
+ /**
21
+ * Registers a named AI provider under bond type `ai`.
22
+ *
23
+ * - **Named**: `setProvider('anthropic', provider)` — bonds a named provider
24
+ * alongside others (e.g. `'xai'`, `'openai'`).
25
+ *
26
+ * @remarks
27
+ * The FIRST call to `setProvider(name, provider)` also auto-promotes that
28
+ * provider to the singleton (so `getProvider()`/`requireProvider()` work
29
+ * without callers having to know the name) — this is a convenience for the
30
+ * common single-provider case, not a permanent "first one wins" pick. Once a
31
+ * SECOND differently-named provider is registered, `getProvider()` stops
32
+ * returning the auto-promoted singleton and declines (`null`) instead,
33
+ * matching the documented ambiguity rule — see `getProvider()`. Call
34
+ * `setProvider(provider)` (no name) if you want a singleton that always wins
35
+ * regardless of how many named providers exist.
36
+ *
37
+ * @param name - Provider identifier used when selecting models.
38
+ * @param provider - Concrete provider bound to `name`.
39
+ */
40
+ export declare function setProvider(name: string, provider: AIProvider): void;
41
+ /**
42
+ * Retrieves the singleton AI provider, or `null` if none is bonded.
43
+ *
44
+ * Falls back to a single named provider when no singleton is bonded —
45
+ * this lets apps that wire `bond('ai', 'anthropic', provider)` directly
46
+ * (without going through `setProvider`'s singleton-fallback) still work
47
+ * with code that uses the simple `getProvider()` / `requireProvider()`
48
+ * accessors. When multiple named providers are bonded, the fallback
49
+ * declines (returns `null`) because the choice is ambiguous — those
50
+ * call sites must use `getProviderByName(name)` explicitly.
51
+ *
52
+ * This also applies to an auto-promoted singleton: `setProvider('a', p1)`
53
+ * followed by `setProvider('b', p2)` does NOT leave `getProvider()` stuck
54
+ * returning `p1` forever — once `'b'` is registered the pick is genuinely
55
+ * ambiguous and `getProvider()` declines (`null`), same as if neither had
56
+ * been auto-promoted. An explicit `setProvider(provider)` singleton is
57
+ * unaffected by how many named providers exist.
58
+ *
59
+ * @returns The bonded AI provider, or `null`.
60
+ */
61
+ export declare function getProvider(): AIProvider | null;
62
+ /**
63
+ * Retrieves a named AI provider, or `null` if not bonded.
64
+ *
65
+ * @param name - The provider name (e.g. `'anthropic'`, `'xai'`).
66
+ * @returns The named AI provider, or `null`.
67
+ */
68
+ export declare function getProviderByName(name: string): AIProvider | null;
69
+ /**
70
+ * Retrieves all named AI providers as a Map keyed by provider name.
71
+ *
72
+ * @returns Map of provider name → AIProvider.
73
+ */
74
+ export declare function getAllProviders(): Map<string, AIProvider>;
75
+ /**
76
+ * Checks whether an AI provider is currently bonded.
77
+ *
78
+ * @param name - Optional provider name. If omitted, checks the singleton.
79
+ * @returns `true` if the provider is bonded.
80
+ */
81
+ export declare function hasProvider(name?: string): boolean;
82
+ /**
83
+ * Retrieves the bonded AI provider, throwing if none is bonded.
84
+ * Use this when AI functionality is required.
85
+ *
86
+ * Routes through the same resolution as `getProvider()` so the single-named-
87
+ * bond fallback applies — apps that wire `bond('ai', 'anthropic', provider)`
88
+ * directly still satisfy this call without having to switch to the explicit
89
+ * `getProviderByName()` pattern. When resolution declined because MULTIPLE
90
+ * named providers are bonded with no explicit singleton, the thrown message
91
+ * says so (distinct from "nothing bonded at all") and points at
92
+ * `getProviderByName()`.
93
+ *
94
+ * @returns The bonded AI provider.
95
+ */
96
+ export declare function requireProvider(): AIProvider;
97
+ //# sourceMappingURL=provider.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../src/provider.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAWH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AAiB5C;;;;;;GAMG;AACH,wBAAgB,WAAW,CAAC,QAAQ,EAAE,UAAU,GAAG,IAAI,CAAA;AACvD;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,WAAW,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,UAAU,GAAG,IAAI,CAAA;AAoDrE;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,WAAW,IAAI,UAAU,GAAG,IAAI,CAE/C;AAED;;;;;GAKG;AACH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,MAAM,GAAG,UAAU,GAAG,IAAI,CAEjE;AAED;;;;GAIG;AACH,wBAAgB,eAAe,IAAI,GAAG,CAAC,MAAM,EAAE,UAAU,CAAC,CAEzD;AAED;;;;;GAKG;AACH,wBAAgB,WAAW,CAAC,IAAI,CAAC,EAAE,MAAM,GAAG,OAAO,CAElD;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,eAAe,IAAI,UAAU,CAgB5C"}
@@ -0,0 +1,152 @@
1
+ /**
2
+ * AI provider bond accessor.
3
+ *
4
+ * Supports both singleton and named providers. Singleton mode bonds a single
5
+ * AI provider for simple apps. Named mode (`setProvider('anthropic', provider)`)
6
+ * allows multiple providers to coexist — the consumer picks the right one based
7
+ * on the model's provider ID.
8
+ *
9
+ * @module
10
+ */
11
+ import { bond, expectBond, get as bondGet, getAll as bondGetAll, isBonded, } from '@molecule/api-bond';
12
+ import { t } from '@molecule/api-i18n';
13
+ const BOND_TYPE = 'ai';
14
+ expectBond(BOND_TYPE);
15
+ /**
16
+ * Whether the current singleton bond was auto-promoted by the FIRST
17
+ * `setProvider(name, provider)` call (as opposed to an explicit
18
+ * `setProvider(provider)` call). Auto-promotion is a convenience default for
19
+ * the common single-named-provider case; once a second, differently-named
20
+ * provider is registered, which provider the auto-promoted singleton points
21
+ * at becomes an accident of registration order, not a real choice — see
22
+ * `getProvider()`. An explicit singleton always wins regardless of how many
23
+ * named providers exist.
24
+ */
25
+ let singletonAutoPromoted = false;
26
+ /**
27
+ * Implementation that powers the `setProvider` overloads.
28
+ *
29
+ * @param nameOrProvider - Provider name (string) or the provider instance (singleton mode).
30
+ * @param provider - The provider instance (only when first arg is a name).
31
+ */
32
+ export function setProvider(nameOrProvider, provider) {
33
+ if (typeof nameOrProvider === 'string') {
34
+ bond(BOND_TYPE, nameOrProvider, provider);
35
+ // Also register as singleton if none exists yet, so validateBonds() passes
36
+ // and getProvider() works as a fallback. Track that this singleton was an
37
+ // auto-promotion (not an explicit `setProvider(provider)` call) so
38
+ // getProvider() can later decline once the pick becomes ambiguous.
39
+ if (!isBonded(BOND_TYPE)) {
40
+ bond(BOND_TYPE, provider);
41
+ singletonAutoPromoted = true;
42
+ }
43
+ }
44
+ else {
45
+ bond(BOND_TYPE, nameOrProvider);
46
+ singletonAutoPromoted = false;
47
+ }
48
+ }
49
+ /**
50
+ * Resolves the effective singleton: the provider `getProvider()` should
51
+ * return, plus whether the "no provider" case is actually an ambiguous
52
+ * multi-provider case (useful for a more actionable `requireProvider()`
53
+ * error).
54
+ *
55
+ * @returns The resolved provider (or `null`) and whether `null` means
56
+ * "ambiguous" rather than "nothing bonded".
57
+ */
58
+ function resolveSingleton() {
59
+ const singleton = bondGet(BOND_TYPE);
60
+ if (singleton) {
61
+ // An auto-promoted singleton is a convenience default for the
62
+ // single-named-provider case. Once a second distinct name is registered,
63
+ // continuing to return the FIRST-registered provider would silently let
64
+ // registration order decide which model answers — decline instead,
65
+ // matching the documented "ambiguous → null" rule below. An explicitly
66
+ // bonded singleton (`setProvider(provider)`) always wins.
67
+ if (singletonAutoPromoted && bondGetAll(BOND_TYPE).size > 1) {
68
+ return { provider: null, ambiguous: true };
69
+ }
70
+ return { provider: singleton, ambiguous: false };
71
+ }
72
+ const named = bondGetAll(BOND_TYPE);
73
+ if (named.size === 1)
74
+ return { provider: named.values().next().value ?? null, ambiguous: false };
75
+ return { provider: null, ambiguous: named.size > 1 };
76
+ }
77
+ /**
78
+ * Retrieves the singleton AI provider, or `null` if none is bonded.
79
+ *
80
+ * Falls back to a single named provider when no singleton is bonded —
81
+ * this lets apps that wire `bond('ai', 'anthropic', provider)` directly
82
+ * (without going through `setProvider`'s singleton-fallback) still work
83
+ * with code that uses the simple `getProvider()` / `requireProvider()`
84
+ * accessors. When multiple named providers are bonded, the fallback
85
+ * declines (returns `null`) because the choice is ambiguous — those
86
+ * call sites must use `getProviderByName(name)` explicitly.
87
+ *
88
+ * This also applies to an auto-promoted singleton: `setProvider('a', p1)`
89
+ * followed by `setProvider('b', p2)` does NOT leave `getProvider()` stuck
90
+ * returning `p1` forever — once `'b'` is registered the pick is genuinely
91
+ * ambiguous and `getProvider()` declines (`null`), same as if neither had
92
+ * been auto-promoted. An explicit `setProvider(provider)` singleton is
93
+ * unaffected by how many named providers exist.
94
+ *
95
+ * @returns The bonded AI provider, or `null`.
96
+ */
97
+ export function getProvider() {
98
+ return resolveSingleton().provider;
99
+ }
100
+ /**
101
+ * Retrieves a named AI provider, or `null` if not bonded.
102
+ *
103
+ * @param name - The provider name (e.g. `'anthropic'`, `'xai'`).
104
+ * @returns The named AI provider, or `null`.
105
+ */
106
+ export function getProviderByName(name) {
107
+ return bondGet(BOND_TYPE, name) ?? null;
108
+ }
109
+ /**
110
+ * Retrieves all named AI providers as a Map keyed by provider name.
111
+ *
112
+ * @returns Map of provider name → AIProvider.
113
+ */
114
+ export function getAllProviders() {
115
+ return bondGetAll(BOND_TYPE);
116
+ }
117
+ /**
118
+ * Checks whether an AI provider is currently bonded.
119
+ *
120
+ * @param name - Optional provider name. If omitted, checks the singleton.
121
+ * @returns `true` if the provider is bonded.
122
+ */
123
+ export function hasProvider(name) {
124
+ return name ? isBonded(BOND_TYPE, name) : isBonded(BOND_TYPE);
125
+ }
126
+ /**
127
+ * Retrieves the bonded AI provider, throwing if none is bonded.
128
+ * Use this when AI functionality is required.
129
+ *
130
+ * Routes through the same resolution as `getProvider()` so the single-named-
131
+ * bond fallback applies — apps that wire `bond('ai', 'anthropic', provider)`
132
+ * directly still satisfy this call without having to switch to the explicit
133
+ * `getProviderByName()` pattern. When resolution declined because MULTIPLE
134
+ * named providers are bonded with no explicit singleton, the thrown message
135
+ * says so (distinct from "nothing bonded at all") and points at
136
+ * `getProviderByName()`.
137
+ *
138
+ * @returns The bonded AI provider.
139
+ */
140
+ export function requireProvider() {
141
+ const { provider, ambiguous } = resolveSingleton();
142
+ if (provider)
143
+ return provider;
144
+ if (ambiguous) {
145
+ throw new Error(t('ai.error.ambiguousProvider', undefined, {
146
+ defaultValue: 'Multiple named AI providers are bonded and no default was set. Use getProviderByName(name) to select one.',
147
+ }));
148
+ }
149
+ throw new Error(t('ai.error.noProvider', undefined, {
150
+ defaultValue: 'AI provider not configured. Bond an AI provider first.',
151
+ }));
152
+ }
@@ -0,0 +1,302 @@
1
+ /**
2
+ * AI provider interface.
3
+ *
4
+ * Model-agnostic interface for AI chat with streaming and tool use.
5
+ * Implement this in a bond package (e.g., `@molecule/api-ai-anthropic`).
6
+ *
7
+ * @module
8
+ */
9
+ /**
10
+ * Chat message in a conversation.
11
+ */
12
+ export interface ChatMessage {
13
+ role: 'user' | 'assistant' | 'system';
14
+ content: string | ContentBlock[];
15
+ /**
16
+ * Model-native reasoning text produced alongside this (assistant) message —
17
+ * e.g. an OpenAI-compatible provider's `reasoning_content`. Some providers
18
+ * (Moonshot's Kimi K3 / k2.7-code and other preserved-thinking models)
19
+ * require it to be replayed verbatim on subsequent requests within a
20
+ * tool-call loop to keep reasoning continuity; callers that captured
21
+ * `thinking` stream events should set it when rebuilding history. Bonds
22
+ * whose provider has no such requirement ignore it.
23
+ */
24
+ reasoning?: string;
25
+ }
26
+ /**
27
+ * Rich content block within a message.
28
+ *
29
+ * Includes text, tool interactions, and file attachments (images, documents,
30
+ * audio, video). Provider bonds map these generic blocks to their native API
31
+ * format (e.g., Anthropic base64 source, OpenAI image_url, etc.).
32
+ */
33
+ export type ContentBlock = {
34
+ type: 'text';
35
+ text: string;
36
+ } | {
37
+ type: 'image';
38
+ mediaType: string;
39
+ data: string;
40
+ } | {
41
+ type: 'document';
42
+ mediaType: string;
43
+ data: string;
44
+ filename?: string;
45
+ } | {
46
+ type: 'audio';
47
+ mediaType: string;
48
+ data: string;
49
+ } | {
50
+ type: 'video';
51
+ mediaType: string;
52
+ data: string;
53
+ } | {
54
+ type: 'tool_use';
55
+ id: string;
56
+ name: string;
57
+ input: unknown;
58
+ } | {
59
+ type: 'tool_result';
60
+ tool_use_id: string;
61
+ content: string | unknown;
62
+ };
63
+ /**
64
+ * Streaming event from an AI chat call.
65
+ */
66
+ export type ChatEvent = {
67
+ type: 'text';
68
+ content: string;
69
+ } | {
70
+ type: 'thinking';
71
+ content: string;
72
+ } | {
73
+ type: 'tool_use';
74
+ id: string;
75
+ name: string;
76
+ input: unknown;
77
+ } | {
78
+ type: 'tool_use_start';
79
+ id: string;
80
+ name: string;
81
+ } | {
82
+ type: 'tool_input_delta';
83
+ id: string;
84
+ chars: number;
85
+ text?: string;
86
+ } | {
87
+ type: 'usage';
88
+ usage: TokenUsage;
89
+ } | {
90
+ type: 'done';
91
+ usage: TokenUsage;
92
+ } | {
93
+ type: 'error';
94
+ message: string;
95
+ errorKey?: string;
96
+ } | {
97
+ type: 'keep_alive';
98
+ };
99
+ /**
100
+ * Token usage from a chat completion.
101
+ */
102
+ export interface TokenUsage {
103
+ inputTokens: number;
104
+ outputTokens: number;
105
+ /** Number of input tokens written to the prompt cache. */
106
+ cacheCreationInputTokens?: number;
107
+ /** Number of input tokens read from the prompt cache. */
108
+ cacheReadInputTokens?: number;
109
+ /**
110
+ * The speed tier the provider REPORTS the request ran at (Anthropic wires it
111
+ * as `usage.speed` per the fast-mode docs, and as `usage.service_tier` on
112
+ * observed live responses — bonds read both). Only set by bonds whose
113
+ * provider has a fast/priority tier — absent means unreported. Metering
114
+ * prefers THIS field over the requested `ChatParams.speed`; when a
115
+ * fast-requested turn succeeds with no report, callers may conservatively
116
+ * bill the requested tier (Anthropic enforces fast-mode entitlement with a
117
+ * hard 429, so a successful fast request was served fast).
118
+ */
119
+ speed?: 'standard' | 'fast';
120
+ }
121
+ /**
122
+ * Details of one rate-limited or overloaded upstream response, reported via a
123
+ * provider config's `onRateLimit` callback each time the provider receives an
124
+ * HTTP 429/503 (or a provider-specific overload status such as Anthropic's
125
+ * 529), before any retry sleep. This surfaces the hits the provider's internal
126
+ * retry loop goes on to recover — the early-warning signal that capacity is
127
+ * running out, which a terminal error event alone would miss entirely.
128
+ */
129
+ export interface AiRateLimitEvent {
130
+ /** Provider name (e.g. 'anthropic'). */
131
+ provider: string;
132
+ /** Model the rejected request targeted. */
133
+ model: string;
134
+ /** HTTP status the upstream returned (429, 503, or 529). */
135
+ status: number;
136
+ /** 1-based attempt number that was rejected. */
137
+ attempt: number;
138
+ /** Whether the provider will retry this request again after a delay. */
139
+ willRetry: boolean;
140
+ /** Delay before the next retry in milliseconds; 0 when `willRetry` is false. */
141
+ retryInMs: number;
142
+ /** The response's parsed `Retry-After` header in seconds, when present and valid. */
143
+ retryAfterSeconds?: number;
144
+ }
145
+ /**
146
+ * Callback invoked on each rate-limited/overloaded upstream response. Must not
147
+ * throw (providers guard it anyway); keep it fast — it runs on the request path.
148
+ */
149
+ export type AiRateLimitCallback = (event: AiRateLimitEvent) => void;
150
+ /**
151
+ * JSON Schema subset for tool parameter definitions.
152
+ */
153
+ export interface JSONSchema {
154
+ type: string;
155
+ properties?: Record<string, JSONSchema>;
156
+ items?: JSONSchema;
157
+ required?: string[];
158
+ description?: string;
159
+ enum?: unknown[];
160
+ [key: string]: unknown;
161
+ }
162
+ /**
163
+ * Tool definition that the AI model can invoke.
164
+ */
165
+ export interface AITool {
166
+ name: string;
167
+ description: string;
168
+ parameters: JSONSchema;
169
+ execute: (input: unknown) => Promise<unknown>;
170
+ }
171
+ /**
172
+ * Provider-native tool handled server-side (e.g., Anthropic's `web_search`).
173
+ *
174
+ * Unlike `AITool`, server tools are executed by the AI provider itself —
175
+ * no client-side `execute` callback is needed. The provider passes them
176
+ * through to the API alongside custom tools.
177
+ */
178
+ export interface ServerTool {
179
+ /**
180
+ * Provider-specific tool type identifier — a VERSIONED string the provider
181
+ * publishes (e.g. Anthropic's `"web_search_20260209"` on current models;
182
+ * older models use earlier variants like `"web_search_20250305"`). Copy the
183
+ * exact value from the provider's docs for the model in use.
184
+ */
185
+ type: string;
186
+ /** Tool name. */
187
+ name: string;
188
+ /** Allow additional provider-specific fields (max_uses, etc.). */
189
+ [key: string]: unknown;
190
+ }
191
+ /**
192
+ * Parameters for a chat call.
193
+ */
194
+ export interface ChatParams {
195
+ messages: ChatMessage[];
196
+ tools?: AITool[];
197
+ /** Provider-native server tools (e.g. web search) — executed by the provider, not the caller. */
198
+ serverTools?: ServerTool[];
199
+ system?: string;
200
+ stream?: boolean;
201
+ maxTokens?: number;
202
+ temperature?: number;
203
+ model?: string;
204
+ /**
205
+ * Enable extended thinking / reasoning on models that support it.
206
+ *
207
+ * `budgetTokens` is the abstract reasoning budget; bonds without a native
208
+ * token-budget param translate it (e.g. via thresholds) into their provider's
209
+ * control. `effort` — when present — is the PROVIDER-NATIVE effort value for
210
+ * the active model, resolved by the caller from the model catalog (the model's
211
+ * own `supportedEffortLevels`), e.g. Anthropic `output_config.effort`
212
+ * (`'low' | 'medium' | 'high' | 'xhigh' | 'max'`) or an OpenAI-compatible
213
+ * `reasoning_effort`. Bonds MUST prefer `effort` over
214
+ * `budgetTokens` when set: on current Anthropic models (Fable 5 / Opus 4.8 /
215
+ * Sonnet 5) a raw `budget_tokens` request is rejected with a 400 — adaptive
216
+ * thinking + effort is the only control.
217
+ */
218
+ thinking?: {
219
+ type: 'enabled';
220
+ budgetTokens: number;
221
+ effort?: string;
222
+ };
223
+ /**
224
+ * Request the provider's fast/priority speed tier for this call (e.g.
225
+ * Anthropic's `speed: "fast"` — same model, faster output, premium pricing).
226
+ *
227
+ * Callers should only set `'fast'` for models whose catalog entry declares
228
+ * `fastPricing` (that field is the capability flag). Bonds whose provider has
229
+ * no speed tier ignore it. Bonds that support it MUST report the speed the
230
+ * provider says the request actually ran at in `TokenUsage.speed`, so
231
+ * metering prices the served tier, not the requested one. No automatic
232
+ * fallback is performed here: a fast-tier rate limit surfaces as a normal
233
+ * error/retry, and the caller decides whether to drop back to standard.
234
+ */
235
+ speed?: 'standard' | 'fast';
236
+ /** Enable prompt caching. Providers that support it will cache system prompts and tools. */
237
+ cacheControl?: {
238
+ type: 'ephemeral';
239
+ };
240
+ /** Abort signal to cancel in-flight API requests when the client disconnects. */
241
+ signal?: AbortSignal;
242
+ /**
243
+ * Control whether the model must call a tool. 'auto' (default) lets the model
244
+ * decide; 'required' forces at least one tool call (any tool); `{ type: 'tool',
245
+ * name }` forces that ONE specific tool — stronger than 'required', which only
246
+ * guarantees *some* tool and can let the model drift to a different one when the
247
+ * conversation history is biased toward it.
248
+ */
249
+ toolChoice?: 'auto' | 'required' | {
250
+ type: 'tool';
251
+ name: string;
252
+ };
253
+ /**
254
+ * Opaque, stable identifier for the END USER on whose behalf this request is
255
+ * made — forwarded to providers that accept one (Anthropic `metadata.user_id`,
256
+ * OpenAI-compatible `user`).
257
+ *
258
+ * This is an ABUSE-ATTRIBUTION control, and it is the difference between a
259
+ * provider suspending one account and suspending your organization's key. With
260
+ * nothing sent, every request from every tenant is indistinguishable from the
261
+ * platform itself, so the only enforcement action available to the provider is
262
+ * against the key that serves all of them.
263
+ *
264
+ * It MUST be opaque — a hash/uuid, never an email, name, phone or anything else
265
+ * that identifies a person to the provider — and it MUST be stable per user, so
266
+ * a repeat offender is recognizable across sessions. Callers are expected to
267
+ * derive it (e.g. an HMAC of their internal user id) and to keep the mapping on
268
+ * their side so an abuse report naming this value can be traced back.
269
+ *
270
+ * Bonds whose provider has no equivalent field ignore it.
271
+ */
272
+ endUserId?: string;
273
+ }
274
+ /**
275
+ * AI provider interface.
276
+ *
277
+ * Each bond package (Anthropic, OpenAI, Gemini, etc.) implements
278
+ * this interface to provide model-specific chat functionality.
279
+ */
280
+ export interface AIProvider {
281
+ readonly name: string;
282
+ /**
283
+ * Send a chat request and stream back events.
284
+ *
285
+ * Returns an async iterable of ChatEvent objects.
286
+ * Always yields a final 'done' event with token usage.
287
+ * @returns An async iterable that yields `ChatEvent` objects (text chunks, tool calls, done, or error).
288
+ */
289
+ chat(params: ChatParams): AsyncIterable<ChatEvent>;
290
+ }
291
+ /**
292
+ * AI provider configuration.
293
+ */
294
+ export interface AIConfig {
295
+ /** Default model to use when not specified in ChatParams. */
296
+ defaultModel?: string;
297
+ /** Maximum tokens for completions. */
298
+ maxTokens?: number;
299
+ /** Default temperature. */
300
+ temperature?: number;
301
+ }
302
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH;;GAEG;AACH,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,MAAM,GAAG,WAAW,GAAG,QAAQ,CAAA;IACrC,OAAO,EAAE,MAAM,GAAG,YAAY,EAAE,CAAA;IAChC;;;;;;;;OAQG;IACH,SAAS,CAAC,EAAE,MAAM,CAAA;CACnB;AAED;;;;;;GAMG;AACH,MAAM,MAAM,YAAY,GACpB;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAC9B;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAClD;IAAE,IAAI,EAAE,UAAU,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAE,GACxE;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,GAClD;IAAE,IAAI,EAAE,O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;IAErB;;;;;;OAMG;IACH,IAAI,CAAC,MAAM,EAAE,UAAU,GAAG,aAAa,CAAC,SAAS,CAAC,CAAA;CACnD;AAED;;GAEG;AACH,MAAM,WAAW,QAAQ;IACvB,6DAA6D;IAC7D,YAAY,CAAC,EAAE,MAAM,CAAA;IACrB,sCAAsC;IACtC,SAAS,CAAC,EAAE,MAAM,CAAA;IAClB,2BAA2B;IAC3B,WAAW,CAAC,EAAE,MAAM,CAAA;CACrB"}
package/dist/types.js ADDED
@@ -0,0 +1,9 @@
1
+ /**
2
+ * AI provider interface.
3
+ *
4
+ * Model-agnostic interface for AI chat with streaming and tool use.
5
+ * Implement this in a bond package (e.g., `@molecule/api-ai-anthropic`).
6
+ *
7
+ * @module
8
+ */
9
+ export {};
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@molecule/api-ai",
3
+ "version": "1.0.0",
4
+ "description": "Model-agnostic AI provider interface with streaming chat and tool use",
5
+ "type": "module",
6
+ "main": "dist/index.js",
7
+ "types": "dist/index.d.ts",
8
+ "scripts": {
9
+ "build": "tsc",
10
+ "test": "vitest run",
11
+ "test:watch": "vitest"
12
+ },
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "import": "./dist/index.js"
17
+ }
18
+ },
19
+ "files": [
20
+ "dist"
21
+ ],
22
+ "keywords": [
23
+ "molecule",
24
+ "ai",
25
+ "llm",
26
+ "chat",
27
+ "streaming"
28
+ ],
29
+ "license": "Apache-2.0",
30
+ "peerDependencies": {
31
+ "@molecule/api-bond": "^1.0.0",
32
+ "@molecule/api-i18n": "^1.0.0"
33
+ },
34
+ "devDependencies": {
35
+ "@molecule/api-bond": "1.0.0",
36
+ "@molecule/api-i18n": "1.0.0",
37
+ "@types/node": "26.1.2",
38
+ "typescript": "6.0.3",
39
+ "vitest": "4.1.10"
40
+ },
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "https://github.com/molecule-dev/molecule.git",
44
+ "directory": "packages/api/core/ai"
45
+ },
46
+ "homepage": "https://github.com/molecule-dev/molecule/tree/main/packages/api/core/ai",
47
+ "bugs": "https://github.com/molecule-dev/molecule/issues",
48
+ "publishConfig": {
49
+ "access": "public"
50
+ }
51
+ }