omo-ai 5.1.64 → 5.1.65

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/bin/darwin/omo-keychain +0 -0
  2. package/bin/lib/doctor-memory-runtime.js +167 -0
  3. package/bin/lib/doctor-reflection-lock.js +102 -6
  4. package/bin/lib/doctor.js +4 -2
  5. package/bin/lib/launcher.js +21 -3
  6. package/bin/lib/provider-map.json +1 -1
  7. package/bin/lib/reflection-lock.generated.js +39 -1
  8. package/bin/lib/service-auth.generated.js +37 -18
  9. package/bin/lib/thread.js +28 -2
  10. package/package.json +2 -2
  11. package/plugin/CHANGELOG.md +54 -0
  12. package/plugin/extensions/dream-persona.md +1 -1
  13. package/plugin/extensions/gateway-store-worker.mjs +1 -1
  14. package/plugin/extensions/memory-run-supervisor.mjs +3 -3
  15. package/plugin/extensions/omo-claim-receipt.js +1 -1
  16. package/plugin/extensions/omo-computer-use.js +1 -1
  17. package/plugin/extensions/omo-desktop-toolkit.js +1 -1
  18. package/plugin/extensions/omo-device-account.js +66 -2
  19. package/plugin/extensions/omo-device-service.js +5 -5
  20. package/plugin/extensions/omo-feedback.js +2 -2
  21. package/plugin/extensions/omo-init-deep-advisor.js +1 -1
  22. package/plugin/extensions/omo-member.js +2 -2
  23. package/plugin/extensions/omo-memory-commands.js +3 -3
  24. package/plugin/extensions/omo-memory-doctor.js +3 -3
  25. package/plugin/extensions/omo-memory-memfs.js +1 -1
  26. package/plugin/extensions/omo-memory-palace.js +2 -2
  27. package/plugin/extensions/omo-memory-sync.js +1 -1
  28. package/plugin/extensions/omo-onboarding-scan.js +3 -3
  29. package/plugin/extensions/omo-recall-store.js +1 -1
  30. package/plugin/extensions/omo-session-history.js +1 -1
  31. package/plugin/extensions/omo-side-panel.js +2 -2
  32. package/plugin/extensions/omo-task.js +2 -2
  33. package/plugin/extensions/omo-telemetry-otlp.js +2 -2
  34. package/plugin/extensions/omo-telemetry-posthog.js +1 -1
  35. package/plugin/extensions/omo-telemetry-recovery.js +1 -1
  36. package/plugin/extensions/omo-thread-client.js +5 -5
  37. package/plugin/extensions/omo.js +3 -3
  38. package/plugin/package.json +2 -1
  39. package/plugin/runtime/agent-toolkit-sdk/sdk.js +2 -2
  40. package/plugin/runtime/ast-grep-mcp/manifest.json +1 -1
  41. package/plugin/runtime/bunshin-ts/sdk.js +2 -2
  42. package/plugin/runtime/category-coverage/index.js +2 -2
  43. package/plugin/runtime/rollback-migrate.js +1 -1
  44. package/plugin/runtime/task-config/index.js +3 -3
  45. package/plugin/runtime/thread-sdk/sdk.js +5 -5
  46. package/plugin/skills/browser/SKILL.md +3 -1
  47. package/plugin/skills/browser/runtime/omowright/index.js +232 -341
  48. package/plugin/skills/browser/runtime/omowright/manifest.json +5 -5
  49. package/plugin/skills/browser/runtime/omowright/page-bundle.js +1586 -1394
  50. package/plugin/skills/browser/scripts/browser-doctor-report.mjs +68 -0
  51. package/plugin/skills/browser/scripts/browser-doctor.mjs +8 -43
  52. package/plugin/skills/browser/scripts/omowright.mjs +7 -1
package/bin/lib/thread.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { readFileSync } from "node:fs"
1
2
  import { userInfo } from "node:os"
2
3
  import { join } from "node:path"
3
4
  import { pathToFileURL } from "node:url"
@@ -186,7 +187,7 @@ export function threadExitCode(result) {
186
187
  * The answer is `{ sdk }` or `{ error, code }`: `unsupported` for the runtime, `internal_error` for a
187
188
  * plugin SDK that cannot be imported (a broken or partial install).
188
189
  */
189
- export async function loadThreadSdk({ pluginRoot, agentDir, env, cwd, engine, loadSqlite, importSdk, identity }) {
190
+ export async function loadThreadSdk({ pluginRoot, agentDir, env, cwd, engine, loadSqlite, importSdk, importThreadClient = () => import(pathToFileURL(join(pluginRoot, "extensions", "omo-thread-client.js")).href), identity }) {
190
191
  try {
191
192
  await (loadSqlite ?? (() => import("node:sqlite")))()
192
193
  } catch {
@@ -200,7 +201,32 @@ export async function loadThreadSdk({ pluginRoot, agentDir, env, cwd, engine, lo
200
201
  }
201
202
  const who = identity ?? { uid: process.getuid?.() ?? 0, user: userInfo().username }
202
203
  const engineStatusAll = async () => engine.run(["host", "status", "--json", "--all", "--include-workers"], { env: { ...env, OMO_AGENT_DIR: agentDir } }).stdout
203
- return { sdk: module.createThreadSdk({ agentDir, cwd, uid: who.uid, user: who.user, env, engineStatusAll }) }
204
+ const remote = await cliRemoteSurface({ pluginRoot, env, cwd, importThreadClient })
205
+ return { sdk: module.createThreadSdk({ agentDir, cwd, uid: who.uid, user: who.user, env, engineStatusAll, ...(remote === undefined ? {} : { remote }) }) }
206
+ }
207
+
208
+ /**
209
+ * The account's other devices and its alias registry for `omo thread` (#12833), from the plugin's own thread client and
210
+ * device-account sidecars: `read` then resolves an alias or another device's thread as the agent tools do. A plugin
211
+ * whose thread client does not offer it keeps the local-only behavior. The SDK closes it on dispose.
212
+ */
213
+ async function cliRemoteSurface({ pluginRoot, env, cwd, importThreadClient }) {
214
+ let client
215
+ try {
216
+ client = await importThreadClient()
217
+ } catch {
218
+ return undefined
219
+ }
220
+ if (typeof client.createCliRemoteSurface !== "function") return undefined
221
+ let version = "0.0.0"
222
+ try {
223
+ const declared = JSON.parse(readFileSync(join(pluginRoot, "package.json"), "utf8")).version
224
+ if (typeof declared === "string") version = declared
225
+ } catch {
226
+ // A plugin manifest that cannot be read only loses the version the device service is told; reads still work.
227
+ }
228
+ const loadAccess = async () => (await import(pathToFileURL(join(pluginRoot, "extensions", "omo-device-account.js")).href)).cliServiceAccess({ env, cwd })
229
+ return client.createCliRemoteSurface({ version, loadAccess })
204
230
  }
205
231
 
206
232
  export async function runThreadCommand(args, options) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omo-ai",
3
- "version": "5.1.64",
3
+ "version": "5.1.65",
4
4
  "type": "module",
5
5
  "description": "OmO Native - the standalone omo command with the OMO extension built in: bun add -g omo-ai",
6
6
  "bin": {
@@ -17,7 +17,7 @@
17
17
  "postinstall": "node bin/senpi-patch.mjs"
18
18
  },
19
19
  "dependencies": {
20
- "@code-yeongyu/senpi": "2026.11.5-1"
20
+ "@code-yeongyu/senpi": "2026.11.6-3"
21
21
  },
22
22
  "repository": {
23
23
  "type": "git",
@@ -7,6 +7,60 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [5.1.65] - 2026-11-08
11
+
12
+ **A message an agent sends to a session on another device now says who sent it.** It used to arrive there as plain text, indistinguishable from that session's own user. It now carries the same sender line and authority notice as a message between sessions on one device (the sending session, its workspace and project, and the device it came from), and a leading `/` in it no longer runs a command or expands a prompt template on the receiving side. `omo remote send` from a terminal is unchanged. ([#12858](https://github.com/code-yeongyu/oh-my-openagent/pull/12858), part of [#12852](https://github.com/code-yeongyu/oh-my-openagent/issues/12852))
13
+
14
+ **Memory retention no longer evaluates its completion-record guard twice per record.** The completion sweep now reads the guard once and keeps or removes the record on that single answer, and the retention tests check their own preconditions instead of asserting them away. No change to what retention keeps or removes. ([#12783](https://github.com/code-yeongyu/oh-my-openagent/pull/12783), follow-up to [#12532](https://github.com/code-yeongyu/oh-my-openagent/pull/12532))
15
+
16
+ **The standalone `omo` binary's `omo doctor` reports memory runtime size again, like the npm install.** Each memory identity's runtime size against its cap and the total across identities are printed by both distributions, so binary/npm doctor parity holds ([#12785](https://github.com/code-yeongyu/oh-my-openagent/issues/12785)). ([#12783](https://github.com/code-yeongyu/oh-my-openagent/pull/12783))
17
+
18
+ **Old binary runtimes are pruned safely when two `omo` launches start at once.** A launch no longer deletes a runtime another launch is still pruning, and a runtime that launch already removed is not reported as a failure. `omo --version`, `--help` and `omo update` never prune. ([#12770](https://github.com/code-yeongyu/oh-my-openagent/pull/12770), follow-up to [#12627](https://github.com/code-yeongyu/oh-my-openagent/pull/12627))
19
+
20
+ **A task child whose engine cannot hold its designated model chain is no longer started.** Before, when a process child's engine could not take its chain (an older engine, a refused `set_retry_fallback`, or no answer in time) or a task host did not advertise `retry_fallback_profile`, the child was still prompted and ran on the engine's own fallback settings, which can reach models outside its chain. The start now fails before the first prompt and names every designated model and the reason, and such a host is refused as incompatible, naming the same models. ([#12759](https://github.com/code-yeongyu/oh-my-openagent/issues/12759)) ([#12761](https://github.com/code-yeongyu/oh-my-openagent/pull/12761))
21
+
22
+ **A command on a closed session on another device now reports the same error as on this device.** It answered `session_not_found` remotely and `unknown_session` locally; both now answer `unknown_session`. ([#12755](https://github.com/code-yeongyu/oh-my-openagent/issues/12755)) ([#12756](https://github.com/code-yeongyu/oh-my-openagent/pull/12756))
23
+
24
+ **omo hands its device keys to the device service from memory, with no credential store read for relay.** A fresh sign-in (`omo login`, `omo account adopt`) deletes the signed-out marker and then hands its in-memory keys and account to a running device service. The memory sync session re-adopts from the credential it already holds when the service reports no adopted device. Every sign-out path (logout, forget, a session the service ended) tells the service to forget the device. The start-up bootstrap no longer reads the stored credential. `device.adopt` carries `account` only to a device service at 0.1.3 or newer, and the pinned device service is raised to 0.1.3 (design D PR 4). ([#12735](https://github.com/code-yeongyu/oh-my-openagent/pull/12735))
25
+
26
+ **`omo remote` can open, send, switch model, interrupt and close sessions on your other devices.** `omo remote open <device> [--project P] [--model M]` starts a session there and prints `<device>/<session>`; `omo remote send <device>/<session> <text>` prints the answer as it streams in and returns when the turn settles (`--steer` steers the running turn, `--follow-up` queues behind it, `--no-wait` returns once the session took the message); `model`, `interrupt` and `close` do what they say. Each verb is the same remote op the agent's thread tools use, and `--json` prints its typed result. A steer to a session on another device now reaches it when that device's engine reports its running turn, instead of always being refused. ([#12709](https://github.com/code-yeongyu/oh-my-openagent/pull/12709), part of [#12320](https://github.com/code-yeongyu/oh-my-openagent/issues/12320))
27
+
28
+ Creating or forking a thread on another device no longer waits for a separate `session.locate` round trip: the create asks the relay for the new session's id on the `open_session` reply and uses it. A relay daemon without that answer (an older host, or an older service on this device) is handled as before, with `session.locate`. ([#12686](https://github.com/code-yeongyu/oh-my-openagent/pull/12686))
29
+
30
+ **`omo update` on the standalone binary now replaces the installed `omo`.** It used to print a replace command for the copy under `~/.omo/binary-runtime/<version>/`, which the next launch put back, so the update never took. A launch also removes old runtime versions there, keeping the previous one for a rollback and any version still running. ([#12627](https://github.com/code-yeongyu/oh-my-openagent/pull/12627), fixes [#12626](https://github.com/code-yeongyu/oh-my-openagent/issues/12626))
31
+
32
+ **Each memory identity's runtime directory is capped at 2 GiB, and `omo doctor` and `/doctor` show how much it holds.** After retention, the 12-hour memory maintenance pass evicts oldest-first until the identity fits `memory.runtime.max_bytes` (default 2 GiB, `0` for unbounded, per-agent overridable under `memory.agents.<id>.runtime`). It removes folded reflection runs first, then the transcripts of fully reflected sessions, idle sidecars, and finally old failed runs beyond the newest ten. Journals that were never or only partly reflected are kept by default; `memory.runtime.discard_unreflected_journals: true` lets the cap evict them too, and only while reflection is succeeding on the identity. Live sessions, in-flight runs and the run-id high water are never touched. `omo doctor` prints each identity's runtime size and the total, and warns when an identity reaches 80 % of its cap. `/doctor` adds a `runtime-size` check with the largest stores and what retention would still free. ([#12538](https://github.com/code-yeongyu/oh-my-openagent/pull/12538))
33
+
34
+ **Memory no longer grows without bound on disk.** The background memory maintenance pass now removes finished reflection runs, fully reflected transcripts, recall sidecars and legacy stores past configurable windows (`memory.runtime.retention_days` 7, `completions_days` 30), in time-boxed slices that resume where they stopped. Transcript input reflection never folded into memory is kept unless you turn on `discard_unreflected_journals` (then removed after `abandoned_journal_days`, 14, only while reflection works for that agent). Nothing a live session owns, no locked or unfinished work and no run id reflection still needs is touched. ([#12532](https://github.com/code-yeongyu/oh-my-openagent/pull/12532))
35
+
36
+ A reflection lock left behind by a run whose processes died (launcher killed before the run started, supervisor and child gone with no outcome, an unreadable run ledger, or a torn `active.lock`) is now released at session start, on the next turn, and by the new `omo doctor --fix` (`--dry-run` to preview, `/doctor --fix` in a session), instead of keeping every later reflection queued; `omo doctor --fix` also reclaims runtime locks whose owner is gone. ([#12517](https://github.com/code-yeongyu/oh-my-openagent/pull/12517))
37
+
38
+ ### Fixed
39
+
40
+ - Senpi: omo now names any senpi feature it relies on that the running senpi lacks in one startup warning, and opening a monitor on another device's session on a senpi without remote wake fails with `remote_wake_unavailable` instead of starting a watch that never wakes. A contract test checks every such feature against the pinned senpi. ([#12862](https://github.com/code-yeongyu/oh-my-openagent/pull/12862), fixes [#12861](https://github.com/code-yeongyu/oh-my-openagent/issues/12861))
41
+ - The browser skill now depends on the published `omowright` package (`^0.3.0`, the first release that ships a built `dist/` that loads under Node as well as Bun) instead of a git commit. Its runtime stager and loader accept omowright's TypeScript sources, the older JavaScript sources, or a compiled `dist/`, in that order, so a future layout change cannot silently break the staged browser runtime (#12842, #12851, #12847). ([#12847](https://github.com/code-yeongyu/oh-my-openagent/pull/12847))
42
+ - Memory facts extraction records facts again with senpi 2026.11.6-3: the facts child (also used by onboarding's understand step) keeps the approval mode its own settings give it and may run only its own record tools without asking, instead of being refused as a child whose parent is gone. ([#12839](https://github.com/code-yeongyu/oh-my-openagent/pull/12839))
43
+ - Concurrent memory account resolves on a desktop host share one open, so the app sees one `descriptor` request instead of one per caller; a failed open is retried by the next resolve (carried from #12717, which this PR supersedes). ([#12839](https://github.com/code-yeongyu/oh-my-openagent/pull/12839))
44
+ - Thread tools: an agent can now reach a session on another device of the same account by its name. A name that matches the title of one live session on another device sends there, and a name shared across devices (or with a thread on this device) is refused as ambiguous with every candidate and its device listed, never picked silently. Claiming or renaming a thread alias on a signed-in CLI device now reaches the account's alias registry instead of always answering that the registry cannot be reached; an alias claimed on one device now reaches that thread from every other device instead of reporting its device offline, and a registry outage never changes how a plain name resolves. `omo thread read` resolves aliases and other devices' threads the way the agent's `thread_read` does. ([#12837](https://github.com/code-yeongyu/oh-my-openagent/pull/12837), fixes [#12833](https://github.com/code-yeongyu/oh-my-openagent/issues/12833))
45
+ - Release: the service-auth release step now refuses a bundle that carries more than one release key set, so it always checks the set the bundle ships. ([#12812](https://github.com/code-yeongyu/oh-my-openagent/pull/12812), fixes [#12617](https://github.com/code-yeongyu/oh-my-openagent/issues/12617))
46
+ - Runtime fallback: when a session times out and no fallback model can be prepared, the user is now warned even if nothing was awaiting a fallback, the warning names the real reason ("no available fallback models" while attempts remain, instead of "max fallback attempts reached"), and a compaction that outlives its watchdog budget returns control as a real cancellation without staying marked as recovering. ([#12790](https://github.com/code-yeongyu/oh-my-openagent/pull/12790), fixes [#12762](https://github.com/code-yeongyu/oh-my-openagent/issues/12762))
47
+ - Standalone binary on Windows: running the provisioned runtime copy directly (`~/.omo/binary-runtime/<version>/omo.exe`) no longer hands off to itself and reports itself as the installed launcher when the home path is spelled with an 8.3 short name or different letter case. ([#12772](https://github.com/code-yeongyu/oh-my-openagent/pull/12772), fixes [#12769](https://github.com/code-yeongyu/oh-my-openagent/issues/12769))
48
+ - While service accounts are closed, the compiled `omo` binary recognises the device-code `omo login` with the same option parse as the command itself, so `omo login -- --device` and similar argv get the immediate refusal instead of being handed on to the command. ([#12723](https://github.com/code-yeongyu/oh-my-openagent/pull/12723), fixes [#12646](https://github.com/code-yeongyu/oh-my-openagent/issues/12646))
49
+ - The browser skill's doctor no longer calls a browser ready when its only BrowserSkill extension is 0.4.0. That release left a "BrowserSkill" tab group in the user's browser after every task. The doctor now reports `outdated-extension` and tells the user to update the extension and delete the saved groups. ([#12663](https://github.com/code-yeongyu/oh-my-openagent/pull/12663))
50
+ - `omo` no longer warns "Could not download the OmO device service. Check the connection and try again." on every interactive start while the device service release it pins has not been published. A 404 for that release is now its own `not_published` state: the start stays quiet, and `omo remote bootstrap` says remote devices are not available in this build yet. A connection failure, a server error or a half-published release still warns. ([#12659](https://github.com/code-yeongyu/oh-my-openagent/pull/12659))
51
+ - When a dream or reflection run deletes, archives or moves a memory note, `[[path]]` and relative markdown links to it in other notes are now updated in the same run, after the completion check has decided which of the run's changes land. A moved note's links follow it, and the moved note's own relative links keep pointing at their targets. A note the run archived, meaning its `ARCHIVE.md` entry names the file (its path, or its file name when no other note shares it), is linked as `[[ARCHIVE.md|<old path> (archived)]]`. Links to any other removed note, such as one the user asked to forget, become plain text. A note the completion check refuses, or one whose rewrite it would refuse (for example a note that already holds secret-like text), or one that is not valid UTF-8, keeps its links as they were, so `/doctor` can still report those. A targeted `/dream --to <doc>` that removes its own target is no longer refused because of these link updates. Facts extraction also no longer writes into a month ledger path that was archived or deleted: that month's new facts go to `notes/facts/<month>-2.md` (then `-3`, ...), so an old link can never start pointing at unrelated new content. ([#12642](https://github.com/code-yeongyu/oh-my-openagent/issues/12642)) ([#12645](https://github.com/code-yeongyu/oh-my-openagent/pull/12645))
52
+ - Runtime fallback keeps compaction retries separate from the primary model chain and preserves substantive retry prompts. Compaction watchdogs defer within a bounded budget, exhausted native retry signals do not trigger an abort, and stuck-session watchdogs still return control when no replacement can be dispatched. Thanks @mradwankhalil. ([#11907](https://github.com/code-yeongyu/oh-my-openagent/pull/11907), fixes [#9786](https://github.com/code-yeongyu/oh-my-openagent/issues/9786))
53
+ - Background tasks let runtime fallback decide who recovers a session error before starting a replacement or finalizing the task. Exhausted and refused retries release recovery ownership, model-less retry errors can finish the task, and a slow decision never starts a competing replacement. ([#9683](https://github.com/code-yeongyu/oh-my-openagent/pull/9683), [#11907](https://github.com/code-yeongyu/oh-my-openagent/pull/11907))
54
+ - Runtime fallback keeps its place in the fallback chain when its own abort echoes back as a stop or idle event, and no longer mistakes its own retry for a manual model change. A failing fallback now moves on to the next model instead of going back to the model that just failed. ([#11901](https://github.com/code-yeongyu/oh-my-openagent/pull/11901), fixes [#6751](https://github.com/code-yeongyu/oh-my-openagent/issues/6751))
55
+ - Runtime fallback: a session timeout whose fallback dispatch is rejected now uses up the attempt, stops at `max_fallback_attempts`, and ends with an abort the caller sees instead of re-arming the timer forever. ([#11898](https://github.com/code-yeongyu/oh-my-openagent/pull/11898), fixes [#6637](https://github.com/code-yeongyu/oh-my-openagent/issues/6637))
56
+ - First-prompt refusal tests now await launch settlement when the bounded start report arrives first, preserving both untyped and non-credential refusal diagnostics without depending on subprocess startup speed (#11732). ([#11852](https://github.com/code-yeongyu/oh-my-openagent/pull/11852))
57
+
58
+ ### Changed
59
+
60
+ - Task children ask through the parent session instead of being refused: a child's permission prompt (and its other select, confirm, input and editor dialogs) is raised on the parent's UI, so Allow runs the child's call and Deny does not. A child the parent turn is waiting on asks on the connection that started that turn; a background child asks every attached client that may answer. Secret inputs and permanent grant selections are never forwarded. Children in their own process or on the task host open in the parent's approval mode and follow every later change of it, one change at a time and always ending on the latest; a child that could not follow is reported to the parent session. ([#12839](https://github.com/code-yeongyu/oh-my-openagent/pull/12839))
61
+ - `omo remote open` and the thread tools' create and fork on another device name the approval mode the new session runs in: the creating session's own mode, or for `omo remote open` the new `--permission-preset` flag, else this device's own setting; a setting that cannot be read is a usage error rather than the loosest mode. ([#12839](https://github.com/code-yeongyu/oh-my-openagent/pull/12839))
62
+ - The compiled engine no longer has the unused `installEngineCaTrust` startup routine. That routine set `NODE_USE_SYSTEM_CA=1` but had no caller, and engine launches set up certificate trust in the launcher trust stage. A new test checks that an engine started without `NODE_USE_SYSTEM_CA` in its environment does not get it from the launcher. Validation of `OMO_EXTRA_CA_CERTIFICATES` is unchanged. ([#12628](https://github.com/code-yeongyu/oh-my-openagent/pull/12628), part of #10762)
63
+
10
64
  ## [5.1.64] - 2026-11-07
11
65
 
12
66
  **Desktop memory sync now starts as soon as the engine boots, without waiting for a session.** An engine started by `omo host ensure` loads extensions only when a session opens, while the desktop opens none until the engine has sent the memory-sync bootstrap handshake, so the two waited on each other. The compiled `omo` and the npm launcher now start that one claim before the engine loads whenever an RPC engine's launch declares a `memory-sync` channel; the first session reuses it. A claim that fails still reports memory sync as unavailable and never falls back to CLI credentials. ([#12702](https://github.com/code-yeongyu/oh-my-openagent/issues/12702)) ([#12704](https://github.com/code-yeongyu/oh-my-openagent/pull/12704))
@@ -66,7 +66,7 @@ This is the dream's core duty: make memory smaller, better placed, and less redu
66
66
  - Demotion is reversible: it MOVES the file to `reference/` with a `[[path]]` cross-reference at the former point of use. It never deletes content.
67
67
  - A `system/` file whose frontmatter `expires` instant has passed is already out of context (the compiler skips it): demote it to `reference/` with its dates, and move any durable line inside it to the right `system/` file first. A temporary section inside a durable `system/` file has no machine expiry: split it into its own file with `expires: <ISO 8601>` (a UTC date or an instant with `Z` or an offset), or demote it when its stated end has passed.
68
68
 
69
- **Fact archiving**: entries in `notes/facts/` older than 6 months get summarized into `ARCHIVE.md`, the single non-system root archive file. Compress them into concise dated summary entries, append those to `ARCHIVE.md`, and remove the summarized originals. Keep anything younger, and keep anything old that's still clearly load-bearing. Delete (don't archive) content the user asked to forget, sensitive or wrong content, and junk with no future-reference value.
69
+ **Fact archiving**: entries in `notes/facts/` older than 6 months get summarized into `ARCHIVE.md`, the single non-system root archive file. Compress them into concise dated summary entries, append those to `ARCHIVE.md` with each entry naming the file it came from (for example `- 2026-03 (notes/facts/2026-03.md): ...`), and remove the summarized originals. Links to an archived file are pointed at `ARCHIVE.md` only when its entry names the file; links to anything you delete instead become plain text. Keep anything younger, and keep anything old that's still clearly load-bearing. Delete (don't archive) content the user asked to forget, sensitive or wrong content, and junk with no future-reference value.
70
70
 
71
71
  ### System Token Budget Contract
72
72
 
@@ -1,2 +1,2 @@
1
- // omo:xuOIQiYjrOkhUxmlBfKTTdGIg4Tqi3k2mDMYWQFh_-o:mg0_lw3g8IhF_1ku_RHA1U1nebviTCdHbR13JDRaV3I
1
+ // omo:3VI0CWsiVbf25vCMsRzCqPBzO0ppxkee3yDpyTtKQoA:mg0_lw3g8IhF_1ku_RHA1U1nebviTCdHbR13JDRaV3I
2
2
  import{chmodSync as e,closeSync as t,existsSync as n,mkdirSync as i,openSync as r}from"node:fs";import{join as s}from"node:path";import{setTimeout as o}from"node:timers/promises";import{parentPort as a}from"node:worker_threads";function d(e,t,n){return Object.assign(Error(`gateway store lock wait exceeded: ${e} waited ${t} ms for the write lock (limit ${n} ms); another process holds it`),{code:"gateway_lock_wait_exceeded"})}function u(e){return"object"==typeof e&&null!==e&&"gateway_lock_wait_exceeded"===e.code}import{join as l}from"node:path";function _(e){return l(e,"gateway")}function c(e){return l(_(e),"gateway.sqlite")}function p(e,t){return l(_(e),"inbox",t)}import{execFile as m}from"node:child_process";var g="epoch:",f=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function b(e){return new Promise(t=>{m("ps",["-o","lstart=","-p",String(e)],{env:{...process.env,LC_ALL:"C",LANG:"C",TZ:"UTC"},windowsHide:!0,timeout:5e3},(e,n)=>{let i=null===e?function(e){let t=/^[A-Z][a-z]{2} ([A-Z][a-z]{2}) +(\d{1,2}) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/.exec(e.trim());if(null===t)return null;let[,n,i,r,s,o,a]=t,d=f.indexOf(n);return d<0?null:Date.UTC(Number(a),d,Number(i),Number(r),Number(s),Number(o))/1e3}(n):null;t(null===i?null:`${g}${i}`)})})}async function E(e){if(!function(e){try{return process.kill(e,0),!0}catch(e){return!(e instanceof Error&&"code"in e&&"ESRCH"===e.code)}}(e.pid))return!0;if(null===e.process_start_time||!e.process_start_time.startsWith(g))return!1;let t=await b(e.pid);return null!==t&&t!==e.process_start_time}function h(e,t){return e.pid===t.pid&&e.process_start_time===t.process_start_time&&e.instance_id===t.instance_id}function*y(e){for(let t=0;t<e.length;){let n,i=t,r=e[t];if(r<=" ")for(n="space";t<e.length&&e[t]<=" ";)t++;else if("-"===r&&"-"===e[t+1])for(n="comment";t<e.length&&"\n"!==e[t];)t++;else if("/"===r&&"*"===e[t+1]){for(n="comment",t+=2;t<e.length&&("*"!==e[t]||"/"!==e[t+1]);)t++;t=Math.min(t+2,e.length)}else if("'"===r||'"'===r||"`"===r||"["===r){n="quoted";let i="["===r?"]":r;for(t++;t<e.length;)if(e[t++]===i){if("["===r||e[t]!==i)break;t++}}else if("?"===r||";"===r)n="?"===r?"parameter":"semicolon",t++;else for(n="text",t++;t<e.length&&e[t]>" "&&!["'",'"',"`","[","?",";","-","/"].includes(e[t]);)t++;yield{kind:n,text:e.slice(i,t)}}}class v{params=[];sinkRows=[];authorizer=null;db;constructor(e){this.db=e,e.function("gw_p",{deterministic:!1},e=>this.params[e]??null),e.function("gw_sink",{varargs:!0,deterministic:!1},(...e)=>(this.sinkRows.push(e),null))}exec(e){this.db.exec(e)}authorized(e,t){let n=this.authorizer;this.authorizer=e,this.db.setAuthorizer(e);try{return t()}finally{this.authorizer=n,this.db.setAuthorizer(n)}}resultColumns(e){return this.authorized(null,()=>{this.db.exec(`CREATE TEMP VIEW gw_result_columns AS ${T(e)}\n`);try{return this.all(["name"],"SELECT cid, name FROM pragma_table_info('gw_result_columns', 'temp')",[],"cid").map(e=>String(e.name))}finally{this.db.exec("DROP VIEW temp.gw_result_columns")}})}run(e,t=[]){this.params=t;try{this.db.exec(T(e))}finally{this.params=[]}return Number(this.all(["n"],"SELECT changes() AS n")[0]?.n??0)}all(e,t,n=[],i){this.params=n,this.sinkRows=[];try{let n=void 0===i?"0":`row_number() OVER (ORDER BY ${i})`;return this.db.exec(`SELECT gw_sink(${n}, ${e.join(", ")}) FROM (${T(t)}\n)${void 0===i?"":` ORDER BY ${i}`}`),(void 0===i?this.sinkRows:this.sinkRows.toSorted((e,t)=>Number(e[0])-Number(t[0]))).map(t=>Object.fromEntries(e.map((e,n)=>[e,t[n+1]??null])))}finally{this.params=[],this.sinkRows=[]}}one(e,t,n=[]){return this.all(e,t,n)[0]}}function T(e){let t=0,n="";for(let i of y(e))n+="parameter"===i.kind?`gw_p(${t++})`:i.text;return n}function w(e){if("object"!=typeof e||null===e)return!1;let t=e;return 5===t.errcode||6===t.errcode||"string"==typeof t.message&&/database is (locked|busy)/i.test(t.message)}import{createHash as N,randomUUID as L}from"node:crypto";import{closeSync as k,constants as O,mkdirSync as x,openSync as R,readdirSync as S,readFileSync as A,rmSync as q,writeSync as I}from"node:fs";import{userInfo as C}from"node:os";import{join as $}from"node:path";var U=5e3,D=864e5,M=6048e5,H=1048576,W=2592e6,X=2592e6,F=256,j="session_released";import{existsSync as P,readFileSync as G}from"node:fs";import{join as B}from"node:path";function J(e){let t=B(e,"mailbox.jsonl");if(P(t))return function(e){let t=e.slice(0,e.lastIndexOf("\n")+1),n=new Map;for(let e of t.split("\n")){if(0===e.length)continue;let t=JSON.parse(e);if(!z(t)||1!==t.version)throw Error("invalid legacy mailbox event");if("snapshot"===t.kind&&Array.isArray(t.items)){n.clear();for(let e of t.items){let t=Y(e);n.set(t.message_seq,t)}}else if("enqueue"===t.kind){let e=Y(t.item);n.set(e.message_seq,e)}else{if("remove"!==t.kind||"number"!=typeof t.message_seq)throw Error("invalid legacy mailbox event");n.delete(t.message_seq)}}return K([...n.values()])}(G(t,"utf8"));let n=B(e,"mailbox.json");if(!P(n))return null;let i=JSON.parse(G(n,"utf8"));if(!z(i)||!z(i.queues))throw Error(`invalid legacy mailbox state: ${n}`);let r=[];for(let e of Object.values(i.queues)){if(!Array.isArray(e))throw Error(`invalid legacy mailbox queue: ${n}`);for(let t of e)r.push(Y(t))}return K(r)}function K(e){return e.toSorted((e,t)=>e.message_seq-t.message_seq)}function Y(e){if(!z(e)||"string"!=typeof e.target||"string"!=typeof e.message||"number"!=typeof e.message_seq||!Number.isInteger(e.message_seq)||"auto"!==e.delivery&&"steer"!==e.delivery&&"follow_up"!==e.delivery||void 0!==e.expected_turn_id&&"string"!=typeof e.expected_turn_id||"string"!=typeof e.operation_id||"string"!=typeof e.accepted_at)throw Error("invalid legacy mailbox item");return{target:e.target,message:e.message,message_seq:e.message_seq,delivery:e.delivery,expected_turn_id:void 0===e.expected_turn_id?null:V(e.expected_turn_id),operation_id:e.operation_id,accepted_at:e.accepted_at}}function V(e){let t=/^turn-(0|[1-9]\d*)$/.exec(e);if(null===t)return null;let n=Number(t[1]);return Number.isSafeInteger(n)?n:null}function z(e){return"object"==typeof e&&null!==e&&!Array.isArray(e)}import{createHash as Z,createHmac as Q,randomUUID as ee,timingSafeEqual as te}from"node:crypto";var ne=["discord","telegram","slack","notion","feishu","herdr","custom","whatsapp"],ie=["milestone","report","question","completion"],re=["auto","follow_up"],se=31622400,oe=2592e6;function ae(e){return new Date(e).toISOString()}function de(e){return{kind:"refused",code:"invalid_arguments",message:e}}function ue(e,t){return"string"!=typeof t||0===t.trim().length?de(`${e} must be a non-empty string.`):t.length>256?de(`${e} is longer than 256 characters.`):/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/.test(t)?de(`${e} carries a control character or a line separator.`):t}function le(e,t){return null==t?null:ue(e,t)}function _e(e){return"object"==typeof e&&null!==e&&"refused"===e.kind}function ce(e){if(null===e||"object"!=typeof e)return JSON.stringify(e)??"null";if(Array.isArray(e))return`[${e.map(ce).join(",")}]`;let t=e;return`{${Object.keys(t).filter(e=>void 0!==t[e]).sort().map(e=>`${JSON.stringify(e)}:${ce(t[e])}`).join(",")}}`}function pe(e){return Buffer.from(e).toString("base64url")}function me(e,t){return pe(JSON.stringify({v:1,as_of:e,after:t}))}var ge="rt1";function fe(e,t){return Q("sha256",e).update(`${ge}.${t}`).digest().subarray(0,16).toString("base64url")}var be=new WeakMap;function Ee(e,t,n){return Ce(e,"DELETE FROM receipts WHERE principal = ? AND operation = ? AND idempotency_key = ? AND expires_at <= ?",[t.principal,t.operation,t.idempotency_key,n])}function he(e,t,n=0){if(t<(be.get(e.sql)??Number.NEGATIVE_INFINITY))return null;let i=function(e,t,n=256){let i=F,r=Ce(e,"DELETE FROM receipts WHERE rowid IN (SELECT rowid FROM receipts WHERE expires_at <= ? LIMIT ?)",[t,n]),s=Ce(e,"DELETE FROM deliveries WHERE delivery_id IN (SELECT d.delivery_id FROM deliveries d WHERE d.state IN ('applied', 'refused') AND d.updated_at <= ? AND NOT EXISTS (SELECT 1 FROM receipts r WHERE r.delivery_id = d.delivery_id) LIMIT ?)",[t-X,i]),o=Ce(e,"DELETE FROM causal_edges WHERE rowid IN (SELECT e.rowid FROM causal_edges e JOIN causal_roots r ON r.root_id = e.root_id WHERE r.expires_at <= ? LIMIT ?)",[t,i]),a=Ce(e,"DELETE FROM causal_roots WHERE root_id IN (SELECT r.root_id FROM causal_roots r WHERE r.expires_at <= ? AND NOT EXISTS (SELECT 1 FROM causal_edges e WHERE e.root_id = r.root_id) LIMIT ?)",[t,i]),d=Ce(e,"DELETE FROM rate_buckets WHERE rowid IN (SELECT rowid FROM rate_buckets WHERE updated_at <= ? LIMIT ?)",[t-4e4,i]),u=Ce(e,`DELETE FROM bindings WHERE binding_id IN (SELECT b.binding_id FROM bindings b WHERE b.status != 'active' AND b.updated_at <= ?\n AND NOT EXISTS (SELECT 1 FROM outbox o WHERE o.binding_id = b.binding_id)\n AND NOT EXISTS (SELECT 1 FROM completion_arms a WHERE a.binding_id = b.binding_id)\n AND NOT EXISTS (SELECT 1 FROM deliveries d WHERE d.binding_id = b.binding_id AND d.state IN ${xe}) LIMIT ?)`,[ae(t-oe),i]),l=Ce(e,"DELETE FROM outbox_cursors WHERE binding_id IN (SELECT c.binding_id FROM outbox_cursors c WHERE NOT EXISTS (SELECT 1 FROM bindings b WHERE b.binding_id = c.binding_id) LIMIT ?)",[i]),_=Ce(e,"DELETE FROM session_meta WHERE durable_id IN (SELECT m.durable_id FROM session_meta m WHERE\n m.incarnation IS NULL\n AND NOT EXISTS (SELECT 1 FROM deliveries d WHERE d.target_durable_id = m.durable_id)\n AND NOT EXISTS (SELECT 1 FROM bindings b WHERE b.session_durable_id = m.durable_id)\n AND NOT EXISTS (SELECT 1 FROM outbox o WHERE o.session_durable_id = m.durable_id)\n AND NOT EXISTS (SELECT 1 FROM completion_arms a WHERE a.session_durable_id = m.durable_id) LIMIT ?)",[i]);return{receipts:r,deliveries:s,causal_edges:o,causal_roots:a,rate_buckets:d,bindings:u,outbox_cursors:l,session_meta:_}}(e,t,Math.max(F-n,0)),r=i.receipts+n>=F||Object.values(i).some(e=>e>=F);return be.set(e.sql,r?t:t+36e5),i}var ye=new Set(["invalid_arguments","caller_context_missing","not_found","ambiguous_target","scope_denied","name_conflict","not_resumable","orphaned","foreign_live_owner","no_active_turn","turn_conflict","not_steerable","message_too_large","queue_full","cursor_invalid","cursor_stale","idempotency_conflict","idempotency_in_progress","idempotency_uncertain","approval_unavailable","approval_route_locked","partial_commit","unsupported","overloaded","transport_closed","host_unavailable","internal_error","model_not_found","model_ambiguous","thinking_level_unsupported","loop_detected","binding_conflict","binding_mismatch","binding_inactive","stale_revision","stale_token","already_answered","answer_in_progress","device_offline","relay_requires_paid_plan","alias_taken"]);function ve(e,t,n,i){if("string"!=typeof(r=e)||!ye.has(r))throw Error(`unknown thread error code: ${String(e)}`);var r;return{code:e,message:t,next_action:n,...void 0===i?{}:{details:i}}}var Te={not_steerable:{code:"not_steerable",next:"Send with delivery auto or follow_up; a steer needs a running turn."},turn_conflict:{code:"turn_conflict",next:"Read the target again and retry with its current turn id, or send with delivery auto."},expired:{code:"not_resumable",next:"The target did not take the message within its lifetime; send it again if it still matters."},binding_closed:{code:"invalid_arguments",next:"The binding this message was queued under was detached or rebound; re-read the binding and send again."}};function we(e,t,n,i,r){let s={kind:"ok",thread_id:e.target_durable_id,delivery_id:e.delivery_id,message_seq:e.seq,effective_mode:e.mode_effective??e.mode_requested,endpoint_kind:n,deduplicated:i};if("admitted"===e.state||"applied"===e.state)return"started"===e.admission_kind||"steered"===e.admission_kind?{...s,delivery:{kind:e.admission_kind,turn_id:String(e.turn_epoch??0)}}:{...s,delivery:{kind:"queued",queue_position:Math.max(t,1)}};if("refused"===e.state){let t=Te[e.reason??""]??{code:"internal_error",next:"Call thread_list and check the target."};return{kind:"error",error:ve(t.code,`Delivery ${e.delivery_id} was refused: ${e.reason??"unknown"}.`,t.next,{delivery_id:e.delivery_id})}}return"uncertain"===e.state?{kind:"error",error:ve("idempotency_uncertain",`Delivery ${e.delivery_id} may or may not have reached the target.`,"Read the target transcript before deciding whether to send again.",{delivery_id:e.delivery_id})}:{...s,delivery:{kind:r?"queued_offline":"queued",queue_position:Math.max(t,1)}}}var Ne=["CREATE TRIGGER IF NOT EXISTS deliveries_require_provenance BEFORE INSERT ON deliveries\n WHEN CASE WHEN json_valid(NEW.envelope) THEN\n coalesce(json_type(NEW.envelope, '$.provenance'), '') != 'object'\n OR coalesce(json_type(NEW.envelope, '$.provenance.workspace'), '') != 'text'\n OR coalesce(length(trim(json_extract(NEW.envelope, '$.provenance.workspace'))), 0) = 0\n OR coalesce(json_type(NEW.envelope, '$.provenance.project'), '') != 'text'\n OR coalesce(length(trim(json_extract(NEW.envelope, '$.provenance.project'))), 0) = 0\n OR coalesce(json_type(NEW.envelope, '$.provenance.lane'), 'text') != 'text'\n OR coalesce(json_type(NEW.envelope, '$.provenance.session'), 'text') != 'text'\n ELSE 1 END\n BEGIN SELECT RAISE(ABORT, 'delivery provenance is required: restart the sending session on the upgraded omo'); END","INSERT OR IGNORE INTO extension_objects (type, name, owner) VALUES ('trigger', 'deliveries_require_provenance', NULL)"];class Le extends Error{found;supported;code="gateway_schema_too_new";constructor(e,t,n="Gateway"){super(`${n} schema ${e} is newer than this binary's supported version ${t}.`),this.found=e,this.supported=t}}var ke=[["CREATE TABLE deliveries (\n delivery_id TEXT PRIMARY KEY,\n target_durable_id TEXT NOT NULL,\n seq INTEGER NOT NULL,\n sender TEXT NOT NULL,\n sender_turn TEXT,\n envelope TEXT NOT NULL,\n body TEXT NOT NULL,\n bytes INTEGER NOT NULL,\n mode_requested TEXT NOT NULL CHECK (mode_requested IN ('auto', 'steer', 'follow_up')),\n mode_effective TEXT CHECK (mode_effective IS NULL OR mode_effective IN ('steer', 'follow_up')),\n expected_turn_id INTEGER,\n state TEXT NOT NULL CHECK (state IN ('queued', 'admitting', 'admitted', 'applied', 'refused', 'uncertain')),\n reason TEXT,\n admitted_by TEXT,\n claimed_at INTEGER,\n attempt INTEGER NOT NULL DEFAULT 0,\n admission_kind TEXT,\n turn_epoch INTEGER,\n root_id TEXT NOT NULL,\n hop INTEGER NOT NULL,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n expires_at INTEGER NOT NULL,\n binding_id TEXT,\n binding_revision INTEGER,\n UNIQUE (target_durable_id, seq)\n )","CREATE INDEX deliveries_target_state_seq ON deliveries (target_durable_id, state, seq)","CREATE INDEX deliveries_root ON deliveries (root_id)","CREATE INDEX deliveries_sender_turn ON deliveries (sender, sender_turn)","CREATE TABLE receipts (\n principal TEXT NOT NULL,\n operation TEXT NOT NULL,\n idempotency_key TEXT NOT NULL,\n args_hash TEXT NOT NULL,\n status TEXT NOT NULL CHECK (status IN ('prepared', 'completed', 'uncertain')),\n delivery_id TEXT,\n owner_instance TEXT NOT NULL,\n result TEXT,\n error_note TEXT,\n created_at INTEGER NOT NULL,\n updated_at INTEGER NOT NULL,\n expires_at INTEGER NOT NULL,\n PRIMARY KEY (principal, operation, idempotency_key)\n )","CREATE INDEX receipts_expiry ON receipts (expires_at)","CREATE TABLE causal_roots (\n root_id TEXT PRIMARY KEY,\n origin_principal TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n expires_at INTEGER NOT NULL\n )","CREATE TABLE causal_edges (\n root_id TEXT NOT NULL,\n from_durable_id TEXT NOT NULL,\n to_durable_id TEXT NOT NULL,\n delivery_id TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n PRIMARY KEY (root_id, from_durable_id, to_durable_id)\n )","CREATE TABLE rate_buckets (\n sender TEXT NOT NULL,\n target_durable_id TEXT NOT NULL,\n tokens REAL NOT NULL,\n updated_at INTEGER NOT NULL,\n PRIMARY KEY (sender, target_durable_id)\n )","CREATE TABLE session_meta (\n durable_id TEXT PRIMARY KEY,\n next_seq INTEGER NOT NULL,\n applied_seq INTEGER NOT NULL DEFAULT 0\n )","CREATE TABLE bindings (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n binding_id TEXT NOT NULL UNIQUE,\n schema_version INTEGER NOT NULL DEFAULT 1,\n revision INTEGER NOT NULL CHECK (revision >= 1),\n status TEXT NOT NULL CHECK (status IN ('active', 'detached', 'expired')),\n platform TEXT NOT NULL CHECK (platform IN ('discord', 'telegram', 'slack', 'notion', 'feishu', 'herdr', 'custom', 'whatsapp')),\n account_id TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n thread_id TEXT NOT NULL,\n root_message_id TEXT,\n progress_message_id TEXT,\n session_realm_id TEXT NOT NULL,\n session_durable_id TEXT NOT NULL,\n direction_inbound INTEGER NOT NULL CHECK (direction_inbound IN (0, 1)),\n direction_outbound INTEGER NOT NULL CHECK (direction_outbound IN (0, 1)),\n inbound_mode TEXT NOT NULL CHECK (inbound_mode IN ('auto', 'follow_up')),\n outbound_events TEXT NOT NULL,\n policy_id TEXT NOT NULL,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n lease_started_at TEXT NOT NULL,\n ttl_seconds INTEGER,\n expires_at TEXT,\n CHECK (direction_inbound = 1 OR direction_outbound = 1)\n )","CREATE UNIQUE INDEX bindings_one_active_thread ON bindings (platform, account_id, chat_id, thread_id) WHERE status = 'active'","CREATE INDEX bindings_session ON bindings (session_durable_id, status)","CREATE TABLE outbox (\n cursor INTEGER PRIMARY KEY AUTOINCREMENT,\n binding_id TEXT NOT NULL,\n revision INTEGER NOT NULL,\n event_kind TEXT NOT NULL CHECK (event_kind IN ('milestone', 'report', 'question', 'completion', 'question_closed')),\n payload TEXT NOT NULL,\n state TEXT NOT NULL CHECK (state IN ('pending', 'acked')),\n provider_message_id TEXT,\n created_at INTEGER NOT NULL,\n acked_at INTEGER\n )","CREATE INDEX outbox_binding_cursor ON outbox (binding_id, cursor)","CREATE TABLE gateway_meta (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n )"],["ALTER TABLE session_meta ADD COLUMN incarnation TEXT","ALTER TABLE outbox ADD COLUMN session_durable_id TEXT","ALTER TABLE outbox ADD COLUMN reply_token TEXT","ALTER TABLE outbox ADD COLUMN ui_request_id TEXT","ALTER TABLE outbox ADD COLUMN incarnation TEXT","ALTER TABLE outbox ADD COLUMN question_state TEXT CHECK (question_state IS NULL OR question_state IN ('pending', 'answered', 'expired', 'cancelled'))","ALTER TABLE outbox ADD COLUMN answer TEXT","ALTER TABLE outbox ADD COLUMN answered_at INTEGER","ALTER TABLE outbox ADD COLUMN outcome TEXT CHECK (outcome IS NULL OR outcome IN ('completed', 'failed', 'cancelled'))","CREATE UNIQUE INDEX outbox_reply_token ON outbox (reply_token) WHERE reply_token IS NOT NULL","CREATE TABLE outbox_cursors (\n binding_id TEXT PRIMARY KEY,\n acked_cursor INTEGER NOT NULL,\n updated_at INTEGER NOT NULL\n )","CREATE TABLE completion_arms (\n arm_seq INTEGER PRIMARY KEY AUTOINCREMENT,\n session_durable_id TEXT NOT NULL,\n binding_id TEXT NOT NULL,\n revision INTEGER NOT NULL,\n text TEXT NOT NULL,\n armed_at INTEGER NOT NULL\n )","CREATE INDEX completion_arms_session ON completion_arms (session_durable_id, armed_at)","INSERT OR IGNORE INTO gateway_meta (key, value) VALUES ('realm_id', 'realm-' || lower(hex(randomblob(16))))","INSERT OR IGNORE INTO gateway_meta (key, value) VALUES ('token_secret', lower(hex(randomblob(32))))"],["ALTER TABLE outbox ADD COLUMN ui_request_kind TEXT CHECK (ui_request_kind IS NULL OR ui_request_kind IN ('question', 'select', 'confirm', 'input', 'editor'))","ALTER TABLE outbox ADD COLUMN answer_state TEXT CHECK (answer_state IS NULL OR answer_state IN ('in_flight', 'delivered'))"],["ALTER TABLE outbox ADD COLUMN answered_by TEXT"],["ALTER TABLE session_meta ADD COLUMN endpoint_socket TEXT","ALTER TABLE session_meta ADD COLUMN endpoint_kind TEXT CHECK (endpoint_kind IS NULL OR endpoint_kind IN ('tui', 'rpc_host'))"],["CREATE TABLE extension_schema (name TEXT PRIMARY KEY, version INTEGER NOT NULL, updated_at INTEGER NOT NULL)","ALTER TABLE deliveries ADD COLUMN actor_user_id TEXT","CREATE TABLE extension_objects (type TEXT NOT NULL, name TEXT NOT NULL, owner TEXT, PRIMARY KEY (type, name))","INSERT INTO extension_objects (type, name, owner) SELECT type, name, NULL FROM sqlite_schema"],["CREATE TABLE bindings_v7 (\n seq INTEGER PRIMARY KEY AUTOINCREMENT,\n binding_id TEXT NOT NULL UNIQUE,\n schema_version INTEGER NOT NULL DEFAULT 1,\n revision INTEGER NOT NULL CHECK (revision >= 1),\n status TEXT NOT NULL CHECK (status IN ('active', 'detached', 'expired')),\n platform TEXT NOT NULL CHECK (platform IN ('discord', 'telegram', 'slack', 'notion', 'feishu', 'herdr', 'custom', 'whatsapp')),\n account_id TEXT NOT NULL,\n chat_id TEXT NOT NULL,\n thread_id TEXT NOT NULL,\n root_message_id TEXT,\n progress_message_id TEXT,\n session_realm_id TEXT NOT NULL,\n session_durable_id TEXT NOT NULL,\n direction_inbound INTEGER NOT NULL CHECK (direction_inbound IN (0, 1)),\n direction_outbound INTEGER NOT NULL CHECK (direction_outbound IN (0, 1)),\n inbound_mode TEXT NOT NULL CHECK (inbound_mode IN ('auto', 'follow_up')),\n outbound_events TEXT NOT NULL,\n policy_id TEXT NOT NULL,\n created_at TEXT NOT NULL,\n updated_at TEXT NOT NULL,\n lease_started_at TEXT NOT NULL,\n ttl_seconds INTEGER,\n expires_at TEXT,\n CHECK (direction_inbound = 1 OR direction_outbound = 1)\n )","INSERT INTO bindings_v7 SELECT seq, binding_id, schema_version, revision, status, platform, account_id, chat_id, thread_id, root_message_id, progress_message_id, session_realm_id, session_durable_id, direction_inbound, direction_outbound, inbound_mode, outbound_events, policy_id, created_at, updated_at, lease_started_at, ttl_seconds, expires_at FROM bindings","UPDATE sqlite_sequence SET seq = (SELECT seq FROM sqlite_sequence WHERE name = 'bindings') WHERE name = 'bindings_v7'","DROP TABLE bindings","ALTER TABLE bindings_v7 RENAME TO bindings","CREATE UNIQUE INDEX bindings_one_active_thread ON bindings (platform, account_id, chat_id, thread_id) WHERE status = 'active'","CREATE INDEX bindings_session ON bindings (session_durable_id, status)"],Ne,[...Ne,"CREATE TABLE IF NOT EXISTS thread_creations (\n creator_durable_id TEXT NOT NULL,\n created_durable_id TEXT NOT NULL,\n created_at INTEGER NOT NULL,\n PRIMARY KEY (creator_durable_id, created_durable_id)\n )","CREATE TABLE IF NOT EXISTS extension_registrations (name TEXT PRIMARY KEY, descriptor_json TEXT NOT NULL, updated_at INTEGER NOT NULL)","INSERT OR IGNORE INTO extension_objects (type, name, owner)\n SELECT s.type, s.name, NULL FROM sqlite_schema s\n WHERE NOT EXISTS (SELECT 1 FROM extension_objects e WHERE e.type = s.type AND e.name = s.name COLLATE NOCASE)"],[...Ne,"CREATE TABLE IF NOT EXISTS toolkit_replay_receipts (\n replay_key TEXT PRIMARY KEY,\n op TEXT NOT NULL,\n args_sha256 TEXT NOT NULL,\n result_json TEXT NOT NULL,\n turn_at INTEGER NOT NULL,\n created_at INTEGER NOT NULL\n )","CREATE INDEX IF NOT EXISTS toolkit_replay_receipts_turn_at ON toolkit_replay_receipts (turn_at)","INSERT OR IGNORE INTO extension_objects (type, name, owner)\n SELECT s.type, s.name, NULL FROM sqlite_schema s\n WHERE NOT EXISTS (SELECT 1 FROM extension_objects e WHERE e.type = s.type AND e.name = s.name COLLATE NOCASE)"]],Oe=["delivery_id","target_durable_id","seq","sender","sender_turn","envelope","body","bytes","mode_requested","mode_effective","expected_turn_id","state","reason","admitted_by","claimed_at","attempt","admission_kind","turn_epoch","root_id","hop","created_at","updated_at","expires_at","binding_id","binding_revision","actor_user_id"],xe="('queued', 'admitting', 'admitted')",Re=/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;function Se(e,t,n){return{kind:"refused",code:e,message:t,...void 0===n?{}:{details:n}}}function Ae(e){let t=e=>null==e?null:Number(e);return{delivery_id:String(e.delivery_id),target_durable_id:String(e.target_durable_id),seq:Number(e.seq),sender:String(e.sender),sender_turn:null===e.sender_turn?null:String(e.sender_turn),envelope:JSON.parse(String(e.envelope)),body:String(e.body),bytes:Number(e.bytes),mode_requested:e.mode_requested,mode_effective:e.mode_effective??null,expected_turn_id:t(e.expected_turn_id),state:e.state,reason:null===e.reason?null:String(e.reason),admitted_by:null===e.admitted_by?null:JSON.parse(String(e.admitted_by)),claimed_at:t(e.claimed_at),attempt:Number(e.attempt),admission_kind:null===e.admission_kind?null:String(e.admission_kind),turn_epoch:t(e.turn_epoch),root_id:String(e.root_id),hop:Number(e.hop),created_at:Number(e.created_at),updated_at:Number(e.updated_at),expires_at:Number(e.expires_at),binding_id:null===e.binding_id?null:String(e.binding_id),binding_revision:t(e.binding_revision),actor_user_id:null===e.actor_user_id?null:String(e.actor_user_id)}}function qe(e,t,n,i){return e.sql.all(Oe,`SELECT ${Oe.join(", ")} FROM deliveries WHERE ${t}`,n,i).map(Ae)}function Ie(e,t){return qe(e,"delivery_id = ?",[t])[0]}function Ce(e,t,n=[]){let i=e.sql.run(t,n);return e.stats.writes+=i,i}function $e(e,t){if("queued"!==t.state&&"admitting"!==t.state&&"admitted"!==t.state)return 0;let n=e.sql.one(["n"],`SELECT COUNT(*) AS n FROM deliveries WHERE target_durable_id = ? AND state IN ${xe} AND seq <= ?`,[t.target_durable_id,t.seq]);return Number(n?.n??1)}async function Ue(e,t,n){if(void 0!==e.afterCommit)return e.sql.exec("SAVEPOINT gateway_enqueue"),!0;let i=Date.now();for(;;)try{return e.sql.exec("BEGIN IMMEDIATE"),e.stats.transactions++,!0}catch(r){if(!w(r))throw r;if(e.emit({kind:"busy",op:t}),!n)return!1;let s=Date.now()-i;if(s+2*e.config.busy_timeout_ms>e.config.lock_wait_max_ms)throw e.emit({kind:"lock_wait_exceeded",op:t,waited_ms:s}),d(t,s,e.config.lock_wait_max_ms);await e.delay(e.config.busy_timeout_ms)}}function De(e){try{e.sql.exec(void 0===e.afterCommit?"ROLLBACK":"ROLLBACK TO gateway_enqueue; RELEASE gateway_enqueue")}catch{return}}async function Me(e,t,n){if(void 0!==e.afterCommit)return await n();await Ue(e,t,!0);try{let t=await n();return e.sql.exec("COMMIT"),t}catch(t){throw De(e),t}}function He(e,t,n,i){let r=p(e.config.agent_dir,t);x(r,{recursive:!0,mode:448});let s,o=$(r,n);try{s=R(o,O.O_CREAT|O.O_EXCL|O.O_WRONLY,384)}catch(e){if(i&&e instanceof Error&&"code"in e&&"EEXIST"===e.code)return o;throw e}try{I(s,JSON.stringify({pid:e.self.pid,process_start_time:e.self.process_start_time}))}finally{k(s)}return e.afterRollback?.push(()=>q(o,{force:!0})),o}function We(e,t,n){if(void 0!==e.afterCommit)return void e.afterCommit.push(()=>We({...e,afterCommit:void 0},t,n));let i=$(p(e.config.agent_dir,t),n);try{q(i),e.stats.marker_unlinks++}catch(e){if(!(e instanceof Error&&"code"in e&&"ENOENT"===e.code))throw e}}function Xe(e,t){try{return S(p(e.config.agent_dir,t)).filter(e=>!e.startsWith("."))}catch(e){if(e instanceof Error&&"code"in e&&"ENOENT"===e.code)return[];throw e}}function Fe(e,t){let n=e.sql.one(["next_seq"],"SELECT next_seq FROM session_meta WHERE durable_id = ?",[t]),i=Number(void 0===n?e.sql.one(["m"],"SELECT COALESCE(MAX(seq), 0) + 1 AS m FROM deliveries WHERE target_durable_id = ?",[t])?.m??1:n.next_seq);return Ce(e,"INSERT INTO session_meta (durable_id, next_seq) VALUES (?, ?) ON CONFLICT(durable_id) DO UPDATE SET next_seq = excluded.next_seq",[t,i+1]),i}function je(e,t){Ce(e,`INSERT INTO deliveries (${Oe.join(", ")}) VALUES (${Oe.map(()=>"?").join(", ")})`,[t.delivery_id,t.target_durable_id,t.seq,t.sender,t.sender_turn,JSON.stringify(t.envelope),t.body,t.bytes,t.mode_requested,t.mode_effective,t.expected_turn_id,t.state,t.reason,null===t.admitted_by?null:JSON.stringify(t.admitted_by),t.claimed_at,t.attempt,t.admission_kind,t.turn_epoch,t.root_id,t.hop,t.created_at,t.updated_at,t.expires_at,t.binding_id,t.binding_revision,t.actor_user_id])}function Pe(e){return N("sha256").update(JSON.stringify(e)).digest("hex")}function Ge(e){let t=Number(e.sql.one(["user_version"],"SELECT user_version FROM pragma_user_version()")?.user_version??0);if(t>ke.length)throw new Le(t,ke.length);return t}class Be extends Error{version;code="gateway_migration_failed";constructor(e,t){super(t),this.version=e,this.name="GatewayMigrationError"}}var Je=new Set([6]);function Ke(e,t,n){let i=e.sql.one(["args_hash","status","delivery_id","owner_instance","result","expires_at"],"SELECT args_hash, status, delivery_id, owner_instance, result, expires_at FROM receipts WHERE principal = ? AND operation = 'deliver' AND idempotency_key = ?",[t,n]);if(void 0!==i)return{args_hash:String(i.args_hash),status:i.status,delivery_id:null===i.delivery_id?null:String(i.delivery_id),owner_instance:String(i.owner_instance),result:null===i.result?null:String(i.result),expires_at:Number(i.expires_at)}}function Ye(e,t,n){if(n.args_hash!==t.receipt.args_hash)return Se("idempotency_conflict","The idempotency key was already used with different arguments.");if("completed"===n.status&&null!==n.result)return{kind:"replay",result:JSON.parse(n.result)};let i=null===n.delivery_id?void 0:Ie(e,n.delivery_id),r=void 0!==i&&("admitted"===i.state||"applied"===i.state||"refused"===i.state);if("prepared"===n.status&&!r&&n.owner_instance===e.config.instance_id)return Se("idempotency_in_progress","The same delivery is already in progress.");if("prepared"===n.status&&r){let n={...we(i,$e(e,i),t.endpoint_kind,!0,!1)};return Ce(e,"UPDATE receipts SET status = 'completed', result = ?, updated_at = ? WHERE principal = ? AND operation = 'deliver' AND idempotency_key = ?",[JSON.stringify(n),t.now,t.sender_principal,t.receipt.idempotency_key]),{kind:"replay",result:n}}return"prepared"===n.status&&Ce(e,"UPDATE receipts SET status = 'uncertain', error_note = ?, updated_at = ? WHERE principal = ? AND operation = 'deliver' AND idempotency_key = ?",["the sender lost the acknowledgement before the target admitted the delivery",t.now,t.sender_principal,t.receipt.idempotency_key]),Se("idempotency_uncertain","The earlier delivery may or may not reach the target; it is never sent twice.",{delivery_id:n.delivery_id,state:i?.state??null})}async function Ve(e,t){if(!("object"==typeof(n=t.provenance)&&null!==n&&"workspace"in n&&"string"==typeof n.workspace&&n.workspace.trim().length>0&&"project"in n&&"string"==typeof n.project&&n.project.trim().length>0&&(!("lane"in n)||void 0===n.lane||"string"==typeof n.lane&&n.lane.trim().length>0)&&(!("session"in n)||void 0===n.session||"string"==typeof n.session&&n.session.trim().length>0)))return Se("invalid_arguments","Delivery provenance is required.");var n;if(!Re.test(t.target_durable_id)||!Re.test(t.delivery_id))return Se("invalid_arguments","The target session id is not a durable session id.");if(!await Ue(e,"enqueue",!1))return{kind:"busy"};let i=null,r=!1,s=e.afterCommit?.length??0,o=void 0===e.afterCommit?"COMMIT":"RELEASE gateway_enqueue";try{let n=Ee(e,{principal:t.sender_principal,operation:"deliver",idempotency_key:t.receipt.idempotency_key},t.now),s=Ke(e,t.sender_principal,t.receipt.idempotency_key);if(void 0!==s){let n=Ye(e,t,s);return e.sql.exec(o),r=!0,n}let a=function(e,t){if(null===t.binding)return{expires_at:null};let n=e.sql.one(["revision","status","session_durable_id","direction_inbound","expires_at"],"SELECT revision, status, session_durable_id, direction_inbound, expires_at FROM bindings WHERE binding_id = ?",[t.binding.binding_id]),i=null==n?.expires_at?null:Date.parse(String(n.expires_at));return void 0===n||"active"!==n.status||Number(n.revision)!==t.binding.revision||String(n.session_durable_id)!==t.target_durable_id||1!==Number(n.direction_inbound)||null!==i&&i<=t.now?Se("invalid_arguments","The binding is not active for this session at this revision.",{binding:t.binding.binding_id}):{expires_at:i}}(e,t);if("kind"in a)return De(e),a;let d=e.sql.one(["n","b"],`SELECT COUNT(*) AS n, COALESCE(SUM(bytes), 0) AS b FROM deliveries WHERE target_durable_id = ? AND state IN ${xe}`,[t.target_durable_id]),u=Buffer.byteLength(t.body);if(Number(d?.n??0)>=128||Number(d?.b??0)+u>H)return De(e),Se("queue_full","The target's delivery backlog is full.",{max_messages:128,max_bytes:H});let l=function(e,t){let n;if(null!==t.cause_delivery_id){let i=Ie(e,t.cause_delivery_id);if(void 0===i||i.target_durable_id!==t.sender_node||"admitting"!==i.state&&"admitted"!==i.state&&"applied"!==i.state)return Se("invalid_arguments","The delivery this send continues is not one the sender received.",{guard:"unknown_cause"});n={root_id:i.root_id,hop:i.hop+1,via:[t.sender_node],new_root:!1}}else n={root_id:`root-${L()}`,hop:1,via:[t.sender_node],new_root:!0};if(null!==t.claimed_root_id&&t.claimed_root_id!==n.root_id)return Se("invalid_arguments","The causal root is derived by the gateway and cannot be chosen by the caller.",{guard:"forged_root"});if(t.target_durable_id===t.sender_node)return Se("loop_detected","A session cannot deliver to itself through the gateway.",{guard:"self_send"});if(!n.new_root){let i=e.sql.one(["expires_at"],"SELECT expires_at FROM causal_roots WHERE root_id = ?",[n.root_id]);(void 0===i||Number(i.expires_at)<=t.now)&&(n={...n,root_id:`root-${L()}`,new_root:!0})}return n}(e,t);if("kind"in l)return De(e),l;let _=function(e,t){if(null===t.sender_turn)return;let n=new Set(e.sql.all(["t"],"SELECT DISTINCT target_durable_id AS t FROM deliveries WHERE sender = ? AND sender_turn = ? AND state != 'refused'",[t.sender_principal,t.sender_turn]).map(e=>String(e.t)));return n.has(t.target_durable_id)||n.size<16?void 0:Se("overloaded","One turn may reach at most 16 sessions.",{budget:"fanout"})}(e,t)??function(e,t){let n=t.rate_principal??t.sender_principal,i=e.sql.one(["tokens","updated_at"],"SELECT tokens, updated_at FROM rate_buckets WHERE sender = ? AND target_durable_id = ?",[n,t.target_durable_id]),r=void 0===i?8:Math.min(8,Number(i.tokens)+Math.max(0,t.now-Number(i.updated_at))/U);if(r<1)return Se("overloaded","Too many deliveries to this session; wait before sending again.",{budget:"pair_rate",retry_after_ms:Math.ceil((1-r)*U)});Ce(e,"INSERT INTO rate_buckets (sender, target_durable_id, tokens, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(sender, target_durable_id) DO UPDATE SET tokens = excluded.tokens, updated_at = excluded.updated_at",[n,t.target_durable_id,r-1,t.now])}(e,t);if(void 0!==_)return De(e),_;l.new_root&&Ce(e,"INSERT INTO causal_roots (root_id, origin_principal, created_at, expires_at) VALUES (?, ?, ?, ?)",[l.root_id,t.sender_principal,t.now,t.now+M]);let c={delivery_id:t.delivery_id,target_durable_id:t.target_durable_id,seq:Fe(e,t.target_durable_id),sender:t.sender_principal,sender_turn:t.sender_turn,envelope:{provenance:t.provenance,origin:t.origin,actor:t.actor,via:l.via,root_id:l.root_id,hop:l.hop,delivery_id:t.delivery_id},body:t.body,bytes:u,mode_requested:t.mode,mode_effective:null,expected_turn_id:t.expected_turn_id,state:"queued",reason:null,admitted_by:null,claimed_at:null,attempt:0,admission_kind:null,turn_epoch:null,root_id:l.root_id,hop:l.hop,created_at:t.now,updated_at:t.now,expires_at:Math.min(t.now+D,a.expires_at??Number.POSITIVE_INFINITY),binding_id:t.binding?.binding_id??null,binding_revision:t.binding?.revision??null,actor_user_id:"external"in t.origin?t.origin.external.author?.user_id??null:null};je(e,c),Ce(e,"INSERT INTO receipts (principal, operation, idempotency_key, args_hash, status, delivery_id, owner_instance, created_at, updated_at, expires_at) VALUES (?, 'deliver', ?, ?, 'prepared', ?, ?, ?, ?, ?)",[t.sender_principal,t.receipt.idempotency_key,t.receipt.args_hash,c.delivery_id,e.config.instance_id,t.now,t.now,t.now+W]),i=He(e,c.target_durable_id,c.delivery_id,!1);let p=$e(e,c);return he(e,t.now,n),void 0===e.afterCommit&&await e.hook("beforeDbCommit"),e.sql.exec(o),r=!0,void 0===e.afterCommit&&await e.hook("afterDbCommit"),{kind:"inserted",row:c,queue_position:p}}catch(t){throw r||(De(e),void 0!==e.afterCommit&&(e.afterCommit.length=s),null!==i&&q(i,{force:!0})),t}}function ze(e,t){if(null===e)return"";let n=t.get(e);if(void 0===n){try{n=A(e,"utf8")}catch(e){if(!(e instanceof Error&&"code"in e&&"ENOENT"===e.code))throw e;n=""}t.set(e,n)}return n}function Ze(e,t,n){if(null===e.runtime_instance||null===t)return!1;let i=n().get(e.runtime_instance);return void 0!==i&&t<=i}function Qe(e,t,n){for(let i of ze(e,n).split("\n")){if(!i.includes(t))continue;let e;try{e=JSON.parse(i)}catch{continue}if("object"!=typeof e||null===e)continue;let n=e;if("custom_message"===n.type&&"session_control_delivery"===n.customType&&n.details?.delivery_id===t)return!0}return!1}function et(e){return`${JSON.stringify(e.admitted_by)}#${e.attempt}`}function tt(e,t,n,i,r={}){"queued"!==n?"refused"!==n?(Ce(e,"UPDATE deliveries SET state = ?, updated_at = ? WHERE delivery_id = ?",[n,i,t.delivery_id]),"applied"===n&&Ce(e,"UPDATE session_meta SET applied_seq = MAX(applied_seq, ?) WHERE durable_id = ?",[t.seq,t.target_durable_id])):Ce(e,"UPDATE deliveries SET state = 'refused', reason = ?, updated_at = ? WHERE delivery_id = ?",[r.reason??null,i,t.delivery_id]):Ce(e,"UPDATE deliveries SET state = 'queued', admitted_by = NULL, claimed_at = NULL, mode_effective = NULL, admission_kind = NULL, turn_epoch = NULL, updated_at = ? WHERE delivery_id = ?",[i,t.delivery_id])}async function nt(e,t){let n,i=t.target_durable_id,r=new Map,s=new Map,o=new Map,a=()=>(n??=function(e,t){let n=new Map;for(let i of ze(e,t).split("\n")){if(!i.includes(j))continue;let e;try{e=JSON.parse(i)}catch{continue}let t=e;if("custom"!==t.type||t.customType!==j)continue;let r=t.data?.host_instance,s="string"==typeof t.data?.released_at?Date.parse(t.data.released_at):Number.NaN;"string"==typeof r&&0!==r.length&&Number.isFinite(s)&&n.set(r,Math.max(s,n.get(r)??s))}return n}(t.session_path,s),n);for(let n of qe(e,"target_durable_id = ? AND state IN ('admitting', 'admitted')",[i])){if(null===n.admitted_by||h(n.admitted_by,t.self))continue;let e=JSON.stringify(n.admitted_by),i=o.get(e);void 0===i&&(i=await E(n.admitted_by),o.set(e,i));let d=i||Ze(n.admitted_by,n.claimed_at,a)?Qe(t.session_path,n.delivery_id,s)?"applied":"queued":"dual";r.set(n.delivery_id,{fingerprint:et(n),to:d})}return!0===e.config.test_hooks.announceBarrier&&e.emit({kind:"barrier",op:"reconcile"}),await Me(e,"reconcile",()=>{let n=new Set(t.ledger.pending),s=new Set(t.ledger.emitted),o=[],a=[];for(let d of qe(e,`target_durable_id = ? AND state IN ${xe}`,[i],"seq")){let i=d.state;if("queued"!==d.state){if(null!==d.admitted_by&&h(d.admitted_by,t.self))i=s.has(d.delivery_id)?"applied":n.has(d.delivery_id)?"admitted":"queued";else if(null===d.admitted_by)i="queued";else{let e=r.get(d.delivery_id);if(void 0===e||e.fingerprint!==et(d)||"dual"===e.to){a.push(d.delivery_id);continue}i=e.to}i!==d.state&&(tt(e,d,i,t.now),o.push({delivery_id:d.delivery_id,from:d.state,to:i}))}else d.expires_at<=t.now&&(tt(e,d,"refused",t.now,{reason:"expired"}),o.push({delivery_id:d.delivery_id,from:d.state,to:"refused"}))}for(let t of Xe(e,i))"queued"!==e.sql.one(["state"],"SELECT state FROM deliveries WHERE delivery_id = ?",[t])?.state&&We(e,i,t);return{queued:qe(e,"target_durable_id = ? AND state = 'queued'",[i],"seq"),transitions:o,dual_runtime:a}})}async function it(e,t){return await Me(e,"complete_receipt",()=>1===Ce(e,"UPDATE receipts SET status = 'completed', result = ?, updated_at = ? WHERE principal = ? AND operation = 'deliver' AND idempotency_key = ? AND status = 'prepared' AND owner_instance = ?",[JSON.stringify(t.result),t.now,t.principal,t.idempotency_key,e.config.instance_id]))}async function rt(e,t){return await Me(e,"abandon_receipt",()=>1===Ce(e,"UPDATE receipts SET status = 'uncertain', error_note = ?, updated_at = ? WHERE principal = ? AND operation = 'deliver' AND idempotency_key = ? AND status = 'prepared' AND owner_instance = ?",[t.error_note,t.now,t.principal,t.idempotency_key,e.config.instance_id]))}function st(e,t){let n=Ke(e,t.principal,t.idempotency_key);if(void 0===n||n.expires_at<=t.now||null===n.delivery_id)return null;let i=Ie(e,n.delivery_id);if(void 0===i)return null;let r="completed"===n.status&&null!==n.result;return{args_hash:n.args_hash,completed:r,result:r?JSON.parse(n.result):null,target_durable_id:i.target_durable_id,binding_revision:i.binding_revision}}async function ot(e,t){return await Me(e,"recover_delivery",()=>{let n=Ke(e,t.principal,t.idempotency_key);return void 0===n||n.expires_at<=t.now?null:Ye(e,{now:t.now,sender_principal:t.principal,endpoint_kind:null,receipt:{idempotency_key:t.idempotency_key,args_hash:t.args_hash}},n)})}function at(e,t){let n=Ie(e,t);return void 0===n?null:{row:n,queue_position:$e(e,n)}}function dt(){try{return C().username}catch{return"unknown"}}import{randomUUID as ut}from"node:crypto";import{renameSync as lt,writeFileSync as _t}from"node:fs";var ct=["question","select","confirm","input","editor"];var pt=new Map([["yes",!0],["y",!0],["true",!0],["no",!1],["n",!1],["false",!1]]);function mt(e){return""===e.replace(/[\s\p{Cf}]/gu,"")}function gt(e){let t=pt.get(e.trim().toLowerCase());return void 0===t?{value:e,answers:{},comment:e}:{value:e,answers:{},comment:e,confirmed:t}}function ft(e,t){switch(e){case null:return mt(t)?{ok:!1,reason:"The question declared no request kind, so the answer needs text; this one is blank. An input or editor that takes an empty answer must be reported with its request kind."}:{ok:!0,fields:gt(t)};case"input":case"editor":return{ok:!0,fields:{value:t}};case"select":return mt(t)?{ok:!1,reason:"A select answer names one of its options; the text is blank."}:{ok:!0,fields:{value:t}};case"question":return mt(t)?{ok:!1,reason:"A question answer needs text; this one is blank."}:{ok:!0,fields:{answers:{},comment:t}};case"confirm":{let e=pt.get(t.trim().toLowerCase());return void 0===e?{ok:!1,reason:"A confirm answer is yes or no (also y/n, true/false; any case, surrounding spaces ignored)."}:{ok:!0,fields:{confirmed:e}}}default:return function(e){throw Error(`unknown extension UI request kind: ${String(e)}`)}(e)}}var bt=["binding_id","schema_version","revision","status","platform","account_id","chat_id","thread_id","root_message_id","progress_message_id","session_realm_id","session_durable_id","direction_inbound","direction_outbound","inbound_mode","outbound_events","policy_id","created_at","updated_at","lease_started_at","ttl_seconds","expires_at"],Et=["cursor","binding_id","revision","event_kind","payload","state","provider_message_id","created_at","reply_token","question_state","outcome","answered_by","answer_state"];function ht(e,t,n){return{kind:"refused",code:e,message:t,...void 0===n?{}:{details:n}}}function yt(e){return null==e?null:String(e)}function vt(e){return null==e?null:JSON.stringify(e)}function Tt(e){return null==e?null:JSON.parse(String(e))}function wt(e,t,n,i){if(void 0!==e.afterCommit)return void e.afterCommit.push(()=>wt({...e,afterCommit:void 0},t,n,i));let r=(o=e.config.agent_dir,l(_(o),"outbox.marker")),s=`${r}.${process.pid}.${ut()}.tmp`;var o;_t(s,JSON.stringify({binding_id:t,cursor:n,written_at:ae(i)}),{mode:384}),lt(s,r)}function Nt(e){return{schema_version:1,binding_id:String(e.binding_id),revision:Number(e.revision),status:e.status,platform:e.platform,account_id:String(e.account_id),chat_id:String(e.chat_id),thread_id:String(e.thread_id),root_message_id:yt(e.root_message_id),progress_message_id:yt(e.progress_message_id),session_realm_id:String(e.session_realm_id),session_durable_id:String(e.session_durable_id),direction:{inbound:1===Number(e.direction_inbound),outbound:1===Number(e.direction_outbound)},inbound_mode:e.inbound_mode,outbound_events:JSON.parse(String(e.outbound_events)),policy_id:String(e.policy_id),created_at:String(e.created_at),updated_at:String(e.updated_at),lease_started_at:String(e.lease_started_at),ttl_seconds:null===e.ttl_seconds||void 0===e.ttl_seconds?null:Number(e.ttl_seconds),expires_at:yt(e.expires_at)}}function Lt(e,t,n,i){let r=`SELECT ${bt.join(", ")} FROM bindings WHERE ${t}${void 0===i?"":` ORDER BY ${i.orderBy} LIMIT ?`}`;return e.sql.all(bt,r,void 0===i?n:[...n,i.limit],i?.orderBy).map(Nt)}function kt(e,t){return Lt(e,"binding_id = ?",[t])[0]}function Ot(e,t){let n=e.sql.one(["value"],"SELECT value FROM gateway_meta WHERE key = ?",[t]);if(void 0===n)throw Error(`gateway_meta ${t} is missing`);return String(n.value)}function xt(e,t){let n=ae(t);Ce(e,"UPDATE bindings SET status = 'expired', updated_at = ? WHERE status = 'active' AND expires_at IS NOT NULL AND expires_at <= ?",[n,n])}function Rt(e,t){Ce(e,"DELETE FROM outbox WHERE state = 'acked' AND acked_at IS NOT NULL AND acked_at <= ?",[t-oe]),Ce(e,"DELETE FROM outbox WHERE state = 'pending' AND binding_id IN (SELECT binding_id FROM bindings WHERE status != 'active' AND updated_at <= ?)",[ae(t-oe)])}function St(e,t){let n=e.sql.one(["args_hash","status","owner_instance","result"],"SELECT args_hash, status, owner_instance, result FROM receipts WHERE principal = ? AND operation = ? AND idempotency_key = ?",[t.principal,t.operation,t.idempotency_key]);if(void 0!==n)return{args_hash:String(n.args_hash),status:String(n.status),owner_instance:String(n.owner_instance),result:yt(n.result)}}async function At(e,t,n,i,r){return await Me(e,t,()=>{xt(e,n);let t=null===i?0:Ee(e,i,n),s=function(e,t){if(null===t)return;let n=St(e,t);return void 0!==n?n.args_hash!==t.args_hash?ht("idempotency_conflict","The idempotency key was already used with different arguments."):"completed"===n.status&&null!==n.result?{...JSON.parse(n.result),kind:"ok",deduplicated:!0}:ht("idempotency_uncertain","An earlier call under this key did not record its outcome."):void 0}(e,i);if(void 0!==s)return s;let o=r();return"ok"===o.kind&&function(e,t,n,i){null!==t&&Ce(e,"INSERT INTO receipts (principal, operation, idempotency_key, args_hash, status, delivery_id, owner_instance, result, created_at, updated_at, expires_at) VALUES (?, ?, ?, ?, 'completed', NULL, ?, ?, ?, ?, ?)",[t.principal,t.operation,t.idempotency_key,t.args_hash,e.config.instance_id,JSON.stringify(i),n,n,n+W])}(e,i,n,{...o,deduplicated:!1}),he(e,n,t),"ok"===o.kind?{...o,deduplicated:!1}:o})}async function qt(e,t){return await Me(e,"tool_receipt_begin",()=>{let n=Ee(e,t,t.now),i=function(e,t){let n=St(e,t);if(void 0===n)return Ce(e,"INSERT INTO receipts (principal, operation, idempotency_key, args_hash, status, delivery_id, owner_instance, created_at, updated_at, expires_at) VALUES (?, ?, ?, ?, 'prepared', NULL, ?, ?, ?, ?)",[t.principal,t.operation,t.idempotency_key,t.args_hash,e.config.instance_id,t.now,t.now,t.now+W]),{kind:"accepted"};if(n.args_hash!==t.args_hash)return{kind:"conflict"};if("completed"===n.status)return{kind:"replay",result:null===n.result?null:JSON.parse(n.result)};if("prepared"===n.status&&n.owner_instance===e.config.instance_id)return{kind:"in_progress"};"prepared"===n.status&&Ce(e,"UPDATE receipts SET status = 'uncertain', error_note = ?, updated_at = ? WHERE principal = ? AND operation = ? AND idempotency_key = ?",["the process that began this call ended before recording its outcome",t.now,t.principal,t.operation,t.idempotency_key]);let i=e.sql.one(["error_note"],"SELECT error_note FROM receipts WHERE principal = ? AND operation = ? AND idempotency_key = ?",[t.principal,t.operation,t.idempotency_key]);return{kind:"uncertain",error_note:yt(i?.error_note)}}(e,t);return he(e,t.now,n),i})}async function It(e,t){let n=t.binding;return await At(e,"bind",t.now,t.receipt,()=>{let i=Lt(e,"platform = ? AND account_id = ? AND chat_id = ? AND thread_id = ? AND status = 'active'",[n.platform,n.account_id,n.chat_id,n.thread_id])[0];if(void 0!==i){return ht("binding_conflict",i.session_durable_id===n.session_durable_id?"This thread is already bound to that session.":"This thread is bound to another session; rebind it explicitly to move it.",{binding_id:i.binding_id,revision:i.revision,session:i.session_durable_id})}let r=ae(t.now),s={schema_version:1,binding_id:`bnd-${ee()}`,revision:1,status:"active",platform:n.platform,account_id:n.account_id,chat_id:n.chat_id,thread_id:n.thread_id,root_message_id:n.root_message_id,progress_message_id:n.progress_message_id,session_realm_id:Ot(e,"realm_id"),session_durable_id:n.session_durable_id,direction:n.direction,inbound_mode:n.inbound_mode,outbound_events:n.outbound_events,policy_id:n.policy_id,created_at:r,updated_at:r,lease_started_at:r,ttl_seconds:n.ttl_seconds,expires_at:null===n.ttl_seconds?null:ae(t.now+1e3*n.ttl_seconds)};return Ce(e,`INSERT INTO bindings (${bt.join(", ")}) VALUES (${bt.map(()=>"?").join(", ")})`,[s.binding_id,s.schema_version,s.revision,s.status,s.platform,s.account_id,s.chat_id,s.thread_id,s.root_message_id,s.progress_message_id,s.session_realm_id,s.session_durable_id,s.direction.inbound?1:0,s.direction.outbound?1:0,s.inbound_mode,JSON.stringify(s.outbound_events),s.policy_id,s.created_at,s.updated_at,s.lease_started_at,s.ttl_seconds,s.expires_at]),{kind:"ok",binding:s}})}function Ct(e,t){return e.sql.all(["delivery_id"],`SELECT delivery_id, seq FROM deliveries WHERE binding_id = ? AND state IN ${xe}`,[t],"seq").map(e=>String(e.delivery_id))}async function $t(e,t){return await At(e,"unbind",t.now,t.receipt,()=>{let n=kt(e,t.binding_id);if(void 0===n)return ht("not_found","No binding has this id.",{binding_id:t.binding_id});if("active"!==n.status)return{kind:"ok",binding:n,already_closed:!0,in_flight:Ct(e,n.binding_id)};if(n.revision!==t.expected_revision)return ht("stale_revision","The binding changed since that revision.",{binding_id:n.binding_id,revision:n.revision});let i=ae(t.now);return Ce(e,"UPDATE bindings SET status = 'detached', revision = revision + 1, updated_at = ? WHERE binding_id = ? AND revision = ?",[i,n.binding_id,n.revision]),Ce(e,"DELETE FROM completion_arms WHERE binding_id = ?",[n.binding_id]),{kind:"ok",binding:kt(e,n.binding_id),already_closed:!1,in_flight:Ct(e,n.binding_id)}})}async function Ut(e,t){return await At(e,"rebind",t.now,t.receipt,()=>{let n=kt(e,t.binding_id);if(void 0===n)return ht("not_found","No binding has this id.",{binding_id:t.binding_id});if("active"!==n.status)return ht("binding_inactive",`The binding is ${n.status}.`,{binding_id:n.binding_id,status:n.status});if(n.revision!==t.expected_revision)return ht("stale_revision","The binding changed since that revision.",{binding_id:n.binding_id,revision:n.revision});if(n.session_durable_id===t.session_durable_id)return ht("invalid_arguments","The binding is already attached to that session.",{binding_id:n.binding_id});let i=ae(t.now),r=e.sql.all(["delivery_id","target"],"SELECT delivery_id, target_durable_id AS target, seq FROM deliveries WHERE binding_id = ? AND binding_revision = ? AND state = 'queued'",[n.binding_id,n.revision],"seq").map(e=>({delivery_id:String(e.delivery_id),target:String(e.target)}));for(let n of r)Ce(e,"UPDATE deliveries SET state = 'refused', reason = 'binding_closed', updated_at = ? WHERE delivery_id = ? AND state = 'queued'",[t.now,n.delivery_id]),We(e,n.target,n.delivery_id);return Ce(e,"UPDATE bindings SET session_durable_id = ?, revision = revision + 1, lease_started_at = ?, updated_at = ? WHERE binding_id = ? AND revision = ?",[t.session_durable_id,i,i,n.binding_id,n.revision]),Ce(e,"DELETE FROM completion_arms WHERE binding_id = ?",[n.binding_id]),{kind:"ok",binding:kt(e,n.binding_id),closed:r.map(e=>e.delivery_id)}})}async function Dt(e,t){let n=void 0===t.cursor?null:function(e){try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));if(1!==t.v||"number"!=typeof t.as_of||!Number.isInteger(t.as_of))return null;let n=t.after;return null===n||Array.isArray(n)&&2===n.length&&n.every(e=>"string"==typeof e)?{v:1,as_of:t.as_of,after:n}:null}catch{return null}}(t.cursor);if(void 0!==t.cursor&&null===n)return ht("cursor_invalid","The bindings cursor is not one this gateway issued.");let i=Math.min(Math.max(t.limit??50,1),200);return await Me(e,"list_bindings",()=>{xt(e,t.now);let r=n?.as_of??Number(e.sql.one(["m"],"SELECT COALESCE(MAX(rowid), 0) AS m FROM bindings")?.m??0),s=["rowid <= ?"],o=[r],a=[["session_durable_id","session_durable_id"],["platform","platform"],["account_id","account_id"],["chat_id","chat_id"],["thread_id","thread_id"],["status","status"]];for(let[e,n]of a){let i=t.filter[e];void 0!==i&&(s.push(`${n} = ?`),o.push(i))}null!=n?.after&&(s.push("(created_at > ? OR (created_at = ? AND binding_id > ?))"),o.push(n.after[0],n.after[0],n.after[1]));let d=Lt(e,s.join(" AND "),o,{orderBy:"created_at, binding_id",limit:i+1}),u=d.slice(0,i),l=u.at(-1);return{kind:"ok",bindings:u,next_cursor:d.length>i&&void 0!==l?me(r,[l.created_at,l.binding_id]):null}})}async function Mt(e,t){return await Me(e,"binding_view",()=>(xt(e,t.now),kt(e,t.binding_id)??null))}function Ht(e,t){return yt(e.sql.one(["incarnation"],"SELECT incarnation FROM session_meta WHERE durable_id = ?",[t])?.incarnation)}function Wt(e,t){Ce(e,"INSERT INTO outbox (binding_id, revision, event_kind, payload, state, provider_message_id, created_at, acked_at, session_durable_id, reply_token, ui_request_id, ui_request_kind, incarnation, question_state, answer, answered_at, outcome) VALUES (?, ?, ?, ?, 'pending', NULL, ?, NULL, ?, ?, ?, ?, ?, ?, NULL, NULL, ?)",[t.binding.binding_id,t.binding.revision,t.event,JSON.stringify({text:t.text}),t.now,t.binding.session_durable_id,t.reply_token??null,t.ui_request_id??null,t.ui_request_kind??null,t.incarnation??null,void 0===t.reply_token?null:"pending",t.outcome??null]);let n=Number(e.sql.one(["c"],"SELECT last_insert_rowid() AS c")?.c);return wt(e,t.binding.binding_id,n,t.now),n}async function Xt(e,t){return await At(e,"report",t.now,t.receipt,()=>{let n=null===t.binding_id?function(e,t,n,i){let r=[...new Set(n.flatMap(n=>{let i=e.sql.one(["binding_id"],"SELECT binding_id FROM deliveries WHERE delivery_id = ? AND target_durable_id = ?",[n,t]),r=yt(i?.binding_id);return null===r?[]:[r]}))].sort(),s=e.sql.all(["binding_id"],"SELECT binding_id FROM bindings WHERE session_durable_id = ? AND status = 'active' AND direction_outbound = 1",[t],"binding_id").map(e=>String(e.binding_id)),[o,...a]=r;if(void 0!==o&&a.length>0)return ht("invalid_arguments",`This session's current run answers messages from ${r.length} bound threads; name binding_id.`,{binding_ids:r});if(void 0!==o&&i&&s.some(e=>e!==o))return ht("invalid_arguments","This session's current run answers a bound thread's message and a user message (typed in its terminal or sent by an extension) together; name binding_id.",{binding_ids:s});if(void 0!==o)return{binding_id:o};let[d,...u]=s;return void 0!==d&&0===u.length?{binding_id:d}:void 0===d?ht("invalid_arguments","This session has no active outbound binding and its current run answers no bound message; name binding_id."):ht("invalid_arguments",`This session has ${s.length} active outbound bindings and its current run answers no bound message; name binding_id.`,{binding_ids:s})}(e,t.session_durable_id,t.origin_delivery_ids,!0===t.origin_local_input):{binding_id:t.binding_id};if("kind"in n)return n;let i=n.binding_id,r=kt(e,i);if(void 0===r)return ht("not_found","No binding has this id.",{binding_id:i});if(r.session_durable_id!==t.session_durable_id)return ht("scope_denied","The binding is attached to another session.",{binding_id:i});if("active"!==r.status)return ht("binding_inactive",`The binding is ${r.status}.`,{binding_id:i,status:r.status});if(!r.direction.outbound)return ht("unsupported","The binding carries no outbound direction.",{binding_id:i,direction:r.direction});if(!r.outbound_events.includes(t.event))return ht("unsupported",`The binding is not subscribed to ${t.event} events.`,{binding_id:i,outbound_events:r.outbound_events});if(null!==t.ui_request_kind&&"question"!==t.event)return ht("invalid_arguments","Only a question names a request kind.");let s={binding_id:i,revision:r.revision,event:t.event};if("completion"===t.event){Ce(e,"INSERT INTO completion_arms (session_durable_id, binding_id, revision, text, armed_at) VALUES (?, ?, ?, ?, ?)",[t.session_durable_id,i,r.revision,t.text,t.now]);let n=Number(e.sql.one(["s"],"SELECT last_insert_rowid() AS s")?.s);return{kind:"ok",...s,cursor:null,reply_token:null,armed:!0,arm_seq:n}}if("question"===t.event){if(null===t.ui_request_id)return ht("invalid_arguments","A question names the session's pending extension UI request (request_id).");let n=Ht(e,t.session_durable_id),o=function(e,t){let n={b:t.binding_id,r:t.revision,s:t.session_durable_id,i:t.incarnation,q:t.ui_request_id,n:ee()},i=pe(JSON.stringify(n));return`${ge}.${i}.${fe(e,i)}`}(Ot(e,"token_secret"),{binding_id:i,revision:r.revision,session_durable_id:t.session_durable_id,incarnation:n,ui_request_id:t.ui_request_id}),a=Wt(e,{binding:r,event:"question",text:t.text,now:t.now,reply_token:o,ui_request_id:t.ui_request_id,...null===t.ui_request_kind?{}:{ui_request_kind:t.ui_request_kind},incarnation:n});return Rt(e,t.now),{kind:"ok",...s,cursor:a,reply_token:o,armed:!1,arm_seq:null}}let o=Wt(e,{binding:r,event:t.event,text:t.text,now:t.now});return Rt(e,t.now),{kind:"ok",...s,cursor:o,reply_token:null,armed:!1,arm_seq:null}})}async function Ft(e,t){return await Me(e,"emit_completions",()=>{xt(e,t.now);let n=["arm_seq","binding_id","revision","text"],i=void 0===t.through_arm_seq?e.sql.all(n,"SELECT arm_seq, binding_id, revision, text FROM completion_arms WHERE session_durable_id = ?",[t.session_durable_id],"arm_seq"):e.sql.all(n,"SELECT arm_seq, binding_id, revision, text FROM completion_arms WHERE session_durable_id = ? AND arm_seq <= ?",[t.session_durable_id,t.through_arm_seq],"arm_seq"),r=new Map;for(let t of i)Ce(e,"DELETE FROM completion_arms WHERE arm_seq = ?",[Number(t.arm_seq)]),r.set(String(t.binding_id),t);let s=[];for(let n of[...r.values()].toSorted((e,t)=>String(e.binding_id)<String(t.binding_id)?-1:1)){let i=kt(e,String(n.binding_id));void 0!==i&&"active"===i.status&&i.revision===Number(n.revision)&&i.session_durable_id===t.session_durable_id&&(i.direction.outbound&&i.outbound_events.includes("completion")&&s.push({binding_id:i.binding_id,cursor:Wt(e,{binding:i,event:"completion",text:String(n.text),now:t.now,outcome:t.outcome})}))}return s}).then(n=>(e.emit({kind:"completions_emitted",session_durable_id:t.session_durable_id,cursors:n.map(e=>e.cursor)}),n))}function jt(e,t){return Number(e.sql.one(["acked_cursor"],"SELECT acked_cursor FROM outbox_cursors WHERE binding_id = ?",[t])?.acked_cursor??0)}async function Pt(e,t){let n=Math.min(Math.max(t.limit??100,1),500);return await Me(e,"read_outbox",()=>{xt(e,t.now),Rt(e,t.now);let i=kt(e,t.binding_id);if(void 0===i)return ht("not_found","No binding has this id.",{binding_id:t.binding_id});let r=jt(e,i.binding_id),s=t.after_cursor??r,o=e.sql.all(Et,`SELECT ${Et.join(", ")} FROM outbox WHERE binding_id = ? AND cursor > ?${t.pendingOnly?" AND state = 'pending'":""} ORDER BY cursor LIMIT ?`,[i.binding_id,s,n],"cursor").map(e=>function(e,t){let n=e.event_kind;return{cursor:Number(e.cursor),binding_id:String(e.binding_id),revision:Number(e.revision),event:n,text:String(JSON.parse(String(e.payload)).text??""),state:e.state,created_at:ae(Number(e.created_at)),edit_message_id:"milestone"===n?t.progress_message_id:null,provider_message_id:yt(e.provider_message_id),reply_token:yt(e.reply_token),question_state:e.question_state??null,outcome:e.outcome??null,answered_by:Tt(e.answered_by),answer_state:e.answer_state??null}}(e,i));return he(e,t.now),{kind:"ok",binding_id:i.binding_id,revision:i.revision,status:i.status,rows:o,next_cursor:o.at(-1)?.cursor??s,acked_cursor:r}})}async function Gt(e,t){return await Me(e,"ack_outbox",()=>{xt(e,t.now);let n=kt(e,t.binding_id);if(void 0===n)return ht("not_found","No binding has this id.",{binding_id:t.binding_id});let i=jt(e,n.binding_id);if(t.cursor<=i)return{kind:"ok",binding_id:n.binding_id,acked_cursor:i,changed:!1};if(void 0===e.sql.one(["cursor"],"SELECT cursor FROM outbox WHERE binding_id = ? AND cursor = ?",[n.binding_id,t.cursor])){let i=Number(e.sql.one(["m"],"SELECT COALESCE(MAX(cursor), 0) AS m FROM outbox WHERE binding_id = ?",[n.binding_id])?.m??0);return ht("cursor_invalid",t.cursor>i?"The cursor is past the newest outbox row of this binding.":"The cursor names no outbox row of this binding.",{newest:i})}return Ce(e,"UPDATE outbox SET state = 'acked', acked_at = ? WHERE binding_id = ? AND cursor <= ? AND state = 'pending'",[t.now,n.binding_id,t.cursor]),Ce(e,"INSERT INTO outbox_cursors (binding_id, acked_cursor, updated_at) VALUES (?, ?, ?) ON CONFLICT(binding_id) DO UPDATE SET acked_cursor = excluded.acked_cursor, updated_at = excluded.updated_at",[n.binding_id,t.cursor,t.now]),void 0!==t.provider_message_id&&(Ce(e,"UPDATE outbox SET provider_message_id = ? WHERE binding_id = ? AND cursor = ?",[t.provider_message_id,n.binding_id,t.cursor]),"milestone"===e.sql.one(["event_kind"],"SELECT event_kind FROM outbox WHERE binding_id = ? AND cursor = ?",[n.binding_id,t.cursor])?.event_kind&&null===n.progress_message_id&&Ce(e,"UPDATE bindings SET progress_message_id = ?, updated_at = ? WHERE binding_id = ?",[t.provider_message_id,ae(t.now),n.binding_id])),{kind:"ok",binding_id:n.binding_id,acked_cursor:t.cursor,changed:!0}})}var Bt="The session no longer waits for this question (answered or closed elsewhere)";async function Jt(e,t){return await Me(e,"claim_answer",()=>{xt(e,t.now);let n=function(e,t){let n=t.split(".");if(3!==n.length||n[0]!==ge)return null;let i=Buffer.from(fe(e,n[1])),r=Buffer.from(n[2]);if(i.length!==r.length||!te(i,r))return null;try{let e=JSON.parse(Buffer.from(n[1],"base64url").toString("utf8"));return"string"!=typeof e.b||"number"!=typeof e.r||"string"!=typeof e.s||"string"!=typeof e.q||null!==e.i&&"string"!=typeof e.i?null:{binding_id:e.b,revision:e.r,session_durable_id:e.s,incarnation:e.i??null,ui_request_id:e.q}}catch{return null}}(Ot(e,"token_secret"),t.reply_token);if(null===n)return ht("invalid_arguments","This is not a reply token this gateway issued.");if(n.binding_id!==t.binding_id)return ht("binding_mismatch","The answer arrived through a different binding than the one that asked the question.",{binding_id:t.binding_id});let i=e.sql.one(["cursor","question_state","answer_state","answer","answered_at","answered_by","ui_request_id","ui_request_kind","session"],"SELECT cursor, question_state, answer_state, answer, answered_at, answered_by, ui_request_id, ui_request_kind, session_durable_id AS session FROM outbox WHERE reply_token = ? AND binding_id = ?",[t.reply_token,n.binding_id]);if(void 0===i)return ht("not_found","The question this token belongs to is no longer in the outbox.");let r="answered"===i.question_state&&"delivered"!==i.answer_state,s=r&&Number(i.answered_at)+12e4<=t.now;if(r&&!s)return ht("answer_in_progress","Another answer to this question is still being handed to the session.",{cursor:Number(i.cursor)});if("answered"===i.question_state&&!s)return ht("already_answered",null===i.answer&&"delivered"===i.answer_state?`${Bt}.`:"This question was already answered.",{cursor:Number(i.cursor)});let o="string"==typeof(d=i.ui_request_kind)&&ct.includes(d)?i.ui_request_kind:null,a=ft(o,t.answer);var d;if(!a.ok)return ht("invalid_arguments",a.reason,{ui_request_kind:o});let u=kt(e,n.binding_id);return void 0===u||"active"!==u.status||u.revision!==n.revision||u.session_durable_id!==n.session_durable_id||Ht(e,n.session_durable_id)!==n.incarnation||yt(i.ui_request_id)!==n.ui_request_id?ht("stale_token","The binding or the session changed since the question was asked.",{binding_id:n.binding_id}):(Ce(e,"UPDATE outbox SET question_state = 'answered', answer_state = 'in_flight', answer = ?, answered_at = ?, answered_by = ? WHERE reply_token = ?",[t.answer,t.now,vt(t.answered_by),t.reply_token]),{kind:"ok",session_durable_id:n.session_durable_id,ui_request_id:n.ui_request_id,ui_request_kind:o,cursor:Number(i.cursor),claimed_at:t.now,taken_over:s?{answer:yt(i.answer),answered_at:null===i.answered_at||void 0===i.answered_at?null:Number(i.answered_at),answered_by:Tt(i.answered_by)}:null})})}function Kt(e,t,n){let i=e.sql.one(["cursor","binding_id"],"SELECT cursor, binding_id FROM outbox WHERE reply_token = ?",[t]);void 0!==i&&wt(e,String(i.binding_id),Number(i.cursor),n)}async function Yt(e,t){return await Me(e,"release_answer",()=>{let n=1===Ce(e,"UPDATE outbox SET question_state = 'pending', answer_state = NULL, answer = NULL, answered_at = NULL, answered_by = NULL WHERE reply_token = ? AND question_state = 'answered' AND answer_state = 'in_flight' AND answered_at = ?",[t.reply_token,t.claimed_at]);return n&&Kt(e,t.reply_token,t.claimed_at),n})}async function Vt(e,t){return await Me(e,"mark_prior_delivered",()=>{let n=1===Ce(e,"UPDATE outbox SET answer_state = 'delivered', answer = ?, answered_at = ?, answered_by = ? WHERE reply_token = ? AND question_state = 'answered' AND answer_state = 'in_flight' AND answered_at = ?",[t.prior.answer,t.prior.answered_at,vt(t.prior.answered_by),t.reply_token,t.claimed_at]);return n&&Kt(e,t.reply_token,t.claimed_at),n})}async function zt(e,t){return await Me(e,"confirm_answer",()=>{let n=1===Ce(e,"UPDATE outbox SET question_state = 'answered', answer_state = 'delivered', answer = ?, answered_at = ?, answered_by = ? WHERE reply_token = ? AND (answer_state IS NOT 'delivered' OR answer IS NULL)",[t.answer,t.claimed_at,vt(t.answered_by),t.reply_token]);return n&&Kt(e,t.reply_token,t.claimed_at),n})}import{existsSync as Zt}from"node:fs";import{extname as Qt}from"node:path";import{fileURLToPath as en}from"node:url";var tn=new Set(["object","string","number","integer","boolean","array","null"]),nn=new Set(["title","description","default","examples"]),rn=["minLength","maxLength","minItems","maxItems"],sn=["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],on=new Set(["type","properties","required","additionalProperties","enum","const","pattern","items","anyOf",...rn,...sn,...nn]),an=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);function dn(e,t="parameters"){if(!an(e))return`${t} must be a schema object`;for(let n of Object.keys(e))if(!n.startsWith("~")&&!on.has(n))return`${t} uses ${n}, which the store cannot check`;let{type:n,properties:i,required:r,additionalProperties:s,items:o,anyOf:a,pattern:d}=e,u=Array.isArray(n)?n:void 0===n?[]:[n];if(Array.isArray(n)&&0===n.length||!u.every(e=>"string"==typeof e&&tn.has(e)))return`${t}.type must name JSON types`;if(void 0!==i){if(!an(i))return`${t}.properties must be an object`;for(let[e,n]of Object.entries(i)){let i=dn(n,`${t}.properties.${e}`);if(void 0!==i)return i}}if(!(void 0===r||Array.isArray(r)&&r.every(e=>"string"==typeof e)))return`${t}.required must list property names`;if(void 0!==s&&"boolean"!=typeof s)return`${t}.additionalProperties must be true or false`;if(void 0!==e.enum&&(!Array.isArray(e.enum)||0===e.enum.length))return`${t}.enum must be a non-empty array`;if(void 0!==d&&"string"!=typeof d)return`${t}.pattern must be a string`;for(let n of rn){let i=e[n];if(void 0!==i&&("number"!=typeof i||!Number.isInteger(i)||i<0))return`${t}.${n} must be a non-negative integer`}for(let n of sn){let i=e[n];if(void 0!==i&&("number"!=typeof i||!Number.isFinite(i)))return`${t}.${n} must be a finite number`}if(void 0!==o){let e=dn(o,`${t}.items`);if(void 0!==e)return e}if(void 0!==a){if(!Array.isArray(a)||0===a.length)return`${t}.anyOf must be a non-empty array`;for(let[e,n]of a.entries()){let i=dn(n,`${t}.anyOf.${e}`);if(void 0!==i)return i}}}function un(e,t){if(Object.is(e,t))return!0;if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length&&e.every((e,n)=>un(e,t[n]));if(!an(e)||!an(t))return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.hasOwn(t,n)&&un(e[n],t[n]))}var ln=(e,t)=>`${e}/${String(t).replaceAll("~","~0").replaceAll("/","~1")}`;function _n(e,t,n=""){let i=e=>({path:n,message:e}),{type:r}=e;if(void 0!==r){let e=Array.isArray(r)?r:[r];if(!e.some(e=>function(e,t){switch(e){case"object":return an(t);case"array":return Array.isArray(t);case"string":return"string"==typeof t;case"boolean":return"boolean"==typeof t;case"null":return null===t;case"number":return"number"==typeof t&&Number.isFinite(t);case"integer":return Number.isInteger(t);default:return!1}}(e,t)))return i(`must be ${e.join(" or ")}`)}if(void 0!==e.const&&!un(e.const,t))return i(`must be ${JSON.stringify(e.const)}`);if(Array.isArray(e.enum)&&!e.enum.some(e=>un(e,t)))return i("must be one of the allowed values");if("string"==typeof t){let n=[...t].length;if("number"==typeof e.minLength&&n<e.minLength)return i(`must have at least ${e.minLength} characters`);if("number"==typeof e.maxLength&&n>e.maxLength)return i(`must have at most ${e.maxLength} characters`);if("string"==typeof e.pattern&&!new RegExp(e.pattern,"u").test(t))return i(`must match pattern ${e.pattern}`)}if("number"==typeof t){if("number"==typeof e.minimum&&t<e.minimum)return i(`must be >= ${e.minimum}`);if("number"==typeof e.maximum&&t>e.maximum)return i(`must be <= ${e.maximum}`);if("number"==typeof e.exclusiveMinimum&&t<=e.exclusiveMinimum)return i(`must be > ${e.exclusiveMinimum}`);if("number"==typeof e.exclusiveMaximum&&t>=e.exclusiveMaximum)return i(`must be < ${e.exclusiveMaximum}`)}if(Array.isArray(t)){if("number"==typeof e.minItems&&t.length<e.minItems)return i(`must have at least ${e.minItems} items`);if("number"==typeof e.maxItems&&t.length>e.maxItems)return i(`must have at most ${e.maxItems} items`);if(an(e.items))for(let[i,r]of t.entries()){let t=_n(e.items,r,ln(n,i));if(void 0!==t)return t}}if(an(t)){let r=an(e.properties)?e.properties:{};for(let n of Array.isArray(e.required)?e.required:[])if(!Object.hasOwn(t,n))return i(`must have property ${n}`);for(let[s,o]of Object.entries(t)){let t=Object.hasOwn(r,s)?r[s]:void 0;if(an(t)){let e=_n(t,o,ln(n,s));if(void 0!==e)return e}else if(!1===e.additionalProperties)return i(`must not have property ${s}`)}}return Array.isArray(e.anyOf)&&!e.anyOf.some(e=>an(e)&&void 0===_n(e,t,n))?i("must match one of the allowed shapes"):void 0}var cn=["caller_session_durable_id","caller_created_target"],pn=/^tor_[a-f0-9]{32}$/,mn=12e4,gn=/^[a-z][a-z0-9_]{1,40}$/,fn=/^[a-z0-9][a-z0-9_-]*$/,bn=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,En=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),hn=e=>"string"==typeof e&&e.length>0;function yn(e,t){return`ext_${e}_${t}`}function vn(e){return!0!==e.internal}function Tn(e,t,n){if(!En(e))return"a sessionCallable entry must be an object";let{op:i,toolName:r,description:s,parameters:o,targetArg:a,wake:d}=e,u=e.await;if(!hn(i))return"op must be a non-empty string";let l=void 0!==e.internal;if(l){let t=function(e,t){if(!0!==e.internal)return`${t}: internal must be true when present`;for(let n of["toolName","await","wake"])if(void 0!==e[n])return`${t}: an internal op registers no tool, so it cannot declare ${n}`;return void 0===e.description||hn(e.description)?void 0:`${t}: description must be a non-empty string when present`}(e,i);if(void 0!==t)return t}else{if("string"!=typeof r||!gn.test(r))return`toolName ${String(r)} must match ${gn.source}`;if(yn(t,r).length>64)return`${yn(t,r)} is longer than 64 characters`;if(!hn(s))return`${r}: description must be a non-empty string`}let _=l?i:String(r);if(!En(o)||"object"!==o.type||!1!==o.additionalProperties)return`${_}: parameters must be an object schema with additionalProperties: false`;let c=o.properties??{};if(!En(c))return`${_}: parameters.properties must be an object`;if(cn.some(e=>Object.hasOwn(c,e)))return`${_}: parameters must not declare ${cn.join(" or ")}; the store stamps them`;let p=dn(o);if(void 0!==p)return`${_}: ${p}`;if(void 0!==a&&("string"!=typeof a||!Object.hasOwn(c,a)))return`${_}: targetArg ${String(a)} must name a field of parameters.properties`;if(void 0!==u){if(!En(u)||!hn(u.statusOp)||!hn(u.expireOp))return`${_}: await needs statusOp and expireOp`;let e=u.timeoutMs;if("number"!=typeof e||!Number.isInteger(e)||e<1||e>mn)return`${_}: await.timeoutMs must be an integer from 1 to 120000`;if(void 0===n)return`${_}: await needs the registration's wakeDir`}return void 0===d||"string"==typeof d&&bn.test(d)?void 0!==d&&void 0===n?`${_}: wake needs the registration's wakeDir`:void 0:`${_}: wake must be a plain file name matching ${bn.source}`}function wn(e,t){let{name:n,sessionCallable:i,wakeDir:r}=e;if(void 0!==r&&("string"!=typeof r||!fn.test(r)))return`wakeDir must be one path segment matching ${fn.source}`;if(void 0===i)return;if(!Array.isArray(i))return"sessionCallable must be an array";let s=new Set,o=new Set;for(let e of i){let i=Tn(e,n,r);if(void 0!==i)return i;let a=e;if(vn(a)){if(s.has(a.toolName))return`toolName ${a.toolName} is declared twice`;s.add(a.toolName)}if(o.has(a.op))return`op ${a.op} is declared twice`;if(o.add(a.op),void 0===t)continue;let d=vn(a)?a.await:void 0;for(let e of[a.op,...void 0===d?[]:[d.statusOp,d.expireOp]])if(!Object.hasOwn(t,e)||"function"!=typeof t[e])return`${vn(a)?a.toolName:a.op}: the module exports no operation ${e}`}}function Nn(e){let t=new Set;for(let n of e?.sessionCallable??[])if(t.add(n.op),vn(n)&&void 0!==n.await)for(let e of[n.await.statusOp,n.await.expireOp])t.add(e);return t}function Ln(e,t){try{let n=JSON.parse(String(t));if(!En(n)||"string"!=typeof n.moduleUrl||!Array.isArray(n.migrations))return;let i=n;return void 0===wn({...i,name:e})?i:void 0}catch{return}}function kn(e,t){let n=e.sql.one(["descriptor_json"],"SELECT descriptor_json FROM extension_registrations WHERE name = ?",[t]);return void 0===n?void 0:Ln(t,n.descriptor_json)}function On(e){return e.sql.all(["name","descriptor_json"],"SELECT name, descriptor_json FROM extension_registrations",[],"name").flatMap(e=>{let t=String(e.name);return(Ln(t,e.descriptor_json)?.sessionCallable??[]).filter(vn).map(e=>({...e,extension:t,registeredName:yn(t,e.toolName)}))})}function xn(e,t){let n=new Set((t.sessionCallable??[]).filter(vn).map(e=>yn(t.name,e.toolName))),i=On(e).find(e=>e.extension!==t.name&&n.has(e.registeredName));return void 0===i?void 0:`tool ${i.registeredName} is already declared by extension ${i.extension}`}async function Rn(e){let t=new URL(e);if("file:"!==t.protocol||![".js",".mjs",".cjs"].includes(Qt(t.pathname)))throw Error("moduleUrl must name a compiled JavaScript file URL.");if(!Zt(en(t)))throw Error(`The extension module ${e} does not exist.`);return await(import(e))}var Sn=0,An=1,qn=1,In=2,Cn=9,$n=10,Un=11,Dn=18,Mn=20,Hn=21,Wn=23,Xn=26,Fn=27,jn=31,Pn=33;class Gn extends Error{code="extension_schema_violation"}var Bn=["type","name","tbl_name","sql"],Jn=e=>e.replace(/[A-Z]/g,e=>e.toLowerCase()),Kn=e=>`${String(e.type)}:${Jn(String(e.name))}`;function Yn(e){return{objects:e.all(Bn,"SELECT type, name, tbl_name, sql FROM sqlite_schema",[],"type, name"),owners:new Map(e.all(["type","name","owner"],"SELECT type, name, owner FROM extension_objects").map(e=>[Kn(e),null===e.owner?null:String(e.owner)]))}}function Vn(e,t){let n=e.all(["name"],"SELECT name FROM extension_objects WHERE owner IS NULL");if(["gateway","thread","sqlite"].includes(t)||n.some(e=>Jn(String(e.name)).startsWith(t)))throw new Gn(`Extension name ${t} collides with a core namespace.`)}function zn(e,t,n,i){let r=new Map(n.objects.map(e=>[Kn(e),e])),s=new Map(i.objects.map(e=>[Kn(e),e])),o=[...new Set([...r.keys(),...s.keys()])].filter(e=>JSON.stringify(r.get(e))!==JSON.stringify(s.get(e)));for(let e of o){let a=r.get(e),d=s.get(e);if(void 0!==a&&n.owners.get(e)!==t)throw new Gn(`Extension ${t} changed an object it does not own: ${String(a.name)}.`);if(void 0===d)continue;if("trigger"===d.type||"view"===d.type)throw new Gn("Store extensions cannot create triggers or views.");let u=Jn(String(d.name));if(("index"!==d.type||null!==d.sql||!u.startsWith(`sqlite_autoindex_${Jn(String(d.tbl_name))}_`))&&!u.startsWith(`${t}_`)||n.owners.has(e)&&n.owners.get(e)!==t)throw new Gn(`Extension ${t} created an object outside its namespace: ${String(d.name)}.`);if("index"===d.type){let e=`table:${Jn(String(d.tbl_name))}`,a=!r.has(e)&&s.has(e)&&o.includes(e);if(n.owners.get(e)!==t&&i.owners.get(e)!==t&&!a)throw new Gn(`Extension ${t} indexed a table it does not own: ${String(d.tbl_name)}.`)}}for(let n of o){let i=r.get(n),o=s.get(n);void 0!==i&&e.run("DELETE FROM extension_objects WHERE type = ? AND name = ? COLLATE NOCASE AND owner = ?",[String(i.type),String(i.name),t]),void 0!==o&&e.run("INSERT INTO extension_objects (type, name, owner) VALUES (?, ?, ?) ON CONFLICT(type, name) DO UPDATE SET owner = excluded.owner",[String(o.type),Jn(String(o.name)),t])}}function Zn(e,t,n){let i,r,s=Yn(e),o=new Map(s.owners),a=new Set(s.objects.filter(e=>"trigger"===e.type||"view"===e.type).map(e=>Jn(String(e.name)))),d=(e,n)=>null!==n&&o.get(`${e}:${n}`)===t,u=(e,n,i=!1)=>!(null===n||!i&&!n.startsWith(`${t}_`)||o.has(`${e}:${n}`))&&(o.set(`${e}:${n}`,t),!0),l=!1,_=Sn,c=e=>(r=`Extension ${t} does not own ${e??"this SQLite operation"}.`,An);try{return e.authorized((e,t,n,r,s)=>{let o=null===t?null:Jn(t),p=null===n?null:Jn(n),m=null===r?null:Jn(r),g=null===s?null:Jn(s);if(null!==g&&a.has(g))return c(g);switch(e){case In:return i="create","main"===m&&u("table",o)?_:c(o);case qn:return i="create","main"===m&&d("table",p)&&u("index",o,!0===o?.startsWith(`sqlite_autoindex_${p}_`))?_:c(o);case Un:return i="drop","main"===m&&d("table",o)?_:c(o);case $n:return i="drop","main"===m&&d("index",o)&&d("table",p)?_:c(o);case Xn:return i="alter","main"===o&&d("table",p)?_:c(p);case Fn:return"main"===m&&d("index",o)?_:c(o);case Mn:case Dn:case Wn:case Cn:return"sqlite_master"===o||"sqlite_temp_master"===o?(e===Wn&&"sql"===p&&(l=!0),e!==Mn||"alter"===i||"drop"===i||"create"===i&&l&&"rowid"===p?_:c(o)):"alter"!==i||"sqlite_sequence"!==o||"name"!==p||e!==Mn&&e!==Wn?("main"===m||null===m&&e===Mn&&""===p)&&d("table",o)?_:c(o):_;case Hn:case Pn:return _;case jn:return"load_extension"===p?c(p):_;default:return c(o)}},n)}catch(e){if(void 0!==r)throw new Gn(r);throw e}}import{createHash as Qn,randomUUID as ei}from"node:crypto";import{execFile as ti}from"node:child_process";import{existsSync as ni,readFileSync as ii,statSync as ri}from"node:fs";import{homedir as si}from"node:os";import{basename as oi,delimiter as ai,dirname as di,isAbsolute as ui,join as li,relative as _i,resolve as ci,sep as pi}from"node:path";var mi=(e,t)=>new Promise(n=>{ti("git",[...e],{cwd:t.cwd,env:t.env,encoding:"utf8",windowsHide:!0,timeout:t.timeoutMs},(e,t,i)=>{if(null===e)return n({ok:!0,stdout:t});n({ok:!1,code:e.code??null,killed:!0===e.killed,stderr:i,message:e.message})})});function gi(e,t){let n=li(e,".git");if(!ni(n))return!1;if(ri(n).isDirectory())return!0;let i=/^gitdir:\s*(.+?)\s*$/m.exec(t(n))?.[1];return void 0!==i&&ni(ci(e,i))}async function fi(e,t,n,i){if(!function(e,t,n,i){if(t.GIT_DIR)return!0;let r=new Set((t.GIT_CEILING_DIRECTORIES??"").split(ai).filter(e=>ui(e)).map(e=>ci(e)));try{for(let t=ci(e);;t=di(t)){if(gi(t,i))return!0;if(di(t)===t||r.has(di(t)))return!1}}catch(e){return n(`finding the sender's repository failed, so git does not classify this send: ${e instanceof Error?e.message:String(e)}`),!1}}(e,t,n,i.readGitFile??(e=>ii(e,"utf8"))))return;let r=await(i.execGit??mi)(["remote","get-url","origin"],{cwd:e,env:t,timeoutMs:1e3});if(r.ok)return r.stdout.trim();"ENOENT"===r.code?n("git is not installed for the sender, so git does not classify this send"):r.killed?n("reading the sender's git origin failed, so git does not classify this send: git did not answer within 1000 ms"):2!==r.code&&n(`reading the sender's git origin failed, so git does not classify this send: ${r.stderr.trim()||r.message}`)}async function bi(e){let t=e.env??process.env,n=t.OMO_PROVENANCE_WORKSPACE?.trim(),i=t.OMO_PROVENANCE_PROJECT?.trim(),r=t.OMO_PROVENANCE_LANE?.trim(),s=r?{lane:r}:{};if(n&&i)return{workspace:n,project:i,...s};let o=e.onWarning??(()=>{}),a=function(e){if(void 0===e)return;let t=/^[a-z][a-z0-9+.-]*:\/\//i.test(e)?URL.parse(e):null,n=null!==t||/^[a-z]:[\\/]/i.test(e)?void 0:/^(?:[^/@:]+@)?[^/:]+:(.+)$/.exec(e)?.[1],i=(t?.pathname??n??e).replace(/\\/g,"/").replace(/\/+$/,"").split("/").filter(Boolean),r=i?.at(-1)?.replace(/\.git$/,""),s=null!==t&&"file:"!==t.protocol||void 0!==n?i.slice(0,-1):[];return r?{owners:s,project:r}:void 0}(await(e.gitRemote??(n=>fi(n,t,o,e)))(e.cwd)),d=i||a?.project||oi(ci(e.cwd))||"root";if(n)return{workspace:n,project:d,...s};let u=e.workspaces??function(e,t,n){try{return e.loadWorkspaces?.(e.cwd,t)??[]}catch(e){return n(`reading provenance.workspaces failed, so the table does not classify this send: ${e instanceof Error?e.message:String(e)}`),[]}}(e,t,o),l=new Set(a?.owners.map(e=>e.toLowerCase())??[]),_=0===l.size?void 0:u.find(e=>e.git_owners?.some(e=>l.has(e.toLowerCase()))),c=t.HOME??t.USERPROFILE??si();return{workspace:(_??u.find(t=>t.paths?.some(t=>function(e,t,n){let i="~"===t?n:t.startsWith("~/")?ci(n,t.slice(2)):t;if(!ui(i))return!1;let r=_i(ci(i),ci(e));return""===r||!ui(r)&&".."!==r&&!r.startsWith(`..${pi}`)}(e.cwd,t,c))))?.name??"unclassified",project:d,...s}}var Ei={loop_detected:"A session cannot message itself through the gateway; address another thread.",overloaded:"Wait before sending to this session again.",queue_full:"Wait for the target to take its queued messages, then send again.",idempotency_conflict:"Retry with a new idempotency_key.",idempotency_in_progress:"Wait for the earlier call to settle, then retry.",idempotency_uncertain:"Read the target transcript before deciding whether to send again; the gateway never resends.",invalid_arguments:"Fix the arguments and send again."};function hi(e,t,n){return{kind:"error",error:ve(e,t,Ei[e]??"Call thread_list and retry after checking the target.",n)}}function yi(e){return t={target:e.target,text:e.text,mode:e.mode,expected_turn_id:e.expected_turn_id,binding:e.binding,author:e.author},Qn("sha256").update(JSON.stringify(t)).digest("hex");var t}function vi(e){let t=!1;for(let n of y(e))if("space"!==n.kind&&"comment"!==n.kind){if(t)throw new Gn("An extension SQL call must contain one statement.");"semicolon"===n.kind&&(t=!0)}}var Ti=/^[ \t\r\n]*([A-Za-z_][A-Za-z0-9_]*)(?:[ \t\r\n]+COLLATE[ \t\r\n]+(BINARY|NOCASE|RTRIM))?(?:[ \t\r\n]+(ASC|DESC))?(?:[ \t\r\n]+NULLS[ \t\r\n]+(FIRST|LAST))?[ \t\r\n]*$/i,wi=e=>JSON.stringify(e.length>80?`${e.slice(0,80)}…`:e),Ni=e=>e?.toUpperCase();var Li=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;function ki(e){return{kind:"refused",code:"invalid_arguments",message:e}}function Oi(e,t,n){return"string"!=typeof t||0===t.trim().length?ki(`author.${e} must be a non-empty string.`):t.length>n?ki(`author.${e} is longer than ${n} characters.`):Li.test(t)?ki(`author.${e} carries a control character or line break.`):t.trim()}var xi={binding_conflict:"Call thread_bindings to find the binding that holds this thread, then thread_rebind it with its revision, or thread_unbind it first.",binding_mismatch:"Answer through the binding that asked the question; the question stays pending.",binding_inactive:"Bind the thread again with thread_bind.",stale_revision:"Call thread_bindings for the current revision and retry with it.",stale_token:"The question was asked under an earlier binding revision or session runtime; wait for the session to ask again.",already_answered:"Nothing to do: the question has its answer.",answer_in_progress:"Retry after a moment: another answer is still being handed to the session, and the question goes back to pending if that fails.",idempotency_conflict:"Retry with a new idempotency_key.",idempotency_uncertain:"Call thread_bindings or thread_outbox to see the current state before retrying with a new key.",scope_denied:"Report through a binding attached to this session; thread_bindings lists them.",unsupported:"Report only the events the binding subscribes to, through a binding with an outbound direction.",not_found:"Call thread_bindings for the binding ids that exist.",cursor_invalid:"Read thread_outbox again and ack a cursor it returned.",host_unavailable:"Retry when the session is running; the question stays pending.",invalid_arguments:"Fix the arguments and call again."},Ri=new Set(["question_already_resolved","unknown_extension_ui_request","unknown_request"]);function Si(e,t,n,i){return{kind:"error",error:ve(e,t,i??xi[e]??"Call thread_bindings and retry after checking the binding.",n)}}function Ai(e){return"refused"===e.kind?Si(e.code,e.message,e.details):e}function qi(e){if(void 0===e)return;let t=function(e){let t=Oi("platform_user_id",e.platform_user_id,256);if("string"!=typeof t)return t;let n=Oi("display",e.display,256);if("string"!=typeof n)return n;if(void 0===e.user_id)return{platform_user_id:t,display:n};let i=Oi("user_id",e.user_id,256);return"string"!=typeof i?i:{platform_user_id:t,display:n,user_id:i}}(e);return"kind"in t?Si("invalid_arguments",t.message):t}function Ii(e){let t=Buffer.byteLength(e);return t>32768?Si("message_too_large",`The text is ${t} bytes, above the 32768-byte limit.`):void 0}function Ci(e,t,n){return void 0===e.idempotency_key?null:{principal:e.principal,operation:t,idempotency_key:e.idempotency_key,args_hash:(i=n,Z("sha256").update(ce(i)).digest("hex"))};var i}function $i(e){let t=e.store,n=e.now??t.now,i=new Set,r=!1;async function s(e){await o(()=>t.releaseAnswer(e))}async function o(e){try{await e()}catch(n){if(!u(n)||r)throw n;let s=function(e,t,n){let i,r=!1,s=()=>{i=setTimeout(()=>{i=void 0,r||e().catch(e=>{r||(u(e)?s():n(e))})},t()),i.unref?.()};return s(),{cancel:()=>{r=!0,clearTimeout(i)}}}(()=>e().then(()=>{i.delete(s)}),()=>t.busyTimeoutMs,()=>{i.delete(s)});i.add(s)}}return{bind:async e=>{let i=function(e){if(!ne.includes(e.platform))return de(`platform must be one of ${ne.join(", ")}.`);let t={account_id:ue("account_id",e.account_id),chat_id:ue("chat_id",e.chat_id),thread_id:ue("thread_id",e.thread_id??"@chat"),root_message_id:le("root_message_id",e.root_message_id),progress_message_id:le("progress_message_id",e.progress_message_id),session_durable_id:ue("session",e.session_durable_id),policy_id:ue("policy_id",e.policy_id??"default")};for(let e of Object.values(t))if(_e(e))return e;let n=e.direction??{inbound:!0,outbound:!0};if(!0!==n.inbound&&!0!==n.outbound)return de("A binding needs at least one direction: inbound, outbound, or both.");let i=e.inbound_mode??"auto";if(!re.includes(i))return de(`inbound_mode must be one of ${re.join(", ")}.`);let r=e.outbound_events??(n.outbound?ie:[]);if(r.some(e=>!ie.includes(e)))return de(`outbound_events may only name ${ie.join(", ")}.`);if(new Set(r).size!==r.length)return de("outbound_events must not repeat an event.");if(n.outbound&&0===r.length)return de("An outbound binding needs at least one outbound event.");let s=void 0===e.ttl_seconds?604800:e.ttl_seconds;return null!==s&&(!Number.isInteger(s)||s<1||s>se)?de("ttl_seconds must be an integer from 1 to 31622400, or null for a binding that never expires."):{platform:e.platform,account_id:t.account_id,chat_id:t.chat_id,thread_id:t.thread_id,root_message_id:t.root_message_id,progress_message_id:t.progress_message_id,session_durable_id:t.session_durable_id,direction:{inbound:!0===n.inbound,outbound:!0===n.outbound},inbound_mode:i,outbound_events:ie.filter(e=>r.includes(e)),policy_id:t.policy_id,ttl_seconds:s}}(e.binding);return Ai("kind"in i?i:await t.bind({now:n(),receipt:Ci(e,"thread_bind",i),binding:i}))},unbind:async e=>{let i={binding_id:e.binding_id,expected_revision:e.expected_revision};return Ai(await t.unbind({now:n(),receipt:Ci(e,"thread_unbind",i),...i}))},rebind:async e=>{let i={binding_id:e.binding_id,expected_revision:e.expected_revision,session_durable_id:e.session_durable_id};return Ai(await t.rebind({now:n(),receipt:Ci(e,"thread_rebind",i),...i}))},bindings:async e=>Ai(await t.listBindings({now:n(),...e})),report:async e=>{let i=Ii(e.text);if(void 0!==i)return i;let r={session_durable_id:e.session_durable_id,binding_id:e.binding_id??null,origin_delivery_ids:e.origin_delivery_ids??[],origin_local_input:!0===e.origin_local_input,event:e.event,text:e.text,ui_request_id:e.request_id??null,ui_request_kind:e.request_kind??null};return Ai(await t.report({now:n(),receipt:Ci(e,"thread_report",r),...r}))},outbox:async e=>Ai(await t.readOutbox({now:n(),...e})),ack:async e=>Ai(await t.ackOutbox({now:n(),...e})),answer:async i=>{let r=Ii(i.answer);if(void 0!==r)return r;let a=qi(i.author);if(void 0!==a&&"kind"in a)return a;let d=a??null,u=await t.claimAnswer({now:n(),binding_id:i.binding_id,reply_token:i.reply_token,answer:i.answer,answered_by:d});if("ok"!==u.kind)return Ai(u);let l={reply_token:i.reply_token,claimed_at:u.claimed_at},_=e.endpoints.respondUi,c=null,p="";if(void 0!==_)try{c=await e.locate(u.session_durable_id)}catch(e){p=`: ${e instanceof Error?e.message:String(e)}`}if(void 0===_||null===c)return await s(l),Si(void 0===_?"unsupported":"host_unavailable",`The session that asked is not reachable to take the answer${p}.`,{session:u.session_durable_id});let m,g=ft(u.ui_request_kind,i.answer);if(!g.ok)return await s(l),Si("invalid_arguments",g.reason,{session:u.session_durable_id,ui_request_kind:u.ui_request_kind});try{m=await _(c,{ui_request_id:u.ui_request_id,fields:g.fields})}catch(e){return await s(l),Si("host_unavailable",`The answer could not be handed to the session: ${e instanceof Error?e.message:String(e)}`,{session:u.session_durable_id})}if(!m.delivered){let e=u.taken_over;if(null!==e&&Ri.has(m.error))return"question_already_resolved"===m.error?(await o(()=>t.markPriorDelivered({...l,prior:e})),Si("already_answered",`The session already took an earlier answer to this question (${m.error}).`,{session:u.session_durable_id,reason:m.error})):(await o(()=>t.markPriorDelivered({...l,prior:{answer:null,answered_at:l.claimed_at}})),Si("already_answered",`${Bt} (${m.error}).`,{session:u.session_durable_id,reason:m.error},"Nothing to do: the session no longer waits for this question."));await s(l);let n="invalid_response"===m.error||"question_incomplete"===m.error;return"host_draining"===m.error?Si("stale_token","The session's host is draining and could not take the answer: host_draining",{session:u.session_durable_id,reason:m.error},"The session's host is handing its sessions over; the question stays pending. Answer it again once the host is back."):Si(n?"invalid_arguments":"stale_token",`The session refused the answer: ${m.error}`,{session:u.session_durable_id,reason:m.error},n?`The session could not read this answer (${m.error}); answer again with text it can take. The question stays pending.`:`The session refused the answer (${m.error}): it no longer waits on this question. Read thread_outbox for a newer question and answer that one.`)}return await async function(e){await o(()=>t.confirmAnswer(e))}({...l,answer:i.answer,answered_by:d}),{kind:"ok",binding_id:i.binding_id,cursor:u.cursor,session_durable_id:u.session_durable_id,answered_by:d}},inbound:async i=>{if(void 0!==i.mode&&!re.includes(i.mode))return Si("invalid_arguments",`A binding message is delivered as ${re.join(" or ")}, never ${String(i.mode)}.`,{mode:i.mode},"Send with mode auto or follow_up, or omit it for the binding's inbound_mode.");let r=qi(i.author);if(void 0!==r&&"kind"in r)return r;let s=await t.bindingView({now:n(),binding_id:i.binding_id});if(null===s)return Si("not_found","No binding has this id.",{binding_id:i.binding_id});let o={principal:`binding:${s.binding_id}`,idempotency_key:`event:${i.event_id}`},a=await t.deliveryReceipt({now:n(),...o});if(null!==a&&null!==a.binding_revision&&a.args_hash===yi({target:a.target_durable_id,text:i.text,mode:i.mode??s.inbound_mode,expected_turn_id:null,binding:{binding_id:s.binding_id,revision:a.binding_revision},author:r})){let e=a.completed?{kind:"replay",result:a.result}:await t.recoverDelivery({now:n(),...o,args_hash:a.args_hash});if("replay"===e?.kind){let t=e.result;return"ok"===t.kind?{...t,deduplicated:!0}:t}if("refused"===e?.kind)return Si(e.code,e.message,e.details)}if("active"!==s.status)return Si("binding_inactive",`The binding is ${s.status}.`,{binding_id:s.binding_id,status:s.status});if(!s.direction.inbound)return Si("unsupported","The binding carries no inbound direction.",{binding_id:s.binding_id});let d=i.mode??s.inbound_mode;return"auto"===d&&"follow_up"===s.inbound_mode?Si("invalid_arguments","The binding delivers at most follow_up; a message cannot ask for more than its binding's inbound_mode.",{binding_id:s.binding_id,mode:d,inbound_mode:s.inbound_mode},"Send with mode follow_up (or omit it), or rebind the thread with inbound_mode auto."):await e.engine.deliver({sender:{kind:"external",origin:{platform:s.platform,account_id:s.account_id,chat_id:s.chat_id,thread_id:s.thread_id,message_id:i.event_id,...void 0===r?{}:{author:r}},binding_id:s.binding_id,binding_revision:s.revision},target:s.session_durable_id,text:i.text,mode:d,all_scope:!0,idempotency_key:`event:${i.event_id}`})},settle:e=>t.emitCompletions({now:n(),...e}),dispose:()=>{r=!0;for(let e of i)e.cancel();i.clear()}}}class Ui extends Error{extension;code="extension_operation_failed";constructor(e){super(`The ${e} extension transaction has ended.`),this.extension=e}}class Di extends Error{extension;code="extension_operation_failed";constructor(e){super(`The ${e} extension ran a statement while a tx helper (enqueue, bind, ...) was still in flight; await the helper first.`),this.extension=e}}class Mi extends Error{code="invalid_arguments"}function Hi(e,t,n,i,r){let s,o=!0,a=0,d=!1,u=Promise.resolve();function l(e){if(d)throw new Ui(t);if(void 0!==s)throw s;return e()}function _(e){if(!o)return Promise.reject(new Ui(t));a++;let n=u.then(()=>l(e));return u=n.then(()=>{a--},e=>{a--,s=e}),n}function c(n,i){if((()=>{if(!o)throw new Ui(t);if(void 0!==s)throw s})(),a>0)throw s=new Di(t),s;let r=Yn(e.sql);try{vi(n);let s=Zn(e.sql,t,i);return zn(e.sql,t,r,Yn(e.sql)),s}catch(e){throw s=e,e}}let p={now:()=>n,busyTimeoutMs:e.config.busy_timeout_ms,enqueue:t=>l(()=>Ve(e,t)),completeReceipt:t=>l(()=>it(e,t)),abandonReceipt:t=>l(()=>rt(e,t)),deliveryView:async t=>l(()=>at(e,t)),deliveryReceipt:async t=>l(()=>st(e,t)),recoverDelivery:t=>l(()=>ot(e,t)),bind:t=>l(()=>It(e,t)),unbind:t=>l(()=>$t(e,t)),rebind:t=>l(()=>Ut(e,t)),listBindings:t=>l(()=>Dt(e,t)),bindingView:t=>l(()=>Mt(e,t)),report:t=>l(()=>Xt(e,t)),readOutbox:t=>l(()=>Pt(e,{...t,pendingOnly:!0})),ackOutbox:t=>l(()=>Gt(e,t)),claimAnswer:t=>l(()=>Jt(e,t)),releaseAnswer:t=>l(()=>Yt(e,t)),confirmAnswer:t=>l(()=>zt(e,t)),markPriorDelivered:t=>l(()=>Vt(e,t)),emitCompletions:t=>l(()=>Ft(e,t))},m={wake:async()=>{throw Error("An extension enqueue cannot contact a live endpoint.")}},g=function(e){let t=e.store,n=e.now??t.now;return{deliver:async function(i){let r=i.mode??"auto";if("steer"===r&&void 0===i.expected_turn_id)return hi("invalid_arguments","A steer needs expected_turn_id (the target's current turn_epoch).");let s=Buffer.byteLength(i.text);if(s>H)return hi("message_too_large",`The message is ${s} bytes, above the 1048576-byte limit.`);let o=await e.resolve(i.target,{all_scope:i.all_scope});if("error"===o.kind)return o;let a=o.target,d="routable"===a.liveness?a.endpoint:null;if(null===d&&"refuse"===function(e,t,n,i){return"offline"===e?"steer"===t?{kind:"refuse",reason:"turn_conflict"}:{kind:"queued_offline"}:"steer"===t?"mid_turn"!==e?{kind:"refuse",reason:"not_steerable"}:null===n||null===i||n!==i?{kind:"refuse",reason:"turn_conflict"}:{kind:"admit",deliverAs:"steer",expected_turn_id:n,expect:"steered"}:{kind:"admit",deliverAs:"followUp",expect:"idle"===e?"started":"queued"}}("offline",r,i.expected_turn_id??null,null).kind)return hi("turn_conflict","The target has no live turn to steer.",{target:a.durable_id});let u=function(e,t){let n="session"===e.kind?e.name?.trim():void 0,i={...t,...n?{session:n}:{}};if("session"===e.kind)return{provenance:i,principal:`session:${e.durable_id}`,rate_principal:`session:${e.durable_id}`,node:e.durable_id,turn:e.turn_id??null,cause:e.cause_delivery_id??null,actor:e.name??e.durable_id,origin:()=>({session:e.durable_id}),binding:null};if("cli"===e.kind){let t=`cli:${e.uid}`;return{provenance:i,principal:t,rate_principal:t,node:t,turn:null,cause:null,actor:e.user,origin:t=>({external:{platform:"cli",account_id:e.user,chat_id:"@cli",thread_id:"@chat",message_id:t}}),binding:null}}let r=`binding:${e.binding_id}`,s=e.origin.author;return{provenance:i,principal:r,rate_principal:void 0===s?r:`${r}#author:${s.platform_user_id}`,node:r,turn:null,cause:null,actor:e.origin.account_id,origin:()=>({external:e.origin}),binding:{binding_id:e.binding_id,revision:e.binding_revision}}}(i.sender,await(e.senderProvenance?.()??bi({cwd:process.cwd()}))),l=ei(),_=i.idempotency_key??`auto:${l}`,c=await t.enqueue({provenance:u.provenance,now:n(),delivery_id:l,target_durable_id:a.durable_id,sender_principal:u.principal,rate_principal:u.rate_principal,sender_node:u.node,sender_turn:u.turn,cause_delivery_id:u.cause,claimed_root_id:i.root_id??null,origin:u.origin(l),actor:u.actor,body:i.text,mode:r,expected_turn_id:i.expected_turn_id??null,binding:u.binding,receipt:{idempotency_key:_,args_hash:yi({target:a.durable_id,text:i.text,mode:r,expected_turn_id:i.expected_turn_id??null,binding:u.binding,author:"external"===i.sender.kind?i.sender.origin.author:void 0})},endpoint_kind:d?.kind??null});if("busy"===c.kind)return hi("overloaded","The gateway store is locked by a suspended writer; nothing was sent.",{budget:"store_lock"});if("refused"===c.kind)return hi(c.code,c.message,c.details);if("replay"===c.kind){let e=c.result;return"ok"===e.kind?{...e,deduplicated:!0}:e}let p=async e=>(await t.completeReceipt({now:n(),principal:u.principal,idempotency_key:_,result:e}),e);try{if(null===d)return await p(we(c.row,c.queue_position,null,!1,!0));let n;try{n=await e.endpoints.wake(d,[l])}catch{n=void 0}let i=await t.deliveryView(l);if(null===i)throw Error(`delivery ${l} vanished after commit`);let r=void 0!==n&&void 0===n.unroutable&&("queued"!==i.row.state||(n.admitted??[]).length>0);return await p(we(i.row,i.queue_position,d.kind,!1,!r))}catch(e){throw await t.abandonReceipt({now:n(),principal:u.principal,idempotency_key:_,error_note:e instanceof Error?e.message:String(e)}).catch(()=>!1),e}}}}({store:p,endpoints:m,senderProvenance:r,resolve:async(e,t)=>{let n=await i(e,t);return"error"===n.kind?n:{kind:"ok",target:{...n.target,endpoint:null,liveness:"dead"}}}}),f=$i({store:p,engine:g,endpoints:m,locate:async()=>null});return{tx:{all:(t,n,i,r)=>c(n,()=>{for(let e of t)vi(e);if(void 0===r)return e.sql.all(t,n,i);let s=function(e){return e.split(",").map(t=>{let n=Ti.exec(t);if(null===n)throw new Gn(`orderBy must list the statement's output columns, each optionally with COLLATE BINARY/NOCASE/RTRIM, ASC/DESC or NULLS FIRST/LAST; got ${wi(e)}. Put LIMIT, OFFSET and table-qualified ordering in the statement itself.`);return{column:n[1],collate:Ni(n[2]),direction:Ni(n[3]),nulls:Ni(n[4])}})}(r);return e.sql.all(["0"],`SELECT 0 FROM (${n}\n) WHERE 0`,i),e.sql.all(t,n,i,function(e,t){return e.map(e=>{let n=t.find(t=>Jn(t)===Jn(e.column));if(void 0===n)throw new Gn(`orderBy must list the statement's output columns; ${wi(e.column)} is not one of them (${wi(t.join(", "))}). Select it in the statement or order by a column it returns.`);return[`"${n.replaceAll('"','""')}"`,e.collate&&`COLLATE ${e.collate}`,e.direction,e.nulls&&`NULLS ${e.nulls}`].filter(Boolean).join(" ")}).join(", ")}(s,e.sql.resultColumns(n)))}),one:(t,n,i)=>c(n,()=>{for(let e of t)vi(e);return e.sql.one(t,n,i)}),exec:(t,n)=>c(t,()=>e.sql.run(t,n)),enqueue:e=>_(()=>f.inbound(e)),outboxAck:e=>_(()=>f.ack(e)),bind:e=>_(()=>f.bind(e)),unbind:e=>_(()=>f.unbind(e)),rebind:e=>_(()=>f.rebind(e)),bindingFor:t=>_(()=>async function(e,t){return await Me(e,"binding_for",()=>(xt(e,t.now),Lt(e,"platform = ? AND account_id = ? AND chat_id = ? AND thread_id = ? AND status = 'active'",[t.platform,t.account_id,t.chat_id,t.thread_id])[0]??null))}(e,{...t,now:n})),bindingsForSession:t=>_(async()=>{if("string"!=typeof t||0===t.length)throw new Mi("bindingsForSession needs a non-empty session durable id.");return Lt(e,"session_durable_id = ? AND status = 'active' AND (expires_at IS NULL OR expires_at > ?)",[t,ae(n)]).toSorted((e,t)=>e.binding_id<t.binding_id?-1:e.binding_id>t.binding_id?1:0)}),outboxPending:e=>_(()=>f.outbox(e))},cancel:()=>{o=!1,d=!0,f.dispose()},finish:async()=>{if(o=!1,await u,f.dispose(),void 0!==s)throw s}}}function Wi(e,t){return{kind:"refused",code:e,message:t}}function Xi(e){let t=e instanceof Error?e.message:String(e);return e instanceof Gn||e instanceof Le||e instanceof Mi?Wi(e.code,t):u(e)?Wi("gateway_lock_wait_exceeded",t):Wi("extension_operation_failed",t)}class Fi{ctx;resolveTarget;senderProvenance;registered=new Map;constructor(e,t,n){this.ctx=e,this.resolveTarget=t,this.senderProvenance=n}async register(e,t,n){if(!/^[a-z][a-z0-9_]{1,31}$/.test(e.name)||!Array.isArray(e.migrations)||!e.migrations.every(e=>Array.isArray(e)&&e.every(e=>"string"==typeof e)))return Wi("invalid_arguments","An extension needs a valid namespace and an array of SQL migration steps.");let i,r=wn(e);if(void 0!==r)return Wi("invalid_arguments",`Extension ${e.name}: ${r}.`);try{Vn(this.ctx.sql,e.name)}catch(e){return Xi(e)}try{i=await Rn(e.moduleUrl)}catch(t){return Wi("extension_import_failed",`Cannot import extension ${e.name}: ${t instanceof Error?t.message:String(t)}`)}let s=wn(e,i);if(void 0!==s)return Wi("invalid_arguments",`Extension ${e.name}: ${s}.`);let o=xn(this.ctx,e);if(void 0!==o)return Wi("invalid_arguments",`Extension ${e.name}: ${o}.`);try{let r=await this.ensure(e,t),s=await Me(this.ctx,"extension_register",()=>function(e,t,n,i){let r=xn(e,t);if(void 0!==r)return r;let s={moduleUrl:t.moduleUrl,migrations:t.migrations,...void 0===t.sessionCallable?{}:{sessionCallable:t.sessionCallable},...void 0===t.wakeDir?{}:{wakeDir:t.wakeDir}},o=void 0===i?"":" WHERE excluded.updated_at >= extension_registrations.updated_at";e.sql.run(`INSERT INTO extension_registrations (name, descriptor_json, updated_at) VALUES (?, ?, ?) ON CONFLICT(name) DO UPDATE SET descriptor_json = excluded.descriptor_json, updated_at = excluded.updated_at${o}`,[t.name,JSON.stringify(s),i??n])}(this.ctx,e,t,n));return void 0!==s?Wi("invalid_arguments",`Extension ${e.name}: ${s}.`):(this.registered.set(e.name,{descriptor:e,module:i}),{kind:"ok",value:{version:r}})}catch(t){return t instanceof Le||this.registered.set(e.name,{descriptor:e,module:i}),Xi(t)}}holds(e){return this.registered.get(e.name)?.descriptor===e}async ensure(e,t){let{name:n,migrations:i}=e,r=this.ctx.sql.one(["version"],"SELECT version FROM extension_schema WHERE name = ?",[n]);if(void 0!==r&&Number(r.version)===i.length)return i.length;for(;;){let e=await Me(this.ctx,"extension_migrate",()=>{let e=this.ctx.sql.one(["version"],"SELECT version FROM extension_schema WHERE name = ?",[n]),r=Number(e?.version??0);if(r>i.length)throw new Le(r,i.length,`Extension ${n}`);let s=Yn(this.ctx.sql);if(void 0===e&&s.objects.some(e=>Jn(String(e.name)).startsWith(`${n}_`)&&null==s.owners.get(`${String(e.type)}:${Jn(String(e.name))}`)))throw new Gn(`Namespace ${n} already contains unowned objects.`);if(r===i.length)return void 0===e&&this.ctx.sql.run("INSERT INTO extension_schema (name, version, updated_at) VALUES (?, 0, ?)",[n,t]),{version:r,applied:!1};for(let e of i[r]){vi(e);let t=Yn(this.ctx.sql);Zn(this.ctx.sql,n,()=>this.ctx.sql.exec(e)),zn(this.ctx.sql,n,t,Yn(this.ctx.sql))}return zn(this.ctx.sql,n,s,Yn(this.ctx.sql)),this.ctx.sql.run("INSERT INTO extension_schema (name, version, updated_at) VALUES (?, ?, ?) ON CONFLICT(name) DO UPDATE SET version = excluded.version, updated_at = excluded.updated_at",[n,r+1,t]),{version:r+1,applied:!0}});if(!e.applied)return e.version}}async call(e,t,n,i){let r=this.registered.get(e),s=kn(this.ctx,e);if(Nn(r?.descriptor).has(t)||Nn(s).has(t))return Wi("caller_not_allowed",`${e}.${t} is session-callable: only the session's own tool reaches it, with the caller the engine resolved.`);let o=r??await this.load(e,s);return"kind"in o?o:await this.run({name:e,descriptor:o.descriptor,module:o.module,op:t,args:()=>n},i)}async load(e,t=kn(this.ctx,e)){if(void 0===t)return Wi("extension_unknown_name",`No store extension is registered as ${e}.`);try{Vn(this.ctx.sql,e)}catch(e){return Xi(e)}try{return{descriptor:{...t,name:e},module:await Rn(t.moduleUrl)}}catch(t){return Wi("extension_import_failed",`Cannot import extension ${e}: ${t instanceof Error?t.message:String(t)}`)}}async run(e,t){let{name:n,op:i,module:r}=e,s=Object.hasOwn(r,i)?r[i]:void 0;if("function"!=typeof s)return Wi("extension_unknown_op",`Extension ${n} exports no operation ${i}.`);let o,a=[],d=[];try{let r=await this.ensure(e.descriptor,t);o=await Me(this.ctx,"extension_call",async()=>{let o=this.ctx.sql.one(["version"],"SELECT version FROM extension_schema WHERE name = ?",[n]),u=Number(o?.version??0);if(u!==r)throw new Le(u,e.descriptor.migrations.length,`Extension ${n}`);let l,_=Yn(this.ctx.sql),c=Hi({...this.ctx,afterCommit:a,afterRollback:d},n,t,this.resolveTarget,this.senderProvenance);try{let t=async()=>{try{return await s(c.tx,e.args())}finally{await c.finish()}},r=new Promise((e,t)=>{l=setTimeout(()=>{c.cancel(),t(Error(`Extension ${n}.${i} exceeded its ${this.ctx.config.lock_wait_max_ms} ms operation budget.`))},this.ctx.config.lock_wait_max_ms)}),o=await Promise.race([t(),r]);zn(this.ctx.sql,n,_,Yn(this.ctx.sql));let d=structuredClone(o);return a.push(...e.effects??[]),d}finally{clearTimeout(l),c.cancel()}})}catch(e){for(let e of d)try{e()}catch(e){this.ctx.emit({kind:"extension_error",extension:n,phase:"after_rollback",error:e instanceof Error?e.message:String(e)})}return Xi(e)}await this.ctx.hook("afterDbCommit");for(let e of a)try{e()}catch(e){this.ctx.emit({kind:"extension_error",extension:n,phase:"after_commit",error:e instanceof Error?e.message:String(e)})}return{kind:"ok",value:o}}}import{randomUUID as ji}from"node:crypto";import{rmSync as Pi,renameSync as Gi,writeFileSync as Bi}from"node:fs";import{dirname as Ji,join as Ki}from"node:path";var Yi=(e,t)=>({result:{kind:"refused",code:e,message:t}});function Vi(e,t,n){return void 0!==e.sql.one(["n"],"SELECT 1 AS n FROM thread_creations WHERE creator_durable_id = ? AND created_durable_id = ?",[t,n])}async function zi(e,t,n){let{name:i,caller:r,phase:s}=n;if("string"!=typeof r||0===r.length||"unknown-caller"===r)return Yi("caller_context_missing","A session-callable op needs the calling session's engine-resolved durable id.");let o=await t.load(i);if("kind"in o)return{result:o};let{descriptor:a}=o,d=a.sessionCallable?.find(e=>e.op===n.op);if(void 0===d)return Yi("extension_unknown_op",`Extension ${i} declares no session-callable op ${n.op}.`);let u=n.args;if("object"!=typeof u||null===u||Array.isArray(u))return Yi("invalid_arguments","Session op arguments must be an object.");let l=cn.find(e=>Object.hasOwn(u,e));if(void 0!==l)return Yi("invalid_arguments",`${l} is stamped by the store from the engine's caller and cannot be passed.`);let _=d.op,p=vn(d)?d.await:void 0;if("op"===s){let e;try{e=_n(d.parameters,u)}catch(e){return Yi("invalid_arguments",`${i}.${d.op} declares parameters that cannot be checked: ${e instanceof Error?e.message:String(e)}`)}if(void 0!==e)return Yi("invalid_arguments",`Parameter validation failed at ${e.path||"/"}: ${e.message}`)}else{if("status"!==s&&"expire"!==s)return Yi("invalid_arguments",`Unknown session call phase ${String(s)}.`);{let e=u.await_request_id;if(void 0===p)return Yi("extension_unknown_op",`${i}.${d.op} declares no await.`);if("string"!=typeof e||!pn.test(e))return Yi("invalid_arguments",`await_request_id must match ${pn.source}.`);_="status"===s?p.statusOp:p.expireOp}}let m=void 0===d.targetArg?void 0:u[d.targetArg],{wakeDir:g}=a,f=vn(d)?d.wake:void 0,b="op"===s&&void 0!==f&&void 0!==g?[()=>function(e,t,n){let i=Ki(Ji(c(e)),t,n),r=`${i}.${process.pid}.${ji()}.tmp`;Bi(r,JSON.stringify({written_at:(new Date).toISOString()}),{mode:384});try{Gi(r,i)}finally{Pi(r,{force:!0})}}(e.config.agent_dir,g,f)]:[],E=await t.run({name:i,descriptor:a,module:o.module,op:_,args:()=>({..."op"===s?u:{await_request_id:u.await_request_id},caller_session_durable_id:r,..."op"===s&&"string"==typeof m&&Vi(e,r,m)?{caller_created_target:!0}:{}}),effects:b},n.now);return"op"===s&&void 0!==p&&void 0!==g?{result:E,await:{timeout_ms:p.timeoutMs,wake_dir:g}}:{result:E}}var Zi=a;if(null===Zi)throw Error("the gateway store worker must run as a worker thread");var Qi,er,tr,nr,ir=[],rr=new Map,sr=!1,or=1,ar=new Map,dr=(e,t)=>new Promise((n,i)=>{let r=or++;ar.set(r,{resolve:n,reject:i}),Zi.postMessage({type:"resolve",id:r,address:e,request:t})}),ur=new Map,lr=()=>new Promise((e,t)=>{let n=or++;ur.set(n,{resolve:e,reject:t}),Zi.postMessage({type:"provenance",id:n})});function _r(e){cr(e instanceof Ui?{kind:"extension_error",extension:e.extension,phase:"stale_transaction",error:e.message}:{kind:"extension_error",extension:nr??"worker",phase:"async",error:e instanceof Error?e.message:String(e)})}function cr(e){Zi?.postMessage({type:"event",event:e})}async function pr(a,u){if("init"===a)return await async function(a){let{config:u}=a,l=_(u.agent_dir);i(s(l,"inbox"),{recursive:!0,mode:448}),e(l,448);let p=c(u.agent_dir);t(r(p,"a",384)),e(p,384);let m=await(import("node:sqlite"));er=new m.DatabaseSync(p,{timeout:u.busy_timeout_ms});let g=new v(er);g.exec(`PRAGMA busy_timeout = ${Math.trunc(u.busy_timeout_ms)}`);let f=Date.now();for(;;)try{g.exec("PRAGMA journal_mode = WAL");break}catch(e){if(!w(e))throw e;let t=Date.now()-f;if(t+10>u.lock_wait_max_ms)throw cr({kind:"lock_wait_exceeded",op:"open",waited_ms:t}),d("open",t,u.lock_wait_max_ms);await o(10)}g.exec("PRAGMA synchronous = FULL");for(let t of["-wal","-shm"])n(`${p}${t}`)&&e(`${p}${t}`,384);let E={pid:process.pid,process_start_time:await b(process.pid),instance_id:u.instance_id,runtime_instance:u.runtime_instance};Qi={sql:g,config:u,self:E,stats:{writes:0,marker_unlinks:0,transactions:0},emit:cr,hook:mr,delay:e=>o(e)};try{await async function(e){if(!(Ge(e)>=ke.length))for(;;){let t=Ge(e);if(t>=ke.length)return;let n=Je.has(t),i=n?Number(e.sql.one(["foreign_keys"],"SELECT foreign_keys FROM pragma_foreign_keys")?.foreign_keys??1):1;n&&e.sql.exec("PRAGMA foreign_keys = OFF");try{await Me(e,"migrate",()=>{let i=Ge(e);if(i===t){for(let t of ke[i])e.sql.exec(t);if(n&&e.sql.all(["parent"],"SELECT parent FROM pragma_foreign_key_check").filter(e=>"bindings"===e.parent).length>0)throw new Be(i+1,`gateway schema ${i+1} would leave a foreign-key violation referencing bindings; staying at v${i}`);e.sql.exec(`PRAGMA user_version = ${i+1}`)}})}finally{n&&e.sql.exec("PRAGMA foreign_keys = "+(0===i?"OFF":"ON"))}}}(Qi),tr=new Fi(Qi,dr,lr);let e=await async function(e,t){let n=0;for(let i of e.config.legacy_mailbox_directories){let r,s=`legacy_mailbox:${i}`;if(void 0!==e.sql.one(["value"],"SELECT value FROM gateway_meta WHERE key = ?",[s]))continue;try{r=J(i)}catch(t){e.emit({kind:"legacy_mailbox_invalid",directory:i,error:t instanceof Error?t.message:String(t)});continue}if(null===r)continue;let o=dt(),a=r.filter(e=>!Re.test(e.target)).map(e=>({message_seq:e.message_seq,target:e.target,reason:"invalid_target"})),d=r.filter(e=>Re.test(e.target));n+=await Me(e,"migrate_legacy",()=>{let n=0;for(let r of d){let s=`legacy-${Pe([i,r.message_seq]).slice(0,32)}`;if(void 0!==Ie(e,s))continue;let a=`root-${L()}`,d=`legacy:${i}`;Ce(e,"INSERT INTO causal_roots (root_id, origin_principal, created_at, expires_at) VALUES (?, ?, ?, ?)",[a,d,t,t+M]);let u=Date.parse(r.accepted_at);je(e,{delivery_id:s,target_durable_id:r.target,seq:Fe(e,r.target),sender:d,sender_turn:null,envelope:{provenance:{workspace:"unclassified",project:"legacy-mailbox"},origin:{external:{platform:"legacy_mailbox",account_id:o,chat_id:i,thread_id:"@chat",message_id:r.operation_id}},actor:"legacy thread mailbox",via:[d],root_id:a,hop:1,delivery_id:s},body:r.message,bytes:Buffer.byteLength(r.message),mode_requested:r.delivery,mode_effective:null,expected_turn_id:r.expected_turn_id,state:"queued",reason:null,admitted_by:null,claimed_at:null,attempt:0,admission_kind:null,turn_epoch:null,root_id:a,hop:1,created_at:Number.isFinite(u)?u:t,updated_at:t,expires_at:t+D,binding_id:null,binding_revision:null,actor_user_id:null}),He(e,r.target,s,!0),n++}return Ce(e,"INSERT INTO gateway_meta (key, value) VALUES (?, ?)",[s,JSON.stringify({migrated_at:t,count:n,skipped:a})]),n}),a.length>0&&e.emit({kind:"legacy_mailbox_skipped",directory:i,items:a})}return n}(Qi,a.now);return Qi.stats.writes=0,Qi.stats.transactions=0,Qi.stats.marker_unlinks=0,{self:E,legacy_migrated:e}}catch(e){try{er.exec("ROLLBACK")}catch{}try{er.close()}finally{er=void 0,Qi=void 0,cr({kind:"store_closed"})}throw e}}(u);if("close"===a)return er?.close(),er=void 0,Qi=void 0,tr=void 0,null;let l=function(){if(void 0===Qi)throw Error("the gateway store is not open");return Qi}();switch(a){case"extension_register":{let e=u;return nr=e.extension.name,{result:await(tr?.register(e.extension,e.now,e.restored_at)),retained:!0===tr?.holds(e.extension)}}case"extension_call":case"extension_session_call":{let e=u;nr=e.name;try{if(void 0===tr)return;return"extension_call"===a?await tr.call(e.name,e.op,e.args,e.now):await zi(l,tr,u)}finally{for(let t of ar.values())t.reject(new Ui(e.name));ar.clear();for(let t of ur.values())t.reject(new Ui(e.name));ur.clear()}}case"session_callable_ops":return On(l);case"record_thread_creation":return await async function(e,t){await Me(e,"record_thread_creation",()=>{e.sql.run("INSERT OR IGNORE INTO thread_creations (creator_durable_id, created_durable_id, created_at) VALUES (?, ?, ?)",[t.creator_durable_id,t.created_durable_id,t.now])})}(l,u);case"enqueue":return await Ve(l,u);case"reconcile":return await nt(l,u);case"claim":return await async function(e,t){return await Me(e,"claim",()=>{let n=Ie(e,t.delivery_id);return void 0===n||"queued"!==n.state?{kind:"lost",state:n?.state??null}:n.expires_at<=t.now?(tt(e,n,"refused",t.now,{reason:"expired"}),We(e,n.target_durable_id,n.delivery_id),{kind:"lost",state:"refused"}):(Ce(e,"UPDATE deliveries SET state = 'admitting', admitted_by = ?, claimed_at = ?, attempt = attempt + 1, mode_effective = ?, updated_at = ? WHERE delivery_id = ? AND state = 'queued'",[JSON.stringify(t.self),t.now,t.lane,t.now,t.delivery_id]),We(e,n.target_durable_id,n.delivery_id),{kind:"claimed",row:Ie(e,t.delivery_id)})})}(l,u);case"record_outcome":return await async function(e,t){return await Me(e,"record_outcome",()=>{let n=Ie(e,t.delivery_id);if(void 0===n||"admitting"!==n.state&&"admitted"!==n.state||null===n.admitted_by||!h(n.admitted_by,t.self))return{kind:"lost",state:n?.state??null};let i=t.outcome;return"requeue"===i.kind?tt(e,n,"queued",t.now):"refused"===i.kind?tt(e,n,"refused",t.now,{reason:i.reason}):(Ce(e,"UPDATE deliveries SET admission_kind = ?, turn_epoch = ?, updated_at = ? WHERE delivery_id = ?",[i.admission_kind,i.turn_epoch,t.now,n.delivery_id]),n.state!==i.kind&&tt(e,n,i.kind,t.now)),{kind:"claimed",row:Ie(e,t.delivery_id)}})}(l,u);case"refuse_queued":return await async function(e,t){return await Me(e,"refuse",()=>{let n=Ie(e,t.delivery_id);return void 0!==n&&"queued"===n.state&&(tt(e,n,"refused",t.now,{reason:t.reason}),We(e,n.target_durable_id,n.delivery_id),!0)})}(l,u);case"complete_receipt":return await it(l,u);case"abandon_receipt":return await rt(l,u);case"delivery_view":return at(l,u);case"delivery_receipt":return st(l,u);case"recover_delivery":return await ot(l,u);case"list":return function(e,t){return void 0!==t.target_durable_id?qe(e,"target_durable_id = ?",[t.target_durable_id],"seq"):void 0!==t.root_id?qe(e,"root_id = ?",[t.root_id],"created_at, seq"):qe(e,"1 = 1",[],"created_at, seq")}(l,u);case"is_referenced":return function(e,t){return Number(e.sql.one(["n"],`SELECT COUNT(*) AS n FROM deliveries WHERE target_durable_id = ? AND state IN ${xe}`,[t])?.n??0)>0||Number(e.sql.one(["n"],"SELECT COUNT(*) AS n FROM bindings WHERE session_durable_id = ? AND status = 'active'",[t])?.n??0)>0||Xe(e,t).length>0}(l,u);case"journal_mode":return function(e){return String(e.sql.one(["journal_mode"],"SELECT journal_mode FROM pragma_journal_mode()")?.journal_mode??"")}(l);case"stats":return function(e){return{...e.stats}}(l);case"tool_receipt_begin":return await qt(l,u);case"tool_receipt_settle":return await async function(e,t){return await Me(e,"tool_receipt_settle",()=>{let n="result"in t;return 1===Ce(e,`UPDATE receipts SET status = ?, ${n?"result":"error_note"} = ?, updated_at = ? WHERE principal = ? AND operation = ? AND idempotency_key = ? AND status = 'prepared' AND owner_instance = ?`,[n?"completed":"uncertain",n?JSON.stringify(t.result):t.error_note,t.now,t.principal,t.operation,t.idempotency_key,e.config.instance_id])})}(l,u);case"bind":return await It(l,u);case"unbind":return await $t(l,u);case"rebind":return await Ut(l,u);case"list_bindings":return await Dt(l,u);case"binding_view":return await Mt(l,u);case"register_incarnation":return await async function(e,t){await Me(e,"register_incarnation",()=>{Ce(e,"INSERT INTO session_meta (durable_id, next_seq, incarnation, endpoint_socket, endpoint_kind)\n VALUES (?, (SELECT COALESCE(MAX(seq), 0) + 1 FROM deliveries WHERE target_durable_id = ?), ?, ?, ?)\n ON CONFLICT(durable_id) DO UPDATE SET incarnation = excluded.incarnation,\n endpoint_socket = excluded.endpoint_socket, endpoint_kind = excluded.endpoint_kind",[t.durable_id,t.durable_id,t.incarnation,t.endpoint?.socket??null,t.endpoint?.kind??null])})}(l,u);case"clear_endpoint":return await async function(e,t){await Me(e,"clear_endpoint",()=>{Ce(e,"UPDATE session_meta SET endpoint_socket = NULL, endpoint_kind = NULL WHERE durable_id = ? AND incarnation = ?",[t.durable_id,t.incarnation])})}(l,u);case"session_owner":return function(e,t){let n=e.sql.one(["incarnation","endpoint_socket","endpoint_kind"],"SELECT incarnation, endpoint_socket, endpoint_kind FROM session_meta WHERE durable_id = ?",[t]);return void 0===n||"string"!=typeof n.incarnation?null:{incarnation:n.incarnation,endpoint:"string"!=typeof n.endpoint_socket||"tui"!==n.endpoint_kind&&"rpc_host"!==n.endpoint_kind?null:{socket:n.endpoint_socket,kind:n.endpoint_kind}}}(l,u);case"report":return await Xt(l,u);case"emit_completions":return await Ft(l,u);case"pending_completion_arms":return function(e,t){return Number(e.sql.one(["n"],"SELECT COUNT(*) AS n FROM completion_arms WHERE session_durable_id = ?",[t])?.n??0)}(l,u);case"latest_completion_arm":return function(e,t){let n=e.sql.one(["s"],"SELECT MAX(arm_seq) AS s FROM completion_arms WHERE session_durable_id = ?",[t])?.s;return null==n?null:Number(n)}(l,u);case"read_outbox":return await Pt(l,u);case"ack_outbox":return await Gt(l,u);case"claim_answer":return await Jt(l,u);case"release_answer":return await Yt(l,u);case"confirm_answer":return await zt(l,u);case"mark_prior_delivered":return await Vt(l,u);case"close_question":return await async function(e,t){return await Me(e,"close_question",()=>{let n=e.sql.all(["cursor","binding_id"],"SELECT cursor, binding_id FROM outbox WHERE event_kind = 'question' AND session_durable_id = ? AND ui_request_id = ? AND (question_state = 'pending' OR (question_state = 'answered' AND answer_state = 'in_flight'))",[t.session_durable_id,t.ui_request_id],"cursor");for(let i of n)Ce(e,"UPDATE outbox SET question_state = 'answered', answer_state = 'delivered', answer = NULL, answered_at = ?, answered_by = NULL WHERE cursor = ? AND (question_state = 'pending' OR (question_state = 'answered' AND answer_state = 'in_flight'))",[t.now,Number(i.cursor)]),wt(e,String(i.binding_id),Number(i.cursor),t.now);return n.length})}(l,u);default:throw Error(`unknown gateway store op: ${a}`)}}async function mr(e){let t=Qi?.config.test_hooks[e];if(void 0===t)return;if("throw"===t)throw Error(`gateway test hook ${e}`);"sigkill"===t&&(process.kill(process.pid,"SIGKILL"),await new Promise(()=>{}));let n=new Promise(t=>rr.set(e,t));cr({kind:"paused",hook:e}),await n}process.on("uncaughtException",_r),process.on("unhandledRejection",_r),Zi.on("message",e=>{if("provenance_resolved"===e.type){let t=ur.get(e.id);return ur.delete(e.id),void(e.ok?t?.resolve(e.value):t?.reject(Error(e.error)))}if("resolution"===e.type){let t=ar.get(e.id);return ar.delete(e.id),void(e.ok?t?.resolve(e.value):t?.reject(Error(e.error)))}if("resume"===e.type)return rr.get(e.hook)?.(),void rr.delete(e.hook);ir.push(e),async function(){if(sr)return;sr=!0;try{for(let e=ir.shift();void 0!==e;e=ir.shift())try{let t=await pr(e.op,e.args);Zi?.postMessage({type:"response",id:e.id,ok:!0,value:t})}catch(t){Zi?.postMessage({type:"response",id:e.id,ok:!1,error:{message:t instanceof Error?t.message:String(t),stack:t instanceof Error?t.stack:void 0,code:"string"==typeof t?.code?t.code:void 0}})}}finally{sr=!1}}()});