omo-ai 5.1.7 → 5.1.8

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.
@@ -3,8 +3,8 @@ import { homedir as osHomedir } from "node:os"
3
3
  import { join } from "node:path"
4
4
  import { bunRoot, findBunBinary, isUnderBunGlobalTree } from "./bun-runtime.js"
5
5
 
6
- // Bumping this rewrites every generated shim on its next node boot; the value is embedded so a
7
- // stale shim is recognizable by content comparison alone.
6
+ // Bumping this rewrites every generated shim on its next launch; the value is embedded so a stale
7
+ // shim is recognizable by content comparison alone.
8
8
  const SHIM_VERSION = 1
9
9
  const SHIM_MARKER = "omo-ai bun launcher shim"
10
10
 
@@ -26,8 +26,8 @@ function quoteForShell(value) {
26
26
  * entrypoint so the launch never pays for a node boot. Both fallbacks land on the entrypoint's
27
27
  * own `#!/usr/bin/env node` shebang, which is byte-identical to what the stock symlink did:
28
28
  * - OMO_RUNTIME=node asks for node end to end, so bun is skipped on purpose;
29
- * - a bun that moved or vanished falls back to the node path, and the next node boot rewrites
30
- * the shim with the freshly discovered bun path.
29
+ * - a bun that moved or vanished falls back to the node path, and the next launch rewrites the
30
+ * shim with the freshly discovered bun path.
31
31
  */
32
32
  export function bunBinShimScript(entryPath, bunPath) {
33
33
  return [
@@ -88,8 +88,11 @@ function repairBinEntry(entry, root, script, io) {
88
88
  * when an entry is already a regular file, reading a few hundred bytes) and must never break a
89
89
  * launch: every failure path - foreign file, missing bin, unwritable bin dir - returns quietly,
90
90
  * one entry's failure never stops the other from being repaired, and only OMO_DEBUG narrates.
91
- * Repairs run under node only, because a bun process either arrived through a shim already or has
92
- * no node boot to save.
91
+ * It runs under bun as well as node: `bun add -g` links the bin back to the node-shebang entrypoint
92
+ * and then runs omo-ai's postinstall (`bin/senpi-patch.mjs`) under bun whenever node is not on
93
+ * PATH, and that postinstall is the only code that runs before the next `omo`. A node-only repair
94
+ * left a bun-only machine (a launchd job, cron, node only through nvm) with an `omo` that cannot
95
+ * start until something boots it under node (#9293).
93
96
  *
94
97
  * The answer is per entry (`entries`), with the primary `<bunRoot>/bin/omo` entry's action and
95
98
  * error mirrored at the top level for callers that only ever cared about that one.
@@ -98,7 +101,6 @@ export function ensureBunBinShim(input) {
98
101
  const env = input.env ?? process.env
99
102
  const homedir = input.homedir ?? osHomedir
100
103
  const platform = input.platform ?? process.platform
101
- const versions = input.versions ?? process.versions
102
104
  const io = {
103
105
  env,
104
106
  scriptPath: input.scriptPath,
@@ -113,7 +115,6 @@ export function ensureBunBinShim(input) {
113
115
  }
114
116
 
115
117
  if (platform !== "darwin" && platform !== "linux") return { action: "skipped-platform", error: undefined, entries: [] }
116
- if (versions.bun) return { action: "skipped-runtime", error: undefined, entries: [] }
117
118
  if (!isUnderBunGlobalTree(input.scriptPath, { env, homedir, platform, realpath: io.realpath })) {
118
119
  return { action: "skipped-install", error: undefined, entries: [] }
119
120
  }
@@ -282,9 +282,17 @@ function ownerLabel(owner) {
282
282
  return owner.version === null ? owner.name : `${owner.name}@${owner.version}`
283
283
  }
284
284
 
285
+ function shellQuote(value) {
286
+ return `'${String(value).replaceAll("'", `'"'"'`)}'`
287
+ }
288
+
285
289
  function omoInstallRemoval(entry, bunRoot) {
286
- if (entry.kind === "standalone") return `remove ${entry.binPath}`
287
- return realPathOf(entry.binPath).startsWith(realPathOf(bunRoot)) ? "bun remove -g omo-ai" : "npm uninstall -g omo-ai"
290
+ if (entry.kind === "standalone") return `rm -f -- ${shellQuote(entry.binPath)}`
291
+ const real = realPathOf(entry.binPath)
292
+ if (real.startsWith(realPathOf(bunRoot))) return `BUN_INSTALL=${shellQuote(bunRoot)} bun remove -g omo-ai`
293
+ const packageMarker = /[\\/]lib[\\/]node_modules[\\/]omo-ai[\\/]/.exec(real)
294
+ const prefix = packageMarker === null ? dirname(entry.directory) : real.slice(0, packageMarker.index)
295
+ return `npm uninstall -g omo-ai --prefix ${shellQuote(prefix)}`
288
296
  }
289
297
 
290
298
  export function formatMigrationLines({ shadowing, nativeDirectory, legacyPackages, registrations, restoreCommand, omoInstalls = [], bunRoot = "", standalone = false }) {
@@ -1,5 +1,5 @@
1
1
  {
2
- "_comment": "Derived from @code-yeongyu/senpi 2026.9.30 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.1-2 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",
@@ -22,6 +22,7 @@
22
22
  "groq",
23
23
  "huggingface",
24
24
  "kimi-coding",
25
+ "meta",
25
26
  "minimax",
26
27
  "minimax-cn",
27
28
  "mistral",
@@ -39,6 +40,7 @@
39
40
  "qwen-token-plan-individual",
40
41
  "radius",
41
42
  "together",
43
+ "typesafe",
42
44
  "venice",
43
45
  "vercel-ai-gateway",
44
46
  "xai",
@@ -56,6 +58,7 @@
56
58
  "devin",
57
59
  "github-copilot",
58
60
  "kimi-coding",
61
+ "meta",
59
62
  "openrouter",
60
63
  "radius",
61
64
  "xai"
@@ -2,9 +2,16 @@ import { existsSync, readFileSync } from "node:fs"
2
2
  import { dirname, join } from "node:path"
3
3
  import { createRequire } from "node:module"
4
4
  import { fileURLToPath } from "node:url"
5
+ import { ensureBunBinShim } from "./lib/bun-bin-shim.js"
5
6
  import { prepareInstalledEngine, preparePluginLaunchSpec, writeEnginePreparedStamp } from "./lib/engine-prepare.js"
6
7
 
7
8
  const packageRoot = dirname(dirname(fileURLToPath(import.meta.url)))
9
+
10
+ // `bun add -g` has just linked the bin back to omo.js, whose `#!/usr/bin/env node` cannot start
11
+ // where node is not on PATH; this postinstall runs right after that link (on bun when node is
12
+ // missing), so it restores the bun launcher shim before anything launches `omo` (#9293). Quiet and
13
+ // fail-open, and a no-op outside a POSIX bun-global install, so it runs before the engine work.
14
+ ensureBunBinShim({ scriptPath: join(packageRoot, "bin", "omo.js") })
8
15
  const require = createRequire(join(packageRoot, "package.json"))
9
16
  let senpiRoot = process.env.OMO_SENPI_PATCH_ROOT
10
17
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "omo-ai",
3
- "version": "5.1.7",
3
+ "version": "5.1.8",
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.9.30"
20
+ "@code-yeongyu/senpi": "2026.10.1-2"
21
21
  },
22
22
  "repository": {
23
23
  "type": "git",
@@ -7,6 +7,42 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [5.1.8] - 2026-10-01
11
+
12
+ **A packaged install runs Bun itself again when you call `bun` from an eval cell or the bash tool.** Before, it started a second agent and handed back that agent's reply as a passing result. Geeky · Heavy and `deep-high` move to GPT-6 Astra at high, Geeky · Normal to GPT-6.1 Sol Fast at medium, a session opened from the desktop app keeps the permission mode it asked for, and memory recall now matches Chinese and Japanese characters one by one. This release runs on the senpi 2026.10.1-2 engine.
13
+
14
+ ### Added
15
+
16
+ A session opened from the desktop app or another multi-session client runs with the permission mode it asked for (full access, accept edits or ask first). Before, the mode was recorded but every session ran with the host default. ([senpi#2461](https://github.com/code-yeongyu/senpi/issues/2461))
17
+
18
+ `web_search` has two hosted routes: a ChatGPT subscription session searches through the subscription's own web search with your ChatGPT login, and Google Search grounding is available as an opt-in entry in `websearch.json`. ([senpi#2341](https://github.com/code-yeongyu/senpi/issues/2341))
19
+
20
+ Ultrafast can be selected explicitly with a model decorator such as `chatgpt-subscription/gpt-6-astra:xhigh:ultrafast`, in `models.json` or per session. Thanks to @audreyt. ([senpi#2412](https://github.com/code-yeongyu/senpi/issues/2412))
21
+
22
+ Memory recall also matches Chinese characters and Japanese kanji one by one, so a question worded differently from the note can still find it; a question without any such character gets the same candidates as before. Thanks to [@ashmoonori-afk](https://github.com/ashmoonori-afk). ([#9341](https://github.com/code-yeongyu/oh-my-openagent/pull/9341))
23
+
24
+ Memory recall can widen its own searches with synonyms, keywords in your other languages and related terms when you set `memory.recall.query_expansion` to `true`; an added term counts for less than the same match on one of the query's own words, a note that holds every word of the query stays first, and with the setting off, the default, nothing changes. Thanks to [@ashmoonori-afk](https://github.com/ashmoonori-afk). ([#9342](https://github.com/code-yeongyu/oh-my-openagent/pull/9342))
25
+
26
+ ### Changed
27
+
28
+ Geeky · Heavy and the `deep-high` category now run GPT-6 Astra at high reasoning instead of xhigh. Geeky · Normal now starts on GPT-6.1 Sol Fast at medium; without the Fast tier it uses plain GPT-6.1 Sol at medium, and Copilot or OpenCode users still get GPT-5.6 Sol at medium. `deep-low` keeps GPT-6.1 Sol at medium. ([#9372](https://github.com/code-yeongyu/oh-my-openagent/issues/9372))
29
+
30
+ When a delegated task stops because its model hit a usage limit, the result now says so, says when no other model in the category's chain could take over (as on `deep-high`, which runs GPT-6 Astra only), and how to recover, instead of ending on the provider's raw error. ([#9372](https://github.com/code-yeongyu/oh-my-openagent/issues/9372))
31
+
32
+ ### Fixed
33
+
34
+ **Hotfix: `eval` and `bash` calls that run `bun` no longer start a phantom agent turn in the packaged engine.** In a compiled engine, a `bun` subprocess ran the engine itself as a second agent instead of the requested script. ([#9362](https://github.com/code-yeongyu/oh-my-openagent/issues/9362), [senpi#2494](https://github.com/code-yeongyu/senpi/pull/2494))
35
+
36
+ Manual `/compact` on a Claude subscription replaces the resident Claude transcript with the compacted summary, so the next request really uses the smaller context. Thanks to @ayalcoh for the fix and @Tinycute00 for the report. ([senpi#2331](https://github.com/code-yeongyu/senpi/issues/2331))
37
+
38
+ With two or more logins for one provider, a usage limit reported only in words switches the request to the next account instead of failing it. Thanks to @orientpine. ([senpi#1768](https://github.com/code-yeongyu/senpi/issues/1768))
39
+
40
+ Package installs and updates no longer flash a console window on Windows. Thanks to @willowite. ([senpi#2450](https://github.com/code-yeongyu/senpi/issues/2450))
41
+
42
+ Standalone release binaries now run JavaScript, Python, a real file read and cell listing on all nine natively executable targets, including Alpine musl. Seven legs run that smoke before their binary is uploaded; the linux-arm64 and linux-arm64-musl smokes run after the build, in parallel with the npm platform publish, and a failure there fails the platform release workflow's result. All twelve target manifests preserve the same derived codemode sidecars, and required wasm assets fail packaging if missing. ([#9291](https://github.com/code-yeongyu/oh-my-openagent/issues/9291))
43
+
44
+ Piping the recommended installer to `sh` or `dash` now hands the script to Bash instead of failing on Bash syntax. If Bash is unavailable, the installer prints the exact `curl ... | bash` command to use and exits cleanly. ([#9325](https://github.com/code-yeongyu/oh-my-openagent/issues/9325))
45
+
10
46
  ## [5.1.7] - 2026-09-30
11
47
 
12
48
  **Computer use on macOS says what it needs and where its engine comes from.** A downloaded install trusts the engine shipped inside its own app, a missing Screen Recording or Accessibility grant opens the right System Settings pane, and `/computer status` and `omo doctor` show which engine you have before it starts. This release runs on the senpi 2026.9.30 engine, like 5.1.6.
@@ -53,6 +89,8 @@ Chat bridges can ask the engine for a chat prompt surface, which drops the routi
53
89
 
54
90
  ### Changed
55
91
 
92
+ The recommended `curl` installer now offers `Remove the other omo install at <path>? [y/N]` when it verifies a second installation. Non-interactive runs keep both unless `--remove-other-installs` is explicit, and `omo doctor` prints the exact Bun, npm, or standalone removal command for the non-active install. ([#9324](https://github.com/code-yeongyu/oh-my-openagent/issues/9324))
93
+
56
94
  The engine's recommended OpenAI model is GPT-6.1 Sol at medium, one slot below GPT-6 Astra. Models you listed yourself in `recommendedModels` stay as you set them. ([senpi#2390](https://github.com/code-yeongyu/senpi/issues/2390))
57
95
 
58
96
  ultrawork reuses QA and review evidence per target instead of rerunning everything after each patch, while keeping the nets that catch what the changer cannot see: each artifact records the commit and what it exercised; after an increment the session reruns the tests of every touched file and its importers, the scenarios that exercise them, and anything whose dependencies or environment moved, cites the capture for the rest, and still runs the full set once before the final message. Every re-review spawns a new reviewer with the delta diff and the cited blockers, at most twice. Defects inside the change's blast radius are fixed in the same run to the ideal state; defects outside it get a tracked issue and a line in the final message instead of growing the run. The memory line now also records every regression a check caught and each QA scenario with its invocation. ([#9294](https://github.com/code-yeongyu/oh-my-openagent/issues/9294), [#9298](https://github.com/code-yeongyu/oh-my-openagent/pull/9298))
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- // omo:5ixRJIhPSEuIl-PJdbo4U6vtImrUaFMyMIZXIZV47NI:wrcNysGCSmPQBapD2B6XCs6Q9IVy4wapNChJ-vEMgU8
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}}import{Buffer as a}from"node:buffer";import{constants as s}from"node:fs";function l(t){return"number"==typeof t?0!==(t&s.O_EXCL):"string"==typeof t&&t.toLowerCase().includes("x")}function c(t){return"function"==typeof t}function u(t){return(...e)=>i(async()=>t(...e))}function d(t){return(...e)=>o(()=>t(...e))}function f(t,e){let r="async"===e?u:d,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(!c(i))return i;let o=r(i),a=Reflect.get(i,"native");return c(a)&&Object.assign(o,{native:r(a)}),n.set(e,o),o}})}var p=new Set(["stat","sync","datasync","chmod","chown","utimes","truncate"]);var m=f(r,"async"),w=f(e,"sync"),{access:h,chmod:y,copyFile:g,cp:v,link:b,lstat:E,mkdir:S,mkdtemp:_,readFile:x,readdir:I,realpath:N,rename:O,rm:k,rmdir:P,stat:T,unlink:R}=m,{accessSync:M,chmodSync:A,fsyncSync:$,linkSync:L,lstatSync:C,mkdirSync:D,readFileSync:U,readdirSync:q,realpathSync:j,statSync:F,unlinkSync:H,writeFileSync:J,writeSync:B}=w,{constants:G,watch:V}=e,Y=async(...t)=>{let e=()=>r.open(...t);return function(t){return new Proxy(t,{get(t,e){let r=Reflect.get(t,e);if(!c(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&&p.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(l(t[1]??"r")?e():i(e)))},K=(t,r,n)=>function(t,e,r,n){return l(r)?t(e,r,n):o(()=>t(e,r,n))}(e.openSync,t,r,n??void 0);function z(t){try{e.closeSync(t)}catch(t){if("EINTR"!==n(t))throw t}}function X(t){try{return o(()=>e.statSync(t)),!0}catch{return!1}}import{join as Z}from"node:path";import{fileURLToPath as W}from"node:url";import{randomUUID as Q}from"node:crypto";import{dirname as tt}from"node:path";async function et(t){return JSON.parse(await x(t,"utf8"))}async function rt(t,e,r=384){let n=`${t}.tmp-${process.pid}-${Q()}`,i=await Y(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 O(n,t),o=!0,await async function(t){try{let e=await Y(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}}(tt(t))}finally{o||await it(n)}}async function nt(t,e){let r=await et(t);await rt(t,{...r,...e})}async function it(t){try{await R(t)}catch(t){if(!(t instanceof Error&&"code"in t&&"ENOENT"===t.code))throw t}}import{spawn as ot,spawnSync as at}from"node:child_process";import{execFile as st}from"node:child_process";var lt=null;function ct(){return lt??=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}}(),lt}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 x(`/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 ct();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(){return"1"===process.env.OMO_MEMORY_SUPERVISOR_ALLOW_TEST_SEAMS}function yt(){if(ht()){let t=process.env.OMO_MEMORY_SUPERVISOR_PLATFORM;if("posix"===t||"win32"===t)return t}return"win32"===process.platform?"win32":"posix"}function gt(t,e){let r=ht()?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=bt(r);!Number.isFinite(i)||i<t||(n=!0,o?.close(),clearInterval(a),e())};if(bt(r)>=t)return n=!0,e(),()=>{};let o=V(r,i),a=setInterval(i,vt);return i(),()=>{n||(n=!0,o.close(),clearInterval(a))}}var vt=25;function bt(t){let e=q(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 Et(t,e){if(!ht())return;let r=process.env.OMO_MEMORY_SUPERVISOR_TASKKILL_RUN_DIR;void 0!==r&&J(`${r}/${t}-${process.pid}.json`,`${JSON.stringify({targetPid:e})}\n`,"utf8")}function St(t){if(!ht())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 _t(t,e,r){let[n,...i]=t;if(void 0===n)throw TypeError("termination command is required");if(r){let t=at(n,[...i,...e],{env:process.env,stdio:"ignore",windowsHide:!0});if(void 0!==t.error)throw t.error;return}ot(n,[...i,...e],{env:process.env,stdio:"ignore",windowsHide:!0}).once("error",t=>process.stderr.write(`${t.message}\n`))}function xt(t,e){Et(`posix-${e}`,t);let r=St("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 _t(r,["--signal-group",String(t),e],!1)}function It(t){void 0!==t&&Et("win32-graceful",t)}function Nt(t,e){"win32"===t?(It(e.pid),e.kill()):void 0!==e.pid&&xt(e.pid,"SIGTERM")}function Ot(t,e,r=!1){void 0!==e&&("win32"===t?function(t,e){_t(St("OMO_MEMORY_SUPERVISOR_TASKKILL_COMMAND")??["taskkill"],["/pid",String(t),"/T","/F"],e)}(e,r):xt(e,"SIGKILL"))}async function kt(t){return await pt(t)}import{join as Pt}from"node:path";function Tt(t){return"object"==typeof t&&null!==t}function Rt(t,e){try{return t?.[e]}catch(t){return void Error}}function Mt(t,e){let r=Rt(t,e);return Tt(r)?r:void 0}function At(t){if(!t)return"";if("string"==typeof t)return t.toLowerCase();if(!Tt(t))try{return JSON.stringify(t).toLowerCase()}catch(t){if(!(t instanceof Error))throw t;return""}let e=Mt(t,"data"),r=[e,Mt(t,"error"),t,Mt(e,"error")].filter(t=>void 0!==t);for(let t of r){let e=Rt(t,"message");if("string"==typeof e&&e.length>0)return e.toLowerCase()}let n=Rt(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 $t(t,e){if(function(t){return"object"==typeof t&&null!==t}(t))try{return t[e]}catch(t){return void Error}}function Lt(t){return"terminal_quota_exhausted"===function(t){let e=$t(t,"data"),r=$t(t,"detail")??$t(e,"detail")??t,n=$t(r,"error")??r,i=$t(n,"type")??$t(r,"type");return"string"==typeof i?i.toLowerCase():void 0}(t)||(e=At(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 Ct(t){if(Lt(t))return"abort";let e=At(t),r=function(t){if(!Tt(t))return;let e=Mt(t,"data"),r=[t,e,Mt(t,"error"),Mt(e,"error")].filter(t=>void 0!==t);for(let t of r){let e=Rt(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 Dt=new Set(["providermodelnotfounderror","ratelimiterror","modelunavailableerror","providerconnectionerror","authenticationerror"]),Ut=new Set(["messageabortederror","permissiondeniederror","contextlengtherror","timeouterror","validationerror","syntaxerror","usererror"]),qt=["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"],jt=["rate limit","cooling down","credentials for model"];function Ft(t){let e=t.name?.toLowerCase();if(void 0!==e&&Ut.has(e))return!1;if(Lt(t))return!1;if("quota_exceeded"===Ct(t))return!0;if(void 0!==e&&Dt.has(e))return!0;let r=t.message?.toLowerCase()??"";return!(!(n=r).includes("retrying in")||!jt.some(t=>n.includes(t)))||(null!=t.statusCode&&(429===t.statusCode||503===t.statusCode||529===t.statusCode)||qt.some(t=>r.includes(t)));var n}var Ht=[/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],Jt=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];var Bt=/^Error: Model "([^"]+)" not found\. Use --list-models to see available models\.$/m,Gt=/^(?:Error:\s*)?No API key found for\s+([^\s.]+)/m,Vt=/(?:^|\s)(\d{3})\s*:/;function Yt(t){if(t.timedOut||0===t.code)return;let e=`${t.stderr}\n${t.stdout}`,r=Bt.exec(e)?.[1];if(void 0!==r)return{kind:"model_not_visible",id:r};let n=Gt.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);if(void 0!==t)return t.slice(0,200)}return}(t);if(void 0===i)return;if(o=i,!Jt.some(t=>t.test(o))&&Ht.some(t=>t.test(o)))return{kind:"context_overflow",detail:i};var o;let a=Number.parseInt(Vt.exec(i)?.[1]??"",10);return Ft({message:i,...Number.isNaN(a)?{}:{statusCode:a}})?{kind:"provider_unavailable",detail:i}:void 0}import{randomUUID as Kt}from"node:crypto";import{dirname as zt,join as Xt}from"node:path";import{randomUUID as Zt}from"node:crypto";import{hostname as Wt}from"node:os";import Qt from"node:path";import te from"node:path";var ee=new Set;function re(t){ee.add(t)}function ne(t){ee.delete(t)}var ie=/\.candidate-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function oe(t){if(t instanceof Error&&"code"in t)return"string"==typeof t.code?t.code:void 0}function ae(t,e){try{t.onFailure?.(e)}catch{}}function se(t){if("win32"!==process.platform)return!1;let e=oe(t);return"EBUSY"===e||"EPERM"===e||"EACCES"===e}import{randomUUID as le}from"node:crypto";import{hostname as ce}from"node:os";function ue(t){return"string"==typeof t&&t.length>0}function de(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:ue(r.process_start)&&ue(r.hostname)&&ue(r.nonce)?!ue(r.created_at)||Number.isNaN(Date.parse(r.created_at))?null:ue(r.purpose)&&(void 0===r.run_id||ue(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 fe(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:ce(),nonce:le(),created_at:(new Date).toISOString(),purpose:t,...void 0===e.runId?{}:{run_id:e.runId}}}class pe extends Error{lockPath;owner;retriable=!0;constructor(t,e){super(`Lock is held: ${t}`),this.lockPath=t,this.owner=e,this.name="LockContentionError"}}function me(t){if(t instanceof Error&&"code"in t)return"string"==typeof t.code?t.code:void 0}function we(t,e){if(void 0!==e)return e(t);if("win32"!==process.platform)return!1;let r=me(t);return"EBUSY"===r||"EPERM"===r||"EACCES"===r}async function he(t){for(let e=0;e<3;e+=1)try{return await(Ee.unlink??R)(t),ne(t),!0}catch(r){if("ENOENT"===me(r))return ne(t),!0;if(!we(r,Ee.isSharingError))throw re(t),Se(Qt.dirname(t)),r;if(e+1===3)return re(t),Se(Qt.dirname(t)),!1}return!1}function ye(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})})}async function ge(t){try{let e=await x(t,"utf8");return{raw:e,record:de(e)}}catch(t){let e=me(t);if("ENOENT"===e)return null;if("\\"===Qt.sep&&"EPERM"===e)return{raw:"",record:null};throw t}}async function ve(t,e){await S(Qt.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-${Zt()}`;try{return{candidatePath:r,handle:await Y(r,"wx",384)}}catch(n){if(await he(r)||Se(Qt.dirname(t)),"EINTR"!==me(n)||e>=128)throw n}}}(t);try{try{await async function(t,e,r,n){let o="string"==typeof e?a.from(e,r??"utf8"):e,s=0;for(;s<o.length;){n?.throwIfAborted();let{bytesWritten:e}=await i(()=>t.write(o,s));if(e<=0)throw Error(`fs write made no progress at offset ${s}`);s+=e}}(n,`${JSON.stringify(e)}\n`,"utf8"),await n.sync()}finally{await n.close()}try{return await b(r,t),!0}catch(t){if(function(t){let e=me(t);return"EEXIST"===e||"ENOENT"===e}(t))return!1;throw t}}finally{await he(r)||Se(Qt.dirname(t))}}var be=new Set,Ee={};function Se(t){be.delete(t)}async function _e(t){if(t.hostname!==Wt())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 xe(t){let e=await ge(t);if(null===e||null===e.record||!await _e(e.record))return!1;let r=`${t}.reaping-${Zt()}`;try{await O(t,r)}catch(t){if("ENOENT"===me(t))return!1;if(we(t))return!1;throw t}let n=await ge(r);if(null!==n&&n.raw===e.raw)return await R(r),!0;try{await b(r,t)}catch(t){if("EEXIST"!==me(t))throw t}return await R(r),!1}async function Ie(t,e,r){if(null===e.record||!await _e(e.record))return!1;let n=`${t}.recovery`,i={...r,nonce:Zt(),created_at:(new Date).toISOString(),purpose:`${r.purpose}:recovery`};for(let t=0;!await ve(n,i);t+=1)if(t>0||!await xe(n))return!1;try{let r=await ge(t);if(null===r)return!0;if(r.raw!==e.raw||null===r.record)return!1;if(!await _e(r.record))return!1;let o=await ge(n);return null!==o&&o.record?.nonce===i.nonce&&(await R(t),!0)}finally{await Oe(n,i)}}async function Ne(t,e,r={}){let n=r.waitTimeoutMs??0,i=r.retryDelayMs??25;if(n<0||i<=0)throw Error("lock wait options must be positive");let o=Qt.dirname(t);be.has(o)||(be.add(o),await async function(t,e=Date.now,r={}){let n;try{n=await I(t)}catch(e){if("ENOENT"===oe(e)){for(let e of ee)te.dirname(e)===t&&ne(e);return 0}throw e}let i=0;for(let o of n){if(!ie.test(o))continue;let n=te.join(t,o);try{let t=await T(n);if(!ee.has(n)&&e()-t.mtimeMs<=36e5)continue;let o=!1;for(let t=0;t<3;t+=1)try{await(r.unlink??R)(n),ne(n),o=!0;break}catch(e){if("ENOENT"===oe(e)){ne(n),o=!0;break}if(!(r.isSharingError?.(e)??se(e)))throw e;t+1===3&&ae(r,n)}o&&(i+=1)}catch(t){"ENOENT"===oe(t)&&ne(n),ae(r,n)}}return i}(o,Date.now,{...void 0===Ee.unlink?{}:{unlink:Ee.unlink},...void 0===Ee.isSharingError?{}:{isSharingError:Ee.isSharingError},onFailure:()=>Se(o)}).catch(()=>{Se(o)}));let a=Date.now()+n;for(;;){r.signal?.throwIfAborted();let n=await ge(t);if(null===n){if(await ve(t,e))return;if(r.signal?.throwIfAborted(),n=await ge(t),null===n)continue}if(!await Ie(t,n,e)){if(r.signal?.throwIfAborted(),Date.now()>=a)throw new pe(t,n.record);await ye(Math.min(i,Math.max(1,a-Date.now())),r.signal)}}}async function Oe(t,e){let r=await ge(t);if(null===r||r.record?.nonce!==e.nonce)return!1;try{return await R(t),!0}catch(t){if("ENOENT"===me(t))return!1;throw t}}async function ke(t,e,r,n){await Ne(t,e,n);try{return await r()}finally{await Oe(t,e)}}Promise.resolve();var Pe=[["\\bAKIA[0-9A-Z]{16}\\b",""],["\\b(?:bearer|token|api[_-]?key|secret|password|passwd|pwd)\\s*[=:]\\s*\\S{1,256}","i"],["\\bAuthorization\\s*:\\s*Bearer\\s+\\S{1,256}","i"],["\\bsk-(?:proj-)?[-_A-Za-z0-9]+\\b",""],["\\b(?:ghp|github_pat|glpat|xox[baprs])-[-_A-Za-z0-9]+\\b",""]];Pe.map(([t,e])=>new RegExp(t,e)),Pe.map(([t,e])=>new RegExp(t,`${e}g`));new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});import{dirname as Te}from"node:path";import{fileURLToPath as Re}from"node:url";Te(Re(import.meta.url));import{dirname as Me}from"node:path";import{fileURLToPath as Ae}from"node:url";Me(Ae(import.meta.url)),new Date(0).toISOString();var $e="\\p{Script=Hangul}\\p{Script=Han}\\p{Script=Hiragana}\\p{Script=Katakana}\\u30fc";new RegExp(`[${$e}]+|(?:(?![${$e}])[\\p{L}\\p{M}\\p{N}])+`,"gu"),new RegExp(`^[${$e}]+$`,"u"),new RegExp(`[${$e}]`,"u"),new RegExp(`[${$e}]`,"gu"),new RegExp(`[\\p{L}${$e}]`,"gu");import{dirname as Le}from"node:path";import{fileURLToPath as Ce}from"node:url";Le(Ce(import.meta.url));function De(t){return Xt(t,"terminal-claim.json")}function Ue(t,e,r){return t.runId===e.runId&&t.attempt===e.attempt&&(void 0===r||t.kind===r)}function qe(t,e){let r=`${t}.${process.pid}.${Kt()}.candidate`;!function(t,e){let r=K(t,"wx",384);try{J(r,`${JSON.stringify(e,null,2)}\n`,"utf8"),$(r)}finally{z(r)}}(r,e);try{L(r,t)}catch(t){if("EEXIST"===Ge(t))return!1;throw t}finally{He(r)}return function(t){let e;try{e=K(t,"r")}catch(t){if("win32"===process.platform&&["EISDIR","EPERM"].includes(Ge(t)??""))return;throw t}try{$(e)}catch(t){if("win32"!==process.platform||!["EPERM","EACCES","EINVAL"].includes(Ge(t)??""))throw t}finally{z(e)}}(zt(t)),!0}function je(t){let e;try{e=U(t,"utf8")}catch(t){if("ENOENT"===Ge(t))return;throw t}try{return{raw:e,claim:Be(JSON.parse(e))}}catch{return{raw:e,claim:void 0}}}async function Fe(t,e,r,n,i,o){let a=await fe("reflection-finalize",{runId:i.runId});return ke(Xt(t,"terminal-claim-recovery.lock"),a,async()=>{let t=je(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||!Je(t.claim,o))return t.claim}He(e)}},{waitTimeoutMs:Number.POSITIVE_INFINITY})}function He(t){try{H(t)}catch(t){if("ENOENT"!==Ge(t))throw t}}function Je(t,e){return"dead"===(e.getPidLiveness??wt)(t.claimantPid)}function Be(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 Ge(t){return t instanceof Error&&"code"in t?String(t.code):void 0}import{join as Ve}from"node:path";async function Ye(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=De(t),a={version:1,kind:r,runId:e.runId,attempt:e.attempt,claimantPid:i},s=0;for(;;){if(qe(o,a))return a;let i=je(o);if(void 0===i)continue;let l=i.claim;if(void 0===l){if(s>0)throw TypeError("Invalid run terminal claim");s+=1,await(n.beforeRecovery?.("invalid"));let r=await Fe(t,o,i,"invalid",e,n);if(void 0!==r)return r;continue}if(Ue(l,e,r))return l;if("publish"!==l.kind||!Je(l,n))return l;await(n.beforeRecovery?.("dead-publish"));let c=await Fe(t,o,i,"dead-publish",e,n);if(void 0!==c)return c}}(t,n,"publish");Ue(i,n,"publish")&&(await rt(Pt(t,"publishing.json"),{version:1,...n,finishedAt:r.finishedAt}),await async function(t,e,r,n=ke,i=fe){let o=await i("reflection-finalize",{runId:e});return n(Ve(t,"terminalization.lock"),o,r,{waitTimeoutMs:Number.POSITIVE_INFINITY})}(t,e.runId,async()=>{if(X(Pt(t,"final.json"))||X(Pt(t,"abandoned.json")))return;if(!Ue(function(t){return Be(JSON.parse(U(De(t),"utf8")))}(t),n,"publish"))return;let i=void 0!==Yt({code:r.childExit.code,stdout:U(e.stdoutPath,"utf8"),stderr:U(e.stderrPath,"utf8"),timedOut:r.timedOut});i&&void 0!==e.nextAttempt&&await nt(Pt(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 rt(Pt(t,"outcome.json"),r),i&&await it(De(t))}))}function Ke(t){try{B(3,`${JSON.stringify(t)}\n`)}catch(t){if(!(t instanceof Error&&"code"in t&&["EPIPE","EBADF"].includes(String(t.code))))throw t}}var ze=process.argv.slice(2);try{if("--child-bootstrap"===ze[0]){if(void 0===ze[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 et(Z(e,"launch.json")),n=yt(),i=t(r.command,[...r.args],{cwd:r.cwd,env:r.env,detached:!1,stdio:["ignore","inherit","inherit"],windowsHide:!0});Ke({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=gt(r.hardDeadlineAt,()=>{"win32"===n?Nt(n,i):xt(process.pid,"SIGTERM")}),s=gt(r.hardDeadlineAt+r.terminationGraceMs,()=>{Ot(n,process.pid)});Ke(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(()=>{a(),s()}))}(ze[1])}else{if(void 0===ze[0])throw TypeError("run directory is required");await async function(e){let r=Z(e,"launch.json"),n=Z(e,"ledger.json"),i=await et(r),o=yt();await nt(n,{launching:!1,pid:process.pid,processStart:await kt(process.pid)});let a,s=K(i.stdoutPath,"w"),l=K(i.stderrPath,"w"),c=t(process.execPath,[W(import.meta.url),"--child-bootstrap",e],{env:process.env,detached:!0,stdio:["pipe",s,l,"pipe"],windowsHide:!0}),u=c.pid,d="",f=c.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{Ot(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===c.pid)throw Error("child bootstrap did not receive a pid");await nt(n,{childPid:c.pid,childProcessStart:await kt(c.pid)}),c.stdin?.end("1\n");let m,w=!1,h=Promise.resolve();"win32"===o&&(h=new Promise(t=>{m=t}));let y=gt(i.hardDeadlineAt,()=>{w=!0,"win32"===o?It(c.pid):Nt(o,c)}),g=gt(i.hardDeadlineAt+i.terminationGraceMs,()=>{Ot(o,a??u),m?.()}),v=await new Promise((t,e)=>{let r=!1;c.once("error",t=>{r||(r=!0,e(t))}),c.once("close",(e,n)=>{r||(r=!0,t({code:e,signal:n}))})}),b=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===b&&await h,y(),g(),u=void 0,z(s),z(l);let E=function(){let t=ht()?process.env.OMO_MEMORY_SUPERVISOR_CLOCK_PATH:void 0;return void 0===t?Date.now():bt(t)}(),S=(new Date).toISOString(),_={version:1,runId:i.runId,attempt:i.attempt,finishedAt:S,childExit:b??v,timedOut:w||Number.isFinite(E)&&E>=i.hardDeadlineAt};await Ye(e,i,_),await it(r),process.exit(0)}(ze[0])}}catch(t){process.stderr.write(`${t instanceof Error?t.stack??t.message:String(t)}\n`),process.exitCode=1}
2
+ // omo:FnFk4hTdD_PkTd2CCM9dX__WMAk6AbaLyUcGHFiItO0:xE1V0Tu0M-W7qbPAWE96oZWECfAaCG1VE1qlEbZRthk
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}}import{Buffer as a}from"node:buffer";import{constants as s}from"node:fs";function l(t){return"number"==typeof t?0!==(t&s.O_EXCL):"string"==typeof t&&t.toLowerCase().includes("x")}async function c(t,e,r,n){let o="string"==typeof e?a.from(e,r??"utf8"):e,s=0;for(;s<o.length;){n?.throwIfAborted();let{bytesWritten:e}=await i(()=>t.write(o,s));if(e<=0)throw Error(`fs write made no progress at offset ${s}`);s+=e}}function u(t){return"function"==typeof t}function d(t){return(...e)=>i(async()=>t(...e))}function f(t){return(...e)=>o(()=>t(...e))}function p(t,e){let r="async"===e?d:f,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(!u(i))return i;let o=r(i),a=Reflect.get(i,"native");return u(a)&&Object.assign(o,{native:r(a)}),n.set(e,o),o}})}var m=new Set(["stat","sync","datasync","chmod","chown","utimes","truncate"]);var w=p(r,"async"),h=p(e,"sync"),{access:y,chmod:g,copyFile:v,cp:b,link:E,lstat:S,mkdir:x,mkdtemp:_,readFile:I,readdir:N,realpath:O,rename:k,rm:P,rmdir:T,stat:M,unlink:R}=w,{accessSync:A,chmodSync:$,fsyncSync:L,linkSync:C,lstatSync:D,mkdirSync:U,readFileSync:q,readdirSync:j,realpathSync:F,statSync:J,unlinkSync:G,writeFileSync:H,writeSync:B}=h,{constants:V,watch:Y}=e,K=async(...t)=>{let e=()=>r.open(...t);return function(t){return new Proxy(t,{get(t,e){let r=Reflect.get(t,e);if(!u(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&&m.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(l(t[1]??"r")?e():i(e)))},z=(t,r,n)=>function(t,e,r,n){return l(r)?t(e,r,n):o(()=>t(e,r,n))}(e.openSync,t,r,n??void 0);function X(t){try{e.closeSync(t)}catch(t){if("EINTR"!==n(t))throw t}}function Z(t){try{return o(()=>e.statSync(t)),!0}catch{return!1}}import{join as W}from"node:path";import{fileURLToPath as Q}from"node:url";import{randomUUID as tt}from"node:crypto";import{dirname as et}from"node:path";async function rt(t){return JSON.parse(await I(t,"utf8"))}async function nt(t,e,r=384){let n=`${t}.tmp-${process.pid}-${tt()}`,i=await K(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 k(n,t),o=!0,await async function(t){try{let e=await K(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}}(et(t))}finally{o||await ot(n)}}async function it(t,e){let r=await rt(t);await nt(t,{...r,...e})}async function ot(t){try{await R(t)}catch(t){if(!(t instanceof Error&&"code"in t&&"ENOENT"===t.code))throw t}}import{spawn as at,spawnSync as st}from"node:child_process";import{execFile as lt}from"node:child_process";var ct=null;function ut(){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 dt=null;async function ft(t){if("win32"!==process.platform)return null;if(!Number.isSafeInteger(t)||t<=0)return null;dt??=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 dt;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 pt(t,e){return await new Promise(r=>{lt(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 mt=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 I(`/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"===ht(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 ut();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 pt("/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"===ht(t))return null;let e=await ft(t);if(null!==e)return`win32-creation-filetime:${e}`;let r=await pt("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 wt(t){let e=t.indexOf(":");return e<=0?null:t.slice(0,e)}function ht(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 yt(){return"1"===process.env.OMO_MEMORY_SUPERVISOR_ALLOW_TEST_SEAMS}function gt(){if(yt()){let t=process.env.OMO_MEMORY_SUPERVISOR_PLATFORM;if("posix"===t||"win32"===t)return t}return"win32"===process.platform?"win32":"posix"}function vt(t,e){let r=yt()?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=Et(r);!Number.isFinite(i)||i<t||(n=!0,o?.close(),clearInterval(a),e())};if(Et(r)>=t)return n=!0,e(),()=>{};let o=Y(r,i),a=setInterval(i,bt);return i(),()=>{n||(n=!0,o.close(),clearInterval(a))}}var bt=25;function Et(t){let e=j(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 St(t,e){if(!yt())return;let r=process.env.OMO_MEMORY_SUPERVISOR_TASKKILL_RUN_DIR;void 0!==r&&H(`${r}/${t}-${process.pid}.json`,`${JSON.stringify({targetPid:e})}\n`,"utf8")}function xt(t){if(!yt())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 _t(t,e,r){let[n,...i]=t;if(void 0===n)throw TypeError("termination command is required");if(r){let t=st(n,[...i,...e],{env:process.env,stdio:"ignore",windowsHide:!0});if(void 0!==t.error)throw t.error;return}at(n,[...i,...e],{env:process.env,stdio:"ignore",windowsHide:!0}).once("error",t=>process.stderr.write(`${t.message}\n`))}function It(t,e){St(`posix-${e}`,t);let r=xt("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 _t(r,["--signal-group",String(t),e],!1)}function Nt(t){void 0!==t&&St("win32-graceful",t)}function Ot(t,e){"win32"===t?(Nt(e.pid),e.kill()):void 0!==e.pid&&It(e.pid,"SIGTERM")}function kt(t,e,r=!1){void 0!==e&&("win32"===t?function(t,e){_t(xt("OMO_MEMORY_SUPERVISOR_TASKKILL_COMMAND")??["taskkill"],["/pid",String(t),"/T","/F"],e)}(e,r):It(e,"SIGKILL"))}async function Pt(t){return await mt(t)}import{join as Tt}from"node:path";function Mt(t){return"object"==typeof t&&null!==t}function Rt(t,e){try{return t?.[e]}catch(t){return void Error}}function At(t,e){let r=Rt(t,e);return Mt(r)?r:void 0}function $t(t){if(!t)return"";if("string"==typeof t)return t.toLowerCase();if(!Mt(t))try{return JSON.stringify(t).toLowerCase()}catch(t){if(!(t instanceof Error))throw t;return""}let e=At(t,"data"),r=[e,At(t,"error"),t,At(e,"error")].filter(t=>void 0!==t);for(let t of r){let e=Rt(t,"message");if("string"==typeof e&&e.length>0)return e.toLowerCase()}let n=Rt(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 Lt(t,e){if(function(t){return"object"==typeof t&&null!==t}(t))try{return t[e]}catch(t){return void Error}}function Ct(t){return"terminal_quota_exhausted"===function(t){let e=Lt(t,"data"),r=Lt(t,"detail")??Lt(e,"detail")??t,n=Lt(r,"error")??r,i=Lt(n,"type")??Lt(r,"type");return"string"==typeof i?i.toLowerCase():void 0}(t)||(e=$t(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 Dt(t){if(Ct(t))return"abort";let e=$t(t),r=function(t){if(!Mt(t))return;let e=At(t,"data"),r=[t,e,At(t,"error"),At(e,"error")].filter(t=>void 0!==t);for(let t of r){let e=Rt(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 Ut=new Set(["providermodelnotfounderror","ratelimiterror","modelunavailableerror","providerconnectionerror","authenticationerror"]),qt=new Set(["messageabortederror","permissiondeniederror","contextlengtherror","timeouterror","validationerror","syntaxerror","usererror"]),jt=["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"],Ft=["rate limit","cooling down","credentials for model"];function Jt(t){let e=t.name?.toLowerCase();if(void 0!==e&&qt.has(e))return!1;if(Ct(t))return!1;if("quota_exceeded"===Dt(t))return!0;if(void 0!==e&&Ut.has(e))return!0;let r=t.message?.toLowerCase()??"";return!(!(n=r).includes("retrying in")||!Ft.some(t=>n.includes(t)))||(null!=t.statusCode&&(429===t.statusCode||503===t.statusCode||529===t.statusCode)||jt.some(t=>r.includes(t)));var n}var Gt=[/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],Ht=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];var Bt=/^Error: Model "([^"]+)" not found\. Use --list-models to see available models\.$/m,Vt=/^(?:Error:\s*)?No API key found for\s+([^\s.]+)/m,Yt=/(?:^|\s)(\d{3})\s*:/;function Kt(t){if(t.timedOut||0===t.code)return;let e=`${t.stderr}\n${t.stdout}`,r=Bt.exec(e)?.[1];if(void 0!==r)return{kind:"model_not_visible",id:r};let n=Vt.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);if(void 0!==t)return t.slice(0,200)}return}(t);if(void 0===i)return;if(o=i,!Ht.some(t=>t.test(o))&&Gt.some(t=>t.test(o)))return{kind:"context_overflow",detail:i};var o;let a=Number.parseInt(Yt.exec(i)?.[1]??"",10);return Jt({message:i,...Number.isNaN(a)?{}:{statusCode:a}})?{kind:"provider_unavailable",detail:i}:void 0}import{randomUUID as zt}from"node:crypto";import{dirname as Xt,join as Zt}from"node:path";import{randomUUID as Wt}from"node:crypto";import{hostname as Qt}from"node:os";import te from"node:path";import ee from"node:path";var re=new Set;function ne(t){re.add(t)}function ie(t){re.delete(t)}var oe=/\.candidate-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ae(t){if(t instanceof Error&&"code"in t)return"string"==typeof t.code?t.code:void 0}function se(t,e){try{t.onFailure?.(e)}catch{}}function le(t){if("win32"!==process.platform)return!1;let e=ae(t);return"EBUSY"===e||"EPERM"===e||"EACCES"===e}import{randomUUID as ce}from"node:crypto";import{hostname as ue}from"node:os";function de(t){return"string"==typeof t&&t.length>0}function fe(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:de(r.process_start)&&de(r.hostname)&&de(r.nonce)?!de(r.created_at)||Number.isNaN(Date.parse(r.created_at))?null:de(r.purpose)&&(void 0===r.run_id||de(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 pe(t,e={}){if(0===t.length)throw Error("lock purpose must not be empty");let r=await mt(process.pid);return{pid:process.pid,process_start:r??"unavailable",hostname:ue(),nonce:ce(),created_at:(new Date).toISOString(),purpose:t,...void 0===e.runId?{}:{run_id:e.runId}}}var me=new Set(["EACCES","EPERM","ENOTSUP"]);class we extends Error{lockPath;owner;retriable=!0;constructor(t,e){super(`Lock is held: ${t}`),this.lockPath=t,this.owner=e,this.name="LockContentionError"}}function he(t){if(t instanceof Error&&"code"in t)return"string"==typeof t.code?t.code:void 0}function ye(t,e){if(void 0!==e)return e(t);if("win32"!==process.platform)return!1;let r=he(t);return"EBUSY"===r||"EPERM"===r||"EACCES"===r}async function ge(t){for(let e=0;e<3;e+=1)try{return await(xe.unlink??R)(t),ie(t),!0}catch(r){if("ENOENT"===he(r))return ie(t),!0;if(!ye(r,xe.isSharingError))throw ne(t),_e(te.dirname(t)),r;if(e+1===3)return ne(t),_e(te.dirname(t)),!1}return!1}function ve(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})})}async function be(t){try{let e=await I(t,"utf8"),r=await M(t,{bigint:!0});return{raw:e,record:fe(e),dev:r.dev,ino:r.ino,mtimeMs:Number(r.mtimeMs)}}catch(t){let e=he(t);if("ENOENT"===e)return null;if("\\"===te.sep&&"EPERM"===e)return{raw:"",record:null,dev:0,ino:0,mtimeMs:Date.now()};throw t}}async function Ee(t,e){await x(te.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-${Wt()}`;try{return{candidatePath:r,handle:await K(r,"wx",384)}}catch(n){if(await ge(r)||_e(te.dirname(t)),"EINTR"!==he(n)||e>=128)throw n}}}(t);try{try{await c(n,`${JSON.stringify(e)}\n`,"utf8"),await n.sync()}finally{await n.close()}try{return await(xe.link??E)(r,t),!0}catch(r){if(function(t){let e=he(t);return"EEXIST"===e||"ENOENT"===e}(r))return!1;if(me.has(he(r)??""))return await async function(t,e){let r;try{r=await K(t,"wx",384)}catch(t){if("EEXIST"===he(t))return!1;throw t}try{return await(xe.writeFallback??c)(r,`${JSON.stringify(e)}\n`,"utf8"),await r.sync(),!0}finally{await r.close()}}(t,e);throw r}}finally{await ge(r)||_e(te.dirname(t))}}var Se=new Set,xe={};function _e(t){Se.delete(t)}async function Ie(t){if(t.hostname!==Qt())return!1;let e=ht(t.pid);if("dead"===e)return!0;if("unknown"===e)return!1;let r=await mt(t.pid);return null!==r&&"unavailable"!==t.process_start&&function(t,e){let r=wt(t);return null!==r&&r===wt(e)&&t!==e}(t.process_start,r)}function Ne(t,e){return t.dev===e.dev&&t.ino===e.ino&&t.mtimeMs===e.mtimeMs&&t.raw===e.raw}async function Oe(t,e,r){return null!==t.record?Ie(t.record):e-t.mtimeMs>r}async function ke(t,e,r){let n=await be(t);if(null===n||!await Oe(n,e,r))return!1;let i=`${t}.reaping-${Wt()}`;try{await k(t,i)}catch(t){if("ENOENT"===he(t))return!1;if(ye(t))return!1;throw t}let o=await be(i);if(null!==o&&Ne(o,n))return await R(i),!0;try{await E(i,t)}catch(t){if("EEXIST"!==he(t))throw t}return await R(i),!1}async function Pe(t,e,r,n,i){if(!await Oe(e,n,i))return!1;let o=`${t}.recovery`,a={...r,nonce:Wt(),created_at:(new Date).toISOString(),purpose:`${r.purpose}:recovery`};for(let t=0;!await Ee(o,a);t+=1)if(t>0||!await ke(o,n,i))return!1;try{let r=await be(t);if(null===r)return!0;if(!Ne(r,e))return!1;if(!await Oe(r,n,i))return!1;let s=await be(o);return null!==s&&s.record?.nonce===a.nonce&&(await R(t),!0)}finally{await Me(o,a)}}async function Te(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=te.dirname(t);Se.has(s)||(Se.add(s),await async function(t,e=Date.now,r={}){let n;try{n=await N(t)}catch(e){if("ENOENT"===ae(e)){for(let e of re)ee.dirname(e)===t&&ie(e);return 0}throw e}let i=0;for(let o of n){if(!oe.test(o))continue;let n=ee.join(t,o);try{let t=await M(n);if(!re.has(n)&&e()-t.mtimeMs<=36e5)continue;let o=!1;for(let t=0;t<3;t+=1)try{await(r.unlink??R)(n),ie(n),o=!0;break}catch(e){if("ENOENT"===ae(e)){ie(n),o=!0;break}if(!(r.isSharingError?.(e)??le(e)))throw e;t+1===3&&se(r,n)}o&&(i+=1)}catch(t){"ENOENT"===ae(t)&&ie(n),se(r,n)}}return i}(s,Date.now,{...void 0===xe.unlink?{}:{unlink:xe.unlink},...void 0===xe.isSharingError?{}:{isSharingError:xe.isSharingError},onFailure:()=>_e(s)}).catch(()=>{_e(s)}));let l=a()+n;for(;;){r.signal?.throwIfAborted();let n=await be(t);if(null===n){if(await Ee(t,e))return;if(r.signal?.throwIfAborted(),n=await be(t),null===n)continue}if(!await Pe(t,n,e,a(),o)){if(r.signal?.throwIfAborted(),a()>=l)throw new we(t,n.record);await ve(Math.min(i,Math.max(1,l-a())),r.signal)}}}async function Me(t,e){let r=await be(t);if(null===r||r.record?.nonce!==e.nonce)return!1;try{return await R(t),!0}catch(t){if("ENOENT"===he(t))return!1;throw t}}async function Re(t,e,r,n){await Te(t,e,n);try{return await r()}finally{await Me(t,e)}}Promise.resolve();var Ae=[["\\bAKIA[0-9A-Z]{16}\\b",""],["\\b(?:bearer|token|api[_-]?key|secret|password|passwd|pwd)\\s*[=:]\\s*\\S{1,256}","i"],["\\bAuthorization\\s*:\\s*Bearer\\s+\\S{1,256}","i"],["\\bsk-(?:proj-)?[-_A-Za-z0-9]+\\b",""],["\\b(?:ghp|github_pat|glpat|xox[baprs])-[-_A-Za-z0-9]+\\b",""]];Ae.map(([t,e])=>new RegExp(t,e)),Ae.map(([t,e])=>new RegExp(t,`${e}g`));new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});import{dirname as $e}from"node:path";import{fileURLToPath as Le}from"node:url";$e(Le(import.meta.url));import{dirname as Ce}from"node:path";import{fileURLToPath as De}from"node:url";Ce(De(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 qe}from"node:path";import{fileURLToPath as je}from"node:url";qe(je(import.meta.url));function Fe(t){return Zt(t,"terminal-claim.json")}function Je(t,e,r){return t.runId===e.runId&&t.attempt===e.attempt&&(void 0===r||t.kind===r)}function Ge(t,e){let r=`${t}.${process.pid}.${zt()}.candidate`;!function(t,e){let r=z(t,"wx",384);try{H(r,`${JSON.stringify(e,null,2)}\n`,"utf8"),L(r)}finally{X(r)}}(r,e);try{C(r,t)}catch(t){if("EEXIST"===ze(t))return!1;throw t}finally{Ve(r)}return function(t){let e;try{e=z(t,"r")}catch(t){if("win32"===process.platform&&["EISDIR","EPERM"].includes(ze(t)??""))return;throw t}try{L(e)}catch(t){if("win32"!==process.platform||!["EPERM","EACCES","EINVAL"].includes(ze(t)??""))throw t}finally{X(e)}}(Xt(t)),!0}function He(t){let e;try{e=q(t,"utf8")}catch(t){if("ENOENT"===ze(t))return;throw t}try{return{raw:e,claim:Ke(JSON.parse(e))}}catch{return{raw:e,claim:void 0}}}async function Be(t,e,r,n,i,o){let a=await pe("reflection-finalize",{runId:i.runId});return Re(Zt(t,"terminal-claim-recovery.lock"),a,async()=>{let t=He(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||!Ye(t.claim,o))return t.claim}Ve(e)}},{waitTimeoutMs:Number.POSITIVE_INFINITY})}function Ve(t){try{G(t)}catch(t){if("ENOENT"!==ze(t))throw t}}function Ye(t,e){return"dead"===(e.getPidLiveness??ht)(t.claimantPid)}function Ke(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 ze(t){return t instanceof Error&&"code"in t?String(t.code):void 0}import{join as Xe}from"node:path";async function Ze(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=Fe(t),a={version:1,kind:r,runId:e.runId,attempt:e.attempt,claimantPid:i},s=0;for(;;){if(Ge(o,a))return a;let i=He(o);if(void 0===i)continue;let l=i.claim;if(void 0===l){if(s>0)throw TypeError("Invalid run terminal claim");s+=1,await(n.beforeRecovery?.("invalid"));let r=await Be(t,o,i,"invalid",e,n);if(void 0!==r)return r;continue}if(Je(l,e,r))return l;if("publish"!==l.kind||!Ye(l,n))return l;await(n.beforeRecovery?.("dead-publish"));let c=await Be(t,o,i,"dead-publish",e,n);if(void 0!==c)return c}}(t,n,"publish");Je(i,n,"publish")&&(await nt(Tt(t,"publishing.json"),{version:1,...n,finishedAt:r.finishedAt}),await async function(t,e,r,n=Re,i=pe){let o=await i("reflection-finalize",{runId:e});return n(Xe(t,"terminalization.lock"),o,r,{waitTimeoutMs:Number.POSITIVE_INFINITY})}(t,e.runId,async()=>{if(Z(Tt(t,"final.json"))||Z(Tt(t,"abandoned.json")))return;if(!Je(function(t){return Ke(JSON.parse(q(Fe(t),"utf8")))}(t),n,"publish"))return;let i=void 0!==Kt({code:r.childExit.code,stdout:q(e.stdoutPath,"utf8"),stderr:q(e.stderrPath,"utf8"),timedOut:r.timedOut});i&&void 0!==e.nextAttempt&&await it(Tt(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 nt(Tt(t,"outcome.json"),r),i&&await ot(Fe(t))}))}function We(t){try{B(3,`${JSON.stringify(t)}\n`)}catch(t){if(!(t instanceof Error&&"code"in t&&["EPIPE","EBADF"].includes(String(t.code))))throw t}}var Qe=process.argv.slice(2);try{if("--child-bootstrap"===Qe[0]){if(void 0===Qe[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 rt(W(e,"launch.json")),n=gt(),i=t(r.command,[...r.args],{cwd:r.cwd,env:r.env,detached:!1,stdio:["ignore","inherit","inherit"],windowsHide:!0});We({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=vt(r.hardDeadlineAt,()=>{"win32"===n?Ot(n,i):It(process.pid,"SIGTERM")}),s=vt(r.hardDeadlineAt+r.terminationGraceMs,()=>{kt(n,process.pid)});We(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(()=>{a(),s()}))}(Qe[1])}else{if(void 0===Qe[0])throw TypeError("run directory is required");await async function(e){let r=W(e,"launch.json"),n=W(e,"ledger.json"),i=await rt(r),o=gt();await it(n,{launching:!1,pid:process.pid,processStart:await Pt(process.pid)});let a,s=z(i.stdoutPath,"w"),l=z(i.stderrPath,"w"),c=t(process.execPath,[Q(import.meta.url),"--child-bootstrap",e],{env:process.env,detached:!0,stdio:["pipe",s,l,"pipe"],windowsHide:!0}),u=c.pid,d="",f=c.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{kt(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===c.pid)throw Error("child bootstrap did not receive a pid");await it(n,{childPid:c.pid,childProcessStart:await Pt(c.pid)}),c.stdin?.end("1\n");let m,w=!1,h=Promise.resolve();"win32"===o&&(h=new Promise(t=>{m=t}));let y=vt(i.hardDeadlineAt,()=>{w=!0,"win32"===o?Nt(c.pid):Ot(o,c)}),g=vt(i.hardDeadlineAt+i.terminationGraceMs,()=>{kt(o,a??u),m?.()}),v=await new Promise((t,e)=>{let r=!1;c.once("error",t=>{r||(r=!0,e(t))}),c.once("close",(e,n)=>{r||(r=!0,t({code:e,signal:n}))})}),b=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===b&&await h,y(),g(),u=void 0,X(s),X(l);let E=function(){let t=yt()?process.env.OMO_MEMORY_SUPERVISOR_CLOCK_PATH:void 0;return void 0===t?Date.now():Et(t)}(),S=(new Date).toISOString(),x={version:1,runId:i.runId,attempt:i.attempt,finishedAt:S,childExit:b??v,timedOut:w||Number.isFinite(E)&&E>=i.hardDeadlineAt};await Ze(e,i,x),await ot(r),process.exit(0)}(Qe[0])}}catch(t){process.stderr.write(`${t instanceof Error?t.stack??t.message:String(t)}\n`),process.exitCode=1}