@gitpagedocs/tools 1.1.62 → 1.1.64
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
|
@@ -1,84 +1,84 @@
|
|
|
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 { collect, requireKey, resolveBaseUrl } from "./shared";
|
|
14
|
-
|
|
15
|
-
/** Google Gemini streamGenerateContent adapter (SSE, API key in query). */
|
|
16
|
-
export class GeminiProvider 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 mapParts(msg: AiMessage): unknown[] {
|
|
29
|
-
const parts: unknown[] = [];
|
|
30
|
-
if (msg.content) parts.push({ text: msg.content });
|
|
31
|
-
for (const att of msg.attachments ?? []) {
|
|
32
|
-
parts.push({ inlineData: { mimeType: att.mimeType, data: att.data } });
|
|
33
|
-
}
|
|
34
|
-
return parts;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
async *stream(request: GenerateRequest, config: ProviderConfig): AsyncGenerator<string> {
|
|
38
|
-
const fetchImpl = resolveFetch(this.fetchImpl);
|
|
39
|
-
requireKey(this.spec, config);
|
|
40
|
-
const base = resolveBaseUrl(this.spec, config);
|
|
41
|
-
const model = encodeURIComponent(config.model || this.spec.defaultModel);
|
|
42
|
-
const query = new URLSearchParams({ alt: "sse", key: config.apiKey as string });
|
|
43
|
-
const url = `${base}/${model}:streamGenerateContent?${query.toString()}`;
|
|
44
|
-
|
|
45
|
-
const contents = request.messages
|
|
46
|
-
.filter((m) => m.role !== "system")
|
|
47
|
-
.map((m) => ({ role: m.role === "assistant" ? "model" : "user", parts: this.mapParts(m) }));
|
|
48
|
-
const systemText =
|
|
49
|
-
request.system ??
|
|
50
|
-
request.messages
|
|
51
|
-
.filter((m) => m.role === "system")
|
|
52
|
-
.map((m) => m.content)
|
|
53
|
-
.join("\n");
|
|
54
|
-
|
|
55
|
-
const response = await fetchImpl(url, {
|
|
56
|
-
method: "POST",
|
|
57
|
-
headers: { "Content-Type": "application/json" },
|
|
58
|
-
body: JSON.stringify({
|
|
59
|
-
contents,
|
|
60
|
-
systemInstruction: systemText ? { parts: [{ text: systemText }] } : undefined,
|
|
61
|
-
generationConfig: { temperature: request.temperature, maxOutputTokens: request.maxTokens },
|
|
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) continue;
|
|
68
|
-
try {
|
|
69
|
-
const parsed = JSON.parse(data) as {
|
|
70
|
-
candidates?: Array<{ content?: { parts?: Array<{ text?: string }> } }>;
|
|
71
|
-
};
|
|
72
|
-
const text = parsed.candidates?.[0]?.content?.parts?.map((p) => p.text ?? "").join("") ?? "";
|
|
73
|
-
if (text) yield text;
|
|
74
|
-
} catch {
|
|
75
|
-
/* ignore partial frames */
|
|
76
|
-
}
|
|
77
|
-
}
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
async generate(request: GenerateRequest, config: ProviderConfig): Promise<GenerateResponse> {
|
|
81
|
-
const text = await collect(this.stream(request, config) as StreamResponse);
|
|
82
|
-
return { text, model: config.model || this.spec.defaultModel };
|
|
83
|
-
}
|
|
84
|
-
}
|
|
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 { collect, requireKey, resolveBaseUrl } from "./shared";
|
|
14
|
+
|
|
15
|
+
/** Google Gemini streamGenerateContent adapter (SSE, API key in query). */
|
|
16
|
+
export class GeminiProvider 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 mapParts(msg: AiMessage): unknown[] {
|
|
29
|
+
const parts: unknown[] = [];
|
|
30
|
+
if (msg.content) parts.push({ text: msg.content });
|
|
31
|
+
for (const att of msg.attachments ?? []) {
|
|
32
|
+
parts.push({ inlineData: { mimeType: att.mimeType, data: att.data } });
|
|
33
|
+
}
|
|
34
|
+
return parts;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async *stream(request: GenerateRequest, config: ProviderConfig): AsyncGenerator<string> {
|
|
38
|
+
const fetchImpl = resolveFetch(this.fetchImpl);
|
|
39
|
+
requireKey(this.spec, config);
|
|
40
|
+
const base = resolveBaseUrl(this.spec, config);
|
|
41
|
+
const model = encodeURIComponent(config.model || this.spec.defaultModel);
|
|
42
|
+
const query = new URLSearchParams({ alt: "sse", key: config.apiKey as string });
|
|
43
|
+
const url = `${base}/${model}:streamGenerateContent?${query.toString()}`;
|
|
44
|
+
|
|
45
|
+
const contents = request.messages
|
|
46
|
+
.filter((m) => m.role !== "system")
|
|
47
|
+
.map((m) => ({ role: m.role === "assistant" ? "model" : "user", parts: this.mapParts(m) }));
|
|
48
|
+
const systemText =
|
|
49
|
+
request.system ??
|
|
50
|
+
request.messages
|
|
51
|
+
.filter((m) => m.role === "system")
|
|
52
|
+
.map((m) => m.content)
|
|
53
|
+
.join("\n");
|
|
54
|
+
|
|
55
|
+
const response = await fetchImpl(url, {
|
|
56
|
+
method: "POST",
|
|
57
|
+
headers: { "Content-Type": "application/json" },
|
|
58
|
+
body: JSON.stringify({
|
|
59
|
+
contents,
|
|
60
|
+
systemInstruction: systemText ? { parts: [{ text: systemText }] } : undefined,
|
|
61
|
+
generationConfig: { temperature: request.temperature, maxOutputTokens: request.maxTokens },
|
|
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) continue;
|
|
68
|
+
try {
|
|
69
|
+
const parsed = JSON.parse(data) as {
|
|
70
|
+
candidates?: Array<{ content?: { parts?: Array<{ text?: string }> } }>;
|
|
71
|
+
};
|
|
72
|
+
const text = parsed.candidates?.[0]?.content?.parts?.map((p) => p.text ?? "").join("") ?? "";
|
|
73
|
+
if (text) yield text;
|
|
74
|
+
} catch {
|
|
75
|
+
/* ignore partial frames */
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
async generate(request: GenerateRequest, config: ProviderConfig): Promise<GenerateResponse> {
|
|
81
|
+
const text = await collect(this.stream(request, config) as StreamResponse);
|
|
82
|
+
return { text, model: config.model || this.spec.defaultModel };
|
|
83
|
+
}
|
|
84
|
+
}
|
|
@@ -1,69 +1,69 @@
|
|
|
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, readJsonLines, resolveFetch } from "../http/streaming";
|
|
12
|
-
import { collect, resolveBaseUrl } from "./shared";
|
|
13
|
-
|
|
14
|
-
/** Local Ollama /api/chat adapter (NDJSON streaming, no auth). */
|
|
15
|
-
export class OllamaProvider 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
|
-
private endpoint(config: ProviderConfig): string {
|
|
28
|
-
const base = resolveBaseUrl(this.spec, config);
|
|
29
|
-
return /\/api\/chat\/?$/i.test(base) ? base.replace(/\/$/, "") : `${base}/api/chat`;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
async *stream(request: GenerateRequest, config: ProviderConfig): AsyncGenerator<string> {
|
|
33
|
-
const fetchImpl = resolveFetch(this.fetchImpl);
|
|
34
|
-
const messages = request.messages.map((m) => {
|
|
35
|
-
const images = (m.attachments ?? []).filter((a) => a.kind === "image").map((a) => a.data);
|
|
36
|
-
return images.length > 0
|
|
37
|
-
? { role: m.role, content: m.content, images }
|
|
38
|
-
: { role: m.role, content: m.content };
|
|
39
|
-
});
|
|
40
|
-
if (request.system) messages.unshift({ role: "system", content: request.system });
|
|
41
|
-
|
|
42
|
-
const response = await fetchImpl(this.endpoint(config), {
|
|
43
|
-
method: "POST",
|
|
44
|
-
headers: { "Content-Type": "application/json" },
|
|
45
|
-
body: JSON.stringify({
|
|
46
|
-
model: config.model || this.spec.defaultModel,
|
|
47
|
-
messages,
|
|
48
|
-
options: { temperature: request.temperature },
|
|
49
|
-
stream: true,
|
|
50
|
-
}),
|
|
51
|
-
signal: request.signal,
|
|
52
|
-
});
|
|
53
|
-
const ok = await ensureOk(response, this.spec.label);
|
|
54
|
-
for await (const line of readJsonLines(ok.body as ReadableStream<Uint8Array>)) {
|
|
55
|
-
try {
|
|
56
|
-
const parsed = JSON.parse(line) as { message?: { content?: string }; done?: boolean };
|
|
57
|
-
if (parsed.message?.content) yield parsed.message.content;
|
|
58
|
-
if (parsed.done) break;
|
|
59
|
-
} catch {
|
|
60
|
-
/* ignore partial frames */
|
|
61
|
-
}
|
|
62
|
-
}
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
async generate(request: GenerateRequest, config: ProviderConfig): Promise<GenerateResponse> {
|
|
66
|
-
const text = await collect(this.stream(request, config) as StreamResponse);
|
|
67
|
-
return { text, model: config.model || this.spec.defaultModel };
|
|
68
|
-
}
|
|
69
|
-
}
|
|
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, readJsonLines, resolveFetch } from "../http/streaming";
|
|
12
|
+
import { collect, resolveBaseUrl } from "./shared";
|
|
13
|
+
|
|
14
|
+
/** Local Ollama /api/chat adapter (NDJSON streaming, no auth). */
|
|
15
|
+
export class OllamaProvider 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
|
+
private endpoint(config: ProviderConfig): string {
|
|
28
|
+
const base = resolveBaseUrl(this.spec, config);
|
|
29
|
+
return /\/api\/chat\/?$/i.test(base) ? base.replace(/\/$/, "") : `${base}/api/chat`;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async *stream(request: GenerateRequest, config: ProviderConfig): AsyncGenerator<string> {
|
|
33
|
+
const fetchImpl = resolveFetch(this.fetchImpl);
|
|
34
|
+
const messages = request.messages.map((m) => {
|
|
35
|
+
const images = (m.attachments ?? []).filter((a) => a.kind === "image").map((a) => a.data);
|
|
36
|
+
return images.length > 0
|
|
37
|
+
? { role: m.role, content: m.content, images }
|
|
38
|
+
: { role: m.role, content: m.content };
|
|
39
|
+
});
|
|
40
|
+
if (request.system) messages.unshift({ role: "system", content: request.system });
|
|
41
|
+
|
|
42
|
+
const response = await fetchImpl(this.endpoint(config), {
|
|
43
|
+
method: "POST",
|
|
44
|
+
headers: { "Content-Type": "application/json" },
|
|
45
|
+
body: JSON.stringify({
|
|
46
|
+
model: config.model || this.spec.defaultModel,
|
|
47
|
+
messages,
|
|
48
|
+
options: { temperature: request.temperature },
|
|
49
|
+
stream: true,
|
|
50
|
+
}),
|
|
51
|
+
signal: request.signal,
|
|
52
|
+
});
|
|
53
|
+
const ok = await ensureOk(response, this.spec.label);
|
|
54
|
+
for await (const line of readJsonLines(ok.body as ReadableStream<Uint8Array>)) {
|
|
55
|
+
try {
|
|
56
|
+
const parsed = JSON.parse(line) as { message?: { content?: string }; done?: boolean };
|
|
57
|
+
if (parsed.message?.content) yield parsed.message.content;
|
|
58
|
+
if (parsed.done) break;
|
|
59
|
+
} catch {
|
|
60
|
+
/* ignore partial frames */
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async generate(request: GenerateRequest, config: ProviderConfig): Promise<GenerateResponse> {
|
|
66
|
+
const text = await collect(this.stream(request, config) as StreamResponse);
|
|
67
|
+
return { text, model: config.model || this.spec.defaultModel };
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -1,75 +1,75 @@
|
|
|
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, toOpenAiMessages } from "./shared";
|
|
13
|
-
|
|
14
|
-
/**
|
|
15
|
-
* Adapter for every OpenAI chat-completions-compatible provider: OpenAI,
|
|
16
|
-
* OpenRouter, Groq, Mistral, DeepSeek, Together, Fireworks, Perplexity, xAI and
|
|
17
|
-
* Azure OpenAI. One strategy, parameterized by the catalog spec.
|
|
18
|
-
*/
|
|
19
|
-
export class OpenAiCompatibleProvider implements AIProvider {
|
|
20
|
-
readonly id: AiProviderId;
|
|
21
|
-
readonly capabilities: ProviderCapabilities;
|
|
22
|
-
|
|
23
|
-
constructor(
|
|
24
|
-
private readonly spec: ProviderSpec,
|
|
25
|
-
private readonly fetchImpl?: FetchLike,
|
|
26
|
-
) {
|
|
27
|
-
this.id = spec.id;
|
|
28
|
-
this.capabilities = spec.capabilities;
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
private endpoint(config: ProviderConfig): string {
|
|
32
|
-
const base = resolveBaseUrl(this.spec, config);
|
|
33
|
-
// Azure deployment URLs already include the full path via baseUrl.
|
|
34
|
-
if (this.spec.id === "azure-openai") return base;
|
|
35
|
-
return `${base}/chat/completions`;
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
private body(request: GenerateRequest, config: ProviderConfig, stream: boolean): string {
|
|
39
|
-
return JSON.stringify({
|
|
40
|
-
model: config.model || this.spec.defaultModel,
|
|
41
|
-
messages: toOpenAiMessages(request),
|
|
42
|
-
temperature: request.temperature,
|
|
43
|
-
max_tokens: request.maxTokens,
|
|
44
|
-
stream,
|
|
45
|
-
});
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
async *stream(request: GenerateRequest, config: ProviderConfig): AsyncGenerator<string> {
|
|
49
|
-
const fetchImpl = resolveFetch(this.fetchImpl);
|
|
50
|
-
const response = await fetchImpl(this.endpoint(config), {
|
|
51
|
-
method: "POST",
|
|
52
|
-
headers: buildAuthHeaders(this.spec, config),
|
|
53
|
-
body: this.body(request, config, true),
|
|
54
|
-
signal: request.signal,
|
|
55
|
-
});
|
|
56
|
-
const ok = await ensureOk(response, this.spec.label);
|
|
57
|
-
for await (const data of readSseData(ok.body as ReadableStream<Uint8Array>)) {
|
|
58
|
-
if (!data || data === "[DONE]") continue;
|
|
59
|
-
try {
|
|
60
|
-
const parsed = JSON.parse(data) as {
|
|
61
|
-
choices?: Array<{ delta?: { content?: string } }>;
|
|
62
|
-
};
|
|
63
|
-
const delta = parsed.choices?.[0]?.delta?.content;
|
|
64
|
-
if (delta) yield delta;
|
|
65
|
-
} catch {
|
|
66
|
-
/* ignore partial JSON frames */
|
|
67
|
-
}
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
async generate(request: GenerateRequest, config: ProviderConfig): Promise<GenerateResponse> {
|
|
72
|
-
const text = await collect(this.stream(request, config) as StreamResponse);
|
|
73
|
-
return { text, model: config.model || this.spec.defaultModel };
|
|
74
|
-
}
|
|
75
|
-
}
|
|
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, toOpenAiMessages } from "./shared";
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Adapter for every OpenAI chat-completions-compatible provider: OpenAI,
|
|
16
|
+
* OpenRouter, Groq, Mistral, DeepSeek, Together, Fireworks, Perplexity, xAI and
|
|
17
|
+
* Azure OpenAI. One strategy, parameterized by the catalog spec.
|
|
18
|
+
*/
|
|
19
|
+
export class OpenAiCompatibleProvider implements AIProvider {
|
|
20
|
+
readonly id: AiProviderId;
|
|
21
|
+
readonly capabilities: ProviderCapabilities;
|
|
22
|
+
|
|
23
|
+
constructor(
|
|
24
|
+
private readonly spec: ProviderSpec,
|
|
25
|
+
private readonly fetchImpl?: FetchLike,
|
|
26
|
+
) {
|
|
27
|
+
this.id = spec.id;
|
|
28
|
+
this.capabilities = spec.capabilities;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
private endpoint(config: ProviderConfig): string {
|
|
32
|
+
const base = resolveBaseUrl(this.spec, config);
|
|
33
|
+
// Azure deployment URLs already include the full path via baseUrl.
|
|
34
|
+
if (this.spec.id === "azure-openai") return base;
|
|
35
|
+
return `${base}/chat/completions`;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
private body(request: GenerateRequest, config: ProviderConfig, stream: boolean): string {
|
|
39
|
+
return JSON.stringify({
|
|
40
|
+
model: config.model || this.spec.defaultModel,
|
|
41
|
+
messages: toOpenAiMessages(request),
|
|
42
|
+
temperature: request.temperature,
|
|
43
|
+
max_tokens: request.maxTokens,
|
|
44
|
+
stream,
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async *stream(request: GenerateRequest, config: ProviderConfig): AsyncGenerator<string> {
|
|
49
|
+
const fetchImpl = resolveFetch(this.fetchImpl);
|
|
50
|
+
const response = await fetchImpl(this.endpoint(config), {
|
|
51
|
+
method: "POST",
|
|
52
|
+
headers: buildAuthHeaders(this.spec, config),
|
|
53
|
+
body: this.body(request, config, true),
|
|
54
|
+
signal: request.signal,
|
|
55
|
+
});
|
|
56
|
+
const ok = await ensureOk(response, this.spec.label);
|
|
57
|
+
for await (const data of readSseData(ok.body as ReadableStream<Uint8Array>)) {
|
|
58
|
+
if (!data || data === "[DONE]") continue;
|
|
59
|
+
try {
|
|
60
|
+
const parsed = JSON.parse(data) as {
|
|
61
|
+
choices?: Array<{ delta?: { content?: string } }>;
|
|
62
|
+
};
|
|
63
|
+
const delta = parsed.choices?.[0]?.delta?.content;
|
|
64
|
+
if (delta) yield delta;
|
|
65
|
+
} catch {
|
|
66
|
+
/* ignore partial JSON frames */
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
async generate(request: GenerateRequest, config: ProviderConfig): Promise<GenerateResponse> {
|
|
72
|
+
const text = await collect(this.stream(request, config) as StreamResponse);
|
|
73
|
+
return { text, model: config.model || this.spec.defaultModel };
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -1,72 +1,72 @@
|
|
|
1
|
-
import type { AiMessage, GenerateRequest, ProviderConfig } from "../../ports/ai";
|
|
2
|
-
import type { ProviderSpec } from "../catalog";
|
|
3
|
-
import { ProviderError } from "../../errors/app-error";
|
|
4
|
-
|
|
5
|
-
/** Build request auth headers from the provider's declared auth style. */
|
|
6
|
-
export function buildAuthHeaders(spec: ProviderSpec, config: ProviderConfig): Record<string, string> {
|
|
7
|
-
const headers: Record<string, string> = { "Content-Type": "application/json", ...config.extraHeaders };
|
|
8
|
-
switch (spec.auth) {
|
|
9
|
-
case "bearer":
|
|
10
|
-
requireKey(spec, config);
|
|
11
|
-
headers.Authorization = `Bearer ${config.apiKey}`;
|
|
12
|
-
break;
|
|
13
|
-
case "x-api-key":
|
|
14
|
-
requireKey(spec, config);
|
|
15
|
-
headers["x-api-key"] = config.apiKey as string;
|
|
16
|
-
headers["anthropic-version"] = "2023-06-01";
|
|
17
|
-
// Required for direct browser calls (the docs run as a static site);
|
|
18
|
-
// ignored server-side. Without it Anthropic rejects the CORS preflight.
|
|
19
|
-
headers["anthropic-dangerous-direct-browser-access"] = "true";
|
|
20
|
-
break;
|
|
21
|
-
case "api-key-header":
|
|
22
|
-
requireKey(spec, config);
|
|
23
|
-
headers["api-key"] = config.apiKey as string;
|
|
24
|
-
break;
|
|
25
|
-
case "query-key":
|
|
26
|
-
case "none":
|
|
27
|
-
break;
|
|
28
|
-
}
|
|
29
|
-
return headers;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export function requireKey(spec: ProviderSpec, config: ProviderConfig): void {
|
|
33
|
-
if (!config.apiKey) {
|
|
34
|
-
throw new ProviderError(`${spec.label} requires an API key.`, { details: { provider: spec.id } });
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
export function resolveBaseUrl(spec: ProviderSpec, config: ProviderConfig): string {
|
|
39
|
-
const base = (config.baseUrl ?? spec.baseUrl).replace(/\/+$/, "");
|
|
40
|
-
if (spec.requiresBaseUrl && !config.baseUrl && !spec.baseUrl) {
|
|
41
|
-
throw new ProviderError(`${spec.label} requires a baseUrl.`, { details: { provider: spec.id } });
|
|
42
|
-
}
|
|
43
|
-
return base;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
/** OpenAI chat-completions message shape (text + optional image parts). */
|
|
47
|
-
export function toOpenAiMessages(request: GenerateRequest): unknown[] {
|
|
48
|
-
const out: unknown[] = [];
|
|
49
|
-
if (request.system) out.push({ role: "system", content: request.system });
|
|
50
|
-
for (const msg of request.messages) {
|
|
51
|
-
out.push(mapOpenAiMessage(msg));
|
|
52
|
-
}
|
|
53
|
-
return out;
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
function mapOpenAiMessage(msg: AiMessage): unknown {
|
|
57
|
-
const images = (msg.attachments ?? []).filter((a) => a.kind === "image");
|
|
58
|
-
if (images.length === 0) return { role: msg.role, content: msg.content };
|
|
59
|
-
const content: unknown[] = [];
|
|
60
|
-
if (msg.content) content.push({ type: "text", text: msg.content });
|
|
61
|
-
for (const img of images) {
|
|
62
|
-
content.push({ type: "image_url", image_url: { url: `data:${img.mimeType};base64,${img.data}` } });
|
|
63
|
-
}
|
|
64
|
-
return { role: msg.role, content };
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
/** Drain an async iterable of text deltas into a single string. */
|
|
68
|
-
export async function collect(stream: AsyncIterable<string>): Promise<string> {
|
|
69
|
-
let text = "";
|
|
70
|
-
for await (const delta of stream) text += delta;
|
|
71
|
-
return text;
|
|
72
|
-
}
|
|
1
|
+
import type { AiMessage, GenerateRequest, ProviderConfig } from "../../ports/ai";
|
|
2
|
+
import type { ProviderSpec } from "../catalog";
|
|
3
|
+
import { ProviderError } from "../../errors/app-error";
|
|
4
|
+
|
|
5
|
+
/** Build request auth headers from the provider's declared auth style. */
|
|
6
|
+
export function buildAuthHeaders(spec: ProviderSpec, config: ProviderConfig): Record<string, string> {
|
|
7
|
+
const headers: Record<string, string> = { "Content-Type": "application/json", ...config.extraHeaders };
|
|
8
|
+
switch (spec.auth) {
|
|
9
|
+
case "bearer":
|
|
10
|
+
requireKey(spec, config);
|
|
11
|
+
headers.Authorization = `Bearer ${config.apiKey}`;
|
|
12
|
+
break;
|
|
13
|
+
case "x-api-key":
|
|
14
|
+
requireKey(spec, config);
|
|
15
|
+
headers["x-api-key"] = config.apiKey as string;
|
|
16
|
+
headers["anthropic-version"] = "2023-06-01";
|
|
17
|
+
// Required for direct browser calls (the docs run as a static site);
|
|
18
|
+
// ignored server-side. Without it Anthropic rejects the CORS preflight.
|
|
19
|
+
headers["anthropic-dangerous-direct-browser-access"] = "true";
|
|
20
|
+
break;
|
|
21
|
+
case "api-key-header":
|
|
22
|
+
requireKey(spec, config);
|
|
23
|
+
headers["api-key"] = config.apiKey as string;
|
|
24
|
+
break;
|
|
25
|
+
case "query-key":
|
|
26
|
+
case "none":
|
|
27
|
+
break;
|
|
28
|
+
}
|
|
29
|
+
return headers;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function requireKey(spec: ProviderSpec, config: ProviderConfig): void {
|
|
33
|
+
if (!config.apiKey) {
|
|
34
|
+
throw new ProviderError(`${spec.label} requires an API key.`, { details: { provider: spec.id } });
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function resolveBaseUrl(spec: ProviderSpec, config: ProviderConfig): string {
|
|
39
|
+
const base = (config.baseUrl ?? spec.baseUrl).replace(/\/+$/, "");
|
|
40
|
+
if (spec.requiresBaseUrl && !config.baseUrl && !spec.baseUrl) {
|
|
41
|
+
throw new ProviderError(`${spec.label} requires a baseUrl.`, { details: { provider: spec.id } });
|
|
42
|
+
}
|
|
43
|
+
return base;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** OpenAI chat-completions message shape (text + optional image parts). */
|
|
47
|
+
export function toOpenAiMessages(request: GenerateRequest): unknown[] {
|
|
48
|
+
const out: unknown[] = [];
|
|
49
|
+
if (request.system) out.push({ role: "system", content: request.system });
|
|
50
|
+
for (const msg of request.messages) {
|
|
51
|
+
out.push(mapOpenAiMessage(msg));
|
|
52
|
+
}
|
|
53
|
+
return out;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function mapOpenAiMessage(msg: AiMessage): unknown {
|
|
57
|
+
const images = (msg.attachments ?? []).filter((a) => a.kind === "image");
|
|
58
|
+
if (images.length === 0) return { role: msg.role, content: msg.content };
|
|
59
|
+
const content: unknown[] = [];
|
|
60
|
+
if (msg.content) content.push({ type: "text", text: msg.content });
|
|
61
|
+
for (const img of images) {
|
|
62
|
+
content.push({ type: "image_url", image_url: { url: `data:${img.mimeType};base64,${img.data}` } });
|
|
63
|
+
}
|
|
64
|
+
return { role: msg.role, content };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Drain an async iterable of text deltas into a single string. */
|
|
68
|
+
export async function collect(stream: AsyncIterable<string>): Promise<string> {
|
|
69
|
+
let text = "";
|
|
70
|
+
for await (const delta of stream) text += delta;
|
|
71
|
+
return text;
|
|
72
|
+
}
|
package/src/ai/registry.ts
CHANGED
|
@@ -1,29 +1,29 @@
|
|
|
1
|
-
import type { AiProviderId, ProviderRegistration, ProviderRegistry } from "../ports/ai";
|
|
2
|
-
import { ProviderError } from "../errors/app-error";
|
|
3
|
-
|
|
4
|
-
/** In-memory provider registry (Registry pattern). */
|
|
5
|
-
export class InMemoryProviderRegistry implements ProviderRegistry {
|
|
6
|
-
private readonly registrations = new Map<AiProviderId, ProviderRegistration>();
|
|
7
|
-
|
|
8
|
-
register(registration: ProviderRegistration): void {
|
|
9
|
-
this.registrations.set(registration.id, registration);
|
|
10
|
-
}
|
|
11
|
-
|
|
12
|
-
has(id: AiProviderId): boolean {
|
|
13
|
-
return this.registrations.has(id);
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
get(id: AiProviderId): ProviderRegistration | undefined {
|
|
17
|
-
return this.registrations.get(id);
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
list(): readonly ProviderRegistration[] {
|
|
21
|
-
return [...this.registrations.values()];
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
require(id: AiProviderId): ProviderRegistration {
|
|
25
|
-
const found = this.registrations.get(id);
|
|
26
|
-
if (!found) throw new ProviderError(`Unknown AI provider: ${id}`, { details: { provider: id } });
|
|
27
|
-
return found;
|
|
28
|
-
}
|
|
29
|
-
}
|
|
1
|
+
import type { AiProviderId, ProviderRegistration, ProviderRegistry } from "../ports/ai";
|
|
2
|
+
import { ProviderError } from "../errors/app-error";
|
|
3
|
+
|
|
4
|
+
/** In-memory provider registry (Registry pattern). */
|
|
5
|
+
export class InMemoryProviderRegistry implements ProviderRegistry {
|
|
6
|
+
private readonly registrations = new Map<AiProviderId, ProviderRegistration>();
|
|
7
|
+
|
|
8
|
+
register(registration: ProviderRegistration): void {
|
|
9
|
+
this.registrations.set(registration.id, registration);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
has(id: AiProviderId): boolean {
|
|
13
|
+
return this.registrations.has(id);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
get(id: AiProviderId): ProviderRegistration | undefined {
|
|
17
|
+
return this.registrations.get(id);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
list(): readonly ProviderRegistration[] {
|
|
21
|
+
return [...this.registrations.values()];
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
require(id: AiProviderId): ProviderRegistration {
|
|
25
|
+
const found = this.registrations.get(id);
|
|
26
|
+
if (!found) throw new ProviderError(`Unknown AI provider: ${id}`, { details: { provider: id } });
|
|
27
|
+
return found;
|
|
28
|
+
}
|
|
29
|
+
}
|