omo-ai 5.0.0-0.beta.90 → 5.0.0

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.
@@ -2,6 +2,7 @@ import { closeSync, lstatSync, openSync, readFileSync, readSync, realpathSync, s
2
2
  import { homedir } from "node:os"
3
3
  import { delimiter, dirname, isAbsolute, join, win32 } from "node:path"
4
4
  import { parseJsonc } from "./jsonc.js"
5
+ import { releaseChannel } from "./package-paths.js"
5
6
  import { opencodeConfigSources } from "./setup-opencode-assets.js"
6
7
 
7
8
  // Migration leftovers from the OpenCode edition, reported and never touched: another `omo` ahead of
@@ -13,7 +14,12 @@ const NATIVE_PACKAGE = "omo-ai"
13
14
  const LEGACY_PACKAGES = ["oh-my-openagent", "oh-my-opencode"]
14
15
  // The native installer repairs an `omo` owned by any of these, so the fix it names works for them.
15
16
  const REPAIRABLE_BIN_OWNERS = [...LEGACY_PACKAGES, "lazycodex"]
16
- const REPAIR_COMMAND = "bunx oh-my-openagent@beta install --platform=native"
17
+ // The installer that repairs it is published on the same channel as this build. Resolved when a line
18
+ // is formatted, never at import: the compiled omo binary imports this module before first-run
19
+ // provisioning, when no package manifest is readable yet (#8891).
20
+ function repairCommand() {
21
+ return `bunx ${releaseChannel() === "beta" ? "oh-my-openagent@beta" : "oh-my-openagent"} install --platform=native`
22
+ }
17
23
 
18
24
  const CODEX_LIGHT_WRAPPER_MARKER = "# OMO_GENERATED_RUNTIME_WRAPPER"
19
25
  const CODEX_LIGHT_CACHE_VERSION = /[\\/]plugins[\\/]cache[\\/]sisyphuslabs[\\/]omo[\\/]([^\\/"'\s]+)[\\/]/
@@ -244,7 +250,7 @@ export function formatMigrationLines({ shadowing, nativeDirectory, legacyPackage
244
250
  const lines = []
245
251
  for (const entry of shadowing) {
246
252
  const fix = entry.kind === "legacy"
247
- ? `${REPAIR_COMMAND} (repairs it), or remove that file.`
253
+ ? `${repairCommand()} (repairs it), or remove that file.`
248
254
  : nativeDirectory === null
249
255
  ? "remove that file, or put omo-ai's bin dir ahead of it on PATH."
250
256
  : `remove that file, or move ${nativeDirectory} ahead of ${entry.directory} on PATH.`
package/bin/lib/doctor.js CHANGED
@@ -3,7 +3,7 @@ import { existsSync, readFileSync, readdirSync, statSync } from "node:fs"
3
3
  import { homedir } from "node:os"
4
4
  import { join, resolve } from "node:path"
5
5
  import { canonicalAgentDir } from "./agent-dir.js"
6
- import { packageManifest, packageRoot, readJson, resolveSenpi, updateTarget } from "./package-paths.js"
6
+ import { packageManifest, packageRoot, readJson, releaseChannel, resolveSenpi, updateTarget } from "./package-paths.js"
7
7
  import { daemonReportLines } from "./daemon.js"
8
8
  import { migrationReport } from "./doctor-migration.js"
9
9
  import { needsSetupSuggestion } from "./setup-detect.js"
@@ -16,7 +16,7 @@ const NPM_FETCH_TIMEOUT_MS = 5000
16
16
  // synchronous and turns any network failure into "could not check".
17
17
 
18
18
  export function installedDistTag(version) {
19
- return typeof version === "string" && version.includes("beta") ? "beta" : "latest"
19
+ return releaseChannel(version)
20
20
  }
21
21
 
22
22
  export function latestFromDistTags(distTags, version) {
@@ -8,7 +8,7 @@ import { runDoctor } from "./doctor.js"
8
8
  import { ensureEnginePrepared } from "./engine-prepare.js"
9
9
  import { migrateLegacyBunGlobalManifest } from "./legacy-bun-global-migration.js"
10
10
  import { adoptLegacyFlatState, canonicalAgentDir } from "./agent-dir.js"
11
- import { nearestNodeBin, packageManifest, packageRoot, readJson, resolveSenpi, updateTarget } from "./package-paths.js"
11
+ import { nearestNodeBin, packageManifest, packageRoot, readJson, releaseChannel, resolveSenpi, updateTarget } from "./package-paths.js"
12
12
  import { runSelfUpdate } from "./self-update.js"
13
13
  import { detectHarnesses } from "./setup-detect.js"
14
14
  import { readSetupSuggestionCache, spawnSetupSuggestionRefresh } from "./setup-detect-cache.js"
@@ -63,7 +63,7 @@ function brandProfile() {
63
63
  ...(changelog ? { changelog } : {}),
64
64
  update: {
65
65
  packageName: "omo-ai",
66
- distTag: "beta",
66
+ distTag: releaseChannel(),
67
67
  command: update.command,
68
68
  changelogUrl: "https://github.com/code-yeongyu/oh-my-openagent/releases",
69
69
  },
@@ -14,7 +14,26 @@ export function packageManifest() {
14
14
 
15
15
  const BUN_GLOBAL_PACKAGE_SUFFIX = "/install/global/node_modules/omo-ai"
16
16
 
17
- export function updateTarget(root = packageRoot, platform = process.platform) {
17
+ /** The npm dist-tag this build ships on: a prerelease version is on beta, a stable one on latest. */
18
+ export function releaseChannel(version = packageManifest().version) {
19
+ return typeof version === "string" && version.includes("-") ? "beta" : "latest"
20
+ }
21
+
22
+ /** The package spec that installs this build's channel: `omo-ai@beta` or the bare `omo-ai`. */
23
+ export function channelPackageSpec(version = packageManifest().version) {
24
+ return releaseChannel(version) === "beta" ? "omo-ai@beta" : "omo-ai"
25
+ }
26
+
27
+ function installedVersion(root) {
28
+ try {
29
+ return readJson(join(root, "package.json")).version
30
+ } catch {
31
+ return packageManifest().version
32
+ }
33
+ }
34
+
35
+ export function updateTarget(root = packageRoot, platform = process.platform, version = installedVersion(root)) {
36
+ const spec = channelPackageSpec(version)
18
37
  const updateCwd = dirname(join(root, "package.json"))
19
38
  const normalizedRoot = updateCwd.replaceAll("\\", "/")
20
39
  if (normalizedRoot.endsWith(BUN_GLOBAL_PACKAGE_SUFFIX)) {
@@ -25,15 +44,15 @@ export function updateTarget(root = packageRoot, platform = process.platform) {
25
44
  const bunInstall = normalizedRoot.slice(0, -BUN_GLOBAL_PACKAGE_SUFFIX.length)
26
45
  return {
27
46
  manager: "bun",
28
- command: "bun add -g omo-ai@beta",
29
- argv: ["bun", "add", "-g", "omo-ai@beta"],
47
+ command: `bun add -g ${spec}`,
48
+ argv: ["bun", "add", "-g", spec],
30
49
  env: { BUN_INSTALL: bunInstall },
31
50
  }
32
51
  }
33
52
  return {
34
53
  manager: "npm",
35
- command: "npm i -g omo-ai@beta",
36
- argv: ["npm", "i", "-g", "omo-ai@beta"],
54
+ command: `npm i -g ${spec}`,
55
+ argv: ["npm", "i", "-g", spec],
37
56
  }
38
57
  }
39
58
 
@@ -1,5 +1,5 @@
1
1
  {
2
- "_comment": "Derived from @code-yeongyu/senpi 2026.9.24-3 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.9.26 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,8 +1,8 @@
1
1
  {
2
2
  "name": "omo-ai",
3
- "version": "5.0.0-0.beta.90",
3
+ "version": "5.0.0",
4
4
  "type": "module",
5
- "description": "OmO Native - the standalone omo command with the OMO extension built in. Beta channel only: bun add -g omo-ai@beta",
5
+ "description": "OmO Native - the standalone omo command with the OMO extension built in: bun add -g omo-ai",
6
6
  "bin": {
7
7
  "omo": "bin/omo.js"
8
8
  },
@@ -18,7 +18,7 @@
18
18
  },
19
19
  "dependencies": {
20
20
  "@babel/parser": "8.0.4",
21
- "@code-yeongyu/senpi": "2026.9.24-3"
21
+ "@code-yeongyu/senpi": "2026.9.26"
22
22
  },
23
23
  "repository": {
24
24
  "type": "git",
@@ -7,6 +7,82 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ### Changed
11
+
12
+ **A local `omo` install now tells you to update with bun.** The launcher that `oh-my-openagent install` writes for a local checkout answered `omo update` with `npm i -g omo-ai`; it now prints `bun add -g omo-ai` (`omo-ai@beta` on a prerelease build), like every other install instruction. Installs from npm keep getting the npm command from `omo update`.
13
+
14
+ ### Fixed
15
+
16
+ **An expired Claude login no longer breaks the first headless or desktop turn.** With no `model_profile` set, OmO Native starts on the Recommended ladder, and a Claude subscription whose saved login can no longer be refreshed still counted as connected: the session was pinned to Claude Opus 5.5, every turn failed on the refresh, and the retry walked only other Claude models before giving up, even when another provider on the ladder (for example Z.ai GLM 5.3) was connected. A model profile now resolves a rung's credentials the way its first turn would before picking it: a login that cannot be refreshed drops that provider and the walk moves on; a provider with several accounts stays eligible while any of them (the pinned one, when an account is pinned) resolves, unless rotation is turned off for it (`credentials.rotation: false` in `models.json`, or a runtime API key), in which case only its default credential counts; a model whose own request configuration fails to resolve drops only that model. The start notice names what was skipped and how to recover on that surface: the desktop points at Provider authentication settings, a headless run at an interactive session's `/login <provider>`. A literal `provider/model` pin in `model_profile` is still applied as written. The resolution runs once per attempted account at session start, sequentially, so a rejected login can add up to the provider's refresh timeout before the next rung is picked.
17
+
18
+ **A delegated task no longer retries a provider that already rejected your credentials.** When a subagent's turn failed because a provider refused the key (for example an OpenCode Go key whose subscription lapsed, carried over by `omo setup`) or an OAuth login could not be refreshed, the task retried the next model on the same provider, which failed the same way. It now skips the rest of that provider and moves to the next provider in the category, or, when none is left, reports the error with how to re-authenticate that provider (Provider authentication settings on the desktop, `/login <provider>` in an interactive session). This covers subagents running as separate processes (the default on macOS and Linux); an in-process subagent still walks its chain inside the engine.
19
+
20
+ ## [5.0.0] - 2026-09-26
21
+
22
+ ### PLEASE REMOVE OPENCODE V1 FOR OMO, LAZYCODEX, IMMEDIATELY.
23
+
24
+ Because OmO Native is out for real. 5.0.0 is its first stable release, and `bun add -g omo-ai` installs it from npm's default channel with no `@beta` tag.
25
+
26
+ ```bash
27
+ bun add -g omo-ai
28
+ ```
29
+
30
+ Strictly speaking you don't have to remove anything. The OmO plugin for OpenCode v1 and LazyCodex keep running, but from here on they get degraded support: new features land in OmO Native first, and some never reach the plugins because the hosts cannot carry them. We recommend removing them anyway. We stopped using them weeks ago, not out of neglect, but because OmO Native is what we keep reaching for.
31
+
32
+ OmO Native is the `omo` command: the pi-based senpi engine with the OMO extension built in. The rest of these notes are for people who run omo today as the OpenCode plugin (oh-my-openagent) or as LazyCodex on the Codex CLI.
33
+
34
+ ### Moving from the OpenCode edition or LazyCodex
35
+
36
+ ```bash
37
+ bunx oh-my-openagent install --platform=native # or: bun add -g omo-ai
38
+ omo setup
39
+ omo doctor
40
+ ```
41
+
42
+ The installer removes the stale global `omo` that oh-my-openagent 4.19.x and older shipped, installs `omo-ai` with bun (npm when bun is missing) and checks that `omo` on your PATH is the new one. `omo setup` reads what your OpenCode install already knows and carries it across after one confirmation: provider API keys, custom OpenAI- or Anthropic-compatible providers from `opencode.jsonc`, MCP servers, global skills and your model choices. OAuth logins are listed with the `/login` command to run, since tokens do not move between tools. `omo doctor` then prints which task categories your connected providers can run and what the OpenCode edition left behind, each with the command that fixes it. `omo update` updates in place.
43
+
44
+ ### What you get that the plugins could not give you
45
+
46
+ | | OpenCode edition / LazyCodex | OmO Native |
47
+ | --- | --- | --- |
48
+ | Runtime | a plugin inside someone else's host, restarted to apply | one `omo` binary on the senpi engine |
49
+ | Tool calls | one tool per model turn | first-party CodeMode: code that calls tools, in parallel |
50
+ | Memory | none built in | git-backed memory with a self block, reflection, and Kibitzer recall |
51
+ | Multi-model work | Team Mode (OpenCode), `spawn_agent` (Codex) | mass ulw: a DAG of nodes routed to different models |
52
+ | Browser | MCP add-ons | omowright built in, attached to your own browser |
53
+
54
+ **The engine.** senpi is our fork of pi. The OMO extension loads into it directly instead of negotiating with a host's plugin API, so hooks, tools and the TUI behave the same on every platform. Cold start to ready fell from 5.8 s to 850 ms across three profiling rounds, and `omo --help` answers in 28 ms.
55
+
56
+ **Memory, and Kibitzer.** Memory lives in a git repository of markdown files. Persona, the person you work with, and a self block are projected into every session. The self block is how the agent forms a self: from what you call it and how you work with it. Reflection and dreaming run as sandboxed background workers after a session settles. Kibitzer is the new part. It is a second agent loop that runs beside your main session on the cheap `quick` category, and it wakes only when a turn touches a memory it has not judged yet. It reads with five read-only tools, checks, and then drops the "oh right" into your conversation through a single hidden nudge. It cannot write memory. Recall costs about 5 ms per tool call on a large corpus, down from 308 ms, and the model it runs on is pinned to the `quick` chain so it never lands on a frontier-priced model.
57
+
58
+ **CodeMode.** Every step can be a JavaScript or Python eval cell whose prelude carries `tool.<name>()`, `parallel()`, `pipeline()` and `agent()`. Twenty reads become one cell and one round trip. On our own sessions, with the model held the same, OmO Native used about half the context per round trip that the OpenCode edition did (0.39x on GPT-5.5, 0.69x on Opus 4.8), and a live GPT-6 Astra session reports a 97.5% prompt-cache hit in its footer.
59
+
60
+ **mass ulw.** Put "mass ulw" in a prompt and the work becomes a graph: nodes with dependency edges, each routed by category to a different model, fed through workpools with retries and recovery. The graph runs live in the TUI and in a herdr side pane ([omo-herdr-dag](https://github.com/jc01rho/omo-herdr-dag) by @jc01rho).
61
+
62
+ **Browser use.** omowright ships with OmO Native. It drives the browser you already use, with your logins, through BrowserSkill, and hands off to you for a login, CAPTCHA or one-time code. For bot-scored sites it runs its own Chromium on a cloaked profile. Nothing to install.
63
+
64
+ **You can see what it is doing.** Your first request opens a phased todo list. Every todo change names your original request, the task in progress and the next one, and the agent reports when the plan is set, when a phase closes and when the work ends. A turn that stops with todos open gets one nudge to finish them. Persistent monitors survive a restart, and questions arrive as cards you answer with a digit or a click.
65
+
66
+ **Lighter on your machine.** Subagents run as sessions inside one shared daemon instead of one engine process each. File watching is one worker per host, where 1,000 sessions used to mean 1,023 threads. Background processes die with the session that started them.
67
+
68
+ **Models.** You name the kind of work and omo picks the model for it. `deep-low`, the default deep lane, now runs GPT-5.6 Sol Fast at medium. Model profiles offer Daily and Geeky lanes, each in Normal and Heavy. Claude, ChatGPT, Kimi and GLM subscriptions sign in with `/login`.
69
+
70
+ ### OpenCode v2
71
+
72
+ We know about OpenCode v2. Our answer to it is coming, and it takes time. Until then, please run OmO Native: it is the version we use every day, and the one this release was built with.
73
+
74
+ ### Next
75
+
76
+ A desktop app is coming soon, and computer use after it.
77
+
78
+ ### Changed
79
+
80
+ **`deep-low` runs GPT-5.6 Sol Fast at medium.** ([#8885](https://github.com/code-yeongyu/oh-my-openagent/issues/8885)) The default deep delegation lane now starts on `gpt-5.6-sol-fast` (medium) on the ChatGPT subscription and OpenAI API lanes and falls back to `gpt-5.6-sol` (medium), which GitHub Copilot and OpenCode Zen also serve. The lane is offered whenever one of those two models is connected, so an account that only has GPT-6 Sol no longer sees it; pin `categories.deep-low.model` to keep a GPT-6 Sol setup.
81
+
82
+ **A stable release ships OmO Native on `latest`, and a stable build stops asking for `@beta`.** ([#8887](https://github.com/code-yeongyu/oh-my-openagent/issues/8887)) The release pipeline now takes omo-ai's channel from the version it publishes: a prerelease still goes to `beta` as `X.Y.Z-0.<suffix>`, while a stable version goes to `latest` as exactly `X.Y.Z`, so `bun add -g omo-ai` installs it with no tag. The dist-tag guard and the live-install check follow the same channel. Every place that prints an install or update line (the update banner, `omo update`, `omo doctor`, the launcher's reinstall hints, the OpenCode installer and its in-session nudge, the post-install notice, and the release-notes footer) derives it from the running build's version.
83
+
84
+ **OmO Native moves to senpi 2026.9.26.** ([#8882](https://github.com/code-yeongyu/oh-my-openagent/issues/8882), [senpi#2139](https://github.com/code-yeongyu/senpi/issues/2139), [senpi#2137](https://github.com/code-yeongyu/senpi/issues/2137), [senpi#2135](https://github.com/code-yeongyu/senpi/issues/2135), [senpi#2143](https://github.com/code-yeongyu/senpi/issues/2143)) The Cursor CLI lane now sends your request together with the hidden messages of the same turn, so the first request of a session no longer reaches the model as an empty plan reminder. The first-turn plan waits for your own first request instead of arming on an onboarding greeting. A handoff block that restates your request is no longer mistaken for a repeating turn, while a turn that really repeats is still stopped.
85
+
10
86
  ## [5.0.0-beta.90] - 2026-09-24
11
87
 
12
88
  ### Changed
@@ -328,7 +404,6 @@ A selected row no longer earns a `border-l-2 border-primary` stripe, and a focus
328
404
 
329
405
  **A session that reattaches to another host generation keeps its memory.** Your memory identity was derived from the directory the host process happened to be started in, not from the session's own workspace. One shared host serves sessions from many projects, so a host ensured from somewhere else handed its own identity to every session that reattached to it: the session was told `memory identity conflict: session is bound to <workspace>-<hash>, but config resolved server-<hash>`, and its memory tools went away while the workspace had not moved at all. Identity now comes from the session's own working directory, and a reattach that still disagrees rebinds to the identity recorded in the session and notes it in the log instead of stopping. The error is kept for the case it was written for: you pointed `memory.agent` at a different identity yourself. ([#8556](https://github.com/code-yeongyu/oh-my-openagent/issues/8556))
330
406
 
331
-
332
407
  ## [5.0.0-beta.80] - 2026-09-20
333
408
 
334
409
  ### Changed
@@ -477,7 +552,6 @@ get it too instead of only a first spawn. ([#8492](https://github.com/code-yeong
477
552
 
478
553
  **RPC socket host: session-event credit on queue acceptance, 30 s dead-peer stall budget, observable cut notice.** (senpi [#1774](https://github.com/code-yeongyu/senpi/issues/1774))
479
554
 
480
-
481
555
  ### OmO
482
556
 
483
557
  **Startup work that nobody waits for no longer runs before the first paint.** Three pieces of the omo-senpi plugin ran on the path the user waits through before the prompt appears, and none of them is observable before the first turn: the init-deep advisor spawned `git rev-parse` and stat'd the onboarding marker from its `session_start` handler just to decide it was ineligible (12.4 ms warm, 20.6 ms cold), the OmO-native session telemetry read the model inventory, loaded omo config twice and built its PostHog client on the same dispatch path (1.8 ms warm, 14.2 ms on the first session of a UTC day), and the LSP component built its mutation formatter - an omo-config read plus a formatter-marker scan - while it registered, for a step only a `tool_result` can reach. The advisor and the telemetry capture now run on the first post-paint edge (`input` / `before_agent_start`, or a 750 ms backstop), the formatter is constructed on the first mutation tool result, and the legacy telemetry product config no longer reads the package manifest at module scope. Tool, command, flag and hook registration is untouched: the engine's tables are complete before the first prompt exactly as before. Measured through a real senpi launch with the plugin (15 interleaved ABBA rounds): `interactiveMode.init` 97 ms to 84 ms median, 83 ms to 69 ms min; the plugin's `factory` row is unchanged at 37 ms. ([#8412](https://github.com/code-yeongyu/oh-my-openagent/issues/8412))
@@ -776,7 +850,6 @@ OmO Native stops greeting you with its entire history, and memory gains a reside
776
850
 
777
851
  The changelog selection fix above lives in the engine and ships with this release. Also included: a cold-start fix for the RPC host, a goal-contract correction so a harness goal advises the loop instead of gating it, and Windows fixes for thread-socket discovery and a DAG race.
778
852
 
779
-
780
853
  ## [5.0.0-beta.1] - 2026-08-09
781
854
 
782
855
  - 13db09a1a Merge pull request #6676 from code-yeongyu/release/v5.0.0-beta.1-source-state
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- // omo:HYLfGSI9QC5bhFXSipZIwXGOPwxCeb7X17Q2sU6caT4:JP635pDLM0iUC-ojQJEN4onwPVNicwkc7_8GFsBcFnk
2
+ // omo:V8SsOapKLPoD1Y59EMAxSXgZwRKAqYz_NvqArm1UGEI:JP635pDLM0iUC-ojQJEN4onwPVNicwkc7_8GFsBcFnk
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}}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:v,cp:g,link:E,lstat:b,mkdir:S,mkdtemp:I,readFile:_,readdir:x,realpath:N,rename:O,rm:k,rmdir:P,stat:T,unlink:R}=m,{accessSync:M,chmodSync:A,fsyncSync:$,linkSync:D,lstatSync:C,mkdirSync:L,readFileSync:U,readdirSync:j,realpathSync:F,statSync:q,unlinkSync:B,writeFileSync:G,writeSync:J}=w,{constants:H,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)))},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 K(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 _(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 _(`/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 vt(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=Et(r);!Number.isFinite(i)||i<t||(n=!0,o?.close(),clearInterval(a),e())};if(Et(r)>=t)return n=!0,e(),()=>{};let o=V(r,i),a=setInterval(i,gt);return i(),()=>{n||(n=!0,o.close(),clearInterval(a))}}var gt=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 bt(t,e){if(!ht())return;let r=process.env.OMO_MEMORY_SUPERVISOR_TASKKILL_RUN_DIR;void 0!==r&&G(`${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 It(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 _t(t,e){bt(`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 It(r,["--signal-group",String(t),e],!1)}function xt(t){void 0!==t&&bt("win32-graceful",t)}function Nt(t,e){"win32"===t?(xt(e.pid),e.kill()):void 0!==e.pid&&_t(e.pid,"SIGTERM")}function Ot(t,e,r=!1){void 0!==e&&("win32"===t?function(t,e){It(St("OMO_MEMORY_SUPERVISOR_TASKKILL_COMMAND")??["taskkill"],["/pid",String(t),"/T","/F"],e)}(e,r):_t(e,"SIGKILL"))}async function kt(t){return await pt(t)}import{join as Pt}from"node:path";var Tt=new Set(["providermodelnotfounderror","ratelimiterror","modelunavailableerror","providerconnectionerror","authenticationerror"]),Rt=new Set(["quotaexceedederror","insufficientcreditserror","freeusagelimiterror"]),Mt=new Set(["messageabortederror","permissiondeniederror","contextlengtherror","timeouterror","validationerror","syntaxerror","usererror"]),At=["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"],$t=["quota will reset after","quota exceeded","free usage limit","billing limit","billing hard limit","monthly limit","plan limit","subscription quota","subscription limit","payment required","out of credits","credits exhausted","insufficient credits","insufficient balance","credit balance","usage limit for this month","exhausted your capacity","daily call limit","daily limit","usage limit reached for","in arrears","fair use policy","recharge and try","使用上限","额度不足","余额不足","已耗尽"],Dt=["rate limit","cooling down","credentials for model"];function Ct(t){if(t.name){let e=t.name.toLowerCase();if(Mt.has(e))return!1;if(Rt.has(e))return!1;if(Tt.has(e))return!0}let e=t.message?.toLowerCase()??"";return!$t.some(t=>e.includes(t))&&(!(!(r=e).includes("retrying in")||!Dt.some(t=>r.includes(t)))||(null!=t.statusCode&&(429===t.statusCode||503===t.statusCode||529===t.statusCode)||At.some(t=>e.includes(t))));var r}var Lt=[/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],Ut=[/^(Throttling error|Service unavailable):/i,/rate limit/i,/too many requests/i];var jt=/^Error: Model "([^"]+)" not found\. Use --list-models to see available models\.$/m,Ft=/^(?:Error:\s*)?No API key found for\s+([^\s.]+)/m,qt=/(?:^|\s)(\d{3})\s*:/;function Bt(t){if(t.timedOut||0===t.code)return;let e=`${t.stderr}\n${t.stdout}`,r=jt.exec(e)?.[1];if(void 0!==r)return{kind:"model_not_visible",id:r};let n=Ft.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,!Ut.some(t=>t.test(o))&&Lt.some(t=>t.test(o)))return{kind:"context_overflow",detail:i};var o;let a=Number.parseInt(qt.exec(i)?.[1]??"",10);return Ct({message:i,...Number.isNaN(a)?{}:{statusCode:a}})?{kind:"provider_unavailable",detail:i}:void 0}import{randomUUID as Gt}from"node:crypto";import{dirname as Jt,join as Ht}from"node:path";import{randomUUID as Vt}from"node:crypto";import{hostname as Yt}from"node:os";import zt from"node:path";import Kt from"node:path";var Xt=new Set;function Zt(t){Xt.add(t)}function Wt(t){Xt.delete(t)}var Qt=/\.candidate-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function te(t){if(t instanceof Error&&"code"in t)return"string"==typeof t.code?t.code:void 0}function ee(t,e){try{t.onFailure?.(e)}catch{}}function re(t){if("win32"!==process.platform)return!1;let e=te(t);return"EBUSY"===e||"EPERM"===e||"EACCES"===e}import{randomUUID as ne}from"node:crypto";import{hostname as ie}from"node:os";function oe(t){return"string"==typeof t&&t.length>0}function ae(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:oe(r.process_start)&&oe(r.hostname)&&oe(r.nonce)?!oe(r.created_at)||Number.isNaN(Date.parse(r.created_at))?null:oe(r.purpose)&&(void 0===r.run_id||oe(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 se(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:ie(),nonce:ne(),created_at:(new Date).toISOString(),purpose:t,...void 0===e.runId?{}:{run_id:e.runId}}}class le extends Error{lockPath;owner;retriable=!0;constructor(t,e){super(`Lock is held: ${t}`),this.lockPath=t,this.owner=e,this.name="LockContentionError"}}function ce(t){if(t instanceof Error&&"code"in t)return"string"==typeof t.code?t.code:void 0}function ue(t,e){if(void 0!==e)return e(t);if("win32"!==process.platform)return!1;let r=ce(t);return"EBUSY"===r||"EPERM"===r||"EACCES"===r}async function de(t){for(let e=0;e<3;e+=1)try{return await(he.unlink??R)(t),Wt(t),!0}catch(r){if("ENOENT"===ce(r))return Wt(t),!0;if(!ue(r,he.isSharingError))throw Zt(t),ye(zt.dirname(t)),r;if(e+1===3)return Zt(t),ye(zt.dirname(t)),!1}return!1}function fe(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 pe(t){try{let e=await _(t,"utf8");return{raw:e,record:ae(e)}}catch(t){let e=ce(t);if("ENOENT"===e)return null;if("\\"===zt.sep&&"EPERM"===e)return{raw:"",record:null};throw t}}async function me(t,e){await S(zt.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-${Vt()}`;try{return{candidatePath:r,handle:await Y(r,"wx",384)}}catch(n){if(await de(r)||ye(zt.dirname(t)),"EINTR"!==ce(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 E(r,t),!0}catch(t){if(function(t){let e=ce(t);return"EEXIST"===e||"ENOENT"===e}(t))return!1;throw t}}finally{await de(r)||ye(zt.dirname(t))}}var we=new Set,he={};function ye(t){we.delete(t)}async function ve(t){if(t.hostname!==Yt())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 ge(t){let e=await pe(t);if(null===e||null===e.record||!await ve(e.record))return!1;let r=`${t}.reaping-${Vt()}`;try{await O(t,r)}catch(t){if("ENOENT"===ce(t))return!1;if(ue(t))return!1;throw t}let n=await pe(r);if(null!==n&&n.raw===e.raw)return await R(r),!0;try{await E(r,t)}catch(t){if("EEXIST"!==ce(t))throw t}return await R(r),!1}async function Ee(t,e,r){if(null===e.record||!await ve(e.record))return!1;let n=`${t}.recovery`,i={...r,nonce:Vt(),created_at:(new Date).toISOString(),purpose:`${r.purpose}:recovery`};for(let t=0;!await me(n,i);t+=1)if(t>0||!await ge(n))return!1;try{let r=await pe(t);if(null===r)return!0;if(r.raw!==e.raw||null===r.record)return!1;if(!await ve(r.record))return!1;let o=await pe(n);return null!==o&&o.record?.nonce===i.nonce&&(await R(t),!0)}finally{await Se(n,i)}}async function be(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=zt.dirname(t);we.has(o)||(we.add(o),await async function(t,e=Date.now,r={}){let n;try{n=await x(t)}catch(e){if("ENOENT"===te(e)){for(let e of Xt)Kt.dirname(e)===t&&Wt(e);return 0}throw e}let i=0;for(let o of n){if(!Qt.test(o))continue;let n=Kt.join(t,o);try{let t=await T(n);if(!Xt.has(n)&&e()-t.mtimeMs<=36e5)continue;let o=!1;for(let t=0;t<3;t+=1)try{await(r.unlink??R)(n),Wt(n),o=!0;break}catch(e){if("ENOENT"===te(e)){Wt(n),o=!0;break}if(!(r.isSharingError?.(e)??re(e)))throw e;t+1===3&&ee(r,n)}o&&(i+=1)}catch(t){"ENOENT"===te(t)&&Wt(n),ee(r,n)}}return i}(o,Date.now,{...void 0===he.unlink?{}:{unlink:he.unlink},...void 0===he.isSharingError?{}:{isSharingError:he.isSharingError},onFailure:()=>ye(o)}).catch(()=>{ye(o)}));let a=Date.now()+n;for(;;){r.signal?.throwIfAborted();let n=await pe(t);if(null===n){if(await me(t,e))return;if(r.signal?.throwIfAborted(),n=await pe(t),null===n)continue}if(!await Ee(t,n,e)){if(r.signal?.throwIfAborted(),Date.now()>=a)throw new le(t,n.record);await fe(Math.min(i,Math.max(1,a-Date.now())),r.signal)}}}async function Se(t,e){let r=await pe(t);if(null===r||r.record?.nonce!==e.nonce)return!1;try{return await R(t),!0}catch(t){if("ENOENT"===ce(t))return!1;throw t}}async function Ie(t,e,r,n){await be(t,e,n);try{return await r()}finally{await Se(t,e)}}Promise.resolve();var _e=[["\\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",""]];_e.map(([t,e])=>new RegExp(t,e)),_e.map(([t,e])=>new RegExp(t,`${e}g`));new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});import{dirname as xe}from"node:path";import{fileURLToPath as Ne}from"node:url";xe(Ne(import.meta.url));import{dirname as Oe}from"node:path";import{fileURLToPath as ke}from"node:url";Oe(ke(import.meta.url)),new Date(0).toISOString();import{dirname as Pe}from"node:path";import{fileURLToPath as Te}from"node:url";Pe(Te(import.meta.url));function Re(t){return Ht(t,"terminal-claim.json")}function Me(t,e,r){return t.runId===e.runId&&t.attempt===e.attempt&&(void 0===r||t.kind===r)}function Ae(t,e){let r=`${t}.${process.pid}.${Gt()}.candidate`;!function(t,e){let r=z(t,"wx",384);try{G(r,`${JSON.stringify(e,null,2)}\n`,"utf8"),$(r)}finally{K(r)}}(r,e);try{D(r,t)}catch(t){if("EEXIST"===je(t))return!1;throw t}finally{Ce(r)}return function(t){let e;try{e=z(t,"r")}catch(t){if("win32"===process.platform&&["EISDIR","EPERM"].includes(je(t)??""))return;throw t}try{$(e)}catch(t){if("win32"!==process.platform||!["EPERM","EACCES","EINVAL"].includes(je(t)??""))throw t}finally{K(e)}}(Jt(t)),!0}function $e(t){let e;try{e=U(t,"utf8")}catch(t){if("ENOENT"===je(t))return;throw t}try{return{raw:e,claim:Ue(JSON.parse(e))}}catch{return{raw:e,claim:void 0}}}async function De(t,e,r,n,i,o){let a=await se("reflection-finalize",{runId:i.runId});return Ie(Ht(t,"terminal-claim-recovery.lock"),a,async()=>{let t=$e(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||!Le(t.claim,o))return t.claim}Ce(e)}},{waitTimeoutMs:Number.POSITIVE_INFINITY})}function Ce(t){try{B(t)}catch(t){if("ENOENT"!==je(t))throw t}}function Le(t,e){return"dead"===(e.getPidLiveness??wt)(t.claimantPid)}function Ue(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 je(t){return t instanceof Error&&"code"in t?String(t.code):void 0}import{join as Fe}from"node:path";async function qe(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=Re(t),a={version:1,kind:r,runId:e.runId,attempt:e.attempt,claimantPid:i},s=0;for(;;){if(Ae(o,a))return a;let i=$e(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 De(t,o,i,"invalid",e,n);if(void 0!==r)return r;continue}if(Me(l,e,r))return l;if("publish"!==l.kind||!Le(l,n))return l;await(n.beforeRecovery?.("dead-publish"));let c=await De(t,o,i,"dead-publish",e,n);if(void 0!==c)return c}}(t,n,"publish");Me(i,n,"publish")&&(await rt(Pt(t,"publishing.json"),{version:1,...n,finishedAt:r.finishedAt}),await async function(t,e,r,n=Ie,i=se){let o=await i("reflection-finalize",{runId:e});return n(Fe(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(!Me(function(t){return Ue(JSON.parse(U(Re(t),"utf8")))}(t),n,"publish"))return;let i=void 0!==Bt({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(Re(t))}))}function Be(t){try{J(3,`${JSON.stringify(t)}\n`)}catch(t){if(!(t instanceof Error&&"code"in t&&["EPIPE","EBADF"].includes(String(t.code))))throw t}}var Ge=process.argv.slice(2);try{if("--child-bootstrap"===Ge[0]){if(void 0===Ge[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});Be({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?Nt(n,i):_t(process.pid,"SIGTERM")}),s=vt(r.hardDeadlineAt+r.terminationGraceMs,()=>{Ot(n,process.pid)});Be(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()}))}(Ge[1])}else{if(void 0===Ge[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=z(i.stdoutPath,"w"),l=z(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=vt(i.hardDeadlineAt,()=>{w=!0,"win32"===o?xt(c.pid):Nt(o,c)}),v=vt(i.hardDeadlineAt+i.terminationGraceMs,()=>{Ot(o,a??u),m?.()}),g=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}))})}),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,K(s),K(l);let b=function(){let t=ht()?process.env.OMO_MEMORY_SUPERVISOR_CLOCK_PATH:void 0;return void 0===t?Date.now():Et(t)}(),S=(new Date).toISOString(),I={version:1,runId:i.runId,attempt:i.attempt,finishedAt:S,childExit:E??g,timedOut:w||Number.isFinite(b)&&b>=i.hardDeadlineAt};await qe(e,i,I),await it(r),process.exit(0)}(Ge[0])}}catch(t){process.stderr.write(`${t instanceof Error?t.stack??t.message:String(t)}\n`),process.exitCode=1}