gemi 0.237.0 → 0.237.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +172 -172
- package/dist/ai/index.js.map +4 -4
- package/dist/ai/store/DatabaseAgentStore.d.ts.map +1 -1
- package/dist/ai/testing/index.js +1 -1
- package/dist/app/index.js +1 -1
- package/dist/auth/UserProvider.d.ts +5 -22
- package/dist/auth/UserProvider.d.ts.map +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-5nn0pgxg.js → chunk-1etmnz40.js} +2 -2
- package/dist/{chunk-5nn0pgxg.js.map → chunk-1etmnz40.js.map} +1 -1
- package/dist/{chunk-t4yx1jqb.js → chunk-2apm69wz.js} +1 -1
- package/dist/{chunk-fgnpyj44.js → chunk-2as2xfem.js} +2 -2
- package/dist/{chunk-fgnpyj44.js.map → chunk-2as2xfem.js.map} +1 -1
- package/dist/{chunk-qj2r0v7w.js → chunk-2fw9pm64.js} +2 -2
- package/dist/{chunk-qj2r0v7w.js.map → chunk-2fw9pm64.js.map} +1 -1
- package/dist/{chunk-0kjcd94c.js → chunk-34a5b9xt.js} +2 -2
- package/dist/{chunk-0kjcd94c.js.map → chunk-34a5b9xt.js.map} +1 -1
- package/dist/{chunk-5fxdjmgd.js → chunk-358krc4n.js} +2 -2
- package/dist/{chunk-5fxdjmgd.js.map → chunk-358krc4n.js.map} +1 -1
- package/dist/{chunk-5pbjc6tm.js → chunk-49kkapvr.js} +2 -2
- package/dist/{chunk-5pbjc6tm.js.map → chunk-49kkapvr.js.map} +1 -1
- package/dist/{chunk-rmwhvgvg.js → chunk-4pjv77s5.js} +2 -2
- package/dist/{chunk-rmwhvgvg.js.map → chunk-4pjv77s5.js.map} +1 -1
- package/dist/{chunk-g29wz7h7.js → chunk-4rs6w1gp.js} +2 -2
- package/dist/{chunk-g29wz7h7.js.map → chunk-4rs6w1gp.js.map} +1 -1
- package/dist/{chunk-7b4tsj9x.js → chunk-4wdc4q33.js} +2 -2
- package/dist/{chunk-7b4tsj9x.js.map → chunk-4wdc4q33.js.map} +1 -1
- package/dist/{chunk-k9devrb5.js → chunk-692nx054.js} +2 -2
- package/dist/{chunk-k9devrb5.js.map → chunk-692nx054.js.map} +1 -1
- package/dist/{chunk-dj5d9wcc.js → chunk-7qhqqf0q.js} +2 -2
- package/dist/{chunk-dj5d9wcc.js.map → chunk-7qhqqf0q.js.map} +1 -1
- package/dist/{chunk-ejf6sz1d.js → chunk-7ytazpjd.js} +1 -1
- package/dist/{chunk-9447c20x.js → chunk-80kga3p1.js} +1 -1
- package/dist/{chunk-89jc9yg9.js → chunk-88c8ck33.js} +3 -3
- package/dist/{chunk-89jc9yg9.js.map → chunk-88c8ck33.js.map} +1 -1
- package/dist/{chunk-dmzgw2d8.js → chunk-8adbpxpm.js} +2 -2
- package/dist/{chunk-dmzgw2d8.js.map → chunk-8adbpxpm.js.map} +1 -1
- package/dist/{chunk-n78b8pp5.js → chunk-8ccjtbm2.js} +27 -27
- package/dist/{chunk-n78b8pp5.js.map → chunk-8ccjtbm2.js.map} +3 -3
- package/dist/{chunk-p91yn1b8.js → chunk-8kp4rkd3.js} +2 -2
- package/dist/{chunk-p91yn1b8.js.map → chunk-8kp4rkd3.js.map} +1 -1
- package/dist/{chunk-yca8nznt.js → chunk-9779ngzq.js} +2 -2
- package/dist/{chunk-yca8nznt.js.map → chunk-9779ngzq.js.map} +1 -1
- package/dist/{chunk-7159w4qq.js → chunk-97t5t8jp.js} +3 -3
- package/dist/{chunk-7159w4qq.js.map → chunk-97t5t8jp.js.map} +1 -1
- package/dist/{chunk-yb7yw0cp.js → chunk-9wf36729.js} +1 -1
- package/dist/chunk-ab5xsxyx.js +13 -0
- package/dist/{chunk-nznkpf8r.js.map → chunk-ab5xsxyx.js.map} +3 -3
- package/dist/{chunk-gakdsme3.js → chunk-ajyfp09w.js} +2 -2
- package/dist/{chunk-gakdsme3.js.map → chunk-ajyfp09w.js.map} +1 -1
- package/dist/{chunk-185k67yf.js → chunk-bxby9c62.js} +2 -2
- package/dist/{chunk-185k67yf.js.map → chunk-bxby9c62.js.map} +1 -1
- package/dist/{chunk-c6zpn9yp.js → chunk-ca1qwsjj.js} +2 -2
- package/dist/{chunk-c6zpn9yp.js.map → chunk-ca1qwsjj.js.map} +1 -1
- package/dist/{chunk-fb0bazw9.js → chunk-cckfxk08.js} +2 -2
- package/dist/{chunk-fb0bazw9.js.map → chunk-cckfxk08.js.map} +1 -1
- package/dist/chunk-cwkf46bk.js +5 -0
- package/dist/{chunk-2mjtssv3.js.map → chunk-cwkf46bk.js.map} +1 -1
- package/dist/{chunk-q4b79hjb.js → chunk-d2jafhaf.js} +4 -4
- package/dist/{chunk-q4b79hjb.js.map → chunk-d2jafhaf.js.map} +1 -1
- package/dist/{chunk-krfz1rzm.js → chunk-dh1wbntq.js} +2 -2
- package/dist/{chunk-krfz1rzm.js.map → chunk-dh1wbntq.js.map} +1 -1
- package/dist/{chunk-b9gf8sqq.js → chunk-dt8bxq4c.js} +2 -2
- package/dist/{chunk-b9gf8sqq.js.map → chunk-dt8bxq4c.js.map} +1 -1
- package/dist/{chunk-vc7ny5zs.js → chunk-ea5fv4h9.js} +2 -2
- package/dist/{chunk-vc7ny5zs.js.map → chunk-ea5fv4h9.js.map} +1 -1
- package/dist/{chunk-gj4hg8xk.js → chunk-engdyem1.js} +2 -2
- package/dist/{chunk-gj4hg8xk.js.map → chunk-engdyem1.js.map} +1 -1
- package/dist/{chunk-3jr6d0cb.js → chunk-fhbre39m.js} +2 -2
- package/dist/{chunk-3jr6d0cb.js.map → chunk-fhbre39m.js.map} +1 -1
- package/dist/chunk-g6re0kkk.js +88 -0
- package/dist/{chunk-bcb1dwhb.js.map → chunk-g6re0kkk.js.map} +4 -4
- package/dist/{chunk-a9p3djqm.js → chunk-g7exgg3k.js} +2 -2
- package/dist/{chunk-a9p3djqm.js.map → chunk-g7exgg3k.js.map} +1 -1
- package/dist/{chunk-k2jxxdj1.js → chunk-gbgwtaqq.js} +1 -1
- package/dist/{chunk-2d757e1s.js → chunk-h0b4rjzn.js} +2 -2
- package/dist/{chunk-2d757e1s.js.map → chunk-h0b4rjzn.js.map} +1 -1
- package/dist/{chunk-jfqfvx3t.js → chunk-h2cvg5r5.js} +2 -2
- package/dist/{chunk-jfqfvx3t.js.map → chunk-h2cvg5r5.js.map} +1 -1
- package/dist/{chunk-3p4wdpag.js → chunk-hgwtg5zp.js} +2 -2
- package/dist/{chunk-3p4wdpag.js.map → chunk-hgwtg5zp.js.map} +1 -1
- package/dist/{chunk-9ey725pw.js → chunk-hk37x8mp.js} +1 -1
- package/dist/{chunk-96v1bwg4.js → chunk-j0bbh93g.js} +2 -2
- package/dist/{chunk-96v1bwg4.js.map → chunk-j0bbh93g.js.map} +1 -1
- package/dist/{chunk-ack021d9.js → chunk-j5r7vm8a.js} +2 -2
- package/dist/{chunk-ack021d9.js.map → chunk-j5r7vm8a.js.map} +1 -1
- package/dist/{chunk-xj3ebwrj.js → chunk-kbz5s9wb.js} +2 -2
- package/dist/{chunk-xj3ebwrj.js.map → chunk-kbz5s9wb.js.map} +1 -1
- package/dist/{chunk-fp6mxxkq.js → chunk-kgpqz8te.js} +2 -2
- package/dist/{chunk-fp6mxxkq.js.map → chunk-kgpqz8te.js.map} +1 -1
- package/dist/{chunk-tmpfcx0v.js → chunk-mhvg8nnb.js} +2 -2
- package/dist/{chunk-tmpfcx0v.js.map → chunk-mhvg8nnb.js.map} +1 -1
- package/dist/{chunk-07fy1618.js → chunk-mk8jwsm4.js} +2 -2
- package/dist/{chunk-07fy1618.js.map → chunk-mk8jwsm4.js.map} +1 -1
- package/dist/{chunk-z55c52fm.js → chunk-mn5xxg4q.js} +2 -2
- package/dist/{chunk-z55c52fm.js.map → chunk-mn5xxg4q.js.map} +1 -1
- package/dist/{chunk-vrp3zzz4.js → chunk-mt68n713.js} +2 -2
- package/dist/{chunk-vrp3zzz4.js.map → chunk-mt68n713.js.map} +1 -1
- package/dist/{chunk-fp31t0ey.js → chunk-mykr2v6g.js} +3 -3
- package/dist/{chunk-fp31t0ey.js.map → chunk-mykr2v6g.js.map} +1 -1
- package/dist/{chunk-8591j0cj.js → chunk-nxap8bmy.js} +2 -2
- package/dist/{chunk-8591j0cj.js.map → chunk-nxap8bmy.js.map} +1 -1
- package/dist/{chunk-mwe7hpbd.js → chunk-p7ae0rnf.js} +2 -2
- package/dist/{chunk-mwe7hpbd.js.map → chunk-p7ae0rnf.js.map} +1 -1
- package/dist/{chunk-va2p7e59.js → chunk-pb7n7vaq.js} +1 -1
- package/dist/{chunk-trbwk80g.js → chunk-pe4f30nw.js} +2 -2
- package/dist/{chunk-trbwk80g.js.map → chunk-pe4f30nw.js.map} +1 -1
- package/dist/{chunk-5kjnbmwp.js → chunk-prvncxxf.js} +3 -3
- package/dist/{chunk-5kjnbmwp.js.map → chunk-prvncxxf.js.map} +1 -1
- package/dist/{chunk-2h1ta6cv.js → chunk-q1grt110.js} +2 -2
- package/dist/{chunk-2h1ta6cv.js.map → chunk-q1grt110.js.map} +1 -1
- package/dist/{chunk-h6z5k6yh.js → chunk-s3fpkpdh.js} +2 -2
- package/dist/{chunk-h6z5k6yh.js.map → chunk-s3fpkpdh.js.map} +1 -1
- package/dist/{chunk-t6xe3jr4.js → chunk-sajfdtkt.js} +2 -2
- package/dist/{chunk-t6xe3jr4.js.map → chunk-sajfdtkt.js.map} +1 -1
- package/dist/{chunk-5c538k7m.js → chunk-tfefp5jh.js} +2 -2
- package/dist/{chunk-5c538k7m.js.map → chunk-tfefp5jh.js.map} +1 -1
- package/dist/{chunk-a3s6cp49.js → chunk-txf4kfze.js} +2 -2
- package/dist/{chunk-a3s6cp49.js.map → chunk-txf4kfze.js.map} +1 -1
- package/dist/{chunk-y9efbqmp.js → chunk-vf9jtq9h.js} +2 -2
- package/dist/{chunk-y9efbqmp.js.map → chunk-vf9jtq9h.js.map} +1 -1
- package/dist/{chunk-kpbm4mbc.js → chunk-vtf7tkef.js} +2 -2
- package/dist/{chunk-kpbm4mbc.js.map → chunk-vtf7tkef.js.map} +1 -1
- package/dist/{chunk-z0xmyrjb.js → chunk-wgpg670d.js} +1 -1
- package/dist/{chunk-vbmtyxr4.js → chunk-wj0q7tyn.js} +3 -3
- package/dist/{chunk-vbmtyxr4.js.map → chunk-wj0q7tyn.js.map} +1 -1
- package/dist/{chunk-sxtg2qha.js → chunk-wskms8nf.js} +1 -1
- package/dist/{chunk-2gj2nhve.js → chunk-wzng3k56.js} +2 -2
- package/dist/{chunk-2gj2nhve.js.map → chunk-wzng3k56.js.map} +1 -1
- package/dist/{chunk-x8pk6qqs.js → chunk-xe76d4v6.js} +2 -2
- package/dist/{chunk-x8pk6qqs.js.map → chunk-xe76d4v6.js.map} +1 -1
- package/dist/{chunk-jwh7t982.js → chunk-xm0fb17q.js} +3 -3
- package/dist/{chunk-jwh7t982.js.map → chunk-xm0fb17q.js.map} +1 -1
- package/dist/{chunk-pqaha4f1.js → chunk-xr8mcx1y.js} +2 -2
- package/dist/{chunk-pqaha4f1.js.map → chunk-xr8mcx1y.js.map} +1 -1
- package/dist/{chunk-w7rgnjt5.js → chunk-y73xy0zy.js} +2 -2
- package/dist/{chunk-w7rgnjt5.js.map → chunk-y73xy0zy.js.map} +1 -1
- package/dist/{chunk-fx45rbbn.js → chunk-ygfwbh8p.js} +2 -2
- package/dist/{chunk-fx45rbbn.js.map → chunk-ygfwbh8p.js.map} +1 -1
- package/dist/{chunk-bg0da5pd.js → chunk-zz0k1na4.js} +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/DB.d.ts.map +1 -1
- package/dist/facades/index.js +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/index.js +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/Model.d.ts.map +1 -1
- package/dist/orm/context.d.ts +50 -0
- package/dist/orm/context.d.ts.map +1 -1
- package/dist/orm/index.js +3 -3
- package/dist/orm/index.js.map +3 -3
- package/dist/probe/index.js +2 -2
- package/dist/probe/index.js.map +1 -1
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/lock/DatabaseLockStore.d.ts.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vitest/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-2mjtssv3.js +0 -5
- package/dist/chunk-bcb1dwhb.js +0 -88
- package/dist/chunk-nznkpf8r.js +0 -9
- /package/dist/{chunk-t4yx1jqb.js.map → chunk-2apm69wz.js.map} +0 -0
- /package/dist/{chunk-ejf6sz1d.js.map → chunk-7ytazpjd.js.map} +0 -0
- /package/dist/{chunk-9447c20x.js.map → chunk-80kga3p1.js.map} +0 -0
- /package/dist/{chunk-yb7yw0cp.js.map → chunk-9wf36729.js.map} +0 -0
- /package/dist/{chunk-k2jxxdj1.js.map → chunk-gbgwtaqq.js.map} +0 -0
- /package/dist/{chunk-9ey725pw.js.map → chunk-hk37x8mp.js.map} +0 -0
- /package/dist/{chunk-va2p7e59.js.map → chunk-pb7n7vaq.js.map} +0 -0
- /package/dist/{chunk-z0xmyrjb.js.map → chunk-wgpg670d.js.map} +0 -0
- /package/dist/{chunk-sxtg2qha.js.map → chunk-wskms8nf.js.map} +0 -0
- /package/dist/{chunk-bg0da5pd.js.map → chunk-zz0k1na4.js.map} +0 -0
package/dist/ai/index.js.map
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
"import { existsSync, readdirSync, readFileSync } from \"node:fs\";\nimport { isAbsolute, join, relative, sep } from \"node:path\";\n\nimport { projectRoot } from \"../support/discover\";\n\n/**\n * The file `gemi build` writes under `dist/server`: every Markdown file under `app/agents`,\n * keyed by its path from the project root (`app/agents/siteNamer/name.md`).\n * @internal\n */\nexport const PROMPTS_MANIFEST = \"prompts.json\";\n\n/**\n * The values a prompt's `{{placeholders}}` are filled from.\n */\nexport type PromptValues = Record<string, string | number>;\n\nexport interface PromptOptions {\n /**\n * The folder prompt names resolve under, relative to the working directory\n * (or absolute). Default `app/agents`: `siteNamer/name` is\n * `app/agents/siteNamer/name.md`, so a prompt can live beside its agent.\n */\n dir?: string;\n /**\n * The folder under `dir` that a bare name (no `/`) resolves in. Default\n * `prompts`: `copy-guide` is `app/agents/prompts/copy-guide.md`.\n */\n shared?: string;\n /**\n * Keep each file after its first read. Default: on when `NODE_ENV` is\n * `production`, off otherwise, so an edited prompt is read again in dev.\n */\n cache?: boolean;\n}\n\n/**\n * Where one render looks (#1163): `Prompt.render(name, values, { dir })`.\n * Unset fields fall back to `Prompt.configure`'s, then the defaults.\n */\nexport type PromptLocation = Pick<PromptOptions, \"dir\" | \"shared\">;\n\n// A partial is `{{> name}}`; a placeholder is `{{name}}`. Neither allows\n// spaces inside the name's braces, so the `{{ ... }}` of a JSX style object or\n// a template-language example in a prompt is left as it is.\nconst PARTIAL = /\\{\\{>\\s*([\\w./-]+)\\s*\\}\\}/g;\nconst PLACEHOLDER = /\\{\\{(\\w+)\\}\\}/g;\nconst NAME = /^[\\w-]+(\\/[\\w-]+)*$/;\n\nconst defaults = { dir: \"app/agents\", shared: \"prompts\" };\nlet options: PromptOptions = {};\nconst files = new Map<string, string>();\n// `gemi build`'s manifest, read once. `undefined`: not read yet; `null`: none.\nlet built: Record<string, string> | null | undefined;\n\nfunction builtPrompts(): Record<string, string> | null {\n if (built === undefined) {\n const file = join(projectRoot(), \"dist\", \"server\", PROMPTS_MANIFEST);\n built = existsSync(file) ? JSON.parse(readFileSync(file, \"utf8\")) : null;\n }\n return built ?? null;\n}\n\nfunction trimFinalNewline(text: string) {\n return text.replace(/\\r?\\n$/, \"\");\n}\n\n/**\n * Every prompt file under `rootDir/app/agents`, keyed by its path from\n * `rootDir`: what `gemi build` writes to `dist/server/prompts.json`, so\n * `gemi start` renders prompts from an image that ships no `app/` source.\n * @internal\n */\nexport function bundlePrompts(rootDir: string): Record<string, string> {\n const prompts: Record<string, string> = {};\n const agents = join(rootDir, defaults.dir);\n if (!existsSync(agents)) return prompts;\n const found = readdirSync(agents, { recursive: true, encoding: \"utf8\" });\n for (const file of found.sort()) {\n if (!file.endsWith(\".md\") || file.split(sep).includes(\"node_modules\")) continue;\n const key = [defaults.dir, ...file.split(sep)].join(\"/\");\n prompts[key] = trimFinalNewline(readFileSync(join(agents, file), \"utf8\"));\n }\n return prompts;\n}\n\nfunction caching() {\n return options.cache ?? process.env.NODE_ENV === \"production\";\n}\n\nfunction pathOf(name: string, at: PromptLocation) {\n if (!NAME.test(name)) {\n throw new Error(\n `\"${name}\" is not a prompt name. Use letters, digits, \"-\" and \"_\", with \"/\" between folders.`,\n );\n }\n const dir = at.dir ?? options.dir ?? defaults.dir;\n const root = isAbsolute(dir) ? dir : join(process.cwd(), dir);\n const file = name.includes(\"/\")\n ? `${name}.md`\n : join(at.shared ?? options.shared ?? defaults.shared, `${name}.md`);\n return join(root, file);\n}\n\nfunction read(name: string, at: PromptLocation) {\n const path = pathOf(name, at);\n const cached = caching() ? files.get(path) : undefined;\n if (cached !== undefined) return cached;\n const production = process.env.NODE_ENV === \"production\";\n if (production) {\n const fromBuild = builtPrompts()?.[relative(projectRoot(), path).split(sep).join(\"/\")];\n if (fromBuild !== undefined) return fromBuild;\n }\n let text: string;\n try {\n text = trimFinalNewline(readFileSync(path, \"utf8\"));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"ENOENT\") {\n const manifest = production ? ` or in dist/server/${PROMPTS_MANIFEST}` : \"\";\n throw new Error(`The prompt \"${name}\" does not exist (looked for ${path}${manifest}).`);\n }\n throw error;\n }\n if (caching()) files.set(path, text);\n return text;\n}\n\nfunction expand(name: string, stack: string[], at: PromptLocation): string {\n if (stack.includes(name)) {\n throw new Error(`The prompt \"${name}\" includes itself: ${[...stack, name].join(\" > \")}.`);\n }\n return read(name, at).replace(PARTIAL, (_, partial: string) =>\n expand(partial, [...stack, name], at),\n );\n}\n\n/**\n * Markdown prompt files with `{{placeholders}}`.\n *\n * ```ts\n * import { Prompt } from \"gemi/ai\";\n *\n * // app/agents/siteNamer/name.md: \"Name a site for {{business}}. {{> shared/tone}}\"\n * Prompt.render(\"siteNamer/name\", { business: \"a bakery\" });\n * ```\n */\nexport class Prompt {\n /**\n * Change where prompts are read from, or whether they are cached. Call it\n * once at boot (a service provider, `app/preload.ts`, a test setup file).\n * Each call replaces the previous options and clears the cache (and forgets\n * the `gemi build` manifest, which is read again on the next render).\n */\n static configure(next: PromptOptions) {\n options = { ...next };\n files.clear();\n built = undefined;\n }\n\n /**\n * The prompt `name`, its partials (`{{> other/name}}`) included and its\n * `{{placeholders}}` filled from `values`, without the file's final newline.\n *\n * A name with a `/` is a path under `dir` (`siteNamer/name`); a bare name is\n * a shared prompt (`copy-guide` is `prompts/copy-guide.md`). Partials resolve\n * the same way and share `values`.\n *\n * Throws when the file (or a partial) is missing, a partial includes itself,\n * or a placeholder has no value, so a prompt never reaches the model with a\n * `{{placeholder}}` left in it. A value no placeholder uses is ignored.\n *\n * `at` reads this render from another folder (#1163) without touching the\n * configured one: `{ dir: \"evals\" }` resolves the name and its partials\n * under `evals`, while every other render keeps using `app/agents`.\n */\n static render(name: string, values: PromptValues = {}, at: PromptLocation = {}): string {\n return expand(name, [], at).replace(PLACEHOLDER, (_, key: string) => {\n if (!Object.hasOwn(values, key)) {\n throw new Error(`The prompt \"${name}\" has no value for {{${key}}}.`);\n }\n return String(values[key]);\n });\n }\n\n /**\n * The placeholder names `name` uses, its partials included, in order of\n * first use. For a test that checks a caller passes every value.\n */\n static placeholders(name: string, at: PromptLocation = {}): string[] {\n const keys = [...expand(name, [], at).matchAll(PLACEHOLDER)].map((match) => match[1]);\n return [...new Set(keys)];\n }\n}\n",
|
|
6
6
|
"import { CronJob } from \"../../services/cron/CronJob\";\nimport { AgentJobs } from \"./AgentJob\";\n\n/**\n * Fails background jobs that ran past their deadline (#461), every minute.\n *\n * Schedule it by exporting it from a file under `app/cron`:\n *\n * export { AgentJobDeadlineSweep } from \"gemi/ai\";\n *\n * Safe on every instance at once: each job is failed by compare-and-set. An\n * app without it still sees an overdue job fail, when the controller next\n * loads the job's thread.\n */\nexport class AgentJobDeadlineSweep extends CronJob {\n name = \"AgentJobDeadlineSweep\";\n cron = \"* * * * *\";\n\n async callback(): Promise<void> {\n // In rounds, so a backlog after an outage is cleared in one tick without\n // holding one huge result set.\n while ((await AgentJobs.sweep({ limit: 100 })) === 100) {\n // keep going\n }\n }\n}\n",
|
|
7
7
|
"import { type AgentJobRecord, isSettled } from \"./AgentJobStore\";\n\n/** How many jobs the `<jobs>` block lists by default. */\nexport const DEFAULT_JOBS_CONTEXT_MAX = 20;\n\n/** `Agent.create({ jobs })`. */\nexport type AgentJobsOptions = {\n /**\n * The `<jobs>` block added to the system prompt on a thread that has\n * background jobs: at most `max` of them (default 20), running ones first,\n * then the newest settled. `false` leaves it out.\n */\n contextBlock?: { max?: number } | false;\n};\n\nconst SUMMARY_CHARS = 300;\nconst ERROR_CHARS = 200;\n\n/**\n * The `<jobs>` block (#461): what the model is told about the thread's\n * background jobs on every turn, beside the tool results in the history.\n *\n * The history already shows each job's call and its `running` or settled\n * result. The block is for what the history cannot show: a job whose result\n * never reached the thread (an orphan), and a list in one place, so a model\n * asked to \"make the images\" sees that a job for them is already running\n * rather than starting another.\n *\n * Bounded by count, `max`, running before settled and newest first inside\n * each. Times are absolute (UTC) rather than ages, so the block is the same\n * text from one turn to the next until a job starts or settles, and the\n * prompt cache holds in between. `null` when there is nothing to list.\n */\nexport function renderJobsBlock(jobs: AgentJobRecord[], max: number): string | null {\n if (max <= 0 || jobs.length === 0) return null;\n const newest = (a: AgentJobRecord, b: AgentJobRecord) =>\n b.createdAt - a.createdAt || (a.id < b.id ? 1 : -1);\n const listed = [\n ...jobs.filter((job) => !isSettled(job.state)).sort(newest),\n ...jobs.filter((job) => isSettled(job.state)).sort(newest),\n ].slice(0, max);\n\n const lines = listed.map((job) => {\n const parts = [`- ${job.id} (${job.toolName})`];\n if (job.state === \"waiting\") {\n parts.push(`waiting for ${(job.after ?? []).join(\", \")} since ${iso(job.createdAt)}`);\n } else if (job.state === \"running\") {\n parts.push(`running since ${iso(job.createdAt)}`);\n } else if (job.state === \"ok\") {\n parts.push(`finished at ${iso(job.settledAt ?? job.updatedAt)}`);\n } else {\n const reason = job.error\n ? `${job.error.code}: ${clip(job.error.message, ERROR_CHARS)}`\n : \"failed\";\n parts.push(`failed at ${iso(job.settledAt ?? job.updatedAt)} (${reason})`);\n }\n if (job.summary !== undefined)\n parts.push(`summary: ${clip(JSON.stringify(job.summary), SUMMARY_CHARS)}`);\n if (job.orphaned) {\n parts.push(\"its tool call was lost when the turn that started it was cut short\");\n }\n return parts.join(\"; \");\n });\n\n return [\n \"<jobs>\",\n \"Background jobs that tools started in this conversation, running ones first. A running job's result replaces its tool result when it finishes. Do not start the same work again while a job for it is running.\",\n ...lines,\n \"</jobs>\",\n ].join(\"\\n\");\n}\n\nfunction iso(ms: number): string {\n return new Date(ms).toISOString().replace(/\\.\\d{3}Z$/, \"Z\");\n}\n\nfunction clip(text: string, chars: number): string {\n return text.length <= chars ? text : `${text.slice(0, chars - 1)}…`;\n}\n",
|
|
8
|
-
"import type { SQL, TransactionSQL } from \"bun\";\n\nimport type { DatabaseConnection } from \"../../database/Connection\";\nimport type { Dialect } from \"../../database/dialect\";\nimport { currentConnectionName, currentTransaction, withTransaction } from \"../../orm/context\";\nimport {\n type AgentJobRecord,\n type AgentJobState,\n type AgentJobStore,\n type AgentJobUpdate,\n isSettled,\n type NewAgentJobRecord,\n} from \"./AgentJobStore\";\n\n/**\n * The columns added for `after`, batches, the inbox and checkpoints (#1222).\n * A table made before them still works for everything else; see `columns()`.\n */\nconst LATER_COLUMNS = [\"after_jobs\", \"batch_key\", \"queued\", \"inbox\", \"job_checkpoint\"] as const;\n\n/** How many times an inbox write retries a compare-and-set it lost to another writer. */\nconst INBOX_ATTEMPTS = 20;\n\nexport type DatabaseAgentJobStoreOptions = {\n /**\n * The table. Default `gemi_agent_jobs`. A plain identifier (letters, digits\n * and underscores), because it is spliced into every statement.\n */\n table?: string;\n};\n\ntype Row = Record<string, unknown>;\n\n/**\n * Background jobs (#461) in a table of the app's own database, so a job and\n * its outcome outlive the process: a deploy in the middle of a render no\n * longer loses it, and every instance sees the same state.\n *\n * Opt in, like the agent store:\n *\n * AgentJobs.use(new DatabaseAgentJobStore(app(DatabaseManager).connection()));\n *\n * Written for SQLite, Postgres and MySQL 8 / MariaDB 10.6+ in raw SQL, as the\n * database queue driver is, and the table is the app's to create: add the\n * Prisma model from the docs, or call `createTable()`.\n *\n * - **Compare-and-set** is `UPDATE … WHERE id = ? AND state IN (…)`, so two\n * instances settling one job cannot both win.\n * - **Time** is epoch milliseconds read from the database's clock, so the\n * deadline sweep on any instance agrees on when a job is overdue.\n * - **Transactions.** `ctx.jobs.start` writes the record and queues the job\n * inside `transaction()`. On Postgres and MySQL, with the database queue\n * driver on the same connection, both rows commit together or not at all.\n * With any other queue the dispatch is held until the record has committed.\n */\nexport class DatabaseAgentJobStore implements AgentJobStore {\n readonly table: string;\n private readonly sql: SQL;\n private readonly dialect: Dialect;\n private readonly connection: string | undefined;\n /** Whether the table has `LATER_COLUMNS`, once asked. */\n private later: Promise<boolean> | undefined;\n\n constructor(\n connection: Pick<DatabaseConnection, \"sql\" | \"dialect\"> &\n Partial<Pick<DatabaseConnection, \"name\">>,\n options: DatabaseAgentJobStoreOptions = {},\n ) {\n const table = options.table ?? \"gemi_agent_jobs\";\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {\n throw new Error(\n `The agent jobs table name \"${table}\" is not a plain identifier. Use letters, digits and underscores.`,\n );\n }\n this.table = table;\n this.sql = connection.sql;\n this.dialect = connection.dialect;\n this.connection = connection.name;\n }\n\n /**\n * Creates the table and its indexes if they do not exist: the DDL Prisma\n * generates for the model in the docs. For tests and for an app that does\n * not manage its schema with Prisma.\n */\n async createTable(): Promise<void> {\n for (const statement of createAgentJobsTableStatements(this.dialect, this.table)) {\n await this.sql.unsafe(statement);\n }\n }\n\n /**\n * Runs `fn` in a transaction on this store's connection, joining one that is\n * already open on it. `ctx.jobs.start` writes the record and queues the job\n * in here.\n */\n async transaction<T>(fn: () => Promise<T>): Promise<T> {\n // A store built from a bare `{ sql, dialect }` has no connection name, so\n // it cannot tell its own transaction from another one, and runs without.\n if (this.connection === undefined || this.joinable()) return fn();\n return withTransaction(this.sql, () => fn(), { connection: this.connection });\n }\n\n async create(job: NewAgentJobRecord): Promise<AgentJobRecord> {\n const usesLater =\n job.after !== undefined || job.batch !== undefined || job.queued !== undefined;\n if (usesLater) await this.requireLaterColumns(\"A job with `after` or `batch`\");\n const q = this.q();\n const now = this.clock(q);\n const state = job.state ?? \"running\";\n if (usesLater) {\n await q`\n INSERT INTO ${this.name(q)}\n (id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,\n orphaned, attachment_scope, created_at, updated_at, deadline_at,\n after_jobs, batch_key, queued)\n VALUES\n (${job.id}, ${job.threadId}, ${job.runId}, ${job.toolCallId}, ${job.toolName},\n ${job.owner}, ${job.job}, ${json(job.summary)}, ${state}, 0, ${job.attachmentScope},\n ${now}, ${now}, ${now} + ${this.ms(q, job.deadlineMs)},\n ${json(job.after)}, ${job.batch ?? null}, ${json(job.queued)})\n `;\n } else {\n await q`\n INSERT INTO ${this.name(q)}\n (id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,\n orphaned, attachment_scope, created_at, updated_at, deadline_at)\n VALUES\n (${job.id}, ${job.threadId}, ${job.runId}, ${job.toolCallId}, ${job.toolName},\n ${job.owner}, ${job.job}, ${json(job.summary)}, ${state}, 0, ${job.attachmentScope},\n ${now}, ${now}, ${now} + ${this.ms(q, job.deadlineMs)})\n `;\n }\n const record = await this.get(job.id);\n if (!record)\n throw new Error(`The background job ${job.id} was not found after it was written.`);\n return record;\n }\n\n async get(id: string): Promise<AgentJobRecord | null> {\n const q = this.q();\n const rows: Row[] = await q`SELECT * FROM ${this.name(q)} WHERE id = ${id}`;\n return rows[0] ? recordOf(rows[0]) : null;\n }\n\n async listForThread(\n threadId: string,\n options: { states?: AgentJobState[]; limit?: number } = {},\n ): Promise<AgentJobRecord[]> {\n const q = this.q();\n const states =\n options.states === undefined\n ? q`1 = 1`\n : options.states.length === 0\n ? q`1 = 0`\n : q`state IN (${list(q, options.states)})`;\n const rows: Row[] =\n options.limit === undefined\n ? await q`\n SELECT * FROM ${this.name(q)}\n WHERE thread_id = ${threadId} AND ${states}\n ORDER BY created_at DESC, id DESC\n `\n : await q`\n SELECT * FROM ${this.name(q)}\n WHERE thread_id = ${threadId} AND ${states}\n ORDER BY created_at DESC, id DESC\n LIMIT ${Math.max(0, Math.floor(options.limit))}\n `;\n return rows.map(recordOf);\n }\n\n async transition(id: string, from: AgentJobState[], to: AgentJobUpdate): Promise<boolean> {\n if (from.length === 0) return false;\n if (\"checkpoint\" in to) await this.requireLaterColumns(\"`job.checkpoint`\");\n const q = this.q();\n const now = this.clock(q);\n const sets = [q`updated_at = ${now}`];\n if (to.deadlineMs !== undefined) {\n sets.push(q`deadline_at = ${now} + ${this.ms(q, to.deadlineMs)}`);\n }\n if (\"checkpoint\" in to) sets.push(q`job_checkpoint = ${json(to.checkpoint)}`);\n if (to.state !== undefined) sets.push(q`state = ${to.state}`);\n if (\"output\" in to) sets.push(q`output = ${json(to.output)}`);\n if (\"error\" in to) sets.push(q`error = ${json(to.error)}`);\n // `usage` is a reserved word in MySQL.\n if (\"usage\" in to) sets.push(q`${this.column(q, \"usage\")} = ${json(to.usage)}`);\n if (\"orphaned\" in to) sets.push(q`orphaned = ${to.orphaned ? 1 : 0}`);\n if (to.state !== undefined && isSettled(to.state)) {\n sets.push(\n to.settledAt !== undefined\n ? q`settled_at = COALESCE(settled_at, ${this.ms(q, to.settledAt)})`\n : q`settled_at = COALESCE(settled_at, ${now})`,\n );\n }\n const set = sets.reduce((all, one) => q`${all}, ${one}`);\n const result = await q`\n UPDATE ${this.name(q)} SET ${set}\n WHERE id = ${id} AND state IN (${list(q, from)})\n `;\n return affected(result) > 0;\n }\n\n async overdue(now: number, limit: number): Promise<AgentJobRecord[]> {\n const q = this.q();\n const rows: Row[] = await q`\n SELECT * FROM ${this.name(q)}\n WHERE state = 'running' AND deadline_at <= ${this.ms(q, now)}\n ORDER BY deadline_at, id\n LIMIT ${Math.max(0, Math.floor(limit))}\n `;\n return rows.map(recordOf);\n }\n\n async waitingOn(id: string): Promise<AgentJobRecord[]> {\n // Asked after every settle: a table without the columns has no waiting jobs.\n if (!(await this.columns())) return [];\n const q = this.q();\n const rows: Row[] = await q`\n SELECT * FROM ${this.name(q)}\n WHERE state = 'waiting' AND after_jobs LIKE ${`%${JSON.stringify(id)}%`}\n ORDER BY created_at, id\n `;\n return rows.map(recordOf).filter((record) => record.after?.includes(id));\n }\n\n async waiting(limit: number): Promise<AgentJobRecord[]> {\n const q = this.q();\n const rows: Row[] = await q`\n SELECT * FROM ${this.name(q)}\n WHERE state = 'waiting'\n ORDER BY created_at, id\n LIMIT ${Math.max(0, Math.floor(limit))}\n `;\n return rows.map(recordOf);\n }\n\n async listBatch(batch: string): Promise<AgentJobRecord[]> {\n if (!(await this.columns())) return [];\n const q = this.q();\n const rows: Row[] = await q`\n SELECT * FROM ${this.name(q)} WHERE batch_key = ${batch} ORDER BY created_at, id\n `;\n return rows.map(recordOf);\n }\n\n /**\n * Compare-and-set on the inbox's text, so two senders (or a sender and the\n * job taking its messages) never lose one another's write.\n */\n async appendInbox(id: string, text: string): Promise<boolean> {\n await this.requireLaterColumns(\"`AgentJobs.message`\");\n for (let attempt = 0; attempt < INBOX_ATTEMPTS; attempt++) {\n const q = this.q();\n const [row] = (await q`\n SELECT state, inbox FROM ${this.name(q)} WHERE id = ${id}\n `) as Row[];\n if (!row || isSettled(String(row.state) as AgentJobState)) return false;\n const before = row.inbox === null || row.inbox === undefined ? null : String(row.inbox);\n const after = JSON.stringify([...((parse(before) as string[] | undefined) ?? []), text]);\n const result = await q`\n UPDATE ${this.name(q)} SET inbox = ${after}, updated_at = ${this.clock(q)}\n WHERE id = ${id} AND state IN ('waiting', 'running') AND ${this.sameInbox(q, before)}\n `;\n if (affected(result) > 0) return true;\n }\n throw new Error(`Could not add a message to background job ${id}: too many writers at once.`);\n }\n\n async takeInbox(id: string): Promise<string[]> {\n if (!(await this.columns())) return [];\n for (let attempt = 0; attempt < INBOX_ATTEMPTS; attempt++) {\n const q = this.q();\n const [row] = (await q`SELECT inbox FROM ${this.name(q)} WHERE id = ${id}`) as Row[];\n if (!row || row.inbox === null || row.inbox === undefined) return [];\n const before = String(row.inbox);\n const result = await q`\n UPDATE ${this.name(q)} SET inbox = NULL WHERE id = ${id} AND ${this.sameInbox(q, before)}\n `;\n if (affected(result) > 0) return (parse(before) as string[] | undefined) ?? [];\n }\n throw new Error(`Could not take the messages of background job ${id}: too many writers.`);\n }\n\n async now(): Promise<number> {\n const q = this.q();\n const [row] = (await q`SELECT ${this.clock(q)} AS now`) as Array<{ now: unknown }>;\n return Number(row!.now);\n }\n\n /**\n * Deletes settled jobs that settled more than `olderThanMs` ago, and answers\n * how many. A settled result is written back into the thread on the next\n * turn, after which the record is only history; nothing removes it unless\n * this is called, from a cron job say. Running jobs are never pruned.\n */\n async prune(olderThanMs: number): Promise<number> {\n const q = this.q();\n const result = await q`\n DELETE FROM ${this.name(q)}\n WHERE state IN ('ok', 'error') AND settled_at <= ${this.clock(q)} - ${this.ms(q, olderThanMs)}\n `;\n return affected(result);\n }\n\n /**\n * Whether the table has the columns `after`, batches, the inbox and\n * checkpoints need (#1222). Asked once, outside any transaction (a failed\n * statement would abort a Postgres one), by selecting them from no rows.\n */\n columns(): Promise<boolean> {\n this.later ??= (async () => {\n try {\n await this.sql.unsafe(\n `SELECT ${LATER_COLUMNS.join(\", \")} FROM ${this.quoted(this.table)} WHERE 1 = 0`,\n );\n return true;\n } catch {\n return false;\n }\n })();\n return this.later;\n }\n\n private async requireLaterColumns(what: string): Promise<void> {\n if (await this.columns()) return;\n // Asked again next time: the app may add them without a restart.\n this.later = undefined;\n throw new Error(\n `${what} needs the columns ${LATER_COLUMNS.join(\", \")} on the ${this.table} table, which it does not have. Add them (see docs/ai-background-jobs.md and UPGRADE.md), or call createTable() on a new table.`,\n );\n }\n\n private sameInbox(q: SQL, before: string | null) {\n return before === null ? q`inbox IS NULL` : q`inbox = ${before}`;\n }\n\n private quoted(name: string): string {\n const mysql = this.dialect === \"mysql\" || this.dialect === \"mariadb\";\n return mysql ? `\\`${name}\\`` : `\"${name}\"`;\n }\n\n /** The open ORM transaction, when it is on this store's connection. */\n private joinable(): TransactionSQL | undefined {\n if (this.connection === undefined) return undefined;\n const tx = currentTransaction();\n if (tx === undefined || currentConnectionName() !== this.connection) return undefined;\n return tx;\n }\n\n /** Read at each call and never kept: a stored transaction handle outlives its transaction. */\n private q(): SQL {\n return (this.joinable() as SQL | undefined) ?? this.sql;\n }\n\n private column(q: SQL, name: string) {\n const mysql = this.dialect === \"mysql\" || this.dialect === \"mariadb\";\n return q.unsafe(mysql ? `\\`${name}\\`` : `\"${name}\"`);\n }\n\n private name(q: SQL) {\n const mysql = this.dialect === \"mysql\" || this.dialect === \"mariadb\";\n return q.unsafe(mysql ? `\\`${this.table}\\`` : `\"${this.table}\"`);\n }\n\n /** The database's clock, in epoch milliseconds. As in `DatabaseQueueDriver`. */\n private clock(q: SQL) {\n switch (this.dialect) {\n case \"postgres\":\n return q`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;\n case \"mysql\":\n case \"mariadb\":\n return q`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;\n case \"sqlite\":\n return q`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`;\n }\n }\n\n private ms(q: SQL, value: number) {\n const ms = Math.max(0, Math.round(value));\n return this.dialect === \"mysql\" || this.dialect === \"mariadb\"\n ? q`CAST(${ms} AS SIGNED)`\n : q`CAST(${ms} AS BIGINT)`;\n }\n}\n\nfunction list(q: SQL, values: string[]) {\n return values.map((value) => q`${value}`).reduce((all, one) => q`${all}, ${one}`);\n}\n\nfunction json(value: unknown): string | null {\n return value === undefined ? null : JSON.stringify(value);\n}\n\nfunction parse(value: unknown): unknown {\n if (value === null || value === undefined) return undefined;\n return JSON.parse(String(value));\n}\n\nfunction recordOf(row: Row): AgentJobRecord {\n const summary = parse(row.summary);\n const output = parse(row.output);\n const error = parse(row.error);\n const usage = parse(row.usage);\n const after = parse(row.after_jobs);\n const queued = parse(row.queued);\n const inbox = parse(row.inbox);\n const checkpoint = parse(row.job_checkpoint);\n return {\n id: String(row.id),\n threadId: String(row.thread_id),\n runId: String(row.run_id),\n toolCallId: String(row.tool_call_id),\n toolName: String(row.tool_name),\n owner: row.owner === null || row.owner === undefined ? null : String(row.owner),\n job: row.job === null || row.job === undefined ? null : String(row.job),\n ...(summary !== undefined ? { summary } : {}),\n state: String(row.state) as AgentJobState,\n ...(output !== undefined ? { output } : {}),\n ...(error !== undefined ? { error: error as AgentJobRecord[\"error\"] } : {}),\n ...(usage !== undefined ? { usage: usage as AgentJobRecord[\"usage\"] } : {}),\n ...(Number(row.orphaned) === 1 ? { orphaned: true as const } : {}),\n attachmentScope:\n row.attachment_scope === null || row.attachment_scope === undefined\n ? null\n : String(row.attachment_scope),\n ...(after !== undefined ? { after: after as string[] } : {}),\n ...(row.batch_key === null || row.batch_key === undefined\n ? {}\n : { batch: String(row.batch_key) }),\n ...(queued !== undefined ? { queued: queued as AgentJobRecord[\"queued\"] } : {}),\n ...(inbox !== undefined && (inbox as string[]).length > 0 ? { inbox: inbox as string[] } : {}),\n ...(checkpoint !== undefined ? { checkpoint } : {}),\n createdAt: Number(row.created_at),\n updatedAt: Number(row.updated_at),\n deadlineAt: Number(row.deadline_at),\n ...(row.settled_at === null || row.settled_at === undefined\n ? {}\n : { settledAt: Number(row.settled_at) }),\n };\n}\n\n/** Rows a `DELETE` or `UPDATE` touched, across the three drivers. */\nfunction affected(result: unknown): number {\n const counts = result as { count?: number | null; affectedRows?: number | null };\n return Math.max(Number(counts.count ?? 0), Number(counts.affectedRows ?? 0));\n}\n\n/**\n * The table as Prisma generates it for the model in the docs, with\n * `IF NOT EXISTS` added.\n */\nexport function createAgentJobsTableStatements(dialect: Dialect, table: string): string[] {\n if (dialect === \"mysql\" || dialect === \"mariadb\") {\n return [\n `CREATE TABLE IF NOT EXISTS \\`${table}\\` (\n \\`id\\` VARCHAR(191) NOT NULL,\n \\`thread_id\\` VARCHAR(191) NOT NULL,\n \\`run_id\\` VARCHAR(191) NOT NULL,\n \\`tool_call_id\\` VARCHAR(191) NOT NULL,\n \\`tool_name\\` VARCHAR(191) NOT NULL,\n \\`owner\\` VARCHAR(191) NULL,\n \\`job\\` VARCHAR(191) NULL,\n \\`summary\\` LONGTEXT NULL,\n \\`state\\` VARCHAR(191) NOT NULL,\n \\`output\\` LONGTEXT NULL,\n \\`error\\` LONGTEXT NULL,\n \\`usage\\` LONGTEXT NULL,\n \\`orphaned\\` INTEGER NOT NULL DEFAULT 0,\n \\`attachment_scope\\` VARCHAR(191) NULL,\n \\`created_at\\` BIGINT NOT NULL,\n \\`updated_at\\` BIGINT NOT NULL,\n \\`deadline_at\\` BIGINT NOT NULL,\n \\`settled_at\\` BIGINT NULL,\n \\`after_jobs\\` LONGTEXT NULL,\n \\`batch_key\\` VARCHAR(191) NULL,\n \\`queued\\` LONGTEXT NULL,\n \\`inbox\\` LONGTEXT NULL,\n \\`job_checkpoint\\` LONGTEXT NULL,\n\n INDEX \\`${table}_thread_id_created_at_idx\\`(\\`thread_id\\`, \\`created_at\\`),\n INDEX \\`${table}_state_deadline_at_idx\\`(\\`state\\`, \\`deadline_at\\`),\n PRIMARY KEY (\\`id\\`)\n) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,\n ];\n }\n\n const key = dialect === \"sqlite\" ? `\"id\" TEXT NOT NULL PRIMARY KEY,` : `\"id\" TEXT NOT NULL,`;\n const constraint =\n dialect === \"sqlite\" ? \"\" : `,\\n\\n CONSTRAINT \"${table}_pkey\" PRIMARY KEY (\"id\")`;\n return [\n `CREATE TABLE IF NOT EXISTS \"${table}\" (\n ${key}\n \"thread_id\" TEXT NOT NULL,\n \"run_id\" TEXT NOT NULL,\n \"tool_call_id\" TEXT NOT NULL,\n \"tool_name\" TEXT NOT NULL,\n \"owner\" TEXT,\n \"job\" TEXT,\n \"summary\" TEXT,\n \"state\" TEXT NOT NULL,\n \"output\" TEXT,\n \"error\" TEXT,\n \"usage\" TEXT,\n \"orphaned\" INTEGER NOT NULL DEFAULT 0,\n \"attachment_scope\" TEXT,\n \"created_at\" BIGINT NOT NULL,\n \"updated_at\" BIGINT NOT NULL,\n \"deadline_at\" BIGINT NOT NULL,\n \"settled_at\" BIGINT,\n \"after_jobs\" TEXT,\n \"batch_key\" TEXT,\n \"queued\" TEXT,\n \"inbox\" TEXT,\n \"job_checkpoint\" TEXT${constraint}\n)`,\n `CREATE INDEX IF NOT EXISTS \"${table}_thread_id_created_at_idx\" ON \"${table}\"(\"thread_id\", \"created_at\")`,\n `CREATE INDEX IF NOT EXISTS \"${table}_state_deadline_at_idx\" ON \"${table}\"(\"state\", \"deadline_at\")`,\n ];\n}\n",
|
|
8
|
+
"import type { SQL, TransactionSQL } from \"bun\";\n\nimport type { DatabaseConnection } from \"../../database/Connection\";\nimport type { Dialect } from \"../../database/dialect\";\nimport { currentConnectionName, currentTransaction, withTransaction } from \"../../orm/context\";\nimport {\n type AgentJobRecord,\n type AgentJobState,\n type AgentJobStore,\n type AgentJobUpdate,\n isSettled,\n type NewAgentJobRecord,\n} from \"./AgentJobStore\";\n\n/**\n * The columns added for `after`, batches, the inbox and checkpoints (#1222).\n * A table made before them still works for everything else; see `columns()`.\n */\nconst LATER_COLUMNS = [\"after_jobs\", \"batch_key\", \"queued\", \"inbox\", \"job_checkpoint\"] as const;\n\n/** How many times an inbox write retries a compare-and-set it lost to another writer. */\nconst INBOX_ATTEMPTS = 20;\n\nexport type DatabaseAgentJobStoreOptions = {\n /**\n * The table. Default `gemi_agent_jobs`. A plain identifier (letters, digits\n * and underscores), because it is spliced into every statement.\n */\n table?: string;\n};\n\ntype Row = Record<string, unknown>;\n\n/**\n * Background jobs (#461) in a table of the app's own database, so a job and\n * its outcome outlive the process: a deploy in the middle of a render no\n * longer loses it, and every instance sees the same state.\n *\n * Opt in, like the agent store:\n *\n * AgentJobs.use(new DatabaseAgentJobStore(app(DatabaseManager).connection()));\n *\n * Written for SQLite, Postgres and MySQL 8 / MariaDB 10.6+ in raw SQL, as the\n * database queue driver is, and the table is the app's to create: add the\n * Prisma model from the docs, or call `createTable()`.\n *\n * - **Compare-and-set** is `UPDATE … WHERE id = ? AND state IN (…)`, so two\n * instances settling one job cannot both win.\n * - **Time** is epoch milliseconds read from the database's clock, so the\n * deadline sweep on any instance agrees on when a job is overdue.\n * - **Transactions.** `ctx.jobs.start` writes the record and queues the job\n * inside `transaction()`. On Postgres and MySQL, with the database queue\n * driver on the same connection, both rows commit together or not at all.\n * With any other queue the dispatch is held until the record has committed.\n */\nexport class DatabaseAgentJobStore implements AgentJobStore {\n readonly table: string;\n private readonly sql: SQL;\n private readonly dialect: Dialect;\n private readonly connection: string | undefined;\n /** Whether the table has `LATER_COLUMNS`, once asked. */\n private later: Promise<boolean> | undefined;\n\n constructor(\n connection: Pick<DatabaseConnection, \"sql\" | \"dialect\"> &\n Partial<Pick<DatabaseConnection, \"name\">>,\n options: DatabaseAgentJobStoreOptions = {},\n ) {\n const table = options.table ?? \"gemi_agent_jobs\";\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {\n throw new Error(\n `The agent jobs table name \"${table}\" is not a plain identifier. Use letters, digits and underscores.`,\n );\n }\n this.table = table;\n this.sql = connection.sql;\n this.dialect = connection.dialect;\n this.connection = connection.name;\n }\n\n /**\n * Creates the table and its indexes if they do not exist: the DDL Prisma\n * generates for the model in the docs. For tests and for an app that does\n * not manage its schema with Prisma.\n */\n async createTable(): Promise<void> {\n for (const statement of createAgentJobsTableStatements(this.dialect, this.table)) {\n await this.sql.unsafe(statement);\n }\n }\n\n /**\n * Runs `fn` in a transaction on this store's connection, joining one that is\n * already open on it. `ctx.jobs.start` writes the record and queues the job\n * in here.\n */\n async transaction<T>(fn: () => Promise<T>): Promise<T> {\n // A store built from a bare `{ sql, dialect }` has no connection name, so\n // it cannot tell its own transaction from another one, and runs without.\n if (this.connection === undefined || this.joinable()) return fn();\n return withTransaction(this.sql, () => fn(), { connection: this.connection, dialect: this.dialect });\n }\n\n async create(job: NewAgentJobRecord): Promise<AgentJobRecord> {\n const usesLater =\n job.after !== undefined || job.batch !== undefined || job.queued !== undefined;\n if (usesLater) await this.requireLaterColumns(\"A job with `after` or `batch`\");\n const q = this.q();\n const now = this.clock(q);\n const state = job.state ?? \"running\";\n if (usesLater) {\n await q`\n INSERT INTO ${this.name(q)}\n (id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,\n orphaned, attachment_scope, created_at, updated_at, deadline_at,\n after_jobs, batch_key, queued)\n VALUES\n (${job.id}, ${job.threadId}, ${job.runId}, ${job.toolCallId}, ${job.toolName},\n ${job.owner}, ${job.job}, ${json(job.summary)}, ${state}, 0, ${job.attachmentScope},\n ${now}, ${now}, ${now} + ${this.ms(q, job.deadlineMs)},\n ${json(job.after)}, ${job.batch ?? null}, ${json(job.queued)})\n `;\n } else {\n await q`\n INSERT INTO ${this.name(q)}\n (id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,\n orphaned, attachment_scope, created_at, updated_at, deadline_at)\n VALUES\n (${job.id}, ${job.threadId}, ${job.runId}, ${job.toolCallId}, ${job.toolName},\n ${job.owner}, ${job.job}, ${json(job.summary)}, ${state}, 0, ${job.attachmentScope},\n ${now}, ${now}, ${now} + ${this.ms(q, job.deadlineMs)})\n `;\n }\n const record = await this.get(job.id);\n if (!record)\n throw new Error(`The background job ${job.id} was not found after it was written.`);\n return record;\n }\n\n async get(id: string): Promise<AgentJobRecord | null> {\n const q = this.q();\n const rows: Row[] = await q`SELECT * FROM ${this.name(q)} WHERE id = ${id}`;\n return rows[0] ? recordOf(rows[0]) : null;\n }\n\n async listForThread(\n threadId: string,\n options: { states?: AgentJobState[]; limit?: number } = {},\n ): Promise<AgentJobRecord[]> {\n const q = this.q();\n const states =\n options.states === undefined\n ? q`1 = 1`\n : options.states.length === 0\n ? q`1 = 0`\n : q`state IN (${list(q, options.states)})`;\n const rows: Row[] =\n options.limit === undefined\n ? await q`\n SELECT * FROM ${this.name(q)}\n WHERE thread_id = ${threadId} AND ${states}\n ORDER BY created_at DESC, id DESC\n `\n : await q`\n SELECT * FROM ${this.name(q)}\n WHERE thread_id = ${threadId} AND ${states}\n ORDER BY created_at DESC, id DESC\n LIMIT ${Math.max(0, Math.floor(options.limit))}\n `;\n return rows.map(recordOf);\n }\n\n async transition(id: string, from: AgentJobState[], to: AgentJobUpdate): Promise<boolean> {\n if (from.length === 0) return false;\n if (\"checkpoint\" in to) await this.requireLaterColumns(\"`job.checkpoint`\");\n const q = this.q();\n const now = this.clock(q);\n const sets = [q`updated_at = ${now}`];\n if (to.deadlineMs !== undefined) {\n sets.push(q`deadline_at = ${now} + ${this.ms(q, to.deadlineMs)}`);\n }\n if (\"checkpoint\" in to) sets.push(q`job_checkpoint = ${json(to.checkpoint)}`);\n if (to.state !== undefined) sets.push(q`state = ${to.state}`);\n if (\"output\" in to) sets.push(q`output = ${json(to.output)}`);\n if (\"error\" in to) sets.push(q`error = ${json(to.error)}`);\n // `usage` is a reserved word in MySQL.\n if (\"usage\" in to) sets.push(q`${this.column(q, \"usage\")} = ${json(to.usage)}`);\n if (\"orphaned\" in to) sets.push(q`orphaned = ${to.orphaned ? 1 : 0}`);\n if (to.state !== undefined && isSettled(to.state)) {\n sets.push(\n to.settledAt !== undefined\n ? q`settled_at = COALESCE(settled_at, ${this.ms(q, to.settledAt)})`\n : q`settled_at = COALESCE(settled_at, ${now})`,\n );\n }\n const set = sets.reduce((all, one) => q`${all}, ${one}`);\n const result = await q`\n UPDATE ${this.name(q)} SET ${set}\n WHERE id = ${id} AND state IN (${list(q, from)})\n `;\n return affected(result) > 0;\n }\n\n async overdue(now: number, limit: number): Promise<AgentJobRecord[]> {\n const q = this.q();\n const rows: Row[] = await q`\n SELECT * FROM ${this.name(q)}\n WHERE state = 'running' AND deadline_at <= ${this.ms(q, now)}\n ORDER BY deadline_at, id\n LIMIT ${Math.max(0, Math.floor(limit))}\n `;\n return rows.map(recordOf);\n }\n\n async waitingOn(id: string): Promise<AgentJobRecord[]> {\n // Asked after every settle: a table without the columns has no waiting jobs.\n if (!(await this.columns())) return [];\n const q = this.q();\n const rows: Row[] = await q`\n SELECT * FROM ${this.name(q)}\n WHERE state = 'waiting' AND after_jobs LIKE ${`%${JSON.stringify(id)}%`}\n ORDER BY created_at, id\n `;\n return rows.map(recordOf).filter((record) => record.after?.includes(id));\n }\n\n async waiting(limit: number): Promise<AgentJobRecord[]> {\n const q = this.q();\n const rows: Row[] = await q`\n SELECT * FROM ${this.name(q)}\n WHERE state = 'waiting'\n ORDER BY created_at, id\n LIMIT ${Math.max(0, Math.floor(limit))}\n `;\n return rows.map(recordOf);\n }\n\n async listBatch(batch: string): Promise<AgentJobRecord[]> {\n if (!(await this.columns())) return [];\n const q = this.q();\n const rows: Row[] = await q`\n SELECT * FROM ${this.name(q)} WHERE batch_key = ${batch} ORDER BY created_at, id\n `;\n return rows.map(recordOf);\n }\n\n /**\n * Compare-and-set on the inbox's text, so two senders (or a sender and the\n * job taking its messages) never lose one another's write.\n */\n async appendInbox(id: string, text: string): Promise<boolean> {\n await this.requireLaterColumns(\"`AgentJobs.message`\");\n for (let attempt = 0; attempt < INBOX_ATTEMPTS; attempt++) {\n const q = this.q();\n const [row] = (await q`\n SELECT state, inbox FROM ${this.name(q)} WHERE id = ${id}\n `) as Row[];\n if (!row || isSettled(String(row.state) as AgentJobState)) return false;\n const before = row.inbox === null || row.inbox === undefined ? null : String(row.inbox);\n const after = JSON.stringify([...((parse(before) as string[] | undefined) ?? []), text]);\n const result = await q`\n UPDATE ${this.name(q)} SET inbox = ${after}, updated_at = ${this.clock(q)}\n WHERE id = ${id} AND state IN ('waiting', 'running') AND ${this.sameInbox(q, before)}\n `;\n if (affected(result) > 0) return true;\n }\n throw new Error(`Could not add a message to background job ${id}: too many writers at once.`);\n }\n\n async takeInbox(id: string): Promise<string[]> {\n if (!(await this.columns())) return [];\n for (let attempt = 0; attempt < INBOX_ATTEMPTS; attempt++) {\n const q = this.q();\n const [row] = (await q`SELECT inbox FROM ${this.name(q)} WHERE id = ${id}`) as Row[];\n if (!row || row.inbox === null || row.inbox === undefined) return [];\n const before = String(row.inbox);\n const result = await q`\n UPDATE ${this.name(q)} SET inbox = NULL WHERE id = ${id} AND ${this.sameInbox(q, before)}\n `;\n if (affected(result) > 0) return (parse(before) as string[] | undefined) ?? [];\n }\n throw new Error(`Could not take the messages of background job ${id}: too many writers.`);\n }\n\n async now(): Promise<number> {\n const q = this.q();\n const [row] = (await q`SELECT ${this.clock(q)} AS now`) as Array<{ now: unknown }>;\n return Number(row!.now);\n }\n\n /**\n * Deletes settled jobs that settled more than `olderThanMs` ago, and answers\n * how many. A settled result is written back into the thread on the next\n * turn, after which the record is only history; nothing removes it unless\n * this is called, from a cron job say. Running jobs are never pruned.\n */\n async prune(olderThanMs: number): Promise<number> {\n const q = this.q();\n const result = await q`\n DELETE FROM ${this.name(q)}\n WHERE state IN ('ok', 'error') AND settled_at <= ${this.clock(q)} - ${this.ms(q, olderThanMs)}\n `;\n return affected(result);\n }\n\n /**\n * Whether the table has the columns `after`, batches, the inbox and\n * checkpoints need (#1222). Asked once, outside any transaction (a failed\n * statement would abort a Postgres one), by selecting them from no rows.\n */\n columns(): Promise<boolean> {\n this.later ??= (async () => {\n try {\n await this.sql.unsafe(\n `SELECT ${LATER_COLUMNS.join(\", \")} FROM ${this.quoted(this.table)} WHERE 1 = 0`,\n );\n return true;\n } catch {\n return false;\n }\n })();\n return this.later;\n }\n\n private async requireLaterColumns(what: string): Promise<void> {\n if (await this.columns()) return;\n // Asked again next time: the app may add them without a restart.\n this.later = undefined;\n throw new Error(\n `${what} needs the columns ${LATER_COLUMNS.join(\", \")} on the ${this.table} table, which it does not have. Add them (see docs/ai-background-jobs.md and UPGRADE.md), or call createTable() on a new table.`,\n );\n }\n\n private sameInbox(q: SQL, before: string | null) {\n return before === null ? q`inbox IS NULL` : q`inbox = ${before}`;\n }\n\n private quoted(name: string): string {\n const mysql = this.dialect === \"mysql\" || this.dialect === \"mariadb\";\n return mysql ? `\\`${name}\\`` : `\"${name}\"`;\n }\n\n /** The open ORM transaction, when it is on this store's connection. */\n private joinable(): TransactionSQL | undefined {\n if (this.connection === undefined) return undefined;\n const tx = currentTransaction();\n if (tx === undefined || currentConnectionName() !== this.connection) return undefined;\n return tx;\n }\n\n /** Read at each call and never kept: a stored transaction handle outlives its transaction. */\n private q(): SQL {\n return (this.joinable() as SQL | undefined) ?? this.sql;\n }\n\n private column(q: SQL, name: string) {\n const mysql = this.dialect === \"mysql\" || this.dialect === \"mariadb\";\n return q.unsafe(mysql ? `\\`${name}\\`` : `\"${name}\"`);\n }\n\n private name(q: SQL) {\n const mysql = this.dialect === \"mysql\" || this.dialect === \"mariadb\";\n return q.unsafe(mysql ? `\\`${this.table}\\`` : `\"${this.table}\"`);\n }\n\n /** The database's clock, in epoch milliseconds. As in `DatabaseQueueDriver`. */\n private clock(q: SQL) {\n switch (this.dialect) {\n case \"postgres\":\n return q`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;\n case \"mysql\":\n case \"mariadb\":\n return q`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;\n case \"sqlite\":\n return q`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`;\n }\n }\n\n private ms(q: SQL, value: number) {\n const ms = Math.max(0, Math.round(value));\n return this.dialect === \"mysql\" || this.dialect === \"mariadb\"\n ? q`CAST(${ms} AS SIGNED)`\n : q`CAST(${ms} AS BIGINT)`;\n }\n}\n\nfunction list(q: SQL, values: string[]) {\n return values.map((value) => q`${value}`).reduce((all, one) => q`${all}, ${one}`);\n}\n\nfunction json(value: unknown): string | null {\n return value === undefined ? null : JSON.stringify(value);\n}\n\nfunction parse(value: unknown): unknown {\n if (value === null || value === undefined) return undefined;\n return JSON.parse(String(value));\n}\n\nfunction recordOf(row: Row): AgentJobRecord {\n const summary = parse(row.summary);\n const output = parse(row.output);\n const error = parse(row.error);\n const usage = parse(row.usage);\n const after = parse(row.after_jobs);\n const queued = parse(row.queued);\n const inbox = parse(row.inbox);\n const checkpoint = parse(row.job_checkpoint);\n return {\n id: String(row.id),\n threadId: String(row.thread_id),\n runId: String(row.run_id),\n toolCallId: String(row.tool_call_id),\n toolName: String(row.tool_name),\n owner: row.owner === null || row.owner === undefined ? null : String(row.owner),\n job: row.job === null || row.job === undefined ? null : String(row.job),\n ...(summary !== undefined ? { summary } : {}),\n state: String(row.state) as AgentJobState,\n ...(output !== undefined ? { output } : {}),\n ...(error !== undefined ? { error: error as AgentJobRecord[\"error\"] } : {}),\n ...(usage !== undefined ? { usage: usage as AgentJobRecord[\"usage\"] } : {}),\n ...(Number(row.orphaned) === 1 ? { orphaned: true as const } : {}),\n attachmentScope:\n row.attachment_scope === null || row.attachment_scope === undefined\n ? null\n : String(row.attachment_scope),\n ...(after !== undefined ? { after: after as string[] } : {}),\n ...(row.batch_key === null || row.batch_key === undefined\n ? {}\n : { batch: String(row.batch_key) }),\n ...(queued !== undefined ? { queued: queued as AgentJobRecord[\"queued\"] } : {}),\n ...(inbox !== undefined && (inbox as string[]).length > 0 ? { inbox: inbox as string[] } : {}),\n ...(checkpoint !== undefined ? { checkpoint } : {}),\n createdAt: Number(row.created_at),\n updatedAt: Number(row.updated_at),\n deadlineAt: Number(row.deadline_at),\n ...(row.settled_at === null || row.settled_at === undefined\n ? {}\n : { settledAt: Number(row.settled_at) }),\n };\n}\n\n/** Rows a `DELETE` or `UPDATE` touched, across the three drivers. */\nfunction affected(result: unknown): number {\n const counts = result as { count?: number | null; affectedRows?: number | null };\n return Math.max(Number(counts.count ?? 0), Number(counts.affectedRows ?? 0));\n}\n\n/**\n * The table as Prisma generates it for the model in the docs, with\n * `IF NOT EXISTS` added.\n */\nexport function createAgentJobsTableStatements(dialect: Dialect, table: string): string[] {\n if (dialect === \"mysql\" || dialect === \"mariadb\") {\n return [\n `CREATE TABLE IF NOT EXISTS \\`${table}\\` (\n \\`id\\` VARCHAR(191) NOT NULL,\n \\`thread_id\\` VARCHAR(191) NOT NULL,\n \\`run_id\\` VARCHAR(191) NOT NULL,\n \\`tool_call_id\\` VARCHAR(191) NOT NULL,\n \\`tool_name\\` VARCHAR(191) NOT NULL,\n \\`owner\\` VARCHAR(191) NULL,\n \\`job\\` VARCHAR(191) NULL,\n \\`summary\\` LONGTEXT NULL,\n \\`state\\` VARCHAR(191) NOT NULL,\n \\`output\\` LONGTEXT NULL,\n \\`error\\` LONGTEXT NULL,\n \\`usage\\` LONGTEXT NULL,\n \\`orphaned\\` INTEGER NOT NULL DEFAULT 0,\n \\`attachment_scope\\` VARCHAR(191) NULL,\n \\`created_at\\` BIGINT NOT NULL,\n \\`updated_at\\` BIGINT NOT NULL,\n \\`deadline_at\\` BIGINT NOT NULL,\n \\`settled_at\\` BIGINT NULL,\n \\`after_jobs\\` LONGTEXT NULL,\n \\`batch_key\\` VARCHAR(191) NULL,\n \\`queued\\` LONGTEXT NULL,\n \\`inbox\\` LONGTEXT NULL,\n \\`job_checkpoint\\` LONGTEXT NULL,\n\n INDEX \\`${table}_thread_id_created_at_idx\\`(\\`thread_id\\`, \\`created_at\\`),\n INDEX \\`${table}_state_deadline_at_idx\\`(\\`state\\`, \\`deadline_at\\`),\n PRIMARY KEY (\\`id\\`)\n) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,\n ];\n }\n\n const key = dialect === \"sqlite\" ? `\"id\" TEXT NOT NULL PRIMARY KEY,` : `\"id\" TEXT NOT NULL,`;\n const constraint =\n dialect === \"sqlite\" ? \"\" : `,\\n\\n CONSTRAINT \"${table}_pkey\" PRIMARY KEY (\"id\")`;\n return [\n `CREATE TABLE IF NOT EXISTS \"${table}\" (\n ${key}\n \"thread_id\" TEXT NOT NULL,\n \"run_id\" TEXT NOT NULL,\n \"tool_call_id\" TEXT NOT NULL,\n \"tool_name\" TEXT NOT NULL,\n \"owner\" TEXT,\n \"job\" TEXT,\n \"summary\" TEXT,\n \"state\" TEXT NOT NULL,\n \"output\" TEXT,\n \"error\" TEXT,\n \"usage\" TEXT,\n \"orphaned\" INTEGER NOT NULL DEFAULT 0,\n \"attachment_scope\" TEXT,\n \"created_at\" BIGINT NOT NULL,\n \"updated_at\" BIGINT NOT NULL,\n \"deadline_at\" BIGINT NOT NULL,\n \"settled_at\" BIGINT,\n \"after_jobs\" TEXT,\n \"batch_key\" TEXT,\n \"queued\" TEXT,\n \"inbox\" TEXT,\n \"job_checkpoint\" TEXT${constraint}\n)`,\n `CREATE INDEX IF NOT EXISTS \"${table}_thread_id_created_at_idx\" ON \"${table}\"(\"thread_id\", \"created_at\")`,\n `CREATE INDEX IF NOT EXISTS \"${table}_state_deadline_at_idx\" ON \"${table}\"(\"state\", \"deadline_at\")`,\n ];\n}\n",
|
|
9
9
|
"import type { SQL, TransactionSQL } from \"bun\";\n\nimport type { DatabaseConnection } from \"../../database/Connection\";\nimport type { Dialect } from \"../../database/dialect\";\nimport { currentConnectionName, currentTransaction } from \"../../orm/context\";\nimport {\n type AgentMemoryListOptions,\n type AgentMemoryRecord,\n type AgentMemorySearchOptions,\n type AgentMemorySource,\n type AgentMemoryStore,\n type AgentMemoryUpdate,\n type AgentMemoryWriteAction,\n hasAnyTag,\n type NewAgentMemoryRecord,\n sameMemory,\n} from \"./AgentMemoryStore\";\nimport { rankMemories } from \"./search\";\n\nexport type DatabaseAgentMemoryStoreOptions = {\n /**\n * The table. Default `gemi_agent_memories`. A plain identifier (letters,\n * digits and underscores), because it is spliced into every statement.\n */\n table?: string;\n};\n\ntype Row = Record<string, unknown>;\n\n/** How many times a keyed write retries when another write to the same key got there first. */\nconst UPSERT_ATTEMPTS = 4;\n\n/**\n * Agent memories (#936) in a table of the app's own database, so they outlive\n * the process and every instance sees the same ones.\n *\n * AgentMemories.use(new DatabaseAgentMemoryStore(app(DatabaseManager).connection()));\n *\n * Written for SQLite, Postgres and MySQL 8 / MariaDB 10.6+ in raw SQL, like\n * `DatabaseAgentJobStore`, and the table is the app's to create: add the\n * Prisma model from docs/ai-memory.md, or call `createTable()`.\n *\n * - **One memory per scope and key**: a unique index on `(scope, key)`. A\n * keyed write reads the slot and updates it by compare-and-set on\n * `version`, or inserts; two writes racing on one key end with one memory.\n * - **Time** is epoch milliseconds read from the database's clock.\n * - **Search** loads the scopes' memories and ranks them in JavaScript\n * (`rankMemories`), the same on every database. A scope is small.\n * - **Deletes are hard.** Nothing is kept of a deleted memory; an app that\n * wants a trail uses `AgentMemories.use(store, { onWrite })`.\n */\nexport class DatabaseAgentMemoryStore implements AgentMemoryStore {\n readonly table: string;\n private readonly sql: SQL;\n private readonly dialect: Dialect;\n private readonly connection: string | undefined;\n\n constructor(\n connection: Pick<DatabaseConnection, \"sql\" | \"dialect\"> &\n Partial<Pick<DatabaseConnection, \"name\">>,\n options: DatabaseAgentMemoryStoreOptions = {},\n ) {\n const table = options.table ?? \"gemi_agent_memories\";\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {\n throw new Error(\n `The agent memories table name \"${table}\" is not a plain identifier. Use letters, digits and underscores.`,\n );\n }\n this.table = table;\n this.sql = connection.sql;\n this.dialect = connection.dialect;\n this.connection = connection.name;\n }\n\n /**\n * Creates the table and its indexes if they do not exist: the DDL Prisma\n * generates for the model in the docs. For tests and for an app that does\n * not manage its schema with Prisma.\n */\n async createTable(): Promise<void> {\n for (const statement of createAgentMemoriesTableStatements(this.dialect, this.table)) {\n await this.sql.unsafe(statement);\n }\n }\n\n async list(\n scopes: readonly string[],\n options: AgentMemoryListOptions = {},\n ): Promise<AgentMemoryRecord[]> {\n if (scopes.length === 0) return [];\n if (options.kinds !== undefined && options.kinds.length === 0) return [];\n const q = this.q();\n const where = [q`scope IN (${list(q, scopes)})`];\n if (options.kinds !== undefined) where.push(q`kind IN (${list(q, options.kinds)})`);\n if (!options.includeExpired) {\n where.push(q`(expires_at IS NULL OR expires_at > ${this.clock(q)})`);\n }\n if (options.after !== undefined) {\n const [cursor]: Row[] = await q`\n SELECT created_at, id FROM ${this.name(q)}\n WHERE id = ${options.after} AND scope IN (${list(q, scopes)})\n `;\n if (cursor) {\n const createdAt = this.ms(q, Number(cursor.created_at));\n where.push(\n q`(created_at > ${createdAt} OR (created_at = ${createdAt} AND id > ${String(cursor.id)}))`,\n );\n }\n }\n const condition = where.reduce((all, one) => q`${all} AND ${one}`);\n // Tags are a JSON column, filtered here rather than in SQL, so a limit\n // has to wait until they are.\n const limit =\n options.limit === undefined || options.tags !== undefined\n ? undefined\n : Math.max(0, Math.floor(options.limit));\n const rows: Row[] =\n limit === undefined\n ? await q`\n SELECT * FROM ${this.name(q)} WHERE ${condition}\n ORDER BY created_at, id\n `\n : await q`\n SELECT * FROM ${this.name(q)} WHERE ${condition}\n ORDER BY created_at, id\n LIMIT ${limit}\n `;\n let records = rows.map(recordOf);\n if (options.tags !== undefined) {\n records = records.filter((record) => hasAnyTag(record, options.tags));\n if (options.limit !== undefined) {\n records = records.slice(0, Math.max(0, Math.floor(options.limit)));\n }\n }\n return records;\n }\n\n async get(id: string): Promise<AgentMemoryRecord | null> {\n const q = this.q();\n const rows: Row[] = await q`SELECT * FROM ${this.name(q)} WHERE id = ${id}`;\n return rows[0] ? recordOf(rows[0]) : null;\n }\n\n async upsert(\n memory: NewAgentMemoryRecord,\n ): Promise<{ record: AgentMemoryRecord; action: AgentMemoryWriteAction }> {\n const key = memory.key ?? null;\n if (key === null) {\n await this.insert(memory, null);\n return { record: await this.mustGet(memory.id), action: \"added\" };\n }\n for (let attempt = 1; ; attempt++) {\n const existing = await this.atKey(memory.scope, key);\n if (existing) {\n if (sameMemory(existing, memory)) return { record: existing, action: \"unchanged\" };\n const record = await this.update(\n existing.id,\n {\n kind: memory.kind,\n content: memory.content,\n tags: memory.tags ?? [],\n pinned: memory.pinned ?? false,\n expiresAt: memory.expiresAt ?? null,\n },\n existing.version,\n );\n if (record) return { record, action: \"updated\" };\n } else {\n try {\n await this.insert(memory, key);\n return { record: await this.mustGet(memory.id), action: \"added\" };\n } catch (error) {\n // Another write took the key between the read and the insert; the\n // next attempt finds it and updates it. Anything else is rethrown\n // once the slot is still empty.\n if (attempt >= UPSERT_ATTEMPTS || !(await this.atKey(memory.scope, key))) throw error;\n }\n }\n if (attempt >= UPSERT_ATTEMPTS) {\n throw new Error(\n `The memory at \"${key}\" in ${memory.scope} kept changing while it was being written.`,\n );\n }\n }\n }\n\n async update(\n id: string,\n patch: AgentMemoryUpdate,\n expectedVersion?: number,\n ): Promise<AgentMemoryRecord | null> {\n const q = this.q();\n const sets = [q`version = version + 1`, q`updated_at = ${this.clock(q)}`];\n if (patch.kind !== undefined) sets.push(q`kind = ${patch.kind}`);\n if (patch.content !== undefined) sets.push(q`content = ${patch.content}`);\n if (patch.key !== undefined) sets.push(q`${this.column(q, \"key\")} = ${patch.key}`);\n if (patch.tags !== undefined) sets.push(q`tags = ${JSON.stringify(patch.tags)}`);\n if (patch.pinned !== undefined) sets.push(q`pinned = ${patch.pinned ? 1 : 0}`);\n if (patch.expiresAt !== undefined) {\n sets.push(\n patch.expiresAt === null\n ? q`expires_at = NULL`\n : q`expires_at = ${this.ms(q, patch.expiresAt)}`,\n );\n }\n const set = sets.reduce((all, one) => q`${all}, ${one}`);\n const result =\n expectedVersion === undefined\n ? await q`UPDATE ${this.name(q)} SET ${set} WHERE id = ${id}`\n : await q`\n UPDATE ${this.name(q)} SET ${set}\n WHERE id = ${id} AND version = ${Math.floor(expectedVersion)}\n `;\n if (affected(result) === 0) return null;\n return this.get(id);\n }\n\n async delete(ids: readonly string[]): Promise<number> {\n if (ids.length === 0) return 0;\n const q = this.q();\n const result = await q`DELETE FROM ${this.name(q)} WHERE id IN (${list(q, [...new Set(ids)])})`;\n return affected(result);\n }\n\n async deleteScope(scope: string): Promise<number> {\n const q = this.q();\n return affected(await q`DELETE FROM ${this.name(q)} WHERE scope = ${scope}`);\n }\n\n async search(\n scopes: readonly string[],\n query: string,\n options: AgentMemorySearchOptions = {},\n ): Promise<AgentMemoryRecord[]> {\n const rows = await this.list(scopes, { kinds: options.kinds, tags: options.tags });\n return rankMemories(rows, query, options.limit);\n }\n\n async count(scope: string): Promise<number> {\n const q = this.q();\n const [row] = (await q`\n SELECT COUNT(*) AS total FROM ${this.name(q)}\n WHERE scope = ${scope} AND (expires_at IS NULL OR expires_at > ${this.clock(q)})\n `) as Array<{ total: unknown }>;\n return Number(row?.total ?? 0);\n }\n\n async touch(ids: readonly string[], at: number): Promise<void> {\n if (ids.length === 0) return;\n const q = this.q();\n await q`\n UPDATE ${this.name(q)} SET last_used_at = ${this.ms(q, at)}\n WHERE id IN (${list(q, [...new Set(ids)])})\n `;\n }\n\n async prune(now: number): Promise<number> {\n const q = this.q();\n return affected(\n await q`DELETE FROM ${this.name(q)} WHERE expires_at IS NOT NULL AND expires_at <= ${this.ms(q, now)}`,\n );\n }\n\n /** The store's clock, in epoch milliseconds. */\n async now(): Promise<number> {\n const q = this.q();\n const [row] = (await q`SELECT ${this.clock(q)} AS now`) as Array<{ now: unknown }>;\n return Number(row!.now);\n }\n\n private async insert(memory: NewAgentMemoryRecord, key: string | null): Promise<void> {\n const q = this.q();\n const now = this.clock(q);\n const expiresAt =\n memory.expiresAt === undefined || memory.expiresAt === null\n ? null\n : Math.max(0, Math.round(memory.expiresAt));\n await q`\n INSERT INTO ${this.name(q)}\n (id, scope, kind, ${this.column(q, \"key\")}, content, tags, pinned, source, version,\n created_at, updated_at, expires_at)\n VALUES\n (${memory.id}, ${memory.scope}, ${memory.kind}, ${key}, ${memory.content},\n ${JSON.stringify(memory.tags ?? [])}, ${memory.pinned ? 1 : 0},\n ${JSON.stringify(memory.source)}, 1, ${now}, ${now},\n ${expiresAt === null ? null : this.ms(q, expiresAt)})\n `;\n }\n\n private async atKey(scope: string, key: string): Promise<AgentMemoryRecord | null> {\n const q = this.q();\n const rows: Row[] = await q`\n SELECT * FROM ${this.name(q)} WHERE scope = ${scope} AND ${this.column(q, \"key\")} = ${key}\n `;\n return rows[0] ? recordOf(rows[0]) : null;\n }\n\n private async mustGet(id: string): Promise<AgentMemoryRecord> {\n const record = await this.get(id);\n if (!record) throw new Error(`The memory ${id} was not found after it was written.`);\n return record;\n }\n\n /** The open ORM transaction, when it is on this store's connection. */\n private joinable(): TransactionSQL | undefined {\n if (this.connection === undefined) return undefined;\n const tx = currentTransaction();\n if (tx === undefined || currentConnectionName() !== this.connection) return undefined;\n return tx;\n }\n\n /** Read at each call and never kept: a stored transaction handle outlives its transaction. */\n private q(): SQL {\n return (this.joinable() as SQL | undefined) ?? this.sql;\n }\n\n /** `key` is a reserved word in MySQL, so it is always quoted. */\n private column(q: SQL, name: string) {\n const mysql = this.dialect === \"mysql\" || this.dialect === \"mariadb\";\n return q.unsafe(mysql ? `\\`${name}\\`` : `\"${name}\"`);\n }\n\n private name(q: SQL) {\n const mysql = this.dialect === \"mysql\" || this.dialect === \"mariadb\";\n return q.unsafe(mysql ? `\\`${this.table}\\`` : `\"${this.table}\"`);\n }\n\n /** The database's clock, in epoch milliseconds. As in `DatabaseAgentJobStore`. */\n private clock(q: SQL) {\n switch (this.dialect) {\n case \"postgres\":\n return q`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;\n case \"mysql\":\n case \"mariadb\":\n return q`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;\n case \"sqlite\":\n return q`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`;\n }\n }\n\n private ms(q: SQL, value: number) {\n const ms = Math.max(0, Math.round(value));\n return this.dialect === \"mysql\" || this.dialect === \"mariadb\"\n ? q`CAST(${ms} AS SIGNED)`\n : q`CAST(${ms} AS BIGINT)`;\n }\n}\n\nfunction list(q: SQL, values: readonly string[]) {\n return values.map((value) => q`${value}`).reduce((all, one) => q`${all}, ${one}`);\n}\n\nfunction parseJson<T>(value: unknown, fallback: T): T {\n if (value === null || value === undefined || value === \"\") return fallback;\n try {\n return JSON.parse(String(value)) as T;\n } catch {\n return fallback;\n }\n}\n\nfunction recordOf(row: Row): AgentMemoryRecord {\n const tags = parseJson<unknown>(row.tags, []);\n return {\n id: String(row.id),\n scope: String(row.scope),\n kind: String(row.kind),\n content: String(row.content),\n key: row.key === null || row.key === undefined ? null : String(row.key),\n tags: Array.isArray(tags) ? tags.map(String) : [],\n pinned: Number(row.pinned) === 1,\n source: parseJson<AgentMemorySource>(row.source, { by: \"app\" }),\n version: Number(row.version),\n createdAt: Number(row.created_at),\n updatedAt: Number(row.updated_at),\n lastUsedAt:\n row.last_used_at === null || row.last_used_at === undefined ? null : Number(row.last_used_at),\n expiresAt:\n row.expires_at === null || row.expires_at === undefined ? null : Number(row.expires_at),\n };\n}\n\n/** Rows a `DELETE` or `UPDATE` touched, across the three drivers. */\nfunction affected(result: unknown): number {\n const counts = result as { count?: number | null; affectedRows?: number | null };\n return Math.max(Number(counts.count ?? 0), Number(counts.affectedRows ?? 0));\n}\n\n/**\n * The table as Prisma generates it for the model in the docs, with\n * `IF NOT EXISTS` added.\n */\nexport function createAgentMemoriesTableStatements(dialect: Dialect, table: string): string[] {\n if (dialect === \"mysql\" || dialect === \"mariadb\") {\n return [\n `CREATE TABLE IF NOT EXISTS \\`${table}\\` (\n \\`id\\` VARCHAR(191) NOT NULL,\n \\`scope\\` VARCHAR(191) NOT NULL,\n \\`kind\\` VARCHAR(191) NOT NULL,\n \\`key\\` VARCHAR(191) NULL,\n \\`content\\` TEXT NOT NULL,\n \\`tags\\` TEXT NULL,\n \\`pinned\\` INTEGER NOT NULL DEFAULT 0,\n \\`source\\` TEXT NOT NULL,\n \\`version\\` INTEGER NOT NULL DEFAULT 1,\n \\`embedding\\` LONGTEXT NULL,\n \\`created_at\\` BIGINT NOT NULL,\n \\`updated_at\\` BIGINT NOT NULL,\n \\`last_used_at\\` BIGINT NULL,\n \\`expires_at\\` BIGINT NULL,\n\n INDEX \\`${table}_scope_kind_created_at_idx\\`(\\`scope\\`, \\`kind\\`, \\`created_at\\`),\n INDEX \\`${table}_expires_at_idx\\`(\\`expires_at\\`),\n UNIQUE INDEX \\`${table}_scope_key_key\\`(\\`scope\\`, \\`key\\`),\n PRIMARY KEY (\\`id\\`)\n) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,\n ];\n }\n\n const key = dialect === \"sqlite\" ? `\"id\" TEXT NOT NULL PRIMARY KEY,` : `\"id\" TEXT NOT NULL,`;\n const constraint =\n dialect === \"sqlite\" ? \"\" : `,\\n\\n CONSTRAINT \"${table}_pkey\" PRIMARY KEY (\"id\")`;\n return [\n `CREATE TABLE IF NOT EXISTS \"${table}\" (\n ${key}\n \"scope\" TEXT NOT NULL,\n \"kind\" TEXT NOT NULL,\n \"key\" TEXT,\n \"content\" TEXT NOT NULL,\n \"tags\" TEXT,\n \"pinned\" INTEGER NOT NULL DEFAULT 0,\n \"source\" TEXT NOT NULL,\n \"version\" INTEGER NOT NULL DEFAULT 1,\n \"embedding\" TEXT,\n \"created_at\" BIGINT NOT NULL,\n \"updated_at\" BIGINT NOT NULL,\n \"last_used_at\" BIGINT,\n \"expires_at\" BIGINT${constraint}\n)`,\n `CREATE INDEX IF NOT EXISTS \"${table}_scope_kind_created_at_idx\" ON \"${table}\"(\"scope\", \"kind\", \"created_at\")`,\n `CREATE INDEX IF NOT EXISTS \"${table}_expires_at_idx\" ON \"${table}\"(\"expires_at\")`,\n `CREATE UNIQUE INDEX IF NOT EXISTS \"${table}_scope_key_key\" ON \"${table}\"(\"scope\", \"key\")`,\n ];\n}\n",
|
|
10
10
|
"/**\n * The statistics an eval report carries (#1005): small samples, honestly.\n *\n * An eval run three times that passed twice is \"2/3\", and the useful thing to\n * say about it is how little that pins down. Pass rates get a Wilson score\n * interval, which stays inside [0, 1] and is not degenerate at 0/n or n/n the\n * way the normal approximation is. Scores get the mean with a t interval,\n * since n is usually 1 to 10, and none at all where there is no spread to\n * read one from (one value, or every value the same).\n *\n * Comparisons use exact or small-sample tests for the same reason: Fisher's\n * exact test for pass rates, Welch's t for scores. A z-test on two runs of\n * 0/1 values calls almost anything significant.\n */\n\n/** A mean with its spread and a 95% interval. `n` is 0 when nothing was measured. */\nexport type Estimate = {\n n: number;\n mean: number;\n /** The sample standard deviation (n − 1); 0 for n < 2. */\n stddev: number;\n /**\n * The 95% interval's bounds, or `null` when the data can't give one: a\n * score measured once, or a score that came out the same every time (that\n * it didn't vary in n runs is not evidence that it can't).\n */\n low: number | null;\n high: number | null;\n};\n\nconst EMPTY: Estimate = { n: 0, mean: 0, stddev: 0, low: null, high: null };\n\nconst Z95 = 1.959964;\n\n// --- distributions -------------------------------------------------------------\n\n/** ln Γ(x), Lanczos (g = 7, n = 9). */\nfunction lnGamma(x: number): number {\n const c = [\n 0.99999999999980993, 676.5203681218851, -1259.1392167224028, 771.32342877765313,\n -176.61502916214059, 12.507343278686905, -0.13857109526572012, 9.9843695780195716e-6,\n 1.5056327351493116e-7,\n ];\n if (x < 0.5) return Math.log(Math.PI / Math.sin(Math.PI * x)) - lnGamma(1 - x);\n x -= 1;\n let a = c[0]!;\n const t = x + 7.5;\n for (let i = 1; i < 9; i++) a += c[i]! / (x + i);\n return 0.5 * Math.log(2 * Math.PI) + (x + 0.5) * Math.log(t) - t + Math.log(a);\n}\n\n/** The continued fraction of the incomplete beta function (Numerical Recipes). */\nfunction betaFraction(a: number, b: number, x: number): number {\n const tiny = 1e-300;\n let c = 1;\n let d = 1 - ((a + b) * x) / (a + 1);\n if (Math.abs(d) < tiny) d = tiny;\n d = 1 / d;\n let h = d;\n for (let m = 1; m <= 300; m++) {\n const m2 = 2 * m;\n let aa = (m * (b - m) * x) / ((a + m2 - 1) * (a + m2));\n d = 1 + aa * d;\n if (Math.abs(d) < tiny) d = tiny;\n c = 1 + aa / c;\n if (Math.abs(c) < tiny) c = tiny;\n d = 1 / d;\n h *= d * c;\n aa = (-(a + m) * (a + b + m) * x) / ((a + m2) * (a + m2 + 1));\n d = 1 + aa * d;\n if (Math.abs(d) < tiny) d = tiny;\n c = 1 + aa / c;\n if (Math.abs(c) < tiny) c = tiny;\n d = 1 / d;\n const step = d * c;\n h *= step;\n if (Math.abs(step - 1) < 1e-14) break;\n }\n return h;\n}\n\n/** The regularized incomplete beta function I_x(a, b). */\nfunction incompleteBeta(x: number, a: number, b: number): number {\n if (x <= 0) return 0;\n if (x >= 1) return 1;\n const front = Math.exp(\n lnGamma(a + b) - lnGamma(a) - lnGamma(b) + a * Math.log(x) + b * Math.log(1 - x),\n );\n return x < (a + 1) / (a + b + 2)\n ? (front * betaFraction(a, b, x)) / a\n : 1 - (front * betaFraction(b, a, 1 - x)) / b;\n}\n\n/** P(|T| ≥ |t|) for Student's t with `df` degrees of freedom (any df > 0). */\nexport function tTwoSided(t: number, df: number): number {\n return incompleteBeta(df / (df + t * t), df / 2, 0.5);\n}\n\n/** The two-sided 95% critical value of Student's t, for any df > 0. */\nexport function t95(df: number): number {\n if (!(df > 0)) return Number.POSITIVE_INFINITY;\n // tTwoSided falls as t grows: bisect for the t where it is 0.05.\n let low = Z95;\n let high = 2;\n while (tTwoSided(high, df) > 0.05) high *= 2;\n for (let i = 0; i < 100; i++) {\n const mid = (low + high) / 2;\n if (tTwoSided(mid, df) > 0.05) low = mid;\n else high = mid;\n }\n return (low + high) / 2;\n}\n\n/** Two-sided p of Fisher's exact test on a 2×2 table (passes out of n on each side). */\nexport function fisherExact(passA: number, nA: number, passB: number, nB: number): number {\n const passes = passA + passB;\n const n = nA + nB;\n const lnChoose = (top: number, k: number) =>\n lnGamma(top + 1) - lnGamma(k + 1) - lnGamma(top - k + 1);\n const probability = (k: number) =>\n Math.exp(lnChoose(nA, k) + lnChoose(nB, passes - k) - lnChoose(n, passes));\n const observed = probability(passA);\n let p = 0;\n for (let k = Math.max(0, passes - nB); k <= Math.min(nA, passes); k++) {\n const each = probability(k);\n // A relative tolerance, so tables as likely as the observed one count\n // despite rounding.\n if (each <= observed * (1 + 1e-7)) p += each;\n }\n return Math.min(1, p);\n}\n\n// --- estimates ------------------------------------------------------------------\n\nfunction stddevOf(values: readonly number[], mean: number): number {\n if (values.length < 2) return 0;\n const sum = values.reduce((total, value) => total + (value - mean) ** 2, 0);\n const stddev = Math.sqrt(sum / (values.length - 1));\n // Values that are all equal can still leave a residue from rounding the\n // mean (0.8 three times): that is no spread, not a tiny one.\n return stddev < 1e-12 * Math.max(1, Math.abs(mean)) ? 0 : stddev;\n}\n\n/** The pass rate of `outcomes`, with a Wilson 95% interval. */\nexport function passRate(outcomes: readonly boolean[]): Estimate {\n const n = outcomes.length;\n if (n === 0) return EMPTY;\n const values = outcomes.map((pass) => (pass ? 1 : 0));\n const p = values.reduce<number>((sum, value) => sum + value, 0) / n;\n const z2 = Z95 * Z95;\n const centre = (p + z2 / (2 * n)) / (1 + z2 / n);\n const margin = (Z95 * Math.sqrt((p * (1 - p)) / n + z2 / (4 * n * n))) / (1 + z2 / n);\n return {\n n,\n mean: p,\n stddev: stddevOf(values, p),\n low: Math.max(0, centre - margin),\n high: Math.min(1, centre + margin),\n };\n}\n\n/** The mean of `values`, with a t 95% interval (none without spread). */\nexport function meanOf(values: readonly number[]): Estimate {\n const n = values.length;\n if (n === 0) return EMPTY;\n const mean = values.reduce((sum, value) => sum + value, 0) / n;\n const stddev = stddevOf(values, mean);\n if (n < 2 || stddev === 0) return { n, mean, stddev, low: null, high: null };\n const margin = (t95(n - 1) * stddev) / Math.sqrt(n);\n return { n, mean, stddev, low: mean - margin, high: mean + margin };\n}\n\n// --- comparisons -----------------------------------------------------------------\n\n/** The change from `before` to `after`, and whether it is more than noise. */\nexport type Delta = {\n before: number;\n after: number;\n delta: number;\n /**\n * The test's two-sided p: Fisher's exact test for a pass rate, Welch's t for\n * a score. `null` when it can't be tested: a side with no samples, a score\n * measured once on a side, or scores without any spread on either side.\n */\n p: number | null;\n /** `p` adjusted for every comparison in the same `compare` (Holm, unless\n * `adjust: \"none\"`). */\n pAdjusted: number | null;\n /** `pAdjusted` below the comparison's `alpha`. */\n significant: boolean;\n};\n\nfunction untested(before: Estimate, after: Estimate, p: number | null): Delta {\n return {\n before: before.mean,\n after: after.mean,\n delta: after.mean - before.mean,\n p,\n pAdjusted: p,\n significant: false,\n };\n}\n\n/** Two pass rates, by Fisher's exact test. */\nexport function passRateDelta(before: Estimate, after: Estimate): Delta {\n if (before.n === 0 || after.n === 0) return untested(before, after, null);\n const passes = (side: Estimate) => Math.round(side.mean * side.n);\n return untested(before, after, fisherExact(passes(before), before.n, passes(after), after.n));\n}\n\n/** Two mean scores, by Welch's t with the Welch–Satterthwaite df. */\nexport function scoreDelta(before: Estimate, after: Estimate): Delta {\n if (before.n < 2 || after.n < 2) return untested(before, after, null);\n const vb = before.stddev ** 2 / before.n;\n const va = after.stddev ** 2 / after.n;\n const se = Math.sqrt(vb + va);\n // No spread on either side: nothing to tell a change from noise with.\n if (se === 0) return untested(before, after, null);\n const df = (vb + va) ** 2 / (vb ** 2 / (before.n - 1) + va ** 2 / (after.n - 1));\n return untested(before, after, tTwoSided((after.mean - before.mean) / se, df));\n}\n\n/**\n * Sets each `pAdjusted` and `significant` over a family of comparisons.\n *\n * `\"holm\"` (the default in `compare`) is Holm's step-down adjustment: it keeps\n * the chance of any false \"significant\" across the whole family under\n * `alpha`, which is what a CI gate reading `regressions` needs when one\n * `compare` tests every case and grader on two measures. `\"none\"` tests each\n * at `alpha` on its own.\n */\nexport function adjust(deltas: readonly Delta[], alpha: number, method: \"holm\" | \"none\"): void {\n if (method === \"holm\") {\n const sorted = deltas.filter((entry) => entry.p !== null).sort((a, b) => a.p! - b.p!);\n let running = 0;\n sorted.forEach((entry, rank) => {\n running = Math.max(running, Math.min(1, entry.p! * (sorted.length - rank)));\n entry.pAdjusted = running;\n });\n } else {\n for (const entry of deltas) entry.pAdjusted = entry.p;\n }\n for (const entry of deltas) {\n entry.significant = entry.pAdjusted !== null && entry.pAdjusted < alpha && entry.delta !== 0;\n }\n}\n",
|
|
11
11
|
"import type { AgentProvider } from \"../AgentProvider\";\nimport type { ReasoningEffort } from \"../Agent\";\nimport { generate } from \"../generate\";\nimport { addUsage, emptyUsage } from \"../runtime\";\nimport type { Infer, Schema } from \"../Schema\";\nimport type { AgentMessage, Usage } from \"../types\";\nimport { measureUsage, priceUsage, type ModelPrice } from \"../usageMeter\";\nimport {\n adjust,\n meanOf,\n passRate,\n passRateDelta,\n scoreDelta,\n type Delta,\n type Estimate,\n} from \"./stats\";\n\n/**\n * A shared eval harness (#1005): cases × runs, graders, LLM judges, judge\n * calibration, statistics, token and cost accounting, and a baseline compare.\n *\n * const suite = Eval.create({\n * name: \"questions\",\n * cases: [{ id: \"moon\", input: { ask: \"Where is the moon?\" } }],\n * runs: 3,\n * task: async (input) => ask(input.ask),\n * graders: {\n * answered: (out) => out.reply.trim() !== \"\",\n * offers: Eval.judge({ provider, prompt: (out) => out.reply, output, verdict }),\n * },\n * });\n * const report = await suite.run();\n * console.log(Eval.format(report));\n *\n * See docs/ai-evals.md.\n */\n\n// --- grades ----------------------------------------------------------------\n\n/** What a grader may answer: `true`/`false`, a score in [0, 1], a result, or\n * `null`/`undefined` for \"does not apply to this sample\". */\nexport type GradeValue = boolean | number | GraderResult | null | undefined;\n\nexport type GraderResult = {\n pass: boolean;\n /** In [0, 1]. Defaults to 1 for a pass and 0 for a fail. */\n score?: number;\n note?: string;\n};\n\n/** A grader's verdict on one sample, as the report keeps it. */\nexport type Grade = {\n pass: boolean;\n score: number;\n note?: string;\n /** Set when the grader threw: the grade is then a fail. */\n error?: string;\n};\n\n// --- cases, tasks and graders ----------------------------------------------\n\nexport type EvalCase<I> = {\n id: string;\n input: I;\n /** Grader names that don't apply to this case (an owner who asked for\n * what a grader would flag, say). */\n skip?: readonly string[];\n};\n\nexport type EvalTaskContext<I> = {\n case: EvalCase<I>;\n /** 1-based. */\n run: number;\n /** Aborted when the suite's `signal` is. */\n signal: AbortSignal;\n};\n\nexport type GraderContext<I> = {\n case: EvalCase<I>;\n input: I;\n /** 1-based; 0 for a calibration example. */\n run: number;\n};\n\nexport type CheckFn<I, O> = (\n output: O,\n ctx: GraderContext<I>,\n) => GradeValue | Promise<GradeValue>;\n\ntype GraderOptions = {\n /**\n * A gate: when it fails, the sample is reported but left out of every pass\n * rate and score. For a content guard, so an empty answer can't win the\n * graders that pass when something is absent.\n */\n gate?: boolean;\n /** The score a numeric answer passes at. Default 0.5. */\n threshold?: number;\n};\n\nexport type CheckGrader<I, O> = GraderOptions & { check: CheckFn<I, O>; kind?: \"check\" };\n\nexport type JudgePrompt =\n | string\n | { prompt?: string; messages?: AgentMessage[] };\n\nexport type JudgeCalibration<I, O> = {\n /** Outputs with a known answer, graded before the suite runs. */\n examples: readonly { id?: string; input: I; output: O; expected: boolean }[];\n /** Below this agreement, `report.calibration[name].ok` is false. Default 0.8. */\n minAgreement?: number;\n};\n\nexport type JudgeSpec<I, O, J extends Schema<any>> = GraderOptions & {\n provider: AgentProvider;\n instructions?: string;\n /** What the judge reads: a prompt, or messages (an image, say). */\n prompt: (output: O, ctx: GraderContext<I>) => JudgePrompt | Promise<JudgePrompt>;\n /** The judgment's schema. */\n output: J;\n /**\n * The grade, from the judgment.\n *\n * Declared as a method on purpose (#1007): a judge sits in the graders'\n * union as `JudgeGrader<I, O, any>`, whose judgment is `Infer<any>`, i.e.\n * `unknown`. A property's function type is checked contravariantly under\n * `strictFunctionTypes`, so a judge whose `verdict` reads `{ ok: boolean }`\n * would not be assignable there; a method's parameters are checked\n * bivariantly, so it is. The judgment is still typed by `output` where the\n * judge is written.\n */\n verdict(judgment: Infer<J>, ctx: GraderContext<I>): GradeValue;\n reasoning?: ReasoningEffort;\n maxOutputTokens?: number;\n temperature?: number;\n /** Judge each sample this many times: the majority passes (a tie fails)\n * and the score is the mean. Default 1. */\n samples?: number;\n calibration?: JudgeCalibration<I, O>;\n};\n\nexport type JudgeGrader<I, O, J extends Schema<any> = Schema<any>> = JudgeSpec<I, O, J> & {\n readonly kind: \"judge\";\n};\n\nexport type EvalGrader<I, O> = CheckFn<I, O> | CheckGrader<I, O> | JudgeGrader<I, O, any>;\n\nexport type EvalGraders<I, O> = Record<string, EvalGrader<I, O>>;\n\n/** What a `graders` function is handed. */\nexport type GraderKit<I, O> = {\n judge: <J extends Schema<any>>(spec: JudgeSpec<I, O, J>) => JudgeGrader<I, O, J>;\n};\n\n/** Prices by model id. A key also prices the ids it is a prefix of\n * (`gpt-5.4` prices `gpt-5.4-2026-03-05`); the longest key wins. */\nexport type EvalPricing = Record<string, ModelPrice>;\nexport type { ModelPrice };\n\nexport type CreateEvalParams<I, O> = {\n name: string;\n cases: readonly EvalCase<I>[];\n /** Runs per case. Default 1. */\n runs?: number;\n /** Samples at once. Default 1. */\n concurrency?: number;\n task: (input: I, ctx: EvalTaskContext<I>) => O | Promise<O>;\n /**\n * By name. A function of the kit when a judge is among them: its `judge`\n * is typed by this eval's input and output, so a judge's `prompt` and\n * `verdict` need no annotations.\n */\n graders: EvalGraders<I, O> | ((kit: GraderKit<I, O>) => EvalGraders<I, O>);\n pricing?: EvalPricing;\n};\n\n// --- the report --------------------------------------------------------------\n\nexport type EvalSample<O = unknown> = {\n case: string;\n run: number;\n /** Every applicable grade passed (and the task didn't throw). False when\n * no grader applied. */\n pass: boolean;\n /** Left out of the statistics: a gate failed, or no grader applied\n * (`ungraded`). Still reported. */\n excluded: boolean;\n /** No grader applied to this sample: nothing checked it, so it is neither\n * a pass nor a fail. */\n ungraded?: true;\n /** The mean of the grades' scores; 0 when the task threw or nothing graded it. */\n score: number;\n /** By grader name; graders that answered \"does not apply\" are absent. */\n grades: Record<string, Grade>;\n /** The task threw this. No grader ran. */\n error?: string;\n /** With `keepOutputs`. */\n output?: O;\n /** The task's model calls. */\n usage: Usage;\n byModel: Record<string, Usage>;\n /** The judges' model calls. */\n judgeUsage: Usage;\n /** USD, the task's and the judges', when `pricing` prices their models. */\n cost?: number;\n durationMs: number;\n};\n\nexport type GraderSummary = { passRate: Estimate; score: Estimate };\n\nexport type EvalSummary = {\n samples: number;\n /** Samples counted in the statistics: no gate failed and some grader applied. */\n kept: number;\n passed: number;\n /** Samples whose task threw. */\n errors: number;\n passRate: Estimate;\n score: Estimate;\n};\n\nexport type CaseSummary = EvalSummary & { graders: Record<string, GraderSummary> };\n\nexport type CalibrationResult = {\n n: number;\n /** The share of examples the judge graded as expected. */\n agreement: number;\n ok: boolean;\n disagreements: { id: string; expected: boolean; got: boolean; note?: string }[];\n usage: Usage;\n};\n\nexport type EvalReport<O = unknown> = {\n name: string;\n startedAt: string;\n durationMs: number;\n runs: number;\n /**\n * The run was stopped (`signal`, or an `onSample` that threw) before every\n * planned sample ran. Its statistics cover only what ran, so\n * `Eval.compare` refuses it.\n */\n aborted: boolean;\n /** The case ids this run was asked for (after `only`), whether or not all ran. */\n planned: string[];\n samples: EvalSample<O>[];\n cases: Record<string, CaseSummary>;\n graders: Record<string, GraderSummary>;\n calibration: Record<string, CalibrationResult>;\n totals: EvalSummary & {\n usage: Usage;\n judgeUsage: Usage;\n byModel: Record<string, Usage>;\n /** USD over every sample, when `pricing` was given. */\n cost?: number;\n /** Models used that `pricing` doesn't price. */\n unpriced: string[];\n };\n};\n\nexport type EvalRunOptions<O> = {\n /** Case ids to run; all when absent. */\n only?: readonly string[];\n runs?: number;\n concurrency?: number;\n signal?: AbortSignal;\n /** Keep each sample's output on the report. Default false. */\n keepOutputs?: boolean;\n /** Called as each sample is graded. If it throws, the run stops starting\n * samples (and aborts the ones running), then rejects with that error. */\n onSample?: (sample: EvalSample<O>) => void;\n};\n\nexport type EvalCompareOptions = {\n /** Default 0.05. */\n alpha?: number;\n /**\n * How `alpha` is held across the comparison's many tests (every case and\n * grader, on pass rate and score). `\"holm\"` (default): Holm's step-down,\n * so the chance of any false \"significant\" in the whole comparison stays\n * under `alpha`. `\"none\"`: each test at `alpha` alone, which with 20 cases\n * flags about two changes per comparison by chance.\n */\n adjust?: \"holm\" | \"none\";\n};\n\nexport type EvalComparison = {\n totals: { passRate: Delta; score: Delta };\n cases: Record<string, { passRate: Delta; score: Delta }>;\n graders: Record<string, { passRate: Delta; score: Delta }>;\n /**\n * Cases and graders only one report has. One the current report lacks is\n * also a regression: a case that didn't run is not a case that passed.\n */\n missing: {\n cases: { fromCurrent: string[]; fromBaseline: string[] };\n graders: { fromCurrent: string[]; fromBaseline: string[] };\n };\n /** Tests that had a p (the family `adjust` corrects over). */\n comparisons: number;\n alpha: number;\n adjust: \"holm\" | \"none\";\n /** \"case moon: pass rate 1.00 → 0.00 (p = 0.029)\" for each significant\n * drop, and each case or grader missing from the current report. */\n regressions: string[];\n improvements: string[];\n};\n\n// --- the suite ---------------------------------------------------------------\n\nexport class Eval<I = unknown, O = unknown> {\n readonly name: string;\n readonly cases: readonly EvalCase<I>[];\n readonly runs: number;\n readonly concurrency: number;\n readonly graders: Readonly<Record<string, EvalGrader<I, O>>>;\n readonly pricing?: EvalPricing;\n private readonly task: CreateEvalParams<I, O>[\"task\"];\n\n private constructor(params: CreateEvalParams<I, O>) {\n this.name = params.name;\n this.cases = params.cases;\n this.runs = params.runs ?? 1;\n this.concurrency = params.concurrency ?? 1;\n this.task = params.task;\n this.graders =\n typeof params.graders === \"function\"\n ? params.graders({ judge: (spec) => Eval.judge(spec) })\n : params.graders;\n this.pricing = params.pricing;\n }\n\n static create<I, O>(params: CreateEvalParams<I, O>): Eval<I, Awaited<O>> {\n const owner = `The eval \"${params.name}\"`;\n assertCount(params.runs, owner, \"runs\");\n assertCount(params.concurrency, owner, \"concurrency\");\n const ids = new Set<string>();\n for (const test of params.cases) {\n if (ids.has(test.id)) throw new Error(`${owner} has two cases with the id \"${test.id}\".`);\n ids.add(test.id);\n }\n const suite = new Eval(params as unknown as CreateEvalParams<I, Awaited<O>>);\n for (const [name, grader] of Object.entries(suite.graders)) {\n if (typeof grader !== \"function\" && grader.kind === \"judge\") {\n assertCount(grader.samples, `${owner}'s judge \"${name}\"`, \"samples\");\n }\n }\n return suite;\n }\n\n /**\n * An LLM judge: `prompt` turns an output into what the judge reads, the\n * judge answers `output`, and `verdict` turns that into a grade.\n */\n static judge<I, O, J extends Schema<any>>(spec: JudgeSpec<I, O, J>): JudgeGrader<I, O, J> {\n return { ...spec, kind: \"judge\" };\n }\n\n /**\n * Compares a report with a baseline. Throws when either was aborted: its\n * statistics are of the samples that happened to run.\n */\n static compare(\n baseline: EvalReport<any>,\n current: EvalReport<any>,\n options: EvalCompareOptions = {},\n ): EvalComparison {\n return compareReports(baseline, current, options);\n }\n\n static format(\n report: EvalReport<any>,\n options: { baseline?: EvalReport<any> } & EvalCompareOptions = {},\n ): string {\n return formatReport(report, options);\n }\n\n /** Calibrates the judges, then runs every case `runs` times and grades it. */\n async run(options: EvalRunOptions<O> = {}): Promise<EvalReport<O>> {\n const owner = `${this.name}.run`;\n assertCount(options.runs, owner, \"runs\");\n assertCount(options.concurrency, owner, \"concurrency\");\n const only = options.only ? new Set(options.only) : null;\n if (only) {\n const unknown = [...only].filter((id) => !this.cases.some((test) => test.id === id));\n if (unknown.length > 0) {\n throw new Error(`The eval \"${this.name}\" has no case ${unknown.map((id) => `\"${id}\"`).join(\", \")}.`);\n }\n }\n const runs = options.runs ?? this.runs;\n const started = Date.now();\n // The caller's signal, and ours: a throwing `onSample` stops the other\n // workers rather than leaving them to spend tokens for a rejected run.\n const stop = new AbortController();\n const signal = options.signal ? AbortSignal.any([options.signal, stop.signal]) : stop.signal;\n const selected = this.cases.filter((test) => !only || only.has(test.id));\n\n const calibration: Record<string, CalibrationResult> = {};\n for (const [name, grader] of Object.entries(this.graders)) {\n if (signal.aborted) break;\n if (typeof grader === \"function\" || grader.kind !== \"judge\" || !grader.calibration) continue;\n calibration[name] = await this.calibrate(grader, signal);\n }\n\n const jobs = selected.flatMap((test) =>\n Array.from({ length: runs }, (_, at) => ({ test, run: at + 1 })),\n );\n const samples: (EvalSample<O> | undefined)[] = Array.from({ length: jobs.length });\n let next = 0;\n let failure: { error: unknown } | undefined;\n const worker = async () => {\n while (next < jobs.length && !signal.aborted) {\n const at = next++;\n const job = jobs[at]!;\n const sample = await this.sample(job.test, job.run, signal, options.keepOutputs ?? false);\n samples[at] = sample;\n try {\n options.onSample?.(sample);\n } catch (error) {\n failure ??= { error };\n stop.abort(error);\n }\n }\n };\n const workers = Math.min(options.concurrency ?? this.concurrency, jobs.length);\n await Promise.all(Array.from({ length: workers }, worker));\n if (failure) throw failure.error;\n\n const ran = samples.filter((sample): sample is EvalSample<O> => sample !== undefined);\n return this.report(\n ran,\n calibration,\n runs,\n new Date(started).toISOString(),\n Date.now() - started,\n { aborted: signal.aborted || ran.length < jobs.length, planned: selected.map((test) => test.id) },\n );\n }\n\n private async sample(\n test: EvalCase<I>,\n run: number,\n signal: AbortSignal,\n keepOutput: boolean,\n ): Promise<EvalSample<O>> {\n const started = Date.now();\n let output: O | undefined;\n let error: string | undefined;\n const task = await measureUsage(async () => {\n try {\n output = await this.task(test.input, { case: test, run, signal });\n } catch (thrown) {\n error = messageOf(thrown);\n }\n });\n\n const grades: Record<string, Grade> = {};\n let excluded = false;\n const judged = await measureUsage(async () => {\n if (error !== undefined) return;\n const ctx: GraderContext<I> = { case: test, input: test.input, run };\n for (const [name, grader] of Object.entries(this.graders)) {\n if (test.skip?.includes(name)) continue;\n const grade = await gradeWith(grader, output as O, ctx, signal);\n if (!grade) continue;\n grades[name] = grade;\n if (!grade.pass && typeof grader !== \"function\" && grader.gate) excluded = true;\n }\n });\n\n const scores = Object.values(grades).map((grade) => grade.score);\n // Nothing applied: not a pass with a perfect score, which would lift the\n // pass rate with samples nobody checked. Left out instead.\n const ungraded = error === undefined && scores.length === 0;\n const priced = this.pricing\n ? costOf(this.pricing, task.byModel).cost + costOf(this.pricing, judged.byModel).cost\n : undefined;\n return {\n case: test.id,\n run,\n pass: error === undefined && !ungraded && Object.values(grades).every((grade) => grade.pass),\n excluded: excluded || ungraded,\n ...(ungraded ? { ungraded: true as const } : {}),\n score: error !== undefined || ungraded ? 0 : mean(scores),\n grades,\n ...(error !== undefined ? { error } : {}),\n ...(keepOutput && error === undefined ? { output } : {}),\n usage: task.usage,\n byModel: mergeByModel(task.byModel, judged.byModel),\n judgeUsage: judged.usage,\n ...(priced !== undefined ? { cost: priced } : {}),\n durationMs: Date.now() - started,\n };\n }\n\n private async calibrate(\n grader: JudgeGrader<I, O, any>,\n signal: AbortSignal,\n ): Promise<CalibrationResult> {\n const calibration = grader.calibration!;\n const disagreements: CalibrationResult[\"disagreements\"] = [];\n let agreed = 0;\n const measured = await measureUsage(async () => {\n for (const [index, example] of calibration.examples.entries()) {\n if (signal.aborted) break;\n const id = example.id ?? `example-${index + 1}`;\n const ctx: GraderContext<I> = { case: { id, input: example.input }, input: example.input, run: 0 };\n const grade = await gradeWith(grader, example.output, ctx, signal);\n const got = grade?.pass ?? false;\n if (got === example.expected) agreed++;\n else disagreements.push({ id, expected: example.expected, got, ...(grade?.note ? { note: grade.note } : {}) });\n }\n });\n const n = calibration.examples.length;\n const agreement = n === 0 ? 1 : agreed / n;\n return {\n n,\n agreement,\n ok: agreement >= (calibration.minAgreement ?? 0.8),\n disagreements,\n usage: measured.usage,\n };\n }\n\n private report(\n samples: EvalSample<O>[],\n calibration: Record<string, CalibrationResult>,\n runs: number,\n startedAt: string,\n durationMs: number,\n progress: { aborted: boolean; planned: string[] },\n ): EvalReport<O> {\n const gates = new Set(\n Object.entries(this.graders)\n .filter(([, grader]) => typeof grader !== \"function\" && grader.gate)\n .map(([name]) => name),\n );\n const cases: Record<string, CaseSummary> = {};\n for (const test of this.cases) {\n const mine = samples.filter((sample) => sample.case === test.id);\n if (mine.length === 0) continue;\n cases[test.id] = { ...summarize(mine), graders: summarizeGraders(mine, gates) };\n }\n let usage = emptyUsage();\n let judgeUsage = emptyUsage();\n const byModel: Record<string, Usage> = {};\n for (const sample of samples) {\n usage = addUsage(usage, sample.usage);\n judgeUsage = addUsage(judgeUsage, sample.judgeUsage);\n for (const [model, used] of Object.entries(sample.byModel)) {\n byModel[model] = addUsage(byModel[model] ?? emptyUsage(), used);\n }\n }\n const priced = this.pricing ? costOf(this.pricing, byModel) : undefined;\n return {\n name: this.name,\n startedAt,\n durationMs,\n runs,\n aborted: progress.aborted,\n planned: progress.planned,\n samples,\n cases,\n graders: summarizeGraders(samples, gates),\n calibration,\n totals: {\n ...summarize(samples),\n usage,\n judgeUsage,\n byModel,\n ...(priced ? { cost: priced.cost } : {}),\n unpriced: priced ? priced.unpriced : Object.keys(byModel),\n },\n };\n }\n}\n\n// --- grading -----------------------------------------------------------------\n\nasync function gradeWith<I, O>(\n grader: EvalGrader<I, O>,\n output: O,\n ctx: GraderContext<I>,\n signal: AbortSignal,\n): Promise<Grade | null> {\n const threshold = typeof grader === \"function\" ? 0.5 : (grader.threshold ?? 0.5);\n try {\n if (typeof grader === \"function\") return toGrade(await grader(output, ctx), threshold);\n if (grader.kind !== \"judge\") return toGrade(await grader.check(output, ctx), threshold);\n return await judgeWith(grader, output, ctx, threshold, signal);\n } catch (thrown) {\n return { pass: false, score: 0, error: messageOf(thrown) };\n }\n}\n\nasync function judgeWith<I, O>(\n judge: JudgeGrader<I, O, any>,\n output: O,\n ctx: GraderContext<I>,\n threshold: number,\n signal: AbortSignal,\n): Promise<Grade | null> {\n const asked = await judge.prompt(output, ctx);\n const input = typeof asked === \"string\" ? { prompt: asked } : asked;\n const grades: Grade[] = [];\n for (let at = 0; at < (judge.samples ?? 1) && !signal.aborted; at++) {\n const result = await generate({\n signal,\n provider: judge.provider,\n ...(judge.instructions !== undefined ? { instructions: judge.instructions } : {}),\n ...input,\n output: judge.output,\n ...(judge.reasoning !== undefined ? { reasoning: judge.reasoning } : {}),\n ...(judge.maxOutputTokens !== undefined ? { maxOutputTokens: judge.maxOutputTokens } : {}),\n ...(judge.temperature !== undefined ? { temperature: judge.temperature } : {}),\n logErrors: false,\n });\n if (!result.ok) {\n grades.push({ pass: false, score: 0, error: `The judge failed: ${result.error.message}` });\n continue;\n }\n const grade = toGrade(judge.verdict(result.output, ctx), threshold);\n if (grade) grades.push(grade);\n }\n if (grades.length === 0) return null;\n if (grades.length === 1) return grades[0]!;\n const passes = grades.filter((grade) => grade.pass).length;\n const notes = grades.map((grade) => grade.note ?? grade.error).filter(Boolean);\n const errors = grades.map((grade) => grade.error).filter(Boolean);\n return {\n pass: passes * 2 > grades.length,\n score: mean(grades.map((grade) => grade.score)),\n ...(notes.length > 0 ? { note: notes.join(\" | \") } : {}),\n ...(errors.length === grades.length ? { error: errors.join(\" | \") } : {}),\n };\n}\n\nfunction toGrade(value: GradeValue, threshold: number): Grade | null {\n if (value === null || value === undefined) return null;\n if (typeof value === \"boolean\") return { pass: value, score: value ? 1 : 0 };\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) throw new Error(`A grader answered the score ${value}.`);\n const score = clamp(value);\n return { pass: score >= threshold, score };\n }\n return {\n pass: value.pass,\n score: value.score === undefined ? (value.pass ? 1 : 0) : clamp(value.score),\n ...(value.note !== undefined ? { note: value.note } : {}),\n };\n}\n\n// --- statistics --------------------------------------------------------------\n\nfunction summarize(samples: readonly EvalSample<any>[]): EvalSummary {\n const kept = samples.filter((sample) => !sample.excluded);\n return {\n samples: samples.length,\n kept: kept.length,\n passed: kept.filter((sample) => sample.pass).length,\n errors: samples.filter((sample) => sample.error !== undefined).length,\n passRate: passRate(kept.map((sample) => sample.pass)),\n score: meanOf(kept.map((sample) => sample.score)),\n };\n}\n\n/**\n * Per grader, over the kept samples. A gate is summarized over every sample\n * it graded: over the kept ones only, its own failures would have excluded\n * themselves and its rate would always read 1.\n */\nfunction summarizeGraders(\n samples: readonly EvalSample<any>[],\n gates: ReadonlySet<string>,\n): Record<string, GraderSummary> {\n const kept = samples.filter((sample) => !sample.excluded);\n const names = [...new Set(samples.flatMap((sample) => Object.keys(sample.grades)))];\n return Object.fromEntries(\n names.map((name) => {\n const from = gates.has(name) ? samples : kept;\n const grades = from.flatMap((sample) => (sample.grades[name] ? [sample.grades[name]!] : []));\n return [\n name,\n {\n passRate: passRate(grades.map((grade) => grade.pass)),\n score: meanOf(grades.map((grade) => grade.score)),\n },\n ];\n }),\n );\n}\n\n// --- cost --------------------------------------------------------------------\n\nfunction costOf(\n pricing: EvalPricing,\n byModel: Record<string, Usage>,\n): { cost: number; unpriced: string[] } {\n let cost = 0;\n const unpriced: string[] = [];\n for (const [model, usage] of Object.entries(byModel)) {\n const price = priceUsage(pricing, model, usage);\n if (price === undefined) {\n unpriced.push(model);\n continue;\n }\n cost += price;\n }\n return { cost, unpriced };\n}\n\nfunction mergeByModel(...maps: Record<string, Usage>[]): Record<string, Usage> {\n const merged: Record<string, Usage> = {};\n for (const map of maps) {\n for (const [model, usage] of Object.entries(map)) {\n merged[model] = addUsage(merged[model] ?? emptyUsage(), usage);\n }\n }\n return merged;\n}\n\n// --- compare and format ------------------------------------------------------\n\nfunction compareReports(\n baseline: EvalReport<any>,\n current: EvalReport<any>,\n options: EvalCompareOptions,\n): EvalComparison {\n for (const [which, report] of [\n [\"baseline\", baseline],\n [\"current report\", current],\n ] as const) {\n if (report.aborted) {\n throw new Error(\n `Eval.compare: the ${which} for \"${report.name}\" was aborted (${report.samples.length} samples ran). Its statistics cover only the samples that ran; run it again in full.`,\n );\n }\n }\n const alpha = options.alpha ?? 0.05;\n const method = options.adjust ?? \"holm\";\n const all: { label: string; passRate: Delta; score: Delta }[] = [];\n const pair = (label: string, before: GraderSummary, after: GraderSummary) => {\n const entry = {\n label,\n passRate: passRateDelta(before.passRate, after.passRate),\n score: scoreDelta(before.score, after.score),\n };\n all.push(entry);\n return { passRate: entry.passRate, score: entry.score };\n };\n const both = (label: string, before: Record<string, GraderSummary>, after: Record<string, GraderSummary>) =>\n Object.fromEntries(\n Object.keys(after)\n .filter((key) => key in before)\n .map((key) => [key, pair(`${label} ${key}`, before[key]!, after[key]!)]),\n );\n const missingOf = (before: string[], after: string[]) => ({\n fromCurrent: before.filter((key) => !after.includes(key)),\n fromBaseline: after.filter((key) => !before.includes(key)),\n });\n\n const totals = pair(\"total\", baseline.totals, current.totals);\n const cases = both(\"case\", baseline.cases, current.cases);\n const graders = both(\"grader\", baseline.graders, current.graders);\n const deltas = all.flatMap((entry) => [entry.passRate, entry.score]);\n adjust(deltas, alpha, method);\n\n const missing = {\n cases: missingOf(\n [...new Set([...(baseline.planned ?? []), ...Object.keys(baseline.cases)])],\n [...new Set([...(current.planned ?? []), ...Object.keys(current.cases)])],\n ),\n graders: missingOf(Object.keys(baseline.graders), Object.keys(current.graders)),\n };\n const regressions: string[] = [\n ...missing.cases.fromCurrent.map((id) => `case ${id}: in the baseline, missing from this report`),\n ...missing.graders.fromCurrent.map((id) => `grader ${id}: in the baseline, missing from this report`),\n ];\n const improvements: string[] = [];\n for (const entry of all) {\n for (const [what, delta] of [\n [\"pass rate\", entry.passRate],\n [\"score\", entry.score],\n ] as const) {\n if (!delta.significant) continue;\n const line = `${entry.label}: ${what} ${delta.before.toFixed(2)} → ${delta.after.toFixed(2)} (p = ${formatP(delta.pAdjusted!)})`;\n (delta.delta < 0 ? regressions : improvements).push(line);\n }\n }\n return {\n totals,\n cases,\n graders,\n missing,\n comparisons: deltas.filter((delta) => delta.p !== null).length,\n alpha,\n adjust: method,\n regressions,\n improvements,\n };\n}\n\nfunction formatP(p: number): string {\n return p < 0.001 ? \"<0.001\" : p.toFixed(3);\n}\n\nfunction formatReport(\n report: EvalReport<any>,\n options: { baseline?: EvalReport<any> } & EvalCompareOptions,\n): string {\n const comparison =\n options.baseline && !options.baseline.aborted && !report.aborted\n ? compareReports(options.baseline, report, options)\n : undefined;\n const { totals } = report;\n const lines: string[] = [];\n lines.push(\n `eval ${report.name}: ${totals.samples} samples, ${totals.kept} kept, ${totals.passed} passed, ${totals.errors} errors (${(report.durationMs / 1000).toFixed(1)}s)`,\n );\n if (report.aborted) {\n lines.push(`ABORTED: only ${totals.samples} of the planned samples ran; not comparable.`);\n }\n const rate = (estimate: Estimate) => {\n if (estimate.n === 0) return \"-\";\n const mean = estimate.mean.toFixed(2);\n if (estimate.low === null || estimate.high === null) {\n return `${mean} (${estimate.n === 1 ? \"n=1\" : \"no spread\"})`;\n }\n return `${mean} [${estimate.low.toFixed(2)}, ${estimate.high.toFixed(2)}]`;\n };\n const change = (delta: Delta | undefined) =>\n delta ? ` ${delta.delta >= 0 ? \"+\" : \"\"}${delta.delta.toFixed(2)}${delta.significant ? \"*\" : \"\"}` : \"\";\n const table = (title: string, rows: [string, string, string, string][]) => {\n const widths = [0, 1, 2, 3].map((column) =>\n Math.max(...[[title, \"n\", \"pass rate\", \"score\"], ...rows].map((row) => row[column]!.length)),\n );\n const render = (row: string[]) => row.map((cell, at) => cell.padEnd(widths[at]!)).join(\" \").trimEnd();\n lines.push(\"\", render([title, \"n\", \"pass rate\", \"score\"]), ...rows.map(render));\n };\n table(\n \"case\",\n Object.entries(report.cases).map(([id, summary]) => [\n id,\n `${summary.kept}/${summary.samples}`,\n rate(summary.passRate) + change(comparison?.cases[id]?.passRate),\n rate(summary.score) + change(comparison?.cases[id]?.score),\n ]),\n );\n table(\n \"grader\",\n Object.entries(report.graders).map(([id, summary]) => [\n id,\n String(summary.passRate.n),\n rate(summary.passRate) + change(comparison?.graders[id]?.passRate),\n rate(summary.score) + change(comparison?.graders[id]?.score),\n ]),\n );\n lines.push(\n \"\",\n `total pass rate ${rate(totals.passRate)}${change(comparison?.totals.passRate)} score ${rate(totals.score)}${change(comparison?.totals.score)}`,\n );\n for (const [name, result] of Object.entries(report.calibration)) {\n lines.push(\n `judge ${name}: agreement ${result.agreement.toFixed(2)} on ${result.n} examples${result.ok ? \"\" : \" (BELOW minAgreement)\"}`,\n );\n }\n const tokens = (usage: Usage) => `${usage.inputTokens} in, ${usage.outputTokens} out`;\n lines.push(\n `tokens: task ${tokens(totals.usage)}; judges ${tokens(totals.judgeUsage)}${totals.cost !== undefined ? `; cost $${totals.cost.toFixed(4)}` : \"\"}${totals.unpriced.length > 0 && totals.cost !== undefined ? ` (unpriced: ${totals.unpriced.join(\", \")})` : \"\"}`,\n );\n if (comparison) {\n lines.push(\n \"\",\n `* significant at ${comparison.alpha} over ${comparison.comparisons} tests (${comparison.adjust === \"holm\" ? \"Holm-adjusted\" : \"unadjusted\"}; Fisher's exact for pass rates, Welch's t for scores)`,\n );\n for (const line of comparison.regressions) lines.push(`regression: ${line}`);\n for (const line of comparison.improvements) lines.push(`improvement: ${line}`);\n }\n return lines.join(\"\\n\");\n}\n\n// --- helpers -----------------------------------------------------------------\n\nfunction mean(values: readonly number[]): number {\n return values.reduce((sum, value) => sum + value, 0) / values.length;\n}\n\nfunction clamp(value: number): number {\n return Math.min(1, Math.max(0, value));\n}\n\nfunction messageOf(thrown: unknown): string {\n return thrown instanceof Error ? thrown.message : String(thrown);\n}\n\nfunction assertCount(value: number | undefined, owner: string, field: string): void {\n if (value === undefined || (Number.isInteger(value) && value >= 1)) return;\n throw new Error(`${owner} sets \\`${field}\\` to ${String(value)}, but it has to be a whole number of at least 1.`);\n}\n",
|
|
@@ -18,7 +18,7 @@
|
|
|
18
18
|
"import type { AgentTurn, AgentTurnParams } from \"./AgentController\";\nimport type { RealtimeClient, RealtimeSession, RealtimeTool } from \"./providers/realtime\";\nimport type { RealtimeEvent, RealtimeSideband } from \"./providers/sideband\";\nimport { addUsage, emptyUsage } from \"./runtime\";\nimport type {\n AgentStreamEvent,\n ClientToolResult,\n ClientTurn,\n PendingToolCall,\n Usage,\n} from \"./types\";\nimport { ToolError } from \"./redact\";\nimport type { VoiceToolHandler } from \"./voiceMcp\";\nimport type { VoiceSessionStore } from \"./voiceStore\";\nimport type { VoiceEndReason } from \"./voice/wire\";\n\n/**\n * A voice front for an `AgentController` (#921).\n *\n * @experimental Not yet verified against a live Azure or OpenAI call; names and\n * behaviour may change in a minor release.\n *\n * THE SHAPE. A realtime voice model talks to the user; the agent the app\n * already has does the work. The voice model gets one delegate tool\n * (`ask_agent({ request })` by default) and three small ones (`stop_work`,\n * `work_status`, `answer_question`). This class runs on the call's sideband,\n * where those function calls arrive, and turns a delegated request into\n * `controller.startTurn(...)` — so the work goes through the controller's\n * `authorizeRequest`, `runOwner`, `context()`, limits, hooks, tools and store,\n * exactly like a typed message, and lands on the same thread the chat shows.\n *\n * WHY NOT GIVE THE VOICE MODEL THE AGENT'S TOOLS. A real agent has dozens of\n * tools, deferred namespaces and prompts tuned for its own model; a realtime\n * model is weaker at long tool chains and re-bills every tool schema on every\n * response; and real work takes minutes, which a voice cannot block on.\n * Delegation keeps one source of truth for what the agent can do.\n *\n * WHAT IT DOES WHILE A TURN RUNS:\n *\n * - The turn's tool calls (or the app's `progress` summary of its events) go\n * into the voice conversation as quiet notes, at most one per\n * `progressIntervalMs`, so the voice can say where the work is when asked.\n * - When the turn ends, its text goes back as the delegate call's\n * `function_call_output`, and the voice is asked to respond, so it speaks the\n * outcome. A turn that ends `awaiting-input` hands its questions to the voice;\n * the spoken answer comes back through `answer_question` as\n * `startTurn({ turn: { toolResults } })`.\n * - One turn at a time. A second request is queued (up to `maxQueued`) and\n * answered at once with `queued`, so the voice can say \"after this one\"; a run\n * already going on the thread (a typed message) is waited for, and looked\n * for again right before `startTurn`. `liveRuns` is per process, so a run on\n * another instance is not seen, and a typed message that starts in the\n * instant between that last look and `startTurn` is superseded, as two typed\n * messages would be.\n * - Delegated turns run as the `user` captured when the call started, for the\n * whole call. A sign-out mid-call is seen only when `authorizeRequest`\n * refuses a turn.\n * - Barge-in stays the vendor's (server VAD cancels the spoken response) and\n * never stops the work. Only `stop_work` does.\n *\n * Ending the call does not stop a running turn: the turn is the thread's, and\n * the chat shows how it ends.\n */\n\n// --- public types ----------------------------------------------------------\n\n/** What the bridge needs of a controller: its `startTurn`. Pass the class. */\nexport type VoiceTurnController<Body extends object> = {\n startTurn(params: AgentTurnParams<Body>): Promise<AgentTurn>;\n};\n\n/** Where the bridge looks for a run already going on the thread. An\n * `AgentController`'s `liveRuns`. */\nexport type VoiceLiveRuns = {\n find(params: { threadId: string }): Promise<{ runId: string } | null>;\n get(runId: string): { result(): Promise<unknown> } | null;\n};\n\nexport type VoiceLimits = {\n /** The call is ended after this long. Default 15 minutes. */\n maxDurationMs?: number;\n /** Ended after this long with nobody speaking and no work running.\n * Default 2 minutes. */\n idleTimeoutMs?: number;\n /** Requests waiting behind the running one. Default 3. */\n maxQueued?: number;\n /** At most one progress note per this long. Default 4 seconds. */\n progressIntervalMs?: number;\n /** How long a closing line may play before the call is hung up. Default 10 s. */\n closingLineMs?: number;\n /** How often `onTick` is called. Default one minute. */\n tickMs?: number;\n /** When the vendor refuses the hangup, how long the sideband is kept open\n * (still metering) waiting for the vendor to end the call. Default 30 s. */\n hangupGraceMs?: number;\n /** A `tools` / MCP call's timeout. Default 60 s. */\n toolTimeoutMs?: number;\n /** `tools` / MCP calls allowed per rolling minute; more are answered\n * `busy`. Default 20. */\n maxToolCallsPerMinute?: number;\n /** A tool's output is cut to this many characters of JSON before the voice\n * model sees it: every character is billed again on each response.\n * Default 8000. */\n toolOutputChars?: number;\n};\n\n/** Lines the voice says before the bridge hangs up. `null` hangs up silently. */\nexport type VoiceLines = {\n maxDuration?: string | null;\n idle?: string | null;\n error?: string | null;\n};\n\nexport type VoiceDelegate = {\n /** The delegate tool's name. Default `ask_agent`. */\n name?: string;\n /** What the voice model is told the tool does. */\n description?: string;\n};\n\nexport type VoiceUsageInfo = {\n sessionId: string;\n /** Usage so far, this response included. */\n total: Usage;\n /** Since the bridge started. */\n elapsedMs: number;\n /** Transcription so far: billed apart from `total`, at the transcription\n * model's rates. */\n transcription: VoiceTranscriptionUsage;\n};\n\n/** Input transcription's usage: tokens for a token-billed model, seconds for a\n * duration-billed one. */\nexport type VoiceTranscriptionUsage = { usage: Usage; seconds: number };\n\nexport type VoiceTranscriptLine = { role: \"user\" | \"assistant\"; text: string; at: number };\n\n/** One `tools` / MCP call and how it went. */\nexport type VoiceToolCallRecord = {\n name: string;\n status: \"running\" | \"done\" | \"failed\" | \"refused\" | \"busy\";\n durationMs?: number;\n /** For `failed` / `refused`: what the model was told. */\n message?: string;\n};\n\n/** One delegated request and how it went. */\nexport type VoiceRequestRecord = {\n request: string;\n status: \"queued\" | \"running\" | \"done\" | \"refused\" | \"dropped\";\n runId?: string;\n finishReason?: string;\n};\n\nexport type VoiceSummary = {\n sessionId: string;\n callId?: string;\n threadId: string;\n reason: VoiceEndReason;\n startedAt: number;\n endedAt: number;\n durationMs: number;\n /** Whole seconds, rounded up: what a per-second or per-minute price reads. */\n seconds: number;\n /** The voice model's responses (`response.done`). */\n usage: Usage;\n /** Input transcription, billed separately from `usage`. */\n transcription: VoiceTranscriptionUsage;\n /** What was said, from the vendor's transcripts. The app decides what to keep. */\n transcript: VoiceTranscriptLine[];\n requests: VoiceRequestRecord[];\n /** Each `tools` / MCP call. */\n toolCalls: VoiceToolCallRecord[];\n /** `error` events the vendor sent, in order. */\n errors: { code?: string; message: string }[];\n};\n\n/**\n * Thrown from `onUsage` or `onTick` to end the call: out of credits, a daily\n * cap. `line` is said first (\"You're out of credits; buy a pack to keep\n * talking.\"), then the call is hung up with reason `usage`.\n */\nexport class VoiceHangup extends Error {\n readonly line?: string;\n\n constructor(line?: string) {\n super(line ?? \"Voice session ended by the app.\");\n this.name = \"VoiceHangup\";\n this.line = line;\n }\n}\n\nexport type VoiceBridgeParams<Body extends object = Record<string, unknown>> = {\n controller: VoiceTurnController<Body>;\n threadId: string;\n /** Who delegated turns run as: `startTurn`'s `user`. */\n user?: unknown;\n body?: Body;\n /** The call: a provider's realtime client and the call id, or a sideband\n * already open (tests, or an app that opened its own). */\n call:\n | { realtime: RealtimeClient; callId: string }\n | { sideband: RealtimeSideband; callId?: string };\n /** Default: a random id. The `VoiceSessionRecord`'s id when there is a store. */\n sessionId?: string;\n /** When set, the latest `body` is read from here before every delegated\n * turn, and the end is recorded. */\n store?: VoiceSessionStore;\n /** Runs already going on the thread are waited for. An `AgentController`'s\n * `liveRuns`. */\n liveRuns?: VoiceLiveRuns;\n delegate?: VoiceDelegate;\n limits?: VoiceLimits;\n lines?: VoiceLines;\n /** The session the call was created with. A `session.updated` whose\n * instructions or tool names differ from it ends the call (a client can send\n * `session.update` on the data channel). */\n session?: RealtimeSession;\n /** A one-line summary of a run event for a progress note, or nothing. The\n * default names each tool call and reads a string (or `message`) a tool\n * yields. */\n progress?: (event: AgentStreamEvent) => string | null | undefined;\n /** A note for the voice when `setBody` changes the body (\"The user selected\n * the hero section.\"). */\n contextNote?: (body: Body) => string | null | undefined;\n /** After each response, with its usage. Throw `VoiceHangup` to end the call.\n * Hooks run in order, off the event loop: a slow one does not delay the\n * call's tool handling. */\n onUsage?: (usage: Usage, info: VoiceUsageInfo) => void | Promise<void>;\n /** After each transcribed utterance, with its usage (`usage` for a\n * token-billed model, `seconds` for a duration-billed one). Throw\n * `VoiceHangup` to end the call. */\n onTranscriptionUsage?: (\n usage: { usage?: Usage; seconds?: number },\n info: VoiceUsageInfo,\n ) => void | Promise<void>;\n /** Every `tickMs`, for time-based metering. Throw `VoiceHangup` to end the call. */\n onTick?: (info: VoiceUsageInfo) => void | Promise<void>;\n /** Once, when the call has ended. */\n onEnd?: (summary: VoiceSummary) => void | Promise<void>;\n /** Every sideband event, for logs. */\n onEvent?: (event: RealtimeEvent) => void;\n /**\n * Tools the bridge runs in this process when the voice calls them, beside\n * the delegate: the app's MCP tools (`mcpVoiceTools`), or its own. Their\n * definitions must also be in the session's `tools` (`this.voice()` adds\n * them).\n */\n tools?: VoiceToolHandler[];\n /** After each `tools` call, in the same hook chain as `onUsage`. Throw\n * `VoiceHangup` to end the call. */\n onToolCall?: (call: VoiceToolCallRecord, info: VoiceUsageInfo) => void | Promise<void>;\n};\n\nexport const DEFAULT_DELEGATE_NAME = \"ask_agent\";\n\nconst DEFAULT_LIMITS = {\n maxDurationMs: 15 * 60_000,\n idleTimeoutMs: 2 * 60_000,\n maxQueued: 3,\n progressIntervalMs: 4_000,\n closingLineMs: 10_000,\n tickMs: 60_000,\n hangupGraceMs: 30_000,\n toolTimeoutMs: 60_000,\n maxToolCallsPerMinute: 20,\n toolOutputChars: 8_000,\n} satisfies Required<VoiceLimits>;\n\nconst DEFAULT_LINES = {\n maxDuration:\n \"We've reached the time limit for this voice session. Tap the microphone to start again.\",\n idle: \"It's gone quiet, so I'll hang up. Tap the microphone when you want to talk again.\",\n error: null,\n} satisfies Required<VoiceLines>;\n\n/**\n * The tools the voice model is given, for its session. `createCall` needs them\n * in `session.tools`; `this.voice()` adds them itself.\n */\nexport function voiceTools(delegate: VoiceDelegate = {}): RealtimeTool[] {\n return [\n {\n name: delegate.name ?? DEFAULT_DELEGATE_NAME,\n description:\n delegate.description ??\n \"Hand one self-contained request to the agent that does the work, in the user's own words with references resolved. It can take minutes; the result comes back when it is done, so tell the user you are on it.\",\n parameters: {\n type: \"object\",\n properties: { request: { type: \"string\", description: \"What the user wants done.\" } },\n required: [\"request\"],\n additionalProperties: false,\n },\n },\n {\n name: \"stop_work\",\n description: \"Stop the work that is running, and drop any requests waiting behind it.\",\n parameters: { type: \"object\", properties: {}, additionalProperties: false },\n },\n {\n name: \"work_status\",\n description: \"What the agent is doing right now, and what is waiting.\",\n parameters: { type: \"object\", properties: {}, additionalProperties: false },\n },\n {\n name: \"answer_question\",\n description:\n \"Answer the question the agent asked (it came back from a request with status needs_input). For an approval, set approve.\",\n parameters: {\n type: \"object\",\n properties: {\n answer: { type: \"string\", description: \"The user's answer, in their words.\" },\n approve: { type: \"boolean\", description: \"For an approval: whether the user approved.\" },\n },\n required: [\"answer\"],\n additionalProperties: false,\n },\n },\n ];\n}\n\n// --- the bridge ------------------------------------------------------------\n\ntype Job = {\n record: VoiceRequestRecord;\n turn: ClientTurn;\n /** The function call to answer when the job ends; `undefined` once answered. */\n callId?: string;\n handle?: AgentTurn;\n /** `stop_work` arrived before the turn started: it is not started. */\n stopRequested?: boolean;\n};\n\n/** Live bridges in this process, by session id. */\nconst live = new Map<string, VoiceBridge<any>>();\n\nexport class VoiceBridge<Body extends object = Record<string, unknown>> {\n readonly sessionId: string;\n readonly threadId: string;\n readonly callId?: string;\n /** Resolves with the summary once the call has ended and `onEnd` has run. */\n readonly ended: Promise<VoiceSummary>;\n\n private readonly params: VoiceBridgeParams<Body>;\n private readonly sideband: RealtimeSideband;\n private readonly hangupCall: () => Promise<void>;\n private readonly limits: Required<VoiceLimits>;\n private readonly lines: Required<VoiceLines>;\n private readonly delegateName: string;\n private readonly startedAt = Date.now();\n\n private body: Body;\n private usage: Usage = emptyUsage();\n private transcription: VoiceTranscriptionUsage = { usage: emptyUsage(), seconds: 0 };\n /** Hooks run one after another, off the event loop. */\n private hooks: Promise<void> = Promise.resolve();\n /** The `event_id` of the bridge's own `response.create` not yet answered. */\n private pendingCreate?: string;\n private transcript: VoiceTranscriptLine[] = [];\n private requests: VoiceRequestRecord[] = [];\n private toolCalls: VoiceToolCallRecord[] = [];\n private toolHandlers = new Map<string, VoiceToolHandler>();\n private toolsRunning = 0;\n private toolCallTimes: number[] = [];\n private errors: VoiceSummary[\"errors\"] = [];\n private running?: Job;\n private queue: Job[] = [];\n private pending: PendingToolCall[] = [];\n private lastProgress?: string;\n private lastNoteAt = 0;\n private noteTimer?: ReturnType<typeof setTimeout>;\n private responseActive = false;\n private responseWanted = false;\n private ending?: Promise<VoiceSummary>;\n private timers: ReturnType<typeof setTimeout>[] = [];\n private idleTimer?: ReturnType<typeof setTimeout>;\n private tickTimer?: ReturnType<typeof setInterval>;\n private resolveEnded!: (summary: VoiceSummary) => void;\n private closingWaiter?: (event: RealtimeEvent) => void;\n\n /** Starts the bridge on a call that has been created. */\n static start<Body extends object>(params: VoiceBridgeParams<Body>): VoiceBridge<Body> {\n return new VoiceBridge(params);\n }\n\n /** A bridge running in this process, by session id. */\n static get(sessionId: string): VoiceBridge<any> | undefined {\n return live.get(sessionId);\n }\n\n /** Ends every call this process holds, e.g. on shutdown, with an optional\n * line (\"Voice paused, tap to resume.\"). */\n static async endAll(line?: string | null): Promise<void> {\n await Promise.all([...live.values()].map((bridge) => bridge.end(\"hangup\", line)));\n }\n\n private constructor(params: VoiceBridgeParams<Body>) {\n this.params = params;\n this.sessionId = params.sessionId ?? crypto.randomUUID();\n this.threadId = params.threadId;\n this.body = (params.body ?? {}) as Body;\n this.limits = { ...DEFAULT_LIMITS, ...definedOnly(params.limits) };\n this.lines = { ...DEFAULT_LINES, ...definedOnly(params.lines) };\n this.delegateName = params.delegate?.name ?? DEFAULT_DELEGATE_NAME;\n const reserved = new Set(voiceTools(params.delegate).map((tool) => tool.name));\n for (const handler of params.tools ?? []) {\n if (reserved.has(handler.tool.name) || this.toolHandlers.has(handler.tool.name)) {\n throw new Error(`VoiceBridge: two tools are named \"${handler.tool.name}\".`);\n }\n this.toolHandlers.set(handler.tool.name, handler);\n }\n\n if (\"realtime\" in params.call) {\n const { realtime, callId } = params.call;\n this.callId = callId;\n this.sideband = realtime.sideband(callId);\n this.hangupCall = () => this.sideband.hangup();\n } else {\n this.callId = params.call.callId ?? params.call.sideband.callId;\n this.sideband = params.call.sideband;\n this.hangupCall = () => this.sideband.hangup();\n }\n\n this.ended = new Promise((resolve) => (this.resolveEnded = resolve));\n live.set(this.sessionId, this);\n\n this.timers.push(\n setTimeout(\n () => void this.end(\"max_duration\", this.lines.maxDuration),\n this.limits.maxDurationMs,\n ),\n );\n this.tickTimer = setInterval(() => void this.tick(), this.limits.tickMs);\n this.touch();\n void this.listen();\n }\n\n // --- the app's handles ----------------------------------------------------\n\n /** The body delegated turns get from now on. Says `contextNote`'s line to\n * the voice when there is one. */\n setBody(body: Body): void {\n this.body = body;\n const note = this.params.contextNote?.(body);\n if (note) this.sideband.addNote(note);\n }\n\n /** Ends the call: says `line` first when given, then hangs up. */\n end(reason: VoiceEndReason = \"hangup\", line?: string | null): Promise<VoiceSummary> {\n return (this.ending ??= this.finish(reason, line ?? null));\n }\n\n // --- events ---------------------------------------------------------------\n\n private async listen(): Promise<void> {\n for await (const event of this.sideband) {\n try {\n this.params.onEvent?.(event);\n } catch {\n // A logger's bug must not end the call.\n }\n this.closingWaiter?.(event);\n await this.handle(event);\n }\n }\n\n private async handle(event: RealtimeEvent): Promise<void> {\n switch (event.type) {\n case \"input_audio_buffer.speech_started\":\n this.touch();\n return;\n case \"response.created\":\n this.responseActive = true;\n this.pendingCreate = undefined;\n this.touch();\n return;\n case \"response.done\": {\n this.responseActive = false;\n if (this.responseWanted && !this.ending) {\n this.responseWanted = false;\n this.createResponse();\n }\n const usage = (event as { usage?: Usage }).usage;\n if (usage) {\n this.usage = addUsage(this.usage, usage);\n const info = this.info();\n this.hook(() => this.params.onUsage?.(usage, info));\n }\n return;\n }\n case \"conversation.item.input_audio_transcription.completed\": {\n const done = event as {\n transcript?: unknown;\n transcriptionUsage?: Usage;\n transcriptionSeconds?: number;\n };\n this.say(\"user\", String(done.transcript ?? \"\"));\n if (done.transcriptionUsage || done.transcriptionSeconds !== undefined) {\n this.transcription = {\n usage: done.transcriptionUsage\n ? addUsage(this.transcription.usage, done.transcriptionUsage)\n : this.transcription.usage,\n seconds: this.transcription.seconds + (done.transcriptionSeconds ?? 0),\n };\n const info = this.info();\n const usage = {\n ...(done.transcriptionUsage ? { usage: done.transcriptionUsage } : {}),\n ...(done.transcriptionSeconds !== undefined\n ? { seconds: done.transcriptionSeconds }\n : {}),\n };\n this.hook(() => this.params.onTranscriptionUsage?.(usage, info));\n }\n return;\n }\n case \"response.output_audio_transcript.done\":\n this.say(\"assistant\", String((event as { transcript?: unknown }).transcript ?? \"\"));\n return;\n case \"response.output_text.done\":\n this.say(\"assistant\", String((event as { text?: unknown }).text ?? \"\"));\n return;\n case \"response.function_call_arguments.done\": {\n const call = event as { call_id: string; name: string; arguments: string };\n this.touch();\n if (!this.ending) this.call(call.call_id, call.name, call.arguments);\n return;\n }\n case \"session.updated\":\n if (this.tampered((event as { session?: Record<string, any> }).session)) {\n void this.end(\"session_tampered\", null);\n }\n return;\n case \"error\": {\n const error = (event as { error?: { code?: string; message?: string; event_id?: string } })\n .error;\n this.errors.push({ code: error?.code, message: String(error?.message ?? \"\") });\n // The vendor refused the bridge's own `response.create`: no response\n // will start, so stop waiting for one — or, when one is already\n // running, ask again once it is done.\n if (this.pendingCreate && error?.event_id === this.pendingCreate) {\n this.pendingCreate = undefined;\n if (error.code === \"conversation_already_has_active_response\") {\n this.responseActive = true;\n this.responseWanted = true;\n } else {\n this.responseActive = false;\n }\n }\n return;\n }\n case \"sideband.closed\": {\n const closed = event as { code: number; byClient: boolean };\n if (!this.ending && !closed.byClient) {\n void this.end(closed.code === 1000 ? \"call_ended\" : \"sideband_lost\", null);\n }\n return;\n }\n }\n }\n\n private say(role: \"user\" | \"assistant\", text: string): void {\n if (text.trim()) this.transcript.push({ role, text, at: Date.now() });\n }\n\n // --- the tools ------------------------------------------------------------\n\n private call(callId: string, name: string, rawArgs: string): void {\n const args = parseArgs(rawArgs);\n if (name === this.delegateName) {\n const request = typeof args.request === \"string\" ? args.request.trim() : \"\";\n if (!request)\n return this.answer(callId, { status: \"error\", message: \"The request was empty.\" });\n return this.enqueue({\n record: { request, status: \"queued\" },\n turn: { text: request },\n callId,\n });\n }\n const handler = this.toolHandlers.get(name);\n if (handler) return void this.runTool(callId, handler, args);\n switch (name) {\n case \"stop_work\": {\n const running = this.running;\n if (running) {\n running.stopRequested = true;\n running.handle?.stop({ reason: \"Stopped by voice.\" });\n }\n const dropped = this.dropQueue();\n return this.answer(callId, { stopped: Boolean(running), dropped });\n }\n case \"work_status\":\n return this.answer(callId, {\n running: this.running\n ? { request: this.running.record.request, step: this.lastProgress ?? \"starting\" }\n : null,\n queued: this.queue.map((job) => job.record.request),\n ...(this.pending.length ? { needsInput: this.questions() } : {}),\n });\n case \"answer_question\": {\n if (!this.pending.length) {\n return this.answer(callId, { status: \"error\", message: \"There is no open question.\" });\n }\n const answer = typeof args.answer === \"string\" ? args.answer : \"\";\n const approve = typeof args.approve === \"boolean\" ? args.approve : undefined;\n const toolResults = this.pending.map((call) => toolResult(call, answer, approve));\n this.pending = [];\n return this.enqueue({\n record: { request: `(answer) ${answer}`, status: \"queued\" },\n turn: { toolResults },\n callId,\n });\n }\n default:\n return this.answer(callId, {\n status: \"error\",\n message: `There is no tool called ${name}.`,\n });\n }\n }\n\n private enqueue(job: Job): void {\n if (!this.running) {\n this.requests.push(job.record);\n void this.run(job);\n return;\n }\n if (this.queue.length >= this.limits.maxQueued) {\n return this.answer(job.callId!, {\n status: \"busy\",\n message: \"Too many requests are waiting. Ask the user to wait for the current one.\",\n });\n }\n this.requests.push(job.record);\n this.queue.push(job);\n this.answer(job.callId!, {\n status: \"queued\",\n position: this.queue.length,\n message: \"It will start when the current request is done.\",\n });\n job.callId = undefined;\n }\n\n private async run(job: Job): Promise<void> {\n this.running = job;\n job.record.status = \"running\";\n this.lastProgress = undefined;\n this.pauseIdle();\n try {\n const waited = new Set<string>();\n await this.waitForThread(waited);\n const body = await this.latestBody();\n // Looked for again: a typed message may have started while the body was\n // read. The window left is the one `find` takes.\n while (!job.stopRequested && (await this.waitForThread(waited))) {\n // waited for one more\n }\n if (job.stopRequested || this.ending) {\n job.record.status = \"dropped\";\n this.complete(job, { status: \"stopped\" });\n return;\n }\n let turn: AgentTurn;\n try {\n turn = await this.params.controller.startTurn({\n threadId: this.threadId,\n user: this.params.user,\n body,\n turn: job.turn,\n });\n } catch (error) {\n job.record.status = \"refused\";\n this.complete(job, {\n status: \"refused\",\n message: error instanceof Error ? error.message : \"The request could not be started.\",\n });\n return;\n }\n job.handle = turn;\n job.record.runId = turn.runId;\n void this.follow(turn);\n const result = await turn.result();\n job.record.status = \"done\";\n job.record.finishReason = result.finishReason;\n if (result.finishReason === \"awaiting-input\" && result.pending.length) {\n this.pending = result.pending;\n this.complete(job, {\n status: \"needs_input\",\n text: result.text,\n questions: this.questions(),\n });\n } else if (result.finishReason === \"error\") {\n this.complete(job, {\n status: \"failed\",\n message: result.error?.message ?? \"The work failed.\",\n });\n } else if (result.finishReason === \"aborted\") {\n this.complete(job, { status: \"stopped\", text: result.text });\n } else {\n this.complete(job, { status: \"done\", text: result.text });\n }\n } catch (error) {\n job.record.status = \"done\";\n this.complete(job, {\n status: \"failed\",\n message: error instanceof Error ? error.message : \"The work failed.\",\n });\n } finally {\n this.running = undefined;\n this.flushNote();\n const next = this.queue.shift();\n if (next && !this.ending) void this.run(next);\n else this.touch();\n }\n }\n\n /**\n * A `tools` / MCP call. It runs beside the voice (the event loop goes on),\n * under the per-minute limit and its timeout, and its output goes back as\n * the call's `function_call_output`. A failure's message reaches the model\n * only when it is a `ToolError`'s.\n */\n private async runTool(\n callId: string,\n handler: VoiceToolHandler,\n args: Record<string, unknown>,\n ): Promise<void> {\n const name = handler.tool.name;\n const now = Date.now();\n this.toolCallTimes = this.toolCallTimes.filter((at) => now - at < 60_000);\n if (this.toolCallTimes.length >= this.limits.maxToolCallsPerMinute) {\n const record: VoiceToolCallRecord = { name, status: \"busy\" };\n this.toolCalls.push(record);\n this.answer(callId, {\n status: \"busy\",\n message: \"Too many tool calls in the last minute. Tell the user to wait a moment.\",\n });\n return;\n }\n this.toolCallTimes.push(now);\n\n const record: VoiceToolCallRecord = { name, status: \"running\" };\n this.toolCalls.push(record);\n this.toolsRunning += 1;\n this.pauseIdle();\n const abort = new AbortController();\n const timeoutMs = handler.timeoutMs ?? this.limits.toolTimeoutMs;\n let timer: ReturnType<typeof setTimeout> | undefined;\n let payload: Record<string, unknown>;\n try {\n const output = await Promise.race([\n handler.run(args, { sessionId: this.sessionId, signal: abort.signal }),\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n // The refusal first: a tool that answers its abort must not win the race.\n reject(new ToolError(`\"${name}\" took longer than ${Math.round(timeoutMs / 1000)} s.`));\n abort.abort();\n }, timeoutMs);\n }),\n ]);\n record.status = \"done\";\n payload = { status: \"done\", output: this.clip(output) };\n } catch (error) {\n if (error instanceof VoiceHangup) {\n record.status = \"refused\";\n record.message = error.message;\n void this.end(\"usage\", error.line ?? null);\n return;\n }\n const message = error instanceof ToolError ? error.message : \"The tool failed.\";\n if (!(error instanceof ToolError)) {\n console.error(`[gemi/ai] the voice tool \"${name}\" threw.`, error);\n }\n record.status = \"failed\";\n record.message = message;\n payload = { status: \"failed\", message };\n } finally {\n clearTimeout(timer);\n record.durationMs = Date.now() - now;\n this.toolsRunning -= 1;\n this.touch();\n }\n const info = this.info();\n this.hook(() => this.params.onToolCall?.({ ...record }, info));\n if (!this.ending) this.answer(callId, payload);\n }\n\n /** A tool's output, cut to `toolOutputChars` of JSON. */\n private clip(output: unknown): unknown {\n let json: string | undefined;\n try {\n json = JSON.stringify(output);\n } catch {\n return String(output);\n }\n if (json === undefined || json.length <= this.limits.toolOutputChars) return output;\n return `${json.slice(0, this.limits.toolOutputChars)}… (cut: ${json.length} characters in all)`;\n }\n\n /** A run already going on the thread (a typed message) is waited for, not\n * superseded. */\n private async waitForThread(waited = new Set<string>()): Promise<boolean> {\n const runs = this.params.liveRuns;\n if (!runs) return false;\n const found = await runs.find({ threadId: this.threadId });\n // A run already waited for counts as over, even if a store still lists it.\n const run = found && !waited.has(found.runId) ? runs.get(found.runId) : null;\n if (!found || !run) return false;\n waited.add(found.runId);\n await run.result().catch(() => undefined);\n return true;\n }\n\n private async latestBody(): Promise<Body> {\n const store = this.params.store;\n if (!store) return this.body;\n const record = await store.get(this.sessionId).catch(() => null);\n if (record) this.body = record.body as Body;\n return this.body;\n }\n\n private async follow(turn: AgentTurn): Promise<void> {\n const summarize = this.params.progress ?? defaultProgress();\n try {\n for await (const event of turn.run) {\n const line = summarize(event as AgentStreamEvent);\n if (line) this.note(line);\n }\n } catch {\n // Progress is a courtesy; the result is read separately.\n }\n }\n\n private complete(job: Job, payload: Record<string, unknown>): void {\n if (this.ending) return;\n if (job.callId) {\n this.sideband.functionOutput(job.callId, payload);\n job.callId = undefined;\n } else {\n this.sideband.addNote(\n `Update on the earlier request \"${job.record.request}\": ${JSON.stringify(payload)}`,\n );\n }\n this.respond();\n }\n\n private answer(callId: string, payload: Record<string, unknown>): void {\n this.sideband.functionOutput(callId, payload);\n this.respond();\n }\n\n /** Asks the voice to speak, once the response in flight (if any) is done:\n * a second `response.create` while one is active is refused by the vendor. */\n private respond(): void {\n if (this.ending) return;\n if (this.responseActive) {\n this.responseWanted = true;\n return;\n }\n this.responseActive = true;\n this.createResponse();\n }\n\n /** `response.create` with an `event_id`, so a refusal can be told apart. */\n private createResponse(): void {\n const eventId = `gemi_voice_${crypto.randomUUID()}`;\n this.pendingCreate = eventId;\n this.sideband.send({ type: \"response.create\", event_id: eventId });\n }\n\n private questions() {\n return this.pending.map((call) => ({\n kind: call.kind,\n tool: String(call.name),\n input: call.input,\n }));\n }\n\n private dropQueue(): number {\n const dropped = this.queue.splice(0);\n for (const job of dropped) job.record.status = \"dropped\";\n return dropped.length;\n }\n\n // --- progress notes -------------------------------------------------------\n\n private note(line: string): void {\n if (line === this.lastProgress) return;\n this.lastProgress = line;\n const wait = this.lastNoteAt + this.limits.progressIntervalMs - Date.now();\n if (wait <= 0) return this.flushNote();\n this.noteTimer ??= setTimeout(() => this.flushNote(), wait);\n }\n\n private flushNote(): void {\n if (this.noteTimer) clearTimeout(this.noteTimer);\n this.noteTimer = undefined;\n if (!this.lastProgress || this.ending || !this.running) return;\n this.lastNoteAt = Date.now();\n this.sideband.addNote(`Progress on \"${this.running.record.request}\": ${this.lastProgress}`);\n }\n\n // --- limits ---------------------------------------------------------------\n\n private touch(): void {\n if (this.idleTimer) clearTimeout(this.idleTimer);\n this.idleTimer = undefined;\n if (this.running || this.toolsRunning > 0 || this.ending) return;\n this.idleTimer = setTimeout(\n () => void this.end(\"idle\", this.lines.idle),\n this.limits.idleTimeoutMs,\n );\n }\n\n private pauseIdle(): void {\n if (this.idleTimer) clearTimeout(this.idleTimer);\n this.idleTimer = undefined;\n }\n\n private info(): VoiceUsageInfo {\n return {\n sessionId: this.sessionId,\n total: this.usage,\n elapsedMs: Date.now() - this.startedAt,\n transcription: this.transcription,\n };\n }\n\n private tick(): void {\n if (this.ending) return;\n const info = this.info();\n this.hook(() => this.params.onTick?.(info));\n }\n\n /** Runs an app hook after the ones before it, without holding up the\n * sideband's events. */\n private hook(fn: () => void | Promise<void>): void {\n this.hooks = this.hooks.then(async () => {\n try {\n await fn();\n } catch (error) {\n if (error instanceof VoiceHangup) void this.end(\"usage\", error.line ?? null);\n else {\n console.error(\"[gemi/ai] a voice hook threw; ending the call.\", error);\n void this.end(\"error\", this.lines.error);\n }\n }\n });\n }\n\n private tampered(session: Record<string, any> | undefined): boolean {\n const expected = this.params.session;\n if (!expected || !session) return false;\n if (\n expected.instructions !== undefined &&\n session.instructions !== undefined &&\n session.instructions !== expected.instructions\n ) {\n return true;\n }\n if (Array.isArray(session.tools)) {\n // `expected.tools` already holds the voice tools when the session came\n // from `this.voice()`, and not when an app passed its own: a set either way.\n const want = new Set(\n [...voiceTools(this.params.delegate), ...(expected.tools ?? [])].map((tool) => tool.name),\n );\n const got = new Set(session.tools.map((tool: { name?: unknown }) => String(tool?.name)));\n if (want.size !== got.size || [...want].some((name) => !got.has(name))) return true;\n }\n return false;\n }\n\n // --- the end --------------------------------------------------------------\n\n private async finish(reason: VoiceEndReason, line: string | null): Promise<VoiceSummary> {\n for (const timer of this.timers) clearTimeout(timer);\n if (this.idleTimer) clearTimeout(this.idleTimer);\n if (this.noteTimer) clearTimeout(this.noteTimer);\n if (this.tickTimer) clearInterval(this.tickTimer);\n this.dropQueue();\n\n const open = reason !== \"call_ended\" && reason !== \"sideband_lost\";\n if (line && open) await this.closingLine(line);\n if (reason !== \"call_ended\") await this.hangUp();\n else this.sideband.close();\n // Hooks queued before the end (the last response's usage) finish first.\n await this.hooks;\n\n const endedAt = Date.now();\n const durationMs = endedAt - this.startedAt;\n const summary: VoiceSummary = {\n sessionId: this.sessionId,\n ...(this.callId ? { callId: this.callId } : {}),\n threadId: this.threadId,\n reason,\n startedAt: this.startedAt,\n endedAt,\n durationMs,\n seconds: Math.ceil(durationMs / 1000),\n usage: this.usage,\n transcription: this.transcription,\n transcript: this.transcript,\n requests: this.requests,\n toolCalls: this.toolCalls,\n errors: this.errors,\n };\n live.delete(this.sessionId);\n await this.params.store\n ?.update(this.sessionId, { endedAt, endReason: reason })\n .catch(() => undefined);\n try {\n await this.params.onEnd?.(summary);\n } catch (error) {\n console.error(\"[gemi/ai] a voice session's onEnd threw.\", error);\n }\n this.resolveEnded(summary);\n return summary;\n }\n\n /**\n * Hangs the call up. When the vendor refuses, the sideband stays open (it is\n * what meters the call) until the vendor ends the call or `hangupGraceMs`\n * passes, so usage that arrives meanwhile is still counted.\n */\n private async hangUp(): Promise<void> {\n try {\n await this.hangupCall();\n } catch (error) {\n console.error(\"[gemi/ai] a voice call could not be hung up; waiting for the vendor.\", error);\n this.errors.push({\n code: \"hangup_failed\",\n message: error instanceof Error ? error.message : String(error),\n });\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n this.sideband.closed,\n new Promise((resolve) => (timer = setTimeout(resolve, this.limits.hangupGraceMs))),\n ]);\n clearTimeout(timer);\n this.sideband.close();\n }\n }\n\n /**\n * Says `line` and waits for it to finish playing, or `closingLineMs`,\n * whichever is first.\n *\n * A response still running is cancelled first, and its own `response.done`\n * is waited for before the line is asked for: a `response.create` sent\n * while one is active is refused, and the cancelled response's audio events\n * must not count as the line's. The line's response is then matched by id:\n * its `response.done`, then `output_audio_buffer.stopped` for it (a\n * WebRTC event; if the sideband does not get it, `closingLineMs` ends the\n * wait).\n */\n private async closingLine(line: string): Promise<void> {\n await new Promise<void>((resolve) => {\n const eventId = `gemi_voice_closing_${crypto.randomUUID()}`;\n const cancelId = `gemi_voice_cancel_${crypto.randomUUID()}`;\n let stage: \"cancelling\" | \"asked\" | \"playing\" = this.responseActive ? \"cancelling\" : \"asked\";\n let lineResponse: string | undefined;\n const timer = setTimeout(finish, this.limits.closingLineMs);\n function finish() {\n clearTimeout(timer);\n resolve();\n }\n const ask = () => {\n stage = \"asked\";\n this.sideband.send({\n type: \"response.create\",\n event_id: eventId,\n response: {\n instructions: `Say exactly this to the user, and nothing else: \"${line}\"`,\n tool_choice: \"none\",\n },\n });\n };\n this.closingWaiter = (event) => {\n const e = event as {\n type: string;\n response?: { id?: string };\n response_id?: string;\n error?: { event_id?: string };\n };\n if (e.type === \"sideband.closed\") return finish();\n if (stage === \"cancelling\") {\n // Done (cancelled), or the cancel refused because nothing was active.\n if (\n e.type === \"response.done\" ||\n (e.type === \"error\" && e.error?.event_id === cancelId)\n ) {\n ask();\n }\n return;\n }\n if (e.type === \"error\" && e.error?.event_id === eventId) return finish();\n if (e.type === \"response.created\" && !lineResponse) {\n lineResponse = e.response?.id;\n return;\n }\n const ours = (id?: string) => !lineResponse || !id || id === lineResponse;\n if (e.type === \"response.done\" && ours(e.response?.id)) stage = \"playing\";\n else if (\n e.type === \"output_audio_buffer.stopped\" &&\n stage === \"playing\" &&\n ours(e.response_id)\n ) {\n finish();\n }\n };\n if (stage === \"cancelling\")\n this.sideband.send({ type: \"response.cancel\", event_id: cancelId });\n else ask();\n });\n this.closingWaiter = undefined;\n }\n}\n\n// --- helpers ---------------------------------------------------------------\n\nfunction definedOnly<T extends object>(value: T | undefined): Partial<T> {\n if (!value) return {};\n return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined)) as Partial<T>;\n}\n\nfunction parseArgs(raw: string): Record<string, unknown> {\n try {\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === \"object\" && !Array.isArray(parsed) ? parsed : {};\n } catch {\n return {};\n }\n}\n\n/**\n * The spoken answer onto a pending call. A question gets the answer as its\n * output. An approval is approved when `approve` says so, and otherwise denied\n * with the answer as the reason: a voice that did not say \"yes\" has not\n * approved anything. A client tool cannot run in a voice call, so it is denied.\n */\nfunction toolResult(\n call: PendingToolCall,\n answer: string,\n approve: boolean | undefined,\n): ClientToolResult {\n const base = {\n toolCallId: call.toolCallId,\n signature: call.signature,\n ...(call.path ? { path: call.path } : {}),\n };\n if (call.kind === \"question\") return { ...base, output: answer };\n if (call.kind === \"approval\") {\n return { ...base, approve: approve === true, ...(answer ? { reason: answer } : {}) };\n }\n return { ...base, approve: false, reason: \"Not available in a voice call.\" };\n}\n\n/** Names each tool call once, and reads a string (or `message`, `label`,\n * `title`) a tool yields. */\nfunction defaultProgress(): (event: AgentStreamEvent) => string | undefined {\n const seen = new Set<string>();\n return (event) => {\n if (event.type === \"tool-call\") {\n if (event.part.partial || event.resent || seen.has(event.part.toolCallId)) return undefined;\n seen.add(event.part.toolCallId);\n return `running ${String(event.part.name)}`;\n }\n if (event.type === \"tool-progress\") {\n const data = event.data as unknown;\n if (typeof data === \"string\") return data;\n if (data && typeof data === \"object\") {\n for (const key of [\"message\", \"label\", \"title\"] as const) {\n const value = (data as Record<string, unknown>)[key];\n if (typeof value === \"string\" && value) return value;\n }\n }\n }\n return undefined;\n };\n}\n",
|
|
19
19
|
"import { HttpRequest } from \"../http/HttpRequest\";\nimport { RequestContext } from \"../http/requestContext\";\nimport type {\n McpCaller,\n McpRegistry,\n McpToolDescriptor,\n McpToolFilter,\n} from \"../services/mcp/McpRegistry\";\nimport type { RealtimeTool } from \"./providers/realtime\";\n\n/**\n * The app's MCP tools in a voice call (#921), run in this process on the\n * call's sideband.\n *\n * WHY NOT THE REALTIME API'S NATIVE `mcp` TOOL. The native tool has the vendor\n * call the app's `/mcp` endpoint with an `authorization` the session carries.\n * The browser holds the call's data channel, and that channel delivers\n * `session.created` / `session.updated` with the session's tools. Nothing the\n * vendors document says the `mcp` tool's `authorization` (or its `headers`) is\n * left out of those events, so a token in it has to be assumed visible to the\n * browser. The native tool also runs the calls at the vendor: the server sees\n * them only after the fact, so it can't refuse, rate-limit or meter them\n * before they run, and the endpoint has to be reachable from the internet.\n *\n * So the calls come to the server instead, like every other tool call of the\n * voice: the model calls a plain function tool, the bridge receives it on the\n * sideband, and runs it here through `McpRegistry.execute`. That means:\n *\n * - No token is minted at all. The caller is a principal built here from the\n * user `start` saw, exactly as the MCP endpoint builds one from a verified\n * credential: `{ kind: \"remote\", principal: { user, via: \"voice\", id, scopes } }`.\n * - The registry applies its remote rules: only tools exposed to remote\n * callers and reached by `scopes`, features checked per call, and nothing\n * of the browser's own request crosses over (the route runs as the\n * principal's user).\n * - `authorize` runs before each call (keep it on the session's site, say),\n * and the bridge's limits and `onToolCall` hook apply, the same hook chain\n * as `onUsage`, so `VoiceHangup` works there too.\n *\n * Tools with `requiresApproval` are left out. A voice call has no approval\n * screen, and the registry refuses a remote call to such a tool without one.\n */\n\n/** A tool the voice model may call that the bridge runs in this process. */\nexport type VoiceToolHandler = {\n /** What the voice model sees: name, description, parameters. */\n tool: RealtimeTool;\n /**\n * Runs one call. `input` is the model's arguments, parsed from JSON and not\n * validated: validate them. Throw a `ToolError` for a failure the model\n * should read; any other error reaches the model as \"The tool failed.\"\n */\n run(input: unknown, info: VoiceToolRunInfo): Promise<unknown>;\n /** Overrides `limits.toolTimeoutMs` for this tool. */\n timeoutMs?: number;\n};\n\nexport type VoiceToolRunInfo = {\n sessionId: string;\n /** Aborted when the call takes longer than its timeout. */\n signal: AbortSignal;\n};\n\n/** One call to a `VoiceToolHandler`, as `authorize` sees it. */\nexport type VoiceToolCall = { name: string; input: unknown; sessionId: string };\n\nexport type VoiceMcpOptions = {\n /** The app's registry: `app(McpRegistry)`. */\n registry: McpRegistry<any>;\n /** Narrows the tools, as `McpRegistry.list` does. */\n filter?: McpToolFilter;\n /**\n * The scopes this call's principal carries, which decide the tools it sees\n * and may call. Default: every scope the registry declares.\n */\n scopes?: readonly string[];\n /**\n * Before each call. Throw a `ToolError` to refuse with a sentence the model\n * reads (a tool aimed at another site), or a `VoiceHangup` to end the call.\n */\n authorize?: (call: VoiceToolCall) => void | Promise<void>;\n /** Per call. Default: `limits.toolTimeoutMs`. */\n timeoutMs?: number;\n};\n\n/** Where an MCP call made from a voice call is dispatched from. Never sent. */\nconst VOICE_MCP_URL = \"http://gemi.internal/__gemi__/voice/mcp\";\n\n/**\n * The registry's tools as `VoiceToolHandler`s, for the user `user`. Call it\n * inside the request that starts the call: features are evaluated against it\n * for the listing (and again, per call, by `execute`).\n *\n * Throws when `user` is empty: MCP tools run as a signed-in user, never as\n * nobody.\n */\nexport async function mcpVoiceTools(\n options: VoiceMcpOptions,\n who: { user: unknown; sessionId: string },\n): Promise<VoiceToolHandler[]> {\n if (!who.user) {\n throw new Error(\n \"Voice MCP tools run as the signed-in user, and this voice session has none. Give `mcp` only to a signed-in user's session.\",\n );\n }\n const { registry } = options;\n const scopes = options.scopes ?? registry.scopes().map((scope) => scope.name);\n const callerFor = (req: HttpRequest<any, any>): McpCaller => ({\n kind: \"remote\",\n req,\n principal: {\n user: who.user as never,\n via: \"voice\",\n id: `voice:${who.sessionId}`,\n scopes,\n },\n });\n\n const descriptors: McpToolDescriptor[] = await registry.available(\n callerFor(serverRequest()),\n options.filter,\n );\n return descriptors\n .filter((descriptor) => !descriptor.requiresApproval)\n .map((descriptor) => ({\n tool: {\n name: descriptor.name,\n description: descriptor.description,\n parameters: descriptor.inputSchema,\n },\n ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n run: (input, info) => {\n const req = serverRequest();\n // A request scope of its own, carrying the user, as `startTurn` opens\n // one: the call runs long after the request that started it.\n return RequestContext.run(\n req,\n async () => {\n await options.authorize?.({ name: descriptor.name, input, sessionId: info.sessionId });\n return registry.execute(callerFor(req), descriptor.name, input, undefined, {\n signal: info.signal,\n });\n },\n { user: who.user as never },\n );\n },\n }));\n}\n\nfunction serverRequest(): HttpRequest<any, any> {\n return new HttpRequest<any, any>(\n new Request(VOICE_MCP_URL, { method: \"POST\" }),\n {},\n \"api\",\n new URL(VOICE_MCP_URL).pathname,\n );\n}\n",
|
|
20
20
|
"import type { VoiceEndReason } from \"./voice/wire\";\n\n/**\n * A voice session's state, outside the process that holds its sideband (#921).\n *\n * A `PATCH` (the selection changed) or a `DELETE` (the user pressed End) can\n * land on any instance behind a load balancer. The instance that answers it\n * reads and writes the session here; the instance holding the sideband reads\n * the latest `body` before every delegated turn. Ending does not need the\n * holder at all: whoever answers the `DELETE` hangs the call up at the vendor,\n * and the holder's sideband sees the call close.\n *\n * Small and JSON-shaped on purpose, so a database or Redis implementation is a\n * page of code. `MemoryVoiceSessionStore` is the process-local default.\n */\nexport type VoiceSessionRecord = {\n id: string;\n /** The vendor's call id. */\n callId: string;\n threadId: string;\n /** `runOwner` of the request that started it; `null` is nobody. */\n owner: string | null;\n /** The controller's `Body`, as last sent. */\n body: Record<string, unknown>;\n /** Epoch ms. */\n startedAt: number;\n endedAt?: number;\n endReason?: VoiceEndReason;\n};\n\nexport interface VoiceSessionStore {\n create(record: VoiceSessionRecord): Promise<void>;\n get(id: string): Promise<VoiceSessionRecord | null>;\n /** Merges `patch` into the record. A missing record is not an error. */\n update(id: string, patch: Partial<Omit<VoiceSessionRecord, \"id\">>): Promise<void>;\n}\n\n/**\n * Process-local. Ended sessions are dropped after `retainEndedMs` (default 10\n * minutes), so a long-lived process does not keep every call it ever had.\n */\nexport class MemoryVoiceSessionStore implements VoiceSessionStore {\n private readonly records = new Map<string, VoiceSessionRecord>();\n private readonly retainEndedMs: number;\n\n constructor(options: { retainEndedMs?: number } = {}) {\n this.retainEndedMs = options.retainEndedMs ?? 10 * 60_000;\n }\n\n async create(record: VoiceSessionRecord): Promise<void> {\n this.sweep();\n this.records.set(record.id, structuredClone(record));\n }\n\n async get(id: string): Promise<VoiceSessionRecord | null> {\n const record = this.records.get(id);\n return record ? structuredClone(record) : null;\n }\n\n async update(id: string, patch: Partial<Omit<VoiceSessionRecord, \"id\">>): Promise<void> {\n const record = this.records.get(id);\n if (!record) return;\n this.records.set(id, { ...record, ...structuredClone(patch), id });\n }\n\n private sweep(): void {\n const cutoff = Date.now() - this.retainEndedMs;\n for (const [id, record] of this.records) {\n if (record.endedAt !== undefined && record.endedAt < cutoff) this.records.delete(id);\n }\n }\n}\n\n/** The store `AgentController.voiceStore` uses unless an app sets another. */\nexport const defaultVoiceStore = new MemoryVoiceSessionStore();\n",
|
|
21
|
-
"import type { SQL, TransactionSQL } from \"bun\";\n\nimport type { DatabaseConnection } from \"../../database/Connection\";\nimport type { Dialect } from \"../../database/dialect\";\nimport { currentConnectionName, currentTransaction, withTransaction } from \"../../orm/context\";\nimport type { AgentStore, CreateThreadParams, ThreadSweepResult } from \"../AgentController\";\nimport { keepSummary, type ThreadSummary } from \"../contextCompaction\";\nimport type { AgentMessage } from \"../types\";\n\nexport type DatabaseAgentStoreOptions = {\n /**\n * The threads table. Default `gemi_agent_threads`. A plain identifier\n * (letters, digits and underscores), because it is spliced into every\n * statement.\n */\n threadsTable?: string;\n /** The messages table. Default `gemi_agent_messages`. A plain identifier. */\n messagesTable?: string;\n /**\n * Refuse every call on the unscoped store (#1177): only a `forScope(scope)`\n * view reads or writes threads. For an app where every thread belongs to a\n * tenant, so a call that forgot its scope is an error rather than a read\n * across all of them. `createTable()` is still allowed. Default `false`.\n */\n requireScope?: boolean;\n /**\n * Called first in every transaction a scoped view opens itself (#1177), with\n * the transaction and the scope. For row-level security keyed on a session\n * setting:\n *\n * beginScope: (tx, scope) => tx`SELECT set_config('app.current_id', ${scope}, true)`\n *\n * With it, every call of a scoped view runs in such a transaction, reads\n * included, so the policy applies to writes made after the request ended\n * (a run's messages as it streams). A call made inside an open ORM\n * transaction on this store's connection joins that one instead, which is\n * the app's, and the app's own setting applies; the hook is not called.\n */\n beginScope?: (tx: SQL, scope: string) => unknown;\n /**\n * Threads expire this long after they are created (#1312), or after their\n * last append with `slidingTtl`. An expired thread is one the store does not\n * have: `loadThread` and `getThread` answer `null` (so the controller\n * answers 404 and runs no turn), `listThreads` leaves it out, and\n * `appendMessages` refuses it. `sweepExpired()` deletes it with its messages\n * and summaries. `createThread({ ttlMs })` sets one thread's, and `null`\n * there keeps that thread.\n *\n * Setting it turns expiry on for this store: its statements read the\n * `expires_at` and `ttl_ms` columns, which `createTable()` and\n * `addExpiryColumns()` add (see the upgrade notes for the Prisma fields).\n * Unset, the store never names them and nothing expires. Threads created\n * before it was set have no expiry.\n */\n ttlMs?: number;\n /**\n * With `ttlMs`, each append moves a thread's expiry to `ttlMs` from then, so\n * a conversation lasts as long as someone keeps writing to it. Default\n * `false`: the expiry is fixed when the thread is created, which suits a\n * thread that lives as long as the token that grants it.\n */\n slidingTtl?: boolean;\n};\n\n/** One thread, as `listThreads` and `getThread` answer it. */\nexport type AgentThreadRecord = {\n id: string;\n /** What `createThread` was given as `userId`, as a string, or `null`. */\n userId: string | null;\n /** The first user message's text, cut at 100 characters, once there is one. */\n title: string | null;\n /** Epoch milliseconds, from the database's clock. */\n createdAt: number;\n /** Epoch milliseconds of the last write. */\n updatedAt: number;\n /**\n * Epoch milliseconds the thread expires at (#1312), or `null` for one that\n * does not. Only on a store with `ttlMs`; absent otherwise.\n */\n expiresAt?: number | null;\n};\n\ntype Row = Record<string, unknown>;\n\n/** Each SQLite client's transactions, chained so they run one at a time. */\nconst sqliteQueue = new WeakMap<SQL, Promise<void>>();\n\n/** How much of the first user message becomes the thread's title. */\nconst TITLE_LENGTH = 100;\n\n/**\n * Conversations (#1063) in two tables of the app's own database, so a thread\n * outlives the process and every instance reads the same one. The durable\n * `AgentStore`; `MemoryAgentStore` stays the default.\n *\n * export class ChatController extends AgentController {\n * agent = chatAgent;\n * store = agentStore; // new DatabaseAgentStore(app(DatabaseManager).connection()), once, at module scope\n * }\n *\n * Written for SQLite, Postgres and MySQL 8 / MariaDB 10.6+ in raw SQL, like\n * the other database stores, and the tables are the app's to create: add the\n * Prisma models from the docs, or call `createTable()`.\n *\n * - **Messages** are rows of JSON, one per message id, in the order the thread\n * first saw them. `appendMessages` replaces a message it already holds in\n * place, so a message written several times during a run keeps one row.\n * - **One writer per thread at a time.** An append runs in a transaction that\n * first updates the thread's row, which locks it on Postgres and MySQL (and\n * takes SQLite's write lock), so two appends to one thread cannot hand out\n * the same position.\n * - **Summaries** for `contextWindow.compact` live on the thread's row and go\n * with it; `lockSummary` is a compare-and-set on the same row, so several\n * instances do not summarise the same thread at once.\n * - **Ownership is the app's.** `createThread` records the `userId` it is\n * given and `listThreads` filters on it, but nothing here checks who is\n * asking: the app's routes do, as they do for any thread id.\n * - **Scopes** (#1177): `forScope(scope)` is the same store bound to one\n * tenant key. It records the scope on every thread and message it writes and\n * filters every read and write by it, so a thread of another scope is one it\n * does not have. The unscoped store is today's: it reads every row, scoped\n * or not, and its statements do not name the `scope` column, so an app that\n * never scopes needs no migration. `requireScope` refuses it outright;\n * `beginScope` opens each scoped call's transaction (row-level security).\n */\nexport class DatabaseAgentStore implements AgentStore {\n readonly threadsTable: string;\n readonly messagesTable: string;\n /** The scope this view is bound to (`forScope`), or `null` for the store itself. */\n readonly scope: string | null = null;\n private readonly sql: SQL;\n private readonly dialect: Dialect;\n private readonly connection: string | undefined;\n private readonly options: DatabaseAgentStoreOptions;\n\n constructor(\n connection: Pick<DatabaseConnection, \"sql\" | \"dialect\"> &\n Partial<Pick<DatabaseConnection, \"name\">>,\n options: DatabaseAgentStoreOptions = {},\n ) {\n this.threadsTable = plainIdentifier(options.threadsTable ?? \"gemi_agent_threads\", \"threads\");\n this.messagesTable = plainIdentifier(\n options.messagesTable ?? \"gemi_agent_messages\",\n \"messages\",\n );\n this.sql = connection.sql;\n this.dialect = connection.dialect;\n this.connection = connection.name;\n this.options = options;\n if (options.ttlMs !== undefined) {\n positiveMs(options.ttlMs, \"ttlMs\");\n }\n }\n\n /** Whether threads expire here: the store has a `ttlMs` (#1312). */\n get expires(): boolean {\n return this.options.ttlMs !== undefined;\n }\n\n /**\n * This store bound to one scope, a tenant key (#1177): every thread and\n * message it writes carries the scope, and every read and write is filtered\n * by it. Cheap: the view shares the store's connection, so make one per\n * request or per job. A view's `forScope` binds the store, not the view.\n */\n forScope(scope: string): DatabaseAgentStore {\n if (typeof scope !== \"string\" || scope === \"\") {\n throw new TypeError(\"A DatabaseAgentStore scope is a non-empty string.\");\n }\n const view = new DatabaseAgentStore(\n { sql: this.sql, dialect: this.dialect, name: this.connection },\n this.options,\n );\n (view as { scope: string | null }).scope = scope;\n return view;\n }\n\n /**\n * Creates both tables and their indexes if they do not exist: the DDL Prisma\n * generates for the models in the docs. For tests and for an app that does\n * not manage its schema with Prisma.\n */\n async createTable(): Promise<void> {\n const statements = createAgentStoreTableStatements(\n this.dialect,\n this.threadsTable,\n this.messagesTable,\n );\n for (const statement of statements) await this.sql.unsafe(statement);\n await this.addScopeColumns();\n await this.addExpiryColumns();\n }\n\n /**\n * Adds the `expires_at` and `ttl_ms` columns and the `expires_at` index\n * (#1312) to a threads table created before them, and does nothing to one\n * that has them. `createTable()` calls it; an app that manages its schema\n * with Prisma adds the fields to its model instead.\n */\n async addExpiryColumns(): Promise<void> {\n if (await this.hasColumn(this.threadsTable, \"expires_at\")) return;\n for (const statement of addExpiryColumnStatements(this.dialect, this.threadsTable)) {\n await this.sql.unsafe(statement);\n }\n }\n\n /**\n * Adds the `scope` columns and index (#1177) to tables created before them,\n * and does nothing to tables that have them. `createTable()` calls it; an app\n * that manages its schema with Prisma adds the fields to its models instead\n * (see the upgrade notes).\n */\n async addScopeColumns(): Promise<void> {\n const statements = addScopeColumnStatements(this.dialect, this.threadsTable, this.messagesTable);\n for (const [table, alter] of statements) {\n if (await this.hasColumn(table, \"scope\")) continue;\n for (const statement of alter) await this.sql.unsafe(statement);\n }\n }\n\n private async hasColumn(table: string, column: string): Promise<boolean> {\n try {\n await this.sql.unsafe(`SELECT ${column} FROM ${this.quote(table)} WHERE 1 = 0`);\n return true;\n } catch {\n return false;\n }\n }\n\n async createThread(params: CreateThreadParams = {}): Promise<{ threadId: string }> {\n const threadId = crypto.randomUUID();\n const userId = params.userId === undefined || params.userId === null ? null : String(params.userId);\n const expiry = this.expiryOf(params);\n await this.run(async (q) => {\n const now = this.clock(q);\n if (expiry) {\n const expiresAt =\n expiry.at !== undefined ? this.ms(q, expiry.at) : expiry.ttlMs === null ? null : q`${now} + ${this.ms(q, expiry.ttlMs)}`;\n const ttlMs = expiry.slides && expiry.ttlMs !== null ? this.ms(q, expiry.ttlMs) : null;\n if (this.scope === null) {\n await q`\n INSERT INTO ${this.threads(q)} (id, user_id, created_at, updated_at, expires_at, ttl_ms)\n VALUES (${threadId}, ${userId}, ${now}, ${now}, ${expiresAt}, ${ttlMs})\n `;\n } else {\n await q`\n INSERT INTO ${this.threads(q)} (id, scope, user_id, created_at, updated_at, expires_at, ttl_ms)\n VALUES (${threadId}, ${this.scope}, ${userId}, ${now}, ${now}, ${expiresAt}, ${ttlMs})\n `;\n }\n } else if (this.scope === null) {\n await q`\n INSERT INTO ${this.threads(q)} (id, user_id, created_at, updated_at)\n VALUES (${threadId}, ${userId}, ${now}, ${now})\n `;\n } else {\n await q`\n INSERT INTO ${this.threads(q)} (id, scope, user_id, created_at, updated_at)\n VALUES (${threadId}, ${this.scope}, ${userId}, ${now}, ${now})\n `;\n }\n });\n return { threadId };\n }\n\n async loadThread(threadId: string): Promise<AgentMessage[] | null> {\n return this.run(async (q) => {\n const thread: Row[] = await q`\n SELECT id FROM ${this.threads(q)}\n WHERE id = ${threadId} AND ${this.inScope(q)} AND ${this.live(q)}\n `;\n if (thread.length === 0) return null;\n const rows: Row[] = await q`\n SELECT message FROM ${this.messages(q)}\n WHERE thread_id = ${threadId} AND ${this.inScope(q)}\n ORDER BY position\n `;\n return rows.map((row) => JSON.parse(String(row.message)) as AgentMessage);\n });\n }\n\n async appendMessages(threadId: string, messages: AgentMessage[]): Promise<void> {\n if (messages.length === 0) {\n // Still an error for a thread that is not there, like a non-empty one.\n if ((await this.getThread(threadId)) === null) throw missingThread(threadId);\n return;\n }\n await this.atomically(async (q) => {\n // The write lock first: the row on Postgres and MySQL, the database on\n // SQLite. Everything below reads and writes under it.\n // A sliding thread's expiry moves with the write (`ttl_ms` is set only\n // on those); an expired thread is not touched, and is refused below.\n if (this.expires) {\n await q`\n UPDATE ${this.threads(q)}\n SET updated_at = ${this.clock(q)},\n expires_at = CASE WHEN ttl_ms IS NULL THEN expires_at ELSE ${this.clock(q)} + ttl_ms END\n WHERE id = ${threadId} AND ${this.inScope(q)} AND ${this.live(q)}\n `;\n } else {\n await q`\n UPDATE ${this.threads(q)} SET updated_at = ${this.clock(q)}\n WHERE id = ${threadId} AND ${this.inScope(q)}\n `;\n }\n const thread: Row[] = await q`\n SELECT title FROM ${this.threads(q)}\n WHERE id = ${threadId} AND ${this.inScope(q)} AND ${this.live(q)}\n `;\n if (thread.length === 0) throw missingThread(threadId);\n\n const ids = [...new Set(messages.map((message) => message.id))];\n const held: Row[] = await q`\n SELECT id FROM ${this.messages(q)}\n WHERE thread_id = ${threadId} AND id IN (${list(q, ids)})\n `;\n const existing = new Set(held.map((row) => String(row.id)));\n const [last] = (await q`\n SELECT MAX(position) AS position FROM ${this.messages(q)} WHERE thread_id = ${threadId}\n `) as Row[];\n let position =\n last?.position === null || last?.position === undefined ? 0 : Number(last.position) + 1;\n\n for (const message of messages) {\n const body = JSON.stringify(message);\n if (existing.has(message.id)) {\n await q`\n UPDATE ${this.messages(q)} SET message = ${body}\n WHERE thread_id = ${threadId} AND id = ${message.id}\n `;\n } else if (this.scope === null) {\n await q`\n INSERT INTO ${this.messages(q)} (thread_id, id, position, message, created_at)\n VALUES (${threadId}, ${message.id}, ${position}, ${body}, ${this.clock(q)})\n `;\n existing.add(message.id);\n position += 1;\n } else {\n await q`\n INSERT INTO ${this.messages(q)} (thread_id, scope, id, position, message, created_at)\n VALUES (${threadId}, ${this.scope}, ${message.id}, ${position}, ${body}, ${this.clock(q)})\n `;\n existing.add(message.id);\n position += 1;\n }\n }\n\n if (thread[0]!.title === null || thread[0]!.title === undefined) {\n const title = titleOf(messages);\n if (title !== null) {\n await q`\n UPDATE ${this.threads(q)} SET title = ${title}\n WHERE id = ${threadId} AND title IS NULL\n `;\n }\n }\n });\n }\n\n async removeMessages(threadId: string, messageIds: string[]): Promise<void> {\n if (messageIds.length === 0) return;\n await this.run(async (q) => {\n await q`\n DELETE FROM ${this.messages(q)}\n WHERE thread_id = ${threadId} AND ${this.inScope(q)}\n AND id IN (${list(q, [...new Set(messageIds)])})\n `;\n });\n }\n\n async loadSummaries(threadId: string): Promise<ThreadSummary[]> {\n return this.run(async (q) => {\n const [row] = (await q`\n SELECT summaries FROM ${this.threads(q)}\n WHERE id = ${threadId} AND ${this.inScope(q)} AND ${this.live(q)}\n `) as Row[];\n return row ? parseSummaries(row.summaries) : [];\n });\n }\n\n async saveSummary(threadId: string, summary: ThreadSummary): Promise<void> {\n await this.atomically(async (q) => {\n await q`\n UPDATE ${this.threads(q)} SET updated_at = updated_at\n WHERE id = ${threadId} AND ${this.inScope(q)}\n `;\n const [row] = (await q`\n SELECT summaries FROM ${this.threads(q)}\n WHERE id = ${threadId} AND ${this.inScope(q)} AND ${this.live(q)}\n `) as Row[];\n // A thread that is gone has nothing to summarise; the summary goes with it.\n if (!row) return;\n const summaries = keepSummary(parseSummaries(row.summaries), summary);\n await q`\n UPDATE ${this.threads(q)} SET summaries = ${JSON.stringify(summaries)}\n WHERE id = ${threadId}\n `;\n });\n }\n\n /**\n * A compare-and-set on the thread's row: taken when no one holds it or the\n * holder's `ttlMs` has run out. One lock per thread rather than per cut,\n * which only means two cuts of one thread are not summarised at once.\n */\n async lockSummary(\n threadId: string,\n cutMessageId: string,\n ttlMs: number,\n ): Promise<(() => Promise<void>) | null> {\n const token = `${cutMessageId}:${crypto.randomUUID()}`;\n const taken = await this.run(async (q) => {\n const now = this.clock(q);\n const result = await q`\n UPDATE ${this.threads(q)}\n SET summary_lock = ${token}, summary_lock_until = ${now} + ${this.ms(q, ttlMs)}\n WHERE id = ${threadId} AND ${this.inScope(q)} AND ${this.live(q)}\n AND (summary_lock_until IS NULL OR summary_lock_until <= ${now})\n `;\n return affected(result) > 0;\n });\n if (!taken) return null;\n return async () => {\n await this.run(async (q) => {\n await q`\n UPDATE ${this.threads(q)} SET summary_lock = NULL, summary_lock_until = NULL\n WHERE id = ${threadId} AND ${this.inScope(q)} AND summary_lock = ${token}\n `;\n });\n };\n }\n\n // --- for the app's own routes ------------------------------------------\n\n /** One thread's record, or `null` for an id the store does not have. */\n async getThread(threadId: string): Promise<AgentThreadRecord | null> {\n return this.run(async (q) => {\n const [row] = (await q`\n SELECT ${this.recordColumns(q)} FROM ${this.threads(q)}\n WHERE id = ${threadId} AND ${this.inScope(q)} AND ${this.live(q)}\n `) as Row[];\n return row ? threadOf(row) : null;\n });\n }\n\n /**\n * The threads, most recently written first: all of them, or one user's\n * (`userId` as `createThread` was given it). For a \"your conversations\"\n * list; `limit` defaults to 50, and `offset` pages. A scoped view lists its\n * scope's threads only.\n */\n async listThreads(\n options: { userId?: string | number | null; limit?: number; offset?: number } = {},\n ): Promise<AgentThreadRecord[]> {\n const limit = Math.max(0, Math.floor(options.limit ?? 50));\n const offset = Math.max(0, Math.floor(options.offset ?? 0));\n return this.run(async (q) => {\n const where =\n options.userId === undefined\n ? q`1 = 1`\n : options.userId === null\n ? q`user_id IS NULL`\n : q`user_id = ${String(options.userId)}`;\n const rows: Row[] = await q`\n SELECT ${this.recordColumns(q)} FROM ${this.threads(q)}\n WHERE ${this.inScope(q)} AND ${this.live(q)} AND ${where}\n ORDER BY updated_at DESC, id DESC\n LIMIT ${limit} OFFSET ${offset}\n `;\n return rows.map(threadOf);\n });\n }\n\n /**\n * Deletes the thread, its messages and its summaries. An id the store does\n * not have is ignored. Agent memories scoped to the thread are not touched:\n * see `AgentMemories.deleteScope`.\n */\n async deleteThread(threadId: string): Promise<void> {\n await this.atomically(async (q) => {\n // The thread's scope is checked on the thread's row; its messages go\n // only once the row is known to be this view's.\n const thread: Row[] = await q`\n SELECT id FROM ${this.threads(q)} WHERE id = ${threadId} AND ${this.inScope(q)}\n `;\n if (thread.length === 0) return;\n await q`DELETE FROM ${this.messages(q)} WHERE thread_id = ${threadId}`;\n await q`DELETE FROM ${this.threads(q)} WHERE id = ${threadId}`;\n });\n }\n\n /**\n * Deletes up to `limit` (default 500) expired threads with their messages\n * and summaries (#1312), oldest expiry first. For a `CronJob` every few\n * minutes, next to `AgentController.sweepAttachments()`.\n *\n * A scoped view sweeps its scope only. `now` (epoch milliseconds) stands in\n * for the database's clock, for tests. A store without `ttlMs` has nothing\n * that expires, and answers `{ deleted: 0 }` without touching the table.\n * An expired thread is already unreadable before the sweep runs; the sweep\n * only reclaims its rows.\n */\n async sweepExpired(options: { now?: number; limit?: number } = {}): Promise<ThreadSweepResult> {\n if (!this.expires) {\n this.guard();\n return { deleted: 0 };\n }\n const limit = Math.max(0, Math.floor(options.limit ?? 500));\n if (limit === 0) return { deleted: 0 };\n return this.atomically(async (q) => {\n const cutoff = options.now === undefined ? this.clock(q) : this.ms(q, options.now);\n const expired = q`expires_at IS NOT NULL AND expires_at <= ${cutoff} AND ${this.inScope(q)}`;\n const candidates: Row[] = await q`\n SELECT id FROM ${this.threads(q)} WHERE ${expired}\n ORDER BY expires_at, id\n LIMIT ${limit}\n `;\n if (candidates.length === 0) return { deleted: 0 };\n const ids = candidates.map((row) => String(row.id));\n // Locks the rows (the database on SQLite), so an append that slides one\n // of them waits for the sweep. Then only the ones still expired go.\n await q`UPDATE ${this.threads(q)} SET updated_at = updated_at WHERE id IN (${list(q, ids)})`;\n const still: Row[] = await q`\n SELECT id FROM ${this.threads(q)} WHERE id IN (${list(q, ids)}) AND ${expired}\n `;\n if (still.length === 0) return { deleted: 0 };\n const gone = still.map((row) => String(row.id));\n await q`DELETE FROM ${this.messages(q)} WHERE thread_id IN (${list(q, gone)})`;\n await q`DELETE FROM ${this.threads(q)} WHERE id IN (${list(q, gone)})`;\n return { deleted: gone.length };\n });\n }\n\n // --- plumbing -------------------------------------------------------------\n\n /**\n * Runs `fn` in a transaction: a savepoint in the open ORM transaction when it\n * is on this store's connection, a transaction of its own otherwise.\n */\n private atomically<T>(fn: (q: SQL) => Promise<T>): Promise<T> {\n this.guard();\n if (this.joinable()) {\n return withTransaction(this.sql, (tx) => fn(tx as unknown as SQL), {\n connection: this.connection,\n });\n }\n const scope = this.scope;\n const beginScope = this.options.beginScope;\n const begin = () =>\n this.sql.begin(async (tx) => {\n if (scope !== null && beginScope) await beginScope(tx as unknown as SQL, scope);\n return fn(tx as unknown as SQL);\n }) as Promise<T>;\n if (this.dialect !== \"sqlite\") return begin();\n // One SQLite client is one connection, which holds one transaction at a\n // time: a second `begin` while the first is open fails with \"cannot start\n // a transaction within a transaction\". So this client's transactions take\n // turns. (Several clients on one file wait on SQLite's own lock.)\n const previous = sqliteQueue.get(this.sql) ?? Promise.resolve();\n const next = previous.then(begin, begin);\n sqliteQueue.set(\n this.sql,\n next.then(\n () => {},\n () => {},\n ),\n );\n return next;\n }\n\n /** The open ORM transaction, when it is on this store's connection. */\n private joinable(): TransactionSQL | undefined {\n if (this.connection === undefined) return undefined;\n const tx = currentTransaction();\n if (tx === undefined || currentConnectionName() !== this.connection) return undefined;\n return tx;\n }\n\n /**\n * Runs one call's statements: in the open ORM transaction when there is one\n * on this connection, in a transaction of its own when a scoped view has\n * `beginScope` (so the hook's setting covers them), on the client otherwise.\n * The handle is read at each call and never kept: a stored transaction\n * handle outlives its transaction.\n */\n private run<T>(fn: (q: SQL) => Promise<T>): Promise<T> {\n this.guard();\n const tx = this.joinable() as SQL | undefined;\n if (tx) return fn(tx);\n if (this.scope !== null && this.options.beginScope) return this.atomically(fn);\n return fn(this.sql);\n }\n\n private guard() {\n if (this.scope === null && this.options.requireScope) {\n throw new Error(\n \"This DatabaseAgentStore requires a scope: call it through store.forScope(scope).\",\n );\n }\n }\n\n /** The scope condition: `1 = 1` on the unscoped store, which reads every row. */\n private inScope(q: SQL) {\n return this.scope === null ? q`1 = 1` : q`scope = ${this.scope}`;\n }\n\n /**\n * Not expired (#1312), by the database's clock. `1 = 1` on a store without\n * `ttlMs`, which never names the expiry columns.\n */\n private live(q: SQL) {\n return this.expires ? q`(expires_at IS NULL OR expires_at > ${this.clock(q)})` : q`1 = 1`;\n }\n\n /** The columns of an `AgentThreadRecord`. */\n private recordColumns(q: SQL) {\n return this.expires\n ? q.unsafe(\"id, user_id, title, created_at, updated_at, expires_at\")\n : q.unsafe(\"id, user_id, title, created_at, updated_at\");\n }\n\n /**\n * A new thread's expiry, or `null` on a store without `ttlMs`, which\n * refuses a thread's own.\n */\n private expiryOf(\n params: CreateThreadParams,\n ): { at?: number; ttlMs: number | null; slides: boolean } | null {\n const own = params.ttlMs !== undefined || params.expiresAt !== undefined;\n if (!this.expires) {\n if (own) {\n throw new Error(\n \"createThread({ ttlMs, expiresAt }) needs a store with `ttlMs`: set `new DatabaseAgentStore(connection, { ttlMs })`, which turns expiry on and reads the expiry columns.\",\n );\n }\n return null;\n }\n if (params.expiresAt !== undefined) {\n const at = params.expiresAt instanceof Date ? params.expiresAt.getTime() : params.expiresAt;\n if (!Number.isFinite(at)) throw new TypeError(\"createThread: `expiresAt` is not a valid time.\");\n return { at, ttlMs: null, slides: false };\n }\n const ttlMs = params.ttlMs === undefined ? this.options.ttlMs! : params.ttlMs;\n if (ttlMs !== null) positiveMs(ttlMs, \"createThread: ttlMs\");\n return { ttlMs, slides: this.options.slidingTtl === true };\n }\n\n\n private quote(name: string) {\n return this.dialect === \"mysql\" || this.dialect === \"mariadb\" ? `\\`${name}\\`` : `\"${name}\"`;\n }\n\n private threads(q: SQL) {\n return q.unsafe(this.quote(this.threadsTable));\n }\n\n private messages(q: SQL) {\n return q.unsafe(this.quote(this.messagesTable));\n }\n\n /** The database's clock, in epoch milliseconds. As in `DatabaseAgentJobStore`. */\n private clock(q: SQL) {\n switch (this.dialect) {\n case \"postgres\":\n return q`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;\n case \"mysql\":\n case \"mariadb\":\n return q`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;\n case \"sqlite\":\n return q`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`;\n }\n }\n\n private ms(q: SQL, value: number) {\n const ms = Math.max(0, Math.round(value));\n return this.dialect === \"mysql\" || this.dialect === \"mariadb\"\n ? q`CAST(${ms} AS SIGNED)`\n : q`CAST(${ms} AS BIGINT)`;\n }\n}\n\nfunction plainIdentifier(table: string, which: string): string {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {\n throw new Error(\n `The agent ${which} table name \"${table}\" is not a plain identifier. Use letters, digits and underscores.`,\n );\n }\n return table;\n}\n\nfunction missingThread(threadId: string): Error {\n // As `MemoryAgentStore` says it: the controller checks before the run and\n // never reaches this; a store-level caller that does gets told.\n return new Error(`Thread ${threadId} does not exist here, or has been deleted.`);\n}\n\nfunction list(q: SQL, values: string[]) {\n return values.map((value) => q`${value}`).reduce((all, one) => q`${all}, ${one}`);\n}\n\nfunction titleOf(messages: AgentMessage[]): string | null {\n for (const message of messages) {\n // An event (#1181) is the server's, not what the person asked about.\n if (message.role !== \"user\" || message.event) continue;\n const text = message.content\n .map((part) => (part.type === \"text\" ? part.text : \"\"))\n .join(\" \")\n .replace(/\\s+/g, \" \")\n .trim();\n if (text) return text.length > TITLE_LENGTH ? `${text.slice(0, TITLE_LENGTH - 1)}…` : text;\n }\n return null;\n}\n\nfunction parseSummaries(value: unknown): ThreadSummary[] {\n if (value === null || value === undefined || value === \"\") return [];\n const parsed = JSON.parse(String(value));\n return Array.isArray(parsed) ? (parsed as ThreadSummary[]) : [];\n}\n\nfunction threadOf(row: Row): AgentThreadRecord {\n return {\n id: String(row.id),\n userId: row.user_id === null || row.user_id === undefined ? null : String(row.user_id),\n title: row.title === null || row.title === undefined ? null : String(row.title),\n createdAt: Number(row.created_at),\n updatedAt: Number(row.updated_at),\n ...(\"expires_at\" in row\n ? { expiresAt: row.expires_at === null || row.expires_at === undefined ? null : Number(row.expires_at) }\n : {}),\n };\n}\n\nfunction positiveMs(value: number, name: string) {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) {\n throw new TypeError(`${name} must be a positive number of milliseconds.`);\n }\n}\n\n/** Rows an `UPDATE` touched, across the three drivers. */\nfunction affected(result: unknown): number {\n const counts = result as { count?: number | null; affectedRows?: number | null };\n return Math.max(Number(counts.count ?? 0), Number(counts.affectedRows ?? 0));\n}\n\n/**\n * The tables as Prisma generates them for the models in the docs, with\n * `IF NOT EXISTS` added.\n */\nexport function createAgentStoreTableStatements(\n dialect: Dialect,\n threadsTable: string,\n messagesTable: string,\n): string[] {\n if (dialect === \"mysql\" || dialect === \"mariadb\") {\n return [\n `CREATE TABLE IF NOT EXISTS \\`${threadsTable}\\` (\n \\`id\\` VARCHAR(191) NOT NULL,\n \\`scope\\` VARCHAR(191) NULL,\n \\`user_id\\` VARCHAR(191) NULL,\n \\`title\\` TEXT NULL,\n \\`summaries\\` LONGTEXT NULL,\n \\`summary_lock\\` VARCHAR(191) NULL,\n \\`summary_lock_until\\` BIGINT NULL,\n \\`created_at\\` BIGINT NOT NULL,\n \\`updated_at\\` BIGINT NOT NULL,\n \\`expires_at\\` BIGINT NULL,\n \\`ttl_ms\\` BIGINT NULL,\n\n INDEX \\`${threadsTable}_user_id_updated_at_idx\\`(\\`user_id\\`, \\`updated_at\\`),\n INDEX \\`${threadsTable}_expires_at_idx\\`(\\`expires_at\\`),\n INDEX \\`${threadsTable}_scope_user_id_updated_at_idx\\`(\\`scope\\`, \\`user_id\\`, \\`updated_at\\`),\n PRIMARY KEY (\\`id\\`)\n) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,\n `CREATE TABLE IF NOT EXISTS \\`${messagesTable}\\` (\n \\`thread_id\\` VARCHAR(191) NOT NULL,\n \\`scope\\` VARCHAR(191) NULL,\n \\`id\\` VARCHAR(191) NOT NULL,\n \\`position\\` INTEGER NOT NULL,\n \\`message\\` LONGTEXT NOT NULL,\n \\`created_at\\` BIGINT NOT NULL,\n\n UNIQUE INDEX \\`${messagesTable}_thread_id_position_key\\`(\\`thread_id\\`, \\`position\\`),\n PRIMARY KEY (\\`thread_id\\`, \\`id\\`)\n) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,\n ];\n }\n\n const threadsKey =\n dialect === \"sqlite\" ? `\"id\" TEXT NOT NULL PRIMARY KEY,` : `\"id\" TEXT NOT NULL,`;\n const threadsConstraint =\n dialect === \"sqlite\" ? \"\" : `,\\n\\n CONSTRAINT \"${threadsTable}_pkey\" PRIMARY KEY (\"id\")`;\n return [\n `CREATE TABLE IF NOT EXISTS \"${threadsTable}\" (\n ${threadsKey}\n \"scope\" TEXT,\n \"user_id\" TEXT,\n \"title\" TEXT,\n \"summaries\" TEXT,\n \"summary_lock\" TEXT,\n \"summary_lock_until\" BIGINT,\n \"created_at\" BIGINT NOT NULL,\n \"updated_at\" BIGINT NOT NULL,\n \"expires_at\" BIGINT,\n \"ttl_ms\" BIGINT${threadsConstraint}\n)`,\n `CREATE INDEX IF NOT EXISTS \"${threadsTable}_expires_at_idx\" ON \"${threadsTable}\"(\"expires_at\")`,\n `CREATE INDEX IF NOT EXISTS \"${threadsTable}_user_id_updated_at_idx\" ON \"${threadsTable}\"(\"user_id\", \"updated_at\")`,\n `CREATE INDEX IF NOT EXISTS \"${threadsTable}_scope_user_id_updated_at_idx\" ON \"${threadsTable}\"(\"scope\", \"user_id\", \"updated_at\")`,\n `CREATE TABLE IF NOT EXISTS \"${messagesTable}\" (\n \"thread_id\" TEXT NOT NULL,\n \"scope\" TEXT,\n \"id\" TEXT NOT NULL,\n \"position\" INTEGER NOT NULL,\n \"message\" TEXT NOT NULL,\n \"created_at\" BIGINT NOT NULL,\n\n CONSTRAINT \"${messagesTable}_pkey\" PRIMARY KEY (\"thread_id\", \"id\")\n)`,\n `CREATE UNIQUE INDEX IF NOT EXISTS \"${messagesTable}_thread_id_position_key\" ON \"${messagesTable}\"(\"thread_id\", \"position\")`,\n ];\n}\n\n/**\n * What brings tables created before scopes (#1177) up to date, per table: the\n * `scope` column, and on the threads table its index. Run only for a table\n * that does not have the column yet.\n */\nexport function addScopeColumnStatements(\n dialect: Dialect,\n threadsTable: string,\n messagesTable: string,\n): [table: string, statements: string[]][] {\n if (dialect === \"mysql\" || dialect === \"mariadb\") {\n return [\n [\n threadsTable,\n [\n `ALTER TABLE \\`${threadsTable}\\` ADD COLUMN \\`scope\\` VARCHAR(191) NULL, ADD INDEX \\`${threadsTable}_scope_user_id_updated_at_idx\\`(\\`scope\\`, \\`user_id\\`, \\`updated_at\\`)`,\n ],\n ],\n [messagesTable, [`ALTER TABLE \\`${messagesTable}\\` ADD COLUMN \\`scope\\` VARCHAR(191) NULL`]],\n ];\n }\n return [\n [\n threadsTable,\n [\n `ALTER TABLE \"${threadsTable}\" ADD COLUMN \"scope\" TEXT`,\n `CREATE INDEX IF NOT EXISTS \"${threadsTable}_scope_user_id_updated_at_idx\" ON \"${threadsTable}\"(\"scope\", \"user_id\", \"updated_at\")`,\n ],\n ],\n [messagesTable, [`ALTER TABLE \"${messagesTable}\" ADD COLUMN \"scope\" TEXT`]],\n ];\n}\n\n/**\n * What brings a threads table created before expiry (#1312) up to date: the\n * `expires_at` and `ttl_ms` columns and the `expires_at` index. Run only for a\n * table that does not have `expires_at` yet.\n */\nexport function addExpiryColumnStatements(dialect: Dialect, threadsTable: string): string[] {\n if (dialect === \"mysql\" || dialect === \"mariadb\") {\n return [\n `ALTER TABLE \\`${threadsTable}\\` ADD COLUMN \\`expires_at\\` BIGINT NULL, ADD COLUMN \\`ttl_ms\\` BIGINT NULL, ADD INDEX \\`${threadsTable}_expires_at_idx\\`(\\`expires_at\\`)`,\n ];\n }\n return [\n `ALTER TABLE \"${threadsTable}\" ADD COLUMN \"expires_at\" BIGINT`,\n `ALTER TABLE \"${threadsTable}\" ADD COLUMN \"ttl_ms\" BIGINT`,\n `CREATE INDEX IF NOT EXISTS \"${threadsTable}_expires_at_idx\" ON \"${threadsTable}\"(\"expires_at\")`,\n ];\n}\n",
|
|
21
|
+
"import type { SQL, TransactionSQL } from \"bun\";\n\nimport type { DatabaseConnection } from \"../../database/Connection\";\nimport type { Dialect } from \"../../database/dialect\";\nimport { currentConnectionName, currentTransaction, queuedOnSqlite, withTransaction } from \"../../orm/context\";\nimport type { AgentStore, CreateThreadParams, ThreadSweepResult } from \"../AgentController\";\nimport { keepSummary, type ThreadSummary } from \"../contextCompaction\";\nimport type { AgentMessage } from \"../types\";\n\nexport type DatabaseAgentStoreOptions = {\n /**\n * The threads table. Default `gemi_agent_threads`. A plain identifier\n * (letters, digits and underscores), because it is spliced into every\n * statement.\n */\n threadsTable?: string;\n /** The messages table. Default `gemi_agent_messages`. A plain identifier. */\n messagesTable?: string;\n /**\n * Refuse every call on the unscoped store (#1177): only a `forScope(scope)`\n * view reads or writes threads. For an app where every thread belongs to a\n * tenant, so a call that forgot its scope is an error rather than a read\n * across all of them. `createTable()` is still allowed. Default `false`.\n */\n requireScope?: boolean;\n /**\n * Called first in every transaction a scoped view opens itself (#1177), with\n * the transaction and the scope. For row-level security keyed on a session\n * setting:\n *\n * beginScope: (tx, scope) => tx`SELECT set_config('app.current_id', ${scope}, true)`\n *\n * With it, every call of a scoped view runs in such a transaction, reads\n * included, so the policy applies to writes made after the request ended\n * (a run's messages as it streams). A call made inside an open ORM\n * transaction on this store's connection joins that one instead, which is\n * the app's, and the app's own setting applies; the hook is not called.\n */\n beginScope?: (tx: SQL, scope: string) => unknown;\n /**\n * Threads expire this long after they are created (#1312), or after their\n * last append with `slidingTtl`. An expired thread is one the store does not\n * have: `loadThread` and `getThread` answer `null` (so the controller\n * answers 404 and runs no turn), `listThreads` leaves it out, and\n * `appendMessages` refuses it. `sweepExpired()` deletes it with its messages\n * and summaries. `createThread({ ttlMs })` sets one thread's, and `null`\n * there keeps that thread.\n *\n * Setting it turns expiry on for this store: its statements read the\n * `expires_at` and `ttl_ms` columns, which `createTable()` and\n * `addExpiryColumns()` add (see the upgrade notes for the Prisma fields).\n * Unset, the store never names them and nothing expires. Threads created\n * before it was set have no expiry.\n */\n ttlMs?: number;\n /**\n * With `ttlMs`, each append moves a thread's expiry to `ttlMs` from then, so\n * a conversation lasts as long as someone keeps writing to it. Default\n * `false`: the expiry is fixed when the thread is created, which suits a\n * thread that lives as long as the token that grants it.\n */\n slidingTtl?: boolean;\n};\n\n/** One thread, as `listThreads` and `getThread` answer it. */\nexport type AgentThreadRecord = {\n id: string;\n /** What `createThread` was given as `userId`, as a string, or `null`. */\n userId: string | null;\n /** The first user message's text, cut at 100 characters, once there is one. */\n title: string | null;\n /** Epoch milliseconds, from the database's clock. */\n createdAt: number;\n /** Epoch milliseconds of the last write. */\n updatedAt: number;\n /**\n * Epoch milliseconds the thread expires at (#1312), or `null` for one that\n * does not. Only on a store with `ttlMs`; absent otherwise.\n */\n expiresAt?: number | null;\n};\n\ntype Row = Record<string, unknown>;\n\n\n/** How much of the first user message becomes the thread's title. */\nconst TITLE_LENGTH = 100;\n\n/**\n * Conversations (#1063) in two tables of the app's own database, so a thread\n * outlives the process and every instance reads the same one. The durable\n * `AgentStore`; `MemoryAgentStore` stays the default.\n *\n * export class ChatController extends AgentController {\n * agent = chatAgent;\n * store = agentStore; // new DatabaseAgentStore(app(DatabaseManager).connection()), once, at module scope\n * }\n *\n * Written for SQLite, Postgres and MySQL 8 / MariaDB 10.6+ in raw SQL, like\n * the other database stores, and the tables are the app's to create: add the\n * Prisma models from the docs, or call `createTable()`.\n *\n * - **Messages** are rows of JSON, one per message id, in the order the thread\n * first saw them. `appendMessages` replaces a message it already holds in\n * place, so a message written several times during a run keeps one row.\n * - **One writer per thread at a time.** An append runs in a transaction that\n * first updates the thread's row, which locks it on Postgres and MySQL (and\n * takes SQLite's write lock), so two appends to one thread cannot hand out\n * the same position.\n * - **Summaries** for `contextWindow.compact` live on the thread's row and go\n * with it; `lockSummary` is a compare-and-set on the same row, so several\n * instances do not summarise the same thread at once.\n * - **Ownership is the app's.** `createThread` records the `userId` it is\n * given and `listThreads` filters on it, but nothing here checks who is\n * asking: the app's routes do, as they do for any thread id.\n * - **Scopes** (#1177): `forScope(scope)` is the same store bound to one\n * tenant key. It records the scope on every thread and message it writes and\n * filters every read and write by it, so a thread of another scope is one it\n * does not have. The unscoped store is today's: it reads every row, scoped\n * or not, and its statements do not name the `scope` column, so an app that\n * never scopes needs no migration. `requireScope` refuses it outright;\n * `beginScope` opens each scoped call's transaction (row-level security).\n */\nexport class DatabaseAgentStore implements AgentStore {\n readonly threadsTable: string;\n readonly messagesTable: string;\n /** The scope this view is bound to (`forScope`), or `null` for the store itself. */\n readonly scope: string | null = null;\n private readonly sql: SQL;\n private readonly dialect: Dialect;\n private readonly connection: string | undefined;\n private readonly options: DatabaseAgentStoreOptions;\n\n constructor(\n connection: Pick<DatabaseConnection, \"sql\" | \"dialect\"> &\n Partial<Pick<DatabaseConnection, \"name\">>,\n options: DatabaseAgentStoreOptions = {},\n ) {\n this.threadsTable = plainIdentifier(options.threadsTable ?? \"gemi_agent_threads\", \"threads\");\n this.messagesTable = plainIdentifier(\n options.messagesTable ?? \"gemi_agent_messages\",\n \"messages\",\n );\n this.sql = connection.sql;\n this.dialect = connection.dialect;\n this.connection = connection.name;\n this.options = options;\n if (options.ttlMs !== undefined) {\n positiveMs(options.ttlMs, \"ttlMs\");\n }\n }\n\n /** Whether threads expire here: the store has a `ttlMs` (#1312). */\n get expires(): boolean {\n return this.options.ttlMs !== undefined;\n }\n\n /**\n * This store bound to one scope, a tenant key (#1177): every thread and\n * message it writes carries the scope, and every read and write is filtered\n * by it. Cheap: the view shares the store's connection, so make one per\n * request or per job. A view's `forScope` binds the store, not the view.\n */\n forScope(scope: string): DatabaseAgentStore {\n if (typeof scope !== \"string\" || scope === \"\") {\n throw new TypeError(\"A DatabaseAgentStore scope is a non-empty string.\");\n }\n const view = new DatabaseAgentStore(\n { sql: this.sql, dialect: this.dialect, name: this.connection },\n this.options,\n );\n (view as { scope: string | null }).scope = scope;\n return view;\n }\n\n /**\n * Creates both tables and their indexes if they do not exist: the DDL Prisma\n * generates for the models in the docs. For tests and for an app that does\n * not manage its schema with Prisma.\n */\n async createTable(): Promise<void> {\n const statements = createAgentStoreTableStatements(\n this.dialect,\n this.threadsTable,\n this.messagesTable,\n );\n for (const statement of statements) await this.sql.unsafe(statement);\n await this.addScopeColumns();\n await this.addExpiryColumns();\n }\n\n /**\n * Adds the `expires_at` and `ttl_ms` columns and the `expires_at` index\n * (#1312) to a threads table created before them, and does nothing to one\n * that has them. `createTable()` calls it; an app that manages its schema\n * with Prisma adds the fields to its model instead.\n */\n async addExpiryColumns(): Promise<void> {\n if (await this.hasColumn(this.threadsTable, \"expires_at\")) return;\n for (const statement of addExpiryColumnStatements(this.dialect, this.threadsTable)) {\n await this.sql.unsafe(statement);\n }\n }\n\n /**\n * Adds the `scope` columns and index (#1177) to tables created before them,\n * and does nothing to tables that have them. `createTable()` calls it; an app\n * that manages its schema with Prisma adds the fields to its models instead\n * (see the upgrade notes).\n */\n async addScopeColumns(): Promise<void> {\n const statements = addScopeColumnStatements(this.dialect, this.threadsTable, this.messagesTable);\n for (const [table, alter] of statements) {\n if (await this.hasColumn(table, \"scope\")) continue;\n for (const statement of alter) await this.sql.unsafe(statement);\n }\n }\n\n private async hasColumn(table: string, column: string): Promise<boolean> {\n try {\n await this.sql.unsafe(`SELECT ${column} FROM ${this.quote(table)} WHERE 1 = 0`);\n return true;\n } catch {\n return false;\n }\n }\n\n async createThread(params: CreateThreadParams = {}): Promise<{ threadId: string }> {\n const threadId = crypto.randomUUID();\n const userId = params.userId === undefined || params.userId === null ? null : String(params.userId);\n const expiry = this.expiryOf(params);\n await this.run(async (q) => {\n const now = this.clock(q);\n if (expiry) {\n const expiresAt =\n expiry.at !== undefined ? this.ms(q, expiry.at) : expiry.ttlMs === null ? null : q`${now} + ${this.ms(q, expiry.ttlMs)}`;\n const ttlMs = expiry.slides && expiry.ttlMs !== null ? this.ms(q, expiry.ttlMs) : null;\n if (this.scope === null) {\n await q`\n INSERT INTO ${this.threads(q)} (id, user_id, created_at, updated_at, expires_at, ttl_ms)\n VALUES (${threadId}, ${userId}, ${now}, ${now}, ${expiresAt}, ${ttlMs})\n `;\n } else {\n await q`\n INSERT INTO ${this.threads(q)} (id, scope, user_id, created_at, updated_at, expires_at, ttl_ms)\n VALUES (${threadId}, ${this.scope}, ${userId}, ${now}, ${now}, ${expiresAt}, ${ttlMs})\n `;\n }\n } else if (this.scope === null) {\n await q`\n INSERT INTO ${this.threads(q)} (id, user_id, created_at, updated_at)\n VALUES (${threadId}, ${userId}, ${now}, ${now})\n `;\n } else {\n await q`\n INSERT INTO ${this.threads(q)} (id, scope, user_id, created_at, updated_at)\n VALUES (${threadId}, ${this.scope}, ${userId}, ${now}, ${now})\n `;\n }\n });\n return { threadId };\n }\n\n async loadThread(threadId: string): Promise<AgentMessage[] | null> {\n return this.run(async (q) => {\n const thread: Row[] = await q`\n SELECT id FROM ${this.threads(q)}\n WHERE id = ${threadId} AND ${this.inScope(q)} AND ${this.live(q)}\n `;\n if (thread.length === 0) return null;\n const rows: Row[] = await q`\n SELECT message FROM ${this.messages(q)}\n WHERE thread_id = ${threadId} AND ${this.inScope(q)}\n ORDER BY position\n `;\n return rows.map((row) => JSON.parse(String(row.message)) as AgentMessage);\n });\n }\n\n async appendMessages(threadId: string, messages: AgentMessage[]): Promise<void> {\n if (messages.length === 0) {\n // Still an error for a thread that is not there, like a non-empty one.\n if ((await this.getThread(threadId)) === null) throw missingThread(threadId);\n return;\n }\n await this.atomically(async (q) => {\n // The write lock first: the row on Postgres and MySQL, the database on\n // SQLite. Everything below reads and writes under it.\n // A sliding thread's expiry moves with the write (`ttl_ms` is set only\n // on those); an expired thread is not touched, and is refused below.\n if (this.expires) {\n await q`\n UPDATE ${this.threads(q)}\n SET updated_at = ${this.clock(q)},\n expires_at = CASE WHEN ttl_ms IS NULL THEN expires_at ELSE ${this.clock(q)} + ttl_ms END\n WHERE id = ${threadId} AND ${this.inScope(q)} AND ${this.live(q)}\n `;\n } else {\n await q`\n UPDATE ${this.threads(q)} SET updated_at = ${this.clock(q)}\n WHERE id = ${threadId} AND ${this.inScope(q)}\n `;\n }\n const thread: Row[] = await q`\n SELECT title FROM ${this.threads(q)}\n WHERE id = ${threadId} AND ${this.inScope(q)} AND ${this.live(q)}\n `;\n if (thread.length === 0) throw missingThread(threadId);\n\n const ids = [...new Set(messages.map((message) => message.id))];\n const held: Row[] = await q`\n SELECT id FROM ${this.messages(q)}\n WHERE thread_id = ${threadId} AND id IN (${list(q, ids)})\n `;\n const existing = new Set(held.map((row) => String(row.id)));\n const [last] = (await q`\n SELECT MAX(position) AS position FROM ${this.messages(q)} WHERE thread_id = ${threadId}\n `) as Row[];\n let position =\n last?.position === null || last?.position === undefined ? 0 : Number(last.position) + 1;\n\n for (const message of messages) {\n const body = JSON.stringify(message);\n if (existing.has(message.id)) {\n await q`\n UPDATE ${this.messages(q)} SET message = ${body}\n WHERE thread_id = ${threadId} AND id = ${message.id}\n `;\n } else if (this.scope === null) {\n await q`\n INSERT INTO ${this.messages(q)} (thread_id, id, position, message, created_at)\n VALUES (${threadId}, ${message.id}, ${position}, ${body}, ${this.clock(q)})\n `;\n existing.add(message.id);\n position += 1;\n } else {\n await q`\n INSERT INTO ${this.messages(q)} (thread_id, scope, id, position, message, created_at)\n VALUES (${threadId}, ${this.scope}, ${message.id}, ${position}, ${body}, ${this.clock(q)})\n `;\n existing.add(message.id);\n position += 1;\n }\n }\n\n if (thread[0]!.title === null || thread[0]!.title === undefined) {\n const title = titleOf(messages);\n if (title !== null) {\n await q`\n UPDATE ${this.threads(q)} SET title = ${title}\n WHERE id = ${threadId} AND title IS NULL\n `;\n }\n }\n });\n }\n\n async removeMessages(threadId: string, messageIds: string[]): Promise<void> {\n if (messageIds.length === 0) return;\n await this.run(async (q) => {\n await q`\n DELETE FROM ${this.messages(q)}\n WHERE thread_id = ${threadId} AND ${this.inScope(q)}\n AND id IN (${list(q, [...new Set(messageIds)])})\n `;\n });\n }\n\n async loadSummaries(threadId: string): Promise<ThreadSummary[]> {\n return this.run(async (q) => {\n const [row] = (await q`\n SELECT summaries FROM ${this.threads(q)}\n WHERE id = ${threadId} AND ${this.inScope(q)} AND ${this.live(q)}\n `) as Row[];\n return row ? parseSummaries(row.summaries) : [];\n });\n }\n\n async saveSummary(threadId: string, summary: ThreadSummary): Promise<void> {\n await this.atomically(async (q) => {\n await q`\n UPDATE ${this.threads(q)} SET updated_at = updated_at\n WHERE id = ${threadId} AND ${this.inScope(q)}\n `;\n const [row] = (await q`\n SELECT summaries FROM ${this.threads(q)}\n WHERE id = ${threadId} AND ${this.inScope(q)} AND ${this.live(q)}\n `) as Row[];\n // A thread that is gone has nothing to summarise; the summary goes with it.\n if (!row) return;\n const summaries = keepSummary(parseSummaries(row.summaries), summary);\n await q`\n UPDATE ${this.threads(q)} SET summaries = ${JSON.stringify(summaries)}\n WHERE id = ${threadId}\n `;\n });\n }\n\n /**\n * A compare-and-set on the thread's row: taken when no one holds it or the\n * holder's `ttlMs` has run out. One lock per thread rather than per cut,\n * which only means two cuts of one thread are not summarised at once.\n */\n async lockSummary(\n threadId: string,\n cutMessageId: string,\n ttlMs: number,\n ): Promise<(() => Promise<void>) | null> {\n const token = `${cutMessageId}:${crypto.randomUUID()}`;\n const taken = await this.run(async (q) => {\n const now = this.clock(q);\n const result = await q`\n UPDATE ${this.threads(q)}\n SET summary_lock = ${token}, summary_lock_until = ${now} + ${this.ms(q, ttlMs)}\n WHERE id = ${threadId} AND ${this.inScope(q)} AND ${this.live(q)}\n AND (summary_lock_until IS NULL OR summary_lock_until <= ${now})\n `;\n return affected(result) > 0;\n });\n if (!taken) return null;\n return async () => {\n await this.run(async (q) => {\n await q`\n UPDATE ${this.threads(q)} SET summary_lock = NULL, summary_lock_until = NULL\n WHERE id = ${threadId} AND ${this.inScope(q)} AND summary_lock = ${token}\n `;\n });\n };\n }\n\n // --- for the app's own routes ------------------------------------------\n\n /** One thread's record, or `null` for an id the store does not have. */\n async getThread(threadId: string): Promise<AgentThreadRecord | null> {\n return this.run(async (q) => {\n const [row] = (await q`\n SELECT ${this.recordColumns(q)} FROM ${this.threads(q)}\n WHERE id = ${threadId} AND ${this.inScope(q)} AND ${this.live(q)}\n `) as Row[];\n return row ? threadOf(row) : null;\n });\n }\n\n /**\n * The threads, most recently written first: all of them, or one user's\n * (`userId` as `createThread` was given it). For a \"your conversations\"\n * list; `limit` defaults to 50, and `offset` pages. A scoped view lists its\n * scope's threads only.\n */\n async listThreads(\n options: { userId?: string | number | null; limit?: number; offset?: number } = {},\n ): Promise<AgentThreadRecord[]> {\n const limit = Math.max(0, Math.floor(options.limit ?? 50));\n const offset = Math.max(0, Math.floor(options.offset ?? 0));\n return this.run(async (q) => {\n const where =\n options.userId === undefined\n ? q`1 = 1`\n : options.userId === null\n ? q`user_id IS NULL`\n : q`user_id = ${String(options.userId)}`;\n const rows: Row[] = await q`\n SELECT ${this.recordColumns(q)} FROM ${this.threads(q)}\n WHERE ${this.inScope(q)} AND ${this.live(q)} AND ${where}\n ORDER BY updated_at DESC, id DESC\n LIMIT ${limit} OFFSET ${offset}\n `;\n return rows.map(threadOf);\n });\n }\n\n /**\n * Deletes the thread, its messages and its summaries. An id the store does\n * not have is ignored. Agent memories scoped to the thread are not touched:\n * see `AgentMemories.deleteScope`.\n */\n async deleteThread(threadId: string): Promise<void> {\n await this.atomically(async (q) => {\n // The thread's scope is checked on the thread's row; its messages go\n // only once the row is known to be this view's.\n const thread: Row[] = await q`\n SELECT id FROM ${this.threads(q)} WHERE id = ${threadId} AND ${this.inScope(q)}\n `;\n if (thread.length === 0) return;\n await q`DELETE FROM ${this.messages(q)} WHERE thread_id = ${threadId}`;\n await q`DELETE FROM ${this.threads(q)} WHERE id = ${threadId}`;\n });\n }\n\n /**\n * Deletes up to `limit` (default 500) expired threads with their messages\n * and summaries (#1312), oldest expiry first. For a `CronJob` every few\n * minutes, next to `AgentController.sweepAttachments()`.\n *\n * A scoped view sweeps its scope only. `now` (epoch milliseconds) stands in\n * for the database's clock, for tests. A store without `ttlMs` has nothing\n * that expires, and answers `{ deleted: 0 }` without touching the table.\n * An expired thread is already unreadable before the sweep runs; the sweep\n * only reclaims its rows.\n */\n async sweepExpired(options: { now?: number; limit?: number } = {}): Promise<ThreadSweepResult> {\n if (!this.expires) {\n this.guard();\n return { deleted: 0 };\n }\n const limit = Math.max(0, Math.floor(options.limit ?? 500));\n if (limit === 0) return { deleted: 0 };\n return this.atomically(async (q) => {\n const cutoff = options.now === undefined ? this.clock(q) : this.ms(q, options.now);\n const expired = q`expires_at IS NOT NULL AND expires_at <= ${cutoff} AND ${this.inScope(q)}`;\n const candidates: Row[] = await q`\n SELECT id FROM ${this.threads(q)} WHERE ${expired}\n ORDER BY expires_at, id\n LIMIT ${limit}\n `;\n if (candidates.length === 0) return { deleted: 0 };\n const ids = candidates.map((row) => String(row.id));\n // Locks the rows (the database on SQLite), so an append that slides one\n // of them waits for the sweep. Then only the ones still expired go.\n await q`UPDATE ${this.threads(q)} SET updated_at = updated_at WHERE id IN (${list(q, ids)})`;\n const still: Row[] = await q`\n SELECT id FROM ${this.threads(q)} WHERE id IN (${list(q, ids)}) AND ${expired}\n `;\n if (still.length === 0) return { deleted: 0 };\n const gone = still.map((row) => String(row.id));\n await q`DELETE FROM ${this.messages(q)} WHERE thread_id IN (${list(q, gone)})`;\n await q`DELETE FROM ${this.threads(q)} WHERE id IN (${list(q, gone)})`;\n return { deleted: gone.length };\n });\n }\n\n // --- plumbing -------------------------------------------------------------\n\n /**\n * Runs `fn` in a transaction: a savepoint in the open ORM transaction when it\n * is on this store's connection, a transaction of its own otherwise.\n */\n private atomically<T>(fn: (q: SQL) => Promise<T>): Promise<T> {\n this.guard();\n if (this.joinable()) {\n return withTransaction(this.sql, (tx) => fn(tx as unknown as SQL), {\n connection: this.connection,\n dialect: this.dialect,\n });\n }\n const scope = this.scope;\n const beginScope = this.options.beginScope;\n const begin = () =>\n this.sql.begin(async (tx) => {\n if (scope !== null && beginScope) await beginScope(tx as unknown as SQL, scope);\n return fn(tx as unknown as SQL);\n }) as Promise<T>;\n if (this.dialect !== \"sqlite\") return begin();\n // One SQLite client is one connection, which holds one transaction at a\n // time: a second `begin` while the first is open fails with \"cannot start\n // a transaction within a transaction\". So its transactions take turns, in\n // the same queue as the ORM's on that connection (#1362). (Several\n // clients on one file wait on SQLite's own lock.)\n return queuedOnSqlite(this.sql, begin);\n }\n\n /** The open ORM transaction, when it is on this store's connection. */\n private joinable(): TransactionSQL | undefined {\n if (this.connection === undefined) return undefined;\n const tx = currentTransaction();\n if (tx === undefined || currentConnectionName() !== this.connection) return undefined;\n return tx;\n }\n\n /**\n * Runs one call's statements: in the open ORM transaction when there is one\n * on this connection, in a transaction of its own when a scoped view has\n * `beginScope` (so the hook's setting covers them), on the client otherwise.\n * The handle is read at each call and never kept: a stored transaction\n * handle outlives its transaction.\n */\n private run<T>(fn: (q: SQL) => Promise<T>): Promise<T> {\n this.guard();\n const tx = this.joinable() as SQL | undefined;\n if (tx) return fn(tx);\n if (this.scope !== null && this.options.beginScope) return this.atomically(fn);\n return fn(this.sql);\n }\n\n private guard() {\n if (this.scope === null && this.options.requireScope) {\n throw new Error(\n \"This DatabaseAgentStore requires a scope: call it through store.forScope(scope).\",\n );\n }\n }\n\n /** The scope condition: `1 = 1` on the unscoped store, which reads every row. */\n private inScope(q: SQL) {\n return this.scope === null ? q`1 = 1` : q`scope = ${this.scope}`;\n }\n\n /**\n * Not expired (#1312), by the database's clock. `1 = 1` on a store without\n * `ttlMs`, which never names the expiry columns.\n */\n private live(q: SQL) {\n return this.expires ? q`(expires_at IS NULL OR expires_at > ${this.clock(q)})` : q`1 = 1`;\n }\n\n /** The columns of an `AgentThreadRecord`. */\n private recordColumns(q: SQL) {\n return this.expires\n ? q.unsafe(\"id, user_id, title, created_at, updated_at, expires_at\")\n : q.unsafe(\"id, user_id, title, created_at, updated_at\");\n }\n\n /**\n * A new thread's expiry, or `null` on a store without `ttlMs`, which\n * refuses a thread's own.\n */\n private expiryOf(\n params: CreateThreadParams,\n ): { at?: number; ttlMs: number | null; slides: boolean } | null {\n const own = params.ttlMs !== undefined || params.expiresAt !== undefined;\n if (!this.expires) {\n if (own) {\n throw new Error(\n \"createThread({ ttlMs, expiresAt }) needs a store with `ttlMs`: set `new DatabaseAgentStore(connection, { ttlMs })`, which turns expiry on and reads the expiry columns.\",\n );\n }\n return null;\n }\n if (params.expiresAt !== undefined) {\n const at = params.expiresAt instanceof Date ? params.expiresAt.getTime() : params.expiresAt;\n if (!Number.isFinite(at)) throw new TypeError(\"createThread: `expiresAt` is not a valid time.\");\n return { at, ttlMs: null, slides: false };\n }\n const ttlMs = params.ttlMs === undefined ? this.options.ttlMs! : params.ttlMs;\n if (ttlMs !== null) positiveMs(ttlMs, \"createThread: ttlMs\");\n return { ttlMs, slides: this.options.slidingTtl === true };\n }\n\n\n private quote(name: string) {\n return this.dialect === \"mysql\" || this.dialect === \"mariadb\" ? `\\`${name}\\`` : `\"${name}\"`;\n }\n\n private threads(q: SQL) {\n return q.unsafe(this.quote(this.threadsTable));\n }\n\n private messages(q: SQL) {\n return q.unsafe(this.quote(this.messagesTable));\n }\n\n /** The database's clock, in epoch milliseconds. As in `DatabaseAgentJobStore`. */\n private clock(q: SQL) {\n switch (this.dialect) {\n case \"postgres\":\n return q`floor(extract(epoch from statement_timestamp()) * 1000)::bigint`;\n case \"mysql\":\n case \"mariadb\":\n return q`(TIMESTAMPDIFF(MICROSECOND, '1970-01-01 00:00:00', UTC_TIMESTAMP(6)) DIV 1000)`;\n case \"sqlite\":\n return q`CAST((julianday('now') - 2440587.5) * 86400000 AS INTEGER)`;\n }\n }\n\n private ms(q: SQL, value: number) {\n const ms = Math.max(0, Math.round(value));\n return this.dialect === \"mysql\" || this.dialect === \"mariadb\"\n ? q`CAST(${ms} AS SIGNED)`\n : q`CAST(${ms} AS BIGINT)`;\n }\n}\n\nfunction plainIdentifier(table: string, which: string): string {\n if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(table)) {\n throw new Error(\n `The agent ${which} table name \"${table}\" is not a plain identifier. Use letters, digits and underscores.`,\n );\n }\n return table;\n}\n\nfunction missingThread(threadId: string): Error {\n // As `MemoryAgentStore` says it: the controller checks before the run and\n // never reaches this; a store-level caller that does gets told.\n return new Error(`Thread ${threadId} does not exist here, or has been deleted.`);\n}\n\nfunction list(q: SQL, values: string[]) {\n return values.map((value) => q`${value}`).reduce((all, one) => q`${all}, ${one}`);\n}\n\nfunction titleOf(messages: AgentMessage[]): string | null {\n for (const message of messages) {\n // An event (#1181) is the server's, not what the person asked about.\n if (message.role !== \"user\" || message.event) continue;\n const text = message.content\n .map((part) => (part.type === \"text\" ? part.text : \"\"))\n .join(\" \")\n .replace(/\\s+/g, \" \")\n .trim();\n if (text) return text.length > TITLE_LENGTH ? `${text.slice(0, TITLE_LENGTH - 1)}…` : text;\n }\n return null;\n}\n\nfunction parseSummaries(value: unknown): ThreadSummary[] {\n if (value === null || value === undefined || value === \"\") return [];\n const parsed = JSON.parse(String(value));\n return Array.isArray(parsed) ? (parsed as ThreadSummary[]) : [];\n}\n\nfunction threadOf(row: Row): AgentThreadRecord {\n return {\n id: String(row.id),\n userId: row.user_id === null || row.user_id === undefined ? null : String(row.user_id),\n title: row.title === null || row.title === undefined ? null : String(row.title),\n createdAt: Number(row.created_at),\n updatedAt: Number(row.updated_at),\n ...(\"expires_at\" in row\n ? { expiresAt: row.expires_at === null || row.expires_at === undefined ? null : Number(row.expires_at) }\n : {}),\n };\n}\n\nfunction positiveMs(value: number, name: string) {\n if (typeof value !== \"number\" || !Number.isFinite(value) || value <= 0) {\n throw new TypeError(`${name} must be a positive number of milliseconds.`);\n }\n}\n\n/** Rows an `UPDATE` touched, across the three drivers. */\nfunction affected(result: unknown): number {\n const counts = result as { count?: number | null; affectedRows?: number | null };\n return Math.max(Number(counts.count ?? 0), Number(counts.affectedRows ?? 0));\n}\n\n/**\n * The tables as Prisma generates them for the models in the docs, with\n * `IF NOT EXISTS` added.\n */\nexport function createAgentStoreTableStatements(\n dialect: Dialect,\n threadsTable: string,\n messagesTable: string,\n): string[] {\n if (dialect === \"mysql\" || dialect === \"mariadb\") {\n return [\n `CREATE TABLE IF NOT EXISTS \\`${threadsTable}\\` (\n \\`id\\` VARCHAR(191) NOT NULL,\n \\`scope\\` VARCHAR(191) NULL,\n \\`user_id\\` VARCHAR(191) NULL,\n \\`title\\` TEXT NULL,\n \\`summaries\\` LONGTEXT NULL,\n \\`summary_lock\\` VARCHAR(191) NULL,\n \\`summary_lock_until\\` BIGINT NULL,\n \\`created_at\\` BIGINT NOT NULL,\n \\`updated_at\\` BIGINT NOT NULL,\n \\`expires_at\\` BIGINT NULL,\n \\`ttl_ms\\` BIGINT NULL,\n\n INDEX \\`${threadsTable}_user_id_updated_at_idx\\`(\\`user_id\\`, \\`updated_at\\`),\n INDEX \\`${threadsTable}_expires_at_idx\\`(\\`expires_at\\`),\n INDEX \\`${threadsTable}_scope_user_id_updated_at_idx\\`(\\`scope\\`, \\`user_id\\`, \\`updated_at\\`),\n PRIMARY KEY (\\`id\\`)\n) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,\n `CREATE TABLE IF NOT EXISTS \\`${messagesTable}\\` (\n \\`thread_id\\` VARCHAR(191) NOT NULL,\n \\`scope\\` VARCHAR(191) NULL,\n \\`id\\` VARCHAR(191) NOT NULL,\n \\`position\\` INTEGER NOT NULL,\n \\`message\\` LONGTEXT NOT NULL,\n \\`created_at\\` BIGINT NOT NULL,\n\n UNIQUE INDEX \\`${messagesTable}_thread_id_position_key\\`(\\`thread_id\\`, \\`position\\`),\n PRIMARY KEY (\\`thread_id\\`, \\`id\\`)\n) DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci`,\n ];\n }\n\n const threadsKey =\n dialect === \"sqlite\" ? `\"id\" TEXT NOT NULL PRIMARY KEY,` : `\"id\" TEXT NOT NULL,`;\n const threadsConstraint =\n dialect === \"sqlite\" ? \"\" : `,\\n\\n CONSTRAINT \"${threadsTable}_pkey\" PRIMARY KEY (\"id\")`;\n return [\n `CREATE TABLE IF NOT EXISTS \"${threadsTable}\" (\n ${threadsKey}\n \"scope\" TEXT,\n \"user_id\" TEXT,\n \"title\" TEXT,\n \"summaries\" TEXT,\n \"summary_lock\" TEXT,\n \"summary_lock_until\" BIGINT,\n \"created_at\" BIGINT NOT NULL,\n \"updated_at\" BIGINT NOT NULL,\n \"expires_at\" BIGINT,\n \"ttl_ms\" BIGINT${threadsConstraint}\n)`,\n `CREATE INDEX IF NOT EXISTS \"${threadsTable}_expires_at_idx\" ON \"${threadsTable}\"(\"expires_at\")`,\n `CREATE INDEX IF NOT EXISTS \"${threadsTable}_user_id_updated_at_idx\" ON \"${threadsTable}\"(\"user_id\", \"updated_at\")`,\n `CREATE INDEX IF NOT EXISTS \"${threadsTable}_scope_user_id_updated_at_idx\" ON \"${threadsTable}\"(\"scope\", \"user_id\", \"updated_at\")`,\n `CREATE TABLE IF NOT EXISTS \"${messagesTable}\" (\n \"thread_id\" TEXT NOT NULL,\n \"scope\" TEXT,\n \"id\" TEXT NOT NULL,\n \"position\" INTEGER NOT NULL,\n \"message\" TEXT NOT NULL,\n \"created_at\" BIGINT NOT NULL,\n\n CONSTRAINT \"${messagesTable}_pkey\" PRIMARY KEY (\"thread_id\", \"id\")\n)`,\n `CREATE UNIQUE INDEX IF NOT EXISTS \"${messagesTable}_thread_id_position_key\" ON \"${messagesTable}\"(\"thread_id\", \"position\")`,\n ];\n}\n\n/**\n * What brings tables created before scopes (#1177) up to date, per table: the\n * `scope` column, and on the threads table its index. Run only for a table\n * that does not have the column yet.\n */\nexport function addScopeColumnStatements(\n dialect: Dialect,\n threadsTable: string,\n messagesTable: string,\n): [table: string, statements: string[]][] {\n if (dialect === \"mysql\" || dialect === \"mariadb\") {\n return [\n [\n threadsTable,\n [\n `ALTER TABLE \\`${threadsTable}\\` ADD COLUMN \\`scope\\` VARCHAR(191) NULL, ADD INDEX \\`${threadsTable}_scope_user_id_updated_at_idx\\`(\\`scope\\`, \\`user_id\\`, \\`updated_at\\`)`,\n ],\n ],\n [messagesTable, [`ALTER TABLE \\`${messagesTable}\\` ADD COLUMN \\`scope\\` VARCHAR(191) NULL`]],\n ];\n }\n return [\n [\n threadsTable,\n [\n `ALTER TABLE \"${threadsTable}\" ADD COLUMN \"scope\" TEXT`,\n `CREATE INDEX IF NOT EXISTS \"${threadsTable}_scope_user_id_updated_at_idx\" ON \"${threadsTable}\"(\"scope\", \"user_id\", \"updated_at\")`,\n ],\n ],\n [messagesTable, [`ALTER TABLE \"${messagesTable}\" ADD COLUMN \"scope\" TEXT`]],\n ];\n}\n\n/**\n * What brings a threads table created before expiry (#1312) up to date: the\n * `expires_at` and `ttl_ms` columns and the `expires_at` index. Run only for a\n * table that does not have `expires_at` yet.\n */\nexport function addExpiryColumnStatements(dialect: Dialect, threadsTable: string): string[] {\n if (dialect === \"mysql\" || dialect === \"mariadb\") {\n return [\n `ALTER TABLE \\`${threadsTable}\\` ADD COLUMN \\`expires_at\\` BIGINT NULL, ADD COLUMN \\`ttl_ms\\` BIGINT NULL, ADD INDEX \\`${threadsTable}_expires_at_idx\\`(\\`expires_at\\`)`,\n ];\n }\n return [\n `ALTER TABLE \"${threadsTable}\" ADD COLUMN \"expires_at\" BIGINT`,\n `ALTER TABLE \"${threadsTable}\" ADD COLUMN \"ttl_ms\" BIGINT`,\n `CREATE INDEX IF NOT EXISTS \"${threadsTable}_expires_at_idx\" ON \"${threadsTable}\"(\"expires_at\")`,\n ];\n}\n",
|
|
22
22
|
"import type { AgentRun } from \"../Agent\";\nimport type { LiveRuns } from \"../AgentController\";\nimport type { AgentStreamEvent, AgentStreamFrame } from \"../types\";\n\n/** Long enough that a refresh, a tab restore or a flaky mobile connection still\n * lands on the tail; short enough that a finished run is not resident for the\n * rest of the day. */\nconst DEFAULT_TTL_MS = 60 * 1000;\n\n/**\n * The oldest an entry may get, ended or not, unless its run's own time limit is\n * longer. See `MemoryLiveRuns.maxAgeMs`.\n *\n * Six times the agent's default `maxRunDurationMs`, so it never races a\n * deadline: a run that honours its limit has ended and been evicted on the\n * `ttlMs` clock long before this. What reaches it is a run that could not be\n * stopped by its deadline, e.g. one wedged in an `onMessage` that never settles.\n */\nconst DEFAULT_MAX_AGE_MS = 60 * 60 * 1000;\n\n/** The longest delay `setTimeout` keeps; past it the runtime fires in ~1ms. */\nconst MAX_TIMER_MS = 2 ** 31 - 1;\n\n/**\n * How many frames are kept per run.\n *\n * The window has to be bounded or it is a memory leak with a long fuse: a\n * server that never restarts holding every token of every conversation it ever\n * streamed.\n *\n * It was 512 on the reasoning that a reattaching client only needs seconds of\n * catch-up. That is true of the *reattaching* client and false of the one that\n * never left: a frame is roughly a token, so 512 is a four-hundred-word answer,\n * and a reader that falls behind a longer one by more than that is cut off with\n * a 410 mid-stream. On a slow connection — the case reattachment exists for —\n * that is not exotic.\n *\n * 4096 covers essentially any single answer. It is affordable because of two\n * measured facts, and it would not have been before either:\n *\n * - `drain` no longer copies the window per wake, so a reader costs the same\n * whatever the window's size. Measured at 64 readers on a 2000-frame run:\n * 1106 ms of CPU at 4096 before, 425 ms after, and 468 ms at 512 — i.e. the\n * size stopped being a term in the cost.\n * - the entries are pointers to frames the run is holding anyway, so the\n * window costs 8 bytes each, not the frame. Eight times more of them is\n * ~28 KB per run, and a thousand concurrent runs is tens of megabytes.\n *\n * Both would change if the run's own buffer ever became bounded — then this\n * window owns the frames, and its size is their size.\n */\nconst DEFAULT_MAX_FRAMES = 4096;\n\n/**\n * A cursor older than anything still buffered.\n *\n * Deliberately an error rather than \"here is the tail I still have\". A client\n * that asked for frame 12 and silently got frame 300 onwards has a transcript\n * with a hole in it and no way to know — it will render a half-message, or an\n * `awaiting-input` for a tool call it never saw. Saying so lets the client do\n * the only correct thing, which is to reload the thread from the store.\n */\nexport class FrameCursorEvictedError extends Error {\n readonly code = \"frame_cursor_evicted\";\n\n constructor(\n readonly runId: string,\n readonly requested: number,\n readonly oldest: number,\n ) {\n super(\n `Frame ${requested} of run ${runId} has been evicted; the oldest frame ` +\n `still buffered is ${oldest}. Reload the thread instead of resuming.`,\n );\n }\n}\n\n/**\n * No run under that id in *this* process.\n *\n * Which is the honest answer, and the one worth being loud about: the run may\n * well be alive on the box next door. See the note on `MemoryLiveRuns` — behind\n * a round-robin load balancer this is what a refresh hits roughly (n-1)/n of\n * the time, and an explicit miss is the difference between a bug someone finds\n * in an hour and one that presents as \"reattach sometimes does nothing\".\n */\nexport class LiveRunNotFoundError extends Error {\n readonly code = \"live_run_not_found\";\n\n constructor(readonly runId: string) {\n super(`No live run ${runId} in this process.`);\n }\n}\n\nexport type RegisterParams = {\n threadId?: string;\n /**\n * Who started the run, as an opaque key (`AgentController.runOwner` makes it\n * `user:<id>`), or `null`/absent for a run nobody in particular owns: an\n * anonymous turn, or one the server started itself (#442).\n *\n * Recorded so `attach` and `stop` can tell the caller from the owner without a\n * store round trip: a `threadId`, a `runId` and a client-minted `clientRunId`\n * are all handles a third party can come to hold, and none of them says whose\n * run it is. An owned run answers only the same key; an unowned one answers\n * whoever holds a handle, which is what every run did before this existed.\n */\n owner?: string | null;\n /**\n * The client's own name for this run, minted before the run had one.\n *\n * `runId` does not reach the client until `run-start`, and a stateless first\n * turn has no `threadId` either, so for the length of a network round trip\n * plus the provider's time to first token there is nothing for `/stop` to\n * name — which is exactly the window a user cancels in. `useChat` sends a\n * `clientRunId` with every turn it starts; recording it here is what makes\n * that window stoppable.\n */\n clientRunId?: string;\n /**\n * Called once per frame, in order, off the buffering path.\n *\n * The controller's `on*` hooks hang off this. It is a callback rather than a\n * second `run.frames()` subscription because every extra subscriber is\n * another consumer of a generator whose multi-subscriber behaviour we do not\n * own, and one pump is one thing to reason about.\n */\n onEvent?: (event: AgentStreamEvent) => void | Promise<void>;\n /** Reported failures: a hook that threw, or a run whose frame iterator did.\n * Injectable so tests can assert on it instead of reading stderr. */\n onInternalError?: (error: unknown) => void;\n /**\n * The run's own time limit (`Agent.maxRunDurationMs`), when the caller knows\n * it. The entry's age ceiling is never shorter than this plus `ttlMs`, so a\n * run allowed two hours is not cut off at `maxAgeMs`; `null` is a run with no\n * limit, and its entry has no ceiling either. Omitted, the ceiling is\n * `maxAgeMs`.\n */\n maxRunDurationMs?: number | null;\n};\n\n/** One run going on a thread, as `MemoryLiveRuns.running` lists it. */\nexport type LiveRunInfo = {\n runId: string;\n /** The last frame emitted, as `find` answers it. */\n seq: number;\n /** When the run was registered, in epoch milliseconds. */\n startedAt: number;\n};\n\ntype Entry = {\n run: AgentRun;\n threadId?: string;\n /** `Date.now()` at `register`. */\n startedAt: number;\n /** See `RegisterParams.owner`. `null` is unowned. */\n owner: string | null;\n clientRunId?: string;\n /** A contiguous window of the run's frames, oldest first. */\n frames: AgentStreamFrame[];\n lastSeq: number;\n /**\n * The lowest `seq` still obtainable, or 0 while nothing has been dropped.\n *\n * Not derivable from `frames[0].seq`, which is what this used to compare\n * against. `seq` starts at 1, so a run that has evicted nothing still has an\n * oldest frame of 1, and a cursor of 0 — the \"I have no transcript yet\"\n * cursor that `replay` itself picks for a run registered but not yet pumped —\n * read as older than the buffer. A ten-frame run in a five-hundred-frame\n * window answered a refresh with 410, which is both false and unactionable:\n * refreshing right after sending is the case `/attach` exists to serve.\n */\n lostBefore: number;\n ended: boolean;\n /**\n * Dropped from the map while its run was still going (the age ceiling).\n * Readers finish on it as they would on `ended`, and the pump stops\n * buffering frames nobody can read any more.\n */\n evicted: boolean;\n evictAt: ReturnType<typeof setTimeout> | null;\n /** The age ceiling's timer. See `maxAgeMs`. */\n expireAt: ReturnType<typeof setTimeout> | null;\n wake: Set<() => void>;\n /**\n * Bumped on every push and on the end.\n *\n * A reader cannot just park on \"wake me when something happens\": it suspends\n * at every `yield` while its consumer reads, and anything that arrives during\n * that suspension notifies an empty waiter set — so the reader parks *after*\n * the event it was waiting for and never hears another. The version it read\n * before scanning is what closes that window: if it moved, there is more to\n * scan and the wait is skipped.\n */\n version: number;\n};\n\n/**\n * The runs currently in flight in this process, and their recent frames.\n *\n * PER-PROCESS IS NOT AN IMPLEMENTATION SHORTCUT THAT A BETTER STORE FIXES. A\n * running generator lives in one process, and a second server cannot attach to\n * it — no amount of Redis moves an in-flight async iterator across a socket.\n * Reattachment therefore needs the request to land where the run is: one\n * server, sticky routing, or a proxy that forwards by `runId`. Worth saying out\n * loud, because the failure mode behind a round-robin load balancer is a\n * refresh that usually works.\n *\n * `find` and `replay` are built so that failure is an explicit miss — a 404\n * naming the run, a 410 naming the cursor — and never an SSE stream that opens,\n * says nothing and closes. An empty stream is indistinguishable from a run that\n * finished quietly, which is exactly the confusion this is supposed to avoid.\n */\nexport class MemoryLiveRuns implements LiveRuns {\n ttlMs: number;\n readonly maxFrames: number;\n /**\n * The oldest an entry may get, counted from `register`, whether or not its\n * run has ended. Default one hour; `null` turns the ceiling off.\n *\n * Eviction normally runs on the `ttlMs` clock, which starts when the run\n * ends — so a run that never ends was never evicted, and its entry, its\n * frames and everything the run closes over stayed in the map for the life\n * of the process (#455). The agent's `maxRunDurationMs` is what ends such a\n * run now; this is the backstop for one that still does not end. When it\n * fires the run is stopped (a no-op for one that has ended) and the entry is\n * evicted `ttlMs` later, ended or not, so a reader attached to it gets the\n * stopped run's last frames and then a closed stream rather than a hang.\n *\n * Per entry it is never shorter than the run's own limit plus `ttlMs`, when\n * the registering caller passes one (`AgentController` does). Read at\n * `register`, so changing it affects runs registered afterwards.\n */\n maxAgeMs: number | null;\n\n private runs = new Map<string, Entry>();\n /** Thread to the most recently registered run for it. */\n private byThread = new Map<string, string>();\n /** Thread to every run registered for it and not yet evicted, oldest first. */\n private threadRuns = new Map<string, Set<string>>();\n /** The client's pre-`run-start` name for a run, to the run. */\n private byClientRun = new Map<string, string>();\n\n constructor(params: { ttlMs?: number; maxFrames?: number; maxAgeMs?: number | null } = {}) {\n this.ttlMs = params.ttlMs ?? DEFAULT_TTL_MS;\n this.maxFrames = params.maxFrames ?? DEFAULT_MAX_FRAMES;\n this.maxAgeMs = params.maxAgeMs === undefined ? DEFAULT_MAX_AGE_MS : params.maxAgeMs;\n }\n\n /**\n * Takes ownership of a run: starts buffering its frames and holds it until\n * `ttlMs` past the end.\n *\n * Settles once the run's last frame has been buffered and every `onEvent` it\n * led to has settled, and never rejects. The hooks run on a chain of their\n * own (see `pump`), so a frame's hook can be called well after the frame\n * arrived — after the run, too — and whoever needs to wait for the app's\n * code has only this to wait on: by the time a hook is called it is too late\n * to start waiting for it.\n */\n register(run: AgentRun, params: RegisterParams = {}): Promise<void> {\n const entry: Entry = {\n run: run as AgentRun,\n threadId: params.threadId,\n startedAt: Date.now(),\n owner: params.owner ?? null,\n clientRunId: params.clientRunId,\n frames: [],\n lastSeq: -1,\n lostBefore: 0,\n ended: false,\n evicted: false,\n evictAt: null,\n expireAt: null,\n wake: new Set(),\n version: 0,\n };\n this.runs.set(run.runId, entry);\n if (params.threadId) {\n this.byThread.set(params.threadId, run.runId);\n let runs = this.threadRuns.get(params.threadId);\n if (!runs) {\n runs = new Set();\n this.threadRuns.set(params.threadId, runs);\n }\n runs.add(run.runId);\n }\n if (params.clientRunId) {\n this.byClientRun.set(params.clientRunId, run.runId);\n }\n this.scheduleExpiry(entry, params.maxRunDurationMs);\n return this.pump(entry, params);\n }\n\n /**\n * The run a client named before the server had named it.\n *\n * Deliberately not folded into `find`, whose parameter is part of the\n * read-side `LiveRuns` interface an app may already implement — widening that\n * parameter would break every such implementation, and this lookup is only\n * ever asked by `/stop`.\n */\n findByClientRunId(clientRunId: string): string | null {\n const runId = this.byClientRun.get(clientRunId);\n return runId && this.runs.has(runId) ? runId : null;\n }\n\n /** What the client asks after a refresh: is anything still going here? */\n async find(params: { threadId: string }): Promise<{ runId: string; seq: number } | null> {\n const runId = this.byThread.get(params.threadId);\n if (!runId) {\n return null;\n }\n const entry = this.runs.get(runId);\n if (!entry) {\n return null;\n }\n // `seq` is the last frame emitted, not the next one: it is the same number\n // the transport puts in `Last-Event-ID`, so a client can compare the two\n // without knowing which end of the range each one means.\n return { runId, seq: entry.lastSeq };\n }\n\n /**\n * Every run still going on the thread in this process, oldest first: more\n * than one when turns run in parallel (`ifBusy: \"parallel\"`). A run that has\n * ended is not listed, though `find` and `get` still answer for it for\n * `ttlMs`.\n */\n running(params: { threadId: string }): LiveRunInfo[] {\n const out: LiveRunInfo[] = [];\n for (const runId of this.threadRuns.get(params.threadId) ?? []) {\n const entry = this.runs.get(runId);\n if (!entry || entry.ended || entry.evicted) continue;\n out.push({ runId, seq: entry.lastSeq, startedAt: entry.startedAt });\n }\n return out;\n }\n\n /** The thread a run held here was registered for, if any. */\n threadOf(runId: string): string | undefined {\n return this.runs.get(runId)?.threadId;\n }\n\n get(runId: string): AgentRun | null {\n return this.runs.get(runId)?.run ?? null;\n }\n\n /** Who started the run (see `RegisterParams.owner`); `null` for an unowned\n * run and for one this process does not hold. */\n ownerOf(runId: string): string | null {\n return this.runs.get(runId)?.owner ?? null;\n }\n\n /**\n * Whether `caller` may read or stop the run: an unowned run (and one this\n * process does not hold) answers anyone, an owned one only its owner. A\n * caller with no key (`null`, an anonymous request) is not the owner of\n * anything.\n */\n mayAccess(runId: string, caller: string | null): boolean {\n const owner = this.ownerOf(runId);\n return owner === null || owner === caller;\n }\n\n /** Whether the run is still going, as opposed to ended and kept for `ttlMs`,\n * or not here at all. */\n isRunning(runId: string): boolean {\n const entry = this.runs.get(runId);\n return !!entry && !entry.ended && !entry.evicted;\n }\n\n /**\n * The buffered frames from `from` onwards, followed by live ones until the\n * run ends.\n *\n * Throws before returning anything, so an evicted cursor and an unknown run\n * are still HTTP statuses rather than events on a stream that already\n * committed to a 200.\n *\n * `from` omitted means \"start wherever you still can\", not \"start at 0\".\n * These are genuinely different requests: a client that names a cursor is\n * telling us where its transcript ends, and handing it a later frame leaves\n * an invisible hole — that is the 410. A client with no cursor at all — the\n * browser reattaching on mount, which is the case `/attach` exists for — has\n * no transcript to put a hole in, and refusing it the tail because the run is\n * older than the buffer would 410 every run past `maxFrames`, i.e. every run\n * long enough to be worth reattaching to.\n */\n replay(runId: string, from?: number): AsyncIterable<AgentStreamFrame> {\n const entry = this.runs.get(runId);\n if (!entry) {\n throw new LiveRunNotFoundError(runId);\n }\n if (from !== undefined && from < entry.lostBefore) {\n throw new FrameCursorEvictedError(runId, from, entry.lostBefore);\n }\n const oldest = entry.frames[0]?.seq;\n // With nothing buffered — a run registered but not yet pumped — `lastSeq`\n // is -1 and this is 0, which is the same answer by another route.\n return this.drain(entry, runId, from ?? oldest ?? entry.lastSeq + 1);\n }\n\n /** Test seam: drops everything and cancels the pending eviction timers. */\n clear(): void {\n for (const entry of this.runs.values()) {\n if (entry.evictAt) {\n clearTimeout(entry.evictAt);\n }\n if (entry.expireAt) {\n clearTimeout(entry.expireAt);\n }\n // Marked ended before waking: a reader parked on `wait` would otherwise\n // come back, find the entry unfinished, and park again forever.\n entry.ended = true;\n this.notify(entry);\n }\n this.runs.clear();\n this.byThread.clear();\n this.threadRuns.clear();\n this.byClientRun.clear();\n }\n\n get size(): number {\n return this.runs.size;\n }\n\n private async pump(entry: Entry, params: RegisterParams): Promise<void> {\n // Hooks run on their own chain: they stay in order relative to each other,\n // and a slow one never stalls the buffer a reattaching client reads from.\n let hooks = Promise.resolve();\n try {\n for await (const frame of entry.run.frames()) {\n // Evicted by the age ceiling with the run still going: nobody can\n // reach this entry any more, so its frames are not kept. The hooks\n // below still hear them — they are the app's, and the run is not over.\n if (entry.evicted) {\n const onEvent = params.onEvent;\n if (onEvent) {\n hooks = hooks.then(() => onEvent(frame.event)).catch((err) => report(params, err));\n }\n continue;\n }\n entry.frames.push(frame);\n entry.lastSeq = frame.seq;\n if (entry.frames.length > this.maxFrames) {\n const dropped = entry.frames.shift();\n if (dropped) entry.lostBefore = dropped.seq + 1;\n }\n this.notify(entry);\n const onEvent = params.onEvent;\n if (onEvent) {\n hooks = hooks.then(() => onEvent(frame.event)).catch((err) => report(params, err));\n }\n }\n } catch (err) {\n // The run's own iterator failed. There is nothing left to replay, so the\n // entry ends here; whoever is attached sees the stream close.\n report(params, err);\n } finally {\n entry.ended = true;\n if (entry.expireAt) {\n clearTimeout(entry.expireAt);\n entry.expireAt = null;\n }\n this.notify(entry);\n // Eviction is scheduled off the ttl clock, BEFORE the hook chain is\n // awaited. `hooks` is app code — `onAwaitingInput` is documented as the\n // place to notify an approver, i.e. network I/O — and a `fetch` with no\n // timeout never rejects, it just never settles. Awaiting it first made\n // retention conditional on app code: one hanging hook pinned its entry,\n // its 512 frames, the run and everything the run closes over in the map\n // for the life of the process, and `find` kept answering with a run that\n // ended hours ago. Retention is this class's job and belongs on its own\n // clock. A hook still pending when the timer fires simply outlives the\n // entry, which is fine — it holds no reference the map needed.\n this.scheduleEviction(entry);\n await hooks;\n }\n }\n\n private async *drain(\n entry: Entry,\n runId: string,\n from: number,\n ): AsyncGenerator<AgentStreamFrame, void, void> {\n let cursor = from;\n while (true) {\n const seen = entry.version;\n // The window is contiguous and ordered, so a reader's position in it is\n // arithmetic, not a search. This used to copy the whole window on every\n // wake and scan it for frames past the cursor, which is O(window) per\n // frame per reader — invisible at a 512-frame cap and the reason the cap\n // could not be raised. Indexing makes the window's size stop mattering.\n for (;;) {\n if (cursor < entry.lostBefore) {\n // The window rolled past this reader mid-stream. Same reasoning as\n // the pre-flight check: a gap the client cannot see is worse than a\n // stream that stops and says why. Re-checked inside the loop rather\n // than once per wake, because a yield suspends this reader for as\n // long as its consumer takes and the pump keeps running.\n throw new FrameCursorEvictedError(runId, cursor, entry.lostBefore);\n }\n const frames = entry.frames;\n const oldest = frames[0]?.seq;\n if (oldest === undefined) {\n break;\n }\n // Clamped rather than treated as a gap: a cursor below the first seq\n // that ever existed is \"from the beginning\", not a lost position.\n const index = Math.max(0, cursor - oldest);\n if (index >= frames.length) {\n break;\n }\n const frame = frames[index]!;\n yield frame;\n cursor = frame.seq + 1;\n }\n if ((entry.ended && cursor > entry.lastSeq) || entry.evicted) {\n return;\n }\n await this.wait(entry, seen);\n }\n }\n\n private wait(entry: Entry, seen: number): Promise<void> {\n if (entry.version !== seen) {\n return Promise.resolve();\n }\n return new Promise<void>((resolve) => entry.wake.add(resolve));\n }\n\n private notify(entry: Entry): void {\n entry.version++;\n const waiters = Array.from(entry.wake);\n entry.wake.clear();\n for (const resolve of waiters) {\n resolve();\n }\n }\n\n private scheduleEviction(entry: Entry): void {\n if (entry.evictAt) {\n return;\n }\n const timer = setTimeout(() => {\n const runId = entry.run.runId;\n if (!entry.ended) {\n // The age ceiling, with the run still going. Its frames are released\n // here because the pump of a run that has not ended still holds the\n // entry, and readers are told to finish (see `drain`), since `ended`\n // may never come. An ended entry keeps both: a reader still behind on\n // it finishes the tail it was reading, as it always has.\n entry.evicted = true;\n entry.frames = [];\n }\n if (this.runs.get(runId) === entry) this.runs.delete(runId);\n if (entry.threadId && this.byThread.get(entry.threadId) === runId) {\n this.byThread.delete(entry.threadId);\n }\n if (entry.threadId) {\n const runs = this.threadRuns.get(entry.threadId);\n runs?.delete(runId);\n if (runs?.size === 0) this.threadRuns.delete(entry.threadId);\n }\n if (entry.clientRunId && this.byClientRun.get(entry.clientRunId) === runId) {\n this.byClientRun.delete(entry.clientRunId);\n }\n // Anyone still draining is holding an ended entry; wake them so they see\n // `ended` and finish rather than hanging on a promise nothing resolves.\n this.notify(entry);\n }, this.ttlMs);\n // A finished run must not be the reason a process stays up.\n (timer as { unref?: () => void }).unref?.();\n entry.evictAt = timer;\n }\n\n /**\n * The age ceiling: stops the run and starts the `ttlMs` eviction clock at\n * `maxAgeMs` after `register`, whether or not the run has ended. See\n * `maxAgeMs`.\n */\n private scheduleExpiry(entry: Entry, runLimit: number | null | undefined): void {\n if (this.maxAgeMs === null || runLimit === null) return;\n const ceiling =\n runLimit === undefined ? this.maxAgeMs : Math.max(this.maxAgeMs, runLimit + this.ttlMs);\n if (!Number.isFinite(ceiling) || ceiling > MAX_TIMER_MS) return;\n const timer = setTimeout(() => {\n entry.expireAt = null;\n if (entry.ended) return;\n try {\n entry.run.stop({\n reason: `The run was still going ${Math.round(ceiling / 1000)}s after it started, past the live-run registry's age limit.`,\n });\n } catch {\n // A run whose `stop` throws is evicted all the same.\n }\n this.scheduleEviction(entry);\n }, ceiling);\n // Like the eviction timer: never the reason a process stays up.\n (timer as { unref?: () => void }).unref?.();\n entry.expireAt = timer;\n }\n}\n\n/**\n * The process-wide default, shared by every `AgentController` that does not\n * bring its own. One map per process is the whole point — see the class note.\n */\nexport const liveRuns = new MemoryLiveRuns();\n\n/**\n * Hands `err` to `onInternalError`, which is app code too: one that throws is\n * dropped rather than rejecting the hook chain, and with it `register`'s\n * promise, which says it never rejects.\n */\nfunction report(params: RegisterParams, err: unknown): void {\n try {\n params.onInternalError?.(err);\n } catch {\n // Nothing is left to tell.\n }\n}\n",
|
|
23
23
|
"/**\n * WHO UPLOADED A PROVIDER FILE (#443).\n *\n * A provider's file id (`file-…`) is scoped to the OpenAI/Azure org, not to\n * any user of the app: the vendor will hand the document to whichever request\n * names it. So an id is a bearer token for the file, and ids leak — a shared\n * transcript, a log line, a browser history entry. Before this, a user who\n * learned another user's id could put it in their own `turn.files` and have\n * the model read the other user's document.\n *\n * `AgentController.upload` now records the id with the uploader's owner key\n * (the same `runOwner(req)` that owns a run, #442), and `stream` refuses a\n * turn naming an id recorded for anyone else with a 403.\n *\n * A record is `{ owner, name, mimeType, size, createdAt }`, keyed by the\n * provider's id. `owner: null` is an anonymous upload and is unowned: it\n * answers whoever holds the id, exactly as every id did before this existed.\n */\nexport type FileOwnerRecord = {\n /** `runOwner(req)` at upload: `user:<id>` by default, `null` for anonymous. */\n owner: string | null;\n name?: string;\n mimeType?: string;\n size?: number;\n createdAt: string;\n /**\n * For a short-lived upload that went to the provider alone (#1307): when\n * `AgentController.sweepAttachments` deletes the provider's file. An upload\n * gemi also stored carries this on its attachment record instead.\n */\n expiresAt?: string;\n /** Deleted once the turn that names it has completed. See `Attachment.deleteAfterTurn`. */\n deleteAfterTurn?: boolean;\n};\n\n/**\n * Where the records live. Two methods so an app can put them in its own table:\n *\n * class DbFileOwners implements FileOwners {\n * async record(fileId, record) { await db.agentFile.create({ data: { fileId, ...record } }) }\n * async get(fileId) { return db.agentFile.findUnique({ where: { fileId } }) }\n * }\n *\n * `get` answers `null` for an id it has no record of. What the controller does\n * with that is `AgentController.requireKnownFiles`.\n */\nexport interface FileOwners {\n record(fileId: string, record: FileOwnerRecord): Promise<void>;\n get(fileId: string): Promise<FileOwnerRecord | null>;\n /** Forgets an id whose file was deleted (#1307). Optional. */\n delete?(fileId: string): Promise<void>;\n /**\n * Up to `limit` ids whose record's `expiresAt` is at or before `now` (#1307).\n * Optional; without it `sweepAttachments` cannot find short-lived\n * provider-only uploads that no turn deleted.\n */\n expired?(now: Date, limit: number): Promise<string[]>;\n}\n\n/**\n * The default: records last as long as the process, like `MemoryAgentStore`\n * and `MemoryAttachmentStore`. Bounded, oldest first, so an upload loop cannot\n * grow it without end; an evicted id reads as unknown.\n *\n * A record is never overwritten: the first owner of an id keeps it, so a\n * second `record` for the same id (which a provider never mints, but a buggy\n * or hostile override could forward) cannot move a file to another user.\n */\nexport class MemoryFileOwners implements FileOwners {\n private readonly records = new Map<string, FileOwnerRecord>();\n\n constructor(private readonly maxEntries = 100_000) {}\n\n async record(fileId: string, record: FileOwnerRecord): Promise<void> {\n if (this.records.has(fileId)) return;\n this.records.set(fileId, { ...record });\n while (this.records.size > this.maxEntries) {\n const oldest = this.records.keys().next().value;\n if (oldest === undefined) break;\n this.records.delete(oldest);\n }\n }\n\n async get(fileId: string): Promise<FileOwnerRecord | null> {\n const record = this.records.get(fileId);\n return record ? { ...record } : null;\n }\n\n async delete(fileId: string): Promise<void> {\n this.records.delete(fileId);\n }\n\n async expired(now: Date, limit: number): Promise<string[]> {\n const found: string[] = [];\n for (const [fileId, record] of this.records) {\n if (found.length >= limit) break;\n if (record.expiresAt && Date.parse(record.expiresAt) <= now.getTime()) found.push(fileId);\n }\n return found;\n }\n}\n\nexport const defaultFileOwners = new MemoryFileOwners();\n",
|
|
24
24
|
"import { app } from \"../../foundation/app\";\nimport { RedisManager } from \"../../services/redis/RedisManager\";\nimport type { ToolResultPart } from \"../types\";\n\n/**\n * EXECUTION RECEIPTS: what makes an approved tool run at most once (#458).\n *\n * A pending call's signature stops an approval being forged, and its spent\n * nonce (`NonceStore`, #445) stops it being *accepted* twice. Neither records\n * what the approved tool did. So a retried submit whose response was lost, a\n * proxy retry, or an answer that reaches two instances whose nonce stores are\n * not shared, either runs `execute` again for a tool that already charged a\n * card, or is refused and the user is told their approval was not used when\n * it was.\n *\n * A receipt store closes that. Before an approved tool runs, the run claims a\n * deterministic execution id (an HMAC, under its own HKDF-derived key, of the\n * call the signature covers: issuing run, tool call id, tool name, canonical\n * input, nesting path and subject). The claim answers one of three things:\n *\n * claimed — nobody has run it: run it, then `complete` with its result.\n * replay — it already ran: the stored result is returned as the call's\n * result, and the tool is not run.\n * blocked — a claim is held but no result recorded: another instance is\n * running it right now, or the process that was running it died.\n * The call gets a `tool_error` result the model can read, and the\n * tool is not run. Not knowing whether a side effect happened is\n * exactly the case where running it again is wrong.\n *\n * Opt-in: `AgentController.receipts` (or `receipts` on `Agent.stream`). Without\n * a store an approved tool runs exactly as before.\n *\n * Implementations:\n *\n * MemoryReceiptStore — one process, lost on restart.\n * RedisReceiptStore — on the app's Redis; shared and atomic.\n * your own — e.g. a table keyed by the execution id:\n *\n * CREATE TABLE agent_tool_receipts (\n * id text PRIMARY KEY,\n * result jsonb, -- NULL while the call is running\n * expires_at timestamptz NOT NULL\n * );\n *\n * class DbReceiptStore implements ReceiptStore {\n * async claim(id, expiresAt) {\n * const inserted = await db.$executeRaw`\n * INSERT INTO agent_tool_receipts (id, expires_at)\n * VALUES (${id}, ${new Date(expiresAt)})\n * ON CONFLICT (id) DO NOTHING`;\n * if (inserted === 1) return { status: \"claimed\" };\n * const [row] = await db.$queryRaw`\n * SELECT result FROM agent_tool_receipts WHERE id = ${id}`;\n * return row?.result ? { status: \"replay\", result: row.result } : { status: \"blocked\" };\n * }\n * async complete(id, result) {\n * await db.$executeRaw`\n * UPDATE agent_tool_receipts SET result = ${result} WHERE id = ${id}`;\n * }\n * async release(id) {\n * await db.$executeRaw`\n * DELETE FROM agent_tool_receipts WHERE id = ${id} AND result IS NULL`;\n * }\n * }\n * // and, from a cron: DELETE FROM agent_tool_receipts WHERE expires_at < now()\n *\n * A receipt only has to outlive the token it answers: past `expiresAt` the\n * signature fails verification on its own, so the call cannot be presented\n * again and the receipt may be dropped.\n */\nexport interface ReceiptStore {\n /**\n * Claims `executionId` until `expiresAt` (epoch milliseconds), if nobody has.\n * Must be atomic across every process sharing the store: two concurrent\n * claims never both answer `claimed`.\n *\n * A rejection refuses the answer, as a `NonceStore` that throws does: an\n * idempotency guard that runs the tool anyway when its store is down is not\n * a guard.\n */\n claim(executionId: string, expiresAt: number): Promise<ReceiptClaim>;\n /**\n * Records the result of a claimed execution, kept until `expiresAt`. Called\n * once the tool's result is known, which may be after the run that claimed\n * it was stopped. A rejection is logged; the claim then stays held, so a\n * replay is `blocked` rather than run again.\n */\n complete(executionId: string, result: ToolResultPart, expiresAt: number): Promise<void>;\n /**\n * Drops a claim that never ran: the answer was refused after it was claimed\n * (its nonce was already spent). A recorded result is never released.\n */\n release(executionId: string): Promise<void>;\n}\n\nexport type ReceiptClaim =\n | { status: \"claimed\" }\n | { status: \"replay\"; result: ToolResultPart }\n | { status: \"blocked\" };\n\ntype MemoryReceipt = { result?: ToolResultPart; expiresAt: number };\n\n/**\n * The in-process store. Holds each receipt until its token expires, swept\n * amortized O(1) per claim. Results are copied in and out, so a caller that\n * edits the part it was handed cannot change what a replay returns.\n */\nexport class MemoryReceiptStore implements ReceiptStore {\n private readonly receipts = new Map<string, MemoryReceipt>();\n private sweepAt = 1024;\n /** Injectable for tests. */\n constructor(private readonly now: () => number = Date.now) {}\n\n async claim(executionId: string, expiresAt: number): Promise<ReceiptClaim> {\n const now = this.now();\n if (this.receipts.size >= this.sweepAt) this.sweep(now);\n const existing = this.receipts.get(executionId);\n if (existing && existing.expiresAt > now) {\n return existing.result\n ? { status: \"replay\", result: structuredClone(existing.result) }\n : { status: \"blocked\" };\n }\n this.receipts.set(executionId, { expiresAt });\n return { status: \"claimed\" };\n }\n\n async complete(executionId: string, result: ToolResultPart, expiresAt: number): Promise<void> {\n this.receipts.set(executionId, { result: structuredClone(result), expiresAt });\n }\n\n async release(executionId: string): Promise<void> {\n const existing = this.receipts.get(executionId);\n if (existing && !existing.result) this.receipts.delete(executionId);\n }\n\n get size(): number {\n return this.receipts.size;\n }\n\n private sweep(now: number) {\n for (const [id, receipt] of this.receipts) {\n if (receipt.expiresAt <= now) this.receipts.delete(id);\n }\n this.sweepAt = Math.max(1024, this.receipts.size * 2);\n }\n}\n\n/** The slice of Bun's `RedisClient` this store needs: `send(command, args)`. */\nexport interface ReceiptRedisClient {\n send(command: string, args: string[]): Promise<any>;\n}\n\nexport interface RedisReceiptStoreOptions {\n /**\n * Client to run against. Defaults to the app's shared client from\n * `RedisServiceProvider`, resolved on first use.\n */\n client?: ReceiptRedisClient;\n /** Key namespace. Defaults to `gemi:ai:receipt`. */\n prefix?: string;\n}\n\nconst PENDING = \"pending\";\nconst DONE = \"done:\";\n\n/** `SET NX`, and on a miss the value that was there, in one round trip. */\nconst CLAIM_SCRIPT = `\nif redis.call('SET', KEYS[1], ARGV[1], 'PX', ARGV[2], 'NX') then return 'claimed' end\nlocal held = redis.call('GET', KEYS[1])\nif not held then return ARGV[1] end\nreturn held`;\n\n/** Deletes the key only while it is an unfinished claim. */\nconst RELEASE_SCRIPT = `\nif redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end\nreturn 0`;\n\n/**\n * Receipts in Redis, shared by every instance of the app. A claim is a\n * `SET ... NX` run in a script with the read that follows a miss, so claiming\n * is atomic; `PX` drops each key at the token's expiry.\n *\n * ```ts\n * const receipts = new RedisReceiptStore();\n *\n * class ChatController extends AgentController<typeof chat> {\n * agent = chat;\n * receipts = receipts;\n * }\n * ```\n */\nexport class RedisReceiptStore implements ReceiptStore {\n private readonly injectedClient?: ReceiptRedisClient;\n private readonly prefix: string;\n\n constructor(options: RedisReceiptStoreOptions = {}) {\n this.injectedClient = options.client;\n this.prefix = options.prefix ?? \"gemi:ai:receipt\";\n }\n\n async claim(executionId: string, expiresAt: number): Promise<ReceiptClaim> {\n const reply = await this.client.send(\"EVAL\", [\n CLAIM_SCRIPT,\n \"1\",\n this.key(executionId),\n PENDING,\n ttl(expiresAt),\n ]);\n // Anything else the script did not return (a client that maps an odd\n // reply to `null`, say) is `blocked`: never a reason to run the tool.\n if (reply === \"claimed\") return { status: \"claimed\" };\n const held = String(reply ?? \"\");\n if (held.startsWith(DONE)) {\n return { status: \"replay\", result: JSON.parse(held.slice(DONE.length)) as ToolResultPart };\n }\n return { status: \"blocked\" };\n }\n\n async complete(executionId: string, result: ToolResultPart, expiresAt: number): Promise<void> {\n await this.client.send(\"SET\", [\n this.key(executionId),\n DONE + JSON.stringify(result),\n \"PX\",\n ttl(expiresAt),\n ]);\n }\n\n async release(executionId: string): Promise<void> {\n await this.client.send(\"EVAL\", [RELEASE_SCRIPT, \"1\", this.key(executionId), PENDING]);\n }\n\n private key(executionId: string) {\n return `${this.prefix}:${executionId}`;\n }\n\n private get client(): ReceiptRedisClient {\n if (this.injectedClient) return this.injectedClient;\n const container = app();\n const client = container.bound(RedisManager) ? container.make(RedisManager).client : undefined;\n if (!client) {\n throw new Error(\n \"RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).\",\n );\n }\n return client;\n }\n}\n\n/** At least 1ms: `PX 0` is an error. */\nfunction ttl(expiresAt: number): string {\n return String(Math.max(1, Math.ceil(expiresAt - Date.now())));\n}\n",
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
"import type { Schema } from \"../Schema\";\nimport type { AgentJobRef, AgentMessage, ToolResultPart } from \"../types\";\nimport { clockOf, expire } from \"./AgentJob\";\nimport {\n type AgentJobRecord,\n type AgentJobState,\n type AgentJobStore,\n isSettled,\n} from \"./AgentJobStore\";\n\n/** How many of a thread's newest jobs are checked for orphans on each load. */\nconst ORPHAN_SCAN = 50;\n\nconst ANY_STATE: AgentJobState[] = [\"waiting\", \"running\", \"ok\", \"error\"];\n\n/**\n * The thread with each background job's current state rendered over the tool\n * result that points at it (#461).\n *\n * A tool that returned a `JobHandle` left a `running` result in the thread.\n * The job settles later, into the job store, and never into the messages: a\n * live run writes whole messages, and a settle racing those writes would be\n * overwritten by the run's stale copy. So the messages are brought up to date\n * here, when the thread is loaded, which `AgentController` does under the\n * thread's lock before a turn and without writing for `readThread`.\n *\n * - A `running` result whose job settled becomes the job's `ok` or `error`\n * result, in place, with the job still named on it (`job`).\n * - A `running` result whose job is still running is left exactly as it is,\n * so the request stays byte-identical, and the prompt cache with it, until\n * the job settles.\n * - A `running` result whose job the store does not have becomes an `error`:\n * the record was lost (a memory store across a restart), and the work may or\n * may not have happened.\n *\n * `settled` is the messages that changed, for the caller to write back, so\n * the store converges and a job settled long ago costs nothing on later loads.\n *\n * `orphans` are jobs whose tool result never reached the thread: the run died\n * between starting the job and storing the result. They are found among the\n * thread's newest jobs, only once the run that started them is gone, and only\n * the ones not marked yet; the caller marks them (`orphaned`).\n */\nexport async function overlayJobs(\n messages: AgentMessage[],\n params: {\n threadId: string;\n store: AgentJobStore;\n isRunLive: (runId: string) => boolean | Promise<boolean>;\n /** The tool's output schema, to check a settled output against. */\n outputSchemaFor?: (toolName: string) => Schema<any> | undefined;\n /** The tool's `toModel` projection of a settled output (#1061). */\n modelOutputFor?: (toolName: string, output: unknown) => unknown;\n /** How many of the thread's newest jobs to read. At least 50. */\n scan?: number;\n },\n): Promise<{\n messages: AgentMessage[];\n settled: AgentMessage[];\n orphans: AgentJobRecord[];\n /** The thread's newest jobs, as they stand after this pass: for the `<jobs>` block. */\n jobs: AgentJobRecord[];\n}> {\n const { store, threadId } = params;\n const scan = Math.max(ORPHAN_SCAN, params.scan ?? 0);\n const recent = await store.listForThread(threadId, { limit: scan });\n\n // The lazy half of the deadline sweep: a running job past its deadline is\n // failed here, so an app with no cron still sees it fail.\n let now: number | undefined;\n const current = async (record: AgentJobRecord): Promise<AgentJobRecord> => {\n if (record.state !== \"running\") return record;\n now ??= await clockOf(store);\n if (record.deadlineAt > now) return record;\n await expire(store, record);\n return (await store.get(record.id)) ?? record;\n };\n for (let index = 0; index < recent.length; index++) {\n recent[index] = await current(recent[index]!);\n }\n const known = new Map(recent.map((record) => [record.id, record]));\n\n const out = messages.slice();\n const settled: AgentMessage[] = [];\n const calls = new Set<string>();\n\n for (let at = 0; at < out.length; at++) {\n const message = out[at]!;\n let content: AgentMessage[\"content\"] | null = null;\n for (let index = 0; index < message.content.length; index++) {\n const part = message.content[index]!;\n if (part.type === \"tool-call\") calls.add(part.toolCallId);\n if (part.type !== \"tool-result\" || part.status !== \"running\") continue;\n\n const id = part.job?.id;\n let record = id ? known.get(id) : undefined;\n if (id && record === undefined) {\n const found = await store.get(id);\n record = found ? await current(found) : undefined;\n if (record) known.set(id, record);\n }\n // Still waiting or running: the result stays `running`, byte for byte.\n if (record && !isSettled(record.state)) continue;\n\n content ??= message.content.slice();\n content[index] = settledResult(part, record, params.outputSchemaFor, params.modelOutputFor);\n }\n if (content) {\n const changed: AgentMessage = { ...message, content };\n out[at] = changed;\n settled.push(changed);\n }\n }\n\n const orphans: AgentJobRecord[] = [];\n for (const record of recent) {\n // A job started from server code (`AgentJobs.start`) settles no tool call.\n if (record.orphaned || record.toolCallId === \"\" || calls.has(record.toolCallId)) continue;\n if (await params.isRunLive(record.runId)) continue;\n orphans.push(record);\n }\n\n return { messages: out, settled, orphans, jobs: recent };\n}\n\n/** Marks orphans found by `overlayJobs`. Never throws: it is bookkeeping. */\nexport async function markOrphans(\n store: AgentJobStore,\n orphans: AgentJobRecord[],\n report: (error: unknown) => void,\n): Promise<void> {\n for (const record of orphans) {\n try {\n await store.transition(record.id, ANY_STATE, { orphaned: true });\n } catch (error) {\n report(error);\n }\n }\n}\n\nfunction settledResult(\n part: Extract<ToolResultPart, { status: \"running\" }>,\n record: AgentJobRecord | undefined,\n outputSchemaFor: ((toolName: string) => Schema<any> | undefined) | undefined,\n modelOutputFor?: (toolName: string, output: unknown) => unknown,\n): ToolResultPart {\n const base = { type: \"tool-result\" as const, toolCallId: part.toolCallId, name: part.name };\n const ok = (output: unknown, job: AgentJobRef): ToolResultPart => {\n const modelOutput = modelOutputFor?.(String(part.name), output);\n return {\n ...base,\n status: \"ok\",\n job,\n output,\n ...(modelOutput !== undefined ? { modelOutput } : {}),\n };\n };\n if (!record) {\n return {\n ...base,\n status: \"error\",\n job: part.job,\n error: {\n code: \"tool_error\",\n message: `The background job for \"${String(part.name)}\" can no longer be found, so its result was lost. It may have run in part or in full: check its effects before repeating it.`,\n toolCallId: part.toolCallId,\n retryable: true,\n },\n };\n }\n\n const job: AgentJobRef = {\n id: record.id,\n ...(record.summary !== undefined ? { summary: record.summary } : {}),\n ...(record.usage ? { usage: record.usage } : {}),\n };\n if (record.state === \"error\") {\n return {\n ...base,\n status: \"error\",\n job,\n error: record.error ?? {\n code: \"tool_error\",\n message: `The background job for \"${String(part.name)}\" failed.`,\n toolCallId: part.toolCallId,\n retryable: true,\n },\n };\n }\n\n const schema = outputSchemaFor?.(String(part.name));\n if (schema) {\n const parsed = schema.safeParse(record.output);\n if (parsed.ok === false) {\n return {\n ...base,\n status: \"error\",\n job,\n error: {\n code: \"invalid_tool_result\",\n message: `The background job for \"${String(part.name)}\" finished with an output that does not match the tool's output schema: ${parsed.errors.join(\", \")}`,\n toolCallId: part.toolCallId,\n retryable: true,\n },\n };\n }\n return ok(parsed.value, job);\n }\n return ok(record.output, job);\n}\n",
|
|
30
30
|
"import { Storage } from \"../facades/Storage\";\nimport { Controller } from \"../http/Controller\";\nimport { refusal, RequestBreakerError } from \"../http/Error\";\nimport { HttpRequest } from \"../http/HttpRequest\";\nimport { RequestContext } from \"../http/requestContext\";\nimport { mediaType } from \"../http/mediaType\";\nimport { refusalKindForStatus } from \"../http/refusal\";\nimport type { MiddlewareInput } from \"../http/middlewareList\";\nimport type { AgentResource } from \"../http/ResourcePolicy\";\nimport type {\n AgentContext,\n AgentProviderRetry,\n AgentRun,\n AgentRunFailure,\n AgentRunResult,\n AgentToolShapes,\n AnyAgent,\n ContextOf,\n PrepareStepContext,\n AgentJoinTurn,\n AgentRunJoin,\n AgentRunTurn,\n PrepareStepResult,\n ReasoningEffort,\n SkillDefinition,\n ToolEntry,\n ToolShapesOf,\n} from \"./Agent\";\nimport type { ContextWindowOptions } from \"./contextWindow\";\nimport { modelOutputOf } from \"./toolModelOutput\";\nimport { isSummaryStore, type ThreadSummary } from \"./contextCompaction\";\nimport { injectedMessageIds, toolCallInputOf, userTurnMessage } from \"./Agent\";\nimport {\n type Attachment,\n ATTACHMENT_ID_PREFIX,\n type AttachmentDestination,\n attachmentLifetime,\n attachmentObjectName,\n type AttachmentRetention,\n type AttachmentScope,\n type AttachmentStorage,\n type AttachmentStore,\n defaultAttachmentStore,\n deleteAttachment,\n newAttachmentId,\n ScopedAttachments,\n} from \"./store/Attachments\";\nimport {\n FrameCursorEvictedError,\n liveRuns as defaultLiveRuns,\n type LiveRunInfo,\n LiveRunNotFoundError,\n MemoryLiveRuns,\n} from \"./store/LiveRuns\";\nimport {\n defaultFileOwners,\n type FileOwnerRecord,\n type FileOwners,\n MemoryFileOwners,\n} from \"./store/FileOwners\";\nimport {\n defaultNonceStore,\n MemoryNonceStore,\n type NonceModel,\n type NonceRedisClient,\n type NonceStore,\n PrismaNonceStore,\n type PrismaNonceStoreOptions,\n RedisNonceStore,\n type RedisNonceStoreOptions,\n} from \"./store/Nonces\";\nimport {\n MemoryReceiptStore,\n type ReceiptClaim,\n type ReceiptRedisClient,\n type ReceiptStore,\n RedisReceiptStore,\n type RedisReceiptStoreOptions,\n} from \"./store/Receipts\";\nimport { defaultAgentStore, MemoryAgentStore } from \"./store/MemoryAgentStore\";\nimport { normalizeProviderError, ProviderHttpError } from \"./providers/errors\";\nimport { redactError, unredactedError } from \"./redact\";\nimport type { ErrorRedactionInfo } from \"./redact\";\nimport { encodeFrame, sseHeaders, sseKeepalive, sseResponse } from \"./store/sse\";\nimport { decodeSSE } from \"./client/sse\";\nimport { settleInterrupted, TurnJournal } from \"./store/TurnJournal\";\nimport { AgentJobs } from \"./jobs/AgentJob\";\nimport { markOrphans, overlayJobs } from \"./jobs/overlay\";\nimport { DEFAULT_JOBS_CONTEXT_MAX, renderJobsBlock } from \"./jobs/contextBlock\";\nimport type { AgentJobRecord } from \"./jobs/AgentJobStore\";\nimport type { AgentMemoryScopes } from \"./memory/runMemory\";\nimport type { AgentUsageLimits } from \"./usageLimits\";\nimport type { Schema } from \"./Schema\";\nimport { RealtimeRequestError, type RealtimeSession } from \"./providers/realtime\";\nimport type { VoiceConfig } from \"./voiceConfig\";\nimport { defaultVoiceStore, type VoiceSessionRecord, type VoiceSessionStore } from \"./voiceStore\";\nimport { emptyUsage } from \"./runtime\";\nimport { mcpVoiceTools } from \"./voiceMcp\";\nimport { DEFAULT_DELEGATE_NAME, VoiceBridge, voiceTools } from \"./VoiceBridge\";\nimport type { VoiceStartResponse } from \"./voice/wire\";\nimport type {\n AgentError,\n AgentMessage,\n AgentStreamEvent,\n AgentStreamFrame,\n ClientTurn,\n JsonToolShapes,\n PendingToolCall,\n ToolDenial,\n ToolResultPart,\n ToolShapes,\n} from \"./types\";\n\n// --- storage -------------------------------------------------------------\n\n/**\n * Where conversations live.\n *\n * Stateless is the default and nothing here is required to hold a conversation:\n * the client can carry its own history, and a pending approval travels in it\n * safely because the server signed it. What a store buys is a conversation that\n * survives the browser — and, with `/attach`, one whose interrupted turn is\n * still there after a refresh.\n */\n/**\n * What `AgentStore.createThread` takes. `ttlMs` and `expiresAt` (#1312) are\n * honoured by `MemoryAgentStore` and by a `DatabaseAgentStore` with `ttlMs`;\n * a store of the app's own may ignore them, or refuse them.\n */\nexport type CreateThreadParams = {\n userId?: string | number;\n /**\n * This thread's lifetime in place of the store's `ttlMs` (#1312); `null`\n * keeps it until it is deleted. Slides with the store's `slidingTtl`.\n */\n ttlMs?: number | null;\n /** A fixed expiry, epoch milliseconds or a `Date`, in place of any `ttlMs`. It never slides. */\n expiresAt?: number | Date;\n};\n\n/** What `sweepExpired` answers. */\nexport type ThreadSweepResult = {\n /** Expired threads deleted, with their messages and summaries. */\n deleted: number;\n};\n\nexport interface AgentStore {\n /**\n * Where a `threadId` comes from. `ApiRouter.agent()` mounts no route for\n * this: the app writes one, calls it here, and hands the id to `useChat` —\n * the mount is the app's because it is where ownership gets recorded, and a\n * store that holds no user cannot do that for it. An id that did not come out\n * of here is `null` from `loadThread` and a 404 from the controller, unless\n * the store's ids are the client's by design (`MemoryAgentStore`'s\n * `clientOwnedIds`).\n */\n createThread(params: CreateThreadParams): Promise<{ threadId: string }>;\n /**\n * The history, or `null` for a thread the store does not have.\n *\n * `null` and `[]` are different answers and the controller acts on the\n * difference: an empty array is a conversation with nothing in it yet, and a\n * turn on it runs; `null` is a 404 before anything runs. A store that answers\n * `[]` for an id it has never seen turns an expired or mistyped thread into a\n * fresh conversation with no signal, and persists the next turn under the\n * dead id. Only a store whose ids are minted by the client should do that,\n * and then on purpose — see `MemoryAgentStore`'s `clientOwnedIds`.\n */\n loadThread(threadId: string): Promise<AgentMessage[] | null>;\n /**\n * Upsert by message id: replace a message the thread already holds, append\n * one it does not, and keep the order the thread had. Called with a thread\n * `loadThread` just found; must not create one.\n *\n * The name says append because that is what almost every call is, but a\n * turn that resolves a pending call reports the earlier assistant message\n * again — same id, now with the result attached — and a store that only\n * appends ends up with both versions. A table keyed by message id has the\n * lookup already but still needs an insert-or-update rather than a plain\n * insert, which would fail on the key; a store that is a list has to look\n * before it pushes.\n *\n * It is also called while a turn runs, not only when it ends (#617): with the\n * user's message as the run starts, with the assistant message in progress\n * (no `finishReason`, the run's id in `runId`) as it opens and at each tool\n * call and result, and with each message again once it is finished. The\n * same message arrives several times, and the last write is the one to\n * keep. Calls for one run never overlap: each waits for the one before.\n */\n appendMessages(threadId: string, messages: AgentMessage[]): Promise<void>;\n /**\n * Delete these messages from the thread; ids it does not hold are ignored.\n *\n * What a threaded `regenerate` needs (#451): the server owns the history,\n * so the answer being replaced has to leave the store, or the model reads\n * `user: X, assistant: A, user: X` and writes a follow-up instead of a new\n * answer. The controller calls it under the thread's lock with the last user\n * turn and everything after it, then runs that turn again.\n *\n * Optional so a store written before it still compiles; without it a turn\n * with `regenerate: true` on a thread is a 501 `regenerate_unsupported`.\n */\n removeMessages?(threadId: string, messageIds: string[]): Promise<void>;\n /**\n * Optional: where `contextWindow.compact` keeps the thread's summaries\n * (#782), so they live, and are deleted, with the thread. Implement both to\n * opt in; without them summaries go to `defaultSummaryStore`, in memory.\n * Same contract as `SummaryStore`.\n */\n loadSummaries?(threadId: string): Promise<ThreadSummary[]>;\n saveSummary?(threadId: string, summary: ThreadSummary): Promise<void>;\n /** Optional cross-process lock for one cut. See `SummaryStore.lockSummary`. */\n lockSummary?(\n threadId: string,\n cutMessageId: string,\n ttlMs: number,\n ): Promise<(() => Promise<void>) | null>;\n /**\n * Optional (#1177): the same store bound to one scope (a tenant key). Every\n * read and write of the returned store is inside that scope, and a thread of\n * another scope is one it does not have. What `storeScope()` needs.\n */\n forScope?(scope: string): AgentStore;\n}\n\n/** The default: conversations last as long as the process. */\nexport { defaultAgentStore, MemoryAgentStore };\n\n/** The attachment half of the same story. See `store/Attachments.ts`. */\nexport {\n type Attachment,\n type AttachmentDestination,\n AttachmentNotFoundError,\n type AttachmentRetention,\n type AttachmentScope,\n type AttachmentStorage,\n type AttachmentStore,\n defaultAttachmentStore,\n InvalidAttachmentScopeError,\n MemoryAttachmentStore,\n type PutAttachmentParams,\n ScopedAttachments,\n type ToolAttachmentPut,\n type ToolAttachmentRecord,\n type ToolAttachments,\n} from \"./store/Attachments\";\n\n/**\n * The runs currently in flight, and their frames.\n *\n * A run outlives the request that started it, so something has to hold it while\n * no one is listening, and hold what it emitted meanwhile so a returning client\n * can catch up rather than start over. That is all this is: a per-process map\n * plus a bounded buffer.\n *\n * Per-process is not an implementation shortcut that a better store fixes — a\n * running generator lives in one process, and a second server cannot attach to\n * it. Reattachment therefore needs the request to land where the run is: one\n * server, sticky routing, or a proxy that forwards by `runId`. Worth saying out\n * loud, because the failure mode behind a round-robin load balancer is a\n * refresh that usually works.\n *\n * This is the read side, which is all `attach` and `stop` need. Registering a\n * run and replaying its buffer are on `MemoryLiveRuns`, the only implementation\n * there can be — see the note there for why a second one would not help.\n */\nexport interface LiveRuns {\n /** What the client asks after a refresh: is anything still going here? */\n find(params: { threadId: string }): Promise<{ runId: string; seq: number } | null>;\n get(runId: string): AgentRun | null;\n /** Kept for a short while after `run-end`, so a refresh a second late still\n * sees the tail instead of an empty screen. */\n ttlMs: number;\n}\n\nexport {\n FrameCursorEvictedError,\n LiveRunNotFoundError,\n MemoryLiveRuns,\n defaultLiveRuns as liveRuns,\n};\n\n/** Who uploaded each provider file id (#443). See `store/FileOwners.ts`. */\nexport { defaultFileOwners, type FileOwnerRecord, type FileOwners, MemoryFileOwners };\n/** Where approved tools' executions are recorded (#458). See `store/Receipts.ts`. */\nexport {\n MemoryReceiptStore,\n type ReceiptClaim,\n type ReceiptRedisClient,\n type ReceiptStore,\n RedisReceiptStore,\n type RedisReceiptStoreOptions,\n};\n/** Where answered calls' nonces are spent (#445). See `store/Nonces.ts`. */\nexport {\n defaultNonceStore,\n MemoryNonceStore,\n type NonceModel,\n type NonceRedisClient,\n type NonceStore,\n PrismaNonceStore,\n type PrismaNonceStoreOptions,\n RedisNonceStore,\n type RedisNonceStoreOptions,\n};\n\n// --- controller ----------------------------------------------------------\n\nexport type AgentHookContext = {\n /**\n * The request that started the turn. Its `state` is the turn's own typed\n * state (#887): a value set in `authorizeRequest()`, `instructions()` or\n * `context()` (`req.state.set(key, value)`) is read here with\n * `ctx.req.state.get(key)`, instead of a `WeakMap` keyed on the request.\n * A request answering an approval is a new turn and starts with none.\n */\n req: HttpRequest<any, any>;\n runId: string;\n threadId?: string;\n /**\n * The approvals the user refused in this turn's run so far (#1260): read\n * live from the run, so `onToolResult` for a refusal already sees it. See\n * `CreateAgentParams.rememberDenials`.\n */\n readonly denials: readonly ToolDenial[];\n /**\n * The turn the run answers (#1339): `id` is `AgentMessage.turn` on every\n * message it writes; `continues` is set when the request added no message\n * of its own (answers to tool calls, or a bare continuation) and carries on\n * that earlier turn; `answers` lists the tool calls it answered. Read live\n * from the run: `undefined` before the run has taken its turn in.\n */\n readonly turn: AgentRunTurn | undefined;\n};\n\n/**\n * The call a tool result answers, as `onToolResult` gets it (#1079): the same\n * shape `onToolCall` gets. `input` is what the model sent, before the tool's\n * schema parsed it, so a call refused for a mis-typed argument has it too.\n */\nexport type ToolResultCall = {\n toolCallId: string;\n name: string;\n input: unknown;\n};\n\n/**\n * What `AgentController.startTurn` takes (#839).\n */\nexport type AgentTurnParams<Body extends object = Record<string, unknown>> = {\n /** The thread the turn is stored on, as a turn from `useChat` would be. */\n threadId: string;\n /** The user's message. Shorthand for `turn: { text }`, and wins over `turn.text`. */\n text?: string;\n /**\n * The whole turn, for files or answers: `{ text, files, toolResults }`, as\n * `useChat` sends it. Neither `text` nor `turn` is a turn with nothing in\n * it, which lets the model continue the thread.\n */\n turn?: ClientTurn;\n /**\n * Who the turn runs as: `req.ctx().user` for `authorizeRequest`, `runOwner`,\n * `context()`, the hooks and every tool, as the authentication middleware\n * would have set it. Absent or `null` is an anonymous turn.\n */\n user?: unknown;\n /** What `useChat`'s `body` option would send: `instructions()`, `context()` and `ctx.body` read it. */\n body?: Body;\n /**\n * The store scope (tenant key) the turn's thread is in (#1177), for a\n * controller whose store is scoped. Wins over `storeScope()`, which still\n * answers when this is absent: it gets the request built for the turn, with\n * `user` and `body`.\n */\n scope?: string;\n /**\n * What to do when the thread already has a run going (#1178). See\n * `AgentTurnBusyPolicy`. Defaults to `\"supersede\"`, what a resend from the\n * chat does. The controller's `busyPolicy` hook is asked with it as\n * `requested`, and its answer is what happens; the default answers it.\n */\n ifBusy?: AgentTurnBusyPolicy;\n /**\n * Something that happened, in place of a person's message (#1181): a job\n * finished, a record changed. Stored as a user message with\n * `message.event` set (`{ name, data }`) and `text` as its text; the model\n * reads it as `<event name=\"…\">`, and a UI can render it apart from what\n * the person wrote. Not with `text` or `turn`.\n */\n event?: AgentTurnEvent;\n};\n\n/** What `startTurn({ event })` takes (#1181). */\nexport type AgentTurnEvent = {\n /** Letters, digits and `.`, `_`, `:`, `-`, at most 64: `\"job-settled\"`. */\n name: string;\n /** What the model is told happened. */\n text?: string;\n /** Plain JSON data, stored with the message and shown to the model after `text`. */\n data?: unknown;\n};\n\n/** What `AgentTurnEvent.name` may be. */\nconst EVENT_NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;\n\n/**\n * What a turn does on a thread that is busy: a run still going, or a turn\n * setting up on it (#1178). A client sends it as `ifBusy` (`useChat`'s\n * `ifBusy` option), server code passes it to `startTurn`, and the\n * controller's `busyPolicy` hook has the last word.\n *\n * - `\"supersede\"` (the default) stops the running run and starts once its\n * transcript is stored, as a resend from the chat does.\n * - `\"queue\"` lets the running run finish, then starts, so the turn sees that\n * run's messages. Queued turns start in the order they were queued, each\n * after the one before has ended. A queued turn holds nothing while it\n * waits: a person who sends meanwhile still supersedes the running run, and\n * the queued turn then waits for theirs too. Per process, like the thread's\n * lock.\n * - `\"join\"` adds the message to the running turn: the run reads it at its\n * next model call, and stores it after the message it was writing, marked\n * `AgentMessage.joined`. Nothing waits and nothing is cut off. The turn's\n * answer is that run's stream (`useChat` keeps showing the reply it was\n * showing). A run that cannot take it any more (it has just ended, or is on\n * its last step) is let finish, and the message starts a turn of its own\n * after it. Only a message joins: a turn with no text, files or event, or\n * one answering tool calls, is started after the run as `\"queue\"` would.\n * - `\"parallel\"` starts a second run on the thread at once, beside the one\n * going. Each has its own `runId` and stream; their messages are stored in\n * the order they arrive. A parallel run reads the thread as it is when it\n * starts, without the messages another run is still writing, plus its own.\n * Each run counts against `maxConcurrentRuns`, and a thread takes at most\n * `maxThreadRuns` at once (a 429 `too_many_runs` past it).\n * - `\"skip\"` starts nothing: `startTurn` answers `{ skipped: true }`, a client\n * turn a 409 `thread_busy`.\n */\nexport type AgentTurnBusyPolicy = \"supersede\" | \"queue\" | \"join\" | \"parallel\" | \"skip\";\n\n/** The busy policies a client turn may ask for (`ifBusy` in its body). */\nexport type AgentClientBusyPolicy = \"supersede\" | \"queue\" | \"join\" | \"parallel\";\n\n/** One run going on the thread, as `AgentController.busyPolicy` is told about it. */\nexport type AgentRunningTurn = {\n runId: string;\n /** When the run started. */\n startedAt: Date;\n /** Who started it (`runOwner`), `null` for an unowned run. A caller may join or supersede only a run it may access. */\n owner: string | null;\n /** What started the turn: the person's text and files, or a server turn's event. Empty for a turn with neither (answers, a continuation). */\n turn: AgentRunningTurnMessage;\n /**\n * The turn the run answers (#1339): the id of the message that started it,\n * `AgentMessage.turn` on everything the run writes. For a run that answers\n * tool calls, the turn that asked them. `undefined` until the run has taken\n * its turn in, a moment after it starts.\n */\n messageId: string | undefined;\n /** The `body` the request that started the run carried, as `instructions()` got it. */\n body: unknown;\n /** The messages that joined it so far, oldest first. */\n joined: AgentRunningTurnMessage[];\n};\n\n/** A message of a running turn, as `AgentRunningTurn` carries it. */\nexport type AgentRunningTurnMessage = {\n text?: string;\n files?: ClientTurn[\"files\"];\n event?: { name: string };\n};\n\n/**\n * What `AgentController.busyPolicy` is told about the turn arriving.\n *\n * `running` describes every run on the thread, other users' included, with\n * their messages' text and files: server-side data to decide with, not to\n * echo to the client.\n */\nexport type BusyPolicyParams<Body extends object = Record<string, unknown>> = {\n threadId: string;\n /** The runs going on the thread in this process, oldest first. Never empty: the hook is asked only when the thread is busy. */\n running: AgentRunningTurn[];\n /** What the turn asked for: the client's `ifBusy`, or `startTurn`'s. `undefined` when it asked nothing. */\n requested: AgentTurnBusyPolicy | undefined;\n /** Where the turn came from: a request to the route, or `startTurn`. */\n source: \"client\" | \"server\";\n /** The turn arriving: its text, files and answers, as `useChat` sends them. */\n turn: ClientTurn | undefined;\n /** The client's `body` option, as `instructions()` gets it. */\n body: Body;\n /** Who is sending (`runOwner`). */\n owner: string | null;\n};\n\n/** What `startTurn({ ifBusy: \"skip\" })` answers when the thread was busy. */\nexport type AgentTurnSkipped = {\n skipped: true;\n threadId: string;\n};\n\n/** A turn `AgentController.startTurn` started. */\nexport type AgentTurn = {\n runId: string;\n threadId: string;\n /** The run: iterate it (or its `frames()`) to follow the turn as it goes. */\n run: AgentRun;\n /**\n * The turn's message joined a run already going (`ifBusy: \"join\"`): `run`\n * is that run, and `result()` is its outcome. If the run ended before it\n * took the message, `result()` is the outcome of the turn started for it\n * after.\n */\n joined: boolean;\n /** What the chat's stop button does. */\n stop(params?: { reason?: string }): void;\n /**\n * Settles when the run has ended, its transcript is stored and the\n * controller's hooks have run (or `hookHoldMs` has passed). Rejects only if\n * the run itself does; a failed model call resolves with `finishReason:\n * \"error\"` and `error`, as `AgentRun.result()` does.\n */\n result(): Promise<AgentTurnResult>;\n};\n\n/**\n * A message of the controller's threads, as `readThread` answers it (#1100):\n * typed by the agent's tools, so it goes into the route's\n * `useChat({ initialMessages })` with no cast. The tools' outputs, progress\n * and previews are in their JSON form (`JsonToolShapes`, #1107), as the\n * thread store hands them back and as `useChat` types them.\n *\n * A controller whose agent is not known (`AgentController`, or the\n * `AgentController<any, any>` bound the route helpers use, or an agent whose\n * tools have no literal names) answers `AgentMessage<any>`. `AgentMessage` is invariant in its tool shapes (a\n * message of an agent with more tools has parts a narrower one does not\n * expect), so a typed answer fits neither `AgentMessage<ToolShapes>` nor\n * `AgentMessage<AgentToolShapes<AnyAgent>>`, and a concrete controller would\n * no longer fit those bounds.\n */\nexport type ThreadMessage<A> = 0 extends 1 & A\n ? AgentMessage<any>\n : A extends AnyAgent\n ? // `AnyAgent`'s shapes (and an untyped tool list's) are an index signature.\n string extends keyof AgentToolShapes<A>\n ? AgentMessage<any>\n : // Re-checked against `ToolShapes` because the mapping over a generic\n // agent's shapes cannot show it keeps `input` and `output`.\n JsonToolShapes<AgentToolShapes<A>> extends infer J extends ToolShapes\n ? AgentMessage<J>\n : never\n : AgentMessage<any>;\n\n/** What `AgentTurn.result()` answers: the run's result, and what a caller reads off it. */\nexport type AgentTurnResult = AgentRunResult<ToolShapes, unknown> & {\n threadId: string;\n /** The text of the run's last assistant message; `\"\"` when it wrote none. */\n text: string;\n /**\n * The calls waiting for an answer when `finishReason` is\n * `\"awaiting-input\"`, and `[]` otherwise. They stay on the thread, signed\n * for the turn's `runOwner`: that user can answer them in the chat, or the\n * caller can with another `startTurn({ turn: { toolResults } })`.\n */\n pending: PendingToolCall[];\n};\n\n/**\n * A turn `startTurn` could not start: what the route would have answered,\n * thrown. `status` and `code` are the route's (`404` `thread_not_found`,\n * `429` `too_many_runs`, `403` for another owner's run or file...).\n */\nexport class AgentTurnError extends Error {\n readonly status: number;\n readonly code?: string;\n readonly kind?: string;\n\n constructor(message: string, params: { status: number; code?: string; kind?: string }) {\n super(message);\n this.name = \"AgentTurnError\";\n this.status = params.status;\n this.code = params.code;\n this.kind = params.kind;\n }\n\n /** @internal Reads a refusal `stream` answered. */\n static async from(response: Response): Promise<AgentTurnError> {\n let error: Record<string, unknown> = {};\n try {\n const parsed = (await response.json()) as { error?: Record<string, unknown> };\n if (parsed?.error && typeof parsed.error === \"object\") error = parsed.error;\n } catch {\n // Not a JSON refusal: the status says what there is to say.\n }\n const text = (key: string) => (typeof error[key] === \"string\" ? (error[key] as string) : undefined);\n return new AgentTurnError(\n text(\"message\") ?? `The agent turn was refused with status ${response.status}.`,\n { status: response.status, code: text(\"code\"), kind: text(\"kind\") },\n );\n }\n}\n\n/** `Body` of a controller instance type, as `AgentRouteRPC` reads it. */\ntype ControllerBody<C> = C extends { [BODY]?: infer B }\n ? B extends object\n ? B\n : Record<string, unknown>\n : Record<string, unknown>;\n\n/** The text of the last assistant message among `messages`, or `\"\"`. */\nfunction lastAssistantText(messages: AgentMessage[]): string {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n if (message.role !== \"assistant\") continue;\n return message.content\n .map((part) => (part.type === \"text\" ? part.text : \"\"))\n .join(\"\");\n }\n return \"\";\n}\n\n/** The `AgentTurn` for a run `startTurn` started (or joined, with `joined`). */\nfunction serverTurnHandle(\n threadId: string,\n run: AgentRun,\n hooks: Promise<void>,\n joined = false,\n): AgentTurn {\n let pending: PendingToolCall[] = [];\n // The pending calls are on the `awaiting-input` event, not on the result.\n // The run's frames are buffered from the start, so this misses nothing.\n const watched = (async () => {\n for await (const event of run) {\n if (event.type === \"awaiting-input\") pending = event.pending as PendingToolCall[];\n }\n })().catch(noop);\n\n let result: Promise<AgentTurnResult> | undefined;\n return {\n runId: run.runId,\n threadId,\n run,\n joined,\n stop: (stopParams) => stopByCaller(run, stopParams),\n result: () =>\n (result ??= (async () => {\n const outcome = await run.result();\n // After the transcript is stored and the hooks are done (or\n // `hookHoldMs` passed), so a caller that reads the thread next sees\n // this turn in it.\n await Promise.all([hooks, watched]);\n const messages = outcome.messages as AgentMessage[];\n return {\n ...outcome,\n threadId,\n text: lastAssistantText(messages),\n pending: outcome.finishReason === \"awaiting-input\" ? pending : [],\n };\n })()),\n };\n}\n\n/**\n * The `AgentTurn` for a `startTurn` whose message joined a running run: that\n * run's, and `result()` is the outcome of the run that answered the message.\n * That is the joined run when it took it, the turn started for it when it did\n * not (or the run it joined in turn), and the joined run's own outcome when a\n * stop dropped it. A message no run could take, because the turn started for\n * it was refused, rejects `result()` with that refusal.\n */\nfunction joinedServerTurn(\n threadId: string,\n joined: { run: AgentRun; answer: Promise<JoinAnswer> },\n): AgentTurn {\n // The running run's own request holds its hooks; the transcript being\n // stored is what this caller can wait for.\n const own = serverTurnHandle(\n threadId,\n joined.run,\n persisted.get(joined.run) ?? joined.run.result().then(noop, noop),\n true,\n );\n let result: Promise<AgentTurnResult> | undefined;\n return {\n ...own,\n stop: (stopParams) => {\n stopByCaller(joined.run, stopParams);\n void joined.answer.then((answer) => {\n if (\"run\" in answer) stopByCaller(answer.run, stopParams);\n }, noop);\n },\n result: () =>\n (result ??= (async () => {\n const answer = await joined.answer;\n if (answer.kind === \"refused\") {\n await own.result();\n throw answer.error;\n }\n if (answer.kind === \"dropped\" || answer.run === joined.run) return own.result();\n return serverTurnHandle(threadId, answer.run, answer.hooks).result();\n })()),\n };\n}\n\n/** Every value `ifBusy` may be. */\nconst BUSY_POLICIES: readonly AgentTurnBusyPolicy[] = [\n \"supersede\",\n \"queue\",\n \"join\",\n \"parallel\",\n \"skip\",\n];\n\n/**\n * What a turn hands `AgentRun.join`: its text and files, or a server turn's\n * event. `null` for a turn that has nothing to join with: no message, or\n * answers to tool calls, which belong to the end of a run, not its middle.\n */\nfunction joinTurnOf(\n turn: ClientTurn | undefined,\n event: AgentTurnEvent | undefined,\n): AgentJoinTurn | null {\n if (event) {\n return {\n event: {\n name: event.name,\n ...(event.text !== undefined ? { text: event.text } : {}),\n ...(event.data !== undefined ? { data: event.data } : {}),\n },\n };\n }\n if (!turn || (turn.toolResults && turn.toolResults.length > 0)) return null;\n if (!turn.text && !(turn.files && turn.files.length > 0)) return null;\n return {\n ...(turn.text ? { text: turn.text } : {}),\n ...(turn.files && turn.files.length > 0 ? { files: turn.files } : {}),\n ...(turn.localId ? { localId: turn.localId } : {}),\n };\n}\n\n/** A turn's message as `AgentRunningTurn` describes it. */\nfunction runningTurnMessage(turn: ClientTurn | AgentJoinTurn | undefined): AgentRunningTurnMessage {\n if (!turn) return {};\n const event = \"event\" in turn ? turn.event : undefined;\n const text = event ? event.text : turn.text;\n return {\n ...(text ? { text } : {}),\n ...(!event && turn.files && turn.files.length > 0 ? { files: turn.files } : {}),\n ...(event ? { event: { name: event.name } } : {}),\n };\n}\n\n/** What a client may send as `ifBusy`: `\"skip\"` is `startTurn`'s alone. */\nconst CLIENT_BUSY_POLICIES: readonly AgentClientBusyPolicy[] = [\n \"supersede\",\n \"queue\",\n \"join\",\n \"parallel\",\n];\n\n/** What `AgentController.attachmentLimits` answers. Both optional. */\nexport type AttachmentLimits = {\n /** The largest file accepted, in bytes. */\n maxBytes?: number;\n /** `<input accept>` entries: `\".pdf\"`, `\"image/*\"`, `\"text/csv\"`. */\n accept?: string[];\n};\n\n/** The file `AgentController.checkUpload` is asked about: what it is, not its bytes. */\nexport type UploadCheckFile = {\n /** The file's name as the client sent it, `\"upload\"` when it sent none. */\n name: string;\n /** In bytes. */\n size: number;\n /** As the client sent it, `\"application/octet-stream\"` when it sent none. */\n mimeType: string;\n};\n\n/**\n * What an upload hook is told beyond the request (#836): the client's `body`\n * option (what `attachmentScope` gets) and the thread the upload is for, when\n * the store knows it.\n */\nexport type UploadContext<Body extends object = Record<string, unknown>> = {\n body: Body;\n /** Only a thread the store found; an id it has never seen is left out. */\n threadId?: string;\n};\n\n/**\n * What `AgentController.checkUpload` returns to refuse a file. Answered **422**\n * with `{ error: { code, message } }`, which `useChat().attach()` rejects with\n * as an `AttachError` carrying the same `code` and `message`.\n */\nexport type UploadRefusal = {\n /** A code the composer can switch on. `\"upload_refused\"` when left out. */\n code?: string;\n /** The sentence the person reads. */\n message: string;\n};\n\n/**\n * What `POST /<path>/files` answers.\n *\n * TWO IDS, AND THEY ARE NOT INTERCHANGEABLE. `fileId` is the *provider's* id and\n * means exactly what it always meant — the value a `FilePart` carries so the\n * model can see the file. `attachmentId` is *gemi's*, and is the handle a tool\n * resolves through `ScopedAttachments` to get the bytes back. A file can have\n * both, and usually does.\n *\n * `fileId` stays first and stays named that on purpose: `useChat.uploadFile`\n * already reads it, apps already put it in a `FilePart`, and renaming it or\n * folding the two into one id would break vision for every existing app while\n * looking like a tidier API. The two ids exist because there are two systems\n * holding the file.\n *\n * Both are optional, and `destination` says which to expect: `provider` has no\n * `attachmentId` (nothing was kept), `storage` has no `fileId` (the provider\n * never saw it, so there is nothing for a `FilePart` to point at), `both` has\n * both.\n *\n * `destination` ALONE IS NOT ENOUGH TO SAY WHY AN ID IS MISSING, which is why\n * `downgraded` is here. An upload that reached a route with no authentication\n * and no `threadId` answers `destination: \"provider\"` — truthfully, that is\n * where the bytes went — and so does a controller that deliberately returns\n * `\"provider\"` from `attachmentDestination`. Those two answers were byte\n * identical, and they are the opposite situations: one is the app's policy\n * working, the other is the app's policy silently not applying because the\n * server could not tell who was calling. The server logs the second one once\n * per process; the client saw nothing at all. `downgraded` is the difference,\n * carried in the answer so a client — or an integration test — can assert on\n * it.\n */\nexport type UploadResult = {\n /** The provider's id, for a `FilePart`. Absent when the file never went there. */\n fileId?: string;\n /** gemi's id, for a tool. Absent when nothing was kept — see `attachmentScope`. */\n attachmentId?: string;\n name: string;\n mimeType: string;\n size: number;\n destination: AttachmentDestination;\n /**\n * Set only when the app's policy asked for a copy and the request had no\n * subject to file it under, so the upload fell back to the provider alone.\n * Absent when `destination` is what the app actually chose.\n *\n * A string rather than `true` because there is exactly one reason today and\n * there will be more (a store that refused the write, say), and a boolean\n * that later needs a reason beside it is two fields where one would have\n * done.\n */\n downgraded?: \"no_scope\";\n};\n\n/**\n * `Controller.kind` is typed as the literal `\"controller\"`, so a subclass that\n * declares a `kind` of its own fails the static-side check (TS2417). Widening\n * it belongs in `http/Controller.ts`, which this slice does not own; erasing\n * the static side of the base here is the smaller change and costs nothing —\n * `Controller.kind` has no reader, in this package or out of it.\n */\nconst ControllerBase = Controller as new () => Controller;\n\n/**\n * The thread a `stream` is setting up on, to the setup ahead of it. Module\n * level because the controller is constructed per request, so nothing on it\n * can be seen by the next request; keyed by thread rather than held on\n * `liveRuns` because it guards the controller's protocol, not the frames. An\n * entry is removed once the last setup queued on it releases.\n */\nconst threadLocks = new Map<string, Promise<void>>();\n\n/**\n * Each run to the promise that its transcript has been stored. Weak, so a run\n * the map has evicted is not kept alive here for a promise nobody will ask for.\n */\nconst persisted = new WeakMap<AgentRun, Promise<void>>();\n\n/**\n * The run a `startTurn` request started, by that request (#839). `stream`\n * answers a `Response`, which is what a route needs; `startTurn` needs the run\n * itself and the promise that its hooks are done, and this is how it gets them\n * without `stream` growing a second return shape. Weak, so a request nobody\n * reads back leaves nothing behind.\n */\nconst serverTurns = new WeakMap<\n HttpRequest<any, any>,\n { run: AgentRun; hooks: Promise<void> } | null\n>();\n\n/** The `scope` each `startTurn` was given, by the request it built (#1177). */\nconst serverTurnScopes = new WeakMap<HttpRequest<any, any>, string>();\n/** `startTurn`'s busy policy, by the request it built (#1178). A route's turn reads the client's `ifBusy` instead. */\nconst busyPolicies = new WeakMap<HttpRequest<any, any>, AgentTurnBusyPolicy>();\n\n/** Whether `response` is a run's stream rather than a refusal. */\nfunction isEventStream(response: Response): boolean {\n return response.headers.get(\"Content-Type\")?.startsWith(\"text/event-stream\") ?? false;\n}\n\n/** What `busyPolicy` is told about each run a controller started. Weak, like `persisted`. */\nconst runRecords = new WeakMap<\n AgentRun,\n {\n startedAt: Date;\n owner: string | null;\n turn: AgentRunningTurnMessage;\n joined: AgentRunningTurnMessage[];\n body: unknown;\n }\n>();\n\n/** Each threaded run's journal, so a parallel run can wait for what another has written. */\nconst journals = new WeakMap<AgentRun, TurnJournal>();\n\n/**\n * A joined turn's answer (`\"join\"`), by the response `withThread` built for\n * it: settles once the stream it answers has ended, including the turn\n * started after when the run did not take the message. What the turn's\n * `maxConcurrentRuns` slot is held for.\n */\nconst joinHolds = new WeakMap<Response, Promise<unknown>>();\n\n/** The run each request started, once it has, with the promise its hooks are done. */\nconst turnRuns = new WeakMap<HttpRequest<any, any>, { run: AgentRun; hooks: Promise<void> }>();\n\n/** How `stream`'s turn is started: alone on its thread, or beside the runs going (`\"parallel\"`). */\ntype StartMode = {\n parallel: boolean;\n /** Frees the parallel run's own `maxConcurrentRuns` slot. */\n release?: () => void;\n};\nconst SOLO: StartMode = { parallel: false };\n\n/** What `withThread` needs to decide a busy thread's policy. */\ntype BusyTurn = {\n req: HttpRequest<any, any>;\n requested: AgentTurnBusyPolicy | undefined;\n /** Whether `busyPolicy` is asked; a regenerate is not. */\n decide: boolean;\n source: \"client\" | \"server\";\n turn: ClientTurn | undefined;\n body: any;\n /** `runLimitKey`'s answer, for a parallel run's own slot. */\n limitKey: string | null;\n /**\n * Set once a parallel turn has waited, outside the lock, for the runs going\n * to take their turns in: the policy it was given, and the runs it waited\n * for, which it does not wait for again (see `PARALLEL_INTAKE_WAIT_MS`).\n */\n intake?: { policy: AgentTurnBusyPolicy; waited: WeakSet<AgentRun> };\n};\n\n/**\n * How long a parallel turn waits for a run going on its thread to take its\n * own turn in before it reads the thread anyway. The wait is outside the\n * thread's lock, so it holds up no other turn; the limit is for a run that\n * takes long to reach its first model call (a slow tool it re-enters, a slow\n * limiter).\n */\nconst PARALLEL_INTAKE_WAIT_MS = 5_000;\n\n/** Each run's intake (see `intakeOf`), once a parallel turn has asked. */\nconst intakes = new WeakMap<AgentRun, { done: boolean; promise: Promise<void> }>();\n\n/** A `startTurn` that joined a run, by the request it built. See `AgentTurn.joined`. */\nconst serverJoins = new WeakMap<\n HttpRequest<any, any>,\n { run: AgentRun; answer: Promise<JoinAnswer> }\n>();\n\n/**\n * What became of a joined message (`\"join\"`):\n *\n * - `answered`: a run took it, the one it joined or, after that one ended\n * without it, the turn started for it (or a run that turn joined).\n * - `dropped`: the run it joined was stopped by a caller (`/stop`,\n * `AgentTurn.stop`) before reading it. Nothing is started or stored for it:\n * a stop stops the conversation, messages sent into it included.\n * - `refused`: the turn started for it was refused (a limit, another user's\n * run, `\"skip\"`). The message is stored, unanswered, so it is not lost, and\n * the refusal is reported: an `error` frame on the stream, and `result()`\n * rejecting for `startTurn`.\n */\ntype JoinAnswer =\n | { kind: \"answered\"; run: AgentRun; hooks: Promise<void> }\n | { kind: \"dropped\" }\n | { kind: \"refused\"; error: AgentTurnError; stored: AgentMessage | null };\n\n/** By the response `joinResponse` answered: what became of its message. */\nconst joinAnswers = new WeakMap<Response, Promise<JoinAnswer>>();\n\n/**\n * Runs a caller stopped (`/stop`, `AgentTurn.stop`), as against runs stopped\n * by a supersede or a time limit: their untaken joined messages are dropped\n * rather than handed on to a turn of their own.\n */\nconst stoppedByCaller = new WeakSet<AgentRun>();\n\nfunction stopByCaller(run: AgentRun, params?: { reason?: string }): void {\n stoppedByCaller.add(run);\n run.stop(params);\n}\n\n/**\n * Settles once `run` has taken its own turn in (its first model call has\n * started, it asked a question, or it ended) and its journal has written\n * what that changed. Watched from the first time a parallel turn asks.\n */\nfunction intakeOf(\n run: AgentRun,\n journal: TurnJournal | undefined,\n): { done: boolean; promise: Promise<void> } {\n const known = intakes.get(run);\n if (known) return known;\n const watched = (async () => {\n for await (const frame of run.frames()) {\n const type = frame.event.type;\n if (type === \"message-start\" || type === \"awaiting-input\" || type === \"run-end\") return;\n }\n })().catch(noop);\n const intake = { done: false, promise: Promise.resolve() };\n intake.promise = Promise.race([watched, run.result().then(noop, noop)])\n .then(() => journal?.settled())\n .then(noop, noop)\n .then(() => {\n intake.done = true;\n });\n intakes.set(run, intake);\n return intake;\n}\n\n/**\n * `startTurn`'s event, by the request it built (#1181). Kept off the request's\n * body on purpose: a client posting to the route cannot write one.\n */\nconst serverEvents = new WeakMap<HttpRequest<any, any>, AgentTurnEvent>();\n\n/** What `withThread` answers a `\"skip\"` turn on a busy thread. Never sent: `startTurn` reads it. */\nconst THREAD_BUSY = \"thread_busy\";\n\n/** The URL of the request `startTurn` builds. Nothing routes to it. */\nconst SERVER_TURN_URL = \"http://gemi.internal/__gemi/agent-turn\";\n\n/**\n * Turns read but not yet registered, by the client's name for them.\n *\n * A run can be stopped from `register` on, and named from `run-start` on. What\n * `/stop` could not reach was a turn still waiting its place on the thread —\n * which is where a user who sent twice and thought better of it presses stop,\n * and the wait is now as long as the old run's unwind. Falling through to\n * `threadId` there found the old run, already stopping, said `stopped: true`,\n * and the queued turn started anyway: unwatched, billing, and with no handle\n * left on the client that had let go of it. The entry is marked rather than\n * removed, because the turn itself is what answers once its wait is over.\n */\nconst pendingTurns = new Map<string, { cancelled: boolean; owner: string | null }>();\n\n// --- limits (#444) -------------------------------------------------------\n\n/** `AgentController.maxBodyBytes`'s default. */\nexport const DEFAULT_MAX_BODY_BYTES = 4 * 1024 * 1024;\n/** `AgentController.maxHistoryMessages`'s default. */\nexport const DEFAULT_MAX_HISTORY_MESSAGES = 1000;\n/** `AgentController.maxConcurrentRuns`'s default. */\nexport const DEFAULT_MAX_CONCURRENT_RUNS = 5;\n/**\n * What `maxThreadRuns` answers: how many runs one thread may have going, and\n * what a parallel turn past that does. A bare number refuses it (429\n * `too_many_runs`); `overflow: \"queue\"` holds it until one of the runs ends,\n * then starts it as a parallel run.\n */\nexport type ThreadRunLimit = number | { max: number; overflow: \"queue\" | \"reject\" };\n\n/**\n * `maxThreadRuns`'s answer, checked: a typo must not turn the limit off\n * (`NaN` is never reached) or turn a queue into a refusal. Throws, which\n * fails the turn, as a `busyPolicy` answer it does not know does.\n */\nfunction threadRunLimit(limit: ThreadRunLimit): { max: number; overflow: \"queue\" | \"reject\" } {\n const { max, overflow } =\n typeof limit === \"number\" ? { max: limit, overflow: \"reject\" as const } : (limit ?? ({} as never));\n const whole = max === Infinity || (Number.isInteger(max) && max > 0);\n if (!whole || (overflow !== \"queue\" && overflow !== \"reject\")) {\n throw new TypeError(\n `AgentController.maxThreadRuns answers a positive whole number (or Infinity), or { max, overflow: \"queue\" | \"reject\" }; got ${JSON.stringify(limit)}.`,\n );\n }\n return { max, overflow };\n}\n\n/** `AgentController.maxThreadRuns`'s default. */\nexport const DEFAULT_MAX_THREAD_RUNS = 3;\n/** The cap on `attach` and `stop` bodies, which carry ids and nothing else. */\nconst SMALL_BODY_BYTES = 64 * 1024;\n\nconst noop = () => {};\n\n/**\n * The runs each `runLimitKey` has going, by lane: a thread is one lane however\n * many turns are queued or superseding on it, and a stateless turn is a lane\n * of its own. A lane is held from the moment its turn is admitted until its\n * last run ends.\n */\nclass RunSlots {\n private byKey = new Map<string, Map<string, number>>();\n\n /**\n * Admits a turn in `lane` for `key`, or answers `null` when `key` already\n * holds `limit` other lanes. Synchronous, so two turns arriving together\n * cannot both see the last free slot. The function it returns frees the\n * turn's hold; calling it twice is harmless.\n */\n take(key: string, lane: string, limit: number): (() => void) | null {\n let lanes = this.byKey.get(key);\n if (!lanes?.has(lane) && (lanes?.size ?? 0) >= limit) {\n return null;\n }\n if (!lanes) {\n lanes = new Map();\n this.byKey.set(key, lanes);\n }\n lanes.set(lane, (lanes.get(lane) ?? 0) + 1);\n let released = false;\n return () => {\n if (released) return;\n released = true;\n const current = this.byKey.get(key);\n const count = (current?.get(lane) ?? 1) - 1;\n if (!current) return;\n if (count > 0) {\n current.set(lane, count);\n } else {\n current.delete(lane);\n if (current.size === 0) this.byKey.delete(key);\n }\n };\n }\n}\n\n/**\n * Slots are counted per `liveRuns` registry rather than per process: the\n * registry is what holds the runs being counted, and an app (or a test) with\n * two registries has two sets of runs.\n */\nconst runSlots = new WeakMap<object, RunSlots>();\n/**\n * Who is watching each thread (`POST /<path>/watch`, #1180), per `liveRuns`\n * registry like `runSlots`: a run is announced to the watchers of the\n * registry it was registered in. Per process, like the runs themselves.\n */\nconst threadWatchers = new WeakMap<object, Map<string, Set<(runId: string) => void>>>();\n\nfunction watchersFor(liveRuns: object): Map<string, Set<(runId: string) => void>> {\n let watchers = threadWatchers.get(liveRuns);\n if (!watchers) {\n watchers = new Map();\n threadWatchers.set(liveRuns, watchers);\n }\n return watchers;\n}\n\n/** Tells the thread's watchers a run started on it. Never throws: a watcher is a stream that may be gone. */\nfunction announceRun(liveRuns: object, threadId: string, runId: string): void {\n const listeners = threadWatchers.get(liveRuns)?.get(threadId);\n if (!listeners) return;\n for (const listener of [...listeners]) {\n try {\n listener(runId);\n } catch {\n // A closed stream; its cancel removes it.\n }\n }\n}\n\nfunction runSlotsFor(liveRuns: object): RunSlots {\n let slots = runSlots.get(liveRuns);\n if (!slots) {\n slots = new RunSlots();\n runSlots.set(liveRuns, slots);\n }\n return slots;\n}\n\n/**\n * The key that carries `Body` on the instance type.\n *\n * A `declare const` unique symbol, so it exists only in the type layer — the\n * same device `Schema.ts` uses for its output type, and for the same reason: a\n * real property would be one an app could see, serialise or depend on.\n */\ndeclare const BODY: unique symbol;\n\n/**\n * What `authorizeRequest` is told about the request, per route.\n *\n * A union on `route` because `body` exists on only two of them: `stream` and\n * `upload` carry the client's `body` option, `attach` and `stop` carry none.\n * Typing it optional everywhere would make every reader of `body.pageId` on\n * `stream` write a check for a case that cannot happen there; narrowing on\n * `route` says which case it is. An override written against the older\n * `{ route; threadId? }` shape still accepts every member.\n */\nexport type AuthorizeRequestParams<Body extends object = Record<string, unknown>> =\n | { route: \"stream\" | \"upload\"; threadId?: string; body: Body }\n | { route: \"attach\" | \"stop\"; threadId?: string; body?: undefined };\n\n/**\n * What `AgentController.attachmentRetention` is told (#1307): which route asks\n * (`upload` for an upload, `stream` for a turn and what its tools store), the\n * thread when there is one the store knows, and the client's `body` option.\n */\nexport type AttachmentRetentionParams<Body extends object = Record<string, unknown>> = {\n route: \"stream\" | \"upload\";\n threadId?: string;\n body: Body;\n};\n\n/** What `AgentController.sweepAttachments` answers. */\nexport type AttachmentSweepResult = {\n /** Attachments and provider-only files deleted. */\n deleted: number;\n /** Ones that could not be deleted; each was passed to `reportHookFailure`, and is tried again next sweep. */\n failed: number;\n};\n\n/**\n * What `AgentController.runTools()` answers for a turn (#1123): tools added to\n * the agent's for this run, and which tools the model is offered. Both are\n * optional; see `AgentStreamParams.tools` and `AgentStreamParams.activeTools`.\n */\nexport type AgentRunTools = {\n tools?: readonly ToolEntry[];\n activeTools?: readonly string[];\n};\n\n/**\n * HOOKS SHARED BY SEVERAL AGENT CONTROLLERS (#989), assigned to a controller's\n * `hooks`. Each one stands in for gemi's default of the controller method with\n * the same name, and takes the same arguments. See `AgentController.hooks`.\n *\n * Plain functions, not methods: they get no `this`. What one hook leaves for\n * another in the same turn (a charge made in `context`, settled in\n * `onStreamComplete`) goes on `req.state`, which every hook reaches\n * (`ctx.req.state` in the event hooks).\n */\nexport type AgentControllerHooks<Body extends object = object, Ctx = AgentContext> = {\n authorizeRequest?: (\n req: HttpRequest<any, any>,\n params: AuthorizeRequestParams<Body>,\n ) => void | Promise<void>;\n runOwner?: (req: HttpRequest<any, any>) => string | null | Promise<string | null>;\n runLimitKey?: (\n req: HttpRequest<any, any>,\n params: { owner: string | null; threadId?: string },\n ) => string | null | Promise<string | null>;\n busyPolicy?: (\n req: HttpRequest<any, any>,\n params: BusyPolicyParams<Body>,\n ) => AgentTurnBusyPolicy | Promise<AgentTurnBusyPolicy>;\n maxThreadRuns?: (\n req: HttpRequest<any, any>,\n params: { threadId: string; owner: string | null; body: Body },\n ) => ThreadRunLimit | Promise<ThreadRunLimit>;\n instructions?: (\n req: HttpRequest<any, any>,\n extra: { body: Body },\n ) => string | Promise<string> | void;\n reasoning?: (\n req: HttpRequest<any, any>,\n extra: { body: Body },\n ) => ReasoningEffort | void | Promise<ReasoningEffort | void>;\n skills?: (\n req: HttpRequest<any, any>,\n extra: { body: Body },\n ) => readonly SkillDefinition[] | void | Promise<readonly SkillDefinition[] | void>;\n runTools?: (\n req: HttpRequest<any, any>,\n extra: { body: Body; context: Ctx },\n ) => AgentRunTools | void | Promise<AgentRunTools | void>;\n usageLimits?: (\n req: HttpRequest<any, any>,\n extra: { body: Body; context: Ctx },\n ) => AgentUsageLimits | void | Promise<AgentUsageLimits | void>;\n trailingContext?: (\n req: HttpRequest<any, any>,\n extra: { body: Body; context: Ctx },\n ) => string | void | Promise<string | void>;\n /** Builds the run's context. `Ctx` is the agents' (see `defineAgentHooks`). */\n context?: (req: HttpRequest<any, any>, extra: { body: Body }) => Ctx | Promise<Ctx>;\n memoryScopes?: (\n req: HttpRequest<any, any>,\n extra: { body: Body },\n ) => AgentMemoryScopes | Promise<AgentMemoryScopes>;\n prepareStep?: (\n step: PrepareStepContext<Ctx>,\n ctx: AgentHookContext,\n ) => PrepareStepResult | void | Promise<PrepareStepResult | void>;\n attachmentScope?: (\n req: HttpRequest<any, any>,\n threadId?: string,\n extra?: { body: Body },\n ) => AttachmentScope | null | Promise<AttachmentScope | null>;\n attachmentLimits?: (\n req: HttpRequest<any, any>,\n ) => AttachmentLimits | null | Promise<AttachmentLimits | null>;\n checkUpload?: (\n file: UploadCheckFile,\n req: HttpRequest<any, any>,\n ctx: UploadContext<Body>,\n ) => UploadRefusal | null | void | Promise<UploadRefusal | null | void>;\n attachmentDestination?: (\n file: File,\n req: HttpRequest<any, any>,\n extra?: UploadContext<Body>,\n ) => AttachmentDestination | Promise<AttachmentDestination>;\n attachmentRetention?: (\n req: HttpRequest<any, any>,\n params: AttachmentRetentionParams<Body>,\n ) => AttachmentRetention | null | Promise<AttachmentRetention | null>;\n onMessage?: (message: AgentMessage, ctx: AgentHookContext) => void | Promise<void>;\n onToolCall?: (\n call: { toolCallId: string; name: string; input: unknown },\n ctx: AgentHookContext,\n ) => void | Promise<void>;\n onToolResult?: (\n result: ToolResultPart,\n ctx: AgentHookContext,\n call: ToolResultCall,\n ) => void | Promise<void>;\n onAwaitingInput?: (pending: PendingToolCall[], ctx: AgentHookContext) => void | Promise<void>;\n redactError?: (error: AgentError, info: ErrorRedactionInfo, ctx: AgentHookContext) => AgentError;\n onError?: (error: AgentRunFailure, ctx: AgentHookContext) => void | Promise<void>;\n onProviderRetry?: (info: AgentProviderRetry, ctx: AgentHookContext) => void | Promise<void>;\n onStreamComplete?: (\n result: AgentRunResult<any, any>,\n ctx: AgentHookContext,\n ) => void | Promise<void>;\n reportHookFailure?: (error: unknown) => void;\n};\n\n/**\n * Types an `AgentControllerHooks` object for the `Body` its controllers take,\n * so each hook's parameters are typed without annotating them (#989). It\n * returns the object unchanged.\n *\n * ```ts\n * export const chatHooks = defineAgentHooks<{ pageId: string }>({\n * runOwner: (req) => teamOwner(req),\n * async onStreamComplete(result, ctx) {\n * await settle(result, ctx.req.state.get(charge));\n * },\n * });\n * ```\n *\n * A controller whose `Body` has at least these fields can use it.\n *\n * `Ctx` types a shared `context` hook (and `prepareStep`'s `step.context`) for\n * agents with a context of their own (#1019): `defineAgentHooks<PageBody,\n * PageContext>({ context: ... })`. It defaults to the app's `AgentContext`.\n * Hooks that build no context fit any controller, whatever its agent's.\n */\nexport function defineAgentHooks<Body extends object = object, Ctx = AgentContext>(\n hooks: AgentControllerHooks<Body, Ctx>,\n): AgentControllerHooks<Body, Ctx> {\n return hooks;\n}\n\nexport abstract class AgentController<\n A extends AnyAgent = AnyAgent,\n /**\n * The extra fields `useChat`'s `body` option sends with every turn, as they\n * arrive in `instructions()` and on `ctx.body`.\n *\n * Declaring it also types the client: `useChat` reads it back off the route\n * through `AgentRouteRPC`, so a `body` the controller does not expect is a\n * compile error at the call site rather than an `undefined` three layers\n * into a tool. It types the shape, not the contents — see `instructions`.\n *\n * Constrained to `object`, not `Record<string, unknown>`: an `interface` gets\n * no implicit index signature, so the tighter bound refused\n * `interface PageBody { pageId: string }` with a `TS2344` that names the\n * constraint and not the reason. An interface is how most apps write a request\n * shape, and turning that into a puzzle about `type` versus `interface` is a\n * poor first impression of the feature.\n */\n Body extends object = Record<string, unknown>,\n> extends ControllerBase {\n static kind = \"agent-controller\" as const;\n\n /**\n * `Body`, in a position nothing can shorten away.\n *\n * It has to appear on the instance type for `AgentRouteRPC` to infer it, and\n * `instructions`'s second parameter is not a safe place to leave that job:\n * TypeScript's parameter-wise inference stops at the shorter signature, so a\n * controller overriding `instructions(req)` — which is every override written\n * before this existed, since that was the only signature — supplied no\n * candidate and silently fell back to the open record. The client-side\n * checking then vanished on the most ordinary upgrade path, with nothing to\n * read.\n *\n * `declare` so it emits no field: there is no value here, only a type for\n * `infer B` to find. Optional and never assigned, so no subclass has to\n * mention it.\n */\n declare readonly [BODY]?: Body;\n\n /** The agent this controller serves. A property rather than a constructor\n * argument so `Router.agent(ChatController)` can take the class, matching how\n * every other controller is mounted. */\n abstract agent: A;\n\n /**\n * HOOKS SHARED WITH OTHER CONTROLLERS (#989), so an app's chats can share\n * their authorization, run owner, upload rules and billing without an\n * app-level base class between them and this one. Assign a module-level\n * object made with `defineAgentHooks`:\n *\n * export const chatHooks = defineAgentHooks<{ pageId: string }>({\n * authorizeRequest: (req, params) => authorizePage(req, params),\n * runOwner: (req) => teamOwner(req),\n * });\n *\n * class PageChatController extends AgentController<typeof pageAgent, PageBody> {\n * agent = pageAgent;\n * hooks = chatHooks;\n * }\n *\n * Each hook stands in for gemi's default of the method with the same name.\n * A method the controller overrides itself wins over the hook, and reaches\n * it with `super.method(...)`, exactly as it would reach a base class's.\n * Unset (the default), every method is gemi's own.\n *\n * Hooks of any `Ctx` are accepted, so a controller whose agent has a\n * context of its own (#1019) can share hooks that build none. Such a\n * controller builds its context in its own `context()`, which is checked\n * against the agent; a shared `context` hook is checked only against the\n * `Ctx` its `defineAgentHooks` names.\n */\n protected hooks?: AgentControllerHooks<Body, any>;\n\n /**\n * Defaults to the process-wide `MemoryAgentStore`.\n *\n * Whatever you put here, make it something that outlives the request: this\n * controller is constructed fresh for every call, so `store = new\n * MemoryAgentStore()` written here is an empty store on every turn and a\n * threaded conversation silently reads back nothing. Assign a module-level\n * instance, or a store whose state is somewhere else entirely.\n */\n store: AgentStore = defaultAgentStore;\n\n /**\n * THE STORE SCOPE OF THIS REQUEST (#1177): a tenant key (an organisation,\n * workspace or app id) that keeps the tenant's threads apart from every\n * other's. When it answers one, `stream` and `upload` use\n * `store.forScope(scope)` instead of `store`, so a thread of another scope\n * is a 404 like an unknown id, and `attach` and `watch` answer 404 for a\n * thread not in the scope (they carry no `body`: it is `{}` there). `null`\n * (the default) uses `store` as it is.\n *\n * ```ts\n * protected storeScope(req, { body }) {\n * return `org:${req.ctx().user.orgId}`;\n * }\n * ```\n *\n * Called once per request, before the store is first read, with the\n * client's `body` (the same unchecked claim `authorizeRequest()` gets): derive\n * the scope from the authenticated user where you can. Server-started turns\n * (`startTurn`, voice) come through here too, with the turn's `user` and\n * `body`; `startTurn({ scope })` passes one explicitly, which wins. The store\n * must implement `forScope` (`DatabaseAgentStore` and `MemoryAgentStore`\n * do); one that does not is an error.\n */\n protected storeScope(\n req: HttpRequest<any, any>,\n params: { body: Body },\n ): string | null | Promise<string | null> {\n void req;\n void params;\n return null;\n }\n\n /**\n * The scope this instance's `store` was bound to by its request, `null` for\n * an unscoped one, `undefined` before any. The scoped view lives on the\n * instance because everything a run does after the request (the journal,\n * the transcript, a queued turn) reads `this.store`. That is safe because\n * gemi builds a controller per request: the router, `startTurn` and the\n * voice bridge (which calls `startTurn`) all construct a fresh one.\n */\n private boundScope: string | null | undefined = undefined;\n\n /**\n * For the routes that do not read the store (`attach`, `watch`): whether\n * the thread is in this request's scope. Always true when the request has\n * none, so an unscoped controller still never consults the store there.\n */\n private async threadInScope(req: HttpRequest<any, any>, threadId: string): Promise<boolean> {\n // Neither route carries the app's `body`.\n await this.scopeStore(req, {} as Body);\n if (this.boundScope === null) return true;\n return (await this.store.loadThread(threadId)) !== null;\n }\n\n /**\n * Swaps `store` for its scoped view, once per request. An instance reused\n * for a request in another scope (app code calling `stream` twice on one\n * controller) is refused rather than handed the first request's view, or\n * left to rescope the store under a run that is still going.\n */\n private async scopeStore(req: HttpRequest<any, any>, body: Body): Promise<void> {\n const explicit = serverTurnScopes.get(req);\n const scope = explicit ?? (await this.storeScope(req, { body })) ?? null;\n if (this.boundScope !== undefined) {\n if (this.boundScope !== scope) {\n throw new Error(\n \"This AgentController instance already served a request in another store scope. Build a controller per request (the router and startTurn do).\",\n );\n }\n return;\n }\n if (scope !== null) this.store = scopedStore(this.store, scope);\n this.boundScope = scope;\n }\n\n /**\n * Defaults to the process-wide map. Overridable so a test — or an app running\n * two agents that must not see each other's runs — can hold its own; not so\n * that it can be moved off the process, which is not a thing that can be\n * done. See `MemoryLiveRuns`.\n */\n liveRuns: MemoryLiveRuns = defaultLiveRuns;\n\n /**\n * VOICE (#921): what `this.voice(Controller)` needs to run voice calls in\n * front of this agent. Absent, the voice routes answer 404. See\n * `VoiceConfig` and `docs/ai-voice.md`.\n */\n voice?: VoiceConfig<Body>;\n\n /**\n * Where voice sessions are recorded, so a `PATCH` or `DELETE` that lands on\n * another instance finds the call. Defaults to the process-wide\n * `MemoryVoiceSessionStore`: assign a shared one when more than one instance\n * serves the route.\n */\n voiceStore: VoiceSessionStore = defaultVoiceStore;\n\n /**\n * Where attachment *records* live — the row that says which bytes, whose, and\n * under what id. Defaults to the process-wide `MemoryAttachmentStore`, with\n * the same warning `store` carries: assign something that outlives the\n * request, because this controller is constructed per call.\n */\n attachments: AttachmentStore = defaultAttachmentStore;\n\n /**\n * Where an attachment's *bytes* live. Defaults to the app's configured\n * `FileStorage` through the `Storage` facade, which resolves the driver per\n * call out of the container — so an app that configured S3 gets S3 here\n * without saying so twice.\n *\n * Overridable mostly for tests and for an app that keeps user uploads in a\n * different bucket from everything else.\n */\n attachmentStorage: AttachmentStorage = Storage;\n\n /**\n * How long an attachment kept for a `\"turn\"` (`attachmentRetention`) may wait\n * for its turn (#1307). An upload no turn ever names, or one whose turn never\n * completed in this process, stops resolving after this and is deleted by\n * `sweepAttachments`. One hour by default.\n */\n turnAttachmentMaxAgeMs = 60 * 60 * 1000;\n\n /**\n * Who uploaded each provider file id (#443). `upload` records the id under\n * `runOwner(req)`, and `stream` refuses a turn whose files name an id\n * recorded for another owner with a 403 `{ error: { kind: \"permission\",\n * message, status } }`. Defaults to the process-wide `MemoryFileOwners`; the\n * same warning as `store` applies — assign something that outlives the\n * request. An app with several processes, or that wants the binding to\n * survive a restart, gives it a table (see `FileOwners`).\n */\n fileOwners: FileOwners = defaultFileOwners;\n\n /**\n * Where the nonce of each answered approval or question is spent, which is\n * what makes a signed answer single-use (#445). On a stateless chat the\n * client carries its history and can rewind it to before a result existed;\n * the spent nonce is then the only thing that refuses the replayed answer.\n *\n * Defaults to the process-wide `MemoryNonceStore`, which is exact for one\n * instance and forgets on restart. An app running several instances (or\n * behind a load balancer whose affinity is best effort) assigns a shared\n * store, built once at module scope like `store`:\n *\n * const nonces = new RedisNonceStore();\n * class ChatController extends AgentController<typeof chat> {\n * nonces = nonces;\n * }\n *\n * or its own `NonceStore` over a table keyed by the nonce. In production a\n * stateless turn served with the in-memory default logs a warning once.\n */\n nonces: NonceStore = defaultNonceStore;\n\n /**\n * Where approved tools' executions are claimed and their results recorded,\n * so that an approval runs its tool at most once (#458). Off by default.\n *\n * The nonce makes an answer single-use; it does not remember what the tool\n * did. So a retried submit whose response was lost is refused (\"already\n * used\") although the tool acted, and an answer that reaches two instances\n * with unshared nonce stores runs the tool twice. With a receipt store the\n * first presentation claims the execution and records its result; a later\n * one gets that result back without running anything, and one that arrives\n * while the first is still running gets a `tool_error` result for the model.\n *\n * Assign one built at module scope, like `nonces`, shared by every instance:\n *\n * const receipts = new RedisReceiptStore();\n * class ChatController extends AgentController<typeof chat> {\n * receipts = receipts;\n * }\n *\n * or your own `ReceiptStore` over a table (see `store/Receipts.ts`).\n * `MemoryReceiptStore` is exact for one instance only.\n */\n receipts?: ReceiptStore;\n\n /**\n * Whether a turn may name a provider file id that `fileOwners` has no record\n * of. `false` by default, which is what keeps the change additive: an id\n * uploaded before the upgrade, before a restart (with the in-memory default),\n * on another process, or by the app outside `upload` still works, as every id\n * did before. An id that IS recorded for someone else is refused either way.\n *\n * Set it to `true` once `fileOwners` is durable and shared, to make the\n * binding complete: then an id is usable only by the owner it was recorded\n * for, or by anyone when it was recorded as anonymous. On a stateless chat\n * the client carries its history, so this also refuses a file a tool attached\n * earlier in the conversation; a strict app keeps its chats on a thread.\n */\n protected requireKnownFiles = false;\n\n /**\n * How long the request that started a run is held open for its hooks, in\n * milliseconds, once the run has settled. The run itself is not bounded\n * here — the request is held for as long as it runs — only the app's code\n * still going after it, from `onMessage` to an `onAwaitingInput` queued\n * behind a slow `onToolCall`.\n *\n * The hooks read the user from that request (`ctx.req.ctx().user`,\n * `Auth.user()`, a policied query), so the request stays open until they are\n * done; but a hook that never settles — a `fetch` with no timeout — would\n * then hold the store, the user and `onRequestEnd` forever, one per turn. Past\n * this the request ends anyway: `onRequestEnd` runs, the user is released,\n * and the hook runs on without one. Thirty seconds is far past a healthy\n * write or notification, so a hook that reaches it is hung rather than slow.\n * Raise it for a hook that is legitimately longer; `Infinity` holds the\n * request until the hooks are done, however long that is.\n */\n protected hookHoldMs = 30_000;\n\n /**\n * Appended to the agent's static instructions for this request — the user's\n * name, tenant, today's date.\n *\n * `body` is what `useChat`'s `body` option sent, with the four keys the wire\n * format owns removed. It is the only way to read it here: this controller\n * consumes the request body itself, so `await req.input()` answers `Body\n * already used` and takes the whole turn down with it.\n *\n * It is client-controlled, exactly like any request body. `Body` types what\n * arrives, it does not check it — a client can send anything, and a tenant id\n * read from here is the client's claim about which tenant it wants, not the\n * middleware's finding about who it is.\n */\n instructions(req: HttpRequest<any, any>, extra: { body: Body }): string | Promise<string> | void {\n return this.hooks?.instructions?.(req, extra);\n }\n\n /**\n * The reasoning effort for this turn's run (#975), when it should differ\n * from the agent's: a turn the app knows is small, say. Answer nothing to\n * keep the agent's. `prepareStep` can still change it for one model call,\n * and sees this as `step.reasoning`.\n *\n * protected reasoning(req, { body }) {\n * return body.selection ? \"low\" : undefined;\n * }\n *\n * Called once per turn, after `authorizeRequest()`, beside `instructions()`.\n * `body` is client-controlled, as there.\n */\n protected reasoning(\n req: HttpRequest<any, any>,\n extra: { body: Body },\n ): ReasoningEffort | void | Promise<ReasoningEffort | void> {\n return this.hooks?.reasoning?.(req, extra);\n }\n\n /**\n * Skills for this turn's run only (#950), beside the agent's own: the\n * designer's pack of the page being edited, when one agent serves every\n * page. Lowered like the agent's skills, so the model sees each one's name\n * and description and loads the body when it needs it, instead of the whole\n * pack riding in `instructions()` on every turn.\n *\n * protected async skills(req, { body }) {\n * const page = await Page.find(body.pageId); // authorized in authorizeRequest()\n * return page.skillPacks.map((pack) =>\n * Skill.create({ name: pack.slug, description: pack.summary, instructions: () => pack.body() }),\n * );\n * }\n *\n * Called once per turn, after `authorizeRequest()`, beside `instructions()`.\n * Answer nothing for none. A name already used by one of the agent's tools\n * or skills fails the turn. `body` is client-controlled, as there.\n */\n protected skills(\n req: HttpRequest<any, any>,\n extra: { body: Body },\n ): readonly SkillDefinition[] | void | Promise<readonly SkillDefinition[] | void> {\n return this.hooks?.skills?.(req, extra);\n }\n\n /**\n * THE TURN'S TOOLS (#1123): tools added to the agent's for this run, and\n * which of them the model is offered, decided per turn from the request and\n * the run's context.\n *\n * ```ts\n * protected async runTools(req, { context }) {\n * const tenant = context.tenant;\n * return {\n * // The tenant's own tools, built from its configuration.\n * tools: tenant.integrations.map((integration) => integrationTool(integration)),\n * // A feature that is off is not offered at all.\n * activeTools: tenant.billingEnabled ? undefined : everythingBut(\"billing\"),\n * };\n * }\n * ```\n *\n * Called once per turn, after `context()` (whose answer it is handed) and\n * before anything is asked of the model, on turns from `useChat`,\n * `startTurn` and voice alike. Answer nothing for the agent's own tools,\n * all offered: the default. A name that clashes with the agent's, or an\n * `activeTools` entry naming no tool, fails the turn. A turn that answers a\n * pending call of a run tool has to return that tool again. `body` is\n * client-controlled, as in `instructions()`.\n */\n protected runTools(\n req: HttpRequest<any, any>,\n extra: { body: Body; context: ContextOf<A> },\n ): AgentRunTools | void | Promise<AgentRunTools | void> {\n return this.hooks?.runTools?.(req, extra);\n }\n\n /**\n * TEXT AFTER THE CONVERSATION (#1345): what the model should know on this\n * turn that is not part of it (the screen the person is on, the time, a\n * small note on the app's state), sent after the last message on every\n * model call of the run.\n *\n * ```ts\n * protected trailingContext(req, { body }) {\n * return `The person is looking at the page \"${body.pageTitle}\".`;\n * }\n * ```\n *\n * Unlike `instructions()`, it is not part of the prompt the provider\n * caches, so it can change on every turn without a cache miss; and unlike a\n * message, it is never stored, so the thread does not fill up with notes.\n * Called once per turn, after `context()`, on turns from `useChat`,\n * `startTurn` and voice alike. Answer nothing to send none (the default).\n * `prepareStep` can change it for one call\n * (`PrepareStepResult.trailingContext`). `body` is client-controlled, as\n * in `instructions()`: treat it as what the client says, not as fact.\n */\n protected trailingContext(\n req: HttpRequest<any, any>,\n extra: { body: Body; context: ContextOf<A> },\n ): string | void | Promise<string | void> {\n return this.hooks?.trailingContext?.(req, extra);\n }\n\n /**\n * THE TURN'S USAGE LIMITS (#1124): budgets on what its run may spend, its\n * own and shared ones under keys this decides (the user, the tenant, the\n * month), and `onUsage` to hear what was spent.\n *\n * ```ts\n * protected usageLimits(req, { context }) {\n * const month = new Date().toISOString().slice(0, 7);\n * return {\n * run: { tokens: 200_000, toolCalls: 50 },\n * scopes: [{ key: `tenant:${context.tenantId}:${month}`, limit: { tokens: 5_000_000 } }],\n * store: this.usageStore, // shared across instances\n * onUsage: (report) => Billing.record(context.tenantId, report.delta.tokens),\n * };\n * }\n * ```\n *\n * Called once per turn, after `context()` (whose answer it is handed), on\n * turns from `useChat`, `startTurn` and voice alike. A run over a limit\n * ends with the error code `\"usage_limit\"` (`onError` and `result().error`\n * carry `usageLimit`, which says which limit); a scope already spent ends\n * the turn before the model is called. Answer nothing for no limits: the\n * default. See `AgentUsageLimits`.\n */\n protected usageLimits(\n req: HttpRequest<any, any>,\n extra: { body: Body; context: ContextOf<A> },\n ): AgentUsageLimits | void | Promise<AgentUsageLimits | void> {\n return this.hooks?.usageLimits?.(req, extra);\n }\n\n /**\n * What every tool of this turn's run gets as `ctx.context` — the user, the\n * tenant, functions the tools call back into. See `AgentContext`.\n *\n * TYPED BY THE AGENT (#1019): it returns `ContextOf<A>`, the context the\n * agent declares (`withContext`), or what its tools need. A field or a\n * function the agent needs and this leaves out is a compile error on the\n * override. This is where the controller's injected services become the\n * functions the tools call:\n *\n * ```ts\n * constructor(private pages = PageEditor.inject()) { super(); }\n *\n * context(req, { body }) {\n * return {\n * pageId: body.pageId,\n * edit: (instruction: string) => this.pages.edit(body.pageId, instruction),\n * };\n * }\n * ```\n *\n * The same method builds the context of a chat turn, a `startTurn`, and a\n * voice call's delegated turns, so all of them are typed by it.\n *\n * The run is not given the request, so this is where the request's facts\n * become the run's: read the user the middleware authenticated here, and a\n * tool reads it from `ctx.context` instead of reaching for `req`. Runs after\n * `authorizeRequest()`, once per turn, and before anything is asked of the\n * model.\n *\n * The default is `{}`. An agent whose context has a required field needs\n * this overridden (or a `context` hook): TypeScript cannot make an inherited\n * method abstract for some agents only, so not overriding it at all is a\n * tool that finds the field missing, not a compile error. What an override\n * returns is checked.\n *\n * Values from `body` are the client's claim, exactly as in `instructions()`;\n * putting one here does not make it any more trustworthy, only easier to\n * mistake for something the server decided.\n */\n context(\n req: HttpRequest<any, any>,\n extra: { body: Body },\n ): ContextOf<A> | Promise<ContextOf<A>> {\n const hook = this.hooks?.context;\n if (hook) return hook(req, extra);\n return {} as ContextOf<A>;\n }\n\n /**\n * THE MEMORY SCOPES THIS TURN MAY USE (#936): the labels the agent declares\n * in `memory.scopes`, each resolved to the app's scope key for this caller.\n *\n * ```ts\n * protected async memoryScopes(req, { body }) {\n * const user = req.ctx().user;\n * const project = await Project.forPage(body.pageId); // authorized in authorizeRequest()\n * return {\n * project: project.memoryOff ? null : `project:${project.publicId}`,\n * user: user && !user.memoryOff ? `user:${user.publicId}` : null,\n * };\n * }\n * ```\n *\n * The model only ever names a label; the key is decided here, on the\n * server, from the request — the same defence `attachmentScope()` gives\n * attachments. A label answered with `null`, or left out, is OFF for the\n * turn: it is not in the `<memory>` block and the tools cannot name it, so\n * a per-account or per-project \"memory off\" switch is a `null` here. A\n * declared `thread` label is the turn's thread (`thread:<threadId>`) unless\n * this answers it.\n *\n * Runs after `authorizeRequest()` and `context()`, once per turn, on turns\n * from `useChat`, `startTurn` and voice alike. The default is `{}`: memory\n * stays off until a controller resolves something. Not called for an agent\n * without `memory`. Values read from `body` are the client's claim, as in\n * `context()`: check them (in `authorizeRequest()` or here) before turning\n * one into a key.\n */\n protected memoryScopes(\n req: HttpRequest<any, any>,\n extra: { body: Body },\n ): AgentMemoryScopes | Promise<AgentMemoryScopes> {\n const hook = this.hooks?.memoryScopes;\n if (hook) return hook(req, extra);\n return {};\n }\n\n /**\n * The `<memory>` block's budget, in tokens, for this controller's turns.\n * `undefined` (the default) uses the agent's `memory.maxTokens` (1,500\n * unless it says otherwise); `0` leaves the block out.\n */\n protected memoryMaxTokens: number | undefined = undefined;\n\n /**\n * Refuse a turn that arrives without a `threadId`, with a 400\n * `thread_required`, before anything runs.\n *\n * A stateless turn is otherwise open to any caller the route's middleware\n * lets through: the client carries the history, so the model runs, and is\n * billed, as a general-purpose chat. An app whose tools resolve their subject\n * from the thread can make them refuse such a turn, but the model has still\n * been paid for by then.\n *\n * It governs `stream` only. `upload` can still reach the provider without a\n * thread (a `provider` destination); refuse that in `authorizeRequest`.\n */\n protected requireThread = false;\n\n /**\n * The largest JSON body `stream` reads, in bytes (#444). Default 4 MB.\n *\n * A turn is a few kilobytes; even a long stateless chat carrying its whole\n * history is well under a megabyte, since files travel by id and not inline.\n * Without a cap the route read whatever arrived (the production server\n * accepts up to 10 GB), parsed it, and sent it to the provider at the app's\n * expense. A body over it is refused with a 413 `{ error: { kind, message,\n * status, code: \"body_too_large\" } }` before it is parsed, and before\n * `authorizeRequest`. Checked against `Content-Length` when there is one and\n * against the bytes read otherwise, so a chunked body cannot get past it.\n * `attach` and `stop` carry only ids and are held to 64 KB. `Infinity` turns\n * it off.\n */\n protected maxBodyBytes = DEFAULT_MAX_BODY_BYTES;\n\n /**\n * The most messages a stateless turn's client-carried history may hold\n * (#444). Default 1000. A longer one is a 413 `history_too_long` before\n * anything runs. Only `body.messages` counts: a threaded turn reads its\n * history from the store, which the client does not write. Every message is\n * sent to the model on every step, so this bounds what one turn can be billed\n * for as much as `maxBodyBytes` does. `Infinity` turns it off.\n */\n protected maxHistoryMessages = DEFAULT_MAX_HISTORY_MESSAGES;\n\n /**\n * Bounds what each model call of this controller's turns is sent (#473):\n * the latest turns of the thread that fit, cut at a turn start, the cut\n * moving `step` turns at a time so the prompt cache keeps hitting. See\n * `ContextWindowOptions`. `undefined` (the default) uses the agent's own\n * `contextWindow`, if it has one; `false` sends the whole history.\n *\n * The store is untouched: `loadThread` still answers the whole thread, every\n * message is still appended, and `readThread` shows all of it. Unlike\n * `maxHistoryMessages`, which refuses a stateless turn, this applies to\n * threaded and stateless turns alike and refuses nothing.\n *\n * protected contextWindow = { maxTurns: 40, maxTokens: 100_000 };\n */\n protected contextWindow: ContextWindowOptions | false | undefined = undefined;\n\n /**\n * Called before every model call of a turn's run, after the agent's own\n * `prepareStep`, with the request it hands over (`step.messages`,\n * `step.instructions`) and the turn's hook context. Answer `{ messages }`,\n * `{ instructions }`, `{ reasoning }` or `{ maxOutputTokens }` to send\n * something else for that call alone; nothing answered is stored. Not called for a sub-agent's model calls.\n *\n * protected prepareStep(step: PrepareStepContext) {\n * return { messages: windowMessages(step.history, { maxTurns: 20 }).messages };\n * }\n */\n protected prepareStep(\n step: PrepareStepContext<ContextOf<A>>,\n ctx: AgentHookContext,\n ): PrepareStepResult | void | Promise<PrepareStepResult | void> {\n return this.hooks?.prepareStep?.(step, ctx);\n }\n\n /**\n * How many runs one caller may have going at once in this process (#444).\n * Default 5. A run outlives the request that started it (so `attach` can\n * find it), which means a client can post a turn and disconnect and the run\n * still bills up to `maxSteps` model calls; without a cap, a thousand posts\n * were a thousand runs.\n *\n * Counted per `runLimitKey` (by default `runOwner`, the authenticated user),\n * and per conversation rather than per request: every turn on one thread is\n * one slot, because a new turn there supersedes, joins or waits for the run\n * going rather than adding to it. So a user resending mid-answer is never\n * refused; a user with five chats answering at once and starting a sixth\n * is, with a 429 `{ error: { kind: \"rate_limit\", message, status, code:\n * \"too_many_runs\" } }`, after `authorizeRequest` and before the model is\n * asked anything. The exception is a parallel run (`ifBusy: \"parallel\"`),\n * which adds a run to the thread and takes a slot of its own; how many one\n * thread may have going is `maxThreadRuns`. A slot is freed when the run\n * ends (stopped, timed out, or finished). `Infinity` turns it off.\n */\n protected maxConcurrentRuns = DEFAULT_MAX_CONCURRENT_RUNS;\n\n /**\n * How many runs one thread may have going at once, with parallel turns\n * (`ifBusy: \"parallel\"`). Asked per turn, so it can differ per thread (a\n * plan, a kind of conversation): default `DEFAULT_MAX_THREAD_RUNS` (3). A\n * parallel turn on a thread that already has this many going is refused\n * with a 429 `too_many_runs` before anything runs; `busyPolicy` sees\n * `running.length` and can join instead. Answer `{ max, overflow: \"queue\" }`\n * to hold such a turn until one of the runs ends instead (#1339), as a\n * queued turn waits: it then starts as one more parallel run. Only parallel\n * turns are counted here: the other policies never add a run to the thread.\n */\n protected maxThreadRuns(\n req: HttpRequest<any, any>,\n params: { threadId: string; owner: string | null; body: Body },\n ): ThreadRunLimit | Promise<ThreadRunLimit> {\n const hook = this.hooks?.maxThreadRuns;\n if (hook) return hook(req, params);\n return DEFAULT_MAX_THREAD_RUNS;\n }\n\n /**\n * What a turn does on a thread that already has a run going (see\n * `AgentTurnBusyPolicy`): asked under the thread's lock, after\n * `authorizeRequest`, for every turn that finds the thread busy, a client's\n * and `startTurn`'s alike. Not asked on a free thread, nor for a regenerate,\n * which always supersedes.\n *\n * `requested` is what the turn asked for (the client's `ifBusy`, or\n * `startTurn`'s), and the default answers it, `\"supersede\"` when it asked\n * nothing. `running` lists the runs going, oldest first, with what started\n * each and what joined it, so an app can decide by what the new message is\n * about:\n *\n * protected async busyPolicy(req: HttpRequest, { running, turn }: BusyPolicyParams) {\n * const current = running.at(-1)!;\n * return (await sameTopic(current.turn.text, turn?.text)) ? \"join\" : \"parallel\";\n * }\n *\n * A client sends `ifBusy` only when asked (`useChat`'s `ifBusy` option), and\n * a client that asks for anything but `\"supersede\"` leaves the running\n * reply alone itself, so whatever this answers is what it shows.\n */\n protected busyPolicy(\n req: HttpRequest<any, any>,\n params: BusyPolicyParams<Body>,\n ): AgentTurnBusyPolicy | Promise<AgentTurnBusyPolicy> {\n const hook = this.hooks?.busyPolicy;\n if (hook) return hook(req, params);\n return params.requested ?? \"supersede\";\n }\n\n /**\n * Who `maxConcurrentRuns` counts a turn against (#444). The default is\n * `runOwner`'s answer, the authenticated user; `null` is not counted.\n *\n * An anonymous turn is therefore not limited by default, because there is\n * nothing sound to count it under: a client address is the proxy's unless\n * `GEMI_TRUST_PROXY` is set, which would put every visitor in one bucket, and\n * the session cookie is the visitor's to drop. An app that serves anonymous\n * chats returns its own key here (`ip:${clientAddress(req)}` behind a trusted\n * proxy, say), sets `requireThread`, or puts `RateLimitMiddleware` on the\n * route.\n */\n protected runLimitKey(\n req: HttpRequest<any, any>,\n params: { owner: string | null; threadId?: string },\n ): string | null | Promise<string | null> {\n const hook = this.hooks?.runLimitKey;\n if (hook) return hook(req, params);\n return params.owner;\n }\n\n /**\n * Decides whether this caller may use this route, on every one of the four:\n * `stream`, `attach`, `stop` and `upload` (#542). Throw a request breaker\n * (`InsufficientPermissionsError`, say) to refuse; return to let it through.\n *\n * It runs before the route does any work of its own: on `stream`, ahead of\n * the thread's lock and load, `instructions()` and the provider, so a refused\n * turn is not charged for, waits behind no run and does not learn whether its\n * thread exists; on `attach`, before a live run's frames are read.\n *\n * `threadId` is the one the client sent, taken on trust and not yet checked\n * against the store — which is what makes this the place to check that the\n * caller owns it. A thread-scoped app that checks it here on every route\n * keeps a thread's live answer, its stop button and its attachments to its\n * owner. It is `undefined` when the request names no thread: a stateless\n * turn, an upload without one, a stop by `runId` or `clientRunId`.\n *\n * `body` is the client's `body` option — the same object `instructions()`,\n * `context()` and `attachmentScope()` get — on the two routes that carry it,\n * `stream` and `upload` (#603). A chat with no thread and no user names its\n * subject there (a page id, say), and this is where to check that the caller\n * may touch it. `attach` and `stop` carry no body, so it is absent on them;\n * narrow on `route` to read it. Like `threadId` it is the client's claim,\n * unchecked.\n *\n * THE DEFAULT CHECKS `resource`, when there is one, and lets everything\n * through otherwise. An override that also wants it calls\n * `super.authorizeRequest(req, params)`.\n */\n protected authorizeRequest(\n req: HttpRequest<any, any>,\n params: AuthorizeRequestParams<Body>,\n ): void | Promise<void> {\n const hook = this.hooks?.authorizeRequest;\n if (hook) return hook(req, params);\n return this.resource?.authorize(req, params);\n }\n\n /**\n * THE RESOURCE THIS CHAT IS ABOUT, checked on every route by the default\n * `authorizeRequest` (#726): a resource policy's `forAgent`, which names the\n * resource's id in the `body` and the resource a thread belongs to.\n *\n * ```ts\n * resource = PagePolicy.forAgent({\n * body: (body: PageBody) => body.pageId,\n * thread: (threadId) => ChatThread.pageIdOf(threadId),\n * });\n * ```\n *\n * `stream` and `upload` are refused unless the caller may use the resource\n * the body names, and, when they name a thread, unless it is that\n * resource's. `attach` and `stop` are refused unless the caller may use the\n * thread's resource. A refusal is the policy's (a 404 by default), the same\n * for a resource or thread that does not exist. A live run still answers\n * only its `runOwner`.\n */\n protected resource?: AgentResource<Body>;\n\n /**\n * WHO OWNS A RUN THIS REQUEST STARTS, and who a request to `attach` or `stop`\n * one is (#442). An opaque key, compared with `===`; `null` is nobody.\n *\n * `stream` records it on the run, and from then on the run answers only that\n * key: `attach` to it, `stop` of it (by `runId`, `threadId` or `clientRunId`,\n * including a turn still waiting its place), and a turn on its thread that\n * would supersede it while it is still going are each refused with a 403\n * `{ error: { kind: \"permission\", message, status } }` for any other caller.\n * That holds whatever `authorizeRequest` says, which is the point: every\n * handle on a run is one a third party can come to hold (a shared link, a\n * log line, a guessable `clientRunId`), and none of them says whose it is.\n *\n * THE DEFAULT IS THE AUTHENTICATED USER, `user:<id>`, and `null` without one.\n * A `null` owner records an unowned run, which answers whoever holds a\n * handle — exactly what every run did before this existed. So:\n *\n * - an anonymous turn starts an unowned run; its `threadId` stays the\n * capability. `sessionId()` is not used as a fallback: it is a cookie the\n * visitor writes, it can be minted between the turn and the reattach (a\n * view visited in between), and a mismatch would lock a visitor out of\n * their own run. An app with its own anonymous identity returns it here.\n * - a run started by an authenticated user cannot be read or stopped by an\n * anonymous request, nor by another user.\n * - a run the server starts itself (registered on `liveRuns` with no\n * `owner`) is unowned.\n *\n * Override it for anything wider than a user — a thread shared by a team\n * returns `team:<id>` (from the user, never from the body) — or `null` to\n * turn the check off. Whatever it reads must be present on all of `stream`,\n * `attach` and `stop`, the same rule `attachmentScope` states: guard the three\n * routes with the same middleware.\n *\n * It is also the `subject` every pending call of the run is signed for\n * (#447): an approval or answer is accepted only on a turn whose `runOwner`\n * is the one the question was asked of. So it must answer the same on the\n * turn that asks and the turn that answers.\n */\n protected runOwner(req: HttpRequest<any, any>): string | null | Promise<string | null> {\n const hook = this.hooks?.runOwner;\n if (hook) return hook(req);\n const user = req.ctx?.()?.user;\n const userId = user?.id ?? user?.publicId;\n if (userId !== undefined && userId !== null && String(userId) !== \"\") {\n return `user:${String(userId)}`;\n }\n return null;\n }\n\n /**\n * STARTS A TURN FROM SERVER CODE (#839): a queue job, a command, an MCP\n * tool, a webhook. No browser and no route: the turn goes through this\n * controller's `stream` as a `useChat` turn would, on a request built here,\n * so the agent, the store, `authorizeRequest` and `resource`, `runOwner`,\n * `maxConcurrentRuns`, the thread's lock, `instructions()`, `context()`,\n * the hooks and the tools' `ctx` (`threadId`, `ctx.jobs`, `ctx.generate`)\n * are the same as for a turn from the chat.\n *\n * ```ts\n * const turn = await ChatController.startTurn({\n * threadId,\n * text: \"Make the hero darker\",\n * user, // req.ctx().user for the turn\n * body: { siteId }, // what useChat's `body` option would send\n * });\n * const { text, finishReason, pending } = await turn.result();\n * ```\n *\n * The route's middleware does not run: the caller is server code and names\n * the user itself (`null` or absent is an anonymous turn). A turn the route\n * would refuse throws an `AgentTurnError` with the status and code it would\n * have answered; a request breaker thrown by `authorizeRequest` is thrown\n * as it is.\n *\n * The run lives in the process that called this, like every run. From a\n * queue job, await `result()` so the worker does not move on without it.\n *\n * On a thread that already has a run going, the turn supersedes it, as a\n * resend from the chat does. Server code reacting to an event usually\n * should not cut off the answer a person is reading: pass\n * `ifBusy: \"queue\"` to start after it instead, `\"join\"` to hand the running\n * turn the message (or event) to read at its next step, `\"parallel\"` to\n * run beside it, or `\"skip\"` to start nothing (answered\n * `{ skipped: true }`). See `AgentTurnBusyPolicy`; the controller's\n * `busyPolicy` decides, and answers `ifBusy` by default. A queued turn's\n * `startTurn` settles once the turn has started; a joined one's at once,\n * with `joined: true` and the running run as `run`.\n */\n static startTurn<C extends AgentController<any, any>>(\n this: new () => C,\n params: AgentTurnParams<ControllerBody<C>> & { ifBusy: \"skip\" },\n ): Promise<AgentTurn | AgentTurnSkipped>;\n static startTurn<C extends AgentController<any, any>>(\n this: new () => C,\n params: AgentTurnParams<ControllerBody<C>> & {\n ifBusy?: \"supersede\" | \"queue\" | \"join\" | \"parallel\";\n },\n ): Promise<AgentTurn>;\n static startTurn<C extends AgentController<any, any>>(\n this: new () => C,\n params: AgentTurnParams<ControllerBody<C>>,\n ): Promise<AgentTurn | AgentTurnSkipped>;\n static async startTurn<C extends AgentController<any, any>>(\n this: new () => C,\n params: AgentTurnParams<ControllerBody<C>>,\n ): Promise<AgentTurn | AgentTurnSkipped> {\n const { threadId } = params;\n if (typeof threadId !== \"string\" || threadId === \"\") {\n throw new TypeError(\n \"AgentController.startTurn needs a `threadId`: a server turn is stored on a thread. Create one with the store's `createThread`.\",\n );\n }\n const ifBusy = params.ifBusy;\n if (ifBusy !== undefined && !BUSY_POLICIES.includes(ifBusy)) {\n throw new TypeError(\n `AgentController.startTurn's \\`ifBusy\\` is \"supersede\", \"queue\", \"join\", \"parallel\" or \"skip\"; got ${JSON.stringify(params.ifBusy)}.`,\n );\n }\n const event = params.event === undefined ? undefined : checkTurnEvent(params);\n const turn: ClientTurn = {\n ...params.turn,\n ...(params.text !== undefined ? { text: params.text } : {}),\n };\n // The app's fields first, so none of them can take the place of the\n // envelope's.\n const payload = { ...(params.body as object | undefined), threadId, turn };\n const req = new HttpRequest<any, any>(\n new Request(SERVER_TURN_URL, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(payload),\n }),\n {},\n \"api\",\n new URL(SERVER_TURN_URL).pathname,\n );\n const controller = new this();\n // Marks the request as `startTurn`'s, so only its run is kept here.\n serverTurns.set(req, null);\n if (params.scope !== undefined) serverTurnScopes.set(req, params.scope);\n if (ifBusy !== undefined) busyPolicies.set(req, ifBusy);\n if (event) serverEvents.set(req, event);\n // A request scope of its own, carrying the caller's user, whether or not\n // this is called from inside another request: the run is not that\n // request's, and must not end with it or read its user.\n const response = await RequestContext.run(req, () => controller.stream(req), {\n user: params.user ?? null,\n });\n\n const joined = serverJoins.get(req);\n const started = serverTurns.get(req);\n if (!started && !joined) {\n const error = await AgentTurnError.from(response);\n if (ifBusy === \"skip\" && error.code === THREAD_BUSY) {\n return { skipped: true, threadId };\n }\n throw error;\n }\n serverTurns.delete(req);\n serverJoins.delete(req);\n // Nobody reads the stream; the run goes on without it (see `toResponse`).\n response.body?.cancel().catch(noop);\n\n if (joined) return joinedServerTurn(threadId, joined);\n\n const { run, hooks } = started!;\n return serverTurnHandle(threadId, run, hooks);\n }\n\n /**\n * `POST /<path>` — one route for every client turn. A first message, an\n * approval, an answer to a question and a client tool's result are all just\n * the next turn, so none of them gets an endpoint of its own.\n */\n async stream(req: HttpRequest<any, any> = new HttpRequest()): Promise<Response> {\n const parsed = await readJsonBody(req, this.maxBodyBytes);\n if (parsed.error) {\n // Before anything is registered or charged for. A run started off a body\n // we could not read would answer nothing, at the user's expense.\n return invalidRequest(parsed);\n }\n const body = parsed.body;\n const threadId = typeof body.threadId === \"string\" ? body.threadId : undefined;\n const parsedTurn = toClientTurn(body);\n if (parsedTurn.error) {\n return invalidRequest({ body: {}, error: parsedTurn.error });\n }\n // Reassigned by a regenerate: the turn run again is the one the store holds.\n let turn = parsedTurn.turn;\n // Replace the thread's last answer rather than answer after it (#451). Only\n // meaningful on a thread: a stateless client trims its own history.\n const regenerate = threadId !== undefined && body.regenerate === true;\n const clientRunId = typeof body.clientRunId === \"string\" ? body.clientRunId : undefined;\n // What the turn asks to do on a busy thread: `startTurn`'s, or the\n // client's `ifBusy`. `busyPolicy` has the last word. See `withThread`.\n let requested: AgentTurnBusyPolicy | undefined = busyPolicies.get(req);\n if (!serverTurns.has(req) && body.ifBusy !== undefined) {\n if (!CLIENT_BUSY_POLICIES.includes(body.ifBusy)) {\n return invalidRequest({\n body: {},\n error: `\\`ifBusy\\` is \"supersede\", \"queue\", \"join\" or \"parallel\"; got ${JSON.stringify(body.ifBusy)}.`,\n });\n }\n requested = body.ifBusy as AgentClientBusyPolicy;\n }\n // The app's fields, separated once and handed to every method that reads\n // them — `authorizeRequest`, `instructions`, `context`, `attachmentScope` —\n // so none of them can disagree about what the client sent. They cannot read\n // it themselves: `readJsonBody` has consumed the request's body by now.\n const extraBody = appBody<Body>(body);\n\n // Before `pendingTurns`, so a refused turn leaves nothing for `/stop` to\n // find. It does not yield, unlike `authorizeRequest` below.\n if (this.requireThread && !threadId) {\n return jsonResponse(400, {\n code: \"thread_required\",\n message: \"This agent takes a turn only on a thread: send a threadId.\",\n });\n }\n\n // Before the first read of the store: every one below is inside the scope.\n await this.scopeStore(req, extraBody);\n\n if (regenerate && !this.store.removeMessages) {\n return jsonResponse(501, {\n code: \"regenerate_unsupported\",\n message:\n \"This agent's store cannot remove messages, so a thread's answer cannot be regenerated. Implement `removeMessages` on the AgentStore.\",\n });\n }\n\n // The client's history is the only part of a stateless turn whose size the\n // client chooses and the model is billed for on every step (#444). A\n // threaded turn's `messages` are ignored, so they are not counted.\n if (\n !threadId &&\n Array.isArray(body.messages) &&\n body.messages.length > this.maxHistoryMessages\n ) {\n return limitResponse(\n 413,\n \"history_too_long\",\n `The conversation has ${body.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`,\n );\n }\n\n // Who this run will belong to. Read before `pending` exists, so a stop that\n // finds the pending turn can already be checked against it. See `runOwner`.\n const owner = await this.runOwner(req);\n\n // From here until `register`, the only thing `/stop` can find this turn by.\n // See `pendingTurns`.\n const pending = clientRunId ? { cancelled: false, owner } : null;\n if (pending) {\n pendingTurns.set(clientRunId, pending);\n }\n\n // The whole of the stateless/threaded difference, in one expression: with a\n // thread the server owns the history, without one the client carries it.\n // Nothing else below branches on it, which is why stateless keeps working\n // even for an app that never configures a store.\n //\n // The `threadId` is the client's, and nothing here checks that this caller\n // owns it — `AgentStore` cannot, since it holds no user. A `threadId` is\n // therefore a capability and has to be unguessable (`createThread` mints a\n // uuid) and, for anything that matters, checked: override `authorizeRequest()`\n // or give it a `store` that scopes by `req.user`. The framework's job is to make\n // sure the route is behind the router's middleware in the first place,\n // which `ApiRouter.agent()` now does.\n //\n // Everything from the load on happens inside `start`, which on a thread\n // runs under the thread's lock once the previous run's transcript is in the\n // store — the load has to come after that, or it reads a history the old\n // answer is missing from. `instructions()` follows the load in there rather\n // than running ahead of the lock, so that a dead thread is still a 404\n // before the app's own work is spent on it; the cost is that a turn queued\n // behind this one waits for `instructions()` as well.\n // The run `start` registered, if it got that far: its end is what frees\n // this turn's `maxConcurrentRuns` slot.\n let started: AgentRun | null = null;\n // What a regenerate took out of the thread, kept until the run replacing\n // it has started.\n let removed: AgentMessage[] = [];\n const start = async (mode: StartMode = SOLO): Promise<Response> => {\n try {\n return await startRun(mode);\n } finally {\n // A regenerate that never started its run — stopped while it waited,\n // or a throw from the app's hooks — puts back what it took out, since\n // no new answer is coming to replace it. Still under the thread's lock,\n // and appended at the end, which is where it was: it was the tail.\n if (threadId && removed.length > 0 && (started as AgentRun | null) === null) {\n await this.store\n .appendMessages(threadId, removed)\n .catch((err) => this.reportHookFailure(err));\n }\n // A parallel turn's own slot, when it did not get as far as a run.\n if (mode.release && (started as AgentRun | null) === null) mode.release();\n }\n };\n const startRun = async (mode: StartMode): Promise<Response> => {\n let messages: AgentMessage[];\n // The `<jobs>` block for this turn's system prompt (#461), on a thread\n // that has background jobs.\n let jobsBlock: string | null = null;\n if (threadId) {\n const history = await this.store.loadThread(threadId);\n if (!history) {\n // Before `instructions()` and before the run: nothing has been\n // charged for, and the client has to learn that its thread is gone —\n // expired, mistyped, or on an instance that no longer exists — rather\n // than see it answered as an empty conversation and have this turn\n // persisted under the dead id.\n //\n // That ordering is deliberate. An ownership check belongs in\n // `authorizeRequest()`, which has already run; one left in\n // `instructions()` has not, so a caller holding a uuid learns whether\n // it is live here without the app's say. The id is unguessable, so\n // the load stays above `instructions()`, whose own work (a database\n // read, typically) would otherwise be spent on a thread that is gone.\n // Move it below and that work is spent on every dead id instead.\n return jsonResponse(404, {\n code: \"thread_not_found\",\n message: `Thread ${threadId} does not exist here, or has expired.`,\n });\n }\n // A message a dead run left unfinished is closed here, and written\n // back, before the run is handed the history: the model then reads it\n // as interrupted, and its open calls have results. Under the thread's\n // lock and after the previous run's transcript is stored, so the only\n // unfinished message left is one no run in this process owns.\n const thread = await this.settleThread(threadId, history, { write: true });\n // Without what another run on the thread is still writing (a parallel\n // run, `ifBusy: \"parallel\"`): an unfinished message is no history to\n // answer from, and a tool call in it with no result yet is one the\n // provider refuses. This run reads the thread as it was when it\n // started, plus its own.\n messages = thread.messages.filter(\n (message) =>\n !(\n message.role === \"assistant\" &&\n message.finishReason === undefined &&\n message.runId &&\n this.liveRuns.isRunning(message.runId)\n ),\n );\n jobsBlock = this.jobsBlock(thread.jobs);\n if (regenerate) {\n const cut = regenerationCut(messages);\n if (!cut) {\n return jsonResponse(409, {\n code: \"nothing_to_regenerate\",\n message: `Thread ${threadId} has no user turn to answer again.`,\n });\n }\n // The last user turn and everything after it leave the store, and the\n // turn is run again from what the store held — not from the client's\n // copy, which may be stale or carry local ids. The user message comes\n // back under a new id when the run reports it. Under the thread's\n // lock and after the previous run's transcript is stored, so nothing\n // writes the removed answer back. Each removed message takes its\n // `usage` with it: the thread never holds both answers' costs.\n removed = messages.slice(cut.index);\n await this.store.removeMessages!(\n threadId,\n removed.map((message) => message.id),\n );\n messages = messages.slice(0, cut.index);\n // The stored turn, under the client's `localId` for it: the message\n // is minted again, and the client has to be told the new id (#466).\n turn = turn?.localId ? { ...cut.turn, localId: turn.localId } : cut.turn;\n }\n } else {\n messages = Array.isArray(body.messages) ? (body.messages as AgentMessage[]) : [];\n warnInMemoryNonces(this.nonces);\n }\n\n const instructions =\n [(await this.instructions(req, { body: extraBody })) || undefined, jobsBlock ?? undefined]\n .filter(Boolean)\n .join(\"\\n\\n\") || undefined;\n const context = await this.context(req, { body: extraBody });\n const reasoning = (await this.reasoning(req, { body: extraBody })) || undefined;\n const skills = (await this.skills(req, { body: extraBody })) || undefined;\n const runTools = (await this.runTools(req, { body: extraBody, context })) || undefined;\n const usageLimits = (await this.usageLimits(req, { body: extraBody, context })) || undefined;\n const trailingContext = (await this.trailingContext(req, { body: extraBody, context })) || undefined;\n // Above the cancel check, not below it, and that placement is the whole\n // reason this is a separate statement rather than an argument on the call\n // below: the comment on that check says nothing yields between it and\n // `register`, and an `await` for the app's `attachmentScope()` — a\n // database read, in any app that has one — is exactly the yield a stop\n // would land in and be missed.\n const scopedAttachments = await this.attachmentsFor(req, threadId, { body: extraBody });\n // How long what this turn's tools store lives (#1307). Validated here,\n // before the run, so a bad answer fails the turn rather than a tool.\n const retention = await this.attachmentRetention(req, {\n route: \"stream\",\n threadId,\n body: extraBody,\n });\n attachmentLifetime(retention, this.turnAttachmentMaxAgeMs);\n const made: Attachment[] = [];\n const attachments =\n scopedAttachments && retention\n ? scopedAttachments.withLifetime({\n next: () => attachmentLifetime(retention, this.turnAttachmentMaxAgeMs)!,\n onPut: (attachment) => made.push(attachment),\n })\n : scopedAttachments;\n // For the same reason as `attachments`: an `await` on the app's code,\n // which has to come before the cancel check below.\n const memoryScopes = (this.agent as AnyAgent).memory\n ? await this.memoryScopes(req, { body: extraBody })\n : undefined;\n\n if (pending?.cancelled) {\n // Stopped while it waited. Nothing has been asked of the model and\n // nothing registered, so there is no run to end and nothing charged\n // for. Checked after the last `await` above, so that a stop landing\n // during it is not missed: from here to `register` nothing yields.\n return stoppedBeforeStart();\n }\n\n // Only a threaded turn has anywhere to be written as it runs. See\n // `TurnJournal`.\n const journal = threadId\n ? new TurnJournal(this.store, threadId, messages, (err) => this.reportHookFailure(err))\n : null;\n\n // Chosen here rather than by the run, so the hook context exists before\n // the run does: `redactError` below is handed it, and the run may call\n // it for its first frame.\n const runId = `run_${crypto.randomUUID()}`;\n let denials: readonly ToolDenial[] = [];\n let ofRun: AgentRun | undefined;\n const ctx: AgentHookContext = {\n req,\n runId,\n threadId,\n get denials() {\n return denials;\n },\n get turn() {\n return ofRun?.turn;\n },\n };\n\n // The app's `onMessage` for the turn's user message, called while the\n // run goes rather than after it (#806). See `EarlyTurn`.\n const early: EarlyTurn = { id: null, notified: Promise.resolve() };\n\n const run = this.agent.stream({\n runId,\n messages,\n turn,\n threadId,\n // Beside other runs, a new message leaves their questions open\n // (#1355): a run started parallel, or a turn that asked to be one\n // and found the thread free (the other turns parked on questions).\n // A server turn (`startTurn`: a scheduled report, an event, a job's\n // result) always does, queued or not (#1371): the person said\n // nothing, so nobody moved on from a question.\n ...(mode.parallel || requested === \"parallel\" || serverTurns.has(req)\n ? { keepOtherTurnsOpen: true }\n : {}),\n // The run reports each message as it finishes it, the user's turn\n // first and before the model is asked anything. Only the store hears\n // about most of them here: the app's `onMessage` runs after the run,\n // in `notifyRun`, except for the turn's own message (below).\n ...(journal ? { onMessage: (message: AgentMessage) => journal.finish(message) } : {}),\n // The turn's user message, once the journal has written it: the app's\n // `onMessage` for it is called now, so whatever the app keeps beside\n // a stored message (where it was sent from, say) is there for a read\n // of the thread while the run is still going (#806). Off the run's\n // path, as the journal is: neither the store nor the hook holds up\n // the model. `notifyRun` waits for it and does not call it again.\n onTurn: (message: AgentMessage) => {\n if (early.id !== null) return;\n early.id = message.id;\n const written = journal ? journal.settled() : Promise.resolve();\n early.notified = written.then(() => this.safely(() => this.onMessage(message, ctx)));\n },\n instructions,\n // A server turn's event (#1181), never the client's: see `serverEvents`.\n ...(serverEvents.has(req) ? { event: serverEvents.get(req)! } : {}),\n // A server turn's message is in no client's copy, so a chat watching\n // the thread is sent it.\n ...(serverTurns.has(req) ? { echoTurn: true } : {}),\n // Only when answered, so the agent's own applies otherwise.\n ...(reasoning ? { reasoning } : {}),\n ...(skills && skills.length > 0 ? { skills } : {}),\n // The turn's own tools and which tools are offered (#1123).\n ...(runTools?.tools && runTools.tools.length > 0 ? { tools: runTools.tools } : {}),\n ...(runTools?.activeTools ? { activeTools: runTools.activeTools } : {}),\n ...(trailingContext ? { trailingContext } : {}),\n // Budgets on what the run may spend (#1124).\n ...(usageLimits ? { usageLimits } : {}),\n // Built from this request once, here, and the only thing the run knows\n // about who asked. The run has no request of its own — see\n // `AgentContext` — so a tool that needs the user reads it from this.\n context,\n // Resolved once, above, and handed to every tool of the run as\n // `ctx.attachments`. It is derived from the request — the user the\n // middleware authenticated, or the thread — and never from anything the\n // model can write, which is the property that makes an attachment id\n // safe to give a model at all. `null` for a request with no subject:\n // tools still get an object, and it throws with a sentence naming\n // `attachmentScope()`.\n attachments,\n // The same object `instructions()` was handed, so the two cannot\n // disagree about what the client sent — and carried on the run\n // because a run outlives the request that started it. By the time a\n // tool executes, the body is long gone.\n // Cast because `Body` is constrained to `object` so an `interface` can be\n // used, and an interface has no index signature to satisfy\n // `Record<string, unknown>`. The value is a parsed JSON object either\n // way; the constraint is about what an app may declare, not about what\n // arrives.\n body: extraBody as Record<string, unknown>,\n // What the client, and for a tool's exception the model, is told about\n // a failure. See `redactError`.\n redactError: (error, info) => this.redactError(error, info, ctx),\n // Each model-call attempt that is asked again (#1192). See\n // `onProviderRetry`.\n onProviderRetry: (info) => this.onProviderRetry(info, ctx),\n // Where answers' nonces are spent. See `nonces`.\n nonces: this.nonces,\n // Where approved tools' executions are recorded. See `receipts`.\n receipts: this.receipts,\n // The principal its pending calls are bound to (#447): an answer is\n // only accepted from the same `runOwner` the question was asked of.\n subject: owner,\n // The memory scopes the server resolved for this caller (#936). The\n // model only ever sees their labels.\n ...(memoryScopes\n ? {\n memory: {\n scopes: memoryScopes,\n ...(this.memoryMaxTokens !== undefined ? { maxTokens: this.memoryMaxTokens } : {}),\n },\n }\n : {}),\n // Background jobs (#461) settle into the thread, so only a threaded\n // turn can start one. The job records who started it.\n ...(threadId ? { jobs: { owner } } : {}),\n // What each model call is sent (#473). Only the request: the store\n // still gets every message through `journal` above.\n ...(this.contextWindow !== undefined ? { contextWindow: this.contextWindow } : {}),\n // Where `contextWindow.compact` keeps this thread's summaries, when\n // the store holds them (#782).\n ...(threadId && isSummaryStore(this.store) ? { summaryStore: this.store } : {}),\n // Only when overridden, so a controller without one adds no call.\n ...(this.prepareStep !== AgentController.prototype.prepareStep || this.hooks?.prepareStep\n ? {\n prepareStep: (step: PrepareStepContext) =>\n this.prepareStep(step as PrepareStepContext<ContextOf<A>>, ctx),\n }\n : {}),\n }) as AgentRun;\n denials = run.denials;\n ofRun = run;\n\n // Registered before the response is built: the run is now owned by the\n // process rather than by this request, which is the property `/attach`\n // depends on and the reason a dropped connection no longer cancels\n // anything.\n const eventHooks = this.liveRuns.register(run, {\n threadId,\n // Who may attach to it and stop it from now on. See `runOwner`.\n owner,\n // The client's handle on a run it started, which is the only one that\n // exists before `run-start` reaches it. See `RegisterParams`.\n clientRunId,\n onEvent: (event) => this.dispatchEvent(event, ctx),\n onInternalError: (err) => this.reportHookFailure(err),\n // So the registry's age ceiling never cuts short a run its agent\n // allowed to be longer. See `MemoryLiveRuns.maxAgeMs`.\n maxRunDurationMs: this.agent.maxRunDurationMs,\n });\n\n started = run;\n // What `busyPolicy` is told about this run while it goes.\n const event = serverEvents.get(req);\n runRecords.set(run, {\n startedAt: new Date(),\n owner,\n turn: event\n ? { ...(event.text ? { text: event.text } : {}), event: { name: event.name } }\n : runningTurnMessage(turn),\n joined: [],\n body: extraBody,\n });\n if (journal) {\n journals.set(run, journal);\n this.follow(run, journal);\n }\n // After `register`, so a watcher that attaches on hearing it finds it.\n if (threadId) announceRun(this.liveRuns, threadId, run.runId);\n\n // Kept, not just fired: the next turn on this thread has to know when\n // this one's transcript is in the store. See `withThread`. The request\n // waits for more than the thread does — the hooks as well — so that\n // `onMessage` still finds the user who sent the message; the thread\n // waits only for the store, so a slow hook is not a slow next turn.\n // The turn's short-lived attachments are deleted once it has completed\n // (#1307). Only for a controller that answers `attachmentRetention`, so\n // every other turn costs no lookups.\n const turnFiles = turn?.files ?? [];\n const afterTurn =\n this.definesRetention() && (turnFiles.length > 0 || retention === \"turn\")\n ? () => this.expireTurn({ scoped: scopedAttachments, files: turnFiles, made, owner })\n : null;\n const { stored, hooks } = this.persistRun(run, ctx, eventHooks, journal, early, afterTurn);\n persisted.set(run, stored);\n turnRuns.set(req, { run, hooks });\n if (serverTurns.has(req)) serverTurns.set(req, { run, hooks });\n // A parallel run's own `maxConcurrentRuns` slot, held until it ends.\n if (mode.release) run.result().then(mode.release, mode.release);\n // Registered now, while the request is certainly open: `waitUntil` is\n // ignored once it has ended, and the run settling can end it before a\n // single hook has been called.\n req.ctx?.()?.waitUntil(hooks);\n\n return run.toResponse();\n };\n\n try {\n // After `pending` is registered, not before: the app's check is a yield —\n // a database read, typically — and a stop pressed during it has to find\n // this turn. Before the thread's lock, which ends the thread's previous\n // run, so a refused or stopped turn does not end it either.\n await this.authorizeRequest(req, { route: \"stream\", threadId, body: extraBody });\n // After the app's check, so a caller it refuses does not learn which ids\n // are someone's; before the thread's lock, so a refused turn supersedes\n // nothing. The client's history only counts without a thread: with one,\n // `body.messages` is ignored and the history comes from the store.\n const foreign = await this.foreignFile(\n [...(turn?.files ?? []), ...(threadId ? [] : clientHistoryFiles(body.messages))],\n owner,\n );\n if (foreign) {\n return foreign;\n }\n if (pending?.cancelled) {\n return stoppedBeforeStart();\n }\n // After the app's check, so a refused caller spends no slot; before the\n // thread's lock, so a turn over the limit waits behind nothing. No yield\n // between the count and the take: see `RunSlots.take`.\n const limitKey = await this.runLimitKey(req, { owner, threadId });\n const release =\n limitKey === null\n ? noop\n : runSlotsFor(this.liveRuns).take(\n limitKey,\n threadId ? `thread:${threadId}` : `run:${crypto.randomUUID()}`,\n this.maxConcurrentRuns,\n );\n if (!release) {\n return limitResponse(\n 429,\n \"too_many_runs\",\n `You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`,\n );\n }\n let response: Response | undefined;\n try {\n response = threadId\n ? await this.withThread(threadId, owner, start, {\n req,\n // A regenerate replaces the thread's last answer, so it always\n // supersedes: there is no answer to join or run beside.\n requested: regenerate ? \"supersede\" : requested,\n decide: !regenerate,\n source: serverTurns.has(req) ? \"server\" : \"client\",\n turn,\n body: extraBody,\n limitKey,\n })\n : await start();\n return response;\n } finally {\n // A turn that never started a run (a dead thread, stopped while it\n // waited, a throw) frees its slot now; one that did, when the run ends;\n // one that joined a run, when the stream it answers has ended.\n const run = started as AgentRun | null;\n const held = response ? joinHolds.get(response) : undefined;\n if (run) {\n run.result().then(release, release);\n } else if (held) {\n held.then(release, release);\n } else {\n release();\n }\n }\n } finally {\n if (pending && pendingTurns.get(clientRunId) === pending) {\n pendingTurns.delete(clientRunId);\n }\n }\n }\n\n /**\n * A thread holds one run at a time; a new turn on it ends the old one first.\n *\n * Since a dropped connection no longer stops a run, a user who sends again\n * mid-answer used to leave the first run going. It could not see the new\n * turn, the new run's `loadThread` could not see its answer, and both\n * appended when they finished — in whichever order the model returned them,\n * so the thread read `user2, assistant2, user1, assistant1`. `byThread` then\n * named the second run while the first was still live and unstoppable by\n * `threadId`.\n *\n * Stopping the old run and waiting for its transcript to land is chosen over\n * refusing the new turn with a 409, because sending again *is* the stop: it\n * is what `useChat.send` means, and a client that has to poll `/stop` until\n * the run is really gone before it may post the turn it has already shown is\n * a worse client for no better thread. The cost is that the new turn waits\n * for the old run to unwind, which is as long as its slowest tool in flight —\n * and that wait is the thing that puts `assistant1` before `user2`.\n *\n * The wait is on `persistRun`'s `stored`, not on `run.result()`. `result()`\n * settling is the transcript being final, not stored: `appendMessages` runs\n * after it, and a `loadThread` in that gap reads a history the old answer is\n * missing from, which is the original bug by a shorter route. It is also\n * *only* that: `stored` settles once the transcript is stored, and the app's\n * hooks run on in `hooks`, which holds the old run's request and not the\n * thread, so a slow `onMessage` is not a slow thread and a hung one is not a\n * hung thread.\n *\n * The lock around it is what makes a *third* turn wait for the second rather\n * than for the first. Two turns arriving together both see the same live\n * run, both stop it, both wait for it, and both start — the same race, one\n * message later. Under the lock the later one finds the earlier one\n * registered and stops that instead. Per process, like `LiveRuns`, and for\n * the same reason: the run it guards lives here.\n *\n * `startTurn`'s `ifBusy` (#1178) is the one way out of superseding: a\n * `\"queue\"` turn waits for the running run to end (outside the lock, so it\n * holds no one up) and looks again; a `\"skip\"` turn answers `thread_busy`.\n */\n private async withThread(\n threadId: string,\n owner: string | null,\n fn: (mode: StartMode) => Promise<Response>,\n busy: BusyTurn,\n ): Promise<Response> {\n if (busy.requested === \"skip\" && threadLocks.has(threadId)) {\n // A turn is setting up on the thread, or superseding its run: busy.\n return threadBusy(threadId);\n }\n for (;;) {\n const outcome = await this.underThreadLock(threadId, owner, fn, busy);\n if (!(\"waitFor\" in outcome)) return outcome.response;\n // A queued turn (#1178) waits for the run outside the lock, so a person\n // who sends meanwhile is not held up behind it: their turn takes the\n // lock and supersedes the run as usual. Then it takes its own place in\n // the lock's line and looks again, which is what keeps queued turns in\n // order: the first to get the lock starts, and the next finds its run.\n await outcome.waitFor;\n }\n }\n\n /** One pass of `withThread` under the thread's lock: start, join, or name the runs a waiting turn waits for. */\n private async underThreadLock(\n threadId: string,\n owner: string | null,\n fn: (mode: StartMode) => Promise<Response>,\n busy: BusyTurn,\n ): Promise<{ response: Response } | { waitFor: Promise<unknown> }> {\n const previous = threadLocks.get(threadId) ?? Promise.resolve();\n let release!: () => void;\n const held = new Promise<void>((resolve) => {\n release = resolve;\n });\n const tail = previous.then(() => held);\n threadLocks.set(threadId, tail);\n await previous;\n try {\n const running = this.liveRuns\n .running({ threadId })\n .map((info) => ({ info, run: this.liveRuns.get(info.runId) }))\n .filter((entry): entry is { info: LiveRunInfo; run: AgentRun } => entry.run !== null);\n\n if (running.length === 0) {\n // A run that already ended is still `find`-able for `ttlMs`, and may\n // still be appending its transcript: the load below has to come after.\n const live = await this.liveRuns.find({ threadId });\n const ended = live ? this.liveRuns.get(live.runId) : null;\n if (ended) await persisted.get(ended);\n return { response: await fn(SOLO) };\n }\n\n const policy =\n busy.intake?.policy ??\n (busy.decide\n ? await this.decideBusy(threadId, owner, running, busy)\n : (busy.requested ?? \"supersede\"));\n // Its transcript stored, as for a supersede; a run of another\n // process's registry has no `persisted`, and its end is enough.\n const ended = (run: AgentRun) => (persisted.get(run) ?? run.result()).then(noop, noop);\n\n if (policy === \"skip\") return { response: threadBusy(threadId) };\n if (policy === \"queue\") {\n return { waitFor: Promise.all(running.map(({ run }) => ended(run))) };\n }\n\n if (policy === \"join\") {\n const mine = running.filter(({ info }) => this.liveRuns.mayAccess(info.runId, owner));\n // Joining puts a message into a run, which is someone else's to\n // allow (#442), as superseding is.\n if (mine.length === 0) return { response: notYourRun() };\n // The newest run this caller may reach: the reply it is most likely\n // reading.\n const target = mine[mine.length - 1]!;\n const joinTurn = joinTurnOf(busy.turn, serverEvents.get(busy.req));\n const accepted = joinTurn ? (target.run.join?.(joinTurn) ?? null) : null;\n // The run is ending (or this turn has nothing to join with): it is\n // let finish, and the turn looks again after it, when the thread is\n // most likely free.\n if (!accepted) return { waitFor: ended(target.run) };\n runRecords.get(target.run)?.joined.push(runningTurnMessage(joinTurn!));\n return {\n response: this.joinResponse(threadId, owner, target.run, accepted, joinTurn!, fn, busy),\n };\n }\n\n if (policy === \"parallel\") {\n // A parallel run reads the thread once the runs going on it have\n // taken their own turns in: a turn that answers (or refuses) a\n // question amends the message that asked it, and a parallel run that\n // read the thread before that write would refuse it a second time.\n // Waited for outside the lock, like a queued turn, then looked at\n // again: a person who supersedes meanwhile is not held up by it.\n const intake = (busy.intake ??= { policy, waited: new WeakSet() });\n const behind = running.filter(\n ({ run }) => !intakeOf(run, journals.get(run)).done && !intake.waited.has(run),\n );\n if (behind.length > 0) {\n for (const { run } of behind) intake.waited.add(run);\n const all = Promise.all(behind.map(({ run }) => intakeOf(run, journals.get(run)).promise));\n let timer: ReturnType<typeof setTimeout> | undefined;\n const limit = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, PARALLEL_INTAKE_WAIT_MS);\n });\n return { waitFor: Promise.race([all, limit]).finally(() => clearTimeout(timer)) };\n }\n const { max, overflow } = threadRunLimit(\n await this.maxThreadRuns(busy.req, { threadId, owner, body: busy.body }),\n );\n if (running.length >= max) {\n // Looked at again once one has ended: another turn may have taken\n // the slot by then, and this one waits again.\n if (overflow === \"queue\") return { waitFor: Promise.race(running.map(({ run }) => ended(run))) };\n return {\n response: limitResponse(\n 429,\n \"too_many_runs\",\n `This conversation already has ${running.length} answers going. Wait for one to finish, or stop it, and send again.`,\n ),\n };\n }\n const slot =\n busy.limitKey === null\n ? noop\n : runSlotsFor(this.liveRuns).take(\n busy.limitKey,\n `run:${crypto.randomUUID()}`,\n this.maxConcurrentRuns,\n );\n if (!slot) {\n return {\n response: limitResponse(\n 429,\n \"too_many_runs\",\n `You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`,\n ),\n };\n }\n return { response: await fn({ parallel: true, release: slot }) };\n }\n\n // \"supersede\"\n if (running.some(({ info }) => !this.liveRuns.mayAccess(info.runId, owner))) {\n // Superseding is a stop, and someone else's run is not this caller's to\n // stop (#442). Only while it is still going: an ended run is kept for\n // `ttlMs` but a turn after it touches nothing of it. Whether this caller\n // may post on the thread at all is `authorizeRequest`'s question.\n return { response: notYourRun() };\n }\n for (const { run } of running) {\n run.stop({ reason: \"superseded by a later turn on this thread\" });\n }\n await Promise.all(running.map(({ run }) => persisted.get(run)));\n return { response: await fn(SOLO) };\n } finally {\n release();\n if (threadLocks.get(threadId) === tail) {\n threadLocks.delete(threadId);\n }\n }\n }\n\n /** `busyPolicy`, asked about the runs going on the thread, its answer checked. */\n private async decideBusy(\n threadId: string,\n owner: string | null,\n running: { info: LiveRunInfo; run: AgentRun }[],\n busy: BusyTurn,\n ): Promise<AgentTurnBusyPolicy> {\n const policy = await this.busyPolicy(busy.req, {\n threadId,\n owner,\n requested: busy.requested,\n source: busy.source,\n turn: busy.turn,\n body: busy.body,\n running: running.map(({ info, run }) => {\n const record = runRecords.get(run);\n return {\n runId: info.runId,\n startedAt: record?.startedAt ?? new Date(info.startedAt),\n owner: this.liveRuns.ownerOf(info.runId),\n turn: record?.turn ?? {},\n messageId: run.turn?.id,\n body: record?.body,\n joined: [...(record?.joined ?? [])],\n };\n }),\n });\n if (!BUSY_POLICIES.includes(policy)) {\n throw new TypeError(\n `AgentController.busyPolicy answers \"supersede\", \"queue\", \"join\", \"parallel\" or \"skip\"; got ${JSON.stringify(policy)}.`,\n );\n }\n return policy;\n }\n\n /**\n * The answer to a turn that joined `run`: that run's stream, from its first\n * frame, so a client that was not following it gets the whole reply, and\n * one that was drops what it already has (`seq`). The joined message shows\n * on it as the run takes it in (a `message-id` frame, or `message`).\n *\n * If the run ends without taking the message (`taken` is `null`: it asked\n * a question, failed, was superseded, ran into a limit), the message starts\n * a turn of its own, as it would have a moment later, and the stream goes\n * on with that run's frames. That turn starts whether or not anyone is\n * still reading, so the message is answered either way. A run a caller\n * stopped drops the message instead, and a turn that is refused stores it\n * and reports the refusal: see `JoinAnswer`.\n */\n private joinResponse(\n threadId: string,\n owner: string | null,\n run: AgentRun,\n accepted: AgentRunJoin,\n joinTurn: AgentJoinTurn,\n fn: (mode: StartMode) => Promise<Response>,\n busy: BusyTurn,\n ): Response {\n const answered = (target: AgentRun): JoinAnswer => ({\n kind: \"answered\",\n run: target,\n hooks: persisted.get(target) ?? target.result().then(noop, noop),\n });\n // The second attempt's response, when the run did not take the message.\n const followUp = accepted.taken.then(async (message): Promise<Response | null> => {\n if (message || stoppedByCaller.has(run)) return null;\n return this.withThread(threadId, owner, fn, busy);\n });\n const answer: Promise<JoinAnswer> = followUp.then(\n async (next) => {\n if (!next) return stoppedByCaller.has(run) ? { kind: \"dropped\" } : answered(run);\n // It joined another run in turn: that one's answer is this one's.\n const nested = joinAnswers.get(next);\n if (nested) return nested;\n const started = turnRuns.get(busy.req);\n if (started && isEventStream(next)) return { kind: \"answered\", ...started };\n const error = await AgentTurnError.from(next);\n return { kind: \"refused\", error, stored: await this.storeUnanswered(threadId, run, joinTurn) };\n },\n async (err) => {\n this.reportHookFailure(err);\n const error = new AgentTurnError(\"The turn started for a joined message failed.\", {\n status: 500,\n });\n return { kind: \"refused\", error, stored: await this.storeUnanswered(threadId, run, joinTurn) };\n },\n );\n if (serverTurns.has(busy.req)) serverJoins.set(busy.req, { run, answer });\n\n async function* frames(): AsyncGenerator<AgentStreamFrame, void, void> {\n let last = -1;\n for await (const frame of run.frames()) {\n last = frame.seq;\n yield frame;\n }\n const next = await followUp.catch(() => null);\n const outcome = await answer;\n if (outcome.kind === \"refused\") {\n next?.body?.cancel().catch(noop);\n // On the joined run's stream, after its end: the client's copy is\n // renamed to what was stored, and the refusal is its error.\n if (outcome.stored && joinTurn.localId) {\n yield {\n seq: ++last,\n event: {\n type: \"message-id\",\n localId: joinTurn.localId,\n messageId: outcome.stored.id,\n message: outcome.stored,\n },\n };\n }\n const limited = outcome.error.status === 429;\n yield {\n seq: ++last,\n event: {\n type: \"error\",\n error: {\n code: limited ? \"rate_limited\" : \"unknown\",\n message: `Your message was not answered: ${outcome.error.message}`,\n retryable: limited,\n },\n },\n };\n return;\n }\n if (!next?.body) return;\n try {\n for await (const frame of decodeSSE(next.body)) yield frame as AgentStreamFrame;\n } finally {\n // A reader that went away; the turn goes on without it.\n next.body.cancel().catch(noop);\n }\n }\n\n const finished = (async () => {\n await run.result().catch(noop);\n const outcome = await answer;\n if (outcome.kind === \"answered\") await outcome.run.result().catch(noop);\n })();\n const response = sseResponse(frames());\n joinHolds.set(response, finished);\n joinAnswers.set(response, answer);\n return response;\n }\n\n /**\n * Stores a joined message no run answered, once the run it joined has\n * stored its own transcript, so it lands after it. A turn start, not\n * `joined`: it joined nothing in the end.\n */\n private async storeUnanswered(\n threadId: string,\n run: AgentRun,\n turn: AgentJoinTurn,\n ): Promise<AgentMessage | null> {\n await persisted.get(run);\n const message = userTurnMessage(turn.event ? turn.event.text : turn.text, turn.files, turn.event);\n message.turn = message.id;\n try {\n await this.store.appendMessages(threadId, [message]);\n return message;\n } catch (err) {\n this.reportHookFailure(err);\n return null;\n }\n }\n\n /**\n * `POST /<path>/attach` — subscribe to a run already in progress, from a\n * cursor. This is a read of a live run, not a continuation of a stopped one:\n * the work never paused, the listener changed.\n *\n * The cursor is `from`, else the client's `cursor`, else `Last-Event-ID`,\n * else the oldest frame still buffered — and it is honoured only for the run\n * the client's `runId` names. A cursor the buffer has dropped is a 410 naming\n * what survives; *no* cursor is the tail, because a page reattaching on mount\n * has no transcript to leave a hole in. See `resolveCursor`.\n */\n async attach(req: HttpRequest<any, any> = new HttpRequest()): Promise<Response> {\n const parsed = await readJsonBody(req, SMALL_BODY_BYTES);\n if (parsed.error) {\n return invalidRequest(parsed);\n }\n const body = parsed.body;\n const threadId =\n typeof body.threadId === \"string\" ? body.threadId : searchParam(req, \"threadId\");\n\n if (!threadId) {\n return jsonResponse(400, {\n code: \"invalid_request\",\n message: \"attach needs a threadId: it is the handle that survives a refresh.\",\n });\n }\n\n // Before the lookup: a refused caller learns neither whether a run is live\n // on the thread nor any frame of it.\n await this.authorizeRequest(req, { route: \"attach\", threadId });\n // A scoped controller (#1177) answers only for its scope's threads: a run\n // on another tenant's thread is a miss here, as no run at all is.\n // `emptyMiss` is the client asking for the miss as a 204 (#1211): a 404 is\n // logged as a red console error on every page load of a chat that probes on\n // mount. Without it the miss stays the 404 older clients check for.\n const emptyMiss = body.emptyMiss === true;\n if (!(await this.threadInScope(req, threadId))) return noLiveRun(threadId, emptyMiss);\n\n // Unscoped, the store is not consulted. This route answers whether a run is in\n // flight here, and a run it finds was started on a thread `stream` had\n // already loaded; a miss is `no_live_run` whether or not the thread exists,\n // because a client that gets one re-reads the thread anyway (see\n // `onAttachMiss`) and learns there. The thread's own 404 is `stream`'s,\n // where a turn would otherwise be persisted under it.\n // A run the client names that is still going on this thread is the one it\n // asks for: with parallel runs (`ifBusy: \"parallel\"`) the thread has more\n // than one, and `watch` announces each by id. Otherwise the thread's\n // newest, as before.\n const named = typeof body.runId === \"string\" ? body.runId : undefined;\n const live =\n named && this.liveRuns.isRunning(named) && this.liveRuns.threadOf(named) === threadId\n ? { runId: named }\n : await this.liveRuns.find({ threadId });\n if (live && !this.liveRuns.mayAccess(live.runId, await this.runOwner(req))) {\n // Another caller's run (#442): none of its frames, ended or not.\n return notYourRun();\n }\n if (!live) {\n // An explicit miss, not a 200 with an empty stream. See `MemoryLiveRuns`:\n // behind a round-robin load balancer this is the common case, and it has\n // to be visible as one: a 404, or the 204 the client asked for.\n return noLiveRun(threadId, emptyMiss);\n }\n\n // A cursor is only a number if you know which run it counts within: `seq`\n // restarts at zero in every run, so honouring a cursor from run_1 against a\n // live run_2 would skip that many frames off the head of a run this client\n // has seen nothing of. `runId` is the client saying which run its cursor\n // means; naming one that is not live forfeits the cursor and takes the\n // tail, which is as close to the start as the buffer can offer.\n //\n // Only a MISMATCH forfeits. An absent `runId` is not a wrong answer, it is\n // an older question: `from` and `Last-Event-ID` predate the pairing and\n // carry no run, and an `EventSource` reconnecting on its own will never\n // grow one. Those keep resuming exactly as before.\n const cursorRunId = typeof body.runId === \"string\" ? body.runId : undefined;\n const cursor = cursorRunId && cursorRunId !== live.runId ? undefined : resolveCursor(req, body);\n\n try {\n return sseResponse(this.liveRuns.replay(live.runId, cursor));\n } catch (err) {\n if (err instanceof FrameCursorEvictedError) {\n // 410 rather than 404: the run is there, the position is not. A client\n // that gets this reloads the thread instead of resuming into a hole.\n return jsonResponse(410, {\n code: err.code,\n message: err.message,\n oldestSeq: err.oldest,\n });\n }\n if (err instanceof LiveRunNotFoundError) {\n // Lost the race with eviction between `find` and `replay`.\n return jsonResponse(404, { code: err.code, message: err.message });\n }\n throw err;\n }\n }\n\n /**\n * `POST /<path>/watch` — follow a thread (#1180): an SSE stream that sends\n * `{ type: \"run-start\", runId }` for each run that starts on the thread\n * from now on, whoever started it (another tab, `startTurn` from a job),\n * and once on connect for a run already going. The client attaches to the\n * run with `/attach`; this stream carries no frames of it. `useChat`'s\n * `watch: true` opens it.\n *\n * Authorized as `attach` is (`authorizeRequest` with `route: \"attach\"`), and\n * a run is announced only to a caller `attach` would let read it\n * (`runOwner`). Per process, like `LiveRuns`: a run started in another\n * process is not announced here (#459). The stream stays open until the\n * client closes it, with keepalive comments while it is quiet.\n */\n async watch(req: HttpRequest<any, any> = new HttpRequest()): Promise<Response> {\n const parsed = await readJsonBody(req, SMALL_BODY_BYTES);\n if (parsed.error) {\n return invalidRequest(parsed);\n }\n const body = parsed.body;\n const threadId =\n typeof body.threadId === \"string\" ? body.threadId : searchParam(req, \"threadId\");\n if (!threadId) {\n return jsonResponse(400, {\n code: \"invalid_request\",\n message: \"watch needs a threadId: it is the thread whose runs are announced.\",\n });\n }\n // Before anything is said about the thread's runs, as for `attach`.\n await this.authorizeRequest(req, { route: \"attach\", threadId });\n // Another scope's thread (#1177) is one this caller cannot follow.\n if (!(await this.threadInScope(req, threadId))) {\n return jsonResponse(404, {\n code: \"thread_not_found\",\n message: `Thread ${threadId} does not exist here, or has expired.`,\n });\n }\n const owner = await this.runOwner(req);\n const liveRuns = this.liveRuns;\n const watchers = watchersFor(liveRuns);\n\n let listener: ((runId: string) => void) | null = null;\n let keepalive: ReturnType<typeof sseKeepalive> | null = null;\n let seq = 0;\n const close = () => {\n keepalive?.stop();\n if (!listener) return;\n const set = watchers.get(threadId);\n set?.delete(listener);\n if (set && set.size === 0) watchers.delete(threadId);\n listener = null;\n };\n const stream = new ReadableStream<Uint8Array>({\n start(controller) {\n keepalive = sseKeepalive(controller);\n const send = (runId: string) => {\n // Someone else's run (#442): `attach` would refuse it, so it is not named.\n if (!liveRuns.mayAccess(runId, owner)) return;\n try {\n controller.enqueue(\n new TextEncoder().encode(\n encodeFrame({ seq: ++seq, event: { type: \"run-start\", runId, threadId } }),\n ),\n );\n keepalive?.touch();\n } catch {\n close();\n }\n };\n listener = send;\n let set = watchers.get(threadId);\n if (!set) {\n set = new Set();\n watchers.set(threadId, set);\n }\n set.add(send);\n // Every run going on it: more than one with parallel turns.\n for (const { runId } of liveRuns.running({ threadId })) send(runId);\n },\n cancel() {\n close();\n },\n });\n // The client going away cancels the body; the request's signal is the\n // same news by another road, for a runtime that does not cancel it.\n req.rawRequest?.signal?.addEventListener(\"abort\", close, { once: true });\n return new Response(stream, { status: 200, headers: sseHeaders() });\n }\n\n /**\n * `POST /<path>/stop` — the explicit cancel. Since a dropped connection no\n * longer stops a run, this and a later turn on the same thread are the only\n * things that do, and it is why stopping cannot be a client-side concern:\n * the tool loop is here, and a client that stops reading has not stopped\n * step four from charging a card.\n *\n * Returns as soon as the run is aborted, not when it has finished unwinding.\n * The terminal events — the stopped tool results, the aborted message — go\n * out on the run's own stream, so whoever is watching it sees the ending,\n * and `onMessage` records it whether anyone is watching or not.\n *\n * Answers `{ stopped }` normally, and a `Response` only to reject a request\n * it could not read — the union is the error, not a second success shape.\n */\n async stop(\n req: HttpRequest<any, any> = new HttpRequest(),\n ): Promise<{ stopped: boolean } | Response> {\n const parsed = await readJsonBody(req, SMALL_BODY_BYTES);\n if (parsed.error) {\n // `{ stopped: false }` would be the wrong answer as well as the wrong\n // status: it means \"there was nothing to stop\", and the truth is that we\n // could not tell what to stop. A client that believes the first one stops\n // asking, and the run keeps going.\n return invalidRequest(parsed);\n }\n const body = parsed.body;\n\n await this.authorizeRequest(req, {\n route: \"stop\",\n threadId: typeof body.threadId === \"string\" ? body.threadId : undefined,\n });\n\n // Three handles, most specific first, because which ones the client has\n // depends on how far the run got. `runId` is the server's own and settles\n // it. `clientRunId` covers the window before `run-start`, when the client\n // has nothing else for a stateless first turn — and, before that, a turn\n // that has not become a run yet because it is waiting its place on the\n // thread, which is ended where it waits. `threadId` is the fallback for a\n // client that did not start this run at all — one that attached to it,\n // whose replayed tail carried no `run-start`.\n const caller = await this.runOwner(req);\n let runId = typeof body.runId === \"string\" ? body.runId : undefined;\n if (!runId && typeof body.clientRunId === \"string\") {\n runId = this.liveRuns.findByClientRunId(body.clientRunId) ?? undefined;\n if (!runId) {\n const pending = pendingTurns.get(body.clientRunId);\n if (pending) {\n // A `clientRunId` is the client's own choice and only as unguessable\n // as it made it, so the turn it names is checked like a run (#442).\n if (pending.owner !== null && pending.owner !== caller) {\n return notYourRun();\n }\n // Not on to `threadId`: that names the run this turn is queued\n // behind, which is already stopping, and answering for it would\n // leave this one to start.\n pending.cancelled = true;\n return { stopped: true };\n }\n }\n }\n if (!runId && typeof body.threadId === \"string\") {\n // By thread, every run going on it (parallel turns), when there is more\n // than one: the stop button stops the conversation. The caller's own\n // are stopped; refused only when none of them is its to stop.\n const going = this.liveRuns.running({ threadId: body.threadId });\n if (going.length > 1) {\n const mine = going.filter((info) => this.liveRuns.mayAccess(info.runId, caller));\n if (mine.length === 0) return notYourRun();\n const reason = typeof body.reason === \"string\" ? body.reason : undefined;\n for (const info of mine) {\n const run = this.liveRuns.get(info.runId);\n if (run) stopByCaller(run, { reason });\n }\n return { stopped: true };\n }\n runId = (await this.liveRuns.find({ threadId: body.threadId }))?.runId;\n }\n\n const run = runId ? this.liveRuns.get(runId) : null;\n if (!run) {\n // Already finished, already evicted, or never here. Not an error: the\n // caller wanted the run stopped and it is not running.\n return { stopped: false };\n }\n if (!this.liveRuns.mayAccess(run.runId, caller)) {\n // Someone else's run, by whichever handle (#442). See `runOwner`.\n return notYourRun();\n }\n\n stopByCaller(run, { reason: typeof body.reason === \"string\" ? body.reason : undefined });\n\n // Deliberately not awaiting `run.result()`. Unwinding means letting tools\n // in flight settle into `denied` results and finalizing the assistant\n // message, which can take as long as the slowest tool — and a stop button\n // that spins for twenty seconds is a stop button people press twice.\n return { stopped: true };\n }\n\n /**\n * WHO A SCOPE BELONGS TO, and the one question in this file whose wrong\n * answer is a data leak rather than a bug.\n *\n * An attachment id given to the model comes back *from* the model, and what\n * the model writes is a function of everything it read — the user's text, a\n * tool's output, a document someone uploaded. So the id is untrusted in\n * exactly the way a request body is, and the scope it resolves under must come\n * from the server's own knowledge of the request. Nothing that reaches this\n * method may be readable or writable by the model: `req` is the HTTP request,\n * and `threadId` is the client's handle, not the model's.\n *\n * THE DEFAULT IS THE AUTHENTICATED USER, falling back to the thread, falling\n * back to `null`.\n *\n * - `user:<id>` when the request is authenticated. `req.ctx().user` is what\n * `AuthenticationMiddleware` and the `Auth` facade put there, so an agent\n * route behind `middlewares = [\"auth\"]` — which `ApiRouter.agent()` makes\n * the default posture — has a subject without the app writing anything.\n * - `thread:<id>` for an unauthenticated chat that has a thread. A `threadId`\n * is minted by `createThread` as a uuid and is documented as a capability,\n * and `upload` only passes one here that `store.loadThread` finds;\n * an anonymous support widget has nothing better, and scoping to the\n * conversation is strictly narrower than scoping to nothing.\n * - `null` otherwise, which means no attachment id is minted at all. There is\n * no third fallback on purpose. `sessionId()` is the tempting one and it is\n * the wrong one: it is a cookie the visitor writes, documented as *not a\n * credential*, so scoping to it is scoping to a value the caller chooses —\n * which is not a scope, it is a lookup key with extra steps.\n *\n * WHAT THIS DEFAULT GETS WRONG, since it will get something wrong for someone:\n * it is per user, not per conversation, so a user's own upload from one thread\n * resolves in another thread of theirs. That is the loose direction, and it is\n * chosen because the tight one breaks the flow the framework actually ships —\n * `useChat.uploadFile` posts a file before any thread exists, so a per-thread\n * default would make the first upload of every conversation unresolvable. An\n * app that wants per-conversation isolation returns\n * `{ key: \\`user:${id}:thread:${threadId}\\` }` here and has it; an app with\n * tenants returns `{ key: \\`org:${orgId}\\` }` and has that. What the default\n * must never be is broader than a user, and it is not.\n *\n * WHATEVER THIS READS MUST BE PRESENT ON EVERY AGENT ROUTE, and the default\n * reads `req.ctx().user`, which is present only where authentication\n * middleware ran. `agent()` mounts four routes and `.middleware()` guards\n * them individually, so `middleware({ stream: \"auth\" })` — the example in\n * `ApiRouter.agent`'s own doc — leaves `POST /chat/files` unauthenticated.\n * The upload then files the record under `thread:<id>` (or nothing at all)\n * while the run that follows, on the guarded route, resolves under\n * `user:<id>`, and every id minted on upload is a miss for the rest of the\n * conversation. It fails as `AttachmentNotFoundError`, worded identically to\n * an id the model invented, which is the point of that error and is also why\n * this particular misconfiguration is invisible. Guard `upload` and `stream`\n * together, or derive the key from something both of them have.\n *\n * gemi does not detect the skew for you, and the reason is the module's whole\n * premise: noticing that an id exists under a *different* scope requires\n * looking it up without one, and an unscoped read is the thing that must not\n * exist here — not even behind a `console.warn`. So the answer is the\n * documentation you are reading and the identical error, not a probe.\n *\n * THE BODY, AND THE ONE RULE FOR READING IT (#603). The third argument is the\n * client's `body` option — what `instructions()` gets — on both routes that\n * resolve a scope: `stream`, and `upload`, where `useChat.uploadFile` sends\n * the same option beside the file. It exists for the chat that has neither a\n * user nor a thread, a stateless page builder say, whose subject is only in\n * the body:\n *\n * protected async attachmentScope(req, threadId, { body }) {\n * const scope = await super.attachmentScope(req, threadId);\n * if (scope) return scope;\n * if (typeof body.pageId !== \"string\") return null;\n * const page = await Page.findFirst({ where: { publicId: body.pageId } });\n * return page ? { key: `page:${page.publicId}` } : null;\n * }\n *\n * The `typeof` line is not tidiness. `Body` types the shape, not the contents,\n * and to an ORM `{ publicId: undefined }` is no filter at all: a request that\n * leaves `pageId` out would find the first page in the table and be filed\n * under it, along with every other request that leaves it out.\n *\n * A body field is a value the caller chose, which is exactly what the\n * `sessionId()` paragraph above refuses. What separates the keys this may be\n * built from is not whether the client sent them — `threadId` is sent by the\n * client too — but WHETHER THE VALUE IS AN UNGUESSABLE CAPABILITY WHOSE\n * EXISTENCE THE SERVER CHECKS. A page `publicId` that is looked up, as above,\n * is one, on the same footing as a `threadId` that `loadThread` finds: holding\n * it is what entitles the caller to the page, and an id nobody minted resolves\n * to nothing. `body.orgId` in an app with users is NOT one, and passing the\n * body is precisely what makes `` { key: `org:${body.orgId}` } `` spellable: an\n * org id is enumerable and the caller may not belong to that org, so that is\n * every tenant's files handed to whoever types another tenant's id. A tenant\n * comes from `req.ctx().user`, never from here. And a value interpolated\n * without being looked up is the `sessionId()` mistake again, however\n * unguessable it looks — an anonymous caller then mints a fresh scope per\n * request. Look it up, and key on what the lookup returned.\n *\n * The same skew rule as above applies to the body, and more quietly: the key\n * must come out the same on `upload` and on `stream`. `useChat` sends the one\n * `body` option to both, so a key derived from a field that stays put for the\n * whole conversation — the page, not the selected element — agrees by\n * construction. One derived from a field that changes between the upload and\n * the turn does not, and fails as that same `AttachmentNotFoundError`.\n *\n * The third argument is new, and the method keeps its first two, so an\n * override written as `attachmentScope(req, threadId)` works unchanged; one\n * that calls `super.attachmentScope(req, threadId)` may leave it off too.\n *\n * The key is opaque and compared with `===`. It is never sent to the client\n * and never shown to the model.\n */\n protected attachmentScope(\n req: HttpRequest<any, any>,\n threadId?: string,\n extra?: { body: Body },\n ): AttachmentScope | null | Promise<AttachmentScope | null> {\n const hook = this.hooks?.attachmentScope;\n if (hook) return hook(req, threadId, extra);\n const user = req.ctx()?.user;\n const userId = user?.id ?? user?.publicId;\n if (userId !== undefined && userId !== null && String(userId) !== \"\") {\n return { key: `user:${String(userId)}` };\n }\n if (threadId) {\n return { key: `thread:${threadId}` };\n }\n return null;\n }\n\n /**\n * HOW LONG A TURN'S ATTACHMENTS LIVE (#1307). `null`, the default, keeps them\n * as before. Asked once per upload (`route: \"upload\"`) for the upload, and\n * once per turn (`route: \"stream\"`) for what the turn's tools store\n * (`ctx.attachments.put`, `ctx.generateImage`, `ctx.editImage`).\n *\n * - `\"turn\"`: deleted, from `attachmentStorage` and from the provider\n * (`AgentProvider.deleteFile`), once the turn has completed, after\n * `onStreamComplete`. An upload is deleted after the turn that names it in\n * `turn.files`; one no turn names stops resolving after\n * `turnAttachmentMaxAgeMs` and is deleted by `sweepAttachments`.\n * - `{ ttlMs }`: kept for that long, then no longer resolves, and is deleted\n * by `sweepAttachments`.\n *\n * The client has everything the stream sent it by then, so a tool that wants\n * the person to see an image it made under `\"turn\"` puts the image in its\n * output; a page that fetches it by id later needs `{ ttlMs }` instead.\n *\n * protected attachmentRetention() {\n * return \"turn\" as const;\n * }\n *\n * A turn's deletion failures are passed to `reportHookFailure`, and the\n * record stays for the sweep to try again. The stores have to be able to\n * delete: `AttachmentStore.delete`/`expired` and `FileOwners.delete`/\n * `expired` (the in-memory defaults do).\n */\n protected attachmentRetention(\n req: HttpRequest<any, any>,\n params: AttachmentRetentionParams<Body>,\n ): AttachmentRetention | null | Promise<AttachmentRetention | null> {\n return this.hooks?.attachmentRetention?.(req, params) ?? null;\n }\n\n /** Whether this controller answers `attachmentRetention` itself or through `hooks`. */\n private definesRetention(): boolean {\n return (\n this.attachmentRetention !== AgentController.prototype.attachmentRetention ||\n Boolean(this.hooks?.attachmentRetention)\n );\n }\n\n /**\n * DELETES EXPIRED ATTACHMENTS (#1307): every attachment whose `expiresAt`\n * has passed (its stored bytes, its provider file and its record), and every\n * short-lived provider-only upload. For a `CronJob`'s callback:\n *\n * await new StoreChatController().sweepAttachments();\n *\n * Deletes at most `limit` of each (default 500) per call. A failure is passed\n * to `reportHookFailure` and counted in `failed`; its record stays, so the\n * next sweep tries again. Throws when `attachments` cannot list or delete\n * (`AttachmentStore.expired` and `delete`).\n */\n async sweepAttachments(\n options: { now?: Date; limit?: number } = {},\n ): Promise<AttachmentSweepResult> {\n const now = options.now ?? new Date();\n const limit = options.limit ?? 500;\n if (!this.attachments.expired || !this.attachments.delete) {\n throw new Error(\n \"sweepAttachments() needs an attachment store with expired() and delete(). Implement both on the controller's `attachments` store.\",\n );\n }\n const result: AttachmentSweepResult = { deleted: 0, failed: 0 };\n const targets = this.deletionTargets();\n for (const attachment of await this.attachments.expired(now, limit)) {\n try {\n await deleteAttachment(attachment, targets);\n result.deleted++;\n } catch (err) {\n result.failed++;\n this.reportHookFailure(err);\n }\n }\n for (const fileId of (await this.fileOwners.expired?.(now, limit)) ?? []) {\n try {\n await this.deleteProviderFile(fileId);\n result.deleted++;\n } catch (err) {\n result.failed++;\n this.reportHookFailure(err);\n }\n }\n return result;\n }\n\n /** Where `deleteAttachment` deletes from, for this controller. */\n private deletionTargets() {\n return {\n store: this.attachments,\n storage: this.attachmentStorage,\n provider: this.agent.provider as { deleteFile?(fileId: string): Promise<void> },\n fileOwners: this.fileOwners,\n };\n }\n\n /** Deletes a provider file and forgets its owner record. */\n private async deleteProviderFile(fileId: string): Promise<void> {\n const provider = this.agent.provider as { deleteFile?(fileId: string): Promise<void> };\n if (!provider.deleteFile) {\n throw new Error(`Cannot delete provider file ${fileId}: the agent's provider has no deleteFile().`);\n }\n await provider.deleteFile(fileId);\n await this.fileOwners.delete?.(fileId);\n }\n\n /**\n * After a turn (#1307): deletes what its tools stored under `\"turn\"`\n * retention (`made`), and every upload the turn named that was kept for a\n * `\"turn\"`. An upload is looked up under the turn's own scope, and a\n * provider-only file only when it was recorded for this caller, so a turn\n * cannot delete anyone else's file by naming it.\n */\n private async expireTurn(turn: {\n scoped: ScopedAttachments | null;\n files: readonly { fileId?: string; attachmentId?: string }[];\n made: readonly Attachment[];\n owner: string | null;\n }): Promise<void> {\n const targets = this.deletionTargets();\n const deletedIds = new Set<string>();\n const deletedFiles = new Set<string>();\n const remove = async (attachment: Attachment) => {\n if (deletedIds.has(attachment.id)) return;\n deletedIds.add(attachment.id);\n if (attachment.fileId) deletedFiles.add(attachment.fileId);\n try {\n await deleteAttachment(attachment, targets);\n } catch (err) {\n this.reportHookFailure(err);\n }\n };\n\n for (const attachment of turn.made) {\n if (attachment.deleteAfterTurn) await remove(attachment);\n }\n for (const file of turn.files) {\n if (file.attachmentId && turn.scoped) {\n const attachment = await turn.scoped.get(file.attachmentId).catch(() => null);\n if (attachment?.deleteAfterTurn) await remove(attachment);\n }\n if (file.fileId && !deletedFiles.has(file.fileId)) {\n deletedFiles.add(file.fileId);\n const record = await this.fileOwners.get(file.fileId);\n if (record?.deleteAfterTurn && record.owner === turn.owner) {\n try {\n await this.deleteProviderFile(file.fileId);\n } catch (err) {\n this.reportHookFailure(err);\n }\n }\n }\n }\n }\n\n /**\n * WHAT THIS ROUTE ACCEPTS AT ALL: a size ceiling and a list of types (#683).\n * Checked once per upload, after `authorizeRequest` and before anything is\n * stored or sent to the provider, and a file outside them is answered **422**\n * with `{ error: { code, message } }` — `file_too_large` or\n * `unsupported_file_type` — which `useChat().attach()` rejects with as an\n * `AttachError`, so a composer can mark the one file.\n *\n * `accept` reads like an `<input accept>`: `\".pdf\"` matches the file name's\n * extension, `\"image/*\"` a type family, `\"text/csv\"` one type. A file\n * matching any entry is accepted. Left out (or `null` returned, the default)\n * means no limit of that kind, which is how the route behaved before.\n *\n * Here rather than in `attachmentDestination`, which an app could throw from\n * to the same end: a throw there is a 500 unless the app builds the response\n * itself, and the provider's own refusal only arrives after the bytes were\n * stored. A limit is a rule about the file, so it is answered before either.\n *\n * protected attachmentLimits() {\n * return { maxBytes: 10 * 1024 * 1024, accept: [\".pdf\", \"image/*\"] };\n * }\n */\n protected attachmentLimits(\n req: HttpRequest<any, any>,\n ): AttachmentLimits | null | Promise<AttachmentLimits | null> {\n const hook = this.hooks?.attachmentLimits;\n if (hook) return hook(req);\n return null;\n }\n\n /**\n * THE APP'S OWN RULE ABOUT ONE UPLOAD (#836): a storage quota, a per-subject\n * cap, anything that needs the file and the request's subject at once.\n * Called once per upload, after `authorizeRequest` and `attachmentLimits` and\n * before anything is stored or sent to the provider.\n *\n * It is told what the file is (`name`, `size`, `mimeType`) and what the\n * upload is about: `body`, the client's `body` option exactly as\n * `attachmentScope` gets it, and `threadId` when the store knows the thread.\n * Return nothing to let the file through, or an `UploadRefusal` to refuse it:\n * the route answers **422** with `{ error: { code, message } }` (`code`\n * defaults to `\"upload_refused\"`), and `useChat().attach()` rejects with an\n * `AttachError` carrying both, as it does for `attachmentLimits`' refusals.\n * A `RequestBreakerError` thrown here is answered as itself; anything else\n * thrown is a 500.\n *\n * protected async checkUpload(file, req, { body }) {\n * if (typeof body.pageId !== \"string\") return;\n * const page = await Page.findFirst({ where: { publicId: body.pageId } });\n * if (!page) return;\n * const used = await storageUsedBy(page);\n * if (used + file.size > capFor(page)) {\n * return { code: \"storage_full\", message: \"This site's storage is full.\" };\n * }\n * }\n *\n * The `body` rule from `attachmentScope` applies here too: it types the\n * shape, not the contents, so check a field before looking it up, and\n * decide whose quota to charge from what the lookup returned.\n *\n * Here rather than in `attachmentDestination`, which also sees the file: a\n * quota is a rule about the file and its subject, not about where the bytes\n * go, and a throw there is a 500 unless the app builds the response itself.\n *\n * A check here is not a reservation: two uploads checked at the same moment\n * both see the old usage. A cap that must never be exceeded by one file is\n * enforced where usage is recorded.\n */\n protected checkUpload(\n file: UploadCheckFile,\n req: HttpRequest<any, any>,\n ctx: UploadContext<Body>,\n ): UploadRefusal | null | void | Promise<UploadRefusal | null | void> {\n return this.hooks?.checkUpload?.(file, req, ctx);\n }\n\n /**\n * WHERE ONE FILE'S BYTES SHOULD GO. Called once per upload, with the file in\n * hand, and since #836 with the same `{ body, threadId }` that `checkUpload`\n * gets as a third argument. An override written as\n * `attachmentDestination(file, req)` works unchanged.\n *\n * The model needs to perceive a file only for vision or document reading; a\n * tool needs the bytes only to forward them. Those are different needs and\n * they were being answered the same way, because `upload` sent everything to\n * the vendor unconditionally — which is a cost and a data-minimisation problem\n * as much as a capability one. A CSV that exists to be imported belongs in\n * storage and not at the provider; an image the model must look at and no tool\n * will forward is the reverse.\n *\n * THE DEFAULT IS `\"both\"`, AND THE JUSTIFICATION IS THE FAILURE MODE, not the\n * hit rate. A mimeType table was the obvious alternative — images and PDFs to\n * the provider, everything else to storage — and it is wrong in the quiet\n * direction. Getting `\"both\"` wrong sends a file to a vendor that did not need\n * it: it costs money, it is visible on an invoice and in the vendor's file\n * list, and it is corrected by overriding one method. Getting `\"storage\"`\n * wrong drops the file out of the model's view with no error anywhere; the\n * model answers as though the image were not there, which is indistinguishable\n * from a bad prompt, and the developer debugs their instructions for an\n * afternoon. Being wrong on the invoice beats being wrong in a way that\n * presents as \"the AI is stupid\".\n *\n * `\"both\"` is also what keeps this change additive: every upload that reached\n * the provider before still reaches it, and storage is added underneath. An\n * app that never asks for an attachment id sees no difference except a second\n * copy it owns.\n *\n * A client may ask, per file, for `\"storage\"` under a `\"both\"` policy — the\n * one direction that only ever removes the vendor. It may not ask for\n * anything else, including `\"provider\"`, which would let a form field decide\n * that the app does not keep its own copy. See `narrowDestination`.\n */\n protected attachmentDestination(\n file: File,\n req: HttpRequest<any, any>,\n extra?: UploadContext<Body>,\n ): AttachmentDestination | Promise<AttachmentDestination> {\n const hook = this.hooks?.attachmentDestination;\n if (hook) return hook(file, req, extra);\n return \"both\";\n }\n\n /**\n * The attachment handle for this request — the object a tool is given.\n *\n * `null` when `attachmentScope` says the request has no subject, and a caller\n * that gets `null` must not fall back to anything: there is no unscoped handle\n * to fall back to, which is the point.\n *\n * Issue #490 hangs `ctx.attachments` off this.\n */\n protected async attachmentsFor(\n req: HttpRequest<any, any>,\n threadId?: string,\n extra: { body: Body } = { body: {} as Body },\n ): Promise<ScopedAttachments | null> {\n const scope = await this.attachmentScope(req, threadId, extra);\n if (!scope) {\n return null;\n }\n return new ScopedAttachments(this.attachments, this.attachmentStorage, scope);\n }\n\n /**\n * `POST /<voice route>` (#921): starts a voice call in front of this agent.\n *\n * Takes the browser's SDP offer (`sdp`), the chat's `threadId`, `pushToTalk`\n * and the app's `body`. Runs `authorizeRequest` (`route: \"stream\"`), then\n * `voice.start` (credits, limits: throw to refuse), creates the call at the\n * vendor with the server's key and the session `start` answered plus the\n * bridge's tools, records it in `voiceStore`, and starts a `VoiceBridge` on\n * its sideband in this process. Answers the vendor's SDP answer and the\n * session's id.\n *\n * Every failure after `start` has run calls the session's `onEnd` with\n * reason `start_failed`, so an app that charged in `start` can refund: no\n * thread (400), a refused thread (the `authorizeRequest` error), a vendor\n * failure (502, or 429 when the vendor rate-limited us, code\n * `voice_unavailable`), and a failure after the vendor call exists (500),\n * which also hangs that call up.\n *\n * @experimental Not yet verified against a live Azure or OpenAI call.\n */\n async voiceStart(\n req: HttpRequest<any, any> = new HttpRequest(),\n ): Promise<VoiceStartResponse | Response> {\n const voice = this.voice;\n if (!voice) return voiceNotEnabled();\n const parsed = await readJsonBody(req, SMALL_BODY_BYTES);\n if (parsed.error) return invalidRequest(parsed);\n const { sdp, threadId: claimed, pushToTalk } = parsed.body;\n if (typeof sdp !== \"string\" || !sdp.trimStart().startsWith(\"v=\")) {\n return jsonResponse(400, {\n code: \"invalid_request\",\n message: \"`sdp` must be the browser's SDP offer.\",\n });\n }\n const body = appBody<Body>(parsed.body, VOICE_START_KEYS);\n const clientThreadId = typeof claimed === \"string\" && claimed !== \"\" ? claimed : undefined;\n await this.authorizeRequest(req, { route: \"stream\", threadId: clientThreadId, body });\n\n const user = req.ctx?.()?.user ?? null;\n const options = await voice.start({\n req,\n body,\n threadId: clientThreadId,\n user,\n pushToTalk: pushToTalk === true,\n });\n const startedAt = Date.now();\n // From here on `start` has run, and may have charged: every way out that\n // is not a running bridge calls `onEnd` with `start_failed` (so the charge\n // can be refunded), and a vendor call that exists by then is hung up, so\n // nothing is left running with nobody metering it.\n let callId: string | undefined;\n const failed = async (error: unknown): Promise<void> => {\n if (error !== undefined) console.error(\"[gemi/ai] a voice session could not start.\", error);\n if (callId) {\n await voice.realtime.hangup(callId).catch((hangupError) => {\n console.error(\"[gemi/ai] a voice call that failed to start could not be hung up.\", hangupError);\n });\n }\n try {\n await options.onEnd?.({\n sessionId: \"\",\n ...(callId ? { callId } : {}),\n threadId: options.threadId ?? clientThreadId ?? \"\",\n reason: \"start_failed\",\n startedAt,\n endedAt: Date.now(),\n durationMs: 0,\n seconds: 0,\n usage: emptyUsage(),\n transcription: { usage: emptyUsage(), seconds: 0 },\n transcript: [],\n requests: [],\n toolCalls: [],\n errors: [],\n });\n } catch (onEndError) {\n console.error(\"[gemi/ai] a voice session's onEnd threw.\", onEndError);\n }\n };\n\n const threadId = options.threadId ?? clientThreadId;\n if (!threadId) {\n await failed(undefined);\n return jsonResponse(400, {\n code: \"invalid_request\",\n message:\n \"A voice session needs a thread: send `threadId`, or answer one from `voice.start`.\",\n });\n }\n try {\n if (threadId !== clientThreadId) {\n await this.authorizeRequest(req, { route: \"stream\", threadId, body });\n }\n } catch (error) {\n await failed(undefined);\n throw error;\n }\n\n // The id first: an MCP principal is keyed to the session.\n const sessionId = crypto.randomUUID();\n let toolHandlers = options.tools ?? [];\n try {\n if (options.mcp) {\n toolHandlers = [\n ...toolHandlers,\n ...(await mcpVoiceTools(options.mcp, { user, sessionId })),\n ];\n }\n } catch (error) {\n await failed(error);\n return jsonResponse(500, {\n code: \"voice_unavailable\",\n message: \"Voice isn't available right now.\",\n });\n }\n const session: RealtimeSession = {\n ...options.session,\n tools: [\n ...voiceTools(voice.delegate),\n ...(options.session?.tools ?? []),\n ...toolHandlers.map((handler) => handler.tool),\n ],\n ...(pushToTalk === true ? { turnDetection: null } : {}),\n };\n let call: { sdpAnswer: string; callId: string };\n try {\n call = await voice.realtime.createCall({\n sdp,\n session,\n safetyIdentifier: options.safetyIdentifier,\n });\n } catch (error) {\n await failed(error);\n const limited = error instanceof RealtimeRequestError && error.code === \"rate_limited\";\n return jsonResponse(limited ? 429 : 502, {\n code: \"voice_unavailable\",\n message: \"Voice isn't available right now.\",\n });\n }\n callId = call.callId;\n\n try {\n await this.voiceStore.create({\n id: sessionId,\n callId: call.callId,\n threadId,\n owner: await this.runOwner(req),\n body: body as Record<string, unknown>,\n startedAt,\n });\n const {\n threadId: _thread,\n session: _session,\n safetyIdentifier: _safety,\n mcp: _mcp,\n tools: _tools,\n ...hooks\n } = options;\n const bridge = VoiceBridge.start<Body>({\n ...hooks,\n tools: toolHandlers,\n controller: this.constructor as unknown as VoiceBridgeController<Body>,\n threadId,\n user,\n body,\n call: { realtime: voice.realtime, callId: call.callId },\n sessionId,\n store: this.voiceStore,\n liveRuns: this.liveRuns,\n delegate: voice.delegate,\n session,\n });\n return {\n sessionId: bridge.sessionId,\n sdp: call.sdpAnswer,\n threadId,\n delegate: voice.delegate?.name ?? DEFAULT_DELEGATE_NAME,\n endsAt: startedAt + (options.limits?.maxDurationMs ?? 15 * 60_000),\n };\n } catch (error) {\n await failed(error);\n return jsonResponse(500, {\n code: \"voice_unavailable\",\n message: \"Voice isn't available right now.\",\n });\n }\n }\n\n /**\n * `PATCH /<voice route>/:sessionId` (#921): the session's new `body` (the\n * selection, the open page). Delegated turns get it from their next start,\n * and `contextNote` tells the voice when the bridge is in this process.\n */\n async voiceUpdate(\n req: HttpRequest<any, any> = new HttpRequest(),\n ): Promise<{ updated: boolean } | Response> {\n if (!this.voice) return voiceNotEnabled();\n const found = await this.voiceSession(req);\n if (found instanceof Response) return found;\n const parsed = await readJsonBody(req, SMALL_BODY_BYTES);\n if (parsed.error) return invalidRequest(parsed);\n const body = appBody<Body>(parsed.body, []);\n await this.authorizeRequest(req, { route: \"stream\", threadId: found.threadId, body });\n if (found.endedAt !== undefined) {\n return jsonResponse(409, { code: \"voice_ended\", message: \"This voice session has ended.\" });\n }\n await this.voiceStore.update(found.id, { body: body as Record<string, unknown> });\n VoiceBridge.get(found.id)?.setBody(body);\n return { updated: true };\n }\n\n /**\n * `DELETE /<voice route>/:sessionId` (#921): ends the call. On the instance\n * holding the bridge it hangs up and runs `onEnd` before answering; on any\n * other it hangs the call up at the vendor, and the holder's sideband sees\n * the call end.\n */\n async voiceEnd(\n req: HttpRequest<any, any> = new HttpRequest(),\n ): Promise<{ ended: boolean } | Response> {\n const voice = this.voice;\n if (!voice) return voiceNotEnabled();\n const found = await this.voiceSession(req);\n if (found instanceof Response) return found;\n await this.authorizeRequest(req, {\n route: \"stream\",\n threadId: found.threadId,\n body: found.body as Body,\n });\n if (found.endedAt !== undefined) return { ended: false };\n const bridge = VoiceBridge.get(found.id);\n if (bridge) {\n await bridge.end(\"hangup\");\n } else {\n await voice.realtime.hangup(found.callId);\n await this.voiceStore.update(found.id, { endedAt: Date.now(), endReason: \"hangup\" });\n }\n return { ended: true };\n }\n\n /** The session a voice `PATCH` or `DELETE` names, if the caller owns it. */\n private async voiceSession(req: HttpRequest<any, any>): Promise<VoiceSessionRecord | Response> {\n const id = (req.params as Record<string, unknown> | undefined)?.sessionId;\n const record = typeof id === \"string\" && id ? await this.voiceStore.get(id) : null;\n if (!record) {\n return jsonResponse(404, { code: \"voice_not_found\", message: \"No such voice session.\" });\n }\n if (record.owner !== null && record.owner !== (await this.runOwner(req))) {\n return notYourRun();\n }\n return record;\n }\n\n /**\n * `POST /<path>/files` — takes an attachment and answers the handles for it.\n *\n * `fileId` IS STILL IN THE ANSWER AND STILL MEANS THE SAME THING: the\n * provider's id for the file, the thing a `FilePart` carries, unchanged. It\n * has to stay, because it is what makes vision work and what\n * `useChat.uploadFile` already reads; `attachmentId` is added beside it rather\n * than in place of it. The two are not interchangeable, and swapping them\n * would reach the vendor as a file id it has never issued — so\n * `toResponsesInput` rejects a `gemi_att_` prefix in `FilePart.fileId` with a\n * sentence saying so, rather than leaving it to whatever the vendor answers\n * (not measured).\n *\n * `fileId` is absent exactly when the file did not go to the provider, which\n * only happens when the app or the client asked for that. `attachmentId` is\n * absent when there was no scope to file the record under — see\n * `attachmentScope` — and the answer then carries `downgraded: \"no_scope\"`,\n * which is the only thing separating that case from a controller that chose\n * `\"provider\"` on purpose. Both answer `destination: \"provider\"`, because both\n * are true about where the bytes went.\n *\n * ORDER: storage first, then the provider. If the second one fails the request\n * fails either way, so the only question is where the orphan is left, and an\n * orphan in our own bucket is ours to sweep on a schedule we set, while an\n * orphan at the vendor sits under a retention policy that is not ours.\n */\n async upload(req: HttpRequest<any, any> = new HttpRequest()): Promise<UploadResult> {\n const form = await req.rawRequest.formData();\n const file = form.get(\"file\");\n if (!(file instanceof Blob)) {\n throw new Error(\"upload expects a multipart body with a `file` field.\");\n }\n const name = file instanceof File && file.name ? file.name : \"upload\";\n const mimeType = file.type || \"application/octet-stream\";\n\n // The client's `body` option, as one JSON part beside the file (#603), so\n // `authorizeRequest` and `attachmentScope` see here what they see on\n // `stream`. Read off the form already parsed: the request's body is\n // consumed, and an override cannot read it again. A malformed part is\n // refused before anything else runs, as a malformed turn is on `stream`.\n const extraBody = uploadAppBody<Body>(form.get(\"body\"));\n\n // The client's thread, read here only so an unauthenticated chat has\n // something to scope to. It is the client's own handle — `stream` already\n // takes it on trust for the whole conversation — and it is not the model's:\n // this is a form field on an HTTP request the user's browser made, not a\n // tool argument.\n //\n // It is only passed on if the store knows it. `stream` answers\n // `thread_not_found` for an id it has never seen, and this route must not\n // be looser: an invented id would otherwise be a scope, and an anonymous\n // caller could keep writing to storage by sending a fresh one each time.\n const threadField = form.get(\"threadId\");\n // The field as sent, before the store is asked about it, so a refused\n // caller does not learn whether the thread exists.\n await this.authorizeRequest(req, {\n route: \"upload\",\n threadId: typeof threadField === \"string\" && threadField.length > 0 ? threadField : undefined,\n body: extraBody,\n });\n // Before the thread is looked up, the policy is asked, or a byte is kept:\n // a file this route never takes costs nothing past this line.\n const refusal = limitRefusal(await this.attachmentLimits(req), file, name, mimeType);\n if (refusal) {\n throw new LimitedUploadError(refusal.code, refusal.message);\n }\n\n await this.scopeStore(req, extraBody);\n const threadId =\n typeof threadField === \"string\" &&\n threadField.length > 0 &&\n (await this.store.loadThread(threadField)) !== null\n ? threadField\n : undefined;\n\n // Who the provider's copy will belong to (#443): the same key that owns a\n // run this caller starts, so the turn that names the file finds it its own.\n const owner = await this.runOwner(req);\n // How long this upload lives (#1307), on the provider's copy and on ours.\n // Asked before anything is kept, so an answer that is not a retention\n // fails the upload rather than keeping the file for good.\n let lifetime: ReturnType<typeof attachmentLifetime> = null;\n const recordOwner = (fileId: string) =>\n this.fileOwners.record(fileId, {\n owner,\n name,\n mimeType,\n size: file.size,\n createdAt: new Date().toISOString(),\n ...lifetime,\n });\n\n // The app's own rule about this file and its subject (#836), still before\n // anything is kept or sent.\n const uploadContext: UploadContext<Body> = { body: extraBody, threadId };\n const appRefusal = await this.checkUpload(\n { name, size: file.size, mimeType },\n req,\n uploadContext,\n );\n if (appRefusal) {\n throw new LimitedUploadError(appRefusal.code || \"upload_refused\", appRefusal.message);\n }\n\n const policy = await this.attachmentDestination(file as File, req, uploadContext);\n const destination = narrowDestination(policy, form.get(\"destination\"));\n\n const scope = await this.attachmentScope(req, threadId, { body: extraBody });\n lifetime = attachmentLifetime(\n await this.attachmentRetention(req, { route: \"upload\", threadId, body: extraBody }),\n this.turnAttachmentMaxAgeMs,\n );\n\n // The app's policy wanted a copy of these bytes and the request has no\n // subject to file them under. Recorded rather than merely warned about,\n // because the answer has to be able to tell the client that what it is\n // getting is not the policy — see `UploadResult.downgraded`.\n const downgraded = destination !== \"provider\" && !scope;\n if (downgraded) {\n if (destination === \"storage\") {\n // Bytes were asked to be kept and there is nobody to keep them for.\n // Storing them anyway files them under a scope every caller shares, and\n // answering nothing is an upload that silently did not happen. Neither\n // is an answer; this is.\n throw new Error(\n 'This upload was routed to storage, but `attachmentScope()` returned null for the request, so there is no subject to file the attachment under. Guard the route (`this.agent(Chat).middleware({ upload: \"auth\" })`), send a `threadId` with the upload, or override `attachmentScope()`.',\n );\n }\n // Policy said `both` and the request has no subject: fall through to the\n // provider alone, which is exactly what this route did before attachments\n // existed. Downgrading rather than throwing is what keeps an\n // unauthenticated chat working across the upgrade — but a downgrade nobody\n // is told about is the failure mode this file keeps arguing against, so it\n // is warned once per process on the server and marked `downgraded` in the\n // answer, so the client can tell this apart from a deliberate\n // provider-only policy.\n warnUnscopedUploadOnce();\n }\n\n if (destination === \"provider\" || !scope) {\n // Identical to the pre-attachment behaviour, down to the answer's\n // `fileId` — plus `downgraded` when this path was not the app's choice.\n const fileId = await providerUpload(this.agent.provider, file as File);\n await recordOwner(fileId);\n const answer: UploadResult = {\n fileId,\n name,\n mimeType,\n size: file.size,\n destination: \"provider\",\n };\n if (downgraded) {\n answer.downgraded = \"no_scope\";\n }\n return answer;\n }\n\n const attachmentId = newAttachmentId();\n const objectName = await this.attachmentStorage.put({\n name: attachmentObjectName(attachmentId, name),\n body: file,\n contentType: mimeType,\n });\n\n const fileId =\n destination === \"both\" ? await providerUpload(this.agent.provider, file as File) : undefined;\n if (fileId) {\n await recordOwner(fileId);\n }\n\n const record: Attachment = {\n id: attachmentId,\n scopeKey: scope.key,\n fileId,\n objectName,\n name,\n mimeType,\n size: file.size,\n createdAt: new Date().toISOString(),\n destination,\n ...lifetime,\n };\n await this.attachments.put(scope, record);\n\n return { fileId, attachmentId, name, mimeType, size: file.size, destination };\n }\n\n /**\n * The 403 for a turn naming a provider file id that is not this caller's, or\n * `null` when every id may be used (#443). See `fileOwners`.\n *\n * Only `fileId` is checked: an `attachmentId` is resolved under the request's\n * own scope, so another user's is already a not-found (`ScopedAttachments`).\n * An entry carrying the caller's own `attachmentId` beside a foreign `fileId`\n * is refused all the same — the `fileId` is what reaches the provider.\n */\n private async foreignFile(\n files: { fileId?: string }[],\n caller: string | null,\n ): Promise<Response | null> {\n const ids = new Set(\n files.map((file) => file.fileId).filter((id): id is string => typeof id === \"string\"),\n );\n for (const fileId of ids) {\n const record = await this.fileOwners.get(fileId);\n if (record ? record.owner !== null && record.owner !== caller : this.requireKnownFiles) {\n // The same sentence for a file that is someone else's and, in strict\n // mode, one nobody recorded: which of the two it is would tell a caller\n // probing ids that the id exists.\n return notYourFile();\n }\n }\n return null;\n }\n\n /**\n * Protected, not private: these exist to be overridden. `onMessage` fires for\n * every completed message, user and assistant alike, and is the intended\n * persistence point for an app that is not using `store`.\n *\n * Once per message, in the transcript's order. The turn's own user message\n * is handed over while the run is still going: on a thread once the store\n * has it, and before the model's answer, so whatever the app keeps beside it\n * is there for a read of the thread during a long run (#806). Every other\n * message is handed over after the run, as before. A run that fails or is\n * stopped after taking the turn in has still reported it.\n *\n * Every hook runs inside the request that started the run, which is held\n * open for them — after the run, and after a client that left — so\n * `ctx.req.ctx().user` is the user who sent the turn. See `hookHoldMs` for\n * how long a hook that does not finish keeps it.\n */\n protected onMessage(message: AgentMessage, ctx: AgentHookContext): void | Promise<void> {\n return this.hooks?.onMessage?.(message, ctx);\n }\n\n protected onToolCall(\n call: { toolCallId: string; name: string; input: unknown },\n ctx: AgentHookContext,\n ): void | Promise<void> {\n return this.hooks?.onToolCall?.(call, ctx);\n }\n\n /**\n * Fires once for each tool result on the run's stream (#1062): `ok`,\n * `error`, `denied` (refused, stopped, interrupted) and `running` (a\n * background job started), from the step loop and from a turn that answers\n * a pending call. The place for an audit log of what the tools did.\n *\n * A result a person approved or refused carries `result.approval`: who\n * (the run's subject) and when. This is the server's own copy, so it is\n * trustworthy in stateless mode too, unlike the one the client posts back.\n *\n * `call` is the call the result answers, with its `input` as the model sent\n * it (what `onToolCall` got), for every status: an audit of a refused call\n * can say what was refused without reading the thread (#1079).\n *\n * Top-level calls only: a sub-agent's results are on its nested transcript.\n * A background job settling later is not a result on this stream; read\n * those off the thread, or from the job store.\n */\n protected onToolResult(\n result: ToolResultPart,\n ctx: AgentHookContext,\n call: ToolResultCall,\n ): void | Promise<void> {\n return this.hooks?.onToolResult?.(result, ctx, call);\n }\n\n /** Fires before the stream ends `awaiting-input` — where to notify whoever\n * has to approve, if they are not the person watching the stream. */\n protected onAwaitingInput(\n pending: PendingToolCall[],\n ctx: AgentHookContext,\n ): void | Promise<void> {\n return this.hooks?.onAwaitingInput?.(pending, ctx);\n }\n\n /**\n * What the client is told about a failure: the run's `error` frame, and the\n * result of a tool that threw, which the model reads too and the store\n * keeps. Return the error to send.\n *\n * The default (`redactError` from `gemi/ai`) keeps `code`, `retryable` and\n * `toolCallId` and replaces every message gemi did not write with a fixed\n * sentence for its code: a provider's error body names resources,\n * deployments and request ids, and an exception's text can be a connection\n * string. A tool that throws a `ToolError` keeps its message. The full\n * detail is in `info` (`info.failure` for the run, `info.cause` for a\n * tool), in the log, on `result().error`, and in `onError`, which is handed\n * the unredacted error.\n *\n * Override it to show more, for instance everything in development:\n *\n * protected redactError(error, info, ctx) {\n * if (process.env.NODE_ENV === \"development\") return error;\n * return super.redactError(error, info, ctx);\n * }\n *\n * Only the `AgentError` fields of what it returns are sent. One that throws\n * is reported and the default is used instead.\n */\n protected redactError(\n error: AgentError,\n info: ErrorRedactionInfo,\n ctx: AgentHookContext,\n ): AgentError {\n const hook = this.hooks?.redactError;\n if (hook) return hook(error, info, ctx);\n return redactError(error, info);\n }\n\n /**\n * A failure on the run's stream, unredacted: the provider's own message,\n * and the HTTP `status` and `requestId` and the provider's error\n * `providerType`, `providerCode` and `providerParam` (#1302) when there were\n * any. The client was sent `redactError`'s copy.\n */\n protected onError(error: AgentRunFailure, ctx: AgentHookContext): void | Promise<void> {\n return this.hooks?.onError?.(error, ctx);\n }\n\n /**\n * A model call of the run (or of a sub-run) failed and is about to be asked\n * again (#1192): the attempt, the unredacted error with its HTTP `status`\n * and `requestId`, the wait before the next attempt and the time spent so\n * far, with the run's `runId`, `agent` and `step`. Called before the wait,\n * not awaited, and a hook that throws is logged and ignored. The client is\n * sent a `retry` frame with the error code only.\n */\n protected onProviderRetry(info: AgentProviderRetry, ctx: AgentHookContext): void | Promise<void> {\n return this.hooks?.onProviderRetry?.(info, ctx);\n }\n\n protected onStreamComplete(\n result: AgentRunResult<ToolShapesOf<A[\"tools\"]>, any>,\n ctx: AgentHookContext,\n ): void | Promise<void> {\n return this.hooks?.onStreamComplete?.(result, ctx);\n }\n\n /**\n * WHAT HAPPENS WHEN A HOOK THROWS: it is reported and the run carries on.\n *\n * The alternative is to fail the run, and that trade is not close. These\n * hooks are an app's persistence and notification points; the run is a model\n * call the user has already been charged for and whose tools may already have\n * charged a card. Letting a failed `INSERT` in `onMessage` abort a generation\n * mid-sentence loses the answer as well as the row, and the user cannot\n * retry into a better outcome. So the answer survives and the failure is\n * logged.\n *\n * It is logged rather than routed to `onError`: `onError` is itself a hook,\n * and a hook that throws inside the handler for hooks that throw is a loop.\n * Override this to send it somewhere with a pager attached.\n */\n protected reportHookFailure(error: unknown): void {\n const hook = this.hooks?.reportHookFailure;\n if (hook) {\n // The reporter for failed hooks is a hook too: one that throws falls\n // back to the log rather than becoming an unhandled rejection.\n try {\n return hook(error);\n } catch (reportError) {\n console.error(\"[gemi/ai] reportHookFailure hook failed\", reportError);\n }\n }\n console.error(\"[gemi/ai] agent controller hook failed\", error);\n }\n\n private async dispatchEvent(event: AgentStreamEvent, ctx: AgentHookContext): Promise<void> {\n switch (event.type) {\n case \"tool-call\":\n // Skipped while the arguments are still streaming: a hook that fires\n // per token would fire with a half-parsed input, which is worse than\n // firing late. And skipped for a re-sent frame, which carries a parked\n // sub-run's record on a call this hook has already seen — once per call\n // is the contract, and a run that re-parks would otherwise fire it for\n // a call some earlier run made.\n if (!event.part.partial && !event.resent) {\n await this.onToolCall(\n {\n toolCallId: event.part.toolCallId,\n name: String(event.part.name),\n input: event.part.input,\n },\n ctx,\n );\n }\n return;\n case \"tool-result\": {\n const result = event.part as ToolResultPart;\n await this.onToolResult(result, ctx, {\n toolCallId: result.toolCallId,\n name: String(result.name),\n input: toolCallInputOf(result),\n });\n return;\n }\n case \"awaiting-input\":\n await this.onAwaitingInput(event.pending as PendingToolCall[], ctx);\n return;\n case \"error\":\n // The frame carries the redacted copy; the hook is server-side and\n // gets what it was made from.\n await this.onError(unredactedError(event.error), ctx);\n return;\n default:\n return;\n }\n }\n\n /**\n * The thread as a client should see it: the store's history, with any\n * assistant message a dead run left unfinished marked `interrupted` (#617).\n *\n * For the app's own route that hands a thread to `useChat` (or a native\n * session) as its initial messages. A message whose run is still going here\n * is left as it is, still being written, so the client attaches to it. `null`\n * for a thread the store does not have, as `loadThread` answers.\n *\n * It does not write: the next turn on the thread settles the same messages\n * the same way and stores them then, under the thread's lock.\n *\n * Typed by the controller's agent (#1100), as `useChat`'s `initialMessages`\n * for the route is, so the result goes there with no cast. A controller that\n * picks its agent per request is typed by the widest one, `A`.\n */\n async readThread(\n threadId: string,\n options: { scope?: string | null } = {},\n ): Promise<ThreadMessage<A>[] | null> {\n // `scope`: the thread's store scope (#1177), as `storeScope()` answers it.\n const store =\n options.scope === null || options.scope === undefined\n ? this.store\n : scopedStore(this.store, options.scope);\n const history = await store.loadThread(threadId);\n if (!history) return null;\n const { messages } = await this.settleThread(threadId, history, { write: false });\n // The store is not typed per agent; these are this agent's messages.\n return messages as ThreadMessage<A>[];\n }\n\n /**\n * Whether the run that was writing a message is still going, so the message\n * is in progress rather than interrupted.\n *\n * The default asks this process's `liveRuns`, which is the whole answer on a\n * single instance: a run lives in the process that started it, and a run\n * that is not there died with an earlier one. A finished run still within\n * `ttlMs` counts as live, since its final write may not have landed yet.\n *\n * Behind several instances it is not the whole answer. A run on another\n * instance is not in this map, so its message reads as interrupted here\n * until that run's own writes replace it. Knowing better needs a lasting\n * record of running runs (#459); override this to consult one.\n */\n protected isRunLive(runId: string, threadId: string): boolean | Promise<boolean> {\n void threadId;\n return this.liveRuns.get(runId) !== null;\n }\n\n private async settleThread(\n threadId: string,\n history: AgentMessage[],\n { write }: { write: boolean },\n ): Promise<{ messages: AgentMessage[]; jobs: AgentJobRecord[] }> {\n const isLive = (runId: string) => this.isRunLive(runId, threadId);\n const interrupted = await settleInterrupted(history, isLive);\n let messages = interrupted.messages;\n let jobs: AgentJobRecord[] = [];\n const settled = new Map(interrupted.settled.map((message) => [message.id, message]));\n\n // Background jobs (#461): each `running` tool result gets its job's\n // current state, and the ones that settled are written back with the\n // rest. A job store that cannot be read leaves the results `running`,\n // which is what the model saw last time, rather than failing the turn.\n if (hasRunningResult(messages) || write) {\n try {\n const overlaid = await overlayJobs(messages, {\n threadId,\n store: AgentJobs.store,\n isRunLive: isLive,\n outputSchemaFor: (name) => this.toolNamed(name)?.outputSchema,\n modelOutputFor: (name, output) =>\n modelOutputOf(this.toolNamed(name), output, (err) => this.reportHookFailure(err)),\n scan: this.jobsBlockMax(),\n });\n messages = overlaid.messages;\n jobs = overlaid.jobs;\n for (const message of overlaid.settled) settled.set(message.id, message);\n if (write && overlaid.orphans.length > 0) {\n await markOrphans(AgentJobs.store, overlaid.orphans, (err) =>\n this.reportHookFailure(err),\n );\n const orphans = new Set(overlaid.orphans.map((record) => record.id));\n jobs = jobs.map((record) =>\n orphans.has(record.id) ? { ...record, orphaned: true as const } : record,\n );\n }\n } catch (err) {\n this.reportHookFailure(err);\n }\n }\n\n if (write && settled.size > 0) {\n try {\n await this.store.appendMessages(threadId, [...settled.values()]);\n } catch (err) {\n // The run still gets the settled history. The store keeps the\n // unfinished copy, and the next turn settles it the same way again.\n this.reportHookFailure(err);\n }\n }\n return { messages, jobs };\n }\n\n /** The agent's `jobs.contextBlock.max`, or 0 for no block. */\n private jobsBlockMax(): number {\n const block = (this.agent as { jobs?: { contextBlock?: { max?: number } | false } }).jobs\n ?.contextBlock;\n if (block === false) return 0;\n return block?.max ?? DEFAULT_JOBS_CONTEXT_MAX;\n }\n\n private jobsBlock(jobs: AgentJobRecord[]): string | null {\n return renderJobsBlock(jobs, this.jobsBlockMax());\n }\n\n /** A tool's output schema, by name, for checking a background job's output. */\n private toolNamed(name: string): ToolLike | undefined {\n const visit = (entries: readonly unknown[]): ToolLike | undefined => {\n for (const entry of entries) {\n const tool = entry as ToolLike & { tools?: unknown[] };\n if (Array.isArray(tool.tools)) {\n const found = visit(tool.tools);\n if (found) return found;\n } else if (tool.name === name) {\n return tool;\n }\n }\n return undefined;\n };\n return visit((this.agent as { tools?: readonly unknown[] }).tools ?? []);\n }\n\n /**\n * Feeds the run's frames to its journal as they are emitted.\n *\n * A subscriber of its own on `run.frames()` rather than a ride on the\n * `onEvent` chain: that chain waits for the app's hooks, and a slow\n * `onToolCall` must not be what decides whether a tool call was stored\n * before the process died. `frames()` is a read of the run's own buffer, the\n * one `toResponse` already reads beside `liveRuns`, so a third reader costs a\n * cursor and nothing else.\n */\n private follow(run: AgentRun, journal: TurnJournal): void {\n void (async () => {\n try {\n for await (const frame of run.frames()) journal.frame(frame);\n } catch (err) {\n this.reportHookFailure(err);\n }\n })();\n }\n\n /**\n * Runs after the stream is over, whether or not anyone was still watching it.\n *\n * The messages come from `result()` rather than from the event stream because\n * assembling a message out of deltas is the agent's job and doing it twice is\n * how the two copies drift. It also means a stopped run persists the same way\n * a finished one does: `stop()` finalizes the transcript, so by the time this\n * resolves there is a valid history to store.\n *\n * `stored` settles when the transcript is in the store, not when the app is\n * done with it. The next turn on this thread waits on that (see\n * `withThread`), and the hooks are the app's: an `onMessage` that writes to\n * something slow would make every later turn wait for it, once per message\n * of the old run, and one that never settles — which `safely` cannot catch —\n * would hold the thread, and every turn queued on it, behind an open\n * connection each. So the hooks run on after it on their own, reported the\n * same way.\n *\n * `hooks` settles once they have too, and every event-stream hook the run\n * led to (`eventHooks`), or after `hookHoldMs` of them, and is what the\n * request that started the run is held open for. Separate from\n * `stored` for the reason above, and it has to exist from the start: by the\n * time the hooks are called the run has settled, and the request with it,\n * unless something was already holding it. Neither rejects.\n */\n private persistRun(\n run: AgentRun,\n ctx: AgentHookContext,\n eventHooks: Promise<void>,\n journal: TurnJournal | null = null,\n early: EarlyTurn = { id: null, notified: Promise.resolve() },\n afterTurn: (() => Promise<void>) | null = null,\n ): { stored: Promise<void>; hooks: Promise<void> } {\n // Last, after every hook, on both paths: `onStreamComplete` (or `onError`)\n // may still read what the turn made.\n const thenAfterTurn = (hooks: Promise<void>) =>\n afterTurn ? hooks.then(() => this.safely(afterTurn)) : hooks;\n // Assigned before `stored` settles, on every path, so `hooks` below reads\n // the chain this run actually started.\n let notified: Promise<void> = Promise.resolve();\n\n const stored = (async () => {\n let result: AgentRunResult<ToolShapes, unknown>;\n try {\n result = await run.result();\n } catch (err) {\n // What was written while it ran stays: it is the most the store can\n // know about a run that did not settle, and the next read marks it\n // interrupted once the run is gone.\n journal?.close();\n await journal?.settled();\n // After the turn's own `onMessage`, if the run got that far: the hooks\n // keep their order on every path.\n notified = thenAfterTurn(\n early.notified.then(() =>\n this.safely(() =>\n this.onError(\n {\n code: \"unknown\",\n message: err instanceof Error ? err.message : String(err),\n retryable: false,\n },\n ctx,\n ),\n ),\n ),\n );\n return;\n }\n\n const messages = result.messages as AgentMessage[];\n\n // The writes made while it ran land first, then the transcript whole: the\n // same messages under the same ids, now final, so this replaces every\n // in-progress copy rather than adding to them.\n journal?.close(messages);\n await journal?.settled();\n\n if (ctx.threadId && messages.length > 0) {\n try {\n await this.store.appendMessages(ctx.threadId, messages);\n } catch (err) {\n this.reportHookFailure(err);\n }\n }\n\n notified = thenAfterTurn(this.notifyRun(result, messages, ctx, early));\n })();\n\n // The bound starts once the run has settled, not with the run: a long run\n // is not a hung hook. `eventHooks` is in it because the event-stream hooks\n // are chained (see `MemoryLiveRuns.register`): an `onAwaitingInput` queued\n // behind a slow `onToolCall` is called after the run, and after every hook\n // above, and has nothing else to hold the request for it.\n const hooks = stored.then(() =>\n within(\n Promise.all([notified, eventHooks]).then(() => {}),\n this.hookHoldMs,\n ),\n );\n return { stored, hooks };\n }\n\n /** The hooks on a finished run, in order. Never rejects: see `safely`. */\n private async notifyRun(\n result: AgentRunResult<ToolShapes, unknown>,\n messages: AgentMessage[],\n ctx: AgentHookContext,\n early: EarlyTurn,\n ): Promise<void> {\n // The turn's message was handed to `onMessage` while the run went. It\n // comes before every message the run made after it, so waiting for it\n // here keeps the hook's order the transcript's.\n await early.notified;\n for (const message of messages) {\n if (message.id === early.id) continue;\n await this.safely(() => this.onMessage(message, ctx));\n }\n\n await this.safely(() => this.onStreamComplete(result as any, ctx));\n }\n\n private async safely(fn: () => void | Promise<void>): Promise<void> {\n try {\n await fn();\n } catch (err) {\n this.reportHookFailure(err);\n }\n }\n}\n\n/**\n * The turn's user message, as far as the app's `onMessage` has heard of it\n * (#806).\n *\n * The turn's message is the one thing a run stores that the app usually wants\n * to tag from the request: where it was sent from, whether the app sent it on\n * the user's behalf. Called after the run with everything else, those tags\n * were missing for the whole of a long run, to a reload or a second tab, while\n * the store already held the message. So it is called as soon as the journal\n * has written it, and `notifyRun` skips it by `id`: once per message, as\n * before, and in the same order.\n */\n/** What the controller reads off one of its agent's tools by name. */\ntype ToolLike = {\n name?: string;\n outputSchema?: Schema<any>;\n toModel?: (output: any) => unknown;\n};\n\ntype EarlyTurn = {\n /** The turn message's id, once the run has reported it. */\n id: string | null;\n /** Settles once its `onMessage` has. Never rejects. */\n notified: Promise<void>;\n};\n\n// --- request plumbing ----------------------------------------------------\n\n/**\n * The keys of the turn envelope itself, which `useChat` puts in the same JSON\n * object as an app's `body`.\n *\n * Listed so `appBody` can take them back out. Sharing one object was the right\n * wire choice — a nested `body` field would be a second envelope for every\n * client, including the Swift and Kotlin ones — but it does mean the app's\n * fields and the framework's are mixed together on arrival, and handing an app\n * `turn` and `messages` would invite reading them. They are this module's to\n * change; an app that depended on their shape would break on a release that\n * never mentioned them.\n */\nconst ENVELOPE_KEYS = [\"turn\", \"clientRunId\", \"threadId\", \"messages\", \"regenerate\", \"ifBusy\"] as const;\n\n/**\n * The turn's own fields, which `toClientTurn` reads off the top level when the\n * body carries no `turn` object. Reserved in that form and only that form —\n * with an envelope present, a top-level `text` is the app's.\n */\nconst BARE_TURN_KEYS = [\"text\", \"files\", \"toolResults\"] as const;\n\n/**\n * An app's own fields, out of the parsed turn body.\n *\n * A fresh object rather than a `delete` on the parsed one. Nothing reads the\n * body after this today — `turn`, `threadId`, `clientRunId` and `messages` are\n * all pulled out above — so this is not load-bearing and no test pins it. It is\n * how a helper that takes a parsed body should behave regardless: the next\n * reader to move a line above this one should not have to know that the body\n * was quietly hollowed out.\n */\nfunction appBody<Body extends object>(\n body: Record<string, any>,\n reserved: readonly string[] = hasTurnEnvelope(body)\n ? ENVELOPE_KEYS\n : [...ENVELOPE_KEYS, ...BARE_TURN_KEYS],\n): Body {\n const extra: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(body)) {\n if (reserved.includes(key)) continue;\n // `JSON.parse` produces `__proto__` as an own property, and `Object.entries`\n // hands it over like any other. Assigning it with `[]` goes through\n // `Object.prototype`'s setter and changes the prototype of the object an app\n // is about to read — from a value the client chose. `defineProperty` writes\n // the key itself, which is what \"the fields the client sent\" means.\n Object.defineProperty(extra, key, {\n value,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n return extra as Body;\n}\n\n/**\n * The app's fields from an upload's `body` form part — the JSON of\n * `useChat`'s `body` option — in the shape `stream` hands out.\n *\n * One JSON part rather than a form field per key: a form field is a string, so\n * `{ count: 3 }` would arrive as `\"3\"` and `Body` would lie on this route and\n * not the other. A missing part is `{}`, as a turn with no app fields is.\n *\n * Only the envelope's four names are taken back out, not the bare-turn ones:\n * `useChat` always sends a `turn` envelope, so on `stream` an app's `text` is\n * the app's, and it has to be here as well.\n *\n * Anything else — a file where the JSON should be, JSON that does not parse,\n * JSON that is not an object — is a 400, not `{}`. Read as empty, the scope\n * would quietly resolve to `null` and the upload downgrade, and the reason\n * would be a missing page rather than a broken client.\n */\nfunction uploadAppBody<Body extends object>(part: FormDataEntryValue | null): Body {\n if (part === null) {\n return {} as Body;\n }\n let parsed: unknown;\n if (typeof part === \"string\") {\n try {\n parsed = JSON.parse(part);\n } catch {\n throw new InvalidUploadError(\"The upload's `body` field is not valid JSON.\");\n }\n }\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n throw new InvalidUploadError(\"The upload's `body` field must be a JSON object.\");\n }\n return appBody<Body>(parsed as Record<string, any>, ENVELOPE_KEYS);\n}\n\n/**\n * A 400 from `upload`, which answers `UploadResult` and so rejects by throwing.\n * The payload is the shape `stream`'s own 400s have, so a client reads both the\n * same way.\n */\nclass InvalidUploadError extends RequestBreakerError {\n constructor(message: string) {\n super(message);\n this.name = \"InvalidUploadError\";\n this.payload = {\n api: { status: 400, data: { error: { code: \"invalid_request\", message } } },\n view: {},\n };\n }\n}\n\n/**\n * The provider's upload, with a refusal of THE FILE answered as the client's\n * problem rather than the server's.\n *\n * A vendor that will not take a file answers 4xx, and before this that left\n * `upload` as an unhandled `ProviderHttpError`: a 500 that tells the person\n * attaching the file nothing about the file. MEASURED on Azure (#682,\n * 2026-10-01): with `purpose: \"user_data\"` a `.docx` was refused with `400\n * Unsupported extension: .docx. Supported extensions: .txt, .md, .pdf, …`; with\n * `assistants` the `.docx` is accepted (and read in a turn), and an `.exe` is\n * refused with `400 Invalid extension exe. Supported formats: \"c\", \"cpp\", …`.\n * Either sentence is exactly what the person needs to read, so it is passed\n * through as the message.\n *\n * Only the statuses that are about the request body: 400, 413, 415 and 422. A\n * 401/403 is our key, a 429/5xx is the vendor's day, and both stay server\n * errors — a person cannot fix either by picking another file.\n */\nasync function providerUpload(provider: { upload(file: File): Promise<string> }, file: File) {\n try {\n return await provider.upload(file);\n } catch (error) {\n if (error instanceof ProviderHttpError && REJECTED_FILE_STATUSES.has(error.status)) {\n throw new RejectedUploadError(normalizeProviderError(error).message);\n }\n throw error;\n }\n}\n\nconst REJECTED_FILE_STATUSES = new Set([400, 413, 415, 422]);\n\n/** A 422 from `upload` for a file outside `attachmentLimits`, or one\n * `checkUpload` refused. */\nclass LimitedUploadError extends RequestBreakerError {\n constructor(code: string, message: string) {\n super(message);\n this.name = \"LimitedUploadError\";\n this.payload = {\n api: { status: 422, data: { error: { code, message } } },\n view: {},\n };\n }\n}\n\n/** Why `file` is outside `limits`, or `null` when it is not. Exported for the\n * tests; the route is the only caller. */\nexport function limitRefusal(\n limits: AttachmentLimits | null | undefined,\n file: Blob,\n name: string,\n mimeType: string,\n): { code: \"file_too_large\" | \"unsupported_file_type\"; message: string } | null {\n if (!limits) return null;\n const { maxBytes, accept } = limits;\n if (typeof maxBytes === \"number\" && file.size > maxBytes) {\n return {\n code: \"file_too_large\",\n message: `${JSON.stringify(name)} is ${formatBytes(file.size)}; the limit is ${formatBytes(maxBytes)}.`,\n };\n }\n if (\n accept &&\n accept.length > 0 &&\n !accept.some((entry) => acceptMatches(entry, name, mimeType))\n ) {\n return {\n code: \"unsupported_file_type\",\n message: `${JSON.stringify(name)} is not a type this chat accepts. Accepted: ${accept.join(\", \")}.`,\n };\n }\n return null;\n}\n\nfunction acceptMatches(entry: string, name: string, mimeType: string): boolean {\n const rule = entry.trim().toLowerCase();\n if (!rule) return false;\n if (rule.startsWith(\".\")) return name.toLowerCase().endsWith(rule);\n const type = mimeType.toLowerCase().split(\";\")[0]!.trim();\n if (rule.endsWith(\"/*\")) return type.startsWith(rule.slice(0, -1));\n return type === rule;\n}\n\nfunction formatBytes(bytes: number): string {\n if (bytes < 1024) return `${bytes} B`;\n const units = [\"KB\", \"MB\", \"GB\"];\n let value = bytes / 1024;\n let unit = 0;\n while (value >= 1024 && unit < units.length - 1) {\n value /= 1024;\n unit++;\n }\n return `${Math.round(value * 10) / 10} ${units[unit]}`;\n}\n\n/**\n * A 422 from `upload`: the provider would not take this file. `code` is\n * `unsupported_file_type` when the vendor said the type was the problem (an\n * extension or format allow-list) and `file_rejected` otherwise, so\n * a composer can mark the one chip without parsing English. Same payload shape\n * as `InvalidUploadError`.\n */\nclass RejectedUploadError extends RequestBreakerError {\n constructor(message: string) {\n super(message);\n this.name = \"RejectedUploadError\";\n const code =\n /(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test(\n message,\n )\n ? \"unsupported_file_type\"\n : \"file_rejected\";\n this.payload = {\n api: { status: 422, data: { error: { code, message } } },\n view: {},\n };\n }\n}\n\n/**\n * A body, or the reason there is not one.\n *\n * Deliberately one shape with an optional `error` rather than a discriminated\n * union on `ok`: this package compiles with `strict: false`, and without\n * `strictNullChecks` TypeScript will not narrow a union by a boolean\n * discriminant — `if (!parsed.ok)` leaves `parsed.message` an error. A field\n * that is either set or not needs no narrowing to read.\n */\ntype ParsedBody = {\n body: Record<string, any>;\n error?: string;\n /** Which HTTP error the rejection is. A missing one is the 400. */\n status?: number;\n code?: string;\n};\n\n/**\n * The body, as JSON — or a reason it is not.\n *\n * Read off the raw request rather than through `req.input()`: that path also\n * accepts `+json` types and answers its failures as a thrown refusal, while\n * these routes are held to `application/json` alone (below) and answer with\n * a `{ code, message }` body of their own.\n *\n * Matching the type by prefix is not the same as ignoring it. A body that\n * arrives as anything other than `application/json` is a 415, and the reason\n * is not tidiness: a cross-site `<form enctype=\"text/plain\">` can be made to\n * concatenate its one field into valid JSON, and a JSON parser that reads\n * whatever it is handed turns that form into a turn on someone else's\n * conversation. Insisting on `application/json` is what makes these routes\n * non-simple requests — the browser will not send one cross-origin without a\n * preflight — and that holds whether or not the app's cookies are `SameSite`\n * and whether or not `CSRFMiddleware` is mounted. Only a request that carries a\n * body is held to this; a bodiless POST has no type to check and stays `{}`.\n *\n * The three cases are kept apart deliberately. NO body is a real request — a\n * reattach, or a turn that just lets the model continue — and reads as `{}`. A\n * body that will not parse, or that parses to something other than an object,\n * is a failed request and has to say so: folding it into `{}` made a truncated\n * proxy response or a mis-serialized client indistinguishable from an empty\n * turn, so `stream` billed a model call with no history and no turn and threw\n * the user's actual message away. That presents as the model hallucinating\n * rather than as an error, which is the expensive way to debug it. Pre-flight\n * failures stay ordinary HTTP errors and never reach the event stream.\n *\n * An array counts as malformed even though `typeof [] === \"object\"`: nothing\n * downstream reads a positional body, so `[1,2,3]` could only ever have run as\n * an empty turn.\n */\nasync function readJsonBody(req: HttpRequest<any, any>, maxBytes: number): Promise<ParsedBody> {\n const raw = req?.rawRequest;\n if (!raw || raw.method === \"GET\" || raw.method === \"HEAD\" || !raw.body) {\n return { body: {} };\n }\n\n if (!isJsonContentType(raw.headers.get(\"Content-Type\"))) {\n // Before the body is read: nothing in a body about to be refused is worth\n // the bytes, and the refusal must not depend on what they were.\n return {\n body: {},\n status: 415,\n code: \"unsupported_media_type\",\n error: \"The request body must be sent as application/json.\",\n };\n }\n\n // Before a byte is read when the client declared its length, and while\n // reading when it did not (#444).\n const declared = Number(raw.headers.get(\"Content-Length\"));\n if (Number.isFinite(declared) && declared > maxBytes) {\n return bodyTooLarge(maxBytes);\n }\n\n let text: string;\n try {\n const read = await readCapped(raw, maxBytes);\n if (read === null) {\n return bodyTooLarge(maxBytes);\n }\n text = read;\n } catch {\n // A body that stopped arriving mid-flight. Same class of failure as one\n // that arrived truncated, and the same answer.\n return { body: {}, error: \"The request body could not be read.\" };\n }\n\n if (!text.trim()) {\n return { body: {} };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch {\n return { body: {}, error: \"The request body is not valid JSON.\" };\n }\n\n if (parsed === null || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n return { body: {}, error: \"The request body must be a JSON object.\" };\n }\n\n return { body: parsed as Record<string, any> };\n}\n\n/**\n * Media types compare case-insensitively and may carry parameters, so the\n * comparison is on the lowercased type with its parameters cut off, and\n * `Application/JSON; charset=utf-8` passes. It is an equality on that type\n * rather than a prefix, so `application/json-seq` and the other types that\n * merely begin with those bytes do not. None of the three types a browser will\n * send without a preflight — `text/plain`, `application/x-www-form-urlencoded`,\n * `multipart/form-data` — does either, and neither does no type at all, which\n * is what a hand-written `fetch` with a string body and no header ends up\n * sending as `text/plain`.\n */\nfunction isJsonContentType(value: string | null): boolean {\n return mediaType(value) === \"application/json\";\n}\n\n/**\n * The body as text, or `null` once more than `maxBytes` of it has arrived, at\n * which point the rest is not read. A limit that is not finite reads it all.\n */\nasync function readCapped(raw: Request, maxBytes: number): Promise<string | null> {\n if (!Number.isFinite(maxBytes) || !raw.body) {\n return await raw.text();\n }\n const reader = raw.body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n size += value.byteLength;\n if (size > maxBytes) {\n await reader.cancel().catch(noop);\n return null;\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(size);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n return new TextDecoder().decode(bytes);\n}\n\nfunction bodyTooLarge(maxBytes: number): ParsedBody {\n return {\n body: {},\n status: 413,\n code: \"body_too_large\",\n error: `The request body is larger than this agent accepts (${maxBytes} bytes).`,\n };\n}\n\n/**\n * A refusal for one of #444's limits: the `{ kind, message, status }` every\n * refusal has (#686), plus the `code` the agent routes' own errors carry, so a\n * client can tell the limits apart without reading the message.\n */\nfunction limitResponse(status: number, code: string, message: string): Response {\n return jsonResponse(status, {\n ...refusal(refusalKindForStatus(status), message, status),\n code,\n });\n}\n\nfunction invalidRequest(parsed: ParsedBody): Response {\n if (parsed.status === 413) {\n return limitResponse(413, parsed.code ?? \"body_too_large\", parsed.error ?? \"\");\n }\n return jsonResponse(parsed.status ?? 400, {\n code: parsed.code ?? \"invalid_request\",\n message: parsed.error,\n });\n}\n\n/**\n * Whether the turn arrived in a `turn` object of its own, rather than spread\n * across the top level of the body.\n *\n * Both forms are accepted, and which one it is decides what belongs to the app:\n * a top-level `text` is the user's message in the bare form and an app's own\n * field in the enveloped one. `toClientTurn` and `appBody` have to agree about\n * that, so they ask the same question here rather than each testing it.\n */\nfunction hasTurnEnvelope(body: Record<string, any>): boolean {\n return Boolean(body.turn) && typeof body.turn === \"object\";\n}\n\n/**\n * The client's turn, accepting both `{ turn: {...} }` and the flattened\n * `{ text, files, toolResults }` — the second is what a hand-written `fetch`\n * writes, and refusing it buys nothing.\n *\n * `turn` is `undefined` for an empty turn, which is a real request:\n * reattaching to a conversation and letting the model continue is a turn with\n * nothing in it. `error` is a turn that is refused with a 400 before anything\n * runs — see `toTurnFiles`.\n */\nfunction toClientTurn(body: Record<string, any>): { turn?: ClientTurn; error?: string } {\n const source = hasTurnEnvelope(body) ? body.turn : body;\n const turn: ClientTurn = {};\n if (typeof source.text === \"string\") {\n turn.text = source.text;\n }\n if (Array.isArray(source.files)) {\n const files = toTurnFiles(source.files);\n if (typeof files === \"string\") {\n return { error: files };\n }\n turn.files = files;\n }\n if (Array.isArray(source.toolResults)) {\n turn.toolResults = source.toolResults;\n }\n if (Object.keys(turn).length === 0) return {};\n // Envelope only: in the bare form the top level is shared with the app's own\n // fields, and an app that already sends a `localId` of its own would lose it\n // to the turn. `null` and `\"\"` read as absent, as they do for `files`.\n if (\n source === body.turn &&\n source.localId !== undefined &&\n source.localId !== null &&\n source.localId !== \"\"\n ) {\n const { localId } = source;\n if (typeof localId !== \"string\") return { error: \"turn.localId must be a string.\" };\n // Echoed back on the stream and nothing else, so the only thing to bound\n // is what one frame carries.\n if (localId.length > MAX_LOCAL_ID_LENGTH) {\n return { error: `turn.localId is longer than ${MAX_LOCAL_ID_LENGTH} characters.` };\n }\n turn.localId = localId;\n }\n return { turn };\n}\n\n/** How long `turn.localId` may be. Comfortably above `local_<uuid>`. */\nconst MAX_LOCAL_ID_LENGTH = 200;\n\n/**\n * `turn.files`, checked field by field, or the sentence refusing it.\n *\n * REFUSED, NOT FILTERED. Every entry becomes a `FilePart` in a user message,\n * and on a thread that message is stored before the provider sees it. An entry\n * the request builder cannot send — no id at all, or a gemi id in `fileId` —\n * then throws from `toResponsesInput` on this turn and on every turn after it,\n * because every later turn re-sends the history: one bad upload bricks the\n * thread. Dropping the entry instead is quieter and worse — the model answers\n * about a file it was never given, with nothing saying so. A 400 here is the\n * one place the client can still do something about it.\n *\n * Scoping is what makes a foreign `attachmentId` harmless (`ScopedAttachments`\n * answers the same not-found for another tenant's id as for an invented one),\n * so the id is not signed or looked up here. What this checks is the shape a\n * crash would come from: strings where strings go, the prefix on\n * `attachmentId`, at least one id. Unknown fields are dropped rather than\n * refused, since `attach()` answers more than a `FilePart` holds (`downgraded`)\n * and passing its answer on whole is the documented use. `null` and `\"\"` read\n * as absent, for every field: `null` is what a serializer that writes\n * `undefined` as `null` means, and `\"\"` is what a form field left blank sends.\n * Neither can be an id, so refusing `attachmentId: \"\"` for its prefix would\n * turn a blank into an error the entry's `fileId` does not deserve.\n */\nfunction toTurnFiles(raw: unknown[]): NonNullable<ClientTurn[\"files\"]> | string {\n const files: NonNullable<ClientTurn[\"files\"]> = [];\n for (const [index, entry] of raw.entries()) {\n const where = `turn.files[${index}]`;\n if (!entry || typeof entry !== \"object\" || Array.isArray(entry)) {\n return `${where} must be an object.`;\n }\n const fields: Record<string, string> = {};\n for (const key of [\"fileId\", \"attachmentId\", \"name\", \"mimeType\"] as const) {\n const value = (entry as Record<string, unknown>)[key];\n if (value === undefined || value === null || value === \"\") continue;\n if (typeof value !== \"string\") {\n return `${where}.${key} must be a string.`;\n }\n fields[key] = value;\n }\n const { fileId, attachmentId, name, mimeType } = fields;\n if (fileId?.startsWith(ATTACHMENT_ID_PREFIX)) {\n return `${where}.fileId holds a gemi attachment id (${fileId}). \\`fileId\\` is the provider's id from the upload response; put this one in \\`attachmentId\\`.`;\n }\n if (attachmentId !== undefined && !attachmentId.startsWith(ATTACHMENT_ID_PREFIX)) {\n return `${where}.attachmentId is not a gemi attachment id: it must start with \"${ATTACHMENT_ID_PREFIX}\".`;\n }\n if (!fileId && !attachmentId) {\n return `${where} has neither a \\`fileId\\` nor an \\`attachmentId\\`. Send the ids the upload response answered.`;\n }\n files.push({\n ...(fileId ? { fileId } : {}),\n ...(attachmentId ? { attachmentId } : {}),\n ...(name !== undefined ? { name } : {}),\n ...(mimeType !== undefined ? { mimeType } : {}),\n });\n }\n return files;\n}\n\n/**\n * Where to resume from, or `undefined` for \"wherever you still can\".\n *\n * An explicit `from` wins, because a client that tracked its own position knows\n * something the transport does not. Otherwise `Last-Event-ID` — the browser\n * sends it on its own when an `EventSource` reconnects, and the frames put\n * `seq` in `id:` precisely so that header is already the right question. It\n * names the last event *received*, so the resume point is one past it.\n *\n * With neither, the answer is `undefined` and NOT 0. A client reattaching on\n * mount is a fresh POST from a page that has just loaded: no `Last-Event-ID`,\n * and no cursor of its own, because the only handle it was given is the\n * `threadId`. Reading that as \"resume from frame 0\" asked `replay` for a frame\n * every run longer than `maxFrames` has already evicted, so the mount-time\n * reattach — the one case `/attach` exists for — 410'd on exactly the long runs\n * it was meant to rescue, and the documented remedy of reloading the thread\n * does not help because the store is only written at run end. `undefined` means\n * the tail, which is all such a client can use anyway.\n */\nfunction resolveCursor(req: HttpRequest<any, any>, body: Record<string, any>): number | undefined {\n if (typeof body.from === \"number\" && Number.isFinite(body.from)) {\n return Math.max(0, Math.floor(body.from));\n }\n // `cursor` is what `useChat` actually sends, and it counts the other way:\n // `from` is the frame to resume AT, `cursor` the last frame the client\n // APPLIED — the same convention as `Last-Event-ID`, and the same `+ 1`. A\n // client that has applied nothing sends -1, which is not a position but the\n // absence of one, so it falls through to the tail rather than asking for\n // frame 0 and 410ing on precisely the long runs `/attach` exists to rescue.\n if (typeof body.cursor === \"number\" && Number.isFinite(body.cursor)) {\n const applied = Math.floor(body.cursor);\n if (applied >= 0) {\n return applied + 1;\n }\n return undefined;\n }\n const header = req?.rawRequest?.headers?.get(\"Last-Event-ID\");\n if (header) {\n const seq = Number.parseInt(header, 10);\n if (Number.isFinite(seq)) {\n return Math.max(0, seq + 1);\n }\n }\n return undefined;\n}\n\nfunction searchParam(req: HttpRequest<any, any>, key: string): string | undefined {\n const value = req?.search?.get(key);\n return typeof value === \"string\" ? value : undefined;\n}\n\n/**\n * Where a threaded regenerate cuts the history: at the last message the user\n * wrote, with the turn that wrote it. A file a tool showed is a user-role\n * message too, but it is part of the answer being replaced, so it is stepped\n * over (`injectedMessageIds`, the test `historyForProvider` uses).\n */\nfunction regenerationCut(\n messages: AgentMessage[],\n): { index: number; turn: ClientTurn } | null {\n const injected = injectedMessageIds(messages);\n for (let index = messages.length - 1; index >= 0; index--) {\n const message = messages[index]!;\n if (message.role !== \"user\" || injected.has(message.id)) continue;\n let text = \"\";\n const files: NonNullable<ClientTurn[\"files\"]> = [];\n for (const part of message.content) {\n if (part.type === \"text\") text += part.text;\n if (part.type === \"file\") {\n files.push({\n ...(part.fileId ? { fileId: part.fileId } : {}),\n ...(part.attachmentId ? { attachmentId: part.attachmentId } : {}),\n ...(part.name ? { name: part.name } : {}),\n ...(part.mimeType ? { mimeType: part.mimeType } : {}),\n });\n }\n }\n if (!text && files.length === 0) continue;\n return {\n index,\n turn: { ...(text ? { text } : {}), ...(files.length > 0 ? { files } : {}) },\n };\n }\n return null;\n}\n\n/** A turn `/stop` ended while it waited, before anything ran or was charged. */\nfunction stoppedBeforeStart(): Response {\n return jsonResponse(409, {\n code: \"stopped\",\n message: \"The turn was stopped before it started.\",\n });\n}\n\n/** `startTurn`'s `event`, checked and copied, or a throw saying what is wrong with it. */\nfunction checkTurnEvent(params: AgentTurnParams<any>): AgentTurnEvent {\n const event = params.event as AgentTurnEvent;\n if (params.text !== undefined || params.turn !== undefined) {\n throw new TypeError(\n \"AgentController.startTurn takes an `event` or a `text`/`turn`, not both: an event is not a person's message.\",\n );\n }\n if (typeof event !== \"object\" || event === null || typeof event.name !== \"string\" || !EVENT_NAME.test(event.name)) {\n throw new TypeError(\n \"AgentController.startTurn's `event.name` must be letters, digits and `.`, `_`, `:`, `-` (at most 64), like \\\"job-settled\\\".\",\n );\n }\n if (event.text !== undefined && typeof event.text !== \"string\") {\n throw new TypeError(\"AgentController.startTurn's `event.text` must be a string.\");\n }\n let data: unknown;\n if (event.data !== undefined) {\n try {\n data = JSON.parse(JSON.stringify(event.data));\n } catch (error) {\n throw new TypeError(`AgentController.startTurn's \\`event.data\\` is not JSON: ${String(error)}`);\n }\n }\n return {\n name: event.name,\n ...(event.text ? { text: event.text } : {}),\n ...(data !== undefined ? { data } : {}),\n };\n}\n\n/** A `startTurn({ ifBusy: \"skip\" })` on a busy thread (#1178). `startTurn` answers `{ skipped: true }` for it. */\nfunction threadBusy(threadId: string): Response {\n return jsonResponse(409, {\n code: THREAD_BUSY,\n message: `Thread ${threadId} has a run going, and this turn was not to interrupt it.`,\n });\n}\n\n/**\n * The refusal for a run that belongs to another caller (#442), in the shape\n * every other refusal has (`{ kind, message, status }`, #686), so `useChat` and\n * the client guards classify it as `permission` without matching on text.\n */\nfunction notYourRun(): Response {\n return jsonResponse(\n 403,\n refusal(\"permission\", \"This run belongs to someone else.\", 403) as Record<string, unknown>,\n );\n}\n\n/** The refusal for a turn naming another owner's provider file (#443). Same\n * shape as `notYourRun`. */\nfunction notYourFile(): Response {\n return jsonResponse(\n 403,\n refusal(\n \"permission\",\n \"A file in this turn was uploaded by someone else.\",\n 403,\n ) as Record<string, unknown>,\n );\n}\n\n/**\n * The file parts of a stateless chat's history, which the client carries and\n * may have written anything into. Read defensively: the history is not\n * validated anywhere else before the run, and a malformed one is the run's\n * problem, not this check's.\n */\nfunction clientHistoryFiles(messages: unknown): { fileId?: string }[] {\n if (!Array.isArray(messages)) return [];\n const files: { fileId?: string }[] = [];\n for (const message of messages) {\n const content = (message as { content?: unknown } | null)?.content;\n if (!Array.isArray(content)) continue;\n for (const part of content) {\n if (part && typeof part === \"object\" && typeof part.fileId === \"string\") {\n files.push({ fileId: part.fileId });\n }\n }\n }\n return files;\n}\n\n/** What `voiceStart` takes out of the body before the rest is the app's. */\nconst VOICE_START_KEYS = [\"sdp\", \"threadId\", \"pushToTalk\"] as const;\n\ntype VoiceBridgeController<Body extends object> = {\n startTurn(params: AgentTurnParams<Body>): Promise<AgentTurn>;\n};\n\nfunction voiceNotEnabled(): Response {\n return jsonResponse(404, {\n code: \"voice_not_enabled\",\n message: \"This agent has no voice: set `voice` on its controller.\",\n });\n}\n\nfunction jsonResponse(status: number, error: Record<string, unknown>): Response {\n return new Response(JSON.stringify({ error }), {\n status,\n headers: { \"Content-Type\": \"application/json\" },\n });\n}\n\n// --- attachments ---------------------------------------------------------\n\n/**\n * Reads the client's `destination` field and applies it to the app's policy.\n *\n * THE ONLY THING A CLIENT MAY ASK FOR IS \"DO NOT SEND THIS TO THE VENDOR\", and\n * that is the entire permitted vocabulary: a `storage` hint under a `both`\n * policy, or a hint that agrees with the policy and changes nothing. Everything\n * else throws.\n *\n * The rule here used to be \"a hint may narrow, never widen\", counting\n * destinations, and counting is what made it wrong in one direction.\n * `both → provider` is fewer destinations and reads as narrowing, but what it\n * removes is *gemi's own copy*, while the third party still gets the file. That\n * is not a client declining exposure, it is a client overriding the app's\n * retention decision from a field in a multipart body: an app that keeps every\n * upload because a tool has to forward it — or because an auditor asked — loses\n * the copy, mints no `attachmentId`, records nothing, and gets no warning\n * either, since the bytes did reach the provider exactly as policy said. The\n * two directions are not alike, because only one of them reduces who ends up\n * holding the file.\n *\n * What is left is defensible on its own terms: `storage` keeps bytes off a\n * vendor the app was willing to send them to, which is a thing the client is\n * entitled to ask for and which cannot hurt anyone if the client is lying. A UI\n * that knows this CSV exists to be imported and will never be read by the model\n * is the case that makes a hint worth having at all. The policy hook is the\n * ceiling; the hint may only take the vendor out from under it.\n *\n * A hint the policy does not permit throws rather than being ignored. Ignoring\n * it is the shape of this bug that never gets found: the client believes it kept\n * a file off the vendor, the file went anyway, and nothing anywhere says so.\n */\nfunction narrowDestination(\n policy: AttachmentDestination,\n hint: FormDataEntryValue | null,\n): AttachmentDestination {\n if (typeof hint !== \"string\" || hint.length === 0) {\n return policy;\n }\n if (hint !== \"both\" && hint !== \"provider\" && hint !== \"storage\") {\n throw new Error(\n `Unknown attachment destination \"${hint}\". Expected \"both\", \"provider\" or \"storage\".`,\n );\n }\n if (hint === policy || (policy === \"both\" && hint === \"storage\")) {\n return hint;\n }\n if (policy === \"both\" && hint === \"provider\") {\n throw new Error(\n 'This upload asked for the \"provider\" destination under a \"both\" policy. A client may ask for \"storage\", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file — that is the app\\'s retention decision. Change `attachmentDestination()` if this file should not be kept.',\n );\n }\n throw new Error(\n `This upload asked for the \"${hint}\" destination, but the server's policy for it is \"${policy}\", and a client hint may only ask for \"storage\" under a \"both\" policy. Change \\`attachmentDestination()\\` if the file really should go there.`,\n );\n}\n\n/**\n * Said once per process, not once per upload.\n *\n * The condition is a property of how the app is wired — an agent route with no\n * authentication and no `threadId` on its uploads — so it is either true for\n * every request or false for every request. Logging it per request would put a\n * line in the log for every file anyone ever uploads, which is how a warning\n * stops being read.\n */\nlet warnedAboutUnscopedUpload = false;\nfunction warnUnscopedUploadOnce(): void {\n if (warnedAboutUnscopedUpload) return;\n warnedAboutUnscopedUpload = true;\n console.warn(\n \"[gemi/ai] An upload had no attachment scope, so its bytes were sent to the model provider only and no attachment id was minted — a tool cannot forward this file. Guard the route with auth, send a `threadId` with the upload, or override `attachmentScope()`.\",\n );\n}\n\n// --- routing -------------------------------------------------------------\n//\n// `agent()` itself belongs on ApiRouter next to `resource()`, which is the\n// method it works like: one call, several routes, all of them the controller's.\n// The types are declared here because they are the ai module's contract, not\n// the router's.\n//\n// class Api extends ApiRouter {\n// routes = {\n// \"/chat\": this.agent(ChatAgentController),\n// };\n// }\n//\n// POST /chat → stream every client turn\n// POST /chat/attach → attach reattach to a run in progress\n// POST /chat/stop → stop explicit cancel\n// POST /chat/files → upload attachments\n//\n// Mounting under a single path is what gives the client one key to name. The\n// agent's tool types ride along on `AgentRoute`, so `useChat(\"/chat\")` gets them\n// out of the existing `RPC` interface — no second augmentation to generate, and\n// renaming the route moves the client key with it.\n\nexport type AgentRouteMethod = \"stream\" | \"attach\" | \"stop\" | \"upload\";\n\nexport type AgentMiddlewareConfig = Partial<Record<AgentRouteMethod, MiddlewareInput>>;\n\n/**\n * What `this.agent(Controller)` returns. `T` is unconstrained so that mounting\n * the route never resolves the controller (#774): an agent whose tools are\n * routes of the same api would otherwise resolve the api's route table from\n * inside it. That `T` is an `AgentController` class is checked when the route\n * is mounted: `this.agent()` throws otherwise.\n */\nexport type AgentRoute<T> = {\n __internal_brand: \"AgentRoute\";\n controller: T;\n middleware(config: AgentMiddlewareConfig): AgentRoute<T>;\n};\n\n/** What `CreateRPC` should produce for an agent route: enough for the client to\n * type its messages, and nothing that drags server code into the bundle. */\nexport type AgentRouteRPC<T extends new () => AgentController<any, any>> = {\n __agent: true;\n // In their JSON form (#1107): what the browser holds is what came over the\n // wire, so a `Date` in a tool's output or preview is a `string` there.\n tools: InstanceType<T>[\"agent\"] extends AnyAgent\n ? JsonToolShapes<AgentToolShapes<InstanceType<T>[\"agent\"]>>\n : ToolShapes;\n output: unknown;\n /**\n * The controller's `Body`, so `useChat` can check what it sends against what\n * the controller declared.\n *\n * Read off the phantom key rather than by matching the class, which is what\n * made this fail: `Body` used to reach the instance type only through\n * `instructions`'s second parameter, and a controller overriding\n * `instructions(req)` — the pre-existing signature, so every existing\n * override — gave inference nothing to work with and got the open record.\n */\n body: InstanceType<T> extends { [BODY]?: infer B } ? B : Record<string, unknown>;\n};\n\n// --- the voice route (#921) ----------------------------------------------\n//\n// class Api extends ApiRouter {\n// routes = {\n// \"/chat\": this.agent(ChatController),\n// \"/chat/voice\": this.voice(ChatController),\n// };\n// }\n//\n// POST /chat/voice → voiceStart create the call\n// PATCH /chat/voice/:sessionId → voiceUpdate the session's body\n// DELETE /chat/voice/:sessionId → voiceEnd hang up\n//\n// One key for the client, `useVoiceSession(\"/chat/voice\")`, as `useChat` has.\n\nexport type VoiceRouteMethod = \"start\" | \"update\" | \"end\";\n\nexport type VoiceMiddlewareConfig = Partial<Record<VoiceRouteMethod, MiddlewareInput>>;\n\n/** What `this.voice(Controller)` returns. Unconstrained `T` for the reason\n * `AgentRoute`'s is (#774); checked when the route is mounted. */\nexport type VoiceRoute<T> = {\n __internal_brand: \"VoiceRoute\";\n controller: T;\n middleware(config: VoiceMiddlewareConfig): VoiceRoute<T>;\n};\n\n/** What `CreateRPC` produces for a voice route: the controller's `Body`, for\n * `useVoiceSession`'s `body` option. */\nexport type VoiceRouteRPC<T extends new () => AgentController<any, any>> = {\n __voice: true;\n body: InstanceType<T> extends { [BODY]?: infer B } ? B : Record<string, unknown>;\n};\n\n/** The longest delay `setTimeout` keeps; past it the runtime fires in ~1ms. */\nconst MAX_TIMEOUT_MS = 2 ** 31 - 1;\n\n/**\n * Settles when `work` does or after `ms`, whichever is first, and never\n * rejects. For how long the request waits on the app's code, not for the code\n * itself, which runs on either way.\n *\n * An `ms` a timer cannot hold — `Infinity` is what \"no bound\" reads as — is\n * no bound. Handed to `setTimeout` it would fire at once, and the request\n * would end before the hooks it was raised for.\n */\nfunction within(work: Promise<void>, ms: number): Promise<void> {\n const settled = work.then(\n () => {},\n () => {},\n );\n if (!(ms <= MAX_TIMEOUT_MS)) {\n return settled;\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, ms);\n });\n return Promise.race([settled, timeout]).finally(() => clearTimeout(timer));\n}\n\nlet warnedInMemoryNonces = false;\n\n/**\n * Once per process, in production: a stateless chat whose answers are spent\n * only in this process's memory. Correct for a single instance, which is why\n * it is a warning; with several, a rewound history replays an approval once\n * per instance (#445).\n */\nfunction warnInMemoryNonces(nonces: NonceStore): void {\n if (warnedInMemoryNonces || process.env.NODE_ENV !== \"production\") return;\n if (!(nonces instanceof MemoryNonceStore)) return;\n warnedInMemoryNonces = true;\n console.warn(\n \"[gemi/ai] A stateless agent chat is spending approval nonces in process memory. \" +\n \"With more than one instance a replayed approval is accepted once per instance. \" +\n \"Set `nonces = new RedisNonceStore()` (or your own NonceStore) on the AgentController.\",\n );\n}\n\n/** Whether any message holds a tool result still waiting on a background job. */\nfunction hasRunningResult(messages: AgentMessage[]): boolean {\n return messages.some((message) =>\n message.content.some((part) => part.type === \"tool-result\" && part.status === \"running\"),\n );\n}\n\n/** `store.forScope(scope)`, or an error naming what is missing (#1177). */\nfunction scopedStore(store: AgentStore, scope: string): AgentStore {\n if (typeof scope !== \"string\" || scope === \"\") {\n throw new TypeError(\"A store scope is a non-empty string.\");\n }\n if (!store.forScope) {\n throw new Error(\n \"This controller's store cannot be scoped: storeScope() or a turn's `scope` needs a store that implements `forScope` (DatabaseAgentStore or MemoryAgentStore).\",\n );\n }\n return store.forScope(scope);\n}\n\n/**\n * `/attach`'s miss: a 204 when the client sent `emptyMiss` (#1211), otherwise\n * the 404 `no_live_run` that clients written before it check for.\n */\nfunction noLiveRun(threadId: string, empty = false): Response {\n if (empty) {\n return new Response(null, { status: 204 });\n }\n return jsonResponse(404, {\n code: \"no_live_run\",\n message: `No run in progress for thread ${threadId} in this process.`,\n });\n}\n"
|
|
31
31
|
],
|
|
32
|
-
"mappings": ";qvDAAA,gBAAS,aAAY,cAAa,OAClC,gBAAS,MAAY,UAAM,KAAU,SAS9B,DAAM,FAAmB,UAmC1B,FAAU,wBACV,FAAc,YACd,FAAO,iBAEP,FAAW,CAAE,IAAK,aAAc,OAAQ,SAAU,EACpD,GAAyB,CAAC,EACxB,GAAQ,IAAI,IAEd,GAEJ,SAAS,EAAY,EA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