@dudko.dev/agent-web 0.0.47 → 0.0.48
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -2
- package/dist/agent-web.js +124 -124
- package/dist/agent-web.js.map +1 -1
- package/dist/{chunk-Y6CD3WOK.js → chunk-6D4RB3H5.js} +11 -213
- package/dist/chunk-6D4RB3H5.js.map +1 -0
- package/dist/{chunk-PTJA7V23.js → chunk-6XHCPSZE.js} +5 -3
- package/dist/{chunk-PTJA7V23.js.map → chunk-6XHCPSZE.js.map} +1 -1
- package/dist/{chunk-Y4MIIBPB.js → chunk-7D2CJQB2.js} +1 -100
- package/dist/chunk-7D2CJQB2.js.map +1 -0
- package/dist/chunk-7Y5UC6L7.js +52 -0
- package/dist/chunk-7Y5UC6L7.js.map +1 -0
- package/dist/chunk-IT77BVAD.js +99 -0
- package/dist/chunk-IT77BVAD.js.map +1 -0
- package/dist/chunk-JTZEUPIG.js +217 -0
- package/dist/chunk-JTZEUPIG.js.map +1 -0
- package/dist/index.cjs +33 -24
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +25 -66
- package/dist/index.d.ts +25 -66
- package/dist/index.js +35 -68
- package/dist/index.js.map +1 -1
- package/dist/mcp.cjs +28 -20
- package/dist/mcp.cjs.map +1 -1
- package/dist/mcp.d.cts +4 -3
- package/dist/mcp.d.ts +4 -3
- package/dist/mcp.js +9 -5
- package/dist/mcp.js.map +1 -1
- package/dist/{sandbox-ZXWD5IWZ.js → sandbox-IGTCMOOX.js} +4 -3
- package/dist/{sandbox-ZXWD5IWZ.js.map → sandbox-IGTCMOOX.js.map} +1 -1
- package/dist/secrets.cjs +329 -0
- package/dist/secrets.cjs.map +1 -0
- package/dist/secrets.d.cts +63 -0
- package/dist/secrets.d.ts +63 -0
- package/dist/secrets.js +20 -0
- package/dist/secrets.js.map +1 -0
- package/dist/{vault-Mar2CY0J.d.ts → skills-ufoyTJ-B.d.cts} +2 -36
- package/dist/{vault-Mar2CY0J.d.cts → skills-ufoyTJ-B.d.ts} +2 -36
- package/dist/vault-BBGybouF.d.cts +35 -0
- package/dist/vault-BBGybouF.d.ts +35 -0
- package/package.json +11 -1
- package/dist/chunk-Y4MIIBPB.js.map +0 -1
- package/dist/chunk-Y6CD3WOK.js.map +0 -1
|
@@ -4,8 +4,9 @@ import {
|
|
|
4
4
|
markCodeExecution,
|
|
5
5
|
normalizePath,
|
|
6
6
|
toolRunContextOf
|
|
7
|
-
} from "./chunk-
|
|
8
|
-
import "./chunk-
|
|
7
|
+
} from "./chunk-6XHCPSZE.js";
|
|
8
|
+
import "./chunk-6D4RB3H5.js";
|
|
9
|
+
import "./chunk-JTZEUPIG.js";
|
|
9
10
|
import {
|
|
10
11
|
RUN_JS_TOOL,
|
|
11
12
|
SANDBOX_MAX_FILE_CHARS,
|
|
@@ -279,4 +280,4 @@ var createSandbox = (config, mounted = {}, warn = () => {
|
|
|
279
280
|
export {
|
|
280
281
|
createSandbox
|
|
281
282
|
};
|
|
282
|
-
//# sourceMappingURL=sandbox-
|
|
283
|
+
//# sourceMappingURL=sandbox-IGTCMOOX.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sandbox/index.ts","../src/sandbox/files.ts"],"sourcesContent":["import { jsonSchema, tool, type Tool, type ToolSet } from 'ai'\nimport { normalizePath } from '../files/vfs.js'\nimport { markCodeExecution } from '../tools/approval.js'\nimport { toolRunContextOf } from '../tools/wrap.js'\nimport {\n createSandboxQueue,\n resolveSandboxLimits,\n RUN_JS_TOOL,\n runGuest,\n runInWorker,\n SANDBOX_PACKAGE,\n SANDBOX_PLANNER_NOTE,\n SANDBOX_SYNTHESIZER_NOTE,\n sandboxPeerMissing,\n sandboxPromptNote,\n sanitizeSandboxResult,\n type ISandboxConfig,\n type ISandboxLib,\n type ISandboxPort,\n type ISandboxRequest,\n type ISandboxResult,\n} from './engine.js'\nimport {\n collectModules,\n createFileHost,\n readWorkspaceText,\n sandboxFilesOf,\n sandboxHostOps,\n type SandboxFiles,\n} from './files.js'\n\n/**\n * `config.sandbox`: the `run_js` tool - the model's code runs in QuickJS compiled to\n * WebAssembly (the optional peer `quickjs-emscripten`), never in the page's own JavaScript\n * engine. This module is loaded only when the sandbox is switched on.\n *\n * Where the guest runs:\n * - `worker` given: in a Web Worker that is terminated when the run is over or over time (the\n * hard stop). One worker per run. The worker module is `@dudko.dev/agent-web/sandbox-worker`.\n * - no `worker`: on the page's thread, stopped by the engine's interrupt handler only. A single\n * long native call in the guest then blocks the page until it returns - prefer a worker.\n */\n\n/** A worker as the sandbox uses it: a real `Worker`, or a `MessagePort` in tests. */\nexport interface SandboxWorkerLike {\n postMessage(message: unknown): void\n addEventListener(type: string, listener: (ev: any) => void): void\n terminate?(): void\n}\n\nexport interface SandboxConfig extends ISandboxConfig {\n /**\n * Builds a fresh Worker for one run, e.g.\n * `() => new Worker(new URL('@dudko.dev/agent-web/sandbox-worker', import.meta.url), { type: 'module' })`\n * (Vite: `import SandboxWorker from '@dudko.dev/agent-web/sandbox-worker?worker'`). Without it\n * the guest runs on the page's thread - isolated all the same, but only softly interruptible.\n */\n worker?: () => SandboxWorkerLike\n /**\n * Loads the engine for the page-thread fallback, e.g. `() => import('quickjs-emscripten')`, so\n * that your bundler resolves it. Default: a runtime `import('quickjs-emscripten')` (Node, or a\n * page with an import map). Not used when `worker` is given.\n */\n engine?: () => Promise<unknown>\n}\n\nexport interface Sandbox {\n tools: ToolSet\n /** The run-stable sentences the stage prompts carry while `run_js` is mounted. */\n notes: { planner: string; executor: string; synthesizer: string }\n /** Whether the guest is bound to the workspace (import / require / fs). */\n files: boolean\n /** Where the guest runs. */\n thread: 'worker' | 'page'\n}\n\nconst MAX_CONCURRENT_RUNS = 4\n\nconst portOf = (worker: SandboxWorkerLike): ISandboxPort => ({\n post: (message) => worker.postMessage(message),\n listen: (onMessage, onClose) => {\n worker.addEventListener('message', (ev: { data: unknown }) => onMessage(ev.data))\n worker.addEventListener('error', (ev: { message?: string }) =>\n onClose?.(ev?.message || 'the worker failed'),\n )\n // A MessagePort (tests) delivers nothing until it is started; a Worker has no start().\n ;(worker as { start?: () => void }).start?.()\n },\n terminate: () => worker.terminate?.(),\n})\n\nconst loadEngine = async (custom: (() => Promise<unknown>) | undefined): Promise<ISandboxLib> => {\n let lib: unknown\n try {\n // A variable specifier plus the two bundler comments: the optional peer is left to the\n // runtime, so a host that never switches the sandbox on builds without it installed.\n const pkg = SANDBOX_PACKAGE\n lib = custom ? await custom() : await import(/* webpackIgnore: true */ /* @vite-ignore */ pkg)\n } catch (err) {\n throw sandboxPeerMissing(\n custom\n ? (err as Error)?.message\n : \"in a bundled app pass sandbox.worker, or sandbox.engine: () => import('quickjs-emscripten')\",\n )\n }\n const l = lib as Partial<ISandboxLib> | undefined\n if (\n typeof l?.newQuickJSWASMModuleFromVariant !== 'function' ||\n typeof l.newVariant !== 'function'\n ) {\n throw sandboxPeerMissing('what sandbox.engine returned is not the quickjs-emscripten module')\n }\n return l as ISandboxLib\n}\n\ninterface RunJsInput {\n code?: string\n entry?: string\n}\n\nconst describeTool = (limits: { timeoutMs: number; memoryLimitBytes: number }, files: boolean) =>\n 'Run JavaScript in an isolated sandbox and get back what it printed (console.log) and the value of its last expression. ' +\n 'Use it to actually execute code you wrote - a function on test data, a calculation, a parser on a sample - instead of predicting its output. ' +\n `Plain JavaScript on QuickJS (ES2023, top-level await, setTimeout): no Node or browser APIs, no network, no packages${files ? '' : ', no files'}. ` +\n (files\n ? 'Workspace files: import or require them by relative path (.js, .mjs, .json), or use the async fs.readFile(path), fs.writeFile(path, text), fs.readdir(path). '\n : '') +\n `Limits: ${limits.timeoutMs} ms, ${Math.round(limits.memoryLimitBytes / (1024 * 1024))} MiB. ` +\n 'A failing program returns { ok: false, error } with its stack: read it and fix the code.'\n\n/**\n * Build the sandbox for one agent. `mounted` are the agent's tools after its allow / exclude\n * filters: file tools among them (from `createFileTools`) are what binds the guest to the\n * workspace, unless `files: false`.\n */\nexport const createSandbox = (\n config: SandboxConfig,\n mounted: ToolSet = {},\n warn: (message: string) => void = () => {},\n): Sandbox => {\n const limits = resolveSandboxLimits(config)\n const files: SandboxFiles | undefined =\n config.files === false ? undefined : sandboxFilesOf(mounted)\n const queue = createSandboxQueue(MAX_CONCURRENT_RUNS)\n if (!config.worker) {\n warn(\n '[sandbox] no sandbox.worker: run_js runs on the page thread (isolated, but a long native call in the guest blocks the page). Pass a worker factory.',\n )\n }\n\n const execute = async (input: RunJsInput, options: unknown): Promise<ISandboxResult> => {\n const agentRun = toolRunContextOf(options)\n const approve = agentRun?.approve\n const signal = (options as { abortSignal?: AbortSignal } | undefined)?.abortSignal\n const hasCode = typeof input?.code === 'string' && input.code.trim() !== ''\n const hasEntry = typeof input?.entry === 'string' && input.entry.trim() !== ''\n if (hasEntry && !files?.read) {\n throw new Error(`${RUN_JS_TOOL}: \"entry\" needs workspace files; pass the program as \"code\"`)\n }\n if (hasCode === hasEntry) {\n throw new Error(\n `${RUN_JS_TOOL}: pass ${files?.read ? 'either \"code\" or \"entry\" (a workspace file)' : '\"code\"'}`,\n )\n }\n let code = input.code as string\n let filename = '/main.js'\n if (hasEntry && files) {\n filename = normalizePath(input.entry as string)\n if (!/\\.(js|mjs)$/i.test(filename)) {\n throw new Error(`${RUN_JS_TOOL}: \"entry\" must be a .js or .mjs file, got \"${filename}\"`)\n }\n code = await readWorkspaceText(files, filename, approve, limits.maxCodeChars)\n }\n if (code.length > limits.maxCodeChars) {\n throw new Error(\n `${RUN_JS_TOOL}: the code is ${code.length} characters; the limit is ${limits.maxCodeChars}`,\n )\n }\n const request: ISandboxRequest = { code, filename, limits }\n if (files) {\n request.modules = await collectModules(files, code, filename, approve, limits.maxCodeChars)\n request.hostOps = sandboxHostOps(files)\n }\n const hostCall = files\n ? createFileHost(files, approve, (file) =>\n agentRun?.emit({\n type: 'file.written',\n path: file.path,\n mediaType: file.mimeType,\n bytes: file.size,\n ...(agentRun.step ? { step: agentRun.step } : {}),\n }),\n )\n : undefined\n return queue(async () => {\n let worker: SandboxWorkerLike | undefined\n if (config.worker) {\n try {\n worker = config.worker()\n } catch (err) {\n // No Worker here (an old or locked-down environment): the page thread still isolates.\n warn(\n `[sandbox] sandbox.worker failed (${(err as Error)?.message ?? err}); running on the page thread`,\n )\n }\n }\n if (worker) {\n return runInWorker(portOf(worker), request, { hostCall, signal })\n }\n const startedAt = Date.now()\n const lib = await loadEngine(config.engine)\n const raw = await runGuest(lib, request, { hostCall })\n return { ...sanitizeSandboxResult(raw, limits), durationMs: Date.now() - startedAt }\n })\n }\n\n const withFiles = Boolean(files?.read)\n const runJs: Tool = tool({\n description: describeTool(limits, Boolean(files)),\n inputSchema: jsonSchema<RunJsInput>({\n type: 'object',\n properties: {\n code: {\n type: 'string',\n description:\n 'The program. Print with console.log; the value of the last expression is returned as \"result\".',\n },\n ...(withFiles\n ? {\n entry: {\n type: 'string',\n description:\n 'Instead of \"code\": the path of a workspace .js / .mjs file to run, e.g. \"/main.js\".',\n },\n }\n : {}),\n },\n ...(withFiles ? {} : { required: ['code'] }),\n additionalProperties: false,\n }),\n execute,\n })\n return {\n // It runs code: asked whenever the run acts on an MCP server's skill (tools/approval.ts).\n tools: { [RUN_JS_TOOL]: markCodeExecution(runJs) },\n notes: {\n planner: SANDBOX_PLANNER_NOTE,\n executor: sandboxPromptNote(Boolean(files)),\n synthesizer: SANDBOX_SYNTHESIZER_NOTE,\n },\n files: Boolean(files),\n thread: config.worker ? 'worker' : 'page',\n }\n}\n","import type { ToolSet } from 'ai'\nimport { fileToolBindingOf } from '../files/tools.js'\nimport {\n isTextMime,\n normalizePath,\n type VirtualFileInfo,\n type VirtualFileSystem,\n} from '../files/vfs.js'\nimport {\n moduleSpecifiersOf,\n resolveModulePath,\n SANDBOX_MAX_FILE_CHARS,\n SANDBOX_MAX_MODULE_CHARS_TOTAL,\n SANDBOX_MAX_MODULES,\n SANDBOX_MODULE_EXTENSIONS,\n type SandboxHostCall,\n type SandboxHostOp,\n} from './engine.js'\n\n/**\n * The workspace a sandbox is bound to: the virtual file system the agent's own file tools work\n * on, and - per operation - the NAME of the tool that grants it. The guest gets an operation\n * only when the agent has the tool for it (a read-only mount gives no `writeFile`), and every\n * call passes the consent gate under that tool's name, so a rule that denies `fs_write` denies\n * the guest's writes too.\n */\nexport interface SandboxFiles {\n vfs: VirtualFileSystem\n read?: string\n write?: string\n list?: string\n}\n\n/** The agent's consent gate, as a tool reaches it (`ToolRunContext.approve`). */\nexport type SandboxApprove = (toolName: string, input: unknown, readOnly: boolean) => Promise<void>\n\n/** Find the file tools among the mounted tools (the first file system that can be read wins). */\nexport const sandboxFilesOf = (tools: ToolSet): SandboxFiles | undefined => {\n let files: SandboxFiles | undefined\n for (const [name, t] of Object.entries(tools)) {\n const binding = fileToolBindingOf(t)\n if (!binding || binding.op === 'delete') continue\n if (!files) files = { vfs: binding.vfs }\n if (files.vfs !== binding.vfs) continue\n files[binding.op] ??= name\n }\n return files && (files.read || files.write || files.list) ? files : undefined\n}\n\nexport const sandboxHostOps = (files: SandboxFiles): SandboxHostOp[] => [\n ...(files.read ? (['readFile'] as const) : []),\n ...(files.write ? (['writeFile'] as const) : []),\n ...(files.list ? (['readdir'] as const) : []),\n]\n\nconst pathOf = (value: unknown, what: string): string => {\n if (typeof value !== 'string' || !value) throw new Error(`${what}: a path (string) is required`)\n // Throws on a path that climbs out of the root; there is nothing above it to reach.\n return normalizePath(value)\n}\n\n/** Read one workspace file as text, under the same rules as `fs_read` plus a size cap. */\nexport const readWorkspaceText = async (\n files: SandboxFiles,\n path: string,\n approve: SandboxApprove | undefined,\n maxChars: number,\n): Promise<string> => {\n if (!files.read) throw new Error('reading files is not available in this sandbox')\n await approve?.(files.read, { path }, true)\n const f = await files.vfs.read(path)\n if (!f) throw new Error(`no file \"${path}\"`)\n if (f.encoding === 'base64' && !isTextMime(f.mimeType)) {\n throw new Error(`\"${path}\" is a binary file (${f.mimeType}) and cannot be read as text`)\n }\n const text = f.encoding === 'base64' ? atob(f.content) : f.content\n if (text.length > maxChars) {\n throw new Error(`\"${path}\" is ${text.length} characters; the sandbox reads at most ${maxChars}`)\n }\n return text\n}\n\n/** Serves the guest's `fs` calls on the agent's side of the boundary. */\nexport const createFileHost =\n (\n files: SandboxFiles,\n approve: SandboxApprove | undefined,\n /** Told about every file the guest wrote, after the write succeeded (the run's `file.written`). */\n onWrite?: (file: VirtualFileInfo) => void,\n ): SandboxHostCall =>\n async (op, args) => {\n switch (op) {\n case 'readFile':\n return readWorkspaceText(\n files,\n pathOf(args[0], 'fs.readFile'),\n approve,\n SANDBOX_MAX_FILE_CHARS,\n )\n case 'writeFile': {\n if (!files.write) throw new Error('writing files is not available in this sandbox')\n const path = pathOf(args[0], 'fs.writeFile')\n const content = args[1]\n if (typeof content !== 'string')\n throw new Error('fs.writeFile: the content must be a string')\n if (content.length > SANDBOX_MAX_FILE_CHARS) {\n throw new Error(\n `fs.writeFile: ${content.length} characters; the sandbox writes at most ${SANDBOX_MAX_FILE_CHARS}`,\n )\n }\n await approve?.(files.write, { path, content }, false)\n const info = await files.vfs.write(path, content)\n onWrite?.(info)\n return undefined\n }\n case 'readdir': {\n if (!files.list) throw new Error('listing files is not available in this sandbox')\n const prefix =\n args[0] === undefined || args[0] === '/' ? '/' : pathOf(args[0], 'fs.readdir')\n await approve?.(files.list, { prefix }, true)\n return (await files.vfs.list(prefix)).map((f) => f.path)\n }\n default:\n throw new Error(`fs.${String(op).slice(0, 40)} is not available in this sandbox`)\n }\n }\n\n/**\n * The workspace modules a program refers to, by literal path, followed through their own\n * imports: what the guest's loader will be able to load. A file that is missing, too large, of\n * another kind, or outside the root is simply not handed over - the guest's `import` of it then\n * fails with the reason. Bounded in count and total size.\n */\nexport const collectModules = async (\n files: SandboxFiles,\n code: string,\n filename: string,\n approve: SandboxApprove | undefined,\n maxModuleChars: number,\n): Promise<Record<string, string>> => {\n const modules: Record<string, string> = {}\n if (!files.read) return modules\n const seen = new Set<string>()\n const queue: { source: string; base: string }[] = [{ source: code, base: filename }]\n let total = 0\n while (queue.length > 0) {\n const { source, base } = queue.shift() as { source: string; base: string }\n for (const spec of moduleSpecifiersOf(source)) {\n let path: string\n try {\n path = normalizePath(resolveModulePath(base, spec))\n } catch {\n continue\n }\n if (seen.has(path)) continue\n seen.add(path)\n if (!SANDBOX_MODULE_EXTENSIONS.some((ext) => path.toLowerCase().endsWith(ext))) continue\n if (seen.size > SANDBOX_MAX_MODULES) return modules\n let text: string\n try {\n text = await readWorkspaceText(files, path, approve, maxModuleChars)\n } catch {\n continue\n }\n if (total + text.length > SANDBOX_MAX_MODULE_CHARS_TOTAL) continue\n total += text.length\n modules[path] = text\n if (!path.toLowerCase().endsWith('.json')) queue.push({ source: text, base: path })\n }\n }\n return modules\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,YAAqC;;;ACqCnD,IAAM,iBAAiB,CAAC,UAA6C;AAC1E,MAAI;AACJ,aAAW,CAAC,MAAM,CAAC,KAAK,OAAO,QAAQ,KAAK,GAAG;AAC7C,UAAM,UAAU,kBAAkB,CAAC;AACnC,QAAI,CAAC,WAAW,QAAQ,OAAO,SAAU;AACzC,QAAI,CAAC,MAAO,SAAQ,EAAE,KAAK,QAAQ,IAAI;AACvC,QAAI,MAAM,QAAQ,QAAQ,IAAK;AAC/B,UAAM,QAAQ,EAAE,MAAM;AAAA,EACxB;AACA,SAAO,UAAU,MAAM,QAAQ,MAAM,SAAS,MAAM,QAAQ,QAAQ;AACtE;AAEO,IAAM,iBAAiB,CAAC,UAAyC;AAAA,EACtE,GAAI,MAAM,OAAQ,CAAC,UAAU,IAAc,CAAC;AAAA,EAC5C,GAAI,MAAM,QAAS,CAAC,WAAW,IAAc,CAAC;AAAA,EAC9C,GAAI,MAAM,OAAQ,CAAC,SAAS,IAAc,CAAC;AAC7C;AAEA,IAAM,SAAS,CAAC,OAAgB,SAAyB;AACvD,MAAI,OAAO,UAAU,YAAY,CAAC,MAAO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ACA,CAAC;AAAA,MACP;AAAA,MACA,GAAI,YAAY,CAAC,IAAI,EAAE,UAAU,CAAC,MAAM,EAAE;AAAA,MAC1C,sBAAsB;AAAA,IACxB,CAAC;AAAA,IACD;AAAA,EACF,CAAC;AACD,SAAO;AAAA;AAAA,IAEL,OAAO,EAAE,CAAC,WAAW,GAAG,kBAAkB,KAAK,EAAE;AAAA,IACjD,OAAO;AAAA,MACL,SAAS;AAAA,MACT,UAAU,kBAAkB,QAAQ,KAAK,CAAC;AAAA,MAC1C,aAAa;AAAA,IACf;AAAA,IACA,OAAO,QAAQ,KAAK;AAAA,IACpB,QAAQ,OAAO,SAAS,WAAW;AAAA,EACrC;AACF;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/sandbox/index.ts","../src/sandbox/files.ts"],"sourcesContent":["import { jsonSchema, tool, type Tool, type ToolSet } from 'ai'\nimport { normalizePath } from '../files/vfs.js'\nimport { markCodeExecution } from '../tools/approval.js'\nimport { toolRunContextOf } from '../tools/wrap.js'\nimport {\n createSandboxQueue,\n resolveSandboxLimits,\n RUN_JS_TOOL,\n runGuest,\n runInWorker,\n SANDBOX_PACKAGE,\n SANDBOX_PLANNER_NOTE,\n SANDBOX_SYNTHESIZER_NOTE,\n sandboxPeerMissing,\n sandboxPromptNote,\n sanitizeSandboxResult,\n type ISandboxConfig,\n type ISandboxLib,\n type ISandboxPort,\n type ISandboxRequest,\n type ISandboxResult,\n} from './engine.js'\nimport {\n collectModules,\n createFileHost,\n readWorkspaceText,\n sandboxFilesOf,\n sandboxHostOps,\n type SandboxFiles,\n} from './files.js'\n\n/**\n * `config.sandbox`: the `run_js` tool - the model's code runs in QuickJS compiled to\n * WebAssembly (the optional peer `quickjs-emscripten`), never in the page's own JavaScript\n * engine. This module is loaded only when the sandbox is switched on.\n *\n * Where the guest runs:\n * - `worker` given: in a Web Worker that is terminated when the run is over or over time (the\n * hard stop). One worker per run. The worker module is `@dudko.dev/agent-web/sandbox-worker`.\n * - no `worker`: on the page's thread, stopped by the engine's interrupt handler only. A single\n * long native call in the guest then blocks the page until it returns - prefer a worker.\n */\n\n/** A worker as the sandbox uses it: a real `Worker`, or a `MessagePort` in tests. */\nexport interface SandboxWorkerLike {\n postMessage(message: unknown): void\n addEventListener(type: string, listener: (ev: any) => void): void\n terminate?(): void\n}\n\nexport interface SandboxConfig extends ISandboxConfig {\n /**\n * Builds a fresh Worker for one run, e.g.\n * `() => new Worker(new URL('@dudko.dev/agent-web/sandbox-worker', import.meta.url), { type: 'module' })`\n * (Vite: `import SandboxWorker from '@dudko.dev/agent-web/sandbox-worker?worker'`). Without it\n * the guest runs on the page's thread - isolated all the same, but only softly interruptible.\n */\n worker?: () => SandboxWorkerLike\n /**\n * Loads the engine for the page-thread fallback, e.g. `() => import('quickjs-emscripten')`, so\n * that your bundler resolves it. Default: a runtime `import('quickjs-emscripten')` (Node, or a\n * page with an import map). Not used when `worker` is given.\n */\n engine?: () => Promise<unknown>\n}\n\nexport interface Sandbox {\n tools: ToolSet\n /** The run-stable sentences the stage prompts carry while `run_js` is mounted. */\n notes: { planner: string; executor: string; synthesizer: string }\n /** Whether the guest is bound to the workspace (import / require / fs). */\n files: boolean\n /** Where the guest runs. */\n thread: 'worker' | 'page'\n}\n\nconst MAX_CONCURRENT_RUNS = 4\n\nconst portOf = (worker: SandboxWorkerLike): ISandboxPort => ({\n post: (message) => worker.postMessage(message),\n listen: (onMessage, onClose) => {\n worker.addEventListener('message', (ev: { data: unknown }) => onMessage(ev.data))\n worker.addEventListener('error', (ev: { message?: string }) =>\n onClose?.(ev?.message || 'the worker failed'),\n )\n // A MessagePort (tests) delivers nothing until it is started; a Worker has no start().\n ;(worker as { start?: () => void }).start?.()\n },\n terminate: () => worker.terminate?.(),\n})\n\nconst loadEngine = async (custom: (() => Promise<unknown>) | undefined): Promise<ISandboxLib> => {\n let lib: unknown\n try {\n // A variable specifier plus the two bundler comments: the optional peer is left to the\n // runtime, so a host that never switches the sandbox on builds without it installed.\n const pkg = SANDBOX_PACKAGE\n lib = custom ? await custom() : await import(/* webpackIgnore: true */ /* @vite-ignore */ pkg)\n } catch (err) {\n throw sandboxPeerMissing(\n custom\n ? (err as Error)?.message\n : \"in a bundled app pass sandbox.worker, or sandbox.engine: () => import('quickjs-emscripten')\",\n )\n }\n const l = lib as Partial<ISandboxLib> | undefined\n if (\n typeof l?.newQuickJSWASMModuleFromVariant !== 'function' ||\n typeof l.newVariant !== 'function'\n ) {\n throw sandboxPeerMissing('what sandbox.engine returned is not the quickjs-emscripten module')\n }\n return l as ISandboxLib\n}\n\ninterface RunJsInput {\n code?: string\n entry?: string\n}\n\nconst describeTool = (limits: { timeoutMs: number; memoryLimitBytes: number }, files: boolean) =>\n 'Run JavaScript in an isolated sandbox and get back what it printed (console.log) and the value of its last expression. ' +\n 'Use it to actually execute code you wrote - a function on test data, a calculation, a parser on a sample - instead of predicting its output. ' +\n `Plain JavaScript on QuickJS (ES2023, top-level await, setTimeout): no Node or browser APIs, no network, no packages${files ? '' : ', no files'}. ` +\n (files\n ? 'Workspace files: import or require them by relative path (.js, .mjs, .json), or use the async fs.readFile(path), fs.writeFile(path, text), fs.readdir(path). '\n : '') +\n `Limits: ${limits.timeoutMs} ms, ${Math.round(limits.memoryLimitBytes / (1024 * 1024))} MiB. ` +\n 'A failing program returns { ok: false, error } with its stack: read it and fix the code.'\n\n/**\n * Build the sandbox for one agent. `mounted` are the agent's tools after its allow / exclude\n * filters: file tools among them (from `createFileTools`) are what binds the guest to the\n * workspace, unless `files: false`.\n */\nexport const createSandbox = (\n config: SandboxConfig,\n mounted: ToolSet = {},\n warn: (message: string) => void = () => {},\n): Sandbox => {\n const limits = resolveSandboxLimits(config)\n const files: SandboxFiles | undefined =\n config.files === false ? undefined : sandboxFilesOf(mounted)\n const queue = createSandboxQueue(MAX_CONCURRENT_RUNS)\n if (!config.worker) {\n warn(\n '[sandbox] no sandbox.worker: run_js runs on the page thread (isolated, but a long native call in the guest blocks the page). Pass a worker factory.',\n )\n }\n\n const execute = async (input: RunJsInput, options: unknown): Promise<ISandboxResult> => {\n const agentRun = toolRunContextOf(options)\n const approve = agentRun?.approve\n const signal = (options as { abortSignal?: AbortSignal } | undefined)?.abortSignal\n const hasCode = typeof input?.code === 'string' && input.code.trim() !== ''\n const hasEntry = typeof input?.entry === 'string' && input.entry.trim() !== ''\n if (hasEntry && !files?.read) {\n throw new Error(`${RUN_JS_TOOL}: \"entry\" needs workspace files; pass the program as \"code\"`)\n }\n if (hasCode === hasEntry) {\n throw new Error(\n `${RUN_JS_TOOL}: pass ${files?.read ? 'either \"code\" or \"entry\" (a workspace file)' : '\"code\"'}`,\n )\n }\n let code = input.code as string\n let filename = '/main.js'\n if (hasEntry && files) {\n filename = normalizePath(input.entry as string)\n if (!/\\.(js|mjs)$/i.test(filename)) {\n throw new Error(`${RUN_JS_TOOL}: \"entry\" must be a .js or .mjs file, got \"${filename}\"`)\n }\n code = await readWorkspaceText(files, filename, approve, limits.maxCodeChars)\n }\n if (code.length > limits.maxCodeChars) {\n throw new Error(\n `${RUN_JS_TOOL}: the code is ${code.length} characters; the limit is ${limits.maxCodeChars}`,\n )\n }\n const request: ISandboxRequest = { code, filename, limits }\n if (files) {\n request.modules = await collectModules(files, code, filename, approve, limits.maxCodeChars)\n request.hostOps = sandboxHostOps(files)\n }\n const hostCall = files\n ? createFileHost(files, approve, (file) =>\n agentRun?.emit({\n type: 'file.written',\n path: file.path,\n mediaType: file.mimeType,\n bytes: file.size,\n ...(agentRun.step ? { step: agentRun.step } : {}),\n }),\n )\n : undefined\n return queue(async () => {\n let worker: SandboxWorkerLike | undefined\n if (config.worker) {\n try {\n worker = config.worker()\n } catch (err) {\n // No Worker here (an old or locked-down environment): the page thread still isolates.\n warn(\n `[sandbox] sandbox.worker failed (${(err as Error)?.message ?? err}); running on the page thread`,\n )\n }\n }\n if (worker) {\n return runInWorker(portOf(worker), request, { hostCall, signal })\n }\n const startedAt = Date.now()\n const lib = await loadEngine(config.engine)\n const raw = await runGuest(lib, request, { hostCall })\n return { ...sanitizeSandboxResult(raw, limits), durationMs: Date.now() - startedAt }\n })\n }\n\n const withFiles = Boolean(files?.read)\n const runJs: Tool = tool({\n description: describeTool(limits, Boolean(files)),\n inputSchema: jsonSchema<RunJsInput>({\n type: 'object',\n properties: {\n code: {\n type: 'string',\n description:\n 'The program. Print with console.log; the value of the last expression is returned as \"result\".',\n },\n ...(withFiles\n ? {\n entry: {\n type: 'string',\n description:\n 'Instead of \"code\": the path of a workspace .js / .mjs file to run, e.g. \"/main.js\".',\n },\n }\n : {}),\n },\n ...(withFiles ? {} : { required: ['code'] }),\n additionalProperties: false,\n }),\n execute,\n })\n return {\n // It runs code: asked whenever the run acts on an MCP server's skill (tools/approval.ts).\n tools: { [RUN_JS_TOOL]: markCodeExecution(runJs) },\n notes: {\n planner: SANDBOX_PLANNER_NOTE,\n executor: sandboxPromptNote(Boolean(files)),\n synthesizer: SANDBOX_SYNTHESIZER_NOTE,\n },\n files: Boolean(files),\n thread: config.worker ? 'worker' : 'page',\n }\n}\n","import type { ToolSet } from 'ai'\nimport { fileToolBindingOf } from '../files/tools.js'\nimport {\n isTextMime,\n normalizePath,\n type VirtualFileInfo,\n type VirtualFileSystem,\n} from '../files/vfs.js'\nimport {\n moduleSpecifiersOf,\n resolveModulePath,\n SANDBOX_MAX_FILE_CHARS,\n SANDBOX_MAX_MODULE_CHARS_TOTAL,\n SANDBOX_MAX_MODULES,\n SANDBOX_MODULE_EXTENSIONS,\n type SandboxHostCall,\n type SandboxHostOp,\n} from './engine.js'\n\n/**\n * The workspace a sandbox is bound to: the virtual file system the agent's own file tools work\n * on, and - per operation - the NAME of the tool that grants it. The guest gets an operation\n * only when the agent has the tool for it (a read-only mount gives no `writeFile`), and every\n * call passes the consent gate under that tool's name, so a rule that denies `fs_write` denies\n * the guest's writes too.\n */\nexport interface SandboxFiles {\n vfs: VirtualFileSystem\n read?: string\n write?: string\n list?: string\n}\n\n/** The agent's consent gate, as a tool reaches it (`ToolRunContext.approve`). */\nexport type SandboxApprove = (toolName: string, input: unknown, readOnly: boolean) => Promise<void>\n\n/** Find the file tools among the mounted tools (the first file system that can be read wins). */\nexport const sandboxFilesOf = (tools: ToolSet): SandboxFiles | undefined => {\n let files: SandboxFiles | undefined\n for (const [name, t] of Object.entries(tools)) {\n const binding = fileToolBindingOf(t)\n if (!binding || binding.op === 'delete') continue\n if (!files) files = { vfs: binding.vfs }\n if (files.vfs !== binding.vfs) continue\n files[binding.op] ??= name\n }\n return files && (files.read || files.write || files.list) ? files : undefined\n}\n\nexport const sandboxHostOps = (files: SandboxFiles): SandboxHostOp[] => [\n ...(files.read ? (['readFile'] as const) : []),\n ...(files.write ? (['writeFile'] as const) : []),\n ...(files.list ? (['readdir'] as const) : []),\n]\n\nconst pathOf = (value: unknown, what: string): string => {\n if (typeof value !== 'string' || !value) throw new Error(`${what}: a path (string) is required`)\n // Throws on a path that climbs out of the root; there is nothing above it to reach.\n return normalizePath(value)\n}\n\n/** Read one workspace file as text, under the same rules as `fs_read` plus a size cap. */\nexport const readWorkspaceText = async (\n files: SandboxFiles,\n path: string,\n approve: SandboxApprove | undefined,\n maxChars: number,\n): Promise<string> => {\n if (!files.read) throw new Error('reading files is not available in this sandbox')\n await approve?.(files.read, { path }, true)\n const f = await files.vfs.read(path)\n if (!f) throw new Error(`no file \"${path}\"`)\n if (f.encoding === 'base64' && !isTextMime(f.mimeType)) {\n throw new Error(`\"${path}\" is a binary file (${f.mimeType}) and cannot be read as text`)\n }\n const text = f.encoding === 'base64' ? atob(f.content) : f.content\n if (text.length > maxChars) {\n throw new Error(`\"${path}\" is ${text.length} characters; the sandbox reads at most ${maxChars}`)\n }\n return text\n}\n\n/** Serves the guest's `fs` calls on the agent's side of the boundary. */\nexport const createFileHost =\n (\n files: SandboxFiles,\n approve: SandboxApprove | undefined,\n /** Told about every file the guest wrote, after the write succeeded (the run's `file.written`). */\n onWrite?: (file: VirtualFileInfo) => void,\n ): SandboxHostCall =>\n async (op, args) => {\n switch (op) {\n case 'readFile':\n return readWorkspaceText(\n files,\n pathOf(args[0], 'fs.readFile'),\n approve,\n SANDBOX_MAX_FILE_CHARS,\n )\n case 'writeFile': {\n if (!files.write) throw new Error('writing files is not available in this sandbox')\n const path = pathOf(args[0], 'fs.writeFile')\n const content = args[1]\n if (typeof content !== 'string')\n throw new Error('fs.writeFile: the content must be a string')\n if (content.length > SANDBOX_MAX_FILE_CHARS) {\n throw new Error(\n `fs.writeFile: ${content.length} characters; the sandbox writes at most ${SANDBOX_MAX_FILE_CHARS}`,\n )\n }\n await approve?.(files.write, { path, content }, false)\n const info = await files.vfs.write(path, content)\n onWrite?.(info)\n return undefined\n }\n case 'readdir': {\n if (!files.list) throw new Error('listing files is not available in this sandbox')\n const prefix =\n args[0] === undefined || args[0] === '/' ? '/' : pathOf(args[0], 'fs.readdir')\n await approve?.(files.list, { prefix }, true)\n return (await files.vfs.list(prefix)).map((f) => f.path)\n }\n default:\n throw new Error(`fs.${String(op).slice(0, 40)} is not available in this sandbox`)\n }\n }\n\n/**\n * The workspace modules a program refers to, by literal path, followed through their own\n * imports: what the guest's loader will be able to load. A file that is missing, too large, of\n * another kind, or outside the root is simply not handed over - the guest's `import` of it then\n * fails with the reason. Bounded in count and total size.\n */\nexport const collectModules = async (\n files: SandboxFiles,\n code: string,\n filename: string,\n approve: SandboxApprove | undefined,\n maxModuleChars: number,\n): Promise<Record<string, string>> => {\n const modules: Record<string, string> = {}\n if (!files.read) return modules\n const seen = new Set<string>()\n const queue: { source: string; base: string }[] = [{ source: code, base: filename }]\n let total = 0\n while (queue.length > 0) {\n const { source, base } = queue.shift() as { source: string; base: string }\n for (const spec of moduleSpecifiersOf(source)) {\n let path: string\n try {\n path = normalizePath(resolveModulePath(base, spec))\n } catch {\n continue\n }\n if (seen.has(path)) continue\n seen.add(path)\n if (!SANDBOX_MODULE_EXTENSIONS.some((ext) => path.toLowerCase().endsWith(ext))) continue\n if (seen.size > SANDBOX_MAX_MODULES) return modules\n let text: string\n try {\n text = await readWorkspaceText(files, path, approve, maxModuleChars)\n } catch {\n continue\n }\n if (total + text.length > SANDBOX_MAX_MODULE_CHARS_TOTAL) continue\n total += text.length\n modules[path] = text\n if (!path.toLowerCase().endsWith('.json')) queue.push({ source: text, base: path })\n }\n }\n return modules\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAY,YAAqC;;;ACqCnD,IAAM,iBAAiB,CAAC,UAA6C;AAC1E,MAAI;AACJ,aAAW,CAAC,MAAM,CAAC,KAAK,OAAO,QAAQ,KAAK,GAAG;AAC7C,UAAM,UAAU,kBAAkB,CAAC;AACnC,QAAI,CAAC,WAAW,QAAQ,OAAO,SAAU;AACzC,QAAI,CAAC,MAAO,SAAQ,EAAE,KAAK,QAAQ,IAAI;AACvC,QAAI,MAAM,QAAQ,QAAQ,IAAK;AAC/B,UAAM,QAAQ,EAAE,MAAM;AAAA,EACxB;AACA,SAAO,UAAU,MAAM,QAAQ,MAAM,SAAS,MAAM,QAAQ,QAAQ;AACtE;AAEO,IAAM,iBAAiB,CAAC,UAAyC;AAAA,EACtE,GAAI,MAAM,OAAQ,CAAC,UAAU,IAAc,CAAC;AAAA,EAC5C,GAAI,MAAM,QAAS,CAAC,WAAW,IAAc,CAAC;AAAA,EAC9C,GAAI,MAAM,OAAQ,CAAC,SAAS,IAAc,CAAC;AAC7C;AAEA,IAAM,SAAS,CAAC,OAAgB,SAAyB;AACvD,MAAI,OAAO,UAAU,YAAY,CAAC,MAAO,OAAM,IAAI,MAAM,GAAG,IAAI,+BAA+B;AAE/F,SAAO,cAAc,KAAK;AAC5B;AAGO,IAAM,oBAAoB,OAC/B,OACA,MACA,SACA,aACoB;AACpB,MAAI,CAAC,MAAM,KAAM,OAAM,IAAI,MAAM,gDAAgD;AACjF,QAAM,UAAU,MAAM,MAAM,EAAE,KAAK,GAAG,IAAI;AAC1C,QAAM,IAAI,MAAM,MAAM,IAAI,KAAK,IAAI;AACnC,MAAI,CAAC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,KAAK,CAAC;AAAA,MAC1C,aAAa;AAAA,IACf;AAAA,IACA,OAAO,QAAQ,KAAK;AAAA,IACpB,QAAQ,OAAO,SAAS,WAAW;AAAA,EACrC;AACF;","names":[]}
|
package/dist/secrets.cjs
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/secrets/index.ts
|
|
21
|
+
var secrets_exports = {};
|
|
22
|
+
__export(secrets_exports, {
|
|
23
|
+
IndexedDBVault: () => IndexedDBVault,
|
|
24
|
+
MemoryCredentialStore: () => MemoryCredentialStore,
|
|
25
|
+
VaultCredentialStore: () => VaultCredentialStore,
|
|
26
|
+
decryptJSON: () => decryptJSON,
|
|
27
|
+
encryptJSON: () => encryptJSON,
|
|
28
|
+
getOrCreateVaultKey: () => getOrCreateVaultKey
|
|
29
|
+
});
|
|
30
|
+
module.exports = __toCommonJS(secrets_exports);
|
|
31
|
+
|
|
32
|
+
// src/storage/db.ts
|
|
33
|
+
var import_idb = require("idb");
|
|
34
|
+
var KEYS_STORE = "keys";
|
|
35
|
+
var SECRETS_STORE = "secrets";
|
|
36
|
+
var SESSIONS_STORE = "sessions";
|
|
37
|
+
var FILES_STORE = "files";
|
|
38
|
+
var RUNS_STORE = "runs";
|
|
39
|
+
var DB_VERSION = 3;
|
|
40
|
+
var cache = /* @__PURE__ */ new Map();
|
|
41
|
+
var openAgentWebDB = (opts = {}) => {
|
|
42
|
+
const name = opts.dbName ?? "agent-web";
|
|
43
|
+
let p = cache.get(name);
|
|
44
|
+
if (!p) {
|
|
45
|
+
const opened = (0, import_idb.openDB)(name, DB_VERSION, {
|
|
46
|
+
upgrade(db) {
|
|
47
|
+
if (!db.objectStoreNames.contains(KEYS_STORE)) db.createObjectStore(KEYS_STORE);
|
|
48
|
+
if (!db.objectStoreNames.contains(SECRETS_STORE)) db.createObjectStore(SECRETS_STORE);
|
|
49
|
+
if (!db.objectStoreNames.contains(SESSIONS_STORE)) db.createObjectStore(SESSIONS_STORE);
|
|
50
|
+
if (!db.objectStoreNames.contains(FILES_STORE)) db.createObjectStore(FILES_STORE);
|
|
51
|
+
if (!db.objectStoreNames.contains(RUNS_STORE)) db.createObjectStore(RUNS_STORE);
|
|
52
|
+
},
|
|
53
|
+
// Another connection (another tab, or this one) deletes or upgrades the database: let it.
|
|
54
|
+
blocking(_current, _next, event) {
|
|
55
|
+
forget(name, opened);
|
|
56
|
+
event.target.close();
|
|
57
|
+
},
|
|
58
|
+
// Closed by the browser, not by us: a dead connection must not stay cached.
|
|
59
|
+
terminated() {
|
|
60
|
+
forget(name, opened);
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
p = opened;
|
|
64
|
+
cache.set(name, p);
|
|
65
|
+
p.catch(() => forget(name, opened));
|
|
66
|
+
}
|
|
67
|
+
return p;
|
|
68
|
+
};
|
|
69
|
+
var forget = (name, p) => {
|
|
70
|
+
if (cache.get(name) === p) cache.delete(name);
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
// src/secrets/crypto.ts
|
|
74
|
+
var KEY_ID = "vault-key-v1";
|
|
75
|
+
var webcrypto = () => {
|
|
76
|
+
const c = globalThis.crypto;
|
|
77
|
+
if (!c?.subtle || !c.getRandomValues) {
|
|
78
|
+
throw new Error("WebCrypto (crypto.subtle) is unavailable in this environment");
|
|
79
|
+
}
|
|
80
|
+
return c;
|
|
81
|
+
};
|
|
82
|
+
var loadOrCreateKey = async (db) => {
|
|
83
|
+
const existing = await db.get(KEYS_STORE, KEY_ID);
|
|
84
|
+
if (existing) return existing;
|
|
85
|
+
const key = await webcrypto().subtle.generateKey(
|
|
86
|
+
{ name: "AES-GCM", length: 256 },
|
|
87
|
+
/* extractable */
|
|
88
|
+
false,
|
|
89
|
+
["encrypt", "decrypt"]
|
|
90
|
+
);
|
|
91
|
+
const tx = db.transaction(KEYS_STORE, "readwrite");
|
|
92
|
+
const winner = await tx.store.get(KEY_ID);
|
|
93
|
+
if (winner) {
|
|
94
|
+
await tx.done;
|
|
95
|
+
return winner;
|
|
96
|
+
}
|
|
97
|
+
await tx.store.put(key, KEY_ID);
|
|
98
|
+
await tx.done;
|
|
99
|
+
return key;
|
|
100
|
+
};
|
|
101
|
+
var keyCache = /* @__PURE__ */ new WeakMap();
|
|
102
|
+
var vaultKeyOf = (db) => {
|
|
103
|
+
let p = keyCache.get(db);
|
|
104
|
+
if (!p) {
|
|
105
|
+
const loading = loadOrCreateKey(db);
|
|
106
|
+
p = loading;
|
|
107
|
+
keyCache.set(db, loading);
|
|
108
|
+
loading.catch(() => {
|
|
109
|
+
if (keyCache.get(db) === loading) keyCache.delete(db);
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
return p;
|
|
113
|
+
};
|
|
114
|
+
var getOrCreateVaultKey = async (dbName) => vaultKeyOf(await openAgentWebDB({ dbName }));
|
|
115
|
+
var textEncoder = new TextEncoder();
|
|
116
|
+
var textDecoder = new TextDecoder();
|
|
117
|
+
var encryptJSON = async (key, value) => {
|
|
118
|
+
const c = webcrypto();
|
|
119
|
+
const iv = c.getRandomValues(new Uint8Array(12));
|
|
120
|
+
const data = textEncoder.encode(JSON.stringify(value));
|
|
121
|
+
const ciphertext = await c.subtle.encrypt({ name: "AES-GCM", iv }, key, data);
|
|
122
|
+
return { iv, ciphertext };
|
|
123
|
+
};
|
|
124
|
+
var decryptJSON = async (key, blob) => {
|
|
125
|
+
const iv = new Uint8Array(blob.iv);
|
|
126
|
+
const plain = await webcrypto().subtle.decrypt({ name: "AES-GCM", iv }, key, blob.ciphertext);
|
|
127
|
+
return JSON.parse(textDecoder.decode(plain));
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
// src/secrets/vault.ts
|
|
131
|
+
var IndexedDBVault = class {
|
|
132
|
+
dbName;
|
|
133
|
+
constructor(opts = {}) {
|
|
134
|
+
this.dbName = opts.dbName;
|
|
135
|
+
}
|
|
136
|
+
/** Encrypt and store a secret string under `id`. */
|
|
137
|
+
async setSecret(id, value) {
|
|
138
|
+
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
139
|
+
const blob = await encryptJSON(await vaultKeyOf(db), value);
|
|
140
|
+
await db.put(SECRETS_STORE, blob, id);
|
|
141
|
+
}
|
|
142
|
+
/** Fetch and decrypt a secret, or undefined if absent. */
|
|
143
|
+
async getSecret(id) {
|
|
144
|
+
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
145
|
+
const blob = await db.get(SECRETS_STORE, id);
|
|
146
|
+
if (!blob) return void 0;
|
|
147
|
+
return decryptJSON(await vaultKeyOf(db), blob);
|
|
148
|
+
}
|
|
149
|
+
async deleteSecret(id) {
|
|
150
|
+
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
151
|
+
await db.delete(SECRETS_STORE, id);
|
|
152
|
+
}
|
|
153
|
+
async listSecretIds() {
|
|
154
|
+
const db = await openAgentWebDB({ dbName: this.dbName });
|
|
155
|
+
return (await db.getAllKeys(SECRETS_STORE)).map(String);
|
|
156
|
+
}
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
// src/sync/tab.ts
|
|
160
|
+
var TAB_TEST = /* @__PURE__ */ Symbol.for("@dudko.dev/agent-web:tab-test");
|
|
161
|
+
var SYNC_VERSION = 1;
|
|
162
|
+
var SYNC_ID_RE = /^[A-Za-z0-9_-]{1,64}$/;
|
|
163
|
+
var randomId = () => {
|
|
164
|
+
const c = globalThis.crypto;
|
|
165
|
+
if (c?.randomUUID) return c.randomUUID().replace(/-/g, "");
|
|
166
|
+
return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 12)}`;
|
|
167
|
+
};
|
|
168
|
+
var TABS = /* @__PURE__ */ Symbol.for("@dudko.dev/agent-web:tabs");
|
|
169
|
+
var tabs = globalThis[TABS] ??= /* @__PURE__ */ new Map();
|
|
170
|
+
var currentTab = () => {
|
|
171
|
+
const seam = globalThis[TAB_TEST];
|
|
172
|
+
const named = typeof seam === "function" ? seam() : void 0;
|
|
173
|
+
const key = typeof named === "string" ? named : "";
|
|
174
|
+
let tab = tabs.get(key);
|
|
175
|
+
if (!tab) {
|
|
176
|
+
tab = { id: randomId(), held: /* @__PURE__ */ new Set(), hubs: /* @__PURE__ */ new Map() };
|
|
177
|
+
tabs.set(key, tab);
|
|
178
|
+
}
|
|
179
|
+
return tab;
|
|
180
|
+
};
|
|
181
|
+
var hubOf = (tab, name) => {
|
|
182
|
+
const Channel = globalThis.BroadcastChannel;
|
|
183
|
+
if (typeof Channel !== "function") return void 0;
|
|
184
|
+
const known = tab.hubs.get(name);
|
|
185
|
+
if (known) return known;
|
|
186
|
+
let channel;
|
|
187
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
188
|
+
const open = () => {
|
|
189
|
+
if (channel) return channel;
|
|
190
|
+
const opened = new Channel(name);
|
|
191
|
+
opened.unref?.();
|
|
192
|
+
opened.onmessage = (event) => {
|
|
193
|
+
for (const listener of [...listeners]) {
|
|
194
|
+
try {
|
|
195
|
+
listener(event.data);
|
|
196
|
+
} catch {
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
};
|
|
200
|
+
channel = opened;
|
|
201
|
+
return opened;
|
|
202
|
+
};
|
|
203
|
+
const hub = {
|
|
204
|
+
post(message) {
|
|
205
|
+
try {
|
|
206
|
+
open().postMessage(message);
|
|
207
|
+
} catch {
|
|
208
|
+
}
|
|
209
|
+
},
|
|
210
|
+
listen(listener) {
|
|
211
|
+
try {
|
|
212
|
+
open();
|
|
213
|
+
} catch {
|
|
214
|
+
return () => void 0;
|
|
215
|
+
}
|
|
216
|
+
listeners.add(listener);
|
|
217
|
+
return () => {
|
|
218
|
+
listeners.delete(listener);
|
|
219
|
+
if (listeners.size === 0 && channel) {
|
|
220
|
+
channel.onmessage = null;
|
|
221
|
+
channel.close();
|
|
222
|
+
channel = void 0;
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
tab.hubs.set(name, hub);
|
|
228
|
+
return hub;
|
|
229
|
+
};
|
|
230
|
+
var isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
231
|
+
var scopeOf = (dbName) => encodeURIComponent(dbName);
|
|
232
|
+
|
|
233
|
+
// src/sync/notices.ts
|
|
234
|
+
var STORAGE_CHANGE_KINDS = [
|
|
235
|
+
"credentials",
|
|
236
|
+
"oauth",
|
|
237
|
+
"files",
|
|
238
|
+
"session",
|
|
239
|
+
"runs",
|
|
240
|
+
"skills",
|
|
241
|
+
"chats",
|
|
242
|
+
"host"
|
|
243
|
+
];
|
|
244
|
+
var OPS = ["put", "delete", "clear"];
|
|
245
|
+
var MAX_NOTICE_KEY_CHARS = 1024;
|
|
246
|
+
var MAX_NOTICE_NAMESPACE_CHARS = 256;
|
|
247
|
+
var KEYLESS = /* @__PURE__ */ new Set(["credentials", "oauth"]);
|
|
248
|
+
var storageChannelName = (dbName) => `@dudko.dev/agent-web/storage:${scopeOf(dbName)}`;
|
|
249
|
+
var nameOk = (value, max) => typeof value === "string" && value.length > 0 && value.length <= max;
|
|
250
|
+
var storageChangeOf = (data) => {
|
|
251
|
+
if (!isRecord(data) || data.v !== SYNC_VERSION || data.t !== "change") return void 0;
|
|
252
|
+
if (typeof data.from !== "string" || !SYNC_ID_RE.test(data.from)) return void 0;
|
|
253
|
+
const kind = data.kind;
|
|
254
|
+
const op = data.op;
|
|
255
|
+
if (!STORAGE_CHANGE_KINDS.includes(kind) || !OPS.includes(op)) return void 0;
|
|
256
|
+
if (data.key !== void 0 && (KEYLESS.has(kind) || !nameOk(data.key, MAX_NOTICE_KEY_CHARS))) {
|
|
257
|
+
return void 0;
|
|
258
|
+
}
|
|
259
|
+
if (data.ns !== void 0 && !nameOk(data.ns, MAX_NOTICE_NAMESPACE_CHARS)) return void 0;
|
|
260
|
+
return {
|
|
261
|
+
kind,
|
|
262
|
+
op,
|
|
263
|
+
...data.key !== void 0 ? { key: data.key } : {},
|
|
264
|
+
...data.ns !== void 0 ? { namespace: data.ns } : {}
|
|
265
|
+
};
|
|
266
|
+
};
|
|
267
|
+
var postStorageChangeFrom = (tab, dbName, change) => {
|
|
268
|
+
if (!dbName) return;
|
|
269
|
+
const message = {
|
|
270
|
+
v: SYNC_VERSION,
|
|
271
|
+
t: "change",
|
|
272
|
+
from: tab.id,
|
|
273
|
+
kind: change.kind,
|
|
274
|
+
op: change.op,
|
|
275
|
+
...change.key !== void 0 && !KEYLESS.has(change.kind) ? { key: change.key } : {},
|
|
276
|
+
...change.namespace !== void 0 ? { ns: change.namespace } : {}
|
|
277
|
+
};
|
|
278
|
+
if (!storageChangeOf(message)) return;
|
|
279
|
+
hubOf(tab, storageChannelName(dbName))?.post(message);
|
|
280
|
+
};
|
|
281
|
+
|
|
282
|
+
// src/secrets/store.ts
|
|
283
|
+
var VaultCredentialStore = class {
|
|
284
|
+
/** The database the vault lives in, and the name its change notices go out under. */
|
|
285
|
+
dbName;
|
|
286
|
+
vault;
|
|
287
|
+
tab;
|
|
288
|
+
constructor(opts = {}) {
|
|
289
|
+
this.dbName = opts.dbName ?? "agent-web";
|
|
290
|
+
this.vault = new IndexedDBVault({ ...opts, dbName: this.dbName });
|
|
291
|
+
this.tab = currentTab();
|
|
292
|
+
}
|
|
293
|
+
getApiKey(ref) {
|
|
294
|
+
return this.vault.getSecret(ref);
|
|
295
|
+
}
|
|
296
|
+
async setApiKey(ref, key) {
|
|
297
|
+
await this.vault.setSecret(ref, key);
|
|
298
|
+
postStorageChangeFrom(this.tab, this.dbName, { kind: "credentials", op: "put" });
|
|
299
|
+
}
|
|
300
|
+
async deleteApiKey(ref) {
|
|
301
|
+
await this.vault.deleteSecret(ref);
|
|
302
|
+
postStorageChangeFrom(this.tab, this.dbName, { kind: "credentials", op: "delete" });
|
|
303
|
+
}
|
|
304
|
+
};
|
|
305
|
+
var MemoryCredentialStore = class {
|
|
306
|
+
map = /* @__PURE__ */ new Map();
|
|
307
|
+
constructor(initial) {
|
|
308
|
+
if (initial) for (const [k, v] of Object.entries(initial)) this.map.set(k, v);
|
|
309
|
+
}
|
|
310
|
+
async getApiKey(ref) {
|
|
311
|
+
return this.map.get(ref);
|
|
312
|
+
}
|
|
313
|
+
async setApiKey(ref, key) {
|
|
314
|
+
this.map.set(ref, key);
|
|
315
|
+
}
|
|
316
|
+
async deleteApiKey(ref) {
|
|
317
|
+
this.map.delete(ref);
|
|
318
|
+
}
|
|
319
|
+
};
|
|
320
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
321
|
+
0 && (module.exports = {
|
|
322
|
+
IndexedDBVault,
|
|
323
|
+
MemoryCredentialStore,
|
|
324
|
+
VaultCredentialStore,
|
|
325
|
+
decryptJSON,
|
|
326
|
+
encryptJSON,
|
|
327
|
+
getOrCreateVaultKey
|
|
328
|
+
});
|
|
329
|
+
//# sourceMappingURL=secrets.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/secrets/index.ts","../src/storage/db.ts","../src/secrets/crypto.ts","../src/secrets/vault.ts","../src/sync/tab.ts","../src/sync/notices.ts","../src/secrets/store.ts"],"sourcesContent":["// The `./secrets` entry: the vault and the credential stores WITHOUT the agent. The main entry\n// carries the whole agent (`ai`, `zod`, the prompts and schemas at module scope): a page that\n// only stores or lists the user's keys - an onboarding screen, a settings form, the first script\n// of an app - imports them from here and loads `idb` and these files only\n// (`tests/secrets-entry.test.ts` checks the built graph). The same classes as the main entry's:\n// in an ESM build both import one chunk, so one connection cache and one key per database.\nexport { IndexedDBVault } from './vault.js'\nexport type { VaultOptions } from './vault.js'\nexport { VaultCredentialStore, MemoryCredentialStore } from './store.js'\nexport type { CredentialStore } from './store.js'\nexport { getOrCreateVaultKey, encryptJSON, decryptJSON } from './crypto.js'\nexport type { EncryptedBlob } from './crypto.js'\n","import { openDB, type IDBPDatabase } from 'idb'\n\nexport interface AgentWebDBOptions {\n /** Database name (default 'agent-web'). Use a distinct name to isolate apps. */\n dbName?: string\n}\n\nexport const KEYS_STORE = 'keys'\nexport const SECRETS_STORE = 'secrets'\nexport const SESSIONS_STORE = 'sessions'\nexport const FILES_STORE = 'files'\nexport const RUNS_STORE = 'runs'\n\n// v1: keys, secrets, sessions. v2: + files (the virtual file system). v3: + runs (checkpoints).\nconst DB_VERSION = 3\n\nlet cache = new Map<string, Promise<IDBPDatabase>>()\n\n/**\n * The single owner of the IndexedDB database. Every persistent store — the\n * non-extractable crypto key, encrypted secrets, and session transcripts —\n * lives under ONE database name + version. Centralising `openDB` here prevents\n * the classic bug where two modules open the same DB name with different store\n * sets and the second call throws a VersionError.\n *\n * One connection per name, shared by every store of the page - and never in another tab's way:\n * when another connection asks to delete or upgrade the database (`versionchange`: another tab's\n * `indexedDB.deleteDatabase`, or a newer copy of this package), this one is closed at once, so\n * that request goes ahead instead of waiting (blocked) for this tab to close. The browser lets the\n * transactions already under way finish first. A connection the browser closed by itself (site\n * data cleared, storage gone) is let go too. Either way the next use opens the database again:\n * after a deletion that is a NEW, EMPTY database at this version (every store of this package\n * starts from nothing - no key, no secret, no session, no file); after an upgrade by a newer copy,\n * the open fails with a `VersionError` until the page is reloaded with that copy.\n */\nexport const openAgentWebDB = (opts: AgentWebDBOptions = {}): Promise<IDBPDatabase> => {\n const name = opts.dbName ?? 'agent-web'\n let p = cache.get(name)\n if (!p) {\n const opened: Promise<IDBPDatabase> = openDB(name, DB_VERSION, {\n upgrade(db) {\n // Idempotent by store: an existing v1 database gains only what it lacks.\n if (!db.objectStoreNames.contains(KEYS_STORE)) db.createObjectStore(KEYS_STORE)\n if (!db.objectStoreNames.contains(SECRETS_STORE)) db.createObjectStore(SECRETS_STORE)\n if (!db.objectStoreNames.contains(SESSIONS_STORE)) db.createObjectStore(SESSIONS_STORE)\n if (!db.objectStoreNames.contains(FILES_STORE)) db.createObjectStore(FILES_STORE)\n if (!db.objectStoreNames.contains(RUNS_STORE)) db.createObjectStore(RUNS_STORE)\n },\n // Another connection (another tab, or this one) deletes or upgrades the database: let it.\n blocking(_current, _next, event) {\n forget(name, opened)\n ;(event.target as IDBDatabase).close()\n },\n // Closed by the browser, not by us: a dead connection must not stay cached.\n terminated() {\n forget(name, opened)\n },\n })\n p = opened\n cache.set(name, p)\n // A failed open (private mode, storage denied) must not stay cached, or\n // every later call would replay the same rejection forever.\n p.catch(() => forget(name, opened))\n }\n return p\n}\n\n/** Drop `name`'s cached connection - only if it is still `p` (a newer one stays). */\nconst forget = (name: string, p: Promise<IDBPDatabase>): void => {\n if (cache.get(name) === p) cache.delete(name)\n}\n\n/** Test hook: drop cached connections so a fresh (e.g. fake-indexeddb) DB is opened. */\nexport const _resetDBCache = (): void => {\n cache = new Map()\n}\n","import type { IDBPDatabase } from 'idb'\nimport { KEYS_STORE, openAgentWebDB } from '../storage/db.js'\n\nconst KEY_ID = 'vault-key-v1'\n\nconst webcrypto = (): Crypto => {\n const c = (globalThis as { crypto?: Crypto }).crypto\n if (!c?.subtle || !c.getRandomValues) {\n throw new Error('WebCrypto (crypto.subtle) is unavailable in this environment')\n }\n return c\n}\n\nconst loadOrCreateKey = async (db: IDBPDatabase): Promise<CryptoKey> => {\n const existing = (await db.get(KEYS_STORE, KEY_ID)) as CryptoKey | undefined\n if (existing) return existing\n const key = await webcrypto().subtle.generateKey(\n { name: 'AES-GCM', length: 256 },\n /* extractable */ false,\n ['encrypt', 'decrypt'],\n )\n // Double-check inside one readwrite transaction: another tab may have created\n // a key while ours was generating. Losing that race and overwriting would\n // leave the other tab's secrets permanently undecryptable.\n const tx = db.transaction(KEYS_STORE, 'readwrite')\n const winner = (await tx.store.get(KEY_ID)) as CryptoKey | undefined\n if (winner) {\n await tx.done\n return winner\n }\n await tx.store.put(key, KEY_ID)\n await tx.done\n return key\n}\n\n/**\n * The key of each CONNECTION, not of each database name: a database deleted under this page (by\n * another tab) and opened again is a new database, without the old key - a key kept by name would\n * go on encrypting under a key that database does not hold, and those secrets could never be read\n * after a reload. A new connection reads (or makes) the key of the database it is open on.\n */\nconst keyCache = new WeakMap<IDBPDatabase, Promise<CryptoKey>>()\n\n/** The vault key of the database `db` is open on (read once per connection, or made). */\nexport const vaultKeyOf = (db: IDBPDatabase): Promise<CryptoKey> => {\n let p = keyCache.get(db)\n if (!p) {\n const loading = loadOrCreateKey(db)\n p = loading\n keyCache.set(db, loading)\n loading.catch(() => {\n if (keyCache.get(db) === loading) keyCache.delete(db)\n })\n }\n return p\n}\n\n/**\n * Fetch (or lazily create) the vault's AES-GCM key. The key is generated\n * NON-EXTRACTABLE and stored as a live `CryptoKey` in IndexedDB — a CryptoKey\n * is structured-cloneable, so it persists across reloads WITHOUT its raw bytes\n * ever being exposed to JavaScript. Not even in-page script can read it out; it\n * can only be used to encrypt / decrypt. That is what makes at-rest storage of\n * the secrets meaningful (see IndexedDBVault's threat model).\n *\n * Concurrent callers share one in-flight promise per connection, and creation is\n * double-checked in a single IDB transaction, so two racing writers can never\n * end up encrypting under different keys. It is the key of the database as it is NOW: after\n * another tab deleted it, the key of the new one.\n */\nexport const getOrCreateVaultKey = async (dbName?: string): Promise<CryptoKey> =>\n vaultKeyOf(await openAgentWebDB({ dbName }))\n\nexport interface EncryptedBlob {\n /** 96-bit random IV, fresh per write. */\n iv: Uint8Array\n ciphertext: ArrayBuffer\n}\n\nconst textEncoder = new TextEncoder()\nconst textDecoder = new TextDecoder()\n\n/** Encrypt a JSON-serialisable value with a fresh 96-bit IV (AES-GCM). */\nexport const encryptJSON = async (key: CryptoKey, value: unknown): Promise<EncryptedBlob> => {\n const c = webcrypto()\n const iv = c.getRandomValues(new Uint8Array(12))\n const data = textEncoder.encode(JSON.stringify(value))\n const ciphertext = await c.subtle.encrypt({ name: 'AES-GCM', iv }, key, data)\n return { iv, ciphertext }\n}\n\n/** Decrypt a blob produced by encryptJSON. Throws if the key or blob don't match. */\nexport const decryptJSON = async <T = unknown>(key: CryptoKey, blob: EncryptedBlob): Promise<T> => {\n // Copy the IV into a fresh ArrayBuffer-backed view: after a round-trip through\n // IndexedDB its element buffer is typed as ArrayBufferLike, which no longer\n // satisfies BufferSource under TS's stricter typed-array generics.\n const iv = new Uint8Array(blob.iv)\n const plain = await webcrypto().subtle.decrypt({ name: 'AES-GCM', iv }, key, blob.ciphertext)\n return JSON.parse(textDecoder.decode(plain)) as T\n}\n","import { openAgentWebDB, SECRETS_STORE } from '../storage/db.js'\nimport { decryptJSON, encryptJSON, vaultKeyOf, type EncryptedBlob } from './crypto.js'\n\nexport interface VaultOptions {\n /** Database name, forwarded to the shared IDB owner (default 'agent-web'). */\n dbName?: string\n}\n\n/**\n * Encrypted key/value secret store backed by IndexedDB. Values are encrypted at\n * rest with the non-extractable AES-GCM vault key (see crypto.ts).\n *\n * ── THREAT MODEL (read before shipping any app-owned key to a browser) ──\n * This vault PROTECTS secrets **at rest** — an IndexedDB / disk dump yields\n * only ciphertext — and against **casual DevTools inspection** — no plaintext\n * key is stored, and the AES key cannot be exported even by in-page script.\n *\n * It does **NOT** defend against **active XSS on your origin**: any script that\n * already runs on the page can call `getSecret()`, or use the live `CryptoKey`\n * to decrypt. Browser storage is not a secrets manager.\n *\n * Therefore this vault is for the **end user's OWN key on their OWN device**\n * (bring-your-own-key). A shared, app-owned key must NEVER reach the client —\n * put it behind a server proxy (`ProviderModelSpec.baseURL`) or the Vercel AI\n * Gateway instead.\n */\nexport class IndexedDBVault {\n private readonly dbName?: string\n\n constructor(opts: VaultOptions = {}) {\n this.dbName = opts.dbName\n }\n\n /** Encrypt and store a secret string under `id`. */\n async setSecret(id: string, value: string): Promise<void> {\n // ONE connection for the key and the write: the secret is written under the key of the very\n // database it lands in. A database deleted by another tab while this encrypts closes this\n // connection, and the write then fails (the browser's InvalidStateError) - never a secret in\n // the new database under a key it does not hold. The next call opens the new one.\n const db = await openAgentWebDB({ dbName: this.dbName })\n const blob = await encryptJSON(await vaultKeyOf(db), value)\n await db.put(SECRETS_STORE, blob, id)\n }\n\n /** Fetch and decrypt a secret, or undefined if absent. */\n async getSecret(id: string): Promise<string | undefined> {\n const db = await openAgentWebDB({ dbName: this.dbName })\n const blob = (await db.get(SECRETS_STORE, id)) as EncryptedBlob | undefined\n if (!blob) return undefined\n return decryptJSON<string>(await vaultKeyOf(db), blob)\n }\n\n async deleteSecret(id: string): Promise<void> {\n const db = await openAgentWebDB({ dbName: this.dbName })\n await db.delete(SECRETS_STORE, id)\n }\n\n async listSecretIds(): Promise<string[]> {\n const db = await openAgentWebDB({ dbName: this.dbName })\n return (await db.getAllKeys(SECRETS_STORE)).map(String)\n }\n}\n","/**\n * Several tabs of one origin.\n *\n * Everything this package keeps lives in IndexedDB, and every tab (and installed PWA window) of\n * the origin shares it - but nothing told one tab what another did. This module is the plumbing\n * the rest of `sync/` stands on:\n *\n * - which TAB this is (one per JS realm): a random id, the Web Locks it holds, and\n * - one `BroadcastChannel` per name per tab (a hub), shared by everything in the tab that posts\n * or listens under that name. A channel never delivers a message to itself, so a tab never\n * hears its own messages - only the other tabs'.\n *\n * Browser APIs only, no dependency; every part is a no-op where the browser lacks the API\n * (`BroadcastChannel`, `navigator.locks`).\n *\n * Two test seams, NOT API (not exported from the package, never documented as options): a\n * function under `Symbol.for('@dudko.dev/agent-web:tab-test')` on `globalThis` names the tab a\n * caller is in (tests run two \"tabs\" in one Node process - Node's BroadcastChannel delivers\n * between instances of one process), and a LockManager-like object under\n * `Symbol.for('@dudko.dev/agent-web:locks-test')` stands in for `navigator.locks` (Node 22 has none;\n * Node 24+ has a real one, shared by the whole process). The seam wins over a native manager; set\n * to `null` it means \"this runtime has no Web Locks\", whatever the runtime has. The real API path\n * is tested in a real browser (the React package's e2e) and on Node's own Web Locks where present\n * (`tests/native-locks.test.ts`).\n */\n\nconst TAB_TEST = Symbol.for('@dudko.dev/agent-web:tab-test')\nconst LOCKS_TEST = Symbol.for('@dudko.dev/agent-web:locks-test')\n\n/** What every message on a channel of this package carries: the shape's version. */\nexport const SYNC_VERSION = 1\n\n/** Ids that cross a channel: a tab's, a watcher's, a request's. */\nexport const SYNC_ID_RE = /^[A-Za-z0-9_-]{1,64}$/\n\nexport interface Hub {\n /** Post to the OTHER tabs listening under this name (never to this tab). */\n post(message: unknown): void\n /** Hear the other tabs. Returns the unsubscribe; the channel closes with its last listener. */\n listen(listener: (data: unknown) => void): () => void\n}\n\nexport interface Tab {\n readonly id: string\n /** The session locks this tab holds right now (their names). */\n readonly held: Set<string>\n readonly hubs: Map<string, Hub>\n}\n\nconst randomId = (): string => {\n const c = globalThis.crypto\n if (c?.randomUUID) return c.randomUUID().replace(/-/g, '')\n return `${Date.now().toString(36)}${Math.random().toString(36).slice(2, 12)}`\n}\n\n// One registry per REALM, not per copy of this library: two copies in one page (an ESM and a CJS\n// build, two bundles) share the tab - its id, its held locks and its channels - so they never hear\n// each other as two tabs. The shape (`id`, `held`, `hubs` with `post` / `listen`) is the\n// contract between copies; keep it.\nconst TABS = Symbol.for('@dudko.dev/agent-web:tabs')\nconst tabs: Map<string, Tab> = ((globalThis as Record<symbol, unknown>)[TABS] ??= new Map<\n string,\n Tab\n>()) as Map<string, Tab>\n\n/** The tab the caller is in. In a browser: one per realm. */\nexport const currentTab = (): Tab => {\n const seam = (globalThis as Record<symbol, unknown>)[TAB_TEST]\n const named = typeof seam === 'function' ? (seam as () => unknown)() : undefined\n const key = typeof named === 'string' ? named : ''\n let tab = tabs.get(key)\n if (!tab) {\n tab = { id: randomId(), held: new Set(), hubs: new Map() }\n tabs.set(key, tab)\n }\n return tab\n}\n\ntype BroadcastChannelLike = {\n postMessage(message: unknown): void\n close(): void\n onmessage: ((event: { data: unknown }) => void) | null\n unref?: () => void\n}\n\n/** The tab's hub for `name`; undefined where there is no BroadcastChannel. */\nexport const hubOf = (tab: Tab, name: string): Hub | undefined => {\n const Channel = (globalThis as { BroadcastChannel?: new (name: string) => BroadcastChannelLike })\n .BroadcastChannel\n if (typeof Channel !== 'function') return undefined\n const known = tab.hubs.get(name)\n if (known) return known\n let channel: BroadcastChannelLike | undefined\n const listeners = new Set<(data: unknown) => void>()\n const open = (): BroadcastChannelLike => {\n if (channel) return channel\n const opened = new Channel(name)\n // Node: an open channel would keep the process alive. Browsers have no such method.\n opened.unref?.()\n opened.onmessage = (event) => {\n for (const listener of [...listeners]) {\n try {\n listener(event.data)\n } catch {\n /* one bad listener must not silence the others */\n }\n }\n }\n channel = opened\n return opened\n }\n const hub: Hub = {\n post(message) {\n try {\n open().postMessage(message)\n } catch {\n /* a notice is best-effort: it must never break the write it reports */\n }\n },\n listen(listener) {\n try {\n open()\n } catch {\n return () => undefined\n }\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n if (listeners.size === 0 && channel) {\n channel.onmessage = null\n channel.close()\n channel = undefined\n }\n }\n },\n }\n tab.hubs.set(name, hub)\n return hub\n}\n\n/** The subset of the Web Locks API used here. */\nexport interface LockManagerLike {\n request(\n name: string,\n options: { mode?: 'exclusive' | 'shared'; ifAvailable?: boolean; signal?: AbortSignal },\n callback: (lock: unknown) => unknown,\n ): Promise<unknown>\n /** Who holds what (`navigator.locks.query()`); a watcher reads it, it never takes the lock. */\n query?(): Promise<{ held?: { name?: string; mode?: string }[] }>\n}\n\n/** True while someone holds `name` EXCLUSIVELY (a run); undefined when it cannot be asked. */\nexport const heldExclusively = async (\n locks: LockManagerLike,\n name: string,\n): Promise<boolean | undefined> => {\n if (typeof locks.query !== 'function') return undefined\n try {\n const state = await locks.query()\n return (state?.held ?? []).some((l) => l?.name === name && l?.mode !== 'shared')\n } catch {\n return undefined\n }\n}\n\n/** `navigator.locks`, or the test seam; undefined where the browser has none. */\nexport const lockManager = (): LockManagerLike | undefined => {\n const seam = (globalThis as Record<symbol, unknown>)[LOCKS_TEST]\n // A test says \"no Web Locks here\" - also on a runtime that has them (Node 24+).\n if (seam === null) return undefined\n if (seam && typeof (seam as LockManagerLike).request === 'function') {\n return seam as LockManagerLike\n }\n const locks = (globalThis as { navigator?: { locks?: LockManagerLike } }).navigator?.locks\n return locks && typeof locks.request === 'function' ? locks : undefined\n}\n\n/** A plain object (not an array, not null): what every message must be before it is read. */\nexport const isRecord = (value: unknown): value is Record<string, unknown> =>\n typeof value === 'object' && value !== null && !Array.isArray(value)\n\n/** The name a database's channels and locks are under: one app's never meets another's. */\nexport const scopeOf = (dbName: string): string => encodeURIComponent(dbName)\n\n/** A fresh id for a watcher or a request. */\nexport const newSyncId = (): string => randomId().slice(0, 32)\n","import { currentTab, hubOf, isRecord, scopeOf, SYNC_ID_RE, SYNC_VERSION, type Tab } from './tab.js'\n\n/**\n * Change notices: after a write to IndexedDB COMMITS, the store that made it tells the other tabs\n * of the origin \"this changed\" - never what it changed to. A notice carries the kind of store, the\n * operation and at most a name (a path, a session id); never a value, a file's content, a message,\n * a key. A tab that hears one reads the store again if it shows that data.\n *\n * One channel per database name (`dbName`), so two apps on one origin with different databases\n * never hear each other. A tab does not hear its own notices. Nothing is sent from an in-memory\n * store (nothing is shared), and nothing anywhere without BroadcastChannel.\n */\n\n/**\n * The stores that announce their writes:\n * - `credentials` - `VaultCredentialStore` (an API key stored or removed). No `key`.\n * - `oauth` - `VaultOAuthStorage` (an MCP server's OAuth record). No `key`.\n * - `files` - `VirtualFileSystem`: `key` = the path, `namespace` = the file system's namespace.\n * - `session` - `IndexedDBStore` (the agent's memory): `key` = the session id.\n * - `runs` - `IndexedDBRunStore` (checkpoints): `key` = the run id.\n * - `skills` - `VfsSkillStore` (the agent's lessons): `key` = the lesson's name, `namespace` =\n * the store's folder.\n * - `chats` - the React package's `ChatHistoryStore`: `key` = the chat id.\n * - `host` - a store of the host's own that is none of the above (`postStorageChange`): `key` =\n * which record, `namespace` = which of the host's stores - names the host chose, never a value.\n */\nexport type StorageChangeKind =\n 'credentials' | 'oauth' | 'files' | 'session' | 'runs' | 'skills' | 'chats' | 'host'\n\n/** `put` = written (created or replaced), `delete` = one removed, `clear` = all of them removed. */\nexport type StorageChangeOp = 'put' | 'delete' | 'clear'\n\nexport interface StorageChange {\n kind: StorageChangeKind\n op: StorageChangeOp\n /** Which one (see `StorageChangeKind`); absent for `clear` and for the kinds that carry none. */\n key?: string\n /** `files`: the file system's namespace; `skills`: the store's folder; `host`: which store. */\n namespace?: string\n}\n\nexport const STORAGE_CHANGE_KINDS: readonly StorageChangeKind[] = [\n 'credentials',\n 'oauth',\n 'files',\n 'session',\n 'runs',\n 'skills',\n 'chats',\n 'host',\n]\nconst OPS: readonly StorageChangeOp[] = ['put', 'delete', 'clear']\n// A notice names, it does not describe: a path, an id. Longer is not a name.\nexport const MAX_NOTICE_KEY_CHARS = 1024\nexport const MAX_NOTICE_NAMESPACE_CHARS = 256\n// The kinds whose name is withheld (see docs/security.md): a vault id may be an MCP server's URL\n// with its query string, and a listener re-reads what it shows anyway.\nconst KEYLESS: ReadonlySet<StorageChangeKind> = new Set(['credentials', 'oauth'])\n\n/** The channel a database's notices go out on. */\nexport const storageChannelName = (dbName: string): string =>\n `@dudko.dev/agent-web/storage:${scopeOf(dbName)}`\n\nconst nameOk = (value: unknown, max: number): value is string =>\n typeof value === 'string' && value.length > 0 && value.length <= max\n\n/**\n * What a message on the channel says, or undefined when it is not a notice of this shape. The\n * channel is open to every page of the origin, so a message is checked before anyone reads it:\n * a known kind and op, a name of bounded length or none (none at all for the keyless kinds), and\n * nothing else is passed on.\n */\nexport const storageChangeOf = (data: unknown): StorageChange | undefined => {\n if (!isRecord(data) || data.v !== SYNC_VERSION || data.t !== 'change') return undefined\n if (typeof data.from !== 'string' || !SYNC_ID_RE.test(data.from)) return undefined\n const kind = data.kind as StorageChangeKind\n const op = data.op as StorageChangeOp\n if (!STORAGE_CHANGE_KINDS.includes(kind) || !OPS.includes(op)) return undefined\n if (data.key !== undefined && (KEYLESS.has(kind) || !nameOk(data.key, MAX_NOTICE_KEY_CHARS))) {\n return undefined\n }\n if (data.ns !== undefined && !nameOk(data.ns, MAX_NOTICE_NAMESPACE_CHARS)) return undefined\n return {\n kind,\n op,\n ...(data.key !== undefined ? { key: data.key as string } : {}),\n ...(data.ns !== undefined ? { namespace: data.ns as string } : {}),\n }\n}\n\n/** Post a notice from `tab` (a store passes the tab it was made in). */\nexport const postStorageChangeFrom = (\n tab: Tab,\n dbName: string | undefined,\n change: StorageChange,\n): void => {\n if (!dbName) return\n const message = {\n v: SYNC_VERSION,\n t: 'change',\n from: tab.id,\n kind: change.kind,\n op: change.op,\n ...(change.key !== undefined && !KEYLESS.has(change.kind) ? { key: change.key } : {}),\n ...(change.namespace !== undefined ? { ns: change.namespace } : {}),\n }\n // What a listener would refuse is not sent: a store with a bad name says nothing.\n if (!storageChangeOf(message)) return\n hubOf(tab, storageChannelName(dbName))?.post(message)\n}\n\n/**\n * Tell the other tabs that a store in database `dbName` changed - for a store of your own on\n * IndexedDB (the built-in ones post their own): one of the built-in kinds when it keeps that kind\n * of thing, `host` for anything else (`namespace` names which of your stores, `key` which record).\n * Call it AFTER the write committed. Never put a value in it: a notice says which, not what. A\n * no-op without `dbName` or BroadcastChannel; a notice of the wrong shape is dropped.\n */\nexport const postStorageChange = (dbName: string | undefined, change: StorageChange): void =>\n postStorageChangeFrom(currentTab(), dbName, change)\n\n/**\n * Hear the OTHER tabs' notices for database `dbName` (default database of the built-in stores:\n * `'agent-web'`; the React package's chat history: `'agent-web-react'`). This tab's own writes\n * are not reported - you made them. Returns the unsubscribe. A no-op (and a no-op unsubscribe)\n * without `dbName` or BroadcastChannel.\n */\nexport const onStorageChange = (\n dbName: string | undefined,\n listener: (change: StorageChange) => void,\n): (() => void) => {\n if (!dbName) return () => undefined\n const tab = currentTab()\n const hub = hubOf(tab, storageChannelName(dbName))\n if (!hub) return () => undefined\n // The tab's one channel for the name never delivers to itself: its own posts do not come back.\n return hub.listen((data) => {\n const change = storageChangeOf(data)\n if (change) listener(change)\n })\n}\n","import { postStorageChangeFrom } from '../sync/notices.js'\nimport { currentTab, type Tab } from '../sync/tab.js'\nimport { IndexedDBVault, type VaultOptions } from './vault.js'\n\n/**\n * The seam the provider registry uses to fetch API keys at model-build time.\n * Swap in any backend: the encrypted vault (default), an in-memory map (tests /\n * SSR), or a `fetch` to your own short-lived-token endpoint.\n */\nexport interface CredentialStore {\n getApiKey(ref: string): Promise<string | undefined>\n setApiKey(ref: string, key: string): Promise<void>\n deleteApiKey(ref: string): Promise<void>\n}\n\n/**\n * Default CredentialStore: encrypted, IndexedDB-backed (see IndexedDBVault). Every tab of the\n * origin shares it: a key stored or removed tells the other tabs that SOMETHING changed (a\n * `credentials` notice: no ref, never a key - see `onStorageChange`).\n */\nexport class VaultCredentialStore implements CredentialStore {\n /** The database the vault lives in, and the name its change notices go out under. */\n readonly dbName: string\n private readonly vault: IndexedDBVault\n private readonly tab: Tab\n\n constructor(opts: VaultOptions = {}) {\n this.dbName = opts.dbName ?? 'agent-web'\n this.vault = new IndexedDBVault({ ...opts, dbName: this.dbName })\n this.tab = currentTab()\n }\n\n getApiKey(ref: string): Promise<string | undefined> {\n return this.vault.getSecret(ref)\n }\n async setApiKey(ref: string, key: string): Promise<void> {\n await this.vault.setSecret(ref, key)\n postStorageChangeFrom(this.tab, this.dbName, { kind: 'credentials', op: 'put' })\n }\n async deleteApiKey(ref: string): Promise<void> {\n await this.vault.deleteSecret(ref)\n postStorageChangeFrom(this.tab, this.dbName, { kind: 'credentials', op: 'delete' })\n }\n}\n\n/** Non-persistent CredentialStore for tests / SSR / ephemeral sessions. */\nexport class MemoryCredentialStore implements CredentialStore {\n private readonly map = new Map<string, string>()\n\n constructor(initial?: Record<string, string>) {\n if (initial) for (const [k, v] of Object.entries(initial)) this.map.set(k, v)\n }\n\n async getApiKey(ref: string): Promise<string | undefined> {\n return this.map.get(ref)\n }\n async setApiKey(ref: string, key: string): Promise<void> {\n this.map.set(ref, key)\n }\n async deleteApiKey(ref: string): Promise<void> {\n this.map.delete(ref)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAA0C;AAOnC,IAAM,aAAa;AACnB,IAAM,gBAAgB;AACtB,IAAM,iBAAiB;AACvB,IAAM,cAAc;AACpB,IAAM,aAAa;AAG1B,IAAM,aAAa;AAEnB,IAAI,QAAQ,oBAAI,IAAmC;AAmB5C,IAAM,iBAAiB,CAAC,OAA0B,CAAC,MAA6B;AACrF,QAAM,OAAO,KAAK,UAAU;AAC5B,MAAI,IAAI,MAAM,IAAI,IAAI;AACtB,MAAI,CAAC,GAAG;AACN,UAAM,aAAgC,mBAAO,MAAM,YAAY;AAAA,MAC7D,QAAQ,IAAI;AAEV,YAAI,CAAC,GAAG,iBAAiB,SAAS,UAAU,EAAG,IAAG,kBAAkB,UAAU;AAC9E,YAAI,CAAC,GAAG,iBAAiB,SAAS,aAAa,EAAG,IAAG,kBAAkB,aAAa;AACpF,YAAI,CAAC,GAAG,iBAAiB,SAAS,cAAc,EAAG,IAAG,kBAAkB,cAAc;AACtF,YAAI,CAAC,GAAG,iBAAiB,SAAS,WAAW,EAAG,IAAG,kBAAkB,WAAW;AAChF,YAAI,CAAC,GAAG,iBAAiB,SAAS,UAAU,EAAG,IAAG,kBAAkB,UAAU;AAAA,MAChF;AAAA;AAAA,MAEA,SAAS,UAAU,OAAO,OAAO;AAC/B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I,KAAK,GAAG;AAAA,EACvB;AAAA,EACA,MAAM,aAAa,KAA4B;AAC7C,SAAK,IAAI,OAAO,GAAG;AAAA,EACrB;AACF;","names":[]}
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { V as VaultOptions } from './vault-BBGybouF.cjs';
|
|
2
|
+
export { I as IndexedDBVault } from './vault-BBGybouF.cjs';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The seam the provider registry uses to fetch API keys at model-build time.
|
|
6
|
+
* Swap in any backend: the encrypted vault (default), an in-memory map (tests /
|
|
7
|
+
* SSR), or a `fetch` to your own short-lived-token endpoint.
|
|
8
|
+
*/
|
|
9
|
+
interface CredentialStore {
|
|
10
|
+
getApiKey(ref: string): Promise<string | undefined>;
|
|
11
|
+
setApiKey(ref: string, key: string): Promise<void>;
|
|
12
|
+
deleteApiKey(ref: string): Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
/**
|
|
15
|
+
* Default CredentialStore: encrypted, IndexedDB-backed (see IndexedDBVault). Every tab of the
|
|
16
|
+
* origin shares it: a key stored or removed tells the other tabs that SOMETHING changed (a
|
|
17
|
+
* `credentials` notice: no ref, never a key - see `onStorageChange`).
|
|
18
|
+
*/
|
|
19
|
+
declare class VaultCredentialStore implements CredentialStore {
|
|
20
|
+
/** The database the vault lives in, and the name its change notices go out under. */
|
|
21
|
+
readonly dbName: string;
|
|
22
|
+
private readonly vault;
|
|
23
|
+
private readonly tab;
|
|
24
|
+
constructor(opts?: VaultOptions);
|
|
25
|
+
getApiKey(ref: string): Promise<string | undefined>;
|
|
26
|
+
setApiKey(ref: string, key: string): Promise<void>;
|
|
27
|
+
deleteApiKey(ref: string): Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
/** Non-persistent CredentialStore for tests / SSR / ephemeral sessions. */
|
|
30
|
+
declare class MemoryCredentialStore implements CredentialStore {
|
|
31
|
+
private readonly map;
|
|
32
|
+
constructor(initial?: Record<string, string>);
|
|
33
|
+
getApiKey(ref: string): Promise<string | undefined>;
|
|
34
|
+
setApiKey(ref: string, key: string): Promise<void>;
|
|
35
|
+
deleteApiKey(ref: string): Promise<void>;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Fetch (or lazily create) the vault's AES-GCM key. The key is generated
|
|
40
|
+
* NON-EXTRACTABLE and stored as a live `CryptoKey` in IndexedDB — a CryptoKey
|
|
41
|
+
* is structured-cloneable, so it persists across reloads WITHOUT its raw bytes
|
|
42
|
+
* ever being exposed to JavaScript. Not even in-page script can read it out; it
|
|
43
|
+
* can only be used to encrypt / decrypt. That is what makes at-rest storage of
|
|
44
|
+
* the secrets meaningful (see IndexedDBVault's threat model).
|
|
45
|
+
*
|
|
46
|
+
* Concurrent callers share one in-flight promise per connection, and creation is
|
|
47
|
+
* double-checked in a single IDB transaction, so two racing writers can never
|
|
48
|
+
* end up encrypting under different keys. It is the key of the database as it is NOW: after
|
|
49
|
+
* another tab deleted it, the key of the new one.
|
|
50
|
+
*/
|
|
51
|
+
declare const getOrCreateVaultKey: (dbName?: string) => Promise<CryptoKey>;
|
|
52
|
+
interface EncryptedBlob {
|
|
53
|
+
/** 96-bit random IV, fresh per write. */
|
|
54
|
+
iv: Uint8Array;
|
|
55
|
+
ciphertext: ArrayBuffer;
|
|
56
|
+
}
|
|
57
|
+
/** Encrypt a JSON-serialisable value with a fresh 96-bit IV (AES-GCM). */
|
|
58
|
+
declare const encryptJSON: (key: CryptoKey, value: unknown) => Promise<EncryptedBlob>;
|
|
59
|
+
/** Decrypt a blob produced by encryptJSON. Throws if the key or blob don't match. */
|
|
60
|
+
declare const decryptJSON: <T = unknown>(key: CryptoKey, blob: EncryptedBlob) => Promise<T>;
|
|
61
|
+
|
|
62
|
+
export { MemoryCredentialStore, VaultCredentialStore, VaultOptions, decryptJSON, encryptJSON, getOrCreateVaultKey };
|
|
63
|
+
export type { CredentialStore, EncryptedBlob };
|