omo-ai 5.1.32 → 5.1.33

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.
@@ -1,5 +1,5 @@
1
1
  {
2
- "_comment": "Derived from @code-yeongyu/senpi 2026.10.12 builtinProviders(). builtinProviderIds and oauthProviderIds are the engine registry verbatim; providers maps a source harness id onto the omo provider that serves the same endpoint; oauthLogins maps a source OAuth id onto the omo provider to run /login for. Re-derive all four whenever the senpi pin changes.",
2
+ "_comment": "Derived from @code-yeongyu/senpi 2026.10.13 builtinProviders(). builtinProviderIds and oauthProviderIds are the engine registry verbatim; providers maps a source harness id onto the omo provider that serves the same endpoint; oauthLogins maps a source OAuth id onto the omo provider to run /login for. Re-derive all four whenever the senpi pin changes.",
3
3
  "builtinProviderIds": [
4
4
  "alibaba-token-plan",
5
5
  "amazon-bedrock",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omo-ai",
3
- "version": "5.1.32",
3
+ "version": "5.1.33",
4
4
  "type": "module",
5
5
  "description": "OmO Native - the standalone omo command with the OMO extension built in: bun add -g omo-ai",
6
6
  "bin": {
@@ -17,7 +17,7 @@
17
17
  "postinstall": "node bin/senpi-patch.mjs"
18
18
  },
19
19
  "dependencies": {
20
- "@code-yeongyu/senpi": "2026.10.12"
20
+ "@code-yeongyu/senpi": "2026.10.13"
21
21
  },
22
22
  "repository": {
23
23
  "type": "git",
@@ -7,6 +7,22 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [5.1.33] - 2026-10-13
11
+
12
+ **omo runs on senpi 2026.10.13: a busy host gives memory back when its sessions end.** An RPC host serving many sessions used to keep the heap of every session it had run until it exited, so a long day of terminal-heavy work held its peak footprint; it now returns freed heap as sessions drop ([senpi#3240](https://github.com/code-yeongyu/senpi/pull/3240), [senpi#3221](https://github.com/code-yeongyu/senpi/pull/3221)). Tool calls through DeepSeek's official API, and gateways that forward to it, stop failing with `400 Invalid schema ... got 'type: null'`, because every tool schema now declares a root `type: "object"` ([senpi#3250](https://github.com/code-yeongyu/senpi/pull/3250)). The Claude subscription lane runs Claude Code 2.1.296 ([senpi#3258](https://github.com/code-yeongyu/senpi/pull/3258)), the model catalog is refreshed from the live providers ([senpi#3248](https://github.com/code-yeongyu/senpi/pull/3248)), large eval data cells no longer stall the shared host ([senpi#3206](https://github.com/code-yeongyu/senpi/pull/3206)), and RPC clients see a scheduled goal continuation and can run it now ([senpi#3208](https://github.com/code-yeongyu/senpi/pull/3208)). Full notes: [senpi 2026.10.13](https://github.com/code-yeongyu/senpi/releases/tag/v2026.10.13).
13
+
14
+ **Daemon-hosted background tasks keep running when their parent exits or starts a new session.** The parent detaches without aborting their turns. On `/new` or exit, one notice names the old session and the `omo --resume` command to collect results; children stay owned by that session. Local in-process and stdio children retain their shutdown behavior. ([#8517](https://github.com/code-yeongyu/oh-my-openagent/issues/8517), [#10018](https://github.com/code-yeongyu/oh-my-openagent/issues/10018))
15
+
16
+ **A child that stops answering no longer hangs a task indefinitely.** Stdio RPC requests have deadlines, and both process runners keep one heartbeat in flight. Three missed ten-second probes end a running child as `child-unresponsive`, preserve its transcript, and name how to inspect and rerun it in `task_output`. The last successful heartbeat appears as `last_seen_at` in the live task snapshot. ([#10017](https://github.com/code-yeongyu/oh-my-openagent/issues/10017))
17
+
18
+ **Resuming a background task no longer waits for a free slot.** When its concurrency group is full, resuming a finished background task now returns at once as pending and sends the follow-up when a slot frees, instead of blocking the call. A second resume of the same task while one is queued is refused, cancelling a queued resume releases nothing it didn't hold, and a fallback retry keeps the latest follow-up prompt. Thanks to @imadal1n. ([#9985](https://github.com/code-yeongyu/oh-my-openagent/pull/9985))
19
+
20
+ **A task child started as its own process never receives its fallback chain after its first prompt.** When the engine answered the capability check only after the chain deadline, the runner still sent `set_retry_fallback` once the first prompt was already out; it now drops the chain at the deadline, and the child keeps the manager's fallback with the usual "no answer" warning. This was the intermittent windows-latest test failure. ([#9582](https://github.com/code-yeongyu/oh-my-openagent/issues/9582), [#10087](https://github.com/code-yeongyu/oh-my-openagent/pull/10087))
21
+
22
+ **ulw-execute stops a checkpoint that keeps failing instead of retrying it for days.** After the same failure twice in a row, a third failed attempt, or four hours open, the checkpoint and every checkpoint that depends on it are marked blocked (`[~]`) with the gap left, recorded in the ledger and the final report, and the run moves on to the rest of the plan. A broken test harness gets one repair attempt, and work found while a checkpoint is open is queued after it unless it blocks that checkpoint. ([#10051](https://github.com/code-yeongyu/oh-my-openagent/issues/10051))
23
+
24
+ **Mass research plans its whole collection before it starts instead of one wave at a time.** `mass ulw research` now defines every angle as a harvest, expand and verify chain that passes its findings to the next step through a file, so a fast angle reaches verification while slow ones are still harvesting, and leads that are still open join each cluster of angles as soon as that cluster settles. The mass-ulw and ulw-execute skills no longer say a single node's completion wakes the session; only a finished or paused run does. ([#10049](https://github.com/code-yeongyu/oh-my-openagent/issues/10049))
25
+
10
26
  ## [5.1.32] - 2026-10-12
11
27
 
12
28
  **5.1.32 is the release that 5.1.31 was meant to be: 5.1.31 never reached npm.** Two checks in the release pipeline stopped it before any package was published, one on the macOS Intel desktop engine and one on the Linux musl builds. omo itself did not change between the two, so every entry below is new to anyone upgrading from 5.1.30. The notarization check now waits for Apple's ticket to reach Gatekeeper, and the musl smoke no longer reports an exited host supervisor as a leak. ([#10081](https://github.com/code-yeongyu/oh-my-openagent/pull/10081), [#10082](https://github.com/code-yeongyu/oh-my-openagent/pull/10082))
@@ -388,7 +404,6 @@ Thanks also to @Dante-dan ([#9575](https://github.com/code-yeongyu/oh-my-openage
388
404
 
389
405
  **Memory's `/doctor` checks load on first use** instead of with the extension, so startup loads less; the command behaves the same. Thanks to @Dante-dan. ([#9520](https://github.com/code-yeongyu/oh-my-openagent/pull/9520))
390
406
 
391
-
392
407
  ## [5.1.14] - 2026-10-03
393
408
 
394
409
  **Permission checks can no longer switch themselves off.** Up to 5.1.13, a failure while the permission system started (a misspelled `permissionPreset` in settings or on the command line, a `null` permission rule, or an unreadable approvals file) left every tool call running with no permission check, and nothing said so. 5.1.14 runs on senpi 2026.10.5, which refuses tool calls with `Permission setup failed: <reason>` until the setting is fixed. If you can't update yet, check that `permissionPreset` names a preset that exists and that no permission rule is `null`. ([senpi#2617](https://github.com/code-yeongyu/senpi/issues/2617), [senpi#2618](https://github.com/code-yeongyu/senpi/pull/2618))
@@ -1,2 +1,2 @@
1
- // omo:RAD7rk_h8eBimpJJldFh7JB3VHhdCsBc4AM9oM2X2FE:5LLt7853QZ0R275mM__hYa8UeDUj-ySee_PqmOY8R7U
1
+ // omo:CP_BuSfsmGNJ934-PbmQrjs2tchXa1gwTTdSHDHAvIo:5LLt7853QZ0R275mM__hYa8UeDUj-ySee_PqmOY8R7U
2
2
  function e(e){return e.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;")}function r(r,s){let i=[`<operating-rules version="${e(r).replaceAll('"',"&quot;")}">`];for(let r of s)i.push(`- ${e(r)}`);return i.push("</operating-rules>"),i.join("\n")}function s(e,r){if(null===e||"object"!=typeof e||Array.isArray(e))throw Error(`${r} must be an object`);return e}function i(e,r){let s=e[r];if("string"!=typeof s||0===s.length)throw Error(`${r} must be a non-empty string`);return s}function o(e){let r=s(e,"a rules target"),o=i(r,"session_durable_id"),n=r.binding_id;if(null!=n&&"string"!=typeof n)throw Error("binding_id must be a string");let t=r.behavioral;if(null===t)return{session_durable_id:o,binding_id:n??void 0,behavioral:null};if(!Array.isArray(t)||!t.every(e=>"string"==typeof e))throw Error("behavioral must be an array of rule texts, or null to clear the session's rules");return{session_durable_id:o,binding_id:n??void 0,behavioral:t}}function n(e,r){let o=i(s(r,"blockForSession args"),"session_durable_id"),n=e.one(["version","block"],"SELECT version, block FROM gateway_rules_blocks WHERE session_durable_id = ?",[o]);return void 0===n?null:{version:String(n.version),block:String(n.block)}}function t(e,r){let o=i(s(r,"sessionsWithRules args"),"scope");return{sessions:e.all(["session_durable_id","version"],"SELECT session_durable_id, version FROM gateway_rules_blocks WHERE scope = ?",[o],"session_durable_id").map(e=>({session_durable_id:String(e.session_durable_id),version:String(e.version)}))}}async function l(n,t){let l=s(t,"rulesCommitted args"),a=i(l,"scope"),d=i(l,"version"),u=l.now??Date.now();if("number"!=typeof u||!Number.isFinite(u))throw Error("now must be a finite timestamp");if(!Array.isArray(l.targets))throw Error("targets must be an array");let _=[];for(let s of l.targets){let i=o(s);if(null===i.behavioral){let e=n.exec("DELETE FROM gateway_rules_blocks WHERE session_durable_id = ?",[i.session_durable_id]);_.push({session_durable_id:i.session_durable_id,outcome:e>0?"removed":"absent"});continue}let t=r(d,i.behavioral),l=n.exec("INSERT INTO gateway_rules_blocks (session_durable_id, scope, version, block, updated_at) VALUES (?, ?, ?, ?, ?)\n ON CONFLICT(session_durable_id) DO UPDATE SET scope = excluded.scope, version = excluded.version, block = excluded.block, updated_at = excluded.updated_at\n WHERE gateway_rules_blocks.version != excluded.version",[i.session_durable_id,a,d,t,u]);if(void 0===i.binding_id){_.push({session_durable_id:i.session_durable_id,outcome:l>0?"updated":"unchanged"});continue}let c=await n.enqueue({binding_id:i.binding_id,event_id:`rules_changed:${a}:${d}:${i.session_durable_id}`,text:[`<operating-rules-changed scope="${e(a).replaceAll('"',"&quot;")}" version="${e(d).replaceAll('"',"&quot;")}">`,"The operating rules for this gateway scope changed; this session's system prompt carries the new block from its next turn.","</operating-rules-changed>"].join("\n"),mode:"follow_up"});_.push({session_durable_id:i.session_durable_id,outcome:l>0?"updated":"unchanged",delivery:"ok"===c.kind?{kind:"ok",delivery_id:c.delivery_id,deduplicated:!0===c.deduplicated}:{kind:"error",error:c.error}})}return{scope:a,version:d,outcomes:_}}export{n as blockForSession,l as rulesCommitted,t as sessionsWithRules};
@@ -1,2 +1,2 @@
1
- // omo:b_5bOr831iKpohD7wJlWZjgzo2fRECUpNWyHBvkBv4s:AEOT6m7SurHmPdK6dTI4x4uLX382bQFFQlmbrTTmOiE
1
+ // omo:txxyHZ-40QWTgMzOyWaNyYoDa8JMueUowib_ZWCSxWg:AEOT6m7SurHmPdK6dTI4x4uLX382bQFFQlmbrTTmOiE
2
2
  import{chmodSync as e,closeSync as t,existsSync as i,mkdirSync as n,openSync as r}from"node:fs";import{join as s}from"node:path";import{setTimeout as a}from"node:timers/promises";import{parentPort as o}from"node:worker_threads";function d(e,t,i){return Object.assign(Error(`gateway store lock wait exceeded: ${e} waited ${t} ms for the write lock (limit ${i} 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,i)=>{let n=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[,i,n,r,s,a,o]=t,d=m.indexOf(i);return d<0?null:Date.UTC(Number(o),d,Number(n),Number(r),Number(s),Number(a))/1e3}(i):null;t(null===n?null:`${g}${n}`)})})}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 i,n=t,r=e[t];if(r<=" ")for(i="space";t<e.length&&e[t]<=" ";)t++;else if("-"===r&&"-"===e[t+1])for(i="comment";t<e.length&&"\n"!==e[t];)t++;else if("/"===r&&"*"===e[t+1]){for(i="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){i="quoted";let n="["===r?"]":r;for(t++;t<e.length;)if(e[t++]===n){if("["===r||e[t]!==n)break;t++}}else if("?"===r||";"===r)i="?"===r?"parameter":"semicolon",t++;else for(i="text",t++;t<e.length&&e[t]>" "&&!["'",'"',"`","[","?",";","-","/"].includes(e[t]);)t++;yield{kind:i,text:e.slice(n,t)}}}class y{params=[];sinkRows=[];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){this.db.setAuthorizer(e);try{return t()}finally{this.db.setAuthorizer(null)}}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,i=[],n){this.params=i,this.sinkRows=[];try{let i=void 0===n?"0":`row_number() OVER (ORDER BY ${n})`;return this.db.exec(`SELECT gw_sink(${i}, ${e.join(", ")}) FROM (${T(t)}\n)${void 0===n?"":` ORDER BY ${n}`}`),(void 0===n?this.sinkRows:this.sinkRows.toSorted((e,t)=>Number(e[0])-Number(t[0]))).map(t=>Object.fromEntries(e.map((e,i)=>[e,t[i+1]??null])))}finally{this.params=[],this.sinkRows=[]}}one(e,t,i=[]){return this.all(e,t,i)[0]}}function T(e){let t=0,i="";for(let n of h(e))i+="parameter"===n.kind?`gw_p(${t++})`:n.text;return i}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 O,readFileSync as S,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,i){return t===i||function(e,t,i){let n=new Map;for(let t of e){let e=n.get(t.from);void 0===e?n.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===i)return!0;for(let t of n.get(e)??[])r.has(t)||(r.add(t),s.push(t))}return!1}(e,i,t)}var D=5e3,M=864e5,$=6048e5,H=1048576,X=2592e6,W=2592e6,F=256,P="session_released";import{existsSync as j,readFileSync as G}from"node:fs";import{join as B}from"node:path";function J(e){let t=B(e,"mailbox.jsonl");if(j(t))return function(e){let t=e.slice(0,e.lastIndexOf("\n")+1),i=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)){i.clear();for(let e of t.items){let t=Y(e);i.set(t.message_seq,t)}}else if("enqueue"===t.kind){let e=Y(t.item);i.set(e.message_seq,e)}else{if("remove"!==t.kind||"number"!=typeof t.message_seq)throw Error("invalid legacy mailbox event");i.delete(t.message_seq)}}return K([...i.values()])}(G(t,"utf8"));let i=B(e,"mailbox.json");if(!j(i))return null;let n=JSON.parse(G(i,"utf8"));if(!z(n)||!z(n.queues))throw Error(`invalid legacy mailbox state: ${i}`);let r=[];for(let e of Object.values(n.queues)){if(!Array.isArray(e))throw Error(`invalid legacy mailbox queue: ${i}`);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 i=Number(t[1]);return Number.isSafeInteger(i)?i: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 ie=["discord","telegram","slack","notion","feishu","herdr","custom","whatsapp"],ne=["milestone","report","question","completion"],re=["auto","follow_up"],se=31622400,ae=2592e6;function oe(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,i){return Ce(e,"DELETE FROM receipts WHERE principal = ? AND operation = ? AND idempotency_key = ? AND expires_at <= ?",[t.principal,t.operation,t.idempotency_key,i])}function he(e,t,i=0){if(t<(Ee.get(e.sql)??Number.NEGATIVE_INFINITY))return null;let n=function(e,t,i=256){let n=F,r=Ce(e,"DELETE FROM receipts WHERE rowid IN (SELECT rowid FROM receipts WHERE expires_at <= ? LIMIT ?)",[t,i]),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-W,n]),a=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,n]),o=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,n]),d=Ce(e,"DELETE FROM rate_buckets WHERE rowid IN (SELECT rowid FROM rate_buckets WHERE updated_at <= ? LIMIT ?)",[t-4e4,n]),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 ?)`,[oe(t-ae),n]),_=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 ?)",[n]),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 ?)",[n]);return{receipts:r,deliveries:s,causal_edges:a,causal_roots:o,rate_buckets:d,bindings:u,outbox_cursors:_,session_meta:l}}(e,t,Math.max(F-i,0)),r=n.receipts+i>=F||Object.values(n).some(e=>e>=F);return Ee.set(e.sql,r?t:t+36e5),n}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,i,n){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:i,...void 0===n?{}:{details:n}}}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,i,n,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:i,deduplicated:n};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,i="Gateway"){super(`${i} 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 Oe(e,t,i){return{kind:"refused",code:e,message:t,...void 0===i?{}:{details:i}}}function Se(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,i,n){return e.sql.all(ke,`SELECT ${ke.join(", ")} FROM deliveries WHERE ${t}`,i,n).map(Se)}function qe(e,t){return Ae(e,"delivery_id = ?",[t])[0]}function Ce(e,t,i=[]){let n=e.sql.run(t,i);return e.stats.writes+=n,n}function Ie(e,t){if("queued"!==t.state&&"admitting"!==t.state&&"admitted"!==t.state)return 0;let i=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(i?.n??1)}async function Ue(e,t,i){if(void 0!==e.afterCommit)return e.sql.exec("SAVEPOINT gateway_enqueue"),!0;let n=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}),!i)return!1;let s=Date.now()-n;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,i){if(void 0!==e.afterCommit)return await i();await Ue(e,t,!0);try{let t=await i();return e.sql.exec("COMMIT"),t}catch(t){throw De(e),t}}function $e(e,t,i,n){let r=c(e.config.agent_dir,t);R(r,{recursive:!0,mode:448});let s,a=I(r,i);try{s=x(a,k.O_CREAT|k.O_EXCL|k.O_WRONLY,384)}catch(e){if(n&&e instanceof Error&&"code"in e&&"EEXIST"===e.code)return a;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(a,{force:!0})),a}function He(e,t,i){if(void 0!==e.afterCommit)return void e.afterCommit.push(()=>He({...e,afterCommit:void 0},t,i));let n=I(c(e.config.agent_dir,t),i);try{A(n),e.stats.marker_unlinks++}catch(e){if(!(e instanceof Error&&"code"in e&&"ENOENT"===e.code))throw e}}function Xe(e,t){try{return O(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 We(e,t){let i=e.sql.one(["next_seq"],"SELECT next_seq FROM session_meta WHERE durable_id = ?",[t]),n=Number(void 0===i?e.sql.one(["m"],"SELECT COALESCE(MAX(seq), 0) + 1 AS m FROM deliveries WHERE target_durable_id = ?",[t])?.m??1:i.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,n+1]),n}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 Ge extends Error{version;code="gateway_migration_failed";constructor(e,t){super(t),this.version=e,this.name="GatewayMigrationError"}}var Be=new Set([6]);function Je(e,t,i){let n=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,i]);if(void 0!==n)return{args_hash:String(n.args_hash),status:n.status,delivery_id:null===n.delivery_id?null:String(n.delivery_id),owner_instance:String(n.owner_instance),result:null===n.result?null:String(n.result),expires_at:Number(n.expires_at)}}function Ke(e,t,i){if(i.args_hash!==t.receipt.args_hash)return Oe("idempotency_conflict","The idempotency key was already used with different arguments.");if("completed"===i.status&&null!==i.result)return{kind:"replay",result:JSON.parse(i.result)};let n=null===i.delivery_id?void 0:qe(e,i.delivery_id),r=void 0!==n&&("admitted"===n.state||"applied"===n.state||"refused"===n.state);if("prepared"===i.status&&!r&&i.owner_instance===e.config.instance_id)return Oe("idempotency_in_progress","The same delivery is already in progress.");if("prepared"===i.status&&r){let i={...we(n,Ie(e,n),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(i),t.now,t.sender_principal,t.receipt.idempotency_key]),{kind:"replay",result:i}}return"prepared"===i.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]),Oe("idempotency_uncertain","The earlier delivery may or may not reach the target; it is never sent twice.",{delivery_id:i.delivery_id,state:n?.state??null})}async function Ye(e,t){if(!xe.test(t.target_durable_id)||!xe.test(t.delivery_id))return Oe("invalid_arguments","The target session id is not a durable session id.");if(!await Ue(e,"enqueue",!1))return{kind:"busy"};let i=null,n=!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),a=Je(e,t.sender_principal,t.receipt.idempotency_key);if(void 0!==a){let i=Ke(e,t,a);return e.sql.exec(s),n=!0,i}let o=function(e,t){if(null===t.binding)return{expires_at:null};let i=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]),n=null==i?.expires_at?null:Date.parse(String(i.expires_at));return void 0===i||"active"!==i.status||Number(i.revision)!==t.binding.revision||String(i.session_durable_id)!==t.target_durable_id||1!==Number(i.direction_inbound)||null!==n&&n<=t.now?Oe("invalid_arguments","The binding is not active for this session at this revision.",{binding:t.binding.binding_id}):{expires_at:n}}(e,t);if("kind"in o)return De(e),o;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),Oe("queue_full","The target's delivery backlog is full.",{max_messages:128,max_bytes:H});let _=function(e,t){let i;if(null!==t.cause_delivery_id){let n=qe(e,t.cause_delivery_id);if(void 0===n||n.target_durable_id!==t.sender_node||"admitting"!==n.state&&"admitted"!==n.state&&"applied"!==n.state)return Oe("invalid_arguments","The delivery this send continues is not one the sender received.",{guard:"unknown_cause"});i={root_id:n.root_id,hop:n.hop+1,via:[...n.envelope.via,t.sender_node],new_root:!1}}else i={root_id:`root-${N()}`,hop:1,via:[t.sender_node],new_root:!0};if(null!==t.claimed_root_id&&t.claimed_root_id!==i.root_id)return Oe("invalid_arguments","The causal root is derived by the gateway and cannot be chosen by the caller.",{guard:"forged_root"});if(!i.new_root){let n=e.sql.one(["expires_at"],"SELECT expires_at FROM causal_roots WHERE root_id = ?",[i.root_id]);if(void 0===n||Number(n.expires_at)<=t.now)return Oe("loop_detected","This causal chain is older than its lifetime.",{guard:"root_expired",root_id:i.root_id})}if(t.target_durable_id===t.sender_node)return Oe("loop_detected","A session cannot deliver to itself through the gateway.",{guard:"self_send"});if(i.hop>4)return Oe("loop_detected",`This delivery would be hop ${i.hop}; at most 4 are allowed.`,{guard:"hop_limit",hop:i.hop});let n=Number(e.sql.one(["n"],"SELECT COUNT(*) AS n FROM deliveries WHERE root_id = ? AND state != 'refused'",[i.root_id])?.n??0);return n>=64?Oe("loop_detected",`This causal chain already carried ${n} deliveries.`,{guard:"causal_budget",root_id:i.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 = ?",[i.root_id]).map(e=>({from:String(e.from_durable_id),to:String(e.to_durable_id)})),t.sender_node,t.target_durable_id)?Oe("loop_detected","The target already leads back to the sender in this causal chain.",{guard:"cycle",root_id:i.root_id}):i}(e,t);if("kind"in _)return De(e),_;let l=function(e,t){if(null===t.sender_turn)return;let i=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 i.has(t.target_durable_id)||i.size<16?void 0:Oe("overloaded","One turn may reach at most 16 sessions.",{budget:"fanout"})}(e,t)??function(e,t){let i=t.rate_principal??t.sender_principal,n=e.sql.one(["tokens","updated_at"],"SELECT tokens, updated_at FROM rate_buckets WHERE sender = ? AND target_durable_id = ?",[i,t.target_durable_id]),r=void 0===n?8:Math.min(8,Number(n.tokens)+Math.max(0,t.now-Number(n.updated_at))/D);if(r<1)return Oe("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",[i,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:We(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,o.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+X]),i=$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),n=!0,void 0===e.afterCommit&&await e.hook("afterDbCommit"),{kind:"inserted",row:c,queue_position:p}}catch(t){throw n||(De(e),void 0!==e.afterCommit&&(e.afterCommit.length=r),null!==i&&A(i,{force:!0})),t}}function Ve(e,t){if(null===e)return"";let i=t.get(e);if(void 0===i){try{i=S(e,"utf8")}catch(e){if(!(e instanceof Error&&"code"in e&&"ENOENT"===e.code))throw e;i=""}t.set(e,i)}return i}function ze(e,t,i){if(null===e.runtime_instance||null===t)return!1;let n=i().get(e.runtime_instance);return void 0!==n&&t<=n}function Qe(e,t,i){for(let n of Ve(e,i).split("\n")){if(!n.includes(t))continue;let e;try{e=JSON.parse(n)}catch{continue}if("object"!=typeof e||null===e)continue;let i=e;if("custom_message"===i.type&&"session_control_delivery"===i.customType&&i.details?.delivery_id===t)return!0}return!1}function Ze(e){return`${JSON.stringify(e.admitted_by)}#${e.attempt}`}function et(e,t,i,n,r={}){"queued"!==i?"refused"!==i?(Ce(e,"UPDATE deliveries SET state = ?, updated_at = ? WHERE delivery_id = ?",[i,n,t.delivery_id]),"applied"===i&&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,n,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 = ?",[n,t.delivery_id])}async function tt(e,t){let i,n=t.target_durable_id,r=new Map,s=new Map,a=new Map,o=()=>(i??=function(e,t){let i=new Map;for(let n of Ve(e,t).split("\n")){if(!n.includes(P))continue;let e;try{e=JSON.parse(n)}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)&&i.set(r,Math.max(s,i.get(r)??s))}return i}(t.session_path,s),i);for(let i of Ae(e,"target_durable_id = ? AND state IN ('admitting', 'admitted')",[n])){if(null===i.admitted_by||f(i.admitted_by,t.self))continue;let e=JSON.stringify(i.admitted_by),n=a.get(e);void 0===n&&(n=await E(i.admitted_by),a.set(e,n));let d=n||ze(i.admitted_by,i.claimed_at,o)?Qe(t.session_path,i.delivery_id,s)?"applied":"queued":"dual";r.set(i.delivery_id,{fingerprint:Ze(i),to:d})}return!0===e.config.test_hooks.announceBarrier&&e.emit({kind:"barrier",op:"reconcile"}),await Me(e,"reconcile",()=>{let i=new Set(t.ledger.pending),s=new Set(t.ledger.emitted),a=[],o=[];for(let d of Ae(e,`target_durable_id = ? AND state IN ${Re}`,[n],"seq")){let n=d.state;if("queued"!==d.state){if(null!==d.admitted_by&&f(d.admitted_by,t.self))n=s.has(d.delivery_id)?"applied":i.has(d.delivery_id)?"admitted":"queued";else if(null===d.admitted_by)n="queued";else{let e=r.get(d.delivery_id);if(void 0===e||e.fingerprint!==Ze(d)||"dual"===e.to){o.push(d.delivery_id);continue}n=e.to}n!==d.state&&(et(e,d,n,t.now),a.push({delivery_id:d.delivery_id,from:d.state,to:n}))}else d.expires_at<=t.now&&(et(e,d,"refused",t.now,{reason:"expired"}),a.push({delivery_id:d.delivery_id,from:d.state,to:"refused"}))}for(let t of Xe(e,n))"queued"!==e.sql.one(["state"],"SELECT state FROM deliveries WHERE delivery_id = ?",[t])?.state&&He(e,n,t);return{queued:Ae(e,"target_durable_id = ? AND state = 'queued'",[n],"seq"),transitions:a,dual_runtime:o}})}async function it(e,t){return await Me(e,"complete_receipt",()=>1===Ce(e,"UPDATE receipts SET status = 'completed', result = ?, updated_at = ? WHERE principal = ? AND operation = 'deliver' AND idempotency_key = ? AND status = 'prepared' AND owner_instance = ?",[JSON.stringify(t.result),t.now,t.principal,t.idempotency_key,e.config.instance_id]))}async function nt(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 i=Je(e,t.principal,t.idempotency_key);if(void 0===i||i.expires_at<=t.now||null===i.delivery_id)return null;let n=qe(e,i.delivery_id);if(void 0===n)return null;let r="completed"===i.status&&null!==i.result;return{args_hash:i.args_hash,completed:r,result:r?JSON.parse(i.result):null,target_durable_id:n.target_durable_id,binding_revision:n.binding_revision}}async function st(e,t){return await Me(e,"recover_delivery",()=>{let i=Je(e,t.principal,t.idempotency_key);return void 0===i||i.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}},i)})}function at(e,t){let i=qe(e,t);return void 0===i?null:{row:i,queue_position:Ie(e,i)}}function ot(){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,i){return{kind:"refused",code:e,message:t,...void 0===i?{}:{details:i}}}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,i,n){if(void 0!==e.afterCommit)return void e.afterCommit.push(()=>vt({...e,afterCommit:void 0},t,i,n));let r=(a=e.config.agent_dir,_(l(a),"outbox.marker")),s=`${r}.${process.pid}.${dt()}.tmp`;var a;_t(s,JSON.stringify({binding_id:t,cursor:i,written_at:oe(n)}),{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,i,n){let r=`SELECT ${bt.join(", ")} FROM bindings WHERE ${t}${void 0===n?"":` ORDER BY ${n.orderBy} LIMIT ?`}`;return e.sql.all(bt,r,void 0===n?i:[...i,n.limit],n?.orderBy).map(wt)}function Lt(e,t){return Nt(e,"binding_id = ?",[t])[0]}function kt(e,t){let i=e.sql.one(["value"],"SELECT value FROM gateway_meta WHERE key = ?",[t]);if(void 0===i)throw Error(`gateway_meta ${t} is missing`);return String(i.value)}function Rt(e,t){let i=oe(t);Ce(e,"UPDATE bindings SET status = 'expired', updated_at = ? WHERE status = 'active' AND expires_at IS NOT NULL AND expires_at <= ?",[i,i])}function xt(e,t){Ce(e,"DELETE FROM outbox WHERE state = 'acked' AND acked_at IS NOT NULL AND acked_at <= ?",[t-ae]),Ce(e,"DELETE FROM outbox WHERE state = 'pending' AND binding_id IN (SELECT binding_id FROM bindings WHERE status != 'active' AND updated_at <= ?)",[oe(t-ae)])}function Ot(e,t){let i=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!==i)return{args_hash:String(i.args_hash),status:String(i.status),owner_instance:String(i.owner_instance),result:ht(i.result)}}async function St(e,t,i,n,r){return await Me(e,t,()=>{Rt(e,i);let t=null===n?0:fe(e,n,i),s=function(e,t){if(null===t)return;let i=Ot(e,t);return void 0!==i?i.args_hash!==t.args_hash?ft("idempotency_conflict","The idempotency key was already used with different arguments."):"completed"===i.status&&null!==i.result?{...JSON.parse(i.result),kind:"ok",deduplicated:!0}:ft("idempotency_uncertain","An earlier call under this key did not record its outcome."):void 0}(e,n);if(void 0!==s)return s;let a=r();return"ok"===a.kind&&function(e,t,i,n){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(n),i,i,i+X])}(e,n,i,{...a,deduplicated:!1}),he(e,i,t),"ok"===a.kind?{...a,deduplicated:!1}:a})}async function At(e,t){return await Me(e,"tool_receipt_begin",()=>{let i=fe(e,t,t.now),n=function(e,t){let i=Ot(e,t);if(void 0===i)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+X]),{kind:"accepted"};if(i.args_hash!==t.args_hash)return{kind:"conflict"};if("completed"===i.status)return{kind:"replay",result:null===i.result?null:JSON.parse(i.result)};if("prepared"===i.status&&i.owner_instance===e.config.instance_id)return{kind:"in_progress"};"prepared"===i.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 n=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(n?.error_note)}}(e,t);return he(e,t.now,i),n})}async function qt(e,t){let i=t.binding;return await St(e,"bind",t.now,t.receipt,()=>{let n=Nt(e,"platform = ? AND account_id = ? AND chat_id = ? AND thread_id = ? AND status = 'active'",[i.platform,i.account_id,i.chat_id,i.thread_id])[0];if(void 0!==n){return ft("binding_conflict",n.session_durable_id===i.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:n.binding_id,revision:n.revision,session:n.session_durable_id})}let r=oe(t.now),s={schema_version:1,binding_id:`bnd-${ee()}`,revision:1,status:"active",platform:i.platform,account_id:i.account_id,chat_id:i.chat_id,thread_id:i.thread_id,root_message_id:i.root_message_id,progress_message_id:i.progress_message_id,session_realm_id:kt(e,"realm_id"),session_durable_id:i.session_durable_id,direction:i.direction,inbound_mode:i.inbound_mode,outbound_events:i.outbound_events,policy_id:i.policy_id,created_at:r,updated_at:r,lease_started_at:r,ttl_seconds:i.ttl_seconds,expires_at:null===i.ttl_seconds?null:oe(t.now+1e3*i.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 St(e,"unbind",t.now,t.receipt,()=>{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});if("active"!==i.status)return{kind:"ok",binding:i,already_closed:!0,in_flight:Ct(e,i.binding_id)};if(i.revision!==t.expected_revision)return ft("stale_revision","The binding changed since that revision.",{binding_id:i.binding_id,revision:i.revision});let n=oe(t.now);return Ce(e,"UPDATE bindings SET status = 'detached', revision = revision + 1, updated_at = ? WHERE binding_id = ? AND revision = ?",[n,i.binding_id,i.revision]),Ce(e,"DELETE FROM completion_arms WHERE binding_id = ?",[i.binding_id]),{kind:"ok",binding:Lt(e,i.binding_id),already_closed:!1,in_flight:Ct(e,i.binding_id)}})}async function Ut(e,t){return await St(e,"rebind",t.now,t.receipt,()=>{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});if("active"!==i.status)return ft("binding_inactive",`The binding is ${i.status}.`,{binding_id:i.binding_id,status:i.status});if(i.revision!==t.expected_revision)return ft("stale_revision","The binding changed since that revision.",{binding_id:i.binding_id,revision:i.revision});if(i.session_durable_id===t.session_durable_id)return ft("invalid_arguments","The binding is already attached to that session.",{binding_id:i.binding_id});let n=oe(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'",[i.binding_id,i.revision],"seq").map(e=>({delivery_id:String(e.delivery_id),target:String(e.target)}));for(let i of r)Ce(e,"UPDATE deliveries SET state = 'refused', reason = 'binding_closed', updated_at = ? WHERE delivery_id = ? AND state = 'queued'",[t.now,i.delivery_id]),He(e,i.target,i.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,n,n,i.binding_id,i.revision]),Ce(e,"DELETE FROM completion_arms WHERE binding_id = ?",[i.binding_id]),{kind:"ok",binding:Lt(e,i.binding_id),closed:r.map(e=>e.delivery_id)}})}async function Dt(e,t){let i=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 i=t.after;return null===i||Array.isArray(i)&&2===i.length&&i.every(e=>"string"==typeof e)?{v:1,as_of:t.as_of,after:i}:null}catch{return null}}(t.cursor);if(void 0!==t.cursor&&null===i)return ft("cursor_invalid","The bindings cursor is not one this gateway issued.");let n=Math.min(Math.max(t.limit??50,1),200);return await Me(e,"list_bindings",()=>{Rt(e,t.now);let r=i?.as_of??Number(e.sql.one(["m"],"SELECT COALESCE(MAX(rowid), 0) AS m FROM bindings")?.m??0),s=["rowid <= ?"],a=[r],o=[["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,i]of o){let n=t.filter[e];void 0!==n&&(s.push(`${i} = ?`),a.push(n))}null!=i?.after&&(s.push("(created_at > ? OR (created_at = ? AND binding_id > ?))"),a.push(i.after[0],i.after[0],i.after[1]));let d=Nt(e,s.join(" AND "),a,{orderBy:"created_at, binding_id",limit:n+1}),u=d.slice(0,n),_=u.at(-1);return{kind:"ok",bindings:u,next_cursor:d.length>n&&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 i=Number(e.sql.one(["c"],"SELECT last_insert_rowid() AS c")?.c);return vt(e,t.binding.binding_id,i,t.now),i}async function Xt(e,t){return await St(e,"report",t.now,t.receipt,()=>{let i=null===t.binding_id?function(e,t,i,n){let r=[...new Set(i.flatMap(i=>{let n=e.sql.one(["binding_id"],"SELECT binding_id FROM deliveries WHERE delivery_id = ? AND target_durable_id = ?",[i,t]),r=ht(n?.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)),[a,...o]=r;if(void 0!==a&&o.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!==a&&n&&s.some(e=>e!==a))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!==a)return{binding_id:a};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 i)return i;let n=i.binding_id,r=Lt(e,n);if(void 0===r)return ft("not_found","No binding has this id.",{binding_id:n});if(r.session_durable_id!==t.session_durable_id)return ft("scope_denied","The binding is attached to another session.",{binding_id:n});if("active"!==r.status)return ft("binding_inactive",`The binding is ${r.status}.`,{binding_id:n,status:r.status});if(!r.direction.outbound)return ft("unsupported","The binding carries no outbound direction.",{binding_id:n,direction:r.direction});if(!r.outbound_events.includes(t.event))return ft("unsupported",`The binding is not subscribed to ${t.event} events.`,{binding_id:n,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:n,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,n,r.revision,t.text,t.now]);let i=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:i}}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 i=$t(e,t.session_durable_id),a=function(e,t){let i={b:t.binding_id,r:t.revision,s:t.session_durable_id,i:t.incarnation,q:t.ui_request_id,n:ee()},n=pe(JSON.stringify(i));return`${me}.${n}.${be(e,n)}`}(kt(e,"token_secret"),{binding_id:n,revision:r.revision,session_durable_id:t.session_durable_id,incarnation:i,ui_request_id:t.ui_request_id}),o=Ht(e,{binding:r,event:"question",text:t.text,now:t.now,reply_token:a,ui_request_id:t.ui_request_id,...null===t.ui_request_kind?{}:{ui_request_kind:t.ui_request_kind},incarnation:i});return xt(e,t.now),{kind:"ok",...s,cursor:o,reply_token:a,armed:!1,arm_seq:null}}let a=Ht(e,{binding:r,event:t.event,text:t.text,now:t.now});return xt(e,t.now),{kind:"ok",...s,cursor:a,reply_token:null,armed:!1,arm_seq:null}})}async function Wt(e,t){return await Me(e,"emit_completions",()=>{Rt(e,t.now);let i=["arm_seq","binding_id","revision","text"],n=void 0===t.through_arm_seq?e.sql.all(i,"SELECT arm_seq, binding_id, revision, text FROM completion_arms WHERE session_durable_id = ?",[t.session_durable_id],"arm_seq"):e.sql.all(i,"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 n)Ce(e,"DELETE FROM completion_arms WHERE arm_seq = ?",[Number(t.arm_seq)]),r.set(String(t.binding_id),t);let s=[];for(let i of[...r.values()].toSorted((e,t)=>String(e.binding_id)<String(t.binding_id)?-1:1)){let n=Lt(e,String(i.binding_id));void 0!==n&&"active"===n.status&&n.revision===Number(i.revision)&&n.session_durable_id===t.session_durable_id&&(n.direction.outbound&&n.outbound_events.includes("completion")&&s.push({binding_id:n.binding_id,cursor:Ht(e,{binding:n,event:"completion",text:String(i.text),now:t.now,outcome:t.outcome})}))}return s}).then(i=>(e.emit({kind:"completions_emitted",session_durable_id:t.session_durable_id,cursors:i.map(e=>e.cursor)}),i))}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 i=Math.min(Math.max(t.limit??100,1),500);return await Me(e,"read_outbox",()=>{Rt(e,t.now),xt(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 r=Ft(e,n.binding_id),s=t.after_cursor??r,a=e.sql.all(Et,`SELECT ${Et.join(", ")} FROM outbox WHERE binding_id = ? AND cursor > ?${t.pendingOnly?" AND state = 'pending'":""} ORDER BY cursor LIMIT ?`,[n.binding_id,s,i],"cursor").map(e=>function(e,t){let i=e.event_kind;return{cursor:Number(e.cursor),binding_id:String(e.binding_id),revision:Number(e.revision),event:i,text:String(JSON.parse(String(e.payload)).text??""),state:e.state,created_at:oe(Number(e.created_at)),edit_message_id:"milestone"===i?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,n));return he(e,t.now),{kind:"ok",binding_id:n.binding_id,revision:n.revision,status:n.status,rows:a,next_cursor:a.at(-1)?.cursor??s,acked_cursor:r}})}async function jt(e,t){return await Me(e,"ack_outbox",()=>{Rt(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 n=Ft(e,i.binding_id);if(t.cursor<=n)return{kind:"ok",binding_id:i.binding_id,acked_cursor:n,changed:!1};if(void 0===e.sql.one(["cursor"],"SELECT cursor FROM outbox WHERE binding_id = ? AND cursor = ?",[i.binding_id,t.cursor])){let n=Number(e.sql.one(["m"],"SELECT COALESCE(MAX(cursor), 0) AS m FROM outbox WHERE binding_id = ?",[i.binding_id])?.m??0);return ft("cursor_invalid",t.cursor>n?"The cursor is past the newest outbox row of this binding.":"The cursor names no outbox row of this binding.",{newest:n})}return Ce(e,"UPDATE outbox SET state = 'acked', acked_at = ? WHERE binding_id = ? AND cursor <= ? AND state = 'pending'",[t.now,i.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",[i.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,i.binding_id,t.cursor]),"milestone"===e.sql.one(["event_kind"],"SELECT event_kind FROM outbox WHERE binding_id = ? AND cursor = ?",[i.binding_id,t.cursor])?.event_kind&&null===i.progress_message_id&&Ce(e,"UPDATE bindings SET progress_message_id = ?, updated_at = ? WHERE binding_id = ?",[t.provider_message_id,oe(t.now),i.binding_id])),{kind:"ok",binding_id:i.binding_id,acked_cursor:t.cursor,changed:!0}})}var Gt="The session no longer waits for this question (answered or closed elsewhere)";async function Bt(e,t){return await Me(e,"claim_answer",()=>{Rt(e,t.now);let i=function(e,t){let i=t.split(".");if(3!==i.length||i[0]!==me)return null;let n=Buffer.from(be(e,i[1])),r=Buffer.from(i[2]);if(n.length!==r.length||!te(n,r))return null;try{let e=JSON.parse(Buffer.from(i[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===i)return ft("invalid_arguments","This is not a reply token this gateway issued.");if(i.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 n=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,i.binding_id]);if(void 0===n)return ft("not_found","The question this token belongs to is no longer in the outbox.");let r="answered"===n.question_state&&"delivered"!==n.answer_state,s=r&&Number(n.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(n.cursor)});if("answered"===n.question_state&&!s)return ft("already_answered",null===n.answer&&"delivered"===n.answer_state?`${Gt}.`:"This question was already answered.",{cursor:Number(n.cursor)});let a="string"==typeof(d=n.ui_request_kind)&&lt.includes(d)?n.ui_request_kind:null,o=mt(a,t.answer);var d;if(!o.ok)return ft("invalid_arguments",o.reason,{ui_request_kind:a});let u=Lt(e,i.binding_id);return void 0===u||"active"!==u.status||u.revision!==i.revision||u.session_durable_id!==i.session_durable_id||$t(e,i.session_durable_id)!==i.incarnation||ht(n.ui_request_id)!==i.ui_request_id?ft("stale_token","The binding or the session changed since the question was asked.",{binding_id:i.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:i.session_durable_id,ui_request_id:i.ui_request_id,ui_request_kind:a,cursor:Number(n.cursor),claimed_at:t.now,taken_over:s?{answer:ht(n.answer),answered_at:null===n.answered_at||void 0===n.answered_at?null:Number(n.answered_at),answered_by:Tt(n.answered_by)}:null})})}function Jt(e,t,i){let n=e.sql.one(["cursor","binding_id"],"SELECT cursor, binding_id FROM outbox WHERE reply_token = ?",[t]);void 0!==n&&vt(e,String(n.binding_id),Number(n.cursor),i)}async function Kt(e,t){return await Me(e,"release_answer",()=>{let i=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 i&&Jt(e,t.reply_token,t.claimed_at),i})}async function Yt(e,t){return await Me(e,"mark_prior_delivered",()=>{let i=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 i&&Jt(e,t.reply_token,t.claimed_at),i})}async function Vt(e,t){return await Me(e,"confirm_answer",()=>{let i=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 i&&Jt(e,t.reply_token,t.claimed_at),i})}import{extname as zt}from"node:path";var Qt=0,Zt=1,ei=1,ti=2,ii=9,ni=10,ri=11,si=18,ai=20,oi=21,di=23,ui=26,_i=27,li=31,ci=33;class pi extends Error{code="extension_schema_violation"}var gi=["type","name","tbl_name","sql"],mi=e=>e.replace(/[A-Z]/g,e=>e.toLowerCase()),bi=e=>`${String(e.type)}:${mi(String(e.name))}`;function Ei(e){return{objects:e.all(gi,"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=>[bi(e),null===e.owner?null:String(e.owner)]))}}function fi(e,t,i,n){let r=new Map(i.objects.map(e=>[bi(e),e])),s=new Map(n.objects.map(e=>[bi(e),e])),a=[...new Set([...r.keys(),...s.keys()])].filter(e=>JSON.stringify(r.get(e))!==JSON.stringify(s.get(e)));for(let e of a){let o=r.get(e),d=s.get(e);if(void 0!==o&&i.owners.get(e)!==t)throw new pi(`Extension ${t} changed an object it does not own: ${String(o.name)}.`);if(void 0===d)continue;if("trigger"===d.type||"view"===d.type)throw new pi("Store extensions cannot create triggers or views.");let u=mi(String(d.name));if(("index"!==d.type||null!==d.sql||!u.startsWith(`sqlite_autoindex_${mi(String(d.tbl_name))}_`))&&!u.startsWith(`${t}_`)||i.owners.has(e)&&i.owners.get(e)!==t)throw new pi(`Extension ${t} created an object outside its namespace: ${String(d.name)}.`);if("index"===d.type){let e=`table:${mi(String(d.tbl_name))}`,o=!r.has(e)&&s.has(e)&&a.includes(e);if(i.owners.get(e)!==t&&n.owners.get(e)!==t&&!o)throw new pi(`Extension ${t} indexed a table it does not own: ${String(d.tbl_name)}.`)}}for(let i of a){let n=r.get(i),a=s.get(i);void 0!==n&&e.run("DELETE FROM extension_objects WHERE type = ? AND name = ? COLLATE NOCASE AND owner = ?",[String(n.type),String(n.name),t]),void 0!==a&&e.run("INSERT INTO extension_objects (type, name, owner) VALUES (?, ?, ?) ON CONFLICT(type, name) DO UPDATE SET owner = excluded.owner",[String(a.type),mi(String(a.name)),t])}}function hi(e,t,i){let n,r,s=Ei(e),a=new Map(s.owners),o=new Set(s.objects.filter(e=>"trigger"===e.type||"view"===e.type).map(e=>mi(String(e.name)))),d=(e,i)=>null!==i&&a.get(`${e}:${i}`)===t,u=(e,i,n=!1)=>!(null===i||!n&&!i.startsWith(`${t}_`)||a.has(`${e}:${i}`))&&(a.set(`${e}:${i}`,t),!0),_=!1,l=Qt,c=e=>(r=`Extension ${t} does not own ${e??"this SQLite operation"}.`,Zt);try{return e.authorized((e,t,i,r,s)=>{let a=null===t?null:mi(t),p=null===i?null:mi(i),g=null===r?null:mi(r),m=null===s?null:mi(s);if(null!==m&&o.has(m))return c(m);switch(e){case ti:return n="create","main"===g&&u("table",a)?l:c(a);case ei:return n="create","main"===g&&d("table",p)&&u("index",a,!0===a?.startsWith(`sqlite_autoindex_${p}_`))?l:c(a);case ri:return n="drop","main"===g&&d("table",a)?l:c(a);case ni:return n="drop","main"===g&&d("index",a)&&d("table",p)?l:c(a);case ui:return n="alter","main"===a&&d("table",p)?l:c(p);case _i:return"main"===g&&d("index",a)?l:c(a);case ai:case si:case di:case ii:return"sqlite_master"===a||"sqlite_temp_master"===a?(e===di&&"sql"===p&&(_=!0),e!==ai||"alter"===n||"drop"===n||"create"===n&&_&&"rowid"===p?l:c(a)):"alter"!==n||"sqlite_sequence"!==a||"name"!==p||e!==ai&&e!==di?("main"===g||null===g&&e===ai&&""===p)&&d("table",a)?l:c(a):l;case oi:case ci:return l;case li:return"load_extension"===p?c(p):l;default:return c(a)}},i)}catch(e){if(void 0!==r)throw new pi(r);throw e}}import{createHash as yi,randomUUID as Ti}from"node:crypto";var vi={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 wi(e,t,i){return{kind:"error",error:Te(e,t,vi[e]??"Call thread_list and retry after checking the target.",i)}}function Ni(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},yi("sha256").update(JSON.stringify(t)).digest("hex");var t}function Li(e){let t=!1;for(let i of h(e))if("space"!==i.kind&&"comment"!==i.kind){if(t)throw new pi("An extension SQL call must contain one statement.");"semicolon"===i.kind&&(t=!0)}}var ki=/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/;function Ri(e){return{kind:"refused",code:"invalid_arguments",message:e}}function xi(e,t,i){return"string"!=typeof t||0===t.trim().length?Ri(`author.${e} must be a non-empty string.`):t.length>i?Ri(`author.${e} is longer than ${i} characters.`):ki.test(t)?Ri(`author.${e} carries a control character or line break.`):t.trim()}var Oi={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,i,n){return{kind:"error",error:Te(e,t,n??Oi[e]??"Call thread_bindings and retry after checking the binding.",i)}}function qi(e){return"refused"===e.kind?Ai(e.code,e.message,e.details):e}function Ci(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 i=xi("display",e.display,256);if("string"!=typeof i)return i;if(void 0===e.user_id)return{platform_user_id:t,display:i};let n=xi("user_id",e.user_id,256);return"string"!=typeof n?n:{platform_user_id:t,display:i,user_id:n}}(e);return"kind"in t?Ai("invalid_arguments",t.message):t}function Ii(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 Ui(e,t,i){return void 0===e.idempotency_key?null:{principal:e.principal,operation:t,idempotency_key:e.idempotency_key,args_hash:(n=i,Q("sha256").update(ce(n)).digest("hex"))};var n}function Di(e){let t=e.store,i=e.now??t.now,n=new Set,r=!1;async function s(e){await a(()=>t.releaseAnswer(e))}async function a(e){try{await e()}catch(i){if(!u(i)||r)throw i;let s=function(e,t,i){let n,r=!1,s=()=>{n=setTimeout(()=>{n=void 0,r||e().catch(e=>{r||(u(e)?s():i(e))})},t()),n.unref?.()};return s(),{cancel:()=>{r=!0,clearTimeout(n)}}}(()=>e().then(()=>{n.delete(s)}),()=>t.busyTimeoutMs,()=>{n.delete(s)});n.add(s)}}return{bind:async e=>{let n=function(e){if(!ie.includes(e.platform))return de(`platform must be one of ${ie.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 i=e.direction??{inbound:!0,outbound:!0};if(!0!==i.inbound&&!0!==i.outbound)return de("A binding needs at least one direction: inbound, outbound, or both.");let n=e.inbound_mode??"auto";if(!re.includes(n))return de(`inbound_mode must be one of ${re.join(", ")}.`);let r=e.outbound_events??(i.outbound?ne:[]);if(r.some(e=>!ne.includes(e)))return de(`outbound_events may only name ${ne.join(", ")}.`);if(new Set(r).size!==r.length)return de("outbound_events must not repeat an event.");if(i.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===i.inbound,outbound:!0===i.outbound},inbound_mode:n,outbound_events:ne.filter(e=>r.includes(e)),policy_id:t.policy_id,ttl_seconds:s}}(e.binding);return qi("kind"in n?n:await t.bind({now:i(),receipt:Ui(e,"thread_bind",n),binding:n}))},unbind:async e=>{let n={binding_id:e.binding_id,expected_revision:e.expected_revision};return qi(await t.unbind({now:i(),receipt:Ui(e,"thread_unbind",n),...n}))},rebind:async e=>{let n={binding_id:e.binding_id,expected_revision:e.expected_revision,session_durable_id:e.session_durable_id};return qi(await t.rebind({now:i(),receipt:Ui(e,"thread_rebind",n),...n}))},bindings:async e=>qi(await t.listBindings({now:i(),...e})),report:async e=>{let n=Ii(e.text);if(void 0!==n)return n;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:i(),receipt:Ui(e,"thread_report",r),...r}))},outbox:async e=>qi(await t.readOutbox({now:i(),...e})),ack:async e=>qi(await t.ackOutbox({now:i(),...e})),answer:async n=>{let r=Ii(n.answer);if(void 0!==r)return r;let o=Ci(n.author);if(void 0!==o&&"kind"in o)return o;let d=o??null,u=await t.claimAnswer({now:i(),binding_id:n.binding_id,reply_token:n.reply_token,answer:n.answer,answered_by:d});if("ok"!==u.kind)return qi(u);let _={reply_token:n.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(_),Ai(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,n.answer);if(!m.ok)return await s(_),Ai("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(_),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(!g.delivered){let e=u.taken_over;if(null!==e&&Si.has(g.error))return"question_already_resolved"===g.error?(await a(()=>t.markPriorDelivered({..._,prior:e})),Ai("already_answered",`The session already took an earlier answer to this question (${g.error}).`,{session:u.session_durable_id,reason:g.error})):(await a(()=>t.markPriorDelivered({..._,prior:{answer:null,answered_at:_.claimed_at}})),Ai("already_answered",`${Gt} (${g.error}).`,{session:u.session_durable_id,reason:g.error},"Nothing to do: the session no longer waits for this question."));await s(_);let i="invalid_response"===g.error||"question_incomplete"===g.error;return Ai(i?"invalid_arguments":"stale_token",`The session refused the answer: ${g.error}`,{session:u.session_durable_id,reason:g.error},i?`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 a(()=>t.confirmAnswer(e))}({..._,answer:n.answer,answered_by:d}),{kind:"ok",binding_id:n.binding_id,cursor:u.cursor,session_durable_id:u.session_durable_id,answered_by:d}},inbound:async n=>{if(void 0!==n.mode&&!re.includes(n.mode))return Ai("invalid_arguments",`A binding message is delivered as ${re.join(" or ")}, never ${String(n.mode)}.`,{mode:n.mode},"Send with mode auto or follow_up, or omit it for the binding's inbound_mode.");let r=Ci(n.author);if(void 0!==r&&"kind"in r)return r;let s=await t.bindingView({now:i(),binding_id:n.binding_id});if(null===s)return Ai("not_found","No binding has this id.",{binding_id:n.binding_id});let a={principal:`binding:${s.binding_id}`,idempotency_key:`event:${n.event_id}`},o=await t.deliveryReceipt({now:i(),...a});if(null!==o&&null!==o.binding_revision&&o.args_hash===Ni({target:o.target_durable_id,text:n.text,mode:n.mode??s.inbound_mode,expected_turn_id:null,binding:{binding_id:s.binding_id,revision:o.binding_revision},author:r})){let e=o.completed?{kind:"replay",result:o.result}:await t.recoverDelivery({now:i(),...a,args_hash:o.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=n.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:n.event_id,...void 0===r?{}:{author:r}},binding_id:s.binding_id,binding_revision:s.revision},target:s.session_durable_id,text:n.text,mode:d,all_scope:!0,idempotency_key:`event:${n.event_id}`})},settle:e=>t.emitCompletions({now:i(),...e}),dispose:()=>{r=!0;for(let e of n)e.cancel();n.clear()}}}class Mi extends Error{extension;code="extension_operation_failed";constructor(e){super(`The ${e} extension transaction has ended.`),this.extension=e}}function $i(e,t,i,n){let r,s=!0,a=!1,o=Promise.resolve();function d(e){if(a)throw new Mi(t);if(void 0!==r)throw r;return e()}function u(e){let i=s?o.then(()=>d(e)):Promise.reject(new Mi(t));return o=i.then(()=>{},e=>{r=e}),i}function _(i,n){(()=>{if(!s)throw new Mi(t);if(void 0!==r)throw r})();let a=Ei(e.sql);try{Li(i);let r=hi(e.sql,t,n);return fi(e.sql,t,a,Ei(e.sql)),r}catch(e){throw r=e,e}}let l={now:()=>i,busyTimeoutMs:e.config.busy_timeout_ms,enqueue:t=>d(()=>Ye(e,t)),completeReceipt:t=>d(()=>it(e,t)),abandonReceipt:t=>d(()=>nt(e,t)),deliveryView:async t=>d(()=>at(e,t)),deliveryReceipt:async t=>d(()=>rt(e,t)),recoverDelivery:t=>d(()=>st(e,t)),bind:t=>d(()=>qt(e,t)),unbind:t=>d(()=>It(e,t)),rebind:t=>d(()=>Ut(e,t)),listBindings:t=>d(()=>Dt(e,t)),bindingView:t=>d(()=>Mt(e,t)),report:t=>d(()=>Xt(e,t)),readOutbox:t=>d(()=>Pt(e,{...t,pendingOnly:!0})),ackOutbox:t=>d(()=>jt(e,t)),claimAnswer:t=>d(()=>Bt(e,t)),releaseAnswer:t=>d(()=>Kt(e,t)),confirmAnswer:t=>d(()=>Vt(e,t)),markPriorDelivered:t=>d(()=>Yt(e,t)),emitCompletions:t=>d(()=>Wt(e,t))},c={wake:async()=>{throw Error("An extension enqueue cannot contact a live endpoint.")}},p=function(e){let t=e.store,i=e.now??t.now;return{deliver:async function(n){let r=n.mode??"auto";if("steer"===r&&void 0===n.expected_turn_id)return wi("invalid_arguments","A steer needs expected_turn_id (the target's current turn_epoch).");let s=Buffer.byteLength(n.text);if(s>H)return wi("message_too_large",`The message is ${s} bytes, above the 1048576-byte limit.`);let a=await e.resolve(n.target,{all_scope:n.all_scope});if("error"===a.kind)return a;let o=a.target,d="routable"===o.liveness?o.endpoint:null;if(null===d&&"refuse"===function(e,t,i,n){return"offline"===e?"steer"===t?{kind:"refuse",reason:"turn_conflict"}:{kind:"queued_offline"}:"steer"===t?"mid_turn"!==e?{kind:"refuse",reason:"not_steerable"}:null===i||null===n||i!==n?{kind:"refuse",reason:"turn_conflict"}:{kind:"admit",deliverAs:"steer",expected_turn_id:i,expect:"steered"}:{kind:"admit",deliverAs:"followUp",expect:"idle"===e?"started":"queued"}}("offline",r,n.expected_turn_id??null,null).kind)return wi("turn_conflict","The target has no live turn to steer.",{target:o.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}`,i=e.origin.author;return{principal:t,rate_principal:void 0===i?t:`${t}#author:${i.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}}}(n.sender),_=Ti(),l=n.idempotency_key??`auto:${_}`,c=await t.enqueue({now:i(),delivery_id:_,target_durable_id:o.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:n.root_id??null,origin:u.origin(_),actor:u.actor,body:n.text,mode:r,expected_turn_id:n.expected_turn_id??null,binding:u.binding,receipt:{idempotency_key:l,args_hash:Ni({target:o.durable_id,text:n.text,mode:r,expected_turn_id:n.expected_turn_id??null,binding:u.binding,author:"external"===n.sender.kind?n.sender.origin.author:void 0})},endpoint_kind:d?.kind??null});if("busy"===c.kind)return wi("overloaded","The gateway store is locked by a suspended writer; nothing was sent.",{budget:"store_lock"});if("refused"===c.kind)return wi(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:i(),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 i=!0;try{await e.endpoints.wake(d,[_])}catch{i=!1}let n=await t.deliveryView(_);if(null===n)throw Error(`delivery ${_} vanished after commit`);return await p(we(n.row,n.queue_position,d.kind,!1,!i))}catch(e){throw await t.abandonReceipt({now:i(),principal:u.principal,idempotency_key:l,error_note:e instanceof Error?e.message:String(e)}).catch(()=>!1),e}}}}({store:l,endpoints:c,resolve:async(e,t)=>{let i=await n(e,t);return"error"===i.kind?i:{kind:"ok",target:{...i.target,endpoint:null,liveness:"dead"}}}}),g=Di({store:l,engine:p,endpoints:c,locate:async()=>null});return{tx:{all:(t,i,n,r)=>_(i,()=>{for(let e of t)Li(e);return void 0!==r&&Li(r),e.sql.all(t,i,n,r)}),one:(t,i,n)=>_(i,()=>{for(let e of t)Li(e);return e.sql.one(t,i,n)}),exec:(t,i)=>_(t,()=>e.sql.run(t,i)),enqueue:e=>u(()=>g.inbound(e)),outboxAck:e=>u(()=>g.ack(e)),bind:e=>u(()=>g.bind(e)),unbind:e=>u(()=>g.unbind(e)),rebind:e=>u(()=>g.rebind(e)),bindingFor:t=>u(()=>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:i})),outboxPending:e=>u(()=>g.outbox(e))},cancel:()=>{s=!1,a=!0,g.dispose()},finish:async()=>{if(s=!1,await o,g.dispose(),void 0!==r)throw r}}}function Hi(e,t){return{kind:"refused",code:e,message:t}}function Xi(e){let t=e instanceof Error?e.message:String(e);return e instanceof pi||e instanceof Ne?Hi(e.code,t):u(e)?Hi("gateway_lock_wait_exceeded",t):Hi("extension_operation_failed",t)}class Wi{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 Hi("invalid_arguments","An extension needs a valid namespace and an array of SQL migration steps.");try{!function(e,t){let i=e.all(["name"],"SELECT name FROM extension_objects WHERE owner IS NULL");if(["gateway","thread","sqlite"].includes(t)||i.some(e=>mi(String(e.name)).startsWith(t)))throw new pi(`Extension name ${t} collides with a core namespace.`)}(this.ctx.sql,e.name)}catch(e){return Xi(e)}let i;try{let t=new URL(e.moduleUrl);if("file:"!==t.protocol||![".js",".mjs",".cjs"].includes(zt(t.pathname)))return Hi("extension_import_failed","moduleUrl must name a compiled JavaScript file URL.");i=await(import(e.moduleUrl))}catch(t){return Hi("extension_import_failed",`Cannot import extension ${e.name}: ${t instanceof Error?t.message:String(t)}`)}try{let n=await this.ensure(e,t);return this.registered.set(e.name,{descriptor:e,module:i}),{kind:"ok",value:{version:n}}}catch(t){return t instanceof Ne||this.registered.set(e.name,{descriptor:e,module:i}),Xi(t)}}holds(e){return this.registered.get(e.name)?.descriptor===e}async ensure(e,t){let{name:i,migrations:n}=e;for(;;){let e=await Me(this.ctx,"extension_migrate",()=>{let e=this.ctx.sql.one(["version"],"SELECT version FROM extension_schema WHERE name = ?",[i]),r=Number(e?.version??0);if(r>n.length)throw new Ne(r,n.length,`Extension ${i}`);let s=Ei(this.ctx.sql);if(void 0===e&&s.objects.some(e=>mi(String(e.name)).startsWith(`${i}_`)&&null==s.owners.get(`${String(e.type)}:${mi(String(e.name))}`)))throw new pi(`Namespace ${i} already contains unowned objects.`);if(r===n.length)return void 0===e&&this.ctx.sql.run("INSERT INTO extension_schema (name, version, updated_at) VALUES (?, 0, ?)",[i,t]),{version:r,applied:!1};for(let e of n[r]){Li(e);let t=Ei(this.ctx.sql);hi(this.ctx.sql,i,()=>this.ctx.sql.exec(e)),fi(this.ctx.sql,i,t,Ei(this.ctx.sql))}return fi(this.ctx.sql,i,s,Ei(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",[i,r+1,t]),{version:r+1,applied:!0}});if(!e.applied)return e.version}}async call(e,t,i,n){let r=this.registered.get(e);if(void 0===r)return Hi("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 Hi("extension_unknown_op",`Extension ${e} exports no operation ${t}.`);let a,o=[],d=[];try{await this.ensure(r.descriptor,n),a=await Me(this.ctx,"extension_call",async()=>{let r,a=Ei(this.ctx.sql),u=$i({...this.ctx,afterCommit:o,afterRollback:d},e,n,this.resolveTarget);try{let n=async()=>{try{return await s(u.tx,i)}finally{await u.finish()}},o=new Promise((i,n)=>{r=setTimeout(()=>{u.cancel(),n(Error(`Extension ${e}.${t} exceeded its ${this.ctx.config.lock_wait_max_ms} ms operation budget.`))},this.ctx.config.lock_wait_max_ms)}),d=await Promise.race([n(),o]);return fi(this.ctx.sql,e,a,Ei(this.ctx.sql)),structuredClone(d)}finally{clearTimeout(r),u.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 Xi(t)}await this.ctx.hook("afterDbCommit");for(let t of o)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:a}}}var Fi=o;if(null===Fi)throw Error("the gateway store worker must run as a worker thread");var Pi,ji,Gi,Bi,Ji=[],Ki=new Map,Yi=!1,Vi=1,zi=new Map,Qi=(e,t)=>new Promise((i,n)=>{let r=Vi++;zi.set(r,{resolve:i,reject:n}),Fi.postMessage({type:"resolve",id:r,address:e,request:t})});function Zi(e){en(e instanceof Mi?{kind:"extension_error",extension:e.extension,phase:"stale_transaction",error:e.message}:{kind:"extension_error",extension:Bi??"worker",phase:"async",error:e instanceof Error?e.message:String(e)})}function en(e){Fi?.postMessage({type:"event",event:e})}async function tn(o,u){if("init"===o)return await async function(o){let{config:u}=o,c=l(u.agent_dir);n(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"));ji=new m.DatabaseSync(p,{timeout:u.busy_timeout_ms});let E=new y(ji);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 en({kind:"lock_wait_exceeded",op:"open",waited_ms:t}),d("open",t,u.lock_wait_max_ms);await a(10)}E.exec("PRAGMA synchronous = FULL");for(let t of["-wal","-shm"])i(`${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};Pi={sql:E,config:u,self:h,stats:{writes:0,marker_unlinks:0,transactions:0},emit:en,hook:nn,delay:e=>a(e)};try{await async function(e){if(!(je(e)>=Le.length))for(;;){let t=je(e);if(t>=Le.length)return;let i=Be.has(t),n=i?Number(e.sql.one(["foreign_keys"],"SELECT foreign_keys FROM pragma_foreign_keys")?.foreign_keys??1):1;i&&e.sql.exec("PRAGMA foreign_keys = OFF");try{await Me(e,"migrate",()=>{let n=je(e);if(n===t){for(let t of Le[n])e.sql.exec(t);if(i&&e.sql.all(["parent"],"SELECT parent FROM pragma_foreign_key_check").filter(e=>"bindings"===e.parent).length>0)throw new Ge(n+1,`gateway schema ${n+1} would leave a foreign-key violation referencing bindings; staying at v${n}`);e.sql.exec(`PRAGMA user_version = ${n+1}`)}})}finally{i&&e.sql.exec("PRAGMA foreign_keys = "+(0===n?"OFF":"ON"))}}}(Pi),Gi=new Wi(Pi,Qi);let e=await async function(e,t){let i=0;for(let n of e.config.legacy_mailbox_directories){let r,s=`legacy_mailbox:${n}`;if(void 0!==e.sql.one(["value"],"SELECT value FROM gateway_meta WHERE key = ?",[s]))continue;try{r=J(n)}catch(t){e.emit({kind:"legacy_mailbox_invalid",directory:n,error:t instanceof Error?t.message:String(t)});continue}if(null===r)continue;let a=ot(),o=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));i+=await Me(e,"migrate_legacy",()=>{let i=0;for(let r of d){let s=`legacy-${Pe([n,r.message_seq]).slice(0,32)}`;if(void 0!==qe(e,s))continue;let o=`root-${N()}`,d=`legacy:${n}`;Ce(e,"INSERT INTO causal_roots (root_id, origin_principal, created_at, expires_at) VALUES (?, ?, ?, ?)",[o,d,t,t+$]);let u=Date.parse(r.accepted_at);Fe(e,{delivery_id:s,target_durable_id:r.target,seq:We(e,r.target),sender:d,sender_turn:null,envelope:{origin:{external:{platform:"legacy_mailbox",account_id:a,chat_id:n,thread_id:"@chat",message_id:r.operation_id}},actor:"legacy thread mailbox",via:[d],root_id:o,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:o,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),i++}return Ce(e,"INSERT INTO gateway_meta (key, value) VALUES (?, ?)",[s,JSON.stringify({migrated_at:t,count:i,skipped:o})]),i}),o.length>0&&e.emit({kind:"legacy_mailbox_skipped",directory:n,items:o})}return i}(Pi,o.now);return Pi.stats.writes=0,Pi.stats.transactions=0,Pi.stats.marker_unlinks=0,{self:h,legacy_migrated:e}}catch(e){try{ji.exec("ROLLBACK")}catch{}try{ji.close()}finally{ji=void 0,Pi=void 0,en({kind:"store_closed"})}throw e}}(u);if("close"===o)return ji?.close(),ji=void 0,Pi=void 0,Gi=void 0,null;let c=function(){if(void 0===Pi)throw Error("the gateway store is not open");return Pi}();switch(o){case"extension_register":{let e=u;return Bi=e.extension.name,{result:await(Gi?.register(e.extension,e.now)),retained:!0===Gi?.holds(e.extension)}}case"extension_call":{let e=u;Bi=e.name;try{return await(Gi?.call(e.name,e.op,e.args,e.now))}finally{for(let t of zi.values())t.reject(new Mi(e.name));zi.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 i=qe(e,t.delivery_id);return void 0===i||"queued"!==i.state?{kind:"lost",state:i?.state??null}:i.expires_at<=t.now?(et(e,i,"refused",t.now,{reason:"expired"}),He(e,i.target_durable_id,i.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,i.target_durable_id,i.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 i=qe(e,t.delivery_id);if(void 0===i||"admitting"!==i.state&&"admitted"!==i.state||null===i.admitted_by||!f(i.admitted_by,t.self))return{kind:"lost",state:i?.state??null};let n=t.outcome;return"requeue"===n.kind?et(e,i,"queued",t.now):"refused"===n.kind?et(e,i,"refused",t.now,{reason:n.reason}):(Ce(e,"UPDATE deliveries SET admission_kind = ?, turn_epoch = ?, updated_at = ? WHERE delivery_id = ?",[n.admission_kind,n.turn_epoch,t.now,i.delivery_id]),i.state!==n.kind&&et(e,i,n.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 i=qe(e,t.delivery_id);return void 0!==i&&"queued"===i.state&&(et(e,i,"refused",t.now,{reason:t.reason}),He(e,i.target_durable_id,i.delivery_id),!0)})}(c,u);case"complete_receipt":return await it(c,u);case"abandon_receipt":return await nt(c,u);case"delivery_view":return at(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||Xe(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 i="result"in t;return 1===Ce(e,`UPDATE receipts SET status = ?, ${i?"result":"error_note"} = ?, updated_at = ? WHERE principal = ? AND operation = ? AND idempotency_key = ? AND status = 'prepared' AND owner_instance = ?`,[i?"completed":"uncertain",i?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 i=e.sql.one(["incarnation","endpoint_socket","endpoint_kind"],"SELECT incarnation, endpoint_socket, endpoint_kind FROM session_meta WHERE durable_id = ?",[t]);return void 0===i||"string"!=typeof i.incarnation?null:{incarnation:i.incarnation,endpoint:"string"!=typeof i.endpoint_socket||"tui"!==i.endpoint_kind&&"rpc_host"!==i.endpoint_kind?null:{socket:i.endpoint_socket,kind:i.endpoint_kind}}}(c,u);case"report":return await Xt(c,u);case"emit_completions":return await Wt(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 i=e.sql.one(["s"],"SELECT MAX(arm_seq) AS s FROM completion_arms WHERE session_durable_id = ?",[t])?.s;return null==i?null:Number(i)}(c,u);case"read_outbox":return await Pt(c,u);case"ack_outbox":return await jt(c,u);case"claim_answer":return await Bt(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 i=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 n of i)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(n.cursor)]),vt(e,String(n.binding_id),Number(n.cursor),t.now);return i.length})}(c,u);default:throw Error(`unknown gateway store op: ${o}`)}}async function nn(e){let t=Pi?.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 i=new Promise(t=>Ki.set(e,t));en({kind:"paused",hook:e}),await i}process.on("uncaughtException",Zi),process.on("unhandledRejection",Zi),Fi.on("message",e=>{if("resolution"===e.type){let t=zi.get(e.id);return zi.delete(e.id),void(e.ok?t?.resolve(e.value):t?.reject(Error(e.error)))}if("resume"===e.type)return Ki.get(e.hook)?.(),void Ki.delete(e.hook);Ji.push(e),async function(){if(Yi)return;Yi=!0;try{for(let e=Ji.shift();void 0!==e;e=Ji.shift())try{let t=await tn(e.op,e.args);Fi?.postMessage({type:"response",id:e.id,ok:!0,value:t})}catch(t){Fi?.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{Yi=!1}}()});
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- // omo:TzNDz2qxV1t5xCKfLrlXFSOYPfm0qLf2DnlmLNWXGds:cQsU6oeTqWhDHYt3xMdcS-Hr-C-Quj8T3Ge10sYMQRQ
2
+ // omo:3bgiyy9XdTybqo5a12gb0AV9EW4dQ98Ib8aGu0EV4HM:cQsU6oeTqWhDHYt3xMdcS-Hr-C-Quj8T3Ge10sYMQRQ
3
3
  import{spawn as t}from"node:child_process";import*as e from"node:fs";import*as r from"node:fs/promises";function n(t){if(t instanceof Error&&"code"in t)return"string"==typeof t.code?t.code:void 0}async function i(t){for(let e=0;;e+=1)try{return await t()}catch(t){if("EINTR"!==n(t)||e>=128)throw t}}function o(t){for(let e=0;;e+=1)try{return t()}catch(t){if("EINTR"!==n(t)||e>=128)throw t}}var a=new Set(["EPERM","EBUSY","EACCES"]),s=[10,25,50,100,200,400],c=t=>new Promise(e=>setTimeout(e,t));import{Buffer as l}from"node:buffer";import{constants as u}from"node:fs";function d(t){return"number"==typeof t?0!==(t&u.O_EXCL):"string"==typeof t&&t.toLowerCase().includes("x")}async function f(t,e,r,n){let o="string"==typeof e?l.from(e,r??"utf8"):e,a=0;for(;a<o.length;){n?.throwIfAborted();let{bytesWritten:e}=await i(()=>t.write(o,a));if(e<=0)throw Error(`fs write made no progress at offset ${a}`);a+=e}}function p(t){return"function"==typeof t}function m(t){return(...e)=>i(async()=>t(...e))}function w(t){return(...e)=>o(()=>t(...e))}function h(t,e){let r="async"===e?m:w,n=new Map;return new Proxy(t,{get(t,e){if(n.has(e))return n.get(e);let i=Reflect.get(t,e);if(!p(i))return i;let o=r(i),a=Reflect.get(i,"native");return p(a)&&Object.assign(o,{native:r(a)}),n.set(e,o),o}})}var y=new Set(["stat","sync","datasync","chmod","chown","utimes","truncate"]);var v=h(r,"async");function g(t,e){return async function(t,e,r){let i="win32"===r.platform?r.delaysMs??s:[],o=r.sleep??c;for(let s=0;;s+=1)try{return void await r.rename(t,e)}catch(t){let e=i[s],r=n(t);if(void 0===e||void 0===r||!a.has(r))throw t;await o(e)}}(t,e,{rename:v.rename,platform:process.platform})}var E=h(e,"sync"),{access:b,chmod:S,copyFile:_,cp:I,link:x,lstat:N,mkdir:O,mkdtemp:k,readFile:M,readdir:P,realpath:T,rm:R,rmdir:A,stat:$,unlink:D}=v,{accessSync:L,chmodSync:C,fsyncSync:U,linkSync:q,lstatSync:j,mkdirSync:F,readFileSync:z,readdirSync:B,realpathSync:G,statSync:H,unlinkSync:J,writeFileSync:K,writeSync:Y}=E,{constants:Z,watch:V}=e,W=async(...t)=>{let e=()=>r.open(...t);return function(t){return new Proxy(t,{get(t,e){let r=Reflect.get(t,e);if(!p(r))return r;let o=e=>Reflect.apply(r,t,[...e]);return"close"===e||e===Symbol.asyncDispose?(...t)=>{let e=o(t);return e instanceof Promise?e.catch(t=>{if("EINTR"!==n(t))throw t}):e}:"string"==typeof e&&y.has(e)?(...t)=>{let e=o(t);return e instanceof Promise?e.catch(e=>{if("EINTR"!==n(e))throw e;return i(async()=>o(t))}):e}:(...t)=>o(t)}})}(await(d(t[1]??"r")?e():i(e)))},X=(t,r,n)=>function(t,e,r,n){return d(r)?t(e,r,n):o(()=>t(e,r,n))}(e.openSync,t,r,n??void 0);function Q(t){try{e.closeSync(t)}catch(t){if("EINTR"!==n(t))throw t}}function tt(t){try{return o(()=>e.statSync(t)),!0}catch{return!1}}import{join as et}from"node:path";import{fileURLToPath as rt}from"node:url";import nt from"node:path";import it from"node:path";import{randomUUID as ot}from"node:crypto";import{hostname as at}from"node:os";import{execFile as st}from"node:child_process";var ct=null;function lt(){return ct??=async function(){if("darwin"!==process.platform)return null;try{let{dlopen:t,FFIType:e}=await(import("bun:ffi")),r=t("/usr/lib/libSystem.B.dylib",{proc_pidinfo:{args:[e.i32,e.i32,e.u64,e.ptr,e.i32],returns:e.i32}});return(t,e,n,i,o)=>Number(r.symbols.proc_pidinfo(t,e,n,i,o))}catch{return null}}(),ct}var ut=null;async function dt(t){if("win32"!==process.platform)return null;if(!Number.isSafeInteger(t)||t<=0)return null;ut??=async function(){if("win32"!==process.platform)return null;try{let{dlopen:t,FFIType:e}=await(import("bun:ffi"));return t("kernel32.dll",{OpenProcess:{args:[e.u32,e.i32,e.u32],returns:e.ptr},GetProcessTimes:{args:[e.ptr,e.ptr,e.ptr,e.ptr,e.ptr],returns:e.i32},CloseHandle:{args:[e.ptr],returns:e.i32}}).symbols}catch{return null}}();let e=await ut;if(null===e)return null;let r=e.OpenProcess(4096,0,t);if(null===r||0===r||0n===r)return null;try{let t=new BigUint64Array(1),n=e.GetProcessTimes(r,t,new BigUint64Array(1),new BigUint64Array(1),new BigUint64Array(1)),i=t[0]??0n;return 0===n||0n===i?null:i}finally{e.CloseHandle(r)}}async function ft(t,e){return await new Promise(r=>{st(t,e,{encoding:"utf8",timeout:2e3,windowsHide:!0},(t,e)=>{if(null!==t)return void r(null);let n=e.trim();r(n.length>0?n:null)})})}var pt=function(t,e){let r;return n=>n!==e?t(n):(r??=t(n).then(t=>(null===t&&(r=void 0),t),t=>{throw r=void 0,t}),r)}(async function(t){if("linux"===process.platform)return await async function(t){try{let e=await M(`/proc/${t}/stat`,"utf8"),r=e.lastIndexOf(")");if(r<0)return null;let n=e.slice(r+2).trim().split(/\s+/)[19];return void 0===n?null:`linux-proc-start-ticks:${n}`}catch{return null}}(t);if("darwin"===process.platform||"freebsd"===process.platform){if("dead"===wt(t))return null;let e=await async function(t){if("darwin"!==process.platform)return null;if(!Number.isSafeInteger(t)||t<=0)return null;let e=await lt();if(null===e)return null;let r=new Uint8Array(136),n=0;try{n=e(t,3,0n,r,136)}catch{return null}if(136!==n)return null;let i=new DataView(r.buffer,r.byteOffset,r.byteLength),o=Number(i.getBigUint64(120,!0));return o>0?o:null}(t);if(null!==e)return`proc-start-epoch:${e}`;let r=await ft("/bin/ps",["-o","lstart=","-p",String(t)]);return null===r?null:`ps-lstart:${r.replace(/\s+/g," ")}`}return"win32"===process.platform?await async function(t){if("dead"===wt(t))return null;let e=await dt(t);if(null!==e)return`win32-creation-filetime:${e}`;let r=await ft("powershell.exe",["-NoProfile","-Command",`(Get-Process -Id ${t} -ErrorAction SilentlyContinue).StartTime.ToUniversalTime().ToString('o')`]);return null===r?null:`win32-creation-date:${r}`}(t):null},process.pid);function mt(t){let e=t.indexOf(":");return e<=0?null:t.slice(0,e)}function wt(t){try{return process.kill(t,0),"alive"}catch(t){let e=function(t){if(t instanceof Error&&"code"in t)return"string"==typeof t.code?t.code:void 0}(t);return"ESRCH"===e?"dead":"EPERM"===e?"alive":"unknown"}}function ht(t){return"string"==typeof t&&t.length>0}function yt(t){let e;try{e=JSON.parse(t)}catch{return null}if("object"!=typeof e||null===e||Array.isArray(e))return null;let r=e;return!Number.isInteger(r.pid)||Number(r.pid)<=0?null:ht(r.process_start)&&ht(r.hostname)&&ht(r.nonce)?!ht(r.created_at)||Number.isNaN(Date.parse(r.created_at))?null:ht(r.purpose)&&(void 0===r.run_id||ht(r.run_id))?{pid:Number(r.pid),process_start:r.process_start,hostname:r.hostname,nonce:r.nonce,created_at:r.created_at,purpose:r.purpose,...void 0===r.run_id?{}:{run_id:r.run_id}}:null:null}async function vt(t,e={}){if(0===t.length)throw Error("lock purpose must not be empty");let r=await pt(process.pid);return{pid:process.pid,process_start:r??"unavailable",hostname:at(),nonce:ot(),created_at:(new Date).toISOString(),purpose:t,...void 0===e.runId?{}:{run_id:e.runId}}}function gt(t){if(t instanceof Error&&"code"in t)return"string"==typeof t.code?t.code:void 0}async function Et(t){try{let e=await M(t,"utf8"),r=await $(t,{bigint:!0});return{raw:e,record:yt(e),dev:r.dev,ino:r.ino,mtimeMs:Number(r.mtimeMs)}}catch(t){let e=gt(t);if("ENOENT"===e)return null;if("\\"===it.sep&&"EPERM"===e)return{raw:"",record:null,dev:0,ino:0,mtimeMs:Date.now()};throw t}}function bt(t,e){return t.dev===e.dev&&t.ino===e.ino&&t.mtimeMs===e.mtimeMs&&t.raw===e.raw}async function St(t,e){let r=await Et(t);if(null===r||r.record?.nonce!==e.nonce)return!1;try{return await D(t),!0}catch(t){if("ENOENT"===gt(t))return!1;throw t}}import{randomUUID as _t}from"node:crypto";import It from"node:path";import xt from"node:path";var Nt=new Set;function Ot(t){Nt.add(t)}function kt(t){Nt.delete(t)}var Mt=/\.candidate-(?:(\d+)-)?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Pt(t){let e=Mt.exec(t)?.[1];return void 0!==e&&"dead"===wt(Number(e))}function Tt(t){if(t instanceof Error&&"code"in t)return"string"==typeof t.code?t.code:void 0}function Rt(t,e){try{t.onFailure?.(e)}catch{}}function At(t){if("win32"!==process.platform)return!1;let e=Tt(t);return"EBUSY"===e||"EPERM"===e||"EACCES"===e}var $t=new Map;function Dt(t){$t.delete(t)}var Lt=new Set(["EACCES","EPERM","ENOTSUP"]);function Ct(t){if(t instanceof Error&&"code"in t)return"string"==typeof t.code?t.code:void 0}function Ut(t,e){if(void 0!==e)return e(t);if("win32"!==process.platform)return!1;let r=Ct(t);return"EBUSY"===r||"EPERM"===r||"EACCES"===r}var qt={};function jt(){return qt}async function Ft(t){for(let e=0;e<3;e+=1)try{return await(qt.unlink??D)(t),kt(t),!0}catch(r){if("ENOENT"===Ct(r))return kt(t),!0;if(!Ut(r,qt.isSharingError))throw Ot(t),Dt(It.dirname(t)),r;if(e+1===3)return Ot(t),Dt(It.dirname(t)),!1}return!1}async function zt(t,e){await O(It.dirname(t),{recursive:!0,mode:448});let{candidatePath:r,handle:n}=await async function(t){for(let e=0;;e+=1){let r=`${t}.candidate-${process.pid}-${_t()}`;try{return{candidatePath:r,handle:await W(r,"wx",384)}}catch(n){if(await Ft(r)||Dt(It.dirname(t)),"EINTR"!==Ct(n)||e>=128)throw n}}}(t);try{try{await f(n,`${JSON.stringify(e)}\n`,"utf8"),await n.sync()}finally{await n.close()}try{return await(qt.link??x)(r,t),!0}catch(r){if(function(t){let e=Ct(t);return"EEXIST"===e||"ENOENT"===e}(r))return!1;if(Lt.has(Ct(r)??""))return await async function(t,e){let r;try{r=await W(t,"wx",384)}catch(t){if("EEXIST"===Ct(t))return!1;throw t}try{return await(qt.writeFallback??f)(r,`${JSON.stringify(e)}\n`,"utf8"),await r.sync(),!0}finally{await r.close()}}(t,e);throw r}}finally{await Ft(r)||Dt(It.dirname(t))}}function Bt(t,e,r=Math.random){let n=Math.min(250,e*2**Math.min(t,30));return Math.max(1,Math.round(n/2+r()*n/2))}function Gt(t,e){return e?.throwIfAborted(),new Promise((r,n)=>{let i=setTimeout(a,t),o=()=>a(e?.reason??new DOMException("The operation was aborted","AbortError"));function a(t){clearTimeout(i),e?.removeEventListener("abort",o),void 0===t?r():n(t)}e?.addEventListener("abort",o,{once:!0})})}import{randomUUID as Ht}from"node:crypto";import{hostname as Jt}from"node:os";function Kt(t){if(t instanceof Error&&"code"in t)return"string"==typeof t.code?t.code:void 0}async function Yt(t){if(t.hostname!==Jt())return!1;let e=wt(t.pid);if("dead"===e)return!0;if("unknown"===e)return!1;let r=await pt(t.pid);return null!==r&&"unavailable"!==t.process_start&&function(t,e){let r=mt(t);return null!==r&&r===mt(e)&&t!==e}(t.process_start,r)}async function Zt(t,e,r){return null!==t.record?Yt(t.record):e-t.mtimeMs>r}async function Vt(t,e,r){let n=await Et(t);if(null===n||!await Zt(n,e,r))return!1;let i=`${t}.reaping-${Ht()}`;try{await g(t,i)}catch(t){if("ENOENT"===Kt(t))return!1;if(Ut(t))return!1;throw t}let o=await Et(i);if(null!==o&&bt(o,n))return await D(i),!0;try{await x(i,t)}catch(t){if("EEXIST"!==Kt(t))throw t}return await D(i),!1}async function Wt(t,e,r,n,i){if(!await Zt(e,n,i))return!1;let o=`${t}.recovery`,a={...r,nonce:Ht(),created_at:(new Date).toISOString(),purpose:`${r.purpose}:recovery`};for(let t=0;null!==await Et(o)||!await zt(o,a);t+=1)if(t>0||!await Vt(o,n,i))return!1;try{let r=await Et(t);if(null===r)return!0;if(!bt(r,e))return!1;if(!await Zt(r,n,i))return!1;let s=await Et(o);return null!==s&&s.record?.nonce===a.nonce&&(await D(t),!0)}finally{await St(o,a)}}class Xt extends Error{lockPath;owner;retriable=!0;constructor(t,e){super(`Lock is held: ${t}`),this.lockPath=t,this.owner=e,this.name="LockContentionError"}}async function Qt(t,e,r={}){let n=r.waitTimeoutMs??0,i=r.retryDelayMs??25,o=r.incompleteLockGraceMs??5e3,a=r.now??Date.now;if(n<0||i<=0||o<0)throw Error("lock wait options must be positive");let s=a()+n;for(let n=0;;n+=1){r.signal?.throwIfAborted();let c=await Et(t);if(null===c){if(await zt(t,e))return;if(r.signal?.throwIfAborted(),c=await Et(t),null===c)continue}if(!await Wt(t,c,e,a(),o)){if(r.signal?.throwIfAborted(),a()>=s)throw new Xt(t,c.record);await Gt(Math.min(Bt(n,i),Math.max(1,s-a())),r.signal)}}}import{hostname as te}from"node:os";import ee from"node:path";function re(t){if(t instanceof Error&&"code"in t)return"string"==typeof t.code?t.code:void 0}async function ne(t){let e=await N(t).catch(()=>{});if(void 0===e||!e.isFile()||!await async function(t){let e;try{e=await M(t,"utf8")}catch(t){if("ENOENT"===re(t))return!1;throw t}let r=yt(e);return null!==r&&r.hostname===te()&&"dead"===wt(r.pid)&&Yt(r)}(t))return!1;let r=await vt("dead-owner-sweep");try{await Qt(t,r,{waitTimeoutMs:0})}catch(t){if(t instanceof Xt)return!1;throw t}return await St(t,r),!0}async function ie(t,e,r={}){let n=nt.dirname(t);if(function(t,e){let r=$t.get(t);return!(void 0!==r&&e-r<6e5||($t.set(t,e),0))}(n,(r.now??Date.now)())){let t=jt();await async function(t,e=Date.now,r={}){let n;try{n=await P(t)}catch(e){if("ENOENT"===Tt(e)){for(let e of Nt)xt.dirname(e)===t&&kt(e);return 0}throw e}let i=0;for(let o of n){if(!Mt.test(o))continue;let n=xt.join(t,o);try{let t=await $(n);if(!(Nt.has(n)||Pt(o)||e()-t.mtimeMs>36e5))continue;let a=!1;for(let t=0;t<3;t+=1)try{await(r.unlink??D)(n),kt(n),a=!0;break}catch(e){if("ENOENT"===Tt(e)){kt(n),a=!0;break}if(!(r.isSharingError?.(e)??At(e)))throw e;t+1===3&&Rt(r,n)}a&&(i+=1)}catch(t){"ENOENT"===Tt(t)&&kt(n),Rt(r,n)}}return i}(n,Date.now,{...void 0===t.unlink?{}:{unlink:t.unlink},...void 0===t.isSharingError?{}:{isSharingError:t.isSharingError},onFailure:()=>Dt(n)}).catch(()=>{Dt(n)}),await async function(t,e={}){let r;try{r=await P(t)}catch(r){return"ENOENT"!==re(r)&&e.onFailure?.(t,r),0}let n=0;for(let i of r){if(!i.endsWith(".lock"))continue;let r=ee.join(t,i);try{await ne(r)&&(n+=1)}catch(t){e.onFailure?.(r,t)}}return n}(n)}return Qt(t,e,r)}async function oe(t,e,r,n){await ie(t,e,n);try{return await r()}finally{await St(t,e)}}Promise.resolve();[{class:"aws_access_key",ere:"(^|[^A-Za-z0-9_])AKIA[0-9A-Z]{16}([^A-Za-z0-9_]|$)"},{class:"credential_assignment",ere:"(^|[^A-Za-z0-9_])([Bb][Ee][Aa][Rr][Ee][Rr]|[Tt][Oo][Kk][Ee][Nn]|[Aa][Pp][Ii][-_]?[Kk][Ee][Yy]|[Ss][Ee][Cc][Rr][Ee][Tt]|[Pp][Aa][Ss][Ss][Ww][Oo][Rr][Dd]|[Pp][Aa][Ss][Ss][Ww][Dd]|[Pp][Ww][Dd])[[:space:]]*[=:][[:space:]]*[^[:space:]]{1,255}"},{class:"authorization_header",ere:"(^|[^A-Za-z0-9_])[Aa][Uu][Tt][Hh][Oo][Rr][Ii][Zz][Aa][Tt][Ii][Oo][Nn][[:space:]]*:[[:space:]]*[Bb][Ee][Aa][Rr][Ee][Rr][[:space:]]+[^[:space:]]{1,255}"},{class:"openai_key",ere:"(^|[^A-Za-z0-9_])sk-(proj-)?[-_A-Za-z0-9]+([^A-Za-z0-9_-]|$)"},{class:"vendor_token",ere:"(^|[^A-Za-z0-9_])(ghp|github_pat|glpat|xox[baprs])[-_][-_A-Za-z0-9]+([^A-Za-z0-9_-]|$)"}].map(({class:t,ere:e})=>[` if printf '%s' "$blob" | grep -E -q -e '${e}'; then`,` printf 'memory pre-commit: %s contains secret-like content (${t})\\n' "$p"`," fi"].join("\n")).join("\n"),new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});import{dirname as ae}from"node:path";import{fileURLToPath as se}from"node:url";ae(se(import.meta.url));import{dirname as ce}from"node:path";import{fileURLToPath as le}from"node:url";ce(le(import.meta.url)),new Date(0).toISOString();var ue="\\p{Script=Hangul}\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\u30fc";new RegExp(`[${ue}]+|(?:(?![${ue}])[\\p{L}\\p{M}\\p{N}])+`,"gu"),new RegExp(`^[${ue}]+$`,"u"),new RegExp(`[${ue}]`,"u"),new RegExp(`[${ue}]`,"gu"),new RegExp(`[\\p{L}${ue}]`,"gu");import{dirname as de}from"node:path";import{fileURLToPath as fe}from"node:url";de(fe(import.meta.url));import{randomUUID as pe}from"node:crypto";import{dirname as me}from"node:path";async function we(t){return JSON.parse(await M(t,"utf8"))}async function he(t,e,r=384){let n=`${t}.tmp-${process.pid}-${pe()}`,i=await W(n,"wx",r),o=!1;try{try{await i.writeFile(`${JSON.stringify(e,null,2)}\n`,"utf8"),await i.sync()}finally{await i.close()}await g(n,t),o=!0,await async function(t){try{let e=await W(t,"r");try{await e.sync()}finally{await e.close()}}catch(t){let e=t instanceof Error&&"code"in t?t.code:void 0;if("win32"!==process.platform||!["EISDIR","EPERM"].includes(String(e)))throw t}}(me(t))}finally{o||await ve(n)}}async function ye(t,e){let r=await we(t);await he(t,{...r,...e})}async function ve(t){try{await D(t)}catch(t){if(!(t instanceof Error&&"code"in t&&"ENOENT"===t.code))throw t}}import{spawn as ge,spawnSync as Ee}from"node:child_process";function be(){return"1"===process.env.OMO_MEMORY_SUPERVISOR_ALLOW_TEST_SEAMS}function Se(){if(be()){let t=process.env.OMO_MEMORY_SUPERVISOR_PLATFORM;if("posix"===t||"win32"===t)return t}return"win32"===process.platform?"win32":"posix"}function _e(){let t=be()?process.env.OMO_MEMORY_SUPERVISOR_CLOCK_PATH:void 0;return void 0===t?Date.now():Ne(t)}function Ie(t,e){let r=be()?process.env.OMO_MEMORY_SUPERVISOR_CLOCK_PATH:void 0;if(void 0===r){let r=setTimeout(e,Math.max(0,t-Date.now()));return()=>clearTimeout(r)}let n=!1,i=()=>{if(n)return;let i=Ne(r);!Number.isFinite(i)||i<t||(n=!0,o?.close(),clearInterval(a),e())};if(Ne(r)>=t)return n=!0,e(),()=>{};let o=V(r,i),a=setInterval(i,xe);return i(),()=>{n||(n=!0,o.close(),clearInterval(a))}}var xe=25;function Ne(t){let e=B(t).map(t=>/^(\d+)-(-?\d+(?:\.\d+)?)$/.exec(t)).filter(t=>null!==t).sort((t,e)=>Number(t[1])-Number(e[1])).at(-1);return void 0===e?Number.NaN:Number(e[2])}function Oe(t,e){if(!be())return;let r=process.env.OMO_MEMORY_SUPERVISOR_TASKKILL_RUN_DIR;void 0!==r&&K(`${r}/${t}-${process.pid}.json`,`${JSON.stringify({targetPid:e})}\n`,"utf8")}function ke(t){if(!be())return;let e=process.env[t];if(void 0===e)return;let r=JSON.parse(e);if(!Array.isArray(r)||!r.every(t=>"string"==typeof t)||0===r.length)throw TypeError(`${t} must be a non-empty string array`);return r}function Me(t,e,r){let[n,...i]=t;if(void 0===n)throw TypeError("termination command is required");if(r){let t=Ee(n,[...i,...e],{env:process.env,stdio:"ignore",windowsHide:!0});if(void 0!==t.error)throw t.error;return}ge(n,[...i,...e],{env:process.env,stdio:"ignore",windowsHide:!0}).once("error",t=>process.stderr.write(`${t.message}\n`))}function Pe(t,e){Oe(`posix-${e}`,t);let r=ke("OMO_MEMORY_SUPERVISOR_POSIX_SIGNAL_COMMAND");if(void 0===r)try{process.kill(-t,e)}catch(t){if(!(t instanceof Error&&"code"in t&&"ESRCH"===t.code))throw t}else Me(r,["--signal-group",String(t),e],!1)}function Te(t){void 0!==t&&Oe("win32-graceful",t)}function Re(t,e){"win32"===t?(Te(e.pid),e.kill()):void 0!==e.pid&&Pe(e.pid,"SIGTERM")}function Ae(t,e,r=!1){void 0!==e&&("win32"===t?function(t,e){Me(ke("OMO_MEMORY_SUPERVISOR_TASKKILL_COMMAND")??["taskkill"],["/pid",String(t),"/T","/F"],e)}(e,r):Pe(e,"SIGKILL"))}async function $e(t){return await pt(t)}import{join as De}from"node:path";function Le(t){return"object"==typeof t&&null!==t}function Ce(t,e){try{return t?.[e]}catch(t){return void Error}}function Ue(t,e){let r=Ce(t,e);return Le(r)?r:void 0}function qe(t){if(!t)return"";if("string"==typeof t)return t.toLowerCase();if(!Le(t))try{return JSON.stringify(t).toLowerCase()}catch(t){if(!(t instanceof Error))throw t;return""}let e=Ue(t,"data"),r=[e,Ue(t,"error"),t,Ue(e,"error")].filter(t=>void 0!==t);for(let t of r){let e=Ce(t,"message");if("string"==typeof e&&e.length>0)return e.toLowerCase()}let n=Ce(t,"name");if("string"==typeof n&&n.length>0){let t=n.match(/:\s*(.+)/);if(t)return t[1]?.trim().toLowerCase()??""}try{return JSON.stringify(t).toLowerCase()}catch(t){if(!(t instanceof Error))throw t;return""}}function je(t,e){if(function(t){return"object"==typeof t&&null!==t}(t))try{return t[e]}catch(t){return void Error}}function Fe(t){return"terminal_quota_exhausted"===function(t){let e=je(t,"data"),r=je(t,"detail")??je(e,"detail")??t,n=je(r,"error")??r,i=je(n,"type")??je(r,"type");return"string"==typeof i?i.toLowerCase():void 0}(t)||(e=qe(t),!/\bnon[-\s]+terminal\s+quota\b/i.test(e)&&!/\bnon[-\s]+terminal\s+billing\s+limit\b/i.test(e)&&(/\bterminal\s+quota\b/i.test(e)||/\bterminal\s+billing\s+limit\b/i.test(e)||/\bhard\s+billing\s+limit\b/i.test(e)));var e}function ze(t){if(Fe(t))return"abort";let e=qe(t),r=function(t){if(!Le(t))return;let e=Ue(t,"data"),r=[t,e,Ue(t,"error"),Ue(e,"error")].filter(t=>void 0!==t);for(let t of r){let e=Ce(t,"name");if("string"==typeof e&&e.length>0)return e}}(t)?.toLowerCase().replace(/[_-]/g,"");return r?.includes("messageabortederror")||r?.includes("aborterror")?"abort":"contextoverflowerror"===r?"context_overflow":r?.includes("ailoadapikeyerror")||r?.includes("loadapi")||/api.?key.?is.?missing/i.test(e)&&/environment variable/i.test(e)?"missing_api_key":/api.?key/i.test(e)&&/must be a string/i.test(e)?"invalid_api_key":r?.includes("providermodelnotfounderror")||r?.includes("modelnotfounderror")||r?.includes("unknownerror")&&/model\s+not\s+found/i.test(e)?"model_not_found":r?.includes("quotaexceeded")||r?.includes("insufficientquota")||r?.includes("billingerror")||r?.includes("resourceexhausted")||r?.includes("insufficientcredits")||r?.includes("usagelimit")||/quota.?exceeded/i.test(e)||/exceeded.*quota/i.test(e)||/quota\b.*\breset/i.test(e)||/usage\s*quota/i.test(e)||/subscription.?(?:quota|limit)/i.test(e)||/insufficient.?(?:quota|balance|funds?|credits?)/i.test(e)||/credits?\s+exhausted/i.test(e)||/\b(?:session|weekly|monthly|daily|hourly|\d+[-\s]hour|plan|call)\s+limit\b/i.test(e)||/\bhit\s+your\b[^.]*\blimit\b/i.test(e)||/\bin\s+arrears\b/i.test(e)||/\brecharge\s+and\s+try\b/i.test(e)||/billing.?(?:hard.?)?limit/i.test(e)||/exhausted\s+your\s+capacity/i.test(e)||/resource.?exhausted/i.test(e)||/out\s+of\s+credits?/i.test(e)||/payment.?required/i.test(e)||/usage\s+limit/i.test(e)||/credit\s+balance.*too\s+low/i.test(e)||/limit\s+exhausted/i.test(e)||/使用上限/.test(e)||/用量上限/.test(e)||/达到.*限制/.test(e)||/额度.*不足/.test(e)||/余额.*不足/.test(e)||/已耗尽/.test(e)||function(t){return/预扣费额度失败/i.test(t)&&/用户剩余额度/i.test(t)||/用户剩余额度/i.test(t)&&/需要预扣费额度/i.test(t)}(e)?"quota_exceeded":void 0}var Be=new Set(["providermodelnotfounderror","ratelimiterror","modelunavailableerror","providerconnectionerror","authenticationerror"]),Ge=new Set(["messageabortederror","permissiondeniederror","contextlengtherror","timeouterror","validationerror","syntaxerror","usererror"]),He=["rate_limit","rate limit","usage_limit_reached","usage limit has been reached","quota","all credentials for model","cooling down","exhausted your capacity","not found","unavailable","insufficient","too many requests","over limit","overloaded","bad gateway","bad request","unknown provider","provider not found","model_not_supported","model not supported","model is not supported","connection error","network error","timeout","service unavailable","internal_server_error","free usage","usage exceeded","credit","balance","temporarily unavailable","try again","请稍后重试","503","502","504","429","529","selected provider is forbidden","provider is forbidden","频率限制","请求过于频繁","暂时不可用","服务不可用","server_error","an error occurred while processing","upstream request failed"],Je=["rate limit","cooling down","credentials for model"];function Ke(t){let e=t.name?.toLowerCase();if(void 0!==e&&Ge.has(e))return!1;if(Fe(t))return!1;if("quota_exceeded"===ze(t))return!0;if(void 0!==e&&Be.has(e))return!0;let r=t.message?.toLowerCase()??"";return!(!(n=r).includes("retrying in")||!Je.some(t=>n.includes(t)))||(null!=t.statusCode&&(429===t.statusCode||503===t.statusCode||529===t.statusCode)||He.some(t=>r.includes(t)));var n}var Ye=[/prompt is too long/i,/request_too_large/i,/input is too long for requested model/i,/exceeds the context window/i,/exceeds (?:the )?(?:model'?s )?maximum context length(?: of [\d,]+ tokens?|\s*\([\d,]+\))/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds (?:the )?maximum allowed input length of [\d,]+ tokens?/i,/input \(\d+ tokens\) is longer than the model'?s context length \d+ tokens/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/too large for model with \d+ maximum context length/i,/prompt has [\d,]+ tokens?, but the configured context size is [\d,]+ tokens?/i,/prompt too long; exceeded (?:max )?context length/i,/range of input length should be/i,/model_context_window_exceeded/i,/context[_ ]length[_ ]exceeded/i,/too many tokens/i,/token limit exceeded/i,/^4(?:00|13)\s*(?:status code)?\s*\(no body\)/i,/(?:request[ _])?(?:body|entity|payload)[_ ]too[_ ]large/i,/Request payload is \d+ (?:bytes, over the \d+ byte|tokens, over the \d+ token) limit Kiro accepts\./i,/Model context limit reached\. Conversation size exceeds model capacity\./i],Ze=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];var Ve=/^Error: Model "([^"]+)" not found\. Use --list-models to see available models\.$/m,We=/^(?:Error:\s*)?No API key found for\s+([^\s.]+)/m,Xe=/(?:^|\s)(\d{3})\s*:/;function Qe(t){if(t.timedOut||0===t.code)return;let e=`${t.stderr}\n${t.stdout}`,r=Ve.exec(e)?.[1];if(void 0!==r)return{kind:"model_not_visible",id:r};let n=We.exec(e)?.[1];if(void 0!==n)return{kind:"auth_missing",provider:n};let i=function(t){for(let e of[t.stderr,t.stdout]){let t=e.split("\n").map(t=>t.trim()).find(t=>t.length>0&&!tr.test(t));if(void 0!==t)return t.slice(0,200)}return}(t);if(void 0===i)return;if(o=i,!Ze.some(t=>t.test(o))&&Ye.some(t=>t.test(o)))return{kind:"context_overflow",detail:i};var o;let a=Number.parseInt(Xe.exec(i)?.[1]??"",10);return Ke({message:i,...Number.isNaN(a)?{}:{statusCode:a}})?{kind:"provider_unavailable",detail:i}:void 0}var tr=/\bunder (?:Bun|Node(?:\.js)?|Deno)\b|^(?:\[[^\]]*\]\s*)?(?:note|notice|info|hint|debug|warn|warning)\s*:/i;import{randomUUID as er}from"node:crypto";import{dirname as rr,join as nr}from"node:path";class ir extends Error{runDir;constructor(t,e){super(`Run terminal claim cannot be recovered in ${t}`,e),this.runDir=t,this.name="RunTerminalClaimUnrecoverableError"}}function or(t){return nr(t,"terminal-claim.json")}function ar(t,e,r){return t.runId===e.runId&&t.attempt===e.attempt&&(void 0===r||t.kind===r)}function sr(t,e){let r=`${t}.${process.pid}.${er()}.candidate`;!function(t,e){let r=X(t,"wx",384);try{K(r,`${JSON.stringify(e,null,2)}\n`,"utf8"),U(r)}finally{Q(r)}}(r,e);try{q(r,t)}catch(t){if("EEXIST"===pr(t))return!1;throw t}finally{ur(r)}return function(t){let e;try{e=X(t,"r")}catch(t){if("win32"===process.platform&&["EISDIR","EPERM"].includes(pr(t)??""))return;throw t}try{U(e)}catch(t){if("win32"!==process.platform||!["EPERM","EACCES","EINVAL"].includes(pr(t)??""))throw t}finally{Q(e)}}(rr(t)),!0}function cr(t){let e;try{e=z(t,"utf8")}catch(t){if("ENOENT"===pr(t))return;throw t}try{return{raw:e,claim:fr(JSON.parse(e))}}catch{return{raw:e,claim:void 0}}}async function lr(t,e,r,n,i,o){let a=await vt("reflection-finalize",{runId:i.runId});return oe(nr(t,"terminal-claim-recovery.lock"),a,async()=>{let t=cr(e);if(void 0!==t){if(t.raw!==r.raw)return t.claim;if("invalid"===n){if(void 0!==t.claim)return t.claim}else{if(void 0===t.claim)return;if("publish"!==t.claim.kind||!dr(t.claim,o))return t.claim}ur(e)}},{waitTimeoutMs:Number.POSITIVE_INFINITY})}function ur(t){try{J(t)}catch(t){if("ENOENT"!==pr(t))throw t}}function dr(t,e){return"dead"===(e.getPidLiveness??wt)(t.claimantPid)}function fr(t){if(!function(t){return null!==t&&"object"==typeof t&&!Array.isArray(t)}(t)||1!==t.version||"publish"!==t.kind&&"abandon"!==t.kind||"string"!=typeof t.runId||!Number.isInteger(t.attempt)||!Number.isInteger(t.claimantPid)||Number(t.claimantPid)<=0)throw TypeError("Invalid run terminal claim");return{version:1,kind:t.kind,runId:t.runId,attempt:Number(t.attempt),claimantPid:Number(t.claimantPid)}}function pr(t){return t instanceof Error&&"code"in t?String(t.code):void 0}import{join as mr}from"node:path";async function wr(t,e,r){let n={runId:e.runId,attempt:e.attempt??1},i=await async function(t,e,r,n={},i=process.pid){let o=or(t),a={version:1,kind:r,runId:e.runId,attempt:e.attempt,claimantPid:i},s=0;for(;;){if(sr(o,a))return a;let i;try{i=cr(o)}catch(e){throw new ir(t,{cause:e})}if(void 0===i)continue;let c=i.claim;if(void 0===c){if(s>0)throw new ir(t);s+=1,await(n.beforeRecovery?.("invalid"));let r=await lr(t,o,i,"invalid",e,n);if(void 0!==r)return r;continue}if(ar(c,e,r))return c;if("publish"!==c.kind||!dr(c,n))return c;await(n.beforeRecovery?.("dead-publish"));let l=await lr(t,o,i,"dead-publish",e,n);if(void 0!==l)return l}}(t,n,"publish");ar(i,n,"publish")&&(await he(De(t,"publishing.json"),{version:1,...n,finishedAt:r.finishedAt}),await async function(t,e,r,n=oe,i=vt){let o=await i("reflection-finalize",{runId:e});return n(mr(t,"terminalization.lock"),o,r,{waitTimeoutMs:Number.POSITIVE_INFINITY})}(t,e.runId,async()=>{if(tt(De(t,"final.json"))||tt(De(t,"abandoned.json")))return;if(!ar(function(t){return fr(JSON.parse(z(or(t),"utf8")))}(t),n,"publish"))return;let i=void 0!==Qe({code:r.childExit.code,stdout:z(e.stdoutPath,"utf8"),stderr:z(e.stderrPath,"utf8"),timedOut:r.timedOut});i&&void 0!==e.nextAttempt&&await ye(De(t,"ledger.json"),{attempt:e.nextAttempt.attempt,model:e.nextAttempt.model,...void 0===e.nextAttempt.thinking?{thinking:void 0}:{thinking:e.nextAttempt.thinking},launching:!0,pid:void 0,processStart:void 0,childPid:void 0,childProcessStart:void 0}),await he(De(t,"outcome.json"),r),i&&await ve(or(t))}))}function hr(t){try{Y(3,`${JSON.stringify(t)}\n`)}catch(t){if(!(t instanceof Error&&"code"in t&&["EPIPE","EBADF"].includes(String(t.code))))throw t}}var yr=process.argv.slice(2);try{if("--child-bootstrap"===yr[0]){if(void 0===yr[1])throw TypeError("run directory is required");await async function(e){if(!await async function(){for await(let t of process.stdin)if(Buffer.byteLength(t)>0)return!0;return!1}())return;let r=await we(et(e,"launch.json")),n=Se(),i=t(r.command,[...r.args],{cwd:r.cwd,env:r.env,detached:!1,stdio:["ignore","inherit","inherit"],windowsHide:!0});hr({code:i.pid??null,signal:"MODEL_PID"});let o=()=>{"win32"!==n&&"win32"!==process.platform||i.kill()};process.on("SIGTERM",o),process.on("SIGINT",o);let a=!1,s=Ie(r.hardDeadlineAt,()=>{a=!0,"win32"===n?Re(n,i):Pe(process.pid,"SIGTERM")}),c=Ie(r.hardDeadlineAt+r.terminationGraceMs,()=>{a=!0,Ae(n,process.pid)}),l=await new Promise(t=>{let e=!1;i.once("error",()=>{e||(e=!0,t({code:null,signal:null}))}),i.once("close",(r,n)=>{e||(e=!0,t({code:r,signal:n}))})}).finally(()=>{s(),c()});var u,d;await he(et(e,"child-exit.json"),{version:1,runId:r.runId,attempt:r.attempt,code:l.code,signal:l.signal,finishedAt:(new Date).toISOString(),timedOut:a||(u=_e(),d=r.hardDeadlineAt,!Number.isFinite(u)||u>=d)}),hr(l)}(yr[1])}else{if(void 0===yr[0])throw TypeError("run directory is required");await async function(e){let r=et(e,"launch.json"),n=et(e,"ledger.json"),i=await we(r),o=Se();await ye(n,{launching:!1,pid:process.pid,processStart:await $e(process.pid)});let a,s=X(i.stdoutPath,"w"),c=X(i.stderrPath,"w"),l=t(process.execPath,[rt(import.meta.url),"--child-bootstrap",e],{env:process.env,detached:!0,stdio:["pipe",s,c,"pipe"],windowsHide:!0}),u=l.pid,d="",f=l.stdio[3];null!=f&&"setEncoding"in f&&(f.setEncoding("utf8"),f.on("data",t=>{d+=t;for(let t of d.split("\n"))try{let e=JSON.parse(t);"MODEL_PID"===e.signal&&"number"==typeof e.code&&(a=e.code)}catch(t){if(!(t instanceof SyntaxError))throw t}}));let p=(t=!1)=>{try{Ae(o,u,t)}catch(t){process.stderr.write(`${t instanceof Error?t.message:String(t)}\n`)}};if(process.once("exit",()=>p(!0)),process.once("SIGTERM",()=>{p(),u=void 0,process.exit(143)}),process.once("SIGINT",()=>{p(),u=void 0,process.exit(130)}),void 0===l.pid)throw Error("child bootstrap did not receive a pid");await ye(n,{childPid:l.pid,childProcessStart:await $e(l.pid)}),l.stdin?.end("1\n");let m,w=!1,h=Promise.resolve();"win32"===o&&(h=new Promise(t=>{m=t}));let y=Ie(i.hardDeadlineAt,()=>{w=!0,"win32"===o?Te(l.pid):Re(o,l)}),v=Ie(i.hardDeadlineAt+i.terminationGraceMs,()=>{Ae(o,a??u),m?.()}),g=await new Promise((t,e)=>{let r=!1;l.once("error",t=>{r||(r=!0,e(t))}),l.once("close",(e,n)=>{r||(r=!0,t({code:e,signal:n}))})}),E=function(t){let e=t.trim().split("\n").at(-1);if(void 0!==e&&0!==e.length)try{let t=JSON.parse(e),r="number"==typeof t.code||null===t.code?t.code:void 0,n="string"==typeof t.signal||null===t.signal?t.signal:void 0;return void 0===r||void 0===n||"MODEL_PID"===n?void 0:{code:r,signal:n}}catch{return}}(d);"win32"===o&&w&&void 0===E&&await h,y(),v(),u=void 0,Q(s),Q(c),function(t,e={}){if(process.env.OMO_MEMORY_KILL_POINT!==t)return;let r=e.kill??((t,e)=>{process.kill(t,e)});"win32"===(e.platform??process.platform)?r(process.pid):r(process.pid,"SIGKILL")}("after-child-exit");let b=_e(),S=(new Date).toISOString(),_={version:1,runId:i.runId,attempt:i.attempt,finishedAt:S,childExit:E??g,timedOut:w||Number.isFinite(b)&&b>=i.hardDeadlineAt};await wr(e,i,_),await ve(r),process.exit(0)}(yr[0])}}catch(t){process.stderr.write(`${t instanceof Error?t.stack??t.message:String(t)}\n`),process.exitCode=1}