@kevinwang15/byok-ai 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +10 -0
  2. package/dist/lib/AskAI.js +383 -0
  3. package/dist/lib/AskAIHistory.js +120 -0
  4. package/dist/lib/AskAIProvider.js +255 -0
  5. package/dist/lib/Markdown.js +111 -0
  6. package/dist/lib/PageElements.js +127 -0
  7. package/dist/lib/agent.js +223 -0
  8. package/dist/lib/answer-components.js +49 -0
  9. package/dist/lib/connection.d.ts +15 -0
  10. package/dist/lib/connection.js +32 -0
  11. package/dist/lib/context.js +9 -0
  12. package/dist/lib/conversation-files.js +164 -0
  13. package/dist/lib/entries/agent.d.ts +9 -0
  14. package/dist/lib/entries/agent.js +5 -0
  15. package/dist/lib/entries/connection.d.ts +2 -0
  16. package/dist/lib/entries/connection.js +1 -0
  17. package/dist/lib/entries/script-engine.d.ts +3 -0
  18. package/dist/lib/entries/script-engine.js +5 -0
  19. package/dist/lib/history.js +16 -0
  20. package/dist/lib/images.js +79 -0
  21. package/dist/lib/index.d.ts +6 -2
  22. package/dist/lib/index.js +18 -2326
  23. package/dist/lib/local-storage.d.ts +8 -0
  24. package/dist/lib/local-storage.js +23 -0
  25. package/dist/lib/mcp-result.js +11 -0
  26. package/dist/lib/mount.js +9 -0
  27. package/dist/lib/node_modules/@jitl/quickjs-ffi-types/dist/index.js +46 -0
  28. package/dist/lib/node_modules/@jitl/quickjs-wasmfile-release-sync/dist/emscripten-module.browser.js +330 -0
  29. package/dist/lib/node_modules/@jitl/quickjs-wasmfile-release-sync/dist/ffi.js +76 -0
  30. package/dist/lib/node_modules/@jitl/quickjs-wasmfile-release-sync/dist/index.js +7 -0
  31. package/dist/lib/node_modules/quickjs-emscripten-core/dist/chunk-V2S4ZYJR.js +1142 -0
  32. package/dist/lib/node_modules/quickjs-emscripten-core/dist/index.js +21 -0
  33. package/dist/lib/node_modules/quickjs-emscripten-core/dist/module-ES6BEMUI.js +1 -0
  34. package/dist/lib/page-context.js +168 -0
  35. package/dist/lib/page-picker.js +119 -0
  36. package/dist/lib/providers.js +84 -0
  37. package/dist/lib/rendering-context.js +4 -0
  38. package/dist/lib/sandbox.js +102 -0
  39. package/dist/lib/script-runner.js +26 -0
  40. package/dist/lib/script.js +9 -0
  41. package/dist/lib/storage.d.ts +0 -13
  42. package/dist/lib/storage.js +67 -0
  43. package/dist/lib/useAskAIImage.js +26 -0
  44. package/dist/lib/usePanelLayout.js +168 -0
  45. package/dist/lib/workspace-tools.js +182 -0
  46. package/package.json +14 -1
  47. /package/dist/lib/{sandbox-worker-BdFlhTIS.js → sandbox-worker.js} +0 -0
@@ -0,0 +1,223 @@
1
+ import { isImageAttachment as e } from "./images.js";
2
+ import { WORKSPACE_ID as t, workspaceTools as n } from "./workspace-tools.js";
3
+ import { PAGE_CONTEXT_ID as r, isPageElementAttachment as i, pageContextTools as a, pageElementsIn as o, pageElementsNote as s } from "./page-context.js";
4
+ import { ToolChoiceViolationError as c, stepCountIs as l, streamText as u } from "ai";
5
+ import { createMCPClient as d } from "@ai-sdk/mcp";
6
+ // frontend/byok/agent.ts
7
+ var f = {
8
+ unsupported: "The user attached an image here, but this model does not accept images.",
9
+ missing: "The user attached an image here that is no longer stored in this browser."
10
+ };
11
+ async function p(t, n = {}) {
12
+ let { images: r } = n, a = [];
13
+ for (let o of t) if (o.role !== "assistant") {
14
+ let t = o.role === "user" ? o.attachments : [], c = t.filter(i), l = [...o.content.flatMap((e) => e.type === "text" ? [e.text] : []), ...c.length ? [s(c, n.pageElements === !0)] : []].join("\n"), u = t.filter(e);
15
+ if (o.role === "system" || !u.length) {
16
+ a.push({
17
+ role: o.role,
18
+ content: l
19
+ });
20
+ continue;
21
+ }
22
+ let d = l ? [{
23
+ type: "text",
24
+ text: l
25
+ }] : [];
26
+ for (let e of u) {
27
+ let t = r?.accepted ? await r.store.load(e.id).catch(() => void 0) : void 0;
28
+ t ? d.push({
29
+ type: "image",
30
+ image: new Uint8Array(await t.arrayBuffer()),
31
+ mediaType: e.contentType
32
+ }) : d.push({
33
+ type: "text",
34
+ text: r?.accepted ? f.missing : f.unsupported
35
+ });
36
+ }
37
+ a.push({
38
+ role: "user",
39
+ content: d
40
+ });
41
+ } else for (let e of o.content) e.type === "text" && a.push({
42
+ role: "assistant",
43
+ content: e.text
44
+ }), e.type === "tool-call" && (a.push({
45
+ role: "assistant",
46
+ content: [{
47
+ type: "tool-call",
48
+ toolCallId: e.toolCallId,
49
+ toolName: e.toolName,
50
+ input: e.args
51
+ }]
52
+ }), a.push({
53
+ role: "tool",
54
+ content: [{
55
+ type: "tool-result",
56
+ toolCallId: e.toolCallId,
57
+ toolName: e.toolName,
58
+ output: {
59
+ type: "text",
60
+ value: e.result === void 0 ? "Tool execution was interrupted. No result is available." : typeof e.result == "string" ? e.result : JSON.stringify(e.result)
61
+ }
62
+ }]
63
+ }));
64
+ return a;
65
+ }
66
+ var m = "No more tool calls are available for this answer. Answer now from the results you have, and say briefly what you could not check.", h = {
67
+ length: "The answer stopped at the model's output limit. Ask it to continue.",
68
+ steps: "The assistant used all its steps before finishing. Ask it to continue, or narrow the question.",
69
+ empty: "The model finished without writing an answer. Try again."
70
+ }, g = "The connection was interrupted. Try again.", _ = "Could not complete the response. Check your key, model, provider CORS support, and MCP connection, then try again.", v = (e) => e instanceof TypeError || typeof navigator < "u" && navigator.onLine === !1;
71
+ function y(e) {
72
+ for (let t = e.length - 1; t >= 0; t--) if (e[t].type === "tool-call") return t;
73
+ return -1;
74
+ }
75
+ function b(e) {
76
+ return { async *run({ messages: i, abortSignal: s }) {
77
+ e.onError("");
78
+ let f = [], b = [], x = () => {
79
+ for (let e of f) e.close().catch(() => {});
80
+ };
81
+ s.addEventListener("abort", x, { once: !0 });
82
+ try {
83
+ s.throwIfAborted();
84
+ let g = {};
85
+ for (let [t, n] of Object.entries(e.clientTools?.() ?? {})) {
86
+ if (!/^[a-zA-Z0-9_-]+$/.test(t) || t.includes("__")) throw Error("Client tool names must contain only letters, numbers, underscores or hyphens, and no \"__\".");
87
+ g[t] = {
88
+ ...n,
89
+ execute: async (n, r) => {
90
+ let i = e.clientTools?.()[t]?.execute;
91
+ if (!i) throw Error(`The page no longer offers ${t}.`);
92
+ return i(n, r);
93
+ }
94
+ };
95
+ }
96
+ let _ = /* @__PURE__ */ new Set();
97
+ for (let n of e.servers) {
98
+ if (s.throwIfAborted(), !/^[a-zA-Z0-9_-]+$/.test(n.id)) throw Error("MCP IDs must contain only letters, numbers, underscores or hyphens.");
99
+ if (e.workspace && n.id === "workspace") throw Error(`The MCP id "${t}" is taken by the workspace tools.`);
100
+ if (e.pageElements && n.id === "page") throw Error(`The MCP id "${r}" is taken by the page context tools.`);
101
+ let i = await d({ transport: {
102
+ type: "http",
103
+ url: new URL(n.url, window.location.href).href,
104
+ fetch: (e, t) => fetch(e, {
105
+ ...t,
106
+ signal: AbortSignal.any([
107
+ s,
108
+ AbortSignal.timeout(6e4),
109
+ ...t?.signal ? [t.signal] : []
110
+ ])
111
+ }),
112
+ headers: typeof n.headers == "function" ? await n.headers() : n.headers
113
+ } });
114
+ f.push(i), s.throwIfAborted();
115
+ let a = await i.tools();
116
+ for (let [e, t] of Object.entries(a)) {
117
+ let r = n.id + "__" + e;
118
+ if (g[r]) throw Error("Duplicate MCP tool: " + r);
119
+ g[r] = t, _.add(r);
120
+ }
121
+ }
122
+ if (e.workspace) {
123
+ let { open: t, run: r } = e.workspace, i;
124
+ Object.assign(g, n({
125
+ workspace: () => i ??= t(),
126
+ run: r,
127
+ tools: () => g,
128
+ isMcp: (e) => _.has(e)
129
+ }));
130
+ }
131
+ e.pageElements && Object.assign(g, a({
132
+ registry: e.pageElements,
133
+ elements: o(i),
134
+ tools: () => g,
135
+ isMcp: (e) => _.has(e),
136
+ canSave: e.workspace !== void 0
137
+ }));
138
+ let v = e.provider.createModel(e.values), x = await p(i, {
139
+ images: e.images && {
140
+ store: e.images,
141
+ accepted: e.provider.acceptsImages === !0
142
+ },
143
+ pageElements: e.pageElements !== void 0
144
+ }), S = [e.systemPrompt, m].filter(Boolean).join("\n\n"), C = async function* (e) {
145
+ for await (let t of e.fullStream) {
146
+ if (t.type === "error" && c.isInstance(t.error)) return "tool-calls";
147
+ if (t.type === "error") throw t.error;
148
+ if (t.type === "finish") return t.finishReason;
149
+ if (t.type === "text-delta") {
150
+ let e = b.at(-1);
151
+ e?.type === "text" ? b[b.length - 1] = {
152
+ type: "text",
153
+ text: e.text + t.text
154
+ } : b.push({
155
+ type: "text",
156
+ text: t.text
157
+ });
158
+ } else if (t.type === "tool-call") b.push({
159
+ type: "tool-call",
160
+ toolCallId: t.toolCallId,
161
+ toolName: t.toolName,
162
+ args: t.input,
163
+ argsText: JSON.stringify(t.input)
164
+ });
165
+ else if (t.type === "tool-result" || t.type === "tool-error") {
166
+ let e = b.findIndex((e) => e.type === "tool-call" && e.toolCallId === t.toolCallId), n = b[e];
167
+ n?.type === "tool-call" && (b[e] = {
168
+ ...n,
169
+ result: t.type === "tool-result" ? t.output : { error: String(t.error) },
170
+ isError: t.type === "tool-error"
171
+ });
172
+ }
173
+ yield { content: [...b] };
174
+ }
175
+ return void 0;
176
+ }, w = () => b.slice(y(b) + 1).some((e) => e.type === "text" && e.text.trim()), T = u({
177
+ model: v,
178
+ system: e.systemPrompt,
179
+ messages: x,
180
+ tools: g,
181
+ stopWhen: l(e.maxSteps),
182
+ abortSignal: s,
183
+ maxRetries: 0,
184
+ onError: () => {},
185
+ prepareStep: ({ steps: t, stepNumber: n }) => {
186
+ let r = t.reduce((e, t) => e + t.toolCalls.length, 0);
187
+ if (!(!(e.maxToolCalls !== void 0 && r >= e.maxToolCalls) && n < e.maxSteps - 1)) return {
188
+ toolChoice: "none",
189
+ instructions: S
190
+ };
191
+ },
192
+ ...e.maxOutputTokens ? { maxOutputTokens: e.maxOutputTokens } : {}
193
+ }), E = yield* C(T);
194
+ if (E === "stop" && !w()) {
195
+ let t = (await T.steps).slice(0, -1).flatMap((e) => e.response.messages);
196
+ E = yield* C(u({
197
+ model: v,
198
+ system: S,
199
+ messages: [
200
+ ...x,
201
+ ...t,
202
+ {
203
+ role: "user",
204
+ content: m
205
+ }
206
+ ],
207
+ tools: g,
208
+ toolChoice: "none",
209
+ abortSignal: s,
210
+ maxRetries: 0,
211
+ onError: () => {},
212
+ ...e.maxOutputTokens ? { maxOutputTokens: e.maxOutputTokens } : {}
213
+ }));
214
+ }
215
+ E === "length" ? e.onError(h.length) : E === "tool-calls" ? e.onError(h.steps) : w() || e.onError(h.empty);
216
+ } catch (t) {
217
+ if (!s.aborted) throw e.onError(v(t) ? g : _), Error("Provider or MCP request failed.");
218
+ } finally {
219
+ s.removeEventListener("abort", x), await Promise.allSettled(f.map((e) => e.close()));
220
+ }
221
+ } };
222
+ }
223
+ export { g as CONNECTION_LOST_MESSAGE, m as FINAL_STEP_INSTRUCTION, f as IMAGE_NOTES, h as INCOMPLETE_MESSAGES, b as createBrowserAdapter, p as toModelMessages };
@@ -0,0 +1,49 @@
1
+ // frontend/byok/answer-components.ts
2
+ var e = (e) => e, t = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
3
+ function n(e) {
4
+ let n = /* @__PURE__ */ new Set();
5
+ for (let { name: r } of e) {
6
+ if (!t.test(r) || r.length > 100) throw Error(`Answer component names are lower-case kebab case, up to 100 characters: "${r}"`);
7
+ if (n.has(r)) throw Error(`Two answer components are named "${r}"`);
8
+ n.add(r);
9
+ }
10
+ }
11
+ function r(e) {
12
+ return e.length === 0 ? "" : `# Components in answers
13
+ Besides Markdown, an answer can show these components. Write one as a fenced block: three backticks and "component:" with its name, then its props as one JSON object, then three backticks.
14
+ - Use one only where it shows something better than text would, next to the text it supports; never only to decorate.
15
+ - Fill its props with values you have (from tool results, or what the user gave); never invent data to fill one.
16
+ - The props must match the component's schema exactly, as strict JSON: no comments, no trailing commas.
17
+ - Only the components listed here exist.
18
+
19
+ ${e.map((e) => [
20
+ `## ${e.name}`,
21
+ e.description,
22
+ `Props (JSON Schema): ${JSON.stringify(e.schema)}`,
23
+ `Example:\n${i(e.name, e.example)}`
24
+ ].join("\n")).join("\n\n")}`;
25
+ }
26
+ var i = (e, t) => "```component:" + e + "\n" + JSON.stringify(t) + "\n```";
27
+ function a(e) {
28
+ let t = null, n = 0;
29
+ for (let r of e.split("\n")) {
30
+ let e = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(r);
31
+ if (e) {
32
+ let [, r, i] = e;
33
+ t ? r[0] === t.marker[0] && r.length >= t.marker.length && !i.trim() && (t = null) : r[0] === "`" && i.includes("`") || (t = {
34
+ at: n,
35
+ marker: r,
36
+ name: /^\s*component:([a-z0-9-]+)\s*$/.exec(i)?.[1] ?? null
37
+ });
38
+ }
39
+ n += r.length + 1;
40
+ }
41
+ return t?.name ? {
42
+ shown: e.slice(0, t.at).trimEnd(),
43
+ pending: t.name
44
+ } : {
45
+ shown: e,
46
+ pending: null
47
+ };
48
+ }
49
+ export { r as answerComponentInstructions, n as checkAnswerComponents, e as defineAnswerComponent, a as splitOpenComponent };
@@ -0,0 +1,15 @@
1
+ import type { ProviderValues } from './types';
2
+ export interface StoredConnection {
3
+ providerId: string;
4
+ values: ProviderValues;
5
+ }
6
+ /** The connection key an assistant uses when it is given none. */
7
+ export declare const defaultConnectionKey: (storageKey: string) => string;
8
+ /** The saved connection, or undefined when there is none or it has another shape. */
9
+ export declare function loadConnection(key: string): StoredConnection | undefined;
10
+ /** Saves the connection, or removes it when `connection` is undefined, and tells the others. */
11
+ export declare function saveConnection(key: string, connection: StoredConnection | undefined): boolean;
12
+ /** Calls `listener` after the connection under `key` may have changed. Returns the unsubscribe. */
13
+ export declare function subscribeConnection(key: string, listener: () => void): () => void;
14
+ /** Whether two saved connections are the same provider with the same values. */
15
+ export declare function sameConnection(a: StoredConnection | undefined, b: StoredConnection | undefined): boolean;
@@ -0,0 +1,32 @@
1
+ import { isRecord as e, readStored as t, writeStored as n } from "./local-storage.js";
2
+ // frontend/byok/connection.ts
3
+ var r = (e) => `${e}:connection`;
4
+ function i(n) {
5
+ let { value: r } = t(n);
6
+ if (e(r) && typeof r.providerId == "string" && e(r.values) && Object.values(r.values).every((e) => typeof e == "string")) return {
7
+ providerId: r.providerId,
8
+ values: r.values
9
+ };
10
+ }
11
+ function a(e, t) {
12
+ let r = n(e, t);
13
+ for (let t of o.get(e) ?? []) t();
14
+ return r;
15
+ }
16
+ var o = /* @__PURE__ */ new Map();
17
+ function s(e, t) {
18
+ let n = o.get(e) ?? /* @__PURE__ */ new Set();
19
+ n.add(t), o.set(e, n);
20
+ let r = (n) => {
21
+ (n.key === e || n.key === null) && t();
22
+ };
23
+ return window.addEventListener("storage", r), () => {
24
+ n.delete(t), n.size || o.delete(e), window.removeEventListener("storage", r);
25
+ };
26
+ }
27
+ function c(e, t) {
28
+ if (!e || !t) return e === t;
29
+ let n = Object.keys(e.values);
30
+ return e.providerId === t.providerId && n.length === Object.keys(t.values).length && n.every((n) => e.values[n] === t.values[n]);
31
+ }
32
+ export { r as defaultConnectionKey, i as loadConnection, c as sameConnection, a as saveConnection, s as subscribeConnection };
@@ -0,0 +1,9 @@
1
+ import { createContext as e, useContext as t } from "react";
2
+ // frontend/byok/context.ts
3
+ var n = e(null), r = () => t(n);
4
+ function i() {
5
+ let e = t(n);
6
+ if (!e) throw Error("useAskAI must be used inside AskAIProvider or AskAI.");
7
+ return e;
8
+ }
9
+ export { n as AskAIContext, i as useAskAI, r as useAskAIOptional };
@@ -0,0 +1,164 @@
1
+ // frontend/byok/conversation-files.ts
2
+ var e = {
3
+ fileBytes: 8388608,
4
+ totalBytes: 67108864,
5
+ files: 200
6
+ }, t = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
7
+ function n(e) {
8
+ if (!t.test(e) || e.includes("..")) return "A file name is 1 to 128 letters, digits, \".\", \"-\" or \"_\", starting with a letter or digit, without \"..\".";
9
+ }
10
+ function r(e) {
11
+ let t = n(e);
12
+ if (t) throw Error(t);
13
+ }
14
+ var i = (e) => /^[a-f0-9]{32}$/.test(e);
15
+ function a(e) {
16
+ if (!i(e)) throw Error("Not an image id.");
17
+ }
18
+ var o = (e) => new TextEncoder().encode(e).length;
19
+ function s(t, n, r) {
20
+ let i = o(r);
21
+ if (i > e.fileBytes) return `A file can hold at most ${e.fileBytes} bytes; this one would be ${i}.`;
22
+ let a = t.filter((e) => e.name !== n);
23
+ if (a.length + 1 > e.files) return `A workspace holds at most ${e.files} files. Delete some first.`;
24
+ let s = a.reduce((e, t) => e + t.size, i);
25
+ if (s > e.totalBytes) return `A workspace holds at most ${e.totalBytes} bytes; it would hold ${s}. Delete some files first.`;
26
+ }
27
+ function c() {
28
+ let e = /* @__PURE__ */ new Map(), t = (t) => e.get(t) ?? e.set(t, {
29
+ files: /* @__PURE__ */ new Map(),
30
+ images: /* @__PURE__ */ new Map()
31
+ }).get(t);
32
+ return {
33
+ workspace: (e) => ({
34
+ async list() {
35
+ return [...t(e).files].map(([e, t]) => ({
36
+ name: e,
37
+ size: o(t.text),
38
+ modifiedAt: t.modifiedAt
39
+ })).sort((e, t) => e.name.localeCompare(t.name));
40
+ },
41
+ async read(n) {
42
+ return r(n), t(e).files.get(n)?.text;
43
+ },
44
+ async write(n, i) {
45
+ r(n);
46
+ let a = s(await this.list(), n, i);
47
+ if (a) throw Error(a);
48
+ t(e).files.set(n, {
49
+ text: i,
50
+ modifiedAt: Date.now()
51
+ });
52
+ },
53
+ async remove(n) {
54
+ return r(n), t(e).files.delete(n);
55
+ }
56
+ }),
57
+ images: (e) => ({
58
+ async save(n, r) {
59
+ a(n), t(e).images.set(n, r);
60
+ },
61
+ async load(n) {
62
+ return a(n), t(e).images.get(n);
63
+ }
64
+ }),
65
+ async remove(t) {
66
+ e.delete(t);
67
+ }
68
+ };
69
+ }
70
+ var l = "This browser does not offer private file storage here, so files and images cannot be kept.", u = () => typeof navigator < "u" && typeof navigator.storage?.getDirectory == "function", d = "The browser has no more storage for this site.", f = (e) => e.replace(/[^A-Za-z0-9_-]/g, (e) => "%" + e.charCodeAt(0).toString(16).padStart(2, "0")), p = (e) => e instanceof DOMException && e.name === "NotFoundError";
71
+ async function m(e, t) {
72
+ if (typeof navigator > "u" || !navigator.storage?.getDirectory) throw Error(l);
73
+ let n;
74
+ try {
75
+ n = await navigator.storage.getDirectory();
76
+ } catch {
77
+ throw Error(l);
78
+ }
79
+ try {
80
+ return await n.getDirectoryHandle(f(e), { create: t });
81
+ } catch (e) {
82
+ if (!t && p(e)) return;
83
+ throw e;
84
+ }
85
+ }
86
+ async function h(e, t) {
87
+ let n = await e.createWritable();
88
+ try {
89
+ await n.write(t), await n.close();
90
+ } catch (e) {
91
+ throw await n.abort().catch(() => {}), e instanceof DOMException && e.name === "QuotaExceededError" ? /* @__PURE__ */ Error(d) : e;
92
+ }
93
+ }
94
+ function g(e) {
95
+ let t = async (t, n, r) => {
96
+ let i = await m(e, r);
97
+ if (i) try {
98
+ return await (await i.getDirectoryHandle(f(t), { create: r })).getDirectoryHandle(n, { create: r });
99
+ } catch (e) {
100
+ if (!r && p(e)) return;
101
+ throw e;
102
+ }
103
+ }, i = async (e, t) => {
104
+ if (e) try {
105
+ return await (await e.getFileHandle(t)).getFile();
106
+ } catch (e) {
107
+ if (p(e)) return;
108
+ throw e;
109
+ }
110
+ };
111
+ return {
112
+ workspace: (e) => ({
113
+ async list() {
114
+ let r = await t(e, "files", !1);
115
+ if (!r) return [];
116
+ let i = [];
117
+ for await (let e of r.values()) {
118
+ if (e.kind !== "file" || n(e.name)) continue;
119
+ let t = await e.getFile();
120
+ i.push({
121
+ name: e.name,
122
+ size: t.size,
123
+ modifiedAt: t.lastModified
124
+ });
125
+ }
126
+ return i.sort((e, t) => e.name.localeCompare(t.name));
127
+ },
128
+ async read(n) {
129
+ return r(n), (await i(await t(e, "files", !1), n))?.text();
130
+ },
131
+ async write(n, i) {
132
+ r(n);
133
+ let a = s(await this.list(), n, i);
134
+ if (a) throw Error(a);
135
+ await h(await (await t(e, "files", !0)).getFileHandle(n, { create: !0 }), i);
136
+ },
137
+ async remove(n) {
138
+ r(n);
139
+ let i = await t(e, "files", !1);
140
+ if (!i) return !1;
141
+ try {
142
+ return await i.removeEntry(n), !0;
143
+ } catch (e) {
144
+ if (p(e)) return !1;
145
+ throw e;
146
+ }
147
+ }
148
+ }),
149
+ images: (e) => ({
150
+ async save(n, r) {
151
+ a(n), await h(await (await t(e, "images", !0)).getFileHandle(n, { create: !0 }), r);
152
+ },
153
+ async load(n) {
154
+ return a(n), i(await t(e, "images", !1), n);
155
+ }
156
+ }),
157
+ async remove(t) {
158
+ await (await m(e, !1).catch(() => void 0))?.removeEntry(f(t), { recursive: !0 }).catch((e) => {
159
+ if (!p(e)) throw e;
160
+ });
161
+ }
162
+ };
163
+ }
164
+ export { e as WORKSPACE_LIMITS, u as browserFilesAvailable, o as byteLength, n as fileNameProblem, i as isImageId, c as memoryConversationFiles, g as opfsConversationFiles, s as writeProblem };
@@ -0,0 +1,9 @@
1
+ export { createBrowserAdapter } from '../agent';
2
+ export { answerComponentInstructions } from '../answer-components';
3
+ export { memoryConversationFiles, WORKSPACE_LIMITS } from '../conversation-files';
4
+ export { SCRIPT_LIMITS } from '../script';
5
+ export type { AnswerComponent } from '../answer-components';
6
+ export type { ConversationFiles, ImageStore, Workspace, WorkspaceFile } from '../conversation-files';
7
+ export type { ScriptRequest, ScriptResult } from '../script';
8
+ export type { ScriptRunner } from '../script-runner';
9
+ export type { McpServerConfig, ProviderPreset, ProviderValues } from '../types';
@@ -0,0 +1,5 @@
1
+ import { createBrowserAdapter as e } from "../agent.js";
2
+ import { answerComponentInstructions as t } from "../answer-components.js";
3
+ import { WORKSPACE_LIMITS as n, memoryConversationFiles as r } from "../conversation-files.js";
4
+ import { SCRIPT_LIMITS as i } from "../script.js";
5
+ export { i as SCRIPT_LIMITS, n as WORKSPACE_LIMITS, t as answerComponentInstructions, e as createBrowserAdapter, r as memoryConversationFiles };
@@ -0,0 +1,2 @@
1
+ export { defaultConnectionKey, loadConnection, sameConnection, subscribeConnection } from '../connection';
2
+ export type { StoredConnection } from '../connection';
@@ -0,0 +1 @@
1
+ export { defaultConnectionKey, loadConnection, sameConnection, subscribeConnection } from "../connection.js";
@@ -0,0 +1,3 @@
1
+ import type { ScriptRunner } from '../script-runner';
2
+ /** Runs a workspace script in this thread, in the same sandbox the page's worker uses. */
3
+ export declare const inProcessScriptRunner: ScriptRunner;
@@ -0,0 +1,5 @@
1
+ import e from "../node_modules/@jitl/quickjs-wasmfile-release-sync/dist/index.js";
2
+ import { runScript as t } from "../sandbox.js";
3
+ // frontend/byok/entries/script-engine.ts
4
+ var n = (n) => t(e, n);
5
+ export { n as inProcessScriptRunner };
@@ -0,0 +1,16 @@
1
+ // frontend/byok/history.ts
2
+ function e(e, t) {
3
+ let n = Math.max(0, (t - e) / 1e3);
4
+ if (n < 60) return "Just now";
5
+ let r = new Intl.RelativeTimeFormat("en", { numeric: "always" });
6
+ return n < 3600 ? r.format(-Math.floor(n / 60), "minute") : n < 86400 ? r.format(-Math.floor(n / 3600), "hour") : n < 604800 ? r.format(-Math.floor(n / 86400), "day") : n < 2592e3 ? r.format(-Math.floor(n / 604800), "week") : n < 31536e3 ? r.format(-Math.floor(n / 2592e3), "month") : r.format(-Math.floor(n / 31536e3), "year");
7
+ }
8
+ function t(e) {
9
+ if (e.draft.trim()) return "Draft: " + e.draft.trim();
10
+ for (let t of [...e.messages].reverse()) {
11
+ let e = t.content.flatMap((e) => e.type === "text" ? [e.text] : []).join(" ").trim();
12
+ if (e) return e.replace(/\s+/g, " ").slice(0, 180);
13
+ }
14
+ return "No messages yet";
15
+ }
16
+ export { t as conversationPreview, e as relativeConversationTime };
@@ -0,0 +1,79 @@
1
+ // frontend/byok/images.ts
2
+ var e = {
3
+ perMessage: 4,
4
+ inputBytes: 20971520,
5
+ longEdge: 1568,
6
+ bytes: 3932160
7
+ }, t = [
8
+ "image/png",
9
+ "image/jpeg",
10
+ "image/webp"
11
+ ], n = "image/png,image/jpeg,image/webp,image/gif,image/bmp,image/avif", r = () => Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)), (e) => e.toString(16).padStart(2, "0")).join(""), i = (e) => e.type === "image" && typeof e.contentType == "string";
12
+ async function a(n) {
13
+ if (n.size > e.inputBytes) throw Error(`"${n.name}" is larger than ${e.inputBytes / 1024 / 1024} MB.`);
14
+ let r;
15
+ try {
16
+ r = await createImageBitmap(n);
17
+ } catch {
18
+ throw Error(`"${n.name}" could not be read as an image.`);
19
+ }
20
+ try {
21
+ let i = Math.min(1, e.longEdge / Math.max(r.width, r.height));
22
+ if (i === 1 && t.includes(n.type) && n.size <= e.bytes) return n;
23
+ let a = Math.max(1, Math.round(r.width * i)), o = Math.max(1, Math.round(r.height * i)), s = new OffscreenCanvas(a, o), c = s.getContext("2d"), l = n.type === "image/png";
24
+ l || (c.fillStyle = "#fff", c.fillRect(0, 0, a, o)), c.drawImage(r, 0, 0, a, o);
25
+ let u = await s.convertToBlob({
26
+ type: l ? "image/png" : "image/jpeg",
27
+ quality: .9
28
+ });
29
+ return u.size <= e.bytes ? u : (c.globalCompositeOperation = "destination-over", c.fillStyle = "#fff", c.fillRect(0, 0, a, o), await s.convertToBlob({
30
+ type: "image/jpeg",
31
+ quality: .85
32
+ }));
33
+ } finally {
34
+ r.close();
35
+ }
36
+ }
37
+ var o = {
38
+ "image/png": "png",
39
+ "image/jpeg": "jpg",
40
+ "image/webp": "webp"
41
+ };
42
+ function s(t) {
43
+ let i = t.prepare ?? a, s = 0;
44
+ return {
45
+ accept: n,
46
+ async add({ file: n }) {
47
+ if (t.attached() + s >= e.perMessage) throw Error(`A message can hold at most ${e.perMessage} images.`);
48
+ s++;
49
+ try {
50
+ let e = await i(n), t = e === n ? n.name : n.name.replace(/\.[^.]*$/, "") + "." + (o[e.type] ?? "img"), a = new File([e], t, { type: e.type });
51
+ return {
52
+ id: r(),
53
+ type: "image",
54
+ name: t,
55
+ contentType: e.type,
56
+ file: a,
57
+ status: {
58
+ type: "requires-action",
59
+ reason: "composer-send"
60
+ }
61
+ };
62
+ } finally {
63
+ s--;
64
+ }
65
+ },
66
+ async remove() {},
67
+ async send(e) {
68
+ return await t.images().save(e.id, e.file), {
69
+ id: e.id,
70
+ type: "image",
71
+ name: e.name,
72
+ contentType: e.contentType,
73
+ status: { type: "complete" },
74
+ content: []
75
+ };
76
+ }
77
+ };
78
+ }
79
+ export { e as IMAGE_LIMITS, s as imageAttachmentAdapter, i as isImageAttachment, a as prepareImage };
@@ -9,9 +9,13 @@ export { createBrowserAdapter } from './agent';
9
9
  export { defaultProviders } from './providers';
10
10
  export type { AskAIOptions, AskAIProps, AskAIChatProps, AskAIProviderProps, ProviderPreset, ProviderFormProps, ProviderValues, McpServerConfig } from './types';
11
11
  export type { Conversation } from './storage';
12
- export { WORKSPACE_LIMITS, browserFilesAvailable } from './conversation-files';
13
- export type { Workspace, WorkspaceFile } from './conversation-files';
12
+ export { WORKSPACE_LIMITS, browserFilesAvailable, memoryConversationFiles } from './conversation-files';
13
+ export type { ConversationFiles, ImageStore, Workspace, WorkspaceFile } from './conversation-files';
14
+ export { defaultConnectionKey, loadConnection, sameConnection, subscribeConnection } from './connection';
15
+ export type { StoredConnection } from './connection';
14
16
  export { SCRIPT_LIMITS } from './script';
17
+ export type { ScriptRequest, ScriptResult } from './script';
18
+ export type { ScriptRunner } from './script-runner';
15
19
  export { IMAGE_LIMITS } from './images';
16
20
  export { mountAskAI } from './mount';
17
21
  export { Markdown, MarkdownText } from './Markdown';