@gitpagedocs/tools 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +34 -0
  2. package/package.json +38 -0
  3. package/src/ai/bootstrap.ts +50 -0
  4. package/src/ai/catalog.ts +209 -0
  5. package/src/ai/env-credentials.ts +29 -0
  6. package/src/ai/factory.ts +14 -0
  7. package/src/ai/http/streaming.ts +52 -0
  8. package/src/ai/index.ts +32 -0
  9. package/src/ai/legacy-adapter.ts +33 -0
  10. package/src/ai/model-registry.ts +13 -0
  11. package/src/ai/providers/anthropic-provider.ts +77 -0
  12. package/src/ai/providers/cohere-provider.ts +66 -0
  13. package/src/ai/providers/gemini-provider.ts +84 -0
  14. package/src/ai/providers/ollama-provider.ts +69 -0
  15. package/src/ai/providers/openai-compatible-provider.ts +75 -0
  16. package/src/ai/providers/shared.ts +94 -0
  17. package/src/ai/registry.ts +29 -0
  18. package/src/cache/file-cache.ts +86 -0
  19. package/src/cache/index.ts +9 -0
  20. package/src/cache/memory-cache.ts +47 -0
  21. package/src/cache/web-storage-cache.ts +91 -0
  22. package/src/config/config-loader.ts +59 -0
  23. package/src/config/index.ts +1 -0
  24. package/src/constants/config.ts +8 -0
  25. package/src/constants/index.ts +1 -0
  26. package/src/crypto/doc-access.ts +64 -0
  27. package/src/crypto/index.ts +4 -0
  28. package/src/crypto/node-crypto-service.ts +87 -0
  29. package/src/crypto/web-crypto-service.ts +104 -0
  30. package/src/crypto/web.ts +4 -0
  31. package/src/documentation/doc-generator.ts +74 -0
  32. package/src/documentation/doc-updater.ts +47 -0
  33. package/src/documentation/index.ts +18 -0
  34. package/src/documentation/marker-patcher.ts +33 -0
  35. package/src/documentation/sections.ts +84 -0
  36. package/src/errors/app-error.ts +84 -0
  37. package/src/errors/index.ts +1 -0
  38. package/src/filesystem/file-service.ts +158 -0
  39. package/src/filesystem/index.ts +2 -0
  40. package/src/i18n/index.ts +36 -0
  41. package/src/i18n/language-bundles.ts +289 -0
  42. package/src/index.ts +26 -0
  43. package/src/logger/index.ts +2 -0
  44. package/src/logger/logger.ts +73 -0
  45. package/src/logger/redaction.ts +43 -0
  46. package/src/platform/index.ts +1 -0
  47. package/src/platform/user-config-dir.ts +48 -0
  48. package/src/ports/ai.ts +109 -0
  49. package/src/ports/cache.ts +16 -0
  50. package/src/ports/config.ts +21 -0
  51. package/src/ports/crypto.ts +33 -0
  52. package/src/ports/index.ts +15 -0
  53. package/src/ports/logger.ts +23 -0
  54. package/src/ports/security.ts +42 -0
  55. package/src/security/credential-vault.ts +117 -0
  56. package/src/security/file-vault-storage.ts +25 -0
  57. package/src/security/index.ts +8 -0
  58. package/src/security/migrate-plaintext-key.ts +38 -0
  59. package/src/security/password-gate.ts +62 -0
  60. package/src/security/web-storage-vault-storage.ts +23 -0
  61. package/src/security/web.ts +9 -0
package/README.md ADDED
@@ -0,0 +1,34 @@
1
+ # @gitpagedocs/tools
2
+
3
+ The **shared business-logic core** of the [Git Page Docs](../README.md) monorepo — the single home for domain logic consumed by the frontend, the CLI, and the MCP server. It ships **TypeScript source** and is consumed via `tsx` (CLI/MCP) or a TS-aware bundler (Next `transpilePackages`).
4
+
5
+ ## Modules (`src/`)
6
+
7
+ | Module | Responsibility |
8
+ |---|---|
9
+ | `ai/` | 14-provider AI system — data-driven `PROVIDER_CATALOG`, registry + factory (no switch chains), 5 family adapters (OpenAI-compatible, Anthropic, Gemini, Ollama, Cohere), SSE/NDJSON streaming, legacy↔catalog id mapping |
10
+ | `security/` | `EncryptedCredentialVault` (AES-256-GCM), `SessionPasswordGate`, plaintext migration; web + file storage adapters |
11
+ | `crypto/` | `NodeCryptoService` + `WebCryptoService` (SHA-256, PBKDF2, AES-256-GCM, masking, secure wipe); `deriveDocAccessKeys` / `verifyDocAccess` (double-hash documentation password gate shared by the CLI `password` command and the frontend gate) |
12
+ | `cache/` | `MemoryCache`, `FileCache`, `WebStorageCache` (Strategy over one `Cache` port) |
13
+ | `config/` | `GitPageDocsConfigLoader` (`.json` / `.js` / `.ts`) |
14
+ | `logger/` | Level-filtered logger with **secret redaction** |
15
+ | `errors/` | `AppError` + typed subclasses |
16
+ | `filesystem/` | `FileService` (root-bounded list/read/write/search) |
17
+ | `documentation/` | `DocumentationService`, `patchManagedRegion`, `DocUpdater` |
18
+ | `i18n/` | Language bundles (`site.languages` toggles in `config.json` + `langs/<lang>.json`): `loadConfigLanguageBundles`, `applyLanguageBundles` (fold into legacy `site.langmenu` / `translations`), `filterEnabledLanguages`, `splitLanguageBundles` (generator side); browser-safe |
19
+ | `ports/` | Type-only contracts (logger, cache, crypto, security, config, ai) |
20
+
21
+ ## Entry points (`exports`)
22
+
23
+ `.` (full barrel) · `./ai` · `./errors` · `./i18n` · `./ports` · `./crypto/web` · `./security/web` · `./cache/web` — the `web` subpaths and `./i18n` are browser-safe (no `node:` imports) for the Next.js bundle.
24
+
25
+ ## Usage
26
+
27
+ ```ts
28
+ import { createDefaultFactory, PROVIDER_CATALOG } from "@gitpagedocs/tools/ai";
29
+ import { EncryptedCredentialVault } from "@gitpagedocs/tools/security/web";
30
+ ```
31
+
32
+ ## Tests
33
+
34
+ Unit + integration + E2E live in `tools/tests/**` (Vitest); self-tests in `tools/smoke/**`. Run from the repo root: `npx vitest run` and `npm run smoke:all`.
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "@gitpagedocs/tools",
3
+ "version": "0.0.1",
4
+ "type": "module",
5
+ "description": "Shared business-logic core for Git Page Docs (consumed by frontend, cli and mcp). Ships TypeScript source; consume via tsx or a TS-aware bundler.",
6
+ "main": "./src/index.ts",
7
+ "types": "./src/index.ts",
8
+ "exports": {
9
+ ".": "./src/index.ts",
10
+ "./ai": "./src/ai/index.ts",
11
+ "./errors": "./src/errors/index.ts",
12
+ "./i18n": "./src/i18n/index.ts",
13
+ "./ports": "./src/ports/index.ts",
14
+ "./crypto/web": "./src/crypto/web.ts",
15
+ "./security/web": "./src/security/web.ts",
16
+ "./cache/web": "./src/cache/web-storage-cache.ts"
17
+ },
18
+ "files": [
19
+ "src",
20
+ "README.md"
21
+ ],
22
+ "engines": {
23
+ "node": ">=20"
24
+ },
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/Vidigal-code/git-page-docs.git",
28
+ "directory": "tools"
29
+ },
30
+ "author": "Vidigal-code",
31
+ "license": "ISC",
32
+ "publishConfig": {
33
+ "access": "public"
34
+ },
35
+ "scripts": {
36
+ "typecheck": "tsc --noEmit -p tsconfig.json"
37
+ }
38
+ }
@@ -0,0 +1,50 @@
1
+ import type { AIProvider, ProviderRegistration } from "../ports/ai";
2
+ import { PROVIDER_CATALOG, type ProviderFamily, type ProviderSpec } from "./catalog";
3
+ import { InMemoryProviderRegistry } from "./registry";
4
+ import { RegistryProviderFactory } from "./factory";
5
+ import { CatalogModelRegistry } from "./model-registry";
6
+ import type { FetchLike } from "./http/streaming";
7
+ import { OpenAiCompatibleProvider } from "./providers/openai-compatible-provider";
8
+ import { AnthropicProvider } from "./providers/anthropic-provider";
9
+ import { GeminiProvider } from "./providers/gemini-provider";
10
+ import { OllamaProvider } from "./providers/ollama-provider";
11
+ import { CohereProvider } from "./providers/cohere-provider";
12
+
13
+ /** Maps a provider family to its adapter constructor (small Factory table). */
14
+ type AdapterCtor = new (spec: ProviderSpec, fetchImpl?: FetchLike) => AIProvider;
15
+
16
+ const FAMILY_ADAPTERS: Record<ProviderFamily, AdapterCtor> = {
17
+ "openai-compatible": OpenAiCompatibleProvider,
18
+ anthropic: AnthropicProvider,
19
+ gemini: GeminiProvider,
20
+ ollama: OllamaProvider,
21
+ cohere: CohereProvider,
22
+ };
23
+
24
+ function toRegistration(spec: ProviderSpec, fetchImpl?: FetchLike): ProviderRegistration {
25
+ const Adapter = FAMILY_ADAPTERS[spec.family];
26
+ return {
27
+ id: spec.id,
28
+ label: spec.label,
29
+ defaultModel: spec.defaultModel,
30
+ capabilities: spec.capabilities,
31
+ create: () => new Adapter(spec, fetchImpl),
32
+ };
33
+ }
34
+
35
+ /** Registry pre-populated with every catalog provider. */
36
+ export function createDefaultRegistry(fetchImpl?: FetchLike): InMemoryProviderRegistry {
37
+ const registry = new InMemoryProviderRegistry();
38
+ for (const spec of Object.values(PROVIDER_CATALOG)) {
39
+ registry.register(toRegistration(spec, fetchImpl));
40
+ }
41
+ return registry;
42
+ }
43
+
44
+ export function createDefaultFactory(fetchImpl?: FetchLike): RegistryProviderFactory {
45
+ return new RegistryProviderFactory(createDefaultRegistry(fetchImpl));
46
+ }
47
+
48
+ export function createModelRegistry(): CatalogModelRegistry {
49
+ return new CatalogModelRegistry();
50
+ }
@@ -0,0 +1,209 @@
1
+ import type { AiProviderId, ModelDescriptor, ProviderCapabilities } from "../ports/ai";
2
+
3
+ /**
4
+ * Single source of truth for AI providers. Adding a provider = adding a catalog
5
+ * entry; the registry/factory are data-driven, so there is no switch to grow.
6
+ */
7
+ export type ProviderFamily =
8
+ | "openai-compatible"
9
+ | "anthropic"
10
+ | "gemini"
11
+ | "ollama"
12
+ | "cohere";
13
+
14
+ export type AuthStyle = "bearer" | "x-api-key" | "query-key" | "api-key-header" | "none";
15
+
16
+ export interface ProviderSpec {
17
+ readonly id: AiProviderId;
18
+ readonly label: string;
19
+ readonly family: ProviderFamily;
20
+ readonly defaultModel: string;
21
+ /** Default API base URL (without the chat path). */
22
+ readonly baseUrl: string;
23
+ /** Provider needs a user-supplied baseUrl (Azure deployment, local Ollama). */
24
+ readonly requiresBaseUrl?: boolean;
25
+ readonly auth: AuthStyle;
26
+ readonly capabilities: ProviderCapabilities;
27
+ readonly models: readonly ModelDescriptor[];
28
+ /**
29
+ * Environment variables that hold this provider's API key, in priority order.
30
+ * The single source for env-based credential detection; consumers read the
31
+ * first non-empty one instead of hardcoding names. Empty for keyless
32
+ * providers (Ollama).
33
+ */
34
+ readonly envVars: readonly string[];
35
+ }
36
+
37
+ const TEXT: ProviderCapabilities = { streaming: true, vision: false, audio: false };
38
+ const VISION: ProviderCapabilities = { streaming: true, vision: true, audio: false };
39
+ const VISION_AUDIO: ProviderCapabilities = { streaming: true, vision: true, audio: true };
40
+
41
+ function models(...ids: string[]): ModelDescriptor[] {
42
+ return ids.map((id) => ({ id }));
43
+ }
44
+
45
+ export const PROVIDER_CATALOG: Readonly<Record<AiProviderId, ProviderSpec>> = {
46
+ openai: {
47
+ id: "openai",
48
+ envVars: ["OPENAI_API_KEY"],
49
+ label: "OpenAI",
50
+ family: "openai-compatible",
51
+ defaultModel: "gpt-4o-mini",
52
+ baseUrl: "https://api.openai.com/v1",
53
+ auth: "bearer",
54
+ capabilities: VISION,
55
+ models: models("gpt-4o", "gpt-4o-mini", "o3-mini", "o1"),
56
+ },
57
+ anthropic: {
58
+ id: "anthropic",
59
+ envVars: ["ANTHROPIC_API_KEY"],
60
+ label: "Anthropic",
61
+ family: "anthropic",
62
+ // Latest Claude API model IDs.
63
+ defaultModel: "claude-sonnet-4-6",
64
+ baseUrl: "https://api.anthropic.com/v1",
65
+ auth: "x-api-key",
66
+ capabilities: VISION,
67
+ models: models("claude-opus-4-8", "claude-sonnet-4-6", "claude-haiku-4-5-20251001"),
68
+ },
69
+ gemini: {
70
+ id: "gemini",
71
+ envVars: ["GEMINI_API_KEY", "GOOGLE_API_KEY"],
72
+ label: "Google Gemini",
73
+ family: "gemini",
74
+ defaultModel: "gemini-2.0-flash",
75
+ baseUrl: "https://generativelanguage.googleapis.com/v1beta/models",
76
+ auth: "query-key",
77
+ capabilities: VISION_AUDIO,
78
+ models: models("gemini-2.0-flash", "gemini-1.5-pro", "gemini-1.5-flash"),
79
+ },
80
+ openrouter: {
81
+ id: "openrouter",
82
+ envVars: ["OPENROUTER_API_KEY"],
83
+ label: "OpenRouter",
84
+ family: "openai-compatible",
85
+ defaultModel: "openai/gpt-4o-mini",
86
+ baseUrl: "https://openrouter.ai/api/v1",
87
+ auth: "bearer",
88
+ capabilities: VISION,
89
+ models: models("openai/gpt-4o-mini", "anthropic/claude-sonnet-4-6", "google/gemini-2.0-flash-exp"),
90
+ },
91
+ ollama: {
92
+ id: "ollama",
93
+ envVars: [],
94
+ label: "Ollama (local)",
95
+ family: "ollama",
96
+ defaultModel: "llama3",
97
+ baseUrl: "http://localhost:11434",
98
+ requiresBaseUrl: false,
99
+ auth: "none",
100
+ capabilities: VISION,
101
+ models: models("llama3", "llama3.1", "mistral", "qwen2.5"),
102
+ },
103
+ "azure-openai": {
104
+ id: "azure-openai",
105
+ envVars: ["AZURE_OPENAI_API_KEY"],
106
+ label: "Azure OpenAI",
107
+ family: "openai-compatible",
108
+ defaultModel: "gpt-4o-mini",
109
+ baseUrl: "",
110
+ requiresBaseUrl: true,
111
+ auth: "api-key-header",
112
+ capabilities: VISION,
113
+ models: models("gpt-4o", "gpt-4o-mini"),
114
+ },
115
+ mistral: {
116
+ id: "mistral",
117
+ envVars: ["MISTRAL_API_KEY"],
118
+ label: "Mistral",
119
+ family: "openai-compatible",
120
+ defaultModel: "mistral-large-latest",
121
+ baseUrl: "https://api.mistral.ai/v1",
122
+ auth: "bearer",
123
+ capabilities: TEXT,
124
+ models: models("mistral-large-latest", "mistral-small-latest", "open-mistral-nemo"),
125
+ },
126
+ deepseek: {
127
+ id: "deepseek",
128
+ envVars: ["DEEPSEEK_API_KEY"],
129
+ label: "DeepSeek",
130
+ family: "openai-compatible",
131
+ defaultModel: "deepseek-chat",
132
+ baseUrl: "https://api.deepseek.com/v1",
133
+ auth: "bearer",
134
+ capabilities: TEXT,
135
+ models: models("deepseek-chat", "deepseek-reasoner"),
136
+ },
137
+ cohere: {
138
+ id: "cohere",
139
+ envVars: ["COHERE_API_KEY"],
140
+ label: "Cohere",
141
+ family: "cohere",
142
+ defaultModel: "command-r-plus",
143
+ baseUrl: "https://api.cohere.com/v2",
144
+ auth: "bearer",
145
+ capabilities: TEXT,
146
+ models: models("command-r-plus", "command-r"),
147
+ },
148
+ groq: {
149
+ id: "groq",
150
+ envVars: ["GROQ_API_KEY"],
151
+ label: "Groq",
152
+ family: "openai-compatible",
153
+ defaultModel: "llama-3.3-70b-versatile",
154
+ baseUrl: "https://api.groq.com/openai/v1",
155
+ auth: "bearer",
156
+ capabilities: TEXT,
157
+ models: models("llama-3.3-70b-versatile", "llama-3.1-8b-instant", "mixtral-8x7b-32768"),
158
+ },
159
+ xai: {
160
+ id: "xai",
161
+ envVars: ["XAI_API_KEY"],
162
+ label: "xAI Grok",
163
+ family: "openai-compatible",
164
+ defaultModel: "grok-2-latest",
165
+ baseUrl: "https://api.x.ai/v1",
166
+ auth: "bearer",
167
+ capabilities: VISION,
168
+ models: models("grok-2-latest", "grok-2-vision-latest"),
169
+ },
170
+ together: {
171
+ id: "together",
172
+ envVars: ["TOGETHER_API_KEY"],
173
+ label: "Together AI",
174
+ family: "openai-compatible",
175
+ defaultModel: "meta-llama/Llama-3.3-70B-Instruct-Turbo",
176
+ baseUrl: "https://api.together.xyz/v1",
177
+ auth: "bearer",
178
+ capabilities: TEXT,
179
+ models: models("meta-llama/Llama-3.3-70B-Instruct-Turbo", "mistralai/Mixtral-8x7B-Instruct-v0.1"),
180
+ },
181
+ fireworks: {
182
+ id: "fireworks",
183
+ envVars: ["FIREWORKS_API_KEY"],
184
+ label: "Fireworks AI",
185
+ family: "openai-compatible",
186
+ defaultModel: "accounts/fireworks/models/llama-v3p3-70b-instruct",
187
+ baseUrl: "https://api.fireworks.ai/inference/v1",
188
+ auth: "bearer",
189
+ capabilities: TEXT,
190
+ models: models("accounts/fireworks/models/llama-v3p3-70b-instruct"),
191
+ },
192
+ perplexity: {
193
+ id: "perplexity",
194
+ envVars: ["PERPLEXITY_API_KEY"],
195
+ label: "Perplexity",
196
+ family: "openai-compatible",
197
+ defaultModel: "sonar",
198
+ baseUrl: "https://api.perplexity.ai",
199
+ auth: "bearer",
200
+ capabilities: TEXT,
201
+ models: models("sonar", "sonar-pro", "sonar-reasoning"),
202
+ },
203
+ };
204
+
205
+ export const ALL_PROVIDER_IDS = Object.keys(PROVIDER_CATALOG) as AiProviderId[];
206
+
207
+ export function getProviderSpec(id: AiProviderId): ProviderSpec {
208
+ return PROVIDER_CATALOG[id];
209
+ }
@@ -0,0 +1,29 @@
1
+ import type { AiProviderId } from "../ports/ai";
2
+ import { PROVIDER_CATALOG } from "./catalog";
3
+
4
+ /** Environment lookup, injectable for tests; defaults to process.env. */
5
+ export type EnvLookup = Readonly<Record<string, string | undefined>>;
6
+
7
+ /**
8
+ * Resolves a provider's API key from the environment, reading the catalog's
9
+ * declared env vars in priority order (the single source — no hardcoded names
10
+ * at the call site). Returns undefined for keyless providers (Ollama) or when
11
+ * none is set.
12
+ */
13
+ export function resolveApiKeyFromEnv(
14
+ providerId: AiProviderId,
15
+ env: EnvLookup = process.env,
16
+ ): string | undefined {
17
+ for (const name of PROVIDER_CATALOG[providerId].envVars) {
18
+ const value = env[name]?.trim();
19
+ if (value) return value;
20
+ }
21
+ return undefined;
22
+ }
23
+
24
+ /** Provider ids that have at least one API key present in the environment. */
25
+ export function detectConfiguredProviders(env: EnvLookup = process.env): AiProviderId[] {
26
+ return (Object.keys(PROVIDER_CATALOG) as AiProviderId[]).filter((id) =>
27
+ PROVIDER_CATALOG[id].envVars.some((name) => Boolean(env[name]?.trim())),
28
+ );
29
+ }
@@ -0,0 +1,14 @@
1
+ import type { AIProvider, AiProviderId, ProviderFactory } from "../ports/ai";
2
+ import type { InMemoryProviderRegistry } from "./registry";
3
+ import { ProviderError } from "../errors/app-error";
4
+
5
+ /** Creates provider strategies from the registry (Factory pattern). */
6
+ export class RegistryProviderFactory implements ProviderFactory {
7
+ constructor(private readonly registry: InMemoryProviderRegistry) {}
8
+
9
+ create(id: AiProviderId): AIProvider {
10
+ const registration = this.registry.get(id);
11
+ if (!registration) throw new ProviderError(`Unknown AI provider: ${id}`, { details: { provider: id } });
12
+ return registration.create();
13
+ }
14
+ }
@@ -0,0 +1,52 @@
1
+ import { ProviderError } from "../../errors/app-error";
2
+
3
+ /** Injected fetch for testability; defaults to the platform global. */
4
+ export type FetchLike = typeof fetch;
5
+
6
+ export function resolveFetch(custom?: FetchLike): FetchLike {
7
+ const f = custom ?? (globalThis.fetch as FetchLike | undefined);
8
+ if (!f) throw new ProviderError("No fetch implementation available in this runtime.");
9
+ return f;
10
+ }
11
+
12
+ /**
13
+ * Yield every line of a streamed body, trimmed, as soon as it is complete;
14
+ * the (possibly empty) text after the last newline is yielded when the body ends.
15
+ * Chunk boundaries may fall anywhere, including inside a multi-byte character.
16
+ */
17
+ export async function* readLines(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {
18
+ const reader = body.getReader();
19
+ const decoder = new TextDecoder("utf-8");
20
+ let buffer = "";
21
+ for (;;) {
22
+ const { value, done } = await reader.read();
23
+ if (done) break;
24
+ buffer += decoder.decode(value, { stream: true });
25
+ const lines = buffer.split("\n");
26
+ buffer = lines.pop() ?? "";
27
+ for (const line of lines) yield line.trim();
28
+ }
29
+ yield buffer.trim();
30
+ }
31
+
32
+ /** Yield the payload of each `data:` line from an SSE response body. */
33
+ export async function* readSseData(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {
34
+ for await (const line of readLines(body)) {
35
+ if (line.startsWith("data:")) yield line.slice(5).trim();
36
+ }
37
+ }
38
+
39
+ /** Yield each complete JSON line from an NDJSON response body (e.g. Ollama). */
40
+ export async function* readJsonLines(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {
41
+ for await (const line of readLines(body)) {
42
+ if (line) yield line;
43
+ }
44
+ }
45
+
46
+ export async function ensureOk(response: Response, providerLabel: string): Promise<Response> {
47
+ if (response.ok && response.body) return response;
48
+ const detail = await response.text().catch(() => "");
49
+ throw new ProviderError(`${providerLabel} request failed: ${response.status} ${response.statusText} ${detail}`, {
50
+ details: { status: response.status },
51
+ });
52
+ }
@@ -0,0 +1,32 @@
1
+ // Shared AI system. Registry-driven (Strategy + Factory + Registry), consumed
2
+ // by the frontend, CLI and MCP. Adding a provider = a catalog entry.
3
+ export {
4
+ PROVIDER_CATALOG,
5
+ ALL_PROVIDER_IDS,
6
+ getProviderSpec,
7
+ } from "./catalog";
8
+ export type { ProviderFamily, ProviderSpec, AuthStyle } from "./catalog";
9
+ export { InMemoryProviderRegistry } from "./registry";
10
+ export { RegistryProviderFactory } from "./factory";
11
+ export { CatalogModelRegistry } from "./model-registry";
12
+ export {
13
+ createDefaultRegistry,
14
+ createDefaultFactory,
15
+ createModelRegistry,
16
+ } from "./bootstrap";
17
+ export type { FetchLike } from "./http/streaming";
18
+ export { OpenAiCompatibleProvider } from "./providers/openai-compatible-provider";
19
+ export { AnthropicProvider } from "./providers/anthropic-provider";
20
+ export { GeminiProvider } from "./providers/gemini-provider";
21
+ export { OllamaProvider } from "./providers/ollama-provider";
22
+ export { CohereProvider } from "./providers/cohere-provider";
23
+ export {
24
+ resolveApiKeyFromEnv,
25
+ detectConfiguredProviders,
26
+ type EnvLookup,
27
+ } from "./env-credentials";
28
+ export {
29
+ legacyProviderToCatalogId,
30
+ parseLegacyProviderAndModel,
31
+ } from "./legacy-adapter";
32
+ export type { ParsedLegacyProvider } from "./legacy-adapter";
@@ -0,0 +1,33 @@
1
+ import type { AiProviderId } from "../ports/ai";
2
+ import { PROVIDER_CATALOG } from "./catalog";
3
+
4
+ /**
5
+ * Bridges the legacy frontend/CLI provider ids ("claude", and the
6
+ * "provider:model" string form) to the shared catalog. Lets existing consumers
7
+ * adopt tools/src/ai without changing their stored config strings.
8
+ */
9
+ const LEGACY_ALIASES: Readonly<Record<string, AiProviderId>> = {
10
+ openai: "openai",
11
+ claude: "anthropic",
12
+ anthropic: "anthropic",
13
+ gemini: "gemini",
14
+ ollama: "ollama",
15
+ };
16
+
17
+ export function legacyProviderToCatalogId(legacy: string | undefined): AiProviderId {
18
+ const key = (legacy ?? "").trim().toLowerCase();
19
+ return LEGACY_ALIASES[key] ?? "openai";
20
+ }
21
+
22
+ export interface ParsedLegacyProvider {
23
+ readonly providerId: AiProviderId;
24
+ readonly model: string;
25
+ }
26
+
27
+ /** Parse a legacy "provider:model" string (e.g. "claude:claude-3-5-sonnet"). */
28
+ export function parseLegacyProviderAndModel(value: string | undefined): ParsedLegacyProvider {
29
+ const [rawProvider, rawModel] = (value ?? "").split(":");
30
+ const providerId = legacyProviderToCatalogId(rawProvider);
31
+ const model = (rawModel ?? "").trim() || PROVIDER_CATALOG[providerId].defaultModel;
32
+ return { providerId, model };
33
+ }
@@ -0,0 +1,13 @@
1
+ import type { AiProviderId, ModelDescriptor, ModelRegistry } from "../ports/ai";
2
+ import { PROVIDER_CATALOG } from "./catalog";
3
+
4
+ /** Model registry backed by the static provider catalog. */
5
+ export class CatalogModelRegistry implements ModelRegistry {
6
+ list(providerId: AiProviderId): readonly ModelDescriptor[] {
7
+ return PROVIDER_CATALOG[providerId]?.models ?? [];
8
+ }
9
+
10
+ defaultModel(providerId: AiProviderId): string | undefined {
11
+ return PROVIDER_CATALOG[providerId]?.defaultModel;
12
+ }
13
+ }
@@ -0,0 +1,77 @@
1
+ import type {
2
+ AIProvider,
3
+ AiMessage,
4
+ AiProviderId,
5
+ GenerateRequest,
6
+ GenerateResponse,
7
+ ProviderCapabilities,
8
+ ProviderConfig,
9
+ StreamResponse,
10
+ } from "../../ports/ai";
11
+ import type { ProviderSpec } from "../catalog";
12
+ import { type FetchLike, ensureOk, readSseData, resolveFetch } from "../http/streaming";
13
+ import { buildAuthHeaders, collect, resolveBaseUrl, toMultimodalParts } from "./shared";
14
+
15
+ /** Anthropic Messages API adapter (content_block_delta streaming). */
16
+ export class AnthropicProvider implements AIProvider {
17
+ readonly id: AiProviderId;
18
+ readonly capabilities: ProviderCapabilities;
19
+
20
+ constructor(
21
+ private readonly spec: ProviderSpec,
22
+ private readonly fetchImpl?: FetchLike,
23
+ ) {
24
+ this.id = spec.id;
25
+ this.capabilities = spec.capabilities;
26
+ }
27
+
28
+ private mapMessage(msg: AiMessage): unknown {
29
+ const parts = toMultimodalParts(msg, (img) => ({
30
+ type: "image",
31
+ source: { type: "base64", media_type: img.mimeType, data: img.data },
32
+ }));
33
+ return { role: msg.role, content: parts ?? msg.content };
34
+ }
35
+
36
+ async *stream(request: GenerateRequest, config: ProviderConfig): AsyncGenerator<string> {
37
+ const fetchImpl = resolveFetch(this.fetchImpl);
38
+ const base = resolveBaseUrl(this.spec, config);
39
+ const chatMessages = request.messages.filter((m) => m.role !== "system").map((m) => this.mapMessage(m));
40
+ const joinedSystem = request.messages
41
+ .filter((m) => m.role === "system")
42
+ .map((m) => m.content)
43
+ .join("\n");
44
+ const system = request.system ?? (joinedSystem || undefined);
45
+
46
+ const response = await fetchImpl(`${base}/messages`, {
47
+ method: "POST",
48
+ headers: buildAuthHeaders(this.spec, config),
49
+ body: JSON.stringify({
50
+ model: config.model || this.spec.defaultModel,
51
+ max_tokens: request.maxTokens ?? 4000,
52
+ temperature: request.temperature,
53
+ system,
54
+ messages: chatMessages,
55
+ stream: true,
56
+ }),
57
+ signal: request.signal,
58
+ });
59
+ const ok = await ensureOk(response, this.spec.label);
60
+ for await (const data of readSseData(ok.body as ReadableStream<Uint8Array>)) {
61
+ if (!data || data === "[DONE]") continue;
62
+ try {
63
+ const parsed = JSON.parse(data) as { type?: string; delta?: { text?: string } };
64
+ if (parsed.type === "content_block_delta" && parsed.delta?.text) {
65
+ yield parsed.delta.text;
66
+ }
67
+ } catch {
68
+ /* ignore partial frames */
69
+ }
70
+ }
71
+ }
72
+
73
+ async generate(request: GenerateRequest, config: ProviderConfig): Promise<GenerateResponse> {
74
+ const text = await collect(this.stream(request, config) as StreamResponse);
75
+ return { text, model: config.model || this.spec.defaultModel };
76
+ }
77
+ }
@@ -0,0 +1,66 @@
1
+ import type {
2
+ AIProvider,
3
+ AiProviderId,
4
+ GenerateRequest,
5
+ GenerateResponse,
6
+ ProviderCapabilities,
7
+ ProviderConfig,
8
+ StreamResponse,
9
+ } from "../../ports/ai";
10
+ import type { ProviderSpec } from "../catalog";
11
+ import { type FetchLike, ensureOk, readSseData, resolveFetch } from "../http/streaming";
12
+ import { buildAuthHeaders, collect, resolveBaseUrl } from "./shared";
13
+
14
+ /** Cohere Chat v2 adapter (SSE content-delta streaming). */
15
+ export class CohereProvider implements AIProvider {
16
+ readonly id: AiProviderId;
17
+ readonly capabilities: ProviderCapabilities;
18
+
19
+ constructor(
20
+ private readonly spec: ProviderSpec,
21
+ private readonly fetchImpl?: FetchLike,
22
+ ) {
23
+ this.id = spec.id;
24
+ this.capabilities = spec.capabilities;
25
+ }
26
+
27
+ async *stream(request: GenerateRequest, config: ProviderConfig): AsyncGenerator<string> {
28
+ const fetchImpl = resolveFetch(this.fetchImpl);
29
+ const base = resolveBaseUrl(this.spec, config);
30
+ const messages: Array<{ role: string; content: string }> = [];
31
+ if (request.system) messages.push({ role: "system", content: request.system });
32
+ for (const m of request.messages) messages.push({ role: m.role, content: m.content });
33
+
34
+ const response = await fetchImpl(`${base}/chat`, {
35
+ method: "POST",
36
+ headers: buildAuthHeaders(this.spec, config),
37
+ body: JSON.stringify({
38
+ model: config.model || this.spec.defaultModel,
39
+ messages,
40
+ temperature: request.temperature,
41
+ max_tokens: request.maxTokens,
42
+ stream: true,
43
+ }),
44
+ signal: request.signal,
45
+ });
46
+ const ok = await ensureOk(response, this.spec.label);
47
+ for await (const data of readSseData(ok.body as ReadableStream<Uint8Array>)) {
48
+ if (!data) continue;
49
+ try {
50
+ const parsed = JSON.parse(data) as {
51
+ type?: string;
52
+ delta?: { message?: { content?: { text?: string } } };
53
+ };
54
+ const text = parsed.delta?.message?.content?.text;
55
+ if (parsed.type === "content-delta" && text) yield text;
56
+ } catch {
57
+ /* ignore partial frames */
58
+ }
59
+ }
60
+ }
61
+
62
+ async generate(request: GenerateRequest, config: ProviderConfig): Promise<GenerateResponse> {
63
+ const text = await collect(this.stream(request, config) as StreamResponse);
64
+ return { text, model: config.model || this.spec.defaultModel };
65
+ }
66
+ }