@gitpagedocs/tools 1.1.62 → 1.1.63
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/README.md +33 -33
- package/package.json +1 -1
- package/src/ai/bootstrap.ts +50 -50
- package/src/ai/catalog.ts +188 -188
- package/src/ai/factory.ts +14 -14
- package/src/ai/http/streaming.ts +60 -60
- package/src/ai/index.ts +27 -27
- package/src/ai/legacy-adapter.ts +33 -33
- package/src/ai/model-registry.ts +13 -13
- package/src/ai/providers/anthropic-provider.ts +83 -83
- package/src/ai/providers/cohere-provider.ts +66 -66
- package/src/ai/providers/gemini-provider.ts +84 -84
- package/src/ai/providers/ollama-provider.ts +69 -69
- package/src/ai/providers/openai-compatible-provider.ts +75 -75
- package/src/ai/providers/shared.ts +72 -72
- package/src/ai/registry.ts +29 -29
- package/src/cache/file-cache.ts +86 -86
- package/src/cache/index.ts +9 -9
- package/src/cache/memory-cache.ts +47 -47
- package/src/cache/web-storage-cache.ts +91 -91
- package/src/config/config-loader.ts +59 -59
- package/src/config/index.ts +1 -1
- package/src/constants/config.ts +8 -8
- package/src/constants/index.ts +1 -1
- package/src/crypto/doc-access.ts +62 -62
- package/src/crypto/index.ts +4 -4
- package/src/crypto/node-crypto-service.ts +87 -87
- package/src/crypto/web-crypto-service.ts +102 -102
- package/src/crypto/web.ts +4 -4
- package/src/documentation/doc-generator.ts +74 -74
- package/src/documentation/doc-updater.ts +47 -47
- package/src/documentation/index.ts +18 -18
- package/src/documentation/marker-patcher.ts +33 -33
- package/src/documentation/sections.ts +84 -84
- package/src/errors/app-error.ts +84 -84
- package/src/errors/index.ts +1 -1
- package/src/filesystem/file-service.ts +121 -121
- package/src/filesystem/index.ts +2 -2
- package/src/index.ts +25 -25
- package/src/logger/index.ts +2 -2
- package/src/logger/logger.ts +73 -73
- package/src/logger/redaction.ts +43 -43
- package/src/platform/index.ts +1 -1
- package/src/platform/user-config-dir.ts +48 -48
- package/src/ports/ai.ts +109 -109
- package/src/ports/cache.ts +16 -16
- package/src/ports/config.ts +21 -21
- package/src/ports/crypto.ts +33 -33
- package/src/ports/index.ts +15 -15
- package/src/ports/logger.ts +23 -23
- package/src/ports/security.ts +42 -42
- package/src/security/credential-vault.ts +117 -117
- package/src/security/file-vault-storage.ts +25 -25
- package/src/security/index.ts +8 -8
- package/src/security/migrate-plaintext-key.ts +38 -38
- package/src/security/password-gate.ts +62 -62
- package/src/security/web-storage-vault-storage.ts +23 -23
- package/src/security/web.ts +9 -9
package/src/ai/http/streaming.ts
CHANGED
|
@@ -1,60 +1,60 @@
|
|
|
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
|
-
/** Yield the payload of each `data:` line from an SSE response body. */
|
|
13
|
-
export async function* readSseData(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {
|
|
14
|
-
const reader = body.getReader();
|
|
15
|
-
const decoder = new TextDecoder("utf-8");
|
|
16
|
-
let buffer = "";
|
|
17
|
-
for (;;) {
|
|
18
|
-
const { value, done } = await reader.read();
|
|
19
|
-
if (done) break;
|
|
20
|
-
buffer += decoder.decode(value, { stream: true });
|
|
21
|
-
const lines = buffer.split("\n");
|
|
22
|
-
buffer = lines.pop() ?? "";
|
|
23
|
-
for (const line of lines) {
|
|
24
|
-
const trimmed = line.trim();
|
|
25
|
-
if (trimmed.startsWith("data:")) {
|
|
26
|
-
yield trimmed.slice(5).trim();
|
|
27
|
-
}
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
const tail = buffer.trim();
|
|
31
|
-
if (tail.startsWith("data:")) yield tail.slice(5).trim();
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
/** Yield each complete JSON line from an NDJSON response body (e.g. Ollama). */
|
|
35
|
-
export async function* readJsonLines(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {
|
|
36
|
-
const reader = body.getReader();
|
|
37
|
-
const decoder = new TextDecoder("utf-8");
|
|
38
|
-
let buffer = "";
|
|
39
|
-
for (;;) {
|
|
40
|
-
const { value, done } = await reader.read();
|
|
41
|
-
if (done) break;
|
|
42
|
-
buffer += decoder.decode(value, { stream: true });
|
|
43
|
-
const lines = buffer.split("\n");
|
|
44
|
-
buffer = lines.pop() ?? "";
|
|
45
|
-
for (const line of lines) {
|
|
46
|
-
const trimmed = line.trim();
|
|
47
|
-
if (trimmed) yield trimmed;
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
const tail = buffer.trim();
|
|
51
|
-
if (tail) yield tail;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export async function ensureOk(response: Response, providerLabel: string): Promise<Response> {
|
|
55
|
-
if (response.ok && response.body) return response;
|
|
56
|
-
const detail = await response.text().catch(() => "");
|
|
57
|
-
throw new ProviderError(`${providerLabel} request failed: ${response.status} ${response.statusText} ${detail}`, {
|
|
58
|
-
details: { status: response.status },
|
|
59
|
-
});
|
|
60
|
-
}
|
|
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
|
+
/** Yield the payload of each `data:` line from an SSE response body. */
|
|
13
|
+
export async function* readSseData(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {
|
|
14
|
+
const reader = body.getReader();
|
|
15
|
+
const decoder = new TextDecoder("utf-8");
|
|
16
|
+
let buffer = "";
|
|
17
|
+
for (;;) {
|
|
18
|
+
const { value, done } = await reader.read();
|
|
19
|
+
if (done) break;
|
|
20
|
+
buffer += decoder.decode(value, { stream: true });
|
|
21
|
+
const lines = buffer.split("\n");
|
|
22
|
+
buffer = lines.pop() ?? "";
|
|
23
|
+
for (const line of lines) {
|
|
24
|
+
const trimmed = line.trim();
|
|
25
|
+
if (trimmed.startsWith("data:")) {
|
|
26
|
+
yield trimmed.slice(5).trim();
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
const tail = buffer.trim();
|
|
31
|
+
if (tail.startsWith("data:")) yield tail.slice(5).trim();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Yield each complete JSON line from an NDJSON response body (e.g. Ollama). */
|
|
35
|
+
export async function* readJsonLines(body: ReadableStream<Uint8Array>): AsyncGenerator<string> {
|
|
36
|
+
const reader = body.getReader();
|
|
37
|
+
const decoder = new TextDecoder("utf-8");
|
|
38
|
+
let buffer = "";
|
|
39
|
+
for (;;) {
|
|
40
|
+
const { value, done } = await reader.read();
|
|
41
|
+
if (done) break;
|
|
42
|
+
buffer += decoder.decode(value, { stream: true });
|
|
43
|
+
const lines = buffer.split("\n");
|
|
44
|
+
buffer = lines.pop() ?? "";
|
|
45
|
+
for (const line of lines) {
|
|
46
|
+
const trimmed = line.trim();
|
|
47
|
+
if (trimmed) yield trimmed;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
const tail = buffer.trim();
|
|
51
|
+
if (tail) yield tail;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export async function ensureOk(response: Response, providerLabel: string): Promise<Response> {
|
|
55
|
+
if (response.ok && response.body) return response;
|
|
56
|
+
const detail = await response.text().catch(() => "");
|
|
57
|
+
throw new ProviderError(`${providerLabel} request failed: ${response.status} ${response.statusText} ${detail}`, {
|
|
58
|
+
details: { status: response.status },
|
|
59
|
+
});
|
|
60
|
+
}
|
package/src/ai/index.ts
CHANGED
|
@@ -1,27 +1,27 @@
|
|
|
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
|
-
legacyProviderToCatalogId,
|
|
25
|
-
parseLegacyProviderAndModel,
|
|
26
|
-
} from "./legacy-adapter";
|
|
27
|
-
export type { ParsedLegacyProvider } from "./legacy-adapter";
|
|
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
|
+
legacyProviderToCatalogId,
|
|
25
|
+
parseLegacyProviderAndModel,
|
|
26
|
+
} from "./legacy-adapter";
|
|
27
|
+
export type { ParsedLegacyProvider } from "./legacy-adapter";
|
package/src/ai/legacy-adapter.ts
CHANGED
|
@@ -1,33 +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
|
-
}
|
|
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
|
+
}
|
package/src/ai/model-registry.ts
CHANGED
|
@@ -1,13 +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
|
-
}
|
|
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
|
+
}
|
|
@@ -1,83 +1,83 @@
|
|
|
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 } 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 images = (msg.attachments ?? []).filter((a) => a.kind === "image");
|
|
30
|
-
if (images.length === 0) return { role: msg.role, content: msg.content };
|
|
31
|
-
const content: unknown[] = [];
|
|
32
|
-
if (msg.content) content.push({ type: "text", text: msg.content });
|
|
33
|
-
for (const img of images) {
|
|
34
|
-
content.push({
|
|
35
|
-
type: "image",
|
|
36
|
-
source: { type: "base64", media_type: img.mimeType, data: img.data },
|
|
37
|
-
});
|
|
38
|
-
}
|
|
39
|
-
return { role: msg.role, content };
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
async *stream(request: GenerateRequest, config: ProviderConfig): AsyncGenerator<string> {
|
|
43
|
-
const fetchImpl = resolveFetch(this.fetchImpl);
|
|
44
|
-
const base = resolveBaseUrl(this.spec, config);
|
|
45
|
-
const chatMessages = request.messages.filter((m) => m.role !== "system").map((m) => this.mapMessage(m));
|
|
46
|
-
const joinedSystem = request.messages
|
|
47
|
-
.filter((m) => m.role === "system")
|
|
48
|
-
.map((m) => m.content)
|
|
49
|
-
.join("\n");
|
|
50
|
-
const system = request.system ?? (joinedSystem || undefined);
|
|
51
|
-
|
|
52
|
-
const response = await fetchImpl(`${base}/messages`, {
|
|
53
|
-
method: "POST",
|
|
54
|
-
headers: buildAuthHeaders(this.spec, config),
|
|
55
|
-
body: JSON.stringify({
|
|
56
|
-
model: config.model || this.spec.defaultModel,
|
|
57
|
-
max_tokens: request.maxTokens ?? 4000,
|
|
58
|
-
temperature: request.temperature,
|
|
59
|
-
system,
|
|
60
|
-
messages: chatMessages,
|
|
61
|
-
stream: true,
|
|
62
|
-
}),
|
|
63
|
-
signal: request.signal,
|
|
64
|
-
});
|
|
65
|
-
const ok = await ensureOk(response, this.spec.label);
|
|
66
|
-
for await (const data of readSseData(ok.body as ReadableStream<Uint8Array>)) {
|
|
67
|
-
if (!data || data === "[DONE]") continue;
|
|
68
|
-
try {
|
|
69
|
-
const parsed = JSON.parse(data) as { type?: string; delta?: { text?: string } };
|
|
70
|
-
if (parsed.type === "content_block_delta" && parsed.delta?.text) {
|
|
71
|
-
yield parsed.delta.text;
|
|
72
|
-
}
|
|
73
|
-
} catch {
|
|
74
|
-
/* ignore partial frames */
|
|
75
|
-
}
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
async generate(request: GenerateRequest, config: ProviderConfig): Promise<GenerateResponse> {
|
|
80
|
-
const text = await collect(this.stream(request, config) as StreamResponse);
|
|
81
|
-
return { text, model: config.model || this.spec.defaultModel };
|
|
82
|
-
}
|
|
83
|
-
}
|
|
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 } 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 images = (msg.attachments ?? []).filter((a) => a.kind === "image");
|
|
30
|
+
if (images.length === 0) return { role: msg.role, content: msg.content };
|
|
31
|
+
const content: unknown[] = [];
|
|
32
|
+
if (msg.content) content.push({ type: "text", text: msg.content });
|
|
33
|
+
for (const img of images) {
|
|
34
|
+
content.push({
|
|
35
|
+
type: "image",
|
|
36
|
+
source: { type: "base64", media_type: img.mimeType, data: img.data },
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
return { role: msg.role, content };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async *stream(request: GenerateRequest, config: ProviderConfig): AsyncGenerator<string> {
|
|
43
|
+
const fetchImpl = resolveFetch(this.fetchImpl);
|
|
44
|
+
const base = resolveBaseUrl(this.spec, config);
|
|
45
|
+
const chatMessages = request.messages.filter((m) => m.role !== "system").map((m) => this.mapMessage(m));
|
|
46
|
+
const joinedSystem = request.messages
|
|
47
|
+
.filter((m) => m.role === "system")
|
|
48
|
+
.map((m) => m.content)
|
|
49
|
+
.join("\n");
|
|
50
|
+
const system = request.system ?? (joinedSystem || undefined);
|
|
51
|
+
|
|
52
|
+
const response = await fetchImpl(`${base}/messages`, {
|
|
53
|
+
method: "POST",
|
|
54
|
+
headers: buildAuthHeaders(this.spec, config),
|
|
55
|
+
body: JSON.stringify({
|
|
56
|
+
model: config.model || this.spec.defaultModel,
|
|
57
|
+
max_tokens: request.maxTokens ?? 4000,
|
|
58
|
+
temperature: request.temperature,
|
|
59
|
+
system,
|
|
60
|
+
messages: chatMessages,
|
|
61
|
+
stream: true,
|
|
62
|
+
}),
|
|
63
|
+
signal: request.signal,
|
|
64
|
+
});
|
|
65
|
+
const ok = await ensureOk(response, this.spec.label);
|
|
66
|
+
for await (const data of readSseData(ok.body as ReadableStream<Uint8Array>)) {
|
|
67
|
+
if (!data || data === "[DONE]") continue;
|
|
68
|
+
try {
|
|
69
|
+
const parsed = JSON.parse(data) as { type?: string; delta?: { text?: string } };
|
|
70
|
+
if (parsed.type === "content_block_delta" && parsed.delta?.text) {
|
|
71
|
+
yield parsed.delta.text;
|
|
72
|
+
}
|
|
73
|
+
} catch {
|
|
74
|
+
/* ignore partial frames */
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async generate(request: GenerateRequest, config: ProviderConfig): Promise<GenerateResponse> {
|
|
80
|
+
const text = await collect(this.stream(request, config) as StreamResponse);
|
|
81
|
+
return { text, model: config.model || this.spec.defaultModel };
|
|
82
|
+
}
|
|
83
|
+
}
|
|
@@ -1,66 +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
|
-
}
|
|
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
|
+
}
|