@kevinwang15/byok-ai 0.1.0 → 0.1.2

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 (48) hide show
  1. package/README.md +21 -2
  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.d.ts +4 -1
  26. package/dist/lib/mcp-result.js +18 -0
  27. package/dist/lib/mount.js +9 -0
  28. package/dist/lib/node_modules/@jitl/quickjs-ffi-types/dist/index.js +46 -0
  29. package/dist/lib/node_modules/@jitl/quickjs-wasmfile-release-sync/dist/emscripten-module.browser.js +330 -0
  30. package/dist/lib/node_modules/@jitl/quickjs-wasmfile-release-sync/dist/ffi.js +76 -0
  31. package/dist/lib/node_modules/@jitl/quickjs-wasmfile-release-sync/dist/index.js +7 -0
  32. package/dist/lib/node_modules/quickjs-emscripten-core/dist/chunk-V2S4ZYJR.js +1142 -0
  33. package/dist/lib/node_modules/quickjs-emscripten-core/dist/index.js +21 -0
  34. package/dist/lib/node_modules/quickjs-emscripten-core/dist/module-ES6BEMUI.js +1 -0
  35. package/dist/lib/page-context.js +185 -0
  36. package/dist/lib/page-picker.js +119 -0
  37. package/dist/lib/providers.js +84 -0
  38. package/dist/lib/rendering-context.js +4 -0
  39. package/dist/lib/sandbox.js +102 -0
  40. package/dist/lib/script-runner.js +26 -0
  41. package/dist/lib/script.js +9 -0
  42. package/dist/lib/storage.d.ts +0 -13
  43. package/dist/lib/storage.js +67 -0
  44. package/dist/lib/useAskAIImage.js +26 -0
  45. package/dist/lib/usePanelLayout.js +168 -0
  46. package/dist/lib/workspace-tools.js +182 -0
  47. package/package.json +14 -1
  48. /package/dist/lib/{sandbox-worker-BdFlhTIS.js → sandbox-worker.js} +0 -0
@@ -0,0 +1,21 @@
1
+ import { EvalFlags as e, GetOwnPropertyNamesFlags as t, IntrinsicsFlags as n, IsEqualOp as r, JSPromiseStateEnum as i } from "../../@jitl/quickjs-ffi-types/dist/index.js";
2
+ import "./chunk-V2S4ZYJR.js";
3
+ // node_modules/quickjs-emscripten-core/dist/index.mjs
4
+ async function a(e) {
5
+ let t = o(await e), [n, r, { QuickJSWASMModule: i }] = await Promise.all([
6
+ t.importModuleLoader().then(o),
7
+ t.importFFI(),
8
+ import("./module-ES6BEMUI.js").then(o)
9
+ ]), a = await n();
10
+ return a.type = "sync", new i(a, new r(a));
11
+ }
12
+ function o(e) {
13
+ return e && "default" in e && e.default ? e.default && "default" in e.default && e.default.default ? e.default.default : e.default : e;
14
+ }
15
+ function s(e) {
16
+ let t = typeof e == "number" ? e : e.getTime();
17
+ return function() {
18
+ return Date.now() > t;
19
+ };
20
+ }
21
+ export { e as EvalFlags, t as GetOwnPropertyNamesFlags, n as IntrinsicsFlags, r as IsEqualOp, i as JSPromiseStateEnum, a as newQuickJSWASMModuleFromVariant, s as shouldInterruptAfterDeadline };
@@ -0,0 +1 @@
1
+ export { QuickJSModuleCallbacks, QuickJSWASMModule, applyBaseRuntimeOptions, applyModuleEvalRuntimeOptions } from "./chunk-V2S4ZYJR.js";
@@ -0,0 +1,185 @@
1
+ import { mcpValue as e } from "./mcp-result.js";
2
+ import { SAVED_RESULT as t, WORKSPACE_ID as n } from "./workspace-tools.js";
3
+ import { jsonSchema as r, tool as i } from "ai";
4
+ // frontend/byok/page-context.ts
5
+ var a = {
6
+ description: "data-ai-context",
7
+ data: "data-ai-context-data",
8
+ read: "data-ai-context-read"
9
+ }, o = {
10
+ perMessage: 8,
11
+ readMs: 6e4,
12
+ resultChars: 2e4
13
+ }, s = "page", c = "page__read_element", l = "application/x-byok-page-element", u = (e) => e.type === "page-element" && e.contentType === "application/x-byok-page-element", d = (e) => e.content[0].data.inside, f = () => Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)), (e) => e.toString(16).padStart(2, "0")).join(""), p = (e) => e === 1 ? "1 element" : `${e} elements`, m = (e) => /^[a-f0-9]{32}$/.test(e);
14
+ function h(e) {
15
+ return e.getAttribute(a.description)?.trim() || void 0;
16
+ }
17
+ function g(e) {
18
+ if (e.hasAttribute(a.data) && e.hasAttribute(a.read)) return `"${h(e)}" sets both ${a.data} and ${a.read}; an element has at most one.`;
19
+ }
20
+ var _ = /* @__PURE__ */ new WeakSet();
21
+ function v(e) {
22
+ if (h(e) === void 0) return !1;
23
+ let t = g(e);
24
+ return t && !_.has(e) && (_.add(e), console.warn(`byok-ai page context: ${t} It can't be added.`)), !t;
25
+ }
26
+ var y = `[${a.description}]`;
27
+ function b(e) {
28
+ let t = [];
29
+ for (let n = e?.closest(y); n; n = n.parentElement?.closest(y)) v(n) && t.unshift(n);
30
+ return t;
31
+ }
32
+ function x(e = document) {
33
+ return [...e.querySelectorAll(y)].filter(v);
34
+ }
35
+ function S(e) {
36
+ let t = [];
37
+ for (let n = e.parentElement?.closest(y); n; n = n.parentElement?.closest(y)) {
38
+ let e = h(n);
39
+ e !== void 0 && t.unshift(e);
40
+ }
41
+ return { inside: t };
42
+ }
43
+ function C() {
44
+ let e = /* @__PURE__ */ new Map();
45
+ return {
46
+ add(t) {
47
+ let n = f();
48
+ return e.set(n, new WeakRef(t)), {
49
+ id: n,
50
+ type: "page-element",
51
+ name: h(t) ?? "",
52
+ contentType: l,
53
+ content: [{
54
+ type: "data",
55
+ name: "page-element",
56
+ data: S(t)
57
+ }]
58
+ };
59
+ },
60
+ picked(t) {
61
+ let n = e.get(t)?.deref();
62
+ return n?.isConnected ? n : void 0;
63
+ }
64
+ };
65
+ }
66
+ function w(e) {
67
+ let t = /* @__PURE__ */ new Set();
68
+ for (let n of e) if (n.role === "user") for (let e of n.attachments) u(e) && t.add(e.id);
69
+ return t;
70
+ }
71
+ function T(e, t) {
72
+ return [`The user added ${e.length === 1 ? "an element" : `${e.length} elements`} from the page to this message${t ? `. Read the data of the ones you need with ${c}` : ". Reading them is not available now, so only their descriptions are known"}:`, ...e.map((e) => {
73
+ let t = d(e);
74
+ return `- ${e.id}: ${JSON.stringify(e.name)}` + (t.length ? ` (inside ${t.map((e) => JSON.stringify(e)).join(" › ")})` : "");
75
+ })].join("\n");
76
+ }
77
+ var E = (e) => e instanceof Error ? e.message : String(e);
78
+ function D(e) {
79
+ try {
80
+ return Function("MCP", "element", `"use strict";\nreturn (\n${e}\n)`);
81
+ } catch (e) {
82
+ throw e instanceof EvalError ? Error(`This page's Content-Security-Policy doesn't allow ${a.read} (it needs 'unsafe-eval'), so only the element's description is known.`, { cause: e }) : Error(`The element's ${a.read} is not a JavaScript expression: ${E(e)}`, { cause: e });
83
+ }
84
+ }
85
+ async function O(e, t = 0) {
86
+ if (t > 8) return e;
87
+ if (e instanceof Promise) return O(await e, t + 1);
88
+ let n = async (e) => {
89
+ try {
90
+ return await O(e, t + 1);
91
+ } catch (e) {
92
+ return { error: E(e) };
93
+ }
94
+ };
95
+ if (Array.isArray(e)) return Promise.all(e.map(n));
96
+ if (typeof e == "object" && e && Object.getPrototypeOf(e) === Object.prototype) {
97
+ let t = await Promise.all(Object.entries(e).map(async ([e, t]) => [e, await n(t)]));
98
+ return Object.fromEntries(t);
99
+ }
100
+ return e;
101
+ }
102
+ function k(e) {
103
+ if (e === void 0) throw Error(`The element's ${a.read} returned nothing.`);
104
+ let t;
105
+ try {
106
+ t = JSON.stringify(e);
107
+ } catch (e) {
108
+ throw Error(`The element's ${a.read} returned a value that is not JSON: ${E(e)}`, { cause: e });
109
+ }
110
+ if (t === void 0) throw Error(`The element's ${a.read} returned a value that is not JSON.`);
111
+ return JSON.parse(t);
112
+ }
113
+ async function A(e, t) {
114
+ let n = h(e);
115
+ if (n === void 0) throw Error("The element no longer has a description.");
116
+ let r = g(e);
117
+ if (r) throw Error(r);
118
+ let i = e.getAttribute(a.data);
119
+ if (i !== null) return {
120
+ description: n,
121
+ data: i
122
+ };
123
+ let s = e.getAttribute(a.read);
124
+ if (s === null) return { description: n };
125
+ let c = D(s), l = t.timeoutMs ?? o.readMs, u = AbortSignal.any([AbortSignal.timeout(l), ...t.signal ? [t.signal] : []]);
126
+ u.throwIfAborted();
127
+ let d = new Promise((e, n) => u.addEventListener("abort", () => n(t.signal?.aborted ? t.signal.reason : /* @__PURE__ */ Error(`The element's ${a.read} took longer than ${l / 1e3} seconds.`)), { once: !0 }));
128
+ d.catch(() => {});
129
+ let f;
130
+ try {
131
+ f = await Promise.race([Promise.resolve().then(() => O(c(t.mcp, e))), d]);
132
+ } catch (e) {
133
+ throw u.aborted ? e : Error(`The element's ${a.read} failed: ${E(e)}`, { cause: e });
134
+ }
135
+ return {
136
+ description: n,
137
+ data: k(f)
138
+ };
139
+ }
140
+ function j(t) {
141
+ return async (n, r = {}) => {
142
+ if (typeof n != "string" || !t.isMcp(n)) throw Error(`MCP(${JSON.stringify(n)}): there is no such MCP tool. Use its full name, "<server id>__<tool name>".`);
143
+ if (typeof r != "object" || !r || Array.isArray(r)) throw Error(`MCP("${n}", params): params is an object.`);
144
+ let i = t.tools()[n]?.execute;
145
+ if (!i) throw Error(`MCP("${n}"): there is no such MCP tool.`);
146
+ return e(await i(r, t.callOptions));
147
+ };
148
+ }
149
+ function M(e, t) {
150
+ let r = JSON.stringify(e.data) ?? "";
151
+ return r.length <= o.resultChars ? e : {
152
+ description: e.description,
153
+ characters: r.length,
154
+ start: r.slice(0, 2e3),
155
+ note: t ? `The data is too large to give here. Save it with ${n}__save_tool_result (tool "${c}", the same arguments) and compute over the file.` : "The data is too large to give here; this is its start."
156
+ };
157
+ }
158
+ function N(e) {
159
+ let n = async ({ id: t }, n) => {
160
+ if (!e.elements.has(t)) throw Error(`No element with the id ${t} was added to this conversation.`);
161
+ let r = e.registry.picked(t);
162
+ if (!r) throw Error("This element is no longer on the page. The user can add it again.");
163
+ return A(r, {
164
+ mcp: j({
165
+ ...e,
166
+ callOptions: n
167
+ }),
168
+ signal: n.abortSignal
169
+ });
170
+ }, a = i({
171
+ description: "Read an element the user added from the page to a message, by the id listed there: its description, and its data as the page has it now (none when the description is all there is). Reading an element gives only its own data, not that of elements inside it.",
172
+ inputSchema: r({
173
+ type: "object",
174
+ additionalProperties: !1,
175
+ required: ["id"],
176
+ properties: { id: {
177
+ type: "string",
178
+ description: "The element's id, as listed in the message."
179
+ } }
180
+ }),
181
+ execute: async (t, r) => M(await n(t, r), e.canSave)
182
+ });
183
+ return a[t] = (e, t) => n(e, t), { [c]: a };
184
+ }
185
+ export { a as PAGE_CONTEXT_ATTRIBUTES, s as PAGE_CONTEXT_ID, o as PAGE_CONTEXT_LIMITS, l as PAGE_ELEMENT_TYPE, c as READ_ELEMENT_TOOL, b as addableChain, x as addableElements, g as declarationProblem, h as descriptionOf, p as elementCount, d as insideOf, v as isAddable, u as isPageElementAttachment, m as isPageElementId, j as mcpCall, N as pageContextTools, C as pageElementRegistry, w as pageElementsIn, T as pageElementsNote, S as placeOf, A as readPageElement };
@@ -0,0 +1,119 @@
1
+ import { addableChain as e, addableElements as t, descriptionOf as n } from "./page-context.js";
2
+ // frontend/byok/page-picker.ts
3
+ function r(e, t) {
4
+ return e ? `${e === 1 ? "One element" : e + " elements"} on this page can be added. Click one, or press Tab to go through them.` + (t ? " ↑ and ↓ choose the outer or inner one." : "") + " Enter adds, Escape cancels." : "Nothing on this page can be added. Press Escape to go back.";
5
+ }
6
+ var i = (e, t) => {
7
+ e.hidden = !t, t && Object.assign(e.style, {
8
+ left: t.left + "px",
9
+ top: t.top + "px",
10
+ width: t.width + "px",
11
+ height: t.height + "px"
12
+ });
13
+ }, a = (e) => {
14
+ let t = e?.isConnected ? e.getBoundingClientRect() : void 0;
15
+ return t && t.width > 0 && t.height > 0 ? t : void 0;
16
+ };
17
+ function o(o = {}) {
18
+ return new Promise((s) => {
19
+ if (o.signal?.aborted) return s(void 0);
20
+ let c = document.activeElement instanceof HTMLElement ? document.activeElement : void 0, l = (e, t) => {
21
+ let n = document.createElement(t);
22
+ return n.dataset.byok = e, n;
23
+ }, u = l("page-picker", "div");
24
+ u.tabIndex = -1, u.setAttribute("role", "dialog"), u.setAttribute("aria-label", "Add from page"), Object.assign(u.style, {
25
+ position: "fixed",
26
+ inset: "0",
27
+ zIndex: "2147483647",
28
+ cursor: "crosshair"
29
+ });
30
+ let d = l("page-picker-highlight", "div"), f = l("page-picker-label", "div");
31
+ Object.assign(d.style, {
32
+ position: "fixed",
33
+ pointerEvents: "none"
34
+ }), Object.assign(f.style, {
35
+ position: "fixed",
36
+ cursor: "default"
37
+ });
38
+ let p = l("page-picker-hint", "div");
39
+ p.setAttribute("role", "status");
40
+ let m = t();
41
+ p.textContent = r(m.length, m.some((t) => e(t).length > 1)), u.append(d, f, p);
42
+ let h, g = [], _ = -1, v, y = () => g[_], b = ({ x: e, y: t }) => document.elementsFromPoint(e, t).find((e) => !u.contains(e)), x = (t) => {
43
+ t &&= e(t).at(-1), t !== h && (h = t, g = t ? e(t) : [], _ = g.length - 1, D());
44
+ }, S = (e) => {
45
+ e < 0 || e >= g.length || e === _ || (_ = e, D(), O());
46
+ }, C = l("page-picker-description", "span"), w = (e, t, n) => {
47
+ let r = l(e, "button");
48
+ return r.type = "button", r.tabIndex = -1, r.textContent = t, r.addEventListener("click", (e) => {
49
+ e.stopPropagation(), S(_ + n);
50
+ }), r;
51
+ }, T = w("page-picker-outer", "↑", -1), E = w("page-picker-inner", "↓", 1);
52
+ f.append(T, C, E);
53
+ let D = () => {
54
+ C.textContent = y() ? n(y()) ?? "" : "";
55
+ for (let [e, t, r] of [[
56
+ T,
57
+ g[_ - 1],
58
+ "Outer"
59
+ ], [
60
+ E,
61
+ g[_ + 1],
62
+ "Inner"
63
+ ]]) {
64
+ e.hidden = !t;
65
+ let i = t ? `${r}: ${n(t)}` : "";
66
+ e.title = i, e.setAttribute("aria-label", i);
67
+ }
68
+ }, O = () => {
69
+ i(d, a(y()));
70
+ let e = a(h);
71
+ if (f.hidden = !e || !a(y()), !e || f.hidden) return;
72
+ let t = e.top - f.offsetHeight, n = t >= 0 ? t : Math.min(e.bottom, innerHeight - f.offsetHeight);
73
+ Object.assign(f.style, {
74
+ top: Math.max(0, n) + "px",
75
+ left: Math.max(0, Math.min(e.left, innerWidth - f.offsetWidth)) + "px"
76
+ });
77
+ }, k = requestAnimationFrame(function e() {
78
+ v && x(b(v)), O(), document.activeElement !== u && u.focus({ preventScroll: !0 }), k = requestAnimationFrame(e);
79
+ }), A = (e) => {
80
+ cancelAnimationFrame(k), u.remove(), window.removeEventListener("keydown", M, !0), o.signal?.removeEventListener("abort", j), c?.isConnected && c.focus(), s(e);
81
+ }, j = () => A(void 0), M = (e) => {
82
+ if (![
83
+ "Escape",
84
+ "Tab",
85
+ "Enter",
86
+ "ArrowUp",
87
+ "ArrowDown"
88
+ ].includes(e.key)) return;
89
+ if (e.preventDefault(), e.stopPropagation(), e.key === "Escape") return A(void 0);
90
+ if (e.key === "Enter") {
91
+ y()?.isConnected && A(y());
92
+ return;
93
+ }
94
+ if (e.key === "ArrowUp") return S(_ - 1);
95
+ if (e.key === "ArrowDown") return S(_ + 1);
96
+ let n = t().filter((e) => e.checkVisibility?.() ?? !0);
97
+ if (!n.length) return;
98
+ let r = n[((y() ? n.indexOf(y()) : -1) + (e.shiftKey ? -1 : 1) + n.length) % n.length];
99
+ v = void 0, r.scrollIntoView({
100
+ block: "nearest",
101
+ inline: "nearest"
102
+ }), x(r), O();
103
+ };
104
+ u.addEventListener("pointermove", (e) => {
105
+ f.contains(e.target) || (v = {
106
+ x: e.clientX,
107
+ y: e.clientY
108
+ });
109
+ }), u.addEventListener("pointerdown", (e) => e.preventDefault()), u.addEventListener("click", (e) => {
110
+ e.preventDefault(), f.contains(e.target) ? e.target === C && y() && A(y()) : (x(b({
111
+ x: e.clientX,
112
+ y: e.clientY
113
+ })), y() && A(y()));
114
+ }), u.addEventListener("contextmenu", (e) => {
115
+ e.preventDefault(), A(void 0);
116
+ }), window.addEventListener("keydown", M, !0), o.signal?.addEventListener("abort", j, { once: !0 }), document.body.append(u), u.focus();
117
+ });
118
+ }
119
+ export { o as pickPageElement, r as pickerHint };
@@ -0,0 +1,84 @@
1
+ import { createOpenAI as e } from "@ai-sdk/openai";
2
+ import { createAnthropic as t } from "@ai-sdk/anthropic";
3
+ import { createGoogleGenerativeAI as n } from "@ai-sdk/google";
4
+ // frontend/byok/providers.ts
5
+ var r = [{
6
+ name: "apiKey",
7
+ label: "API key",
8
+ type: "password",
9
+ placeholder: "Paste your API key",
10
+ required: !0
11
+ }, {
12
+ name: "model",
13
+ label: "Model",
14
+ placeholder: "Model ID",
15
+ required: !0
16
+ }], i = [
17
+ {
18
+ id: "openai",
19
+ name: "OpenAI",
20
+ description: "Connect directly with your OpenAI API key.",
21
+ defaultValues: { model: "gpt-4.1-mini" },
22
+ fields: r,
23
+ acceptsImages: !0,
24
+ createModel: (t) => e({ apiKey: t.apiKey })(t.model)
25
+ },
26
+ {
27
+ id: "anthropic",
28
+ name: "Anthropic",
29
+ description: "Claude, with direct browser access explicitly enabled.",
30
+ defaultValues: { model: "claude-sonnet-4-5" },
31
+ fields: r,
32
+ acceptsImages: !0,
33
+ createModel: (e) => t({
34
+ apiKey: e.apiKey,
35
+ headers: { "anthropic-dangerous-direct-browser-access": "true" }
36
+ })(e.model)
37
+ },
38
+ {
39
+ id: "google",
40
+ name: "Google Gemini",
41
+ description: "Use your Google AI Studio key.",
42
+ defaultValues: { model: "gemini-2.5-flash" },
43
+ fields: r,
44
+ acceptsImages: !0,
45
+ createModel: (e) => n({ apiKey: e.apiKey })(e.model)
46
+ },
47
+ {
48
+ id: "compatible",
49
+ name: "OpenAI compatible",
50
+ description: "Your own endpoint, local model, or gateway. Browser CORS support is required.",
51
+ defaultValues: {
52
+ model: "",
53
+ baseURL: ""
54
+ },
55
+ acceptsImages: !0,
56
+ fields: [{
57
+ name: "baseURL",
58
+ label: "API base URL",
59
+ type: "url",
60
+ placeholder: "https://your-provider.example/v1",
61
+ required: !0
62
+ }, ...r.map((e) => e.name === "apiKey" ? {
63
+ ...e,
64
+ required: !1
65
+ } : e)],
66
+ validate: (e) => {
67
+ try {
68
+ let t = new URL(e.baseURL);
69
+ if (t.protocol !== "https:" && !(t.protocol === "http:" && [
70
+ "localhost",
71
+ "127.0.0.1",
72
+ "[::1]"
73
+ ].includes(t.hostname))) return "Use HTTPS, or HTTP for localhost.";
74
+ } catch {
75
+ return "Enter a valid API base URL.";
76
+ }
77
+ },
78
+ createModel: (t) => e({
79
+ apiKey: t.apiKey || "local",
80
+ baseURL: t.baseURL
81
+ }).chat(t.model)
82
+ }
83
+ ];
84
+ export { i as defaultProviders };
@@ -0,0 +1,4 @@
1
+ import { createContext as e } from "react";
2
+ // frontend/byok/rendering-context.ts
3
+ var t = e(void 0);
4
+ export { t as MessageRenderingContext };
@@ -0,0 +1,102 @@
1
+ import { newQuickJSWASMModuleFromVariant as e, shouldInterruptAfterDeadline as t } from "./node_modules/quickjs-emscripten-core/dist/index.js";
2
+ import { fileNameProblem as n, writeProblem as r } from "./conversation-files.js";
3
+ import { SCRIPT_LIMITS as i } from "./script.js";
4
+ // frontend/byok/sandbox.ts
5
+ var a = "\"use strict\";\n(() => {\n const host = { read: __read, write: __write, remove: __remove, list: __list, log: __log };\n for (const name of [\"__read\", \"__write\", \"__remove\", \"__list\", \"__log\"]) delete globalThis[name];\n const text = value => typeof value === \"string\" ? value : JSON.stringify(value);\n const show = value => typeof value === \"string\" ? value : (() => { try { return JSON.stringify(value) } catch { return String(value) } })();\n const files = Object.freeze({\n list: () => JSON.parse(host.list()),\n read: name => host.read(String(name)),\n readJSON: name => { const content = host.read(String(name)); return content === undefined ? undefined : JSON.parse(content) },\n write: (name, value) => {\n if (value === undefined) throw new TypeError(\"files.write needs a string, or a value to save as JSON\");\n host.write(String(name), text(value));\n },\n delete: name => host.remove(String(name)),\n });\n const log = (...values) => host.log(values.map(show).join(\" \"));\n Object.defineProperty(globalThis, \"files\", { value: files });\n Object.defineProperty(globalThis, \"console\", { value: Object.freeze({ log, info: log, warn: log, error: log }) });\n})();";
6
+ function o(e) {
7
+ return /interrupted/i.test(e) ? `The script ran longer than ${i.timeMs / 1e3} seconds and was stopped.` : /out of memory/i.test(e) ? "The script used more memory than allowed." : /stack overflow|maximum call stack/i.test(e) ? "The script recursed too deeply." : e.slice(0, 2e3);
8
+ }
9
+ async function s(s, c) {
10
+ let l = "", u = !1, d = (e) => {
11
+ u || (l.length + e.length + 1 > i.logChars ? (l += e.slice(0, Math.max(0, i.logChars - l.length)), u = !0) : l += (l ? "\n" : "") + e);
12
+ }, f = (e) => ({
13
+ ok: !1,
14
+ error: e,
15
+ logs: l,
16
+ logsTruncated: u
17
+ }), p = /* @__PURE__ */ new Map(), m = /* @__PURE__ */ new Set(), h = (e) => p.has(e) ? p.get(e) : m.has(e) ? void 0 : c.files[e], g = () => [.../* @__PURE__ */ new Set([...Object.keys(c.files), ...p.keys()])].flatMap((e) => {
18
+ let t = h(e);
19
+ return t === void 0 ? [] : [{
20
+ name: e,
21
+ size: new TextEncoder().encode(t).length,
22
+ modifiedAt: 0
23
+ }];
24
+ }).sort((e, t) => e.name.localeCompare(t.name)), _;
25
+ try {
26
+ _ = await e(s);
27
+ } catch {
28
+ return f("The script engine could not start.");
29
+ }
30
+ let v = _.newRuntime();
31
+ v.setMemoryLimit(i.memoryBytes), v.setMaxStackSize(i.stackBytes), v.setInterruptHandler(t(Date.now() + i.timeMs));
32
+ let y = v.newContext(), b = (e, t) => {
33
+ let n = y.newFunction(e, (...e) => {
34
+ let n = e.map((e) => y.typeof(e) === "string" ? y.getString(e) : "");
35
+ try {
36
+ let e = t(...n);
37
+ return typeof e == "string" ? y.newString(e) : y.undefined;
38
+ } catch (e) {
39
+ return { error: y.newError(e instanceof Error ? e.message : String(e)) };
40
+ }
41
+ });
42
+ y.setProp(y.global, e, n), n.dispose();
43
+ }, x = (e) => {
44
+ let t = n(e);
45
+ if (t) throw Error(t);
46
+ };
47
+ b("__read", (e) => (x(e), h(e))), b("__write", (e, t) => {
48
+ x(e);
49
+ let n = r(g(), e, t);
50
+ if (n) throw Error(n);
51
+ p.set(e, t), m.delete(e);
52
+ }), b("__remove", (e) => {
53
+ x(e);
54
+ let t = h(e) !== void 0;
55
+ return p.delete(e), e in c.files && m.add(e), t ? "true" : "false";
56
+ }), b("__list", () => JSON.stringify(g().map(({ name: e, size: t }) => ({
57
+ name: e,
58
+ size: t
59
+ })))), b("__log", (e) => d(e));
60
+ let S = (e, t) => {
61
+ let n = e.getPromiseState(t);
62
+ if (n.type === "pending") return { error: "The script returned a promise that never settled. Nothing here is asynchronous: return the value itself." };
63
+ if (n.type === "rejected") {
64
+ let t = e.dump(n.error);
65
+ return n.error.dispose(), { error: typeof t == "string" ? t : [t?.message, t?.stack].filter(Boolean).join("\n") };
66
+ }
67
+ let r = n.value, i = e.getProp(e.global, "JSON"), a = e.getProp(i, "stringify"), o = e.callFunction(a, i, r);
68
+ if (a.dispose(), i.dispose(), r.dispose(), o.error) {
69
+ let t = e.dump(o.error);
70
+ return o.error.dispose(), { error: "The returned value is not JSON: " + (t?.message ?? String(t)) };
71
+ }
72
+ let s = e.typeof(o.value) === "string" ? e.getString(o.value) : void 0;
73
+ return o.value.dispose(), { text: s };
74
+ };
75
+ try {
76
+ let e = y.evalCode(a, "prelude.js");
77
+ if (e.error) return e.error.dispose(), f("The script engine could not start.");
78
+ e.value.dispose();
79
+ let t = y.evalCode(`(async () => { "use strict"; ${c.code}\n})()`, "script.js");
80
+ if (t.error) {
81
+ let e = y.dump(t.error);
82
+ return t.error.dispose(), f(o([e?.message, e?.stack].filter(Boolean).join("\n") || String(e)));
83
+ }
84
+ let n = v.executePendingJobs();
85
+ if (n.error) {
86
+ let e = y.dump(n.error);
87
+ return n.error.dispose(), t.value.dispose(), f(o(e?.message ?? String(e)));
88
+ }
89
+ let r = S(y, t.value);
90
+ return t.value.dispose(), "error" in r ? f(o(String(r.error))) : r.text !== void 0 && r.text.length > i.resultChars ? f(`The returned value is ${r.text.length} characters as JSON, over the ${i.resultChars} allowed. Return a summary, or write the full result to a file and return its name.`) : {
91
+ ok: !0,
92
+ result: r.text === void 0 ? null : JSON.parse(r.text),
93
+ logs: l,
94
+ logsTruncated: u,
95
+ written: Object.fromEntries(p),
96
+ deleted: [...m]
97
+ };
98
+ } catch (e) {
99
+ return f(o(e instanceof Error ? e.message : String(e)));
100
+ }
101
+ }
102
+ export { s as runScript };
@@ -0,0 +1,26 @@
1
+ import { SCRIPT_LIMITS as e } from "./script.js";
2
+ // frontend/byok/script-runner.ts
3
+ var t = 5e3, n, r = async () => new (await (n ??= (import("./sandbox-worker.js").then((e) => e.default))))(), i = async (i, a) => {
4
+ let o = (e) => ({
5
+ ok: !1,
6
+ error: e,
7
+ logs: "",
8
+ logsTruncated: !1
9
+ });
10
+ if (a?.aborted) return o("Stopped.");
11
+ let s;
12
+ try {
13
+ s = await r();
14
+ } catch {
15
+ return n = void 0, o("The script engine could not start.");
16
+ }
17
+ return a?.aborted ? (s.terminate(), o("Stopped.")) : new Promise((n) => {
18
+ let r = (e) => {
19
+ clearTimeout(l), a?.removeEventListener("abort", c), s.terminate(), n(e);
20
+ }, c = () => r(o("Stopped.")), l = setTimeout(() => r(o(`The script ran longer than ${e.timeMs / 1e3} seconds and was stopped.`)), e.timeMs + t);
21
+ a?.addEventListener("abort", c), s.onmessage = (e) => r(e.data), s.onerror = (e) => {
22
+ e.preventDefault(), r(o("The script engine could not start."));
23
+ }, s.postMessage(i);
24
+ });
25
+ };
26
+ export { i as workerScriptRunner };
@@ -0,0 +1,9 @@
1
+ // frontend/byok/script.ts
2
+ var e = {
3
+ timeMs: 1e4,
4
+ memoryBytes: 268435456,
5
+ stackBytes: 1048576,
6
+ resultChars: 2e4,
7
+ logChars: 2e4
8
+ };
9
+ export { e as SCRIPT_LIMITS };
@@ -1,5 +1,4 @@
1
1
  import type { ThreadMessage } from '@assistant-ui/react';
2
- import type { ProviderValues } from './types';
3
2
  export interface Conversation {
4
3
  id: string;
5
4
  title: string;
@@ -11,12 +10,7 @@ export interface StoredConversations {
11
10
  conversations: Conversation[];
12
11
  activeConversationId?: string;
13
12
  }
14
- export interface StoredConnection {
15
- providerId: string;
16
- values: ProviderValues;
17
- }
18
13
  export declare const DEFAULT_STORAGE_KEY = "byok-ai:conversations";
19
- export declare const defaultConnectionKey: (storageKey: string) => string;
20
14
  export declare function newConversation(id?: string): Conversation;
21
15
  /** A conversation with no messages and no unsent draft. It is never listed or saved. */
22
16
  export declare const isEmptyConversation: (conversation: Pick<Conversation, "messages" | "draft">) => boolean;
@@ -26,10 +20,3 @@ export declare function loadConversations(key: string): {
26
20
  error: boolean;
27
21
  };
28
22
  export declare function saveConversations(key: string, data: StoredConversations): boolean;
29
- export declare function loadConnection(key: string): StoredConnection | undefined;
30
- /** Saves the connection, or removes it when `connection` is undefined, and tells the others. */
31
- export declare function saveConnection(key: string, connection: StoredConnection | undefined): boolean;
32
- /** Calls `listener` after the connection under `key` may have changed. Returns the unsubscribe. */
33
- export declare function subscribeConnection(key: string, listener: () => void): () => void;
34
- /** Whether two saved connections are the same provider with the same values. */
35
- export declare function sameConnection(a: StoredConnection | undefined, b: StoredConnection | undefined): boolean;
@@ -0,0 +1,67 @@
1
+ import { isImageId as e } from "./conversation-files.js";
2
+ import { isPageElementId as t } from "./page-context.js";
3
+ import { isRecord as n, readStored as r, writeStored as i } from "./local-storage.js";
4
+ // frontend/byok/storage.ts
5
+ var a = "byok-ai:conversations";
6
+ function o() {
7
+ return Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)), (e) => e.toString(16).padStart(2, "0")).join("");
8
+ }
9
+ function s(e = o()) {
10
+ return {
11
+ id: e,
12
+ title: "New conversation",
13
+ updatedAt: Date.now(),
14
+ messages: [],
15
+ draft: ""
16
+ };
17
+ }
18
+ var c = (e) => e.messages.length === 0 && !e.draft.trim(), l = (t) => n(t) && t.type === "image" && typeof t.id == "string" && e(t.id) && typeof t.name == "string" && typeof t.contentType == "string" && n(t.status) && t.status.type === "complete", u = (e) => Array.isArray(e) && e.length === 1 && n(e[0]) && e[0].type === "data" && e[0].name === "page-element" && n(e[0].data) && Array.isArray(e[0].data.inside) && e[0].data.inside.every((e) => typeof e == "string"), d = (e) => n(e) && e.type === "page-element" && typeof e.id == "string" && t(e.id) && typeof e.name == "string" && e.contentType === "application/x-byok-page-element" && n(e.status) && e.status.type === "complete" && u(e.content);
19
+ function f(e) {
20
+ if (!n(e) || typeof e.id != "string" || ![
21
+ "user",
22
+ "assistant",
23
+ "system"
24
+ ].includes(String(e.role)) || !Array.isArray(e.content) || !e.content.every((e) => n(e) && typeof e.type == "string" && (e.type !== "text" || typeof e.text == "string")) || e.role === "user" && (!Array.isArray(e.attachments) || !e.attachments.every((e) => l(e) || d(e)))) return;
25
+ let t = new Date(typeof e.createdAt == "string" ? e.createdAt : NaN);
26
+ if (!Number.isFinite(t.getTime())) return;
27
+ let r = e.role === "assistant" && n(e.status) && ["running", "requires-action"].includes(String(e.status.type));
28
+ return {
29
+ ...e,
30
+ createdAt: t,
31
+ ...r ? { status: {
32
+ type: "incomplete",
33
+ reason: "cancelled"
34
+ } } : {}
35
+ };
36
+ }
37
+ function p(e) {
38
+ if (!n(e) || typeof e.id != "string" || typeof e.title != "string" || typeof e.draft != "string" || typeof e.updatedAt != "number" || !Number.isFinite(e.updatedAt) || !Array.isArray(e.messages)) return;
39
+ let t = e.messages.map(f);
40
+ if (!t.some((e) => !e)) return {
41
+ id: e.id,
42
+ title: e.title,
43
+ updatedAt: e.updatedAt,
44
+ draft: e.draft,
45
+ messages: t
46
+ };
47
+ }
48
+ function m(e) {
49
+ let { value: t, error: i } = r(e);
50
+ return t === null ? {
51
+ data: { conversations: [] },
52
+ error: i
53
+ } : !n(t) || !Array.isArray(t.conversations) ? {
54
+ data: { conversations: [] },
55
+ error: !0
56
+ } : {
57
+ data: {
58
+ conversations: t.conversations.flatMap((e) => p(e) ?? []),
59
+ activeConversationId: typeof t.activeConversationId == "string" ? t.activeConversationId : void 0
60
+ },
61
+ error: !1
62
+ };
63
+ }
64
+ function h(e, t) {
65
+ return i(e, t);
66
+ }
67
+ export { a as DEFAULT_STORAGE_KEY, c as isEmptyConversation, m as loadConversations, s as newConversation, h as saveConversations };