@qikbar/qikbar 0.0.24 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +92 -0
  3. package/dist/ai/agent.d.ts +42 -0
  4. package/dist/ai/byok.d.ts +29 -0
  5. package/dist/ai/index.d.ts +8 -0
  6. package/dist/ai/providers.d.ts +82 -0
  7. package/dist/ai/sse.d.ts +9 -0
  8. package/dist/ai.js +36 -0
  9. package/dist/ai.js.map +7 -0
  10. package/dist/chunks/bar-D5CSPT3U.js +2031 -0
  11. package/dist/chunks/bar-D5CSPT3U.js.map +7 -0
  12. package/dist/chunks/chunk-2ADXL7KQ.js +358 -0
  13. package/dist/chunks/chunk-2ADXL7KQ.js.map +7 -0
  14. package/dist/chunks/chunk-6TC6G2C5.js +107 -0
  15. package/dist/chunks/chunk-6TC6G2C5.js.map +7 -0
  16. package/dist/chunks/chunk-HBBSETRF.js +153 -0
  17. package/dist/chunks/chunk-HBBSETRF.js.map +7 -0
  18. package/dist/chunks/chunk-I77YSUJN.js +104 -0
  19. package/dist/chunks/chunk-I77YSUJN.js.map +7 -0
  20. package/dist/chunks/chunk-IJ3WUM3T.js +544 -0
  21. package/dist/chunks/chunk-IJ3WUM3T.js.map +7 -0
  22. package/dist/chunks/chunk-MPTP2EWW.js +8 -0
  23. package/dist/chunks/chunk-MPTP2EWW.js.map +7 -0
  24. package/dist/chunks/chunk-N4Y2Z6YD.js +69 -0
  25. package/dist/chunks/chunk-N4Y2Z6YD.js.map +7 -0
  26. package/dist/chunks/chunk-PQEHV3D4.js +124 -0
  27. package/dist/chunks/chunk-PQEHV3D4.js.map +7 -0
  28. package/dist/chunks/chunk-VXTYD56F.js +453 -0
  29. package/dist/chunks/chunk-VXTYD56F.js.map +7 -0
  30. package/dist/chunks/chunk-YCVJQ7U3.js +52 -0
  31. package/dist/chunks/chunk-YCVJQ7U3.js.map +7 -0
  32. package/dist/core/define.d.ts +40 -0
  33. package/dist/core/frecency.d.ts +16 -0
  34. package/dist/core/hotkeys.d.ts +39 -0
  35. package/dist/core/lazy.d.ts +48 -0
  36. package/dist/core/search.d.ts +42 -0
  37. package/dist/core/storage.d.ts +5 -0
  38. package/dist/core/types.d.ts +601 -0
  39. package/dist/extensions/index.d.ts +30 -0
  40. package/dist/extensions/math.d.ts +14 -0
  41. package/dist/extensions.js +476 -0
  42. package/dist/extensions.js.map +7 -0
  43. package/dist/index.d.ts +27 -0
  44. package/dist/index.js +67 -0
  45. package/dist/index.js.map +7 -0
  46. package/dist/qikbar.global.js +259 -0
  47. package/dist/qikbar.global.js.map +7 -0
  48. package/dist/react/index.d.ts +66 -0
  49. package/dist/react.js +119 -0
  50. package/dist/react.js.map +7 -0
  51. package/dist/server/index.d.ts +47 -0
  52. package/dist/server.js +93 -0
  53. package/dist/server.js.map +7 -0
  54. package/dist/styles.css +222 -0
  55. package/dist/theme.d.ts +5 -0
  56. package/dist/theme.js +20 -0
  57. package/dist/theme.js.map +7 -0
  58. package/dist/ui/bar.d.ts +252 -0
  59. package/dist/ui/dom.d.ts +21 -0
  60. package/dist/ui/icons.d.ts +88 -0
  61. package/dist/ui/markdown.d.ts +8 -0
  62. package/dist/ui/nav.d.ts +8 -0
  63. package/dist/ui/styles.d.ts +6 -0
  64. package/dist/ui/themes.d.ts +27 -0
  65. package/dist/ui/views.d.ts +148 -0
  66. package/dist/utils.d.ts +10 -0
  67. package/dist/utils.js +50 -0
  68. package/dist/utils.js.map +7 -0
  69. package/package.json +88 -43
  70. package/dist/qikbar.es.js +0 -8748
  71. package/dist/qikbar.umd.js +0 -113
  72. package/dist/types/boot.d.ts +0 -72
  73. package/dist/types/index.d.ts +0 -1
  74. package/dist/types/init.d.ts +0 -2
  75. package/dist/types/main.d.ts +0 -4
  76. package/dist/types/shared/AsyncRoot.d.ts +0 -5
  77. package/dist/types/shared/CommandFooter.d.ts +0 -5
  78. package/dist/types/shared/Crumbs.d.ts +0 -6
  79. package/dist/types/shared/Details.d.ts +0 -3
  80. package/dist/types/shared/ErrorBoundary.d.ts +0 -15
  81. package/dist/types/shared/Icon.d.ts +0 -4
  82. package/dist/types/shared/List.d.ts +0 -30
  83. package/dist/types/shared/Qikbar.d.ts +0 -5
  84. package/dist/types/shared/Root.d.ts +0 -4
  85. package/dist/types/shared/Search.d.ts +0 -1
  86. package/dist/types/shared/commandContext.d.ts +0 -8
  87. package/dist/types/shared/useDebounce.d.ts +0 -1
  88. package/dist/types/utils/liquid.d.ts +0 -4
  89. package/dist/types/vite-env.d.ts +0 -1
@@ -0,0 +1,358 @@
1
+ // src/ai/sse.ts
2
+ async function* lines(response) {
3
+ if (!response.body) return;
4
+ let reader = response.body.getReader(), decoder = new TextDecoder(), buffer = "";
5
+ try {
6
+ for (; ; ) {
7
+ let { value, done } = await reader.read();
8
+ if (done) break;
9
+ buffer += decoder.decode(value, { stream: !0 });
10
+ let nl;
11
+ for (; (nl = buffer.indexOf(`
12
+ `)) >= 0; ) {
13
+ let line = buffer.slice(0, nl).replace(/\r$/, "");
14
+ buffer = buffer.slice(nl + 1), yield line;
15
+ }
16
+ }
17
+ buffer += decoder.decode(), buffer && (yield buffer);
18
+ } finally {
19
+ reader.releaseLock();
20
+ }
21
+ }
22
+ async function* parseSSE(response) {
23
+ let event, data = [];
24
+ for await (let line of lines(response))
25
+ line === "" ? (data.length && (yield { event, data: data.join(`
26
+ `) }), event = void 0, data = []) : line.startsWith("data:") ? data.push(line.slice(line[5] === " " ? 6 : 5)) : line.startsWith("event:") && (event = line.slice(6).trim());
27
+ data.length && (yield { event, data: data.join(`
28
+ `) });
29
+ }
30
+ async function* parseNDJSON(response) {
31
+ for await (let line of lines(response))
32
+ line.trim() && (yield JSON.parse(line));
33
+ }
34
+ async function errorFromResponse(response, provider) {
35
+ let detail = "";
36
+ try {
37
+ let text = await response.text();
38
+ try {
39
+ let json = JSON.parse(text);
40
+ detail = json?.error?.message ?? json?.message ?? json?.error ?? text;
41
+ } catch {
42
+ detail = text;
43
+ }
44
+ } catch {
45
+ }
46
+ return new Error(`${provider} ${response.status}: ${String(detail || response.statusText).slice(0, 300)}`);
47
+ }
48
+
49
+ // src/ai/providers.ts
50
+ var callCounter = 0, newCallId = () => `call_${Date.now().toString(36)}${(callCounter++).toString(36)}`;
51
+ function parseArgs(json) {
52
+ if (!json.trim()) return { args: {} };
53
+ try {
54
+ let parsed = JSON.parse(json);
55
+ return parsed && typeof parsed == "object" && !Array.isArray(parsed) ? { args: parsed } : { args: {}, error: "Tool arguments must be a JSON object." };
56
+ } catch {
57
+ return { args: {}, error: `Invalid JSON arguments: ${json.slice(0, 200)}` };
58
+ }
59
+ }
60
+ var ANTHROPIC_EFFORT_MODELS = /claude-(opus|sonnet|haiku|fable|mythos)-5|claude-opus-4-[5-8]/, ANTHROPIC_FALLBACK_MODELS = /^claude-(opus-5|opus-5-5|sonnet-5-5|fable-5-1)$/;
61
+ function anthropic(options = {}) {
62
+ let model = options.model ?? "claude-opus-5-5", baseURL = (options.baseURL ?? "https://api.anthropic.com").replace(/\/$/, ""), doFetch = options.fetch ?? ((...args) => fetch(...args));
63
+ function toMessages(messages) {
64
+ let out = [];
65
+ for (let m of messages)
66
+ if (m.role === "user") out.push({ role: "user", content: m.content });
67
+ else if (m.role === "assistant")
68
+ if (m.raw?.provider === "anthropic") out.push({ role: "assistant", content: m.raw.data });
69
+ else {
70
+ let blocks = [];
71
+ m.content && blocks.push({ type: "text", text: m.content });
72
+ for (let c of m.toolCalls ?? []) blocks.push({ type: "tool_use", id: c.id, name: c.name, input: c.args });
73
+ out.push({ role: "assistant", content: blocks.length ? blocks : m.content || "\u2026" });
74
+ }
75
+ else {
76
+ let block = { type: "tool_result", tool_use_id: m.toolCallId, content: m.content, ...m.isError ? { is_error: !0 } : {} }, last = out[out.length - 1];
77
+ last?.role === "user" && Array.isArray(last.content) && last.content[0]?.type === "tool_result" ? last.content.push(block) : out.push({ role: "user", content: [block] });
78
+ }
79
+ return out;
80
+ }
81
+ return {
82
+ id: "anthropic",
83
+ model,
84
+ async *stream(req) {
85
+ let headers = {
86
+ "content-type": "application/json",
87
+ "anthropic-version": "2023-06-01",
88
+ ...options.headers
89
+ };
90
+ options.apiKey && (headers["x-api-key"] = options.apiKey, headers["anthropic-dangerous-direct-browser-access"] = "true");
91
+ let body = {
92
+ model,
93
+ max_tokens: req.maxTokens ?? options.maxTokens ?? 16e3,
94
+ stream: !0,
95
+ messages: toMessages(req.messages)
96
+ };
97
+ req.system && (body.system = req.system), req.tools?.length && (body.tools = req.tools.map((t) => ({ name: t.name, description: t.description, input_schema: t.parameters, eager_input_streaming: !0 })));
98
+ let effort = options.effort === void 0 ? ANTHROPIC_EFFORT_MODELS.test(model) ? "low" : !1 : options.effort;
99
+ effort && (body.output_config = { effort }), options.fallbacks !== !1 && ANTHROPIC_FALLBACK_MODELS.test(model) && !options.baseURL && (body.fallbacks = "default", headers["anthropic-beta"] = [headers["anthropic-beta"], "server-side-fallback-2026-07-01"].filter(Boolean).join(","));
100
+ let res = await doFetch(`${baseURL}/v1/messages`, { method: "POST", headers, body: JSON.stringify(body), signal: req.signal });
101
+ if (!res.ok) throw await errorFromResponse(res, "Anthropic");
102
+ let blocks = {}, stopReason, text = "";
103
+ for await (let msg of parseSSE(res)) {
104
+ if (!msg.data || msg.data === "[DONE]") continue;
105
+ let ev = JSON.parse(msg.data);
106
+ switch (ev.type) {
107
+ case "content_block_start": {
108
+ let block = { ...ev.content_block };
109
+ block.type === "tool_use" && (block._json = ""), blocks[ev.index] = block, block.type === "text" && block.text && (text += block.text, yield { type: "text", text: block.text });
110
+ break;
111
+ }
112
+ case "content_block_delta": {
113
+ let block = blocks[ev.index], d = ev.delta;
114
+ if (!block) break;
115
+ d.type === "text_delta" ? (block.text = (block.text ?? "") + d.text, text += d.text, yield { type: "text", text: d.text }) : d.type === "input_json_delta" ? block._json += d.partial_json : d.type === "thinking_delta" ? block.thinking = (block.thinking ?? "") + d.thinking : d.type === "signature_delta" && (block.signature = d.signature);
116
+ break;
117
+ }
118
+ case "content_block_stop": {
119
+ let block = blocks[ev.index];
120
+ if (block?.type === "tool_use") {
121
+ let { args, error } = parseArgs(block._json);
122
+ block.input = args, error && (block._error = error), delete block._json;
123
+ }
124
+ break;
125
+ }
126
+ case "message_delta":
127
+ ev.delta?.stop_reason && (stopReason = ev.delta.stop_reason);
128
+ break;
129
+ case "error":
130
+ throw new Error(`Anthropic: ${ev.error?.message ?? "stream error"}`);
131
+ }
132
+ }
133
+ let ordered = Object.keys(blocks).map(Number).sort((a, b) => a - b).map((i) => blocks[i]), toolCalls = [];
134
+ if (stopReason !== "max_tokens" && stopReason !== "refusal")
135
+ for (let b of ordered) {
136
+ if (b.type !== "tool_use") continue;
137
+ let call = { id: b.id, name: b.name, args: b.input ?? {} };
138
+ b._error && (call.error = b._error), toolCalls.push(call), yield { type: "tool_call", call };
139
+ }
140
+ for (let b of ordered) delete b._error;
141
+ stopReason === "refusal" && (yield { type: "error", error: "The model declined to answer this request." }), yield {
142
+ type: "done",
143
+ stopReason,
144
+ message: { role: "assistant", content: text, toolCalls: toolCalls.length ? toolCalls : void 0, raw: { provider: "anthropic", data: ordered } }
145
+ };
146
+ }
147
+ };
148
+ }
149
+ function openai(options = {}) {
150
+ let model = options.model ?? "gpt-6-luna", baseURL = (options.baseURL ?? "https://api.openai.com/v1").replace(/\/$/, ""), doFetch = options.fetch ?? ((...args) => fetch(...args));
151
+ function toMessages(messages, system) {
152
+ let out = [];
153
+ system && out.push({ role: "system", content: system });
154
+ for (let m of messages)
155
+ m.role === "user" ? out.push({ role: "user", content: m.content }) : m.role === "assistant" ? out.push({
156
+ role: "assistant",
157
+ content: m.content || null,
158
+ ...m.toolCalls?.length ? { tool_calls: m.toolCalls.map((c) => ({ id: c.id, type: "function", function: { name: c.name, arguments: JSON.stringify(c.args) } })) } : {}
159
+ }) : out.push({ role: "tool", tool_call_id: m.toolCallId, content: m.content });
160
+ return out;
161
+ }
162
+ return {
163
+ id: options.id ?? "openai",
164
+ model,
165
+ tools: options.tools ?? !0,
166
+ async *stream(req) {
167
+ let body = { model, stream: !0, messages: toMessages(req.messages, req.system) }, maxTokens = req.maxTokens ?? options.maxTokens;
168
+ maxTokens && (body.max_completion_tokens = maxTokens), req.tools?.length && options.tools !== !1 && (body.tools = req.tools.map((t) => ({ type: "function", function: { name: t.name, description: t.description, parameters: t.parameters } })));
169
+ let res = await doFetch(`${baseURL}/chat/completions`, {
170
+ method: "POST",
171
+ headers: {
172
+ "content-type": "application/json",
173
+ ...options.apiKey ? { authorization: `Bearer ${options.apiKey}` } : {},
174
+ ...options.headers
175
+ },
176
+ body: JSON.stringify(body),
177
+ signal: req.signal
178
+ });
179
+ if (!res.ok) throw await errorFromResponse(res, options.id ?? "OpenAI");
180
+ let text = "", stopReason, calls = [];
181
+ for await (let msg of parseSSE(res)) {
182
+ if (!msg.data || msg.data === "[DONE]") continue;
183
+ let chunk = JSON.parse(msg.data);
184
+ if (chunk.error) throw new Error(`${options.id ?? "OpenAI"}: ${chunk.error.message ?? chunk.error}`);
185
+ let choice = chunk.choices?.[0];
186
+ if (!choice) continue;
187
+ let delta = choice.delta ?? {};
188
+ typeof delta.content == "string" && delta.content && (text += delta.content, yield { type: "text", text: delta.content });
189
+ for (let tc of delta.tool_calls ?? []) {
190
+ let i = tc.index ?? 0;
191
+ calls[i] ?? (calls[i] = { id: tc.id ?? newCallId(), name: "", json: "" }), tc.id && (calls[i].id = tc.id), tc.function?.name && (calls[i].name += tc.function.name), tc.function?.arguments && (calls[i].json += tc.function.arguments);
192
+ }
193
+ choice.finish_reason && (stopReason = choice.finish_reason);
194
+ }
195
+ let toolCalls = [];
196
+ if (stopReason !== "length" && stopReason !== "content_filter")
197
+ for (let c of calls.filter(Boolean)) {
198
+ let { args, error } = parseArgs(c.json), call = { id: c.id, name: c.name, args, ...error ? { error } : {} };
199
+ toolCalls.push(call), yield { type: "tool_call", call };
200
+ }
201
+ stopReason === "content_filter" && (yield { type: "error", error: "The response was blocked by the provider\u2019s content filter." }), yield { type: "done", stopReason, message: { role: "assistant", content: text, toolCalls: toolCalls.length ? toolCalls : void 0 } };
202
+ }
203
+ };
204
+ }
205
+ function openaiCompatible(options) {
206
+ return openai({ id: "openai-compatible", ...options });
207
+ }
208
+ function ollama(options = { model: "llama3.2" }) {
209
+ return openai({ id: "ollama", baseURL: options.baseURL ?? "http://localhost:11434/v1", model: options.model, tools: options.tools });
210
+ }
211
+ function geminiSchema(schema) {
212
+ let { additionalProperties: _a, $schema: _s, default: _d, ...rest } = schema, out = { ...rest };
213
+ return rest.properties && (out.properties = Object.fromEntries(Object.entries(rest.properties).map(([k, v]) => [k, geminiSchema(v)]))), rest.items && (out.items = geminiSchema(rest.items)), out;
214
+ }
215
+ function gemini(options = {}) {
216
+ let model = options.model ?? "gemini-flash-latest", baseURL = (options.baseURL ?? "https://generativelanguage.googleapis.com/v1beta").replace(/\/$/, ""), doFetch = options.fetch ?? ((...args) => fetch(...args));
217
+ function toContents(messages) {
218
+ let out = [];
219
+ for (let m of messages)
220
+ if (m.role === "user") out.push({ role: "user", parts: [{ text: m.content }] });
221
+ else if (m.role === "assistant")
222
+ if (m.raw?.provider === "gemini") out.push({ role: "model", parts: m.raw.data });
223
+ else {
224
+ let parts = [];
225
+ m.content && parts.push({ text: m.content });
226
+ for (let c of m.toolCalls ?? []) parts.push({ functionCall: { name: c.name, args: c.args } });
227
+ out.push({ role: "model", parts: parts.length ? parts : [{ text: "" }] });
228
+ }
229
+ else {
230
+ let part = { functionResponse: { name: m.toolName ?? "tool", response: m.isError ? { error: m.content } : { result: m.content } } }, last = out[out.length - 1];
231
+ last?.role === "user" && last.parts[0]?.functionResponse ? last.parts.push(part) : out.push({ role: "user", parts: [part] });
232
+ }
233
+ return out;
234
+ }
235
+ return {
236
+ id: "gemini",
237
+ model,
238
+ async *stream(req) {
239
+ let body = { contents: toContents(req.messages) };
240
+ req.system && (body.systemInstruction = { parts: [{ text: req.system }] }), req.tools?.length && (body.tools = [
241
+ {
242
+ functionDeclarations: req.tools.map((t) => ({
243
+ name: t.name,
244
+ description: t.description,
245
+ ...t.parameters?.properties && Object.keys(t.parameters.properties).length ? { parameters: geminiSchema(t.parameters) } : {}
246
+ }))
247
+ }
248
+ ]);
249
+ let maxTokens = req.maxTokens ?? options.maxTokens;
250
+ maxTokens && (body.generationConfig = { maxOutputTokens: maxTokens });
251
+ let res = await doFetch(`${baseURL}/models/${encodeURIComponent(model)}:streamGenerateContent?alt=sse`, {
252
+ method: "POST",
253
+ headers: { "content-type": "application/json", ...options.apiKey ? { "x-goog-api-key": options.apiKey } : {}, ...options.headers },
254
+ body: JSON.stringify(body),
255
+ signal: req.signal
256
+ });
257
+ if (!res.ok) throw await errorFromResponse(res, "Gemini");
258
+ let text = "", stopReason, parts = [], toolCalls = [];
259
+ for await (let msg of parseSSE(res)) {
260
+ if (!msg.data) continue;
261
+ let chunk = JSON.parse(msg.data);
262
+ if (chunk.error) throw new Error(`Gemini: ${chunk.error.message}`);
263
+ if (chunk.promptFeedback?.blockReason) {
264
+ yield { type: "error", error: `Blocked by Gemini (${chunk.promptFeedback.blockReason}).` };
265
+ continue;
266
+ }
267
+ let cand = chunk.candidates?.[0];
268
+ if (cand) {
269
+ for (let part of cand.content?.parts ?? [])
270
+ if (part.functionCall) {
271
+ parts.push(part);
272
+ let call = { id: part.functionCall.id ?? newCallId(), name: part.functionCall.name, args: part.functionCall.args ?? {} };
273
+ toolCalls.push(call);
274
+ } else if (typeof part.text == "string") {
275
+ let last = parts[parts.length - 1];
276
+ !part.thought && last && typeof last.text == "string" && !last.thought && !last.thoughtSignature && !part.thoughtSignature ? last.text += part.text : parts.push({ ...part }), !part.thought && part.text && (text += part.text, yield { type: "text", text: part.text });
277
+ } else parts.push(part);
278
+ cand.finishReason && (stopReason = cand.finishReason);
279
+ }
280
+ }
281
+ if (stopReason !== "MAX_TOKENS") for (let call of toolCalls) yield { type: "tool_call", call };
282
+ stopReason === "SAFETY" && (yield { type: "error", error: "The response was blocked by Gemini safety filters." }), yield {
283
+ type: "done",
284
+ stopReason,
285
+ message: { role: "assistant", content: text, toolCalls: toolCalls.length && stopReason !== "MAX_TOKENS" ? toolCalls : void 0, raw: { provider: "gemini", data: parts } }
286
+ };
287
+ }
288
+ };
289
+ }
290
+ var browserAI = /* @__PURE__ */ Object.assign(
291
+ function() {
292
+ return {
293
+ id: "browser",
294
+ model: "on-device",
295
+ tools: !1,
296
+ async *stream(req) {
297
+ let LM = globalThis.LanguageModel;
298
+ if (!LM) throw new Error("Built-in AI is not available in this browser.");
299
+ let history = req.messages.filter((m) => m.role !== "tool"), last = history.pop(), initialPrompts = [
300
+ ...req.system ? [{ role: "system", content: req.system }] : [],
301
+ ...history.map((m) => ({ role: m.role, content: m.content }))
302
+ ], session = await LM.create({ initialPrompts, signal: req.signal }), total = "";
303
+ try {
304
+ let stream = session.promptStreaming(last?.content ?? "", { signal: req.signal });
305
+ for await (let chunk of stream) {
306
+ let delta = chunk.startsWith(total) && total ? chunk.slice(total.length) : chunk;
307
+ total += delta, delta && (yield { type: "text", text: delta });
308
+ }
309
+ } finally {
310
+ session.destroy?.();
311
+ }
312
+ yield { type: "done", message: { role: "assistant", content: total } };
313
+ }
314
+ };
315
+ },
316
+ {
317
+ /** Whether the on-device model can be used in this browser. */
318
+ async isAvailable() {
319
+ let LM = globalThis.LanguageModel;
320
+ if (!LM?.availability) return !1;
321
+ try {
322
+ return await LM.availability() !== "unavailable";
323
+ } catch {
324
+ return !1;
325
+ }
326
+ }
327
+ }
328
+ );
329
+ function proxy(options) {
330
+ let opts = typeof options == "string" ? { url: options } : options, doFetch = opts.fetch ?? ((...args) => fetch(...args));
331
+ return {
332
+ id: "proxy",
333
+ async *stream(req) {
334
+ let extra = typeof opts.headers == "function" ? await opts.headers() : opts.headers, res = await doFetch(opts.url, {
335
+ method: "POST",
336
+ headers: { "content-type": "application/json", accept: "application/x-ndjson", ...extra },
337
+ credentials: opts.credentials ?? "same-origin",
338
+ body: JSON.stringify({ messages: req.messages, system: req.system, tools: req.tools, maxTokens: req.maxTokens }),
339
+ signal: req.signal
340
+ });
341
+ if (!res.ok) throw await errorFromResponse(res, "AI proxy");
342
+ yield* parseNDJSON(res);
343
+ }
344
+ };
345
+ }
346
+
347
+ export {
348
+ parseSSE,
349
+ parseNDJSON,
350
+ anthropic,
351
+ openai,
352
+ openaiCompatible,
353
+ ollama,
354
+ gemini,
355
+ browserAI,
356
+ proxy
357
+ };
358
+ //# sourceMappingURL=chunk-2ADXL7KQ.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/ai/sse.ts", "../../src/ai/providers.ts"],
4
+ "sourcesContent": ["/** Read a fetch body as lines. */\nasync function* lines(response: Response): AsyncIterable<string> {\n if (!response.body) return\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n try {\n for (;;) {\n const { value, done } = await reader.read()\n if (done) break\n buffer += decoder.decode(value, { stream: true })\n let nl: number\n while ((nl = buffer.indexOf('\\n')) >= 0) {\n const line = buffer.slice(0, nl).replace(/\\r$/, '')\n buffer = buffer.slice(nl + 1)\n yield line\n }\n }\n buffer += decoder.decode()\n if (buffer) yield buffer\n } finally {\n reader.releaseLock()\n }\n}\n\nexport interface SSEMessage {\n event?: string\n data: string\n}\n\n/** Parse a Server-Sent Events stream. */\nexport async function* parseSSE(response: Response): AsyncIterable<SSEMessage> {\n let event: string | undefined\n let data: string[] = []\n for await (const line of lines(response)) {\n if (line === '') {\n if (data.length) yield { event, data: data.join('\\n') }\n event = undefined\n data = []\n } else if (line.startsWith('data:')) {\n data.push(line.slice(line[5] === ' ' ? 6 : 5))\n } else if (line.startsWith('event:')) {\n event = line.slice(6).trim()\n }\n }\n if (data.length) yield { event, data: data.join('\\n') }\n}\n\n/** Parse a newline-delimited JSON stream. */\nexport async function* parseNDJSON<T = unknown>(response: Response): AsyncIterable<T> {\n for await (const line of lines(response)) {\n if (line.trim()) yield JSON.parse(line) as T\n }\n}\n\nexport async function errorFromResponse(response: Response, provider: string): Promise<Error> {\n let detail = ''\n try {\n const text = await response.text()\n try {\n const json = JSON.parse(text)\n detail = json?.error?.message ?? json?.message ?? json?.error ?? text\n } catch {\n detail = text\n }\n } catch {\n // ignore\n }\n return new Error(`${provider} ${response.status}: ${String(detail || response.statusText).slice(0, 300)}`)\n}\n", "/**\n * Zero-dependency AI providers. Each one streams text and tool calls through\n * the same `AIProvider` interface, so the bar works with any model.\n *\n * Security: providers that take an `apiKey` call the vendor directly from the\n * browser. That's fine for prototypes, internal tools, and \"bring your own key\"\n * setups where users paste their own key. For production apps with a shared\n * key, use `proxy()` on the client and `createHandler()` from `@qikbar/qikbar/server`.\n */\n\nimport type { AIEvent, AIMessage, AIProvider, AIRequest, AIToolCall, AIToolDefinition, JSONSchema } from '../core/types.js'\nimport { errorFromResponse, parseNDJSON, parseSSE } from './sse.js'\n\nlet callCounter = 0\nconst newCallId = () => `call_${Date.now().toString(36)}${(callCounter++).toString(36)}`\n\nfunction parseArgs(json: string): { args: Record<string, unknown>; error?: string } {\n if (!json.trim()) return { args: {} }\n try {\n const parsed = JSON.parse(json)\n if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return { args: parsed }\n return { args: {}, error: 'Tool arguments must be a JSON object.' }\n } catch {\n return { args: {}, error: `Invalid JSON arguments: ${json.slice(0, 200)}` }\n }\n}\n\n// \u2500\u2500\u2500 Anthropic \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface AnthropicOptions {\n apiKey?: string\n /** Default `\"claude-opus-5-5\"`. Use `\"claude-haiku-5-5\"` for the lowest latency and cost. */\n model?: string\n baseURL?: string\n maxTokens?: number\n /** Reasoning effort. Default `\"low\"` \u2014 a command bar should feel instant. */\n effort?: 'low' | 'medium' | 'high' | 'xhigh' | 'max' | false\n /**\n * Server-side refusal fallbacks (Claude API only). When a safety classifier\n * declines a request, the API re-runs it on a fallback model. Default `true`\n * on models that support it.\n */\n fallbacks?: boolean\n headers?: Record<string, string>\n /** Custom fetch (e.g. for proxies or tests). */\n fetch?: typeof fetch\n}\n\nconst ANTHROPIC_EFFORT_MODELS = /claude-(opus|sonnet|haiku|fable|mythos)-5|claude-opus-4-[5-8]/\nconst ANTHROPIC_FALLBACK_MODELS = /^claude-(opus-5|opus-5-5|sonnet-5-5|fable-5-1)$/\n\nexport function anthropic(options: AnthropicOptions = {}): AIProvider {\n const model = options.model ?? 'claude-opus-5-5'\n const baseURL = (options.baseURL ?? 'https://api.anthropic.com').replace(/\\/$/, '')\n const doFetch = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args))\n\n function toMessages(messages: AIMessage[]) {\n const out: { role: 'user' | 'assistant'; content: unknown }[] = []\n for (const m of messages) {\n if (m.role === 'user') out.push({ role: 'user', content: m.content })\n else if (m.role === 'assistant') {\n if (m.raw?.provider === 'anthropic') out.push({ role: 'assistant', content: m.raw.data })\n else {\n const blocks: unknown[] = []\n if (m.content) blocks.push({ type: 'text', text: m.content })\n for (const c of m.toolCalls ?? []) blocks.push({ type: 'tool_use', id: c.id, name: c.name, input: c.args })\n out.push({ role: 'assistant', content: blocks.length ? blocks : m.content || '\u2026' })\n }\n } else {\n // All results for one assistant turn go back in a single user message.\n const block = { type: 'tool_result', tool_use_id: m.toolCallId, content: m.content, ...(m.isError ? { is_error: true } : {}) }\n const last = out[out.length - 1]\n if (last?.role === 'user' && Array.isArray(last.content) && (last.content as any[])[0]?.type === 'tool_result') (last.content as unknown[]).push(block)\n else out.push({ role: 'user', content: [block] })\n }\n }\n return out\n }\n\n return {\n id: 'anthropic',\n model,\n async *stream(req: AIRequest): AsyncIterable<AIEvent> {\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n 'anthropic-version': '2023-06-01',\n ...options.headers,\n }\n if (options.apiKey) {\n headers['x-api-key'] = options.apiKey\n headers['anthropic-dangerous-direct-browser-access'] = 'true'\n }\n const body: Record<string, unknown> = {\n model,\n max_tokens: req.maxTokens ?? options.maxTokens ?? 16000,\n stream: true,\n messages: toMessages(req.messages),\n }\n if (req.system) body.system = req.system\n if (req.tools?.length) {\n body.tools = req.tools.map((t) => ({ name: t.name, description: t.description, input_schema: t.parameters, eager_input_streaming: true }))\n }\n const effort = options.effort === undefined ? (ANTHROPIC_EFFORT_MODELS.test(model) ? 'low' : false) : options.effort\n if (effort) body.output_config = { effort }\n if (options.fallbacks !== false && ANTHROPIC_FALLBACK_MODELS.test(model) && !options.baseURL) {\n body.fallbacks = 'default'\n headers['anthropic-beta'] = [headers['anthropic-beta'], 'server-side-fallback-2026-07-01'].filter(Boolean).join(',')\n }\n\n const res = await doFetch(`${baseURL}/v1/messages`, { method: 'POST', headers, body: JSON.stringify(body), signal: req.signal })\n if (!res.ok) throw await errorFromResponse(res, 'Anthropic')\n\n const blocks: Record<number, any> = {}\n let stopReason: string | undefined\n let text = ''\n for await (const msg of parseSSE(res)) {\n if (!msg.data || msg.data === '[DONE]') continue\n const ev = JSON.parse(msg.data)\n switch (ev.type) {\n case 'content_block_start': {\n const block = { ...ev.content_block }\n if (block.type === 'tool_use') block._json = ''\n blocks[ev.index] = block\n if (block.type === 'text' && block.text) {\n text += block.text\n yield { type: 'text', text: block.text }\n }\n break\n }\n case 'content_block_delta': {\n const block = blocks[ev.index]\n const d = ev.delta\n if (!block) break\n if (d.type === 'text_delta') {\n block.text = (block.text ?? '') + d.text\n text += d.text\n yield { type: 'text', text: d.text }\n } else if (d.type === 'input_json_delta') block._json += d.partial_json\n else if (d.type === 'thinking_delta') block.thinking = (block.thinking ?? '') + d.thinking\n else if (d.type === 'signature_delta') block.signature = d.signature\n break\n }\n case 'content_block_stop': {\n const block = blocks[ev.index]\n if (block?.type === 'tool_use') {\n const { args, error } = parseArgs(block._json)\n block.input = args\n if (error) block._error = error\n delete block._json\n }\n break\n }\n case 'message_delta':\n if (ev.delta?.stop_reason) stopReason = ev.delta.stop_reason\n break\n case 'error':\n throw new Error(`Anthropic: ${ev.error?.message ?? 'stream error'}`)\n }\n }\n\n const ordered = Object.keys(blocks)\n .map(Number)\n .sort((a, b) => a - b)\n .map((i) => blocks[i])\n const toolCalls: AIToolCall[] = []\n // Never run tools from a truncated or declined turn.\n if (stopReason !== 'max_tokens' && stopReason !== 'refusal') {\n for (const b of ordered) {\n if (b.type !== 'tool_use') continue\n const call: AIToolCall = { id: b.id, name: b.name, args: b.input ?? {} }\n if (b._error) call.error = b._error\n toolCalls.push(call)\n yield { type: 'tool_call', call }\n }\n }\n for (const b of ordered) delete b._error\n if (stopReason === 'refusal') yield { type: 'error', error: 'The model declined to answer this request.' }\n yield {\n type: 'done',\n stopReason,\n message: { role: 'assistant', content: text, toolCalls: toolCalls.length ? toolCalls : undefined, raw: { provider: 'anthropic', data: ordered } },\n }\n },\n }\n}\n\n// \u2500\u2500\u2500 OpenAI (and every OpenAI-compatible API) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface OpenAIOptions {\n apiKey?: string\n /** Default `\"gpt-6-luna\"`. */\n model?: string\n /** Point at any OpenAI-compatible API: Groq, OpenRouter, Together, Mistral, Ollama (`http://localhost:11434/v1`), LM Studio, vLLM\u2026 */\n baseURL?: string\n maxTokens?: number\n headers?: Record<string, string>\n /** Some local models don't support tools. Default true. */\n tools?: boolean\n fetch?: typeof fetch\n /** Provider id shown in the UI. Default `\"openai\"`. */\n id?: string\n}\n\nexport function openai(options: OpenAIOptions = {}): AIProvider {\n const model = options.model ?? 'gpt-6-luna'\n const baseURL = (options.baseURL ?? 'https://api.openai.com/v1').replace(/\\/$/, '')\n const doFetch = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args))\n\n function toMessages(messages: AIMessage[], system?: string) {\n const out: Record<string, unknown>[] = []\n if (system) out.push({ role: 'system', content: system })\n for (const m of messages) {\n if (m.role === 'user') out.push({ role: 'user', content: m.content })\n else if (m.role === 'assistant')\n out.push({\n role: 'assistant',\n content: m.content || null,\n ...(m.toolCalls?.length\n ? { tool_calls: m.toolCalls.map((c) => ({ id: c.id, type: 'function', function: { name: c.name, arguments: JSON.stringify(c.args) } })) }\n : {}),\n })\n else out.push({ role: 'tool', tool_call_id: m.toolCallId, content: m.content })\n }\n return out\n }\n\n return {\n id: options.id ?? 'openai',\n model,\n tools: options.tools ?? true,\n async *stream(req: AIRequest): AsyncIterable<AIEvent> {\n const body: Record<string, unknown> = { model, stream: true, messages: toMessages(req.messages, req.system) }\n const maxTokens = req.maxTokens ?? options.maxTokens\n if (maxTokens) body.max_completion_tokens = maxTokens\n if (req.tools?.length && options.tools !== false) {\n body.tools = req.tools.map((t) => ({ type: 'function', function: { name: t.name, description: t.description, parameters: t.parameters } }))\n }\n const res = await doFetch(`${baseURL}/chat/completions`, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n ...(options.apiKey ? { authorization: `Bearer ${options.apiKey}` } : {}),\n ...options.headers,\n },\n body: JSON.stringify(body),\n signal: req.signal,\n })\n if (!res.ok) throw await errorFromResponse(res, options.id ?? 'OpenAI')\n\n let text = ''\n let stopReason: string | undefined\n const calls: { id: string; name: string; json: string }[] = []\n for await (const msg of parseSSE(res)) {\n if (!msg.data || msg.data === '[DONE]') continue\n const chunk = JSON.parse(msg.data)\n if (chunk.error) throw new Error(`${options.id ?? 'OpenAI'}: ${chunk.error.message ?? chunk.error}`)\n const choice = chunk.choices?.[0]\n if (!choice) continue\n const delta = choice.delta ?? {}\n if (typeof delta.content === 'string' && delta.content) {\n text += delta.content\n yield { type: 'text', text: delta.content }\n }\n for (const tc of delta.tool_calls ?? []) {\n const i = tc.index ?? 0\n calls[i] ??= { id: tc.id ?? newCallId(), name: '', json: '' }\n if (tc.id) calls[i].id = tc.id\n if (tc.function?.name) calls[i].name += tc.function.name\n if (tc.function?.arguments) calls[i].json += tc.function.arguments\n }\n if (choice.finish_reason) stopReason = choice.finish_reason\n }\n const toolCalls: AIToolCall[] = []\n if (stopReason !== 'length' && stopReason !== 'content_filter') {\n for (const c of calls.filter(Boolean)) {\n const { args, error } = parseArgs(c.json)\n const call: AIToolCall = { id: c.id, name: c.name, args, ...(error ? { error } : {}) }\n toolCalls.push(call)\n yield { type: 'tool_call', call }\n }\n }\n if (stopReason === 'content_filter') yield { type: 'error', error: 'The response was blocked by the provider\u2019s content filter.' }\n yield { type: 'done', stopReason, message: { role: 'assistant', content: text, toolCalls: toolCalls.length ? toolCalls : undefined } }\n },\n }\n}\n\n/** Any OpenAI-compatible endpoint (Groq, OpenRouter, Together, Mistral, DeepSeek, xAI, Ollama, LM Studio\u2026). */\nexport function openaiCompatible(options: OpenAIOptions & { baseURL: string; model: string }): AIProvider {\n return openai({ id: 'openai-compatible', ...options })\n}\n\n/** Local models via Ollama. */\nexport function ollama(options: { model: string; baseURL?: string; tools?: boolean } = { model: 'llama3.2' }): AIProvider {\n return openai({ id: 'ollama', baseURL: options.baseURL ?? 'http://localhost:11434/v1', model: options.model, tools: options.tools })\n}\n\n// \u2500\u2500\u2500 Google Gemini \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface GeminiOptions {\n apiKey?: string\n /** Default `\"gemini-flash-latest\"`. */\n model?: string\n baseURL?: string\n maxTokens?: number\n headers?: Record<string, string>\n fetch?: typeof fetch\n}\n\n/** Gemini's function declarations accept an OpenAPI subset of JSON schema. */\nfunction geminiSchema(schema: JSONSchema): JSONSchema {\n const { additionalProperties: _a, $schema: _s, default: _d, ...rest } = schema as Record<string, any>\n const out: Record<string, any> = { ...rest }\n if (rest.properties) out.properties = Object.fromEntries(Object.entries(rest.properties).map(([k, v]) => [k, geminiSchema(v as JSONSchema)]))\n if (rest.items) out.items = geminiSchema(rest.items)\n return out\n}\n\nexport function gemini(options: GeminiOptions = {}): AIProvider {\n const model = options.model ?? 'gemini-flash-latest'\n const baseURL = (options.baseURL ?? 'https://generativelanguage.googleapis.com/v1beta').replace(/\\/$/, '')\n const doFetch = options.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args))\n\n function toContents(messages: AIMessage[]) {\n const out: { role: 'user' | 'model'; parts: unknown[] }[] = []\n for (const m of messages) {\n if (m.role === 'user') out.push({ role: 'user', parts: [{ text: m.content }] })\n else if (m.role === 'assistant') {\n if (m.raw?.provider === 'gemini') out.push({ role: 'model', parts: m.raw.data as unknown[] })\n else {\n const parts: unknown[] = []\n if (m.content) parts.push({ text: m.content })\n for (const c of m.toolCalls ?? []) parts.push({ functionCall: { name: c.name, args: c.args } })\n out.push({ role: 'model', parts: parts.length ? parts : [{ text: '' }] })\n }\n } else {\n const part = { functionResponse: { name: m.toolName ?? 'tool', response: m.isError ? { error: m.content } : { result: m.content } } }\n const last = out[out.length - 1]\n if (last?.role === 'user' && (last.parts[0] as any)?.functionResponse) last.parts.push(part)\n else out.push({ role: 'user', parts: [part] })\n }\n }\n return out\n }\n\n return {\n id: 'gemini',\n model,\n async *stream(req: AIRequest): AsyncIterable<AIEvent> {\n const body: Record<string, unknown> = { contents: toContents(req.messages) }\n if (req.system) body.systemInstruction = { parts: [{ text: req.system }] }\n if (req.tools?.length) {\n body.tools = [\n {\n functionDeclarations: req.tools.map((t: AIToolDefinition) => ({\n name: t.name,\n description: t.description,\n ...(t.parameters?.properties && Object.keys(t.parameters.properties).length ? { parameters: geminiSchema(t.parameters) } : {}),\n })),\n },\n ]\n }\n const maxTokens = req.maxTokens ?? options.maxTokens\n if (maxTokens) body.generationConfig = { maxOutputTokens: maxTokens }\n const res = await doFetch(`${baseURL}/models/${encodeURIComponent(model)}:streamGenerateContent?alt=sse`, {\n method: 'POST',\n headers: { 'content-type': 'application/json', ...(options.apiKey ? { 'x-goog-api-key': options.apiKey } : {}), ...options.headers },\n body: JSON.stringify(body),\n signal: req.signal,\n })\n if (!res.ok) throw await errorFromResponse(res, 'Gemini')\n\n let text = ''\n let stopReason: string | undefined\n const parts: any[] = []\n const toolCalls: AIToolCall[] = []\n for await (const msg of parseSSE(res)) {\n if (!msg.data) continue\n const chunk = JSON.parse(msg.data)\n if (chunk.error) throw new Error(`Gemini: ${chunk.error.message}`)\n if (chunk.promptFeedback?.blockReason) {\n yield { type: 'error', error: `Blocked by Gemini (${chunk.promptFeedback.blockReason}).` }\n continue\n }\n const cand = chunk.candidates?.[0]\n if (!cand) continue\n for (const part of cand.content?.parts ?? []) {\n if (part.functionCall) {\n parts.push(part)\n const call: AIToolCall = { id: part.functionCall.id ?? newCallId(), name: part.functionCall.name, args: part.functionCall.args ?? {} }\n toolCalls.push(call)\n } else if (typeof part.text === 'string') {\n const last = parts[parts.length - 1]\n if (!part.thought && last && typeof last.text === 'string' && !last.thought && !last.thoughtSignature && !part.thoughtSignature) last.text += part.text\n else parts.push({ ...part })\n if (!part.thought && part.text) {\n text += part.text\n yield { type: 'text', text: part.text }\n }\n } else parts.push(part)\n }\n if (cand.finishReason) stopReason = cand.finishReason\n }\n if (stopReason !== 'MAX_TOKENS') for (const call of toolCalls) yield { type: 'tool_call', call }\n if (stopReason === 'SAFETY') yield { type: 'error', error: 'The response was blocked by Gemini safety filters.' }\n yield {\n type: 'done',\n stopReason,\n message: { role: 'assistant', content: text, toolCalls: toolCalls.length && stopReason !== 'MAX_TOKENS' ? toolCalls : undefined, raw: { provider: 'gemini', data: parts } },\n }\n },\n }\n}\n\n// \u2500\u2500\u2500 Built-in browser AI (Chrome's on-device model) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/**\n * Chrome's built-in on-device model via the Prompt API (`LanguageModel`).\n * Free and private, no API key. No tool calling. Check `browserAI.isAvailable()` first.\n */\nexport const browserAI = /* @__PURE__ */ Object.assign(\n function browserAI(): AIProvider {\n return {\n id: 'browser',\n model: 'on-device',\n tools: false,\n async *stream(req: AIRequest): AsyncIterable<AIEvent> {\n const LM = (globalThis as any).LanguageModel\n if (!LM) throw new Error('Built-in AI is not available in this browser.')\n const history = req.messages.filter((m) => m.role !== 'tool')\n const last = history.pop()\n const initialPrompts = [\n ...(req.system ? [{ role: 'system', content: req.system }] : []),\n ...history.map((m) => ({ role: m.role, content: m.content })),\n ]\n const session = await LM.create({ initialPrompts, signal: req.signal })\n let total = ''\n try {\n const stream = session.promptStreaming(last?.content ?? '', { signal: req.signal })\n for await (const chunk of stream as AsyncIterable<string>) {\n // Older Chrome versions emitted the full text so far; newer ones emit deltas.\n const delta = chunk.startsWith(total) && total ? chunk.slice(total.length) : chunk\n total += delta\n if (delta) yield { type: 'text', text: delta }\n }\n } finally {\n session.destroy?.()\n }\n yield { type: 'done', message: { role: 'assistant', content: total } }\n },\n }\n },\n {\n /** Whether the on-device model can be used in this browser. */\n async isAvailable(): Promise<boolean> {\n const LM = (globalThis as any).LanguageModel\n if (!LM?.availability) return false\n try {\n return (await LM.availability()) !== 'unavailable'\n } catch {\n return false\n }\n },\n },\n)\n\n// \u2500\u2500\u2500 Proxy (recommended for production) \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface ProxyOptions {\n /** Your endpoint created with `createHandler()` from `@qikbar/qikbar/server`. */\n url: string\n headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>)\n credentials?: RequestCredentials\n fetch?: typeof fetch\n}\n\n/** Stream through your own server so API keys never reach the browser. */\nexport function proxy(options: ProxyOptions | string): AIProvider {\n const opts = typeof options === 'string' ? { url: options } : options\n const doFetch = opts.fetch ?? ((...args: Parameters<typeof fetch>) => fetch(...args))\n return {\n id: 'proxy',\n async *stream(req: AIRequest): AsyncIterable<AIEvent> {\n const extra = typeof opts.headers === 'function' ? await opts.headers() : opts.headers\n const res = await doFetch(opts.url, {\n method: 'POST',\n headers: { 'content-type': 'application/json', accept: 'application/x-ndjson', ...extra },\n credentials: opts.credentials ?? 'same-origin',\n body: JSON.stringify({ messages: req.messages, system: req.system, tools: req.tools, maxTokens: req.maxTokens }),\n signal: req.signal,\n })\n if (!res.ok) throw await errorFromResponse(res, 'AI proxy')\n yield* parseNDJSON<AIEvent>(res)\n },\n }\n}\n"],
5
+ "mappings": ";AACA,gBAAgB,MAAM,UAA2C;AAC/D,MAAI,CAAC,SAAS,KAAM;AACpB,MAAM,SAAS,SAAS,KAAK,UAAU,GACjC,UAAU,IAAI,YAAY,GAC5B,SAAS;AACb,MAAI;AACF,eAAS;AACP,UAAM,EAAE,OAAO,KAAK,IAAI,MAAM,OAAO,KAAK;AAC1C,UAAI,KAAM;AACV,gBAAU,QAAQ,OAAO,OAAO,EAAE,QAAQ,GAAK,CAAC;AAChD,UAAI;AACJ,cAAQ,KAAK,OAAO,QAAQ;AAAA,CAAI,MAAM,KAAG;AACvC,YAAM,OAAO,OAAO,MAAM,GAAG,EAAE,EAAE,QAAQ,OAAO,EAAE;AAClD,iBAAS,OAAO,MAAM,KAAK,CAAC,GAC5B,MAAM;AAAA,MACR;AAAA,IACF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O,KAAwC;AACpD,UAAM,QAAQ,OAAO,KAAK,WAAY,aAAa,MAAM,KAAK,QAAQ,IAAI,KAAK,SACzE,MAAM,MAAM,QAAQ,KAAK,KAAK;AAAA,QAClC,QAAQ;AAAA,QACR,SAAS,EAAE,gBAAgB,oBAAoB,QAAQ,wBAAwB,GAAG,MAAM;AAAA,QACxF,aAAa,KAAK,eAAe;AAAA,QACjC,MAAM,KAAK,UAAU,EAAE,UAAU,IAAI,UAAU,QAAQ,IAAI,QAAQ,OAAO,IAAI,OAAO,WAAW,IAAI,UAAU,CAAC;AAAA,QAC/G,QAAQ,IAAI;AAAA,MACd,CAAC;AACD,UAAI,CAAC,IAAI,GAAI,OAAM,MAAM,kBAAkB,KAAK,UAAU;AAC1D,aAAO,YAAqB,GAAG;AAAA,IACjC;AAAA,EACF;AACF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,107 @@
1
+ import {
2
+ anthropic,
3
+ gemini,
4
+ openai
5
+ } from "./chunk-2ADXL7KQ.js";
6
+ import {
7
+ defaultStorage
8
+ } from "./chunk-YCVJQ7U3.js";
9
+
10
+ // src/ai/byok.ts
11
+ var LABELS = {
12
+ anthropic: "Anthropic (Claude)",
13
+ openai: "OpenAI",
14
+ gemini: "Google Gemini",
15
+ "openai-compatible": "OpenAI-compatible (OpenRouter, Groq, Ollama\u2026)"
16
+ };
17
+ function read(storage, key) {
18
+ try {
19
+ let raw = storage.getItem(key);
20
+ return raw ? JSON.parse(raw) : void 0;
21
+ } catch {
22
+ return;
23
+ }
24
+ }
25
+ var byok = /* @__PURE__ */ Object.assign(function(options = {}) {
26
+ let storage = options.storage ?? defaultStorage(), key = options.key ?? "qikbar:byok";
27
+ return {
28
+ id: "byok",
29
+ get model() {
30
+ return read(storage, key)?.model;
31
+ },
32
+ async *stream(req) {
33
+ let s = read(storage, key);
34
+ if (!s?.apiKey && s?.vendor !== "openai-compatible") {
35
+ yield { type: "error", error: "Add your AI API key first: search for \u201CAI Settings\u201D in the command bar." }, yield { type: "done", message: { role: "assistant", content: "" } };
36
+ return;
37
+ }
38
+ yield* (s.vendor === "anthropic" ? anthropic({ apiKey: s.apiKey, model: s.model || void 0 }) : s.vendor === "gemini" ? gemini({ apiKey: s.apiKey, model: s.model || void 0 }) : openai({ apiKey: s.apiKey || void 0, model: s.model || void 0, baseURL: s.baseURL || void 0 })).stream(req);
39
+ }
40
+ };
41
+ }, {
42
+ /** An extension with an "AI Settings" command where users enter their own key. */
43
+ settings: settingsExtension
44
+ });
45
+ function settingsExtension(options = {}) {
46
+ let storage = options.storage ?? defaultStorage(), key = options.key ?? "qikbar:byok", vendors = options.vendors ?? Object.keys(LABELS);
47
+ return {
48
+ name: "qikbar-ai-settings",
49
+ title: "AI",
50
+ icon: "key",
51
+ commands: [
52
+ {
53
+ name: "settings",
54
+ title: "AI Settings",
55
+ subtitle: "Use your own API key",
56
+ keywords: ["api key", "openai", "anthropic", "claude", "gemini", "model", "byok"],
57
+ icon: "key",
58
+ view: () => {
59
+ let current = read(storage, key);
60
+ return {
61
+ type: "form",
62
+ title: "AI Settings",
63
+ submitLabel: "Save",
64
+ fields: [
65
+ {
66
+ name: "vendor",
67
+ label: "Provider",
68
+ type: "select",
69
+ options: vendors.map((v) => ({ title: LABELS[v], value: v })),
70
+ defaultValue: current?.vendor ?? vendors[0]
71
+ },
72
+ {
73
+ name: "apiKey",
74
+ label: "API key",
75
+ type: "password",
76
+ placeholder: "Stored only in this browser",
77
+ defaultValue: current?.apiKey ?? "",
78
+ description: "Your key never leaves your browser except to call the provider directly."
79
+ },
80
+ { name: "model", label: "Model", placeholder: "Leave empty for the default", defaultValue: current?.model ?? "" },
81
+ { name: "baseURL", label: "Base URL", placeholder: "Only for OpenAI-compatible APIs", defaultValue: current?.baseURL ?? "" }
82
+ ],
83
+ onSubmit(values, ctx) {
84
+ storage.setItem(key, JSON.stringify(values)), ctx.toast({ title: "AI settings saved", style: "success" });
85
+ }
86
+ };
87
+ }
88
+ },
89
+ {
90
+ name: "clear",
91
+ title: "Remove AI API Key",
92
+ icon: "trash",
93
+ keywords: ["byok", "api key"],
94
+ searchOnly: !0,
95
+ async run(ctx) {
96
+ if (!await ctx.confirm({ title: "Remove your API key?", destructive: !0, confirmLabel: "Remove" })) return !1;
97
+ storage.removeItem(key), ctx.toast({ title: "API key removed", style: "success" });
98
+ }
99
+ }
100
+ ]
101
+ };
102
+ }
103
+
104
+ export {
105
+ byok
106
+ };
107
+ //# sourceMappingURL=chunk-6TC6G2C5.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/ai/byok.ts"],
4
+ "sourcesContent": ["import { defineExtension } from '../core/define.js'\nimport { defaultStorage } from '../core/storage.js'\nimport type { AIEvent, AIProvider, AIRequest, Extension, StorageAdapter } from '../core/types.js'\nimport { anthropic, gemini, openai } from './providers.js'\n\nexport type ByokVendor = 'anthropic' | 'openai' | 'gemini' | 'openai-compatible'\n\nexport interface ByokSettings {\n vendor: ByokVendor\n apiKey: string\n model?: string\n baseURL?: string\n}\n\nexport interface ByokOptions {\n /** Vendors offered in settings. Default: all. */\n vendors?: ByokVendor[]\n /** Storage key. Default `\"qikbar:byok\"`. */\n key?: string\n storage?: StorageAdapter\n}\n\nconst LABELS: Record<ByokVendor, string> = {\n anthropic: 'Anthropic (Claude)',\n openai: 'OpenAI',\n gemini: 'Google Gemini',\n 'openai-compatible': 'OpenAI-compatible (OpenRouter, Groq, Ollama\u2026)',\n}\n\nfunction read(storage: StorageAdapter, key: string): ByokSettings | undefined {\n try {\n const raw = storage.getItem(key)\n return raw ? (JSON.parse(raw) as ByokSettings) : undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * \"Bring your own key\": your users paste their own API key, stored only in their\n * browser. Pair with `byok.settings()` so they can configure it from the bar.\n *\n * ```ts\n * createQikbar({ ai: byok(), extensions: [byok.settings()] })\n * ```\n */\nexport const byok = /* @__PURE__ */ Object.assign(function byok(options: ByokOptions = {}): AIProvider {\n const storage = options.storage ?? defaultStorage()\n const key = options.key ?? 'qikbar:byok'\n return {\n id: 'byok',\n get model() {\n return read(storage, key)?.model\n },\n async *stream(req: AIRequest): AsyncIterable<AIEvent> {\n const s = read(storage, key)\n if (!s?.apiKey && s?.vendor !== 'openai-compatible') {\n yield { type: 'error', error: 'Add your AI API key first: search for \u201CAI Settings\u201D in the command bar.' }\n yield { type: 'done', message: { role: 'assistant', content: '' } }\n return\n }\n const provider =\n s.vendor === 'anthropic'\n ? anthropic({ apiKey: s.apiKey, model: s.model || undefined })\n : s.vendor === 'gemini'\n ? gemini({ apiKey: s.apiKey, model: s.model || undefined })\n : openai({ apiKey: s.apiKey || undefined, model: s.model || undefined, baseURL: s.baseURL || undefined })\n yield* provider.stream(req)\n },\n }\n}, {\n /** An extension with an \"AI Settings\" command where users enter their own key. */\n settings: settingsExtension,\n})\n\nfunction settingsExtension(options: ByokOptions = {}): Extension {\n const storage = options.storage ?? defaultStorage()\n const key = options.key ?? 'qikbar:byok'\n const vendors = options.vendors ?? (Object.keys(LABELS) as ByokVendor[])\n return defineExtension({\n name: 'qikbar-ai-settings',\n title: 'AI',\n icon: 'key',\n commands: [\n {\n name: 'settings',\n title: 'AI Settings',\n subtitle: 'Use your own API key',\n keywords: ['api key', 'openai', 'anthropic', 'claude', 'gemini', 'model', 'byok'],\n icon: 'key',\n view: () => {\n const current = read(storage, key)\n return {\n type: 'form',\n title: 'AI Settings',\n submitLabel: 'Save',\n fields: [\n {\n name: 'vendor',\n label: 'Provider',\n type: 'select',\n options: vendors.map((v) => ({ title: LABELS[v], value: v })),\n defaultValue: current?.vendor ?? vendors[0],\n },\n {\n name: 'apiKey',\n label: 'API key',\n type: 'password',\n placeholder: 'Stored only in this browser',\n defaultValue: current?.apiKey ?? '',\n description: 'Your key never leaves your browser except to call the provider directly.',\n },\n { name: 'model', label: 'Model', placeholder: 'Leave empty for the default', defaultValue: current?.model ?? '' },\n { name: 'baseURL', label: 'Base URL', placeholder: 'Only for OpenAI-compatible APIs', defaultValue: current?.baseURL ?? '' },\n ],\n onSubmit(values, ctx) {\n storage.setItem(key, JSON.stringify(values))\n ctx.toast({ title: 'AI settings saved', style: 'success' })\n },\n }\n },\n },\n {\n name: 'clear',\n title: 'Remove AI API Key',\n icon: 'trash',\n keywords: ['byok', 'api key'],\n searchOnly: true,\n async run(ctx) {\n if (!(await ctx.confirm({ title: 'Remove your API key?', destructive: true, confirmLabel: 'Remove' }))) return false\n storage.removeItem(key)\n ctx.toast({ title: 'API key removed', style: 'success' })\n },\n },\n ],\n })\n}\n"],
5
+ "mappings": ";;;;;;;;;;AAsBA,IAAM,SAAqC;AAAA,EACzC,WAAW;AAAA,EACX,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,qBAAqB;AACvB;AAEA,SAAS,KAAK,SAAyB,KAAuC;AAC5E,MAAI;AACF,QAAM,MAAM,QAAQ,QAAQ,GAAG;AAC/B,WAAO,MAAO,KAAK,MAAM,GAAG,IAAqB;AAAA,EACnD,QAAQ;AACN;AAAA,EACF;AACF;AAUO,IAAM,OAAuB,uBAAO,OAAO,SAAc,UAAuB,CAAC,GAAe;AACrG,MAAM,UAAU,QAAQ,WAAW,eAAe,GAC5C,MAAM,QAAQ,OAAO;AAC3B,SAAO;AAAA,IACL,IAAI;AAAA,IACJ,IAAI,QAAQ;AACV,aAAO,KAAK,SAAS,GAAG,GAAG;AAAA,IAC7B;AAAA,IACA,OAAO,OAAO,KAAwC;AACpD,UAAM,IAAI,KAAK,SAAS,GAAG;AAC3B,UAAI,CAAC,GAAG,UAAU,GAAG,WAAW,qBAAqB;AACnD,cAAM,EAAE,MAAM,SAAS,OAAO,oFAA0E,GACxG,MAAM,EAAE,MAAM,QAAQ,SAAS,EAAE,MAAM,aAAa,SAAS,GAAG,EAAE;AAClE;AAAA,MACF;AAOA,cALE,EAAE,WAAW,cACT,UAAU,EAAE,QAAQ,EAAE,QAAQ,OAAO,EAAE,SAAS,OAAU,CAAC,IAC3D,EAAE,WAAW,WACX,OAAO,EAAE,QAA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