omo-ai 5.1.44 → 5.1.45

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 (130) hide show
  1. package/bin/lib/bun-bin-shim.js +53 -72
  2. package/bin/lib/doctor.js +2 -2
  3. package/bin/lib/dori.js +187 -0
  4. package/bin/lib/launcher.js +7 -6
  5. package/bin/lib/provider-map.json +1 -1
  6. package/bin/lib/service-auth.generated.js +4 -4
  7. package/bin/omo.js +3 -4
  8. package/bin/senpi-patch.mjs +3 -4
  9. package/package.json +2 -2
  10. package/plugin/CHANGELOG.md +155 -7
  11. package/plugin/extensions/dream-persona.md +1 -1
  12. package/plugin/extensions/gateway-rules-extension.mjs +1 -1
  13. package/plugin/extensions/gateway-store-worker.mjs +2 -2
  14. package/plugin/extensions/memory-run-supervisor.mjs +1 -1
  15. package/plugin/extensions/omo-claim-receipt.js +2 -2
  16. package/plugin/extensions/omo-computer-use.js +2 -2
  17. package/plugin/extensions/omo-device-account.js +2 -0
  18. package/plugin/extensions/omo-dori-migration.js +2 -0
  19. package/plugin/extensions/omo-feedback.js +2 -2
  20. package/plugin/extensions/omo-init-deep-advisor.js +2 -2
  21. package/plugin/extensions/omo-member.js +2 -2
  22. package/plugin/extensions/omo-memory-commands.js +11 -0
  23. package/plugin/extensions/omo-memory-doctor.js +3 -3
  24. package/plugin/extensions/omo-memory-memfs.js +3 -3
  25. package/plugin/extensions/omo-memory-palace.js +3 -3
  26. package/plugin/extensions/omo-memory-sync.js +2 -2
  27. package/plugin/extensions/omo-onboarding-scan.js +3 -3
  28. package/plugin/extensions/omo-recall-store.js +1 -1
  29. package/plugin/extensions/omo-session-history.js +2 -2
  30. package/plugin/extensions/omo-side-panel.js +3 -3
  31. package/plugin/extensions/omo-task.js +2 -2
  32. package/plugin/extensions/omo-telemetry-posthog.js +2 -2
  33. package/plugin/extensions/omo-telemetry-recovery.js +2 -0
  34. package/plugin/extensions/omo-thread-client.js +2 -2
  35. package/plugin/extensions/omo.js +3 -3
  36. package/plugin/extensions/reflection-persona.md +1 -1
  37. package/plugin/package.json +9 -2
  38. package/plugin/runtime/agent-toolkit-sdk/sdk.js +2 -2
  39. package/plugin/runtime/ast-grep-mcp/cli.js +6 -6
  40. package/plugin/runtime/ast-grep-mcp/manifest.json +2 -2
  41. package/plugin/runtime/category-coverage/index.js +39 -75
  42. package/plugin/runtime/dori/layer2.js +2 -0
  43. package/plugin/runtime/dori/replay.js +2 -0
  44. package/plugin/runtime/lsp-daemon/dist/.omo-runtime-manifest.json +4 -4
  45. package/plugin/runtime/lsp-daemon/dist/cli.js +4 -4
  46. package/plugin/runtime/lsp-daemon/dist/client.js +4 -4
  47. package/plugin/runtime/lsp-daemon/dist/index.js +4 -4
  48. package/plugin/runtime/rollback-migrate.js +2 -2
  49. package/plugin/runtime/task-config/index.js +1 -1
  50. package/plugin/runtime/thread-sdk/sdk.js +2 -2
  51. package/plugin/scripts/install.mjs +5 -2
  52. package/plugin/skills/browser/SKILL.md +21 -22
  53. package/plugin/skills/browser/references/commands.md +2 -9
  54. package/plugin/skills/browser/references/install.md +1 -2
  55. package/plugin/skills/browser/runtime/omowright/manifest.json +1 -1
  56. package/plugin/skills/browser/scripts/browser-doctor.mjs +2 -2
  57. package/plugin/skills/browser/scripts/browser-engine-guard.mjs +63 -487
  58. package/plugin/skills/browser/scripts/browser-install.mjs +1 -1
  59. package/plugin/skills/browser/scripts/omowright.mjs +1 -10
  60. package/plugin/skills/frontend/SKILL.md +79 -118
  61. package/plugin/skills/frontend/references/design/README.md +75 -221
  62. package/plugin/skills/frontend/references/design/stylegallery.md +32 -27
  63. package/plugin/skills/frontend/references/perfection/README.md +2 -2
  64. package/plugin/skills/frontend/scripts/perfection/check-accent-stripes.ts +8 -24
  65. package/plugin/skills/frontend/scripts/perfection/check-draft-guard.ts +40 -0
  66. package/plugin/skills/frontend/scripts/perfection/collect-files.ts +53 -0
  67. package/plugin/skills/frontend/scripts/perfection/draft-guard/findings.ts +16 -0
  68. package/plugin/skills/frontend/scripts/perfection/draft-guard/lint.ts +38 -0
  69. package/plugin/skills/frontend/scripts/perfection/draft-guard/rules.ts +69 -0
  70. package/plugin/skills/frontend/scripts/perfection/draft-guard/text-nodes.ts +121 -0
  71. package/plugin/skills/frontend/scripts/perfection/fixtures/draft-guard/negative/attr-lookalikes.tsx +10 -0
  72. package/plugin/skills/frontend/scripts/perfection/fixtures/draft-guard/negative/bound-values.tsx +12 -0
  73. package/plugin/skills/frontend/scripts/perfection/fixtures/draft-guard/negative/const-generics.tsx +3 -0
  74. package/plugin/skills/frontend/scripts/perfection/fixtures/draft-guard/negative/generics.tsx +7 -0
  75. package/plugin/skills/frontend/scripts/perfection/fixtures/draft-guard/negative/measured-stats.html +6 -0
  76. package/plugin/skills/frontend/scripts/perfection/fixtures/draft-guard/negative/plain-copy.html +9 -0
  77. package/plugin/skills/frontend/scripts/perfection/fixtures/draft-guard/negative/state-copy.html +11 -0
  78. package/plugin/skills/frontend/scripts/perfection/fixtures/draft-guard/positive/attribute-edges.html +7 -0
  79. package/plugin/skills/frontend/scripts/perfection/fixtures/draft-guard/positive/components.tsx +16 -0
  80. package/plugin/skills/frontend/scripts/perfection/fixtures/draft-guard/positive/decorative-badge.vue +7 -0
  81. package/plugin/skills/frontend/scripts/perfection/fixtures/draft-guard/positive/emoji-icons.tsx +9 -0
  82. package/plugin/skills/frontend/scripts/perfection/fixtures/draft-guard/positive/jsx-edges.tsx +1 -0
  83. package/plugin/skills/frontend/scripts/perfection/fixtures/draft-guard/positive/promo-copy.html +6 -0
  84. package/plugin/skills/frontend/scripts/perfection/fixtures/draft-guard/positive/promo-copy.tsx +8 -0
  85. package/plugin/skills/frontend/scripts/perfection/fixtures/draft-guard/positive/vanity-stats.html +5 -0
  86. package/plugin/skills/programming/SKILL.md +10 -7
  87. package/plugin/skills/programming/references/typescript/README.md +10 -7
  88. package/plugin/skills/programming/references/typescript/bootstrap.md +9 -23
  89. package/plugin/skills/programming/references/typescript/oxc-lint.md +130 -0
  90. package/plugin/skills/programming/references/typescript/tsconfig-strict.md +6 -62
  91. package/plugin/skills/programming/scripts/typescript/check-no-excuse-rules.ts +12 -12
  92. package/plugin/skills/programming/scripts/typescript/new-project.ts +20 -81
  93. package/plugin/skills/programming/scripts/typescript/oxc/.oxfmtrc.json +9 -0
  94. package/plugin/skills/programming/scripts/typescript/oxc/.oxlintrc.json +46 -0
  95. package/plugin/skills/programming/scripts/typescript/oxc/lint/oxlint-plugin/LICENSE +21 -0
  96. package/plugin/skills/programming/scripts/typescript/oxc/lint/oxlint-plugin/index.js +10 -0
  97. package/plugin/skills/programming/scripts/typescript/oxc/lint/oxlint-plugin/no-em-dash-copy.js +28 -0
  98. package/plugin/skills/programming/scripts/typescript/oxc/lint/oxlint-plugin/require-suppression-reason.js +62 -0
  99. package/plugin/skills/programming/scripts/typescript/oxc/tsconfig.json +29 -0
  100. package/plugin/skills/refactor/SKILL.md +13 -13
  101. package/plugin/skills/ulw-execute/SKILL.md +1 -1
  102. package/plugin/skills/ulw-research/SKILL.md +1 -1
  103. package/plugin/skills/ulw-research/references/deliverable-phase.md +7 -6
  104. package/plugin/skills/ulw-research/references/fact-ledger-grammar.md +116 -0
  105. package/plugin/skills/ulw-research/references/report-gates.md +51 -3
  106. package/plugin/skills/ulw-research/scripts/claims-index.mjs +125 -0
  107. package/plugin/skills/ulw-research/scripts/contracts.mjs +68 -3
  108. package/plugin/skills/ulw-research/scripts/fact-ledger-kinds.mjs +136 -0
  109. package/plugin/skills/ulw-research/scripts/fact-ledger-schema.mjs +204 -0
  110. package/plugin/skills/ulw-research/scripts/fact-ledger.mjs +103 -0
  111. package/plugin/skills/ulw-research/scripts/fidelity-brief.mjs +145 -0
  112. package/plugin/skills/ulw-research/scripts/fidelity-state.mjs +63 -0
  113. package/plugin/skills/ulw-research/scripts/gates-static.mjs +1 -1
  114. package/plugin/skills/ulw-research/scripts/gates-structure.mjs +1 -1
  115. package/plugin/skills/ulw-research/scripts/gates-text.mjs +1 -27
  116. package/plugin/skills/ulw-research/scripts/lexicon.mjs +47 -0
  117. package/plugin/skills/ulw-research/scripts/numerals.mjs +226 -0
  118. package/plugin/skills/ulw-research/scripts/outcome.mjs +2 -3
  119. package/plugin/skills/ulw-research/scripts/particles-ko.mjs +108 -0
  120. package/plugin/skills/ulw-research/scripts/rational.mjs +139 -0
  121. package/plugin/skills/ulw-research/scripts/report-tools-commands.mjs +2 -2
  122. package/plugin/skills/ulw-research/scripts/sentence-split.mjs +77 -0
  123. package/plugin/skills/ulw-research/scripts/text-normalize.mjs +82 -0
  124. package/plugin/skills/ulw-research/scripts/text-similarity.mjs +28 -0
  125. package/plugin/skills/ulw-research/scripts/units.mjs +105 -0
  126. package/plugin/skills/visual-qa/SKILL.md +70 -63
  127. package/plugin/skills/visualize/SKILL.md +1 -1
  128. package/plugin/telemetry-schema.json +3857 -0
  129. package/plugin/telemetry-schema.omo-cloud.json +3850 -0
  130. package/bin/lib/gateway.js +0 -166
@@ -1,2 +1,2 @@
1
- // omo:T1TG4E4G1BqsUkRQfufdvehS2rr5hDbub0U_IZXfFYs:seTg07_ixK2ZBs7D8IU0hmPynnUB4xBhI7gMmDFMUdc
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 _}from"node:path";function l(e){return _(e,"gateway")}function c(e,t){return _(l(e),"inbox",t)}import{execFile as p}from"node:child_process";var g="epoch:",m=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function b(e){return new Promise(t=>{p("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=m.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 f(e,t){return e.pid===t.pid&&e.process_start_time===t.process_start_time&&e.instance_id===t.instance_id}function*h(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 y{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 h(e))n+="parameter"===i.kind?`gw_p(${t++})`:i.text;return n}function v(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 w,randomUUID as N}from"node:crypto";import{closeSync as L,constants as k,mkdirSync as R,openSync as x,readdirSync as S,readFileSync as O,rmSync as A,writeSync as q}from"node:fs";import{userInfo as C}from"node:os";import{join as I}from"node:path";function U(e,t,n){return t===n||function(e,t,n){let i=new Map;for(let t of e){let e=i.get(t.from);void 0===e?i.set(t.from,[t.to]):e.push(t.to)}let r=new Set([t]),s=[t];for(;s.length>0;){let e=s.pop();if(e===n)return!0;for(let t of i.get(e)??[])r.has(t)||(r.add(t),s.push(t))}return!1}(e,n,t)}var D=5e3,M=864e5,$=6048e5,H=1048576,W=2592e6,X=2592e6,F=256,P="session_released";import{existsSync as j,readFileSync as B}from"node:fs";import{join as G}from"node:path";function J(e){let t=G(e,"mailbox.jsonl");if(j(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()])}(B(t,"utf8"));let n=G(e,"mailbox.json");if(!j(n))return null;let i=JSON.parse(B(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 Q,createHmac as Z,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 _e(e,t){return null==t?null:ue(e,t)}function le(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 ge(e,t){return pe(JSON.stringify({v:1,as_of:e,after:t}))}var me="rt1";function be(e,t){return Z("sha256",e).update(`${me}.${t}`).digest().subarray(0,16).toString("base64url")}var Ee=new WeakMap;function fe(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<(Ee.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 ${Re}) LIMIT ?)`,[ae(t-oe),i]),_=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]),l=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:_,session_meta:l}}(e,t,Math.max(F-n,0)),r=i.receipts+n>=F||Object.values(i).some(e=>e>=F);return Ee.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"]);function Te(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 ve={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=ve[e.reason??""]??{code:"internal_error",next:"Call thread_list and check the target."};return{kind:"error",error:Te(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:Te("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)}}}class Ne 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 Le=[["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)"]],ke=["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"],Re="('queued', 'admitting', 'admitted')",xe=/^[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 Oe(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 Ae(e,t,n,i){return e.sql.all(ke,`SELECT ${ke.join(", ")} FROM deliveries WHERE ${t}`,n,i).map(Oe)}function qe(e,t){return Ae(e,"delivery_id = ?",[t])[0]}function Ce(e,t,n=[]){let i=e.sql.run(t,n);return e.stats.writes+=i,i}function Ie(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 ${Re} 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(!v(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 $e(e,t,n,i){let r=c(e.config.agent_dir,t);R(r,{recursive:!0,mode:448});let s,o=I(r,n);try{s=x(o,k.O_CREAT|k.O_EXCL|k.O_WRONLY,384)}catch(e){if(i&&e instanceof Error&&"code"in e&&"EEXIST"===e.code)return o;throw e}try{q(s,JSON.stringify({pid:e.self.pid,process_start_time:e.self.process_start_time}))}finally{L(s)}return e.afterRollback?.push(()=>A(o,{force:!0})),o}function He(e,t,n){if(void 0!==e.afterCommit)return void e.afterCommit.push(()=>He({...e,afterCommit:void 0},t,n));let i=I(c(e.config.agent_dir,t),n);try{A(i),e.stats.marker_unlinks++}catch(e){if(!(e instanceof Error&&"code"in e&&"ENOENT"===e.code))throw e}}function We(e,t){try{return S(c(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 Xe(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 Fe(e,t){Ce(e,`INSERT INTO deliveries (${ke.join(", ")}) VALUES (${ke.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 w("sha256").update(JSON.stringify(e)).digest("hex")}function je(e){let t=Number(e.sql.one(["user_version"],"SELECT user_version FROM pragma_user_version()")?.user_version??0);if(t>Le.length)throw new Ne(t,Le.length);return t}class Be extends Error{version;code="gateway_migration_failed";constructor(e,t){super(t),this.version=e,this.name="GatewayMigrationError"}}var Ge=new Set([6]);function Je(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 Ke(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:qe(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,Ie(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 Ye(e,t){if(!xe.test(t.target_durable_id)||!xe.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 n=null,i=!1,r=e.afterCommit?.length??0,s=void 0===e.afterCommit?"COMMIT":"RELEASE gateway_enqueue";try{let r=fe(e,{principal:t.sender_principal,operation:"deliver",idempotency_key:t.receipt.idempotency_key},t.now),o=Je(e,t.sender_principal,t.receipt.idempotency_key);if(void 0!==o){let n=Ke(e,t,o);return e.sql.exec(s),i=!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 ${Re}`,[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 _=function(e,t){let n;if(null!==t.cause_delivery_id){let i=qe(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:[...i.envelope.via,t.sender_node],new_root:!1}}else n={root_id:`root-${N()}`,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(!n.new_root){let i=e.sql.one(["expires_at"],"SELECT expires_at FROM causal_roots WHERE root_id = ?",[n.root_id]);if(void 0===i||Number(i.expires_at)<=t.now)return Se("loop_detected","This causal chain is older than its lifetime.",{guard:"root_expired",root_id:n.root_id})}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.hop>4)return Se("loop_detected",`This delivery would be hop ${n.hop}; at most 4 are allowed.`,{guard:"hop_limit",hop:n.hop});let i=Number(e.sql.one(["n"],"SELECT COUNT(*) AS n FROM deliveries WHERE root_id = ? AND state != 'refused'",[n.root_id])?.n??0);return i>=64?Se("loop_detected",`This causal chain already carried ${i} deliveries.`,{guard:"causal_budget",root_id:n.root_id}):U(e.sql.all(["from_durable_id","to_durable_id"],"SELECT from_durable_id, to_durable_id FROM causal_edges WHERE root_id = ?",[n.root_id]).map(e=>({from:String(e.from_durable_id),to:String(e.to_durable_id)})),t.sender_node,t.target_durable_id)?Se("loop_detected","The target already leads back to the sender in this causal chain.",{guard:"cycle",root_id:n.root_id}):n}(e,t);if("kind"in _)return De(e),_;let l=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))/D);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)*D)});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!==l)return De(e),l;_.new_root&&Ce(e,"INSERT INTO causal_roots (root_id, origin_principal, created_at, expires_at) VALUES (?, ?, ?, ?)",[_.root_id,t.sender_principal,t.now,t.now+$]),Ce(e,"INSERT OR IGNORE INTO causal_edges (root_id, from_durable_id, to_durable_id, delivery_id, created_at) VALUES (?, ?, ?, ?, ?)",[_.root_id,t.sender_node,t.target_durable_id,t.delivery_id,t.now]);let c={delivery_id:t.delivery_id,target_durable_id:t.target_durable_id,seq:Xe(e,t.target_durable_id),sender:t.sender_principal,sender_turn:t.sender_turn,envelope:{origin:t.origin,actor:t.actor,via:_.via,root_id:_.root_id,hop:_.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:_.root_id,hop:_.hop,created_at:t.now,updated_at:t.now,expires_at:Math.min(t.now+M,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};Fe(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]),n=$e(e,c.target_durable_id,c.delivery_id,!1);let p=Ie(e,c);return he(e,t.now,r),void 0===e.afterCommit&&await e.hook("beforeDbCommit"),e.sql.exec(s),i=!0,void 0===e.afterCommit&&await e.hook("afterDbCommit"),{kind:"inserted",row:c,queue_position:p}}catch(t){throw i||(De(e),void 0!==e.afterCommit&&(e.afterCommit.length=r),null!==n&&A(n,{force:!0})),t}}function Ve(e,t){if(null===e)return"";let n=t.get(e);if(void 0===n){try{n=O(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 Ve(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 Ze(e){return`${JSON.stringify(e.admitted_by)}#${e.attempt}`}function et(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 tt(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 Ve(e,t).split("\n")){if(!i.includes(P))continue;let e;try{e=JSON.parse(i)}catch{continue}let t=e;if("custom"!==t.type||t.customType!==P)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 Ae(e,"target_durable_id = ? AND state IN ('admitting', 'admitted')",[i])){if(null===n.admitted_by||f(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:Ze(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 Ae(e,`target_durable_id = ? AND state IN ${Re}`,[i],"seq")){let i=d.state;if("queued"!==d.state){if(null!==d.admitted_by&&f(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!==Ze(d)||"dual"===e.to){a.push(d.delivery_id);continue}i=e.to}i!==d.state&&(et(e,d,i,t.now),o.push({delivery_id:d.delivery_id,from:d.state,to:i}))}else d.expires_at<=t.now&&(et(e,d,"refused",t.now,{reason:"expired"}),o.push({delivery_id:d.delivery_id,from:d.state,to:"refused"}))}for(let t of We(e,i))"queued"!==e.sql.one(["state"],"SELECT state FROM deliveries WHERE delivery_id = ?",[t])?.state&&He(e,i,t);return{queued:Ae(e,"target_durable_id = ? AND state = 'queued'",[i],"seq"),transitions:o,dual_runtime:a}})}async function nt(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 it(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 rt(e,t){let n=Je(e,t.principal,t.idempotency_key);if(void 0===n||n.expires_at<=t.now||null===n.delivery_id)return null;let i=qe(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 st(e,t){return await Me(e,"recover_delivery",()=>{let n=Je(e,t.principal,t.idempotency_key);return void 0===n||n.expires_at<=t.now?null:Ke(e,{now:t.now,sender_principal:t.principal,endpoint_kind:null,receipt:{idempotency_key:t.idempotency_key,args_hash:t.args_hash}},n)})}function ot(e,t){let n=qe(e,t);return void 0===n?null:{row:n,queue_position:Ie(e,n)}}function at(){try{return C().username}catch{return"unknown"}}import{randomUUID as dt}from"node:crypto";import{renameSync as ut,writeFileSync as _t}from"node:fs";var lt=["question","select","confirm","input","editor"];var ct=new Map([["yes",!0],["y",!0],["true",!0],["no",!1],["n",!1],["false",!1]]);function pt(e){return""===e.replace(/[\s\p{Cf}]/gu,"")}function gt(e){let t=ct.get(e.trim().toLowerCase());return void 0===t?{value:e,answers:{},comment:e}:{value:e,answers:{},comment:e,confirmed:t}}function mt(e,t){switch(e){case null:return pt(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 pt(t)?{ok:!1,reason:"A select answer names one of its options; the text is blank."}:{ok:!0,fields:{value:t}};case"question":return pt(t)?{ok:!1,reason:"A question answer needs text; this one is blank."}:{ok:!0,fields:{answers:{},comment:t}};case"confirm":{let e=ct.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 ft(e,t,n){return{kind:"refused",code:e,message:t,...void 0===n?{}:{details:n}}}function ht(e){return null==e?null:String(e)}function yt(e){return null==e?null:JSON.stringify(e)}function Tt(e){return null==e?null:JSON.parse(String(e))}function vt(e,t,n,i){if(void 0!==e.afterCommit)return void e.afterCommit.push(()=>vt({...e,afterCommit:void 0},t,n,i));let r=(o=e.config.agent_dir,_(l(o),"outbox.marker")),s=`${r}.${process.pid}.${dt()}.tmp`;var o;_t(s,JSON.stringify({binding_id:t,cursor:n,written_at:ae(i)}),{mode:384}),ut(s,r)}function wt(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:ht(e.root_message_id),progress_message_id:ht(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:ht(e.expires_at)}}function Nt(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(wt)}function Lt(e,t){return Nt(e,"binding_id = ?",[t])[0]}function kt(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 Rt(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 xt(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:ht(n.result)}}async function Ot(e,t,n,i,r){return await Me(e,t,()=>{Rt(e,n);let t=null===i?0:fe(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?ft("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}:ft("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 At(e,t){return await Me(e,"tool_receipt_begin",()=>{let n=fe(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:ht(i?.error_note)}}(e,t);return he(e,t.now,n),i})}async function qt(e,t){let n=t.binding;return await Ot(e,"bind",t.now,t.receipt,()=>{let i=Nt(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 ft("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:kt(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 ${Re}`,[t],"seq").map(e=>String(e.delivery_id))}async function It(e,t){return await Ot(e,"unbind",t.now,t.receipt,()=>{let n=Lt(e,t.binding_id);if(void 0===n)return ft("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 ft("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:Lt(e,n.binding_id),already_closed:!1,in_flight:Ct(e,n.binding_id)}})}async function Ut(e,t){return await Ot(e,"rebind",t.now,t.receipt,()=>{let n=Lt(e,t.binding_id);if(void 0===n)return ft("not_found","No binding has this id.",{binding_id:t.binding_id});if("active"!==n.status)return ft("binding_inactive",`The binding is ${n.status}.`,{binding_id:n.binding_id,status:n.status});if(n.revision!==t.expected_revision)return ft("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 ft("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]),He(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:Lt(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 ft("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",()=>{Rt(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=Nt(e,s.join(" AND "),o,{orderBy:"created_at, binding_id",limit:i+1}),u=d.slice(0,i),_=u.at(-1);return{kind:"ok",bindings:u,next_cursor:d.length>i&&void 0!==_?ge(r,[_.created_at,_.binding_id]):null}})}async function Mt(e,t){return await Me(e,"binding_view",()=>(Rt(e,t.now),Lt(e,t.binding_id)??null))}function $t(e,t){return ht(e.sql.one(["incarnation"],"SELECT incarnation FROM session_meta WHERE durable_id = ?",[t])?.incarnation)}function Ht(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 vt(e,t.binding.binding_id,n,t.now),n}async function Wt(e,t){return await Ot(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=ht(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 ft("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 ft("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?ft("invalid_arguments","This session has no active outbound binding and its current run answers no bound message; name binding_id."):ft("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=Lt(e,i);if(void 0===r)return ft("not_found","No binding has this id.",{binding_id:i});if(r.session_durable_id!==t.session_durable_id)return ft("scope_denied","The binding is attached to another session.",{binding_id:i});if("active"!==r.status)return ft("binding_inactive",`The binding is ${r.status}.`,{binding_id:i,status:r.status});if(!r.direction.outbound)return ft("unsupported","The binding carries no outbound direction.",{binding_id:i,direction:r.direction});if(!r.outbound_events.includes(t.event))return ft("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 ft("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 ft("invalid_arguments","A question names the session's pending extension UI request (request_id).");let n=$t(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`${me}.${i}.${be(e,i)}`}(kt(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=Ht(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 xt(e,t.now),{kind:"ok",...s,cursor:a,reply_token:o,armed:!1,arm_seq:null}}let o=Ht(e,{binding:r,event:t.event,text:t.text,now:t.now});return xt(e,t.now),{kind:"ok",...s,cursor:o,reply_token:null,armed:!1,arm_seq:null}})}async function Xt(e,t){return await Me(e,"emit_completions",()=>{Rt(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=Lt(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:Ht(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 Ft(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",()=>{Rt(e,t.now),xt(e,t.now);let i=Lt(e,t.binding_id);if(void 0===i)return ft("not_found","No binding has this id.",{binding_id:t.binding_id});let r=Ft(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:ht(e.provider_message_id),reply_token:ht(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 jt(e,t){return await Me(e,"ack_outbox",()=>{Rt(e,t.now);let n=Lt(e,t.binding_id);if(void 0===n)return ft("not_found","No binding has this id.",{binding_id:t.binding_id});let i=Ft(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 ft("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 Gt(e,t){return await Me(e,"claim_answer",()=>{Rt(e,t.now);let n=function(e,t){let n=t.split(".");if(3!==n.length||n[0]!==me)return null;let i=Buffer.from(be(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}}(kt(e,"token_secret"),t.reply_token);if(null===n)return ft("invalid_arguments","This is not a reply token this gateway issued.");if(n.binding_id!==t.binding_id)return ft("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 ft("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 ft("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 ft("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)&&lt.includes(d)?i.ui_request_kind:null,a=mt(o,t.answer);var d;if(!a.ok)return ft("invalid_arguments",a.reason,{ui_request_kind:o});let u=Lt(e,n.binding_id);return void 0===u||"active"!==u.status||u.revision!==n.revision||u.session_durable_id!==n.session_durable_id||$t(e,n.session_durable_id)!==n.incarnation||ht(i.ui_request_id)!==n.ui_request_id?ft("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,yt(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:ht(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 Jt(e,t,n){let i=e.sql.one(["cursor","binding_id"],"SELECT cursor, binding_id FROM outbox WHERE reply_token = ?",[t]);void 0!==i&&vt(e,String(i.binding_id),Number(i.cursor),n)}async function Kt(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&&Jt(e,t.reply_token,t.claimed_at),n})}async function Yt(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,yt(t.prior.answered_by),t.reply_token,t.claimed_at]);return n&&Jt(e,t.reply_token,t.claimed_at),n})}async function Vt(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,yt(t.answered_by),t.reply_token]);return n&&Jt(e,t.reply_token,t.claimed_at),n})}import{extname as zt}from"node:path";var Qt=0,Zt=1,en=1,tn=2,nn=9,rn=10,sn=11,on=18,an=20,dn=21,un=23,_n=26,ln=27,cn=31,pn=33;class gn extends Error{code="extension_schema_violation"}var mn=["type","name","tbl_name","sql"],bn=e=>e.replace(/[A-Z]/g,e=>e.toLowerCase()),En=e=>`${String(e.type)}:${bn(String(e.name))}`;function fn(e){return{objects:e.all(mn,"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=>[En(e),null===e.owner?null:String(e.owner)]))}}function hn(e,t,n,i){let r=new Map(n.objects.map(e=>[En(e),e])),s=new Map(i.objects.map(e=>[En(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=bn(String(d.name));if(("index"!==d.type||null!==d.sql||!u.startsWith(`sqlite_autoindex_${bn(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:${bn(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),bn(String(o.name)),t])}}function yn(e,t,n){let i,r,s=fn(e),o=new Map(s.owners),a=new Set(s.objects.filter(e=>"trigger"===e.type||"view"===e.type).map(e=>bn(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),_=!1,l=Qt,c=e=>(r=`Extension ${t} does not own ${e??"this SQLite operation"}.`,Zt);try{return e.authorized((e,t,n,r,s)=>{let o=null===t?null:bn(t),p=null===n?null:bn(n),g=null===r?null:bn(r),m=null===s?null:bn(s);if(null!==m&&a.has(m))return c(m);switch(e){case tn:return i="create","main"===g&&u("table",o)?l:c(o);case en:return i="create","main"===g&&d("table",p)&&u("index",o,!0===o?.startsWith(`sqlite_autoindex_${p}_`))?l:c(o);case sn:return i="drop","main"===g&&d("table",o)?l:c(o);case rn:return i="drop","main"===g&&d("index",o)&&d("table",p)?l:c(o);case _n:return i="alter","main"===o&&d("table",p)?l:c(p);case ln:return"main"===g&&d("index",o)?l:c(o);case an:case on:case un:case nn:return"sqlite_master"===o||"sqlite_temp_master"===o?(e===un&&"sql"===p&&(_=!0),e!==an||"alter"===i||"drop"===i||"create"===i&&_&&"rowid"===p?l:c(o)):"alter"!==i||"sqlite_sequence"!==o||"name"!==p||e!==an&&e!==un?("main"===g||null===g&&e===an&&""===p)&&d("table",o)?l:c(o):l;case dn:case pn:return l;case cn:return"load_extension"===p?c(p):l;default:return c(o)}},n)}catch(e){if(void 0!==r)throw new gn(r);throw e}}import{createHash as Tn,randomUUID as vn}from"node:crypto";var wn={loop_detected:"Stop relaying here: a direct reply to the session that messaged you is a cycle. That session reads your answer with thread_read; a bound external thread gets it through thread_report, and its questions come back through thread_answer.",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 Nn(e,t,n){return{kind:"error",error:Te(e,t,wn[e]??"Call thread_list and retry after checking the target.",n)}}function Ln(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},Tn("sha256").update(JSON.stringify(t)).digest("hex");var t}function kn(e){let t=!1;for(let n of h(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 Rn=/^[ \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,xn=e=>JSON.stringify(e.length>80?`${e.slice(0,80)}…`:e),Sn=e=>e?.toUpperCase();var On=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;function An(e){return{kind:"refused",code:"invalid_arguments",message:e}}function qn(e,t,n){return"string"!=typeof t||0===t.trim().length?An(`author.${e} must be a non-empty string.`):t.length>n?An(`author.${e} is longer than ${n} characters.`):On.test(t)?An(`author.${e} carries a control character or line break.`):t.trim()}var Cn={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."},In=new Set(["question_already_resolved","unknown_extension_ui_request","unknown_request"]);function Un(e,t,n,i){return{kind:"error",error:Te(e,t,i??Cn[e]??"Call thread_bindings and retry after checking the binding.",n)}}function Dn(e){return"refused"===e.kind?Un(e.code,e.message,e.details):e}function Mn(e){if(void 0===e)return;let t=function(e){let t=qn("platform_user_id",e.platform_user_id,256);if("string"!=typeof t)return t;let n=qn("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=qn("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?Un("invalid_arguments",t.message):t}function $n(e){let t=Buffer.byteLength(e);return t>32768?Un("message_too_large",`The text is ${t} bytes, above the 32768-byte limit.`):void 0}function Hn(e,t,n){return void 0===e.idempotency_key?null:{principal:e.principal,operation:t,idempotency_key:e.idempotency_key,args_hash:(i=n,Q("sha256").update(ce(i)).digest("hex"))};var i}function Wn(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:_e("root_message_id",e.root_message_id),progress_message_id:_e("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(le(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 Dn("kind"in i?i:await t.bind({now:n(),receipt:Hn(e,"thread_bind",i),binding:i}))},unbind:async e=>{let i={binding_id:e.binding_id,expected_revision:e.expected_revision};return Dn(await t.unbind({now:n(),receipt:Hn(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 Dn(await t.rebind({now:n(),receipt:Hn(e,"thread_rebind",i),...i}))},bindings:async e=>Dn(await t.listBindings({now:n(),...e})),report:async e=>{let i=$n(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 Dn(await t.report({now:n(),receipt:Hn(e,"thread_report",r),...r}))},outbox:async e=>Dn(await t.readOutbox({now:n(),...e})),ack:async e=>Dn(await t.ackOutbox({now:n(),...e})),answer:async i=>{let r=$n(i.answer);if(void 0!==r)return r;let a=Mn(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 Dn(u);let _={reply_token:i.reply_token,claimed_at:u.claimed_at},l=e.endpoints.respondUi,c=null,p="";if(void 0!==l)try{c=await e.locate(u.session_durable_id)}catch(e){p=`: ${e instanceof Error?e.message:String(e)}`}if(void 0===l||null===c)return await s(_),Un(void 0===l?"unsupported":"host_unavailable",`The session that asked is not reachable to take the answer${p}.`,{session:u.session_durable_id});let g,m=mt(u.ui_request_kind,i.answer);if(!m.ok)return await s(_),Un("invalid_arguments",m.reason,{session:u.session_durable_id,ui_request_kind:u.ui_request_kind});try{g=await l(c,{ui_request_id:u.ui_request_id,fields:m.fields})}catch(e){return await s(_),Un("host_unavailable",`The answer could not be handed to the session: ${e instanceof Error?e.message:String(e)}`,{session:u.session_durable_id})}if(!g.delivered){let e=u.taken_over;if(null!==e&&In.has(g.error))return"question_already_resolved"===g.error?(await o(()=>t.markPriorDelivered({..._,prior:e})),Un("already_answered",`The session already took an earlier answer to this question (${g.error}).`,{session:u.session_durable_id,reason:g.error})):(await o(()=>t.markPriorDelivered({..._,prior:{answer:null,answered_at:_.claimed_at}})),Un("already_answered",`${Bt} (${g.error}).`,{session:u.session_durable_id,reason:g.error},"Nothing to do: the session no longer waits for this question."));await s(_);let n="invalid_response"===g.error||"question_incomplete"===g.error;return Un(n?"invalid_arguments":"stale_token",`The session refused the answer: ${g.error}`,{session:u.session_durable_id,reason:g.error},n?`The session could not read this answer (${g.error}); answer again with text it can take. The question stays pending.`:`The session refused the answer (${g.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))}({..._,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 Un("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=Mn(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 Un("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===Ln({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 Un(e.code,e.message,e.details)}if("active"!==s.status)return Un("binding_inactive",`The binding is ${s.status}.`,{binding_id:s.binding_id,status:s.status});if(!s.direction.inbound)return Un("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?Un("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 Xn extends Error{extension;code="extension_operation_failed";constructor(e){super(`The ${e} extension transaction has ended.`),this.extension=e}}class Fn 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}}function Pn(e,t,n,i){let r,s=!0,o=0,a=!1,d=Promise.resolve();function u(e){if(a)throw new Xn(t);if(void 0!==r)throw r;return e()}function _(e){if(!s)return Promise.reject(new Xn(t));o++;let n=d.then(()=>u(e));return d=n.then(()=>{o--},e=>{o--,r=e}),n}function l(n,i){if((()=>{if(!s)throw new Xn(t);if(void 0!==r)throw r})(),o>0)throw r=new Fn(t),r;let a=fn(e.sql);try{kn(n);let r=yn(e.sql,t,i);return hn(e.sql,t,a,fn(e.sql)),r}catch(e){throw r=e,e}}let c={now:()=>n,busyTimeoutMs:e.config.busy_timeout_ms,enqueue:t=>u(()=>Ye(e,t)),completeReceipt:t=>u(()=>nt(e,t)),abandonReceipt:t=>u(()=>it(e,t)),deliveryView:async t=>u(()=>ot(e,t)),deliveryReceipt:async t=>u(()=>rt(e,t)),recoverDelivery:t=>u(()=>st(e,t)),bind:t=>u(()=>qt(e,t)),unbind:t=>u(()=>It(e,t)),rebind:t=>u(()=>Ut(e,t)),listBindings:t=>u(()=>Dt(e,t)),bindingView:t=>u(()=>Mt(e,t)),report:t=>u(()=>Wt(e,t)),readOutbox:t=>u(()=>Pt(e,{...t,pendingOnly:!0})),ackOutbox:t=>u(()=>jt(e,t)),claimAnswer:t=>u(()=>Gt(e,t)),releaseAnswer:t=>u(()=>Kt(e,t)),confirmAnswer:t=>u(()=>Vt(e,t)),markPriorDelivered:t=>u(()=>Yt(e,t)),emitCompletions:t=>u(()=>Xt(e,t))},p={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 Nn("invalid_arguments","A steer needs expected_turn_id (the target's current turn_epoch).");let s=Buffer.byteLength(i.text);if(s>H)return Nn("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 Nn("turn_conflict","The target has no live turn to steer.",{target:a.durable_id});let u=function(e){if("session"===e.kind)return{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{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 t=`binding:${e.binding_id}`,n=e.origin.author;return{principal:t,rate_principal:void 0===n?t:`${t}#author:${n.platform_user_id}`,node:t,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),_=vn(),l=i.idempotency_key??`auto:${_}`,c=await t.enqueue({now:n(),delivery_id:_,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(_),actor:u.actor,body:i.text,mode:r,expected_turn_id:i.expected_turn_id??null,binding:u.binding,receipt:{idempotency_key:l,args_hash:Ln({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 Nn("overloaded","The gateway store is locked by a suspended writer; nothing was sent.",{budget:"store_lock"});if("refused"===c.kind)return Nn(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:l,result:e}),e);try{if(null===d)return await p(we(c.row,c.queue_position,null,!1,!0));let n=!0;try{await e.endpoints.wake(d,[_])}catch{n=!1}let i=await t.deliveryView(_);if(null===i)throw Error(`delivery ${_} vanished after commit`);return await p(we(i.row,i.queue_position,d.kind,!1,!n))}catch(e){throw await t.abandonReceipt({now:n(),principal:u.principal,idempotency_key:l,error_note:e instanceof Error?e.message:String(e)}).catch(()=>!1),e}}}}({store:c,endpoints:p,resolve:async(e,t)=>{let n=await i(e,t);return"error"===n.kind?n:{kind:"ok",target:{...n.target,endpoint:null,liveness:"dead"}}}}),m=Wn({store:c,engine:g,endpoints:p,locate:async()=>null});return{tx:{all:(t,n,i,r)=>l(n,()=>{for(let e of t)kn(e);if(void 0===r)return e.sql.all(t,n,i);let s=function(e){return e.split(",").map(t=>{let n=Rn.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 ${xn(e)}. Put LIMIT, OFFSET and table-qualified ordering in the statement itself.`);return{column:n[1],collate:Sn(n[2]),direction:Sn(n[3]),nulls:Sn(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=>bn(t)===bn(e.column));if(void 0===n)throw new gn(`orderBy must list the statement's output columns; ${xn(e.column)} is not one of them (${xn(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)=>l(n,()=>{for(let e of t)kn(e);return e.sql.one(t,n,i)}),exec:(t,n)=>l(t,()=>e.sql.run(t,n)),enqueue:e=>_(()=>m.inbound(e)),outboxAck:e=>_(()=>m.ack(e)),bind:e=>_(()=>m.bind(e)),unbind:e=>_(()=>m.unbind(e)),rebind:e=>_(()=>m.rebind(e)),bindingFor:t=>_(()=>async function(e,t){return await Me(e,"binding_for",()=>(Rt(e,t.now),Nt(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})),outboxPending:e=>_(()=>m.outbox(e))},cancel:()=>{s=!1,a=!0,m.dispose()},finish:async()=>{if(s=!1,await d,m.dispose(),void 0!==r)throw r}}}function jn(e,t){return{kind:"refused",code:e,message:t}}function Bn(e){let t=e instanceof Error?e.message:String(e);return e instanceof gn||e instanceof Ne?jn(e.code,t):u(e)?jn("gateway_lock_wait_exceeded",t):jn("extension_operation_failed",t)}class Gn{ctx;resolveTarget;registered=new Map;constructor(e,t){this.ctx=e,this.resolveTarget=t}async register(e,t){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 jn("invalid_arguments","An extension needs a valid namespace and an array of SQL migration steps.");try{!function(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=>bn(String(e.name)).startsWith(t)))throw new gn(`Extension name ${t} collides with a core namespace.`)}(this.ctx.sql,e.name)}catch(e){return Bn(e)}let n;try{let t=new URL(e.moduleUrl);if("file:"!==t.protocol||![".js",".mjs",".cjs"].includes(zt(t.pathname)))return jn("extension_import_failed","moduleUrl must name a compiled JavaScript file URL.");n=await(import(e.moduleUrl))}catch(t){return jn("extension_import_failed",`Cannot import extension ${e.name}: ${t instanceof Error?t.message:String(t)}`)}try{let i=await this.ensure(e,t);return this.registered.set(e.name,{descriptor:e,module:n}),{kind:"ok",value:{version:i}}}catch(t){return t instanceof Ne||this.registered.set(e.name,{descriptor:e,module:n}),Bn(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 Ne(r,i.length,`Extension ${n}`);let s=fn(this.ctx.sql);if(void 0===e&&s.objects.some(e=>bn(String(e.name)).startsWith(`${n}_`)&&null==s.owners.get(`${String(e.type)}:${bn(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]){kn(e);let t=fn(this.ctx.sql);yn(this.ctx.sql,n,()=>this.ctx.sql.exec(e)),hn(this.ctx.sql,n,t,fn(this.ctx.sql))}return hn(this.ctx.sql,n,s,fn(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);if(void 0===r)return jn("extension_unknown_name",`No store extension is registered as ${e}.`);let s=Object.hasOwn(r.module,t)?r.module[t]:void 0;if("function"!=typeof s)return jn("extension_unknown_op",`Extension ${e} exports no operation ${t}.`);let o,a=[],d=[];try{let u=await this.ensure(r.descriptor,i);o=await Me(this.ctx,"extension_call",async()=>{let o=this.ctx.sql.one(["version"],"SELECT version FROM extension_schema WHERE name = ?",[e]),_=Number(o?.version??0);if(_!==u)throw new Ne(_,r.descriptor.migrations.length,`Extension ${e}`);let l,c=fn(this.ctx.sql),p=Pn({...this.ctx,afterCommit:a,afterRollback:d},e,i,this.resolveTarget);try{let i=async()=>{try{return await s(p.tx,n)}finally{await p.finish()}},r=new Promise((n,i)=>{l=setTimeout(()=>{p.cancel(),i(Error(`Extension ${e}.${t} exceeded its ${this.ctx.config.lock_wait_max_ms} ms operation budget.`))},this.ctx.config.lock_wait_max_ms)}),o=await Promise.race([i(),r]);return hn(this.ctx.sql,e,c,fn(this.ctx.sql)),structuredClone(o)}finally{clearTimeout(l),p.cancel()}})}catch(t){for(let t of d)try{t()}catch(t){this.ctx.emit({kind:"extension_error",extension:e,phase:"after_rollback",error:t instanceof Error?t.message:String(t)})}return Bn(t)}await this.ctx.hook("afterDbCommit");for(let t of a)try{t()}catch(t){this.ctx.emit({kind:"extension_error",extension:e,phase:"after_commit",error:t instanceof Error?t.message:String(t)})}return{kind:"ok",value:o}}}var Jn=a;if(null===Jn)throw Error("the gateway store worker must run as a worker thread");var Kn,Yn,Vn,zn,Qn=[],Zn=new Map,ei=!1,ti=1,ni=new Map,ii=(e,t)=>new Promise((n,i)=>{let r=ti++;ni.set(r,{resolve:n,reject:i}),Jn.postMessage({type:"resolve",id:r,address:e,request:t})});function ri(e){si(e instanceof Xn?{kind:"extension_error",extension:e.extension,phase:"stale_transaction",error:e.message}:{kind:"extension_error",extension:zn??"worker",phase:"async",error:e instanceof Error?e.message:String(e)})}function si(e){Jn?.postMessage({type:"event",event:e})}async function oi(a,u){if("init"===a)return await async function(a){let{config:u}=a,c=l(u.agent_dir);i(s(c,"inbox"),{recursive:!0,mode:448}),e(c,448);let p=(g=u.agent_dir,_(l(g),"gateway.sqlite"));var g;t(r(p,"a",384)),e(p,384);let m=await(import("node:sqlite"));Yn=new m.DatabaseSync(p,{timeout:u.busy_timeout_ms});let E=new y(Yn);E.exec(`PRAGMA busy_timeout = ${Math.trunc(u.busy_timeout_ms)}`);let f=Date.now();for(;;)try{E.exec("PRAGMA journal_mode = WAL");break}catch(e){if(!v(e))throw e;let t=Date.now()-f;if(t+10>u.lock_wait_max_ms)throw si({kind:"lock_wait_exceeded",op:"open",waited_ms:t}),d("open",t,u.lock_wait_max_ms);await o(10)}E.exec("PRAGMA synchronous = FULL");for(let t of["-wal","-shm"])n(`${p}${t}`)&&e(`${p}${t}`,384);let h={pid:process.pid,process_start_time:await b(process.pid),instance_id:u.instance_id,runtime_instance:u.runtime_instance};Kn={sql:E,config:u,self:h,stats:{writes:0,marker_unlinks:0,transactions:0},emit:si,hook:ai,delay:e=>o(e)};try{await async function(e){if(!(je(e)>=Le.length))for(;;){let t=je(e);if(t>=Le.length)return;let n=Ge.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=je(e);if(i===t){for(let t of Le[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"))}}}(Kn),Vn=new Gn(Kn,ii);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=at(),a=r.filter(e=>!xe.test(e.target)).map(e=>({message_seq:e.message_seq,target:e.target,reason:"invalid_target"})),d=r.filter(e=>xe.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!==qe(e,s))continue;let a=`root-${N()}`,d=`legacy:${i}`;Ce(e,"INSERT INTO causal_roots (root_id, origin_principal, created_at, expires_at) VALUES (?, ?, ?, ?)",[a,d,t,t+$]);let u=Date.parse(r.accepted_at);Fe(e,{delivery_id:s,target_durable_id:r.target,seq:Xe(e,r.target),sender:d,sender_turn:null,envelope:{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+M,binding_id:null,binding_revision:null,actor_user_id:null}),$e(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}(Kn,a.now);return Kn.stats.writes=0,Kn.stats.transactions=0,Kn.stats.marker_unlinks=0,{self:h,legacy_migrated:e}}catch(e){try{Yn.exec("ROLLBACK")}catch{}try{Yn.close()}finally{Yn=void 0,Kn=void 0,si({kind:"store_closed"})}throw e}}(u);if("close"===a)return Yn?.close(),Yn=void 0,Kn=void 0,Vn=void 0,null;let c=function(){if(void 0===Kn)throw Error("the gateway store is not open");return Kn}();switch(a){case"extension_register":{let e=u;return zn=e.extension.name,{result:await(Vn?.register(e.extension,e.now)),retained:!0===Vn?.holds(e.extension)}}case"extension_call":{let e=u;zn=e.name;try{return await(Vn?.call(e.name,e.op,e.args,e.now))}finally{for(let t of ni.values())t.reject(new Xn(e.name));ni.clear()}}case"enqueue":return await Ye(c,u);case"reconcile":return await tt(c,u);case"claim":return await async function(e,t){return await Me(e,"claim",()=>{let n=qe(e,t.delivery_id);return void 0===n||"queued"!==n.state?{kind:"lost",state:n?.state??null}:n.expires_at<=t.now?(et(e,n,"refused",t.now,{reason:"expired"}),He(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]),He(e,n.target_durable_id,n.delivery_id),{kind:"claimed",row:qe(e,t.delivery_id)})})}(c,u);case"record_outcome":return await async function(e,t){return await Me(e,"record_outcome",()=>{let n=qe(e,t.delivery_id);if(void 0===n||"admitting"!==n.state&&"admitted"!==n.state||null===n.admitted_by||!f(n.admitted_by,t.self))return{kind:"lost",state:n?.state??null};let i=t.outcome;return"requeue"===i.kind?et(e,n,"queued",t.now):"refused"===i.kind?et(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&&et(e,n,i.kind,t.now)),{kind:"claimed",row:qe(e,t.delivery_id)}})}(c,u);case"refuse_queued":return await async function(e,t){return await Me(e,"refuse",()=>{let n=qe(e,t.delivery_id);return void 0!==n&&"queued"===n.state&&(et(e,n,"refused",t.now,{reason:t.reason}),He(e,n.target_durable_id,n.delivery_id),!0)})}(c,u);case"complete_receipt":return await nt(c,u);case"abandon_receipt":return await it(c,u);case"delivery_view":return ot(c,u);case"delivery_receipt":return rt(c,u);case"recover_delivery":return await st(c,u);case"list":return function(e,t){return void 0!==t.target_durable_id?Ae(e,"target_durable_id = ?",[t.target_durable_id],"seq"):void 0!==t.root_id?Ae(e,"root_id = ?",[t.root_id],"created_at, seq"):Ae(e,"1 = 1",[],"created_at, seq")}(c,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 ${Re}`,[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||We(e,t).length>0}(c,u);case"journal_mode":return function(e){return String(e.sql.one(["journal_mode"],"SELECT journal_mode FROM pragma_journal_mode()")?.journal_mode??"")}(c);case"stats":return function(e){return{...e.stats}}(c);case"tool_receipt_begin":return await At(c,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])})}(c,u);case"bind":return await qt(c,u);case"unbind":return await It(c,u);case"rebind":return await Ut(c,u);case"list_bindings":return await Dt(c,u);case"binding_view":return await Mt(c,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])})}(c,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])})}(c,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}}}(c,u);case"report":return await Wt(c,u);case"emit_completions":return await Xt(c,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)}(c,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)}(c,u);case"read_outbox":return await Pt(c,u);case"ack_outbox":return await jt(c,u);case"claim_answer":return await Gt(c,u);case"release_answer":return await Kt(c,u);case"confirm_answer":return await Vt(c,u);case"mark_prior_delivered":return await Yt(c,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)]),vt(e,String(i.binding_id),Number(i.cursor),t.now);return n.length})}(c,u);default:throw Error(`unknown gateway store op: ${a}`)}}async function ai(e){let t=Kn?.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=>Zn.set(e,t));si({kind:"paused",hook:e}),await n}process.on("uncaughtException",ri),process.on("unhandledRejection",ri),Jn.on("message",e=>{if("resolution"===e.type){let t=ni.get(e.id);return ni.delete(e.id),void(e.ok?t?.resolve(e.value):t?.reject(Error(e.error)))}if("resume"===e.type)return Zn.get(e.hook)?.(),void Zn.delete(e.hook);Qn.push(e),async function(){if(ei)return;ei=!0;try{for(let e=Qn.shift();void 0!==e;e=Qn.shift())try{let t=await oi(e.op,e.args);Jn?.postMessage({type:"response",id:e.id,ok:!0,value:t})}catch(t){Jn?.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{ei=!1}}()});
1
+ // omo:VciI9NqX2Ioj7MLVhsFcVqtAdsSwTHab6UHFh31Ohx4:3peSAwsEO0uWJmgboYiy-_IhpQgc1QkQZX9JuVpQKPY
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";function U(e,t,n){return t===n||function(e,t,n){let i=new Map;for(let t of e){let e=i.get(t.from);void 0===e?i.set(t.from,[t.to]):e.push(t.to)}let r=new Set([t]),s=[t];for(;s.length>0;){let e=s.pop();if(e===n)return!0;for(let t of i.get(e)??[])r.has(t)||(r.add(t),s.push(t))}return!1}(e,n,t)}var D=5e3,M=864e5,H=6048e5,W=1048576,F=2592e6,X=2592e6,j=256,P="session_released";import{existsSync as G,readFileSync as B}from"node:fs";import{join as J}from"node:path";function K(e){let t=J(e,"mailbox.jsonl");if(G(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=V(e);n.set(t.message_seq,t)}}else if("enqueue"===t.kind){let e=V(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 Y([...n.values()])}(B(t,"utf8"));let n=J(e,"mailbox.json");if(!G(n))return null;let i=JSON.parse(B(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(V(t))}return Y(r)}function Y(e){return e.toSorted((e,t)=>e.message_seq-t.message_seq)}function V(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:z(e.expected_turn_id),operation_id:e.operation_id,accepted_at:e.accepted_at}}function z(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 Q,createHmac as ee,randomUUID as te,timingSafeEqual as ne}from"node:crypto";var ie=["discord","telegram","slack","notion","feishu","herdr","custom","whatsapp"],re=["milestone","report","question","completion"],se=["auto","follow_up"],oe=31622400,ae=2592e6;function de(e){return new Date(e).toISOString()}function ue(e){return{kind:"refused",code:"invalid_arguments",message:e}}function le(e,t){return"string"!=typeof t||0===t.trim().length?ue(`${e} must be a non-empty string.`):t.length>256?ue(`${e} is longer than 256 characters.`):/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/.test(t)?ue(`${e} carries a control character or a line separator.`):t}function _e(e,t){return null==t?null:le(e,t)}function ce(e){return"object"==typeof e&&null!==e&&"refused"===e.kind}function pe(e){if(null===e||"object"!=typeof e)return JSON.stringify(e)??"null";if(Array.isArray(e))return`[${e.map(pe).join(",")}]`;let t=e;return`{${Object.keys(t).filter(e=>void 0!==t[e]).sort().map(e=>`${JSON.stringify(e)}:${pe(t[e])}`).join(",")}}`}function me(e){return Buffer.from(e).toString("base64url")}function ge(e,t){return me(JSON.stringify({v:1,as_of:e,after:t}))}var fe="rt1";function be(e,t){return ee("sha256",e).update(`${fe}.${t}`).digest().subarray(0,16).toString("base64url")}var Ee=new WeakMap;function he(e,t,n){return $e(e,"DELETE FROM receipts WHERE principal = ? AND operation = ? AND idempotency_key = ? AND expires_at <= ?",[t.principal,t.operation,t.idempotency_key,n])}function ye(e,t,n=0){if(t<(Ee.get(e.sql)??Number.NEGATIVE_INFINITY))return null;let i=function(e,t,n=256){let i=j,r=$e(e,"DELETE FROM receipts WHERE rowid IN (SELECT rowid FROM receipts WHERE expires_at <= ? LIMIT ?)",[t,n]),s=$e(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=$e(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=$e(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=$e(e,"DELETE FROM rate_buckets WHERE rowid IN (SELECT rowid FROM rate_buckets WHERE updated_at <= ? LIMIT ?)",[t-4e4,i]),u=$e(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 ${Re}) LIMIT ?)`,[de(t-ae),i]),l=$e(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]),_=$e(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(j-n,0)),r=i.receipts+n>=j||Object.values(i).some(e=>e>=j);return Ee.set(e.sql,r?t:t+36e5),i}var ve=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"]);function Te(e,t,n,i){if("string"!=typeof(r=e)||!ve.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 we={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 Ne(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=we[e.reason??""]??{code:"internal_error",next:"Call thread_list and check the target."};return{kind:"error",error:Te(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:Te("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 Le=["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 ke 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 Oe=[["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)"],Le,[...Le,"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)"],[...Le,"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)"]],xe=["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"],Re="('queued', 'admitting', 'admitted')",Se=/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/;function Ae(e,t,n){return{kind:"refused",code:e,message:t,...void 0===n?{}:{details:n}}}function qe(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 Ie(e,t,n,i){return e.sql.all(xe,`SELECT ${xe.join(", ")} FROM deliveries WHERE ${t}`,n,i).map(qe)}function Ce(e,t){return Ie(e,"delivery_id = ?",[t])[0]}function $e(e,t,n=[]){let i=e.sql.run(t,n);return e.stats.writes+=i,i}function Ue(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 ${Re} AND seq <= ?`,[t.target_durable_id,t.seq]);return Number(n?.n??1)}async function De(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 Me(e){try{e.sql.exec(void 0===e.afterCommit?"ROLLBACK":"ROLLBACK TO gateway_enqueue; RELEASE gateway_enqueue")}catch{return}}async function He(e,t,n){if(void 0!==e.afterCommit)return await n();await De(e,t,!0);try{let t=await n();return e.sql.exec("COMMIT"),t}catch(t){throw Me(e),t}}function We(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 Fe(e,t,n){if(void 0!==e.afterCommit)return void e.afterCommit.push(()=>Fe({...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 je(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 $e(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 Pe(e,t){$e(e,`INSERT INTO deliveries (${xe.join(", ")}) VALUES (${xe.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 Ge(e){return N("sha256").update(JSON.stringify(e)).digest("hex")}function Be(e){let t=Number(e.sql.one(["user_version"],"SELECT user_version FROM pragma_user_version()")?.user_version??0);if(t>Oe.length)throw new ke(t,Oe.length);return t}class Je extends Error{version;code="gateway_migration_failed";constructor(e,t){super(t),this.version=e,this.name="GatewayMigrationError"}}var Ke=new Set([6]);function Ye(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 Ve(e,t,n){if(n.args_hash!==t.receipt.args_hash)return Ae("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:Ce(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 Ae("idempotency_in_progress","The same delivery is already in progress.");if("prepared"===n.status&&r){let n={...Ne(i,Ue(e,i),t.endpoint_kind,!0,!1)};return $e(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&&$e(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]),Ae("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 ze(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 Ae("invalid_arguments","Delivery provenance is required.");var n;if(!Se.test(t.target_durable_id)||!Se.test(t.delivery_id))return Ae("invalid_arguments","The target session id is not a durable session id.");if(!await De(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=he(e,{principal:t.sender_principal,operation:"deliver",idempotency_key:t.receipt.idempotency_key},t.now),s=Ye(e,t.sender_principal,t.receipt.idempotency_key);if(void 0!==s){let n=Ve(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?Ae("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 Me(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 ${Re}`,[t.target_durable_id]),u=Buffer.byteLength(t.body);if(Number(d?.n??0)>=128||Number(d?.b??0)+u>W)return Me(e),Ae("queue_full","The target's delivery backlog is full.",{max_messages:128,max_bytes:W});let l=function(e,t){let n;if(null!==t.cause_delivery_id){let i=Ce(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 Ae("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:[...i.envelope.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 Ae("invalid_arguments","The causal root is derived by the gateway and cannot be chosen by the caller.",{guard:"forged_root"});if(!n.new_root){let i=e.sql.one(["expires_at"],"SELECT expires_at FROM causal_roots WHERE root_id = ?",[n.root_id]);if(void 0===i||Number(i.expires_at)<=t.now)return Ae("loop_detected","This causal chain is older than its lifetime.",{guard:"root_expired",root_id:n.root_id})}if(t.target_durable_id===t.sender_node)return Ae("loop_detected","A session cannot deliver to itself through the gateway.",{guard:"self_send"});if(n.hop>4)return Ae("loop_detected",`This delivery would be hop ${n.hop}; at most 4 are allowed.`,{guard:"hop_limit",hop:n.hop});let i=Number(e.sql.one(["n"],"SELECT COUNT(*) AS n FROM deliveries WHERE root_id = ? AND state != 'refused'",[n.root_id])?.n??0);return i>=64?Ae("loop_detected",`This causal chain already carried ${i} deliveries.`,{guard:"causal_budget",root_id:n.root_id}):U(e.sql.all(["from_durable_id","to_durable_id"],"SELECT from_durable_id, to_durable_id FROM causal_edges WHERE root_id = ?",[n.root_id]).map(e=>({from:String(e.from_durable_id),to:String(e.to_durable_id)})),t.sender_node,t.target_durable_id)?Ae("loop_detected","The target already leads back to the sender in this causal chain.",{guard:"cycle",root_id:n.root_id}):n}(e,t);if("kind"in l)return Me(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:Ae("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))/D);if(r<1)return Ae("overloaded","Too many deliveries to this session; wait before sending again.",{budget:"pair_rate",retry_after_ms:Math.ceil((1-r)*D)});$e(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 Me(e),_;l.new_root&&$e(e,"INSERT INTO causal_roots (root_id, origin_principal, created_at, expires_at) VALUES (?, ?, ?, ?)",[l.root_id,t.sender_principal,t.now,t.now+H]),$e(e,"INSERT OR IGNORE INTO causal_edges (root_id, from_durable_id, to_durable_id, delivery_id, created_at) VALUES (?, ?, ?, ?, ?)",[l.root_id,t.sender_node,t.target_durable_id,t.delivery_id,t.now]);let c={delivery_id:t.delivery_id,target_durable_id:t.target_durable_id,seq:je(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+M,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};Pe(e,c),$e(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+F]),i=We(e,c.target_durable_id,c.delivery_id,!1);let p=Ue(e,c);return ye(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||(Me(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 Qe(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 et(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 tt(e){return`${JSON.stringify(e.admitted_by)}#${e.attempt}`}function nt(e,t,n,i,r={}){"queued"!==n?"refused"!==n?($e(e,"UPDATE deliveries SET state = ?, updated_at = ? WHERE delivery_id = ?",[n,i,t.delivery_id]),"applied"===n&&$e(e,"UPDATE session_meta SET applied_seq = MAX(applied_seq, ?) WHERE durable_id = ?",[t.seq,t.target_durable_id])):$e(e,"UPDATE deliveries SET state = 'refused', reason = ?, updated_at = ? WHERE delivery_id = ?",[r.reason??null,i,t.delivery_id]):$e(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 it(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(P))continue;let e;try{e=JSON.parse(i)}catch{continue}let t=e;if("custom"!==t.type||t.customType!==P)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 Ie(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||Qe(n.admitted_by,n.claimed_at,a)?et(t.session_path,n.delivery_id,s)?"applied":"queued":"dual";r.set(n.delivery_id,{fingerprint:tt(n),to:d})}return!0===e.config.test_hooks.announceBarrier&&e.emit({kind:"barrier",op:"reconcile"}),await He(e,"reconcile",()=>{let n=new Set(t.ledger.pending),s=new Set(t.ledger.emitted),o=[],a=[];for(let d of Ie(e,`target_durable_id = ? AND state IN ${Re}`,[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!==tt(d)||"dual"===e.to){a.push(d.delivery_id);continue}i=e.to}i!==d.state&&(nt(e,d,i,t.now),o.push({delivery_id:d.delivery_id,from:d.state,to:i}))}else d.expires_at<=t.now&&(nt(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&&Fe(e,i,t);return{queued:Ie(e,"target_durable_id = ? AND state = 'queued'",[i],"seq"),transitions:o,dual_runtime:a}})}async function rt(e,t){return await He(e,"complete_receipt",()=>1===$e(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 st(e,t){return await He(e,"abandon_receipt",()=>1===$e(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 ot(e,t){let n=Ye(e,t.principal,t.idempotency_key);if(void 0===n||n.expires_at<=t.now||null===n.delivery_id)return null;let i=Ce(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 at(e,t){return await He(e,"recover_delivery",()=>{let n=Ye(e,t.principal,t.idempotency_key);return void 0===n||n.expires_at<=t.now?null:Ve(e,{now:t.now,sender_principal:t.principal,endpoint_kind:null,receipt:{idempotency_key:t.idempotency_key,args_hash:t.args_hash}},n)})}function dt(e,t){let n=Ce(e,t);return void 0===n?null:{row:n,queue_position:Ue(e,n)}}function ut(){try{return C().username}catch{return"unknown"}}import{randomUUID as lt}from"node:crypto";import{renameSync as _t,writeFileSync as ct}from"node:fs";var pt=["question","select","confirm","input","editor"];var mt=new Map([["yes",!0],["y",!0],["true",!0],["no",!1],["n",!1],["false",!1]]);function gt(e){return""===e.replace(/[\s\p{Cf}]/gu,"")}function ft(e){let t=mt.get(e.trim().toLowerCase());return void 0===t?{value:e,answers:{},comment:e}:{value:e,answers:{},comment:e,confirmed:t}}function bt(e,t){switch(e){case null:return gt(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:ft(t)};case"input":case"editor":return{ok:!0,fields:{value:t}};case"select":return gt(t)?{ok:!1,reason:"A select answer names one of its options; the text is blank."}:{ok:!0,fields:{value:t}};case"question":return gt(t)?{ok:!1,reason:"A question answer needs text; this one is blank."}:{ok:!0,fields:{answers:{},comment:t}};case"confirm":{let e=mt.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 Et=["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"],ht=["cursor","binding_id","revision","event_kind","payload","state","provider_message_id","created_at","reply_token","question_state","outcome","answered_by","answer_state"];function yt(e,t,n){return{kind:"refused",code:e,message:t,...void 0===n?{}:{details:n}}}function vt(e){return null==e?null:String(e)}function Tt(e){return null==e?null:JSON.stringify(e)}function wt(e){return null==e?null:JSON.parse(String(e))}function Nt(e,t,n,i){if(void 0!==e.afterCommit)return void e.afterCommit.push(()=>Nt({...e,afterCommit:void 0},t,n,i));let r=(o=e.config.agent_dir,l(_(o),"outbox.marker")),s=`${r}.${process.pid}.${lt()}.tmp`;var o;ct(s,JSON.stringify({binding_id:t,cursor:n,written_at:de(i)}),{mode:384}),_t(s,r)}function Lt(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:vt(e.root_message_id),progress_message_id:vt(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:vt(e.expires_at)}}function kt(e,t,n,i){let r=`SELECT ${Et.join(", ")} FROM bindings WHERE ${t}${void 0===i?"":` ORDER BY ${i.orderBy} LIMIT ?`}`;return e.sql.all(Et,r,void 0===i?n:[...n,i.limit],i?.orderBy).map(Lt)}function Ot(e,t){return kt(e,"binding_id = ?",[t])[0]}function xt(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 Rt(e,t){let n=de(t);$e(e,"UPDATE bindings SET status = 'expired', updated_at = ? WHERE status = 'active' AND expires_at IS NOT NULL AND expires_at <= ?",[n,n])}function St(e,t){$e(e,"DELETE FROM outbox WHERE state = 'acked' AND acked_at IS NOT NULL AND acked_at <= ?",[t-ae]),$e(e,"DELETE FROM outbox WHERE state = 'pending' AND binding_id IN (SELECT binding_id FROM bindings WHERE status != 'active' AND updated_at <= ?)",[de(t-ae)])}function At(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:vt(n.result)}}async function qt(e,t,n,i,r){return await He(e,t,()=>{Rt(e,n);let t=null===i?0:he(e,i,n),s=function(e,t){if(null===t)return;let n=At(e,t);return void 0!==n?n.args_hash!==t.args_hash?yt("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}:yt("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&&$e(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+F])}(e,i,n,{...o,deduplicated:!1}),ye(e,n,t),"ok"===o.kind?{...o,deduplicated:!1}:o})}async function It(e,t){return await He(e,"tool_receipt_begin",()=>{let n=he(e,t,t.now),i=function(e,t){let n=At(e,t);if(void 0===n)return $e(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+F]),{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&&$e(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:vt(i?.error_note)}}(e,t);return ye(e,t.now,n),i})}async function Ct(e,t){let n=t.binding;return await qt(e,"bind",t.now,t.receipt,()=>{let i=kt(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 yt("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=de(t.now),s={schema_version:1,binding_id:`bnd-${te()}`,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:xt(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:de(t.now+1e3*n.ttl_seconds)};return $e(e,`INSERT INTO bindings (${Et.join(", ")}) VALUES (${Et.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 $t(e,t){return e.sql.all(["delivery_id"],`SELECT delivery_id, seq FROM deliveries WHERE binding_id = ? AND state IN ${Re}`,[t],"seq").map(e=>String(e.delivery_id))}async function Ut(e,t){return await qt(e,"unbind",t.now,t.receipt,()=>{let n=Ot(e,t.binding_id);if(void 0===n)return yt("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:$t(e,n.binding_id)};if(n.revision!==t.expected_revision)return yt("stale_revision","The binding changed since that revision.",{binding_id:n.binding_id,revision:n.revision});let i=de(t.now);return $e(e,"UPDATE bindings SET status = 'detached', revision = revision + 1, updated_at = ? WHERE binding_id = ? AND revision = ?",[i,n.binding_id,n.revision]),$e(e,"DELETE FROM completion_arms WHERE binding_id = ?",[n.binding_id]),{kind:"ok",binding:Ot(e,n.binding_id),already_closed:!1,in_flight:$t(e,n.binding_id)}})}async function Dt(e,t){return await qt(e,"rebind",t.now,t.receipt,()=>{let n=Ot(e,t.binding_id);if(void 0===n)return yt("not_found","No binding has this id.",{binding_id:t.binding_id});if("active"!==n.status)return yt("binding_inactive",`The binding is ${n.status}.`,{binding_id:n.binding_id,status:n.status});if(n.revision!==t.expected_revision)return yt("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 yt("invalid_arguments","The binding is already attached to that session.",{binding_id:n.binding_id});let i=de(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)$e(e,"UPDATE deliveries SET state = 'refused', reason = 'binding_closed', updated_at = ? WHERE delivery_id = ? AND state = 'queued'",[t.now,n.delivery_id]),Fe(e,n.target,n.delivery_id);return $e(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]),$e(e,"DELETE FROM completion_arms WHERE binding_id = ?",[n.binding_id]),{kind:"ok",binding:Ot(e,n.binding_id),closed:r.map(e=>e.delivery_id)}})}async function Mt(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 yt("cursor_invalid","The bindings cursor is not one this gateway issued.");let i=Math.min(Math.max(t.limit??50,1),200);return await He(e,"list_bindings",()=>{Rt(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=kt(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?ge(r,[l.created_at,l.binding_id]):null}})}async function Ht(e,t){return await He(e,"binding_view",()=>(Rt(e,t.now),Ot(e,t.binding_id)??null))}function Wt(e,t){return vt(e.sql.one(["incarnation"],"SELECT incarnation FROM session_meta WHERE durable_id = ?",[t])?.incarnation)}function Ft(e,t){$e(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 Nt(e,t.binding.binding_id,n,t.now),n}async function Xt(e,t){return await qt(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=vt(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 yt("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 yt("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?yt("invalid_arguments","This session has no active outbound binding and its current run answers no bound message; name binding_id."):yt("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=Ot(e,i);if(void 0===r)return yt("not_found","No binding has this id.",{binding_id:i});if(r.session_durable_id!==t.session_durable_id)return yt("scope_denied","The binding is attached to another session.",{binding_id:i});if("active"!==r.status)return yt("binding_inactive",`The binding is ${r.status}.`,{binding_id:i,status:r.status});if(!r.direction.outbound)return yt("unsupported","The binding carries no outbound direction.",{binding_id:i,direction:r.direction});if(!r.outbound_events.includes(t.event))return yt("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 yt("invalid_arguments","Only a question names a request kind.");let s={binding_id:i,revision:r.revision,event:t.event};if("completion"===t.event){$e(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 yt("invalid_arguments","A question names the session's pending extension UI request (request_id).");let n=Wt(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:te()},i=me(JSON.stringify(n));return`${fe}.${i}.${be(e,i)}`}(xt(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=Ft(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 St(e,t.now),{kind:"ok",...s,cursor:a,reply_token:o,armed:!1,arm_seq:null}}let o=Ft(e,{binding:r,event:t.event,text:t.text,now:t.now});return St(e,t.now),{kind:"ok",...s,cursor:o,reply_token:null,armed:!1,arm_seq:null}})}async function jt(e,t){return await He(e,"emit_completions",()=>{Rt(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)$e(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=Ot(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:Ft(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 Pt(e,t){return Number(e.sql.one(["acked_cursor"],"SELECT acked_cursor FROM outbox_cursors WHERE binding_id = ?",[t])?.acked_cursor??0)}async function Gt(e,t){let n=Math.min(Math.max(t.limit??100,1),500);return await He(e,"read_outbox",()=>{Rt(e,t.now),St(e,t.now);let i=Ot(e,t.binding_id);if(void 0===i)return yt("not_found","No binding has this id.",{binding_id:t.binding_id});let r=Pt(e,i.binding_id),s=t.after_cursor??r,o=e.sql.all(ht,`SELECT ${ht.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:de(Number(e.created_at)),edit_message_id:"milestone"===n?t.progress_message_id:null,provider_message_id:vt(e.provider_message_id),reply_token:vt(e.reply_token),question_state:e.question_state??null,outcome:e.outcome??null,answered_by:wt(e.answered_by),answer_state:e.answer_state??null}}(e,i));return ye(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 Bt(e,t){return await He(e,"ack_outbox",()=>{Rt(e,t.now);let n=Ot(e,t.binding_id);if(void 0===n)return yt("not_found","No binding has this id.",{binding_id:t.binding_id});let i=Pt(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 yt("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 $e(e,"UPDATE outbox SET state = 'acked', acked_at = ? WHERE binding_id = ? AND cursor <= ? AND state = 'pending'",[t.now,n.binding_id,t.cursor]),$e(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&&($e(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&&$e(e,"UPDATE bindings SET progress_message_id = ?, updated_at = ? WHERE binding_id = ?",[t.provider_message_id,de(t.now),n.binding_id])),{kind:"ok",binding_id:n.binding_id,acked_cursor:t.cursor,changed:!0}})}var Jt="The session no longer waits for this question (answered or closed elsewhere)";async function Kt(e,t){return await He(e,"claim_answer",()=>{Rt(e,t.now);let n=function(e,t){let n=t.split(".");if(3!==n.length||n[0]!==fe)return null;let i=Buffer.from(be(e,n[1])),r=Buffer.from(n[2]);if(i.length!==r.length||!ne(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}}(xt(e,"token_secret"),t.reply_token);if(null===n)return yt("invalid_arguments","This is not a reply token this gateway issued.");if(n.binding_id!==t.binding_id)return yt("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 yt("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 yt("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 yt("already_answered",null===i.answer&&"delivered"===i.answer_state?`${Jt}.`:"This question was already answered.",{cursor:Number(i.cursor)});let o="string"==typeof(d=i.ui_request_kind)&&pt.includes(d)?i.ui_request_kind:null,a=bt(o,t.answer);var d;if(!a.ok)return yt("invalid_arguments",a.reason,{ui_request_kind:o});let u=Ot(e,n.binding_id);return void 0===u||"active"!==u.status||u.revision!==n.revision||u.session_durable_id!==n.session_durable_id||Wt(e,n.session_durable_id)!==n.incarnation||vt(i.ui_request_id)!==n.ui_request_id?yt("stale_token","The binding or the session changed since the question was asked.",{binding_id:n.binding_id}):($e(e,"UPDATE outbox SET question_state = 'answered', answer_state = 'in_flight', answer = ?, answered_at = ?, answered_by = ? WHERE reply_token = ?",[t.answer,t.now,Tt(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:vt(i.answer),answered_at:null===i.answered_at||void 0===i.answered_at?null:Number(i.answered_at),answered_by:wt(i.answered_by)}:null})})}function Yt(e,t,n){let i=e.sql.one(["cursor","binding_id"],"SELECT cursor, binding_id FROM outbox WHERE reply_token = ?",[t]);void 0!==i&&Nt(e,String(i.binding_id),Number(i.cursor),n)}async function Vt(e,t){return await He(e,"release_answer",()=>{let n=1===$e(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&&Yt(e,t.reply_token,t.claimed_at),n})}async function zt(e,t){return await He(e,"mark_prior_delivered",()=>{let n=1===$e(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,Tt(t.prior.answered_by),t.reply_token,t.claimed_at]);return n&&Yt(e,t.reply_token,t.claimed_at),n})}async function Zt(e,t){return await He(e,"confirm_answer",()=>{let n=1===$e(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,Tt(t.answered_by),t.reply_token]);return n&&Yt(e,t.reply_token,t.claimed_at),n})}import{existsSync as Qt}from"node:fs";import{extname as en}from"node:path";import{fileURLToPath as tn}from"node:url";var nn=new Set(["object","string","number","integer","boolean","array","null"]),rn=new Set(["title","description","default","examples"]),sn=["minLength","maxLength","minItems","maxItems"],on=["minimum","maximum","exclusiveMinimum","exclusiveMaximum"],an=new Set(["type","properties","required","additionalProperties","enum","const","pattern","items","anyOf",...sn,...on,...rn]),dn=e=>"object"==typeof e&&null!==e&&!Array.isArray(e);function un(e,t="parameters"){if(!dn(e))return`${t} must be a schema object`;for(let n of Object.keys(e))if(!n.startsWith("~")&&!an.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&&nn.has(e)))return`${t}.type must name JSON types`;if(void 0!==i){if(!dn(i))return`${t}.properties must be an object`;for(let[e,n]of Object.entries(i)){let i=un(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 sn){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 on){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=un(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=un(n,`${t}.anyOf.${e}`);if(void 0!==i)return i}}}function ln(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)=>ln(e,t[n]));if(!dn(e)||!dn(t))return!1;let n=Object.keys(e);return n.length===Object.keys(t).length&&n.every(n=>Object.hasOwn(t,n)&&ln(e[n],t[n]))}var _n=(e,t)=>`${e}/${String(t).replaceAll("~","~0").replaceAll("/","~1")}`;function cn(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 dn(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&&!ln(e.const,t))return i(`must be ${JSON.stringify(e.const)}`);if(Array.isArray(e.enum)&&!e.enum.some(e=>ln(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(dn(e.items))for(let[i,r]of t.entries()){let t=cn(e.items,r,_n(n,i));if(void 0!==t)return t}}if(dn(t)){let r=dn(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(dn(t)){let e=cn(t,o,_n(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=>dn(e)&&void 0===cn(e,t,n))?i("must match one of the allowed shapes"):void 0}var pn=["caller_session_durable_id","caller_created_target"],mn=/^tor_[a-f0-9]{32}$/,gn=12e4,fn=/^[a-z][a-z0-9_]{1,40}$/,bn=/^[a-z0-9][a-z0-9_-]*$/,En=/^[A-Za-z0-9][A-Za-z0-9._-]*$/,hn=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),yn=e=>"string"==typeof e&&e.length>0;function vn(e,t){return`ext_${e}_${t}`}function Tn(e){return!0!==e.internal}function wn(e,t,n){if(!hn(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(!yn(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||yn(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||!fn.test(r))return`toolName ${String(r)} must match ${fn.source}`;if(vn(t,r).length>64)return`${vn(t,r)} is longer than 64 characters`;if(!yn(s))return`${r}: description must be a non-empty string`}let _=l?i:String(r);if(!hn(o)||"object"!==o.type||!1!==o.additionalProperties)return`${_}: parameters must be an object schema with additionalProperties: false`;let c=o.properties??{};if(!hn(c))return`${_}: parameters.properties must be an object`;if(pn.some(e=>Object.hasOwn(c,e)))return`${_}: parameters must not declare ${pn.join(" or ")}; the store stamps them`;let p=un(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(!hn(u)||!yn(u.statusOp)||!yn(u.expireOp))return`${_}: await needs statusOp and expireOp`;let e=u.timeoutMs;if("number"!=typeof e||!Number.isInteger(e)||e<1||e>gn)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&&En.test(d)?void 0!==d&&void 0===n?`${_}: wake needs the registration's wakeDir`:void 0:`${_}: wake must be a plain file name matching ${En.source}`}function Nn(e,t){let{name:n,sessionCallable:i,wakeDir:r}=e;if(void 0!==r&&("string"!=typeof r||!bn.test(r)))return`wakeDir must be one path segment matching ${bn.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=wn(e,n,r);if(void 0!==i)return i;let a=e;if(Tn(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=Tn(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`${Tn(a)?a.toolName:a.op}: the module exports no operation ${e}`}}function Ln(e){let t=new Set;for(let n of e?.sessionCallable??[])if(t.add(n.op),Tn(n)&&void 0!==n.await)for(let e of[n.await.statusOp,n.await.expireOp])t.add(e);return t}function kn(e,t){try{let n=JSON.parse(String(t));if(!hn(n)||"string"!=typeof n.moduleUrl||!Array.isArray(n.migrations))return;let i=n;return void 0===Nn({...i,name:e})?i:void 0}catch{return}}function On(e,t){let n=e.sql.one(["descriptor_json"],"SELECT descriptor_json FROM extension_registrations WHERE name = ?",[t]);return void 0===n?void 0:kn(t,n.descriptor_json)}function xn(e){return e.sql.all(["name","descriptor_json"],"SELECT name, descriptor_json FROM extension_registrations",[],"name").flatMap(e=>{let t=String(e.name);return(kn(t,e.descriptor_json)?.sessionCallable??[]).filter(Tn).map(e=>({...e,extension:t,registeredName:vn(t,e.toolName)}))})}function Rn(e,t){let n=new Set((t.sessionCallable??[]).filter(Tn).map(e=>vn(t.name,e.toolName))),i=xn(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 Sn(e){let t=new URL(e);if("file:"!==t.protocol||![".js",".mjs",".cjs"].includes(en(t.pathname)))throw Error("moduleUrl must name a compiled JavaScript file URL.");if(!Qt(tn(t)))throw Error(`The extension module ${e} does not exist.`);return await(import(e))}var An=0,qn=1,In=1,Cn=2,$n=9,Un=10,Dn=11,Mn=18,Hn=20,Wn=21,Fn=23,Xn=26,jn=27,Pn=31,Gn=33;class Bn extends Error{code="extension_schema_violation"}var Jn=["type","name","tbl_name","sql"],Kn=e=>e.replace(/[A-Z]/g,e=>e.toLowerCase()),Yn=e=>`${String(e.type)}:${Kn(String(e.name))}`;function Vn(e){return{objects:e.all(Jn,"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=>[Yn(e),null===e.owner?null:String(e.owner)]))}}function zn(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=>Kn(String(e.name)).startsWith(t)))throw new Bn(`Extension name ${t} collides with a core namespace.`)}function Zn(e,t,n,i){let r=new Map(n.objects.map(e=>[Yn(e),e])),s=new Map(i.objects.map(e=>[Yn(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 Bn(`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 Bn("Store extensions cannot create triggers or views.");let u=Kn(String(d.name));if(("index"!==d.type||null!==d.sql||!u.startsWith(`sqlite_autoindex_${Kn(String(d.tbl_name))}_`))&&!u.startsWith(`${t}_`)||n.owners.has(e)&&n.owners.get(e)!==t)throw new Bn(`Extension ${t} created an object outside its namespace: ${String(d.name)}.`);if("index"===d.type){let e=`table:${Kn(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 Bn(`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),Kn(String(o.name)),t])}}function Qn(e,t,n){let i,r,s=Vn(e),o=new Map(s.owners),a=new Set(s.objects.filter(e=>"trigger"===e.type||"view"===e.type).map(e=>Kn(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,_=An,c=e=>(r=`Extension ${t} does not own ${e??"this SQLite operation"}.`,qn);try{return e.authorized((e,t,n,r,s)=>{let o=null===t?null:Kn(t),p=null===n?null:Kn(n),m=null===r?null:Kn(r),g=null===s?null:Kn(s);if(null!==g&&a.has(g))return c(g);switch(e){case Cn:return i="create","main"===m&&u("table",o)?_:c(o);case In:return i="create","main"===m&&d("table",p)&&u("index",o,!0===o?.startsWith(`sqlite_autoindex_${p}_`))?_:c(o);case Dn:return i="drop","main"===m&&d("table",o)?_:c(o);case Un: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 jn:return"main"===m&&d("index",o)?_:c(o);case Hn:case Mn:case Fn:case $n:return"sqlite_master"===o||"sqlite_temp_master"===o?(e===Fn&&"sql"===p&&(l=!0),e!==Hn||"alter"===i||"drop"===i||"create"===i&&l&&"rowid"===p?_:c(o)):"alter"!==i||"sqlite_sequence"!==o||"name"!==p||e!==Hn&&e!==Fn?("main"===m||null===m&&e===Hn&&""===p)&&d("table",o)?_:c(o):_;case Wn:case Gn:return _;case Pn:return"load_extension"===p?c(p):_;default:return c(o)}},n)}catch(e){if(void 0!==r)throw new Bn(r);throw e}}import{createHash as ei,randomUUID as ti}from"node:crypto";import{execFile as ni}from"node:child_process";import{existsSync as ii,readFileSync as ri,statSync as si}from"node:fs";import{homedir as oi}from"node:os";import{basename as ai,delimiter as di,dirname as ui,isAbsolute as li,join as _i,relative as ci,resolve as pi,sep as mi}from"node:path";var gi=(e,t)=>new Promise(n=>{ni("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 fi(e,t){let n=_i(e,".git");if(!ii(n))return!1;if(si(n).isDirectory())return!0;let i=/^gitdir:\s*(.+?)\s*$/m.exec(t(n))?.[1];return void 0!==i&&ii(pi(e,i))}async function bi(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(di).filter(e=>li(e)).map(e=>pi(e)));try{for(let t=pi(e);;t=ui(t)){if(fi(t,i))return!0;if(ui(t)===t||r.has(ui(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=>ri(e,"utf8"))))return;let r=await(i.execGit??gi)(["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 Ei(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=>bi(n,t,o,e)))(e.cwd)),d=i||a?.project||ai(pi(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??oi();return{workspace:(_??u.find(t=>t.paths?.some(t=>function(e,t,n){let i="~"===t?n:t.startsWith("~/")?pi(n,t.slice(2)):t;if(!li(i))return!1;let r=ci(pi(i),pi(e));return""===r||!li(r)&&".."!==r&&!r.startsWith(`..${mi}`)}(e.cwd,t,c))))?.name??"unclassified",project:d,...s}}var hi={loop_detected:"Stop relaying here: a direct reply to the session that messaged you is a cycle. That session reads your answer with thread_read; a bound external thread gets it through thread_report, and its questions come back through thread_answer.",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 yi(e,t,n){return{kind:"error",error:Te(e,t,hi[e]??"Call thread_list and retry after checking the target.",n)}}function vi(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},ei("sha256").update(JSON.stringify(t)).digest("hex");var t}function Ti(e){let t=!1;for(let n of y(e))if("space"!==n.kind&&"comment"!==n.kind){if(t)throw new Bn("An extension SQL call must contain one statement.");"semicolon"===n.kind&&(t=!0)}}var wi=/^[ \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,Ni=e=>JSON.stringify(e.length>80?`${e.slice(0,80)}…`:e),Li=e=>e?.toUpperCase();var ki=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;function Oi(e){return{kind:"refused",code:"invalid_arguments",message:e}}function xi(e,t,n){return"string"!=typeof t||0===t.trim().length?Oi(`author.${e} must be a non-empty string.`):t.length>n?Oi(`author.${e} is longer than ${n} characters.`):ki.test(t)?Oi(`author.${e} carries a control character or line break.`):t.trim()}var Ri={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."},Si=new Set(["question_already_resolved","unknown_extension_ui_request","unknown_request"]);function Ai(e,t,n,i){return{kind:"error",error:Te(e,t,i??Ri[e]??"Call thread_bindings and retry after checking the binding.",n)}}function qi(e){return"refused"===e.kind?Ai(e.code,e.message,e.details):e}function Ii(e){if(void 0===e)return;let t=function(e){let t=xi("platform_user_id",e.platform_user_id,256);if("string"!=typeof t)return t;let n=xi("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=xi("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?Ai("invalid_arguments",t.message):t}function Ci(e){let t=Buffer.byteLength(e);return t>32768?Ai("message_too_large",`The text is ${t} bytes, above the 32768-byte limit.`):void 0}function $i(e,t,n){return void 0===e.idempotency_key?null:{principal:e.principal,operation:t,idempotency_key:e.idempotency_key,args_hash:(i=n,Q("sha256").update(pe(i)).digest("hex"))};var i}function Ui(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(!ie.includes(e.platform))return ue(`platform must be one of ${ie.join(", ")}.`);let t={account_id:le("account_id",e.account_id),chat_id:le("chat_id",e.chat_id),thread_id:le("thread_id",e.thread_id??"@chat"),root_message_id:_e("root_message_id",e.root_message_id),progress_message_id:_e("progress_message_id",e.progress_message_id),session_durable_id:le("session",e.session_durable_id),policy_id:le("policy_id",e.policy_id??"default")};for(let e of Object.values(t))if(ce(e))return e;let n=e.direction??{inbound:!0,outbound:!0};if(!0!==n.inbound&&!0!==n.outbound)return ue("A binding needs at least one direction: inbound, outbound, or both.");let i=e.inbound_mode??"auto";if(!se.includes(i))return ue(`inbound_mode must be one of ${se.join(", ")}.`);let r=e.outbound_events??(n.outbound?re:[]);if(r.some(e=>!re.includes(e)))return ue(`outbound_events may only name ${re.join(", ")}.`);if(new Set(r).size!==r.length)return ue("outbound_events must not repeat an event.");if(n.outbound&&0===r.length)return ue("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>oe)?ue("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:re.filter(e=>r.includes(e)),policy_id:t.policy_id,ttl_seconds:s}}(e.binding);return qi("kind"in i?i:await t.bind({now:n(),receipt:$i(e,"thread_bind",i),binding:i}))},unbind:async e=>{let i={binding_id:e.binding_id,expected_revision:e.expected_revision};return qi(await t.unbind({now:n(),receipt:$i(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 qi(await t.rebind({now:n(),receipt:$i(e,"thread_rebind",i),...i}))},bindings:async e=>qi(await t.listBindings({now:n(),...e})),report:async e=>{let i=Ci(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 qi(await t.report({now:n(),receipt:$i(e,"thread_report",r),...r}))},outbox:async e=>qi(await t.readOutbox({now:n(),...e})),ack:async e=>qi(await t.ackOutbox({now:n(),...e})),answer:async i=>{let r=Ci(i.answer);if(void 0!==r)return r;let a=Ii(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 qi(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),Ai(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=bt(u.ui_request_kind,i.answer);if(!g.ok)return await s(l),Ai("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),Ai("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&&Si.has(m.error))return"question_already_resolved"===m.error?(await o(()=>t.markPriorDelivered({...l,prior:e})),Ai("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}})),Ai("already_answered",`${Jt} (${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?Ai("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."):Ai(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&&!se.includes(i.mode))return Ai("invalid_arguments",`A binding message is delivered as ${se.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=Ii(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 Ai("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===vi({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 Ai(e.code,e.message,e.details)}if("active"!==s.status)return Ai("binding_inactive",`The binding is ${s.status}.`,{binding_id:s.binding_id,status:s.status});if(!s.direction.inbound)return Ai("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?Ai("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 Di extends Error{extension;code="extension_operation_failed";constructor(e){super(`The ${e} extension transaction has ended.`),this.extension=e}}class Mi 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 Hi extends Error{code="invalid_arguments"}function Wi(e,t,n,i,r){let s,o=!0,a=0,d=!1,u=Promise.resolve();function l(e){if(d)throw new Di(t);if(void 0!==s)throw s;return e()}function _(e){if(!o)return Promise.reject(new Di(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 Di(t);if(void 0!==s)throw s})(),a>0)throw s=new Mi(t),s;let r=Vn(e.sql);try{Ti(n);let s=Qn(e.sql,t,i);return Zn(e.sql,t,r,Vn(e.sql)),s}catch(e){throw s=e,e}}let p={now:()=>n,busyTimeoutMs:e.config.busy_timeout_ms,enqueue:t=>l(()=>ze(e,t)),completeReceipt:t=>l(()=>rt(e,t)),abandonReceipt:t=>l(()=>st(e,t)),deliveryView:async t=>l(()=>dt(e,t)),deliveryReceipt:async t=>l(()=>ot(e,t)),recoverDelivery:t=>l(()=>at(e,t)),bind:t=>l(()=>Ct(e,t)),unbind:t=>l(()=>Ut(e,t)),rebind:t=>l(()=>Dt(e,t)),listBindings:t=>l(()=>Mt(e,t)),bindingView:t=>l(()=>Ht(e,t)),report:t=>l(()=>Xt(e,t)),readOutbox:t=>l(()=>Gt(e,{...t,pendingOnly:!0})),ackOutbox:t=>l(()=>Bt(e,t)),claimAnswer:t=>l(()=>Kt(e,t)),releaseAnswer:t=>l(()=>Vt(e,t)),confirmAnswer:t=>l(()=>Zt(e,t)),markPriorDelivered:t=>l(()=>zt(e,t)),emitCompletions:t=>l(()=>jt(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 yi("invalid_arguments","A steer needs expected_turn_id (the target's current turn_epoch).");let s=Buffer.byteLength(i.text);if(s>W)return yi("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 yi("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?.()??Ei({cwd:process.cwd()}))),l=ti(),_=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:vi({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 yi("overloaded","The gateway store is locked by a suspended writer; nothing was sent.",{budget:"store_lock"});if("refused"===c.kind)return yi(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(Ne(c.row,c.queue_position,null,!1,!0));let n=!0;try{await e.endpoints.wake(d,[l])}catch{n=!1}let i=await t.deliveryView(l);if(null===i)throw Error(`delivery ${l} vanished after commit`);return await p(Ne(i.row,i.queue_position,d.kind,!1,!n))}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=Ui({store:p,engine:g,endpoints:m,locate:async()=>null});return{tx:{all:(t,n,i,r)=>c(n,()=>{for(let e of t)Ti(e);if(void 0===r)return e.sql.all(t,n,i);let s=function(e){return e.split(",").map(t=>{let n=wi.exec(t);if(null===n)throw new Bn(`orderBy must list the statement's output columns, each optionally with COLLATE BINARY/NOCASE/RTRIM, ASC/DESC or NULLS FIRST/LAST; got ${Ni(e)}. Put LIMIT, OFFSET and table-qualified ordering in the statement itself.`);return{column:n[1],collate:Li(n[2]),direction:Li(n[3]),nulls:Li(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=>Kn(t)===Kn(e.column));if(void 0===n)throw new Bn(`orderBy must list the statement's output columns; ${Ni(e.column)} is not one of them (${Ni(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)Ti(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 He(e,"binding_for",()=>(Rt(e,t.now),kt(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 Hi("bindingsForSession needs a non-empty session durable id.");return kt(e,"session_durable_id = ? AND status = 'active' AND (expires_at IS NULL OR expires_at > ?)",[t,de(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}}}var Fi=6048e5;function Xi(e,t){return{kind:"refused",code:e,message:t}}function ji(e){let t=e instanceof Error?e.message:String(e);return e instanceof Bn||e instanceof ke||e instanceof Hi?Xi(e.code,t):u(e)?Xi("gateway_lock_wait_exceeded",t):Xi("extension_operation_failed",t)}class Pi{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 Xi("invalid_arguments","An extension needs a valid namespace and an array of SQL migration steps.");let i,r=Nn(e);if(void 0!==r)return Xi("invalid_arguments",`Extension ${e.name}: ${r}.`);try{zn(this.ctx.sql,e.name)}catch(e){return ji(e)}try{i=await Sn(e.moduleUrl)}catch(t){return Xi("extension_import_failed",`Cannot import extension ${e.name}: ${t instanceof Error?t.message:String(t)}`)}let s=Nn(e,i);if(void 0!==s)return Xi("invalid_arguments",`Extension ${e.name}: ${s}.`);let o=Rn(this.ctx,e);if(void 0!==o)return Xi("invalid_arguments",`Extension ${e.name}: ${o}.`);try{let r=await this.ensure(e,t),s=await He(this.ctx,"extension_register",()=>function(e,t,n,i){let r=Rn(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?Xi("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 ke||this.registered.set(e.name,{descriptor:e,module:i}),ji(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 He(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 ke(r,i.length,`Extension ${n}`);let s=Vn(this.ctx.sql);if(void 0===e&&s.objects.some(e=>Kn(String(e.name)).startsWith(`${n}_`)&&null==s.owners.get(`${String(e.type)}:${Kn(String(e.name))}`)))throw new Bn(`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]){Ti(e);let t=Vn(this.ctx.sql);Qn(this.ctx.sql,n,()=>this.ctx.sql.exec(e)),Zn(this.ctx.sql,n,t,Vn(this.ctx.sql))}return Zn(this.ctx.sql,n,s,Vn(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=On(this.ctx,e);if(Ln(r?.descriptor).has(t)||Ln(s).has(t))return Xi("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=On(this.ctx,e)){if(void 0===t)return Xi("extension_unknown_name",`No store extension is registered as ${e}.`);try{zn(this.ctx.sql,e)}catch(e){return ji(e)}try{return{descriptor:{...t,name:e},module:await Sn(t.moduleUrl)}}catch(t){return Xi("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 Xi("extension_unknown_op",`Extension ${n} exports no operation ${i}.`);let o,a,d=[],u=[];try{let r=await this.ensure(e.descriptor,t);o=await He(this.ctx,"extension_call",async()=>{if(void 0!==e.replay){let t=function(e,t){e.sql.run("DELETE FROM toolkit_replay_receipts WHERE turn_at < ?",[Date.now()-Fi]);let n=e.sql.one(["op","args_sha256","result_json"],"SELECT op, args_sha256, result_json FROM toolkit_replay_receipts WHERE replay_key = ?",[t.key]);if(void 0===n)return;if(n.op!==t.op||n.args_sha256!==t.args_sha256){let e=[n.op!==t.op?"op":void 0,n.args_sha256!==t.args_sha256?"args":void 0].filter(e=>void 0!==e);return{stop:{kind:"refused",code:"toolkit_replay_divergence",message:`Replayed call ${t.key} differs from what its key recorded; it was not run again. replay_differs=${e.join(",")} recorded_op=${String(n.op)} attempted_op=${t.op}`}}}return{replayed:JSON.parse(String(n.result_json))}}(this.ctx,e.replay);if(void 0!==t)return a=t,"replayed"in t?t.replayed:void 0}let o=this.ctx.sql.one(["version"],"SELECT version FROM extension_schema WHERE name = ?",[n]),l=Number(o?.version??0);if(l!==r)throw new ke(l,e.descriptor.migrations.length,`Extension ${n}`);let _,c=Vn(this.ctx.sql),p=Wi({...this.ctx,afterCommit:d,afterRollback:u},n,t,this.resolveTarget,this.senderProvenance);try{let r=async()=>{try{return await s(p.tx,e.args())}finally{await p.finish()}},o=new Promise((e,t)=>{_=setTimeout(()=>{p.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)}),a=await Promise.race([r(),o]);Zn(this.ctx.sql,n,c,Vn(this.ctx.sql));let u=structuredClone(a);return void 0!==e.replay&&function(e,t,n,i){e.sql.run("INSERT OR REPLACE INTO toolkit_replay_receipts (replay_key, op, args_sha256, result_json, turn_at, created_at) VALUES (?, ?, ?, ?, ?, ?)",[t.key,t.op,t.args_sha256,JSON.stringify(n??null),t.turn_at,i])}(this.ctx,e.replay,u,t),d.push(...e.effects??[]),u}finally{clearTimeout(_),p.cancel()}})}catch(e){for(let e of u)try{e()}catch(e){this.ctx.emit({kind:"extension_error",extension:n,phase:"after_rollback",error:e instanceof Error?e.message:String(e)})}return ji(e)}if(void 0!==a&&"stop"in a)return a.stop;await this.ctx.hook("afterDbCommit");for(let e of d)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 Gi}from"node:crypto";import{rmSync as Bi,renameSync as Ji,writeFileSync as Ki}from"node:fs";import{dirname as Yi,join as Vi}from"node:path";var zi=(e,t)=>({result:{kind:"refused",code:e,message:t}});function Zi(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 Qi(e,t,n){let{name:i,caller:r,phase:s,replay:o}=n;if("string"!=typeof r||0===r.length||"unknown-caller"===r)return zi("caller_context_missing","A session-callable op needs the calling session's engine-resolved durable id.");let a=await t.load(i);if("kind"in a)return{result:a};let{descriptor:d}=a,u=d.sessionCallable?.find(e=>e.op===n.op);if(void 0===u)return zi("extension_unknown_op",`Extension ${i} declares no session-callable op ${n.op}.`);let l=n.args;if("object"!=typeof l||null===l||Array.isArray(l))return zi("invalid_arguments","Session op arguments must be an object.");let _=pn.find(e=>Object.hasOwn(l,e));if(void 0!==_)return zi("invalid_arguments",`${_} is stamped by the store from the engine's caller and cannot be passed.`);let p=u.op,m=Tn(u)?u.await:void 0;if("op"===s){let e;try{e=cn(u.parameters,l)}catch(e){return zi("invalid_arguments",`${i}.${u.op} declares parameters that cannot be checked: ${e instanceof Error?e.message:String(e)}`)}if(void 0!==e)return zi("invalid_arguments",`Parameter validation failed at ${e.path||"/"}: ${e.message}`)}else{if("status"!==s&&"expire"!==s)return zi("invalid_arguments",`Unknown session call phase ${String(s)}.`);{let e=l.await_request_id;if(void 0===m)return zi("extension_unknown_op",`${i}.${u.op} declares no await.`);if("string"!=typeof e||!mn.test(e))return zi("invalid_arguments",`await_request_id must match ${mn.source}.`);p="status"===s?m.statusOp:m.expireOp}}let g=void 0===u.targetArg?void 0:l[u.targetArg],{wakeDir:f}=d,b=Tn(u)?u.wake:void 0;if("op"===s&&void 0!==o&&n.now-o.turn_at>Fi)return E="toolkit_replay_expired",h=`Call ${o.key} (${o.op}) belongs to a turn older than the seven-day replay window; it was not run again.`,{result:{kind:"refused",code:E,message:h}};var E,h;let y="op"===s&&void 0!==b&&void 0!==f?[()=>function(e,t,n){let i=Vi(Yi(c(e)),t,n),r=`${i}.${process.pid}.${Gi()}.tmp`;Ki(r,JSON.stringify({written_at:(new Date).toISOString()}),{mode:384});try{Ji(r,i)}finally{Bi(r,{force:!0})}}(e.config.agent_dir,f,b)]:[],v=await t.run({name:i,descriptor:d,module:a.module,op:p,args:()=>({..."op"===s?l:{await_request_id:l.await_request_id},caller_session_durable_id:r,..."op"===s&&"string"==typeof g&&Zi(e,r,g)?{caller_created_target:!0}:{}}),effects:y,..."op"===s&&void 0===o?{}:{replay:o}},n.now);return"op"===s&&void 0!==m&&void 0!==f?{result:v,await:{timeout_ms:m.timeoutMs,wake_dir:f}}:{result:v}}var er=a;if(null===er)throw Error("the gateway store worker must run as a worker thread");var tr,nr,ir,rr,sr=[],or=new Map,ar=!1,dr=1,ur=new Map,lr=(e,t)=>new Promise((n,i)=>{let r=dr++;ur.set(r,{resolve:n,reject:i}),er.postMessage({type:"resolve",id:r,address:e,request:t})}),_r=new Map,cr=()=>new Promise((e,t)=>{let n=dr++;_r.set(n,{resolve:e,reject:t}),er.postMessage({type:"provenance",id:n})});function pr(e){mr(e instanceof Di?{kind:"extension_error",extension:e.extension,phase:"stale_transaction",error:e.message}:{kind:"extension_error",extension:rr??"worker",phase:"async",error:e instanceof Error?e.message:String(e)})}function mr(e){er?.postMessage({type:"event",event:e})}async function gr(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"));nr=new m.DatabaseSync(p,{timeout:u.busy_timeout_ms});let g=new v(nr);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 mr({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};tr={sql:g,config:u,self:E,stats:{writes:0,marker_unlinks:0,transactions:0},emit:mr,hook:fr,delay:e=>o(e)};try{await async function(e){if(!(Be(e)>=Oe.length))for(;;){let t=Be(e);if(t>=Oe.length)return;let n=Ke.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 He(e,"migrate",()=>{let i=Be(e);if(i===t){for(let t of Oe[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 Je(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"))}}}(tr),ir=new Pi(tr,lr,cr);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=K(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=ut(),a=r.filter(e=>!Se.test(e.target)).map(e=>({message_seq:e.message_seq,target:e.target,reason:"invalid_target"})),d=r.filter(e=>Se.test(e.target));n+=await He(e,"migrate_legacy",()=>{let n=0;for(let r of d){let s=`legacy-${Ge([i,r.message_seq]).slice(0,32)}`;if(void 0!==Ce(e,s))continue;let a=`root-${L()}`,d=`legacy:${i}`;$e(e,"INSERT INTO causal_roots (root_id, origin_principal, created_at, expires_at) VALUES (?, ?, ?, ?)",[a,d,t,t+H]);let u=Date.parse(r.accepted_at);Pe(e,{delivery_id:s,target_durable_id:r.target,seq:je(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+M,binding_id:null,binding_revision:null,actor_user_id:null}),We(e,r.target,s,!0),n++}return $e(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}(tr,a.now);return tr.stats.writes=0,tr.stats.transactions=0,tr.stats.marker_unlinks=0,{self:E,legacy_migrated:e}}catch(e){try{nr.exec("ROLLBACK")}catch{}try{nr.close()}finally{nr=void 0,tr=void 0,mr({kind:"store_closed"})}throw e}}(u);if("close"===a)return nr?.close(),nr=void 0,tr=void 0,ir=void 0,null;let l=function(){if(void 0===tr)throw Error("the gateway store is not open");return tr}();switch(a){case"extension_register":{let e=u;return rr=e.extension.name,{result:await(ir?.register(e.extension,e.now,e.restored_at)),retained:!0===ir?.holds(e.extension)}}case"extension_call":case"extension_session_call":{let e=u;rr=e.name;try{if(void 0===ir)return;return"extension_call"===a?await ir.call(e.name,e.op,e.args,e.now):await Qi(l,ir,u)}finally{for(let t of ur.values())t.reject(new Di(e.name));ur.clear();for(let t of _r.values())t.reject(new Di(e.name));_r.clear()}}case"session_callable_ops":return xn(l);case"record_thread_creation":return await async function(e,t){await He(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 ze(l,u);case"reconcile":return await it(l,u);case"claim":return await async function(e,t){return await He(e,"claim",()=>{let n=Ce(e,t.delivery_id);return void 0===n||"queued"!==n.state?{kind:"lost",state:n?.state??null}:n.expires_at<=t.now?(nt(e,n,"refused",t.now,{reason:"expired"}),Fe(e,n.target_durable_id,n.delivery_id),{kind:"lost",state:"refused"}):($e(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]),Fe(e,n.target_durable_id,n.delivery_id),{kind:"claimed",row:Ce(e,t.delivery_id)})})}(l,u);case"record_outcome":return await async function(e,t){return await He(e,"record_outcome",()=>{let n=Ce(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?nt(e,n,"queued",t.now):"refused"===i.kind?nt(e,n,"refused",t.now,{reason:i.reason}):($e(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&&nt(e,n,i.kind,t.now)),{kind:"claimed",row:Ce(e,t.delivery_id)}})}(l,u);case"refuse_queued":return await async function(e,t){return await He(e,"refuse",()=>{let n=Ce(e,t.delivery_id);return void 0!==n&&"queued"===n.state&&(nt(e,n,"refused",t.now,{reason:t.reason}),Fe(e,n.target_durable_id,n.delivery_id),!0)})}(l,u);case"complete_receipt":return await rt(l,u);case"abandon_receipt":return await st(l,u);case"delivery_view":return dt(l,u);case"delivery_receipt":return ot(l,u);case"recover_delivery":return await at(l,u);case"list":return function(e,t){return void 0!==t.target_durable_id?Ie(e,"target_durable_id = ?",[t.target_durable_id],"seq"):void 0!==t.root_id?Ie(e,"root_id = ?",[t.root_id],"created_at, seq"):Ie(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 ${Re}`,[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 It(l,u);case"tool_receipt_settle":return await async function(e,t){return await He(e,"tool_receipt_settle",()=>{let n="result"in t;return 1===$e(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 Ct(l,u);case"unbind":return await Ut(l,u);case"rebind":return await Dt(l,u);case"list_bindings":return await Mt(l,u);case"binding_view":return await Ht(l,u);case"register_incarnation":return await async function(e,t){await He(e,"register_incarnation",()=>{$e(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 He(e,"clear_endpoint",()=>{$e(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 jt(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 Gt(l,u);case"ack_outbox":return await Bt(l,u);case"claim_answer":return await Kt(l,u);case"release_answer":return await Vt(l,u);case"confirm_answer":return await Zt(l,u);case"mark_prior_delivered":return await zt(l,u);case"close_question":return await async function(e,t){return await He(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)$e(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)]),Nt(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 fr(e){let t=tr?.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=>or.set(e,t));mr({kind:"paused",hook:e}),await n}process.on("uncaughtException",pr),process.on("unhandledRejection",pr),er.on("message",e=>{if("provenance_resolved"===e.type){let t=_r.get(e.id);return _r.delete(e.id),void(e.ok?t?.resolve(e.value):t?.reject(Error(e.error)))}if("resolution"===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("resume"===e.type)return or.get(e.hook)?.(),void or.delete(e.hook);sr.push(e),async function(){if(ar)return;ar=!0;try{for(let e=sr.shift();void 0!==e;e=sr.shift())try{let t=await gr(e.op,e.args);er?.postMessage({type:"response",id:e.id,ok:!0,value:t})}catch(t){er?.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{ar=!1}}()});