@qikbar/qikbar 0.0.25 → 0.2.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 (114) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +121 -0
  3. package/bin/qikbar.mjs +203 -0
  4. package/dist/ai/agent.d.ts +42 -0
  5. package/dist/ai/byok.d.ts +29 -0
  6. package/dist/ai/embeddings.d.ts +51 -0
  7. package/dist/ai/index.d.ts +12 -0
  8. package/dist/ai/mcp.d.ts +84 -0
  9. package/dist/ai/providers.d.ts +82 -0
  10. package/dist/ai/sse.d.ts +9 -0
  11. package/dist/ai.js +54 -0
  12. package/dist/ai.js.map +7 -0
  13. package/dist/chunks/bar-P3SCR4SJ.js +2555 -0
  14. package/dist/chunks/bar-P3SCR4SJ.js.map +7 -0
  15. package/dist/chunks/chunk-5FI7DNG7.js +271 -0
  16. package/dist/chunks/chunk-5FI7DNG7.js.map +7 -0
  17. package/dist/chunks/chunk-INTEVQYK.js +108 -0
  18. package/dist/chunks/chunk-INTEVQYK.js.map +7 -0
  19. package/dist/chunks/chunk-JHQAIXM7.js +458 -0
  20. package/dist/chunks/chunk-JHQAIXM7.js.map +7 -0
  21. package/dist/chunks/chunk-MPTP2EWW.js +8 -0
  22. package/dist/chunks/chunk-MPTP2EWW.js.map +7 -0
  23. package/dist/chunks/chunk-MRHKJ2FZ.js +419 -0
  24. package/dist/chunks/chunk-MRHKJ2FZ.js.map +7 -0
  25. package/dist/chunks/chunk-N4Y2Z6YD.js +69 -0
  26. package/dist/chunks/chunk-N4Y2Z6YD.js.map +7 -0
  27. package/dist/chunks/chunk-OLXZNYZ4.js +193 -0
  28. package/dist/chunks/chunk-OLXZNYZ4.js.map +7 -0
  29. package/dist/chunks/chunk-PQEHV3D4.js +124 -0
  30. package/dist/chunks/chunk-PQEHV3D4.js.map +7 -0
  31. package/dist/chunks/chunk-R2AY6LRL.js +575 -0
  32. package/dist/chunks/chunk-R2AY6LRL.js.map +7 -0
  33. package/dist/chunks/chunk-TIM4VBM4.js +98 -0
  34. package/dist/chunks/chunk-TIM4VBM4.js.map +7 -0
  35. package/dist/chunks/chunk-YCVJQ7U3.js +52 -0
  36. package/dist/chunks/chunk-YCVJQ7U3.js.map +7 -0
  37. package/dist/chunks/launcher-B5MGOPEQ.js +37 -0
  38. package/dist/chunks/launcher-B5MGOPEQ.js.map +7 -0
  39. package/dist/core/define.d.ts +40 -0
  40. package/dist/core/frecency.d.ts +16 -0
  41. package/dist/core/hotkeys.d.ts +39 -0
  42. package/dist/core/labels.d.ts +98 -0
  43. package/dist/core/launcher.d.ts +8 -0
  44. package/dist/core/lazy.d.ts +60 -0
  45. package/dist/core/search.d.ts +42 -0
  46. package/dist/core/storage.d.ts +5 -0
  47. package/dist/core/types.d.ts +737 -0
  48. package/dist/element/index.d.ts +56 -0
  49. package/dist/element.js +146 -0
  50. package/dist/element.js.map +7 -0
  51. package/dist/extensions/index.d.ts +30 -0
  52. package/dist/extensions/math.d.ts +14 -0
  53. package/dist/extensions.js +476 -0
  54. package/dist/extensions.js.map +7 -0
  55. package/dist/index.d.ts +31 -0
  56. package/dist/index.js +85 -0
  57. package/dist/index.js.map +7 -0
  58. package/dist/locales/index.d.ts +24 -0
  59. package/dist/locales.js +810 -0
  60. package/dist/locales.js.map +7 -0
  61. package/dist/qikbar.global.js +302 -0
  62. package/dist/qikbar.global.js.map +7 -0
  63. package/dist/react/index.d.ts +66 -0
  64. package/dist/react.js +121 -0
  65. package/dist/react.js.map +7 -0
  66. package/dist/server/index.d.ts +66 -0
  67. package/dist/server.js +129 -0
  68. package/dist/server.js.map +7 -0
  69. package/dist/solid/index.d.ts +42 -0
  70. package/dist/solid.js +93 -0
  71. package/dist/solid.js.map +7 -0
  72. package/dist/styles.css +253 -0
  73. package/dist/svelte/index.d.ts +58 -0
  74. package/dist/svelte.js +55 -0
  75. package/dist/svelte.js.map +7 -0
  76. package/dist/theme.d.ts +5 -0
  77. package/dist/theme.js +20 -0
  78. package/dist/theme.js.map +7 -0
  79. package/dist/ui/bar.d.ts +338 -0
  80. package/dist/ui/dom.d.ts +21 -0
  81. package/dist/ui/icons.d.ts +93 -0
  82. package/dist/ui/markdown.d.ts +10 -0
  83. package/dist/ui/nav.d.ts +8 -0
  84. package/dist/ui/styles.d.ts +6 -0
  85. package/dist/ui/themes.d.ts +27 -0
  86. package/dist/ui/views.d.ts +156 -0
  87. package/dist/ui/webmcp.d.ts +33 -0
  88. package/dist/utils.d.ts +10 -0
  89. package/dist/utils.js +50 -0
  90. package/dist/utils.js.map +7 -0
  91. package/dist/vue/index.d.ts +74 -0
  92. package/dist/vue.js +122 -0
  93. package/dist/vue.js.map +7 -0
  94. package/package.json +129 -43
  95. package/dist/qikbar.es.js +0 -8748
  96. package/dist/qikbar.umd.js +0 -113
  97. package/dist/types/boot.d.ts +0 -72
  98. package/dist/types/index.d.ts +0 -1
  99. package/dist/types/init.d.ts +0 -2
  100. package/dist/types/main.d.ts +0 -4
  101. package/dist/types/shared/AsyncRoot.d.ts +0 -5
  102. package/dist/types/shared/CommandFooter.d.ts +0 -5
  103. package/dist/types/shared/Crumbs.d.ts +0 -6
  104. package/dist/types/shared/Details.d.ts +0 -3
  105. package/dist/types/shared/ErrorBoundary.d.ts +0 -15
  106. package/dist/types/shared/Icon.d.ts +0 -4
  107. package/dist/types/shared/List.d.ts +0 -30
  108. package/dist/types/shared/Qikbar.d.ts +0 -5
  109. package/dist/types/shared/Root.d.ts +0 -4
  110. package/dist/types/shared/Search.d.ts +0 -1
  111. package/dist/types/shared/commandContext.d.ts +0 -8
  112. package/dist/types/shared/useDebounce.d.ts +0 -1
  113. package/dist/types/utils/liquid.d.ts +0 -4
  114. package/dist/types/vite-env.d.ts +0 -1
@@ -0,0 +1,271 @@
1
+ import {
2
+ anthropic,
3
+ gemini,
4
+ openai,
5
+ parseSSE
6
+ } from "./chunk-MRHKJ2FZ.js";
7
+ import {
8
+ defaultStorage
9
+ } from "./chunk-YCVJQ7U3.js";
10
+ import {
11
+ __publicField
12
+ } from "./chunk-MPTP2EWW.js";
13
+
14
+ // src/ai/byok.ts
15
+ var LABELS = {
16
+ anthropic: "Anthropic (Claude)",
17
+ openai: "OpenAI",
18
+ gemini: "Google Gemini",
19
+ "openai-compatible": "OpenAI-compatible (OpenRouter, Groq, Ollama\u2026)"
20
+ };
21
+ function read(storage, key) {
22
+ try {
23
+ let raw = storage.getItem(key);
24
+ return raw ? JSON.parse(raw) : void 0;
25
+ } catch {
26
+ return;
27
+ }
28
+ }
29
+ var byok = /* @__PURE__ */ Object.assign(function(options = {}) {
30
+ let storage = options.storage ?? defaultStorage(), key = options.key ?? "qikbar:byok";
31
+ return {
32
+ id: "byok",
33
+ get model() {
34
+ return read(storage, key)?.model;
35
+ },
36
+ async *stream(req) {
37
+ let s = read(storage, key);
38
+ if (!s?.apiKey && s?.vendor !== "openai-compatible") {
39
+ 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: "" } };
40
+ return;
41
+ }
42
+ 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);
43
+ }
44
+ };
45
+ }, {
46
+ /** An extension with an "AI Settings" command where users enter their own key. */
47
+ settings: settingsExtension
48
+ });
49
+ function settingsExtension(options = {}) {
50
+ let storage = options.storage ?? defaultStorage(), key = options.key ?? "qikbar:byok", vendors = options.vendors ?? Object.keys(LABELS);
51
+ return {
52
+ name: "qikbar-ai-settings",
53
+ title: "AI",
54
+ icon: "key",
55
+ commands: [
56
+ {
57
+ name: "settings",
58
+ title: "AI Settings",
59
+ subtitle: "Use your own API key",
60
+ keywords: ["api key", "openai", "anthropic", "claude", "gemini", "model", "byok"],
61
+ icon: "key",
62
+ view: () => {
63
+ let current = read(storage, key);
64
+ return {
65
+ type: "form",
66
+ title: "AI Settings",
67
+ submitLabel: "Save",
68
+ fields: [
69
+ {
70
+ name: "vendor",
71
+ label: "Provider",
72
+ type: "select",
73
+ options: vendors.map((v) => ({ title: LABELS[v], value: v })),
74
+ defaultValue: current?.vendor ?? vendors[0]
75
+ },
76
+ {
77
+ name: "apiKey",
78
+ label: "API key",
79
+ type: "password",
80
+ placeholder: "Stored only in this browser",
81
+ defaultValue: current?.apiKey ?? "",
82
+ description: "Your key never leaves your browser except to call the provider directly."
83
+ },
84
+ { name: "model", label: "Model", placeholder: "Leave empty for the default", defaultValue: current?.model ?? "" },
85
+ { name: "baseURL", label: "Base URL", placeholder: "Only for OpenAI-compatible APIs", defaultValue: current?.baseURL ?? "" }
86
+ ],
87
+ onSubmit(values, ctx) {
88
+ storage.setItem(key, JSON.stringify(values)), ctx.toast({ title: "AI settings saved", style: "success" });
89
+ }
90
+ };
91
+ }
92
+ },
93
+ {
94
+ name: "clear",
95
+ title: "Remove AI API Key",
96
+ icon: "trash",
97
+ keywords: ["byok", "api key"],
98
+ searchOnly: !0,
99
+ async run(ctx) {
100
+ if (!await ctx.confirm({ title: "Remove your API key?", destructive: !0, confirmLabel: "Remove" })) return !1;
101
+ storage.removeItem(key), ctx.toast({ title: "API key removed", style: "success" });
102
+ }
103
+ }
104
+ ]
105
+ };
106
+ }
107
+
108
+ // src/ai/mcp.ts
109
+ var MCP_PROTOCOL_VERSION = "2025-06-18", MCPError = class extends Error {
110
+ constructor(message, code) {
111
+ super(message);
112
+ __publicField(this, "code", code);
113
+ this.name = "MCPError";
114
+ }
115
+ }, MCPClient = class {
116
+ constructor(options) {
117
+ __publicField(this, "options", options);
118
+ __publicField(this, "session");
119
+ __publicField(this, "protocol", MCP_PROTOCOL_VERSION);
120
+ __publicField(this, "ready");
121
+ __publicField(this, "negotiated", !1);
122
+ __publicField(this, "nextId", 1);
123
+ __publicField(this, "serverInfo");
124
+ }
125
+ async headers() {
126
+ let h = this.options.headers, extra = typeof h == "function" ? await h() : h ?? {};
127
+ return {
128
+ "content-type": "application/json",
129
+ accept: "application/json, text/event-stream",
130
+ ...this.session ? { "mcp-session-id": this.session } : {},
131
+ ...this.negotiated ? { "mcp-protocol-version": this.protocol } : {},
132
+ ...extra
133
+ };
134
+ }
135
+ async post(body, signal, expectId) {
136
+ let res = await (this.options.fetch ?? globalThis.fetch)(this.options.url, {
137
+ method: "POST",
138
+ headers: await this.headers(),
139
+ body: JSON.stringify(body),
140
+ signal,
141
+ credentials: this.options.credentials ?? "same-origin"
142
+ }), session = res.headers.get("mcp-session-id");
143
+ if (session && (this.session = session), res.status === 404 && this.session && expectId != null)
144
+ throw this.session = void 0, this.ready = void 0, this.negotiated = !1, new MCPError("MCP session expired", 404);
145
+ if (!res.ok && res.status !== 202) {
146
+ let text = await res.text().catch(() => "");
147
+ throw new MCPError(`MCP server responded ${res.status}${text ? `: ${text.slice(0, 200)}` : ""}`, res.status);
148
+ }
149
+ if (expectId == null || res.status === 202) return;
150
+ if ((res.headers.get("content-type") ?? "").includes("text/event-stream")) {
151
+ for await (let ev of parseSSE(res)) {
152
+ if (!ev.data) continue;
153
+ let msg;
154
+ try {
155
+ msg = JSON.parse(ev.data);
156
+ } catch {
157
+ continue;
158
+ }
159
+ for (let m of Array.isArray(msg) ? msg : [msg]) if (m.id === expectId) return m;
160
+ }
161
+ throw new MCPError("MCP stream ended without a response");
162
+ }
163
+ let json = await res.json(), list = Array.isArray(json) ? json : [json];
164
+ return list.find((m) => m.id === expectId) ?? list[0];
165
+ }
166
+ async request(method, params, signal, retry = !0) {
167
+ method !== "initialize" && await this.connect(signal);
168
+ let id = this.nextId++, res;
169
+ try {
170
+ res = await this.post({ jsonrpc: "2.0", id, method, ...params ? { params } : {} }, signal, id);
171
+ } catch (err) {
172
+ if (retry && err instanceof MCPError && err.code === 404 && method !== "initialize") return this.request(method, params, signal, !1);
173
+ throw err;
174
+ }
175
+ if (!res) throw new MCPError(`No response to ${method}`);
176
+ if (res.error) throw new MCPError(res.error.message, res.error.code);
177
+ return res.result;
178
+ }
179
+ /** Initialize the session (once). */
180
+ connect(signal) {
181
+ return this.ready ?? (this.ready = (async () => {
182
+ let result = await this.request(
183
+ "initialize",
184
+ { protocolVersion: MCP_PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: "qikbar", version: "0.2.0" } },
185
+ signal
186
+ );
187
+ result?.protocolVersion && (this.protocol = result.protocolVersion), this.negotiated = !0, this.serverInfo = result?.serverInfo, await this.post({ jsonrpc: "2.0", method: "notifications/initialized" }, signal);
188
+ })()), this.ready.catch(() => {
189
+ this.ready = void 0;
190
+ }), this.ready;
191
+ }
192
+ /** List every tool, following pagination. */
193
+ async listTools(signal) {
194
+ let tools = [], cursor;
195
+ for (let page = 0; page < 20; page++) {
196
+ let res = await this.request("tools/list", cursor ? { cursor } : void 0, signal);
197
+ if (tools.push(...res?.tools ?? []), cursor = res?.nextCursor, !cursor) break;
198
+ }
199
+ return tools;
200
+ }
201
+ /** Call a tool and return its result as text for the model. */
202
+ async callTool(name, args, signal) {
203
+ let res = await this.request("tools/call", { name, arguments: args }, signal), text = contentToText(res?.content, res?.structuredContent);
204
+ if (res?.isError) throw new MCPError(text || `Tool ${name} failed`);
205
+ return text;
206
+ }
207
+ /** End the session (best effort). */
208
+ async close() {
209
+ if (!this.session) return;
210
+ let doFetch = this.options.fetch ?? globalThis.fetch;
211
+ try {
212
+ await doFetch(this.options.url, { method: "DELETE", headers: await this.headers(), credentials: this.options.credentials ?? "same-origin" });
213
+ } catch {
214
+ }
215
+ this.session = void 0, this.ready = void 0, this.negotiated = !1;
216
+ }
217
+ };
218
+ function contentToText(content, structured) {
219
+ let parts = [];
220
+ for (let c of content ?? [])
221
+ c.type === "text" && c.text != null ? parts.push(c.text) : c.type === "resource" && c.resource?.text ? parts.push(c.resource.text) : c.type === "resource_link" ? parts.push(`[${c.name ?? c.uri}](${c.uri})`) : (c.type === "image" || c.type === "audio") && parts.push(`[${c.type}${c.mimeType ? ` ${c.mimeType}` : ""}]`);
222
+ return !parts.length && structured !== void 0 ? JSON.stringify(structured) : parts.join(`
223
+
224
+ `);
225
+ }
226
+ function nameFromUrl(url) {
227
+ try {
228
+ return (new URL(url, typeof location < "u" ? location.href : "http://localhost").host.replace(/^(www|api|mcp)\./, "").split(".")[0] || "mcp").replace(/[^a-zA-Z0-9_-]/g, "_");
229
+ } catch {
230
+ return "mcp";
231
+ }
232
+ }
233
+ function mcp(options) {
234
+ let client = new MCPClient(options), name = (options.name ?? nameFromUrl(options.url)).replace(/[^a-zA-Z0-9_-]/g, "_"), cache, ttl = options.ttl ?? 5 * 6e4, shouldConfirm = (info) => {
235
+ let c = options.confirm;
236
+ return typeof c == "function" ? c(info) : typeof c == "boolean" ? c : info.annotations?.readOnlyHint !== !0;
237
+ }, load = async (signal) => (await client.listTools(signal)).filter((t) => (!options.include || options.include.includes(t.name)) && !options.exclude?.includes(t.name)).map(
238
+ (info) => ({
239
+ name: info.name,
240
+ description: info.description || info.annotations?.title || info.title || info.name,
241
+ parameters: info.inputSchema ?? { type: "object", properties: {} },
242
+ confirm: shouldConfirm(info) ? () => `Allow ${info.annotations?.title ?? info.title ?? info.name} (${name})?` : !1,
243
+ run: (args, ctx) => client.callTool(info.name, args ?? {}, ctx.signal)
244
+ })
245
+ );
246
+ return {
247
+ name,
248
+ client,
249
+ refresh() {
250
+ cache = void 0;
251
+ },
252
+ tools(signal) {
253
+ if (!cache || Date.now() - cache.at > ttl) {
254
+ let entry = { at: Date.now(), tools: load(signal) };
255
+ cache = entry, entry.tools.catch(() => {
256
+ cache === entry && (cache = void 0);
257
+ });
258
+ }
259
+ return cache.tools;
260
+ }
261
+ };
262
+ }
263
+
264
+ export {
265
+ byok,
266
+ MCP_PROTOCOL_VERSION,
267
+ MCPError,
268
+ MCPClient,
269
+ mcp
270
+ };
271
+ //# sourceMappingURL=chunk-5FI7DNG7.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/ai/byok.ts", "../../src/ai/mcp.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", "/**\n * A minimal MCP client (Streamable HTTP transport) that turns a remote MCP\n * server's tools into tools the bar's AI can call.\n *\n * ```ts\n * import { mcp } from '@qikbar/qikbar/ai'\n * createQikbar({ ai: { provider, mcp: [mcp({ url: '/api/mcp' })] } })\n * ```\n *\n * Browsers can only reach servers that allow CORS. For third-party servers,\n * proxy them through your backend (which also keeps tokens server-side).\n */\n\nimport type { JSONSchema, Tool, ToolProvider } from '../core/types.js'\nimport { parseSSE } from './sse.js'\n\nexport const MCP_PROTOCOL_VERSION = '2025-06-18'\n\nexport interface MCPOptions {\n /** The server's Streamable HTTP endpoint. */\n url: string\n /** Prefix for tool names and the label shown in errors. Default derived from the URL. */\n name?: string\n /** Extra headers, e.g. `{ Authorization: 'Bearer \u2026' }`. A function is called per request. */\n headers?: Record<string, string> | (() => Record<string, string> | Promise<Record<string, string>>)\n /** Only expose these tools (by name). */\n include?: string[]\n /** Hide these tools (by name). */\n exclude?: string[]\n /**\n * Ask the user before running a tool. Default: ask unless the server marks the tool\n * `readOnlyHint: true`. Pass `true`/`false` to always/never ask, or a function per tool.\n */\n confirm?: boolean | ((tool: MCPToolInfo) => boolean)\n /** Re-list tools after this many ms. Default 5 minutes. */\n ttl?: number\n /** Custom fetch (for tests or proxies). */\n fetch?: typeof fetch\n /** Send cookies to the server (same-origin proxies). Default `\"same-origin\"`. */\n credentials?: RequestCredentials\n}\n\nexport interface MCPToolInfo {\n name: string\n title?: string\n description?: string\n inputSchema?: JSONSchema\n annotations?: { title?: string; readOnlyHint?: boolean; destructiveHint?: boolean; idempotentHint?: boolean; openWorldHint?: boolean }\n}\n\ninterface MCPContent {\n type: string\n text?: string\n mimeType?: string\n resource?: { uri?: string; text?: string }\n uri?: string\n name?: string\n}\n\ninterface JsonRpcResponse {\n jsonrpc: '2.0'\n id?: number | string\n result?: any\n error?: { code: number; message: string; data?: unknown }\n}\n\nexport class MCPError extends Error {\n constructor(\n message: string,\n readonly code?: number,\n ) {\n super(message)\n this.name = 'MCPError'\n }\n}\n\n/** A low-level MCP client. Most apps only need `mcp()`. */\nexport class MCPClient {\n private session?: string\n private protocol = MCP_PROTOCOL_VERSION\n private ready?: Promise<void>\n private negotiated = false\n private nextId = 1\n serverInfo?: { name?: string; version?: string }\n\n constructor(private options: MCPOptions) {}\n\n private async headers(): Promise<Record<string, string>> {\n const h = this.options.headers\n const extra = typeof h === 'function' ? await h() : (h ?? {})\n return {\n 'content-type': 'application/json',\n accept: 'application/json, text/event-stream',\n ...(this.session ? { 'mcp-session-id': this.session } : {}),\n ...(this.negotiated ? { 'mcp-protocol-version': this.protocol } : {}),\n ...extra,\n }\n }\n\n private async post(body: object, signal?: AbortSignal, expectId?: number): Promise<JsonRpcResponse | undefined> {\n const doFetch = this.options.fetch ?? globalThis.fetch\n const res = await doFetch(this.options.url, {\n method: 'POST',\n headers: await this.headers(),\n body: JSON.stringify(body),\n signal,\n credentials: this.options.credentials ?? 'same-origin',\n })\n const session = res.headers.get('mcp-session-id')\n if (session) this.session = session\n if (res.status === 404 && this.session && expectId != null) {\n // The server forgot our session: start over once.\n this.session = undefined\n this.ready = undefined\n this.negotiated = false\n throw new MCPError('MCP session expired', 404)\n }\n if (!res.ok && res.status !== 202) {\n const text = await res.text().catch(() => '')\n throw new MCPError(`MCP server responded ${res.status}${text ? `: ${text.slice(0, 200)}` : ''}`, res.status)\n }\n if (expectId == null || res.status === 202) return undefined\n const type = res.headers.get('content-type') ?? ''\n if (type.includes('text/event-stream')) {\n for await (const ev of parseSSE(res)) {\n if (!ev.data) continue\n let msg: JsonRpcResponse | JsonRpcResponse[]\n try {\n msg = JSON.parse(ev.data)\n } catch {\n continue\n }\n for (const m of Array.isArray(msg) ? msg : [msg]) if (m.id === expectId) return m\n }\n throw new MCPError('MCP stream ended without a response')\n }\n const json = (await res.json()) as JsonRpcResponse | JsonRpcResponse[]\n const list = Array.isArray(json) ? json : [json]\n return list.find((m) => m.id === expectId) ?? list[0]\n }\n\n private async request<T = any>(method: string, params: object | undefined, signal?: AbortSignal, retry = true): Promise<T> {\n if (method !== 'initialize') await this.connect(signal)\n const id = this.nextId++\n let res: JsonRpcResponse | undefined\n try {\n res = await this.post({ jsonrpc: '2.0', id, method, ...(params ? { params } : {}) }, signal, id)\n } catch (err) {\n if (retry && err instanceof MCPError && err.code === 404 && method !== 'initialize') return this.request(method, params, signal, false)\n throw err\n }\n if (!res) throw new MCPError(`No response to ${method}`)\n if (res.error) throw new MCPError(res.error.message, res.error.code)\n return res.result as T\n }\n\n /** Initialize the session (once). */\n connect(signal?: AbortSignal): Promise<void> {\n this.ready ??= (async () => {\n const result = await this.request<{ protocolVersion?: string; serverInfo?: { name?: string; version?: string } }>(\n 'initialize',\n { protocolVersion: MCP_PROTOCOL_VERSION, capabilities: {}, clientInfo: { name: 'qikbar', version: '0.2.0' } },\n signal,\n )\n if (result?.protocolVersion) this.protocol = result.protocolVersion\n this.negotiated = true\n this.serverInfo = result?.serverInfo\n await this.post({ jsonrpc: '2.0', method: 'notifications/initialized' }, signal)\n })()\n this.ready.catch(() => {\n this.ready = undefined\n })\n return this.ready\n }\n\n /** List every tool, following pagination. */\n async listTools(signal?: AbortSignal): Promise<MCPToolInfo[]> {\n const tools: MCPToolInfo[] = []\n let cursor: string | undefined\n for (let page = 0; page < 20; page++) {\n const res = await this.request<{ tools?: MCPToolInfo[]; nextCursor?: string }>('tools/list', cursor ? { cursor } : undefined, signal)\n tools.push(...(res?.tools ?? []))\n cursor = res?.nextCursor\n if (!cursor) break\n }\n return tools\n }\n\n /** Call a tool and return its result as text for the model. */\n async callTool(name: string, args: Record<string, unknown>, signal?: AbortSignal): Promise<string> {\n const res = await this.request<{ content?: MCPContent[]; structuredContent?: unknown; isError?: boolean }>('tools/call', { name, arguments: args }, signal)\n const text = contentToText(res?.content, res?.structuredContent)\n if (res?.isError) throw new MCPError(text || `Tool ${name} failed`)\n return text\n }\n\n /** End the session (best effort). */\n async close() {\n if (!this.session) return\n const doFetch = this.options.fetch ?? globalThis.fetch\n try {\n await doFetch(this.options.url, { method: 'DELETE', headers: await this.headers(), credentials: this.options.credentials ?? 'same-origin' })\n } catch {\n // ignore\n }\n this.session = undefined\n this.ready = undefined\n this.negotiated = false\n }\n}\n\nfunction contentToText(content: MCPContent[] | undefined, structured: unknown): string {\n const parts: string[] = []\n for (const c of content ?? []) {\n if (c.type === 'text' && c.text != null) parts.push(c.text)\n else if (c.type === 'resource' && c.resource?.text) parts.push(c.resource.text)\n else if (c.type === 'resource_link') parts.push(`[${c.name ?? c.uri}](${c.uri})`)\n else if (c.type === 'image' || c.type === 'audio') parts.push(`[${c.type}${c.mimeType ? ` ${c.mimeType}` : ''}]`)\n }\n if (!parts.length && structured !== undefined) return JSON.stringify(structured)\n return parts.join('\\n\\n')\n}\n\nfunction nameFromUrl(url: string): string {\n try {\n const u = new URL(url, typeof location !== 'undefined' ? location.href : 'http://localhost')\n const host = u.host.replace(/^(www|api|mcp)\\./, '').split('.')[0]\n return (host || 'mcp').replace(/[^a-zA-Z0-9_-]/g, '_')\n } catch {\n return 'mcp'\n }\n}\n\n/** Use an MCP server's tools in the bar's AI chat. */\nexport function mcp(options: MCPOptions): ToolProvider & { client: MCPClient; refresh(): void } {\n const client = new MCPClient(options)\n const name = (options.name ?? nameFromUrl(options.url)).replace(/[^a-zA-Z0-9_-]/g, '_')\n let cache: { at: number; tools: Promise<Tool[]> } | undefined\n const ttl = options.ttl ?? 5 * 60_000\n\n const shouldConfirm = (info: MCPToolInfo) => {\n const c = options.confirm\n if (typeof c === 'function') return c(info)\n if (typeof c === 'boolean') return c\n return info.annotations?.readOnlyHint !== true\n }\n\n const load = async (signal?: AbortSignal): Promise<Tool[]> => {\n const infos = await client.listTools(signal)\n return infos\n .filter((t) => (!options.include || options.include.includes(t.name)) && !options.exclude?.includes(t.name))\n .map(\n (info): Tool => ({\n name: info.name,\n description: info.description || info.annotations?.title || info.title || info.name,\n parameters: info.inputSchema ?? { type: 'object', properties: {} },\n confirm: shouldConfirm(info) ? () => `Allow ${info.annotations?.title ?? info.title ?? info.name} (${name})?` : false,\n run: (args, ctx) => client.callTool(info.name, (args ?? {}) as Record<string, unknown>, ctx.signal),\n }),\n )\n }\n\n return {\n name,\n client,\n refresh() {\n cache = undefined\n },\n tools(signal) {\n if (!cache || Date.now() - cache.at > ttl) {\n const entry = { at: Date.now(), tools: load(signal) }\n cache = entry\n entry.tools.catch(() => {\n if (cache === entry) cache = undefined\n })\n }\n return cache.tools\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,QAAQ,EAAE,QAAQ,OAAO,EAAE,SAAS,OAAU,CAAC,IACx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I,KAAK,IAAI,OAAO;AAAA,MAChH,KAAK,CAAC,MAAM,QAAQ,OAAO,SAAS,KAAK,MAAO,QAAQ,CAAC,GAA+B,IAAI,MAAM;AAAA,IACpG;AAAA,EACF;AAGJ,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,UAAU;AACR,cAAQ;AAAA,IACV;AAAA,IACA,MAAM,QAAQ;AACZ,UAAI,CAAC,SAAS,KAAK,IAAI,IAAI,MAAM,KAAK,KAAK;AACzC,YAAM,QAAQ,EAAE,IAAI,KAAK,IAAI,GAAG,OAAO,KAAK,MAAM,EAAE;AACpD,gBAAQ,OACR,MAAM,MAAM,MAAM,MAAM;AACtB,UAAI,UAAU,UAAO,QAAQ;AAAA,QAC/B,CAAC;AAAA,MACH;AACA,aAAO,MAAM;AAAA,IACf;AAAA,EACF;AACF;",
6
+ "names": []
7
+ }
@@ -0,0 +1,108 @@
1
+ // src/core/define.ts
2
+ function list(view) {
3
+ return { ...view, type: "list" };
4
+ }
5
+ function grid(view) {
6
+ return { ...view, type: "grid" };
7
+ }
8
+ function detail(view) {
9
+ return { ...view, type: "detail" };
10
+ }
11
+ function form(view) {
12
+ return { ...view, type: "form" };
13
+ }
14
+ function chat(view = {}) {
15
+ return { ...view, type: "chat" };
16
+ }
17
+ var action = {
18
+ /** Copy text to the clipboard. */
19
+ copy(content, options = {}) {
20
+ return {
21
+ title: "Copy to Clipboard",
22
+ labelKey: "copyToClipboard",
23
+ icon: "copy",
24
+ shortcut: "mod+c",
25
+ ...options,
26
+ async run(ctx) {
27
+ let ok = await ctx.copy(typeof content == "function" ? content() : content), l = ctx.labels;
28
+ ctx.toast({ title: ok ? l?.copied ?? "Copied to clipboard" : l?.copyFailed ?? "Copy failed", style: ok ? "success" : "failure" });
29
+ }
30
+ };
31
+ },
32
+ /** Open an external URL in a new tab. */
33
+ open(url, options = {}) {
34
+ return {
35
+ title: "Open in Browser",
36
+ labelKey: "openInBrowser",
37
+ icon: "external",
38
+ ...options,
39
+ run: (ctx) => ctx.openUrl(url)
40
+ };
41
+ },
42
+ /** Navigate within your app. */
43
+ navigate(href, options = {}) {
44
+ return {
45
+ title: "Open",
46
+ labelKey: "open",
47
+ icon: "arrow-right",
48
+ ...options,
49
+ run: (ctx) => ctx.navigate(href)
50
+ };
51
+ },
52
+ /** Navigate in a new tab. */
53
+ navigateNewTab(href, options = {}) {
54
+ return {
55
+ title: "Open in New Tab",
56
+ labelKey: "openInNewTab",
57
+ icon: "external",
58
+ shortcut: "mod+enter",
59
+ ...options,
60
+ run: (ctx) => ctx.navigate(href, { newTab: !0 })
61
+ };
62
+ },
63
+ /** Push a view. */
64
+ push(title, view, options = {}) {
65
+ return {
66
+ title,
67
+ icon: "chevron-right",
68
+ ...options,
69
+ run: (ctx) => typeof view == "function" ? view(ctx) : view
70
+ };
71
+ },
72
+ /** Ask the AI about something. */
73
+ ask(prompt, options = {}) {
74
+ return {
75
+ title: "Ask AI",
76
+ icon: "sparkles",
77
+ shortcut: "mod+j",
78
+ ...options,
79
+ run: () => ({ type: "chat", prompt })
80
+ };
81
+ }
82
+ };
83
+ function defineExtension(extension) {
84
+ return extension;
85
+ }
86
+ function defineCommands(commands) {
87
+ return commands;
88
+ }
89
+ function defineSource(source) {
90
+ return source;
91
+ }
92
+ function defineTool(tool) {
93
+ return tool;
94
+ }
95
+
96
+ export {
97
+ list,
98
+ grid,
99
+ detail,
100
+ form,
101
+ chat,
102
+ action,
103
+ defineExtension,
104
+ defineCommands,
105
+ defineSource,
106
+ defineTool
107
+ };
108
+ //# sourceMappingURL=chunk-INTEVQYK.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../src/core/define.ts"],
4
+ "sourcesContent": ["/**\n * Helpers for building views, actions and extensions.\n * They only add the `type` field and give you type inference \u2014 everything is plain data.\n */\n\nimport type {\n Action,\n ChatView,\n Command,\n Context,\n DetailView,\n Extension,\n FormView,\n GridView,\n ListView,\n Source,\n Tool,\n View,\n} from './types.js'\n\ntype Without<T, K extends keyof T> = Omit<T, K>\n\n/** A searchable list of items. */\nexport function list(view: Without<ListView, 'type'>): ListView {\n return { ...view, type: 'list' }\n}\n\n/** A grid of images. */\nexport function grid(view: Without<GridView, 'type'>): GridView {\n return { ...view, type: 'grid' }\n}\n\n/** A markdown document, optionally streamed. */\nexport function detail(view: Without<DetailView, 'type'>): DetailView {\n return { ...view, type: 'detail' }\n}\n\n/** A form. */\nexport function form(view: Without<FormView, 'type'>): FormView {\n return { ...view, type: 'form' }\n}\n\n/** An AI chat. */\nexport function chat(view: Without<ChatView, 'type'> = {}): ChatView {\n return { ...view, type: 'chat' }\n}\n\n/** Ready-made actions. */\nexport const action = {\n /** Copy text to the clipboard. */\n copy(content: string | (() => string), options: Partial<Action> = {}): Action {\n return {\n title: 'Copy to Clipboard',\n labelKey: 'copyToClipboard',\n icon: 'copy',\n shortcut: 'mod+c',\n ...options,\n async run(ctx: Context) {\n const ok = await ctx.copy(typeof content === 'function' ? content() : content)\n const l = ctx.labels\n ctx.toast({ title: ok ? (l?.copied ?? 'Copied to clipboard') : (l?.copyFailed ?? 'Copy failed'), style: ok ? 'success' : 'failure' })\n },\n }\n },\n /** Open an external URL in a new tab. */\n open(url: string, options: Partial<Action> = {}): Action {\n return {\n title: 'Open in Browser',\n labelKey: 'openInBrowser',\n icon: 'external',\n ...options,\n run: (ctx) => ctx.openUrl(url),\n }\n },\n /** Navigate within your app. */\n navigate(href: string, options: Partial<Action> = {}): Action {\n return {\n title: 'Open',\n labelKey: 'open',\n icon: 'arrow-right',\n ...options,\n run: (ctx) => ctx.navigate(href),\n }\n },\n /** Navigate in a new tab. */\n navigateNewTab(href: string, options: Partial<Action> = {}): Action {\n return {\n title: 'Open in New Tab',\n labelKey: 'openInNewTab',\n icon: 'external',\n shortcut: 'mod+enter',\n ...options,\n run: (ctx) => ctx.navigate(href, { newTab: true }),\n }\n },\n /** Push a view. */\n push(title: string, view: View | ((ctx: Context) => View | Promise<View>), options: Partial<Action> = {}): Action {\n return {\n title,\n icon: 'chevron-right',\n ...options,\n run: (ctx) => (typeof view === 'function' ? view(ctx) : view),\n }\n },\n /** Ask the AI about something. */\n ask(prompt: string, options: Partial<Action> = {}): Action {\n return {\n title: 'Ask AI',\n icon: 'sparkles',\n shortcut: 'mod+j',\n ...options,\n run: () => ({ type: 'chat', prompt }) satisfies ChatView,\n }\n },\n}\n\n/** Define an extension (identity function with type inference). */\nexport function defineExtension<T extends Extension>(extension: T): T {\n return extension\n}\n\n/** Define a set of commands. */\nexport function defineCommands<T extends Command[]>(commands: T): T {\n return commands\n}\n\n/** Define a search source. */\nexport function defineSource(source: Source): Source {\n return source\n}\n\n/** Define an AI tool. */\nexport function defineTool<Args = Record<string, unknown>>(tool: Tool<Args>): Tool<Args> {\n return tool\n}\n"],
5
+ "mappings": ";AAuBO,SAAS,KAAK,MAA2C;AAC9D,SAAO,EAAE,GAAG,MAAM,MAAM,OAAO;AACjC;AAGO,SAAS,KAAK,MAA2C;AAC9D,SAAO,EAAE,GAAG,MAAM,MAAM,OAAO;AACjC;AAGO,SAAS,OAAO,MAA+C;AACpE,SAAO,EAAE,GAAG,MAAM,MAAM,SAAS;AACnC;AAGO,SAAS,KAAK,MAA2C;AAC9D,SAAO,EAAE,GAAG,MAAM,MAAM,OAAO;AACjC;AAGO,SAAS,KAAK,OAAkC,CAAC,GAAa;AACnE,SAAO,EAAE,GAAG,MAAM,MAAM,OAAO;AACjC;AAGO,IAAM,SAAS;AAAA;AAAA,EAEpB,KAAK,SAAkC,UAA2B,CAAC,GAAW;AAC5E,WAAO;AAAA,MACL,OAAO;AAAA,MACP,UAAU;AAAA,MACV,MAAM;AAAA,MACN,UAAU;AAAA,MACV,GAAG;AAAA,MACH,MAAM,IAAI,KAAc;AACtB,YAAM,KAAK,MAAM,IAAI,KAAK,OAAO,WAAY,aAAa,QAAQ,IAAI,OAAO,GACvE,IAAI,IAAI;AACd,YAAI,MAAM,EAAE,OAAO,KAAM,GAAG,UAAU,wBAA0B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