@dudko.dev/agent-web 0.0.50 → 0.0.52
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 +49 -4
- package/dist/agent-web.js +173 -165
- package/dist/agent-web.js.map +1 -1
- package/dist/{chunk-3V27UZT6.js → chunk-DOWC4CFZ.js} +257 -3
- package/dist/chunk-DOWC4CFZ.js.map +1 -0
- package/dist/{chunk-IT77BVAD.js → chunk-HXUR2SG5.js} +2 -2
- package/dist/{chunk-JTZEUPIG.js → chunk-NUL6QEAX.js} +49 -49
- package/dist/chunk-NUL6QEAX.js.map +1 -0
- package/dist/{chunk-6XHCPSZE.js → chunk-QWOKTI62.js} +58 -6
- package/dist/chunk-QWOKTI62.js.map +1 -0
- package/dist/chunk-R5VCITT3.js +192 -0
- package/dist/chunk-R5VCITT3.js.map +1 -0
- package/dist/{chunk-7Y5UC6L7.js → chunk-SVGIGIRR.js} +3 -3
- package/dist/fit-reference-worker.cjs +158 -0
- package/dist/fit-reference-worker.cjs.map +1 -0
- package/dist/fit-reference-worker.d.cts +1 -0
- package/dist/fit-reference-worker.d.ts +1 -0
- package/dist/fit-reference-worker.js +16 -0
- package/dist/fit-reference-worker.js.map +1 -0
- package/dist/index.cjs +1366 -366
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +130 -72
- package/dist/index.d.ts +130 -72
- package/dist/index.js +589 -89
- package/dist/index.js.map +1 -1
- package/dist/mcp.js +2 -2
- package/dist/media-fit-worker-Do1qzteo.d.cts +159 -0
- package/dist/media-fit-worker-Do1qzteo.d.ts +159 -0
- package/dist/{sandbox-IGTCMOOX.js → sandbox-QNEDQZTA.js} +3 -3
- package/dist/secrets.js +3 -3
- package/dist/{webllm-BEL5A4OF.js → webllm-EZSJGU6P.js} +2 -2
- package/package.json +14 -2
- package/dist/chunk-3V27UZT6.js.map +0 -1
- package/dist/chunk-6XHCPSZE.js.map +0 -1
- package/dist/chunk-JTZEUPIG.js.map +0 -1
- /package/dist/{chunk-IT77BVAD.js.map → chunk-HXUR2SG5.js.map} +0 -0
- /package/dist/{chunk-7Y5UC6L7.js.map → chunk-SVGIGIRR.js.map} +0 -0
- /package/dist/{sandbox-IGTCMOOX.js.map → sandbox-QNEDQZTA.js.map} +0 -0
- /package/dist/{webllm-BEL5A4OF.js.map → webllm-EZSJGU6P.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/storage/db.ts","../src/sync/tab.ts","../src/sync/notices.ts"],"sourcesContent":["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","/**\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"],"mappings":";AAAA,SAAS,cAAiC;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,SAAgC,OAAO,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,eAAO,MAAM,MAAM;AAClB,QAAC,MAAM,OAAuB,MAAM;AAAA,MACvC;AAAA;AAAA,MAEA,aA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L6QEAX.js";
|
|
10
10
|
|
|
11
11
|
// src/limits.ts
|
|
12
12
|
var over = (value, cap2) => typeof cap2 === "number" && cap2 > 0 && (value ?? 0) >= cap2;
|
|
@@ -570,7 +570,8 @@ var wrapToolsForRun = (tools, o) => {
|
|
|
570
570
|
...o.clock ? { clock: o.clock } : {},
|
|
571
571
|
...o.mcpSkills ? { mcpSkills: o.mcpSkills } : {},
|
|
572
572
|
...o.sessionLocks ? { sessionLocks: o.sessionLocks } : {},
|
|
573
|
-
...o.askUser ? { askUser: o.askUser } : {}
|
|
573
|
+
...o.askUser ? { askUser: o.askUser } : {},
|
|
574
|
+
...o.pictures ? { pictures: o.pictures } : {}
|
|
574
575
|
};
|
|
575
576
|
return execute.call(t, input, { ...options, agentRun });
|
|
576
577
|
};
|
|
@@ -824,6 +825,43 @@ var bind = (t, binding) => {
|
|
|
824
825
|
return t;
|
|
825
826
|
};
|
|
826
827
|
var fileToolBindingOf = (t) => t && typeof t === "object" ? t[FILE_TOOL] : void 0;
|
|
828
|
+
var lineRangeOf = (startLine, endLine) => {
|
|
829
|
+
if (startLine === void 0 && endLine === void 0) return void 0;
|
|
830
|
+
const whole = (v) => typeof v === "number" && Number.isInteger(v) && v >= 1;
|
|
831
|
+
if (startLine !== void 0 && !whole(startLine))
|
|
832
|
+
throw new Error("startLine is a whole number, 1 or more (1 is the first line)");
|
|
833
|
+
if (endLine !== void 0 && !whole(endLine))
|
|
834
|
+
throw new Error("endLine is a whole number, 1 or more");
|
|
835
|
+
const from = startLine ?? 1;
|
|
836
|
+
const to = endLine;
|
|
837
|
+
if (to !== void 0 && to < from)
|
|
838
|
+
throw new Error(`endLine (${to}) is before startLine (${from})`);
|
|
839
|
+
return { from, ...to !== void 0 ? { to } : {} };
|
|
840
|
+
};
|
|
841
|
+
var readLines = (path, text, range, maxChars) => {
|
|
842
|
+
const lines = text.split("\n");
|
|
843
|
+
const count = lines.length > 1 && lines[lines.length - 1] === "" ? lines.length - 1 : lines.length;
|
|
844
|
+
if (range.from > count)
|
|
845
|
+
throw new Error(
|
|
846
|
+
`"${path}" has ${count} line${count === 1 ? "" : "s"}; startLine ${range.from} is past its end`
|
|
847
|
+
);
|
|
848
|
+
const last = Math.min(range.to ?? count, count);
|
|
849
|
+
const out = [];
|
|
850
|
+
let size = 0;
|
|
851
|
+
let line = range.from;
|
|
852
|
+
for (; line <= last; line++) {
|
|
853
|
+
const next = lines[line - 1];
|
|
854
|
+
if (size + next.length + 1 > maxChars && out.length > 0) break;
|
|
855
|
+
out.push(next.length > maxChars ? `${next.slice(0, maxChars)}\u2026 [line cut]` : next);
|
|
856
|
+
size += next.length + 1;
|
|
857
|
+
}
|
|
858
|
+
const shown = line - 1;
|
|
859
|
+
const head = `[${path}, lines ${range.from}-${shown} of ${count}]`;
|
|
860
|
+
const tail = shown < last ? `
|
|
861
|
+
\u2026 [truncated at ${maxChars} chars: read on from line ${shown + 1}]` : "";
|
|
862
|
+
return `${head}
|
|
863
|
+
${out.join("\n")}${tail}`;
|
|
864
|
+
};
|
|
827
865
|
var createFileTools = (vfs, opts = {}) => {
|
|
828
866
|
const p = opts.prefix ?? "fs_";
|
|
829
867
|
const maxRead = opts.maxReadChars ?? 5e4;
|
|
@@ -845,14 +883,27 @@ var createFileTools = (vfs, opts = {}) => {
|
|
|
845
883
|
),
|
|
846
884
|
[`${p}read`]: markReadOnly(
|
|
847
885
|
tool({
|
|
848
|
-
description: "Read a text file from the workspace by its path.",
|
|
886
|
+
description: "Read a text file from the workspace by its path. For part of a long file, pass a line range: startLine (1 is the first line) and endLine (inclusive; to the end when left out).",
|
|
849
887
|
inputSchema: jsonSchema({
|
|
850
888
|
type: "object",
|
|
851
|
-
properties: {
|
|
889
|
+
properties: {
|
|
890
|
+
path: { type: "string", description: 'Absolute path, e.g. "/notes.md"' },
|
|
891
|
+
startLine: {
|
|
892
|
+
type: "integer",
|
|
893
|
+
minimum: 1,
|
|
894
|
+
description: "The first line to read (1-based). Leave out for the whole file."
|
|
895
|
+
},
|
|
896
|
+
endLine: {
|
|
897
|
+
type: "integer",
|
|
898
|
+
minimum: 1,
|
|
899
|
+
description: "The last line to read (inclusive). Leave out to read to the end."
|
|
900
|
+
}
|
|
901
|
+
},
|
|
852
902
|
required: ["path"],
|
|
853
903
|
additionalProperties: false
|
|
854
904
|
}),
|
|
855
|
-
execute: async ({ path }) => {
|
|
905
|
+
execute: async ({ path, startLine, endLine }) => {
|
|
906
|
+
const range = lineRangeOf(startLine, endLine);
|
|
856
907
|
const f = await vfs.read(path);
|
|
857
908
|
if (!f) {
|
|
858
909
|
const known = (await vfs.list()).map((x) => x.path).slice(0, 30);
|
|
@@ -862,6 +913,7 @@ var createFileTools = (vfs, opts = {}) => {
|
|
|
862
913
|
return `"${f.path}" is a binary file (${f.mimeType}, ${f.size} bytes) and cannot be read as text.`;
|
|
863
914
|
}
|
|
864
915
|
const text = f.encoding === "base64" ? atob(f.content) : f.content;
|
|
916
|
+
if (range) return readLines(f.path, text, range, maxRead);
|
|
865
917
|
return text.length > maxRead ? `${text.slice(0, maxRead)}\u2026 [truncated ${text.length - maxRead} chars]` : text;
|
|
866
918
|
}
|
|
867
919
|
})
|
|
@@ -964,4 +1016,4 @@ export {
|
|
|
964
1016
|
fileToolBindingOf,
|
|
965
1017
|
createFileTools
|
|
966
1018
|
};
|
|
967
|
-
//# sourceMappingURL=chunk-
|
|
1019
|
+
//# sourceMappingURL=chunk-QWOKTI62.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/limits.ts","../src/tools/approval.ts","../src/tiers.ts","../src/tools/types.ts","../src/tools/wrap.ts","../src/files/vfs.ts","../src/files/tools.ts"],"sourcesContent":["import type { IUsage } from './agent/loop-types.js'\n\n/**\n * Run-level token budgets. Every cap is cumulative over one `run()` and soft:\n * it is checked between steps and at every tool-calling round inside a step,\n * so a run stops at the next boundary after crossing it and then writes its\n * final answer (synthesis still runs, bounded by `perCall.synthesizer`).\n */\nexport interface TokenLimits {\n /** Cumulative input (prompt) tokens per run. */\n maxInputTokens?: number\n /** Cumulative output tokens per run, thinking included. */\n maxOutputTokens?: number\n /** Cumulative thinking tokens per run. */\n maxReasoningTokens?: number\n /** Cumulative input + output tokens per run. */\n maxTotalTokens?: number\n /** Max output tokens of ONE model call, per phase (wins over the legacy `budgets`). */\n perCall?: {\n planner?: number\n executor?: number\n replanner?: number\n synthesizer?: number\n compaction?: number\n }\n}\n\nexport type LimitKind = 'input' | 'output' | 'reasoning' | 'total' | 'tool-calls'\n\nexport interface LimitBreach {\n kind: LimitKind\n tokens: number\n cap: number\n}\n\nconst over = (value: number | undefined, cap: number | undefined): boolean =>\n typeof cap === 'number' && cap > 0 && (value ?? 0) >= cap\n\n/**\n * The first cap the usage has reached, or undefined. Order: total, input,\n * output, reasoning — the broadest budget is reported first. Pure.\n */\nexport const checkLimits = (\n usage: IUsage,\n limits: TokenLimits | undefined,\n): LimitBreach | undefined => {\n if (!limits) return undefined\n if (over(usage.totalTokens, limits.maxTotalTokens)) {\n return { kind: 'total', tokens: usage.totalTokens, cap: limits.maxTotalTokens as number }\n }\n if (over(usage.inputTokens, limits.maxInputTokens)) {\n return { kind: 'input', tokens: usage.inputTokens, cap: limits.maxInputTokens as number }\n }\n if (over(usage.outputTokens, limits.maxOutputTokens)) {\n return { kind: 'output', tokens: usage.outputTokens, cap: limits.maxOutputTokens as number }\n }\n if (over(usage.reasoningTokens, limits.maxReasoningTokens)) {\n return {\n kind: 'reasoning',\n tokens: usage.reasoningTokens ?? 0,\n cap: limits.maxReasoningTokens as number,\n }\n }\n return undefined\n}\n\n/** Raised by a tool call that would exceed `maxToolCalls`. */\nexport class ToolBudgetError extends Error {\n constructor(cap: number) {\n super(\n `Tool-call budget exhausted (${cap} per run). Do not call more tools; report what you have.`,\n )\n this.name = 'ToolBudgetError'\n }\n\n toJSON(): string {\n return this.message\n }\n}\n","import type { Tool } from 'ai'\nimport type { IPlanStep } from '../agent/loop-types.js'\nimport {\n createMcpSkillGrants,\n type McpSkillConsentView,\n type McpSkillGrants,\n} from '../mcp/skills.js'\n\n/**\n * Tool consent. Every tool call passes a gate that decides allow / ask / deny:\n *\n * - `autopilot` — run everything (default; explicit `rules` still apply);\n * - `ask-writes` — run read-only tools, ask before anything that may change state;\n * - `ask-all` — ask before every call;\n * - `read-only` — run read-only tools, refuse the rest without asking.\n *\n * A tool is read-only when its MCP annotations say so (`readOnlyHint`) or the\n * host marked it (`defineTool({ readOnly: true })` / `markReadOnly`). Unknown =\n * may write: the safe assumption.\n */\nexport type ToolApprovalMode = 'autopilot' | 'ask-writes' | 'ask-all' | 'read-only'\nexport type ToolPermission = 'allow' | 'ask' | 'deny'\n\nexport const TOOL_APPROVAL_MODES: readonly ToolApprovalMode[] = [\n 'autopilot',\n 'ask-writes',\n 'ask-all',\n 'read-only',\n]\n\nexport interface ToolApprovalRequest {\n /** Unique per request — echo it back from a UI. */\n id: string\n toolName: string\n input: unknown\n readOnly: boolean\n step?: IPlanStep\n /**\n * Set when the call comes from a helper the model started (`subagents.dynamic`), not from the\n * run itself: the helper's id (as in its `subagent.start` event) and its depth.\n */\n subagent?: { id: string; depth: number }\n /**\n * Set when the call comes from an MCP App (`Agent.approveAppToolCall`), not from the model:\n * a UI says so (\"The app “travel” wants to run …\"). `toolName` above is then the name the\n * agent's rules match (`server__tool`), `app.tool` the server's own name for it.\n */\n app?: ToolApprovalApp\n /**\n * Set when the call runs code (`run_js`, or a tool marked with `markCodeExecution`) while the\n * run acts on skills an MCP server served: those skills, by name. Such a call is ALWAYS asked,\n * whatever the mode, a rule or an earlier \"always allow\" say (the Skills extension: a server's\n * skill must not lead to code running here without a person's approval).\n */\n mcpSkills?: string[]\n /**\n * Set when the request is not about a tool call but about an MCP server's skill that is about\n * to enter the model's context (`load_skill`, the planner's pick, a resumed run; `skills` on a\n * server, consent `'ask'` / `'once-per-skill'`): the server, the skill, its description and\n * size and the very text the model would read - the SERVER's words, to show as plain text.\n * `toolName` is `'load_skill'`. Approve to let it in (`remember: true` = every skill of that\n * server for the agent's life, nested ones excepted), deny to keep it out. Asked whatever the\n * approval mode and the rules say.\n */\n skill?: McpSkillConsentView\n}\n\n/** Who asks when an MCP App asks (see `ToolApprovalRequest.app`). */\nexport interface ToolApprovalApp {\n /** The MCP server the app came from (its tools are the only ones it may call). */\n server: string\n /** The tool's own name on that server. */\n tool: string\n /** The app's `ui://` resource. */\n resourceUri: string\n}\n\n/** What the gate hands `onRequest` beside the request. */\nexport interface ToolApprovalContext {\n /**\n * Aborted when the question ends WITHOUT your answer: no decision within `timeoutMs`\n * (`signal.reason` is an Error named 'TimeoutError'), the run was stopped ('AbortError'), or\n * the handler failed. Take the prompt down then: an answer given later is ignored. Never\n * aborted once you have answered.\n */\n signal: AbortSignal\n}\n\n/**\n * `true`/`false`, or an object. `remember: true` on an approval allows this\n * tool for the rest of the agent's life (\"always allow\").\n */\nexport type ToolApprovalDecision =\n boolean | { approved: boolean; reason?: string; remember?: boolean }\n\nexport interface ToolApprovalConfig {\n /** Default policy (default 'autopilot'). */\n mode?: ToolApprovalMode\n /**\n * Per-tool overrides by exact name or `*` glob, e.g. `{ 'github__delete_*': 'deny' }`.\n * They win over the mode — an explicit 'ask' still asks under autopilot.\n */\n rules?: Record<string, ToolPermission>\n /** Resolves an approval request (a UI prompt, a policy service, …). */\n onRequest?: (\n req: ToolApprovalRequest,\n ctx: ToolApprovalContext,\n ) => ToolApprovalDecision | Promise<ToolApprovalDecision>\n /**\n * No decision within this many ms → deny. Default 300 000 ({@link TOOL_APPROVAL_TIMEOUT_MS}).\n * `0` or `Infinity`: no bound - the question waits until the run is stopped; so does a value\n * above 2^31 - 1 (about 24.8 days, the most a timer holds). Negative or NaN: `createAgent`\n * throws. The only bound on the wait: the step's `chatTimeoutMs` (and a subagent's\n * `timeoutMs`) stop while a person decides.\n */\n timeoutMs?: number\n}\n\n/** How long a question waits for a decision when `toolApproval.timeoutMs` is not set: 5 minutes. */\nexport const TOOL_APPROVAL_TIMEOUT_MS = 300_000\n\n// The longest delay a timer holds (2^31 - 1 ms, about 24.8 days). `setTimeout` fires a longer one\n// - Infinity included - after about 1 ms, so a bound past it is taken as no bound at all.\nconst MAX_TIMER_MS = 2_147_483_647\n\n/**\n * `toolApproval.timeoutMs` as the gate uses it: absent = {@link TOOL_APPROVAL_TIMEOUT_MS}; `0`,\n * `Infinity` or more than a timer holds = no bound (0: the question waits until the run is\n * stopped). Anything that is not a number of at least 0 is a configuration error.\n */\nexport const resolveApprovalTimeout = (value: unknown): number => {\n if (value === undefined || value === null) return TOOL_APPROVAL_TIMEOUT_MS\n if (typeof value !== 'number' || Number.isNaN(value) || value < 0) {\n throw new Error(\n `toolApproval.timeoutMs must be a number of milliseconds of at least 0 (0 or Infinity: no limit), got: ${typeof value === 'number' ? String(value) : JSON.stringify(value)}`,\n )\n }\n return value === 0 || value > MAX_TIMER_MS ? 0 : Math.max(1, Math.floor(value))\n}\n\n/** Raised by a denied tool call; recorded as a failed call the replanner sees. */\nexport class ToolDeniedError extends Error {\n constructor(reason?: string) {\n super(\n `Tool call denied by the user${reason ? `: ${reason}` : ''}. Do not retry it; continue without it, or report what is blocked.`,\n )\n this.name = 'ToolDeniedError'\n }\n\n toJSON(): string {\n return this.message\n }\n}\n\n/** Mark a tool as read-only so `ask-writes` / `read-only` let it through. Returns it. */\nexport const markReadOnly = <T extends object>(tool: T, readOnly = true): T => {\n ;(tool as { readOnly?: boolean }).readOnly = readOnly\n return tool\n}\n\n/**\n * Mark a tool as one that runs code (the sandbox's `run_js` is): while a run acts on an MCP\n * server's skill, every call of it is asked (`decideToolPermission`).\n */\nexport const markCodeExecution = <T extends object>(tool: T, codeExecution = true): T => {\n ;(tool as { codeExecution?: boolean }).codeExecution = codeExecution\n return tool\n}\n\nexport const isCodeExecutionTool = (tool: unknown): boolean =>\n (tool as { codeExecution?: unknown } | undefined)?.codeExecution === true\n\nexport const isReadOnlyTool = (tool: Tool | undefined): boolean =>\n (tool as { readOnly?: unknown } | undefined)?.readOnly === true\n\nconst globToRegExp = (glob: string): RegExp =>\n new RegExp(\n `^${glob\n .split('*')\n .map((s) => s.replace(/[.+?^${}()|[\\]\\\\]/g, '\\\\$&'))\n .join('.*')}$`,\n )\n\n/** The most specific matching rule: an exact name, else the longest glob. Pure. */\nexport const matchRule = (\n rules: Record<string, ToolPermission> | undefined,\n toolName: string,\n): ToolPermission | undefined => {\n if (!rules) return undefined\n if (Object.hasOwn(rules, toolName)) return rules[toolName]\n let best: { len: number; perm: ToolPermission } | undefined\n for (const [pattern, perm] of Object.entries(rules)) {\n if (!pattern.includes('*')) continue\n if (!globToRegExp(pattern).test(toolName)) continue\n const len = pattern.replace(/\\*/g, '').length\n if (!best || len > best.len) best = { len, perm }\n }\n return best?.perm\n}\n\n/**\n * What the gate does for one call, before any human is involved. Order:\n * remembered \"always allow\" → most specific rule → mode default. Pure.\n * Then one rule that only ever tightens: a call that runs code (`codeExecution`) while the run\n * acts on an MCP server's skill (`mcpSkills`) is asked when it would have been allowed - by the\n * mode, a rule or an \"always allow\" alike. A deny stays a deny.\n */\nexport const decideToolPermission = (opts: {\n toolName: string\n readOnly: boolean\n mode: ToolApprovalMode\n rules?: Record<string, ToolPermission>\n remembered?: ReadonlySet<string>\n codeExecution?: boolean\n mcpSkills?: readonly string[]\n}): ToolPermission => {\n const permission = decideByPolicy(opts)\n return permission === 'allow' && opts.codeExecution && opts.mcpSkills?.length ? 'ask' : permission\n}\n\nconst decideByPolicy = (opts: {\n toolName: string\n readOnly: boolean\n mode: ToolApprovalMode\n rules?: Record<string, ToolPermission>\n remembered?: ReadonlySet<string>\n}): ToolPermission => {\n if (opts.remembered?.has(opts.toolName)) return 'allow'\n const rule = matchRule(opts.rules, opts.toolName)\n if (rule) return rule\n switch (opts.mode) {\n case 'autopilot':\n return 'allow'\n case 'read-only':\n return opts.readOnly ? 'allow' : 'deny'\n case 'ask-writes':\n return opts.readOnly ? 'allow' : 'ask'\n case 'ask-all':\n return 'ask'\n }\n}\n\n/** Why `{ park: true }` is a denial here: parking is the server package's (docs/design.md). */\nexport const PARK_REFUSED_REASON =\n \"parking ({ park: true }) is the server package's (@dudko.dev/agent): a run in a page cannot wait for an answer outside it, so the call is denied\"\n\nconst normalizeDecision = (\n d: ToolApprovalDecision,\n): { approved: boolean; reason?: string; remember?: boolean } =>\n typeof d === 'boolean'\n ? { approved: d }\n : // A host ported from the server agent: the call is denied as before, and now says why.\n (d as { park?: unknown } | null)?.park === true\n ? { approved: false, reason: PARK_REFUSED_REASON }\n : { approved: Boolean(d?.approved), reason: d?.reason, remember: d?.remember }\n\n/** Mutable approval state shared by every run of one agent. */\nexport interface ApprovalState {\n mode: ToolApprovalMode\n readonly config: ToolApprovalConfig\n /** The wait's bound, `config.timeoutMs` resolved (resolveApprovalTimeout): 0 = none. */\n readonly timeoutMs: number\n /** Tools the user chose to \"always allow\". */\n readonly remembered: Set<string>\n /** What a person allowed of MCP servers' skills for the agent's life (helpers share it). */\n readonly mcpSkillGrants: McpSkillGrants\n}\n\n/** Throws on a `timeoutMs` that is not a usable number: a configuration error, at `createAgent`. */\nexport const createApprovalState = (config: ToolApprovalConfig | undefined): ApprovalState => ({\n mode: config?.mode ?? 'autopilot',\n config: config ?? {},\n timeoutMs: resolveApprovalTimeout(config?.timeoutMs),\n remembered: new Set<string>(),\n mcpSkillGrants: createMcpSkillGrants(),\n})\n\nlet seq = 0\n\nexport interface ApprovalEvents {\n requested: (req: ToolApprovalRequest) => void\n resolved: (r: {\n id: string\n name: string\n approved: boolean\n reason?: string\n automatic: boolean\n }) => void\n /**\n * A person is being asked (right after `requested`): stop the run's time limits - the step's,\n * a subagent's - for the length of the wait. Returns what starts them again (wait-clock.ts).\n */\n wait?: () => () => void\n}\n\n/**\n * Run the gate for one call. Resolves when the call may proceed; throws\n * {@link ToolDeniedError} otherwise. `alwaysAllow` short-circuits (built-ins).\n */\nexport const gateToolCall = async (\n state: ApprovalState,\n call: {\n toolName: string\n input: unknown\n readOnly: boolean\n step?: IPlanStep\n subagent?: { id: string; depth: number }\n app?: ToolApprovalApp\n /** The tool runs code: asked while the run acts on an MCP server's skill (`mcpSkills`). */\n codeExecution?: boolean\n /** The MCP skills the run acts on (with `codeExecution` only). */\n mcpSkills?: string[]\n },\n events: ApprovalEvents,\n signal?: AbortSignal,\n): Promise<void> => {\n const { codeExecution, mcpSkills: acting, ...shown } = call\n const permission = decideToolPermission({\n toolName: call.toolName,\n readOnly: call.readOnly,\n mode: state.mode,\n rules: state.config.rules,\n remembered: state.remembered,\n ...(codeExecution ? { codeExecution } : {}),\n ...(acting?.length ? { mcpSkills: acting } : {}),\n })\n if (permission === 'allow') return\n // Asked only because the run acts on an MCP server's skill: the request says which.\n const bySkill =\n Boolean(codeExecution && acting?.length) &&\n decideByPolicy({\n toolName: call.toolName,\n readOnly: call.readOnly,\n mode: state.mode,\n rules: state.config.rules,\n remembered: state.remembered,\n }) === 'allow'\n const id = `approval-${Date.now().toString(36)}-${(seq += 1)}`\n if (permission === 'deny') {\n const reason =\n state.mode === 'read-only' && !matchRule(state.config.rules, call.toolName)\n ? 'the agent is in read-only mode'\n : 'blocked by policy'\n events.resolved({ id, name: call.toolName, approved: false, reason, automatic: true })\n throw new ToolDeniedError(reason)\n }\n const onRequest = state.config.onRequest\n if (!onRequest) {\n const reason = bySkill\n ? \"code runs only with a person's approval while the run acts on an MCP server's skill, and no approval handler is configured\"\n : 'no approval handler configured'\n events.resolved({ id, name: call.toolName, approved: false, reason, automatic: true })\n throw new ToolDeniedError(reason)\n }\n const req: ToolApprovalRequest = { id, ...shown, ...(bySkill ? { mcpSkills: acting } : {}) }\n events.requested(req)\n let decision: { approved: boolean; reason?: string; remember?: boolean }\n // The host's own signal: aborted when the question ends without its answer (the bound, a\n // stop, a failed handler), so a prompt left open can be taken down. Never after an answer.\n const asked = new AbortController()\n // A person is being asked: the step's limit is about models and tools, and does not run\n // meanwhile. The wait has its own bound, `timeoutMs`, and a stop still ends it at once.\n const resume = events.wait?.()\n try {\n decision = normalizeDecision(\n await withDeadline(\n Promise.resolve(onRequest(req, { signal: asked.signal })),\n state.timeoutMs,\n signal,\n ),\n )\n } catch (err) {\n // Before the resolved event: a host that closes its prompt hears of it first.\n asked.abort(err)\n resume?.()\n const reason = err instanceof Error ? err.message : String(err)\n events.resolved({ id, name: call.toolName, approved: false, reason, automatic: true })\n throw new ToolDeniedError(reason)\n }\n resume?.()\n if (decision.approved && decision.remember) state.remembered.add(call.toolName)\n events.resolved({\n id,\n name: call.toolName,\n approved: decision.approved,\n reason: decision.reason,\n automatic: false,\n })\n if (!decision.approved) throw new ToolDeniedError(decision.reason)\n}\n\n/**\n * Ask the person whether an MCP server's skill may enter the model's context: the same\n * `onRequest`, `timeoutMs` and events as a tool call (the request carries `skill`, `toolName` is\n * `load_skill`), but no mode, no rule and no \"always allow\" of the tools' - a yes with `remember`\n * is \"Always for this server\", kept by the caller. Resolves with the answer (`by` says whether a\n * person gave it); throws only when the run was stopped.\n */\nexport const askMcpSkillConsent = async (\n state: ApprovalState,\n call: {\n input: unknown\n skill: McpSkillConsentView\n step?: IPlanStep\n subagent?: { id: string; depth: number }\n },\n events: ApprovalEvents,\n signal?: AbortSignal,\n): Promise<{\n approved: boolean\n remember?: boolean\n reason?: string\n by: 'person' | 'no-handler' | 'no-answer'\n}> => {\n const id = `approval-${Date.now().toString(36)}-${(seq += 1)}`\n const name = 'load_skill'\n const onRequest = state.config.onRequest\n if (!onRequest) {\n const reason = 'no approval handler configured'\n events.resolved({ id, name, approved: false, reason, automatic: true })\n return { approved: false, reason, by: 'no-handler' }\n }\n const req: ToolApprovalRequest = {\n id,\n toolName: name,\n input: call.input,\n readOnly: true,\n ...(call.step ? { step: call.step } : {}),\n ...(call.subagent ? { subagent: call.subagent } : {}),\n skill: call.skill,\n }\n events.requested(req)\n const asked = new AbortController()\n const resume = events.wait?.()\n let decision: { approved: boolean; reason?: string; remember?: boolean }\n try {\n decision = normalizeDecision(\n await withDeadline(\n Promise.resolve(onRequest(req, { signal: asked.signal })),\n state.timeoutMs,\n signal,\n ),\n )\n } catch (err) {\n asked.abort(err)\n resume?.()\n const reason = err instanceof Error ? err.message : String(err)\n events.resolved({ id, name, approved: false, reason, automatic: true })\n if (signal?.aborted) throw err\n return { approved: false, reason, by: 'no-answer' }\n }\n resume?.()\n events.resolved({\n id,\n name,\n approved: decision.approved,\n reason: decision.reason,\n automatic: false,\n })\n return {\n approved: decision.approved,\n ...(decision.remember ? { remember: true } : {}),\n ...(decision.reason ? { reason: decision.reason } : {}),\n by: 'person',\n }\n}\n\n// Named like the reasons of `AbortSignal.timeout` / `abort()`: they are the host signal's too.\nconst namedError = (message: string, name: string): Error =>\n Object.assign(new Error(message), { name })\n\n// `timeoutMs` is resolved (resolveApprovalTimeout): 0 = no bound, else what a timer can hold.\nexport const withDeadline = <T>(\n p: Promise<T>,\n timeoutMs: number,\n signal?: AbortSignal,\n): Promise<T> => {\n if (!(timeoutMs > 0) && !signal) return p\n return new Promise<T>((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined\n const done = () => {\n if (timer !== undefined) clearTimeout(timer)\n signal?.removeEventListener('abort', onAbort)\n }\n const onAbort = () => {\n done()\n reject(namedError('the run was stopped while waiting for approval', 'AbortError'))\n }\n if (signal?.aborted) return onAbort()\n signal?.addEventListener('abort', onAbort, { once: true })\n if (timeoutMs > 0) {\n timer = setTimeout(() => {\n done()\n reject(namedError(`no approval decision within ${timeoutMs} ms`, 'TimeoutError'))\n }, timeoutMs)\n }\n p.then(\n (v) => {\n done()\n resolve(v)\n },\n (e) => {\n done()\n reject(e)\n },\n )\n })\n}\n","import type {\n EscalationConfig,\n EscalationReason,\n IStepResult,\n ModelTier,\n StepComplexity,\n TierReason,\n} from './agent/loop-types.js'\n\n// Model tiers (config.executorTiers) and escalation (config.escalation): the pure rules. Which\n// tier a step runs on, which tier is tried after a failure, what counts as a failure a stronger\n// model could fix, and what the stronger model is shown of the attempt before it. The Node\n// sibling's src/tiers.ts carries the same rules under the same names: change both, with tests.\n\n// Weakest first: the order escalation climbs.\nexport const MODEL_TIERS: readonly ModelTier[] = ['light', 'standard', 'strong']\n\nexport const STEP_COMPLEXITIES: readonly StepComplexity[] = ['low', 'medium', 'high']\n\nconst TIER_OF: Record<StepComplexity, ModelTier> = {\n low: 'light',\n medium: 'standard',\n high: 'strong',\n}\n\nexport const isStepComplexity = (v: unknown): v is StepComplexity =>\n typeof v === 'string' && (STEP_COMPLEXITIES as readonly string[]).includes(v)\n\n/**\n * The tier a step runs on. The planner's complexity names the tier it wants (low -> light,\n * medium -> standard, high -> strong); a step the planner did not mark runs on `standard`.\n * A tier the host did not configure falls back to the NEAREST configured one, and of two equally\n * near the STRONGER: a step is never handed to a model weaker than it has to be. `standard` is\n * always configured (it is the agent's own model), so in practice a missing `light` or `strong`\n * means `standard` - the rule is general so that it stays true if that ever changes.\n */\nexport const pickTier = (\n complexity: StepComplexity | undefined,\n configured: ReadonlySet<ModelTier>,\n): { tier: ModelTier; reason: TierReason } => {\n const wanted: ModelTier = complexity ? TIER_OF[complexity] : 'standard'\n if (configured.has(wanted)) {\n return { tier: wanted, reason: complexity ? 'planned' : 'default' }\n }\n const at = MODEL_TIERS.indexOf(wanted)\n let best: ModelTier | undefined\n let bestDistance = Infinity\n for (const tier of MODEL_TIERS) {\n if (!configured.has(tier)) {\n continue\n }\n const distance = Math.abs(MODEL_TIERS.indexOf(tier) - at)\n // `<=`: the list runs weakest first, so on a tie the later (stronger) tier wins.\n if (distance <= bestDistance) {\n best = tier\n bestDistance = distance\n }\n }\n if (!best) {\n throw new Error('no executor tier is configured')\n }\n return { tier: best, reason: 'fallback' }\n}\n\n// The next configured tier above `tier`, or undefined when it is the strongest one.\nexport const nextStrongerTier = (\n tier: ModelTier,\n configured: ReadonlySet<ModelTier>,\n): ModelTier | undefined =>\n MODEL_TIERS.slice(MODEL_TIERS.indexOf(tier) + 1).find((t) => configured.has(t))\n\nexport interface IResolvedEscalation {\n enabled: boolean\n maxPerStep: number\n maxPerRun: number\n}\n\nexport const DEFAULT_ESCALATIONS_PER_STEP = 1\nexport const DEFAULT_ESCALATIONS_PER_RUN = 3\n\nconst cap = (v: number | undefined, fallback: number): number =>\n typeof v === 'number' && Number.isFinite(v) && v >= 0 ? Math.floor(v) : fallback\n\n/**\n * Escalation is ON by default once tiers are configured, and cannot be on without them. A host\n * that routes easy steps to a light model has accepted that the planner's rating may be wrong;\n * without escalation a mis-rated step fails outright and the replanner (another paid call) has\n * to plan around a failure that a model the host already configured would not have had. The cost\n * is bounded: one retry per step and three per run unless the host says otherwise.\n */\nexport const resolveEscalation = (\n setting: boolean | EscalationConfig | undefined,\n tiersActive: boolean,\n): IResolvedEscalation => {\n const cfg = typeof setting === 'object' && setting !== null ? setting : {}\n const maxPerStep = cap(cfg.maxPerStep, DEFAULT_ESCALATIONS_PER_STEP)\n const maxPerRun = cap(cfg.maxPerRun, DEFAULT_ESCALATIONS_PER_RUN)\n return {\n enabled: tiersActive && setting !== false && maxPerStep > 0 && maxPerRun > 0,\n maxPerStep,\n maxPerRun,\n }\n}\n\nconst nameOf = (v: unknown): string =>\n v && typeof v === 'object' && typeof (v as { name?: unknown }).name === 'string'\n ? (v as { name: string }).name\n : ''\n\nconst textOf = (v: unknown): string => {\n if (typeof v === 'string') {\n return v\n }\n if (v && typeof v === 'object' && typeof (v as { message?: unknown }).message === 'string') {\n return (v as { message: string }).message\n }\n return ''\n}\n\n// A failed call the USER (or the approval policy) refused: a bigger model must not get a second\n// go at something a person said no to.\nexport const isDeniedOutput = (output: unknown): boolean =>\n nameOf(output) === 'ToolDeniedError' || /Tool call denied by the user/.test(textOf(output))\n\n// A failed call the run's tool-call budget refused.\nexport const isBudgetOutput = (output: unknown): boolean =>\n nameOf(output) === 'ToolBudgetError' || /tool-call budget exhausted/i.test(textOf(output))\n\n// A failed call whose ARGUMENTS the model got wrong (they did not parse, or did not match the\n// tool's schema) - the AI SDK's InvalidToolInputError (which reaches the trace as its text), or\n// the prompted path's own message.\nexport const isInvalidArgumentsOutput = (output: unknown): boolean =>\n /InvalidToolInput|InvalidToolArguments|ToolCallRepair/.test(nameOf(output)) ||\n /InvalidToolInputError|Invalid input for tool |^invalid args for \"/i.test(textOf(output))\n\n// \"Repeatedly\": the same tool was called with bad arguments at least twice in the attempt and\n// never got a good call in after the last of them.\nconst argumentsKeptFailing = (calls: IStepResult['toolCalls']): boolean => {\n const bad = new Map<string, number[]>()\n calls.forEach((c, i) => {\n if (!c.ok && isInvalidArgumentsOutput(c.output)) {\n bad.set(c.name, [...(bad.get(c.name) ?? []), i])\n }\n })\n return [...bad].some(\n ([name, at]) =>\n at.length >= 2 && !calls.slice(at[at.length - 1] + 1).some((c) => c.ok && c.name === name),\n )\n}\n\n// What one executor attempt at a step came to, as far as escalation needs to know.\nexport interface IAttemptOutcome {\n toolCalls: IStepResult['toolCalls']\n blocked: boolean\n // The model wrote no text at all.\n empty: boolean\n // The last model call ended on the output cap (finishReason 'length').\n cut: boolean\n // A run-level budget (tokens, tool calls) stopped the attempt.\n stopped: boolean\n}\n\n/**\n * Why an attempt that RETURNED should be retried on a stronger model, or undefined when it should\n * not. Never for an attempt a budget stopped, or one in which the user (or the approval policy)\n * denied a tool: those are not the model's failures.\n */\nexport const escalationReasonOf = (o: IAttemptOutcome): EscalationReason | undefined => {\n if (o.stopped || o.toolCalls.some((c) => !c.ok && isBudgetOutput(c.output))) {\n return undefined\n }\n if (o.toolCalls.some((c) => !c.ok && isDeniedOutput(c.output))) {\n return undefined\n }\n if (o.cut) {\n return 'output-cut'\n }\n if (o.blocked) {\n return 'blocked'\n }\n if (argumentsKeptFailing(o.toolCalls)) {\n return 'tool-arguments'\n }\n if (o.empty && !o.toolCalls.some((c) => c.ok)) {\n return 'empty-result'\n }\n return undefined\n}\n\nconst statusIn = (\n err: unknown,\n match: (status: number) => boolean,\n seen: Set<unknown> = new Set(),\n): boolean => {\n if (!err || typeof err !== 'object' || seen.has(err)) {\n return false\n }\n seen.add(err)\n const e = err as { statusCode?: number; status?: number; cause?: unknown; lastError?: unknown }\n const status = e.statusCode ?? e.status\n if (typeof status === 'number' && match(status)) {\n return true\n }\n return statusIn(e.cause, match, seen) || statusIn(e.lastError, match, seen)\n}\n\n/**\n * Whether an attempt that THREW may be retried on a stronger model. Not a stop or a timeout (the\n * call was cut, not wrong), not refused credentials (401 / 403: the next call fails the same way\n * and the host must hear about it), not a rate limit (429: that is for retry and backoff, and a\n * bigger model on the same account is the last thing to send), not a denial or a spent budget.\n */\nexport const isEscalatableError = (err: unknown): boolean => {\n const name = nameOf(err)\n if (name === 'AbortError' || name === 'TimeoutError') {\n return false\n }\n if (isDeniedOutput(err) || isBudgetOutput(err)) {\n return false\n }\n return !statusIn(err, (s) => s === 401 || s === 403 || s === 429)\n}\n\n// One attempt at a step that a stronger model now continues.\nexport interface IEarlierAttempt {\n tier: ModelTier\n reason: EscalationReason\n // What the attempt said (its summary, or the error it died of).\n summary: string\n toolCalls: IStepResult['toolCalls']\n}\n\nconst INPUT_CHARS = 400\nconst OUTPUT_CHARS = 1500\n\nconst asText = (v: unknown, max: number): string => {\n let s: string\n try {\n s = typeof v === 'string' ? v : (JSON.stringify(v) ?? String(v))\n } catch {\n s = String(v)\n }\n return s.length > max ? `${s.slice(0, max)}... [truncated, ${s.length - max} chars]` : s\n}\n\nconst WHY: Record<EscalationReason, string> = {\n blocked: 'it reported that it was blocked',\n 'empty-result': 'it produced no result',\n 'tool-arguments': 'it kept calling a tool with arguments that did not parse',\n 'output-cut': 'its output was cut off by the output cap',\n error: 'its model call failed',\n}\n\n/**\n * What the stronger model is shown of the attempts before it - in the USER prompt, so the system\n * prompt stays run-stable. It names every tool call with its arguments and result, because the\n * calls that succeeded HAPPENED: the step continues from them, it does not start over.\n */\nexport const renderEarlierAttempts = (attempts: IEarlierAttempt[]): string => {\n if (attempts.length === 0) {\n return ''\n }\n const blocks = attempts.map((a, i) => {\n const calls = a.toolCalls.length\n ? a.toolCalls\n .map(\n (c) =>\n ` - ${c.name} ${asText(c.input, INPUT_CHARS)} -> ${c.ok ? 'ok' : 'FAILED'}: ${asText(c.output, OUTPUT_CHARS)}`,\n )\n .join('\\n')\n : ' (no tool calls)'\n return [\n `Attempt ${i + 1} (${a.tier} model) stopped because ${WHY[a.reason]}.`,\n ` It said: ${asText(a.summary, OUTPUT_CHARS) || '(nothing)'}`,\n ' Tool calls it made:',\n calls,\n ].join('\\n')\n })\n return [\n 'EARLIER ATTEMPT AT THIS STEP - a smaller model started this step and did not finish it. You are continuing it, not starting over.',\n 'Every tool call below marked ok was REALLY executed and its effect is already in place: do not make it again, use its result. Redo only what FAILED or is still missing.',\n ...blocks,\n ].join('\\n')\n}\n\nconst stable = (v: unknown): unknown => {\n if (Array.isArray(v)) {\n return v.map(stable)\n }\n if (v && typeof v === 'object') {\n return Object.fromEntries(\n Object.keys(v as object)\n .sort()\n .map((k) => [k, stable((v as Record<string, unknown>)[k])]),\n )\n }\n return v\n}\n\n// Identity of a tool call: its name and its arguments, key order aside.\nexport const toolCallKey = (name: string, input: unknown): string => {\n try {\n return `${name}\\u0000${JSON.stringify(stable(input)) ?? ''}`\n } catch {\n return `${name}\\u0000${String(input)}`\n }\n}\n\n/**\n * The writes of the step in flight, kept while it may be escalated. A stronger model continuing\n * the step is TOLD what was already done; this is what makes it true even if it does not listen:\n * a call to a tool that is not read-only, with the same arguments as a call that already\n * succeeded in an EARLIER attempt at this step, is not executed again - it gets the earlier\n * result back. Within one attempt nothing changes (a model may repeat a call there as it always\n * could), and read-only tools are never held back.\n */\nexport interface IStepWrites {\n // 0 for the first attempt, +1 per escalation.\n attempt: number\n done: Map<string, { attempt: number; output: unknown }>\n}\n\nexport const createStepWrites = (): IStepWrites => ({ attempt: 0, done: new Map() })\n\n// The earlier result to hand back instead of running the call, or undefined to run it.\nexport const replayedWrite = (\n writes: IStepWrites | undefined,\n name: string,\n input: unknown,\n): { output: unknown } | undefined => {\n const hit = writes?.done.get(toolCallKey(name, input))\n return hit && hit.attempt < writes!.attempt ? { output: hit.output } : undefined\n}\n\nexport const recordWrite = (\n writes: IStepWrites | undefined,\n name: string,\n input: unknown,\n output: unknown,\n): void => {\n writes?.done.set(toolCallKey(name, input), { attempt: writes.attempt, output })\n}\n\nexport const REPLAY_NOTE =\n '[not run again: this exact call already succeeded in an earlier attempt at this step, and its effect is in place. Its result then:]'\n\nexport const replayOutput = (output: unknown): string => `${REPLAY_NOTE} ${asText(output, 20_000)}`\n\n/**\n * Whether a tool call's `output` (in a `step.tool-result` event or a step's `toolCalls`) is the\n * answer to a write that was NOT run again: the same call already succeeded in an earlier attempt\n * at the step, and the model was handed that result under `REPLAY_NOTE`. For a UI that marks such\n * a call instead of showing it as a second execution.\n */\nexport const isReplayedToolOutput = (output: unknown): boolean =>\n typeof output === 'string' && output.startsWith(REPLAY_NOTE)\n","import type { Tool, ToolSet } from 'ai'\n\n/**\n * The canonical tool shape is the AI SDK `Tool` — the same object the native\n * tool-calling path passes straight to `streamText({ tools })`, and the same\n * shape MCP tools take. We add one optional field, `promptHint`, a short\n * human-readable parameter hint (e.g. \"{ text: string, x?: number }\") used only\n * by the prompted/salvage path when it renders the tool catalogue into a text\n * prompt for weak local models.\n */\nexport type AgentTool = Tool & { promptHint?: string; readOnly?: boolean }\n\n/** A named collection of tools — a plain AI SDK ToolSet, usable directly. */\nexport type AgentToolSet = ToolSet\n\n/** Read the optional promptHint attached by defineTool, if any. */\nexport const promptHintOf = (tool: Tool): string | undefined =>\n typeof (tool as { promptHint?: unknown }).promptHint === 'string'\n ? (tool as { promptHint?: string }).promptHint\n : undefined\n","import { asSchema, type Tool, type ToolSet } from 'ai'\nimport type { IPlanStep, IUsage } from '../agent/loop-types.js'\nimport type { RunControlPort } from '../agent/control.js'\nimport type { AgentEvent, UsagePhase } from '../events.js'\nimport { ToolBudgetError } from '../limits.js'\nimport {\n decideToolPermission,\n gateToolCall,\n isCodeExecutionTool,\n isReadOnlyTool,\n type ApprovalState,\n} from './approval.js'\nimport { recordWrite, replayOutput, replayedWrite, type IStepWrites } from '../tiers.js'\nimport { promptHintOf } from './types.js'\nimport type { SpawnRun } from '../subagent/dynamic.js'\nimport type { IWaitClock } from '../wait-clock.js'\nimport type { AskUserChannel } from './ask-user.js'\nimport type { IGeneratedPictures } from './media-shared.js'\n\n/**\n * What a tool's `execute` can reach of the run that called it, passed as\n * `options.agentRun`. Subagent tools use it to stream nested events and to\n * charge their usage to the parent run.\n */\nexport interface ToolRunContext {\n emit: (event: AgentEvent) => void\n /** The plan step being executed, when there is one. */\n step?: IPlanStep\n signal?: AbortSignal\n /**\n * Add what was spent on the parent's behalf to the run: a subagent's tokens (the default\n * phase, 'subagent'), a media model's call (phase 'media'), or a grounded search's tokens\n * (phase 'search').\n */\n addUsage: (usage: IUsage, phase?: UsagePhase) => void\n /** The run's usage so far (media tools read their per-run call count from it). */\n usage?: () => IUsage\n /**\n * Run the agent's consent gate for a call made on its behalf (e.g. a host\n * tool a subagent calls). Resolves when allowed, throws ToolDeniedError.\n */\n approve: (toolName: string, input: unknown, readOnly: boolean) => Promise<void>\n /** The run's control, when the host passed one: subagents register here so they can be listed and stopped. */\n control?: RunControlPort\n /** The run's id (for provenance). */\n runId?: string\n /** Pages web_fetch read in this run (origin + path), kept as provenance for any lesson the run writes. */\n fetched?: string[]\n /** Internal - what the built-in `spawn_subagent` tool reads of the run (`subagents.dynamic`). */\n spawn?: SpawnRun\n /**\n * Set on the run of a helper the model started (`subagents.dynamic`): the call is the\n * helper's, not the run's the host started. An MCP tool reads it to decide whether the call\n * may ask the user something (`onElicitation`, `elicitation.subagents`).\n */\n subagent?: { id: string; depth: number }\n /**\n * The questions MCP servers asked the user in this run (`onElicitation`): one object per run,\n * shared with the helpers it starts (`elicitation.maxPerRun`).\n */\n elicitations?: { count: number }\n /**\n * Internal - the run's clock (wait-clock.ts): the step's `chatTimeoutMs` and the time limits\n * of the subagents the run's tool calls start are deadlines of it, and whoever asks a person\n * something on the run's behalf (the consent gate, an MCP question) pauses it for the wait.\n */\n clock?: IWaitClock\n /**\n * Internal - the skills of MCP servers the run acts on, its callers' included: a call of a\n * tool that runs code is asked while there is one (`decideToolPermission`). A helper the model\n * starts inherits it.\n */\n mcpSkills?: () => string[]\n /**\n * Internal - the session locks the run holds (its own and its callers', `sessionLock`): an\n * in-process subagent runs under them rather than wait for its own parent.\n */\n sessionLocks?: () => readonly string[]\n /**\n * Internal - the run's way to the person (`config.askUser`): `ask_user` asks through it, a\n * helper the run starts shares it, and a subagent the host defined asks through it too.\n */\n askUser?: AskUserChannel\n /**\n * Internal - the run's pictures for its model (`media.viewGenerated`): `generate_image` leaves\n * the picture it made here for the executor to show its model once. Absent when off.\n */\n pictures?: IGeneratedPictures\n}\n\n/** Read the run context the agent passes to a tool's execute (undefined outside a run). */\nexport const toolRunContextOf = (options: unknown): ToolRunContext | undefined =>\n (options as { agentRun?: ToolRunContext } | undefined)?.agentRun\n\nconst truncated = (s: string, max: number): string =>\n s.length > max ? `${s.slice(0, max)}… [truncated ${s.length - max} chars]` : s\n\nconst toText = (v: unknown): string => {\n if (typeof v === 'string') return v\n try {\n return JSON.stringify(v) ?? String(v)\n } catch {\n return String(v)\n }\n}\n\ntype ToModelOutput = NonNullable<Tool['toModelOutput']>\n\n/**\n * Cap what the MODEL sees of a tool result at `maxChars` (the raw output still\n * reaches events and the trace). A tool's own `toModelOutput` runs first.\n */\nexport const limitModelOutput = (\n original: Tool['toModelOutput'],\n maxChars: number,\n): ToModelOutput =>\n (async (opts: Parameters<ToModelOutput>[0]) => {\n const base = original\n ? await original(opts)\n : typeof opts.output === 'string'\n ? ({ type: 'text', value: opts.output } as const)\n : ({ type: 'json', value: (opts.output ?? null) as never } as const)\n if (base.type === 'text' || base.type === 'error-text') {\n return { ...base, value: truncated(base.value, maxChars) }\n }\n if (base.type === 'json' || base.type === 'error-json') {\n const text = toText(base.value)\n if (text.length <= maxChars) return base\n return {\n type: base.type === 'json' ? 'text' : 'error-text',\n value: truncated(text, maxChars),\n }\n }\n return base\n }) as ToModelOutput\n\nexport interface WrapToolsOptions {\n approval: ApprovalState\n /** Names that skip the gate and the call budget (built-in meta-tools). */\n builtins: ReadonlySet<string>\n emit: (event: AgentEvent) => void\n step: () => IPlanStep | undefined\n signal?: AbortSignal\n addUsage: (usage: IUsage, phase?: UsagePhase) => void\n /** The run's usage so far, handed to tools through their run context. */\n usage?: () => IUsage\n /** Called before each counted call; throw to refuse it. */\n countCall: () => void\n maxToolOutputChars: number\n /** The run's control, handed to tools through their run context. */\n control?: RunControlPort\n runId?: string\n /** Shared with every call of the run, so a lesson can name what the run read. */\n fetched?: string[]\n /**\n * The writes of the step in flight, while that step may be escalated to a stronger tier (else\n * undefined, and nothing changes): a write that already succeeded in an EARLIER attempt at the\n * step is not executed again - the call gets the earlier result back (see `tiers.ts`).\n */\n stepWrites?: () => IStepWrites | undefined\n /** The run's place among the helpers the model starts, handed to tools through their run context. */\n spawn?: SpawnRun\n /** Set on a helper's own run: every consent request it makes carries it. */\n subagent?: { id: string; depth: number }\n /** The run's count of questions asked of the user, handed to tools through their run context. */\n elicitations?: { count: number }\n /** The run's clock: the gate pauses it while a person decides; handed to tools too. */\n clock?: IWaitClock\n /**\n * The skills of MCP servers the run acts on (its callers' included): while there is one, a\n * call of a tool that runs code (`isCodeExecutionTool`) is asked whatever the mode says.\n */\n mcpSkills?: () => string[]\n /** The session locks the run holds, handed to tools through their run context. */\n sessionLocks?: () => readonly string[]\n /** The run's way to the person (`config.askUser`), handed to tools through their run context. */\n askUser?: AskUserChannel\n /** The run's pictures for its model (`media.viewGenerated`), handed to tools through their run context. */\n pictures?: IGeneratedPictures\n}\n\nconst isAsyncIterable = (v: unknown): v is AsyncIterable<unknown> =>\n typeof v === 'object' && v !== null && Symbol.asyncIterator in v\n\n/** Record a call's result once it is known, without changing what `execute` returns or when. */\nconst recording = (out: unknown, record: (value: unknown) => void): unknown => {\n if (isAsyncIterable(out)) {\n return (async function* () {\n let last: unknown\n for await (const value of out) {\n last = value\n yield value\n }\n record(last)\n })()\n }\n if (out && typeof (out as { then?: unknown }).then === 'function') {\n return (out as Promise<unknown>).then((value) => {\n record(value)\n return value\n })\n }\n record(out)\n return out\n}\n\n/**\n * Wrap every tool for one run: the consent gate, the tool-call budget, the\n * model-facing output cap, and the run context passed as `options.agentRun`.\n * When the gate allows a call synchronously, `execute` is invoked without an\n * extra await, so a streaming tool keeps returning its iterable.\n */\nexport const wrapToolsForRun = (tools: ToolSet, o: WrapToolsOptions): ToolSet => {\n const out: ToolSet = {}\n const gate = (\n toolName: string,\n input: unknown,\n readOnly: boolean,\n signal?: AbortSignal,\n codeExecution?: boolean,\n ) =>\n gateToolCall(\n o.approval,\n {\n toolName,\n input,\n readOnly,\n step: o.step(),\n ...(o.subagent ? { subagent: o.subagent } : {}),\n ...(codeExecution ? { codeExecution, mcpSkills: o.mcpSkills?.() ?? [] } : {}),\n },\n {\n requested: (req) =>\n o.emit({\n type: 'tool.approval-requested',\n id: req.id,\n name: req.toolName,\n input: req.input,\n readOnly: req.readOnly,\n step: req.step,\n ...(req.subagent ? { subagent: req.subagent } : {}),\n ...(req.mcpSkills ? { mcpSkills: req.mcpSkills } : {}),\n }),\n resolved: (r) => o.emit({ type: 'tool.approval-resolved', ...r }),\n ...(o.clock ? { wait: o.clock.pause } : {}),\n },\n signal ?? o.signal,\n )\n for (const [name, t] of Object.entries(tools)) {\n const execute = (t as { execute?: (input: unknown, options: unknown) => unknown }).execute\n const builtin = o.builtins.has(name)\n const readOnly = builtin || isReadOnlyTool(t)\n const codeExecution = !builtin && isCodeExecutionTool(t)\n const wrapped: Record<string, unknown> = { ...t }\n if (o.maxToolOutputChars > 0) {\n wrapped.toModelOutput = limitModelOutput(t.toModelOutput, o.maxToolOutputChars)\n }\n if (typeof execute === 'function') {\n wrapped.execute = (input: unknown, options: unknown) => {\n // A read-only or built-in tool is never held back or recorded.\n const writes = readOnly ? undefined : o.stepWrites?.()\n // Before the consent gate and the budget: a call that is not made costs neither.\n const earlier = replayedWrite(writes, name, input)\n if (earlier) return replayOutput(earlier.output)\n const call = (): unknown => {\n if (!builtin) o.countCall()\n const agentRun: ToolRunContext = {\n emit: o.emit,\n step: o.step(),\n signal: o.signal,\n addUsage: o.addUsage,\n ...(o.usage ? { usage: o.usage } : {}),\n approve: (toolName, toolInput, ro) => gate(toolName, toolInput, ro),\n ...(o.control ? { control: o.control } : {}),\n ...(o.runId ? { runId: o.runId } : {}),\n ...(o.fetched ? { fetched: o.fetched } : {}),\n ...(o.spawn ? { spawn: o.spawn } : {}),\n ...(o.subagent ? { subagent: o.subagent } : {}),\n ...(o.elicitations ? { elicitations: o.elicitations } : {}),\n ...(o.clock ? { clock: o.clock } : {}),\n ...(o.mcpSkills ? { mcpSkills: o.mcpSkills } : {}),\n ...(o.sessionLocks ? { sessionLocks: o.sessionLocks } : {}),\n ...(o.askUser ? { askUser: o.askUser } : {}),\n ...(o.pictures ? { pictures: o.pictures } : {}),\n }\n return execute.call(t, input, { ...(options as object), agentRun })\n }\n const run = (): unknown =>\n writes ? recording(call(), (value) => recordWrite(writes, name, input, value)) : call()\n if (builtin) return run()\n const permission = decideToolPermission({\n toolName: name,\n readOnly,\n mode: o.approval.mode,\n rules: o.approval.config.rules,\n remembered: o.approval.remembered,\n ...(codeExecution ? { codeExecution, mcpSkills: o.mcpSkills?.() ?? [] } : {}),\n })\n if (permission === 'allow') return run()\n return gate(\n name,\n input,\n readOnly,\n (options as { abortSignal?: AbortSignal } | undefined)?.abortSignal,\n codeExecution,\n ).then(run)\n }\n }\n out[name] = wrapped as Tool\n }\n return out\n}\n\n/** Throws ToolBudgetError once `cap` calls were made (cap ≤ 0 = unlimited). */\nexport const createCallCounter = (cap: number | undefined, initial = 0) => {\n // `initial` is a resumed run's count: the cap is per RUN, not per process.\n let calls = Math.max(0, Math.floor(initial))\n return {\n count: (): void => {\n if (cap && cap > 0 && calls >= cap) throw new ToolBudgetError(cap)\n calls += 1\n },\n get calls() {\n return calls\n },\n get exhausted() {\n return Boolean(cap && cap > 0 && calls >= cap)\n },\n }\n}\n\ntype JsonSchemaLike = {\n type?: string | string[]\n properties?: Record<string, JsonSchemaLike>\n required?: string[]\n items?: JsonSchemaLike\n enum?: unknown[]\n}\n\nconst typeHint = (s: JsonSchemaLike | undefined, depth: number): string => {\n if (!s) return 'any'\n if (Array.isArray(s.enum) && s.enum.length > 0 && s.enum.length <= 8) {\n return s.enum.map((v) => JSON.stringify(v)).join(' | ')\n }\n const type = Array.isArray(s.type) ? s.type.find((x) => x !== 'null') : s.type\n if (type === 'array') return `${typeHint(s.items, depth)}[]`\n if (type === 'object' || s.properties) {\n if (depth > 1 || !s.properties) return 'object'\n return objectHint(s, depth + 1)\n }\n return type ?? 'any'\n}\n\nconst objectHint = (s: JsonSchemaLike, depth = 0): string => {\n const required = new Set(s.required ?? [])\n const props = Object.entries(s.properties ?? {})\n if (props.length === 0) return '{}'\n return `{ ${props\n .slice(0, 12)\n .map(([k, v]) => `${k}${required.has(k) ? '' : '?'}: ${typeHint(v, depth)}`)\n .join(', ')}${props.length > 12 ? ', …' : ''} }`\n}\n\n/**\n * A short parameter hint (\"{ text: string, x?: number }\") derived from a\n * tool's JSON schema — so tools without a hand-written `promptHint` (every MCP\n * tool) still tell a prompted model what to pass. Undefined when unknown.\n */\nexport const schemaHintOf = async (t: Tool): Promise<string | undefined> => {\n const own = promptHintOf(t)\n if (own) return own\n try {\n const schema = (await asSchema(t.inputSchema as never).jsonSchema) as JsonSchemaLike\n return schema && typeof schema === 'object' ? objectHint(schema) : undefined\n } catch {\n return undefined\n }\n}\n","import { FILES_STORE, openAgentWebDB } from '../storage/db.js'\nimport { postStorageChangeFrom } from '../sync/notices.js'\nimport { currentTab, type Tab } from '../sync/tab.js'\n\n/**\n * A small virtual file system for the browser — the agent's (and the user's)\n * workspace: attachments the user drops in, reports the agent writes, images\n * pasted into the chat. Persistent in IndexedDB by default, in-memory on\n * request (tests, private mode). Paths are POSIX-like and always absolute\n * (\"/notes/todo.md\"); there are no real directories — a \"directory\" is a path\n * prefix.\n */\nexport interface VirtualFile {\n path: string\n /** Text, or base64 for binary content (see `encoding`). */\n content: string\n encoding: 'utf8' | 'base64'\n mimeType: string\n /** Size of the decoded content in bytes. */\n size: number\n updatedAt: number\n}\n\n/** A listing entry (no content). */\nexport type VirtualFileInfo = Omit<VirtualFile, 'content'>\n\nexport interface VirtualFileSystemOptions {\n /** Keep files in memory only (default false: IndexedDB). */\n memory?: boolean\n /** IndexedDB database name, forwarded to the shared owner (default 'agent-web'). */\n dbName?: string\n /** Isolates several file systems in one database (default 'default'). */\n namespace?: string\n /** Refuse a single file larger than this many bytes (default 10 MB). */\n maxFileBytes?: number\n}\n\nexport type VfsListener = (change: { type: 'write' | 'delete'; path: string }) => void\n\nconst MIME: Record<string, string> = {\n txt: 'text/plain',\n md: 'text/markdown',\n json: 'application/json',\n csv: 'text/csv',\n html: 'text/html',\n css: 'text/css',\n js: 'text/javascript',\n ts: 'text/typescript',\n svg: 'image/svg+xml',\n png: 'image/png',\n jpg: 'image/jpeg',\n jpeg: 'image/jpeg',\n gif: 'image/gif',\n webp: 'image/webp',\n pdf: 'application/pdf',\n xml: 'application/xml',\n yaml: 'text/yaml',\n yml: 'text/yaml',\n}\n\n/** A best-effort MIME type from a file name. */\nexport const mimeFromPath = (path: string): string =>\n MIME[path.split('.').pop()?.toLowerCase() ?? ''] ?? 'application/octet-stream'\n\n/** True for MIME types the agent can read as text. */\nexport const isTextMime = (mime: string): boolean =>\n /^text\\/|json|xml|yaml|javascript|typescript|svg/.test(mime)\n\n/**\n * Normalise a path: absolute, forward slashes, no \".\" / \"..\" / empty segments.\n * Throws on a path that escapes the root.\n */\nexport const normalizePath = (input: string): string => {\n const parts: string[] = []\n for (const seg of String(input ?? '')\n .replace(/\\\\/g, '/')\n .split('/')) {\n if (!seg || seg === '.') continue\n if (seg === '..') {\n if (parts.length === 0) throw new Error(`path \"${input}\" escapes the root`)\n parts.pop()\n continue\n }\n parts.push(seg)\n }\n if (parts.length === 0) throw new Error('a file path is required')\n return `/${parts.join('/')}`\n}\n\nconst byteLength = (content: string, encoding: VirtualFile['encoding']): number =>\n encoding === 'base64'\n ? Math.floor((content.replace(/=+$/, '').length * 3) / 4)\n : new TextEncoder().encode(content).length\n\n/** Base64 of bytes, chunked so a large file can't blow the call stack. */\nexport const bytesToBase64 = (bytes: Uint8Array): string => {\n let bin = ''\n for (let i = 0; i < bytes.length; i += 0x8000) {\n bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000))\n }\n return btoa(bin)\n}\n\nexport class VirtualFileSystem {\n /**\n * The IndexedDB database the files live in - and the name the other tabs hear of a change\n * under (`files` notices, see `onStorageChange`). Undefined for an in-memory file system:\n * nothing of it is shared.\n */\n readonly dbName: string | undefined\n /** Isolates several file systems in one database: a `files` notice carries it. */\n readonly namespace: string\n private readonly memory?: Map<string, VirtualFile>\n private readonly ns: string\n private readonly maxFileBytes: number\n private readonly listeners = new Set<VfsListener>()\n private readonly tab: Tab\n\n constructor(opts: VirtualFileSystemOptions = {}) {\n if (opts.memory) this.memory = new Map()\n this.dbName = opts.memory ? undefined : (opts.dbName ?? 'agent-web')\n this.ns = opts.namespace ?? 'default'\n this.namespace = this.ns\n this.maxFileBytes = opts.maxFileBytes ?? 10 * 1024 * 1024\n this.tab = currentTab()\n }\n\n private key(path: string): string {\n return `${this.ns}:${path}`\n }\n\n /** After a write committed: the other tabs hear which file (never its content). */\n private announce(op: 'put' | 'delete', path: string): void {\n postStorageChangeFrom(this.tab, this.dbName, {\n kind: 'files',\n op,\n key: path,\n namespace: this.ns,\n })\n }\n\n /**\n * Subscribe to writes and deletes made through THIS file system (e.g. to refresh a file list).\n * Another tab's changes come as `files` notices (`onStorageChange(vfs.dbName, ...)`). Returns\n * an unsubscribe.\n */\n onChange(listener: VfsListener): () => void {\n this.listeners.add(listener)\n return () => this.listeners.delete(listener)\n }\n\n private notify(type: 'write' | 'delete', path: string): void {\n for (const l of this.listeners) {\n try {\n l({ type, path })\n } catch {\n /* a bad listener must not break a write */\n }\n }\n }\n\n async write(\n path: string,\n content: string | Uint8Array,\n opts: { mimeType?: string; encoding?: VirtualFile['encoding'] } = {},\n ): Promise<VirtualFileInfo> {\n const p = normalizePath(path)\n const binary = content instanceof Uint8Array\n const encoding = binary ? 'base64' : (opts.encoding ?? 'utf8')\n const text = binary ? bytesToBase64(content) : content\n const size = binary ? content.length : byteLength(text, encoding)\n if (size > this.maxFileBytes) {\n throw new Error(`\"${p}\" is ${size} bytes; the limit is ${this.maxFileBytes}`)\n }\n const file: VirtualFile = {\n path: p,\n content: text,\n encoding,\n mimeType: opts.mimeType ?? mimeFromPath(p),\n size,\n updatedAt: Date.now(),\n }\n if (this.memory) this.memory.set(p, file)\n else {\n const db = await openAgentWebDB({ dbName: this.dbName })\n await db.put(FILES_STORE, file, this.key(p))\n this.announce('put', p)\n }\n this.notify('write', p)\n const { content: _drop, ...info } = file\n return info\n }\n\n /** Store a data URL (\"data:image/png;base64,…\") as a file. */\n async writeDataUrl(path: string, dataUrl: string): Promise<VirtualFileInfo> {\n const m = /^data:([^;,]+)?(;base64)?,(.*)$/s.exec(dataUrl)\n if (!m) throw new Error('not a data URL')\n const mimeType = m[1] ?? 'application/octet-stream'\n return m[2]\n ? this.write(path, m[3], { mimeType, encoding: 'base64' })\n : this.write(path, decodeURIComponent(m[3]), { mimeType })\n }\n\n async read(path: string): Promise<VirtualFile | undefined> {\n const p = normalizePath(path)\n if (this.memory) return this.memory.get(p)\n const db = await openAgentWebDB({ dbName: this.dbName })\n return (await db.get(FILES_STORE, this.key(p))) as VirtualFile | undefined\n }\n\n /** The file as a data URL (for <img src>, downloads). */\n async readDataUrl(path: string): Promise<string | undefined> {\n const f = await this.read(path)\n if (!f) return undefined\n return f.encoding === 'base64'\n ? `data:${f.mimeType};base64,${f.content}`\n : `data:${f.mimeType};charset=utf-8,${encodeURIComponent(f.content)}`\n }\n\n async delete(path: string): Promise<boolean> {\n const p = normalizePath(path)\n let existed: boolean\n if (this.memory) existed = this.memory.delete(p)\n else {\n const db = await openAgentWebDB({ dbName: this.dbName })\n existed = (await db.get(FILES_STORE, this.key(p))) !== undefined\n await db.delete(FILES_STORE, this.key(p))\n if (existed) this.announce('delete', p)\n }\n if (existed) this.notify('delete', p)\n return existed\n }\n\n /** Files under a prefix (\"/\" = all), sorted by path. */\n async list(prefix = '/'): Promise<VirtualFileInfo[]> {\n const dir = prefix === '/' ? '/' : `${normalizePath(prefix)}/`\n let files: VirtualFile[]\n if (this.memory) files = [...this.memory.values()]\n else {\n const db = await openAgentWebDB({ dbName: this.dbName })\n const range = IDBKeyRange.bound(`${this.ns}:`, `${this.ns}:`)\n files = (await db.getAll(FILES_STORE, range)) as VirtualFile[]\n }\n return files\n .filter((f) => dir === '/' || f.path.startsWith(dir))\n .map(({ content: _drop, ...info }) => info)\n .sort((a, b) => a.path.localeCompare(b.path))\n }\n\n /** Remove every file (of this namespace). */\n async clear(): Promise<void> {\n for (const f of await this.list()) await this.delete(f.path)\n }\n}\n","import { jsonSchema, tool, type ToolSet } from 'ai'\nimport { markReadOnly } from '../tools/approval.js'\nimport { toolRunContextOf } from '../tools/wrap.js'\nimport { isTextMime, normalizePath, type VirtualFileSystem } from './vfs.js'\n\nexport interface FileToolsOptions {\n /** Tool-name prefix (default 'fs_' → fs_list, fs_read, fs_write, fs_delete). */\n prefix?: string\n /** Mount only the read tools (default false). */\n readOnly?: boolean\n /** Cap on the text fs_read returns (default 50 000 chars; the rest is cut with a marker). */\n maxReadChars?: number\n}\n\nconst FILE_TOOL = Symbol.for('@dudko.dev/agent-web:file-tool')\n\n/** What one of these tools does, and on which file system (read by `config.sandbox`). */\nexport interface FileToolBinding {\n vfs: VirtualFileSystem\n op: 'list' | 'read' | 'write' | 'delete'\n}\n\nconst bind = <T extends object>(t: T, binding: FileToolBinding): T => {\n Object.defineProperty(t, FILE_TOOL, { value: binding, enumerable: false })\n return t\n}\n\n/** The file-system binding of a tool made by `createFileTools` (undefined for any other tool). */\nexport const fileToolBindingOf = (t: unknown): FileToolBinding | undefined =>\n t && typeof t === 'object' ? (t as { [FILE_TOOL]?: FileToolBinding })[FILE_TOOL] : undefined\n\n/** A line range `fs_read` was asked for: 1-based, inclusive; `to` undefined is to the end. */\ninterface LineRange {\n from: number\n to?: number\n}\n\n/** The range of `fs_read`'s arguments, checked - or undefined for the whole file. Throws on a bad one. */\nconst lineRangeOf = (startLine: unknown, endLine: unknown): LineRange | undefined => {\n if (startLine === undefined && endLine === undefined) return undefined\n const whole = (v: unknown) => typeof v === 'number' && Number.isInteger(v) && v >= 1\n if (startLine !== undefined && !whole(startLine))\n throw new Error('startLine is a whole number, 1 or more (1 is the first line)')\n if (endLine !== undefined && !whole(endLine))\n throw new Error('endLine is a whole number, 1 or more')\n const from = (startLine as number | undefined) ?? 1\n const to = endLine as number | undefined\n if (to !== undefined && to < from)\n throw new Error(`endLine (${to}) is before startLine (${from})`)\n return { from, ...(to !== undefined ? { to } : {}) }\n}\n\n/**\n * Lines `from`..`to` of a file, after one line that says which they are of how many - and, when\n * they are more than `maxChars`, the whole lines that fit and the line to read on from.\n */\nconst readLines = (path: string, text: string, range: LineRange, maxChars: number): string => {\n const lines = text.split('\\n')\n // A file that ends with a newline has no empty last line to read.\n const count = lines.length > 1 && lines[lines.length - 1] === '' ? lines.length - 1 : lines.length\n if (range.from > count)\n throw new Error(\n `\"${path}\" has ${count} line${count === 1 ? '' : 's'}; startLine ${range.from} is past its end`,\n )\n const last = Math.min(range.to ?? count, count)\n const out: string[] = []\n let size = 0\n let line = range.from\n for (; line <= last; line++) {\n const next = lines[line - 1]\n // At least part of the first line, so a range always gives something to read.\n if (size + next.length + 1 > maxChars && out.length > 0) break\n out.push(next.length > maxChars ? `${next.slice(0, maxChars)}… [line cut]` : next)\n size += next.length + 1\n }\n const shown = line - 1\n const head = `[${path}, lines ${range.from}-${shown} of ${count}]`\n const tail =\n shown < last ? `\\n… [truncated at ${maxChars} chars: read on from line ${shown + 1}]` : ''\n return `${head}\\n${out.join('\\n')}${tail}`\n}\n\n/**\n * Tools that give the agent the virtual file system: list, read, write and\n * delete. Listing and reading are marked read-only, so the `ask-writes`\n * consent mode lets them through and asks before writes and deletes.\n * `fs_read` takes an optional line range (`startLine` / `endLine`) for part of a long file.\n */\nexport const createFileTools = (vfs: VirtualFileSystem, opts: FileToolsOptions = {}): ToolSet => {\n const p = opts.prefix ?? 'fs_'\n const maxRead = opts.maxReadChars ?? 50_000\n const tools: ToolSet = {\n [`${p}list`]: markReadOnly(\n tool({\n description:\n 'List the files in the workspace (attachments the user added, files you wrote). Optionally only under a directory prefix.',\n inputSchema: jsonSchema<{ prefix?: string }>({\n type: 'object',\n properties: { prefix: { type: 'string', description: 'Directory prefix, e.g. \"/docs\"' } },\n additionalProperties: false,\n }),\n execute: async ({ prefix }) =>\n (await vfs.list(prefix || '/')).map((f) => ({\n path: f.path,\n mimeType: f.mimeType,\n size: f.size,\n })),\n }),\n ),\n [`${p}read`]: markReadOnly(\n tool({\n description:\n 'Read a text file from the workspace by its path. For part of a long file, pass a line range: startLine (1 is the first line) and endLine (inclusive; to the end when left out).',\n inputSchema: jsonSchema<{ path: string; startLine?: number; endLine?: number }>({\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Absolute path, e.g. \"/notes.md\"' },\n startLine: {\n type: 'integer',\n minimum: 1,\n description: 'The first line to read (1-based). Leave out for the whole file.',\n },\n endLine: {\n type: 'integer',\n minimum: 1,\n description: 'The last line to read (inclusive). Leave out to read to the end.',\n },\n },\n required: ['path'],\n additionalProperties: false,\n }),\n execute: async ({ path, startLine, endLine }) => {\n const range = lineRangeOf(startLine, endLine)\n const f = await vfs.read(path)\n if (!f) {\n const known = (await vfs.list()).map((x) => x.path).slice(0, 30)\n throw new Error(`no file \"${path}\"; files: ${known.join(', ') || 'none'}`)\n }\n if (f.encoding === 'base64' && !isTextMime(f.mimeType)) {\n return `\"${f.path}\" is a binary file (${f.mimeType}, ${f.size} bytes) and cannot be read as text.`\n }\n const text = f.encoding === 'base64' ? atob(f.content) : f.content\n if (range) return readLines(f.path, text, range, maxRead)\n return text.length > maxRead\n ? `${text.slice(0, maxRead)}… [truncated ${text.length - maxRead} chars]`\n : text\n },\n }),\n ),\n }\n bind(tools[`${p}list`], { vfs, op: 'list' })\n bind(tools[`${p}read`], { vfs, op: 'read' })\n if (opts.readOnly) return tools\n tools[`${p}write`] = tool({\n description:\n 'Write a text file to the workspace (creates or replaces it). Use it for reports, drafts, data the user should be able to open.',\n inputSchema: jsonSchema<{ path: string; content: string; mimeType?: string }>({\n type: 'object',\n properties: {\n path: { type: 'string', description: 'Absolute path, e.g. \"/reports/summary.md\"' },\n content: { type: 'string', description: 'The full file content' },\n mimeType: { type: 'string', description: 'Optional MIME type (guessed from the name)' },\n },\n required: ['path', 'content'],\n additionalProperties: false,\n }),\n execute: async ({ path, content, mimeType }, options) => {\n const info = await vfs.write(path, content, mimeType ? { mimeType } : {})\n // Tell the run what was written (a UI shows it in the turn). Only after the write succeeded.\n const run = toolRunContextOf(options)\n run?.emit({\n type: 'file.written',\n path: info.path,\n mediaType: info.mimeType,\n bytes: info.size,\n ...(run.step ? { step: run.step } : {}),\n })\n return { written: info.path, size: info.size }\n },\n })\n tools[`${p}delete`] = tool({\n description: 'Delete a file from the workspace.',\n inputSchema: jsonSchema<{ path: string }>({\n type: 'object',\n properties: { path: { type: 'string' } },\n required: ['path'],\n additionalProperties: false,\n }),\n execute: async ({ path }, options) => {\n const deleted = await vfs.delete(path)\n const run = toolRunContextOf(options)\n if (deleted) {\n run?.emit({\n type: 'file.deleted',\n path: normalizePath(path),\n ...(run.step ? { step: run.step } : {}),\n })\n }\n return { deleted }\n },\n })\n bind(tools[`${p}write`], { vfs, op: 'write' })\n bind(tools[`${p}delete`], { vfs, op: 'delete' })\n return tools\n}\n"],"mappings":";;;;;;;;;;;AAmCA,IAAM,OAAO,CAAC,OAA2BA,SACvC,OAAOA,SAAQ,YAAYA,OAAM,MAAM,SAAS,MAAMA;AAMjD,IAAM,cAAc,CACzB,OACA,WAC4B;AAC5B,MAAI,CAAC,OAAQ,QAAO;AACpB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a,WAA6B;AAAA,MACxC,MAAM;AAAA,MACN,YAAY,EAAE,MAAM,EAAE,MAAM,SAAS,EAAE;AAAA,MACvC,UAAU,CAAC,MAAM;AAAA,MACjB,sBAAsB;AAAA,IACxB,CAAC;AAAA,IACD,SAAS,OAAO,EAAE,KAAK,GAAG,YAAY;AACpC,YAAM,UAAU,MAAM,IAAI,OAAO,IAAI;AACrC,YAAM,MAAM,iBAAiB,OAAO;AACpC,UAAI,SAAS;AACX,aAAK,KAAK;AAAA,UACR,MAAM;AAAA,UACN,MAAM,cAAc,IAAI;AAAA,UACxB,GAAI,IAAI,OAAO,EAAE,MAAM,IAAI,KAAK,IAAI,CAAC;AAAA,QACvC,CAAC;AAAA,MACH;AACA,aAAO,EAAE,QAAQ;AAAA,IACnB;AAAA,EACF,CAAC;AACD,OAAK,MAAM,GAAG,CAAC,OAAO,GAAG,EAAE,KAAK,IAAI,QAAQ,CAAC;AAC7C,OAAK,MAAM,GAAG,CAAC,QAAQ,GAAG,EAAE,KAAK,IAAI,SAAS,CAAC;AAC/C,SAAO;AACT;","names":["cap","tool","tool","cap"]}
|
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
// src/tools/media-fit.ts
|
|
2
|
+
var QUALITIES = [0.85, 0.72, 0.6];
|
|
3
|
+
var STEP = 0.75;
|
|
4
|
+
var SIZES = 6;
|
|
5
|
+
var positive = (n) => typeof n === "number" && Number.isFinite(n) && n > 0;
|
|
6
|
+
var scaled = (width, height, scale) => ({
|
|
7
|
+
width: Math.max(1, Math.floor(width * scale)),
|
|
8
|
+
height: Math.max(1, Math.floor(height * scale))
|
|
9
|
+
});
|
|
10
|
+
var isPortrait = (w, h) => w < h;
|
|
11
|
+
var decodeScaled = async (blob, width, height, maxSide) => {
|
|
12
|
+
const scale = Math.min(1, maxSide / Math.max(width, height));
|
|
13
|
+
const target = scaled(width, height, scale);
|
|
14
|
+
const decode = (portrait, w, h) => createImageBitmap(
|
|
15
|
+
blob,
|
|
16
|
+
portrait ? { resizeWidth: w, resizeQuality: "high" } : { resizeHeight: h, resizeQuality: "high" }
|
|
17
|
+
);
|
|
18
|
+
const first = await decode(isPortrait(width, height), target.width, target.height);
|
|
19
|
+
const turned = width !== height && isPortrait(first.width, first.height) !== isPortrait(width, height) && Math.max(first.width, first.height) < Math.max(target.width, target.height);
|
|
20
|
+
if (!turned) return first;
|
|
21
|
+
first.close();
|
|
22
|
+
const again = scaled(height, width, scale);
|
|
23
|
+
return decode(isPortrait(height, width), again.width, again.height);
|
|
24
|
+
};
|
|
25
|
+
var fitSide = (bitmap, maxSide) => scaled(bitmap.width, bitmap.height, Math.min(1, maxSide / Math.max(bitmap.width, bitmap.height)));
|
|
26
|
+
var draw = (bitmap, width, height, opaque) => {
|
|
27
|
+
const canvas = new OffscreenCanvas(width, height);
|
|
28
|
+
const ctx = canvas.getContext("2d");
|
|
29
|
+
if (!ctx) throw new Error("fitReferenceImage: no 2D canvas");
|
|
30
|
+
if (opaque) {
|
|
31
|
+
ctx.fillStyle = "#fff";
|
|
32
|
+
ctx.fillRect(0, 0, width, height);
|
|
33
|
+
}
|
|
34
|
+
ctx.imageSmoothingEnabled = true;
|
|
35
|
+
ctx.imageSmoothingQuality = "high";
|
|
36
|
+
ctx.drawImage(bitmap, 0, 0, width, height);
|
|
37
|
+
return canvas;
|
|
38
|
+
};
|
|
39
|
+
var bytesOf = async (blob) => new Uint8Array(await blob.arrayBuffer());
|
|
40
|
+
var fitReferenceImage = async (picture, bounds, options) => {
|
|
41
|
+
if (typeof createImageBitmap !== "function" || typeof OffscreenCanvas === "undefined") {
|
|
42
|
+
return void 0;
|
|
43
|
+
}
|
|
44
|
+
const { maxSide, maxBytes } = bounds ?? {};
|
|
45
|
+
if (!positive(maxSide) || !positive(maxBytes)) return void 0;
|
|
46
|
+
if (!(picture?.bytes instanceof Uint8Array) || !positive(picture.width) || !positive(picture.height))
|
|
47
|
+
return void 0;
|
|
48
|
+
const signal = options?.signal;
|
|
49
|
+
signal?.throwIfAborted();
|
|
50
|
+
let bitmap;
|
|
51
|
+
try {
|
|
52
|
+
bitmap = await decodeScaled(
|
|
53
|
+
new Blob([picture.bytes], { type: picture.mediaType }),
|
|
54
|
+
picture.width,
|
|
55
|
+
picture.height,
|
|
56
|
+
maxSide
|
|
57
|
+
);
|
|
58
|
+
} catch {
|
|
59
|
+
signal?.throwIfAborted();
|
|
60
|
+
return void 0;
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
let size = fitSide(bitmap, maxSide);
|
|
64
|
+
if (picture.mediaType === "image/png") {
|
|
65
|
+
signal?.throwIfAborted();
|
|
66
|
+
const png = await draw(bitmap, size.width, size.height, false).convertToBlob({
|
|
67
|
+
type: "image/png"
|
|
68
|
+
});
|
|
69
|
+
if (png.size <= maxBytes) return { bytes: await bytesOf(png), mediaType: "image/png" };
|
|
70
|
+
}
|
|
71
|
+
for (let step = 0; step < SIZES; step++) {
|
|
72
|
+
const canvas = draw(bitmap, size.width, size.height, true);
|
|
73
|
+
for (const quality of QUALITIES) {
|
|
74
|
+
signal?.throwIfAborted();
|
|
75
|
+
const jpeg = await canvas.convertToBlob({ type: "image/jpeg", quality });
|
|
76
|
+
if (jpeg.size <= maxBytes) return { bytes: await bytesOf(jpeg), mediaType: jpeg.type };
|
|
77
|
+
}
|
|
78
|
+
size = scaled(size.width, size.height, STEP);
|
|
79
|
+
}
|
|
80
|
+
return void 0;
|
|
81
|
+
} finally {
|
|
82
|
+
bitmap.close();
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
var ownBytes = (bytes) => bytes.byteOffset === 0 && bytes.byteLength === bytes.buffer.byteLength && !(typeof SharedArrayBuffer !== "undefined" && bytes.buffer instanceof SharedArrayBuffer) ? bytes : bytes.slice();
|
|
86
|
+
var fitReferenceInWorker = (createWorker) => (picture, bounds, options) => new Promise((resolve, reject) => {
|
|
87
|
+
const signal = options?.signal;
|
|
88
|
+
if (signal?.aborted) {
|
|
89
|
+
reject(signal.reason ?? new Error("aborted"));
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
let worker;
|
|
93
|
+
try {
|
|
94
|
+
worker = createWorker();
|
|
95
|
+
} catch (err) {
|
|
96
|
+
reject(err);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
let settled = false;
|
|
100
|
+
const finish = (fn) => {
|
|
101
|
+
if (settled) return;
|
|
102
|
+
settled = true;
|
|
103
|
+
signal?.removeEventListener("abort", onAbort);
|
|
104
|
+
worker.terminate();
|
|
105
|
+
fn();
|
|
106
|
+
};
|
|
107
|
+
const onAbort = () => finish(() => reject(signal?.reason ?? new Error("aborted")));
|
|
108
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
109
|
+
worker.addEventListener("message", (ev) => {
|
|
110
|
+
const a = ev.data;
|
|
111
|
+
if (!a || a.type !== "fit-reference") return;
|
|
112
|
+
if (!a.ok) {
|
|
113
|
+
finish(() => reject(new Error(`fitReferenceInWorker: ${String(a.error).slice(0, 200)}`)));
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
finish(
|
|
117
|
+
() => resolve(
|
|
118
|
+
a.bytes instanceof Uint8Array ? {
|
|
119
|
+
bytes: a.bytes,
|
|
120
|
+
...typeof a.mediaType === "string" ? { mediaType: a.mediaType } : {}
|
|
121
|
+
} : void 0
|
|
122
|
+
)
|
|
123
|
+
);
|
|
124
|
+
});
|
|
125
|
+
worker.addEventListener(
|
|
126
|
+
"error",
|
|
127
|
+
(ev) => finish(
|
|
128
|
+
() => reject(new Error(`fitReferenceInWorker: the worker failed (${ev?.message ?? "error"})`))
|
|
129
|
+
)
|
|
130
|
+
);
|
|
131
|
+
worker.addEventListener(
|
|
132
|
+
"messageerror",
|
|
133
|
+
() => finish(() => reject(new Error("fitReferenceInWorker: the answer could not be read")))
|
|
134
|
+
);
|
|
135
|
+
const bytes = ownBytes(picture.bytes);
|
|
136
|
+
const request = {
|
|
137
|
+
type: "fit-reference",
|
|
138
|
+
picture: {
|
|
139
|
+
bytes,
|
|
140
|
+
mediaType: picture.mediaType,
|
|
141
|
+
width: picture.width,
|
|
142
|
+
height: picture.height,
|
|
143
|
+
path: picture.path
|
|
144
|
+
},
|
|
145
|
+
bounds: { maxSide: bounds.maxSide, maxBytes: bounds.maxBytes }
|
|
146
|
+
};
|
|
147
|
+
try {
|
|
148
|
+
worker.postMessage(request, [bytes.buffer]);
|
|
149
|
+
} catch (err) {
|
|
150
|
+
finish(() => reject(err));
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
var serveFitReferenceWorker = (opts = {}) => {
|
|
154
|
+
const scope = opts.scope ?? globalThis;
|
|
155
|
+
const fit = opts.fit ?? fitReferenceImage;
|
|
156
|
+
scope.addEventListener("message", (ev) => {
|
|
157
|
+
const req = ev.data;
|
|
158
|
+
if (!req || req.type !== "fit-reference") return;
|
|
159
|
+
const answer = (a, transfer = []) => scope.postMessage(a, transfer);
|
|
160
|
+
const signal = new AbortController().signal;
|
|
161
|
+
Promise.resolve().then(() => fit(req.picture, req.bounds, { signal })).then(
|
|
162
|
+
(out) => {
|
|
163
|
+
if (!out || !(out.bytes instanceof Uint8Array)) {
|
|
164
|
+
answer({ type: "fit-reference", ok: true });
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
const bytes = ownBytes(out.bytes);
|
|
168
|
+
answer(
|
|
169
|
+
{
|
|
170
|
+
type: "fit-reference",
|
|
171
|
+
ok: true,
|
|
172
|
+
bytes,
|
|
173
|
+
...typeof out.mediaType === "string" ? { mediaType: out.mediaType } : {}
|
|
174
|
+
},
|
|
175
|
+
[bytes.buffer]
|
|
176
|
+
);
|
|
177
|
+
},
|
|
178
|
+
(err) => answer({
|
|
179
|
+
type: "fit-reference",
|
|
180
|
+
ok: false,
|
|
181
|
+
error: err instanceof Error ? err.message : String(err)
|
|
182
|
+
})
|
|
183
|
+
);
|
|
184
|
+
});
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
export {
|
|
188
|
+
fitReferenceImage,
|
|
189
|
+
fitReferenceInWorker,
|
|
190
|
+
serveFitReferenceWorker
|
|
191
|
+
};
|
|
192
|
+
//# sourceMappingURL=chunk-R5VCITT3.js.map
|