The one and only agent harness for complex codebases. Project memory, planning, execution, and verified completion inside Codex.
JavaScript aiai-agentsclaudeclaude-codeclicodexdeveloper-toolslazylazycodexoh-my-openagentomoopenaiorchestrationtypescript
chore: sync Codex marketplace v5.0.0-beta.90
github-actions[bot]8d16365e3f21
diff --git a/plugins/omo/.codex-plugin/plugin.json b/plugins/omo/.codex-plugin/plugin.jsonindex 58e105c1..05c2cf39 100644--- a/plugins/omo/.codex-plugin/plugin.json+++ b/plugins/omo/.codex-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "omo",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","description": "One Codex plugin namespace for Yeongyu's local Codex components.","author": {"name": "Yeongyu Kim",diff --git a/plugins/omo/components/bootstrap/hooks/hooks.json b/plugins/omo/components/bootstrap/hooks/hooks.jsonindex a8273257..68be7b06 100644--- a/plugins/omo/components/bootstrap/hooks/hooks.json+++ b/plugins/omo/components/bootstrap/hooks/hooks.json@@ -8,7 +8,7 @@"command": "node \"${PLUGIN_ROOT}/components/bootstrap/dist/cli.js\" hook session-start","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\bootstrap.ps1\"","timeout": 30,- "statusMessage": "(OmO 5.0.0-beta.89) Checking Bootstrap Provisioning"+ "statusMessage": "(OmO 5.0.0-beta.90) Checking Bootstrap Provisioning"}]}diff --git a/plugins/omo/components/bootstrap/package.json b/plugins/omo/components/bootstrap/package.jsonindex 36439e79..defbd809 100644--- a/plugins/omo/components/bootstrap/package.json+++ b/plugins/omo/components/bootstrap/package.json@@ -1,6 +1,6 @@{"name": "@sisyphuslabs/codex-bootstrap",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","description": "Codex SessionStart bootstrap component that provisions LazyCodex runtime dependencies from a detached worker.","type": "module","private": true,diff --git a/plugins/omo/components/comment-checker/hooks/hooks.json b/plugins/omo/components/comment-checker/hooks/hooks.jsonindex ba380f81..bf778571 100644--- a/plugins/omo/components/comment-checker/hooks/hooks.json+++ b/plugins/omo/components/comment-checker/hooks/hooks.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use","timeout": 30,- "statusMessage": "(OmO 5.0.0-beta.89) Checking Comments"+ "statusMessage": "(OmO 5.0.0-beta.90) Checking Comments"}]}diff --git a/plugins/omo/components/comment-checker/package.json b/plugins/omo/components/comment-checker/package.jsonindex fe66f9c7..2be5b8a0 100644--- a/plugins/omo/components/comment-checker/package.json+++ b/plugins/omo/components/comment-checker/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-comment-checker",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","description": "Codex plugin that runs comment-checker after edit-like PostToolUse hooks.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/git-bash/hooks/hooks.json b/plugins/omo/components/git-bash/hooks/hooks.jsonindex e73f2e2b..1324782a 100644--- a/plugins/omo/components/git-bash/hooks/hooks.json+++ b/plugins/omo/components/git-bash/hooks/hooks.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use","timeout": 5,- "statusMessage": "(OmO 5.0.0-beta.89) Recommending Git Bash MCP"+ "statusMessage": "(OmO 5.0.0-beta.90) Recommending Git Bash MCP"}]}@@ -20,7 +20,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact","timeout": 5,- "statusMessage": "(OmO 5.0.0-beta.89) Resetting Git Bash MCP Reminder"+ "statusMessage": "(OmO 5.0.0-beta.90) Resetting Git Bash MCP Reminder"}]}diff --git a/plugins/omo/components/git-bash/package.json b/plugins/omo/components/git-bash/package.jsonindex 16f49bb9..31c47ab2 100644--- a/plugins/omo/components/git-bash/package.json+++ b/plugins/omo/components/git-bash/package.json@@ -1,6 +1,6 @@{"name": "@sisyphuslabs/codex-git-bash-hook",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","description": "Codex hook component that reminds Windows sessions to prefer the OMO git_bash MCP.","type": "module","private": true,diff --git a/plugins/omo/components/lazycodex-executor-verify/hooks/hooks.json b/plugins/omo/components/lazycodex-executor-verify/hooks/hooks.jsonindex 286fc73d..12360fd4 100644--- a/plugins/omo/components/lazycodex-executor-verify/hooks/hooks.json+++ b/plugins/omo/components/lazycodex-executor-verify/hooks/hooks.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/lazycodex-executor-verify/dist/cli.js\" hook subagent-stop","timeout": 10,- "statusMessage": "(OmO 5.0.0-beta.89) Verifying LazyCodex Executor Evidence"+ "statusMessage": "(OmO 5.0.0-beta.90) Verifying LazyCodex Executor Evidence"}]}diff --git a/plugins/omo/components/lazycodex-executor-verify/package.json b/plugins/omo/components/lazycodex-executor-verify/package.jsonindex 1c464a83..610e703a 100644--- a/plugins/omo/components/lazycodex-executor-verify/package.json+++ b/plugins/omo/components/lazycodex-executor-verify/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-lazycodex-executor-verify",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","description": "Codex SubagentStop evidence verifier for LazyCodex executor completions.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/lsp/dist/.omo-runtime-manifest.json b/plugins/omo/components/lsp/dist/.omo-runtime-manifest.jsonindex 47d0ed83..ed223875 100644--- a/plugins/omo/components/lsp/dist/.omo-runtime-manifest.json+++ b/plugins/omo/components/lsp/dist/.omo-runtime-manifest.json@@ -1,7 +1,7 @@{"schemaVersion": 1,- "version": "5.0.0-beta.89",- "inputDigest": "sha256:5bd77d1313eca86b5e1dee027c016557f30a207aba677b12b40bf1d48462ecfd",+ "version": "5.0.0-beta.90",+ "inputDigest": "sha256:308338a1ab18c48b4a80a0e3c24e4ceeec8a36e5fc16f49ab06fc54f6dc3a8b0","outputs": [{"path": "cli.d.ts",diff --git a/plugins/omo/components/lsp/hooks/hooks.json b/plugins/omo/components/lsp/hooks/hooks.jsonindex 30126a29..1ccfef9f 100644--- a/plugins/omo/components/lsp/hooks/hooks.json+++ b/plugins/omo/components/lsp/hooks/hooks.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use","timeout": 60,- "statusMessage": "(OmO 5.0.0-beta.89) Checking LSP Diagnostics"+ "statusMessage": "(OmO 5.0.0-beta.90) Checking LSP Diagnostics"}]}@@ -21,7 +21,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact","timeout": 5,- "statusMessage": "(OmO 5.0.0-beta.89) Resetting LSP Diagnostics Cache"+ "statusMessage": "(OmO 5.0.0-beta.90) Resetting LSP Diagnostics Cache"}]}diff --git a/plugins/omo/components/lsp/package.json b/plugins/omo/components/lsp/package.jsonindex 4ae282eb..f32bd40b 100644--- a/plugins/omo/components/lsp/package.json+++ b/plugins/omo/components/lsp/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-lsp",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","description": "Codex plugin that exposes Language Server Protocol tools and post-edit diagnostics.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/rules/bundled-rules/hephaestus/gpt-5.6.md b/plugins/omo/components/rules/bundled-rules/hephaestus/gpt-5.6.mdindex 6e1ef699..98ab3ed4 100644--- a/plugins/omo/components/rules/bundled-rules/hephaestus/gpt-5.6.md+++ b/plugins/omo/components/rules/bundled-rules/hephaestus/gpt-5.6.md@@ -68,7 +68,11 @@ Write only what the current correct path needs: no handlers, fallbacks, retries,# Output-On a multi-step task, open with one or two visible sentences naming the first step, then update only at meaningful phase changes - a plan-changing discovery, a decision, a blocker.+At a handoff - turn start (after the one-line read), a todo phase change, a blocker or plan change, the final message - first work out what the user asked for and what they need to know now, then open with one block:++> [Outcome so far] toward [the user's original ask and the result they wanted]. You need: [ledger N/M done, findings, blockers]. Now: [todo task in progress]. Next: [next open task].++Now and Next are todo labels verbatim; the Next stated is executed in this same response with tool calls. Between handoffs, no narration.Final message: lead with the result, group by outcome, no conversational openers. Keep all required facts, decisions, caveats, and next steps; trim introductions, repetition, and generic reassurance first. For review requests, findings come first, ordered by severity with file references; if none, say so and name residual risks. No emojis or em dashes unless requested. Never output broken inline citations like `【F:README.md†L5-L14】` - they break the CLI.diff --git a/plugins/omo/components/rules/bundled-rules/hephaestus/gpt-6.md b/plugins/omo/components/rules/bundled-rules/hephaestus/gpt-6.mdindex 667e58a9..5de5cdb6 100644--- a/plugins/omo/components/rules/bundled-rules/hephaestus/gpt-6.md+++ b/plugins/omo/components/rules/bundled-rules/hephaestus/gpt-6.md@@ -106,7 +106,11 @@ Be direct and tactful: disagree when you have a reason and state it. No flattery## Reporting-While working, speak only when a finding, tradeoff, or blocker changes the plan, in one or two sentences naming the concrete outcome and next step. Routine reads and passing checks go unnarrated.+At a handoff - turn start (after the routing line), a todo phase change, a blocker or plan change, the final message - first work out what the user asked for and what they need to know now, then open with one block:++> [Outcome so far] toward [the user's original ask and the result they wanted]. You need: [ledger N/M done, findings, blockers]. Now: [todo task in progress]. Next: [next open task].++Now and Next are todo labels verbatim; the Next stated is executed in this same response with tool calls. Between handoffs, no narration.The final message stands alone: outcome first, then the evidence needed to trust it - what was verified and how, what could not be verified and why, and pre-existing problems left in place. Order it so the conclusion is easiest to check, not in the order you worked. Deliver the full requested artifact; trim repetition and background before required content.diff --git a/plugins/omo/components/rules/hooks/hooks.json b/plugins/omo/components/rules/hooks/hooks.jsonindex 4c79dd54..cc8895ad 100644--- a/plugins/omo/components/rules/hooks/hooks.json+++ b/plugins/omo/components/rules/hooks/hooks.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook session-start","timeout": 10,- "statusMessage": "(OmO 5.0.0-beta.89) Loading Project Rules"+ "statusMessage": "(OmO 5.0.0-beta.90) Loading Project Rules"}]}@@ -19,7 +19,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit","timeout": 10,- "statusMessage": "(OmO 5.0.0-beta.89) Loading Project Rules"+ "statusMessage": "(OmO 5.0.0-beta.90) Loading Project Rules"}]}@@ -32,7 +32,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use","timeout": 10,- "statusMessage": "(OmO 5.0.0-beta.89) Matching Project Rules"+ "statusMessage": "(OmO 5.0.0-beta.90) Matching Project Rules"}]}@@ -45,7 +45,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-compact","timeout": 10,- "statusMessage": "(OmO 5.0.0-beta.89) Resetting Project Rule Cache"+ "statusMessage": "(OmO 5.0.0-beta.90) Resetting Project Rule Cache"}]}diff --git a/plugins/omo/components/rules/package.json b/plugins/omo/components/rules/package.jsonindex 4cb2298d..50987ffb 100644--- a/plugins/omo/components/rules/package.json+++ b/plugins/omo/components/rules/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-rules",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","description": "Codex plugin that injects project rule files into model context through lifecycle hooks.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/teammode/hooks/hooks.json b/plugins/omo/components/teammode/hooks/hooks.jsonindex b2b423ef..26087e47 100644--- a/plugins/omo/components/teammode/hooks/hooks.json+++ b/plugins/omo/components/teammode/hooks/hooks.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use","timeout": 10,- "statusMessage": "(OmO 5.0.0-beta.89) Checking Thread Title Hygiene"+ "statusMessage": "(OmO 5.0.0-beta.90) Checking Thread Title Hygiene"}]}diff --git a/plugins/omo/components/teammode/package.json b/plugins/omo/components/teammode/package.jsonindex b29c4151..09db9ca1 100644--- a/plugins/omo/components/teammode/package.json+++ b/plugins/omo/components/teammode/package.json@@ -1,6 +1,6 @@{"name": "@sisyphuslabs/codex-teammode",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","description": "Codex team-mode hook component that keeps background thread titles descriptive after create_thread.","type": "module","private": true,diff --git a/plugins/omo/components/telemetry/hooks/hooks.json b/plugins/omo/components/telemetry/hooks/hooks.jsonindex 28e5a12e..0fc4e83b 100644--- a/plugins/omo/components/telemetry/hooks/hooks.json+++ b/plugins/omo/components/telemetry/hooks/hooks.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook session-start","timeout": 5,- "statusMessage": "(OmO 5.0.0-beta.89) Recording Session Telemetry"+ "statusMessage": "(OmO 5.0.0-beta.90) Recording Session Telemetry"}]}diff --git a/plugins/omo/components/telemetry/package.json b/plugins/omo/components/telemetry/package.jsonindex d07f19e0..9149cc1d 100644--- a/plugins/omo/components/telemetry/package.json+++ b/plugins/omo/components/telemetry/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-telemetry",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","description": "Codex plugin component that emits omo-codex anonymous daily-active telemetry on SessionStart.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/ultrawork/dist/cli.js b/plugins/omo/components/ultrawork/dist/cli.jsindex b297174e..d852e5b0 100755--- a/plugins/omo/components/ultrawork/dist/cli.js+++ b/plugins/omo/components/ultrawork/dist/cli.js@@ -19,7 +19,7 @@ var ULTRAWORK_DIRECTIVE_TEXT = `<ultrawork-mode>[CODE RED] Maximum precision. Outcome-first. Evidence-driven.# Role-Expert coding agent. Ship verified work. No process narration.+Expert coding agent. Ship verified work; report at handoffs, not between them.# GoalDeliver EXACTLY what the user asked, end-to-end working, proven by@@ -451,8 +451,12 @@ commits this session — then stage + draft the message instead.# Output discipline- First line literally: \`ULTRAWORK MODE ENABLED!\`- After bootstrap: 1-2 paragraph plan summary + notepad path.-- During execution: surface only state changes (existing tests read,- scenario PASS/FAIL with evidence paths, reviewer verdict).+- During execution: at every handoff - todo phase change, blocker,+ plan change, before a long pass - one handoff block composed after+ weighing what the user asked and needs to know now:+ \`[Outcome so far] toward [ask + wanted]. You need: [ledger,+ evidence paths, PASS/FAIL, reviewer verdict]. Now: [todo in+ progress]. Next: [next open todo].\`; nothing between handoffs.- Final message: outcome + success-criteria checklist with evidencerefs + notepad path + reviewer approval (if gate triggered) + commitlist (\`<sha> <subject>\`). No file-by-file changelog unless asked.diff --git a/plugins/omo/components/ultrawork/hooks/hooks.json b/plugins/omo/components/ultrawork/hooks/hooks.jsonindex 61024e8e..84e00f2c 100644--- a/plugins/omo/components/ultrawork/hooks/hooks.json+++ b/plugins/omo/components/ultrawork/hooks/hooks.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit","timeout": 5,- "statusMessage": "(OmO 5.0.0-beta.89) Checking Ultrawork Trigger"+ "statusMessage": "(OmO 5.0.0-beta.90) Checking Ultrawork Trigger"}]}diff --git a/plugins/omo/components/ultrawork/package.json b/plugins/omo/components/ultrawork/package.jsonindex a5dcf40c..2c88875d 100644--- a/plugins/omo/components/ultrawork/package.json+++ b/plugins/omo/components/ultrawork/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-ultrawork",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","description": "Codex plugin that injects the ultrawork orchestration directive and ships LazyCodex planning, review, QA, and gate agent roles.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/ultrawork/src/directive-content.ts b/plugins/omo/components/ultrawork/src/directive-content.tsindex 372b3bd2..c78ae458 100644--- a/plugins/omo/components/ultrawork/src/directive-content.ts+++ b/plugins/omo/components/ultrawork/src/directive-content.ts@@ -1,4 +1,4 @@// GENERATED by scripts/sync-directive.mjs from packages/prompts-core/prompts/ultrawork/codex.md.// Do not hand-edit. Freshness is enforced by test/directive-source.test.ts.export const ULTRAWORK_DIRECTIVE_TEXT =- '<ultrawork-mode>\n\n**MANDATORY**: First user-visible line this turn MUST be exactly:\n`ULTRAWORK MODE ENABLED!`\n\n[CODE RED] Maximum precision. Outcome-first. Evidence-driven.\n\n# Role\nExpert coding agent. Ship verified work. No process narration.\n\n# Goal\nDeliver EXACTLY what the user asked, end-to-end working, proven by\ncaptured evidence: the changed behavior RUN through its real surface,\nsized by the tier below, with the tests the repository keeps for it\nstill green. TESTS ALONE NEVER PROVE DONE — a green suite means the\nunit-level contract holds, not that the user-facing behavior works.\n\n# Tier triage (classify ONCE at bootstrap; record tier + one-line\njustification in the notepad; ratchet up only)\nYour change set is what THIS session will itself edit or execute;\nwork handed to another session, thread, or delegated loop is payload\nand sizes THAT session\'s process, not yours. Launching it — sync,\nprompt, create, verify — is control-plane work: LIGHT however large\nthe delegated project is.\nDefault is LIGHT. Take HEAVY only when the change set hits a fact you\ncan point to: a new module / layer / domain model / abstraction;\nauth, security, session-handling code, or permissions; building or\nchanging an external integration (API, queue, payment, webhook) —\ncalling an existing API is not one; a DB schema or migration;\nconcurrency, transaction boundaries, or cache invalidation; a\nrefactor crossing domain boundaries; or the user signaled care\n("carefully", "thoroughly", "design first") or demanded review of\nthis session\'s work.\nWhen unsure, take HEAVY. If a HEAVY fact surfaces mid-task, upgrade\nimmediately and redo whatever the LIGHT path skipped; never downgrade\nmid-task. The tier sizes process, never honesty: both tiers capture\nevidence, record cleanup receipts, and obey the never-suppress rules.\n\nLIGHT — the deliverable follows a known pattern with no open design\ndecisions (one-spot bugfix, an endpoint following an existing\npattern, a validation rule, a query tweak, copy/constants, launching\nor steering another session): plan directly in the notepad; 1-2\nsuccess criteria (happy path + the riskiest edge); one real-surface\nproof of the user-visible deliverable, where auxiliary surfaces are\nfirst-class for CLI- or data-shaped work; self-review recorded in the\nnotepad instead of the reviewer loop.\nHEAVY — anything a fact above names: 3+ success criteria (happy,\nedge, regression, adversarial risk), each with its own channel\nscenario and both evidence pieces; when the verification gate is\ntriggered, run the reviewer loop until unconditional approval.\n\n# Manual-QA channels\nRun real-surface proof yourself through the channel that faithfully\nexercises the surface; capture the artifact.\n\n 1. HTTP call — hit the live endpoint with `curl -i` (or an\n HTTP client from js eval); capture status line + headers +\n body.\n 2. Terminal / TUI - drive a real pty and prove it through the\n xterm.js web terminal (see the TUI visual QA note below). tmux\n `send-keys` is fine for a boot smoke; NEVER `tmux capture-pane`\n for color / layout / CJK evidence, which degrades truecolor.\n 3. Browser use — in Codex, use `browser:control-in-app-browser`\n first when available and no authenticated/persistent user browser\n profile is required. Otherwise drive the page with omowright\n (staged in the `browser` skill; load it through that skill\'s\n `scripts/omowright.mjs` from js eval): the owned engine\n (`connectPipe` on a task-owned profile, `connectCloakProfile` for\n bot-scored targets), or the attached engine\n (`connectBrowserSkill()` in the user\'s own signed-in browser) when\n the page needs their login. Capture action log + screenshot path.\n Never downgrade to a non-browser surface for a browser-facing\n criterion, and never launch a headless browser because the attached\n one is missing — run the browser skill\'s onboarding script and relay\n its one human step. NEVER clear cookies, cache, or site data\n (`Network.clearBrowserCookies`, `Storage.clearCookies`,\n `chrome.browsingData.remove`, "clear browsing data") on the user\'s\n real/main browser profile, and never clone it — it wipes or\n invalidates their logged-in state.\n 4. Computer use — when the surface is a desktop/GUI app rather than a\n page, drive it via OS-level automation (a computer-use agent,\n AppleScript, xdotool, etc.) against the running app; capture\n action log + screenshot. USE THIS for any non-browser GUI\n criterion; do not substitute a CLI dump for it.\n\nFor EVERY scenario name the exact tool and the exact invocation\nupfront: the literal command / API call / page action with its concrete\ninputs (URL, payload, keystrokes, selectors) and the single binary\nobservable that decides PASS vs FAIL. "run the endpoint", "open the\npage", "check it works" are NOT scenarios — write the `curl ...`, the\n`send-keys ...`, the Browser plugin action, the `page.click(...)`, the\nexpected status/text.\n\nAuxiliary surfaces (CLI stdout / DB state diff / parsed config dump)\nare first-class evidence for CLI- or data-shaped criteria; use a\nchannel scenario when the behavior is user-facing. `--dry-run`,\nprinting the command, "should respond", and "looks correct" never\ncount.\n\nFor TUI visual QA, render the terminal through the real xterm.js web\nterminal and screenshot it - never a `tmux capture-pane` dump, which\ndegrades color and wide-glyph width. In this repo:\n`node script/qa/web-terminal-visual-qa.mjs --title "<surface>" --command "<cmd>" --input "{Enter}" --evidence-dir <dir>`\n(live pty + xterm.js in Chrome; `--from-file <capture>` replays a raw\nstream). Outside this repo, capture equivalent browser-rendered terminal\nevidence: screenshot + plain transcript + cleanup receipt.\n\n# Bootstrap (DO ALL FOUR BEFORE ANY OTHER WORK — NO SKIPPING)\n\n## 0. Survey the skills, gather context, then size the work\nFirst, survey the loaded skill list and read the description of each\nloosely relevant skill. Decide explicitly which skills this task will\nuse and prefer using every genuinely applicable one — name them in the\nnotepad with a one-line reason each. Skipping a skill that fits the\ntask is a defect. Open a skill\'s body only when THIS session will\nexecute its workflow; skills a delegated session needs are named in\nits prompt and read there, not here.\nNext, fire the first discovery wave under Finding things below.\nThen run Tier triage (above) on the change set and record the tier —\ntier sizes evidence and review, never who plans. Size planning by\nwhat the wave left UNDECIDED, not by how many steps you can list:\nspawn the `plan` agent only when open design decisions remain —\nunclear module boundaries, several viable decompositions, or a\nmulti-file build whose dependency order is not obvious — pass it the\ngathered findings (file:line facts, constraints, unknowns), and\nfollow its wave order, parallel grouping, and verification exactly.\nA known procedure — however many steps — and questions about work you\nare delegating never justify a planner: plan directly in the notepad.\nNever spawn `plan` before the discovery wave has returned.\n\n## 1. Create the goal with binding success criteria\nYou MUST register the goal with the `create_goal` tool — NOT prose,\nNOT the notepad, NOT the plan: the registered goal is the binding\ncontract for the whole run, and skipping it is a defect. Call it with\nexactly `objective`; do not include `status`. Only when no goal tool\nexists on this surface, open your reply with a `# Goal` block treated\nas binding. Goals are unlimited; never invent a numeric budget or\nlimit.\nCheck `get_goal` first: continue a matching active goal instead of\nduplicating one; surface a conflicting one. Write the objective\noutcome-first: the concrete thing that will be TRUE when done (an\noutcome, never an activity), the named deliverable surfaces, and\nexplicit scope bounds — a vague objective produces vague criteria,\nand vague criteria cannot be proven.\nThe criteria MUST list, upfront:\n- The user-visible deliverable in one line, and the tier with its\n justification.\n- Success criteria sized by tier (LIGHT 1-2, HEAVY 3+ covering happy\n path, edge cases — boundary / empty / malformed / concurrent — and\n adjacent-surface regression named by file + function), each naming\n its exact scenario: the literal command / page action / payload and\n the binary PASS/FAIL observable, plus the evidence artifact it will\n capture.\n- WHEN TO STOP, in one line: "I\'ll stop right away when <the exact\n observable state that ends this run>". The Stop rules bind to this\n line — the moment it holds, you stop.\n\nThese scenarios are the contract. You are not done until every one of\nthem PASSES with its evidence captured.\n\n## 2. Open the durable notepad\nRun: `NOTE=$(mktemp -t ulw-$(date +%Y%m%d-%H%M%S).XXXXXX.md)`. Echo the\npath. Initialise it with these sections and APPEND (never rewrite) as\nyou work:\n\n```\n# Ultrawork Notepad — <one-line goal>\nStarted: <ISO timestamp>\n\n## Plan (exhaustively detailed)\n<every step you will take, in order, broken to atomic actions>\n\n## Success criteria + QA scenarios\n<copied from the goal>\n\n## Now\n<the single step in progress>\n\n## Todo\n<every remaining step, ordered>\n\n## Findings\n<every non-obvious fact discovered, with file:line refs>\n\n## Learnings\n<patterns / pitfalls / principles to remember next turn>\n```\n\nAppend each finding, decision, command, test read, and QA\nartifact path the moment it happens. Update `## Now` and\n`## Todo` on every transition. Append-only — never rewrite. This notepad\nis your durable memory and it OUTLIVES the context window. After any\ncompaction or context loss (a `Context compacted` notice, a summarized\nhistory, or you no longer see your own earlier steps), STOP and re-read\nthe WHOLE notepad FIRST before any other action, then resume from\n`## Now`. Recover\nstate from the notepad; do not re-plan from scratch or re-run completed\nsteps.\n\n## 3. Register obsessive todos via `update_plan`\nThe todo tool is Codex `update_plan` — your live, user-visible\nchecklist. Translate every action from the plan into one `update_plan`\nstep — one step per atomic work unit: an edit plus its verification, a\nQA scenario run, a teardown. Keep each step small enough to finish\nwithin a few tool calls.\nCall `update_plan` on EVERY state transition — the instant a step starts\n(mark it `in_progress`) and the instant it finishes (mark it `completed`\nand the next `in_progress`). Exactly ONE `in_progress` at a time. Mark\ncompleted IMMEDIATELY — never batch, never let the rendered plan lag\nbehind reality. Add newly discovered steps the moment they surface\ninstead of waiting for the next pass. Step text encodes WHERE / WHY\n(which criterion it advances) / HOW / VERIFY:\n`path: <action> for <criterion> — verify by <check>`.\n\nGOOD pair (ordered):\n `test/foo.test.ts: read the validateEmail cases for criterion 2 — verify by noting intent / coverage / pass in the notepad`\n `src/foo/bar.ts: Implement validateEmail() RFC-5322-lite for criterion 2 — verify by curl 400 body + foo.test.ts green`\nBAD: "Implement feature" / "Fix bug" / "Add tests later" → rewrite.\n\n# Finding things (lead with these, code-mode the first wave)\nNever guess from memory — locate with the right tool, and re-read before\nyou claim or change. **USE CODE MODE AGGRESSIVELY FOR BOUNDED WAVES.**\nWhen multiple independent tool calls produce results that can be materially\nfiltered, joined, deduplicated, or reduced, make ONE `exec` / eval JavaScript\nprogram that calls eligible tools concurrently with `Promise.all` and emits only\ndecision-relevant evidence. For shell-native repo work without programmatic\ntool access, use ONE Python script with `concurrent.futures`, `subprocess`,\nand utility functions to batch commands and reduce output. Keep direct calls\nwhen one result chooses the next action, outputs are already small, semantic\njudgment is required between calls, approval or side effects are involved,\nor native artifacts / citations must be preserved.\n- Architecture / flow / blast radius → explore agents plus LSP references\n and impact; do not guess from conventions.\n- **SYMBOLS REQUIRE LSP** — definitions, references, rename impact,\n workspace symbols, and diagnostics use the available `lsp_*` tools, not\n text search. Run diagnostics after edits and treat errors as blocking.\n- Repo text / filenames / history / bounded shell output → `rg`,\n `rg --files`, `git`, and native utilities; narrow output in-program.\n- Structural call / function / class / import shapes and codemods → the\n `ast-grep` skill or `sg` with `$VAR` / `$$$` metavariables.\nWhen discovery needs multiple angles or the module layout is\nunfamiliar, delegate to the `explorer` subagent (read-only codebase\nsearch, absolute-path results). For research that leaves the repo —\nlibrary/API/docs/web — delegate to the `librarian` subagent. Spawn them\n`fork_context: false` and keep doing root work while they run.\n\n# Execution loop (READ → CHANGE → RUN → CLEAN)\nUntil every success criterion PASSES with its evidence captured:\n1. Pick next criterion → mark in_progress → update notepad `## Now`.\n2. READ what already proves the area BEFORE touching it. Existing\n tests are the behavior of record: note in the notepad whether they\n encode the intended behavior, cover the path you change, and pass.\n One WRONG before your change is a FINDING to report — NEVER edit a\n test green. A bug: reproduce it first and capture the failure. A\n refactor: the existing tests are green on the unchanged code first.\n3. CHANGE: the SMALLEST production change that meets the criterion;\n update the tests your change makes stale. Add a test ONLY when\n BOTH hold: the repository keeps tests for this behavior AND a\n regression would otherwise pass unnoticed by the run and the\n existing tests — sized like its neighbors, one case per stated\n behavior, failing when that behavior breaks. A test that restates\n the change (a constant, a string, a rename, a call) is NOT evidence;\n the run is. Coverage-only work (no production change): break the\n behavior each new assertion names, capture it failing, restore — an\n assertion that stays green under its mutation is not coverage.\n PROSE TARGET (prompt, SKILL.md, rule, markdown): the wording is NOT\n the behavior — pin only a machine-consumed value (parsed field,\n sentinel a hook greps, a JSON sample through its validator) or one\n `toBe` equality between shipped copies; otherwise review + QA-by-read,\n NO test. Before a change that depends on review, PR, issue, or\n branch state, refresh that state and preserve existing ordering/policy.\n4. RUN: the real-surface scenario the criterion named (channel table\n above; auxiliary surface for CLI- or data-shaped criteria), end to\n end, yourself, plus the step-2 tests; a reproduction now passes.\n Paste the artifact path into the notepad.\n5. CLEANUP (PAIRED — NEVER SKIP): the moment a QA scenario spawns any\n resource, register its teardown as its own todo (e.g.\n `cleanup: kill server pid for criterion 2 — verify kill -0 fails`).\n Every runtime artifact the QA spawned in step 4 MUST be torn down\n before this step completes:\n server PIDs (`kill <pid>`; verify `kill -0` fails), `tmux` sessions\n (`tmux kill-session -t ulw-qa-<criterion>`; verify with `tmux ls`),\n browsers / sessions (`browser.close()` / `session.stop()`), containers\n (`docker rm -f`), bound ports (`lsof -i :<port>` empty), temp\n sockets / files / dirs (`rm -rf` the `mktemp` paths), QA-only env\n vars. Append a one-line cleanup receipt to the notepad next to the\n artifact, e.g. `cleanup: killed 12345; tmux kill-session ulw-qa-foo;\n rm -rf /tmp/ulw.aB12cD`. No receipt → criterion stays in_progress.\n6. Verify: LSP diagnostics clean on changed files + the test scope\n this criterion touched green (no skipped, no xfail added this\n turn). Re-run a validation command (suite, typecheck, build) only\n when its inputs changed since its last green run; ONE full-suite\n pass belongs immediately before the final message, not after\n every increment.\n7. Mark completed. Append non-obvious findings / learnings.\n8. After each increment, re-run the scenarios that increment could\n have affected; re-run the full set once, right before the final\n message. Record PASS/FAIL inline with the evidence paths AND the\n cleanup receipt. Loop until all PASS.\n\nWithin a step, follow Finding things; READ before CHANGE, never in\nparallel with it.\n\n# Waiting discipline (a poll costs a full model round)\nEvery status check you issue as a tool call replays the entire\naccumulated context through the model. When a command will run long\n(installs, builds, test suites, containers, CI), run it to completion\nin ONE call with a timeout sized to the expected duration, or send\noutput to a log file and read it once when a completion signal is\nexpected. Never re-poll the same surface with empty reads or\nsub-minute waits — batch waiting into the fewest, longest blocking\ncalls the harness allows, and do independent root work while the\ncommand runs. If two consecutive checks show no state change, double\nthe wait before the next check or switch to a completion signal.\n\n# Codex subagent reliability\nEvery `multi_agent_v1.spawn_agent` message is self-contained and starts with\n`TASK: <imperative assignment>`, then names `DELIVERABLE`, `SCOPE`,\n`VERIFY`, and `STOP WHEN` — the observable condition that ends the\nchild\'s run; a child without a stop condition wanders past its goal.\nState that it is an executable assignment, not a context handoff. Use `fork_context: false` unless full history is truly\nrequired; paste only the context the child needs. Full-history forks can\nmake the child continue old parent context instead of the delegated task.\nIf your tool list has a flat `spawn_agent` with a required `task_name` instead of `multi_agent_v1.*` (`multi_agent_v2`), rewrite: `fork_context: false` becomes `fork_turns: "none"`, `send_input` becomes `send_message`, finished agents end on their own (no `close_agent`; `followup_task` re-tasks, `interrupt_agent` stops), and `wait_agent` takes only `timeout_ms`, returning on any child mailbox activity.\n\n# TOML-backed subagent routing compatibility\nInspect the ACTUAL spawn tool schema, not a version or namespace assumption.\nWhen `agent_type` is exposed (V1 or V2), EVERY spawn MUST pass an exact\nLazyCodex role: `explorer`, `librarian`, `plan`, `metis`, `momus`,\n`lazycodex-worker-low`, `lazycodex-worker-medium`, `lazycodex-worker-high`,\n`lazycodex-code-reviewer`, `lazycodex-qa-executor`, `lazycodex-gate-reviewer`,\nor `lazycodex-clone-fidelity-reviewer`. Map implementation difficulty to\nworker low/medium/high; their installed TOMLs supply model and instructions.\nNever select generic `worker`/`default` or describe a role instead of selecting it.\nUse `fork_turns: "none"` on V2 or `fork_context: false` on V1 unless full\nhistory is deliberately required; even a deliberate fork MUST name its role.\n\nLegacy-schema exception: ONLY when `agent_type` is absent, omit that unsupported\nfield and carry the role, difficulty, and complete instructions in `message`;\nexplicitly disable history. This cannot select a specialized TOML. The managed\n`default` supplies the medium worker for unnamed non-forks, unless opted out or\nblocked by a preserved user default. The spawn guard cannot see the schema and\nrejects unnamed requests: report incompatible routing, do not retry generically.\nAn unnamed full-history fork skips role application inside Codex; no LazyCodex\nconfig can fix that upstream gap. Never claim this path has been repaired.\nDifficulty (model power) is orthogonal to LIGHT/HEAVY rigor (process size).\n\nTreat child status as a progress signal, not a timeout counter. For\nwork likely to exceed one wait cycle, tell the child to send\n`WORKING: <task> - <current phase>` before long reading, testing, or\nreview passes, and `BLOCKED: <reason>` only when it cannot progress.\nTrack spawned agent names locally. Use `multi_agent_v1.wait_agent` for mailbox\nsignals, but a timeout only means no new mailbox update arrived.\nTreat a running child as alive and keep doing independent root work.\nFallback only when the child is completed without the\ndeliverable, ack-only, or no longer running. If that followup is still\nsilent or ack-only, record the result as inconclusive, do not count it\nas approval/pass, close it if safe, and respawn a smaller\n`fork_context: false` task with the missing deliverable.\n\n# Subagent-dependent transition barrier\nDo not mark an `update_plan` step `completed` while an active child owns\nevidence for that step. Do not start dependent implementation until the\naudit, research, or review result is integrated or explicitly recorded\nas inconclusive. Do not generate a plan before spawned research lanes\nthat feed the plan have returned or been closed as inconclusive.\nSpawn every independent child for the current wave first. After the wave\nis launched, run `multi_agent_v1.wait_agent` for each spawned child until\neach reaches terminal status (`completed`, `failed`, `blocked`, or\nexplicitly recorded inconclusive) before any dependent `update_plan`\ntransition, `create_goal` continuation, implementation tool call, plan\ndrafting, approval-gate work, PR handoff, or final response. A timeout is\nnot terminal status.\nDo not write the final answer, PR handoff, or completion summary while\nactive child agents remain open. Use `multi_agent_v1.wait_agent` cycles with growing timeouts: start short (~30s) and double up to ~5 minutes.\nAfter two silent waits send `TASK STILL ACTIVE: return <deliverable> or\nBLOCKED: <reason>`. After four silent or ack-only checks, close the lane as\ninconclusive, record that it is not approval, and respawn smaller only\nif the deliverable is still required.\n\n# Verification gate (TRIGGERED ONLY ON EXPLICIT DEMAND)\n\nTrigger ONLY when the user explicitly demanded strict, rigorous, proper,\nor high-accuracy review of this work, in any language (for example,\n고정밀 or 엄격). The tier alone never triggers the gate. HEAVY without\nsuch a demand records the same self-review as LIGHT.\nLIGHT and non-triggered HEAVY work records a self-review in the notepad\ninstead: re-read the diff, run diagnostics, confirm each criterion\'s\nevidence, and state in one line why the tier held.\n\nWhen triggered, follow this procedure (NON-NEGOTIABLE):\n1. Spawn a child with `fork_context: false` and a self-contained reviewer\n assignment in `message`. The `multi_agent_v1.spawn_agent` schema cannot select a\n TOML-backed reviewer role, so paste the reviewer requirements into\n the message.\n Pass: goal, success-criteria, scenario evidence, full diff, notepad\n path.\n2. Verify each reviewer concern yourself. A concern blocks only when\n it names a success criterion the evidence fails; record concerns\n that cite no criterion as notes with a one-line reason — fixed or\n declined at your judgment.\n3. Fix every criterion-cited blocker. Re-run ONLY the scenario QA\n affected by the fix; capture fresh evidence for the delta. Update\n notepad.\n4. Re-submit to the SAME reviewer at most twice, passing only the\n delta diff, the blockers it cited, and the already-approved criteria\n marked out-of-scope. An approval whose only remaining items are\n notes counts as approval.\n5. On approval, declare done. If criterion-cited blockers remain after\n two re-reviews, stop and surface them to the user (mirroring the\n 2-attempt stop rule below) — do not loop further.\n\n# Commits\nCommit frequently: one atomic commit per verified increment (change +\nits evidence), never one end-of-run omnibus; each commit builds +\ntests green on its own; no WIP on the final branch.\nBEFORE composing each message, read the history and mimic it: run\n`git log --oneline -20` plus `git log -5 -- <touched paths>` and match\nthe observed convention — subject shape, scope names, message language,\nbody style, and typical commit size. Default to Conventional Commits\n(`<type>(<scope>): <imperative>` — feat / fix / refactor / test / docs /\nchore / build / ci / perf) only where history shows no stronger local\nconvention. If a plan file exists, final commit footer:\n`Plan: .omo/plans/<slug>.md`. Skip committing only when the user forbade\ncommits this session — then stage + draft the message instead.\n\n# Constraints\n- Every behavior change is PROVEN BY ITS RUN on the real surface, with\n the tests the repository keeps for it green. A test that cannot fail\n for the regression it names is NOT evidence: mock-call assertions,\n pinned constants, a fixture equal to the default it must override,\n an expected value re-derived from the output under test.\n- Smallest correct change. No drive-by refactors.\n- Never suppress lints / errors / test failures. Never delete, skip,\n `.only`, `.skip`, `xfail`, or comment out tests to green the suite.\n- Never claim done from inference — only from captured evidence.\n\n# Output discipline\n- First line literally: `ULTRAWORK MODE ENABLED!`\n- After bootstrap: 1-2 paragraph plan summary + notepad path.\n- During execution: surface only state changes (existing tests read,\n scenario PASS/FAIL with evidence paths, reviewer verdict).\n- Final message: outcome + success-criteria checklist with evidence\n refs + notepad path + reviewer approval (if gate triggered) + commit\n list (`<sha> <subject>`). No file-by-file changelog unless asked.\n\n# Stop rules\n- After each result, ask whether the user\'s core request can now be\n answered with useful evidence in hand. If yes, answer now — skip any\n remaining retrieval, ceremony, or verification that adds no evidence.\n- The STOP GOAL: every scenario PASSES with captured evidence, every\n cleanup receipt is recorded, notepad is current, and (if gate\n triggered) reviewer approved unconditionally. Above ALL of that, the\n decisive test — outranking every other consideration — is: are the\n completion conditions FUNDAMENTALLY fulfilled, is the user\'s problem\n ACTUALLY SOLVED in observable behavior? If no, you are NOT done,\n whatever the ledger says. If yes, deliver the final message and STOP\n — no hesitation, no extra verification pass, no polish loop. Work\n past the stop goal is scope creep, not diligence.\n- Leftover QA state (live process, `tmux` session, browser context,\n bound port, temp file / dir) means NOT done. Tear it down, record\n the receipt, then continue.\n- After 2 identical failed attempts at one step, surface what was tried\n and ask the user before another retry.\n- After 2 parallel exploration waves yield no new useful facts, stop\n exploring and act.\n\n</ultrawork-mode>\n';+ '<ultrawork-mode>\n\n**MANDATORY**: First user-visible line this turn MUST be exactly:\n`ULTRAWORK MODE ENABLED!`\n\n[CODE RED] Maximum precision. Outcome-first. Evidence-driven.\n\n# Role\nExpert coding agent. Ship verified work; report at handoffs, not between them.\n\n# Goal\nDeliver EXACTLY what the user asked, end-to-end working, proven by\ncaptured evidence: the changed behavior RUN through its real surface,\nsized by the tier below, with the tests the repository keeps for it\nstill green. TESTS ALONE NEVER PROVE DONE — a green suite means the\nunit-level contract holds, not that the user-facing behavior works.\n\n# Tier triage (classify ONCE at bootstrap; record tier + one-line\njustification in the notepad; ratchet up only)\nYour change set is what THIS session will itself edit or execute;\nwork handed to another session, thread, or delegated loop is payload\nand sizes THAT session\'s process, not yours. Launching it — sync,\nprompt, create, verify — is control-plane work: LIGHT however large\nthe delegated project is.\nDefault is LIGHT. Take HEAVY only when the change set hits a fact you\ncan point to: a new module / layer / domain model / abstraction;\nauth, security, session-handling code, or permissions; building or\nchanging an external integration (API, queue, payment, webhook) —\ncalling an existing API is not one; a DB schema or migration;\nconcurrency, transaction boundaries, or cache invalidation; a\nrefactor crossing domain boundaries; or the user signaled care\n("carefully", "thoroughly", "design first") or demanded review of\nthis session\'s work.\nWhen unsure, take HEAVY. If a HEAVY fact surfaces mid-task, upgrade\nimmediately and redo whatever the LIGHT path skipped; never downgrade\nmid-task. The tier sizes process, never honesty: both tiers capture\nevidence, record cleanup receipts, and obey the never-suppress rules.\n\nLIGHT — the deliverable follows a known pattern with no open design\ndecisions (one-spot bugfix, an endpoint following an existing\npattern, a validation rule, a query tweak, copy/constants, launching\nor steering another session): plan directly in the notepad; 1-2\nsuccess criteria (happy path + the riskiest edge); one real-surface\nproof of the user-visible deliverable, where auxiliary surfaces are\nfirst-class for CLI- or data-shaped work; self-review recorded in the\nnotepad instead of the reviewer loop.\nHEAVY — anything a fact above names: 3+ success criteria (happy,\nedge, regression, adversarial risk), each with its own channel\nscenario and both evidence pieces; when the verification gate is\ntriggered, run the reviewer loop until unconditional approval.\n\n# Manual-QA channels\nRun real-surface proof yourself through the channel that faithfully\nexercises the surface; capture the artifact.\n\n 1. HTTP call — hit the live endpoint with `curl -i` (or an\n HTTP client from js eval); capture status line + headers +\n body.\n 2. Terminal / TUI - drive a real pty and prove it through the\n xterm.js web terminal (see the TUI visual QA note below). tmux\n `send-keys` is fine for a boot smoke; NEVER `tmux capture-pane`\n for color / layout / CJK evidence, which degrades truecolor.\n 3. Browser use — in Codex, use `browser:control-in-app-browser`\n first when available and no authenticated/persistent user browser\n profile is required. Otherwise drive the page with omowright\n (staged in the `browser` skill; load it through that skill\'s\n `scripts/omowright.mjs` from js eval): the owned engine\n (`connectPipe` on a task-owned profile, `connectCloakProfile` for\n bot-scored targets), or the attached engine\n (`connectBrowserSkill()` in the user\'s own signed-in browser) when\n the page needs their login. Capture action log + screenshot path.\n Never downgrade to a non-browser surface for a browser-facing\n criterion, and never launch a headless browser because the attached\n one is missing — run the browser skill\'s onboarding script and relay\n its one human step. NEVER clear cookies, cache, or site data\n (`Network.clearBrowserCookies`, `Storage.clearCookies`,\n `chrome.browsingData.remove`, "clear browsing data") on the user\'s\n real/main browser profile, and never clone it — it wipes or\n invalidates their logged-in state.\n 4. Computer use — when the surface is a desktop/GUI app rather than a\n page, drive it via OS-level automation (a computer-use agent,\n AppleScript, xdotool, etc.) against the running app; capture\n action log + screenshot. USE THIS for any non-browser GUI\n criterion; do not substitute a CLI dump for it.\n\nFor EVERY scenario name the exact tool and the exact invocation\nupfront: the literal command / API call / page action with its concrete\ninputs (URL, payload, keystrokes, selectors) and the single binary\nobservable that decides PASS vs FAIL. "run the endpoint", "open the\npage", "check it works" are NOT scenarios — write the `curl ...`, the\n`send-keys ...`, the Browser plugin action, the `page.click(...)`, the\nexpected status/text.\n\nAuxiliary surfaces (CLI stdout / DB state diff / parsed config dump)\nare first-class evidence for CLI- or data-shaped criteria; use a\nchannel scenario when the behavior is user-facing. `--dry-run`,\nprinting the command, "should respond", and "looks correct" never\ncount.\n\nFor TUI visual QA, render the terminal through the real xterm.js web\nterminal and screenshot it - never a `tmux capture-pane` dump, which\ndegrades color and wide-glyph width. In this repo:\n`node script/qa/web-terminal-visual-qa.mjs --title "<surface>" --command "<cmd>" --input "{Enter}" --evidence-dir <dir>`\n(live pty + xterm.js in Chrome; `--from-file <capture>` replays a raw\nstream). Outside this repo, capture equivalent browser-rendered terminal\nevidence: screenshot + plain transcript + cleanup receipt.\n\n# Bootstrap (DO ALL FOUR BEFORE ANY OTHER WORK — NO SKIPPING)\n\n## 0. Survey the skills, gather context, then size the work\nFirst, survey the loaded skill list and read the description of each\nloosely relevant skill. Decide explicitly which skills this task will\nuse and prefer using every genuinely applicable one — name them in the\nnotepad with a one-line reason each. Skipping a skill that fits the\ntask is a defect. Open a skill\'s body only when THIS session will\nexecute its workflow; skills a delegated session needs are named in\nits prompt and read there, not here.\nNext, fire the first discovery wave under Finding things below.\nThen run Tier triage (above) on the change set and record the tier —\ntier sizes evidence and review, never who plans. Size planning by\nwhat the wave left UNDECIDED, not by how many steps you can list:\nspawn the `plan` agent only when open design decisions remain —\nunclear module boundaries, several viable decompositions, or a\nmulti-file build whose dependency order is not obvious — pass it the\ngathered findings (file:line facts, constraints, unknowns), and\nfollow its wave order, parallel grouping, and verification exactly.\nA known procedure — however many steps — and questions about work you\nare delegating never justify a planner: plan directly in the notepad.\nNever spawn `plan` before the discovery wave has returned.\n\n## 1. Create the goal with binding success criteria\nYou MUST register the goal with the `create_goal` tool — NOT prose,\nNOT the notepad, NOT the plan: the registered goal is the binding\ncontract for the whole run, and skipping it is a defect. Call it with\nexactly `objective`; do not include `status`. Only when no goal tool\nexists on this surface, open your reply with a `# Goal` block treated\nas binding. Goals are unlimited; never invent a numeric budget or\nlimit.\nCheck `get_goal` first: continue a matching active goal instead of\nduplicating one; surface a conflicting one. Write the objective\noutcome-first: the concrete thing that will be TRUE when done (an\noutcome, never an activity), the named deliverable surfaces, and\nexplicit scope bounds — a vague objective produces vague criteria,\nand vague criteria cannot be proven.\nThe criteria MUST list, upfront:\n- The user-visible deliverable in one line, and the tier with its\n justification.\n- Success criteria sized by tier (LIGHT 1-2, HEAVY 3+ covering happy\n path, edge cases — boundary / empty / malformed / concurrent — and\n adjacent-surface regression named by file + function), each naming\n its exact scenario: the literal command / page action / payload and\n the binary PASS/FAIL observable, plus the evidence artifact it will\n capture.\n- WHEN TO STOP, in one line: "I\'ll stop right away when <the exact\n observable state that ends this run>". The Stop rules bind to this\n line — the moment it holds, you stop.\n\nThese scenarios are the contract. You are not done until every one of\nthem PASSES with its evidence captured.\n\n## 2. Open the durable notepad\nRun: `NOTE=$(mktemp -t ulw-$(date +%Y%m%d-%H%M%S).XXXXXX.md)`. Echo the\npath. Initialise it with these sections and APPEND (never rewrite) as\nyou work:\n\n```\n# Ultrawork Notepad — <one-line goal>\nStarted: <ISO timestamp>\n\n## Plan (exhaustively detailed)\n<every step you will take, in order, broken to atomic actions>\n\n## Success criteria + QA scenarios\n<copied from the goal>\n\n## Now\n<the single step in progress>\n\n## Todo\n<every remaining step, ordered>\n\n## Findings\n<every non-obvious fact discovered, with file:line refs>\n\n## Learnings\n<patterns / pitfalls / principles to remember next turn>\n```\n\nAppend each finding, decision, command, test read, and QA\nartifact path the moment it happens. Update `## Now` and\n`## Todo` on every transition. Append-only — never rewrite. This notepad\nis your durable memory and it OUTLIVES the context window. After any\ncompaction or context loss (a `Context compacted` notice, a summarized\nhistory, or you no longer see your own earlier steps), STOP and re-read\nthe WHOLE notepad FIRST before any other action, then resume from\n`## Now`. Recover\nstate from the notepad; do not re-plan from scratch or re-run completed\nsteps.\n\n## 3. Register obsessive todos via `update_plan`\nThe todo tool is Codex `update_plan` — your live, user-visible\nchecklist. Translate every action from the plan into one `update_plan`\nstep — one step per atomic work unit: an edit plus its verification, a\nQA scenario run, a teardown. Keep each step small enough to finish\nwithin a few tool calls.\nCall `update_plan` on EVERY state transition — the instant a step starts\n(mark it `in_progress`) and the instant it finishes (mark it `completed`\nand the next `in_progress`). Exactly ONE `in_progress` at a time. Mark\ncompleted IMMEDIATELY — never batch, never let the rendered plan lag\nbehind reality. Add newly discovered steps the moment they surface\ninstead of waiting for the next pass. Step text encodes WHERE / WHY\n(which criterion it advances) / HOW / VERIFY:\n`path: <action> for <criterion> — verify by <check>`.\n\nGOOD pair (ordered):\n `test/foo.test.ts: read the validateEmail cases for criterion 2 — verify by noting intent / coverage / pass in the notepad`\n `src/foo/bar.ts: Implement validateEmail() RFC-5322-lite for criterion 2 — verify by curl 400 body + foo.test.ts green`\nBAD: "Implement feature" / "Fix bug" / "Add tests later" → rewrite.\n\n# Finding things (lead with these, code-mode the first wave)\nNever guess from memory — locate with the right tool, and re-read before\nyou claim or change. **USE CODE MODE AGGRESSIVELY FOR BOUNDED WAVES.**\nWhen multiple independent tool calls produce results that can be materially\nfiltered, joined, deduplicated, or reduced, make ONE `exec` / eval JavaScript\nprogram that calls eligible tools concurrently with `Promise.all` and emits only\ndecision-relevant evidence. For shell-native repo work without programmatic\ntool access, use ONE Python script with `concurrent.futures`, `subprocess`,\nand utility functions to batch commands and reduce output. Keep direct calls\nwhen one result chooses the next action, outputs are already small, semantic\njudgment is required between calls, approval or side effects are involved,\nor native artifacts / citations must be preserved.\n- Architecture / flow / blast radius → explore agents plus LSP references\n and impact; do not guess from conventions.\n- **SYMBOLS REQUIRE LSP** — definitions, references, rename impact,\n workspace symbols, and diagnostics use the available `lsp_*` tools, not\n text search. Run diagnostics after edits and treat errors as blocking.\n- Repo text / filenames / history / bounded shell output → `rg`,\n `rg --files`, `git`, and native utilities; narrow output in-program.\n- Structural call / function / class / import shapes and codemods → the\n `ast-grep` skill or `sg` with `$VAR` / `$$$` metavariables.\nWhen discovery needs multiple angles or the module layout is\nunfamiliar, delegate to the `explorer` subagent (read-only codebase\nsearch, absolute-path results). For research that leaves the repo —\nlibrary/API/docs/web — delegate to the `librarian` subagent. Spawn them\n`fork_context: false` and keep doing root work while they run.\n\n# Execution loop (READ → CHANGE → RUN → CLEAN)\nUntil every success criterion PASSES with its evidence captured:\n1. Pick next criterion → mark in_progress → update notepad `## Now`.\n2. READ what already proves the area BEFORE touching it. Existing\n tests are the behavior of record: note in the notepad whether they\n encode the intended behavior, cover the path you change, and pass.\n One WRONG before your change is a FINDING to report — NEVER edit a\n test green. A bug: reproduce it first and capture the failure. A\n refactor: the existing tests are green on the unchanged code first.\n3. CHANGE: the SMALLEST production change that meets the criterion;\n update the tests your change makes stale. Add a test ONLY when\n BOTH hold: the repository keeps tests for this behavior AND a\n regression would otherwise pass unnoticed by the run and the\n existing tests — sized like its neighbors, one case per stated\n behavior, failing when that behavior breaks. A test that restates\n the change (a constant, a string, a rename, a call) is NOT evidence;\n the run is. Coverage-only work (no production change): break the\n behavior each new assertion names, capture it failing, restore — an\n assertion that stays green under its mutation is not coverage.\n PROSE TARGET (prompt, SKILL.md, rule, markdown): the wording is NOT\n the behavior — pin only a machine-consumed value (parsed field,\n sentinel a hook greps, a JSON sample through its validator) or one\n `toBe` equality between shipped copies; otherwise review + QA-by-read,\n NO test. Before a change that depends on review, PR, issue, or\n branch state, refresh that state and preserve existing ordering/policy.\n4. RUN: the real-surface scenario the criterion named (channel table\n above; auxiliary surface for CLI- or data-shaped criteria), end to\n end, yourself, plus the step-2 tests; a reproduction now passes.\n Paste the artifact path into the notepad.\n5. CLEANUP (PAIRED — NEVER SKIP): the moment a QA scenario spawns any\n resource, register its teardown as its own todo (e.g.\n `cleanup: kill server pid for criterion 2 — verify kill -0 fails`).\n Every runtime artifact the QA spawned in step 4 MUST be torn down\n before this step completes:\n server PIDs (`kill <pid>`; verify `kill -0` fails), `tmux` sessions\n (`tmux kill-session -t ulw-qa-<criterion>`; verify with `tmux ls`),\n browsers / sessions (`browser.close()` / `session.stop()`), containers\n (`docker rm -f`), bound ports (`lsof -i :<port>` empty), temp\n sockets / files / dirs (`rm -rf` the `mktemp` paths), QA-only env\n vars. Append a one-line cleanup receipt to the notepad next to the\n artifact, e.g. `cleanup: killed 12345; tmux kill-session ulw-qa-foo;\n rm -rf /tmp/ulw.aB12cD`. No receipt → criterion stays in_progress.\n6. Verify: LSP diagnostics clean on changed files + the test scope\n this criterion touched green (no skipped, no xfail added this\n turn). Re-run a validation command (suite, typecheck, build) only\n when its inputs changed since its last green run; ONE full-suite\n pass belongs immediately before the final message, not after\n every increment.\n7. Mark completed. Append non-obvious findings / learnings.\n8. After each increment, re-run the scenarios that increment could\n have affected; re-run the full set once, right before the final\n message. Record PASS/FAIL inline with the evidence paths AND the\n cleanup receipt. Loop until all PASS.\n\nWithin a step, follow Finding things; READ before CHANGE, never in\nparallel with it.\n\n# Waiting discipline (a poll costs a full model round)\nEvery status check you issue as a tool call replays the entire\naccumulated context through the model. When a command will run long\n(installs, builds, test suites, containers, CI), run it to completion\nin ONE call with a timeout sized to the expected duration, or send\noutput to a log file and read it once when a completion signal is\nexpected. Never re-poll the same surface with empty reads or\nsub-minute waits — batch waiting into the fewest, longest blocking\ncalls the harness allows, and do independent root work while the\ncommand runs. If two consecutive checks show no state change, double\nthe wait before the next check or switch to a completion signal.\n\n# Codex subagent reliability\nEvery `multi_agent_v1.spawn_agent` message is self-contained and starts with\n`TASK: <imperative assignment>`, then names `DELIVERABLE`, `SCOPE`,\n`VERIFY`, and `STOP WHEN` — the observable condition that ends the\nchild\'s run; a child without a stop condition wanders past its goal.\nState that it is an executable assignment, not a context handoff. Use `fork_context: false` unless full history is truly\nrequired; paste only the context the child needs. Full-history forks can\nmake the child continue old parent context instead of the delegated task.\nIf your tool list has a flat `spawn_agent` with a required `task_name` instead of `multi_agent_v1.*` (`multi_agent_v2`), rewrite: `fork_context: false` becomes `fork_turns: "none"`, `send_input` becomes `send_message`, finished agents end on their own (no `close_agent`; `followup_task` re-tasks, `interrupt_agent` stops), and `wait_agent` takes only `timeout_ms`, returning on any child mailbox activity.\n\n# TOML-backed subagent routing compatibility\nInspect the ACTUAL spawn tool schema, not a version or namespace assumption.\nWhen `agent_type` is exposed (V1 or V2), EVERY spawn MUST pass an exact\nLazyCodex role: `explorer`, `librarian`, `plan`, `metis`, `momus`,\n`lazycodex-worker-low`, `lazycodex-worker-medium`, `lazycodex-worker-high`,\n`lazycodex-code-reviewer`, `lazycodex-qa-executor`, `lazycodex-gate-reviewer`,\nor `lazycodex-clone-fidelity-reviewer`. Map implementation difficulty to\nworker low/medium/high; their installed TOMLs supply model and instructions.\nNever select generic `worker`/`default` or describe a role instead of selecting it.\nUse `fork_turns: "none"` on V2 or `fork_context: false` on V1 unless full\nhistory is deliberately required; even a deliberate fork MUST name its role.\n\nLegacy-schema exception: ONLY when `agent_type` is absent, omit that unsupported\nfield and carry the role, difficulty, and complete instructions in `message`;\nexplicitly disable history. This cannot select a specialized TOML. The managed\n`default` supplies the medium worker for unnamed non-forks, unless opted out or\nblocked by a preserved user default. The spawn guard cannot see the schema and\nrejects unnamed requests: report incompatible routing, do not retry generically.\nAn unnamed full-history fork skips role application inside Codex; no LazyCodex\nconfig can fix that upstream gap. Never claim this path has been repaired.\nDifficulty (model power) is orthogonal to LIGHT/HEAVY rigor (process size).\n\nTreat child status as a progress signal, not a timeout counter. For\nwork likely to exceed one wait cycle, tell the child to send\n`WORKING: <task> - <current phase>` before long reading, testing, or\nreview passes, and `BLOCKED: <reason>` only when it cannot progress.\nTrack spawned agent names locally. Use `multi_agent_v1.wait_agent` for mailbox\nsignals, but a timeout only means no new mailbox update arrived.\nTreat a running child as alive and keep doing independent root work.\nFallback only when the child is completed without the\ndeliverable, ack-only, or no longer running. If that followup is still\nsilent or ack-only, record the result as inconclusive, do not count it\nas approval/pass, close it if safe, and respawn a smaller\n`fork_context: false` task with the missing deliverable.\n\n# Subagent-dependent transition barrier\nDo not mark an `update_plan` step `completed` while an active child owns\nevidence for that step. Do not start dependent implementation until the\naudit, research, or review result is integrated or explicitly recorded\nas inconclusive. Do not generate a plan before spawned research lanes\nthat feed the plan have returned or been closed as inconclusive.\nSpawn every independent child for the current wave first. After the wave\nis launched, run `multi_agent_v1.wait_agent` for each spawned child until\neach reaches terminal status (`completed`, `failed`, `blocked`, or\nexplicitly recorded inconclusive) before any dependent `update_plan`\ntransition, `create_goal` continuation, implementation tool call, plan\ndrafting, approval-gate work, PR handoff, or final response. A timeout is\nnot terminal status.\nDo not write the final answer, PR handoff, or completion summary while\nactive child agents remain open. Use `multi_agent_v1.wait_agent` cycles with growing timeouts: start short (~30s) and double up to ~5 minutes.\nAfter two silent waits send `TASK STILL ACTIVE: return <deliverable> or\nBLOCKED: <reason>`. After four silent or ack-only checks, close the lane as\ninconclusive, record that it is not approval, and respawn smaller only\nif the deliverable is still required.\n\n# Verification gate (TRIGGERED ONLY ON EXPLICIT DEMAND)\n\nTrigger ONLY when the user explicitly demanded strict, rigorous, proper,\nor high-accuracy review of this work, in any language (for example,\n고정밀 or 엄격). The tier alone never triggers the gate. HEAVY without\nsuch a demand records the same self-review as LIGHT.\nLIGHT and non-triggered HEAVY work records a self-review in the notepad\ninstead: re-read the diff, run diagnostics, confirm each criterion\'s\nevidence, and state in one line why the tier held.\n\nWhen triggered, follow this procedure (NON-NEGOTIABLE):\n1. Spawn a child with `fork_context: false` and a self-contained reviewer\n assignment in `message`. The `multi_agent_v1.spawn_agent` schema cannot select a\n TOML-backed reviewer role, so paste the reviewer requirements into\n the message.\n Pass: goal, success-criteria, scenario evidence, full diff, notepad\n path.\n2. Verify each reviewer concern yourself. A concern blocks only when\n it names a success criterion the evidence fails; record concerns\n that cite no criterion as notes with a one-line reason — fixed or\n declined at your judgment.\n3. Fix every criterion-cited blocker. Re-run ONLY the scenario QA\n affected by the fix; capture fresh evidence for the delta. Update\n notepad.\n4. Re-submit to the SAME reviewer at most twice, passing only the\n delta diff, the blockers it cited, and the already-approved criteria\n marked out-of-scope. An approval whose only remaining items are\n notes counts as approval.\n5. On approval, declare done. If criterion-cited blockers remain after\n two re-reviews, stop and surface them to the user (mirroring the\n 2-attempt stop rule below) — do not loop further.\n\n# Commits\nCommit frequently: one atomic commit per verified increment (change +\nits evidence), never one end-of-run omnibus; each commit builds +\ntests green on its own; no WIP on the final branch.\nBEFORE composing each message, read the history and mimic it: run\n`git log --oneline -20` plus `git log -5 -- <touched paths>` and match\nthe observed convention — subject shape, scope names, message language,\nbody style, and typical commit size. Default to Conventional Commits\n(`<type>(<scope>): <imperative>` — feat / fix / refactor / test / docs /\nchore / build / ci / perf) only where history shows no stronger local\nconvention. If a plan file exists, final commit footer:\n`Plan: .omo/plans/<slug>.md`. Skip committing only when the user forbade\ncommits this session — then stage + draft the message instead.\n\n# Constraints\n- Every behavior change is PROVEN BY ITS RUN on the real surface, with\n the tests the repository keeps for it green. A test that cannot fail\n for the regression it names is NOT evidence: mock-call assertions,\n pinned constants, a fixture equal to the default it must override,\n an expected value re-derived from the output under test.\n- Smallest correct change. No drive-by refactors.\n- Never suppress lints / errors / test failures. Never delete, skip,\n `.only`, `.skip`, `xfail`, or comment out tests to green the suite.\n- Never claim done from inference — only from captured evidence.\n\n# Output discipline\n- First line literally: `ULTRAWORK MODE ENABLED!`\n- After bootstrap: 1-2 paragraph plan summary + notepad path.\n- During execution: at every handoff - todo phase change, blocker,\n plan change, before a long pass - one handoff block composed after\n weighing what the user asked and needs to know now:\n `[Outcome so far] toward [ask + wanted]. You need: [ledger,\n evidence paths, PASS/FAIL, reviewer verdict]. Now: [todo in\n progress]. Next: [next open todo].`; nothing between handoffs.\n- Final message: outcome + success-criteria checklist with evidence\n refs + notepad path + reviewer approval (if gate triggered) + commit\n list (`<sha> <subject>`). No file-by-file changelog unless asked.\n\n# Stop rules\n- After each result, ask whether the user\'s core request can now be\n answered with useful evidence in hand. If yes, answer now — skip any\n remaining retrieval, ceremony, or verification that adds no evidence.\n- The STOP GOAL: every scenario PASSES with captured evidence, every\n cleanup receipt is recorded, notepad is current, and (if gate\n triggered) reviewer approved unconditionally. Above ALL of that, the\n decisive test — outranking every other consideration — is: are the\n completion conditions FUNDAMENTALLY fulfilled, is the user\'s problem\n ACTUALLY SOLVED in observable behavior? If no, you are NOT done,\n whatever the ledger says. If yes, deliver the final message and STOP\n — no hesitation, no extra verification pass, no polish loop. Work\n past the stop goal is scope creep, not diligence.\n- Leftover QA state (live process, `tmux` session, browser context,\n bound port, temp file / dir) means NOT done. Tear it down, record\n the receipt, then continue.\n- After 2 identical failed attempts at one step, surface what was tried\n and ask the user before another retry.\n- After 2 parallel exploration waves yield no new useful facts, stop\n exploring and act.\n\n</ultrawork-mode>\n';diff --git a/plugins/omo/components/ulw-execute-continuation/directive.md b/plugins/omo/components/ulw-execute-continuation/directive.mdindex 5345c3cc..2c03f4e3 100644--- a/plugins/omo/components/ulw-execute-continuation/directive.md+++ b/plugins/omo/components/ulw-execute-continuation/directive.md@@ -52,7 +52,7 @@ Before completion, run your own manual QA on the real surface and a self-review# Output discipline-- Surface only state changes: sub-agent dispatched, scenario PASS/FAIL with artifact path, checkbox marked, evidence appended.+- At every handoff - checkbox marked, blocker, plan change, before a long pass - open with one block composed after weighing what the user asked and needs to know now: `[Outcome so far] toward [ask + wanted]. You need: [sub-agents dispatched, scenario PASS/FAIL with artifact path, checkbox marked, evidence appended]. Now: [checkbox in progress]. Next: [next open checkbox].`; nothing between handoffs.- Do NOT print "Should I continue?", restate the plan, or recap prior turns — the Stop hook continues you; the ledger and plan are the durable record.Begin now. If no checkbox remains, run the Final gate; otherwise pick the next checkbox, dispatch the parallel sub-agents, verify, mark, continue.diff --git a/plugins/omo/components/ulw-execute-continuation/hooks/hooks.json b/plugins/omo/components/ulw-execute-continuation/hooks/hooks.jsonindex 53c2bfef..85aa4346 100644--- a/plugins/omo/components/ulw-execute-continuation/hooks/hooks.json+++ b/plugins/omo/components/ulw-execute-continuation/hooks/hooks.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ulw-execute-continuation/dist/cli.js\" hook stop","timeout": 10,- "statusMessage": "(OmO 5.0.0-beta.89) Checking Ulw-Execute Continuation"+ "statusMessage": "(OmO 5.0.0-beta.90) Checking Ulw-Execute Continuation"}]}diff --git a/plugins/omo/components/ulw-execute-continuation/package.json b/plugins/omo/components/ulw-execute-continuation/package.jsonindex d96902f8..7e9a49db 100644--- a/plugins/omo/components/ulw-execute-continuation/package.json+++ b/plugins/omo/components/ulw-execute-continuation/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-ulw-execute-continuation",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","description": "Codex Stop hook continuation injector for omo-codex ulw-execute plans.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/components/ulw-loop/directive.md b/plugins/omo/components/ulw-loop/directive.mdindex 77a3b7f5..f3a5101a 100644--- a/plugins/omo/components/ulw-loop/directive.md+++ b/plugins/omo/components/ulw-loop/directive.md@@ -6,7 +6,7 @@[CODE RED] Maximum precision. Outcome-first. Evidence-driven.# Role-Expert coding agent. Ship verified work. No process narration.+Expert coding agent. Ship verified work; report at handoffs, not between them.# GoalDeliver EXACTLY what the user asked, end-to-end working, proven by@@ -438,8 +438,12 @@ commits this session — then stage + draft the message instead.# Output discipline- First line literally: `ULTRAWORK MODE ENABLED!`- After bootstrap: 1-2 paragraph plan summary + notepad path.-- During execution: surface only state changes (existing tests read,- scenario PASS/FAIL with evidence paths, reviewer verdict).+- During execution: at every handoff - todo phase change, blocker,+ plan change, before a long pass - one handoff block composed after+ weighing what the user asked and needs to know now:+ `[Outcome so far] toward [ask + wanted]. You need: [ledger,+ evidence paths, PASS/FAIL, reviewer verdict]. Now: [todo in+ progress]. Next: [next open todo].`; nothing between handoffs.- Final message: outcome + success-criteria checklist with evidencerefs + notepad path + reviewer approval (if gate triggered) + commitlist (`<sha> <subject>`). No file-by-file changelog unless asked.diff --git a/plugins/omo/components/ulw-loop/hooks/hooks.json b/plugins/omo/components/ulw-loop/hooks/hooks.jsonindex 0a541942..98cc9037 100644--- a/plugins/omo/components/ulw-loop/hooks/hooks.json+++ b/plugins/omo/components/ulw-loop/hooks/hooks.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook user-prompt-submit --with-ultrawork","timeout": 10,- "statusMessage": "(OmO 5.0.0-beta.89) Checking Ulw-Loop Steering"+ "statusMessage": "(OmO 5.0.0-beta.90) Checking Ulw-Loop Steering"}]}@@ -20,7 +20,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook post-tool-use-spawn","timeout": 5,- "statusMessage": "(OmO 5.0.0-beta.89) Recording Spawn Admission"+ "statusMessage": "(OmO 5.0.0-beta.90) Recording Spawn Admission"}]}@@ -33,7 +33,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use","timeout": 5,- "statusMessage": "(OmO 5.0.0-beta.89) Enforcing Unlimited Ulw-Loop Budget"+ "statusMessage": "(OmO 5.0.0-beta.90) Enforcing Unlimited Ulw-Loop Budget"}]},@@ -44,7 +44,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook pre-tool-use-spawn","timeout": 5,- "statusMessage": "(OmO 5.0.0-beta.89) Guarding Ulw-Loop Spawns"+ "statusMessage": "(OmO 5.0.0-beta.90) Guarding Ulw-Loop Spawns"}]}@@ -56,7 +56,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/dist/cli.js\" hook stop","timeout": 10,- "statusMessage": "(OmO 5.0.0-beta.89) Checking Ulw-Loop Resume"+ "statusMessage": "(OmO 5.0.0-beta.90) Checking Ulw-Loop Resume"}]}diff --git a/plugins/omo/components/ulw-loop/package.json b/plugins/omo/components/ulw-loop/package.jsonindex 4f443218..7b2e0744 100644--- a/plugins/omo/components/ulw-loop/package.json+++ b/plugins/omo/components/ulw-loop/package.json@@ -1,6 +1,6 @@{"name": "@code-yeongyu/codex-ulw-loop",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","description": "Codex plugin: durable repo-native multi-goal orchestration with embedded success criteria and observable evidence audit.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/dist/cli-node/index.js b/plugins/omo/dist/cli-node/index.jsindex 8d2405f6..85fc01d7 100755--- a/plugins/omo/dist/cli-node/index.js+++ b/plugins/omo/dist/cli-node/index.js@@ -65,7 +65,7 @@ var package_default;var init_package = __esm(() => {package_default = {name: "oh-my-opencode",- version: "5.0.0-beta.89",+ version: "5.0.0-beta.90",description: "The Best AI Agent Harness - Batteries-Included OpenCode Plugin with Multi-Model Orchestration, Parallel Background Agents, and Crafted LSP/AST Tools",main: "./dist/index.js",types: "dist/index.d.ts",@@ -248,7 +248,7 @@ var init_package = __esm(() => {zod: "^4.6.5"},devDependencies: {- "@code-yeongyu/senpi": "2026.9.24",+ "@code-yeongyu/senpi": "2026.9.24-3","@oh-my-opencode/agents-md-core": "workspace:*","@oh-my-opencode/ast-grep-mcp": "workspace:*","@oh-my-opencode/boulder-state": "workspace:*",@@ -284,23 +284,23 @@ var init_package = __esm(() => {"@xterm/xterm": "^6.0.0","bun-types": "1.4.2","node-pty": "^1.1.0",- omowright: "github:code-yeongyu/omowright#25781c8ac04f9aae358b06551520b792ac45c6ed",+ omowright: "github:code-yeongyu/omowright#293ca5002cbd4c8b0c104c5934683385ef7e0d3a","puppeteer-core": "^25.11.0",typescript: "^7.0.2"},optionalDependencies: {- "oh-my-opencode-darwin-arm64": "5.0.0-beta.89",- "oh-my-opencode-darwin-x64": "5.0.0-beta.89",- "oh-my-opencode-darwin-x64-baseline": "5.0.0-beta.89",- "oh-my-opencode-linux-arm64": "5.0.0-beta.89",- "oh-my-opencode-linux-arm64-musl": "5.0.0-beta.89",- "oh-my-opencode-linux-x64": "5.0.0-beta.89",- "oh-my-opencode-linux-x64-baseline": "5.0.0-beta.89",- "oh-my-opencode-linux-x64-musl": "5.0.0-beta.89",- "oh-my-opencode-linux-x64-musl-baseline": "5.0.0-beta.89",- "oh-my-opencode-windows-arm64": "5.0.0-beta.89",- "oh-my-opencode-windows-x64": "5.0.0-beta.89",- "oh-my-opencode-windows-x64-baseline": "5.0.0-beta.89"+ "oh-my-opencode-darwin-arm64": "5.0.0-beta.90",+ "oh-my-opencode-darwin-x64": "5.0.0-beta.90",+ "oh-my-opencode-darwin-x64-baseline": "5.0.0-beta.90",+ "oh-my-opencode-linux-arm64": "5.0.0-beta.90",+ "oh-my-opencode-linux-arm64-musl": "5.0.0-beta.90",+ "oh-my-opencode-linux-x64": "5.0.0-beta.90",+ "oh-my-opencode-linux-x64-baseline": "5.0.0-beta.90",+ "oh-my-opencode-linux-x64-musl": "5.0.0-beta.90",+ "oh-my-opencode-linux-x64-musl-baseline": "5.0.0-beta.90",+ "oh-my-opencode-windows-arm64": "5.0.0-beta.90",+ "oh-my-opencode-windows-x64": "5.0.0-beta.90",+ "oh-my-opencode-windows-x64-baseline": "5.0.0-beta.90"},overrides: {"@earendil-works/pi-agent-core": "0.84.2",@@ -9618,6 +9618,117 @@ function getOpenCodeConfigPaths(options) {var TAURI_APP_IDENTIFIER = "ai.opencode.desktop", TAURI_APP_IDENTIFIER_DEV = "ai.opencode.desktop.dev";var init_opencode_config_dir = () => {};+// packages/omo-opencode/src/shared/opencode-plugin-sandbox.ts+import { existsSync as existsSync6, mkdirSync as mkdirSync3, readdirSync, readFileSync, realpathSync as realpathSync3, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "node:fs";+import { basename, dirname as dirname2, join as join7, resolve as resolve2 } from "node:path";+function getPluginSandboxRoot(cacheDir) {+ return join7(cacheDir, SANDBOX_PARENT_DIR);+}+function toPluginSandboxSpec(entry) {+ const name = ACCEPTED_PACKAGE_NAMES.find((candidate) => entry === candidate || entry.startsWith(`${candidate}@`));+ if (!name)+ return null;+ return entry === name ? `${name}@latest` : entry;+}+function getPluginSandboxDir(cacheDir, entry) {+ const spec = toPluginSandboxSpec(entry);+ if (!spec)+ return null;+ return join7(getPluginSandboxRoot(cacheDir), spec);+}+function canonicalize(path) {+ try {+ return realpathSync3(path);+ } catch {+ return resolve2(path);+ }+}+function isPluginSandboxDir(dir, cacheDir) {+ if (toPluginSandboxSpec(basename(dir)) === null)+ return false;+ return canonicalize(dirname2(dir)) === canonicalize(getPluginSandboxRoot(cacheDir));+}+function removePluginSandbox(dir, cacheDir) {+ if (!isPluginSandboxDir(dir, cacheDir))+ return false;+ if (!existsSync6(dir))+ return false;+ const discarded = join7(dirname2(dir), `.${basename(dir)}.discarded-${process.pid}-${Date.now()}`);+ renameSync3(dir, discarded);+ try {+ rmSync2(discarded, { recursive: true, force: true });+ } catch (error) {+ if (!(error instanceof Error))+ throw error;+ log2(`[plugin-sandbox] Refreshed ${dir}, but could not delete the discarded copy ${discarded}: ${error.message}`);+ }+ return true;+}+function markPluginSandboxStale(dir, cacheDir, reason = "", pid = process.pid) {+ if (!isPluginSandboxDir(dir, cacheDir))+ return false;+ if (!existsSync6(dir))+ return false;+ writeFileSync2(join7(dir, REFRESH_MARKER_FILE), `${pid}+${reason}`);+ return true;+}+function describeUnappliedPluginSandboxRefresh(dir, pid = process.pid) {+ const markerPath = join7(dir, REFRESH_MARKER_FILE);+ if (!existsSync6(markerPath))+ return null;+ const [pidLine = "", ...reasonLines] = readFileSync(markerPath, "utf-8").split(`+`);+ const requester = Number(pidLine);+ if (requester === pid)+ return null;+ const reason = reasonLines.join(`+`).trim();+ if (reason)+ return reason;+ if (Number.isInteger(requester) && requester > 0 && isProcessAlive(requester))+ return null;+ return "the refresh requested earlier did not run when OpenCode exited";+}+function isPluginSandboxMarkedStale(dir) {+ return existsSync6(join7(dir, REFRESH_MARKER_FILE));+}+function acquirePluginSandboxLease(dir, pid = process.pid) {+ const leaseDir = join7(dir, LEASE_DIR);+ mkdirSync3(leaseDir, { recursive: true });+ writeFileSync2(join7(leaseDir, String(pid)), "");+}+function releasePluginSandboxLease(dir, pid = process.pid) {+ rmSync2(join7(dir, LEASE_DIR, String(pid)), { force: true });+}+function isProcessAlive(pid) {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return error.code === "EPERM";+ }+}+function hasOtherLivePluginSandboxLease(dir, pid = process.pid) {+ const leaseDir = join7(dir, LEASE_DIR);+ if (!existsSync6(leaseDir))+ return false;+ for (const entry of readdirSync(leaseDir)) {+ const holder = Number(entry);+ if (!Number.isInteger(holder) || holder <= 0 || holder === pid)+ continue;+ if (isProcessAlive(holder))+ return true;+ rmSync2(join7(leaseDir, entry), { force: true });+ }+ return false;+}+var SANDBOX_PARENT_DIR = "packages", REFRESH_MARKER_FILE = ".omo-refresh-pending", LEASE_DIR = ".omo-leases";+var init_opencode_plugin_sandbox = __esm(() => {+ init_logger2();+ init_plugin_identity();+});+// packages/omo-opencode/src/shared/resolve-agent-definition-paths.tsvar init_resolve_agent_definition_paths = __esm(() => {init_contains_path2();@@ -9626,8 +9737,8 @@ var init_resolve_agent_definition_paths = __esm(() => {// packages/omo-opencode/src/shared/opencode-version.tsimport { execSync } from "child_process";-import { existsSync as existsSync6, readFileSync, realpathSync as realpathSync3 } from "fs";-import { dirname as dirname2, join as join7 } from "path";+import { existsSync as existsSync7, readFileSync as readFileSync2, realpathSync as realpathSync4 } from "fs";+import { dirname as dirname3, join as join8 } from "path";function parseVersion(version) {const cleaned = version.replace(/^v/, "").split("-")[0];return cleaned.split(".").map((n) => parseInt(n, 10) || 0);@@ -9668,7 +9779,7 @@ function parsePackageVersion(content) {function getPackageVersionFromBinary(binaryPath, deps) {try {const realBinaryPath = deps.realpath(binaryPath);- const packagePath = join7(dirname2(dirname2(realBinaryPath)), "package.json");+ const packagePath = join8(dirname3(dirname3(realBinaryPath)), "package.json");if (!deps.exists(packagePath))return null;return parsePackageVersion(deps.readText(packagePath));@@ -9728,15 +9839,15 @@ var init_opencode_version = __esm(() => {return envPath;return globalThis.Bun?.which("opencode") ?? null;},- exists: existsSync6,- realpath: realpathSync3,- readText: (filePath) => readFileSync(filePath, "utf-8")+ exists: existsSync7,+ realpath: realpathSync4,+ readText: (filePath) => readFileSync2(filePath, "utf-8")};});// packages/omo-opencode/src/shared/opencode-storage-detection.ts-import { existsSync as existsSync7 } from "node:fs";-import { join as join8 } from "node:path";+import { existsSync as existsSync8 } from "node:fs";+import { join as join9 } from "node:path";function isSqliteBackend() {if (cachedResult === true)return true;@@ -9744,8 +9855,8 @@ function isSqliteBackend() {return false;const check = () => {const versionOk = isOpenCodeVersionAtLeast(OPENCODE_SQLITE_VERSION);- const dbPath = join8(getDataDir(), "opencode", "opencode.db");- return versionOk && existsSync7(dbPath);+ const dbPath = join9(getDataDir(), "opencode", "opencode.db");+ return versionOk && existsSync8(dbPath);};if (cachedResult === FALSE_PENDING_RETRY) {const result = check();@@ -9813,11 +9924,11 @@ var init_zip_extractor = __esm(() => {var init_bun_file_shim = () => {};// packages/omo-opencode/src/shared/binary-downloader.ts-import { chmodSync, existsSync as existsSync8, mkdirSync as mkdirSync3, unlinkSync as unlinkSync3 } from "node:fs";+import { chmodSync, existsSync as existsSync9, mkdirSync as mkdirSync4, unlinkSync as unlinkSync3 } from "node:fs";import * as path6 from "node:path";function getCachedBinaryPath(cacheDir, binaryName) {const binaryPath = path6.join(cacheDir, binaryName);- return existsSync8(binaryPath) ? binaryPath : null;+ return existsSync9(binaryPath) ? binaryPath : null;}var init_binary_downloader = __esm(() => {init_bun_spawn_shim();@@ -9900,14 +10011,14 @@ import {chmodSync as chmodSync2,closeSync as closeSync2,openSync as openSync2,- renameSync as renameSync3,+ renameSync as renameSync4,unlinkSync as unlinkSync4,- writeFileSync as writeFileSync2+ writeFileSync as writeFileSync3} from "node:fs";function writeFileAtomically2(filePath, content, deps = {}) {const tempPath = `${filePath}.tmp`;const mode = deps.mode;- writeFileSync2(tempPath, content, { encoding: "utf-8", mode });+ writeFileSync3(tempPath, content, { encoding: "utf-8", mode });if (mode !== undefined) {chmodSync2(tempPath, mode);}@@ -9919,13 +10030,13 @@ function writeFileAtomically2(filePath, content, deps = {}) {}try {deps.beforeRenameSync?.(tempPath);- renameSync3(tempPath, filePath);+ renameSync4(tempPath, filePath);} catch (error) {const isWindows = process.platform === "win32";const isPermissionError = error instanceof Error && (error.message.includes("EPERM") || error.message.includes("EACCES"));if (isWindows && isPermissionError) {unlinkSync4(filePath);- renameSync3(tempPath, filePath);+ renameSync4(tempPath, filePath);} else {throw error;}@@ -9939,8 +10050,8 @@ var init_write_file_atomically = __esm(() => {});// packages/omo-opencode/src/shared/json-file-cache-store.ts-import { existsSync as existsSync9, mkdirSync as mkdirSync4, readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "node:fs";-import { join as join10 } from "node:path";+import { existsSync as existsSync10, mkdirSync as mkdirSync5, readFileSync as readFileSync3, writeFileSync as writeFileSync4 } from "node:fs";+import { join as join11 } from "node:path";function toLogLabel(cacheLabel) {return cacheLabel.toLowerCase();}@@ -9948,12 +10059,12 @@ function createJsonFileCacheStore(options) {let memoryValue;let writtenInCurrentProcess = false;function getCacheFilePath() {- return join10(options.getCacheDir(), options.filename);+ return join11(options.getCacheDir(), options.filename);}function ensureCacheDir() {const cacheDir = options.getCacheDir();- if (!existsSync9(cacheDir)) {- mkdirSync4(cacheDir, { recursive: true });+ if (!existsSync10(cacheDir)) {+ mkdirSync5(cacheDir, { recursive: true });}}function read() {@@ -9961,13 +10072,13 @@ function createJsonFileCacheStore(options) {return memoryValue;}const cacheFile = getCacheFilePath();- if (!existsSync9(cacheFile)) {+ if (!existsSync10(cacheFile)) {memoryValue = null;log2(`[${options.logPrefix}] ${options.cacheLabel} file not found`, { cacheFile });return null;}try {- const content = readFileSync2(cacheFile, "utf-8");+ const content = readFileSync3(cacheFile, "utf-8");const value = JSON.parse(content);memoryValue = value;log2(`[${options.logPrefix}] Read ${toLogLabel(options.cacheLabel)}`, options.describe(value));@@ -9987,13 +10098,13 @@ function createJsonFileCacheStore(options) {if (writtenInCurrentProcess) {return true;}- return existsSync9(getCacheFilePath());+ return existsSync10(getCacheFilePath());}function write(value) {ensureCacheDir();const cacheFile = getCacheFilePath();try {- writeFileSync3(cacheFile, options.serialize?.(value) ?? JSON.stringify(value, null, 2));+ writeFileSync4(cacheFile, options.serialize?.(value) ?? JSON.stringify(value, null, 2));memoryValue = value;writtenInCurrentProcess = true;log2(`[${options.logPrefix}] ${options.cacheLabel} written`, options.describe(value));@@ -64782,19 +64893,19 @@ var init_fallback_model_availability = __esm(() => {});// packages/omo-opencode/src/shared/opencode-storage-paths.ts-import { join as join11 } from "node:path";+import { join as join12 } from "node:path";var OPENCODE_STORAGE, MESSAGE_STORAGE, PART_STORAGE, SESSION_STORAGE;var init_opencode_storage_paths = __esm(() => {init_data_path();OPENCODE_STORAGE = getOpenCodeStorageDir();- MESSAGE_STORAGE = join11(OPENCODE_STORAGE, "message");- PART_STORAGE = join11(OPENCODE_STORAGE, "part");- SESSION_STORAGE = join11(OPENCODE_STORAGE, "session");+ MESSAGE_STORAGE = join12(OPENCODE_STORAGE, "message");+ PART_STORAGE = join12(OPENCODE_STORAGE, "part");+ SESSION_STORAGE = join12(OPENCODE_STORAGE, "session");});// packages/omo-opencode/src/shared/compaction-marker.ts-import { existsSync as existsSync10, readdirSync, readFileSync as readFileSync3 } from "node:fs";-import { join as join12 } from "node:path";+import { existsSync as existsSync11, readdirSync as readdirSync2, readFileSync as readFileSync4 } from "node:fs";+import { join as join13 } from "node:path";function isCompactionPart(part) {return typeof part === "object" && part !== null && part.type === "compaction";}@@ -64808,20 +64919,20 @@ function isCompactionMessage(message) {return isCompactionAgent(message.info?.agent ?? message.agent) || hasCompactionPart(message.parts);}function getCompactionPartStorageDir(messageID) {- return join12(PART_STORAGE, messageID);+ return join13(PART_STORAGE, messageID);}function hasCompactionPartInStorage(messageID) {if (!messageID) {return false;}const partDir = getCompactionPartStorageDir(messageID);- if (!existsSync10(partDir)) {+ if (!existsSync11(partDir)) {return false;}try {- return readdirSync(partDir).filter((fileName) => fileName.endsWith(".json")).some((fileName) => {+ return readdirSync2(partDir).filter((fileName) => fileName.endsWith(".json")).some((fileName) => {try {- const content = readFileSync3(join12(partDir, fileName), "utf-8");+ const content = readFileSync4(join13(partDir, fileName), "utf-8");return isCompactionPart(JSON.parse(content));} catch (error) {if (error instanceof Error) {@@ -64922,23 +65033,23 @@ var init_hook_message_injector = __esm(() => {});// packages/omo-opencode/src/shared/opencode-message-dir.ts-import { existsSync as existsSync11, readdirSync as readdirSync2 } from "node:fs";-import { join as join13 } from "node:path";+import { existsSync as existsSync12, readdirSync as readdirSync3 } from "node:fs";+import { join as join14 } from "node:path";function getMessageDir(sessionID) {if (!sessionID.startsWith("ses_"))return null;if (/[/\\]|\.\./.test(sessionID))return null;- if (!existsSync11(MESSAGE_STORAGE))+ if (!existsSync12(MESSAGE_STORAGE))return null;- const directPath = join13(MESSAGE_STORAGE, sessionID);- if (existsSync11(directPath)) {+ const directPath = join14(MESSAGE_STORAGE, sessionID);+ if (existsSync12(directPath)) {return directPath;}try {- for (const dir of readdirSync2(MESSAGE_STORAGE)) {- const sessionPath = join13(MESSAGE_STORAGE, dir, sessionID);- if (existsSync11(sessionPath)) {+ for (const dir of readdirSync3(MESSAGE_STORAGE)) {+ const sessionPath = join14(MESSAGE_STORAGE, dir, sessionID);+ if (existsSync12(sessionPath)) {return sessionPath;}}@@ -68045,6 +68156,7 @@ var init_shared = __esm(() => {init_jsonc_parser2();init_migration2();init_opencode_config_dir();+ init_opencode_plugin_sandbox();init_resolve_agent_definition_paths();init_opencode_version();init_opencode_storage_detection();@@ -75068,36 +75180,36 @@ function toPosixPath(path) {var init_posix_path = () => {};// packages/omo-config-core/src/loader/types.ts-import { existsSync as existsSync12, lstatSync as lstatSync2, readFileSync as readFileSync4, realpathSync as realpathSync4 } from "node:fs";+import { existsSync as existsSync13, lstatSync as lstatSync2, readFileSync as readFileSync5, realpathSync as realpathSync5 } from "node:fs";var DEFAULT_READ_FILE_SYSTEM;var init_types3 = __esm(() => {DEFAULT_READ_FILE_SYSTEM = {- existsSync: existsSync12,+ existsSync: existsSync13,lstatSync: lstatSync2,- readFileSync: readFileSync4,- realpathSync: realpathSync4+ readFileSync: readFileSync5,+ realpathSync: realpathSync5};});// packages/omo-config-core/src/loader/paths.tsimport { userInfo } from "node:os";-import { dirname as dirname3, join as join14, posix as posix2, resolve as resolve2 } from "node:path";+import { dirname as dirname4, join as join15, posix as posix2, resolve as resolve3 } from "node:path";function resolveHomeDir(env = process.env) {const homeDir = env.HOME ?? env.USERPROFILE ?? process.cwd();- return homeDir.startsWith("/") ? posix2.resolve(homeDir) : toPosixPath(resolve2(homeDir));+ return homeDir.startsWith("/") ? posix2.resolve(homeDir) : toPosixPath(resolve3(homeDir));}function resolveUserOmoConfigPath(env = process.env) {- return join14(resolveUserOmoConfigDirectory(env), "omo.jsonc");+ return join15(resolveUserOmoConfigDirectory(env), "omo.jsonc");}function resolveUserOmoConfigDirectory(env = process.env) {- return join14(resolveHomeDir(env), ".omo");+ return join15(resolveHomeDir(env), ".omo");}function detectUserOmoJsonPath(env, fileSystem) {const configDir = resolveUserOmoConfigDirectory(env);- const jsoncPath = join14(configDir, "omo.jsonc");+ const jsoncPath = join15(configDir, "omo.jsonc");if (fileSystem.existsSync(jsoncPath))return jsoncPath;- const jsonPath = join14(configDir, "omo.json");+ const jsonPath = join15(configDir, "omo.json");return fileSystem.existsSync(jsonPath) ? jsonPath : jsoncPath;}function isSymlinkedProjectPath(path, fileSystem) {@@ -75115,13 +75227,13 @@ function isLoadableProjectConfigFile(path, fileSystem) {return fileSystem.existsSync(path) && !isSymlinkedProjectPath(path, fileSystem);}function detectOmoJsonPath(dir, fileSystem) {- const omoDir = join14(dir, ".omo");+ const omoDir = join15(dir, ".omo");if (isSymlinkedProjectPath(omoDir, fileSystem))return null;- const jsoncPath = join14(omoDir, "omo.jsonc");+ const jsoncPath = join15(omoDir, "omo.jsonc");if (isLoadableProjectConfigFile(jsoncPath, fileSystem))return jsoncPath;- const jsonPath = join14(omoDir, "omo.json");+ const jsonPath = join15(omoDir, "omo.json");return isLoadableProjectConfigFile(jsonPath, fileSystem) ? jsonPath : null;}function realpathOrSelf(path, fileSystem) {@@ -75134,8 +75246,8 @@ function realpathOrSelf(path, fileSystem) {}}function findProjectConfigPathsFarthestFirst(cwd, homeDir, fileSystem, accountHomeDir = homeDir) {- const startDir = resolve2(cwd);- const boundaryDirs = [...new Set([resolve2(homeDir), resolve2(accountHomeDir)])];+ const startDir = resolve3(cwd);+ const boundaryDirs = [...new Set([resolve3(homeDir), resolve3(accountHomeDir)])];const realBoundaryDirs = new Set(boundaryDirs.map((path) => realpathOrSelf(path, fileSystem)));const nearestFirst = [];let currentDir = startDir;@@ -75146,7 +75258,7 @@ function findProjectConfigPathsFarthestFirst(cwd, homeDir, fileSystem, accountHonearestFirst.push(configPath);if (isHomeDir)break;- const parentDir = dirname3(currentDir);+ const parentDir = dirname4(currentDir);if (parentDir === currentDir)break;currentDir = parentDir;@@ -75667,30 +75779,30 @@ var init_models = __esm(() => {// packages/omo-config-core/src/writer/types.tsimport {copyFileSync,- existsSync as existsSync13,+ existsSync as existsSync14,lstatSync as lstatSync3,- mkdirSync as mkdirSync5,- readFileSync as readFileSync5,- readdirSync as readdirSync3,- renameSync as renameSync4,+ mkdirSync as mkdirSync6,+ readFileSync as readFileSync6,+ readdirSync as readdirSync4,+ renameSync as renameSync5,unlinkSync as unlinkSync5,- writeFileSync as writeFileSync4+ writeFileSync as writeFileSync5} from "node:fs";var DEFAULT_WRITE_FILE_SYSTEM, OmoConfigWriteError;var init_types4 = __esm(() => {DEFAULT_WRITE_FILE_SYSTEM = {copyFileSync,- existsSync: existsSync13,+ existsSync: existsSync14,lstatSync: lstatSync3,- mkdirSync: mkdirSync5,- readFileSync: readFileSync5,- readdirSync: readdirSync3,- renameSync: renameSync4,+ mkdirSync: mkdirSync6,+ readFileSync: readFileSync6,+ readdirSync: readdirSync4,+ renameSync: renameSync5,unlinkSync: unlinkSync5,writeFileExclusiveSync: (path, content) => {- writeFileSync4(path, content, { encoding: "utf-8", flag: "wx" });+ writeFileSync5(path, content, { encoding: "utf-8", flag: "wx" });},- writeFileSync: writeFileSync4+ writeFileSync: writeFileSync5};OmoConfigWriteError = class OmoConfigWriteError extends Error {path;@@ -75730,7 +75842,7 @@ var init_jsonc_parse = __esm(() => {// packages/omo-config-core/src/writer/writer.tsimport { randomUUID as randomUUID2 } from "node:crypto";-import { dirname as dirname4, join as join15, posix as posix3 } from "node:path";+import { dirname as dirname5, join as join16, posix as posix3 } from "node:path";function backupSuffix() {return new Date().toISOString().replace(/[:.]/g, "-");}@@ -75763,17 +75875,17 @@ function resolveWritePath(options) {const jsoncPath = resolveUserOmoConfigPath(options.env);if (fileSystem.existsSync(jsoncPath))return jsoncPath;- const jsonPath = join15(dirname4(jsoncPath), "omo.json");+ const jsonPath = join16(dirname5(jsoncPath), "omo.json");return fileSystem.existsSync(jsonPath) ? jsonPath : jsoncPath;}- const jsoncPath = join15(options.projectDir ?? process.cwd(), ".omo", "omo.jsonc");+ const jsoncPath = join16(options.projectDir ?? process.cwd(), ".omo", "omo.jsonc");if (fileSystem.existsSync(jsoncPath))return jsoncPath;- const jsonPath = join15(dirname4(jsoncPath), "omo.json");+ const jsonPath = join16(dirname5(jsoncPath), "omo.json");return fileSystem.existsSync(jsonPath) ? jsonPath : jsoncPath;}function directoryPath(path) {- return path.startsWith("/") ? posix3.dirname(path) : dirname4(path);+ return path.startsWith("/") ? posix3.dirname(path) : dirname5(path);}function writeAtomically(path, content, fileSystem) {const tempPath = `${path}.${randomUUID2()}.tmp`;@@ -76059,7 +76171,7 @@ var init_types5 = __esm(() => {});// packages/omo-config-core/src/migration/commit.ts-import { basename, dirname as dirname5, join as join16, resolve as resolve3 } from "node:path";+import { basename as basename2, dirname as dirname6, join as join17, resolve as resolve4 } from "node:path";function parseDocument(path, content) {const parsed = parseJsoncSafe3(content);if (parsed.errors.length > 0 || !isPlainObject5(parsed.data)) {@@ -76082,52 +76194,100 @@ function markerValue(target, migrationId, targetPath) {}return hasMigrationMarker(target, migrationId) ? value : [...value, migrationId];}+function stripRetiredCodegraph(document) {+ const stripped = structuredClone(document);+ const removedPaths = [];+ const strip = (value, path) => {+ if (!isPlainObject5(value))+ return;+ if (Object.prototype.hasOwnProperty.call(value, "codegraph")) {+ delete value.codegraph;+ removedPaths.push([...path, "codegraph"]);+ }+ };+ strip(stripped, []);+ for (const harness of OMO_HARNESS_BLOCKS)+ strip(stripped[harness], [harness]);+ if (isPlainObject5(stripped.profiles)) {+ for (const [profileName, profile] of Object.entries(stripped.profiles)) {+ strip(profile, ["profiles", profileName]);+ if (!isPlainObject5(profile))+ continue;+ for (const harness of OMO_HARNESS_BLOCKS)+ strip(profile[harness], ["profiles", profileName, harness]);+ }+ }+ return {+ diagnostics: removedPaths.map((path) => `removed: ${path.join(".") || "codegraph"} (retired configuration)`),+ document: stripped,+ edits: removedPaths.map((path) => ({ path, value: undefined }))+ };+}+function uniqueDiagnostics(diagnostics) {+ return [...new Set(diagnostics)];+}function validateTarget(targetPath, document) {const result = OmoConfigSchema.safeParse(document);if (result.success)return;- const detail = result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ");+ const detail = result.error.issues.map((issue) => `${issue.path.map(String).join(".")}: ${issue.message}`).join(", ");throw new MigrationValidationError(targetPath, detail);}function writerInput(targetPath, env) {const homeDir = resolveHomeDir(env);- const userDirectory = toPosixPath(join16(homeDir, ".omo"));- const fileName = basename(targetPath);- if (toPosixPath(dirname5(targetPath)) === userDirectory && (fileName === "omo.json" || fileName === "omo.jsonc")) {+ const userDirectory = toPosixPath(join17(homeDir, ".omo"));+ const fileName = basename2(targetPath);+ if (toPosixPath(dirname6(targetPath)) === userDirectory && (fileName === "omo.json" || fileName === "omo.jsonc")) {return { scope: "user" };}- if (basename(dirname5(targetPath)) === ".omo" && (fileName === "omo.json" || fileName === "omo.jsonc")) {- return { projectDir: dirname5(dirname5(targetPath)), scope: "project" };+ if (basename2(dirname6(targetPath)) === ".omo" && (fileName === "omo.json" || fileName === "omo.jsonc")) {+ return { projectDir: dirname6(dirname6(targetPath)), scope: "project" };}throw new MigrationTransactionError(`Migration target is not an omo config path: ${targetPath}`);}function sameResolvedPath(a, b) {- return toPosixPath(resolve3(a)) === toPosixPath(resolve3(b));+ return toPosixPath(resolve4(a)) === toPosixPath(resolve4(b));}function prepareTargetWrite(input) {- const merged = mergeWithoutClobber(input.target, input.additions);+ const targetCleanup = stripRetiredCodegraph(input.target);+ const additionsCleanup = stripRetiredCodegraph(input.additions);+ const merged = mergeWithoutClobber(targetCleanup.document, additionsCleanup.document);const marker = markerValue(input.target, input.migrationId, input.targetPath);const document = { ...merged.merged, _migrations: marker };validateTarget(input.targetPath, document);- const edits = [...collectMigrationEdits(merged.additions), { path: ["_migrations"], value: marker }];- return { diagnostics: merged.diagnostics, document, edits };+ const edits = [+ ...targetCleanup.edits,+ ...collectMigrationEdits(merged.additions),+ { path: ["_migrations"], value: marker }+ ];+ return {+ diagnostics: uniqueDiagnostics([...merged.diagnostics, ...targetCleanup.diagnostics, ...additionsCleanup.diagnostics]),+ document,+ edits+ };}function prepareTargetReplacement(input) {+ const targetCleanup = stripRetiredCodegraph(input.target);+ const documentCleanup = stripRetiredCodegraph(input.document);const marker = markerValue(input.target, input.migrationId, input.targetPath);- const document = { ...input.document, _migrations: marker };+ const document = { ...documentCleanup.document, _migrations: marker };validateTarget(input.targetPath, document);- const edits = [];- for (const key of Object.keys(input.target)) {- if (key !== "_migrations" && !Object.prototype.hasOwnProperty.call(input.document, key)) {+ const edits = [...targetCleanup.edits];+ for (const key of Object.keys(targetCleanup.document)) {+ if (key !== "_migrations" && !Object.prototype.hasOwnProperty.call(documentCleanup.document, key)) {edits.push({ path: [key], value: undefined });}}- for (const [key, value] of Object.entries(input.document)) {+ for (const [key, value] of Object.entries(documentCleanup.document)) {if (key !== "_migrations")edits.push({ path: [key], value });}edits.push({ path: ["_migrations"], value: marker });- return { diagnostics: [], document, edits };+ return {+ diagnostics: uniqueDiagnostics([...targetCleanup.diagnostics, ...documentCleanup.diagnostics]),+ document,+ edits+ };}function writePreparedTarget(input) {input.writeTarget({@@ -76137,7 +76297,7 @@ function writePreparedTarget(input) {targetPath: input.targetPath});}-var writeOmoMigrationTarget = (input) => {+var OMO_HARNESS_BLOCKS, writeOmoMigrationTarget = (input) => {const options = writerInput(input.targetPath, input.env);const result = updateOmoConfig({...options,@@ -76159,12 +76319,13 @@ var init_commit = __esm(() => {init_writer2();init_merge2();init_types5();+ OMO_HARNESS_BLOCKS = [...OMO_CONFIG_HARNESS_IDS, ...OMO_CONFIG_LEGACY_HARNESS_IDS].map(harnessBlockKey);});// packages/omo-config-core/src/migration/journal.ts-import { join as join17 } from "node:path";+import { join as join18 } from "node:path";function migrationJournalPath(env) {- return toPosixPath(join17(resolveHomeDir(env), ".omo", ".migration-journal.json"));+ return toPosixPath(join18(resolveHomeDir(env), ".omo", ".migration-journal.json"));}function isFileExistsError2(error) {return error instanceof Error && Reflect.get(error, "code") === "EEXIST";@@ -76257,9 +76418,9 @@ var init_journal = __esm(() => {});// packages/omo-config-core/src/migration/lock.ts-import { join as join18 } from "node:path";+import { join as join19 } from "node:path";function migrationLockPath(env) {- return toPosixPath(join18(resolveHomeDir(env), ".omo", ".migration.lock"));+ return toPosixPath(join19(resolveHomeDir(env), ".omo", ".migration.lock"));}function mutationGuardPath(env) {return `${migrationLockPath(env)}.guard`;@@ -76336,7 +76497,7 @@ function releaseMutationGuard(input) {function acquireMigrationLock(input) {const leaseDurationMs = input.leaseDurationMs ?? DEFAULT_LEASE_DURATION_MS;const path = migrationLockPath(input.env);- input.fileSystem.mkdirSync(toPosixPath(join18(resolveHomeDir(input.env), ".omo")), { recursive: true });+ input.fileSystem.mkdirSync(toPosixPath(join19(resolveHomeDir(input.env), ".omo")), { recursive: true });for (let attempt = 0;attempt < 3; attempt += 1) {const currentContent = leaseContent(input.process, input.clock, leaseDurationMs);try {@@ -76460,7 +76621,7 @@ var init_recovery = __esm(() => {});// packages/omo-config-core/src/migration/batch.ts-import { dirname as dirname6, posix as posix4 } from "node:path";+import { dirname as dirname7, posix as posix4 } from "node:path";function parseSource(path, content) {const parsed = parseJsoncSafe3(content);if (parsed.errors.length > 0) {@@ -76509,7 +76670,7 @@ function assertSafeSourcePaths(sources, protectedPaths) {}}function directoryPath2(path) {- return path.startsWith("/") ? posix4.dirname(path) : dirname6(path);+ return path.startsWith("/") ? posix4.dirname(path) : dirname7(path);}function ensureBackupDirectories(moves, fileSystem) {for (const move of moves)@@ -76726,18 +76887,18 @@ var init_plugin_name_with_version = __esm(() => {});// packages/omo-opencode/src/cli/config-manager/backup-config.ts-import { copyFileSync as copyFileSync2, existsSync as existsSync14, mkdirSync as mkdirSync6 } from "node:fs";-import { dirname as dirname7 } from "node:path";+import { copyFileSync as copyFileSync2, existsSync as existsSync15, mkdirSync as mkdirSync7 } from "node:fs";+import { dirname as dirname8 } from "node:path";function backupConfigFile(configPath) {- if (!existsSync14(configPath)) {+ if (!existsSync15(configPath)) {return { success: true };}const timestamp = new Date().toISOString().replace(/[:.]/g, "-");const backupPath = `${configPath}.backup-${timestamp}`;try {- const dir = dirname7(backupPath);- if (!existsSync14(dir)) {- mkdirSync6(dir, { recursive: true });+ const dir = dirname8(backupPath);+ if (!existsSync15(dir)) {+ mkdirSync7(dir, { recursive: true });}copyFileSync2(configPath, backupPath);return { success: true, backupPath };@@ -76751,11 +76912,11 @@ function backupConfigFile(configPath) {var init_backup_config = () => {};// packages/omo-opencode/src/cli/config-manager/ensure-config-directory-exists.ts-import { existsSync as existsSync15, mkdirSync as mkdirSync7 } from "node:fs";+import { existsSync as existsSync16, mkdirSync as mkdirSync8 } from "node:fs";function ensureConfigDirectoryExists() {const configDir = getConfigDir();- if (!existsSync15(configDir)) {- mkdirSync7(configDir, { recursive: true });+ if (!existsSync16(configDir)) {+ mkdirSync8(configDir, { recursive: true });}}var init_ensure_config_directory_exists = __esm(() => {@@ -76792,14 +76953,14 @@ function formatErrorWithSuggestion(err, context) {}// packages/omo-opencode/src/cli/config-manager/opencode-config-format.ts-import { existsSync as existsSync16 } from "node:fs";+import { existsSync as existsSync17 } from "node:fs";function detectConfigFormat() {const configJsonc = getConfigJsonc();const configJson = getConfigJson();- if (existsSync16(configJsonc)) {+ if (existsSync17(configJsonc)) {return { format: "jsonc", path: configJsonc };}- if (existsSync16(configJson)) {+ if (existsSync17(configJson)) {return { format: "json", path: configJson };}return { format: "none", path: configJson };@@ -76809,7 +76970,7 @@ var init_opencode_config_format = __esm(() => {});// packages/omo-opencode/src/cli/config-manager/parse-opencode-config-file.ts-import { readFileSync as readFileSync6, statSync as statSync3 } from "node:fs";+import { readFileSync as readFileSync7, statSync as statSync3 } from "node:fs";function isEmptyOrWhitespace(content) {return content.trim().length === 0;}@@ -76819,7 +76980,7 @@ function parseOpenCodeConfigFileWithError(path) {if (stat.size === 0) {return { config: null, error: `Config file is empty: ${path}. Delete it or add valid JSON content.` };}- const content = readFileSync6(path, "utf-8");+ const content = readFileSync7(path, "utf-8");if (isEmptyOrWhitespace(content)) {return { config: null, error: `Config file contains only whitespace: ${path}. Delete it or add valid JSON content.` };}@@ -76932,30 +77093,30 @@ function extractVersionFromPluginEntry(entry) {}// packages/omo-opencode/src/cli/config-manager/add-plugin-to-opencode-config.ts-import { existsSync as existsSync17, readdirSync as readdirSync4, readFileSync as readFileSync7, writeFileSync as writeFileSync5 } from "node:fs";-import { basename as basename2, dirname as dirname8, join as join19 } from "node:path";+import { existsSync as existsSync18, readdirSync as readdirSync5, readFileSync as readFileSync8, writeFileSync as writeFileSync6 } from "node:fs";+import { basename as basename3, dirname as dirname9, join as join20 } from "node:path";function detectConfigFormatInDir(configDir) {- const configJsonc = join19(configDir, "opencode.jsonc");- const configJson = join19(configDir, "opencode.json");- if (existsSync17(configJsonc)) {+ const configJsonc = join20(configDir, "opencode.jsonc");+ const configJson = join20(configDir, "opencode.json");+ if (existsSync18(configJsonc)) {return { format: "jsonc", path: configJsonc };}- if (existsSync17(configJson)) {+ if (existsSync18(configJson)) {return { format: "json", path: configJson };}return { format: "none", path: configJson };}function getParentConfigDirForProfile(configDir) {- const parentDir = dirname8(configDir);- if (basename2(parentDir) !== "profiles")+ const parentDir = dirname9(configDir);+ if (basename3(parentDir) !== "profiles")return null;- return dirname8(parentDir);+ return dirname9(parentDir);}function listProfileConfigDirs(rootConfigDir) {- const profilesDir = join19(rootConfigDir, "profiles");- if (!existsSync17(profilesDir))+ const profilesDir = join20(rootConfigDir, "profiles");+ if (!existsSync18(profilesDir))return [];- return readdirSync4(profilesDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => join19(profilesDir, entry.name)).filter((profileDir) => detectConfigFormatInDir(profileDir).format !== "none");+ return readdirSync5(profilesDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => join20(profilesDir, entry.name)).filter((profileDir) => detectConfigFormatInDir(profileDir).format !== "none");}function getConfigTargets() {const primaryConfigDir = getConfigDir();@@ -77020,7 +77181,7 @@ function writePluginEntryToTarget(params) {try {if (target.format === "none") {const config = { plugin: [pluginEntry] };- writeFileSync5(target.path, JSON.stringify(config, null, 2) + `+ writeFileSync6(target.path, JSON.stringify(config, null, 2) + ``);return { success: true, configPath: target.path };}@@ -77063,15 +77224,15 @@ function writePluginEntryToTarget(params) {normalizedPlugins.push(nextPluginEntry);config.plugin = normalizedPlugins;if (target.format === "jsonc") {- const content = readFileSync7(target.path, "utf-8");+ const content = readFileSync8(target.path, "utf-8");const edits = modify2(content, ["plugin"], normalizedPlugins, {formattingOptions: { insertSpaces: true, tabSize: 2, eol: `` },getInsertionIndex: () => 0});- writeFileSync5(target.path, applyEdits2(content, edits));+ writeFileSync6(target.path, applyEdits2(content, edits));} else {- writeFileSync5(target.path, JSON.stringify(config, null, 2) + `+ writeFileSync6(target.path, JSON.stringify(config, null, 2) + ``);}return { success: true, configPath: target.path };@@ -77462,13 +77623,13 @@ var init_generate_omo_config = __esm(() => {});// packages/omo-opencode/src/config-migration/types.ts-import { existsSync as existsSync18, readdirSync as readdirSync5, realpathSync as realpathSync5 } from "node:fs";+import { existsSync as existsSync19, readdirSync as readdirSync6, realpathSync as realpathSync6 } from "node:fs";var DEFAULT_DISCOVERY_FILE_SYSTEM;var init_types6 = __esm(() => {DEFAULT_DISCOVERY_FILE_SYSTEM = {- existsSync: existsSync18,- readdirSync: readdirSync5,- realpathSync: realpathSync5+ existsSync: existsSync19,+ readdirSync: readdirSync6,+ realpathSync: realpathSync6};});@@ -78489,14 +78650,14 @@ function deepMergeRecord(target, source) {}// packages/omo-opencode/src/cli/config-manager/write-omo-config.ts-import { existsSync as existsSync19, readFileSync as readFileSync8 } from "node:fs";+import { existsSync as existsSync20, readFileSync as readFileSync9 } from "node:fs";function record2(value) {return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};}function existingOpenCodeConfig(path) {- if (!existsSync19(path))+ if (!existsSync20(path))return {};- const document = parseJsonc(readFileSync8(path, "utf-8"));+ const document = parseJsonc(readFileSync9(path, "utf-8"));return record2(document["[opencode]"]);}function writeOmoConfig(installConfig) {@@ -78694,10 +78855,10 @@ var init_opencode_binary = __esm(() => {});// packages/omo-opencode/src/cli/config-manager/detect-current-config.ts-import { existsSync as existsSync20, readFileSync as readFileSync9 } from "node:fs";+import { existsSync as existsSync21, readFileSync as readFileSync10 } from "node:fs";function detectProvidersFromOmoConfig() {const omoConfigPath = getOmoConfigPath();- if (!existsSync20(omoConfigPath)) {+ if (!existsSync21(omoConfigPath)) {return {hasOpenAI: true,hasOpencodeZen: true,@@ -78711,7 +78872,7 @@ function detectProvidersFromOmoConfig() {};}try {- const content = readFileSync9(omoConfigPath, "utf-8");+ const content = readFileSync10(omoConfigPath, "utf-8");const omoConfig = parseJsonc(content);if (!omoConfig || typeof omoConfig !== "object") {return {@@ -78851,10 +79012,10 @@ var init_detect_current_config = __esm(() => {});// packages/omo-opencode/src/cli/config-manager/bun-install.ts-import { existsSync as existsSync21 } from "node:fs";-import { join as join20 } from "node:path";+import { existsSync as existsSync22 } from "node:fs";+import { join as join21 } from "node:path";function getDefaultWorkspaceDir() {- return join20(getOpenCodeCacheDir(), "packages");+ return join21(getOpenCodeCacheDir(), "packages");}function readProcessOutput(stream) {if (!stream) {@@ -78880,7 +79041,7 @@ async function runBunInstallWithDetails(options) {const outputMode = options?.outputMode ?? "pipe";const cacheDir = options?.workspaceDir ?? getDefaultWorkspaceDir();const packageJsonPath = `${cacheDir}/package.json`;- if (!existsSync21(packageJsonPath)) {+ if (!existsSync22(packageJsonPath)) {return {success: false,error: `Workspace not initialized: ${packageJsonPath} not found. OpenCode should create this on first run.`@@ -78961,14 +79122,14 @@ var init_config_manager = __esm(() => {});// packages/telemetry-core/src/day-claim.ts-import { closeSync as closeSync3, mkdirSync as mkdirSync8, openSync as openSync3, readdirSync as readdirSync7, rmSync as rmSync2 } from "node:fs";-import { join as join51 } from "node:path";+import { closeSync as closeSync3, mkdirSync as mkdirSync9, openSync as openSync3, readdirSync as readdirSync8, rmSync as rmSync3 } from "node:fs";+import { join as join52 } from "node:path";function getTelemetryDayClaimFilePath(stateDir, dayUTC) {- return join51(stateDir, `${CLAIM_PREFIX}${dayUTC}${CLAIM_SUFFIX}`);+ return join52(stateDir, `${CLAIM_PREFIX}${dayUTC}${CLAIM_SUFFIX}`);}function claimUtcDay(stateDir, dayUTC) {try {- mkdirSync8(stateDir, { recursive: true });+ mkdirSync9(stateDir, { recursive: true });closeSync3(openSync3(getTelemetryDayClaimFilePath(stateDir, dayUTC), "wx"));} catch (error) {return error.code === "EEXIST" ? "already-claimed" : "unavailable";@@ -78980,7 +79141,7 @@ function pruneSupersededClaims(stateDir, dayUTC) {const currentClaim = `${CLAIM_PREFIX}${dayUTC}${CLAIM_SUFFIX}`;let entries;try {- entries = readdirSync7(stateDir);+ entries = readdirSync8(stateDir);} catch {return;}@@ -78990,7 +79151,7 @@ function pruneSupersededClaims(stateDir, dayUTC) {if (!entry.startsWith(CLAIM_PREFIX) || !entry.endsWith(CLAIM_SUFFIX))continue;try {- rmSync2(join51(stateDir, entry), { force: true });+ rmSync3(join52(stateDir, entry), { force: true });} catch {}}}@@ -78998,21 +79159,21 @@ var CLAIM_PREFIX = "daily-active.", CLAIM_SUFFIX = ".claim";var init_day_claim = () => {};// packages/telemetry-core/src/activity-state.ts-import { existsSync as existsSync24, mkdirSync as mkdirSync9, readFileSync as readFileSync11 } from "node:fs";-import { basename as basename8, join as join52 } from "node:path";+import { existsSync as existsSync25, mkdirSync as mkdirSync10, readFileSync as readFileSync12 } from "node:fs";+import { basename as basename9, join as join53 } from "node:path";function resolveTelemetryStateDir(product, options = {}) {const dataDir = resolveXdgDataDir(product.cacheDirName, {env: options.env,osProvider: options.osProvider});- const xdgStateDir = options.env?.XDG_DATA_HOME === undefined ? undefined : join52(options.env.XDG_DATA_HOME, product.cacheDirName);- if (dataDir === xdgStateDir || xdgStateDir === undefined && basename8(dataDir) === product.cacheDirName) {+ const xdgStateDir = options.env?.XDG_DATA_HOME === undefined ? undefined : join53(options.env.XDG_DATA_HOME, product.cacheDirName);+ if (dataDir === xdgStateDir || xdgStateDir === undefined && basename9(dataDir) === product.cacheDirName) {return dataDir;}- return join52(dataDir, product.cacheDirName);+ return join53(dataDir, product.cacheDirName);}function getTelemetryActivityStateFilePath(stateDir) {- return join52(stateDir, POSTHOG_ACTIVITY_STATE_FILE);+ return join53(stateDir, POSTHOG_ACTIVITY_STATE_FILE);}function getDailyActiveCaptureState(input) {const dayUTC = getUtcDayString(input.now ?? new Date);@@ -79045,11 +79206,11 @@ function isPostHogActivityState(value) {}function readPostHogActivityState(stateDir, diagnostics) {const stateFilePath = getTelemetryActivityStateFilePath(stateDir);- if (!existsSync24(stateFilePath)) {+ if (!existsSync25(stateFilePath)) {return {};}try {- const stateContent = readFileSync11(stateFilePath, "utf-8");+ const stateContent = readFileSync12(stateFilePath, "utf-8");const stateJson = JSON.parse(stateContent);if (!isPostHogActivityState(stateJson)) {return {};@@ -79068,7 +79229,7 @@ function readPostHogActivityState(stateDir, diagnostics) {function writePostHogActivityState(stateDir, nextState, diagnostics) {const stateFilePath = getTelemetryActivityStateFilePath(stateDir);try {- mkdirSync9(stateDir, { recursive: true });+ mkdirSync10(stateDir, { recursive: true });writeFileAtomically(stateFilePath, `${JSON.stringify(nextState, null, 2)}`);} catch (error) {@@ -79092,16 +79253,16 @@ var init_activity_state = __esm(() => {var DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com", DEFAULT_POSTHOG_API_KEY = "phc_CFJhj5HyvA62QPhvyaUCtaq23aUfznnijg5VaaGkNk74", UNCONFIGURED_POSTHOG_API_KEY = "phc_REPLACE_ME_OMO_NATIVE";// packages/telemetry-core/src/diagnostics.ts-import { appendFileSync as appendFileSync2, existsSync as existsSync25, mkdirSync as mkdirSync10, readFileSync as readFileSync12 } from "node:fs";-import { join as join53 } from "node:path";+import { appendFileSync as appendFileSync2, existsSync as existsSync26, mkdirSync as mkdirSync11, readFileSync as readFileSync13 } from "node:fs";+import { join as join54 } from "node:path";function getTelemetryDiagnosticsFilePath(diagnosticsDir) {- return join53(diagnosticsDir, DIAGNOSTICS_FILE_NAME);+ return join54(diagnosticsDir, DIAGNOSTICS_FILE_NAME);}function writeTelemetryDiagnostic(input, options) {const now = options.now ?? new Date;try {cleanupTelemetryDiagnostics({ diagnosticsDir: options.diagnosticsDir, now });- mkdirSync10(options.diagnosticsDir, { recursive: true });+ mkdirSync11(options.diagnosticsDir, { recursive: true });appendFileSync2(getTelemetryDiagnosticsFilePath(options.diagnosticsDir), `${JSON.stringify(toDiagnosticRecord(input, now))}`, "utf-8");} catch (error) {@@ -79113,12 +79274,12 @@ function writeTelemetryDiagnostic(input, options) {}function cleanupTelemetryDiagnostics(options) {const diagnosticsFilePath = getTelemetryDiagnosticsFilePath(options.diagnosticsDir);- if (!existsSync25(diagnosticsFilePath)) {+ if (!existsSync26(diagnosticsFilePath)) {return;}try {const cutoffMs = (options.now ?? new Date).getTime() - DIAGNOSTICS_RETENTION_MS;- const retainedLines = trimToMaxBytes(readFileSync12(diagnosticsFilePath, "utf-8").split(`+ const retainedLines = trimToMaxBytes(readFileSync13(diagnosticsFilePath, "utf-8").split(``).filter((line) => shouldRetainLine(line, cutoffMs)));writeFileAtomically(diagnosticsFilePath, retainedLines.length === 0 ? "" : `${retainedLines.join(``)}@@ -79260,7 +79421,7 @@ var init_env = __esm(() => {});// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs-import { dirname as dirname17, posix as posix7, sep as sep7 } from "path";+import { dirname as dirname18, posix as posix7, sep as sep7 } from "path";function createModulerModifier() {const getModuleFromFileName = createGetModuleFromFilename();return async (frames) => {@@ -79269,7 +79430,7 @@ function createModulerModifier() {return frames;};}-function createGetModuleFromFilename(basePath = process.argv[1] ? dirname17(process.argv[1]) : process.cwd(), isWindows = sep7 === "\\") {+function createGetModuleFromFilename(basePath = process.argv[1] ? dirname18(process.argv[1]) : process.cwd(), isWindows = sep7 === "\\") {const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath;return (filename) => {if (!filename)@@ -88838,7 +88999,7 @@ var package_default2;var init_package2 = __esm(() => {package_default2 = {name: "@oh-my-opencode/omo-codex",- version: "5.0.0-beta.89",+ version: "5.0.0-beta.90",type: "module",private: true,description: "Codex harness adapter for oh-my-openagent. Vendored Codex plugin namespace (omo) + TypeScript installer + telemetry.",@@ -89028,6 +89189,40 @@ var init_telemetry2 = __esm(() => {init_posthog();});+// packages/omo-opencode/src/hooks/auto-update-checker/checker/bundled-version.ts+function getBundledVersion() {+ return package_default.version;+}+var init_bundled_version = __esm(() => {+ init_package();+});++// packages/omo-opencode/src/hooks/auto-update-checker/version-channel.ts+function isPrereleaseVersion(version) {+ return version.includes("-");+}+function isDistTag(version) {+ const startsWithDigit = /^\d/.test(version);+ return !startsWithDigit;+}+function extractChannel(version) {+ if (!version)+ return "latest";+ if (isDistTag(version)) {+ return version;+ }+ if (isPrereleaseVersion(version)) {+ const prereleasePart = version.split("-")[1];+ if (prereleasePart) {+ const channelMatch = prereleasePart.match(/^(alpha|beta|rc|canary|next)/);+ if (channelMatch) {+ return channelMatch[1];+ }+ }+ }+ return "latest";+}+// node_modules/.bun/[email protected]/node_modules/sisteransi/src/index.jsvar require_src = __commonJS(function(exports, module) {var ESC = "\x1B";@@ -89357,11 +89552,6 @@ var init_cached_version = __esm(() => {init_package_json_locator();});-// packages/omo-opencode/src/hooks/auto-update-checker/checker/bundled-version.ts-var init_bundled_version = __esm(() => {- init_package();-});-// packages/omo-opencode/src/hooks/auto-update-checker/checker/pinned-version-updater.tsvar init_pinned_version_updater = __esm(() => {init_logger2();@@ -89391,40 +89581,73 @@ var init_latest_version = __esm(() => {init_constants5();});-// packages/omo-opencode/src/hooks/auto-update-checker/version-channel.ts-function isPrereleaseVersion(version) {- return version.includes("-");-}-function isDistTag(version) {- const startsWithDigit = /^\d/.test(version);- return !startsWithDigit;+// packages/omo-opencode/src/hooks/auto-update-checker/checker/semver-compare.ts+function parseSemver(version) {+ const match = SEMVER_REGEX.exec(version.trim());+ if (!match)+ return null;+ const [, major, minor, patch, prerelease] = match;+ return {+ core: [Number(major), Number(minor), Number(patch)],+ prerelease: prerelease ? prerelease.split(".") : []+ };}-function extractChannel(version) {- if (!version)- return "latest";- if (isDistTag(version)) {- return version;+function comparePrerelease(a, b) {+ if (a.length === 0 && b.length === 0)+ return 0;+ if (a.length === 0)+ return 1;+ if (b.length === 0)+ return -1;+ const length = Math.min(a.length, b.length);+ for (let i = 0;i < length; i++) {+ const idA = a[i] ?? "";+ const idB = b[i] ?? "";+ if (idA === idB)+ continue;+ const numA = /^\d+$/.test(idA);+ const numB = /^\d+$/.test(idB);+ if (numA && numB)+ return Number(idA) < Number(idB) ? -1 : 1;+ if (numA)+ return -1;+ if (numB)+ return 1;+ return idA < idB ? -1 : 1;}- if (isPrereleaseVersion(version)) {- const prereleasePart = version.split("-")[1];- if (prereleasePart) {- const channelMatch = prereleasePart.match(/^(alpha|beta|rc|canary|next)/);- if (channelMatch) {- return channelMatch[1];- }- }+ if (a.length === b.length)+ return 0;+ return a.length < b.length ? -1 : 1;+}+function compareSemverVersions(a, b) {+ const parsedA = parseSemver(a);+ const parsedB = parseSemver(b);+ if (!parsedA || !parsedB)+ return null;+ for (let i = 0;i < 3; i++) {+ const partA = parsedA.core[i] ?? 0;+ const partB = parsedB.core[i] ?? 0;+ if (partA !== partB)+ return partA < partB ? -1 : 1;}- return "latest";+ return comparePrerelease(parsedA.prerelease, parsedB.prerelease);}+function isStrictlyNewerVersion(currentVersion, latestVersion) {+ return compareSemverVersions(currentVersion, latestVersion) === -1;+}+var SEMVER_REGEX;+var init_semver_compare = __esm(() => {+ SEMVER_REGEX = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;+});// packages/omo-opencode/src/hooks/auto-update-checker/checker/check-for-update.tsvar init_check_for_update = __esm(() => {init_logger2();- init_opencode_version();init_local_dev_path();init_plugin_entry();init_cached_version();init_latest_version();+ init_semver_compare();});// packages/omo-opencode/src/hooks/auto-update-checker/checker/sync-package-json.ts@@ -89540,6 +89763,76 @@ var init_sync_package_json = __esm(() => {EXACT_SEMVER_REGEX2 = /^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/;});+// packages/omo-opencode/src/hooks/auto-update-checker/checker/sandbox-refresh.ts+function refreshMarkedSandbox(sandboxDir, cacheDir, pid) {+ try {+ releasePluginSandboxLease(sandboxDir, pid);+ if (!isPluginSandboxMarkedStale(sandboxDir))+ return;+ if (hasOtherLivePluginSandboxLease(sandboxDir, pid)) {+ markPluginSandboxStale(sandboxDir, cacheDir, "another OpenCode window was still open", pid);+ log2(`[auto-update-checker] Another OpenCode process still runs from ${sandboxDir}; the last one to exit refreshes it`);+ return;+ }+ const removed = removePluginSandbox(sandboxDir, cacheDir);+ log2(removed ? `[auto-update-checker] Removed stale OpenCode plugin sandbox on exit: ${sandboxDir}` : `[auto-update-checker] OpenCode plugin sandbox already gone: ${sandboxDir}`);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log2(`[auto-update-checker] Failed to remove OpenCode plugin sandbox ${sandboxDir}: ${message}`);+ try {+ markPluginSandboxStale(sandboxDir, cacheDir, `could not remove it: ${message}`, pid);+ } catch (markError) {+ log2(`[auto-update-checker] Could not record the failed refresh of ${sandboxDir}:`, markError);+ }+ }+}+function trackPluginSandbox(sandboxDir, deps = {}) {+ const cacheDir = deps.cacheDir ?? getOpenCodeCacheDir();+ if (!isPluginSandboxDir(sandboxDir, cacheDir))+ return false;+ if (trackedSandboxDirs.has(sandboxDir))+ return true;+ trackedSandboxDirs.add(sandboxDir);+ const pid = deps.pid ?? process.pid;+ try {+ acquirePluginSandboxLease(sandboxDir, pid);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log2(`[auto-update-checker] Could not lease OpenCode plugin sandbox ${sandboxDir}: ${message}`);+ }+ const onExit = deps.onExit ?? ((callback) => process.once("exit", callback));+ onExit(() => refreshMarkedSandbox(sandboxDir, cacheDir, pid));+ return true;+}+function scheduleOpenCodeSandboxRefreshOnExit(sandboxDir, deps = {}) {+ const cacheDir = deps.cacheDir ?? getOpenCodeCacheDir();+ if (!isPluginSandboxDir(sandboxDir, cacheDir)) {+ log2(`[auto-update-checker] Not an OpenCode plugin sandbox, leaving it alone: ${sandboxDir}`);+ return null;+ }+ const pid = deps.pid ?? process.pid;+ let unapplied;+ try {+ unapplied = describeUnappliedPluginSandboxRefresh(sandboxDir, pid);+ markPluginSandboxStale(sandboxDir, cacheDir, "", pid);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log2(`[auto-update-checker] Could not request a refresh of OpenCode plugin sandbox ${sandboxDir}: ${message}`);+ return `could not request it: ${message}`;+ }+ trackPluginSandbox(sandboxDir, { ...deps, cacheDir });+ log2(`[auto-update-checker] Scheduled OpenCode plugin sandbox refresh on exit: ${sandboxDir}`);+ return unapplied;+}+var trackedSandboxDirs;+var init_sandbox_refresh = __esm(() => {+ init_logger2();+ init_data_path();+ init_opencode_plugin_sandbox();+ init_package_json_locator();+ trackedSandboxDirs = new Set;+});+// packages/omo-opencode/src/hooks/auto-update-checker/checker.tsvar init_checker = __esm(() => {init_local_dev_path();@@ -89551,6 +89844,8 @@ var init_checker = __esm(() => {init_latest_version();init_check_for_update();init_sync_package_json();+ init_semver_compare();+ init_sandbox_refresh();});// packages/omo-opencode/src/hooks/auto-update-checker/cache.ts@@ -89709,20 +90004,20 @@ var init_update_toasts = __esm(() => {});// packages/omo-opencode/src/hooks/auto-update-checker/hook/background-update-check.ts-import { existsSync as existsSync46 } from "node:fs";-import { dirname as dirname30, join as join75 } from "node:path";+import { existsSync as existsSync48 } from "node:fs";+import { dirname as dirname32, join as join78 } from "node:path";import { fileURLToPath as fileURLToPath5 } from "node:url";function defaultGetModuleHostingWorkspace() {try {- const currentDir = dirname30(fileURLToPath5(import.meta.url));+ const currentDir = dirname32(fileURLToPath5(import.meta.url));const pkgJsonPath = findPackageJsonUp(currentDir);if (!pkgJsonPath)return null;- const pkgDir = dirname30(pkgJsonPath);- const nodeModulesDir = dirname30(pkgDir);+ const pkgDir = dirname32(pkgJsonPath);+ const nodeModulesDir = dirname32(pkgDir);if (nodeModulesDir.split(/[\\/]/).pop() !== "node_modules")return null;- return dirname30(nodeModulesDir);+ return dirname32(nodeModulesDir);} catch (error) {if (error instanceof Error) {return null;@@ -89736,6 +90031,9 @@ function getCacheWorkspaceDir(deps) {function getPinnedVersionToastMessage(latestVersion) {return `Update available: ${latestVersion} (version pinned, update manually)`;}+function getUnappliedRefreshToastMessage(latestVersion, reason, sandboxDir) {+ return `v${latestVersion} available, but the last restart could not apply it (${reason}). Close every OpenCode window and start it again; if this notice returns, delete ${sandboxDir} (known issue #5367).`;+}function isOpenCodeManagedSandbox(moduleWorkspace, cacheWorkspace, configDir) {if (!moduleWorkspace)return false;@@ -89807,8 +90105,8 @@ function createBackgroundUpdateCheckRunner(overrides = {}) {deps.log("[auto-update-checker] Failed to fetch latest version for channel:", channel);return;}- if (currentVersion === latestVersion) {- deps.log("[auto-update-checker] Already on latest version for channel:", channel);+ if (!isStrictlyNewerVersion(currentVersion, latestVersion)) {+ deps.log(`[auto-update-checker] No newer version for channel ${channel} (current: ${currentVersion}, registry: ${latestVersion})`);return;}deps.log(`[auto-update-checker] Update available (${channel}): ${currentVersion} → ${latestVersion}`);@@ -89824,8 +90122,9 @@ function createBackgroundUpdateCheckRunner(overrides = {}) {}const moduleWorkspace = deps.getModuleHostingWorkspace();if (isOpenCodeManagedSandbox(moduleWorkspace, getCacheWorkspaceDir(deps), deps.getOpenCodeConfigPaths({ binary: "opencode" }).configDir)) {- await deps.showUpdateAvailableToast(ctx, latestVersion, getToastMessage);- deps.log(`[auto-update-checker] OpenCode-managed sandbox detected (${moduleWorkspace}); skipping auto-update install. Notification only. See #4318.`);+ const unapplied = moduleWorkspace ? deps.scheduleSandboxRefresh(moduleWorkspace) : null;+ await deps.showUpdateAvailableToast(ctx, latestVersion, unapplied && moduleWorkspace ? () => getUnappliedRefreshToastMessage(latestVersion, unapplied, moduleWorkspace) : getToastMessage);+ deps.log(`[auto-update-checker] OpenCode-managed sandbox detected (${moduleWorkspace}); sandbox refresh scheduled for exit. See #4318/#5367.`);return;}const syncResult = deps.syncCachePackageJsonToIntent(pluginInfo);@@ -89861,10 +90160,12 @@ var init_background_update_check = __esm(() => {init_constants5();init_checker();init_package_json_locator();+ init_sandbox_refresh();+ init_semver_compare();init_update_toasts();defaultDeps4 = {- existsSync: existsSync46,- join: join75,+ existsSync: existsSync48,+ join: join78,runBunInstallWithDetails,log: log2,getOpenCodeCacheDir,@@ -89877,7 +90178,8 @@ var init_background_update_check = __esm(() => {syncCachePackageJsonToIntent,showUpdateAvailableToast,showAutoUpdatedToast,- getModuleHostingWorkspace: defaultGetModuleHostingWorkspace+ getModuleHostingWorkspace: defaultGetModuleHostingWorkspace,+ scheduleSandboxRefresh: scheduleOpenCodeSandboxRefreshOnExit};runBackgroundUpdateCheck = createBackgroundUpdateCheckRunner();});@@ -89920,6 +90222,7 @@ var init_hook = __esm(() => {init_logger2();init_checker();init_background_update_check();+ init_sandbox_refresh();init_config_errors_toast();init_connected_providers_status();init_model_capabilities_status();@@ -92291,7 +92594,7 @@ function getUnsupportedOpenCodeVersionMessage(openCodeVersion) {}// packages/omo-codex/src/install/install-codex.ts-import { join as join54, resolve as resolve12 } from "node:path";+import { join as join55, resolve as resolve13 } from "node:path";// packages/omo-codex/src/install/codex-default-role-config.tsinit_src4();@@ -92304,12 +92607,12 @@ function readDefaultRoleConfig(options = {}) {}// packages/omo-codex/src/install/install-codex.ts-import { existsSync as existsSync26 } from "node:fs";+import { existsSync as existsSync27 } from "node:fs";import { homedir as homedir6 } from "node:os";// packages/omo-codex/src/install/codex-cache-bins.tsimport { chmod, lstat as lstat4, mkdir, readFile as readFile3, readdir as readdir2, readlink as readlink3, rm as rm3, stat as stat2, symlink, writeFile } from "node:fs/promises";-import { basename as basename3, isAbsolute as isAbsolute2, join as join24, relative, resolve as resolve5, sep } from "node:path";+import { basename as basename4, isAbsolute as isAbsolute2, join as join25, relative, resolve as resolve6, sep } from "node:path";// packages/omo-codex/src/install/codex-cache-command-shim.tsvar COMMAND_SHIM_MARKER = ":: generated by oh-my-openagent Codex installer";@@ -92354,7 +92657,7 @@ function windowsCommandShim(targetPath) {// packages/omo-codex/src/install/codex-cache-dangling-bins.tsimport { lstat as lstat2, readFile, readdir, readlink, rm, stat } from "node:fs/promises";-import { dirname as dirname9, isAbsolute, join as join21, resolve as resolve4 } from "node:path";+import { dirname as dirname10, isAbsolute, join as join22, resolve as resolve5 } from "node:path";// packages/omo-codex/src/install/codex-cache-fs.tsimport { lstat } from "node:fs/promises";@@ -92382,7 +92685,7 @@ async function removeDanglingManagedComponentBins(binDir, platform, managedBinNaconst binName = managedBinNameForEntry(entry.name, platform);if (binName === null || !managedBinNames.has(binName))continue;- const linkPath = join21(binDir, entry.name);+ const linkPath = join22(binDir, entry.name);if (platform === "win32") {await removeDanglingGeneratedCommandShim(linkPath);continue;@@ -92401,7 +92704,7 @@ async function removeDanglingManagedSymlink(linkPath) {if (!linkStat.isSymbolicLink())return;const linkTarget = await readlink(linkPath);- const target = isAbsolute(linkTarget) ? linkTarget : resolve4(dirname9(linkPath), linkTarget);+ const target = isAbsolute(linkTarget) ? linkTarget : resolve5(dirname10(linkPath), linkTarget);if (!await isFileSystemEntry(target) && isManagedComponentBinTarget(target))await rm(linkPath, { force: true });} catch (error) {@@ -92464,7 +92767,7 @@ function hasOmoCodexPluginPrefix(parts, endExclusive) {// packages/omo-codex/src/install/codex-cache-legacy-bins.tsimport { lstat as lstat3, readFile as readFile2, readlink as readlink2, rm as rm2 } from "node:fs/promises";-import { join as join22 } from "node:path";+import { join as join23 } from "node:path";var LEGACY_CODEX_COMPONENT_BINS = [{ name: "omo", component: "ulw-loop" },{ name: "codex-comment-checker", component: "comment-checker" },@@ -92481,7 +92784,7 @@ function isLegacyCodexBinTarget(binName, target) {}async function removeLegacyCodexComponentBins(binDir, platform) {for (const entry of LEGACY_CODEX_COMPONENT_BINS) {- const linkPath = join22(binDir, platform === "win32" ? `${entry.name}.cmd` : entry.name);+ const linkPath = join23(binDir, platform === "win32" ? `${entry.name}.cmd` : entry.name);await removeLegacyCodexComponentBin(linkPath, entry.component, platform);}}@@ -92532,10 +92835,10 @@ function isNodeErrorWithCode2(error) {}// packages/omo-codex/src/install/codex-cache-runtime-wrapper.ts-import { join as join23 } from "node:path";+import { join as join24 } from "node:path";var RUNTIME_WRAPPER_MARKER = "OMO_GENERATED_RUNTIME_WRAPPER";function posixRuntimeWrapper(binName, cliPath, codexHome, binDir, nodeCliPath) {- const ulwLoopBin = toPosixPath2(join23(binDir, "omo-ulw-loop"));+ const ulwLoopBin = toPosixPath2(join24(binDir, "omo-ulw-loop"));const nodeCli = escapePosixDoubleQuoted(toPosixPath2(nodeCliPath));const escapedCliPath = escapePosixDoubleQuoted(toPosixPath2(cliPath));const escapedCodexHome = escapePosixDoubleQuoted(toPosixPath2(codexHome));@@ -92582,7 +92885,7 @@ function posixRuntimeWrapper(binName, cliPath, codexHome, binDir, nodeCliPath) {`);}function windowsRuntimeWrapper(binName, cliPath, codexHome, binDir, nodeCliPath) {- const ulwLoopBin = join23(binDir, "omo-ulw-loop.cmd");+ const ulwLoopBin = join24(binDir, "omo-ulw-loop.cmd");return ["@echo off",`rem ${RUNTIME_WRAPPER_MARKER}`,@@ -92651,34 +92954,34 @@ async function removeCachedManagedNpmBinShims(pluginRoot) {const binLinks = await discoverPackageBins(pluginRoot);if (binLinks.length === 0)return;- const npmBinDir = join24(pluginRoot, "node_modules", ".bin");+ const npmBinDir = join25(pluginRoot, "node_modules", ".bin");if (!await isFileSystemEntry2(npmBinDir))return;const managedBinNames = new Set(binLinks.map((link) => link.name));for (const name of managedBinNames) {for (const suffix of ["", ".cmd", ".ps1"]) {- await rm3(join24(npmBinDir, `${name}${suffix}`), { force: true });+ await rm3(join25(npmBinDir, `${name}${suffix}`), { force: true });}}}async function linkRootRuntimeBin(input) {- const cliPath = join24(input.repoRoot, "dist", "cli", "index.js");+ const cliPath = join25(input.repoRoot, "dist", "cli", "index.js");const platform = input.platform ?? process.platform;- const legacyPath = join24(input.binDir, platform === "win32" ? "omo.cmd" : "omo");+ const legacyPath = join25(input.binDir, platform === "win32" ? "omo.cmd" : "omo");if (!await isFile(cliPath)) {await removeGeneratedRuntimeWrapper(legacyPath);return null;}const binName = "omo-agent-toolkit";- const nodeCliPath = join24(input.repoRoot, "dist", "cli-node", "index.js");+ const nodeCliPath = join25(input.repoRoot, "dist", "cli-node", "index.js");await mkdir(input.binDir, { recursive: true });if (platform === "win32") {- const linkPath = join24(input.binDir, `${binName}.cmd`);+ const linkPath = join25(input.binDir, `${binName}.cmd`);await replaceRuntimeWrapper(linkPath, windowsRuntimeWrapper(binName, cliPath, input.codexHome, input.binDir, nodeCliPath));await removeGeneratedRuntimeWrapper(legacyPath);return { name: binName, path: linkPath, target: cliPath };}- const linkPath = join24(input.binDir, binName);+ const linkPath = join25(input.binDir, binName);await replaceRuntimeWrapper(linkPath, posixRuntimeWrapper(binName, cliPath, input.codexHome, input.binDir, nodeCliPath));await chmod(linkPath, 493);await removeGeneratedRuntimeWrapper(legacyPath);@@ -92686,11 +92989,11 @@ async function linkRootRuntimeBin(input) {}async function linkCachedPluginBin(binDir, link, platform) {if (platform === "win32") {- const linkPath = join24(binDir, `${link.name}.cmd`);+ const linkPath = join25(binDir, `${link.name}.cmd`);await replaceCommandShim(linkPath, link.target);return linkPath;}- const linkPath = join24(binDir, link.name);+ const linkPath = join25(binDir, link.name);await replaceSymlink(linkPath, link.target);return linkPath;}@@ -92721,14 +93024,14 @@ async function discoverPackageBins(root) {async function collectPackageBins(directory, root, links) {const entries = await readdir2(directory, { withFileTypes: true });if (entries.some((entry) => entry.isFile() && entry.name === "package.json")) {- await appendPackageBinLinks(join24(directory, "package.json"), directory, root, links);+ await appendPackageBinLinks(join25(directory, "package.json"), directory, root, links);}for (const entry of entries) {if (!entry.isDirectory())continue;if (entry.name === "node_modules" || entry.name === ".git" || entry.name === "dist")continue;- const childPath = join24(directory, entry.name);+ const childPath = join25(directory, entry.name);if (!childPath.startsWith(root))continue;await collectPackageBins(childPath, root, links);@@ -92741,7 +93044,7 @@ async function appendPackageBinLinks(packageJsonPath, packageRoot, root, links)const packageName = packageJson.name;const packageBin = packageJson.bin;if (typeof packageBin === "string" && typeof packageName === "string") {- const name = assertSafeCommandName(basename3(packageName));+ const name = assertSafeCommandName(basename4(packageName));if (!isReservedNestedBinName(name, packageRoot, root)) {links.push({ name, target: resolvePackageBinTarget(packageRoot, packageBin) });}@@ -92770,8 +93073,8 @@ function isReservedNestedBinName(name, packageRoot, root) {function resolvePackageBinTarget(packageRoot, target) {if (target.includes("\x00"))throw new Error("Package bin target must stay inside package root");- const root = resolve5(packageRoot);- const resolvedTarget = resolve5(root, target);+ const root = resolve6(packageRoot);+ const resolvedTarget = resolve6(root, target);const relativeTarget = relative(root, resolvedTarget);if (relativeTarget === "" || relativeTarget !== ".." && !relativeTarget.startsWith(`..${sep}`) && !isAbsolute2(relativeTarget)) {return resolvedTarget;@@ -92863,11 +93166,11 @@ async function existingNonSymlink(path) {}// packages/omo-codex/src/install/codex-cache-install.tsimport { cp as cp2, mkdir as mkdir3, readFile as readFile8, readdir as readdir4, rename, rm as rm4 } from "node:fs/promises";-import { basename as basename4, dirname as dirname12, join as join30, sep as sep5 } from "node:path";+import { basename as basename5, dirname as dirname13, join as join31, sep as sep5 } from "node:path";// packages/omo-codex/src/install/codex-cache-bundled-mcps.tsimport { cp, mkdir as mkdir2, readFile as readFile4, stat as stat3 } from "node:fs/promises";-import { dirname as dirname10, join as join25, resolve as resolve6 } from "node:path";+import { dirname as dirname11, join as join26, resolve as resolve7 } from "node:path";var BUNDLED_MCP_RUNTIMES = [{label: "Git Bash MCP",@@ -92885,7 +93188,7 @@ var BUNDLED_MCP_RUNTIMES = [}];async function copyBundledMcpRuntimeDists(input) {- const sourceArgs = await readSourceMcpArgs(join25(input.sourceRoot, ".mcp.json"));+ const sourceArgs = await readSourceMcpArgs(join26(input.sourceRoot, ".mcp.json"));for (const runtime of BUNDLED_MCP_RUNTIMES) {if (!sourceArgs.has(runtime.sourceArg))continue;@@ -92894,15 +93197,15 @@ async function copyBundledMcpRuntimeDists(input) {}function resolveBundledMcpRuntimeArg(pluginRoot, arg) {const runtime = BUNDLED_MCP_RUNTIMES.find((candidate) => candidate.sourceArg === arg);- return runtime ? join25(pluginRoot, runtime.destinationArg) : null;+ return runtime ? join26(pluginRoot, runtime.destinationArg) : null;}async function copyBundledMcpRuntimeDist(pluginRoot, sourceRoot, runtime) {- const sourcePath = resolve6(sourceRoot, runtime.sourceDistFromPlugin);+ const sourcePath = resolve7(sourceRoot, runtime.sourceDistFromPlugin);if (!await isDirectory(sourcePath)) {throw new Error(`missing built ${runtime.label} dist at ${sourcePath}`);}- const destinationPath = join25(pluginRoot, runtime.destinationDistFromPlugin);- await mkdir2(dirname10(destinationPath), { recursive: true });+ const destinationPath = join26(pluginRoot, runtime.destinationDistFromPlugin);+ await mkdir2(dirname11(destinationPath), { recursive: true });await cp(sourcePath, destinationPath, { recursive: true });}async function readSourceMcpArgs(path) {@@ -92938,48 +93241,48 @@ async function isDirectory(path) {}// packages/omo-codex/src/install/codex-cache-local-dependencies.ts-import { realpathSync as realpathSync6 } from "node:fs";+import { realpathSync as realpathSync7 } from "node:fs";import { readFile as readFile5, readdir as readdir3, writeFile as writeFile2 } from "node:fs/promises";-import { dirname as dirname11, isAbsolute as isAbsolute4, join as join27, relative as relative3, resolve as resolve8, sep as sep2 } from "node:path";+import { dirname as dirname12, isAbsolute as isAbsolute4, join as join28, relative as relative3, resolve as resolve9, sep as sep2 } from "node:path";// packages/omo-codex/src/install/codex-cache-paths.ts-import { existsSync as existsSync22, readdirSync as readdirSync6 } from "node:fs";-import { isAbsolute as isAbsolute3, join as join26, relative as relative2, resolve as resolve7 } from "node:path";+import { existsSync as existsSync23, readdirSync as readdirSync7 } from "node:fs";+import { isAbsolute as isAbsolute3, join as join27, relative as relative2, resolve as resolve8 } from "node:path";var DEFAULT_CODEX_MARKETPLACE_NAME = "sisyphuslabs";var DEFAULT_CODEX_PLUGIN_NAME = "omo";function resolveDefaultCodexHome(homeDir) {- return join26(homeDir, ".codex");+ return join27(homeDir, ".codex");}function resolveCodexPluginCacheRoot(codexHome, input = {}) {- return join26(codexHome, "plugins", "cache", input.marketplaceName ?? DEFAULT_CODEX_MARKETPLACE_NAME, input.pluginName ?? DEFAULT_CODEX_PLUGIN_NAME);+ return join27(codexHome, "plugins", "cache", input.marketplaceName ?? DEFAULT_CODEX_MARKETPLACE_NAME, input.pluginName ?? DEFAULT_CODEX_PLUGIN_NAME);}function resolveCachedCodexComponentCliPath(pluginRoot, componentName) {- return join26(pluginRoot, "components", componentName, "dist", "cli.js");+ return join27(pluginRoot, "components", componentName, "dist", "cli.js");}function resolveCodexComponentBinCandidates(input) {return [- input.env.CODEX_LOCAL_BIN_DIR ? join26(input.env.CODEX_LOCAL_BIN_DIR, input.executableName) : undefined,- join26(input.homeDir, ".local", "bin", input.executableName),- join26(resolveDefaultCodexHome(input.homeDir), "bin", input.executableName)+ input.env.CODEX_LOCAL_BIN_DIR ? join27(input.env.CODEX_LOCAL_BIN_DIR, input.executableName) : undefined,+ join27(input.homeDir, ".local", "bin", input.executableName),+ join27(resolveDefaultCodexHome(input.homeDir), "bin", input.executableName)].filter((value) => typeof value === "string");}function findNewestCachedCodexComponentCli(input) {const versionsRoot = resolveCodexPluginCacheRoot(input.codexHome, input);- if (!existsSync22(versionsRoot))+ if (!existsSync23(versionsRoot))return null;- const versions = readdirSync6(versionsRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(compareVersionNames).reverse();+ const versions = readdirSync7(versionsRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(compareVersionNames).reverse();for (const version of versions) {- const candidate = resolveCachedCodexComponentCliPath(join26(versionsRoot, version), input.componentName);- if (existsSync22(candidate))+ const candidate = resolveCachedCodexComponentCliPath(join27(versionsRoot, version), input.componentName);+ if (existsSync23(candidate))return candidate;}return null;}function resolveCachedRuntimePath(pluginRoot, sourceRoot, runtimePath) {- const targetPath = resolve7(pluginRoot, runtimePath);+ const targetPath = resolve8(pluginRoot, runtimePath);if (isPathInside(targetPath, pluginRoot))return targetPath;- return resolve7(sourceRoot, runtimePath);+ return resolve8(sourceRoot, runtimePath);}function isPathInside(candidatePath, rootPath) {const pathFromRoot = relative2(rootPath, candidatePath);@@ -93009,8 +93312,8 @@ async function rewriteCachedPackageLocalFileDependencies(pluginRoot, sourceRoot)const parsed = JSON.parse(raw);if (!isPlainRecord4(parsed))continue;- const packageDir = dirname11(packageJsonPath);- const sourcePackageDir = join27(sourceRoot, relative3(pluginRoot, packageDir));+ const packageDir = dirname12(packageJsonPath);+ const sourcePackageDir = join28(sourceRoot, relative3(pluginRoot, packageDir));let changed = false;for (const field of ["dependencies", "optionalDependencies", "peerDependencies"]) {const dependencies = parsed[field];@@ -93022,10 +93325,10 @@ async function rewriteCachedPackageLocalFileDependencies(pluginRoot, sourceRoot)const filePath = specifier.slice("file:".length);if (filePath.length === 0 || isAbsolute4(filePath))continue;- const targetPath = resolve8(packageDir, filePath);+ const targetPath = resolve9(packageDir, filePath);if (isPathInside(targetPath, pluginRoot))continue;- const sourceTargetPath = resolve8(sourcePackageDir, filePath);+ const sourceTargetPath = resolve9(sourcePackageDir, filePath);dependencies[name] = `file:${sourceTargetPath}`;rewritePackageLockFileDependency({dependencyName: name,@@ -93051,7 +93354,7 @@ async function rewriteCachedPackageLocalFileDependencies(pluginRoot, sourceRoot)return rewroteAnyPackageJson;}async function readPackageLock(pluginRoot) {- const path = join27(pluginRoot, "package-lock.json");+ const path = join28(pluginRoot, "package-lock.json");try {const parsed = JSON.parse(await readFile5(path, "utf8"));return { path, value: isPlainRecord4(parsed) ? parsed : null, changed: false };@@ -93102,7 +93405,7 @@ function toPackageLockPath(path) {}function canonicalizeExistingPath(path) {try {- return realpathSync6(path);+ return realpathSync7(path);} catch (error) {if (error instanceof Error)return path;@@ -93112,14 +93415,14 @@ function canonicalizeExistingPath(path) {async function collectPackageJsonPaths(directory, root, paths) {const entries = await readdir3(directory, { withFileTypes: true });if (entries.some((entry) => entry.isFile() && entry.name === "package.json")) {- paths.push(join27(directory, "package.json"));+ paths.push(join28(directory, "package.json"));}for (const entry of entries) {if (!entry.isDirectory())continue;if (entry.name === "node_modules" || entry.name === ".git" || entry.name === "dist")continue;- const childPath = join27(directory, entry.name);+ const childPath = join28(directory, entry.name);if (!isPathInside(childPath, root))continue;await collectPackageJsonPaths(childPath, root, paths);@@ -93128,10 +93431,10 @@ async function collectPackageJsonPaths(directory, root, paths) {// packages/omo-codex/src/install/codex-cache-mcp-manifest.tsimport { readFile as readFile6, writeFile as writeFile3 } from "node:fs/promises";-import { join as join28, sep as sep3 } from "node:path";+import { join as join29, sep as sep3 } from "node:path";var CONTEXT7_API_KEY_ENV = "CONTEXT7_API_KEY";async function rewriteCachedMcpManifest(pluginRoot, sourceRoot = pluginRoot) {- const manifestPath = join28(pluginRoot, ".mcp.json");+ const manifestPath = join29(pluginRoot, ".mcp.json");if (!await fileExistsStrict(manifestPath))return;const raw = await readFile6(manifestPath, "utf8");@@ -93224,7 +93527,7 @@ function isPlaceholderContext7ApiKey(value) {return normalized.length === 0 || normalized === "your api key";}async function rewriteCachedManifestRoot(pluginRoot, fromRoot, toRoot) {- const manifestPath = join28(pluginRoot, ".mcp.json");+ const manifestPath = join29(pluginRoot, ".mcp.json");if (!await fileExistsStrict(manifestPath))return;const raw = await readFile6(manifestPath, "utf8");@@ -93260,7 +93563,7 @@ async function rewriteCachedManifestRoot(pluginRoot, fromRoot, toRoot) {// packages/omo-codex/src/install/codex-hook-targets.tsimport { readFile as readFile7 } from "node:fs/promises";-import { join as join29, sep as sep4 } from "node:path";+import { join as join30, sep as sep4 } from "node:path";var PLUGIN_ROOT_TARGET_PATTERN = /\$\{PLUGIN_ROOT\}[\\/]+([^"']+)/g;async function findMissingHookCommandTargets(pluginRoot) {const commands = [];@@ -93277,7 +93580,7 @@ async function findMissingHookCommandTargets(pluginRoot) {const targetSuffix = match[1];if (targetSuffix === undefined)continue;- const target = join29(pluginRoot, ...targetSuffix.split(/[\\/]+/));+ const target = join30(pluginRoot, ...targetSuffix.split(/[\\/]+/));if (seen.has(target))continue;seen.add(target);@@ -93288,17 +93591,17 @@ async function findMissingHookCommandTargets(pluginRoot) {return missing;}async function hookManifestPaths(pluginRoot) {- const pluginManifestPath = join29(pluginRoot, ".codex-plugin", "plugin.json");+ const pluginManifestPath = join30(pluginRoot, ".codex-plugin", "plugin.json");if (!await fileExistsStrict(pluginManifestPath))- return [join29(pluginRoot, "hooks", "hooks.json")];+ return [join30(pluginRoot, "hooks", "hooks.json")];const parsed = JSON.parse(await readFile7(pluginManifestPath, "utf8"));if (!isPlainRecord4(parsed))return [];if (typeof parsed.hooks === "string" && parsed.hooks.trim() !== "") {- return [join29(pluginRoot, stripDotSlash(parsed.hooks))];+ return [join30(pluginRoot, stripDotSlash(parsed.hooks))];}if (Array.isArray(parsed.hooks)) {- return parsed.hooks.filter((hookPath) => typeof hookPath === "string" && hookPath.trim() !== "").map((hookPath) => join29(pluginRoot, stripDotSlash(hookPath)));+ return parsed.hooks.filter((hookPath) => typeof hookPath === "string" && hookPath.trim() !== "").map((hookPath) => join30(pluginRoot, stripDotSlash(hookPath)));}return [];}@@ -93336,7 +93639,7 @@ async function installCachedPlugin(input) {await maybeRunNpmInstall(input.sourcePath, input.runCommand, npmInstallEnv);await maybeRunNpmBuild(input.sourcePath, input.runCommand, env);}- const targetPath = join30(input.codexHome, "plugins", "cache", input.marketplaceName, input.name, input.version);+ const targetPath = join31(input.codexHome, "plugins", "cache", input.marketplaceName, input.name, input.version);const tempPath = createTempSiblingPath(targetPath);await rm4(tempPath, { recursive: true, force: true });try {@@ -93362,14 +93665,14 @@ async function installCachedPlugin(input) {return { name: input.name, version: input.version, path: targetPath };}async function maybeRunNpmInstall(cwd, runCommand, env, args = ["install"]) {- if (!await fileExistsStrict(join30(cwd, "package.json")))+ if (!await fileExistsStrict(join31(cwd, "package.json")))return;await runCommand("npm", args, { cwd, env });}async function maybeRunNpmBuild(cwd, runCommand, env) {- if (!await fileExistsStrict(join30(cwd, "package.json")))+ if (!await fileExistsStrict(join31(cwd, "package.json")))return;- const packageJson = JSON.parse(await readFile8(join30(cwd, "package.json"), "utf8"));+ const packageJson = JSON.parse(await readFile8(join31(cwd, "package.json"), "utf8"));if (!isPlainRecord4(packageJson))return;const scripts = packageJson.scripts;@@ -93378,9 +93681,9 @@ async function maybeRunNpmBuild(cwd, runCommand, env) {await runCommand("npm", ["run", "build"], { cwd, env });}async function maybeRunNpmSyncSkills(cwd, runCommand, env) {- if (!await fileExistsStrict(join30(cwd, "package.json")))+ if (!await fileExistsStrict(join31(cwd, "package.json")))return;- const packageJson = JSON.parse(await readFile8(join30(cwd, "package.json"), "utf8"));+ const packageJson = JSON.parse(await readFile8(join31(cwd, "package.json"), "utf8"));if (!isPlainRecord4(packageJson))return;const scripts = packageJson.scripts;@@ -93392,13 +93695,13 @@ function sanitizeNpmInstallEnv(env) {return Object.fromEntries(Object.entries(env).filter(([key]) => key.toLowerCase() !== "npm_config_allow_scripts"));}function createTempSiblingPath(targetPath) {- return join30(dirname12(targetPath), `.tmp-${basename4(targetPath)}-${process.pid}-${Date.now()}`);+ return join31(dirname13(targetPath), `.tmp-${basename5(targetPath)}-${process.pid}-${Date.now()}`);}function createBackupSiblingPath(targetPath) {- return join30(dirname12(targetPath), `.backup-${basename4(targetPath)}-${process.pid}-${Date.now()}`);+ return join31(dirname13(targetPath), `.backup-${basename5(targetPath)}-${process.pid}-${Date.now()}`);}async function copyDirectory(sourcePath, targetPath) {- await mkdir3(dirname12(targetPath), { recursive: true });+ await mkdir3(dirname13(targetPath), { recursive: true });await cp2(sourcePath, targetPath, { recursive: true, filter: (source) => shouldCopyPluginPath(source, sourcePath) });}async function promoteDirectory(tempPath, targetPath, renameDirectory) {@@ -93443,18 +93746,18 @@ var removedSparkshellPromptSurfaceFiles = new Set(["directive.md", "plugin.json"var removedSparkshellTextFilePattern = /\.(?:json|md|toml|ya?ml)$/i;async function assertNoRemovedSparkshellPromptReferences(pluginRoot) {for (const filePath of await listRemovedSparkshellPromptSurfaceFiles(pluginRoot, "")) {- const content = await readFile8(join30(pluginRoot, filePath), "utf8");+ const content = await readFile8(join31(pluginRoot, filePath), "utf8");if (!removedSparkshellReferencePattern.test(content))continue;throw new Error(`removed sparkshell reference found in Codex plugin prompt surface: ${filePath}`);}}async function listRemovedSparkshellPromptSurfaceFiles(pluginRoot, relativeDirectory) {- const directory = relativeDirectory === "" ? pluginRoot : join30(pluginRoot, relativeDirectory);+ const directory = relativeDirectory === "" ? pluginRoot : join31(pluginRoot, relativeDirectory);const entries = await readdir4(directory, { withFileTypes: true });const files = [];for (const entry of entries) {- const relativePath = relativeDirectory === "" ? entry.name : join30(relativeDirectory, entry.name);+ const relativePath = relativeDirectory === "" ? entry.name : join31(relativeDirectory, entry.name);if (entry.isDirectory()) {if (shouldDescendIntoRemovedSparkshellPromptSurface(relativePath)) {files.push(...await listRemovedSparkshellPromptSurfaceFiles(pluginRoot, relativePath));@@ -93494,43 +93797,43 @@ async function copyRootRuntimeDists(input) {if (repoRoot === null)return;for (const runtimePath of ["dist/cli", "dist/cli-node"]) {- const sourcePath = join30(repoRoot, runtimePath);- if (!await fileExistsStrict(join30(sourcePath, "index.js")))+ const sourcePath = join31(repoRoot, runtimePath);+ if (!await fileExistsStrict(join31(sourcePath, "index.js")))continue;- await mkdir3(dirname12(join30(input.pluginRoot, runtimePath)), { recursive: true });- await cp2(sourcePath, join30(input.pluginRoot, runtimePath), { recursive: true });+ await mkdir3(dirname13(join31(input.pluginRoot, runtimePath)), { recursive: true });+ await cp2(sourcePath, join31(input.pluginRoot, runtimePath), { recursive: true });}}-var canonicalPromptRelativePaths = [join30("packages", "prompts-core", "prompts", "ultrawork", "codex.md")];+var canonicalPromptRelativePaths = [join31("packages", "prompts-core", "prompts", "ultrawork", "codex.md")];async function copyCanonicalPromptSources(input) {const repoRoot = repoRootForCodexPluginSource(input.sourcePath);if (repoRoot === null)return;for (const relativePath of canonicalPromptRelativePaths) {- const sourceFile = join30(repoRoot, relativePath);+ const sourceFile = join31(repoRoot, relativePath);if (!await fileExistsStrict(sourceFile))continue;- const targetFile = join30(input.pluginRoot, relativePath);- await mkdir3(dirname12(targetFile), { recursive: true });+ const targetFile = join31(input.pluginRoot, relativePath);+ await mkdir3(dirname13(targetFile), { recursive: true });await cp2(sourceFile, targetFile);}}function repoRootForCodexPluginSource(sourcePath) {- const codexPackageRoot = dirname12(sourcePath);- const packagesRoot = dirname12(codexPackageRoot);- if (basename4(sourcePath) !== "plugin")+ const codexPackageRoot = dirname13(sourcePath);+ const packagesRoot = dirname13(codexPackageRoot);+ if (basename5(sourcePath) !== "plugin")return null;- if (basename4(codexPackageRoot) !== "omo-codex")+ if (basename5(codexPackageRoot) !== "omo-codex")return null;- if (basename4(packagesRoot) !== "packages")+ if (basename5(packagesRoot) !== "packages")return null;- return dirname12(packagesRoot);+ return dirname13(packagesRoot);}// packages/omo-codex/src/install/codex-cache-prune.tsimport { lstat as lstat5, readdir as readdir5, rm as rm5, stat as stat4 } from "node:fs/promises";-import { join as join31 } from "node:path";+import { join as join32 } from "node:path";async function pruneMarketplaceCache(input) {- const cacheRoot = join31(input.codexHome, "plugins", "cache", input.marketplaceName);+ const cacheRoot = join32(input.codexHome, "plugins", "cache", input.marketplaceName);if (!await fileExistsStrict(cacheRoot))return;const keep = new Set(input.keepPluginNames);@@ -93538,15 +93841,15 @@ async function pruneMarketplaceCache(input) {for (const entry of entries) {if (!entry.isDirectory() || keep.has(entry.name))continue;- await rm5(join31(cacheRoot, entry.name), { recursive: true, force: true });+ await rm5(join32(cacheRoot, entry.name), { recursive: true, force: true });}}async function pruneMarketplacePluginCaches(input) {- const cacheRoot = join31(input.codexHome, "plugins", "cache", input.marketplaceName);+ const cacheRoot = join32(input.codexHome, "plugins", "cache", input.marketplaceName);if (!await fileExistsStrict(cacheRoot))return;for (const pluginName of input.pluginNames) {- await rm5(join31(cacheRoot, pluginName), { recursive: true, force: true });+ await rm5(join32(cacheRoot, pluginName), { recursive: true, force: true });}const remainingEntries = await readCacheEntryNames(cacheRoot);if (remainingEntries.length === 0) {@@ -93593,17 +93896,17 @@ async function isBrokenCacheSymlink(path) {}// packages/omo-codex/src/install/codex-cached-marketplace-manifest.tsimport { mkdir as mkdir4, rename as rename2, rm as rm6, stat as stat5, writeFile as writeFile4 } from "node:fs/promises";-import { join as join32 } from "node:path";+import { join as join33 } from "node:path";async function writeCachedMarketplaceManifest(input) {- const marketplaceDir = join32(input.marketplaceRoot, ".agents", "plugins");+ const marketplaceDir = join33(input.marketplaceRoot, ".agents", "plugins");await mkdir4(marketplaceDir, { recursive: true });for (const plugin of input.plugins) {- const pluginPath = join32(input.marketplaceRoot, plugin.name, plugin.version);+ const pluginPath = join33(input.marketplaceRoot, plugin.name, plugin.version);if (!await isDirectory2(pluginPath))throw new Error(`Cannot write cached marketplace manifest: ${pluginPath} does not exist`);}- const manifestPath = join32(marketplaceDir, "marketplace.json");- const tempPath = join32(marketplaceDir, `.marketplace.json.tmp-${process.pid}-${Date.now()}`);+ const manifestPath = join33(marketplaceDir, "marketplace.json");+ const tempPath = join33(marketplaceDir, `.marketplace.json.tmp-${process.pid}-${Date.now()}`);try {await writeFile4(tempPath, `${JSON.stringify({name: input.marketplaceName,@@ -93630,9 +93933,9 @@ async function isDirectory2(path) {}// packages/omo-codex/src/install/codex-package-layout.ts-import { existsSync as existsSync23 } from "node:fs";+import { existsSync as existsSync24 } from "node:fs";import { readFile as readFile9 } from "node:fs/promises";-import { join as join33 } from "node:path";+import { join as join34 } from "node:path";var PACKAGED_CODEX_INSTALLER_NAMES = new Set(["@code-yeongyu/lazycodex","@code-yeongyu/lazycodex-ai",@@ -93642,10 +93945,10 @@ var PACKAGED_CODEX_INSTALLER_NAMES = new Set(["oh-my-openagent"]);async function shouldBuildSourcePackages(repoRoot) {- if (existsSync23(join33(repoRoot, "packages", "omo-opencode", "src", "index.ts")))+ if (existsSync24(join34(repoRoot, "packages", "omo-opencode", "src", "index.ts")))return true;- const packageJsonPath = join33(repoRoot, "package.json");- if (!existsSync23(packageJsonPath))+ const packageJsonPath = join34(repoRoot, "package.json");+ if (!existsSync24(packageJsonPath))return true;const packageJson = JSON.parse(await readFile9(packageJsonPath, "utf8"));if (!isPlainRecord4(packageJson) || typeof packageJson.name !== "string")@@ -93655,7 +93958,7 @@ async function shouldBuildSourcePackages(repoRoot) {// packages/omo-codex/src/install/codex-config-toml.tsimport { mkdir as mkdir5, readFile as readFile11 } from "node:fs/promises";-import { dirname as dirname15 } from "node:path";+import { dirname as dirname16 } from "node:path";// packages/omo-codex/src/install/toml-section-editor.tsfunction findTomlSection(config, header) {@@ -94252,12 +94555,12 @@ function tomlKeySegment(value) {// packages/omo-codex/src/install/codex-config-atomic-write.tsimport { lstat as lstat6, readlink as readlink4, realpath, rename as rename3, unlink, writeFile as writeFile5 } from "node:fs/promises";-import { basename as basename5, dirname as dirname13, isAbsolute as isAbsolute5, join as join34, resolve as resolve9 } from "node:path";+import { basename as basename6, dirname as dirname14, isAbsolute as isAbsolute5, join as join35, resolve as resolve10 } from "node:path";var RENAME_RETRY_DELAYS_MS = [10, 25, 50];var RETRIABLE_RENAME_CODES = new Set(["EPERM", "EBUSY"]);async function writeFileAtomic(targetPath, data) {const writeTarget = await resolveSymlinkTarget(targetPath);- const temporaryPath = join34(dirname13(writeTarget), `.tmp-${basename5(writeTarget)}-${process.pid}-${Date.now()}`);+ const temporaryPath = join35(dirname14(writeTarget), `.tmp-${basename6(writeTarget)}-${process.pid}-${Date.now()}`);await writeFile5(temporaryPath, data);try {await renameWithRetry(temporaryPath, writeTarget);@@ -94286,7 +94589,7 @@ async function resolveSymlinkTarget(targetPath) {if (!(error instanceof Error))throw error;const linkValue = await readlink4(targetPath);- return isAbsolute5(linkValue) ? linkValue : resolve9(dirname13(targetPath), linkValue);+ return isAbsolute5(linkValue) ? linkValue : resolve10(dirname14(targetPath), linkValue);}}async function renameWithRetry(fromPath, toPath) {@@ -94751,7 +95054,7 @@ function isRootSetting(line, key) {// packages/omo-codex/src/install/codex-model-catalog.tsimport { readFile as readFile10 } from "node:fs/promises";-import { join as join35 } from "node:path";+import { join as join36 } from "node:path";var FALLBACK_CODEX_MODEL_CATALOG = {current: {model: "gpt-6-astra",@@ -94782,7 +95085,7 @@ var FALLBACK_CODEX_MODEL_CATALOG = {]};async function readCodexModelCatalog(codexPackageRoot) {- const catalogPath = join35(codexPackageRoot, "plugin", "model-catalog.json");+ const catalogPath = join36(codexPackageRoot, "plugin", "model-catalog.json");try {const parsed = JSON.parse(await readFile10(catalogPath, "utf8"));return parseCodexModelCatalog(parsed) ?? FALLBACK_CODEX_MODEL_CATALOG;@@ -94865,8 +95168,8 @@ function isRootSetting2(line, key) {}// packages/omo-codex/src/install/codex-multi-agent-v2-config.ts-import { readFileSync as readFileSync10 } from "node:fs";-import { dirname as dirname14, isAbsolute as isAbsolute6, join as join36 } from "node:path";+import { readFileSync as readFileSync11 } from "node:fs";+import { dirname as dirname15, isAbsolute as isAbsolute6, join as join37 } from "node:path";var CODEX_AGENTS_HEADER = "agents";var CODEX_MULTI_AGENT_V2_HEADER = "features.multi_agent_v2";function ensureCodexMultiAgentV2Config(config, options = {}) {@@ -94894,13 +95197,13 @@ function resolveCodexMultiAgentVersion(config, configPath) {}function resolveCatalogPath(configuredPath, configPath) {if (configuredPath === null)- return join36(dirname14(configPath), "models_cache.json");- return isAbsolute6(configuredPath) ? configuredPath : join36(dirname14(configPath), configuredPath);+ return join37(dirname15(configPath), "models_cache.json");+ return isAbsolute6(configuredPath) ? configuredPath : join37(dirname15(configPath), configuredPath);}function readCatalogMultiAgentVersion(model, cachePath) {let raw;try {- raw = readFileSync10(cachePath, "utf8");+ raw = readFileSync11(cachePath, "utf8");} catch {return null;}@@ -95006,7 +95309,7 @@ function readBooleanSetting(sectionText, key) {// packages/omo-codex/src/install/codex-config-toml.tsasync function updateCodexConfig(input) {- await mkdir5(dirname15(input.configPath), { recursive: true });+ await mkdir5(dirname16(input.configPath), { recursive: true });let config;try {config = await readFile11(input.configPath, "utf8");@@ -95057,7 +95360,7 @@ function isMissingFileError(error) {// packages/omo-codex/src/install/codex-hook-trust.tsimport { createHash as createHash2 } from "node:crypto";import { readFile as readFile12 } from "node:fs/promises";-import { join as join37 } from "node:path";+import { join as join38 } from "node:path";var EVENT_LABELS = new Map([["PreToolUse", "pre_tool_use"],["PermissionRequest", "permission_request"],@@ -95071,7 +95374,7 @@ var EVENT_LABELS = new Map([["Stop", "stop"]]);async function trustedHookStatesForPlugin(input) {- const manifestPath = join37(input.pluginRoot, ".codex-plugin", "plugin.json");+ const manifestPath = join38(input.pluginRoot, ".codex-plugin", "plugin.json");if (!await exists(manifestPath))return [];const manifest = JSON.parse(await readFile12(manifestPath, "utf8"));@@ -95079,7 +95382,7 @@ async function trustedHookStatesForPlugin(input) {return [];const states = [];for (const hookPath of hookManifestPaths2(manifest.hooks)) {- const hooksPath = join37(input.pluginRoot, hookPath);+ const hooksPath = join38(input.pluginRoot, hookPath);if (!await exists(hooksPath))continue;const parsed = JSON.parse(await readFile12(hooksPath, "utf8"));@@ -95206,11 +95509,11 @@ function toCodexResolution(resolution) {// packages/omo-codex/src/install/link-cached-plugin-agents.tsimport { copyFile, lstat as lstat10, mkdir as mkdir6, readdir as readdir7, rm as rm9, writeFile as writeFile7 } from "node:fs/promises";-import { basename as basename6, join as join41 } from "node:path";+import { basename as basename7, join as join42 } from "node:path";// packages/omo-codex/src/install/preserved-agent-settings.tsimport { lstat as lstat7, readFile as readFile13, readdir as readdir6, writeFile as writeFile6 } from "node:fs/promises";-import { join as join38 } from "node:path";+import { join as join39 } from "node:path";// packages/omo-codex/src/install/managed-agent-reasoning-defaults.tsvar MANAGED_REASONING_DEFAULT_UPGRADES = new Map([@@ -95403,7 +95706,7 @@ function resolveManagedAgentReasoning(input) {// packages/omo-codex/src/install/preserved-agent-settings.tsasync function capturePreservedAgentReasoning(input) {- const agentsDir = join38(input.codexHome, "agents");+ const agentsDir = join39(input.codexHome, "agents");if (!await exists2(agentsDir))return new Map;const preserved = new Map;@@ -95411,7 +95714,7 @@ async function capturePreservedAgentReasoning(input) {for (const entry of agentEntries) {if (!entry.name.endsWith(".toml"))continue;- const content = await readTextIfExists(join38(agentsDir, entry.name));+ const content = await readTextIfExists(join39(agentsDir, entry.name));if (content === null)continue;const effort = extractReasoningEffort(content);@@ -95425,7 +95728,7 @@ async function capturePreservedAgentReasoning(input) {return preserved;}async function capturePreservedAgentServiceTier(input) {- const agentsDir = join38(input.codexHome, "agents");+ const agentsDir = join39(input.codexHome, "agents");if (!await exists2(agentsDir))return new Map;const preserved = new Map;@@ -95433,7 +95736,7 @@ async function capturePreservedAgentServiceTier(input) {for (const entry of agentEntries) {if (!entry.name.endsWith(".toml"))continue;- const content = await readTextIfExists(join38(agentsDir, entry.name));+ const content = await readTextIfExists(join39(agentsDir, entry.name));if (content === null)continue;preserved.set(agentNameFromToml(entry.name), extractServiceTier(content));@@ -95567,7 +95870,7 @@ function nodeErrorCode(error) {// packages/omo-codex/src/install/retired-managed-agent-purge.tsimport { lstat as lstat8, readFile as readFile14, rm as rm7 } from "node:fs/promises";-import { join as join39 } from "node:path";+import { join as join40 } from "node:path";var RETIRED_MANAGED_AGENT_FILES = [{fileName: "codex-ultrawork-reviewer.toml",@@ -95579,11 +95882,11 @@ var RETIRED_MANAGED_AGENT_FILES = [}];async function purgeRetiredManagedAgentFiles(input) {- const agentsDir = join39(input.codexHome, "agents");+ const agentsDir = join40(input.codexHome, "agents");if (!await exists3(agentsDir))return;for (const retiredAgent of RETIRED_MANAGED_AGENT_FILES) {- const agentPath = join39(agentsDir, retiredAgent.fileName);+ const agentPath = join40(agentsDir, retiredAgent.fileName);if (!await exists3(agentPath))continue;const agentStat = await lstat8(agentPath);@@ -95626,12 +95929,12 @@ function nodeErrorCode2(error) {// packages/omo-codex/src/install/default-agent-role.tsimport { createHash as createHash3 } from "node:crypto";import { lstat as lstat9, readFile as readFile15, rm as rm8 } from "node:fs/promises";-import { join as join40 } from "node:path";+import { join as join41 } from "node:path";var REGISTRATION = { name: "default", configFile: "./agents/default.toml" };async function installDefaultAgentRole(input) {- const target = join40(input.codexHome, "agents", "default.toml");- const receipt = join40(input.codexHome, "agents", ".lazycodex-default.sha256");- const configPath = join40(input.codexHome, "config.toml");+ const target = join41(input.codexHome, "agents", "default.toml");+ const receipt = join41(input.codexHome, "agents", ".lazycodex-default.sha256");+ const configPath = join41(input.codexHome, "config.toml");const config = await readIfPresent(configPath);const entry = await lstat9(target).catch((error) => {if (error instanceof Error && "code" in error && error.code === "ENOENT")@@ -95692,13 +95995,13 @@ async function linkCachedPluginAgents(input) {await writeManifest(input.pluginRoot, []);return [];}- const agentsDir = join41(input.codexHome, "agents");+ const agentsDir = join42(input.codexHome, "agents");await mkdir6(agentsDir, { recursive: true });const linked = [];for (const agentPath of bundledAgents) {- const agentFileName = basename6(agentPath);+ const agentFileName = basename7(agentPath);const agentName = agentNameFromToml2(agentFileName);- const linkPath = join41(agentsDir, agentFileName);+ const linkPath = join42(agentsDir, agentFileName);await replaceWithCopy(linkPath, agentPath);await restorePreservedReasoning({agentName,@@ -95723,7 +96026,7 @@ async function linkCachedPluginAgents(input) {return linked;}async function discoverBundledAgents(pluginRoot) {- const componentsRoot = join41(pluginRoot, "components");+ const componentsRoot = join42(pluginRoot, "components");if (!await exists4(componentsRoot))return [];const componentEntries = await readdir7(componentsRoot, { withFileTypes: true });@@ -95731,14 +96034,14 @@ async function discoverBundledAgents(pluginRoot) {for (const entry of componentEntries) {if (!entry.isDirectory())continue;- const agentsRoot = join41(componentsRoot, entry.name, "agents");+ const agentsRoot = join42(componentsRoot, entry.name, "agents");if (!await exists4(agentsRoot))continue;const agentEntries = await readdir7(agentsRoot, { withFileTypes: true });for (const file of agentEntries) {if (!file.isFile() || !file.name.endsWith(".toml"))continue;- agents.push(join41(agentsRoot, file.name));+ agents.push(join42(agentsRoot, file.name));}}agents.sort();@@ -95758,7 +96061,7 @@ async function prepareReplacement(linkPath) {await rm9(linkPath, { force: true });}async function writeManifest(pluginRoot, agentPaths) {- const manifestPath = join41(pluginRoot, MANIFEST_FILE);+ const manifestPath = join42(pluginRoot, MANIFEST_FILE);const payload = { agents: [...agentPaths].sort() };await writeFile7(manifestPath, `${JSON.stringify(payload, null, "\t")}`);@@ -95784,10 +96087,10 @@ function nodeErrorCode3(error) {// packages/omo-codex/src/install/codex-marketplace.tsimport { readFile as readFile16 } from "node:fs/promises";-import { join as join42 } from "node:path";+import { join as join43 } from "node:path";var DEFAULT_MARKETPLACE_PATH = "packages/omo-codex/marketplace.json";async function readMarketplace(repoRoot, options) {- const marketplacePath = options?.marketplacePath ?? join42(repoRoot, DEFAULT_MARKETPLACE_PATH);+ const marketplacePath = options?.marketplacePath ?? join43(repoRoot, DEFAULT_MARKETPLACE_PATH);const raw = await readFile16(marketplacePath, "utf8");const parsed = JSON.parse(raw);if (!isPlainRecord4(parsed))@@ -95806,10 +96109,10 @@ async function readMarketplace(repoRoot, options) {function resolvePluginSource(repoRoot, plugin, options) {const sourcePath = localSourcePath(options?.pathOverride ?? plugin.source);const relativePath = sourcePath.slice(2);- return join42(repoRoot, ...relativePath.split(/[\\/]/));+ return join43(repoRoot, ...relativePath.split(/[\\/]/));}async function readPluginManifest(pluginRoot) {- const raw = await readFile16(join42(pluginRoot, ".codex-plugin", "plugin.json"), "utf8");+ const raw = await readFile16(join43(pluginRoot, ".codex-plugin", "plugin.json"), "utf8");const parsed = JSON.parse(raw);if (!isPlainRecord4(parsed))throw new Error(`${pluginRoot} plugin.json must be an object`);@@ -95891,7 +96194,7 @@ function validateLocalSourcePath(path) {// packages/omo-codex/src/install/codex-marketplace-snapshot.tsimport { cp as cp3, mkdir as mkdir7, rename as rename4, rm as rm10, writeFile as writeFile8 } from "node:fs/promises";-import { join as join43, sep as sep6 } from "node:path";+import { join as join44, sep as sep6 } from "node:path";var INSTALLED_MARKETPLACES_DIR = ".tmp/marketplaces";async function writeInstalledMarketplaceSnapshot(input) {const marketplaceRoot = installedMarketplaceRoot(input.codexHome, input.marketplace.name);@@ -95904,21 +96207,21 @@ async function writeInstalledMarketplaceSnapshot(input) {return snapshotPlugins;}function installedMarketplaceRoot(codexHome, marketplaceName) {- return join43(codexHome, INSTALLED_MARKETPLACES_DIR, marketplaceName);+ return join44(codexHome, INSTALLED_MARKETPLACES_DIR, marketplaceName);}async function writeMarketplaceManifest(marketplaceRoot, marketplace) {- const manifestDir = join43(marketplaceRoot, ".agents", "plugins");+ const manifestDir = join44(marketplaceRoot, ".agents", "plugins");await mkdir7(manifestDir, { recursive: true });- const tempPath = join43(manifestDir, `.marketplace-${process.pid}-${Date.now()}.json.tmp`);+ const tempPath = join44(manifestDir, `.marketplace-${process.pid}-${Date.now()}.json.tmp`);await writeFile8(tempPath, `${JSON.stringify(marketplace, null, "\t")}`);- await rename4(tempPath, join43(manifestDir, "marketplace.json"));+ await rename4(tempPath, join44(manifestDir, "marketplace.json"));}async function writeSnapshotPlugin(marketplaceRoot, plugin) {- const pluginsDir = join43(marketplaceRoot, "plugins");+ const pluginsDir = join44(marketplaceRoot, "plugins");await mkdir7(pluginsDir, { recursive: true });- const targetPath = join43(pluginsDir, plugin.name);- const tempPath = join43(pluginsDir, `.tmp-${plugin.name}-${process.pid}-${Date.now()}`);+ const targetPath = join44(pluginsDir, plugin.name);+ const tempPath = join44(pluginsDir, `.tmp-${plugin.name}-${process.pid}-${Date.now()}`);await rm10(tempPath, { recursive: true, force: true });await cp3(plugin.sourcePath, tempPath, {recursive: true,@@ -95940,10 +96243,10 @@ function shouldCopyMarketplaceSourcePath(path, root) {// packages/omo-codex/src/install/lazycodex-version-stamp.tsimport { readdir as readdir8, readFile as readFile17, writeFile as writeFile9 } from "node:fs/promises";-import { join as join44 } from "node:path";+import { join as join45 } from "node:path";async function readDistributionManifest(repoRoot) {try {- const parsed = JSON.parse(await readFile17(join44(repoRoot, "package.json"), "utf8"));+ const parsed = JSON.parse(await readFile17(join45(repoRoot, "package.json"), "utf8"));if (!isPlainRecord4(parsed) || typeof parsed.version !== "string" || parsed.version.trim().length === 0)return;return {@@ -95967,19 +96270,19 @@ function resolveLazyCodexPluginVersion(input) {return input.manifestVersion ?? "local";}async function stampLazyCodexPluginVersion(input) {- const manifestPath = join44(input.pluginRoot, ".codex-plugin", "plugin.json");+ const manifestPath = join45(input.pluginRoot, ".codex-plugin", "plugin.json");const hookPaths = await readPluginHookPaths(manifestPath);await stampJsonVersion(manifestPath, input.version);- await stampJsonVersion(join44(input.pluginRoot, "package.json"), input.version);+ await stampJsonVersion(join45(input.pluginRoot, "package.json"), input.version);for (const hookPath of hookPaths) {- await stampHookStatusMessages(join44(input.pluginRoot, hookPath), input.version);+ await stampHookStatusMessages(join45(input.pluginRoot, hookPath), input.version);}await stampComponentVersions(input);}async function writeLazyCodexInstallSnapshot(input) {if (input.distributionManifest === undefined)return;- await writeFile9(join44(input.pluginRoot, "lazycodex-install.json"), `${JSON.stringify({+ await writeFile9(join45(input.pluginRoot, "lazycodex-install.json"), `${JSON.stringify({packageName: input.distributionManifest.name,version: input.distributionManifest.version}, null, "\t")}@@ -96036,16 +96339,16 @@ async function stampHookStatusMessages(path, version) {async function stampComponentVersions(input) {let entries;try {- entries = await readdir8(join44(input.pluginRoot, "components"));+ entries = await readdir8(join45(input.pluginRoot, "components"));} catch (error) {if (error instanceof Error)return;throw error;}for (const entry of entries) {- const componentRoot = join44(input.pluginRoot, "components", entry);- await stampJsonVersion(join44(componentRoot, "package.json"), input.version);- await stampHookStatusMessages(join44(componentRoot, "hooks", "hooks.json"), input.version);+ const componentRoot = join45(input.pluginRoot, "components", entry);+ await stampJsonVersion(join45(componentRoot, "package.json"), input.version);+ await stampHookStatusMessages(join45(componentRoot, "hooks", "hooks.json"), input.version);}}function stampHookGroups(hooks, version) {@@ -96103,7 +96406,7 @@ var defaultRunCommand = async (command, args, options) => {// packages/omo-codex/src/install/codex-project-local-cleanup.tsimport { copyFile as copyFile2, lstat as lstat11, readFile as readFile18, writeFile as writeFile10 } from "node:fs/promises";-import { dirname as dirname16, join as join45, resolve as resolve10 } from "node:path";+import { dirname as dirname17, join as join46, resolve as resolve11 } from "node:path";var LEGACY_AGENT_CONFLICT_KEYS = ["max_threads"];var PROJECT_LOCAL_ARTIFACT_PATHS = [".codex/hooks.json",@@ -96206,37 +96509,37 @@ async function findProjectLocalCodexConfigs(startDirectory, codexHome) {if (startDirectoryStat !== null && !startDirectoryStat.isDirectory()) {throw new ProjectLocalCleanupStartDirectoryError(startDirectory);}- const codexHomeConfigPath = codexHome === undefined ? null : join45(resolve10(codexHome), "config.toml");- let current = resolve10(startDirectory);+ const codexHomeConfigPath = codexHome === undefined ? null : join46(resolve11(codexHome), "config.toml");+ let current = resolve11(startDirectory);const configPathsFromCwd = [];while (true) {- const configPath = join45(current, ".codex", "config.toml");+ const configPath = join46(current, ".codex", "config.toml");if (await isRegularProjectLocalConfig(current, configPath)) {- if (codexHomeConfigPath === null || resolve10(configPath) !== codexHomeConfigPath) {+ if (codexHomeConfigPath === null || resolve11(configPath) !== codexHomeConfigPath) {configPathsFromCwd.push(configPath);}}- if (await exists5(join45(current, ".git"))) {+ if (await exists5(join46(current, ".git"))) {return configPathsFromCwd.length === 0 ? null : {projectRoot: current,configPaths: [...configPathsFromCwd].reverse(),artifactRoots: artifactRootsForConfigPaths(configPathsFromCwd)};}- const parent = dirname16(current);+ const parent = dirname17(current);if (parent === current) {const nearestConfigPath = configPathsFromCwd[0];return nearestConfigPath === undefined ? null : {- projectRoot: dirname16(dirname16(nearestConfigPath)),+ projectRoot: dirname17(dirname17(nearestConfigPath)),configPaths: [nearestConfigPath],- artifactRoots: [dirname16(dirname16(nearestConfigPath))]+ artifactRoots: [dirname17(dirname17(nearestConfigPath))]};}current = parent;}}async function isRegularProjectLocalConfig(directory, configPath) {- const codexDirStat = await maybeLstat(join45(directory, ".codex"));+ const codexDirStat = await maybeLstat(join46(directory, ".codex"));if (codexDirStat === null || !codexDirStat.isDirectory() || codexDirStat.isSymbolicLink())return false;const configStat = await maybeLstat(configPath);@@ -96245,7 +96548,7 @@ async function isRegularProjectLocalConfig(directory, configPath) {function artifactRootsForConfigPaths(configPaths) {const roots = [];for (const configPath of configPaths) {- const root = dirname16(dirname16(configPath));+ const root = dirname17(dirname17(configPath));if (!roots.includes(root))roots.push(root);}@@ -96256,7 +96559,7 @@ async function collectProjectLocalArtifacts(projectRoots) {const seenPaths = new Set;for (const projectRoot of projectRoots) {for (const relativePath of PROJECT_LOCAL_ARTIFACT_PATHS) {- const artifactPath = join45(projectRoot, relativePath);+ const artifactPath = join46(projectRoot, relativePath);if (seenPaths.has(artifactPath))continue;const entryStat = await maybeLstat(artifactPath);@@ -96334,13 +96637,13 @@ function formatUnknownError(error) {import { createHash as createHash4 } from "node:crypto";import { lstat as lstat12, readFile as readFile20, readdir as readdir10, rm as rm11 } from "node:fs/promises";import { tmpdir as tmpdir3 } from "node:os";-import { join as join46, posix as posix6 } from "node:path";+import { join as join47, posix as posix6 } from "node:path";// packages/omo-codex/src/install/lsp-daemon-reaper-attestation.tsimport { execFile } from "node:child_process";import { readFile as readFile19, readdir as readdir9, readlink as readlink5 } from "node:fs/promises";import { connect } from "node:net";-import { basename as basename7 } from "node:path";+import { basename as basename8 } from "node:path";var PROBE_TIMEOUT_MS = 500;async function probeLegacyJsonRpcEndpoint(endpoint, timeoutMs = PROBE_TIMEOUT_MS) {return await new Promise((resolve) => {@@ -96472,14 +96775,14 @@ function splitCmdline(buffer) {function isNodeCliDaemonArgv(argv) {if (argv.length < 2 || !argv.includes("daemon"))return false;- const executable = basename7(argv[0] ?? "");+ const executable = basename8(argv[0] ?? "");if (!/^node(?:\.exe)?$/i.test(executable))return false;return argv.some((value) => value === "cli.js" || value.endsWith("/cli.js") || value.endsWith("\\cli.js"));}function lsofShowsUnixEndpoint(output, pid, endpoint) {const lines = output.split(/\r?\n/).filter((line) => line.length > 0);- const endpointName = basename7(endpoint);+ const endpointName = basename8(endpoint);return lines.includes(`p${pid}`) && lines.some((line) => line === `n${endpoint}` || line === `n${endpointName}`);}function isNodeCliDaemonCommand(command) {@@ -96507,7 +96810,7 @@ async function readBinary(readFileImpl, path) {var LEGACY_EXIT_WAIT_TIMEOUT_MS = 5000;var LEGACY_VERSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;async function reapLspDaemons(codexHome, deps = {}) {- const daemonRoot = join46(codexHome, "codex-lsp", "daemon");+ const daemonRoot = join47(codexHome, "codex-lsp", "daemon");const platform = deps.platform ?? process.platform;const tmpDir = deps.tmpDir ?? tmpdir3();const probe = deps.probeLegacyJsonRpc ?? probeLegacyJsonRpcEndpoint;@@ -96517,7 +96820,7 @@ async function reapLspDaemons(codexHome, deps = {}) {const entries = await readdir10(daemonRoot, { withFileTypes: true }).catch(() => []);const results = [];for (const entry of [...entries].sort((left, right) => left.name.localeCompare(right.name))) {- const versionPath = join46(daemonRoot, entry.name);+ const versionPath = join47(daemonRoot, entry.name);const parsedVersion = parseVersionEntry(entry.name);if (parsedVersion === null || !entry.isDirectory()) {await removeVersionDir(versionPath);@@ -96565,7 +96868,7 @@ function parseVersionEntry(entryName) {return LEGACY_VERSION_PATTERN.test(version) ? version : null;}async function readLegacyMetadata(input) {- const pidText = await readRegularTrimmedFile(join46(input.versionPath, "daemon.pid"));+ const pidText = await readRegularTrimmedFile(join47(input.versionPath, "daemon.pid"));if (pidText === "non_regular")return { kind: "remove", reason: "removed non-regular legacy daemon metadata" };if (pidText === null)@@ -96573,7 +96876,7 @@ async function readLegacyMetadata(input) {const pid = Number.parseInt(pidText, 10);if (!Number.isInteger(pid) || pid <= 0)return { kind: "remove", reason: "removed malformed legacy daemon metadata" };- const endpointText = await readRegularTrimmedFile(join46(input.versionPath, "daemon.endpoint"));+ const endpointText = await readRegularTrimmedFile(join47(input.versionPath, "daemon.endpoint"));if (endpointText === "non_regular")return { kind: "remove", reason: "removed non-regular legacy daemon metadata" };if (endpointText === null)@@ -96652,25 +96955,25 @@ function processIsRunning(pid) {// packages/omo-codex/src/install/codex-installer-bin-dir.tsimport { homedir as homedir5 } from "node:os";-import { join as join47, resolve as resolve11 } from "node:path";+import { join as join48, resolve as resolve12 } from "node:path";function resolveCodexInstallerBinDir(input) {const explicitBinDir = input.binDir ?? input.env?.CODEX_LOCAL_BIN_DIR;if (explicitBinDir !== undefined && explicitBinDir.trim().length > 0)- return resolve11(explicitBinDir.trim());+ return resolve12(explicitBinDir.trim());const homeDir = input.homeDir ?? homedir5();- const defaultCodexHome = resolve11(homeDir, ".codex");- const resolvedCodexHome = resolve11(input.codexHome);+ const defaultCodexHome = resolve12(homeDir, ".codex");+ const resolvedCodexHome = resolve12(input.codexHome);if (resolvedCodexHome !== defaultCodexHome)- return join47(resolvedCodexHome, "bin");- return resolve11(homeDir, ".local", "bin");+ return join48(resolvedCodexHome, "bin");+ return resolve12(homeDir, ".local", "bin");}// packages/omo-codex/src/install/codex-installed-bin-dir.tsimport { readFile as readFile21, readdir as readdir11, writeFile as writeFile11 } from "node:fs/promises";-import { join as join48 } from "node:path";+import { join as join49 } from "node:path";var INSTALLED_BIN_DIR_MANIFEST = ".installed-bin-dir.json";async function writeInstalledCodexBinDir(input) {- await writeFile11(join48(input.pluginRoot, INSTALLED_BIN_DIR_MANIFEST), `${JSON.stringify({ binDir: input.binDir }, null, 2)}+ await writeFile11(join49(input.pluginRoot, INSTALLED_BIN_DIR_MANIFEST), `${JSON.stringify({ binDir: input.binDir }, null, 2)}`);}async function readInstalledCodexBinDir(codexHome) {@@ -96683,14 +96986,14 @@ async function readInstalledCodexBinDir(codexHome) {}async function installedBinDirManifestPaths(codexHome) {const paths = [- join48(codexHome, ".tmp", "marketplaces", "sisyphuslabs", "plugins", "omo", INSTALLED_BIN_DIR_MANIFEST)+ join49(codexHome, ".tmp", "marketplaces", "sisyphuslabs", "plugins", "omo", INSTALLED_BIN_DIR_MANIFEST)];- const versionRoot = join48(codexHome, "plugins", "cache", "sisyphuslabs", "omo");+ const versionRoot = join49(codexHome, "plugins", "cache", "sisyphuslabs", "omo");const entries = await readdir11(versionRoot, { withFileTypes: true }).catch(() => null);if (entries !== null) {for (const entry of entries) {if (entry.isDirectory())- paths.push(join48(versionRoot, entry.name, INSTALLED_BIN_DIR_MANIFEST));+ paths.push(join49(versionRoot, entry.name, INSTALLED_BIN_DIR_MANIFEST));}}return paths;@@ -96715,7 +97018,7 @@ async function readBinDirFromManifest(manifestPath) {// packages/omo-codex/src/install/codex-git-bash-hooks.tsimport { readFile as readFile22, writeFile as writeFile12 } from "node:fs/promises";-import { join as join49 } from "node:path";+import { join as join50 } from "node:path";var WINDOWS_ONLY_GIT_BASH_HOOKS = new Set(["./hooks/pre-tool-use-recommending-git-bash-mcp.json","./hooks/post-compact-resetting-git-bash-mcp-reminder.json"@@ -96723,7 +97026,7 @@ var WINDOWS_ONLY_GIT_BASH_HOOKS = new Set([async function removeGitBashHooksOffWindows(input) {if (input.platform === "win32")return;- const manifestPath = join49(input.pluginRoot, ".codex-plugin", "plugin.json");+ const manifestPath = join50(input.pluginRoot, ".codex-plugin", "plugin.json");const parsed = JSON.parse(await readFile22(manifestPath, "utf8"));if (!isPlainRecord4(parsed) || !Array.isArray(parsed.hooks))return;@@ -96736,7 +97039,7 @@ async function removeGitBashHooksOffWindows(input) {// packages/omo-codex/src/install/install-ast-grep-sg.tsinit_src();-import { join as join50 } from "node:path";+import { join as join51 } from "node:path";function describeResult(result) {if (result.kind === "succeeded")return null;@@ -96750,7 +97053,7 @@ async function installAstGrepForCodex(options) {return;const platform = options.platform ?? process.platform;const targetDir = astGrepRuntimeDir(options.codexHome, platform, options.arch ?? process.arch);- const skillDir = join50(plugin.path, "skills", "ast-grep");+ const skillDir = join51(plugin.path, "skills", "ast-grep");const installer = options.installer ?? runAstGrepSkillInstall;try {const result = await installer({ platform, skillDir, targetDir });@@ -96782,9 +97085,9 @@ var SISYPHUS_LEGACY_CACHE_MARKETPLACES = ["lazycodex", "code-yeongyu-codex-plugiasync function runCodexInstaller(options = {}) {const env = options.env ?? process.env;const platform = options.platform ?? process.platform;- const repoRoot = resolve12(options.repoRoot ?? findRepoRoot({ importerDir: import.meta.dir, env }));- const codexHome = resolve12(options.codexHome ?? env.CODEX_HOME ?? join54(homedir6(), ".codex"));- const projectDirectory = resolve12(options.projectDirectory ?? env.OMO_CODEX_PROJECT ?? process.cwd());+ const repoRoot = resolve13(options.repoRoot ?? findRepoRoot({ importerDir: import.meta.dir, env }));+ const codexHome = resolve13(options.codexHome ?? env.CODEX_HOME ?? join55(homedir6(), ".codex"));+ const projectDirectory = resolve13(options.projectDirectory ?? env.OMO_CODEX_PROJECT ?? process.cwd());const binDir = resolveCodexInstallerBinDir({ binDir: options.binDir, codexHome, env });const runCommand = options.runCommand ?? defaultRunCommand;const log = options.log ?? (() => {@@ -96800,9 +97103,9 @@ async function runCodexInstaller(options = {}) {if (!gitBashResolution.found) {throw new Error(gitBashResolution.installHint);}- const codexPackageRoot = join54(repoRoot, "packages", "omo-codex");+ const codexPackageRoot = join55(repoRoot, "packages", "omo-codex");const marketplace = await readMarketplace(repoRoot, {- marketplacePath: join54(codexPackageRoot, "marketplace.json")+ marketplacePath: join55(codexPackageRoot, "marketplace.json")});const distributionManifest = await readDistributionManifest(repoRoot);const installed = [];@@ -96848,7 +97151,7 @@ async function runCodexInstaller(options = {}) {if (runtimeLink !== null)log(`Linked ${runtimeLink.name} -> ${runtimeLink.target}`);else- log(`Warning: skipped the omo-agent-toolkit runtime wrapper because ${join54(repoRoot, "dist", "cli", "index.js")} is missing; omo-agent-toolkit ulw-loop commands will be unavailable until a package shipping dist/cli is installed`);+ log(`Warning: skipped the omo-agent-toolkit runtime wrapper because ${join55(repoRoot, "dist", "cli", "index.js")} is missing; omo-agent-toolkit ulw-loop commands will be unavailable until a package shipping dist/cli is installed`);}pluginSources.push({ name: entry.name, sourcePath });installed.push(plugin);@@ -96915,13 +97218,13 @@ async function runCodexInstaller(options = {}) {continue;log(`Warning: deferred legacy Codex LSP daemon cleanup for v${cleanup.version}: ${cleanup.reason}`);}- const marketplaceRoot = join54(codexHome, "plugins", "cache", marketplace.name);+ const marketplaceRoot = join55(codexHome, "plugins", "cache", marketplace.name);await writeCachedMarketplaceManifest({marketplaceName: marketplace.name,marketplaceRoot,plugins: installed});- const configPath = join54(codexHome, "config.toml");+ const configPath = join55(codexHome, "config.toml");await updateCodexConfig({configPath,repoRoot: codexPackageRoot,@@ -96980,25 +97283,25 @@ function findRepoRootFromImporter(importerDir) {for (let depth = 0;depth <= 7; depth += 1) {if (isRepoRootWithCodexPlugin(current))return current;- for (const wrapperPackageRoot of [join54(current, "node_modules", "oh-my-openagent"), join54(current, "oh-my-openagent")]) {+ for (const wrapperPackageRoot of [join55(current, "node_modules", "oh-my-openagent"), join55(current, "oh-my-openagent")]) {if (isRepoRootWithCodexPlugin(wrapperPackageRoot))return wrapperPackageRoot;}- current = resolve12(current, "..");+ current = resolve13(current, "..");}throw new Error("Unable to locate vendored Codex plugin: expected packages/omo-codex/plugin/.codex-plugin/plugin.json in this package or sibling oh-my-openagent package within 7 parent levels");}function findRepoRoot(input) {const wrapperPackageRoot = input.env?.OMO_WRAPPER_PACKAGE_ROOT;if (wrapperPackageRoot !== undefined && wrapperPackageRoot.trim().length > 0) {- const resolvedWrapperPackageRoot = resolve12(wrapperPackageRoot);+ const resolvedWrapperPackageRoot = resolve13(wrapperPackageRoot);if (isRepoRootWithCodexPlugin(resolvedWrapperPackageRoot))return resolvedWrapperPackageRoot;}return findRepoRootFromImporter(input.importerDir);}function isRepoRootWithCodexPlugin(repoRoot) {- return existsSync26(join54(repoRoot, "packages", "omo-codex", "plugin", ".codex-plugin", "plugin.json"));+ return existsSync27(join55(repoRoot, "packages", "omo-codex", "plugin", ".codex-plugin", "plugin.json"));}function codexMarketplaceSource(marketplaceRoot) {return { sourceType: "local", source: marketplaceRoot };@@ -97006,7 +97309,7 @@ function codexMarketplaceSource(marketplaceRoot) {// packages/omo-codex/src/install/codex-installation-detection.tsinit_bun_which_shim();import { execFile as execFile2 } from "node:child_process";-import { existsSync as existsSync27 } from "node:fs";+import { existsSync as existsSync28 } from "node:fs";import { homedir as homedir7 } from "node:os";import { posix as posix8, win32 as win324 } from "node:path";var CODEX_PATH_CHECK_LABEL = "codex (PATH)";@@ -97019,7 +97322,7 @@ async function detectCodexInstallation(input = {}) {const platform = input.platform ?? process.platform;const env = input.env ?? process.env;const homeDir = input.homeDir ?? homedir7();- const exists = input.exists ?? existsSync27;+ const exists = input.exists ?? existsSync28;const which = input.which ?? bunWhich;const checkedPaths = [CODEX_PATH_CHECK_LABEL];const cliPath = nonEmptyValue2(which("codex"));@@ -97135,11 +97438,11 @@ function defaultRunCommand2(command, args) {// packages/omo-codex/src/install/codex-cleanup.tsimport { lstat as lstat15, readFile as readFile25, readdir as readdir13, rm as rm13, rmdir } from "node:fs/promises";import { homedir as homedir8 } from "node:os";-import { isAbsolute as isAbsolute11, join as join57, relative as relative6, resolve as resolve15 } from "node:path";+import { isAbsolute as isAbsolute11, join as join58, relative as relative6, resolve as resolve16 } from "node:path";// packages/omo-codex/src/install/codex-cleanup-bins.tsimport { lstat as lstat13, readFile as readFile23, readdir as readdir12, readlink as readlink6, rm as rm12 } from "node:fs/promises";-import { dirname as dirname18, isAbsolute as isAbsolute9, join as join55, resolve as resolve13 } from "node:path";+import { dirname as dirname19, isAbsolute as isAbsolute9, join as join56, resolve as resolve14 } from "node:path";var ROOT_RUNTIME_BIN_NAME = "omo";var MANAGED_CODEX_BIN_NAMES = new Set([ROOT_RUNTIME_BIN_NAME,@@ -97169,7 +97472,7 @@ async function removeManagedCodexBins(binDir, platform) {const binName = managedBinNameForEntry2(entry.name, platform);if (binName === null || !MANAGED_CODEX_BIN_NAMES.has(binName))continue;- const linkPath = join55(binDir, entry.name);+ const linkPath = join56(binDir, entry.name);if (await isManagedCodexBin(linkPath, platform, binName)) {await rm12(linkPath, { force: true });removed.push(linkPath);@@ -97195,7 +97498,7 @@ async function isManagedCodexBin(linkPath, platform, binName) {if (platform === "win32")return false;const linkTarget = await readlink6(linkPath);- const target = isAbsolute9(linkTarget) ? linkTarget : resolve13(dirname18(linkPath), linkTarget);+ const target = isAbsolute9(linkTarget) ? linkTarget : resolve14(dirname19(linkPath), linkTarget);return isManagedComponentBinTarget(target) || isLegacyCodexBinTarget(binName, target);}if (!entryStat.isFile())@@ -97206,7 +97509,7 @@ async function isManagedCodexBin(linkPath, platform, binName) {// packages/omo-codex/src/install/codex-cleanup-config.tsimport { lstat as lstat14, mkdir as mkdir8, readFile as readFile24, writeFile as writeFile13 } from "node:fs/promises";-import { dirname as dirname19 } from "node:path";+import { dirname as dirname20 } from "node:path";var MANAGED_MARKETPLACES = ["sisyphuslabs", "lazycodex", "code-yeongyu-codex-plugins"];var LEGACY_MANAGED_CODEX_AGENT_NAMES_TO_PURGE2 = ["codex-ultrawork-reviewer"];var CURRENT_MANAGED_CODEX_AGENT_NAMES2 = [@@ -97243,7 +97546,7 @@ async function cleanupCodexConfig(configPath, now) {if (next === original)return { changed: false };const backupPath = `${configPath}.backup-${formatBackupTimestamp2(now?.() ?? new Date)}`;- await mkdir8(dirname19(configPath), { recursive: true });+ await mkdir8(dirname20(configPath), { recursive: true });await writeFile13(backupPath, original);await writeFile13(configPath, `${next.trimEnd()}`);@@ -97322,28 +97625,28 @@ function nodeErrorCode5(error) {}// packages/omo-codex/src/install/codex-cleanup-safety.ts-import { dirname as dirname20, isAbsolute as isAbsolute10, join as join56, relative as relative5, resolve as resolve14 } from "node:path";+import { dirname as dirname21, isAbsolute as isAbsolute10, join as join57, relative as relative5, resolve as resolve15 } from "node:path";function codexHomeResolvesToFilesystemRoot(codexHome) {- const resolved = resolve14(codexHome);- return dirname20(resolved) === resolved;+ const resolved = resolve15(codexHome);+ return dirname21(resolved) === resolved;}function validateManagedCleanupTarget(input) {if (!isAbsolute10(input.path))return skipped(input.path, "outside managed Codex cleanup scope");- const codexHome = resolve14(input.codexHome);+ const codexHome = resolve15(input.codexHome);if (codexHomeResolvesToFilesystemRoot(codexHome))return skipped(input.path, "Codex home resolves to a filesystem root");- const target = resolve14(input.path);+ const target = resolve15(input.path);if (!isWithinDirectory(codexHome, target))return skipped(input.path, "outside managed Codex cleanup scope");if (target === codexHome)return skipped(input.path, "outside managed Codex cleanup scope");const exactManagedRoots = new Set([- resolve14(join56(codexHome, "plugins", "cache", "sisyphuslabs")),- resolve14(join56(codexHome, ".tmp", "marketplaces", "sisyphuslabs")),- resolve14(join56(codexHome, "runtime", "ast-grep")),- resolve14(join56(codexHome, "runtime", "node")),- resolve14(join56(codexHome, "plugins", "data", "omo-sisyphuslabs", "bootstrap"))+ resolve15(join57(codexHome, "plugins", "cache", "sisyphuslabs")),+ resolve15(join57(codexHome, ".tmp", "marketplaces", "sisyphuslabs")),+ resolve15(join57(codexHome, "runtime", "ast-grep")),+ resolve15(join57(codexHome, "runtime", "node")),+ resolve15(join57(codexHome, "plugins", "data", "omo-sisyphuslabs", "bootstrap"))]);if (exactManagedRoots.has(target))return null;@@ -97373,8 +97676,8 @@ function skipped(path, reason) {var INSTALLED_AGENTS_MANIFEST = ".installed-agents.json";async function cleanupCodexLight(input = {}) {const env = input.env ?? process.env;- const codexHome = resolve15(input.codexHome ?? env.CODEX_HOME ?? join57(homedir8(), ".codex"));- const configPath = join57(codexHome, "config.toml");+ const codexHome = resolve16(input.codexHome ?? env.CODEX_HOME ?? join58(homedir8(), ".codex"));+ const configPath = join58(codexHome, "config.toml");const installedBinDir = await readInstalledCodexBinDir(codexHome);const agentPaths = await collectInstalledAgentPaths(codexHome, configPath);const configCleanup = await cleanupCodexConfig(configPath, input.now);@@ -97428,17 +97731,17 @@ function firstConfiguredPath(...values) {}function managedGlobalStatePaths(codexHome) {return [- join57(codexHome, "plugins", "cache", "sisyphuslabs"),- join57(codexHome, ".tmp", "marketplaces", "sisyphuslabs"),- join57(codexHome, "runtime", "ast-grep"),- join57(codexHome, "runtime", "node"),- join57(codexHome, "plugins", "data", "omo-sisyphuslabs", "bootstrap")+ join58(codexHome, "plugins", "cache", "sisyphuslabs"),+ join58(codexHome, ".tmp", "marketplaces", "sisyphuslabs"),+ join58(codexHome, "runtime", "ast-grep"),+ join58(codexHome, "runtime", "node"),+ join58(codexHome, "plugins", "data", "omo-sisyphuslabs", "bootstrap")];}var BOOTSTRAP_DATA_GLOB_MAX_DEPTH = 5;async function collectBootstrapDataDirsByGlob(codexHome) {const results = [];- await walkForManagedBootstrapDirs(join57(codexHome, "plugins"), 0, results);+ await walkForManagedBootstrapDirs(join58(codexHome, "plugins"), 0, results);return results;}async function walkForManagedBootstrapDirs(directory, depth, results) {@@ -97450,9 +97753,9 @@ async function walkForManagedBootstrapDirs(directory, depth, results) {for (const entry of entries) {if (!entry.isDirectory())continue;- const childPath = join57(directory, entry.name);+ const childPath = join58(directory, entry.name);if (isManagedBootstrapOwnerName(entry.name)) {- const bootstrapDir = join57(childPath, "bootstrap");+ const bootstrapDir = join58(childPath, "bootstrap");if (await exists6(bootstrapDir))results.push(bootstrapDir);continue;@@ -97486,7 +97789,7 @@ async function attemptRemove(path) {}async function pruneEmptyRuntimeDirBestEffort(codexHome) {try {- await rmdir(join57(codexHome, "runtime"));+ await rmdir(join58(codexHome, "runtime"));} catch (error) {if (isExpectedRuntimePruneFailure(error))return;@@ -97498,14 +97801,14 @@ function isExpectedRuntimePruneFailure(error) {}async function collectInstalledAgentPaths(codexHome, configPath) {const manifestPaths = [- join57(codexHome, ".tmp", "marketplaces", "sisyphuslabs", "plugins", "omo", INSTALLED_AGENTS_MANIFEST)+ join58(codexHome, ".tmp", "marketplaces", "sisyphuslabs", "plugins", "omo", INSTALLED_AGENTS_MANIFEST)];- const versionRoot = join57(codexHome, "plugins", "cache", "sisyphuslabs", "omo");+ const versionRoot = join58(codexHome, "plugins", "cache", "sisyphuslabs", "omo");if (await exists6(versionRoot)) {const entries = await readdir13(versionRoot, { withFileTypes: true });for (const entry of entries) {if (entry.isDirectory())- manifestPaths.push(join57(versionRoot, entry.name, INSTALLED_AGENTS_MANIFEST));+ manifestPaths.push(join58(versionRoot, entry.name, INSTALLED_AGENTS_MANIFEST));}}const paths = new Set;@@ -97523,7 +97826,7 @@ async function readManagedAgentPathsFromConfig(codexHome, configPath) {if (!await exists6(configPath))return [];const config = await readFile25(configPath, "utf8");- return MANAGED_CODEX_AGENT_NAMES2.filter((agentName) => config.includes(`config_file = ${JSON.stringify(`./agents/${agentName}.toml`)}`)).map((agentName) => join57(codexHome, "agents", `${agentName}.toml`));+ return MANAGED_CODEX_AGENT_NAMES2.filter((agentName) => config.includes(`config_file = ${JSON.stringify(`./agents/${agentName}.toml`)}`)).map((agentName) => join58(codexHome, "agents", `${agentName}.toml`));}async function readInstalledAgentManifest(manifestPath) {if (!await exists6(manifestPath))@@ -97534,7 +97837,7 @@ async function readInstalledAgentManifest(manifestPath) {return parsed.agents.filter((path) => typeof path === "string");}async function removeManifestListedAgentLinks(codexHome, paths) {- const agentsDir = join57(codexHome, "agents");+ const agentsDir = join58(codexHome, "agents");const removed = [];const skipped = [];for (const path of paths) {@@ -97584,16 +97887,16 @@ function nodeErrorCode6(error) {}// packages/omo-senpi/src/install/install-senpi.tsimport { execFile as execFile3 } from "node:child_process";-import { existsSync as existsSync30 } from "node:fs";+import { existsSync as existsSync31 } from "node:fs";import { homedir as homedir11 } from "node:os";-import { dirname as dirname24, join as join62, resolve as resolve19 } from "node:path";+import { dirname as dirname25, join as join63, resolve as resolve20 } from "node:path";import { fileURLToPath } from "node:url";import { promisify as promisify2 } from "node:util";// packages/omo-senpi/src/components/agent-home/resolve-agent-home.ts-import { existsSync as existsSync28 } from "node:fs";+import { existsSync as existsSync29 } from "node:fs";import { homedir as homedir9 } from "node:os";-import { join as join58, resolve as resolve16 } from "node:path";+import { join as join59, resolve as resolve17 } from "node:path";var AGENT_DIR_ENV_NAMES = ["OMO_CODING_AGENT_DIR","SENPI_CODING_AGENT_DIR",@@ -97601,31 +97904,31 @@ var AGENT_DIR_ENV_NAMES = [];var AGENT_HOME_SENTINEL = "settings.json";function resolveAgentHome(options) {- const { env, homeDir = homedir9(), exists = existsSync28 } = options;+ const { env, homeDir = homedir9(), exists = existsSync29 } = options;for (const name of AGENT_DIR_ENV_NAMES) {const configured = env[name]?.trim();if (configured)- return resolve16(configured);+ return resolve17(configured);}- const brandedHome = join58(homeDir, ".omo");- const canonical = join58(brandedHome, "agent");- if (exists(join58(canonical, AGENT_HOME_SENTINEL)))+ const brandedHome = join59(homeDir, ".omo");+ const canonical = join59(brandedHome, "agent");+ if (exists(join59(canonical, AGENT_HOME_SENTINEL)))return canonical;- if (exists(join58(brandedHome, AGENT_HOME_SENTINEL)))+ if (exists(join59(brandedHome, AGENT_HOME_SENTINEL)))return brandedHome;- return join58(homeDir, ".senpi", "agent");+ return join59(homeDir, ".senpi", "agent");}// packages/omo-senpi/src/install/local-launcher.ts-import { chmodSync as chmodSync3, existsSync as existsSync29, mkdirSync as mkdirSync11, readFileSync as readFileSync13, rmSync as rmSync3, writeFileSync as writeFileSync6 } from "node:fs";+import { chmodSync as chmodSync3, existsSync as existsSync30, mkdirSync as mkdirSync12, readFileSync as readFileSync14, rmSync as rmSync4, writeFileSync as writeFileSync7 } from "node:fs";import { homedir as homedir10 } from "node:os";-import { dirname as dirname21, join as join59, resolve as resolve17 } from "node:path";+import { dirname as dirname22, join as join60, resolve as resolve18 } from "node:path";var MARKER = "omo-local-launcher";function localLauncherPath(homeDir = homedir10()) {- return join59(homeDir, ".local", "bin", "omo");+ return join60(homeDir, ".local", "bin", "omo");}function localLauncherCmdPath(homeDir = homedir10()) {- return join59(homeDir, ".local", "bin", "omo.cmd");+ return join60(homeDir, ".local", "bin", "omo.cmd");}function renderLocalLauncher(options) {const brand = {@@ -97638,7 +97941,7 @@ function renderLocalLauncher(options) {userAgent: "omo",originator: "omo",changelog: {- path: join59(options.pluginPath, "CHANGELOG.md").replaceAll("\\", "/")+ path: join60(options.pluginPath, "CHANGELOG.md").replaceAll("\\", "/")},update: {packageName: "omo-ai",@@ -97694,13 +97997,13 @@ child.on("close", (code, signal) => {}function installLocalLauncher(options) {const path = localLauncherPath(options.homeDir);- if (existsSync29(path) && !readFileSync13(path, "utf8").includes(MARKER))+ if (existsSync30(path) && !readFileSync14(path, "utf8").includes(MARKER))return;- mkdirSync11(dirname21(path), { recursive: true });- writeFileSync6(path, renderLocalLauncher(options));+ mkdirSync12(dirname22(path), { recursive: true });+ writeFileSync7(path, renderLocalLauncher(options));chmodSync3(path, 493);if ((options.platform ?? process.platform) === "win32") {- writeFileSync6(localLauncherCmdPath(options.homeDir), `@echo off\r+ writeFileSync7(localLauncherCmdPath(options.homeDir), `@echo off\rnode "%~dp0omo" %*\r`);}@@ -97711,7 +98014,7 @@ node "%~dp0omo" %*\rimport { createHash as createHash6 } from "node:crypto";import { constants as constants9 } from "node:fs";import { access as access2, readFile as readFile27, stat as stat6 } from "node:fs/promises";-import { dirname as dirname23, join as join61 } from "node:path";+import { dirname as dirname24, join as join62 } from "node:path";// packages/memory-core/src/personas/manifest.tsvar PERSONA_ASSET_FILENAMES = {@@ -97730,12 +98033,12 @@ var PERSONA_ASSET_FILES = [// packages/omo-senpi/src/install/senpi-settings.tsimport { constants as constants8 } from "node:fs";import { access, copyFile as copyFile3, mkdir as mkdir9, readFile as readFile26, rename as rename5, writeFile as writeFile14 } from "node:fs/promises";-import { basename as basename9, dirname as dirname22, join as join60, resolve as resolve18 } from "node:path";+import { basename as basename10, dirname as dirname23, join as join61, resolve as resolve19 } from "node:path";var OMO_SENPI_PACKAGE_NAME = "@code-yeongyu/omo-senpi";var GENERATED_PLUGIN_BASENAME = /^omo-senpi-cli-plugin-[A-Za-z0-9]{6}$/;var LEGACY_BUILTIN_SHADOW_PACKAGES = [- join60("packages", "pi-goal"),- join60("packages", "pi-webfetch")+ join61("packages", "pi-goal"),+ join61("packages", "pi-webfetch")];async function readSettings(settingsPath) {let raw;@@ -97764,25 +98067,25 @@ function dedupePackages(packages) {return [...new Set(packages)];}function removeLegacyBuiltinShadows(packages, repoRoot, agentDir) {- const shadowPaths = new Set(LEGACY_BUILTIN_SHADOW_PACKAGES.map((path) => resolve18(repoRoot, path)));- return packages.filter((entry) => !shadowPaths.has(resolve18(agentDir, entry)));+ const shadowPaths = new Set(LEGACY_BUILTIN_SHADOW_PACKAGES.map((path) => resolve19(repoRoot, path)));+ return packages.filter((entry) => !shadowPaths.has(resolve19(agentDir, entry)));}async function removeSupersededOmoPackages(packages, currentPluginPath, agentDir) {- const currentPath = resolve18(currentPluginPath);+ const currentPath = resolve19(currentPluginPath);const entries = await Promise.all(packages.map(async (entry) => {- const packagePath = resolve18(agentDir, entry);+ const packagePath = resolve19(agentDir, entry);if (packagePath === currentPath)return currentPath;if (await readPackageName(packagePath) === OMO_SENPI_PACKAGE_NAME)return;- if (GENERATED_PLUGIN_BASENAME.test(basename9(entry)) && !await fileExists(packagePath))+ if (GENERATED_PLUGIN_BASENAME.test(basename10(entry)) && !await fileExists(packagePath))return;return entry;}));return entries.filter((entry) => entry !== undefined);}async function writeSettingsAtomically(settingsPath, settings) {- await mkdir9(dirname22(settingsPath), { recursive: true });+ await mkdir9(dirname23(settingsPath), { recursive: true });const backupPath = await nextBackupPath(settingsPath);if (await fileExists(settingsPath)) {await copyFile3(settingsPath, backupPath);@@ -97814,7 +98117,7 @@ function isRecord15(value) {async function readPackageName(packagePath) {let raw;try {- raw = await readFile26(join60(packagePath, "package.json"), "utf8");+ raw = await readFile26(join61(packagePath, "package.json"), "utf8");} catch (error) {if (isErrno(error, "ENOENT") || isErrno(error, "ENOTDIR"))return;@@ -97846,52 +98149,52 @@ function isErrno(error, code) {// packages/omo-senpi/src/install/plugin-artifacts.tsvar REQUIRED_PLUGIN_ARTIFACTS = [- join61("extensions", "omo.js"),- join61("extensions", "omo-task.js"),- join61("extensions", "omo-member.js"),- join61("extensions", "memory-run-supervisor.mjs"),- ...PERSONA_ASSET_FILES.map((filename) => join61("extensions", filename)),- join61("skills", "ast-grep", "SKILL.md"),- join61("skills", "browser", "SKILL.md"),- join61("skills", "coding-agent-sessions", "SKILL.md"),- join61("skills", "debugging", "SKILL.md"),- join61("skills", "frontend", "SKILL.md"),- join61("skills", "git-master", "SKILL.md"),- join61("skills", "init-deep", "SKILL.md"),- join61("skills", "lsp-setup", "SKILL.md"),- join61("skills", "programming", "SKILL.md"),- join61("skills", "refactor", "SKILL.md"),- join61("skills", "remove-ai-slops", "SKILL.md"),- join61("skills", "review-work", "SKILL.md"),- join61("skills", "ultimate-browsing", "SKILL.md"),- join61("skills", "ultrawork", "SKILL.md"),- join61("skills", "ulw-execute", "SKILL.md"),- join61("skills", "ulw-loop", "SKILL.md"),- join61("skills", "ulw-plan", "SKILL.md"),- join61("skills", "ulw-research", "SKILL.md"),- join61("skills", "visual-qa", "SKILL.md"),- join61("skills-conditional", "x-search", "SKILL.md"),- join61("runtime", "agent-toolkit-sdk", "sdk.js"),- join61("runtime", "ast-grep-mcp", "cli.js"),- join61("runtime", "lsp-daemon", "dist", "cli.js"),- join61("runtime", "lsp-daemon", "dist", "index.js"),- join61("runtime", "lsp-daemon", "dist", "index.d.ts"),- join61("runtime", "lsp-daemon", "dist", "daemon-client.js"),- join61("runtime", "lsp-daemon", "dist", "daemon-client.d.ts"),- join61("runtime", "lsp-daemon", "dist", "package.json"),- join61("runtime", "lsp-daemon", "dist", ".omo-runtime-manifest.json"),- join61("scripts", "install.mjs"),+ join62("extensions", "omo.js"),+ join62("extensions", "omo-task.js"),+ join62("extensions", "omo-member.js"),+ join62("extensions", "memory-run-supervisor.mjs"),+ ...PERSONA_ASSET_FILES.map((filename) => join62("extensions", filename)),+ join62("skills", "ast-grep", "SKILL.md"),+ join62("skills", "browser", "SKILL.md"),+ join62("skills", "coding-agent-sessions", "SKILL.md"),+ join62("skills", "debugging", "SKILL.md"),+ join62("skills", "frontend", "SKILL.md"),+ join62("skills", "git-master", "SKILL.md"),+ join62("skills", "init-deep", "SKILL.md"),+ join62("skills", "lsp-setup", "SKILL.md"),+ join62("skills", "programming", "SKILL.md"),+ join62("skills", "refactor", "SKILL.md"),+ join62("skills", "remove-ai-slops", "SKILL.md"),+ join62("skills", "review-work", "SKILL.md"),+ join62("skills", "ultimate-browsing", "SKILL.md"),+ join62("skills", "ultrawork", "SKILL.md"),+ join62("skills", "ulw-execute", "SKILL.md"),+ join62("skills", "ulw-loop", "SKILL.md"),+ join62("skills", "ulw-plan", "SKILL.md"),+ join62("skills", "ulw-research", "SKILL.md"),+ join62("skills", "visual-qa", "SKILL.md"),+ join62("skills-conditional", "x-search", "SKILL.md"),+ join62("runtime", "agent-toolkit-sdk", "sdk.js"),+ join62("runtime", "ast-grep-mcp", "cli.js"),+ join62("runtime", "lsp-daemon", "dist", "cli.js"),+ join62("runtime", "lsp-daemon", "dist", "index.js"),+ join62("runtime", "lsp-daemon", "dist", "index.d.ts"),+ join62("runtime", "lsp-daemon", "dist", "daemon-client.js"),+ join62("runtime", "lsp-daemon", "dist", "daemon-client.d.ts"),+ join62("runtime", "lsp-daemon", "dist", "package.json"),+ join62("runtime", "lsp-daemon", "dist", ".omo-runtime-manifest.json"),+ join62("scripts", "install.mjs"),"daemon-launch-spec.json"];async function ensurePluginArtifacts(context) {if (context.allowBuild) {- await context.runCommand("node", [join61(context.pluginPath, "scripts", "build-extension.mjs")], { cwd: context.repoRoot });- await context.runCommand("node", [join61("packages", "omo-codex", "plugin", "scripts", "materialize-shared-upstreams.mjs")], { cwd: context.repoRoot });- await context.runCommand("node", [join61(context.pluginPath, "scripts", "sync-skills.mjs")], { cwd: context.repoRoot });- await context.runCommand("node", [join61(context.pluginPath, "scripts", "build-install.mjs")], { cwd: context.repoRoot });- await context.runCommand("node", [join61(context.pluginPath, "scripts", "stage-lsp-daemon-runtime.mjs")], { cwd: context.repoRoot });- await context.runCommand("node", [join61(context.pluginPath, "scripts", "stage-ast-grep-mcp-runtime.mjs")], { cwd: context.repoRoot });- await context.runCommand("node", [join61(context.pluginPath, "scripts", "stage-x-search-skill.mjs")], { cwd: context.repoRoot });+ await context.runCommand("node", [join62(context.pluginPath, "scripts", "build-extension.mjs")], { cwd: context.repoRoot });+ await context.runCommand("node", [join62("packages", "omo-codex", "plugin", "scripts", "materialize-shared-upstreams.mjs")], { cwd: context.repoRoot });+ await context.runCommand("node", [join62(context.pluginPath, "scripts", "sync-skills.mjs")], { cwd: context.repoRoot });+ await context.runCommand("node", [join62(context.pluginPath, "scripts", "build-install.mjs")], { cwd: context.repoRoot });+ await context.runCommand("node", [join62(context.pluginPath, "scripts", "stage-lsp-daemon-runtime.mjs")], { cwd: context.repoRoot });+ await context.runCommand("node", [join62(context.pluginPath, "scripts", "stage-ast-grep-mcp-runtime.mjs")], { cwd: context.repoRoot });+ await context.runCommand("node", [join62(context.pluginPath, "scripts", "stage-x-search-skill.mjs")], { cwd: context.repoRoot });}if (await hasMissingPluginArtifact(context.pluginPath)) {throw new Error(`Packed omo-senpi plugin is missing required runtime artifacts at ${context.pluginPath}`);@@ -97900,14 +98203,14 @@ async function ensurePluginArtifacts(context) {}async function hasMissingPluginArtifact(pluginPath) {for (const artifact of REQUIRED_PLUGIN_ARTIFACTS) {- if (!await fileExists2(join61(pluginPath, artifact)))+ if (!await fileExists2(join62(pluginPath, artifact)))return true;}return false;}async function verifyAstGrepRuntimeIntegrity(pluginPath, platform) {- const runtimeEntry = join61(pluginPath, "runtime", "ast-grep-mcp", "cli.js");- const manifestPath = join61(dirname23(runtimeEntry), "manifest.json");+ const runtimeEntry = join62(pluginPath, "runtime", "ast-grep-mcp", "cli.js");+ const manifestPath = join62(dirname24(runtimeEntry), "manifest.json");let runtimeStat;try {runtimeStat = await stat6(runtimeEntry);@@ -97982,7 +98285,7 @@ async function runSenpiInstaller(options = {}) {const backupPath = await writeSettingsAtomically(context.settingsPath, settings);const launcherPath = installLocalLauncher({pluginPath: context.pluginPath,- senpiCliPath: join62(context.repoRoot, "packages", "coding-agent", "dist", "cli.js"),+ senpiCliPath: join63(context.repoRoot, "packages", "coding-agent", "dist", "cli.js"),homeDir: context.homeDir});return {@@ -97999,16 +98302,16 @@ async function runSenpiInstaller(options = {}) {function resolveInstallContext(options) {const env = options.env ?? process.env;const allowBuild = options.pluginPath === undefined;- const repoRoot = resolve19(options.repoRoot ?? (allowBuild ? findRepoRoot2(dirname24(fileURLToPath(import.meta.url))) : dirname24(resolve19(options.pluginPath))));+ const repoRoot = resolve20(options.repoRoot ?? (allowBuild ? findRepoRoot2(dirname25(fileURLToPath(import.meta.url))) : dirname25(resolve20(options.pluginPath))));const homeDir = options.homeDir ?? env.HOME ?? homedir11();- const agentDir = resolve19(options.agentDir ?? resolveAgentHome({ env, homeDir }));- const pluginPath = resolve19(options.pluginPath ?? join62(repoRoot, "packages", "omo-senpi", "plugin"));+ const agentDir = resolve20(options.agentDir ?? resolveAgentHome({ env, homeDir }));+ const pluginPath = resolve20(options.pluginPath ?? join63(repoRoot, "packages", "omo-senpi", "plugin"));return {env,repoRoot,agentDir,homeDir,- settingsPath: join62(agentDir, "settings.json"),+ settingsPath: join63(agentDir, "settings.json"),pluginPath,platform: options.platform ?? process.platform,allowBuild,@@ -98025,14 +98328,14 @@ async function defaultRunCommand3(command, args, options) {function findRepoRoot2(importerDir) {let current = importerDir;for (let depth = 0;depth <= 7; depth += 1) {- if (fileExistsSync(join62(current, "packages", "omo-senpi", "plugin", "package.json")))+ if (fileExistsSync(join63(current, "packages", "omo-senpi", "plugin", "package.json")))return current;- current = resolve19(current, "..");+ current = resolve20(current, "..");}throw new Error("Unable to locate packages/omo-senpi/plugin/package.json from installer module");}function fileExistsSync(path) {- return existsSync30(path);+ return existsSync31(path);}// packages/omo-opencode/src/cli/install-native-dev/index.tsasync function runNativeDevInstaller(options) {@@ -98040,6 +98343,8 @@ async function runNativeDevInstaller(options) {}// packages/omo-opencode/src/cli/install-native/plan.ts+init_shared();+init_bundled_version();var NATIVE_PACKAGE_SPEC = "omo-ai@beta";var NATIVE_SETUP_COMMAND = "omo setup";var NATIVE_RECOMMENDED_RUNTIME_NOTE = "bun is the recommended runtime for OmO Native; npm works, but bun is what the beta channel is tested on.";@@ -98053,9 +98358,254 @@ function resolveNativeInstallPlan(bunAvailable) {function formatNativeInstallCommand(plan) {return [plan.command, ...plan.args].join(" ");}+function formatNativeInstallEntryCommand(plan, pluginVersion = getBundledVersion()) {+ const runner = plan.packageManager === "bun" ? "bunx" : "npx";+ const tag = isPrereleaseVersion(pluginVersion) ? "@beta" : "";+ return `${runner} ${PUBLISHED_PACKAGE_NAME}${tag} install --platform=native`;+}+// packages/omo-opencode/src/cli/install-native/legacy-omo-bin.ts+import { lstatSync as lstatSync4, readFileSync as readFileSync15, realpathSync as realpathSync8 } from "node:fs";+import { dirname as dirname26, isAbsolute as isAbsolute12, join as join64, posix as posix9, win32 as win325 } from "node:path";+var NATIVE_OMO_PACKAGE = "omo-ai";+var LEGACY_OMO_BIN_PACKAGES = ["oh-my-openagent", "oh-my-opencode", "lazycodex"];+var CODEX_LIGHT_WRAPPER_MARKER = "OMO_GENERATED_RUNTIME_WRAPPER";+var CODEX_LIGHT_CACHE_VERSION = /[\\/]plugins[\\/]cache[\\/]sisyphuslabs[\\/]omo[\\/]([^\\/"'\s]+)[\\/]/;+var OMO_BIN_NAME = "omo";+var WINDOWS_BIN_SUFFIXES = ["", ".cmd", ".ps1", ".exe"];+var OWNER_WALK_UP_LIMIT = 6;+var SHIM_READ_LIMIT = 8192;+function resolveOmoBinEnvironment(input) {+ const isWindows = input.platform === "win32";+ const pathRules = isWindows ? win325 : posix9;+ const pathValue = input.env["PATH"] ?? input.env["Path"] ?? "";+ const pathDirectories = pathValue.split(pathRules.delimiter).map((entry) => entry.trim()).filter((entry) => pathRules.isAbsolute(entry)).filter((entry) => !/(?:^|[\\/])node_modules[\\/]\.bin[\\/]?$/.test(entry));+ const bunInstall = input.env["BUN_INSTALL"];+ const bunBinDir = bunInstall ? pathRules.join(bunInstall, "bin") : pathRules.join(input.homeDir, ".bun", "bin");+ const extraDirectories = pathDirectories.includes(bunBinDir) ? [] : [bunBinDir];+ return { pathDirectories, extraDirectories, isWindows };+}+function scanOmoBins(environment) {+ const visited = new Set;+ const entries = [];+ const visit = (directory, onPath) => {+ if (directory === "" || visited.has(directory))+ return;+ visited.add(directory);+ const shimPaths = omoShimPathsIn(directory, environment.isWindows);+ const binPath = shimPaths[0];+ if (binPath === undefined)+ return;+ const owner = resolveOwner(binPath);+ entries.push({+ binPath,+ directory,+ onPath,+ kind: classify(owner),+ packageName: owner?.name ?? null,+ packageVersion: owner?.version ?? null,+ shimPaths+ });+ };+ for (const directory of environment.pathDirectories)+ visit(directory, true);+ for (const directory of environment.extraDirectories)+ visit(directory, false);+ return entries;+}+function legacyOmoBins(entries) {+ return entries.filter((entry) => entry.kind === "legacy");+}+function nativeOmoBin(entries) {+ return entries.find((entry) => entry.kind === "native") ?? null;+}+function firstOmoBinOnPath(entries) {+ return entries.find((entry) => entry.onPath) ?? null;+}+function classify(owner) {+ if (owner === null)+ return "foreign";+ if (owner.name === NATIVE_OMO_PACKAGE)+ return "native";+ return LEGACY_OMO_BIN_PACKAGES.includes(owner.name) ? "legacy" : "foreign";+}+function omoShimPathsIn(directory, isWindows) {+ const suffixes = isWindows ? WINDOWS_BIN_SUFFIXES : [""];+ return suffixes.map((suffix) => join64(directory, `${OMO_BIN_NAME}${suffix}`)).filter(pathExists);+}+function pathExists(path) {+ try {+ lstatSync4(path);+ return true;+ } catch {+ return false;+ }+}+function resolveOwner(binPath) {+ const real = realPathOf(binPath);+ const fromLink = isInsideNodeModules(real) ? ownerOfFile(real) : null;+ if (fromLink !== null)+ return fromLink;+ const shim = readShimText(binPath);+ if (shim === null)+ return null;+ const lightWrapper = codexLightWrapperOwner(shim);+ if (lightWrapper !== null)+ return lightWrapper;+ for (const entry of shimEntryPaths(shim, dirname26(binPath))) {+ if (!isInsideNodeModules(entry) || !pathExists(entry))+ continue;+ const owner = ownerOfFile(entry);+ if (owner !== null)+ return owner;+ }+ return null;+}+function shimEntryPaths(shim, shimDirectory) {+ const paths = [];+ for (const match of shim.matchAll(/(?<=["'])[^"'\n]*node_modules[\\/][^"'\n]*(?=["'])/g)) {+ const quoted = match[0];+ const relativeToShim = quoted.match(/^(?:%~?dp0%?|\$\{?basedir\}?)[\\/]?(.*)$/)?.[1];+ if (relativeToShim !== undefined)+ paths.push(join64(shimDirectory, relativeToShim.replace(/\\/g, "/")));+ else if (isAbsolute12(quoted))+ paths.push(quoted);+ }+ return paths;+}+function codexLightWrapperOwner(shim) {+ if (!shim.includes(CODEX_LIGHT_WRAPPER_MARKER))+ return null;+ const version = shim.match(CODEX_LIGHT_CACHE_VERSION)?.[1];+ return version === undefined ? null : { name: "lazycodex", version };+}+function isInsideNodeModules(path) {+ return /(?:^|[\\/])node_modules[\\/]/.test(path);+}+function ownerOfFile(file) {+ let directory = dirname26(file);+ for (let depth = 0;depth < OWNER_WALK_UP_LIMIT; depth += 1) {+ const manifest = readWholeFile(join64(directory, "package.json"));+ if (manifest !== null) {+ const parsed = parseManifest(manifest);+ if (parsed !== null)+ return parsed;+ }+ const parent = dirname26(directory);+ if (parent === directory)+ return null;+ directory = parent;+ }+ return null;+}+function parseManifest(manifest) {+ try {+ const parsed = JSON.parse(manifest);+ if (typeof parsed !== "object" || parsed === null)+ return null;+ const record = parsed;+ if (typeof record.name !== "string" || record.name === "")+ return null;+ return { name: record.name, version: typeof record.version === "string" ? record.version : null };+ } catch {+ return null;+ }+}+function realPathOf(path) {+ try {+ return realpathSync8(path);+ } catch {+ return path;+ }+}+function readShimText(path) {+ return readWholeFile(path)?.slice(0, SHIM_READ_LIMIT) ?? null;+}+function readWholeFile(path) {+ try {+ return readFileSync15(path, "utf8");+ } catch {+ return null;+ }+}+// packages/omo-opencode/src/cli/install-native/repair-legacy-omo-bin.ts+import { rmSync as rmSync5 } from "node:fs";+function describePackage(entry) {+ const name = entry.packageName ?? "an unknown package";+ return entry.packageVersion === null ? name : `${name}@${entry.packageVersion}`;+}+function removeFileCommand(binPath, isWindows) {+ return isWindows ? `del "${binPath}"` : `rm "${binPath}"`;+}+function repairLegacyOmoBins(entries, options) {+ const removed = [];+ const failures = [];+ const notes = [];+ const warnings = [];+ for (const entry of entries) {+ const owner = describePackage(entry);+ try {+ for (const shimPath of entry.shimPaths)+ rmSync5(shimPath);+ removed.push({+ binPath: entry.binPath,+ packageName: entry.packageName ?? "",+ packageVersion: entry.packageVersion+ });+ notes.push(`Removed the stale omo command left by ${owner} (${entry.binPath}). That package and its other commands are untouched; reinstalling it would put its omo back in front of omo-ai.`);+ } catch (error) {+ const reason = error instanceof Error ? error.message : String(error);+ failures.push({ binPath: entry.binPath, reason });+ warnings.push(`Could not remove the stale omo command owned by ${owner} (${entry.binPath}): ${reason}. Remove it yourself with ${removeFileCommand(entry.binPath, options.isWindows)}, or drop the whole package with npm uninstall -g ${entry.packageName ?? "oh-my-openagent"}.`);+ }+ }+ return { removed, failures, notes, warnings };+}+// packages/omo-opencode/src/cli/install-native/verify-omo-command.ts+function pathOrderFix(directory, isWindows) {+ return isWindows ? `set PATH=${directory};%PATH%` : `export PATH="${directory}:$PATH"`;+}+async function verifyOmoCommand(options) {+ const entries = scanOmoBins(options.environment);+ const native = nativeOmoBin(entries);+ const resolved = firstOmoBinOnPath(entries);+ if (native === null) {+ return {+ ok: false,+ notes: [],+ warnings: ["Could not find an omo command owned by omo-ai after the install. Run omo --version yourself to check."]+ };+ }+ if (!native.onPath) {+ return {+ ok: false,+ notes: [],+ warnings: [+ `omo-ai installed ${native.binPath}, but ${native.directory} is not on PATH. Add it: ${pathOrderFix(native.directory, options.environment.isWindows)}`+ ]+ };+ }+ if (resolved !== null && resolved.binPath !== native.binPath) {+ return { ok: false, notes: [], warnings: [shadowWarning(resolved, native, options.environment.isWindows)] };+ }+ const probe = await options.probeVersion(native.binPath, ["--version"]);+ const printed = probe.stdout.trim().split(`+`)[0] ?? "";+ if (probe.exitCode !== 0 || !printed.startsWith("omo ")) {+ return {+ ok: false,+ notes: [],+ warnings: [`omo --version did not report omo-ai (exit ${probe.exitCode}): ${printed || "no output"}`]+ };+ }+ return { ok: true, binPath: native.binPath, notes: [`omo --version reports ${printed}`], warnings: [] };+}+function shadowWarning(resolved, native, isWindows) {+ return `omo on PATH still resolves to ${resolved.binPath} (${describePackage(resolved)}), not to the omo-ai command at ${native.binPath}. Put omo-ai first: ${pathOrderFix(native.directory, isWindows)}`;+}// packages/omo-opencode/src/cli/install-native/run-native-install.tsinit_bun_which_shim();init_spawn_with_windows_hide();+import { homedir as homedir12 } from "node:os";function describeExit(plan, result) {const stderr = result.stderr?.trim();const head = `${plan.packageManager} exited with code ${result.exitCode}`;@@ -98064,24 +98614,54 @@ function describeExit(plan, result) {}async function runNativeInstall(dependencies = defaultNativeInstallDependencies()) {const plan = resolveNativeInstallPlan(await dependencies.isBunAvailable());+ const environment = dependencies.environment;const notes = plan.packageManager === "npm" ? [NATIVE_RECOMMENDED_RUNTIME_NOTE] : [];+ const warnings = [];const manualCommand = formatNativeInstallCommand(plan);+ const repair = repairLegacyOmoBins(legacyOmoBins(scanOmoBins(environment)), { isWindows: environment.isWindows });+ notes.push(...repair.notes);+ warnings.push(...repair.warnings);+ const hints = repair.failures.map((failure) => `Remove the stale omo command first: ${removeFileCommand(failure.binPath, environment.isWindows)}`);+ const failed = (reason) => ({+ ok: false,+ verified: false,+ plan,+ notes,+ warnings,+ failure: hints.length > 0 ? { reason, manualCommand, hints } : { reason, manualCommand }+ });try {const result = await dependencies.spawn(plan.command, plan.args);- if (result.exitCode === 0)- return { ok: true, plan, notes };- return { ok: false, plan, notes, failure: { reason: describeExit(plan, result), manualCommand } };+ if (result.exitCode !== 0)+ return failed(describeExit(plan, result));} catch (error) {- const reason = error instanceof Error ? error.message : String(error);- return { ok: false, plan, notes, failure: { reason, manualCommand } };+ return failed(error instanceof Error ? error.message : String(error));}+ if (plan.packageManager === "npm") {+ for (const name of new Set(repair.removed.map((removal) => removal.packageName))) {+ if (NPM_LEGACY_OMO_PACKAGES.includes(name))+ notes.push(npmUninstallNote(name, manualCommand));+ }+ }+ const verification = await verifyOmoCommand({ environment, probeVersion: dependencies.probeVersion });+ notes.push(...verification.notes);+ warnings.push(...verification.warnings);+ return verification.ok ? { ok: true, verified: true, omoBinPath: verification.binPath, plan, notes, warnings } : { ok: true, verified: false, plan, notes, warnings };}-function nativeInstallSuccessLine() {+var NPM_LEGACY_OMO_PACKAGES = ["oh-my-openagent", "oh-my-opencode"];+function npmUninstallNote(packageName, installCommand) {+ return `If you later run npm uninstall -g ${packageName}, npm also deletes the omo command omo-ai now owns. Run ${installCommand} again afterwards to restore it.`;+}+function nativeInstallSuccessLine(verified) {+ if (!verified) {+ return `OmO Native installed, but omo on your PATH is not omo-ai yet. Apply the fix above, then run ${NATIVE_SETUP_COMMAND}.`;+ }return `OmO Native installed. Run ${NATIVE_SETUP_COMMAND} to finish onboarding.`;}function nativeInstallFailureLines(failure) {return [`OmO Native install failed: ${failure.reason}`,+ ...failure.hints ?? [],`Install it yourself with: ${failure.manualCommand}`,`Then run ${NATIVE_SETUP_COMMAND}.`];@@ -98089,6 +98669,7 @@ function nativeInstallFailureLines(failure) {function defaultNativeInstallDependencies() {return {isBunAvailable: () => bunWhich("bun") !== null,+ environment: resolveOmoBinEnvironment({ env: process.env, platform: process.platform, homeDir: homedir12() }),spawn: async (command, args) => {const proc = spawnWithWindowsHide([command, ...args], {env: process.env,@@ -98096,12 +98677,58 @@ function defaultNativeInstallDependencies() {stderr: "inherit"});return { exitCode: await proc.exited };+ },+ probeVersion: async (command, args) => {+ const proc = spawnWithWindowsHide([command, ...args], {+ env: process.env,+ stdout: "pipe",+ stderr: "pipe"+ });+ const stdout = proc.stdout === undefined ? "" : await new Response(proc.stdout).text();+ return { exitCode: await proc.exited, stdout };}};}+// packages/omo-opencode/src/cli/install-native/offer-native-setup.ts+init_spawn_with_windows_hide();+var NATIVE_SETUP_OFFER_QUESTION = "Run omo setup now to carry your OpenCode credentials, MCP servers and skills over?";+async function offerNativeSetup(outcome, dependencies) {+ const binPath = outcome.verified ? outcome.omoBinPath : undefined;+ if (binPath === undefined)+ return { kind: "not-offered" };+ if (!await dependencies.confirm(NATIVE_SETUP_OFFER_QUESTION))+ return { kind: "declined" };+ const runSetup = dependencies.runSetup ?? runSetupInheritingTerminal;+ dependencies.onStart?.(nativeSetupStartLine(binPath));+ try {+ return { kind: "ran", binPath, exitCode: await runSetup(binPath, ["setup"]) };+ } catch (error) {+ return { kind: "failed", binPath, reason: error instanceof Error ? error.message : String(error) };+ }+}+function nativeSetupStartLine(binPath) {+ return `Starting ${binPath} setup`;+}+function nativeSetupFollowUpLine(result) {+ if (result.kind === "failed") {+ return `Could not start ${result.binPath} setup (${result.reason}). Run ${NATIVE_SETUP_COMMAND} to finish onboarding.`;+ }+ if (result.kind !== "ran" || result.exitCode === 0)+ return null;+ return `omo setup exited with code ${result.exitCode}. Run ${NATIVE_SETUP_COMMAND} again to finish onboarding.`;+}+async function runSetupInheritingTerminal(binPath, args) {+ const proc = spawnWithWindowsHide([binPath, ...args], {+ env: process.env,+ stdin: "inherit",+ stdout: "inherit",+ stderr: "inherit"+ });+ return proc.exited;+}// packages/omo-opencode/src/cli/native-edition-hint.ts-var NATIVE_EDITION_INSTALL_COMMAND = "bun add -g omo-ai@beta";-var NATIVE_EDITION_GUIDE_URL = "https://github.com/code-yeongyu/oh-my-openagent/blob/dev/docs/guide/installation.md#omo-native-beta-omo-via-omo-ai";+var NATIVE_EDITION_INSTALL_COMMAND = formatNativeInstallEntryCommand(resolveNativeInstallPlan(true));+var NATIVE_EDITION_GUIDE_URL = "https://github.com/code-yeongyu/oh-my-openagent/blob/dev/docs/guide/migrating-from-opencode.md";var NATIVE_EDITION_HINT_TITLE = "OmO Native (beta)";var PLAIN_PAINT = {command: (text) => text,@@ -98154,26 +98781,39 @@ async function starGitHubRepositories(platform = "both", runCommand = runGitHubSinit_provider_availability();// packages/omo-opencode/src/cli/config-manager/add-tui-plugin-to-tui-config.ts-import { existsSync as existsSync32, mkdirSync as mkdirSync12, readFileSync as readFileSync15 } from "node:fs";-import { join as join64 } from "node:path";+import { existsSync as existsSync33, mkdirSync as mkdirSync13, readFileSync as readFileSync17 } from "node:fs";+import { join as join66 } from "node:path";// packages/omo-opencode/src/cli/doctor/checks/tui-plugin-config.tsinit_shared();-import { existsSync as existsSync31, readFileSync as readFileSync14 } from "node:fs";-import { join as join63 } from "node:path";+import { existsSync as existsSync32, readFileSync as readFileSync16 } from "node:fs";+import { join as join65 } from "node:path";var TUI_SUBPATH = "tui";var TUI_EXPORT_SUBPATH = `./${TUI_SUBPATH}`;+function tuiPluginSpecName(entry) {+ if (typeof entry === "string")+ return entry;+ if (isPluginTupleEntry(entry))+ return entry[0];+ return null;+}+function isOmoSourceFileSpec(name) {+ const normalized = name.toLowerCase().replaceAll("\\", "/");+ if (!normalized.startsWith("file://"))+ return false;+ return /\/(omo(?:-[^/]*)?|oh-my-opencode|oh-my-openagent)\/(src|dist)\/index\.(ts|js)$/.test(normalized);+}function fileEntryPackageJsonPath(entry) {let path = entry.slice("file:".length);if (path.startsWith("//"))path = path.slice(2);- return join63(path, "package.json");+ return join65(path, "package.json");}function packageJsonExportsTui(pkgJsonPath) {- if (!existsSync31(pkgJsonPath))+ if (!existsSync32(pkgJsonPath))return null;try {- const parsed = JSON.parse(readFileSync14(pkgJsonPath, "utf-8"));+ const parsed = JSON.parse(readFileSync16(pkgJsonPath, "utf-8"));if (parsed.exports === undefined)return null;if (typeof parsed.exports === "string")@@ -98197,7 +98837,8 @@ function packageNameFromServerEntry(entry) {return null;}function isPackagePluginEntry(entry) {- return packageNameFromServerEntry(entry) !== null;+ const name = tuiPluginSpecName(entry);+ return name !== null && packageNameFromServerEntry(name) !== null;}function packageExportsTuiForServerEntry(entry) {if (typeof entry === "string" && entry.startsWith("file:"))@@ -98205,16 +98846,16 @@ function packageExportsTuiForServerEntry(entry) {const packageName = packageNameFromServerEntry(entry);if (packageName === null)return null;- return packageJsonExportsTui(join63(getOpenCodeConfigDir({ binary: "opencode" }), "node_modules", packageName, "package.json"));+ return packageJsonExportsTui(join65(getOpenCodeConfigDir({ binary: "opencode" }), "node_modules", packageName, "package.json"));}function isOurFilePluginEntry(entry) {if (typeof entry !== "string" || !entry.startsWith("file:"))return false;try {const pkgJsonPath = fileEntryPackageJsonPath(entry);- if (!existsSync31(pkgJsonPath))+ if (!existsSync32(pkgJsonPath))return false;- const parsed = JSON.parse(readFileSync14(pkgJsonPath, "utf-8"));+ const parsed = JSON.parse(readFileSync16(pkgJsonPath, "utf-8"));return typeof parsed.name === "string" && ACCEPTED_PACKAGE_NAMES.includes(parsed.name);} catch (error) {log2("[tui-plugin-config] Failed to inspect file plugin package", {@@ -98234,27 +98875,49 @@ function isServerPluginEntry(entry) {return false;}function isTuiPluginEntry(entry) {- return typeof entry === "string" && (isPackagePluginEntry(entry) || entry.startsWith("file:") && isOurFilePluginEntry(entry));+ const name = tuiPluginSpecName(entry);+ if (name === null)+ return false;+ return isPackagePluginEntry(name) || name.startsWith("file:") && isOurFilePluginEntry(name);}function isNamedTuiPluginEntry(entry) {+ const name = tuiPluginSpecName(entry);+ if (name === null)+ return false;const canonicalPrefix = `${PLUGIN_NAME}/${TUI_SUBPATH}`;const legacyPrefix = `${LEGACY_PLUGIN_NAME}/${TUI_SUBPATH}`;- return typeof entry === "string" && (entry === canonicalPrefix || entry.startsWith(`${canonicalPrefix}@`) || entry === legacyPrefix || entry.startsWith(`${legacyPrefix}@`));+ return name === canonicalPrefix || name.startsWith(`${canonicalPrefix}@`) || name === legacyPrefix || name.startsWith(`${legacyPrefix}@`);+}+function isOmoManagedTuiEntry(entry) {+ const name = tuiPluginSpecName(entry);+ if (name === null)+ return false;+ return isNamedTuiPluginEntry(name) || isTuiPluginEntry(name) || isOmoSourceFileSpec(name);}function isCanonicalNamedTuiPluginEntry(entry) {+ const name = tuiPluginSpecName(entry);+ if (name === null)+ return false;const canonicalPrefix = `${PLUGIN_NAME}/${TUI_SUBPATH}`;- return typeof entry === "string" && (entry === canonicalPrefix || entry.startsWith(`${canonicalPrefix}@`));+ return name === canonicalPrefix || name.startsWith(`${canonicalPrefix}@`);}function detectServerPluginRegistration() {const paths = getOpenCodeConfigPaths({ binary: "opencode", version: null });- const configPath = existsSync31(paths.configJsonc) ? paths.configJsonc : existsSync31(paths.configJson) ? paths.configJson : null;+ const configPath = existsSync32(paths.configJsonc) ? paths.configJsonc : existsSync32(paths.configJson) ? paths.configJson : null;if (!configPath) {return { registered: false, configPath: null, entry: null, packageExportsTui: null };}try {- const parsed = parseJsonc(readFileSync14(configPath, "utf-8"));+ const parsed = parseJsonc(readFileSync16(configPath, "utf-8"));const plugins = parsed.plugin ?? [];- const serverEntry = plugins.find(isServerPluginEntry);+ let serverEntry;+ for (const entry of plugins) {+ const name = tuiPluginSpecName(entry);+ if (name !== null && isServerPluginEntry(name)) {+ serverEntry = name;+ break;+ }+ }return {registered: serverEntry !== undefined,configPath,@@ -98270,19 +98933,20 @@ function detectServerPluginRegistration() {}}function detectTuiPluginRegistration() {- const tuiJsonPath = join63(getOpenCodeConfigDir({ binary: "opencode" }), "tui.json");- if (!existsSync31(tuiJsonPath)) {+ const tuiJsonPath = join65(getOpenCodeConfigDir({ binary: "opencode" }), "tui.json");+ if (!existsSync32(tuiJsonPath)) {return {registered: false,configPath: tuiJsonPath,exists: false,hasPackageTuiEntry: false,hasNamedTuiEntry: false,- hasCanonicalNamedTuiEntry: false+ hasCanonicalNamedTuiEntry: false,+ managedEntryCount: 0};}try {- const parsed = parseJsonc(readFileSync14(tuiJsonPath, "utf-8"));+ const parsed = parseJsonc(readFileSync16(tuiJsonPath, "utf-8"));const plugins = parsed.plugin ?? [];return {registered: plugins.some(isTuiPluginEntry),@@ -98290,7 +98954,8 @@ function detectTuiPluginRegistration() {exists: true,hasPackageTuiEntry: plugins.some(isPackagePluginEntry),hasNamedTuiEntry: plugins.some(isNamedTuiPluginEntry),- hasCanonicalNamedTuiEntry: plugins.some(isCanonicalNamedTuiPluginEntry)+ hasCanonicalNamedTuiEntry: plugins.some(isCanonicalNamedTuiPluginEntry),+ managedEntryCount: plugins.filter(isOmoManagedTuiEntry).length};} catch (error) {log2("[tui-plugin-config] Failed to inspect TUI plugin config", {@@ -98303,7 +98968,8 @@ function detectTuiPluginRegistration() {exists: true,hasPackageTuiEntry: false,hasNamedTuiEntry: false,- hasCanonicalNamedTuiEntry: false+ hasCanonicalNamedTuiEntry: false,+ managedEntryCount: 0};}}@@ -98360,6 +99026,23 @@ async function checkTuiPluginConfig() {issues};}+ if (tui.managedEntryCount > 1) {+ const desiredEntry = server.entry ?? PLUGIN_NAME;+ issues.push({+ title: "TUI plugin is registered more than once in tui.json",+ description: `tui.json lists ${tui.managedEntryCount} entries for ${PLUGIN_NAME} ` + "(bare name, version/tag spec, legacy name, /tui subpath, or file:). " + "OpenCode loads each one, so the plugin runs twice.",+ fix: `Re-run the installer (\`npx oh-my-openagent install\`) to keep a single "${desiredEntry}" entry in ${tui.configPath}.`,+ affects: ["TUI startup", "plugin loading"],+ severity: "warning"+ });+ return {+ name,+ status: "warn",+ message: "TUI plugin is registered more than once in tui.json",+ details: details.length > 0 ? details : undefined,+ issues+ };+ }if (server.registered && !tui.registered) {if (server.packageExportsTui === false) {return {@@ -98415,7 +99098,7 @@ init_shared();init_write_file_atomically();function readConfig(path) {try {- const parsed = parseJsonc(readFileSync15(path, "utf-8"));+ const parsed = parseJsonc(readFileSync17(path, "utf-8"));if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {return parsed;}@@ -98426,16 +99109,31 @@ function readConfig(path) {return null;}function readServerConfig(configDir) {- const jsoncPath = join64(configDir, "opencode.jsonc");- if (existsSync32(jsoncPath))+ const jsoncPath = join66(configDir, "opencode.jsonc");+ if (existsSync33(jsoncPath))return readConfig(jsoncPath);- const jsonPath = join64(configDir, "opencode.json");- if (existsSync32(jsonPath))+ const jsonPath = join66(configDir, "opencode.json");+ if (existsSync33(jsonPath))return readConfig(jsonPath);return null;}function pluginEntries(config) {- return Array.isArray(config.plugin) ? config.plugin.filter((entry) => typeof entry === "string") : [];+ if (Array.isArray(config.plugin))+ return config.plugin;+ if (typeof config.plugin === "string")+ return [config.plugin];+ return [];+}+function pluginFieldInvalid(config) {+ return config.plugin !== undefined && !Array.isArray(config.plugin) && typeof config.plugin !== "string";+}+function serverPluginEntry(config) {+ for (const entry of pluginEntries(config)) {+ const name = tuiPluginSpecName(entry);+ if (name !== null && isServerPluginEntry(name))+ return name;+ }+ return;}function desiredTuiEntry(serverEntry) {if (serverEntry === PLUGIN_NAME || serverEntry.startsWith(`${PLUGIN_NAME}@`)) {@@ -98450,7 +99148,7 @@ function desiredTuiEntry(serverEntry) {return null;}function readTuiConfig(tuiJsonPath) {- if (!existsSync32(tuiJsonPath)) {+ if (!existsSync33(tuiJsonPath)) {return { config: {}, malformed: false };}const config = readConfig(tuiJsonPath);@@ -98463,7 +99161,7 @@ function formatConfig(config) {function ensureTuiPluginEntry(opts = {}) {const configDir = opts.configDir ?? getOpenCodeConfigDir({ binary: "opencode", version: null });const serverConfig = readServerConfig(configDir);- const serverEntry = serverConfig ? pluginEntries(serverConfig).find(isServerPluginEntry) : undefined;+ const serverEntry = serverConfig ? serverPluginEntry(serverConfig) : undefined;if (!serverEntry) {return { changed: false, reason: "no-server-entry" };}@@ -98471,31 +99169,87 @@ function ensureTuiPluginEntry(opts = {}) {if (!desiredEntry) {return { changed: false, reason: "no-server-entry" };}- const tuiJsonPath = join64(configDir, "tui.json");+ const tuiJsonPath = join66(configDir, "tui.json");const { config, malformed } = readTuiConfig(tuiJsonPath);- if (malformed) {+ if (malformed || pluginFieldInvalid(config)) {return { changed: false, reason: "malformed" };}- const plugins = pluginEntries(config).filter((entry) => !isNamedTuiPluginEntry(entry));- if (plugins.includes(desiredEntry)) {+ const entries = pluginEntries(config);+ const otherEntries = entries.filter((entry) => !isOmoManagedTuiEntry(entry));+ const pluginIsArray = Array.isArray(config.plugin);+ const isOnlyDesiredEntry = pluginIsArray && entries.length === otherEntries.length + 1 && entries.includes(desiredEntry);+ if (isOnlyDesiredEntry) {return { changed: false, reason: "already-present" };}- mkdirSync12(configDir, { recursive: true });- writeFileAtomically2(tuiJsonPath, formatConfig({ ...config, plugin: [...plugins, desiredEntry] }));+ mkdirSync13(configDir, { recursive: true });+ writeFileAtomically2(tuiJsonPath, formatConfig({ ...config, plugin: [...otherEntries, desiredEntry] }));return { changed: true, reason: "added" };}+// packages/omo-opencode/src/cli/config-manager/refresh-opencode-plugin-sandbox.ts+init_shared();+init_config_context();+import { existsSync as existsSync34, readFileSync as readFileSync18 } from "node:fs";+import { join as join67 } from "node:path";+function readPluginEntries(configDir) {+ for (const name of ["opencode.jsonc", "opencode.json"]) {+ const configPath = join67(configDir, name);+ if (!existsSync34(configPath))+ continue;+ try {+ const parsed = parseJsonc(readFileSync18(configPath, "utf-8"));+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))+ continue;+ return (parsed.plugin ?? []).filter((entry) => typeof entry === "string");+ } catch (error) {+ if (!(error instanceof Error))+ throw error;+ log2(`[install] Could not read plugin entries from ${configPath}: ${error.message}`);+ }+ }+ return [];+}+function refreshOpenCodePluginSandboxes(options = {}) {+ const configDir = options.configDir ?? getConfigDir();+ const cacheDir = options.cacheDir ?? getOpenCodeCacheDir();+ const removed = [];+ const deferred = [];+ const failed = [];+ for (const entry of readPluginEntries(configDir)) {+ const sandboxDir = getPluginSandboxDir(cacheDir, entry);+ if (!sandboxDir)+ continue;+ try {+ if (hasOtherLivePluginSandboxLease(sandboxDir) && markPluginSandboxStale(sandboxDir, cacheDir)) {+ deferred.push(sandboxDir);+ log2(`[install] OpenCode is running from ${sandboxDir}; marked it for refresh when OpenCode exits`);+ continue;+ }+ if (!removePluginSandbox(sandboxDir, cacheDir))+ continue;+ removed.push(sandboxDir);+ log2(`[install] Removed stale OpenCode plugin sandbox: ${sandboxDir}`);+ } catch (error) {+ if (!(error instanceof Error))+ throw error;+ failed.push({ dir: sandboxDir, message: error.message });+ log2(`[install] Failed to remove OpenCode plugin sandbox ${sandboxDir}: ${error.message}`);+ }+ }+ return { removed, deferred, failed };+}+// packages/omo-opencode/src/cli/install-ast-grep-sg.ts-import { homedir as homedir12 } from "node:os";-import { join as join65 } from "node:path";+import { homedir as homedir13 } from "node:os";+import { join as join68 } from "node:path";// packages/shared-skills/index.mjs-import { existsSync as existsSync33 } from "node:fs";+import { existsSync as existsSync35 } from "node:fs";import { fileURLToPath as fileURLToPath2 } from "node:url";var SKILLS_PROBE_SPECIFIERS = ["./skills/", "../skills/", "../../skills/"];function sharedSkillsRootPath() {const candidates = SKILLS_PROBE_SPECIFIERS.map((specifier) => fileURLToPath2(new URL(specifier, import.meta.url)));- return candidates.find((candidate) => existsSync33(candidate)) ?? candidates[0];+ return candidates.find((candidate) => existsSync35(candidate)) ?? candidates[0];}// packages/omo-opencode/src/cli/install-ast-grep-sg.ts@@ -98509,9 +99263,9 @@ function describeResult2(result) {}async function installAstGrepForOpenCode(options = {}) {const platform = options.platform ?? process.platform;- const baseDir = join65(options.homeDir ?? homedir12(), ".omo");+ const baseDir = join68(options.homeDir ?? homedir13(), ".omo");const targetDir = astGrepRuntimeDir(baseDir, platform, options.arch ?? process.arch);- const skillDir = join65(options.sharedSkillsRoot ?? sharedSkillsRootPath(), "ast-grep");+ const skillDir = join68(options.sharedSkillsRoot ?? sharedSkillsRootPath(), "ast-grep");const installer = options.installer ?? runAstGrepSkillInstall;try {const result = await installer({ platform, skillDir, targetDir });@@ -98596,6 +99350,21 @@ async function runCliInstaller(args, version) {const message = error instanceof Error ? error.message : String(error);printWarning(`Could not update OpenCode TUI config: ${message}`);}+ try {+ const { removed, deferred, failed } = refreshOpenCodePluginSandboxes();+ if (removed.length > 0) {+ printInfo("Refreshed the OpenCode plugin cache; the next OpenCode start loads the installed version.");+ }+ if (deferred.length > 0) {+ printInfo("OpenCode is running from its plugin cache; it refreshes when the last OpenCode window closes. Restart OpenCode to load the installed version.");+ }+ for (const { dir, message } of failed) {+ printWarning(`Could not refresh the OpenCode plugin cache at ${dir} (${message}). Close OpenCode and delete that directory, or OpenCode keeps loading the previous version.`);+ }+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ printWarning(`Could not refresh the OpenCode plugin cache: ${message}`);+ }printStep(step++, totalSteps, `Writing ${PLUGIN_NAME} configuration...`);const omoResult = writeOmoConfig(config);if (!omoResult.success) {@@ -98636,14 +99405,16 @@ async function runCliInstaller(args, version) {if (config.hasNative) {printInfo("Installing OmO Native...");const outcome = await runNativeInstall();+ for (const note of outcome.notes)+ printInfo(note);+ for (const warning of outcome.warnings)+ printWarning(warning);if (outcome.failure) {for (const line of nativeInstallFailureLines(outcome.failure))printError(line);return 1;}- for (const note of outcome.notes)- printInfo(note);- printSuccess(nativeInstallSuccessLine());+ printSuccess(nativeInstallSuccessLine(outcome.verified));console.log();}if (config.hasNativeDev) {@@ -100113,6 +100884,21 @@ async function runTuiInstaller(args, version) {const message = error instanceof Error ? error.message : String(error);log4.warn(`Could not update OpenCode TUI config: ${message}`);}+ try {+ const { removed, deferred, failed } = refreshOpenCodePluginSandboxes();+ if (removed.length > 0) {+ log4.info("Refreshed the OpenCode plugin cache; the next OpenCode start loads the installed version.");+ }+ if (deferred.length > 0) {+ log4.info("OpenCode is running from its plugin cache; it refreshes when the last OpenCode window closes. Restart OpenCode to load the installed version.");+ }+ for (const { dir, message } of failed) {+ log4.warn(`Could not refresh the OpenCode plugin cache at ${dir} (${message}). Close OpenCode and delete that directory, or OpenCode keeps loading the previous version.`);+ }+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log4.warn(`Could not refresh the OpenCode plugin cache: ${message}`);+ }spinner2.start(`Writing ${PLUGIN_NAME} configuration`);const omoResult = writeOmoConfig(config);if (!omoResult.success) {@@ -100157,14 +100943,30 @@ async function runTuiInstaller(args, version) {const outcome = await runNativeInstall();if (outcome.failure) {spinner2.stop(`OmO Native install failed ${import_picocolors4.default.yellow("[!]")}`);+ for (const note of outcome.notes)+ log4.info(note);+ for (const warning of outcome.warnings)+ log4.warn(warning);for (const line of nativeInstallFailureLines(outcome.failure))log4.error(line);outro(import_picocolors4.default.red("Installation failed."));return 1;}- spinner2.stop(nativeInstallSuccessLine());+ spinner2.stop(nativeInstallSuccessLine(outcome.verified));for (const note of outcome.notes)log4.info(note);+ for (const warning of outcome.warnings)+ log4.warn(warning);+ const setup = await offerNativeSetup(outcome, {+ confirm: async (message) => {+ const answer = await confirm({ message, initialValue: true });+ return !isCancel(answer) && answer;+ },+ onStart: (line) => log4.step(line)+ });+ const followUp = nativeSetupFollowUpLine(setup);+ if (followUp !== null)+ log4.warn(followUp);}if (config.hasNativeDev) {spinner2.start("Installing the OmO Native development adapter");@@ -102147,7 +102949,7 @@ var import_picocolors11 = __toESM(require_picocolors(), 1);// packages/omo-opencode/src/cli/run/opencode-binary-resolver.tsinit_bun_which_shim();init_spawn_with_windows_hide();-import { delimiter as delimiter2, dirname as dirname25, posix as posix9, win32 as win325 } from "node:path";+import { delimiter as delimiter2, dirname as dirname27, posix as posix10, win32 as win326 } from "node:path";var OPENCODE_COMMANDS = ["opencode", "opencode-desktop"];var WINDOWS_SUFFIXES = ["", ".exe", ".cmd", ".bat", ".ps1"];function getCommandCandidates(platform) {@@ -102157,8 +102959,8 @@ function getCommandCandidates(platform) {}function getPathTools(platform) {if (platform === "win32")- return win325;- return posix9;+ return win326;+ return posix10;}function collectCandidateBinaryPaths(pathEnv, which = bunWhich, platform = process.platform) {const seen = new Set;@@ -102205,7 +103007,7 @@ async function findWorkingOpencodeBinary(pathEnv = process.env.PATH, probe = canreturn null;}function buildPathWithBinaryFirst(pathEnv, binaryPath) {- const preferredDir = dirname25(binaryPath);+ const preferredDir = dirname27(binaryPath);const existing = (pathEnv ?? "").split(delimiter2).filter((entry) => entry.length > 0 && entry !== preferredDir);return [preferredDir, ...existing].join(delimiter2);}@@ -102785,26 +103587,26 @@ function isClosingFence(line, fence) {return run?.charAt(0) === fence.marker && run.length >= fence.length;}// packages/boulder-state/src/top-level-task.ts-import { existsSync as existsSync34, readFileSync as readFileSync16 } from "node:fs";+import { existsSync as existsSync36, readFileSync as readFileSync19 } from "node:fs";function readCurrentTopLevelTask(planPath) {- if (!existsSync34(planPath)) {+ if (!existsSync36(planPath)) {return null;}try {- const content = readFileSync16(planPath, "utf-8");+ const content = readFileSync19(planPath, "utf-8");return parseCurrentTopLevelTask(content);} catch {return null;}}// packages/boulder-state/src/storage/path.ts-import { existsSync as existsSync35 } from "node:fs";-import { isAbsolute as isAbsolute12, join as join66, relative as relative8, resolve as resolve20 } from "node:path";+import { existsSync as existsSync37 } from "node:fs";+import { isAbsolute as isAbsolute13, join as join69, relative as relative8, resolve as resolve21 } from "node:path";function getBoulderFilePath(directory) {- return join66(directory, BOULDER_DIR, BOULDER_FILE);+ return join69(directory, BOULDER_DIR, BOULDER_FILE);}function resolveTrackedPath(baseDirectory, trackedPath) {- return isAbsolute12(trackedPath) ? resolve20(trackedPath) : resolve20(baseDirectory, trackedPath);+ return isAbsolute13(trackedPath) ? resolve21(trackedPath) : resolve21(baseDirectory, trackedPath);}function resolveBoulderPlanPath(directory, state) {const absolutePlanPath = resolveTrackedPath(directory, state.active_plan);@@ -102812,26 +103614,26 @@ function resolveBoulderPlanPath(directory, state) {if (!worktreePath) {return absolutePlanPath;}- const absoluteDirectory = resolve20(directory);+ const absoluteDirectory = resolve21(directory);const relativePlanPath = relative8(absoluteDirectory, absolutePlanPath);- if (relativePlanPath.length === 0 || relativePlanPath.startsWith("..") || isAbsolute12(relativePlanPath)) {+ if (relativePlanPath.length === 0 || relativePlanPath.startsWith("..") || isAbsolute13(relativePlanPath)) {return absolutePlanPath;}const absoluteWorktreePath = resolveTrackedPath(directory, worktreePath);- const worktreePlanPath = resolve20(absoluteWorktreePath, relativePlanPath);- return existsSync35(worktreePlanPath) ? worktreePlanPath : absolutePlanPath;+ const worktreePlanPath = resolve21(absoluteWorktreePath, relativePlanPath);+ return existsSync37(worktreePlanPath) ? worktreePlanPath : absolutePlanPath;}function resolveBoulderPlanPathForWork(directory, work) {return resolveBoulderPlanPath(directory, work);}// packages/boulder-state/src/storage/plan-progress.ts-import { existsSync as existsSync36, readFileSync as readFileSync17, readdirSync as readdirSync8, statSync as statSync4 } from "node:fs";+import { existsSync as existsSync38, readFileSync as readFileSync20, readdirSync as readdirSync9, statSync as statSync4 } from "node:fs";function getPlanProgress(planPath) {- if (!existsSync36(planPath)) {+ if (!existsSync38(planPath)) {return { total: 0, completed: 0, isComplete: false };}try {- const content = readFileSync17(planPath, "utf-8");+ const content = readFileSync20(planPath, "utf-8");const checklist = parsePlanChecklist(content);return {total: checklist.total,@@ -102910,14 +103712,14 @@ function selectMirrorWork(state) {return sorted[0] ?? null;}// packages/boulder-state/src/storage/read-state.ts-import { existsSync as existsSync37, readFileSync as readFileSync18 } from "node:fs";+import { existsSync as existsSync39, readFileSync as readFileSync21 } from "node:fs";function readBoulderState(directory) {const filePath = getBoulderFilePath(directory);- if (!existsSync37(filePath)) {+ if (!existsSync39(filePath)) {return null;}try {- const content = readFileSync18(filePath, "utf-8");+ const content = readFileSync21(filePath, "utf-8");const parsed = JSON.parse(content);if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.keys(parsed).length === 0) {return null;@@ -102985,17 +103787,17 @@ init_state();// packages/omo-opencode/src/features/run-continuation-state/constants.tsvar CONTINUATION_MARKER_DIR = ".omo/run-continuation";// packages/omo-opencode/src/features/run-continuation-state/storage.ts-import { existsSync as existsSync38, mkdirSync as mkdirSync13, readFileSync as readFileSync19, rmSync as rmSync4, writeFileSync as writeFileSync7 } from "node:fs";-import { join as join67 } from "node:path";+import { existsSync as existsSync40, mkdirSync as mkdirSync14, readFileSync as readFileSync22, rmSync as rmSync6, writeFileSync as writeFileSync8 } from "node:fs";+import { join as join70 } from "node:path";function getMarkerPath(directory, sessionID) {- return join67(directory, CONTINUATION_MARKER_DIR, `${sessionID}.json`);+ return join70(directory, CONTINUATION_MARKER_DIR, `${sessionID}.json`);}function readContinuationMarker(directory, sessionID) {const markerPath = getMarkerPath(directory, sessionID);- if (!existsSync38(markerPath))+ if (!existsSync40(markerPath))return null;try {- const raw = readFileSync19(markerPath, "utf-8");+ const raw = readFileSync22(markerPath, "utf-8");const parsed = JSON.parse(raw);if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))return null;@@ -103060,8 +103862,8 @@ async function isSessionInBoulderLineage(input) {// packages/omo-opencode/src/hooks/atlas/session-last-agent.tsinit_shared();init_compaction_marker();-import { readFileSync as readFileSync20, readdirSync as readdirSync9 } from "node:fs";-import { join as join68 } from "node:path";+import { readFileSync as readFileSync23, readdirSync as readdirSync10 } from "node:fs";+import { join as join71 } from "node:path";var defaultSessionLastAgentDeps = {getMessageDir,isSqliteBackend,@@ -103119,9 +103921,9 @@ async function getLastAgentFromSession(sessionID, client, deps = {}) {if (!messageDir)return null;try {- const messages = readdirSync9(messageDir).filter((fileName) => fileName.endsWith(".json")).map((fileName) => {+ const messages = readdirSync10(messageDir).filter((fileName) => fileName.endsWith(".json")).map((fileName) => {try {- const content = readFileSync20(join68(messageDir, fileName), "utf-8");+ const content = readFileSync23(join71(messageDir, fileName), "utf-8");const parsed = JSON.parse(content);return {fileName,@@ -103164,8 +103966,8 @@ init_agent_display_names();// packages/omo-opencode/src/hooks/ralph-loop/storage.tsinit_frontmatter2();-import { existsSync as existsSync39, readFileSync as readFileSync21, writeFileSync as writeFileSync8, unlinkSync as unlinkSync6, mkdirSync as mkdirSync14 } from "node:fs";-import { dirname as dirname26, join as join69 } from "node:path";+import { existsSync as existsSync41, readFileSync as readFileSync24, writeFileSync as writeFileSync9, unlinkSync as unlinkSync6, mkdirSync as mkdirSync15 } from "node:fs";+import { dirname as dirname28, join as join72 } from "node:path";// packages/omo-opencode/src/hooks/ralph-loop/constants.tsvar DEFAULT_STATE_FILE = ".omo/ralph-loop.local.md";@@ -103174,15 +103976,15 @@ var DEFAULT_COMPLETION_PROMISE = "DONE";// packages/omo-opencode/src/hooks/ralph-loop/storage.tsfunction getStateFilePath(directory, customPath) {- return customPath ? join69(directory, customPath) : join69(directory, DEFAULT_STATE_FILE);+ return customPath ? join72(directory, customPath) : join72(directory, DEFAULT_STATE_FILE);}function readState(directory, customPath) {const filePath = getStateFilePath(directory, customPath);- if (!existsSync39(filePath)) {+ if (!existsSync41(filePath)) {return null;}try {- const content = readFileSync21(filePath, "utf-8");+ const content = readFileSync24(filePath, "utf-8");const { data, body } = parseFrontmatter(content);const active = data.active;const iteration = data.iteration;@@ -104274,14 +105076,14 @@ async function getLocalVersion(options = {}) {}}// packages/omo-opencode/src/cli/doctor/checks/system.ts-import { existsSync as existsSync50, readFileSync as readFileSync31 } from "node:fs";+import { existsSync as existsSync52, readFileSync as readFileSync34 } from "node:fs";// packages/omo-opencode/src/cli/doctor/checks/system-binary.tsinit_extract_semver();init_bun_which_shim();-import { existsSync as existsSync47, accessSync as accessSync4, constants as constants12 } from "node:fs";-import { homedir as homedir15 } from "node:os";-import { join as join76 } from "node:path";+import { existsSync as existsSync49, accessSync as accessSync4, constants as constants12 } from "node:fs";+import { homedir as homedir16 } from "node:os";+import { join as join79 } from "node:path";// packages/omo-opencode/src/cli/doctor/framework/spawn-with-timeout.tsinit_spawn_with_windows_hide();@@ -104368,22 +105170,22 @@ function isExecutable2(path) {}}function getDesktopAppPaths(platform) {- const home = homedir15();+ const home = homedir16();switch (platform) {case "darwin":return ["/Applications/OpenCode.app/Contents/MacOS/OpenCode",- join76(home, "Applications", "OpenCode.app", "Contents", "MacOS", "OpenCode")+ join79(home, "Applications", "OpenCode.app", "Contents", "MacOS", "OpenCode")];case "win32": {const programFiles = process.env.ProgramFiles;const localAppData = process.env.LOCALAPPDATA;const paths = [];if (programFiles) {- paths.push(join76(programFiles, "OpenCode", "OpenCode.exe"));+ paths.push(join79(programFiles, "OpenCode", "OpenCode.exe"));}if (localAppData) {- paths.push(join76(localAppData, "OpenCode", "OpenCode.exe"));+ paths.push(join79(localAppData, "OpenCode", "OpenCode.exe"));}return paths;}@@ -104391,8 +105193,8 @@ function getDesktopAppPaths(platform) {return ["/usr/bin/opencode","/usr/lib/opencode/opencode",- join76(home, "Applications", "opencode-desktop-linux-x86_64.AppImage"),- join76(home, "Applications", "opencode-desktop-linux-aarch64.AppImage")+ join79(home, "Applications", "opencode-desktop-linux-x86_64.AppImage"),+ join79(home, "Applications", "opencode-desktop-linux-aarch64.AppImage")];default:return [];@@ -104404,7 +105206,7 @@ function buildVersionCommand(binaryPath, platform) {}return [binaryPath, "--version"];}-function findDesktopBinary(platform = process.platform, checkExists = existsSync47) {+function findDesktopBinary(platform = process.platform, checkExists = existsSync49) {for (const desktopPath of getDesktopAppPaths(platform)) {if (checkExists(desktopPath)) {return { binary: "opencode", path: desktopPath };@@ -104412,7 +105214,7 @@ function findDesktopBinary(platform = process.platform, checkExists = existsSync}return null;}-async function findOpenCodeBinary(platform = process.platform, checkExists = existsSync47) {+async function findOpenCodeBinary(platform = process.platform, checkExists = existsSync49) {for (const binary of OPENCODE_BINARIES2) {const path = bunWhich(binary);if (path && checkExists(path)) {@@ -104424,7 +105226,7 @@ async function findOpenCodeBinary(platform = process.platform, checkExists = exiconst candidates = getCommandCandidates2(platform);for (const entry of pathEnv.split(delimiter).filter(Boolean)) {for (const command of candidates) {- const fullPath = join76(entry, command);+ const fullPath = join79(entry, command);if (checkExists(fullPath) && isExecutable2(fullPath)) {return { binary: command, path: fullPath };}@@ -104470,12 +105272,12 @@ function compareVersions3(current, minimum) {// packages/omo-opencode/src/cli/doctor/checks/system-plugin.tsinit_shared();-import { existsSync as existsSync48, readFileSync as readFileSync29 } from "node:fs";+import { existsSync as existsSync50, readFileSync as readFileSync32 } from "node:fs";function detectConfigPath() {const paths = getOpenCodeConfigPaths({ binary: "opencode", version: null });- if (existsSync48(paths.configJsonc))+ if (existsSync50(paths.configJsonc))return paths.configJsonc;- if (existsSync48(paths.configJson))+ if (existsSync50(paths.configJson))return paths.configJson;return null;}@@ -104523,7 +105325,7 @@ function getPluginInfo() {};}try {- const content = readFileSync29(configPath, "utf-8");+ const content = readFileSync32(configPath, "utf-8");const parsedConfig = parseJsonc(content);const pluginEntry = findPluginEntry2(parsedConfig.plugin ?? []);if (!pluginEntry) {@@ -104565,39 +105367,39 @@ init_file_utils2();init_checker();init_auto_update_checker();init_package_json_locator();-import { existsSync as existsSync49, readFileSync as readFileSync30, readdirSync as readdirSync11 } from "node:fs";+import { existsSync as existsSync51, readFileSync as readFileSync33, readdirSync as readdirSync12 } from "node:fs";import { createRequire as createRequire2 } from "node:module";-import { homedir as homedir16 } from "node:os";-import { join as join77 } from "node:path";+import { homedir as homedir17 } from "node:os";+import { join as join80 } from "node:path";import { fileURLToPath as fileURLToPath6 } from "node:url";init_shared();function getPlatformDefaultCacheDir(platform = process.platform) {if (platform === "darwin")- return join77(homedir16(), "Library", "Caches");+ return join80(homedir17(), "Library", "Caches");if (platform === "win32")- return process.env.LOCALAPPDATA ?? join77(homedir16(), "AppData", "Local");- return join77(homedir16(), ".cache");+ return process.env.LOCALAPPDATA ?? join80(homedir17(), "AppData", "Local");+ return join80(homedir17(), ".cache");}function resolveOpenCodeCacheDir() {const xdgCacheHome = process.env.XDG_CACHE_HOME;if (xdgCacheHome)- return join77(xdgCacheHome, "opencode");+ return join80(xdgCacheHome, "opencode");const fromShared = getOpenCodeCacheDir();- const platformDefault = join77(getPlatformDefaultCacheDir(), "opencode");- if (existsSync49(fromShared) || !existsSync49(platformDefault))+ const platformDefault = join80(getPlatformDefaultCacheDir(), "opencode");+ if (existsSync51(fromShared) || !existsSync51(platformDefault))return fromShared;return platformDefault;}function resolveExistingDir(dirPath) {- if (!existsSync49(dirPath))+ if (!existsSync51(dirPath))return dirPath;return resolveSymlink(dirPath);}function readPackageJson(filePath) {- if (!existsSync49(filePath))+ if (!existsSync51(filePath))return null;try {- const content = readFileSync30(filePath, "utf-8");+ const content = readFileSync33(filePath, "utf-8");return parseJsonc(content);} catch (error) {if (!(error instanceof Error)) {@@ -104615,26 +105417,26 @@ function normalizeVersion(value) {function createPackageCandidates(rootDir) {return ACCEPTED_PACKAGE_NAMES.map((packageName) => ({packageName,- installedPackagePath: join77(rootDir, "node_modules", packageName, "package.json")+ installedPackagePath: join80(rootDir, "node_modules", packageName, "package.json")}));}function createTaggedInstallCandidates(rootDir) {- const packagesDir = join77(rootDir, "packages");- if (!existsSync49(packagesDir))+ const packagesDir = join80(rootDir, "packages");+ if (!existsSync51(packagesDir))return [];const candidates = [];- for (const entryName of readdirSync11(packagesDir).sort()) {+ for (const entryName of readdirSync12(packagesDir).sort()) {const packageName = ACCEPTED_PACKAGE_NAMES.find((name) => entryName.startsWith(`${name}@`));if (packageName === undefined)continue;- const installDir = join77(packagesDir, entryName);+ const installDir = join80(packagesDir, entryName);candidates.push({cacheDir: installDir,- cachePackagePath: join77(installDir, "package.json"),+ cachePackagePath: join80(installDir, "package.json"),packageCandidates: [{packageName,- installedPackagePath: join77(installDir, "node_modules", packageName, "package.json")+ installedPackagePath: join80(installDir, "node_modules", packageName, "package.json")}]});@@ -104642,7 +105444,7 @@ function createTaggedInstallCandidates(rootDir) {return candidates;}function selectInstalledPackage(candidate) {- return candidate.packageCandidates.find((packageCandidate) => existsSync49(packageCandidate.installedPackagePath)) ?? candidate.packageCandidates[0];+ return candidate.packageCandidates.find((packageCandidate) => existsSync51(packageCandidate.installedPackagePath)) ?? candidate.packageCandidates[0];}function getExpectedVersion(cachePackage, packageName) {return normalizeVersion(cachePackage?.dependencies?.[packageName]) ?? normalizeVersion(cachePackage?.dependencies?.[PACKAGE_NAME]);@@ -104653,7 +105455,7 @@ function resolveInstalledPackageJsonPath() {for (const packageName of ACCEPTED_PACKAGE_NAMES) {try {const packageJsonPath = require2.resolve(`${packageName}/package.json`);- if (existsSync49(packageJsonPath)) {+ if (existsSync51(packageJsonPath)) {return { packageName, packageJsonPath };}} catch {@@ -104679,22 +105481,22 @@ function getLoadedPluginVersion() {const candidates = [{cacheDir: configDir,- cachePackagePath: join77(configDir, "package.json"),+ cachePackagePath: join80(configDir, "package.json"),packageCandidates: createPackageCandidates(configDir)},...createTaggedInstallCandidates(configDir),{cacheDir,- cachePackagePath: join77(cacheDir, "package.json"),+ cachePackagePath: join80(cacheDir, "package.json"),packageCandidates: createPackageCandidates(cacheDir)},...createTaggedInstallCandidates(cacheDir)];- const selectedCandidate = candidates.find((candidate) => candidate.packageCandidates.some((packageCandidate) => existsSync49(packageCandidate.installedPackagePath))) ?? candidates[0];+ const selectedCandidate = candidates.find((candidate) => candidate.packageCandidates.some((packageCandidate) => existsSync51(packageCandidate.installedPackagePath))) ?? candidates[0];const { cacheDir: selectedDir, cachePackagePath } = selectedCandidate;const selectedPackage = selectInstalledPackage(selectedCandidate);const candidateInstalledPath = selectedPackage.installedPackagePath;- const candidateExists = existsSync49(candidateInstalledPath);+ const candidateExists = existsSync51(candidateInstalledPath);const resolvedFallback = candidateExists ? null : resolveInstalledPackageJsonPath();const installedPackagePath = resolvedFallback?.packageJsonPath ?? candidateInstalledPath;const resolvedPackageName = resolvedFallback?.packageName ?? selectedPackage.packageName;@@ -104730,8 +105532,8 @@ var defaultDeps5 = {getLoadedPluginVersion,getLatestPluginVersion,getSuggestedInstallTag,- configExists: existsSync50,- readConfigFile: (path) => readFileSync31(path, "utf-8"),+ configExists: existsSync52,+ readConfigFile: (path) => readFileSync34(path, "utf-8"),parseConfigContent: (content) => parseJsonc(content)};function isConfigValid(configPath, deps) {@@ -104876,26 +105678,26 @@ async function checkSystem(deps = defaultDeps5) {// packages/omo-opencode/src/cli/doctor/checks/model-resolution-cache.tsinit_shared();-import { existsSync as existsSync51, readFileSync as readFileSync32 } from "node:fs";-import { homedir as homedir17 } from "node:os";-import { join as join78 } from "node:path";+import { existsSync as existsSync53, readFileSync as readFileSync35 } from "node:fs";+import { homedir as homedir18 } from "node:os";+import { join as join81 } from "node:path";function getUserConfigDir2() {const xdgConfig = process.env.XDG_CONFIG_HOME;if (xdgConfig)- return join78(xdgConfig, "opencode");- return join78(homedir17(), ".config", "opencode");+ return join81(xdgConfig, "opencode");+ return join81(homedir18(), ".config", "opencode");}function loadCustomProviderNames() {const configDir = getUserConfigDir2();const candidatePaths = [- join78(configDir, "opencode.json"),- join78(configDir, "opencode.jsonc")+ join81(configDir, "opencode.json"),+ join81(configDir, "opencode.jsonc")];for (const configPath of candidatePaths) {- if (!existsSync51(configPath))+ if (!existsSync53(configPath))continue;try {- const content = readFileSync32(configPath, "utf-8");+ const content = readFileSync35(configPath, "utf-8");const data = parseJsonc(content);if (data?.provider && typeof data.provider === "object") {return Object.keys(data.provider);@@ -104910,16 +105712,16 @@ function loadCustomProviderNames() {return [];}function loadAvailableModelsFromCache() {- const cacheFile = join78(getOpenCodeCacheDir(), "models.json");+ const cacheFile = join81(getOpenCodeCacheDir(), "models.json");const customProviders = loadCustomProviderNames();- if (!existsSync51(cacheFile)) {+ if (!existsSync53(cacheFile)) {if (customProviders.length > 0) {return { providers: customProviders, modelCount: 0, cacheExists: true };}return { providers: [], modelCount: 0, cacheExists: false };}try {- const content = readFileSync32(cacheFile, "utf-8");+ const content = readFileSync35(cacheFile, "utf-8");const data = parseJsonc(content);const cacheProviders = Object.keys(data);let modelCount = 0;@@ -104972,7 +105774,7 @@ function loadOmoConfig2() {// packages/omo-opencode/src/cli/doctor/checks/model-resolution-details.tsinit_shared();-import { join as join79 } from "node:path";+import { join as join82 } from "node:path";// packages/omo-opencode/src/cli/doctor/checks/model-resolution-variant.tsfunction formatModelWithVariant(model, variant) {@@ -105014,7 +105816,7 @@ function formatCapabilityResolutionLabel(mode) {}function buildModelResolutionDetails(options) {const details = [];- const cacheFile = join79(getOpenCodeCacheDir(), "models.json");+ const cacheFile = join82(getOpenCodeCacheDir(), "models.json");details.push("═══ Available Models (from cache) ═══");details.push("");if (options.available.cacheExists) {@@ -105170,9 +105972,9 @@ async function checkModels() {// packages/omo-opencode/src/cli/doctor/checks/legacy-config-leftovers.tsinit_config_migration();-import { posix as posix10, win32 as win326 } from "node:path";+import { posix as posix11, win32 as win327 } from "node:path";function findLegacyConfigLeftovers(options) {- const pathOperations = options.pathOperations ?? (process.platform === "win32" ? win326 : posix10);+ const pathOperations = options.pathOperations ?? (process.platform === "win32" ? win327 : posix11);const paths = createLegacyConfigMigrationPlans({cwd: options.cwd,environment: options.environment ?? process.env,@@ -105354,8 +106156,8 @@ async function checkBrowserProvider() {init_src4();init_main();init_config_migration();-import { existsSync as existsSync52, readFileSync as readFileSync33 } from "node:fs";-import { join as join80 } from "node:path";+import { existsSync as existsSync54, readFileSync as readFileSync36 } from "node:fs";+import { join as join83 } from "node:path";var CANONICAL_REPLACEMENT = new Map([["variant", "reasoning"],["reasoningEffort", "reasoning"],@@ -105416,16 +106218,16 @@ function userConfigPaths() {const home = process.env.HOME ?? process.env.USERPROFILE;if (home === undefined || home.length === 0)return [];- return [join80(home, ".omo", "omo.jsonc"), join80(home, ".omo", "omo.json")];+ return [join83(home, ".omo", "omo.jsonc"), join83(home, ".omo", "omo.json")];}async function checkDeprecatedReasoningKeys() {const issues = [];const scanned = [];for (const configPath of userConfigPaths()) {- if (!existsSync52(configPath))+ if (!existsSync54(configPath))continue;scanned.push(configPath);- const parsed = parse2(readFileSync33(configPath, "utf-8"));+ const parsed = parse2(readFileSync36(configPath, "utf-8"));issues.push(...collectIssues(configPath, parsed, "", migrateFixSuffix(parsed)));}return {@@ -105439,39 +106241,39 @@ async function checkDeprecatedReasoningKeys() {// packages/omo-opencode/src/cli/doctor/checks/dependencies.tsinit_src();-import { existsSync as existsSync53 } from "node:fs";+import { existsSync as existsSync55 } from "node:fs";import { createRequire as createRequire3 } from "node:module";-import { homedir as homedir19 } from "node:os";-import { dirname as dirname31, join as join83 } from "node:path";+import { homedir as homedir20 } from "node:os";+import { dirname as dirname33, join as join86 } from "node:path";// packages/omo-opencode/src/hooks/comment-checker/downloader.ts-import { join as join82 } from "path";-import { homedir as homedir18, tmpdir as tmpdir4 } from "os";+import { join as join85 } from "path";+import { homedir as homedir19, tmpdir as tmpdir4 } from "os";// packages/comment-checker-core/src/release.ts-import { join as join81 } from "node:path";+import { join as join84 } from "node:path";function commentCheckerBinaryName(platform) {return platform === "win32" ? "comment-checker.exe" : "comment-checker";}function commentCheckerCacheDir(input) {if (input.platform === "win32") {const localAppData = input.env.LOCALAPPDATA || input.env.APPDATA;- const base = localAppData || join81(input.homedir, "AppData", "Local");- return join81(base, input.cacheDirName, "bin");+ const base = localAppData || join84(input.homedir, "AppData", "Local");+ return join84(base, input.cacheDirName, "bin");}- const base = input.env.XDG_CACHE_HOME || join81(input.homedir, ".cache");- return join81(base, input.cacheDirName, "bin");+ const base = input.env.XDG_CACHE_HOME || join84(input.homedir, ".cache");+ return join84(base, input.cacheDirName, "bin");}// packages/omo-opencode/src/hooks/comment-checker/downloader.tsinit_binary_downloader();init_logger2();init_plugin_identity();var DEBUG = process.env.COMMENT_CHECKER_DEBUG === "1";-var DEBUG_FILE = join82(tmpdir4(), "comment-checker-debug.log");+var DEBUG_FILE = join85(tmpdir4(), "comment-checker-debug.log");function getCacheDir2() {return commentCheckerCacheDir({platform: process.platform,env: process.env,- homedir: homedir18(),+ homedir: homedir19(),cacheDirName: CACHE_DIR_NAME});}@@ -105523,7 +106325,7 @@ async function getBinaryVersion(binary) {}}async function checkAstGrepCli() {- const runtimeDir = astGrepRuntimeDir(join83(homedir19(), ".omo"));+ const runtimeDir = astGrepRuntimeDir(join86(homedir20(), ".omo"));const sgPath = findSgBinarySync({ runtimeDir });if (sgPath === null) {return {@@ -105552,12 +106354,12 @@ function findCommentCheckerPackageBinary(baseDirOverride, resolvePackageJsonPathconst binaryName = process.platform === "win32" ? "comment-checker.exe" : "comment-checker";const platformKey = `${process.platform}-${process.arch === "x64" ? "x64" : process.arch}`;try {- const packageDir = baseDirOverride ?? dirname31(resolvePackageJsonPath());- const vendorPath = join83(packageDir, "vendor", platformKey, binaryName);- if (existsSync53(vendorPath))+ const packageDir = baseDirOverride ?? dirname33(resolvePackageJsonPath());+ const vendorPath = join86(packageDir, "vendor", platformKey, binaryName);+ if (existsSync55(vendorPath))return vendorPath;- const binPath = join83(packageDir, "bin", binaryName);- if (existsSync53(binPath))+ const binPath = join86(packageDir, "bin", binaryName);+ if (existsSync55(binPath))return binPath;} catch (error) {if (!(error instanceof Error) && !isModuleResolutionFailure(error))@@ -105703,8 +106505,8 @@ async function getGhCliInfo(dependencies = {}) {// packages/omo-opencode/src/mcp/lsp.tsinit_zod();init_opencode_config_dir();-import { existsSync as existsSync54, readFileSync as readFileSync34 } from "node:fs";-import { delimiter as delimiter3, dirname as dirname32, resolve as resolve22 } from "node:path";+import { existsSync as existsSync56, readFileSync as readFileSync37 } from "node:fs";+import { delimiter as delimiter3, dirname as dirname34, resolve as resolve23 } from "node:path";import { fileURLToPath as fileURLToPath7 } from "node:url";// packages/omo-opencode/src/mcp/cli-suffix.ts@@ -105717,7 +106519,7 @@ function hasCliSuffix(candidatePath, suffix) {// packages/omo-opencode/src/mcp/runtime-executable.tsinit_bun_which_shim();-import { basename as basename10 } from "node:path";+import { basename as basename11 } from "node:path";var NODE_EXECUTABLE_NAMES = new Set(["node", "node.exe"]);function isUnsafeCommandName2(commandName) {if (commandName.length === 0)@@ -105733,7 +106535,7 @@ function isUnsafeCommandName2(commandName) {return false;}function isNodeExecPath(execPath) {- return NODE_EXECUTABLE_NAMES.has(basename10(execPath).toLowerCase());+ return NODE_EXECUTABLE_NAMES.has(basename11(execPath).toLowerCase());}function resolveRuntimeExecutable(commandName, options = {}) {if (isUnsafeCommandName2(commandName)) {@@ -105751,7 +106553,7 @@ function resolveRuntimeExecutable(commandName, options = {}) {}// packages/omo-opencode/src/mcp/shared/ancestor-cli-resolver.ts-import { resolve as resolve21 } from "node:path";+import { resolve as resolve22 } from "node:path";function resolveJavaScriptRuntime(resolveExecutable) {const node = resolveExecutable("node");return node.available ? node : resolveExecutable("bun");@@ -105759,9 +106561,9 @@ function resolveJavaScriptRuntime(resolveExecutable) {function createAncestorCliCandidates(options) {const candidates = [];const seenPaths = new Set;- let currentDirectory = resolve21(options.startDirectory);+ let currentDirectory = resolve22(options.startDirectory);while (true) {- const distCliPath = resolve21(currentDirectory, options.packageRel, options.distCliRel);+ const distCliPath = resolve22(currentDirectory, options.packageRel, options.distCliRel);if (!seenPaths.has(distCliPath)) {const runtime = resolveJavaScriptRuntime(options.resolveExecutable);seenPaths.add(distCliPath);@@ -105773,7 +106575,7 @@ function createAncestorCliCandidates(options) {runtimeAvailable: runtime.available});}- const sourceCliPath = resolve21(currentDirectory, options.packageRel, options.sourceCliRel);+ const sourceCliPath = resolve22(currentDirectory, options.packageRel, options.sourceCliRel);if (!seenPaths.has(sourceCliPath)) {const runtime = options.resolveExecutable("bun");const sourceCandidateAvailable = options.isSourceCandidateAvailable?.({@@ -105790,7 +106592,7 @@ function createAncestorCliCandidates(options) {runtimeAvailable: runtime.available});}- const parentDirectory = resolve21(currentDirectory, "..");+ const parentDirectory = resolve22(currentDirectory, "..");if (parentDirectory === currentDirectory)return candidates;currentDirectory = parentDirectory;@@ -105835,7 +106637,7 @@ var LSP_BOOTSTRAP_SCRIPT = [].join(";");function getModuleDirectory(moduleUrl) {try {- return dirname32(fileURLToPath7(moduleUrl));+ return dirname34(fileURLToPath7(moduleUrl));} catch (error) {if (!(error instanceof Error))throw error;@@ -105843,11 +106645,11 @@ function getModuleDirectory(moduleUrl) {}}function findBootstrapRoot(candidates, pathExists) {- return candidates.find((candidate) => pathExists(resolve22(candidate.root, "package.json")))?.root ?? process.cwd();+ return candidates.find((candidate) => pathExists(resolve23(candidate.root, "package.json")))?.root ?? process.cwd();}function readDaemonPackageVersion(root) {try {- const packageJson = JSON.parse(readFileSync34(resolve22(root, PACKAGE_REL, "package.json"), "utf-8"));+ const packageJson = JSON.parse(readFileSync37(resolve23(root, PACKAGE_REL, "package.json"), "utf-8"));return DaemonPackageSchema.parse(packageJson).version;} catch (error) {if (!(error instanceof Error))@@ -105859,17 +106661,17 @@ function createBootstrapCandidate(root, pathExists, resolveExecutable) {const runtime = resolveJavaScriptRuntime(resolveExecutable);const bun = resolveExecutable("bun");const npm = resolveExecutable("npm");- const packageManifestPath = resolve22(root, PACKAGE_REL, "package.json");+ const packageManifestPath = resolve23(root, PACKAGE_REL, "package.json");return {command: [runtime.command, "-e", LSP_BOOTSTRAP_SCRIPT, root, npm.command, bun.command],root,- path: resolve22(root, PACKAGE_REL, DIST_CLI_REL),+ path: resolve23(root, PACKAGE_REL, DIST_CLI_REL),exists: runtime.available && npm.available && pathExists(packageManifestPath),runtimeAvailable: runtime.available};}function resolveLspCommand(options = {}) {- const pathExists = options.exists ?? existsSync54;+ const pathExists = options.exists ?? existsSync56;const resolveExecutable = options.resolveExecutable ?? resolveRuntimeExecutable;const moduleDirectory = getModuleDirectory(options.moduleUrl ?? import.meta.url);const candidates = moduleDirectory ? createAncestorCliCandidates({@@ -105879,7 +106681,7 @@ function resolveLspCommand(options = {}) {sourceCliRel: SOURCE_CLI_REL,pathExists,resolveExecutable,- isSourceCandidateAvailable: ({ root }) => pathExists(resolve22(root, LSP_TOOLS_PACKAGE_REL, DIST_CLI_REL)) && readDaemonPackageVersion(root) !== null+ isSourceCandidateAvailable: ({ root }) => pathExists(resolve23(root, LSP_TOOLS_PACKAGE_REL, DIST_CLI_REL)) && readDaemonPackageVersion(root) !== null}) : [];const distCandidate = candidates.find((candidate) => hasCliSuffix(candidate.path, DIST_CLI_REL) && candidate.exists);if (distCandidate) {@@ -105893,7 +106695,7 @@ function resolveLspCommand(options = {}) {}function createLspMcpConfig(options = {}) {const resolvedCommand = resolveLspCommand(options);- const cwd = resolve22(options.cwd ?? process.cwd());+ const cwd = resolve23(options.cwd ?? process.cwd());const configDir = getOpenCodeConfigDir({ binary: "opencode" });const sourceVersion = hasCliSuffix(resolvedCommand.path, SOURCE_CLI_REL) ? readDaemonPackageVersion(resolvedCommand.root) : null;return {@@ -105903,9 +106705,9 @@ function createLspMcpConfig(options = {}) {cwd,environment: {LSP_TOOLS_MCP_CWD: cwd,- LSP_TOOLS_MCP_PROJECT_CONFIG: PROJECT_LSP_CONFIGS.map((configPath) => resolve22(cwd, configPath)).join(delimiter3),- LSP_TOOLS_MCP_USER_CONFIG: resolve22(configDir, "lsp.json"),- LSP_TOOLS_MCP_INSTALL_DECISIONS: resolve22(configDir, "lsp-install-decisions.json"),+ LSP_TOOLS_MCP_PROJECT_CONFIG: PROJECT_LSP_CONFIGS.map((configPath) => resolve23(cwd, configPath)).join(delimiter3),+ LSP_TOOLS_MCP_USER_CONFIG: resolve23(configDir, "lsp.json"),+ LSP_TOOLS_MCP_INSTALL_DECISIONS: resolve23(configDir, "lsp-install-decisions.json"),...sourceVersion ? {[OMO_LSP_DAEMON_CLI]: resolvedCommand.path,[OMO_LSP_DAEMON_VERSION]: sourceVersion@@ -105930,24 +106732,24 @@ function getInstalledLspServers(options = {}) {// packages/omo-opencode/src/cli/doctor/checks/tools-mcp.tsinit_shared();-import { existsSync as existsSync55, readFileSync as readFileSync35 } from "node:fs";-import { homedir as homedir20 } from "node:os";-import { join as join84 } from "node:path";+import { existsSync as existsSync57, readFileSync as readFileSync38 } from "node:fs";+import { homedir as homedir21 } from "node:os";+import { join as join87 } from "node:path";var BUILTIN_MCP_SERVERS = ["websearch", "context7", "grep_app", "lsp"];function getMcpConfigPaths() {return [- join84(homedir20(), ".claude", ".mcp.json"),- join84(process.cwd(), ".mcp.json"),- join84(process.cwd(), ".claude", ".mcp.json")+ join87(homedir21(), ".claude", ".mcp.json"),+ join87(process.cwd(), ".mcp.json"),+ join87(process.cwd(), ".claude", ".mcp.json")];}function loadUserMcpConfig() {const servers = {};for (const configPath of getMcpConfigPaths()) {- if (!existsSync55(configPath))+ if (!existsSync57(configPath))continue;try {- const content = readFileSync35(configPath, "utf-8");+ const content = readFileSync38(configPath, "utf-8");const config = parseJsonc(content);if (config.mcpServers) {Object.assign(servers, config.mcpServers);@@ -106082,17 +106884,17 @@ async function checkTools() {// packages/omo-opencode/src/cli/doctor/checks/telemetry.tsinit_src5();-import { existsSync as existsSync56, readFileSync as readFileSync36 } from "node:fs";+import { existsSync as existsSync58, readFileSync as readFileSync39 } from "node:fs";function isTelemetryState(value) {return value !== null && typeof value === "object" && !Array.isArray(value);}function readLastActiveDay(stateFilePath) {- if (!existsSync56(stateFilePath)) {+ if (!existsSync58(stateFilePath)) {return "never";}let parsed;try {- parsed = JSON.parse(readFileSync36(stateFilePath, "utf-8"));+ parsed = JSON.parse(readFileSync39(stateFilePath, "utf-8"));} catch (error) {if (error instanceof Error) {return "unreadable";@@ -106150,17 +106952,17 @@ async function probeBinary(cmd, args, spawnImpl) {}// packages/team-core/src/team-registry/paths.ts-import { homedir as homedir21 } from "node:os";+import { homedir as homedir22 } from "node:os";import path13 from "node:path";function resolveBaseDir(config) {- return expandHomeDirectory(config.base_dir ?? path13.join(homedir21(), ".omo"));+ return expandHomeDirectory(config.base_dir ?? path13.join(homedir22(), ".omo"));}function expandHomeDirectory(directoryPath) {if (directoryPath === "~") {- return homedir21();+ return homedir22();}if (directoryPath.startsWith("~/") || directoryPath.startsWith("~\\")) {- return path13.join(homedir21(), directoryPath.slice(2));+ return path13.join(homedir22(), directoryPath.slice(2));}return directoryPath;}@@ -106176,7 +106978,7 @@ async function checkTeamMode() {const deps = await checkTeamModeDependencies(teamModeConfig);const baseDir = resolveBaseDir(teamModeConfig);const [baseDirExists, teamCount, runtimeCount] = await Promise.all([- pathExists(baseDir),+ pathExists2(baseDir),safeCount(path14.join(baseDir, "teams")),safeCount(path14.join(baseDir, "runtime"))]);@@ -106203,7 +107005,7 @@ async function safeCount(dir) {throw error;}}-async function pathExists(dir) {+async function pathExists2(dir) {try {const stats = await fs10.stat(dir);return stats.isDirectory();@@ -106217,10 +107019,10 @@ async function pathExists(dir) {// packages/omo-opencode/src/cli/doctor/checks/codex.tsinit_src();-import { existsSync as existsSync57 } from "node:fs";+import { existsSync as existsSync59 } from "node:fs";import { lstat as lstat16, readdir as readdir14, readFile as readFile28 } from "node:fs/promises";-import { homedir as homedir22 } from "node:os";-import { basename as basename11, join as join85, resolve as resolve23 } from "node:path";+import { homedir as homedir23 } from "node:os";+import { basename as basename12, join as join88, resolve as resolve24 } from "node:path";// packages/omo-opencode/package.jsonvar package_default3 = {name: "@oh-my-opencode/omo-opencode",@@ -106290,13 +107092,13 @@ var CODEX_BIN_NAMES = ["omo-git-bash-hook"];async function gatherCodexSummary(deps = {}) {- const codexHome = resolve23(deps.codexHome ?? process.env.CODEX_HOME ?? join85(homedir22(), ".codex"));+ const codexHome = resolve24(deps.codexHome ?? process.env.CODEX_HOME ?? join88(homedir23(), ".codex"));const binDir = resolveCodexInstallerBinDir({ binDir: deps.binDir, codexHome, env: process.env });const detection = await (deps.detectCodexInstallation ?? detectCodexInstallation)();const pluginRoot = await resolveInstalledPluginRoot(codexHome);- const manifest = pluginRoot === null ? null : await readJson(join85(pluginRoot, ".codex-plugin", "plugin.json"));- const installSnapshot = pluginRoot === null ? null : await readJson(join85(pluginRoot, "lazycodex-install.json"));- const configPath = join85(codexHome, "config.toml");+ const manifest = pluginRoot === null ? null : await readJson(join88(pluginRoot, ".codex-plugin", "plugin.json"));+ const installSnapshot = pluginRoot === null ? null : await readJson(join88(pluginRoot, "lazycodex-install.json"));+ const configPath = join88(codexHome, "config.toml");const pluginVersion = stringField(manifest, "version");return {codexPath: detection.found && "path" in detection ? detection.path : null,@@ -106353,7 +107155,7 @@ function buildCodexIssues(summary) {if (summary.pluginRoot === null) {issues.push({title: "OMO Codex plugin is not installed",- description: `Expected cached plugin at ${join85("plugins", "cache", MARKETPLACE_NAME, PLUGIN_NAME2, DEFAULT_PLUGIN_VERSION)} under CODEX_HOME.`,+ description: `Expected cached plugin at ${join88("plugins", "cache", MARKETPLACE_NAME, PLUGIN_NAME2, DEFAULT_PLUGIN_VERSION)} under CODEX_HOME.`,fix: "Run: npx lazycodex-ai install",severity: "error",affects: ["plugin loading"]@@ -106418,15 +107220,15 @@ function buildCodexIssues(summary) {return issues;}async function resolveInstalledPluginRoot(codexHome) {- const pluginRoot = join85(codexHome, "plugins", "cache", MARKETPLACE_NAME, PLUGIN_NAME2);- if (!existsSync57(pluginRoot))+ const pluginRoot = join88(codexHome, "plugins", "cache", MARKETPLACE_NAME, PLUGIN_NAME2);+ if (!existsSync59(pluginRoot))return null;const versions = await readdir14(pluginRoot, { withFileTypes: true });const candidates = versions.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(compareVersionsDescending);- return candidates.length === 0 ? null : join85(pluginRoot, candidates[0] ?? DEFAULT_PLUGIN_VERSION);+ return candidates.length === 0 ? null : join88(pluginRoot, candidates[0] ?? DEFAULT_PLUGIN_VERSION);}async function readCodexConfigSummary(configPath) {- if (!existsSync57(configPath)) {+ if (!existsSync59(configPath)) {return {exists: false,marketplaceConfigured: false,@@ -106451,17 +107253,17 @@ async function readCodexConfigSummary(configPath) {async function readLinkedBins(binDir) {const linked = [];for (const name of CODEX_BIN_NAMES) {- if (await pathExists2(join85(binDir, process.platform === "win32" ? `${name}.cmd` : name)))+ if (await pathExists3(join88(binDir, process.platform === "win32" ? `${name}.cmd` : name)))linked.push(name);}return linked;}async function readLinkedAgents(codexHome) {- const agentsDir = join85(codexHome, "agents");- if (!existsSync57(agentsDir))+ const agentsDir = join88(codexHome, "agents");+ if (!existsSync59(agentsDir))return [];const entries = await readdir14(agentsDir, { withFileTypes: true });- return entries.filter((entry) => entry.isFile() || entry.isSymbolicLink()).map((entry) => basename11(entry.name, ".toml")).sort();+ return entries.filter((entry) => entry.isFile() || entry.isSymbolicLink()).map((entry) => basename12(entry.name, ".toml")).sort();}async function readJson(path) {try {@@ -106558,7 +107360,7 @@ function compareVersionsDescending(left, right) {}return right.localeCompare(left);}-async function pathExists2(path) {+async function pathExists3(path) {try {await lstat16(path);return true;@@ -106590,8 +107392,8 @@ function resolveLatestVersion(input) {// packages/omo-opencode/src/cli/doctor/checks/codex-components.tsinit_src();import { readdir as readdir15, readFile as readFile29, stat as stat7 } from "node:fs/promises";-import { homedir as homedir23 } from "node:os";-import { dirname as dirname33, isAbsolute as isAbsolute13, join as join86, relative as relative9, resolve as resolve24, sep as sep9 } from "node:path";+import { homedir as homedir24 } from "node:os";+import { dirname as dirname35, isAbsolute as isAbsolute14, join as join89, relative as relative9, resolve as resolve25, sep as sep9 } from "node:path";var CODEX_COMPONENTS_CHECK_ID = "codex-components";var CODEX_COMPONENTS_CHECK_NAME = "codex-components";var PLUGIN_DATA_DIR_NAME = "omo-sisyphuslabs";@@ -106601,7 +107403,7 @@ async function checkCodexComponents(deps = {}) {const env = deps.env ?? process.env;const platform = deps.platform ?? process.platform;const arch = deps.arch ?? process.arch;- const codexHome = resolve24(deps.codexHome ?? env["CODEX_HOME"] ?? join86(homedir23(), ".codex"));+ const codexHome = resolve25(deps.codexHome ?? env["CODEX_HOME"] ?? join89(homedir24(), ".codex"));const summary = await gatherCodexSummary({ ...deps, codexHome });if (summary.pluginRoot === null) {return {@@ -106626,7 +107428,7 @@ async function checkCodexComponents(deps = {}) {});}const runtimeSgDir = runtimeSgDirectory(codexHome, platform, arch);- const runtimeSgPath = join86(runtimeSgDir, sgBinaryName(platform));+ const runtimeSgPath = join89(runtimeSgDir, sgBinaryName(platform));const sg = findSgBinarySync({arch,env,@@ -106665,8 +107467,8 @@ async function auditBundleTargets(pluginRoot) {const manifest = await readJson2(manifestPath);if (manifest === null || !isRecord18(manifest["mcpServers"]))continue;- const manifestRoot = dirname33(manifestPath);- const isRootManifest = resolve24(manifestRoot) === resolve24(pluginRoot);+ const manifestRoot = dirname35(manifestPath);+ const isRootManifest = resolve25(manifestRoot) === resolve25(pluginRoot);for (const server of Object.values(manifest["mcpServers"])) {if (!isRecord18(server) || !Array.isArray(server["args"]))continue;@@ -106686,7 +107488,7 @@ async function auditBundleTargets(pluginRoot) {continue;const commands = [];collectHookCommands(manifest, commands);- const hookPluginRoot = dirname33(dirname33(hookManifestPath));+ const hookPluginRoot = dirname35(dirname35(hookManifestPath));for (const command of commands) {for (const relativePath of extractPluginRootPaths(command)) {referencedCount += 1;@@ -106708,8 +107510,8 @@ function recordBrokenTarget(broken, classified, origin) {broken.push(entry);}async function classifyBundleTarget(bundleRoot, baseRoot, relativePath, allowEscape) {- const targetPath = resolve24(baseRoot, relativePath);- const bundleRootPath = resolve24(bundleRoot);+ const targetPath = resolve25(baseRoot, relativePath);+ const bundleRootPath = resolve25(bundleRoot);const bundleRootPrefix = bundleRootPath.endsWith(sep9) ? bundleRootPath : `${bundleRootPath}${sep9}`;if (targetPath !== bundleRootPath && !targetPath.startsWith(bundleRootPrefix)) {if (allowEscape)@@ -106725,7 +107527,7 @@ async function classifyBundleTarget(bundleRoot, baseRoot, relativePath, allowEsc}async function findHookManifestPaths(root) {const paths = await findManifestPaths(root, "hooks.json");- return paths.filter((path) => dirname33(path).endsWith(`${sep9}hooks`));+ return paths.filter((path) => dirname35(path).endsWith(`${sep9}hooks`));}async function findManifestPaths(root, manifestName) {let entries;@@ -106738,7 +107540,7 @@ async function findManifestPaths(root, manifestName) {for (const entry of entries) {if (entry.name === "node_modules" || entry.name === ".git")continue;- const entryPath = join86(root, entry.name);+ const entryPath = join89(root, entry.name);if (entry.isDirectory()) {paths.push(...await findManifestPaths(entryPath, manifestName));continue;@@ -106779,21 +107581,21 @@ function extractPluginRootPaths(command) {}function isPluginRuntimePathArg(arg) {const normalized = normalizePathSeparators(arg);- return normalized.endsWith(".js") && normalized.includes("/dist/") && (normalized.startsWith("./") || normalized.startsWith("../") || normalized.startsWith("components/") || normalized.startsWith("/") || isAbsolute13(arg));+ return normalized.endsWith(".js") && normalized.includes("/dist/") && (normalized.startsWith("./") || normalized.startsWith("../") || normalized.startsWith("components/") || normalized.startsWith("/") || isAbsolute14(arg));}function runtimeSgDirectory(codexHome, platform, arch) {- return join86(codexHome, "runtime", "ast-grep", runtimeSlug(platform, arch));+ return join89(codexHome, "runtime", "ast-grep", runtimeSlug(platform, arch));}function describeSgSource(sgPath, env, runtimeSgDir, platform) {const override = env[SG_PATH_ENV_KEY]?.trim();if (override !== undefined && override.length > 0 && sgPath === override)return `env override ${SG_PATH_ENV_KEY}`;- if (sgPath === join86(runtimeSgDir, sgBinaryName(platform)))+ if (sgPath === join89(runtimeSgDir, sgBinaryName(platform)))return "runtime dir";return "PATH";}async function readBootstrapStateSummary(codexHome) {- const statePath = join86(codexHome, "plugins", "data", PLUGIN_DATA_DIR_NAME, "bootstrap", "state.json");+ const statePath = join89(codexHome, "plugins", "data", PLUGIN_DATA_DIR_NAME, "bootstrap", "state.json");const raw = await readJson2(statePath);if (raw === null)return null;@@ -106869,24 +107671,24 @@ function isRecord18(value) {}// packages/omo-opencode/src/cli/doctor/checks/codex-runtime-wrapper.ts-import { existsSync as existsSync58 } from "node:fs";+import { existsSync as existsSync60 } from "node:fs";import { readFile as readFile30 } from "node:fs/promises";-import { homedir as homedir24 } from "node:os";-import { join as join87, resolve as resolve25 } from "node:path";+import { homedir as homedir25 } from "node:os";+import { join as join90, resolve as resolve26 } from "node:path";var RUNTIME_WRAPPER_MARKER2 = "OMO_GENERATED_RUNTIME_WRAPPER";var CHECK_NAME = "codex-runtime-wrapper";var REINSTALL_COMMAND = "npx --yes lazycodex-ai@latest install --no-tui";async function checkCodexRuntimeWrapper(deps = {}) {- const codexHome = resolve25(deps.codexHome ?? process.env.CODEX_HOME ?? join87(homedir24(), ".codex"));+ const codexHome = resolve26(deps.codexHome ?? process.env.CODEX_HOME ?? join90(homedir25(), ".codex"));const binDir = resolveCodexInstallerBinDir({ binDir: deps.binDir, codexHome, env: process.env });const platform = deps.platform ?? process.platform;- const wrapperPath = join87(binDir, platform === "win32" ? "omo-agent-toolkit.cmd" : "omo-agent-toolkit");- const legacyWrapperPath = join87(binDir, platform === "win32" ? "omo.cmd" : "omo");+ const wrapperPath = join90(binDir, platform === "win32" ? "omo-agent-toolkit.cmd" : "omo-agent-toolkit");+ const legacyWrapperPath = join90(binDir, platform === "win32" ? "omo.cmd" : "omo");const [wrapper, legacyWrapper] = await Promise.all([readRuntimeWrapper(wrapperPath), readRuntimeWrapper(legacyWrapperPath)]);const issues = [];if (wrapper?.includes(RUNTIME_WRAPPER_MARKER2) === true) {const targetPath = parseRuntimeTargetPath(wrapper);- if (targetPath !== null && !existsSync58(targetPath)) {+ if (targetPath !== null && !existsSync60(targetPath)) {issues.push({title: "omo-agent-toolkit runtime wrapper target is missing",description: `Generated omo-agent-toolkit runtime wrapper at ${wrapperPath} points to missing target ${targetPath}.`,@@ -107409,26 +108211,26 @@ Doctor failed unexpectedly: ${message}`];import { createHash as createHash7 } from "node:crypto";import {chmodSync as chmodSync5,- existsSync as existsSync61,- mkdirSync as mkdirSync16,- readdirSync as readdirSync12,- readFileSync as readFileSync38,- renameSync as renameSync7,+ existsSync as existsSync63,+ mkdirSync as mkdirSync17,+ readdirSync as readdirSync13,+ readFileSync as readFileSync41,+ renameSync as renameSync8,unlinkSync as unlinkSync9,- writeFileSync as writeFileSync12+ writeFileSync as writeFileSync13} from "node:fs";-import { basename as basename12, dirname as dirname34, join as join90 } from "node:path";+import { basename as basename13, dirname as dirname36, join as join93 } from "node:path";// packages/mcp-client-core/src/config-dir.ts-import { existsSync as existsSync59, realpathSync as realpathSync8 } from "node:fs";-import { homedir as homedir25 } from "node:os";-import { join as join88, resolve as resolve26 } from "node:path";+import { existsSync as existsSync61, realpathSync as realpathSync10 } from "node:fs";+import { homedir as homedir26 } from "node:os";+import { join as join91, resolve as resolve27 } from "node:path";function resolveConfigPath2(pathValue) {- const resolvedPath = resolve26(pathValue);- if (!existsSync59(resolvedPath))+ const resolvedPath = resolve27(pathValue);+ if (!existsSync61(resolvedPath))return resolvedPath;try {- return realpathSync8(resolvedPath);+ return realpathSync10(resolvedPath);} catch (error) {if (!(error instanceof Error))throw error;@@ -107440,13 +108242,13 @@ function getOpenCodeCliConfigDir(env = process.env) {if (customConfigDir) {return resolveConfigPath2(customConfigDir);}- const xdgConfigDir = env["XDG_CONFIG_HOME"]?.trim() || join88(homedir25(), ".config");- return resolveConfigPath2(join88(xdgConfigDir, "opencode"));+ const xdgConfigDir = env["XDG_CONFIG_HOME"]?.trim() || join91(homedir26(), ".config");+ return resolveConfigPath2(join91(xdgConfigDir, "opencode"));}// packages/mcp-client-core/src/mcp-oauth/storage-index.ts-import { chmodSync as chmodSync4, existsSync as existsSync60, readFileSync as readFileSync37, renameSync as renameSync6, writeFileSync as writeFileSync11 } from "node:fs";-import { join as join89 } from "node:path";+import { chmodSync as chmodSync4, existsSync as existsSync62, readFileSync as readFileSync40, renameSync as renameSync7, writeFileSync as writeFileSync12 } from "node:fs";+import { join as join92 } from "node:path";var INDEX_FILE_NAME = "index.json";function isTokenIndex(value) {if (typeof value !== "object" || value === null || Array.isArray(value))@@ -107454,14 +108256,14 @@ function isTokenIndex(value) {return Object.values(value).every((entry) => typeof entry === "string");}function getIndexPath(storageDir) {- return join89(storageDir, INDEX_FILE_NAME);+ return join92(storageDir, INDEX_FILE_NAME);}function readTokenIndex(storageDir) {const indexPath = getIndexPath(storageDir);- if (!existsSync60(indexPath))+ if (!existsSync62(indexPath))return {};try {- const parsed = JSON.parse(readFileSync37(indexPath, "utf-8"));+ const parsed = JSON.parse(readFileSync40(indexPath, "utf-8"));return isTokenIndex(parsed) ? parsed : {};} catch (readError) {if (!(readError instanceof Error))@@ -107473,9 +108275,9 @@ function writeTokenIndex(storageDir, index) {try {const indexPath = getIndexPath(storageDir);const tempPath = `${indexPath}.tmp.${Date.now()}`;- writeFileSync11(tempPath, JSON.stringify(index, null, 2), { encoding: "utf-8", mode: 384 });+ writeFileSync12(tempPath, JSON.stringify(index, null, 2), { encoding: "utf-8", mode: 384 });chmodSync4(tempPath, 384);- renameSync6(tempPath, indexPath);+ renameSync7(tempPath, indexPath);return true;} catch (writeError) {if (!(writeError instanceof Error))@@ -107498,16 +108300,16 @@ function deleteTokenIndexEntry(storageDir, hash) {var STORAGE_DIR_NAME = "mcp-oauth";var LEGACY_STORAGE_FILE_NAME = "mcp-oauth.json";function getMcpOauthStorageDir() {- return join90(getOpenCodeCliConfigDir(), STORAGE_DIR_NAME);+ return join93(getOpenCodeCliConfigDir(), STORAGE_DIR_NAME);}function getMcpOauthServerHash(serverHost, resource) {return createHash7("sha256").update(buildKey(serverHost, resource)).digest("hex").slice(0, 32);}function getMcpOauthStoragePath(serverHost, resource) {- return join90(getMcpOauthStorageDir(), `${getMcpOauthServerHash(serverHost, resource)}.json`);+ return join93(getMcpOauthStorageDir(), `${getMcpOauthServerHash(serverHost, resource)}.json`);}function getLegacyStoragePath() {- return join90(getOpenCodeCliConfigDir(), LEGACY_STORAGE_FILE_NAME);+ return join93(getOpenCodeCliConfigDir(), LEGACY_STORAGE_FILE_NAME);}function normalizeHost2(serverHost) {let host = serverHost.trim();@@ -107568,10 +108370,10 @@ function isOAuthTokenData(value) {return clientSecret === undefined || typeof clientSecret === "string";}function readTokenFile(filePath) {- if (!existsSync61(filePath))+ if (!existsSync63(filePath))return null;try {- const parsed = JSON.parse(readFileSync38(filePath, "utf-8"));+ const parsed = JSON.parse(readFileSync41(filePath, "utf-8"));return isOAuthTokenData(parsed) ? parsed : null;} catch (readError) {if (!(readError instanceof Error))@@ -107581,10 +108383,10 @@ function readTokenFile(filePath) {}function readLegacyStore() {const filePath = getLegacyStoragePath();- if (!existsSync61(filePath))+ if (!existsSync63(filePath))return null;try {- const parsed = JSON.parse(readFileSync38(filePath, "utf-8"));+ const parsed = JSON.parse(readFileSync41(filePath, "utf-8"));if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))return null;const result = {};@@ -107601,14 +108403,14 @@ function readLegacyStore() {}function writeTokenFile(filePath, token) {try {- const dir = dirname34(filePath);- if (!existsSync61(dir)) {- mkdirSync16(dir, { recursive: true });+ const dir = dirname36(filePath);+ if (!existsSync63(dir)) {+ mkdirSync17(dir, { recursive: true });}const tempPath = `${filePath}.tmp.${Date.now()}`;- writeFileSync12(tempPath, JSON.stringify(token, null, 2), { encoding: "utf-8", mode: 384 });+ writeFileSync13(tempPath, JSON.stringify(token, null, 2), { encoding: "utf-8", mode: 384 });chmodSync5(tempPath, 384);- renameSync7(tempPath, filePath);+ renameSync8(tempPath, filePath);return true;} catch (writeError) {if (!(writeError instanceof Error))@@ -107626,7 +108428,7 @@ function saveToken(serverHost, resource, token) {}function deleteToken(serverHost, resource) {const filePath = getMcpOauthStoragePath(serverHost, resource);- if (!existsSync61(filePath))+ if (!existsSync63(filePath))return deleteLegacyToken(serverHost, resource);try {unlinkSync9(filePath);@@ -107648,7 +108450,7 @@ function deleteLegacyToken(serverHost, resource) {if (Object.keys(store).length === 0) {try {const filePath = getLegacyStoragePath();- if (existsSync61(filePath))+ if (existsSync63(filePath))unlinkSync9(filePath);return true;} catch (deleteError) {@@ -107662,7 +108464,7 @@ function deleteLegacyToken(serverHost, resource) {function writeLegacyStore(store) {try {const filePath = getLegacyStoragePath();- writeFileSync12(filePath, JSON.stringify(store, null, 2), { encoding: "utf-8", mode: 384 });+ writeFileSync13(filePath, JSON.stringify(store, null, 2), { encoding: "utf-8", mode: 384 });chmodSync5(filePath, 384);return true;} catch (writeError) {@@ -107686,7 +108488,7 @@ function listTokensByHost(serverHost) {for (const [hash, indexedKey] of Object.entries(index)) {if (!indexedKey.startsWith(prefix))continue;- const indexedToken = readTokenFile(join90(getMcpOauthStorageDir(), `${hash}.json`));+ const indexedToken = readTokenFile(join93(getMcpOauthStorageDir(), `${hash}.json`));if (indexedToken)result[indexedKey] = indexedToken;}@@ -107695,14 +108497,14 @@ function listTokensByHost(serverHost) {function listAllTokens() {const result = { ...readLegacyStore() ?? {} };const dir = getMcpOauthStorageDir();- if (!existsSync61(dir))+ if (!existsSync63(dir))return result;const index = readTokenIndex(dir);- for (const entry of readdirSync12(dir, { withFileTypes: true })) {+ for (const entry of readdirSync13(dir, { withFileTypes: true })) {if (!entry.isFile() || !entry.name.endsWith(".json") || entry.name === "index.json")continue;- const token = readTokenFile(join90(dir, entry.name));- const hash = basename12(entry.name, ".json");+ const token = readTokenFile(join93(dir, entry.name));+ const hash = basename13(entry.name, ".json");if (token)result[index[hash] ?? hash] = token;}@@ -108267,7 +109069,7 @@ function createMcpOAuthCommand() {}// packages/omo-opencode/src/cli/boulder/boulder.ts-import { existsSync as existsSync62 } from "node:fs";+import { existsSync as existsSync64 } from "node:fs";// packages/omo-opencode/src/cli/boulder/formatter.tsvar import_picocolors22 = __toESM(require_picocolors(), 1);@@ -108404,10 +109206,10 @@ async function boulder(options) {const boulderFilePath = getBoulderFilePath(directory);const state = readBoulderState(directory);if (!state) {- const message = existsSync62(boulderFilePath) ? formatReadErrorMessage(options.json) : formatNoBoulderMessage(options.json);+ const message = existsSync64(boulderFilePath) ? formatReadErrorMessage(options.json) : formatNoBoulderMessage(options.json);process.stderr.write(`${message}`);- return existsSync62(boulderFilePath) ? 2 : 1;+ return existsSync64(boulderFilePath) ? 2 : 1;}const works = getBoulderWorks(state);const filteredWorks = options.workId ? works.filter((work) => work.work_id === options.workId) : works;@@ -108425,12 +109227,12 @@ async function boulder(options) {}// packages/omo-opencode/src/cli/codex-ulw-loop.tsimport { spawn as spawn5 } from "node:child_process";-import { existsSync as existsSync63, readFileSync as readFileSync39, realpathSync as realpathSync9 } from "node:fs";-import { homedir as homedir26 } from "node:os";+import { existsSync as existsSync65, readFileSync as readFileSync42, realpathSync as realpathSync11 } from "node:fs";+import { homedir as homedir27 } from "node:os";var ULW_LOOP_DELEGATION_SENTINEL = "OMO_ULW_LOOP_DELEGATED";function resolveCodexUlwLoopCommand(input = {}) {const env = input.env ?? process.env;- const homeDir = input.homeDir ?? homedir26();+ const homeDir = input.homeDir ?? homedir27();const localComponentBin = resolveLocalUlwLoopBin(env, homeDir);if (localComponentBin !== null)return { executable: localComponentBin, argsPrefix: [] };@@ -108467,15 +109269,15 @@ async function codexUlwLoop(args) {}function resolveLocalUlwLoopBin(env, homeDir) {const candidates = resolveCodexComponentBinCandidates({ executableName: "omo-ulw-loop", env, homeDir });- return candidates.find((candidate) => existsSync63(candidate)) ?? null;+ return candidates.find((candidate) => existsSync65(candidate)) ?? null;}function resolveLegacyLocalOmoBin(env, homeDir, currentExecutablePaths) {const candidates = resolveCodexComponentBinCandidates({ executableName: "omo", env, homeDir });- return candidates.find((candidate) => existsSync63(candidate) && !isCurrentExecutable(candidate, currentExecutablePaths) && !isGeneratedRuntimeWrapper(candidate)) ?? null;+ return candidates.find((candidate) => existsSync65(candidate) && !isCurrentExecutable(candidate, currentExecutablePaths) && !isGeneratedRuntimeWrapper(candidate)) ?? null;}function isGeneratedRuntimeWrapper(candidate) {try {- return readFileSync39(candidate, "utf8").includes(RUNTIME_WRAPPER_MARKER);+ return readFileSync42(candidate, "utf8").includes(RUNTIME_WRAPPER_MARKER);} catch (error) {if (error instanceof Error)return false;@@ -108488,7 +109290,7 @@ function isCurrentExecutable(candidate, currentExecutablePaths) {}function realpathOrSelf2(path) {try {- return realpathSync9(path);+ return realpathSync11(path);} catch (error) {if (error instanceof Error)return path;@@ -108670,7 +109472,7 @@ function linkedWorktrees(records) {return records.slice(1);}// packages/omo-opencode/src/cli/worktree-sweep/sweep.ts-import { existsSync as existsSync64 } from "node:fs";+import { existsSync as existsSync66 } from "node:fs";import { stat as stat8 } from "node:fs/promises";import os7 from "node:os";import { normalize as normalize2 } from "node:path";@@ -108761,7 +109563,7 @@ async function isOlderThan(worktreePath, days, now) {}}async function classifyRecord(repo, record, defaultBranch, options) {- const pathExists = existsSync64(record.path);+ const pathExists = existsSync66(record.path);const external = isExcludedPath(record.path, options.excludePrefixes, options.home);if (record.locked || !pathExists || external) {return classifyWorktree({@@ -108911,7 +109713,7 @@ removes with 'git worktree remove' (never --force) and then prunes.// packages/omo-opencode/src/cli/config-migrate.tsinit_startup_migration();-import { posix as posix11 } from "node:path";+import { posix as posix12 } from "node:path";function reports(result) {return result.results.map((entry) => ({diagnostics: entry.diagnostics,@@ -108942,7 +109744,7 @@ function runConfigMigrate(options = {}) {dryRun: options.dryRun ?? false,environment,...homeDir === undefined ? {} : { env: { HOME: homeDir }, homeDir },- pathOperations: posix11+ pathOperations: posix12});const report = reports(result);const response = {diff --git a/plugins/omo/dist/cli/index.js b/plugins/omo/dist/cli/index.jsindex 7911f9d5..72e32b8a 100755--- a/plugins/omo/dist/cli/index.js+++ b/plugins/omo/dist/cli/index.js@@ -64,7 +64,7 @@ var package_default;var init_package = __esm(() => {package_default = {name: "oh-my-opencode",- version: "5.0.0-beta.89",+ version: "5.0.0-beta.90",description: "The Best AI Agent Harness - Batteries-Included OpenCode Plugin with Multi-Model Orchestration, Parallel Background Agents, and Crafted LSP/AST Tools",main: "./dist/index.js",types: "dist/index.d.ts",@@ -247,7 +247,7 @@ var init_package = __esm(() => {zod: "^4.6.5"},devDependencies: {- "@code-yeongyu/senpi": "2026.9.24",+ "@code-yeongyu/senpi": "2026.9.24-3","@oh-my-opencode/agents-md-core": "workspace:*","@oh-my-opencode/ast-grep-mcp": "workspace:*","@oh-my-opencode/boulder-state": "workspace:*",@@ -283,23 +283,23 @@ var init_package = __esm(() => {"@xterm/xterm": "^6.0.0","bun-types": "1.4.2","node-pty": "^1.1.0",- omowright: "github:code-yeongyu/omowright#25781c8ac04f9aae358b06551520b792ac45c6ed",+ omowright: "github:code-yeongyu/omowright#293ca5002cbd4c8b0c104c5934683385ef7e0d3a","puppeteer-core": "^25.11.0",typescript: "^7.0.2"},optionalDependencies: {- "oh-my-opencode-darwin-arm64": "5.0.0-beta.89",- "oh-my-opencode-darwin-x64": "5.0.0-beta.89",- "oh-my-opencode-darwin-x64-baseline": "5.0.0-beta.89",- "oh-my-opencode-linux-arm64": "5.0.0-beta.89",- "oh-my-opencode-linux-arm64-musl": "5.0.0-beta.89",- "oh-my-opencode-linux-x64": "5.0.0-beta.89",- "oh-my-opencode-linux-x64-baseline": "5.0.0-beta.89",- "oh-my-opencode-linux-x64-musl": "5.0.0-beta.89",- "oh-my-opencode-linux-x64-musl-baseline": "5.0.0-beta.89",- "oh-my-opencode-windows-arm64": "5.0.0-beta.89",- "oh-my-opencode-windows-x64": "5.0.0-beta.89",- "oh-my-opencode-windows-x64-baseline": "5.0.0-beta.89"+ "oh-my-opencode-darwin-arm64": "5.0.0-beta.90",+ "oh-my-opencode-darwin-x64": "5.0.0-beta.90",+ "oh-my-opencode-darwin-x64-baseline": "5.0.0-beta.90",+ "oh-my-opencode-linux-arm64": "5.0.0-beta.90",+ "oh-my-opencode-linux-arm64-musl": "5.0.0-beta.90",+ "oh-my-opencode-linux-x64": "5.0.0-beta.90",+ "oh-my-opencode-linux-x64-baseline": "5.0.0-beta.90",+ "oh-my-opencode-linux-x64-musl": "5.0.0-beta.90",+ "oh-my-opencode-linux-x64-musl-baseline": "5.0.0-beta.90",+ "oh-my-opencode-windows-arm64": "5.0.0-beta.90",+ "oh-my-opencode-windows-x64": "5.0.0-beta.90",+ "oh-my-opencode-windows-x64-baseline": "5.0.0-beta.90"},overrides: {"@earendil-works/pi-agent-core": "0.84.2",@@ -9617,6 +9617,117 @@ function getOpenCodeConfigPaths(options) {var TAURI_APP_IDENTIFIER = "ai.opencode.desktop", TAURI_APP_IDENTIFIER_DEV = "ai.opencode.desktop.dev";var init_opencode_config_dir = () => {};+// packages/omo-opencode/src/shared/opencode-plugin-sandbox.ts+import { existsSync as existsSync6, mkdirSync as mkdirSync3, readdirSync, readFileSync, realpathSync as realpathSync3, renameSync as renameSync3, rmSync as rmSync2, writeFileSync as writeFileSync2 } from "fs";+import { basename, dirname as dirname2, join as join7, resolve as resolve2 } from "path";+function getPluginSandboxRoot(cacheDir) {+ return join7(cacheDir, SANDBOX_PARENT_DIR);+}+function toPluginSandboxSpec(entry) {+ const name = ACCEPTED_PACKAGE_NAMES.find((candidate) => entry === candidate || entry.startsWith(`${candidate}@`));+ if (!name)+ return null;+ return entry === name ? `${name}@latest` : entry;+}+function getPluginSandboxDir(cacheDir, entry) {+ const spec = toPluginSandboxSpec(entry);+ if (!spec)+ return null;+ return join7(getPluginSandboxRoot(cacheDir), spec);+}+function canonicalize(path) {+ try {+ return realpathSync3(path);+ } catch {+ return resolve2(path);+ }+}+function isPluginSandboxDir(dir, cacheDir) {+ if (toPluginSandboxSpec(basename(dir)) === null)+ return false;+ return canonicalize(dirname2(dir)) === canonicalize(getPluginSandboxRoot(cacheDir));+}+function removePluginSandbox(dir, cacheDir) {+ if (!isPluginSandboxDir(dir, cacheDir))+ return false;+ if (!existsSync6(dir))+ return false;+ const discarded = join7(dirname2(dir), `.${basename(dir)}.discarded-${process.pid}-${Date.now()}`);+ renameSync3(dir, discarded);+ try {+ rmSync2(discarded, { recursive: true, force: true });+ } catch (error) {+ if (!(error instanceof Error))+ throw error;+ log2(`[plugin-sandbox] Refreshed ${dir}, but could not delete the discarded copy ${discarded}: ${error.message}`);+ }+ return true;+}+function markPluginSandboxStale(dir, cacheDir, reason = "", pid = process.pid) {+ if (!isPluginSandboxDir(dir, cacheDir))+ return false;+ if (!existsSync6(dir))+ return false;+ writeFileSync2(join7(dir, REFRESH_MARKER_FILE), `${pid}+${reason}`);+ return true;+}+function describeUnappliedPluginSandboxRefresh(dir, pid = process.pid) {+ const markerPath = join7(dir, REFRESH_MARKER_FILE);+ if (!existsSync6(markerPath))+ return null;+ const [pidLine = "", ...reasonLines] = readFileSync(markerPath, "utf-8").split(`+`);+ const requester = Number(pidLine);+ if (requester === pid)+ return null;+ const reason = reasonLines.join(`+`).trim();+ if (reason)+ return reason;+ if (Number.isInteger(requester) && requester > 0 && isProcessAlive(requester))+ return null;+ return "the refresh requested earlier did not run when OpenCode exited";+}+function isPluginSandboxMarkedStale(dir) {+ return existsSync6(join7(dir, REFRESH_MARKER_FILE));+}+function acquirePluginSandboxLease(dir, pid = process.pid) {+ const leaseDir = join7(dir, LEASE_DIR);+ mkdirSync3(leaseDir, { recursive: true });+ writeFileSync2(join7(leaseDir, String(pid)), "");+}+function releasePluginSandboxLease(dir, pid = process.pid) {+ rmSync2(join7(dir, LEASE_DIR, String(pid)), { force: true });+}+function isProcessAlive(pid) {+ try {+ process.kill(pid, 0);+ return true;+ } catch (error) {+ return error.code === "EPERM";+ }+}+function hasOtherLivePluginSandboxLease(dir, pid = process.pid) {+ const leaseDir = join7(dir, LEASE_DIR);+ if (!existsSync6(leaseDir))+ return false;+ for (const entry of readdirSync(leaseDir)) {+ const holder = Number(entry);+ if (!Number.isInteger(holder) || holder <= 0 || holder === pid)+ continue;+ if (isProcessAlive(holder))+ return true;+ rmSync2(join7(leaseDir, entry), { force: true });+ }+ return false;+}+var SANDBOX_PARENT_DIR = "packages", REFRESH_MARKER_FILE = ".omo-refresh-pending", LEASE_DIR = ".omo-leases";+var init_opencode_plugin_sandbox = __esm(() => {+ init_logger2();+ init_plugin_identity();+});+// packages/omo-opencode/src/shared/resolve-agent-definition-paths.tsvar init_resolve_agent_definition_paths = __esm(() => {init_contains_path2();@@ -9625,8 +9736,8 @@ var init_resolve_agent_definition_paths = __esm(() => {// packages/omo-opencode/src/shared/opencode-version.tsimport { execSync } from "child_process";-import { existsSync as existsSync6, readFileSync, realpathSync as realpathSync3 } from "fs";-import { dirname as dirname2, join as join7 } from "path";+import { existsSync as existsSync7, readFileSync as readFileSync2, realpathSync as realpathSync4 } from "fs";+import { dirname as dirname3, join as join8 } from "path";function parseVersion(version) {const cleaned = version.replace(/^v/, "").split("-")[0];return cleaned.split(".").map((n) => parseInt(n, 10) || 0);@@ -9667,7 +9778,7 @@ function parsePackageVersion(content) {function getPackageVersionFromBinary(binaryPath, deps) {try {const realBinaryPath = deps.realpath(binaryPath);- const packagePath = join7(dirname2(dirname2(realBinaryPath)), "package.json");+ const packagePath = join8(dirname3(dirname3(realBinaryPath)), "package.json");if (!deps.exists(packagePath))return null;return parsePackageVersion(deps.readText(packagePath));@@ -9727,15 +9838,15 @@ var init_opencode_version = __esm(() => {return envPath;return globalThis.Bun?.which("opencode") ?? null;},- exists: existsSync6,- realpath: realpathSync3,- readText: (filePath) => readFileSync(filePath, "utf-8")+ exists: existsSync7,+ realpath: realpathSync4,+ readText: (filePath) => readFileSync2(filePath, "utf-8")};});// packages/omo-opencode/src/shared/opencode-storage-detection.ts-import { existsSync as existsSync7 } from "fs";-import { join as join8 } from "path";+import { existsSync as existsSync8 } from "fs";+import { join as join9 } from "path";function isSqliteBackend() {if (cachedResult === true)return true;@@ -9743,8 +9854,8 @@ function isSqliteBackend() {return false;const check = () => {const versionOk = isOpenCodeVersionAtLeast(OPENCODE_SQLITE_VERSION);- const dbPath = join8(getDataDir(), "opencode", "opencode.db");- return versionOk && existsSync7(dbPath);+ const dbPath = join9(getDataDir(), "opencode", "opencode.db");+ return versionOk && existsSync8(dbPath);};if (cachedResult === FALSE_PENDING_RETRY) {const result = check();@@ -9812,11 +9923,11 @@ var init_zip_extractor = __esm(() => {var init_bun_file_shim = () => {};// packages/omo-opencode/src/shared/binary-downloader.ts-import { chmodSync, existsSync as existsSync8, mkdirSync as mkdirSync3, unlinkSync as unlinkSync3 } from "fs";+import { chmodSync, existsSync as existsSync9, mkdirSync as mkdirSync4, unlinkSync as unlinkSync3 } from "fs";import * as path6 from "path";function getCachedBinaryPath(cacheDir, binaryName) {const binaryPath = path6.join(cacheDir, binaryName);- return existsSync8(binaryPath) ? binaryPath : null;+ return existsSync9(binaryPath) ? binaryPath : null;}var init_binary_downloader = __esm(() => {init_bun_spawn_shim();@@ -9899,14 +10010,14 @@ import {chmodSync as chmodSync2,closeSync as closeSync2,openSync as openSync2,- renameSync as renameSync3,+ renameSync as renameSync4,unlinkSync as unlinkSync4,- writeFileSync as writeFileSync2+ writeFileSync as writeFileSync3} from "fs";function writeFileAtomically2(filePath, content, deps = {}) {const tempPath = `${filePath}.tmp`;const mode = deps.mode;- writeFileSync2(tempPath, content, { encoding: "utf-8", mode });+ writeFileSync3(tempPath, content, { encoding: "utf-8", mode });if (mode !== undefined) {chmodSync2(tempPath, mode);}@@ -9918,13 +10029,13 @@ function writeFileAtomically2(filePath, content, deps = {}) {}try {deps.beforeRenameSync?.(tempPath);- renameSync3(tempPath, filePath);+ renameSync4(tempPath, filePath);} catch (error) {const isWindows = process.platform === "win32";const isPermissionError = error instanceof Error && (error.message.includes("EPERM") || error.message.includes("EACCES"));if (isWindows && isPermissionError) {unlinkSync4(filePath);- renameSync3(tempPath, filePath);+ renameSync4(tempPath, filePath);} else {throw error;}@@ -9938,8 +10049,8 @@ var init_write_file_atomically = __esm(() => {});// packages/omo-opencode/src/shared/json-file-cache-store.ts-import { existsSync as existsSync9, mkdirSync as mkdirSync4, readFileSync as readFileSync2, writeFileSync as writeFileSync3 } from "fs";-import { join as join10 } from "path";+import { existsSync as existsSync10, mkdirSync as mkdirSync5, readFileSync as readFileSync3, writeFileSync as writeFileSync4 } from "fs";+import { join as join11 } from "path";function toLogLabel(cacheLabel) {return cacheLabel.toLowerCase();}@@ -9947,12 +10058,12 @@ function createJsonFileCacheStore(options) {let memoryValue;let writtenInCurrentProcess = false;function getCacheFilePath() {- return join10(options.getCacheDir(), options.filename);+ return join11(options.getCacheDir(), options.filename);}function ensureCacheDir() {const cacheDir = options.getCacheDir();- if (!existsSync9(cacheDir)) {- mkdirSync4(cacheDir, { recursive: true });+ if (!existsSync10(cacheDir)) {+ mkdirSync5(cacheDir, { recursive: true });}}function read() {@@ -9960,13 +10071,13 @@ function createJsonFileCacheStore(options) {return memoryValue;}const cacheFile = getCacheFilePath();- if (!existsSync9(cacheFile)) {+ if (!existsSync10(cacheFile)) {memoryValue = null;log2(`[${options.logPrefix}] ${options.cacheLabel} file not found`, { cacheFile });return null;}try {- const content = readFileSync2(cacheFile, "utf-8");+ const content = readFileSync3(cacheFile, "utf-8");const value = JSON.parse(content);memoryValue = value;log2(`[${options.logPrefix}] Read ${toLogLabel(options.cacheLabel)}`, options.describe(value));@@ -9986,13 +10097,13 @@ function createJsonFileCacheStore(options) {if (writtenInCurrentProcess) {return true;}- return existsSync9(getCacheFilePath());+ return existsSync10(getCacheFilePath());}function write(value) {ensureCacheDir();const cacheFile = getCacheFilePath();try {- writeFileSync3(cacheFile, options.serialize?.(value) ?? JSON.stringify(value, null, 2));+ writeFileSync4(cacheFile, options.serialize?.(value) ?? JSON.stringify(value, null, 2));memoryValue = value;writtenInCurrentProcess = true;log2(`[${options.logPrefix}] ${options.cacheLabel} written`, options.describe(value));@@ -64781,19 +64892,19 @@ var init_fallback_model_availability = __esm(() => {});// packages/omo-opencode/src/shared/opencode-storage-paths.ts-import { join as join11 } from "path";+import { join as join12 } from "path";var OPENCODE_STORAGE, MESSAGE_STORAGE, PART_STORAGE, SESSION_STORAGE;var init_opencode_storage_paths = __esm(() => {init_data_path();OPENCODE_STORAGE = getOpenCodeStorageDir();- MESSAGE_STORAGE = join11(OPENCODE_STORAGE, "message");- PART_STORAGE = join11(OPENCODE_STORAGE, "part");- SESSION_STORAGE = join11(OPENCODE_STORAGE, "session");+ MESSAGE_STORAGE = join12(OPENCODE_STORAGE, "message");+ PART_STORAGE = join12(OPENCODE_STORAGE, "part");+ SESSION_STORAGE = join12(OPENCODE_STORAGE, "session");});// packages/omo-opencode/src/shared/compaction-marker.ts-import { existsSync as existsSync10, readdirSync, readFileSync as readFileSync3 } from "fs";-import { join as join12 } from "path";+import { existsSync as existsSync11, readdirSync as readdirSync2, readFileSync as readFileSync4 } from "fs";+import { join as join13 } from "path";function isCompactionPart(part) {return typeof part === "object" && part !== null && part.type === "compaction";}@@ -64807,20 +64918,20 @@ function isCompactionMessage(message) {return isCompactionAgent(message.info?.agent ?? message.agent) || hasCompactionPart(message.parts);}function getCompactionPartStorageDir(messageID) {- return join12(PART_STORAGE, messageID);+ return join13(PART_STORAGE, messageID);}function hasCompactionPartInStorage(messageID) {if (!messageID) {return false;}const partDir = getCompactionPartStorageDir(messageID);- if (!existsSync10(partDir)) {+ if (!existsSync11(partDir)) {return false;}try {- return readdirSync(partDir).filter((fileName) => fileName.endsWith(".json")).some((fileName) => {+ return readdirSync2(partDir).filter((fileName) => fileName.endsWith(".json")).some((fileName) => {try {- const content = readFileSync3(join12(partDir, fileName), "utf-8");+ const content = readFileSync4(join13(partDir, fileName), "utf-8");return isCompactionPart(JSON.parse(content));} catch (error) {if (error instanceof Error) {@@ -64921,23 +65032,23 @@ var init_hook_message_injector = __esm(() => {});// packages/omo-opencode/src/shared/opencode-message-dir.ts-import { existsSync as existsSync11, readdirSync as readdirSync2 } from "fs";-import { join as join13 } from "path";+import { existsSync as existsSync12, readdirSync as readdirSync3 } from "fs";+import { join as join14 } from "path";function getMessageDir(sessionID) {if (!sessionID.startsWith("ses_"))return null;if (/[/\\]|\.\./.test(sessionID))return null;- if (!existsSync11(MESSAGE_STORAGE))+ if (!existsSync12(MESSAGE_STORAGE))return null;- const directPath = join13(MESSAGE_STORAGE, sessionID);- if (existsSync11(directPath)) {+ const directPath = join14(MESSAGE_STORAGE, sessionID);+ if (existsSync12(directPath)) {return directPath;}try {- for (const dir of readdirSync2(MESSAGE_STORAGE)) {- const sessionPath = join13(MESSAGE_STORAGE, dir, sessionID);- if (existsSync11(sessionPath)) {+ for (const dir of readdirSync3(MESSAGE_STORAGE)) {+ const sessionPath = join14(MESSAGE_STORAGE, dir, sessionID);+ if (existsSync12(sessionPath)) {return sessionPath;}}@@ -67966,6 +68077,7 @@ var init_shared = __esm(() => {init_jsonc_parser2();init_migration2();init_opencode_config_dir();+ init_opencode_plugin_sandbox();init_resolve_agent_definition_paths();init_opencode_version();init_opencode_storage_detection();@@ -74989,36 +75101,36 @@ function toPosixPath(path) {var init_posix_path = () => {};// packages/omo-config-core/src/loader/types.ts-import { existsSync as existsSync12, lstatSync as lstatSync2, readFileSync as readFileSync4, realpathSync as realpathSync4 } from "fs";+import { existsSync as existsSync13, lstatSync as lstatSync2, readFileSync as readFileSync5, realpathSync as realpathSync5 } from "fs";var DEFAULT_READ_FILE_SYSTEM;var init_types3 = __esm(() => {DEFAULT_READ_FILE_SYSTEM = {- existsSync: existsSync12,+ existsSync: existsSync13,lstatSync: lstatSync2,- readFileSync: readFileSync4,- realpathSync: realpathSync4+ readFileSync: readFileSync5,+ realpathSync: realpathSync5};});// packages/omo-config-core/src/loader/paths.tsimport { userInfo } from "os";-import { dirname as dirname3, join as join14, posix as posix2, resolve as resolve2 } from "path";+import { dirname as dirname4, join as join15, posix as posix2, resolve as resolve3 } from "path";function resolveHomeDir(env = process.env) {const homeDir = env.HOME ?? env.USERPROFILE ?? process.cwd();- return homeDir.startsWith("/") ? posix2.resolve(homeDir) : toPosixPath(resolve2(homeDir));+ return homeDir.startsWith("/") ? posix2.resolve(homeDir) : toPosixPath(resolve3(homeDir));}function resolveUserOmoConfigPath(env = process.env) {- return join14(resolveUserOmoConfigDirectory(env), "omo.jsonc");+ return join15(resolveUserOmoConfigDirectory(env), "omo.jsonc");}function resolveUserOmoConfigDirectory(env = process.env) {- return join14(resolveHomeDir(env), ".omo");+ return join15(resolveHomeDir(env), ".omo");}function detectUserOmoJsonPath(env, fileSystem) {const configDir = resolveUserOmoConfigDirectory(env);- const jsoncPath = join14(configDir, "omo.jsonc");+ const jsoncPath = join15(configDir, "omo.jsonc");if (fileSystem.existsSync(jsoncPath))return jsoncPath;- const jsonPath = join14(configDir, "omo.json");+ const jsonPath = join15(configDir, "omo.json");return fileSystem.existsSync(jsonPath) ? jsonPath : jsoncPath;}function isSymlinkedProjectPath(path, fileSystem) {@@ -75036,13 +75148,13 @@ function isLoadableProjectConfigFile(path, fileSystem) {return fileSystem.existsSync(path) && !isSymlinkedProjectPath(path, fileSystem);}function detectOmoJsonPath(dir, fileSystem) {- const omoDir = join14(dir, ".omo");+ const omoDir = join15(dir, ".omo");if (isSymlinkedProjectPath(omoDir, fileSystem))return null;- const jsoncPath = join14(omoDir, "omo.jsonc");+ const jsoncPath = join15(omoDir, "omo.jsonc");if (isLoadableProjectConfigFile(jsoncPath, fileSystem))return jsoncPath;- const jsonPath = join14(omoDir, "omo.json");+ const jsonPath = join15(omoDir, "omo.json");return isLoadableProjectConfigFile(jsonPath, fileSystem) ? jsonPath : null;}function realpathOrSelf(path, fileSystem) {@@ -75055,8 +75167,8 @@ function realpathOrSelf(path, fileSystem) {}}function findProjectConfigPathsFarthestFirst(cwd, homeDir, fileSystem, accountHomeDir = homeDir) {- const startDir = resolve2(cwd);- const boundaryDirs = [...new Set([resolve2(homeDir), resolve2(accountHomeDir)])];+ const startDir = resolve3(cwd);+ const boundaryDirs = [...new Set([resolve3(homeDir), resolve3(accountHomeDir)])];const realBoundaryDirs = new Set(boundaryDirs.map((path) => realpathOrSelf(path, fileSystem)));const nearestFirst = [];let currentDir = startDir;@@ -75067,7 +75179,7 @@ function findProjectConfigPathsFarthestFirst(cwd, homeDir, fileSystem, accountHonearestFirst.push(configPath);if (isHomeDir)break;- const parentDir = dirname3(currentDir);+ const parentDir = dirname4(currentDir);if (parentDir === currentDir)break;currentDir = parentDir;@@ -75588,30 +75700,30 @@ var init_models = __esm(() => {// packages/omo-config-core/src/writer/types.tsimport {copyFileSync,- existsSync as existsSync13,+ existsSync as existsSync14,lstatSync as lstatSync3,- mkdirSync as mkdirSync5,- readFileSync as readFileSync5,- readdirSync as readdirSync3,- renameSync as renameSync4,+ mkdirSync as mkdirSync6,+ readFileSync as readFileSync6,+ readdirSync as readdirSync4,+ renameSync as renameSync5,unlinkSync as unlinkSync5,- writeFileSync as writeFileSync4+ writeFileSync as writeFileSync5} from "fs";var DEFAULT_WRITE_FILE_SYSTEM, OmoConfigWriteError;var init_types4 = __esm(() => {DEFAULT_WRITE_FILE_SYSTEM = {copyFileSync,- existsSync: existsSync13,+ existsSync: existsSync14,lstatSync: lstatSync3,- mkdirSync: mkdirSync5,- readFileSync: readFileSync5,- readdirSync: readdirSync3,- renameSync: renameSync4,+ mkdirSync: mkdirSync6,+ readFileSync: readFileSync6,+ readdirSync: readdirSync4,+ renameSync: renameSync5,unlinkSync: unlinkSync5,writeFileExclusiveSync: (path, content) => {- writeFileSync4(path, content, { encoding: "utf-8", flag: "wx" });+ writeFileSync5(path, content, { encoding: "utf-8", flag: "wx" });},- writeFileSync: writeFileSync4+ writeFileSync: writeFileSync5};OmoConfigWriteError = class OmoConfigWriteError extends Error {path;@@ -75651,7 +75763,7 @@ var init_jsonc_parse = __esm(() => {// packages/omo-config-core/src/writer/writer.tsimport { randomUUID as randomUUID2 } from "crypto";-import { dirname as dirname4, join as join15, posix as posix3 } from "path";+import { dirname as dirname5, join as join16, posix as posix3 } from "path";function backupSuffix() {return new Date().toISOString().replace(/[:.]/g, "-");}@@ -75684,17 +75796,17 @@ function resolveWritePath(options) {const jsoncPath = resolveUserOmoConfigPath(options.env);if (fileSystem.existsSync(jsoncPath))return jsoncPath;- const jsonPath = join15(dirname4(jsoncPath), "omo.json");+ const jsonPath = join16(dirname5(jsoncPath), "omo.json");return fileSystem.existsSync(jsonPath) ? jsonPath : jsoncPath;}- const jsoncPath = join15(options.projectDir ?? process.cwd(), ".omo", "omo.jsonc");+ const jsoncPath = join16(options.projectDir ?? process.cwd(), ".omo", "omo.jsonc");if (fileSystem.existsSync(jsoncPath))return jsoncPath;- const jsonPath = join15(dirname4(jsoncPath), "omo.json");+ const jsonPath = join16(dirname5(jsoncPath), "omo.json");return fileSystem.existsSync(jsonPath) ? jsonPath : jsoncPath;}function directoryPath(path) {- return path.startsWith("/") ? posix3.dirname(path) : dirname4(path);+ return path.startsWith("/") ? posix3.dirname(path) : dirname5(path);}function writeAtomically(path, content, fileSystem) {const tempPath = `${path}.${randomUUID2()}.tmp`;@@ -75980,7 +76092,7 @@ var init_types5 = __esm(() => {});// packages/omo-config-core/src/migration/commit.ts-import { basename, dirname as dirname5, join as join16, resolve as resolve3 } from "path";+import { basename as basename2, dirname as dirname6, join as join17, resolve as resolve4 } from "path";function parseDocument(path, content) {const parsed = parseJsoncSafe3(content);if (parsed.errors.length > 0 || !isPlainObject5(parsed.data)) {@@ -76003,52 +76115,100 @@ function markerValue(target, migrationId, targetPath) {}return hasMigrationMarker(target, migrationId) ? value : [...value, migrationId];}+function stripRetiredCodegraph(document) {+ const stripped = structuredClone(document);+ const removedPaths = [];+ const strip = (value, path) => {+ if (!isPlainObject5(value))+ return;+ if (Object.prototype.hasOwnProperty.call(value, "codegraph")) {+ delete value.codegraph;+ removedPaths.push([...path, "codegraph"]);+ }+ };+ strip(stripped, []);+ for (const harness of OMO_HARNESS_BLOCKS)+ strip(stripped[harness], [harness]);+ if (isPlainObject5(stripped.profiles)) {+ for (const [profileName, profile] of Object.entries(stripped.profiles)) {+ strip(profile, ["profiles", profileName]);+ if (!isPlainObject5(profile))+ continue;+ for (const harness of OMO_HARNESS_BLOCKS)+ strip(profile[harness], ["profiles", profileName, harness]);+ }+ }+ return {+ diagnostics: removedPaths.map((path) => `removed: ${path.join(".") || "codegraph"} (retired configuration)`),+ document: stripped,+ edits: removedPaths.map((path) => ({ path, value: undefined }))+ };+}+function uniqueDiagnostics(diagnostics) {+ return [...new Set(diagnostics)];+}function validateTarget(targetPath, document) {const result = OmoConfigSchema.safeParse(document);if (result.success)return;- const detail = result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join(", ");+ const detail = result.error.issues.map((issue) => `${issue.path.map(String).join(".")}: ${issue.message}`).join(", ");throw new MigrationValidationError(targetPath, detail);}function writerInput(targetPath, env) {const homeDir = resolveHomeDir(env);- const userDirectory = toPosixPath(join16(homeDir, ".omo"));- const fileName = basename(targetPath);- if (toPosixPath(dirname5(targetPath)) === userDirectory && (fileName === "omo.json" || fileName === "omo.jsonc")) {+ const userDirectory = toPosixPath(join17(homeDir, ".omo"));+ const fileName = basename2(targetPath);+ if (toPosixPath(dirname6(targetPath)) === userDirectory && (fileName === "omo.json" || fileName === "omo.jsonc")) {return { scope: "user" };}- if (basename(dirname5(targetPath)) === ".omo" && (fileName === "omo.json" || fileName === "omo.jsonc")) {- return { projectDir: dirname5(dirname5(targetPath)), scope: "project" };+ if (basename2(dirname6(targetPath)) === ".omo" && (fileName === "omo.json" || fileName === "omo.jsonc")) {+ return { projectDir: dirname6(dirname6(targetPath)), scope: "project" };}throw new MigrationTransactionError(`Migration target is not an omo config path: ${targetPath}`);}function sameResolvedPath(a, b) {- return toPosixPath(resolve3(a)) === toPosixPath(resolve3(b));+ return toPosixPath(resolve4(a)) === toPosixPath(resolve4(b));}function prepareTargetWrite(input) {- const merged = mergeWithoutClobber(input.target, input.additions);+ const targetCleanup = stripRetiredCodegraph(input.target);+ const additionsCleanup = stripRetiredCodegraph(input.additions);+ const merged = mergeWithoutClobber(targetCleanup.document, additionsCleanup.document);const marker = markerValue(input.target, input.migrationId, input.targetPath);const document = { ...merged.merged, _migrations: marker };validateTarget(input.targetPath, document);- const edits = [...collectMigrationEdits(merged.additions), { path: ["_migrations"], value: marker }];- return { diagnostics: merged.diagnostics, document, edits };+ const edits = [+ ...targetCleanup.edits,+ ...collectMigrationEdits(merged.additions),+ { path: ["_migrations"], value: marker }+ ];+ return {+ diagnostics: uniqueDiagnostics([...merged.diagnostics, ...targetCleanup.diagnostics, ...additionsCleanup.diagnostics]),+ document,+ edits+ };}function prepareTargetReplacement(input) {+ const targetCleanup = stripRetiredCodegraph(input.target);+ const documentCleanup = stripRetiredCodegraph(input.document);const marker = markerValue(input.target, input.migrationId, input.targetPath);- const document = { ...input.document, _migrations: marker };+ const document = { ...documentCleanup.document, _migrations: marker };validateTarget(input.targetPath, document);- const edits = [];- for (const key of Object.keys(input.target)) {- if (key !== "_migrations" && !Object.prototype.hasOwnProperty.call(input.document, key)) {+ const edits = [...targetCleanup.edits];+ for (const key of Object.keys(targetCleanup.document)) {+ if (key !== "_migrations" && !Object.prototype.hasOwnProperty.call(documentCleanup.document, key)) {edits.push({ path: [key], value: undefined });}}- for (const [key, value] of Object.entries(input.document)) {+ for (const [key, value] of Object.entries(documentCleanup.document)) {if (key !== "_migrations")edits.push({ path: [key], value });}edits.push({ path: ["_migrations"], value: marker });- return { diagnostics: [], document, edits };+ return {+ diagnostics: uniqueDiagnostics([...targetCleanup.diagnostics, ...documentCleanup.diagnostics]),+ document,+ edits+ };}function writePreparedTarget(input) {input.writeTarget({@@ -76058,7 +76218,7 @@ function writePreparedTarget(input) {targetPath: input.targetPath});}-var writeOmoMigrationTarget = (input) => {+var OMO_HARNESS_BLOCKS, writeOmoMigrationTarget = (input) => {const options = writerInput(input.targetPath, input.env);const result = updateOmoConfig({...options,@@ -76080,12 +76240,13 @@ var init_commit = __esm(() => {init_writer2();init_merge2();init_types5();+ OMO_HARNESS_BLOCKS = [...OMO_CONFIG_HARNESS_IDS, ...OMO_CONFIG_LEGACY_HARNESS_IDS].map(harnessBlockKey);});// packages/omo-config-core/src/migration/journal.ts-import { join as join17 } from "path";+import { join as join18 } from "path";function migrationJournalPath(env) {- return toPosixPath(join17(resolveHomeDir(env), ".omo", ".migration-journal.json"));+ return toPosixPath(join18(resolveHomeDir(env), ".omo", ".migration-journal.json"));}function isFileExistsError2(error) {return error instanceof Error && Reflect.get(error, "code") === "EEXIST";@@ -76178,9 +76339,9 @@ var init_journal = __esm(() => {});// packages/omo-config-core/src/migration/lock.ts-import { join as join18 } from "path";+import { join as join19 } from "path";function migrationLockPath(env) {- return toPosixPath(join18(resolveHomeDir(env), ".omo", ".migration.lock"));+ return toPosixPath(join19(resolveHomeDir(env), ".omo", ".migration.lock"));}function mutationGuardPath(env) {return `${migrationLockPath(env)}.guard`;@@ -76257,7 +76418,7 @@ function releaseMutationGuard(input) {function acquireMigrationLock(input) {const leaseDurationMs = input.leaseDurationMs ?? DEFAULT_LEASE_DURATION_MS;const path = migrationLockPath(input.env);- input.fileSystem.mkdirSync(toPosixPath(join18(resolveHomeDir(input.env), ".omo")), { recursive: true });+ input.fileSystem.mkdirSync(toPosixPath(join19(resolveHomeDir(input.env), ".omo")), { recursive: true });for (let attempt = 0;attempt < 3; attempt += 1) {const currentContent = leaseContent(input.process, input.clock, leaseDurationMs);try {@@ -76381,7 +76542,7 @@ var init_recovery = __esm(() => {});// packages/omo-config-core/src/migration/batch.ts-import { dirname as dirname6, posix as posix4 } from "path";+import { dirname as dirname7, posix as posix4 } from "path";function parseSource(path, content) {const parsed = parseJsoncSafe3(content);if (parsed.errors.length > 0) {@@ -76430,7 +76591,7 @@ function assertSafeSourcePaths(sources, protectedPaths) {}}function directoryPath2(path) {- return path.startsWith("/") ? posix4.dirname(path) : dirname6(path);+ return path.startsWith("/") ? posix4.dirname(path) : dirname7(path);}function ensureBackupDirectories(moves, fileSystem) {for (const move of moves)@@ -76647,18 +76808,18 @@ var init_plugin_name_with_version = __esm(() => {});// packages/omo-opencode/src/cli/config-manager/backup-config.ts-import { copyFileSync as copyFileSync2, existsSync as existsSync14, mkdirSync as mkdirSync6 } from "fs";-import { dirname as dirname7 } from "path";+import { copyFileSync as copyFileSync2, existsSync as existsSync15, mkdirSync as mkdirSync7 } from "fs";+import { dirname as dirname8 } from "path";function backupConfigFile(configPath) {- if (!existsSync14(configPath)) {+ if (!existsSync15(configPath)) {return { success: true };}const timestamp = new Date().toISOString().replace(/[:.]/g, "-");const backupPath = `${configPath}.backup-${timestamp}`;try {- const dir = dirname7(backupPath);- if (!existsSync14(dir)) {- mkdirSync6(dir, { recursive: true });+ const dir = dirname8(backupPath);+ if (!existsSync15(dir)) {+ mkdirSync7(dir, { recursive: true });}copyFileSync2(configPath, backupPath);return { success: true, backupPath };@@ -76672,11 +76833,11 @@ function backupConfigFile(configPath) {var init_backup_config = () => {};// packages/omo-opencode/src/cli/config-manager/ensure-config-directory-exists.ts-import { existsSync as existsSync15, mkdirSync as mkdirSync7 } from "fs";+import { existsSync as existsSync16, mkdirSync as mkdirSync8 } from "fs";function ensureConfigDirectoryExists() {const configDir = getConfigDir();- if (!existsSync15(configDir)) {- mkdirSync7(configDir, { recursive: true });+ if (!existsSync16(configDir)) {+ mkdirSync8(configDir, { recursive: true });}}var init_ensure_config_directory_exists = __esm(() => {@@ -76713,14 +76874,14 @@ function formatErrorWithSuggestion(err, context) {}// packages/omo-opencode/src/cli/config-manager/opencode-config-format.ts-import { existsSync as existsSync16 } from "fs";+import { existsSync as existsSync17 } from "fs";function detectConfigFormat() {const configJsonc = getConfigJsonc();const configJson = getConfigJson();- if (existsSync16(configJsonc)) {+ if (existsSync17(configJsonc)) {return { format: "jsonc", path: configJsonc };}- if (existsSync16(configJson)) {+ if (existsSync17(configJson)) {return { format: "json", path: configJson };}return { format: "none", path: configJson };@@ -76730,7 +76891,7 @@ var init_opencode_config_format = __esm(() => {});// packages/omo-opencode/src/cli/config-manager/parse-opencode-config-file.ts-import { readFileSync as readFileSync6, statSync as statSync3 } from "fs";+import { readFileSync as readFileSync7, statSync as statSync3 } from "fs";function isEmptyOrWhitespace(content) {return content.trim().length === 0;}@@ -76740,7 +76901,7 @@ function parseOpenCodeConfigFileWithError(path) {if (stat.size === 0) {return { config: null, error: `Config file is empty: ${path}. Delete it or add valid JSON content.` };}- const content = readFileSync6(path, "utf-8");+ const content = readFileSync7(path, "utf-8");if (isEmptyOrWhitespace(content)) {return { config: null, error: `Config file contains only whitespace: ${path}. Delete it or add valid JSON content.` };}@@ -76853,30 +77014,30 @@ function extractVersionFromPluginEntry(entry) {}// packages/omo-opencode/src/cli/config-manager/add-plugin-to-opencode-config.ts-import { existsSync as existsSync17, readdirSync as readdirSync4, readFileSync as readFileSync7, writeFileSync as writeFileSync5 } from "fs";-import { basename as basename2, dirname as dirname8, join as join19 } from "path";+import { existsSync as existsSync18, readdirSync as readdirSync5, readFileSync as readFileSync8, writeFileSync as writeFileSync6 } from "fs";+import { basename as basename3, dirname as dirname9, join as join20 } from "path";function detectConfigFormatInDir(configDir) {- const configJsonc = join19(configDir, "opencode.jsonc");- const configJson = join19(configDir, "opencode.json");- if (existsSync17(configJsonc)) {+ const configJsonc = join20(configDir, "opencode.jsonc");+ const configJson = join20(configDir, "opencode.json");+ if (existsSync18(configJsonc)) {return { format: "jsonc", path: configJsonc };}- if (existsSync17(configJson)) {+ if (existsSync18(configJson)) {return { format: "json", path: configJson };}return { format: "none", path: configJson };}function getParentConfigDirForProfile(configDir) {- const parentDir = dirname8(configDir);- if (basename2(parentDir) !== "profiles")+ const parentDir = dirname9(configDir);+ if (basename3(parentDir) !== "profiles")return null;- return dirname8(parentDir);+ return dirname9(parentDir);}function listProfileConfigDirs(rootConfigDir) {- const profilesDir = join19(rootConfigDir, "profiles");- if (!existsSync17(profilesDir))+ const profilesDir = join20(rootConfigDir, "profiles");+ if (!existsSync18(profilesDir))return [];- return readdirSync4(profilesDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => join19(profilesDir, entry.name)).filter((profileDir) => detectConfigFormatInDir(profileDir).format !== "none");+ return readdirSync5(profilesDir, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => join20(profilesDir, entry.name)).filter((profileDir) => detectConfigFormatInDir(profileDir).format !== "none");}function getConfigTargets() {const primaryConfigDir = getConfigDir();@@ -76941,7 +77102,7 @@ function writePluginEntryToTarget(params) {try {if (target.format === "none") {const config = { plugin: [pluginEntry] };- writeFileSync5(target.path, JSON.stringify(config, null, 2) + `+ writeFileSync6(target.path, JSON.stringify(config, null, 2) + ``);return { success: true, configPath: target.path };}@@ -76984,15 +77145,15 @@ function writePluginEntryToTarget(params) {normalizedPlugins.push(nextPluginEntry);config.plugin = normalizedPlugins;if (target.format === "jsonc") {- const content = readFileSync7(target.path, "utf-8");+ const content = readFileSync8(target.path, "utf-8");const edits = modify(content, ["plugin"], normalizedPlugins, {formattingOptions: { insertSpaces: true, tabSize: 2, eol: `` },getInsertionIndex: () => 0});- writeFileSync5(target.path, applyEdits(content, edits));+ writeFileSync6(target.path, applyEdits(content, edits));} else {- writeFileSync5(target.path, JSON.stringify(config, null, 2) + `+ writeFileSync6(target.path, JSON.stringify(config, null, 2) + ``);}return { success: true, configPath: target.path };@@ -77383,13 +77544,13 @@ var init_generate_omo_config = __esm(() => {});// packages/omo-opencode/src/config-migration/types.ts-import { existsSync as existsSync18, readdirSync as readdirSync5, realpathSync as realpathSync5 } from "fs";+import { existsSync as existsSync19, readdirSync as readdirSync6, realpathSync as realpathSync6 } from "fs";var DEFAULT_DISCOVERY_FILE_SYSTEM;var init_types6 = __esm(() => {DEFAULT_DISCOVERY_FILE_SYSTEM = {- existsSync: existsSync18,- readdirSync: readdirSync5,- realpathSync: realpathSync5+ existsSync: existsSync19,+ readdirSync: readdirSync6,+ realpathSync: realpathSync6};});@@ -78410,14 +78571,14 @@ function deepMergeRecord(target, source) {}// packages/omo-opencode/src/cli/config-manager/write-omo-config.ts-import { existsSync as existsSync19, readFileSync as readFileSync8 } from "fs";+import { existsSync as existsSync20, readFileSync as readFileSync9 } from "fs";function record2(value) {return value !== null && typeof value === "object" && !Array.isArray(value) ? value : {};}function existingOpenCodeConfig(path) {- if (!existsSync19(path))+ if (!existsSync20(path))return {};- const document = parseJsonc(readFileSync8(path, "utf-8"));+ const document = parseJsonc(readFileSync9(path, "utf-8"));return record2(document["[opencode]"]);}function writeOmoConfig(installConfig) {@@ -78615,10 +78776,10 @@ var init_opencode_binary = __esm(() => {});// packages/omo-opencode/src/cli/config-manager/detect-current-config.ts-import { existsSync as existsSync20, readFileSync as readFileSync9 } from "fs";+import { existsSync as existsSync21, readFileSync as readFileSync10 } from "fs";function detectProvidersFromOmoConfig() {const omoConfigPath = getOmoConfigPath();- if (!existsSync20(omoConfigPath)) {+ if (!existsSync21(omoConfigPath)) {return {hasOpenAI: true,hasOpencodeZen: true,@@ -78632,7 +78793,7 @@ function detectProvidersFromOmoConfig() {};}try {- const content = readFileSync9(omoConfigPath, "utf-8");+ const content = readFileSync10(omoConfigPath, "utf-8");const omoConfig = parseJsonc(content);if (!omoConfig || typeof omoConfig !== "object") {return {@@ -78772,10 +78933,10 @@ var init_detect_current_config = __esm(() => {});// packages/omo-opencode/src/cli/config-manager/bun-install.ts-import { existsSync as existsSync21 } from "fs";-import { join as join20 } from "path";+import { existsSync as existsSync22 } from "fs";+import { join as join21 } from "path";function getDefaultWorkspaceDir() {- return join20(getOpenCodeCacheDir(), "packages");+ return join21(getOpenCodeCacheDir(), "packages");}function readProcessOutput(stream) {if (!stream) {@@ -78801,7 +78962,7 @@ async function runBunInstallWithDetails(options) {const outputMode = options?.outputMode ?? "pipe";const cacheDir = options?.workspaceDir ?? getDefaultWorkspaceDir();const packageJsonPath = `${cacheDir}/package.json`;- if (!existsSync21(packageJsonPath)) {+ if (!existsSync22(packageJsonPath)) {return {success: false,error: `Workspace not initialized: ${packageJsonPath} not found. OpenCode should create this on first run.`@@ -78882,14 +79043,14 @@ var init_config_manager = __esm(() => {});// packages/telemetry-core/src/day-claim.ts-import { closeSync as closeSync3, mkdirSync as mkdirSync8, openSync as openSync3, readdirSync as readdirSync7, rmSync as rmSync2 } from "fs";-import { join as join51 } from "path";+import { closeSync as closeSync3, mkdirSync as mkdirSync9, openSync as openSync3, readdirSync as readdirSync8, rmSync as rmSync3 } from "fs";+import { join as join52 } from "path";function getTelemetryDayClaimFilePath(stateDir, dayUTC) {- return join51(stateDir, `${CLAIM_PREFIX}${dayUTC}${CLAIM_SUFFIX}`);+ return join52(stateDir, `${CLAIM_PREFIX}${dayUTC}${CLAIM_SUFFIX}`);}function claimUtcDay(stateDir, dayUTC) {try {- mkdirSync8(stateDir, { recursive: true });+ mkdirSync9(stateDir, { recursive: true });closeSync3(openSync3(getTelemetryDayClaimFilePath(stateDir, dayUTC), "wx"));} catch (error) {return error.code === "EEXIST" ? "already-claimed" : "unavailable";@@ -78901,7 +79062,7 @@ function pruneSupersededClaims(stateDir, dayUTC) {const currentClaim = `${CLAIM_PREFIX}${dayUTC}${CLAIM_SUFFIX}`;let entries;try {- entries = readdirSync7(stateDir);+ entries = readdirSync8(stateDir);} catch {return;}@@ -78911,7 +79072,7 @@ function pruneSupersededClaims(stateDir, dayUTC) {if (!entry.startsWith(CLAIM_PREFIX) || !entry.endsWith(CLAIM_SUFFIX))continue;try {- rmSync2(join51(stateDir, entry), { force: true });+ rmSync3(join52(stateDir, entry), { force: true });} catch {}}}@@ -78919,21 +79080,21 @@ var CLAIM_PREFIX = "daily-active.", CLAIM_SUFFIX = ".claim";var init_day_claim = () => {};// packages/telemetry-core/src/activity-state.ts-import { existsSync as existsSync24, mkdirSync as mkdirSync9, readFileSync as readFileSync11 } from "fs";-import { basename as basename8, join as join52 } from "path";+import { existsSync as existsSync25, mkdirSync as mkdirSync10, readFileSync as readFileSync12 } from "fs";+import { basename as basename9, join as join53 } from "path";function resolveTelemetryStateDir(product, options = {}) {const dataDir = resolveXdgDataDir(product.cacheDirName, {env: options.env,osProvider: options.osProvider});- const xdgStateDir = options.env?.XDG_DATA_HOME === undefined ? undefined : join52(options.env.XDG_DATA_HOME, product.cacheDirName);- if (dataDir === xdgStateDir || xdgStateDir === undefined && basename8(dataDir) === product.cacheDirName) {+ const xdgStateDir = options.env?.XDG_DATA_HOME === undefined ? undefined : join53(options.env.XDG_DATA_HOME, product.cacheDirName);+ if (dataDir === xdgStateDir || xdgStateDir === undefined && basename9(dataDir) === product.cacheDirName) {return dataDir;}- return join52(dataDir, product.cacheDirName);+ return join53(dataDir, product.cacheDirName);}function getTelemetryActivityStateFilePath(stateDir) {- return join52(stateDir, POSTHOG_ACTIVITY_STATE_FILE);+ return join53(stateDir, POSTHOG_ACTIVITY_STATE_FILE);}function getDailyActiveCaptureState(input) {const dayUTC = getUtcDayString(input.now ?? new Date);@@ -78966,11 +79127,11 @@ function isPostHogActivityState(value) {}function readPostHogActivityState(stateDir, diagnostics) {const stateFilePath = getTelemetryActivityStateFilePath(stateDir);- if (!existsSync24(stateFilePath)) {+ if (!existsSync25(stateFilePath)) {return {};}try {- const stateContent = readFileSync11(stateFilePath, "utf-8");+ const stateContent = readFileSync12(stateFilePath, "utf-8");const stateJson = JSON.parse(stateContent);if (!isPostHogActivityState(stateJson)) {return {};@@ -78989,7 +79150,7 @@ function readPostHogActivityState(stateDir, diagnostics) {function writePostHogActivityState(stateDir, nextState, diagnostics) {const stateFilePath = getTelemetryActivityStateFilePath(stateDir);try {- mkdirSync9(stateDir, { recursive: true });+ mkdirSync10(stateDir, { recursive: true });writeFileAtomically(stateFilePath, `${JSON.stringify(nextState, null, 2)}`);} catch (error) {@@ -79013,16 +79174,16 @@ var init_activity_state = __esm(() => {var DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com", DEFAULT_POSTHOG_API_KEY = "phc_CFJhj5HyvA62QPhvyaUCtaq23aUfznnijg5VaaGkNk74", UNCONFIGURED_POSTHOG_API_KEY = "phc_REPLACE_ME_OMO_NATIVE";// packages/telemetry-core/src/diagnostics.ts-import { appendFileSync as appendFileSync2, existsSync as existsSync25, mkdirSync as mkdirSync10, readFileSync as readFileSync12 } from "fs";-import { join as join53 } from "path";+import { appendFileSync as appendFileSync2, existsSync as existsSync26, mkdirSync as mkdirSync11, readFileSync as readFileSync13 } from "fs";+import { join as join54 } from "path";function getTelemetryDiagnosticsFilePath(diagnosticsDir) {- return join53(diagnosticsDir, DIAGNOSTICS_FILE_NAME);+ return join54(diagnosticsDir, DIAGNOSTICS_FILE_NAME);}function writeTelemetryDiagnostic(input, options) {const now = options.now ?? new Date;try {cleanupTelemetryDiagnostics({ diagnosticsDir: options.diagnosticsDir, now });- mkdirSync10(options.diagnosticsDir, { recursive: true });+ mkdirSync11(options.diagnosticsDir, { recursive: true });appendFileSync2(getTelemetryDiagnosticsFilePath(options.diagnosticsDir), `${JSON.stringify(toDiagnosticRecord(input, now))}`, "utf-8");} catch (error) {@@ -79034,12 +79195,12 @@ function writeTelemetryDiagnostic(input, options) {}function cleanupTelemetryDiagnostics(options) {const diagnosticsFilePath = getTelemetryDiagnosticsFilePath(options.diagnosticsDir);- if (!existsSync25(diagnosticsFilePath)) {+ if (!existsSync26(diagnosticsFilePath)) {return;}try {const cutoffMs = (options.now ?? new Date).getTime() - DIAGNOSTICS_RETENTION_MS;- const retainedLines = trimToMaxBytes(readFileSync12(diagnosticsFilePath, "utf-8").split(`+ const retainedLines = trimToMaxBytes(readFileSync13(diagnosticsFilePath, "utf-8").split(``).filter((line) => shouldRetainLine(line, cutoffMs)));writeFileAtomically(diagnosticsFilePath, retainedLines.length === 0 ? "" : `${retainedLines.join(``)}@@ -79181,7 +79342,7 @@ var init_env = __esm(() => {});// node_modules/.bun/[email protected]/node_modules/posthog-node/dist/extensions/error-tracking/modifiers/module.node.mjs-import { dirname as dirname17, posix as posix7, sep as sep7 } from "path";+import { dirname as dirname18, posix as posix7, sep as sep7 } from "path";function createModulerModifier() {const getModuleFromFileName = createGetModuleFromFilename();return async (frames) => {@@ -79190,7 +79351,7 @@ function createModulerModifier() {return frames;};}-function createGetModuleFromFilename(basePath = process.argv[1] ? dirname17(process.argv[1]) : process.cwd(), isWindows = sep7 === "\\") {+function createGetModuleFromFilename(basePath = process.argv[1] ? dirname18(process.argv[1]) : process.cwd(), isWindows = sep7 === "\\") {const normalizedBase = isWindows ? normalizeWindowsPath(basePath) : basePath;return (filename) => {if (!filename)@@ -88759,7 +88920,7 @@ var package_default2;var init_package2 = __esm(() => {package_default2 = {name: "@oh-my-opencode/omo-codex",- version: "5.0.0-beta.89",+ version: "5.0.0-beta.90",type: "module",private: true,description: "Codex harness adapter for oh-my-openagent. Vendored Codex plugin namespace (omo) + TypeScript installer + telemetry.",@@ -88949,6 +89110,40 @@ var init_telemetry2 = __esm(() => {init_posthog();});+// packages/omo-opencode/src/hooks/auto-update-checker/checker/bundled-version.ts+function getBundledVersion() {+ return package_default.version;+}+var init_bundled_version = __esm(() => {+ init_package();+});++// packages/omo-opencode/src/hooks/auto-update-checker/version-channel.ts+function isPrereleaseVersion(version) {+ return version.includes("-");+}+function isDistTag(version) {+ const startsWithDigit = /^\d/.test(version);+ return !startsWithDigit;+}+function extractChannel(version) {+ if (!version)+ return "latest";+ if (isDistTag(version)) {+ return version;+ }+ if (isPrereleaseVersion(version)) {+ const prereleasePart = version.split("-")[1];+ if (prereleasePart) {+ const channelMatch = prereleasePart.match(/^(alpha|beta|rc|canary|next)/);+ if (channelMatch) {+ return channelMatch[1];+ }+ }+ }+ return "latest";+}+// node_modules/.bun/[email protected]/node_modules/sisteransi/src/index.jsvar require_src = __commonJS(function(exports, module) {var ESC = "\x1B";@@ -89278,11 +89473,6 @@ var init_cached_version = __esm(() => {init_package_json_locator();});-// packages/omo-opencode/src/hooks/auto-update-checker/checker/bundled-version.ts-var init_bundled_version = __esm(() => {- init_package();-});-// packages/omo-opencode/src/hooks/auto-update-checker/checker/pinned-version-updater.tsvar init_pinned_version_updater = __esm(() => {init_logger2();@@ -89312,40 +89502,73 @@ var init_latest_version = __esm(() => {init_constants5();});-// packages/omo-opencode/src/hooks/auto-update-checker/version-channel.ts-function isPrereleaseVersion(version) {- return version.includes("-");-}-function isDistTag(version) {- const startsWithDigit = /^\d/.test(version);- return !startsWithDigit;+// packages/omo-opencode/src/hooks/auto-update-checker/checker/semver-compare.ts+function parseSemver(version) {+ const match = SEMVER_REGEX.exec(version.trim());+ if (!match)+ return null;+ const [, major, minor, patch, prerelease] = match;+ return {+ core: [Number(major), Number(minor), Number(patch)],+ prerelease: prerelease ? prerelease.split(".") : []+ };}-function extractChannel(version) {- if (!version)- return "latest";- if (isDistTag(version)) {- return version;+function comparePrerelease(a, b) {+ if (a.length === 0 && b.length === 0)+ return 0;+ if (a.length === 0)+ return 1;+ if (b.length === 0)+ return -1;+ const length = Math.min(a.length, b.length);+ for (let i = 0;i < length; i++) {+ const idA = a[i] ?? "";+ const idB = b[i] ?? "";+ if (idA === idB)+ continue;+ const numA = /^\d+$/.test(idA);+ const numB = /^\d+$/.test(idB);+ if (numA && numB)+ return Number(idA) < Number(idB) ? -1 : 1;+ if (numA)+ return -1;+ if (numB)+ return 1;+ return idA < idB ? -1 : 1;}- if (isPrereleaseVersion(version)) {- const prereleasePart = version.split("-")[1];- if (prereleasePart) {- const channelMatch = prereleasePart.match(/^(alpha|beta|rc|canary|next)/);- if (channelMatch) {- return channelMatch[1];- }- }+ if (a.length === b.length)+ return 0;+ return a.length < b.length ? -1 : 1;+}+function compareSemverVersions(a, b) {+ const parsedA = parseSemver(a);+ const parsedB = parseSemver(b);+ if (!parsedA || !parsedB)+ return null;+ for (let i = 0;i < 3; i++) {+ const partA = parsedA.core[i] ?? 0;+ const partB = parsedB.core[i] ?? 0;+ if (partA !== partB)+ return partA < partB ? -1 : 1;}- return "latest";+ return comparePrerelease(parsedA.prerelease, parsedB.prerelease);+}+function isStrictlyNewerVersion(currentVersion, latestVersion) {+ return compareSemverVersions(currentVersion, latestVersion) === -1;}+var SEMVER_REGEX;+var init_semver_compare = __esm(() => {+ SEMVER_REGEX = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;+});// packages/omo-opencode/src/hooks/auto-update-checker/checker/check-for-update.tsvar init_check_for_update = __esm(() => {init_logger2();- init_opencode_version();init_local_dev_path();init_plugin_entry();init_cached_version();init_latest_version();+ init_semver_compare();});// packages/omo-opencode/src/hooks/auto-update-checker/checker/sync-package-json.ts@@ -89461,6 +89684,76 @@ var init_sync_package_json = __esm(() => {EXACT_SEMVER_REGEX2 = /^\d+\.\d+\.\d+(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$/;});+// packages/omo-opencode/src/hooks/auto-update-checker/checker/sandbox-refresh.ts+function refreshMarkedSandbox(sandboxDir, cacheDir, pid) {+ try {+ releasePluginSandboxLease(sandboxDir, pid);+ if (!isPluginSandboxMarkedStale(sandboxDir))+ return;+ if (hasOtherLivePluginSandboxLease(sandboxDir, pid)) {+ markPluginSandboxStale(sandboxDir, cacheDir, "another OpenCode window was still open", pid);+ log2(`[auto-update-checker] Another OpenCode process still runs from ${sandboxDir}; the last one to exit refreshes it`);+ return;+ }+ const removed = removePluginSandbox(sandboxDir, cacheDir);+ log2(removed ? `[auto-update-checker] Removed stale OpenCode plugin sandbox on exit: ${sandboxDir}` : `[auto-update-checker] OpenCode plugin sandbox already gone: ${sandboxDir}`);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log2(`[auto-update-checker] Failed to remove OpenCode plugin sandbox ${sandboxDir}: ${message}`);+ try {+ markPluginSandboxStale(sandboxDir, cacheDir, `could not remove it: ${message}`, pid);+ } catch (markError) {+ log2(`[auto-update-checker] Could not record the failed refresh of ${sandboxDir}:`, markError);+ }+ }+}+function trackPluginSandbox(sandboxDir, deps = {}) {+ const cacheDir = deps.cacheDir ?? getOpenCodeCacheDir();+ if (!isPluginSandboxDir(sandboxDir, cacheDir))+ return false;+ if (trackedSandboxDirs.has(sandboxDir))+ return true;+ trackedSandboxDirs.add(sandboxDir);+ const pid = deps.pid ?? process.pid;+ try {+ acquirePluginSandboxLease(sandboxDir, pid);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log2(`[auto-update-checker] Could not lease OpenCode plugin sandbox ${sandboxDir}: ${message}`);+ }+ const onExit = deps.onExit ?? ((callback) => process.once("exit", callback));+ onExit(() => refreshMarkedSandbox(sandboxDir, cacheDir, pid));+ return true;+}+function scheduleOpenCodeSandboxRefreshOnExit(sandboxDir, deps = {}) {+ const cacheDir = deps.cacheDir ?? getOpenCodeCacheDir();+ if (!isPluginSandboxDir(sandboxDir, cacheDir)) {+ log2(`[auto-update-checker] Not an OpenCode plugin sandbox, leaving it alone: ${sandboxDir}`);+ return null;+ }+ const pid = deps.pid ?? process.pid;+ let unapplied;+ try {+ unapplied = describeUnappliedPluginSandboxRefresh(sandboxDir, pid);+ markPluginSandboxStale(sandboxDir, cacheDir, "", pid);+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log2(`[auto-update-checker] Could not request a refresh of OpenCode plugin sandbox ${sandboxDir}: ${message}`);+ return `could not request it: ${message}`;+ }+ trackPluginSandbox(sandboxDir, { ...deps, cacheDir });+ log2(`[auto-update-checker] Scheduled OpenCode plugin sandbox refresh on exit: ${sandboxDir}`);+ return unapplied;+}+var trackedSandboxDirs;+var init_sandbox_refresh = __esm(() => {+ init_logger2();+ init_data_path();+ init_opencode_plugin_sandbox();+ init_package_json_locator();+ trackedSandboxDirs = new Set;+});+// packages/omo-opencode/src/hooks/auto-update-checker/checker.tsvar init_checker = __esm(() => {init_local_dev_path();@@ -89472,6 +89765,8 @@ var init_checker = __esm(() => {init_latest_version();init_check_for_update();init_sync_package_json();+ init_semver_compare();+ init_sandbox_refresh();});// packages/omo-opencode/src/hooks/auto-update-checker/cache.ts@@ -89630,20 +89925,20 @@ var init_update_toasts = __esm(() => {});// packages/omo-opencode/src/hooks/auto-update-checker/hook/background-update-check.ts-import { existsSync as existsSync46 } from "fs";-import { dirname as dirname30, join as join75 } from "path";+import { existsSync as existsSync48 } from "fs";+import { dirname as dirname32, join as join78 } from "path";import { fileURLToPath as fileURLToPath5 } from "url";function defaultGetModuleHostingWorkspace() {try {- const currentDir = dirname30(fileURLToPath5(import.meta.url));+ const currentDir = dirname32(fileURLToPath5(import.meta.url));const pkgJsonPath = findPackageJsonUp(currentDir);if (!pkgJsonPath)return null;- const pkgDir = dirname30(pkgJsonPath);- const nodeModulesDir = dirname30(pkgDir);+ const pkgDir = dirname32(pkgJsonPath);+ const nodeModulesDir = dirname32(pkgDir);if (nodeModulesDir.split(/[\\/]/).pop() !== "node_modules")return null;- return dirname30(nodeModulesDir);+ return dirname32(nodeModulesDir);} catch (error) {if (error instanceof Error) {return null;@@ -89657,6 +89952,9 @@ function getCacheWorkspaceDir(deps) {function getPinnedVersionToastMessage(latestVersion) {return `Update available: ${latestVersion} (version pinned, update manually)`;}+function getUnappliedRefreshToastMessage(latestVersion, reason, sandboxDir) {+ return `v${latestVersion} available, but the last restart could not apply it (${reason}). Close every OpenCode window and start it again; if this notice returns, delete ${sandboxDir} (known issue #5367).`;+}function isOpenCodeManagedSandbox(moduleWorkspace, cacheWorkspace, configDir) {if (!moduleWorkspace)return false;@@ -89728,8 +90026,8 @@ function createBackgroundUpdateCheckRunner(overrides = {}) {deps.log("[auto-update-checker] Failed to fetch latest version for channel:", channel);return;}- if (currentVersion === latestVersion) {- deps.log("[auto-update-checker] Already on latest version for channel:", channel);+ if (!isStrictlyNewerVersion(currentVersion, latestVersion)) {+ deps.log(`[auto-update-checker] No newer version for channel ${channel} (current: ${currentVersion}, registry: ${latestVersion})`);return;}deps.log(`[auto-update-checker] Update available (${channel}): ${currentVersion} \u2192 ${latestVersion}`);@@ -89745,8 +90043,9 @@ function createBackgroundUpdateCheckRunner(overrides = {}) {}const moduleWorkspace = deps.getModuleHostingWorkspace();if (isOpenCodeManagedSandbox(moduleWorkspace, getCacheWorkspaceDir(deps), deps.getOpenCodeConfigPaths({ binary: "opencode" }).configDir)) {- await deps.showUpdateAvailableToast(ctx, latestVersion, getToastMessage);- deps.log(`[auto-update-checker] OpenCode-managed sandbox detected (${moduleWorkspace}); skipping auto-update install. Notification only. See #4318.`);+ const unapplied = moduleWorkspace ? deps.scheduleSandboxRefresh(moduleWorkspace) : null;+ await deps.showUpdateAvailableToast(ctx, latestVersion, unapplied && moduleWorkspace ? () => getUnappliedRefreshToastMessage(latestVersion, unapplied, moduleWorkspace) : getToastMessage);+ deps.log(`[auto-update-checker] OpenCode-managed sandbox detected (${moduleWorkspace}); sandbox refresh scheduled for exit. See #4318/#5367.`);return;}const syncResult = deps.syncCachePackageJsonToIntent(pluginInfo);@@ -89782,10 +90081,12 @@ var init_background_update_check = __esm(() => {init_constants5();init_checker();init_package_json_locator();+ init_sandbox_refresh();+ init_semver_compare();init_update_toasts();defaultDeps4 = {- existsSync: existsSync46,- join: join75,+ existsSync: existsSync48,+ join: join78,runBunInstallWithDetails,log: log2,getOpenCodeCacheDir,@@ -89798,7 +90099,8 @@ var init_background_update_check = __esm(() => {syncCachePackageJsonToIntent,showUpdateAvailableToast,showAutoUpdatedToast,- getModuleHostingWorkspace: defaultGetModuleHostingWorkspace+ getModuleHostingWorkspace: defaultGetModuleHostingWorkspace,+ scheduleSandboxRefresh: scheduleOpenCodeSandboxRefreshOnExit};runBackgroundUpdateCheck = createBackgroundUpdateCheckRunner();});@@ -89841,6 +90143,7 @@ var init_hook = __esm(() => {init_logger2();init_checker();init_background_update_check();+ init_sandbox_refresh();init_config_errors_toast();init_connected_providers_status();init_model_capabilities_status();@@ -92212,7 +92515,7 @@ function getUnsupportedOpenCodeVersionMessage(openCodeVersion) {}// packages/omo-codex/src/install/install-codex.ts-import { join as join54, resolve as resolve12 } from "path";+import { join as join55, resolve as resolve13 } from "path";// packages/omo-codex/src/install/codex-default-role-config.tsinit_src4();@@ -92225,12 +92528,12 @@ function readDefaultRoleConfig(options = {}) {}// packages/omo-codex/src/install/install-codex.ts-import { existsSync as existsSync26 } from "fs";+import { existsSync as existsSync27 } from "fs";import { homedir as homedir6 } from "os";// packages/omo-codex/src/install/codex-cache-bins.tsimport { chmod, lstat as lstat4, mkdir, readFile as readFile3, readdir as readdir2, readlink as readlink3, rm as rm3, stat as stat2, symlink, writeFile } from "fs/promises";-import { basename as basename3, isAbsolute as isAbsolute2, join as join24, relative, resolve as resolve5, sep } from "path";+import { basename as basename4, isAbsolute as isAbsolute2, join as join25, relative, resolve as resolve6, sep } from "path";// packages/omo-codex/src/install/codex-cache-command-shim.tsvar COMMAND_SHIM_MARKER = ":: generated by oh-my-openagent Codex installer";@@ -92275,7 +92578,7 @@ function windowsCommandShim(targetPath) {// packages/omo-codex/src/install/codex-cache-dangling-bins.tsimport { lstat as lstat2, readFile, readdir, readlink, rm, stat } from "fs/promises";-import { dirname as dirname9, isAbsolute, join as join21, resolve as resolve4 } from "path";+import { dirname as dirname10, isAbsolute, join as join22, resolve as resolve5 } from "path";// packages/omo-codex/src/install/codex-cache-fs.tsimport { lstat } from "fs/promises";@@ -92303,7 +92606,7 @@ async function removeDanglingManagedComponentBins(binDir, platform, managedBinNaconst binName = managedBinNameForEntry(entry.name, platform);if (binName === null || !managedBinNames.has(binName))continue;- const linkPath = join21(binDir, entry.name);+ const linkPath = join22(binDir, entry.name);if (platform === "win32") {await removeDanglingGeneratedCommandShim(linkPath);continue;@@ -92322,7 +92625,7 @@ async function removeDanglingManagedSymlink(linkPath) {if (!linkStat.isSymbolicLink())return;const linkTarget = await readlink(linkPath);- const target = isAbsolute(linkTarget) ? linkTarget : resolve4(dirname9(linkPath), linkTarget);+ const target = isAbsolute(linkTarget) ? linkTarget : resolve5(dirname10(linkPath), linkTarget);if (!await isFileSystemEntry(target) && isManagedComponentBinTarget(target))await rm(linkPath, { force: true });} catch (error) {@@ -92385,7 +92688,7 @@ function hasOmoCodexPluginPrefix(parts, endExclusive) {// packages/omo-codex/src/install/codex-cache-legacy-bins.tsimport { lstat as lstat3, readFile as readFile2, readlink as readlink2, rm as rm2 } from "fs/promises";-import { join as join22 } from "path";+import { join as join23 } from "path";var LEGACY_CODEX_COMPONENT_BINS = [{ name: "omo", component: "ulw-loop" },{ name: "codex-comment-checker", component: "comment-checker" },@@ -92402,7 +92705,7 @@ function isLegacyCodexBinTarget(binName, target) {}async function removeLegacyCodexComponentBins(binDir, platform) {for (const entry of LEGACY_CODEX_COMPONENT_BINS) {- const linkPath = join22(binDir, platform === "win32" ? `${entry.name}.cmd` : entry.name);+ const linkPath = join23(binDir, platform === "win32" ? `${entry.name}.cmd` : entry.name);await removeLegacyCodexComponentBin(linkPath, entry.component, platform);}}@@ -92453,10 +92756,10 @@ function isNodeErrorWithCode2(error) {}// packages/omo-codex/src/install/codex-cache-runtime-wrapper.ts-import { join as join23 } from "path";+import { join as join24 } from "path";var RUNTIME_WRAPPER_MARKER = "OMO_GENERATED_RUNTIME_WRAPPER";function posixRuntimeWrapper(binName, cliPath, codexHome, binDir, nodeCliPath) {- const ulwLoopBin = toPosixPath2(join23(binDir, "omo-ulw-loop"));+ const ulwLoopBin = toPosixPath2(join24(binDir, "omo-ulw-loop"));const nodeCli = escapePosixDoubleQuoted(toPosixPath2(nodeCliPath));const escapedCliPath = escapePosixDoubleQuoted(toPosixPath2(cliPath));const escapedCodexHome = escapePosixDoubleQuoted(toPosixPath2(codexHome));@@ -92503,7 +92806,7 @@ function posixRuntimeWrapper(binName, cliPath, codexHome, binDir, nodeCliPath) {`);}function windowsRuntimeWrapper(binName, cliPath, codexHome, binDir, nodeCliPath) {- const ulwLoopBin = join23(binDir, "omo-ulw-loop.cmd");+ const ulwLoopBin = join24(binDir, "omo-ulw-loop.cmd");return ["@echo off",`rem ${RUNTIME_WRAPPER_MARKER}`,@@ -92572,34 +92875,34 @@ async function removeCachedManagedNpmBinShims(pluginRoot) {const binLinks = await discoverPackageBins(pluginRoot);if (binLinks.length === 0)return;- const npmBinDir = join24(pluginRoot, "node_modules", ".bin");+ const npmBinDir = join25(pluginRoot, "node_modules", ".bin");if (!await isFileSystemEntry2(npmBinDir))return;const managedBinNames = new Set(binLinks.map((link) => link.name));for (const name of managedBinNames) {for (const suffix of ["", ".cmd", ".ps1"]) {- await rm3(join24(npmBinDir, `${name}${suffix}`), { force: true });+ await rm3(join25(npmBinDir, `${name}${suffix}`), { force: true });}}}async function linkRootRuntimeBin(input) {- const cliPath = join24(input.repoRoot, "dist", "cli", "index.js");+ const cliPath = join25(input.repoRoot, "dist", "cli", "index.js");const platform = input.platform ?? process.platform;- const legacyPath = join24(input.binDir, platform === "win32" ? "omo.cmd" : "omo");+ const legacyPath = join25(input.binDir, platform === "win32" ? "omo.cmd" : "omo");if (!await isFile(cliPath)) {await removeGeneratedRuntimeWrapper(legacyPath);return null;}const binName = "omo-agent-toolkit";- const nodeCliPath = join24(input.repoRoot, "dist", "cli-node", "index.js");+ const nodeCliPath = join25(input.repoRoot, "dist", "cli-node", "index.js");await mkdir(input.binDir, { recursive: true });if (platform === "win32") {- const linkPath = join24(input.binDir, `${binName}.cmd`);+ const linkPath = join25(input.binDir, `${binName}.cmd`);await replaceRuntimeWrapper(linkPath, windowsRuntimeWrapper(binName, cliPath, input.codexHome, input.binDir, nodeCliPath));await removeGeneratedRuntimeWrapper(legacyPath);return { name: binName, path: linkPath, target: cliPath };}- const linkPath = join24(input.binDir, binName);+ const linkPath = join25(input.binDir, binName);await replaceRuntimeWrapper(linkPath, posixRuntimeWrapper(binName, cliPath, input.codexHome, input.binDir, nodeCliPath));await chmod(linkPath, 493);await removeGeneratedRuntimeWrapper(legacyPath);@@ -92607,11 +92910,11 @@ async function linkRootRuntimeBin(input) {}async function linkCachedPluginBin(binDir, link, platform) {if (platform === "win32") {- const linkPath = join24(binDir, `${link.name}.cmd`);+ const linkPath = join25(binDir, `${link.name}.cmd`);await replaceCommandShim(linkPath, link.target);return linkPath;}- const linkPath = join24(binDir, link.name);+ const linkPath = join25(binDir, link.name);await replaceSymlink(linkPath, link.target);return linkPath;}@@ -92642,14 +92945,14 @@ async function discoverPackageBins(root) {async function collectPackageBins(directory, root, links) {const entries = await readdir2(directory, { withFileTypes: true });if (entries.some((entry) => entry.isFile() && entry.name === "package.json")) {- await appendPackageBinLinks(join24(directory, "package.json"), directory, root, links);+ await appendPackageBinLinks(join25(directory, "package.json"), directory, root, links);}for (const entry of entries) {if (!entry.isDirectory())continue;if (entry.name === "node_modules" || entry.name === ".git" || entry.name === "dist")continue;- const childPath = join24(directory, entry.name);+ const childPath = join25(directory, entry.name);if (!childPath.startsWith(root))continue;await collectPackageBins(childPath, root, links);@@ -92662,7 +92965,7 @@ async function appendPackageBinLinks(packageJsonPath, packageRoot, root, links)const packageName = packageJson.name;const packageBin = packageJson.bin;if (typeof packageBin === "string" && typeof packageName === "string") {- const name = assertSafeCommandName(basename3(packageName));+ const name = assertSafeCommandName(basename4(packageName));if (!isReservedNestedBinName(name, packageRoot, root)) {links.push({ name, target: resolvePackageBinTarget(packageRoot, packageBin) });}@@ -92691,8 +92994,8 @@ function isReservedNestedBinName(name, packageRoot, root) {function resolvePackageBinTarget(packageRoot, target) {if (target.includes("\x00"))throw new Error("Package bin target must stay inside package root");- const root = resolve5(packageRoot);- const resolvedTarget = resolve5(root, target);+ const root = resolve6(packageRoot);+ const resolvedTarget = resolve6(root, target);const relativeTarget = relative(root, resolvedTarget);if (relativeTarget === "" || relativeTarget !== ".." && !relativeTarget.startsWith(`..${sep}`) && !isAbsolute2(relativeTarget)) {return resolvedTarget;@@ -92784,11 +93087,11 @@ async function existingNonSymlink(path) {}// packages/omo-codex/src/install/codex-cache-install.tsimport { cp as cp2, mkdir as mkdir3, readFile as readFile8, readdir as readdir4, rename, rm as rm4 } from "fs/promises";-import { basename as basename4, dirname as dirname12, join as join30, sep as sep5 } from "path";+import { basename as basename5, dirname as dirname13, join as join31, sep as sep5 } from "path";// packages/omo-codex/src/install/codex-cache-bundled-mcps.tsimport { cp, mkdir as mkdir2, readFile as readFile4, stat as stat3 } from "fs/promises";-import { dirname as dirname10, join as join25, resolve as resolve6 } from "path";+import { dirname as dirname11, join as join26, resolve as resolve7 } from "path";var BUNDLED_MCP_RUNTIMES = [{label: "Git Bash MCP",@@ -92806,7 +93109,7 @@ var BUNDLED_MCP_RUNTIMES = [}];async function copyBundledMcpRuntimeDists(input) {- const sourceArgs = await readSourceMcpArgs(join25(input.sourceRoot, ".mcp.json"));+ const sourceArgs = await readSourceMcpArgs(join26(input.sourceRoot, ".mcp.json"));for (const runtime of BUNDLED_MCP_RUNTIMES) {if (!sourceArgs.has(runtime.sourceArg))continue;@@ -92815,15 +93118,15 @@ async function copyBundledMcpRuntimeDists(input) {}function resolveBundledMcpRuntimeArg(pluginRoot, arg) {const runtime = BUNDLED_MCP_RUNTIMES.find((candidate) => candidate.sourceArg === arg);- return runtime ? join25(pluginRoot, runtime.destinationArg) : null;+ return runtime ? join26(pluginRoot, runtime.destinationArg) : null;}async function copyBundledMcpRuntimeDist(pluginRoot, sourceRoot, runtime) {- const sourcePath = resolve6(sourceRoot, runtime.sourceDistFromPlugin);+ const sourcePath = resolve7(sourceRoot, runtime.sourceDistFromPlugin);if (!await isDirectory(sourcePath)) {throw new Error(`missing built ${runtime.label} dist at ${sourcePath}`);}- const destinationPath = join25(pluginRoot, runtime.destinationDistFromPlugin);- await mkdir2(dirname10(destinationPath), { recursive: true });+ const destinationPath = join26(pluginRoot, runtime.destinationDistFromPlugin);+ await mkdir2(dirname11(destinationPath), { recursive: true });await cp(sourcePath, destinationPath, { recursive: true });}async function readSourceMcpArgs(path) {@@ -92859,48 +93162,48 @@ async function isDirectory(path) {}// packages/omo-codex/src/install/codex-cache-local-dependencies.ts-import { realpathSync as realpathSync6 } from "fs";+import { realpathSync as realpathSync7 } from "fs";import { readFile as readFile5, readdir as readdir3, writeFile as writeFile2 } from "fs/promises";-import { dirname as dirname11, isAbsolute as isAbsolute4, join as join27, relative as relative3, resolve as resolve8, sep as sep2 } from "path";+import { dirname as dirname12, isAbsolute as isAbsolute4, join as join28, relative as relative3, resolve as resolve9, sep as sep2 } from "path";// packages/omo-codex/src/install/codex-cache-paths.ts-import { existsSync as existsSync22, readdirSync as readdirSync6 } from "fs";-import { isAbsolute as isAbsolute3, join as join26, relative as relative2, resolve as resolve7 } from "path";+import { existsSync as existsSync23, readdirSync as readdirSync7 } from "fs";+import { isAbsolute as isAbsolute3, join as join27, relative as relative2, resolve as resolve8 } from "path";var DEFAULT_CODEX_MARKETPLACE_NAME = "sisyphuslabs";var DEFAULT_CODEX_PLUGIN_NAME = "omo";function resolveDefaultCodexHome(homeDir) {- return join26(homeDir, ".codex");+ return join27(homeDir, ".codex");}function resolveCodexPluginCacheRoot(codexHome, input = {}) {- return join26(codexHome, "plugins", "cache", input.marketplaceName ?? DEFAULT_CODEX_MARKETPLACE_NAME, input.pluginName ?? DEFAULT_CODEX_PLUGIN_NAME);+ return join27(codexHome, "plugins", "cache", input.marketplaceName ?? DEFAULT_CODEX_MARKETPLACE_NAME, input.pluginName ?? DEFAULT_CODEX_PLUGIN_NAME);}function resolveCachedCodexComponentCliPath(pluginRoot, componentName) {- return join26(pluginRoot, "components", componentName, "dist", "cli.js");+ return join27(pluginRoot, "components", componentName, "dist", "cli.js");}function resolveCodexComponentBinCandidates(input) {return [- input.env.CODEX_LOCAL_BIN_DIR ? join26(input.env.CODEX_LOCAL_BIN_DIR, input.executableName) : undefined,- join26(input.homeDir, ".local", "bin", input.executableName),- join26(resolveDefaultCodexHome(input.homeDir), "bin", input.executableName)+ input.env.CODEX_LOCAL_BIN_DIR ? join27(input.env.CODEX_LOCAL_BIN_DIR, input.executableName) : undefined,+ join27(input.homeDir, ".local", "bin", input.executableName),+ join27(resolveDefaultCodexHome(input.homeDir), "bin", input.executableName)].filter((value) => typeof value === "string");}function findNewestCachedCodexComponentCli(input) {const versionsRoot = resolveCodexPluginCacheRoot(input.codexHome, input);- if (!existsSync22(versionsRoot))+ if (!existsSync23(versionsRoot))return null;- const versions = readdirSync6(versionsRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(compareVersionNames).reverse();+ const versions = readdirSync7(versionsRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(compareVersionNames).reverse();for (const version of versions) {- const candidate = resolveCachedCodexComponentCliPath(join26(versionsRoot, version), input.componentName);- if (existsSync22(candidate))+ const candidate = resolveCachedCodexComponentCliPath(join27(versionsRoot, version), input.componentName);+ if (existsSync23(candidate))return candidate;}return null;}function resolveCachedRuntimePath(pluginRoot, sourceRoot, runtimePath) {- const targetPath = resolve7(pluginRoot, runtimePath);+ const targetPath = resolve8(pluginRoot, runtimePath);if (isPathInside(targetPath, pluginRoot))return targetPath;- return resolve7(sourceRoot, runtimePath);+ return resolve8(sourceRoot, runtimePath);}function isPathInside(candidatePath, rootPath) {const pathFromRoot = relative2(rootPath, candidatePath);@@ -92930,8 +93233,8 @@ async function rewriteCachedPackageLocalFileDependencies(pluginRoot, sourceRoot)const parsed = JSON.parse(raw);if (!isPlainRecord4(parsed))continue;- const packageDir = dirname11(packageJsonPath);- const sourcePackageDir = join27(sourceRoot, relative3(pluginRoot, packageDir));+ const packageDir = dirname12(packageJsonPath);+ const sourcePackageDir = join28(sourceRoot, relative3(pluginRoot, packageDir));let changed = false;for (const field of ["dependencies", "optionalDependencies", "peerDependencies"]) {const dependencies = parsed[field];@@ -92943,10 +93246,10 @@ async function rewriteCachedPackageLocalFileDependencies(pluginRoot, sourceRoot)const filePath = specifier.slice("file:".length);if (filePath.length === 0 || isAbsolute4(filePath))continue;- const targetPath = resolve8(packageDir, filePath);+ const targetPath = resolve9(packageDir, filePath);if (isPathInside(targetPath, pluginRoot))continue;- const sourceTargetPath = resolve8(sourcePackageDir, filePath);+ const sourceTargetPath = resolve9(sourcePackageDir, filePath);dependencies[name] = `file:${sourceTargetPath}`;rewritePackageLockFileDependency({dependencyName: name,@@ -92972,7 +93275,7 @@ async function rewriteCachedPackageLocalFileDependencies(pluginRoot, sourceRoot)return rewroteAnyPackageJson;}async function readPackageLock(pluginRoot) {- const path = join27(pluginRoot, "package-lock.json");+ const path = join28(pluginRoot, "package-lock.json");try {const parsed = JSON.parse(await readFile5(path, "utf8"));return { path, value: isPlainRecord4(parsed) ? parsed : null, changed: false };@@ -93023,7 +93326,7 @@ function toPackageLockPath(path) {}function canonicalizeExistingPath(path) {try {- return realpathSync6(path);+ return realpathSync7(path);} catch (error) {if (error instanceof Error)return path;@@ -93033,14 +93336,14 @@ function canonicalizeExistingPath(path) {async function collectPackageJsonPaths(directory, root, paths) {const entries = await readdir3(directory, { withFileTypes: true });if (entries.some((entry) => entry.isFile() && entry.name === "package.json")) {- paths.push(join27(directory, "package.json"));+ paths.push(join28(directory, "package.json"));}for (const entry of entries) {if (!entry.isDirectory())continue;if (entry.name === "node_modules" || entry.name === ".git" || entry.name === "dist")continue;- const childPath = join27(directory, entry.name);+ const childPath = join28(directory, entry.name);if (!isPathInside(childPath, root))continue;await collectPackageJsonPaths(childPath, root, paths);@@ -93049,10 +93352,10 @@ async function collectPackageJsonPaths(directory, root, paths) {// packages/omo-codex/src/install/codex-cache-mcp-manifest.tsimport { readFile as readFile6, writeFile as writeFile3 } from "fs/promises";-import { join as join28, sep as sep3 } from "path";+import { join as join29, sep as sep3 } from "path";var CONTEXT7_API_KEY_ENV = "CONTEXT7_API_KEY";async function rewriteCachedMcpManifest(pluginRoot, sourceRoot = pluginRoot) {- const manifestPath = join28(pluginRoot, ".mcp.json");+ const manifestPath = join29(pluginRoot, ".mcp.json");if (!await fileExistsStrict(manifestPath))return;const raw = await readFile6(manifestPath, "utf8");@@ -93145,7 +93448,7 @@ function isPlaceholderContext7ApiKey(value) {return normalized.length === 0 || normalized === "your api key";}async function rewriteCachedManifestRoot(pluginRoot, fromRoot, toRoot) {- const manifestPath = join28(pluginRoot, ".mcp.json");+ const manifestPath = join29(pluginRoot, ".mcp.json");if (!await fileExistsStrict(manifestPath))return;const raw = await readFile6(manifestPath, "utf8");@@ -93181,7 +93484,7 @@ async function rewriteCachedManifestRoot(pluginRoot, fromRoot, toRoot) {// packages/omo-codex/src/install/codex-hook-targets.tsimport { readFile as readFile7 } from "fs/promises";-import { join as join29, sep as sep4 } from "path";+import { join as join30, sep as sep4 } from "path";var PLUGIN_ROOT_TARGET_PATTERN = /\$\{PLUGIN_ROOT\}[\\/]+([^"']+)/g;async function findMissingHookCommandTargets(pluginRoot) {const commands = [];@@ -93198,7 +93501,7 @@ async function findMissingHookCommandTargets(pluginRoot) {const targetSuffix = match[1];if (targetSuffix === undefined)continue;- const target = join29(pluginRoot, ...targetSuffix.split(/[\\/]+/));+ const target = join30(pluginRoot, ...targetSuffix.split(/[\\/]+/));if (seen.has(target))continue;seen.add(target);@@ -93209,17 +93512,17 @@ async function findMissingHookCommandTargets(pluginRoot) {return missing;}async function hookManifestPaths(pluginRoot) {- const pluginManifestPath = join29(pluginRoot, ".codex-plugin", "plugin.json");+ const pluginManifestPath = join30(pluginRoot, ".codex-plugin", "plugin.json");if (!await fileExistsStrict(pluginManifestPath))- return [join29(pluginRoot, "hooks", "hooks.json")];+ return [join30(pluginRoot, "hooks", "hooks.json")];const parsed = JSON.parse(await readFile7(pluginManifestPath, "utf8"));if (!isPlainRecord4(parsed))return [];if (typeof parsed.hooks === "string" && parsed.hooks.trim() !== "") {- return [join29(pluginRoot, stripDotSlash(parsed.hooks))];+ return [join30(pluginRoot, stripDotSlash(parsed.hooks))];}if (Array.isArray(parsed.hooks)) {- return parsed.hooks.filter((hookPath) => typeof hookPath === "string" && hookPath.trim() !== "").map((hookPath) => join29(pluginRoot, stripDotSlash(hookPath)));+ return parsed.hooks.filter((hookPath) => typeof hookPath === "string" && hookPath.trim() !== "").map((hookPath) => join30(pluginRoot, stripDotSlash(hookPath)));}return [];}@@ -93257,7 +93560,7 @@ async function installCachedPlugin(input) {await maybeRunNpmInstall(input.sourcePath, input.runCommand, npmInstallEnv);await maybeRunNpmBuild(input.sourcePath, input.runCommand, env);}- const targetPath = join30(input.codexHome, "plugins", "cache", input.marketplaceName, input.name, input.version);+ const targetPath = join31(input.codexHome, "plugins", "cache", input.marketplaceName, input.name, input.version);const tempPath = createTempSiblingPath(targetPath);await rm4(tempPath, { recursive: true, force: true });try {@@ -93283,14 +93586,14 @@ async function installCachedPlugin(input) {return { name: input.name, version: input.version, path: targetPath };}async function maybeRunNpmInstall(cwd, runCommand, env, args = ["install"]) {- if (!await fileExistsStrict(join30(cwd, "package.json")))+ if (!await fileExistsStrict(join31(cwd, "package.json")))return;await runCommand("npm", args, { cwd, env });}async function maybeRunNpmBuild(cwd, runCommand, env) {- if (!await fileExistsStrict(join30(cwd, "package.json")))+ if (!await fileExistsStrict(join31(cwd, "package.json")))return;- const packageJson = JSON.parse(await readFile8(join30(cwd, "package.json"), "utf8"));+ const packageJson = JSON.parse(await readFile8(join31(cwd, "package.json"), "utf8"));if (!isPlainRecord4(packageJson))return;const scripts = packageJson.scripts;@@ -93299,9 +93602,9 @@ async function maybeRunNpmBuild(cwd, runCommand, env) {await runCommand("npm", ["run", "build"], { cwd, env });}async function maybeRunNpmSyncSkills(cwd, runCommand, env) {- if (!await fileExistsStrict(join30(cwd, "package.json")))+ if (!await fileExistsStrict(join31(cwd, "package.json")))return;- const packageJson = JSON.parse(await readFile8(join30(cwd, "package.json"), "utf8"));+ const packageJson = JSON.parse(await readFile8(join31(cwd, "package.json"), "utf8"));if (!isPlainRecord4(packageJson))return;const scripts = packageJson.scripts;@@ -93313,13 +93616,13 @@ function sanitizeNpmInstallEnv(env) {return Object.fromEntries(Object.entries(env).filter(([key]) => key.toLowerCase() !== "npm_config_allow_scripts"));}function createTempSiblingPath(targetPath) {- return join30(dirname12(targetPath), `.tmp-${basename4(targetPath)}-${process.pid}-${Date.now()}`);+ return join31(dirname13(targetPath), `.tmp-${basename5(targetPath)}-${process.pid}-${Date.now()}`);}function createBackupSiblingPath(targetPath) {- return join30(dirname12(targetPath), `.backup-${basename4(targetPath)}-${process.pid}-${Date.now()}`);+ return join31(dirname13(targetPath), `.backup-${basename5(targetPath)}-${process.pid}-${Date.now()}`);}async function copyDirectory(sourcePath, targetPath) {- await mkdir3(dirname12(targetPath), { recursive: true });+ await mkdir3(dirname13(targetPath), { recursive: true });await cp2(sourcePath, targetPath, { recursive: true, filter: (source) => shouldCopyPluginPath(source, sourcePath) });}async function promoteDirectory(tempPath, targetPath, renameDirectory) {@@ -93364,18 +93667,18 @@ var removedSparkshellPromptSurfaceFiles = new Set(["directive.md", "plugin.json"var removedSparkshellTextFilePattern = /\.(?:json|md|toml|ya?ml)$/i;async function assertNoRemovedSparkshellPromptReferences(pluginRoot) {for (const filePath of await listRemovedSparkshellPromptSurfaceFiles(pluginRoot, "")) {- const content = await readFile8(join30(pluginRoot, filePath), "utf8");+ const content = await readFile8(join31(pluginRoot, filePath), "utf8");if (!removedSparkshellReferencePattern.test(content))continue;throw new Error(`removed sparkshell reference found in Codex plugin prompt surface: ${filePath}`);}}async function listRemovedSparkshellPromptSurfaceFiles(pluginRoot, relativeDirectory) {- const directory = relativeDirectory === "" ? pluginRoot : join30(pluginRoot, relativeDirectory);+ const directory = relativeDirectory === "" ? pluginRoot : join31(pluginRoot, relativeDirectory);const entries = await readdir4(directory, { withFileTypes: true });const files = [];for (const entry of entries) {- const relativePath = relativeDirectory === "" ? entry.name : join30(relativeDirectory, entry.name);+ const relativePath = relativeDirectory === "" ? entry.name : join31(relativeDirectory, entry.name);if (entry.isDirectory()) {if (shouldDescendIntoRemovedSparkshellPromptSurface(relativePath)) {files.push(...await listRemovedSparkshellPromptSurfaceFiles(pluginRoot, relativePath));@@ -93415,43 +93718,43 @@ async function copyRootRuntimeDists(input) {if (repoRoot === null)return;for (const runtimePath of ["dist/cli", "dist/cli-node"]) {- const sourcePath = join30(repoRoot, runtimePath);- if (!await fileExistsStrict(join30(sourcePath, "index.js")))+ const sourcePath = join31(repoRoot, runtimePath);+ if (!await fileExistsStrict(join31(sourcePath, "index.js")))continue;- await mkdir3(dirname12(join30(input.pluginRoot, runtimePath)), { recursive: true });- await cp2(sourcePath, join30(input.pluginRoot, runtimePath), { recursive: true });+ await mkdir3(dirname13(join31(input.pluginRoot, runtimePath)), { recursive: true });+ await cp2(sourcePath, join31(input.pluginRoot, runtimePath), { recursive: true });}}-var canonicalPromptRelativePaths = [join30("packages", "prompts-core", "prompts", "ultrawork", "codex.md")];+var canonicalPromptRelativePaths = [join31("packages", "prompts-core", "prompts", "ultrawork", "codex.md")];async function copyCanonicalPromptSources(input) {const repoRoot = repoRootForCodexPluginSource(input.sourcePath);if (repoRoot === null)return;for (const relativePath of canonicalPromptRelativePaths) {- const sourceFile = join30(repoRoot, relativePath);+ const sourceFile = join31(repoRoot, relativePath);if (!await fileExistsStrict(sourceFile))continue;- const targetFile = join30(input.pluginRoot, relativePath);- await mkdir3(dirname12(targetFile), { recursive: true });+ const targetFile = join31(input.pluginRoot, relativePath);+ await mkdir3(dirname13(targetFile), { recursive: true });await cp2(sourceFile, targetFile);}}function repoRootForCodexPluginSource(sourcePath) {- const codexPackageRoot = dirname12(sourcePath);- const packagesRoot = dirname12(codexPackageRoot);- if (basename4(sourcePath) !== "plugin")+ const codexPackageRoot = dirname13(sourcePath);+ const packagesRoot = dirname13(codexPackageRoot);+ if (basename5(sourcePath) !== "plugin")return null;- if (basename4(codexPackageRoot) !== "omo-codex")+ if (basename5(codexPackageRoot) !== "omo-codex")return null;- if (basename4(packagesRoot) !== "packages")+ if (basename5(packagesRoot) !== "packages")return null;- return dirname12(packagesRoot);+ return dirname13(packagesRoot);}// packages/omo-codex/src/install/codex-cache-prune.tsimport { lstat as lstat5, readdir as readdir5, rm as rm5, stat as stat4 } from "fs/promises";-import { join as join31 } from "path";+import { join as join32 } from "path";async function pruneMarketplaceCache(input) {- const cacheRoot = join31(input.codexHome, "plugins", "cache", input.marketplaceName);+ const cacheRoot = join32(input.codexHome, "plugins", "cache", input.marketplaceName);if (!await fileExistsStrict(cacheRoot))return;const keep = new Set(input.keepPluginNames);@@ -93459,15 +93762,15 @@ async function pruneMarketplaceCache(input) {for (const entry of entries) {if (!entry.isDirectory() || keep.has(entry.name))continue;- await rm5(join31(cacheRoot, entry.name), { recursive: true, force: true });+ await rm5(join32(cacheRoot, entry.name), { recursive: true, force: true });}}async function pruneMarketplacePluginCaches(input) {- const cacheRoot = join31(input.codexHome, "plugins", "cache", input.marketplaceName);+ const cacheRoot = join32(input.codexHome, "plugins", "cache", input.marketplaceName);if (!await fileExistsStrict(cacheRoot))return;for (const pluginName of input.pluginNames) {- await rm5(join31(cacheRoot, pluginName), { recursive: true, force: true });+ await rm5(join32(cacheRoot, pluginName), { recursive: true, force: true });}const remainingEntries = await readCacheEntryNames(cacheRoot);if (remainingEntries.length === 0) {@@ -93514,17 +93817,17 @@ async function isBrokenCacheSymlink(path) {}// packages/omo-codex/src/install/codex-cached-marketplace-manifest.tsimport { mkdir as mkdir4, rename as rename2, rm as rm6, stat as stat5, writeFile as writeFile4 } from "fs/promises";-import { join as join32 } from "path";+import { join as join33 } from "path";async function writeCachedMarketplaceManifest(input) {- const marketplaceDir = join32(input.marketplaceRoot, ".agents", "plugins");+ const marketplaceDir = join33(input.marketplaceRoot, ".agents", "plugins");await mkdir4(marketplaceDir, { recursive: true });for (const plugin of input.plugins) {- const pluginPath = join32(input.marketplaceRoot, plugin.name, plugin.version);+ const pluginPath = join33(input.marketplaceRoot, plugin.name, plugin.version);if (!await isDirectory2(pluginPath))throw new Error(`Cannot write cached marketplace manifest: ${pluginPath} does not exist`);}- const manifestPath = join32(marketplaceDir, "marketplace.json");- const tempPath = join32(marketplaceDir, `.marketplace.json.tmp-${process.pid}-${Date.now()}`);+ const manifestPath = join33(marketplaceDir, "marketplace.json");+ const tempPath = join33(marketplaceDir, `.marketplace.json.tmp-${process.pid}-${Date.now()}`);try {await writeFile4(tempPath, `${JSON.stringify({name: input.marketplaceName,@@ -93551,9 +93854,9 @@ async function isDirectory2(path) {}// packages/omo-codex/src/install/codex-package-layout.ts-import { existsSync as existsSync23 } from "fs";+import { existsSync as existsSync24 } from "fs";import { readFile as readFile9 } from "fs/promises";-import { join as join33 } from "path";+import { join as join34 } from "path";var PACKAGED_CODEX_INSTALLER_NAMES = new Set(["@code-yeongyu/lazycodex","@code-yeongyu/lazycodex-ai",@@ -93563,10 +93866,10 @@ var PACKAGED_CODEX_INSTALLER_NAMES = new Set(["oh-my-openagent"]);async function shouldBuildSourcePackages(repoRoot) {- if (existsSync23(join33(repoRoot, "packages", "omo-opencode", "src", "index.ts")))+ if (existsSync24(join34(repoRoot, "packages", "omo-opencode", "src", "index.ts")))return true;- const packageJsonPath = join33(repoRoot, "package.json");- if (!existsSync23(packageJsonPath))+ const packageJsonPath = join34(repoRoot, "package.json");+ if (!existsSync24(packageJsonPath))return true;const packageJson = JSON.parse(await readFile9(packageJsonPath, "utf8"));if (!isPlainRecord4(packageJson) || typeof packageJson.name !== "string")@@ -93576,7 +93879,7 @@ async function shouldBuildSourcePackages(repoRoot) {// packages/omo-codex/src/install/codex-config-toml.tsimport { mkdir as mkdir5, readFile as readFile11 } from "fs/promises";-import { dirname as dirname15 } from "path";+import { dirname as dirname16 } from "path";// packages/omo-codex/src/install/toml-section-editor.tsfunction findTomlSection(config, header) {@@ -94173,12 +94476,12 @@ function tomlKeySegment(value) {// packages/omo-codex/src/install/codex-config-atomic-write.tsimport { lstat as lstat6, readlink as readlink4, realpath, rename as rename3, unlink, writeFile as writeFile5 } from "fs/promises";-import { basename as basename5, dirname as dirname13, isAbsolute as isAbsolute5, join as join34, resolve as resolve9 } from "path";+import { basename as basename6, dirname as dirname14, isAbsolute as isAbsolute5, join as join35, resolve as resolve10 } from "path";var RENAME_RETRY_DELAYS_MS = [10, 25, 50];var RETRIABLE_RENAME_CODES = new Set(["EPERM", "EBUSY"]);async function writeFileAtomic(targetPath, data) {const writeTarget = await resolveSymlinkTarget(targetPath);- const temporaryPath = join34(dirname13(writeTarget), `.tmp-${basename5(writeTarget)}-${process.pid}-${Date.now()}`);+ const temporaryPath = join35(dirname14(writeTarget), `.tmp-${basename6(writeTarget)}-${process.pid}-${Date.now()}`);await writeFile5(temporaryPath, data);try {await renameWithRetry(temporaryPath, writeTarget);@@ -94207,7 +94510,7 @@ async function resolveSymlinkTarget(targetPath) {if (!(error instanceof Error))throw error;const linkValue = await readlink4(targetPath);- return isAbsolute5(linkValue) ? linkValue : resolve9(dirname13(targetPath), linkValue);+ return isAbsolute5(linkValue) ? linkValue : resolve10(dirname14(targetPath), linkValue);}}async function renameWithRetry(fromPath, toPath) {@@ -94672,7 +94975,7 @@ function isRootSetting(line, key) {// packages/omo-codex/src/install/codex-model-catalog.tsimport { readFile as readFile10 } from "fs/promises";-import { join as join35 } from "path";+import { join as join36 } from "path";var FALLBACK_CODEX_MODEL_CATALOG = {current: {model: "gpt-6-astra",@@ -94703,7 +95006,7 @@ var FALLBACK_CODEX_MODEL_CATALOG = {]};async function readCodexModelCatalog(codexPackageRoot) {- const catalogPath = join35(codexPackageRoot, "plugin", "model-catalog.json");+ const catalogPath = join36(codexPackageRoot, "plugin", "model-catalog.json");try {const parsed = JSON.parse(await readFile10(catalogPath, "utf8"));return parseCodexModelCatalog(parsed) ?? FALLBACK_CODEX_MODEL_CATALOG;@@ -94786,8 +95089,8 @@ function isRootSetting2(line, key) {}// packages/omo-codex/src/install/codex-multi-agent-v2-config.ts-import { readFileSync as readFileSync10 } from "fs";-import { dirname as dirname14, isAbsolute as isAbsolute6, join as join36 } from "path";+import { readFileSync as readFileSync11 } from "fs";+import { dirname as dirname15, isAbsolute as isAbsolute6, join as join37 } from "path";var CODEX_AGENTS_HEADER = "agents";var CODEX_MULTI_AGENT_V2_HEADER = "features.multi_agent_v2";function ensureCodexMultiAgentV2Config(config, options = {}) {@@ -94815,13 +95118,13 @@ function resolveCodexMultiAgentVersion(config, configPath) {}function resolveCatalogPath(configuredPath, configPath) {if (configuredPath === null)- return join36(dirname14(configPath), "models_cache.json");- return isAbsolute6(configuredPath) ? configuredPath : join36(dirname14(configPath), configuredPath);+ return join37(dirname15(configPath), "models_cache.json");+ return isAbsolute6(configuredPath) ? configuredPath : join37(dirname15(configPath), configuredPath);}function readCatalogMultiAgentVersion(model, cachePath) {let raw;try {- raw = readFileSync10(cachePath, "utf8");+ raw = readFileSync11(cachePath, "utf8");} catch {return null;}@@ -94927,7 +95230,7 @@ function readBooleanSetting(sectionText, key) {// packages/omo-codex/src/install/codex-config-toml.tsasync function updateCodexConfig(input) {- await mkdir5(dirname15(input.configPath), { recursive: true });+ await mkdir5(dirname16(input.configPath), { recursive: true });let config;try {config = await readFile11(input.configPath, "utf8");@@ -94978,7 +95281,7 @@ function isMissingFileError(error) {// packages/omo-codex/src/install/codex-hook-trust.tsimport { createHash as createHash2 } from "crypto";import { readFile as readFile12 } from "fs/promises";-import { join as join37 } from "path";+import { join as join38 } from "path";var EVENT_LABELS = new Map([["PreToolUse", "pre_tool_use"],["PermissionRequest", "permission_request"],@@ -94992,7 +95295,7 @@ var EVENT_LABELS = new Map([["Stop", "stop"]]);async function trustedHookStatesForPlugin(input) {- const manifestPath = join37(input.pluginRoot, ".codex-plugin", "plugin.json");+ const manifestPath = join38(input.pluginRoot, ".codex-plugin", "plugin.json");if (!await exists(manifestPath))return [];const manifest = JSON.parse(await readFile12(manifestPath, "utf8"));@@ -95000,7 +95303,7 @@ async function trustedHookStatesForPlugin(input) {return [];const states = [];for (const hookPath of hookManifestPaths2(manifest.hooks)) {- const hooksPath = join37(input.pluginRoot, hookPath);+ const hooksPath = join38(input.pluginRoot, hookPath);if (!await exists(hooksPath))continue;const parsed = JSON.parse(await readFile12(hooksPath, "utf8"));@@ -95127,11 +95430,11 @@ function toCodexResolution(resolution) {// packages/omo-codex/src/install/link-cached-plugin-agents.tsimport { copyFile, lstat as lstat10, mkdir as mkdir6, readdir as readdir7, rm as rm9, writeFile as writeFile7 } from "fs/promises";-import { basename as basename6, join as join41 } from "path";+import { basename as basename7, join as join42 } from "path";// packages/omo-codex/src/install/preserved-agent-settings.tsimport { lstat as lstat7, readFile as readFile13, readdir as readdir6, writeFile as writeFile6 } from "fs/promises";-import { join as join38 } from "path";+import { join as join39 } from "path";// packages/omo-codex/src/install/managed-agent-reasoning-defaults.tsvar MANAGED_REASONING_DEFAULT_UPGRADES = new Map([@@ -95324,7 +95627,7 @@ function resolveManagedAgentReasoning(input) {// packages/omo-codex/src/install/preserved-agent-settings.tsasync function capturePreservedAgentReasoning(input) {- const agentsDir = join38(input.codexHome, "agents");+ const agentsDir = join39(input.codexHome, "agents");if (!await exists2(agentsDir))return new Map;const preserved = new Map;@@ -95332,7 +95635,7 @@ async function capturePreservedAgentReasoning(input) {for (const entry of agentEntries) {if (!entry.name.endsWith(".toml"))continue;- const content = await readTextIfExists(join38(agentsDir, entry.name));+ const content = await readTextIfExists(join39(agentsDir, entry.name));if (content === null)continue;const effort = extractReasoningEffort(content);@@ -95346,7 +95649,7 @@ async function capturePreservedAgentReasoning(input) {return preserved;}async function capturePreservedAgentServiceTier(input) {- const agentsDir = join38(input.codexHome, "agents");+ const agentsDir = join39(input.codexHome, "agents");if (!await exists2(agentsDir))return new Map;const preserved = new Map;@@ -95354,7 +95657,7 @@ async function capturePreservedAgentServiceTier(input) {for (const entry of agentEntries) {if (!entry.name.endsWith(".toml"))continue;- const content = await readTextIfExists(join38(agentsDir, entry.name));+ const content = await readTextIfExists(join39(agentsDir, entry.name));if (content === null)continue;preserved.set(agentNameFromToml(entry.name), extractServiceTier(content));@@ -95488,7 +95791,7 @@ function nodeErrorCode(error) {// packages/omo-codex/src/install/retired-managed-agent-purge.tsimport { lstat as lstat8, readFile as readFile14, rm as rm7 } from "fs/promises";-import { join as join39 } from "path";+import { join as join40 } from "path";var RETIRED_MANAGED_AGENT_FILES = [{fileName: "codex-ultrawork-reviewer.toml",@@ -95500,11 +95803,11 @@ var RETIRED_MANAGED_AGENT_FILES = [}];async function purgeRetiredManagedAgentFiles(input) {- const agentsDir = join39(input.codexHome, "agents");+ const agentsDir = join40(input.codexHome, "agents");if (!await exists3(agentsDir))return;for (const retiredAgent of RETIRED_MANAGED_AGENT_FILES) {- const agentPath = join39(agentsDir, retiredAgent.fileName);+ const agentPath = join40(agentsDir, retiredAgent.fileName);if (!await exists3(agentPath))continue;const agentStat = await lstat8(agentPath);@@ -95547,12 +95850,12 @@ function nodeErrorCode2(error) {// packages/omo-codex/src/install/default-agent-role.tsimport { createHash as createHash3 } from "crypto";import { lstat as lstat9, readFile as readFile15, rm as rm8 } from "fs/promises";-import { join as join40 } from "path";+import { join as join41 } from "path";var REGISTRATION = { name: "default", configFile: "./agents/default.toml" };async function installDefaultAgentRole(input) {- const target = join40(input.codexHome, "agents", "default.toml");- const receipt = join40(input.codexHome, "agents", ".lazycodex-default.sha256");- const configPath = join40(input.codexHome, "config.toml");+ const target = join41(input.codexHome, "agents", "default.toml");+ const receipt = join41(input.codexHome, "agents", ".lazycodex-default.sha256");+ const configPath = join41(input.codexHome, "config.toml");const config = await readIfPresent(configPath);const entry = await lstat9(target).catch((error) => {if (error instanceof Error && "code" in error && error.code === "ENOENT")@@ -95613,13 +95916,13 @@ async function linkCachedPluginAgents(input) {await writeManifest(input.pluginRoot, []);return [];}- const agentsDir = join41(input.codexHome, "agents");+ const agentsDir = join42(input.codexHome, "agents");await mkdir6(agentsDir, { recursive: true });const linked = [];for (const agentPath of bundledAgents) {- const agentFileName = basename6(agentPath);+ const agentFileName = basename7(agentPath);const agentName = agentNameFromToml2(agentFileName);- const linkPath = join41(agentsDir, agentFileName);+ const linkPath = join42(agentsDir, agentFileName);await replaceWithCopy(linkPath, agentPath);await restorePreservedReasoning({agentName,@@ -95644,7 +95947,7 @@ async function linkCachedPluginAgents(input) {return linked;}async function discoverBundledAgents(pluginRoot) {- const componentsRoot = join41(pluginRoot, "components");+ const componentsRoot = join42(pluginRoot, "components");if (!await exists4(componentsRoot))return [];const componentEntries = await readdir7(componentsRoot, { withFileTypes: true });@@ -95652,14 +95955,14 @@ async function discoverBundledAgents(pluginRoot) {for (const entry of componentEntries) {if (!entry.isDirectory())continue;- const agentsRoot = join41(componentsRoot, entry.name, "agents");+ const agentsRoot = join42(componentsRoot, entry.name, "agents");if (!await exists4(agentsRoot))continue;const agentEntries = await readdir7(agentsRoot, { withFileTypes: true });for (const file of agentEntries) {if (!file.isFile() || !file.name.endsWith(".toml"))continue;- agents.push(join41(agentsRoot, file.name));+ agents.push(join42(agentsRoot, file.name));}}agents.sort();@@ -95679,7 +95982,7 @@ async function prepareReplacement(linkPath) {await rm9(linkPath, { force: true });}async function writeManifest(pluginRoot, agentPaths) {- const manifestPath = join41(pluginRoot, MANIFEST_FILE);+ const manifestPath = join42(pluginRoot, MANIFEST_FILE);const payload = { agents: [...agentPaths].sort() };await writeFile7(manifestPath, `${JSON.stringify(payload, null, "\t")}`);@@ -95705,10 +96008,10 @@ function nodeErrorCode3(error) {// packages/omo-codex/src/install/codex-marketplace.tsimport { readFile as readFile16 } from "fs/promises";-import { join as join42 } from "path";+import { join as join43 } from "path";var DEFAULT_MARKETPLACE_PATH = "packages/omo-codex/marketplace.json";async function readMarketplace(repoRoot, options) {- const marketplacePath = options?.marketplacePath ?? join42(repoRoot, DEFAULT_MARKETPLACE_PATH);+ const marketplacePath = options?.marketplacePath ?? join43(repoRoot, DEFAULT_MARKETPLACE_PATH);const raw = await readFile16(marketplacePath, "utf8");const parsed = JSON.parse(raw);if (!isPlainRecord4(parsed))@@ -95727,10 +96030,10 @@ async function readMarketplace(repoRoot, options) {function resolvePluginSource(repoRoot, plugin, options) {const sourcePath = localSourcePath(options?.pathOverride ?? plugin.source);const relativePath = sourcePath.slice(2);- return join42(repoRoot, ...relativePath.split(/[\\/]/));+ return join43(repoRoot, ...relativePath.split(/[\\/]/));}async function readPluginManifest(pluginRoot) {- const raw = await readFile16(join42(pluginRoot, ".codex-plugin", "plugin.json"), "utf8");+ const raw = await readFile16(join43(pluginRoot, ".codex-plugin", "plugin.json"), "utf8");const parsed = JSON.parse(raw);if (!isPlainRecord4(parsed))throw new Error(`${pluginRoot} plugin.json must be an object`);@@ -95812,7 +96115,7 @@ function validateLocalSourcePath(path) {// packages/omo-codex/src/install/codex-marketplace-snapshot.tsimport { cp as cp3, mkdir as mkdir7, rename as rename4, rm as rm10, writeFile as writeFile8 } from "fs/promises";-import { join as join43, sep as sep6 } from "path";+import { join as join44, sep as sep6 } from "path";var INSTALLED_MARKETPLACES_DIR = ".tmp/marketplaces";async function writeInstalledMarketplaceSnapshot(input) {const marketplaceRoot = installedMarketplaceRoot(input.codexHome, input.marketplace.name);@@ -95825,21 +96128,21 @@ async function writeInstalledMarketplaceSnapshot(input) {return snapshotPlugins;}function installedMarketplaceRoot(codexHome, marketplaceName) {- return join43(codexHome, INSTALLED_MARKETPLACES_DIR, marketplaceName);+ return join44(codexHome, INSTALLED_MARKETPLACES_DIR, marketplaceName);}async function writeMarketplaceManifest(marketplaceRoot, marketplace) {- const manifestDir = join43(marketplaceRoot, ".agents", "plugins");+ const manifestDir = join44(marketplaceRoot, ".agents", "plugins");await mkdir7(manifestDir, { recursive: true });- const tempPath = join43(manifestDir, `.marketplace-${process.pid}-${Date.now()}.json.tmp`);+ const tempPath = join44(manifestDir, `.marketplace-${process.pid}-${Date.now()}.json.tmp`);await writeFile8(tempPath, `${JSON.stringify(marketplace, null, "\t")}`);- await rename4(tempPath, join43(manifestDir, "marketplace.json"));+ await rename4(tempPath, join44(manifestDir, "marketplace.json"));}async function writeSnapshotPlugin(marketplaceRoot, plugin) {- const pluginsDir = join43(marketplaceRoot, "plugins");+ const pluginsDir = join44(marketplaceRoot, "plugins");await mkdir7(pluginsDir, { recursive: true });- const targetPath = join43(pluginsDir, plugin.name);- const tempPath = join43(pluginsDir, `.tmp-${plugin.name}-${process.pid}-${Date.now()}`);+ const targetPath = join44(pluginsDir, plugin.name);+ const tempPath = join44(pluginsDir, `.tmp-${plugin.name}-${process.pid}-${Date.now()}`);await rm10(tempPath, { recursive: true, force: true });await cp3(plugin.sourcePath, tempPath, {recursive: true,@@ -95861,10 +96164,10 @@ function shouldCopyMarketplaceSourcePath(path, root) {// packages/omo-codex/src/install/lazycodex-version-stamp.tsimport { readdir as readdir8, readFile as readFile17, writeFile as writeFile9 } from "fs/promises";-import { join as join44 } from "path";+import { join as join45 } from "path";async function readDistributionManifest(repoRoot) {try {- const parsed = JSON.parse(await readFile17(join44(repoRoot, "package.json"), "utf8"));+ const parsed = JSON.parse(await readFile17(join45(repoRoot, "package.json"), "utf8"));if (!isPlainRecord4(parsed) || typeof parsed.version !== "string" || parsed.version.trim().length === 0)return;return {@@ -95888,19 +96191,19 @@ function resolveLazyCodexPluginVersion(input) {return input.manifestVersion ?? "local";}async function stampLazyCodexPluginVersion(input) {- const manifestPath = join44(input.pluginRoot, ".codex-plugin", "plugin.json");+ const manifestPath = join45(input.pluginRoot, ".codex-plugin", "plugin.json");const hookPaths = await readPluginHookPaths(manifestPath);await stampJsonVersion(manifestPath, input.version);- await stampJsonVersion(join44(input.pluginRoot, "package.json"), input.version);+ await stampJsonVersion(join45(input.pluginRoot, "package.json"), input.version);for (const hookPath of hookPaths) {- await stampHookStatusMessages(join44(input.pluginRoot, hookPath), input.version);+ await stampHookStatusMessages(join45(input.pluginRoot, hookPath), input.version);}await stampComponentVersions(input);}async function writeLazyCodexInstallSnapshot(input) {if (input.distributionManifest === undefined)return;- await writeFile9(join44(input.pluginRoot, "lazycodex-install.json"), `${JSON.stringify({+ await writeFile9(join45(input.pluginRoot, "lazycodex-install.json"), `${JSON.stringify({packageName: input.distributionManifest.name,version: input.distributionManifest.version}, null, "\t")}@@ -95957,16 +96260,16 @@ async function stampHookStatusMessages(path, version) {async function stampComponentVersions(input) {let entries;try {- entries = await readdir8(join44(input.pluginRoot, "components"));+ entries = await readdir8(join45(input.pluginRoot, "components"));} catch (error) {if (error instanceof Error)return;throw error;}for (const entry of entries) {- const componentRoot = join44(input.pluginRoot, "components", entry);- await stampJsonVersion(join44(componentRoot, "package.json"), input.version);- await stampHookStatusMessages(join44(componentRoot, "hooks", "hooks.json"), input.version);+ const componentRoot = join45(input.pluginRoot, "components", entry);+ await stampJsonVersion(join45(componentRoot, "package.json"), input.version);+ await stampHookStatusMessages(join45(componentRoot, "hooks", "hooks.json"), input.version);}}function stampHookGroups(hooks, version) {@@ -96024,7 +96327,7 @@ var defaultRunCommand = async (command, args, options) => {// packages/omo-codex/src/install/codex-project-local-cleanup.tsimport { copyFile as copyFile2, lstat as lstat11, readFile as readFile18, writeFile as writeFile10 } from "fs/promises";-import { dirname as dirname16, join as join45, resolve as resolve10 } from "path";+import { dirname as dirname17, join as join46, resolve as resolve11 } from "path";var LEGACY_AGENT_CONFLICT_KEYS = ["max_threads"];var PROJECT_LOCAL_ARTIFACT_PATHS = [".codex/hooks.json",@@ -96127,37 +96430,37 @@ async function findProjectLocalCodexConfigs(startDirectory, codexHome) {if (startDirectoryStat !== null && !startDirectoryStat.isDirectory()) {throw new ProjectLocalCleanupStartDirectoryError(startDirectory);}- const codexHomeConfigPath = codexHome === undefined ? null : join45(resolve10(codexHome), "config.toml");- let current = resolve10(startDirectory);+ const codexHomeConfigPath = codexHome === undefined ? null : join46(resolve11(codexHome), "config.toml");+ let current = resolve11(startDirectory);const configPathsFromCwd = [];while (true) {- const configPath = join45(current, ".codex", "config.toml");+ const configPath = join46(current, ".codex", "config.toml");if (await isRegularProjectLocalConfig(current, configPath)) {- if (codexHomeConfigPath === null || resolve10(configPath) !== codexHomeConfigPath) {+ if (codexHomeConfigPath === null || resolve11(configPath) !== codexHomeConfigPath) {configPathsFromCwd.push(configPath);}}- if (await exists5(join45(current, ".git"))) {+ if (await exists5(join46(current, ".git"))) {return configPathsFromCwd.length === 0 ? null : {projectRoot: current,configPaths: [...configPathsFromCwd].reverse(),artifactRoots: artifactRootsForConfigPaths(configPathsFromCwd)};}- const parent = dirname16(current);+ const parent = dirname17(current);if (parent === current) {const nearestConfigPath = configPathsFromCwd[0];return nearestConfigPath === undefined ? null : {- projectRoot: dirname16(dirname16(nearestConfigPath)),+ projectRoot: dirname17(dirname17(nearestConfigPath)),configPaths: [nearestConfigPath],- artifactRoots: [dirname16(dirname16(nearestConfigPath))]+ artifactRoots: [dirname17(dirname17(nearestConfigPath))]};}current = parent;}}async function isRegularProjectLocalConfig(directory, configPath) {- const codexDirStat = await maybeLstat(join45(directory, ".codex"));+ const codexDirStat = await maybeLstat(join46(directory, ".codex"));if (codexDirStat === null || !codexDirStat.isDirectory() || codexDirStat.isSymbolicLink())return false;const configStat = await maybeLstat(configPath);@@ -96166,7 +96469,7 @@ async function isRegularProjectLocalConfig(directory, configPath) {function artifactRootsForConfigPaths(configPaths) {const roots = [];for (const configPath of configPaths) {- const root = dirname16(dirname16(configPath));+ const root = dirname17(dirname17(configPath));if (!roots.includes(root))roots.push(root);}@@ -96177,7 +96480,7 @@ async function collectProjectLocalArtifacts(projectRoots) {const seenPaths = new Set;for (const projectRoot of projectRoots) {for (const relativePath of PROJECT_LOCAL_ARTIFACT_PATHS) {- const artifactPath = join45(projectRoot, relativePath);+ const artifactPath = join46(projectRoot, relativePath);if (seenPaths.has(artifactPath))continue;const entryStat = await maybeLstat(artifactPath);@@ -96255,13 +96558,13 @@ function formatUnknownError(error) {import { createHash as createHash4 } from "crypto";import { lstat as lstat12, readFile as readFile20, readdir as readdir10, rm as rm11 } from "fs/promises";import { tmpdir as tmpdir3 } from "os";-import { join as join46, posix as posix6 } from "path";+import { join as join47, posix as posix6 } from "path";// packages/omo-codex/src/install/lsp-daemon-reaper-attestation.tsimport { execFile } from "child_process";import { readFile as readFile19, readdir as readdir9, readlink as readlink5 } from "fs/promises";import { connect } from "net";-import { basename as basename7 } from "path";+import { basename as basename8 } from "path";var PROBE_TIMEOUT_MS = 500;async function probeLegacyJsonRpcEndpoint(endpoint, timeoutMs = PROBE_TIMEOUT_MS) {return await new Promise((resolve) => {@@ -96393,14 +96696,14 @@ function splitCmdline(buffer) {function isNodeCliDaemonArgv(argv) {if (argv.length < 2 || !argv.includes("daemon"))return false;- const executable = basename7(argv[0] ?? "");+ const executable = basename8(argv[0] ?? "");if (!/^node(?:\.exe)?$/i.test(executable))return false;return argv.some((value) => value === "cli.js" || value.endsWith("/cli.js") || value.endsWith("\\cli.js"));}function lsofShowsUnixEndpoint(output, pid, endpoint) {const lines = output.split(/\r?\n/).filter((line) => line.length > 0);- const endpointName = basename7(endpoint);+ const endpointName = basename8(endpoint);return lines.includes(`p${pid}`) && lines.some((line) => line === `n${endpoint}` || line === `n${endpointName}`);}function isNodeCliDaemonCommand(command) {@@ -96428,7 +96731,7 @@ async function readBinary(readFileImpl, path) {var LEGACY_EXIT_WAIT_TIMEOUT_MS = 5000;var LEGACY_VERSION_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$/;async function reapLspDaemons(codexHome, deps = {}) {- const daemonRoot = join46(codexHome, "codex-lsp", "daemon");+ const daemonRoot = join47(codexHome, "codex-lsp", "daemon");const platform = deps.platform ?? process.platform;const tmpDir = deps.tmpDir ?? tmpdir3();const probe = deps.probeLegacyJsonRpc ?? probeLegacyJsonRpcEndpoint;@@ -96438,7 +96741,7 @@ async function reapLspDaemons(codexHome, deps = {}) {const entries = await readdir10(daemonRoot, { withFileTypes: true }).catch(() => []);const results = [];for (const entry of [...entries].sort((left, right) => left.name.localeCompare(right.name))) {- const versionPath = join46(daemonRoot, entry.name);+ const versionPath = join47(daemonRoot, entry.name);const parsedVersion = parseVersionEntry(entry.name);if (parsedVersion === null || !entry.isDirectory()) {await removeVersionDir(versionPath);@@ -96486,7 +96789,7 @@ function parseVersionEntry(entryName) {return LEGACY_VERSION_PATTERN.test(version) ? version : null;}async function readLegacyMetadata(input) {- const pidText = await readRegularTrimmedFile(join46(input.versionPath, "daemon.pid"));+ const pidText = await readRegularTrimmedFile(join47(input.versionPath, "daemon.pid"));if (pidText === "non_regular")return { kind: "remove", reason: "removed non-regular legacy daemon metadata" };if (pidText === null)@@ -96494,7 +96797,7 @@ async function readLegacyMetadata(input) {const pid = Number.parseInt(pidText, 10);if (!Number.isInteger(pid) || pid <= 0)return { kind: "remove", reason: "removed malformed legacy daemon metadata" };- const endpointText = await readRegularTrimmedFile(join46(input.versionPath, "daemon.endpoint"));+ const endpointText = await readRegularTrimmedFile(join47(input.versionPath, "daemon.endpoint"));if (endpointText === "non_regular")return { kind: "remove", reason: "removed non-regular legacy daemon metadata" };if (endpointText === null)@@ -96573,25 +96876,25 @@ function processIsRunning(pid) {// packages/omo-codex/src/install/codex-installer-bin-dir.tsimport { homedir as homedir5 } from "os";-import { join as join47, resolve as resolve11 } from "path";+import { join as join48, resolve as resolve12 } from "path";function resolveCodexInstallerBinDir(input) {const explicitBinDir = input.binDir ?? input.env?.CODEX_LOCAL_BIN_DIR;if (explicitBinDir !== undefined && explicitBinDir.trim().length > 0)- return resolve11(explicitBinDir.trim());+ return resolve12(explicitBinDir.trim());const homeDir = input.homeDir ?? homedir5();- const defaultCodexHome = resolve11(homeDir, ".codex");- const resolvedCodexHome = resolve11(input.codexHome);+ const defaultCodexHome = resolve12(homeDir, ".codex");+ const resolvedCodexHome = resolve12(input.codexHome);if (resolvedCodexHome !== defaultCodexHome)- return join47(resolvedCodexHome, "bin");- return resolve11(homeDir, ".local", "bin");+ return join48(resolvedCodexHome, "bin");+ return resolve12(homeDir, ".local", "bin");}// packages/omo-codex/src/install/codex-installed-bin-dir.tsimport { readFile as readFile21, readdir as readdir11, writeFile as writeFile11 } from "fs/promises";-import { join as join48 } from "path";+import { join as join49 } from "path";var INSTALLED_BIN_DIR_MANIFEST = ".installed-bin-dir.json";async function writeInstalledCodexBinDir(input) {- await writeFile11(join48(input.pluginRoot, INSTALLED_BIN_DIR_MANIFEST), `${JSON.stringify({ binDir: input.binDir }, null, 2)}+ await writeFile11(join49(input.pluginRoot, INSTALLED_BIN_DIR_MANIFEST), `${JSON.stringify({ binDir: input.binDir }, null, 2)}`);}async function readInstalledCodexBinDir(codexHome) {@@ -96604,14 +96907,14 @@ async function readInstalledCodexBinDir(codexHome) {}async function installedBinDirManifestPaths(codexHome) {const paths = [- join48(codexHome, ".tmp", "marketplaces", "sisyphuslabs", "plugins", "omo", INSTALLED_BIN_DIR_MANIFEST)+ join49(codexHome, ".tmp", "marketplaces", "sisyphuslabs", "plugins", "omo", INSTALLED_BIN_DIR_MANIFEST)];- const versionRoot = join48(codexHome, "plugins", "cache", "sisyphuslabs", "omo");+ const versionRoot = join49(codexHome, "plugins", "cache", "sisyphuslabs", "omo");const entries = await readdir11(versionRoot, { withFileTypes: true }).catch(() => null);if (entries !== null) {for (const entry of entries) {if (entry.isDirectory())- paths.push(join48(versionRoot, entry.name, INSTALLED_BIN_DIR_MANIFEST));+ paths.push(join49(versionRoot, entry.name, INSTALLED_BIN_DIR_MANIFEST));}}return paths;@@ -96636,7 +96939,7 @@ async function readBinDirFromManifest(manifestPath) {// packages/omo-codex/src/install/codex-git-bash-hooks.tsimport { readFile as readFile22, writeFile as writeFile12 } from "fs/promises";-import { join as join49 } from "path";+import { join as join50 } from "path";var WINDOWS_ONLY_GIT_BASH_HOOKS = new Set(["./hooks/pre-tool-use-recommending-git-bash-mcp.json","./hooks/post-compact-resetting-git-bash-mcp-reminder.json"@@ -96644,7 +96947,7 @@ var WINDOWS_ONLY_GIT_BASH_HOOKS = new Set([async function removeGitBashHooksOffWindows(input) {if (input.platform === "win32")return;- const manifestPath = join49(input.pluginRoot, ".codex-plugin", "plugin.json");+ const manifestPath = join50(input.pluginRoot, ".codex-plugin", "plugin.json");const parsed = JSON.parse(await readFile22(manifestPath, "utf8"));if (!isPlainRecord4(parsed) || !Array.isArray(parsed.hooks))return;@@ -96657,7 +96960,7 @@ async function removeGitBashHooksOffWindows(input) {// packages/omo-codex/src/install/install-ast-grep-sg.tsinit_src();-import { join as join50 } from "path";+import { join as join51 } from "path";function describeResult(result) {if (result.kind === "succeeded")return null;@@ -96671,7 +96974,7 @@ async function installAstGrepForCodex(options) {return;const platform = options.platform ?? process.platform;const targetDir = astGrepRuntimeDir(options.codexHome, platform, options.arch ?? process.arch);- const skillDir = join50(plugin.path, "skills", "ast-grep");+ const skillDir = join51(plugin.path, "skills", "ast-grep");const installer = options.installer ?? runAstGrepSkillInstall;try {const result = await installer({ platform, skillDir, targetDir });@@ -96703,9 +97006,9 @@ var SISYPHUS_LEGACY_CACHE_MARKETPLACES = ["lazycodex", "code-yeongyu-codex-plugiasync function runCodexInstaller(options = {}) {const env = options.env ?? process.env;const platform = options.platform ?? process.platform;- const repoRoot = resolve12(options.repoRoot ?? findRepoRoot({ importerDir: import.meta.dir, env }));- const codexHome = resolve12(options.codexHome ?? env.CODEX_HOME ?? join54(homedir6(), ".codex"));- const projectDirectory = resolve12(options.projectDirectory ?? env.OMO_CODEX_PROJECT ?? process.cwd());+ const repoRoot = resolve13(options.repoRoot ?? findRepoRoot({ importerDir: import.meta.dir, env }));+ const codexHome = resolve13(options.codexHome ?? env.CODEX_HOME ?? join55(homedir6(), ".codex"));+ const projectDirectory = resolve13(options.projectDirectory ?? env.OMO_CODEX_PROJECT ?? process.cwd());const binDir = resolveCodexInstallerBinDir({ binDir: options.binDir, codexHome, env });const runCommand = options.runCommand ?? defaultRunCommand;const log = options.log ?? (() => {@@ -96721,9 +97024,9 @@ async function runCodexInstaller(options = {}) {if (!gitBashResolution.found) {throw new Error(gitBashResolution.installHint);}- const codexPackageRoot = join54(repoRoot, "packages", "omo-codex");+ const codexPackageRoot = join55(repoRoot, "packages", "omo-codex");const marketplace = await readMarketplace(repoRoot, {- marketplacePath: join54(codexPackageRoot, "marketplace.json")+ marketplacePath: join55(codexPackageRoot, "marketplace.json")});const distributionManifest = await readDistributionManifest(repoRoot);const installed = [];@@ -96769,7 +97072,7 @@ async function runCodexInstaller(options = {}) {if (runtimeLink !== null)log(`Linked ${runtimeLink.name} -> ${runtimeLink.target}`);else- log(`Warning: skipped the omo-agent-toolkit runtime wrapper because ${join54(repoRoot, "dist", "cli", "index.js")} is missing; omo-agent-toolkit ulw-loop commands will be unavailable until a package shipping dist/cli is installed`);+ log(`Warning: skipped the omo-agent-toolkit runtime wrapper because ${join55(repoRoot, "dist", "cli", "index.js")} is missing; omo-agent-toolkit ulw-loop commands will be unavailable until a package shipping dist/cli is installed`);}pluginSources.push({ name: entry.name, sourcePath });installed.push(plugin);@@ -96836,13 +97139,13 @@ async function runCodexInstaller(options = {}) {continue;log(`Warning: deferred legacy Codex LSP daemon cleanup for v${cleanup.version}: ${cleanup.reason}`);}- const marketplaceRoot = join54(codexHome, "plugins", "cache", marketplace.name);+ const marketplaceRoot = join55(codexHome, "plugins", "cache", marketplace.name);await writeCachedMarketplaceManifest({marketplaceName: marketplace.name,marketplaceRoot,plugins: installed});- const configPath = join54(codexHome, "config.toml");+ const configPath = join55(codexHome, "config.toml");await updateCodexConfig({configPath,repoRoot: codexPackageRoot,@@ -96901,25 +97204,25 @@ function findRepoRootFromImporter(importerDir) {for (let depth = 0;depth <= 7; depth += 1) {if (isRepoRootWithCodexPlugin(current))return current;- for (const wrapperPackageRoot of [join54(current, "node_modules", "oh-my-openagent"), join54(current, "oh-my-openagent")]) {+ for (const wrapperPackageRoot of [join55(current, "node_modules", "oh-my-openagent"), join55(current, "oh-my-openagent")]) {if (isRepoRootWithCodexPlugin(wrapperPackageRoot))return wrapperPackageRoot;}- current = resolve12(current, "..");+ current = resolve13(current, "..");}throw new Error("Unable to locate vendored Codex plugin: expected packages/omo-codex/plugin/.codex-plugin/plugin.json in this package or sibling oh-my-openagent package within 7 parent levels");}function findRepoRoot(input) {const wrapperPackageRoot = input.env?.OMO_WRAPPER_PACKAGE_ROOT;if (wrapperPackageRoot !== undefined && wrapperPackageRoot.trim().length > 0) {- const resolvedWrapperPackageRoot = resolve12(wrapperPackageRoot);+ const resolvedWrapperPackageRoot = resolve13(wrapperPackageRoot);if (isRepoRootWithCodexPlugin(resolvedWrapperPackageRoot))return resolvedWrapperPackageRoot;}return findRepoRootFromImporter(input.importerDir);}function isRepoRootWithCodexPlugin(repoRoot) {- return existsSync26(join54(repoRoot, "packages", "omo-codex", "plugin", ".codex-plugin", "plugin.json"));+ return existsSync27(join55(repoRoot, "packages", "omo-codex", "plugin", ".codex-plugin", "plugin.json"));}function codexMarketplaceSource(marketplaceRoot) {return { sourceType: "local", source: marketplaceRoot };@@ -96927,7 +97230,7 @@ function codexMarketplaceSource(marketplaceRoot) {// packages/omo-codex/src/install/codex-installation-detection.tsinit_bun_which_shim();import { execFile as execFile2 } from "child_process";-import { existsSync as existsSync27 } from "fs";+import { existsSync as existsSync28 } from "fs";import { homedir as homedir7 } from "os";import { posix as posix8, win32 as win324 } from "path";var CODEX_PATH_CHECK_LABEL = "codex (PATH)";@@ -96940,7 +97243,7 @@ async function detectCodexInstallation(input = {}) {const platform = input.platform ?? process.platform;const env = input.env ?? process.env;const homeDir = input.homeDir ?? homedir7();- const exists = input.exists ?? existsSync27;+ const exists = input.exists ?? existsSync28;const which = input.which ?? bunWhich;const checkedPaths = [CODEX_PATH_CHECK_LABEL];const cliPath = nonEmptyValue2(which("codex"));@@ -97056,11 +97359,11 @@ function defaultRunCommand2(command, args) {// packages/omo-codex/src/install/codex-cleanup.tsimport { lstat as lstat15, readFile as readFile25, readdir as readdir13, rm as rm13, rmdir } from "fs/promises";import { homedir as homedir8 } from "os";-import { isAbsolute as isAbsolute11, join as join57, relative as relative6, resolve as resolve15 } from "path";+import { isAbsolute as isAbsolute11, join as join58, relative as relative6, resolve as resolve16 } from "path";// packages/omo-codex/src/install/codex-cleanup-bins.tsimport { lstat as lstat13, readFile as readFile23, readdir as readdir12, readlink as readlink6, rm as rm12 } from "fs/promises";-import { dirname as dirname18, isAbsolute as isAbsolute9, join as join55, resolve as resolve13 } from "path";+import { dirname as dirname19, isAbsolute as isAbsolute9, join as join56, resolve as resolve14 } from "path";var ROOT_RUNTIME_BIN_NAME = "omo";var MANAGED_CODEX_BIN_NAMES = new Set([ROOT_RUNTIME_BIN_NAME,@@ -97090,7 +97393,7 @@ async function removeManagedCodexBins(binDir, platform) {const binName = managedBinNameForEntry2(entry.name, platform);if (binName === null || !MANAGED_CODEX_BIN_NAMES.has(binName))continue;- const linkPath = join55(binDir, entry.name);+ const linkPath = join56(binDir, entry.name);if (await isManagedCodexBin(linkPath, platform, binName)) {await rm12(linkPath, { force: true });removed.push(linkPath);@@ -97116,7 +97419,7 @@ async function isManagedCodexBin(linkPath, platform, binName) {if (platform === "win32")return false;const linkTarget = await readlink6(linkPath);- const target = isAbsolute9(linkTarget) ? linkTarget : resolve13(dirname18(linkPath), linkTarget);+ const target = isAbsolute9(linkTarget) ? linkTarget : resolve14(dirname19(linkPath), linkTarget);return isManagedComponentBinTarget(target) || isLegacyCodexBinTarget(binName, target);}if (!entryStat.isFile())@@ -97127,7 +97430,7 @@ async function isManagedCodexBin(linkPath, platform, binName) {// packages/omo-codex/src/install/codex-cleanup-config.tsimport { lstat as lstat14, mkdir as mkdir8, readFile as readFile24, writeFile as writeFile13 } from "fs/promises";-import { dirname as dirname19 } from "path";+import { dirname as dirname20 } from "path";var MANAGED_MARKETPLACES = ["sisyphuslabs", "lazycodex", "code-yeongyu-codex-plugins"];var LEGACY_MANAGED_CODEX_AGENT_NAMES_TO_PURGE2 = ["codex-ultrawork-reviewer"];var CURRENT_MANAGED_CODEX_AGENT_NAMES2 = [@@ -97164,7 +97467,7 @@ async function cleanupCodexConfig(configPath, now) {if (next === original)return { changed: false };const backupPath = `${configPath}.backup-${formatBackupTimestamp2(now?.() ?? new Date)}`;- await mkdir8(dirname19(configPath), { recursive: true });+ await mkdir8(dirname20(configPath), { recursive: true });await writeFile13(backupPath, original);await writeFile13(configPath, `${next.trimEnd()}`);@@ -97243,28 +97546,28 @@ function nodeErrorCode5(error) {}// packages/omo-codex/src/install/codex-cleanup-safety.ts-import { dirname as dirname20, isAbsolute as isAbsolute10, join as join56, relative as relative5, resolve as resolve14 } from "path";+import { dirname as dirname21, isAbsolute as isAbsolute10, join as join57, relative as relative5, resolve as resolve15 } from "path";function codexHomeResolvesToFilesystemRoot(codexHome) {- const resolved = resolve14(codexHome);- return dirname20(resolved) === resolved;+ const resolved = resolve15(codexHome);+ return dirname21(resolved) === resolved;}function validateManagedCleanupTarget(input) {if (!isAbsolute10(input.path))return skipped(input.path, "outside managed Codex cleanup scope");- const codexHome = resolve14(input.codexHome);+ const codexHome = resolve15(input.codexHome);if (codexHomeResolvesToFilesystemRoot(codexHome))return skipped(input.path, "Codex home resolves to a filesystem root");- const target = resolve14(input.path);+ const target = resolve15(input.path);if (!isWithinDirectory(codexHome, target))return skipped(input.path, "outside managed Codex cleanup scope");if (target === codexHome)return skipped(input.path, "outside managed Codex cleanup scope");const exactManagedRoots = new Set([- resolve14(join56(codexHome, "plugins", "cache", "sisyphuslabs")),- resolve14(join56(codexHome, ".tmp", "marketplaces", "sisyphuslabs")),- resolve14(join56(codexHome, "runtime", "ast-grep")),- resolve14(join56(codexHome, "runtime", "node")),- resolve14(join56(codexHome, "plugins", "data", "omo-sisyphuslabs", "bootstrap"))+ resolve15(join57(codexHome, "plugins", "cache", "sisyphuslabs")),+ resolve15(join57(codexHome, ".tmp", "marketplaces", "sisyphuslabs")),+ resolve15(join57(codexHome, "runtime", "ast-grep")),+ resolve15(join57(codexHome, "runtime", "node")),+ resolve15(join57(codexHome, "plugins", "data", "omo-sisyphuslabs", "bootstrap"))]);if (exactManagedRoots.has(target))return null;@@ -97294,8 +97597,8 @@ function skipped(path, reason) {var INSTALLED_AGENTS_MANIFEST = ".installed-agents.json";async function cleanupCodexLight(input = {}) {const env = input.env ?? process.env;- const codexHome = resolve15(input.codexHome ?? env.CODEX_HOME ?? join57(homedir8(), ".codex"));- const configPath = join57(codexHome, "config.toml");+ const codexHome = resolve16(input.codexHome ?? env.CODEX_HOME ?? join58(homedir8(), ".codex"));+ const configPath = join58(codexHome, "config.toml");const installedBinDir = await readInstalledCodexBinDir(codexHome);const agentPaths = await collectInstalledAgentPaths(codexHome, configPath);const configCleanup = await cleanupCodexConfig(configPath, input.now);@@ -97349,17 +97652,17 @@ function firstConfiguredPath(...values) {}function managedGlobalStatePaths(codexHome) {return [- join57(codexHome, "plugins", "cache", "sisyphuslabs"),- join57(codexHome, ".tmp", "marketplaces", "sisyphuslabs"),- join57(codexHome, "runtime", "ast-grep"),- join57(codexHome, "runtime", "node"),- join57(codexHome, "plugins", "data", "omo-sisyphuslabs", "bootstrap")+ join58(codexHome, "plugins", "cache", "sisyphuslabs"),+ join58(codexHome, ".tmp", "marketplaces", "sisyphuslabs"),+ join58(codexHome, "runtime", "ast-grep"),+ join58(codexHome, "runtime", "node"),+ join58(codexHome, "plugins", "data", "omo-sisyphuslabs", "bootstrap")];}var BOOTSTRAP_DATA_GLOB_MAX_DEPTH = 5;async function collectBootstrapDataDirsByGlob(codexHome) {const results = [];- await walkForManagedBootstrapDirs(join57(codexHome, "plugins"), 0, results);+ await walkForManagedBootstrapDirs(join58(codexHome, "plugins"), 0, results);return results;}async function walkForManagedBootstrapDirs(directory, depth, results) {@@ -97371,9 +97674,9 @@ async function walkForManagedBootstrapDirs(directory, depth, results) {for (const entry of entries) {if (!entry.isDirectory())continue;- const childPath = join57(directory, entry.name);+ const childPath = join58(directory, entry.name);if (isManagedBootstrapOwnerName(entry.name)) {- const bootstrapDir = join57(childPath, "bootstrap");+ const bootstrapDir = join58(childPath, "bootstrap");if (await exists6(bootstrapDir))results.push(bootstrapDir);continue;@@ -97407,7 +97710,7 @@ async function attemptRemove(path) {}async function pruneEmptyRuntimeDirBestEffort(codexHome) {try {- await rmdir(join57(codexHome, "runtime"));+ await rmdir(join58(codexHome, "runtime"));} catch (error) {if (isExpectedRuntimePruneFailure(error))return;@@ -97419,14 +97722,14 @@ function isExpectedRuntimePruneFailure(error) {}async function collectInstalledAgentPaths(codexHome, configPath) {const manifestPaths = [- join57(codexHome, ".tmp", "marketplaces", "sisyphuslabs", "plugins", "omo", INSTALLED_AGENTS_MANIFEST)+ join58(codexHome, ".tmp", "marketplaces", "sisyphuslabs", "plugins", "omo", INSTALLED_AGENTS_MANIFEST)];- const versionRoot = join57(codexHome, "plugins", "cache", "sisyphuslabs", "omo");+ const versionRoot = join58(codexHome, "plugins", "cache", "sisyphuslabs", "omo");if (await exists6(versionRoot)) {const entries = await readdir13(versionRoot, { withFileTypes: true });for (const entry of entries) {if (entry.isDirectory())- manifestPaths.push(join57(versionRoot, entry.name, INSTALLED_AGENTS_MANIFEST));+ manifestPaths.push(join58(versionRoot, entry.name, INSTALLED_AGENTS_MANIFEST));}}const paths = new Set;@@ -97444,7 +97747,7 @@ async function readManagedAgentPathsFromConfig(codexHome, configPath) {if (!await exists6(configPath))return [];const config = await readFile25(configPath, "utf8");- return MANAGED_CODEX_AGENT_NAMES2.filter((agentName) => config.includes(`config_file = ${JSON.stringify(`./agents/${agentName}.toml`)}`)).map((agentName) => join57(codexHome, "agents", `${agentName}.toml`));+ return MANAGED_CODEX_AGENT_NAMES2.filter((agentName) => config.includes(`config_file = ${JSON.stringify(`./agents/${agentName}.toml`)}`)).map((agentName) => join58(codexHome, "agents", `${agentName}.toml`));}async function readInstalledAgentManifest(manifestPath) {if (!await exists6(manifestPath))@@ -97455,7 +97758,7 @@ async function readInstalledAgentManifest(manifestPath) {return parsed.agents.filter((path) => typeof path === "string");}async function removeManifestListedAgentLinks(codexHome, paths) {- const agentsDir = join57(codexHome, "agents");+ const agentsDir = join58(codexHome, "agents");const removed = [];const skipped = [];for (const path of paths) {@@ -97505,16 +97808,16 @@ function nodeErrorCode6(error) {}// packages/omo-senpi/src/install/install-senpi.tsimport { execFile as execFile3 } from "child_process";-import { existsSync as existsSync30 } from "fs";+import { existsSync as existsSync31 } from "fs";import { homedir as homedir11 } from "os";-import { dirname as dirname24, join as join62, resolve as resolve19 } from "path";+import { dirname as dirname25, join as join63, resolve as resolve20 } from "path";import { fileURLToPath } from "url";import { promisify as promisify2 } from "util";// packages/omo-senpi/src/components/agent-home/resolve-agent-home.ts-import { existsSync as existsSync28 } from "fs";+import { existsSync as existsSync29 } from "fs";import { homedir as homedir9 } from "os";-import { join as join58, resolve as resolve16 } from "path";+import { join as join59, resolve as resolve17 } from "path";var AGENT_DIR_ENV_NAMES = ["OMO_CODING_AGENT_DIR","SENPI_CODING_AGENT_DIR",@@ -97522,31 +97825,31 @@ var AGENT_DIR_ENV_NAMES = [];var AGENT_HOME_SENTINEL = "settings.json";function resolveAgentHome(options) {- const { env, homeDir = homedir9(), exists = existsSync28 } = options;+ const { env, homeDir = homedir9(), exists = existsSync29 } = options;for (const name of AGENT_DIR_ENV_NAMES) {const configured = env[name]?.trim();if (configured)- return resolve16(configured);+ return resolve17(configured);}- const brandedHome = join58(homeDir, ".omo");- const canonical = join58(brandedHome, "agent");- if (exists(join58(canonical, AGENT_HOME_SENTINEL)))+ const brandedHome = join59(homeDir, ".omo");+ const canonical = join59(brandedHome, "agent");+ if (exists(join59(canonical, AGENT_HOME_SENTINEL)))return canonical;- if (exists(join58(brandedHome, AGENT_HOME_SENTINEL)))+ if (exists(join59(brandedHome, AGENT_HOME_SENTINEL)))return brandedHome;- return join58(homeDir, ".senpi", "agent");+ return join59(homeDir, ".senpi", "agent");}// packages/omo-senpi/src/install/local-launcher.ts-import { chmodSync as chmodSync3, existsSync as existsSync29, mkdirSync as mkdirSync11, readFileSync as readFileSync13, rmSync as rmSync3, writeFileSync as writeFileSync6 } from "fs";+import { chmodSync as chmodSync3, existsSync as existsSync30, mkdirSync as mkdirSync12, readFileSync as readFileSync14, rmSync as rmSync4, writeFileSync as writeFileSync7 } from "fs";import { homedir as homedir10 } from "os";-import { dirname as dirname21, join as join59, resolve as resolve17 } from "path";+import { dirname as dirname22, join as join60, resolve as resolve18 } from "path";var MARKER = "omo-local-launcher";function localLauncherPath(homeDir = homedir10()) {- return join59(homeDir, ".local", "bin", "omo");+ return join60(homeDir, ".local", "bin", "omo");}function localLauncherCmdPath(homeDir = homedir10()) {- return join59(homeDir, ".local", "bin", "omo.cmd");+ return join60(homeDir, ".local", "bin", "omo.cmd");}function renderLocalLauncher(options) {const brand = {@@ -97559,7 +97862,7 @@ function renderLocalLauncher(options) {userAgent: "omo",originator: "omo",changelog: {- path: join59(options.pluginPath, "CHANGELOG.md").replaceAll("\\", "/")+ path: join60(options.pluginPath, "CHANGELOG.md").replaceAll("\\", "/")},update: {packageName: "omo-ai",@@ -97615,13 +97918,13 @@ child.on("close", (code, signal) => {}function installLocalLauncher(options) {const path = localLauncherPath(options.homeDir);- if (existsSync29(path) && !readFileSync13(path, "utf8").includes(MARKER))+ if (existsSync30(path) && !readFileSync14(path, "utf8").includes(MARKER))return;- mkdirSync11(dirname21(path), { recursive: true });- writeFileSync6(path, renderLocalLauncher(options));+ mkdirSync12(dirname22(path), { recursive: true });+ writeFileSync7(path, renderLocalLauncher(options));chmodSync3(path, 493);if ((options.platform ?? process.platform) === "win32") {- writeFileSync6(localLauncherCmdPath(options.homeDir), `@echo off\r+ writeFileSync7(localLauncherCmdPath(options.homeDir), `@echo off\rnode "%~dp0omo" %*\r`);}@@ -97632,7 +97935,7 @@ node "%~dp0omo" %*\rimport { createHash as createHash6 } from "crypto";import { constants as constants9 } from "fs";import { access as access2, readFile as readFile27, stat as stat6 } from "fs/promises";-import { dirname as dirname23, join as join61 } from "path";+import { dirname as dirname24, join as join62 } from "path";// packages/memory-core/src/personas/manifest.tsvar PERSONA_ASSET_FILENAMES = {@@ -97651,12 +97954,12 @@ var PERSONA_ASSET_FILES = [// packages/omo-senpi/src/install/senpi-settings.tsimport { constants as constants8 } from "fs";import { access, copyFile as copyFile3, mkdir as mkdir9, readFile as readFile26, rename as rename5, writeFile as writeFile14 } from "fs/promises";-import { basename as basename9, dirname as dirname22, join as join60, resolve as resolve18 } from "path";+import { basename as basename10, dirname as dirname23, join as join61, resolve as resolve19 } from "path";var OMO_SENPI_PACKAGE_NAME = "@code-yeongyu/omo-senpi";var GENERATED_PLUGIN_BASENAME = /^omo-senpi-cli-plugin-[A-Za-z0-9]{6}$/;var LEGACY_BUILTIN_SHADOW_PACKAGES = [- join60("packages", "pi-goal"),- join60("packages", "pi-webfetch")+ join61("packages", "pi-goal"),+ join61("packages", "pi-webfetch")];async function readSettings(settingsPath) {let raw;@@ -97685,25 +97988,25 @@ function dedupePackages(packages) {return [...new Set(packages)];}function removeLegacyBuiltinShadows(packages, repoRoot, agentDir) {- const shadowPaths = new Set(LEGACY_BUILTIN_SHADOW_PACKAGES.map((path) => resolve18(repoRoot, path)));- return packages.filter((entry) => !shadowPaths.has(resolve18(agentDir, entry)));+ const shadowPaths = new Set(LEGACY_BUILTIN_SHADOW_PACKAGES.map((path) => resolve19(repoRoot, path)));+ return packages.filter((entry) => !shadowPaths.has(resolve19(agentDir, entry)));}async function removeSupersededOmoPackages(packages, currentPluginPath, agentDir) {- const currentPath = resolve18(currentPluginPath);+ const currentPath = resolve19(currentPluginPath);const entries = await Promise.all(packages.map(async (entry) => {- const packagePath = resolve18(agentDir, entry);+ const packagePath = resolve19(agentDir, entry);if (packagePath === currentPath)return currentPath;if (await readPackageName(packagePath) === OMO_SENPI_PACKAGE_NAME)return;- if (GENERATED_PLUGIN_BASENAME.test(basename9(entry)) && !await fileExists(packagePath))+ if (GENERATED_PLUGIN_BASENAME.test(basename10(entry)) && !await fileExists(packagePath))return;return entry;}));return entries.filter((entry) => entry !== undefined);}async function writeSettingsAtomically(settingsPath, settings) {- await mkdir9(dirname22(settingsPath), { recursive: true });+ await mkdir9(dirname23(settingsPath), { recursive: true });const backupPath = await nextBackupPath(settingsPath);if (await fileExists(settingsPath)) {await copyFile3(settingsPath, backupPath);@@ -97735,7 +98038,7 @@ function isRecord15(value) {async function readPackageName(packagePath) {let raw;try {- raw = await readFile26(join60(packagePath, "package.json"), "utf8");+ raw = await readFile26(join61(packagePath, "package.json"), "utf8");} catch (error) {if (isErrno(error, "ENOENT") || isErrno(error, "ENOTDIR"))return;@@ -97767,52 +98070,52 @@ function isErrno(error, code) {// packages/omo-senpi/src/install/plugin-artifacts.tsvar REQUIRED_PLUGIN_ARTIFACTS = [- join61("extensions", "omo.js"),- join61("extensions", "omo-task.js"),- join61("extensions", "omo-member.js"),- join61("extensions", "memory-run-supervisor.mjs"),- ...PERSONA_ASSET_FILES.map((filename) => join61("extensions", filename)),- join61("skills", "ast-grep", "SKILL.md"),- join61("skills", "browser", "SKILL.md"),- join61("skills", "coding-agent-sessions", "SKILL.md"),- join61("skills", "debugging", "SKILL.md"),- join61("skills", "frontend", "SKILL.md"),- join61("skills", "git-master", "SKILL.md"),- join61("skills", "init-deep", "SKILL.md"),- join61("skills", "lsp-setup", "SKILL.md"),- join61("skills", "programming", "SKILL.md"),- join61("skills", "refactor", "SKILL.md"),- join61("skills", "remove-ai-slops", "SKILL.md"),- join61("skills", "review-work", "SKILL.md"),- join61("skills", "ultimate-browsing", "SKILL.md"),- join61("skills", "ultrawork", "SKILL.md"),- join61("skills", "ulw-execute", "SKILL.md"),- join61("skills", "ulw-loop", "SKILL.md"),- join61("skills", "ulw-plan", "SKILL.md"),- join61("skills", "ulw-research", "SKILL.md"),- join61("skills", "visual-qa", "SKILL.md"),- join61("skills-conditional", "x-search", "SKILL.md"),- join61("runtime", "agent-toolkit-sdk", "sdk.js"),- join61("runtime", "ast-grep-mcp", "cli.js"),- join61("runtime", "lsp-daemon", "dist", "cli.js"),- join61("runtime", "lsp-daemon", "dist", "index.js"),- join61("runtime", "lsp-daemon", "dist", "index.d.ts"),- join61("runtime", "lsp-daemon", "dist", "daemon-client.js"),- join61("runtime", "lsp-daemon", "dist", "daemon-client.d.ts"),- join61("runtime", "lsp-daemon", "dist", "package.json"),- join61("runtime", "lsp-daemon", "dist", ".omo-runtime-manifest.json"),- join61("scripts", "install.mjs"),+ join62("extensions", "omo.js"),+ join62("extensions", "omo-task.js"),+ join62("extensions", "omo-member.js"),+ join62("extensions", "memory-run-supervisor.mjs"),+ ...PERSONA_ASSET_FILES.map((filename) => join62("extensions", filename)),+ join62("skills", "ast-grep", "SKILL.md"),+ join62("skills", "browser", "SKILL.md"),+ join62("skills", "coding-agent-sessions", "SKILL.md"),+ join62("skills", "debugging", "SKILL.md"),+ join62("skills", "frontend", "SKILL.md"),+ join62("skills", "git-master", "SKILL.md"),+ join62("skills", "init-deep", "SKILL.md"),+ join62("skills", "lsp-setup", "SKILL.md"),+ join62("skills", "programming", "SKILL.md"),+ join62("skills", "refactor", "SKILL.md"),+ join62("skills", "remove-ai-slops", "SKILL.md"),+ join62("skills", "review-work", "SKILL.md"),+ join62("skills", "ultimate-browsing", "SKILL.md"),+ join62("skills", "ultrawork", "SKILL.md"),+ join62("skills", "ulw-execute", "SKILL.md"),+ join62("skills", "ulw-loop", "SKILL.md"),+ join62("skills", "ulw-plan", "SKILL.md"),+ join62("skills", "ulw-research", "SKILL.md"),+ join62("skills", "visual-qa", "SKILL.md"),+ join62("skills-conditional", "x-search", "SKILL.md"),+ join62("runtime", "agent-toolkit-sdk", "sdk.js"),+ join62("runtime", "ast-grep-mcp", "cli.js"),+ join62("runtime", "lsp-daemon", "dist", "cli.js"),+ join62("runtime", "lsp-daemon", "dist", "index.js"),+ join62("runtime", "lsp-daemon", "dist", "index.d.ts"),+ join62("runtime", "lsp-daemon", "dist", "daemon-client.js"),+ join62("runtime", "lsp-daemon", "dist", "daemon-client.d.ts"),+ join62("runtime", "lsp-daemon", "dist", "package.json"),+ join62("runtime", "lsp-daemon", "dist", ".omo-runtime-manifest.json"),+ join62("scripts", "install.mjs"),"daemon-launch-spec.json"];async function ensurePluginArtifacts(context) {if (context.allowBuild) {- await context.runCommand("node", [join61(context.pluginPath, "scripts", "build-extension.mjs")], { cwd: context.repoRoot });- await context.runCommand("node", [join61("packages", "omo-codex", "plugin", "scripts", "materialize-shared-upstreams.mjs")], { cwd: context.repoRoot });- await context.runCommand("node", [join61(context.pluginPath, "scripts", "sync-skills.mjs")], { cwd: context.repoRoot });- await context.runCommand("node", [join61(context.pluginPath, "scripts", "build-install.mjs")], { cwd: context.repoRoot });- await context.runCommand("node", [join61(context.pluginPath, "scripts", "stage-lsp-daemon-runtime.mjs")], { cwd: context.repoRoot });- await context.runCommand("node", [join61(context.pluginPath, "scripts", "stage-ast-grep-mcp-runtime.mjs")], { cwd: context.repoRoot });- await context.runCommand("node", [join61(context.pluginPath, "scripts", "stage-x-search-skill.mjs")], { cwd: context.repoRoot });+ await context.runCommand("node", [join62(context.pluginPath, "scripts", "build-extension.mjs")], { cwd: context.repoRoot });+ await context.runCommand("node", [join62("packages", "omo-codex", "plugin", "scripts", "materialize-shared-upstreams.mjs")], { cwd: context.repoRoot });+ await context.runCommand("node", [join62(context.pluginPath, "scripts", "sync-skills.mjs")], { cwd: context.repoRoot });+ await context.runCommand("node", [join62(context.pluginPath, "scripts", "build-install.mjs")], { cwd: context.repoRoot });+ await context.runCommand("node", [join62(context.pluginPath, "scripts", "stage-lsp-daemon-runtime.mjs")], { cwd: context.repoRoot });+ await context.runCommand("node", [join62(context.pluginPath, "scripts", "stage-ast-grep-mcp-runtime.mjs")], { cwd: context.repoRoot });+ await context.runCommand("node", [join62(context.pluginPath, "scripts", "stage-x-search-skill.mjs")], { cwd: context.repoRoot });}if (await hasMissingPluginArtifact(context.pluginPath)) {throw new Error(`Packed omo-senpi plugin is missing required runtime artifacts at ${context.pluginPath}`);@@ -97821,14 +98124,14 @@ async function ensurePluginArtifacts(context) {}async function hasMissingPluginArtifact(pluginPath) {for (const artifact of REQUIRED_PLUGIN_ARTIFACTS) {- if (!await fileExists2(join61(pluginPath, artifact)))+ if (!await fileExists2(join62(pluginPath, artifact)))return true;}return false;}async function verifyAstGrepRuntimeIntegrity(pluginPath, platform) {- const runtimeEntry = join61(pluginPath, "runtime", "ast-grep-mcp", "cli.js");- const manifestPath = join61(dirname23(runtimeEntry), "manifest.json");+ const runtimeEntry = join62(pluginPath, "runtime", "ast-grep-mcp", "cli.js");+ const manifestPath = join62(dirname24(runtimeEntry), "manifest.json");let runtimeStat;try {runtimeStat = await stat6(runtimeEntry);@@ -97903,7 +98206,7 @@ async function runSenpiInstaller(options = {}) {const backupPath = await writeSettingsAtomically(context.settingsPath, settings);const launcherPath = installLocalLauncher({pluginPath: context.pluginPath,- senpiCliPath: join62(context.repoRoot, "packages", "coding-agent", "dist", "cli.js"),+ senpiCliPath: join63(context.repoRoot, "packages", "coding-agent", "dist", "cli.js"),homeDir: context.homeDir});return {@@ -97920,16 +98223,16 @@ async function runSenpiInstaller(options = {}) {function resolveInstallContext(options) {const env = options.env ?? process.env;const allowBuild = options.pluginPath === undefined;- const repoRoot = resolve19(options.repoRoot ?? (allowBuild ? findRepoRoot2(dirname24(fileURLToPath(import.meta.url))) : dirname24(resolve19(options.pluginPath))));+ const repoRoot = resolve20(options.repoRoot ?? (allowBuild ? findRepoRoot2(dirname25(fileURLToPath(import.meta.url))) : dirname25(resolve20(options.pluginPath))));const homeDir = options.homeDir ?? env.HOME ?? homedir11();- const agentDir = resolve19(options.agentDir ?? resolveAgentHome({ env, homeDir }));- const pluginPath = resolve19(options.pluginPath ?? join62(repoRoot, "packages", "omo-senpi", "plugin"));+ const agentDir = resolve20(options.agentDir ?? resolveAgentHome({ env, homeDir }));+ const pluginPath = resolve20(options.pluginPath ?? join63(repoRoot, "packages", "omo-senpi", "plugin"));return {env,repoRoot,agentDir,homeDir,- settingsPath: join62(agentDir, "settings.json"),+ settingsPath: join63(agentDir, "settings.json"),pluginPath,platform: options.platform ?? process.platform,allowBuild,@@ -97946,14 +98249,14 @@ async function defaultRunCommand3(command, args, options) {function findRepoRoot2(importerDir) {let current = importerDir;for (let depth = 0;depth <= 7; depth += 1) {- if (fileExistsSync(join62(current, "packages", "omo-senpi", "plugin", "package.json")))+ if (fileExistsSync(join63(current, "packages", "omo-senpi", "plugin", "package.json")))return current;- current = resolve19(current, "..");+ current = resolve20(current, "..");}throw new Error("Unable to locate packages/omo-senpi/plugin/package.json from installer module");}function fileExistsSync(path) {- return existsSync30(path);+ return existsSync31(path);}// packages/omo-opencode/src/cli/install-native-dev/index.tsasync function runNativeDevInstaller(options) {@@ -97961,6 +98264,8 @@ async function runNativeDevInstaller(options) {}// packages/omo-opencode/src/cli/install-native/plan.ts+init_shared();+init_bundled_version();var NATIVE_PACKAGE_SPEC = "omo-ai@beta";var NATIVE_SETUP_COMMAND = "omo setup";var NATIVE_RECOMMENDED_RUNTIME_NOTE = "bun is the recommended runtime for OmO Native; npm works, but bun is what the beta channel is tested on.";@@ -97974,9 +98279,254 @@ function resolveNativeInstallPlan(bunAvailable) {function formatNativeInstallCommand(plan) {return [plan.command, ...plan.args].join(" ");}+function formatNativeInstallEntryCommand(plan, pluginVersion = getBundledVersion()) {+ const runner = plan.packageManager === "bun" ? "bunx" : "npx";+ const tag = isPrereleaseVersion(pluginVersion) ? "@beta" : "";+ return `${runner} ${PUBLISHED_PACKAGE_NAME}${tag} install --platform=native`;+}+// packages/omo-opencode/src/cli/install-native/legacy-omo-bin.ts+import { lstatSync as lstatSync4, readFileSync as readFileSync15, realpathSync as realpathSync8 } from "fs";+import { dirname as dirname26, isAbsolute as isAbsolute12, join as join64, posix as posix9, win32 as win325 } from "path";+var NATIVE_OMO_PACKAGE = "omo-ai";+var LEGACY_OMO_BIN_PACKAGES = ["oh-my-openagent", "oh-my-opencode", "lazycodex"];+var CODEX_LIGHT_WRAPPER_MARKER = "OMO_GENERATED_RUNTIME_WRAPPER";+var CODEX_LIGHT_CACHE_VERSION = /[\\/]plugins[\\/]cache[\\/]sisyphuslabs[\\/]omo[\\/]([^\\/"'\s]+)[\\/]/;+var OMO_BIN_NAME = "omo";+var WINDOWS_BIN_SUFFIXES = ["", ".cmd", ".ps1", ".exe"];+var OWNER_WALK_UP_LIMIT = 6;+var SHIM_READ_LIMIT = 8192;+function resolveOmoBinEnvironment(input) {+ const isWindows = input.platform === "win32";+ const pathRules = isWindows ? win325 : posix9;+ const pathValue = input.env["PATH"] ?? input.env["Path"] ?? "";+ const pathDirectories = pathValue.split(pathRules.delimiter).map((entry) => entry.trim()).filter((entry) => pathRules.isAbsolute(entry)).filter((entry) => !/(?:^|[\\/])node_modules[\\/]\.bin[\\/]?$/.test(entry));+ const bunInstall = input.env["BUN_INSTALL"];+ const bunBinDir = bunInstall ? pathRules.join(bunInstall, "bin") : pathRules.join(input.homeDir, ".bun", "bin");+ const extraDirectories = pathDirectories.includes(bunBinDir) ? [] : [bunBinDir];+ return { pathDirectories, extraDirectories, isWindows };+}+function scanOmoBins(environment) {+ const visited = new Set;+ const entries = [];+ const visit = (directory, onPath) => {+ if (directory === "" || visited.has(directory))+ return;+ visited.add(directory);+ const shimPaths = omoShimPathsIn(directory, environment.isWindows);+ const binPath = shimPaths[0];+ if (binPath === undefined)+ return;+ const owner = resolveOwner(binPath);+ entries.push({+ binPath,+ directory,+ onPath,+ kind: classify(owner),+ packageName: owner?.name ?? null,+ packageVersion: owner?.version ?? null,+ shimPaths+ });+ };+ for (const directory of environment.pathDirectories)+ visit(directory, true);+ for (const directory of environment.extraDirectories)+ visit(directory, false);+ return entries;+}+function legacyOmoBins(entries) {+ return entries.filter((entry) => entry.kind === "legacy");+}+function nativeOmoBin(entries) {+ return entries.find((entry) => entry.kind === "native") ?? null;+}+function firstOmoBinOnPath(entries) {+ return entries.find((entry) => entry.onPath) ?? null;+}+function classify(owner) {+ if (owner === null)+ return "foreign";+ if (owner.name === NATIVE_OMO_PACKAGE)+ return "native";+ return LEGACY_OMO_BIN_PACKAGES.includes(owner.name) ? "legacy" : "foreign";+}+function omoShimPathsIn(directory, isWindows) {+ const suffixes = isWindows ? WINDOWS_BIN_SUFFIXES : [""];+ return suffixes.map((suffix) => join64(directory, `${OMO_BIN_NAME}${suffix}`)).filter(pathExists);+}+function pathExists(path) {+ try {+ lstatSync4(path);+ return true;+ } catch {+ return false;+ }+}+function resolveOwner(binPath) {+ const real = realPathOf(binPath);+ const fromLink = isInsideNodeModules(real) ? ownerOfFile(real) : null;+ if (fromLink !== null)+ return fromLink;+ const shim = readShimText(binPath);+ if (shim === null)+ return null;+ const lightWrapper = codexLightWrapperOwner(shim);+ if (lightWrapper !== null)+ return lightWrapper;+ for (const entry of shimEntryPaths(shim, dirname26(binPath))) {+ if (!isInsideNodeModules(entry) || !pathExists(entry))+ continue;+ const owner = ownerOfFile(entry);+ if (owner !== null)+ return owner;+ }+ return null;+}+function shimEntryPaths(shim, shimDirectory) {+ const paths = [];+ for (const match of shim.matchAll(/(?<=["'])[^"'\n]*node_modules[\\/][^"'\n]*(?=["'])/g)) {+ const quoted = match[0];+ const relativeToShim = quoted.match(/^(?:%~?dp0%?|\$\{?basedir\}?)[\\/]?(.*)$/)?.[1];+ if (relativeToShim !== undefined)+ paths.push(join64(shimDirectory, relativeToShim.replace(/\\/g, "/")));+ else if (isAbsolute12(quoted))+ paths.push(quoted);+ }+ return paths;+}+function codexLightWrapperOwner(shim) {+ if (!shim.includes(CODEX_LIGHT_WRAPPER_MARKER))+ return null;+ const version = shim.match(CODEX_LIGHT_CACHE_VERSION)?.[1];+ return version === undefined ? null : { name: "lazycodex", version };+}+function isInsideNodeModules(path) {+ return /(?:^|[\\/])node_modules[\\/]/.test(path);+}+function ownerOfFile(file) {+ let directory = dirname26(file);+ for (let depth = 0;depth < OWNER_WALK_UP_LIMIT; depth += 1) {+ const manifest = readWholeFile(join64(directory, "package.json"));+ if (manifest !== null) {+ const parsed = parseManifest(manifest);+ if (parsed !== null)+ return parsed;+ }+ const parent = dirname26(directory);+ if (parent === directory)+ return null;+ directory = parent;+ }+ return null;+}+function parseManifest(manifest) {+ try {+ const parsed = JSON.parse(manifest);+ if (typeof parsed !== "object" || parsed === null)+ return null;+ const record = parsed;+ if (typeof record.name !== "string" || record.name === "")+ return null;+ return { name: record.name, version: typeof record.version === "string" ? record.version : null };+ } catch {+ return null;+ }+}+function realPathOf(path) {+ try {+ return realpathSync8(path);+ } catch {+ return path;+ }+}+function readShimText(path) {+ return readWholeFile(path)?.slice(0, SHIM_READ_LIMIT) ?? null;+}+function readWholeFile(path) {+ try {+ return readFileSync15(path, "utf8");+ } catch {+ return null;+ }+}+// packages/omo-opencode/src/cli/install-native/repair-legacy-omo-bin.ts+import { rmSync as rmSync5 } from "fs";+function describePackage(entry) {+ const name = entry.packageName ?? "an unknown package";+ return entry.packageVersion === null ? name : `${name}@${entry.packageVersion}`;+}+function removeFileCommand(binPath, isWindows) {+ return isWindows ? `del "${binPath}"` : `rm "${binPath}"`;+}+function repairLegacyOmoBins(entries, options) {+ const removed = [];+ const failures = [];+ const notes = [];+ const warnings = [];+ for (const entry of entries) {+ const owner = describePackage(entry);+ try {+ for (const shimPath of entry.shimPaths)+ rmSync5(shimPath);+ removed.push({+ binPath: entry.binPath,+ packageName: entry.packageName ?? "",+ packageVersion: entry.packageVersion+ });+ notes.push(`Removed the stale omo command left by ${owner} (${entry.binPath}). That package and its other commands are untouched; reinstalling it would put its omo back in front of omo-ai.`);+ } catch (error) {+ const reason = error instanceof Error ? error.message : String(error);+ failures.push({ binPath: entry.binPath, reason });+ warnings.push(`Could not remove the stale omo command owned by ${owner} (${entry.binPath}): ${reason}. Remove it yourself with ${removeFileCommand(entry.binPath, options.isWindows)}, or drop the whole package with npm uninstall -g ${entry.packageName ?? "oh-my-openagent"}.`);+ }+ }+ return { removed, failures, notes, warnings };+}+// packages/omo-opencode/src/cli/install-native/verify-omo-command.ts+function pathOrderFix(directory, isWindows) {+ return isWindows ? `set PATH=${directory};%PATH%` : `export PATH="${directory}:$PATH"`;+}+async function verifyOmoCommand(options) {+ const entries = scanOmoBins(options.environment);+ const native = nativeOmoBin(entries);+ const resolved = firstOmoBinOnPath(entries);+ if (native === null) {+ return {+ ok: false,+ notes: [],+ warnings: ["Could not find an omo command owned by omo-ai after the install. Run omo --version yourself to check."]+ };+ }+ if (!native.onPath) {+ return {+ ok: false,+ notes: [],+ warnings: [+ `omo-ai installed ${native.binPath}, but ${native.directory} is not on PATH. Add it: ${pathOrderFix(native.directory, options.environment.isWindows)}`+ ]+ };+ }+ if (resolved !== null && resolved.binPath !== native.binPath) {+ return { ok: false, notes: [], warnings: [shadowWarning(resolved, native, options.environment.isWindows)] };+ }+ const probe = await options.probeVersion(native.binPath, ["--version"]);+ const printed = probe.stdout.trim().split(`+`)[0] ?? "";+ if (probe.exitCode !== 0 || !printed.startsWith("omo ")) {+ return {+ ok: false,+ notes: [],+ warnings: [`omo --version did not report omo-ai (exit ${probe.exitCode}): ${printed || "no output"}`]+ };+ }+ return { ok: true, binPath: native.binPath, notes: [`omo --version reports ${printed}`], warnings: [] };+}+function shadowWarning(resolved, native, isWindows) {+ return `omo on PATH still resolves to ${resolved.binPath} (${describePackage(resolved)}), not to the omo-ai command at ${native.binPath}. Put omo-ai first: ${pathOrderFix(native.directory, isWindows)}`;+}// packages/omo-opencode/src/cli/install-native/run-native-install.tsinit_bun_which_shim();init_spawn_with_windows_hide();+import { homedir as homedir12 } from "os";function describeExit(plan, result) {const stderr = result.stderr?.trim();const head = `${plan.packageManager} exited with code ${result.exitCode}`;@@ -97985,24 +98535,54 @@ function describeExit(plan, result) {}async function runNativeInstall(dependencies = defaultNativeInstallDependencies()) {const plan = resolveNativeInstallPlan(await dependencies.isBunAvailable());+ const environment = dependencies.environment;const notes = plan.packageManager === "npm" ? [NATIVE_RECOMMENDED_RUNTIME_NOTE] : [];+ const warnings = [];const manualCommand = formatNativeInstallCommand(plan);+ const repair = repairLegacyOmoBins(legacyOmoBins(scanOmoBins(environment)), { isWindows: environment.isWindows });+ notes.push(...repair.notes);+ warnings.push(...repair.warnings);+ const hints = repair.failures.map((failure) => `Remove the stale omo command first: ${removeFileCommand(failure.binPath, environment.isWindows)}`);+ const failed = (reason) => ({+ ok: false,+ verified: false,+ plan,+ notes,+ warnings,+ failure: hints.length > 0 ? { reason, manualCommand, hints } : { reason, manualCommand }+ });try {const result = await dependencies.spawn(plan.command, plan.args);- if (result.exitCode === 0)- return { ok: true, plan, notes };- return { ok: false, plan, notes, failure: { reason: describeExit(plan, result), manualCommand } };+ if (result.exitCode !== 0)+ return failed(describeExit(plan, result));} catch (error) {- const reason = error instanceof Error ? error.message : String(error);- return { ok: false, plan, notes, failure: { reason, manualCommand } };+ return failed(error instanceof Error ? error.message : String(error));+ }+ if (plan.packageManager === "npm") {+ for (const name of new Set(repair.removed.map((removal) => removal.packageName))) {+ if (NPM_LEGACY_OMO_PACKAGES.includes(name))+ notes.push(npmUninstallNote(name, manualCommand));+ }}+ const verification = await verifyOmoCommand({ environment, probeVersion: dependencies.probeVersion });+ notes.push(...verification.notes);+ warnings.push(...verification.warnings);+ return verification.ok ? { ok: true, verified: true, omoBinPath: verification.binPath, plan, notes, warnings } : { ok: true, verified: false, plan, notes, warnings };}-function nativeInstallSuccessLine() {+var NPM_LEGACY_OMO_PACKAGES = ["oh-my-openagent", "oh-my-opencode"];+function npmUninstallNote(packageName, installCommand) {+ return `If you later run npm uninstall -g ${packageName}, npm also deletes the omo command omo-ai now owns. Run ${installCommand} again afterwards to restore it.`;+}+function nativeInstallSuccessLine(verified) {+ if (!verified) {+ return `OmO Native installed, but omo on your PATH is not omo-ai yet. Apply the fix above, then run ${NATIVE_SETUP_COMMAND}.`;+ }return `OmO Native installed. Run ${NATIVE_SETUP_COMMAND} to finish onboarding.`;}function nativeInstallFailureLines(failure) {return [`OmO Native install failed: ${failure.reason}`,+ ...failure.hints ?? [],`Install it yourself with: ${failure.manualCommand}`,`Then run ${NATIVE_SETUP_COMMAND}.`];@@ -98010,6 +98590,7 @@ function nativeInstallFailureLines(failure) {function defaultNativeInstallDependencies() {return {isBunAvailable: () => bunWhich("bun") !== null,+ environment: resolveOmoBinEnvironment({ env: process.env, platform: process.platform, homeDir: homedir12() }),spawn: async (command, args) => {const proc = spawnWithWindowsHide([command, ...args], {env: process.env,@@ -98017,12 +98598,58 @@ function defaultNativeInstallDependencies() {stderr: "inherit"});return { exitCode: await proc.exited };+ },+ probeVersion: async (command, args) => {+ const proc = spawnWithWindowsHide([command, ...args], {+ env: process.env,+ stdout: "pipe",+ stderr: "pipe"+ });+ const stdout = proc.stdout === undefined ? "" : await new Response(proc.stdout).text();+ return { exitCode: await proc.exited, stdout };}};}+// packages/omo-opencode/src/cli/install-native/offer-native-setup.ts+init_spawn_with_windows_hide();+var NATIVE_SETUP_OFFER_QUESTION = "Run omo setup now to carry your OpenCode credentials, MCP servers and skills over?";+async function offerNativeSetup(outcome, dependencies) {+ const binPath = outcome.verified ? outcome.omoBinPath : undefined;+ if (binPath === undefined)+ return { kind: "not-offered" };+ if (!await dependencies.confirm(NATIVE_SETUP_OFFER_QUESTION))+ return { kind: "declined" };+ const runSetup = dependencies.runSetup ?? runSetupInheritingTerminal;+ dependencies.onStart?.(nativeSetupStartLine(binPath));+ try {+ return { kind: "ran", binPath, exitCode: await runSetup(binPath, ["setup"]) };+ } catch (error) {+ return { kind: "failed", binPath, reason: error instanceof Error ? error.message : String(error) };+ }+}+function nativeSetupStartLine(binPath) {+ return `Starting ${binPath} setup`;+}+function nativeSetupFollowUpLine(result) {+ if (result.kind === "failed") {+ return `Could not start ${result.binPath} setup (${result.reason}). Run ${NATIVE_SETUP_COMMAND} to finish onboarding.`;+ }+ if (result.kind !== "ran" || result.exitCode === 0)+ return null;+ return `omo setup exited with code ${result.exitCode}. Run ${NATIVE_SETUP_COMMAND} again to finish onboarding.`;+}+async function runSetupInheritingTerminal(binPath, args) {+ const proc = spawnWithWindowsHide([binPath, ...args], {+ env: process.env,+ stdin: "inherit",+ stdout: "inherit",+ stderr: "inherit"+ });+ return proc.exited;+}// packages/omo-opencode/src/cli/native-edition-hint.ts-var NATIVE_EDITION_INSTALL_COMMAND = "bun add -g omo-ai@beta";-var NATIVE_EDITION_GUIDE_URL = "https://github.com/code-yeongyu/oh-my-openagent/blob/dev/docs/guide/installation.md#omo-native-beta-omo-via-omo-ai";+var NATIVE_EDITION_INSTALL_COMMAND = formatNativeInstallEntryCommand(resolveNativeInstallPlan(true));+var NATIVE_EDITION_GUIDE_URL = "https://github.com/code-yeongyu/oh-my-openagent/blob/dev/docs/guide/migrating-from-opencode.md";var NATIVE_EDITION_HINT_TITLE = "OmO Native (beta)";var PLAIN_PAINT = {command: (text) => text,@@ -98075,26 +98702,39 @@ async function starGitHubRepositories(platform = "both", runCommand = runGitHubSinit_provider_availability();// packages/omo-opencode/src/cli/config-manager/add-tui-plugin-to-tui-config.ts-import { existsSync as existsSync32, mkdirSync as mkdirSync12, readFileSync as readFileSync15 } from "fs";-import { join as join64 } from "path";+import { existsSync as existsSync33, mkdirSync as mkdirSync13, readFileSync as readFileSync17 } from "fs";+import { join as join66 } from "path";// packages/omo-opencode/src/cli/doctor/checks/tui-plugin-config.tsinit_shared();-import { existsSync as existsSync31, readFileSync as readFileSync14 } from "fs";-import { join as join63 } from "path";+import { existsSync as existsSync32, readFileSync as readFileSync16 } from "fs";+import { join as join65 } from "path";var TUI_SUBPATH = "tui";var TUI_EXPORT_SUBPATH = `./${TUI_SUBPATH}`;+function tuiPluginSpecName(entry) {+ if (typeof entry === "string")+ return entry;+ if (isPluginTupleEntry(entry))+ return entry[0];+ return null;+}+function isOmoSourceFileSpec(name) {+ const normalized = name.toLowerCase().replaceAll("\\", "/");+ if (!normalized.startsWith("file://"))+ return false;+ return /\/(omo(?:-[^/]*)?|oh-my-opencode|oh-my-openagent)\/(src|dist)\/index\.(ts|js)$/.test(normalized);+}function fileEntryPackageJsonPath(entry) {let path = entry.slice("file:".length);if (path.startsWith("//"))path = path.slice(2);- return join63(path, "package.json");+ return join65(path, "package.json");}function packageJsonExportsTui(pkgJsonPath) {- if (!existsSync31(pkgJsonPath))+ if (!existsSync32(pkgJsonPath))return null;try {- const parsed = JSON.parse(readFileSync14(pkgJsonPath, "utf-8"));+ const parsed = JSON.parse(readFileSync16(pkgJsonPath, "utf-8"));if (parsed.exports === undefined)return null;if (typeof parsed.exports === "string")@@ -98118,7 +98758,8 @@ function packageNameFromServerEntry(entry) {return null;}function isPackagePluginEntry(entry) {- return packageNameFromServerEntry(entry) !== null;+ const name = tuiPluginSpecName(entry);+ return name !== null && packageNameFromServerEntry(name) !== null;}function packageExportsTuiForServerEntry(entry) {if (typeof entry === "string" && entry.startsWith("file:"))@@ -98126,16 +98767,16 @@ function packageExportsTuiForServerEntry(entry) {const packageName = packageNameFromServerEntry(entry);if (packageName === null)return null;- return packageJsonExportsTui(join63(getOpenCodeConfigDir({ binary: "opencode" }), "node_modules", packageName, "package.json"));+ return packageJsonExportsTui(join65(getOpenCodeConfigDir({ binary: "opencode" }), "node_modules", packageName, "package.json"));}function isOurFilePluginEntry(entry) {if (typeof entry !== "string" || !entry.startsWith("file:"))return false;try {const pkgJsonPath = fileEntryPackageJsonPath(entry);- if (!existsSync31(pkgJsonPath))+ if (!existsSync32(pkgJsonPath))return false;- const parsed = JSON.parse(readFileSync14(pkgJsonPath, "utf-8"));+ const parsed = JSON.parse(readFileSync16(pkgJsonPath, "utf-8"));return typeof parsed.name === "string" && ACCEPTED_PACKAGE_NAMES.includes(parsed.name);} catch (error) {log2("[tui-plugin-config] Failed to inspect file plugin package", {@@ -98155,27 +98796,49 @@ function isServerPluginEntry(entry) {return false;}function isTuiPluginEntry(entry) {- return typeof entry === "string" && (isPackagePluginEntry(entry) || entry.startsWith("file:") && isOurFilePluginEntry(entry));+ const name = tuiPluginSpecName(entry);+ if (name === null)+ return false;+ return isPackagePluginEntry(name) || name.startsWith("file:") && isOurFilePluginEntry(name);}function isNamedTuiPluginEntry(entry) {+ const name = tuiPluginSpecName(entry);+ if (name === null)+ return false;const canonicalPrefix = `${PLUGIN_NAME}/${TUI_SUBPATH}`;const legacyPrefix = `${LEGACY_PLUGIN_NAME}/${TUI_SUBPATH}`;- return typeof entry === "string" && (entry === canonicalPrefix || entry.startsWith(`${canonicalPrefix}@`) || entry === legacyPrefix || entry.startsWith(`${legacyPrefix}@`));+ return name === canonicalPrefix || name.startsWith(`${canonicalPrefix}@`) || name === legacyPrefix || name.startsWith(`${legacyPrefix}@`);+}+function isOmoManagedTuiEntry(entry) {+ const name = tuiPluginSpecName(entry);+ if (name === null)+ return false;+ return isNamedTuiPluginEntry(name) || isTuiPluginEntry(name) || isOmoSourceFileSpec(name);}function isCanonicalNamedTuiPluginEntry(entry) {+ const name = tuiPluginSpecName(entry);+ if (name === null)+ return false;const canonicalPrefix = `${PLUGIN_NAME}/${TUI_SUBPATH}`;- return typeof entry === "string" && (entry === canonicalPrefix || entry.startsWith(`${canonicalPrefix}@`));+ return name === canonicalPrefix || name.startsWith(`${canonicalPrefix}@`);}function detectServerPluginRegistration() {const paths = getOpenCodeConfigPaths({ binary: "opencode", version: null });- const configPath = existsSync31(paths.configJsonc) ? paths.configJsonc : existsSync31(paths.configJson) ? paths.configJson : null;+ const configPath = existsSync32(paths.configJsonc) ? paths.configJsonc : existsSync32(paths.configJson) ? paths.configJson : null;if (!configPath) {return { registered: false, configPath: null, entry: null, packageExportsTui: null };}try {- const parsed = parseJsonc(readFileSync14(configPath, "utf-8"));+ const parsed = parseJsonc(readFileSync16(configPath, "utf-8"));const plugins = parsed.plugin ?? [];- const serverEntry = plugins.find(isServerPluginEntry);+ let serverEntry;+ for (const entry of plugins) {+ const name = tuiPluginSpecName(entry);+ if (name !== null && isServerPluginEntry(name)) {+ serverEntry = name;+ break;+ }+ }return {registered: serverEntry !== undefined,configPath,@@ -98191,19 +98854,20 @@ function detectServerPluginRegistration() {}}function detectTuiPluginRegistration() {- const tuiJsonPath = join63(getOpenCodeConfigDir({ binary: "opencode" }), "tui.json");- if (!existsSync31(tuiJsonPath)) {+ const tuiJsonPath = join65(getOpenCodeConfigDir({ binary: "opencode" }), "tui.json");+ if (!existsSync32(tuiJsonPath)) {return {registered: false,configPath: tuiJsonPath,exists: false,hasPackageTuiEntry: false,hasNamedTuiEntry: false,- hasCanonicalNamedTuiEntry: false+ hasCanonicalNamedTuiEntry: false,+ managedEntryCount: 0};}try {- const parsed = parseJsonc(readFileSync14(tuiJsonPath, "utf-8"));+ const parsed = parseJsonc(readFileSync16(tuiJsonPath, "utf-8"));const plugins = parsed.plugin ?? [];return {registered: plugins.some(isTuiPluginEntry),@@ -98211,7 +98875,8 @@ function detectTuiPluginRegistration() {exists: true,hasPackageTuiEntry: plugins.some(isPackagePluginEntry),hasNamedTuiEntry: plugins.some(isNamedTuiPluginEntry),- hasCanonicalNamedTuiEntry: plugins.some(isCanonicalNamedTuiPluginEntry)+ hasCanonicalNamedTuiEntry: plugins.some(isCanonicalNamedTuiPluginEntry),+ managedEntryCount: plugins.filter(isOmoManagedTuiEntry).length};} catch (error) {log2("[tui-plugin-config] Failed to inspect TUI plugin config", {@@ -98224,7 +98889,8 @@ function detectTuiPluginRegistration() {exists: true,hasPackageTuiEntry: false,hasNamedTuiEntry: false,- hasCanonicalNamedTuiEntry: false+ hasCanonicalNamedTuiEntry: false,+ managedEntryCount: 0};}}@@ -98281,6 +98947,23 @@ async function checkTuiPluginConfig() {issues};}+ if (tui.managedEntryCount > 1) {+ const desiredEntry = server.entry ?? PLUGIN_NAME;+ issues.push({+ title: "TUI plugin is registered more than once in tui.json",+ description: `tui.json lists ${tui.managedEntryCount} entries for ${PLUGIN_NAME} ` + "(bare name, version/tag spec, legacy name, /tui subpath, or file:). " + "OpenCode loads each one, so the plugin runs twice.",+ fix: `Re-run the installer (\`npx oh-my-openagent install\`) to keep a single "${desiredEntry}" entry in ${tui.configPath}.`,+ affects: ["TUI startup", "plugin loading"],+ severity: "warning"+ });+ return {+ name,+ status: "warn",+ message: "TUI plugin is registered more than once in tui.json",+ details: details.length > 0 ? details : undefined,+ issues+ };+ }if (server.registered && !tui.registered) {if (server.packageExportsTui === false) {return {@@ -98336,7 +99019,7 @@ init_shared();init_write_file_atomically();function readConfig(path) {try {- const parsed = parseJsonc(readFileSync15(path, "utf-8"));+ const parsed = parseJsonc(readFileSync17(path, "utf-8"));if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {return parsed;}@@ -98347,16 +99030,31 @@ function readConfig(path) {return null;}function readServerConfig(configDir) {- const jsoncPath = join64(configDir, "opencode.jsonc");- if (existsSync32(jsoncPath))+ const jsoncPath = join66(configDir, "opencode.jsonc");+ if (existsSync33(jsoncPath))return readConfig(jsoncPath);- const jsonPath = join64(configDir, "opencode.json");- if (existsSync32(jsonPath))+ const jsonPath = join66(configDir, "opencode.json");+ if (existsSync33(jsonPath))return readConfig(jsonPath);return null;}function pluginEntries(config) {- return Array.isArray(config.plugin) ? config.plugin.filter((entry) => typeof entry === "string") : [];+ if (Array.isArray(config.plugin))+ return config.plugin;+ if (typeof config.plugin === "string")+ return [config.plugin];+ return [];+}+function pluginFieldInvalid(config) {+ return config.plugin !== undefined && !Array.isArray(config.plugin) && typeof config.plugin !== "string";+}+function serverPluginEntry(config) {+ for (const entry of pluginEntries(config)) {+ const name = tuiPluginSpecName(entry);+ if (name !== null && isServerPluginEntry(name))+ return name;+ }+ return;}function desiredTuiEntry(serverEntry) {if (serverEntry === PLUGIN_NAME || serverEntry.startsWith(`${PLUGIN_NAME}@`)) {@@ -98371,7 +99069,7 @@ function desiredTuiEntry(serverEntry) {return null;}function readTuiConfig(tuiJsonPath) {- if (!existsSync32(tuiJsonPath)) {+ if (!existsSync33(tuiJsonPath)) {return { config: {}, malformed: false };}const config = readConfig(tuiJsonPath);@@ -98384,7 +99082,7 @@ function formatConfig(config) {function ensureTuiPluginEntry(opts = {}) {const configDir = opts.configDir ?? getOpenCodeConfigDir({ binary: "opencode", version: null });const serverConfig = readServerConfig(configDir);- const serverEntry = serverConfig ? pluginEntries(serverConfig).find(isServerPluginEntry) : undefined;+ const serverEntry = serverConfig ? serverPluginEntry(serverConfig) : undefined;if (!serverEntry) {return { changed: false, reason: "no-server-entry" };}@@ -98392,31 +99090,87 @@ function ensureTuiPluginEntry(opts = {}) {if (!desiredEntry) {return { changed: false, reason: "no-server-entry" };}- const tuiJsonPath = join64(configDir, "tui.json");+ const tuiJsonPath = join66(configDir, "tui.json");const { config, malformed } = readTuiConfig(tuiJsonPath);- if (malformed) {+ if (malformed || pluginFieldInvalid(config)) {return { changed: false, reason: "malformed" };}- const plugins = pluginEntries(config).filter((entry) => !isNamedTuiPluginEntry(entry));- if (plugins.includes(desiredEntry)) {+ const entries = pluginEntries(config);+ const otherEntries = entries.filter((entry) => !isOmoManagedTuiEntry(entry));+ const pluginIsArray = Array.isArray(config.plugin);+ const isOnlyDesiredEntry = pluginIsArray && entries.length === otherEntries.length + 1 && entries.includes(desiredEntry);+ if (isOnlyDesiredEntry) {return { changed: false, reason: "already-present" };}- mkdirSync12(configDir, { recursive: true });- writeFileAtomically2(tuiJsonPath, formatConfig({ ...config, plugin: [...plugins, desiredEntry] }));+ mkdirSync13(configDir, { recursive: true });+ writeFileAtomically2(tuiJsonPath, formatConfig({ ...config, plugin: [...otherEntries, desiredEntry] }));return { changed: true, reason: "added" };}+// packages/omo-opencode/src/cli/config-manager/refresh-opencode-plugin-sandbox.ts+init_shared();+init_config_context();+import { existsSync as existsSync34, readFileSync as readFileSync18 } from "fs";+import { join as join67 } from "path";+function readPluginEntries(configDir) {+ for (const name of ["opencode.jsonc", "opencode.json"]) {+ const configPath = join67(configDir, name);+ if (!existsSync34(configPath))+ continue;+ try {+ const parsed = parseJsonc(readFileSync18(configPath, "utf-8"));+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))+ continue;+ return (parsed.plugin ?? []).filter((entry) => typeof entry === "string");+ } catch (error) {+ if (!(error instanceof Error))+ throw error;+ log2(`[install] Could not read plugin entries from ${configPath}: ${error.message}`);+ }+ }+ return [];+}+function refreshOpenCodePluginSandboxes(options = {}) {+ const configDir = options.configDir ?? getConfigDir();+ const cacheDir = options.cacheDir ?? getOpenCodeCacheDir();+ const removed = [];+ const deferred = [];+ const failed = [];+ for (const entry of readPluginEntries(configDir)) {+ const sandboxDir = getPluginSandboxDir(cacheDir, entry);+ if (!sandboxDir)+ continue;+ try {+ if (hasOtherLivePluginSandboxLease(sandboxDir) && markPluginSandboxStale(sandboxDir, cacheDir)) {+ deferred.push(sandboxDir);+ log2(`[install] OpenCode is running from ${sandboxDir}; marked it for refresh when OpenCode exits`);+ continue;+ }+ if (!removePluginSandbox(sandboxDir, cacheDir))+ continue;+ removed.push(sandboxDir);+ log2(`[install] Removed stale OpenCode plugin sandbox: ${sandboxDir}`);+ } catch (error) {+ if (!(error instanceof Error))+ throw error;+ failed.push({ dir: sandboxDir, message: error.message });+ log2(`[install] Failed to remove OpenCode plugin sandbox ${sandboxDir}: ${error.message}`);+ }+ }+ return { removed, deferred, failed };+}+// packages/omo-opencode/src/cli/install-ast-grep-sg.ts-import { homedir as homedir12 } from "os";-import { join as join65 } from "path";+import { homedir as homedir13 } from "os";+import { join as join68 } from "path";// packages/shared-skills/index.mjs-import { existsSync as existsSync33 } from "fs";+import { existsSync as existsSync35 } from "fs";import { fileURLToPath as fileURLToPath2 } from "url";var SKILLS_PROBE_SPECIFIERS = ["./skills/", "../skills/", "../../skills/"];function sharedSkillsRootPath() {const candidates = SKILLS_PROBE_SPECIFIERS.map((specifier) => fileURLToPath2(new URL(specifier, import.meta.url)));- return candidates.find((candidate) => existsSync33(candidate)) ?? candidates[0];+ return candidates.find((candidate) => existsSync35(candidate)) ?? candidates[0];}// packages/omo-opencode/src/cli/install-ast-grep-sg.ts@@ -98430,9 +99184,9 @@ function describeResult2(result) {}async function installAstGrepForOpenCode(options = {}) {const platform = options.platform ?? process.platform;- const baseDir = join65(options.homeDir ?? homedir12(), ".omo");+ const baseDir = join68(options.homeDir ?? homedir13(), ".omo");const targetDir = astGrepRuntimeDir(baseDir, platform, options.arch ?? process.arch);- const skillDir = join65(options.sharedSkillsRoot ?? sharedSkillsRootPath(), "ast-grep");+ const skillDir = join68(options.sharedSkillsRoot ?? sharedSkillsRootPath(), "ast-grep");const installer = options.installer ?? runAstGrepSkillInstall;try {const result = await installer({ platform, skillDir, targetDir });@@ -98517,6 +99271,21 @@ async function runCliInstaller(args, version) {const message = error instanceof Error ? error.message : String(error);printWarning(`Could not update OpenCode TUI config: ${message}`);}+ try {+ const { removed, deferred, failed } = refreshOpenCodePluginSandboxes();+ if (removed.length > 0) {+ printInfo("Refreshed the OpenCode plugin cache; the next OpenCode start loads the installed version.");+ }+ if (deferred.length > 0) {+ printInfo("OpenCode is running from its plugin cache; it refreshes when the last OpenCode window closes. Restart OpenCode to load the installed version.");+ }+ for (const { dir, message } of failed) {+ printWarning(`Could not refresh the OpenCode plugin cache at ${dir} (${message}). Close OpenCode and delete that directory, or OpenCode keeps loading the previous version.`);+ }+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ printWarning(`Could not refresh the OpenCode plugin cache: ${message}`);+ }printStep(step++, totalSteps, `Writing ${PLUGIN_NAME} configuration...`);const omoResult = writeOmoConfig(config);if (!omoResult.success) {@@ -98557,14 +99326,16 @@ async function runCliInstaller(args, version) {if (config.hasNative) {printInfo("Installing OmO Native...");const outcome = await runNativeInstall();+ for (const note of outcome.notes)+ printInfo(note);+ for (const warning of outcome.warnings)+ printWarning(warning);if (outcome.failure) {for (const line of nativeInstallFailureLines(outcome.failure))printError(line);return 1;}- for (const note of outcome.notes)- printInfo(note);- printSuccess(nativeInstallSuccessLine());+ printSuccess(nativeInstallSuccessLine(outcome.verified));console.log();}if (config.hasNativeDev) {@@ -100034,6 +100805,21 @@ async function runTuiInstaller(args, version) {const message = error instanceof Error ? error.message : String(error);log4.warn(`Could not update OpenCode TUI config: ${message}`);}+ try {+ const { removed, deferred, failed } = refreshOpenCodePluginSandboxes();+ if (removed.length > 0) {+ log4.info("Refreshed the OpenCode plugin cache; the next OpenCode start loads the installed version.");+ }+ if (deferred.length > 0) {+ log4.info("OpenCode is running from its plugin cache; it refreshes when the last OpenCode window closes. Restart OpenCode to load the installed version.");+ }+ for (const { dir, message } of failed) {+ log4.warn(`Could not refresh the OpenCode plugin cache at ${dir} (${message}). Close OpenCode and delete that directory, or OpenCode keeps loading the previous version.`);+ }+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log4.warn(`Could not refresh the OpenCode plugin cache: ${message}`);+ }spinner2.start(`Writing ${PLUGIN_NAME} configuration`);const omoResult = writeOmoConfig(config);if (!omoResult.success) {@@ -100078,14 +100864,30 @@ async function runTuiInstaller(args, version) {const outcome = await runNativeInstall();if (outcome.failure) {spinner2.stop(`OmO Native install failed ${import_picocolors4.default.yellow("[!]")}`);+ for (const note of outcome.notes)+ log4.info(note);+ for (const warning of outcome.warnings)+ log4.warn(warning);for (const line of nativeInstallFailureLines(outcome.failure))log4.error(line);outro(import_picocolors4.default.red("Installation failed."));return 1;}- spinner2.stop(nativeInstallSuccessLine());+ spinner2.stop(nativeInstallSuccessLine(outcome.verified));for (const note of outcome.notes)log4.info(note);+ for (const warning of outcome.warnings)+ log4.warn(warning);+ const setup = await offerNativeSetup(outcome, {+ confirm: async (message) => {+ const answer = await confirm({ message, initialValue: true });+ return !isCancel(answer) && answer;+ },+ onStart: (line) => log4.step(line)+ });+ const followUp = nativeSetupFollowUpLine(setup);+ if (followUp !== null)+ log4.warn(followUp);}if (config.hasNativeDev) {spinner2.start("Installing the OmO Native development adapter");@@ -102068,7 +102870,7 @@ var import_picocolors11 = __toESM(require_picocolors(), 1);// packages/omo-opencode/src/cli/run/opencode-binary-resolver.tsinit_bun_which_shim();init_spawn_with_windows_hide();-import { delimiter as delimiter2, dirname as dirname25, posix as posix9, win32 as win325 } from "path";+import { delimiter as delimiter2, dirname as dirname27, posix as posix10, win32 as win326 } from "path";var OPENCODE_COMMANDS = ["opencode", "opencode-desktop"];var WINDOWS_SUFFIXES = ["", ".exe", ".cmd", ".bat", ".ps1"];function getCommandCandidates(platform) {@@ -102078,8 +102880,8 @@ function getCommandCandidates(platform) {}function getPathTools(platform) {if (platform === "win32")- return win325;- return posix9;+ return win326;+ return posix10;}function collectCandidateBinaryPaths(pathEnv, which = bunWhich, platform = process.platform) {const seen = new Set;@@ -102126,7 +102928,7 @@ async function findWorkingOpencodeBinary(pathEnv = process.env.PATH, probe = canreturn null;}function buildPathWithBinaryFirst(pathEnv, binaryPath) {- const preferredDir = dirname25(binaryPath);+ const preferredDir = dirname27(binaryPath);const existing = (pathEnv ?? "").split(delimiter2).filter((entry) => entry.length > 0 && entry !== preferredDir);return [preferredDir, ...existing].join(delimiter2);}@@ -102706,26 +103508,26 @@ function isClosingFence(line, fence) {return run?.charAt(0) === fence.marker && run.length >= fence.length;}// packages/boulder-state/src/top-level-task.ts-import { existsSync as existsSync34, readFileSync as readFileSync16 } from "fs";+import { existsSync as existsSync36, readFileSync as readFileSync19 } from "fs";function readCurrentTopLevelTask(planPath) {- if (!existsSync34(planPath)) {+ if (!existsSync36(planPath)) {return null;}try {- const content = readFileSync16(planPath, "utf-8");+ const content = readFileSync19(planPath, "utf-8");return parseCurrentTopLevelTask(content);} catch {return null;}}// packages/boulder-state/src/storage/path.ts-import { existsSync as existsSync35 } from "fs";-import { isAbsolute as isAbsolute12, join as join66, relative as relative8, resolve as resolve20 } from "path";+import { existsSync as existsSync37 } from "fs";+import { isAbsolute as isAbsolute13, join as join69, relative as relative8, resolve as resolve21 } from "path";function getBoulderFilePath(directory) {- return join66(directory, BOULDER_DIR, BOULDER_FILE);+ return join69(directory, BOULDER_DIR, BOULDER_FILE);}function resolveTrackedPath(baseDirectory, trackedPath) {- return isAbsolute12(trackedPath) ? resolve20(trackedPath) : resolve20(baseDirectory, trackedPath);+ return isAbsolute13(trackedPath) ? resolve21(trackedPath) : resolve21(baseDirectory, trackedPath);}function resolveBoulderPlanPath(directory, state) {const absolutePlanPath = resolveTrackedPath(directory, state.active_plan);@@ -102733,26 +103535,26 @@ function resolveBoulderPlanPath(directory, state) {if (!worktreePath) {return absolutePlanPath;}- const absoluteDirectory = resolve20(directory);+ const absoluteDirectory = resolve21(directory);const relativePlanPath = relative8(absoluteDirectory, absolutePlanPath);- if (relativePlanPath.length === 0 || relativePlanPath.startsWith("..") || isAbsolute12(relativePlanPath)) {+ if (relativePlanPath.length === 0 || relativePlanPath.startsWith("..") || isAbsolute13(relativePlanPath)) {return absolutePlanPath;}const absoluteWorktreePath = resolveTrackedPath(directory, worktreePath);- const worktreePlanPath = resolve20(absoluteWorktreePath, relativePlanPath);- return existsSync35(worktreePlanPath) ? worktreePlanPath : absolutePlanPath;+ const worktreePlanPath = resolve21(absoluteWorktreePath, relativePlanPath);+ return existsSync37(worktreePlanPath) ? worktreePlanPath : absolutePlanPath;}function resolveBoulderPlanPathForWork(directory, work) {return resolveBoulderPlanPath(directory, work);}// packages/boulder-state/src/storage/plan-progress.ts-import { existsSync as existsSync36, readFileSync as readFileSync17, readdirSync as readdirSync8, statSync as statSync4 } from "fs";+import { existsSync as existsSync38, readFileSync as readFileSync20, readdirSync as readdirSync9, statSync as statSync4 } from "fs";function getPlanProgress(planPath) {- if (!existsSync36(planPath)) {+ if (!existsSync38(planPath)) {return { total: 0, completed: 0, isComplete: false };}try {- const content = readFileSync17(planPath, "utf-8");+ const content = readFileSync20(planPath, "utf-8");const checklist = parsePlanChecklist(content);return {total: checklist.total,@@ -102831,14 +103633,14 @@ function selectMirrorWork(state) {return sorted[0] ?? null;}// packages/boulder-state/src/storage/read-state.ts-import { existsSync as existsSync37, readFileSync as readFileSync18 } from "fs";+import { existsSync as existsSync39, readFileSync as readFileSync21 } from "fs";function readBoulderState(directory) {const filePath = getBoulderFilePath(directory);- if (!existsSync37(filePath)) {+ if (!existsSync39(filePath)) {return null;}try {- const content = readFileSync18(filePath, "utf-8");+ const content = readFileSync21(filePath, "utf-8");const parsed = JSON.parse(content);if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || Object.keys(parsed).length === 0) {return null;@@ -102906,17 +103708,17 @@ init_state();// packages/omo-opencode/src/features/run-continuation-state/constants.tsvar CONTINUATION_MARKER_DIR = ".omo/run-continuation";// packages/omo-opencode/src/features/run-continuation-state/storage.ts-import { existsSync as existsSync38, mkdirSync as mkdirSync13, readFileSync as readFileSync19, rmSync as rmSync4, writeFileSync as writeFileSync7 } from "fs";-import { join as join67 } from "path";+import { existsSync as existsSync40, mkdirSync as mkdirSync14, readFileSync as readFileSync22, rmSync as rmSync6, writeFileSync as writeFileSync8 } from "fs";+import { join as join70 } from "path";function getMarkerPath(directory, sessionID) {- return join67(directory, CONTINUATION_MARKER_DIR, `${sessionID}.json`);+ return join70(directory, CONTINUATION_MARKER_DIR, `${sessionID}.json`);}function readContinuationMarker(directory, sessionID) {const markerPath = getMarkerPath(directory, sessionID);- if (!existsSync38(markerPath))+ if (!existsSync40(markerPath))return null;try {- const raw = readFileSync19(markerPath, "utf-8");+ const raw = readFileSync22(markerPath, "utf-8");const parsed = JSON.parse(raw);if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))return null;@@ -102981,8 +103783,8 @@ async function isSessionInBoulderLineage(input) {// packages/omo-opencode/src/hooks/atlas/session-last-agent.tsinit_shared();init_compaction_marker();-import { readFileSync as readFileSync20, readdirSync as readdirSync9 } from "fs";-import { join as join68 } from "path";+import { readFileSync as readFileSync23, readdirSync as readdirSync10 } from "fs";+import { join as join71 } from "path";var defaultSessionLastAgentDeps = {getMessageDir,isSqliteBackend,@@ -103040,9 +103842,9 @@ async function getLastAgentFromSession(sessionID, client, deps = {}) {if (!messageDir)return null;try {- const messages = readdirSync9(messageDir).filter((fileName) => fileName.endsWith(".json")).map((fileName) => {+ const messages = readdirSync10(messageDir).filter((fileName) => fileName.endsWith(".json")).map((fileName) => {try {- const content = readFileSync20(join68(messageDir, fileName), "utf-8");+ const content = readFileSync23(join71(messageDir, fileName), "utf-8");const parsed = JSON.parse(content);return {fileName,@@ -103085,8 +103887,8 @@ init_agent_display_names();// packages/omo-opencode/src/hooks/ralph-loop/storage.tsinit_frontmatter2();-import { existsSync as existsSync39, readFileSync as readFileSync21, writeFileSync as writeFileSync8, unlinkSync as unlinkSync6, mkdirSync as mkdirSync14 } from "fs";-import { dirname as dirname26, join as join69 } from "path";+import { existsSync as existsSync41, readFileSync as readFileSync24, writeFileSync as writeFileSync9, unlinkSync as unlinkSync6, mkdirSync as mkdirSync15 } from "fs";+import { dirname as dirname28, join as join72 } from "path";// packages/omo-opencode/src/hooks/ralph-loop/constants.tsvar DEFAULT_STATE_FILE = ".omo/ralph-loop.local.md";@@ -103095,15 +103897,15 @@ var DEFAULT_COMPLETION_PROMISE = "DONE";// packages/omo-opencode/src/hooks/ralph-loop/storage.tsfunction getStateFilePath(directory, customPath) {- return customPath ? join69(directory, customPath) : join69(directory, DEFAULT_STATE_FILE);+ return customPath ? join72(directory, customPath) : join72(directory, DEFAULT_STATE_FILE);}function readState(directory, customPath) {const filePath = getStateFilePath(directory, customPath);- if (!existsSync39(filePath)) {+ if (!existsSync41(filePath)) {return null;}try {- const content = readFileSync21(filePath, "utf-8");+ const content = readFileSync24(filePath, "utf-8");const { data, body } = parseFrontmatter(content);const active = data.active;const iteration = data.iteration;@@ -104195,14 +104997,14 @@ async function getLocalVersion(options = {}) {}}// packages/omo-opencode/src/cli/doctor/checks/system.ts-import { existsSync as existsSync50, readFileSync as readFileSync31 } from "fs";+import { existsSync as existsSync52, readFileSync as readFileSync34 } from "fs";// packages/omo-opencode/src/cli/doctor/checks/system-binary.tsinit_extract_semver();init_bun_which_shim();-import { existsSync as existsSync47, accessSync as accessSync4, constants as constants12 } from "fs";-import { homedir as homedir15 } from "os";-import { join as join76 } from "path";+import { existsSync as existsSync49, accessSync as accessSync4, constants as constants12 } from "fs";+import { homedir as homedir16 } from "os";+import { join as join79 } from "path";// packages/omo-opencode/src/cli/doctor/framework/spawn-with-timeout.tsinit_spawn_with_windows_hide();@@ -104289,22 +105091,22 @@ function isExecutable2(path) {}}function getDesktopAppPaths(platform) {- const home = homedir15();+ const home = homedir16();switch (platform) {case "darwin":return ["/Applications/OpenCode.app/Contents/MacOS/OpenCode",- join76(home, "Applications", "OpenCode.app", "Contents", "MacOS", "OpenCode")+ join79(home, "Applications", "OpenCode.app", "Contents", "MacOS", "OpenCode")];case "win32": {const programFiles = process.env.ProgramFiles;const localAppData = process.env.LOCALAPPDATA;const paths = [];if (programFiles) {- paths.push(join76(programFiles, "OpenCode", "OpenCode.exe"));+ paths.push(join79(programFiles, "OpenCode", "OpenCode.exe"));}if (localAppData) {- paths.push(join76(localAppData, "OpenCode", "OpenCode.exe"));+ paths.push(join79(localAppData, "OpenCode", "OpenCode.exe"));}return paths;}@@ -104312,8 +105114,8 @@ function getDesktopAppPaths(platform) {return ["/usr/bin/opencode","/usr/lib/opencode/opencode",- join76(home, "Applications", "opencode-desktop-linux-x86_64.AppImage"),- join76(home, "Applications", "opencode-desktop-linux-aarch64.AppImage")+ join79(home, "Applications", "opencode-desktop-linux-x86_64.AppImage"),+ join79(home, "Applications", "opencode-desktop-linux-aarch64.AppImage")];default:return [];@@ -104325,7 +105127,7 @@ function buildVersionCommand(binaryPath, platform) {}return [binaryPath, "--version"];}-function findDesktopBinary(platform = process.platform, checkExists = existsSync47) {+function findDesktopBinary(platform = process.platform, checkExists = existsSync49) {for (const desktopPath of getDesktopAppPaths(platform)) {if (checkExists(desktopPath)) {return { binary: "opencode", path: desktopPath };@@ -104333,7 +105135,7 @@ function findDesktopBinary(platform = process.platform, checkExists = existsSync}return null;}-async function findOpenCodeBinary(platform = process.platform, checkExists = existsSync47) {+async function findOpenCodeBinary(platform = process.platform, checkExists = existsSync49) {for (const binary of OPENCODE_BINARIES2) {const path = bunWhich(binary);if (path && checkExists(path)) {@@ -104345,7 +105147,7 @@ async function findOpenCodeBinary(platform = process.platform, checkExists = exiconst candidates = getCommandCandidates2(platform);for (const entry of pathEnv.split(delimiter).filter(Boolean)) {for (const command of candidates) {- const fullPath = join76(entry, command);+ const fullPath = join79(entry, command);if (checkExists(fullPath) && isExecutable2(fullPath)) {return { binary: command, path: fullPath };}@@ -104391,12 +105193,12 @@ function compareVersions3(current, minimum) {// packages/omo-opencode/src/cli/doctor/checks/system-plugin.tsinit_shared();-import { existsSync as existsSync48, readFileSync as readFileSync29 } from "fs";+import { existsSync as existsSync50, readFileSync as readFileSync32 } from "fs";function detectConfigPath() {const paths = getOpenCodeConfigPaths({ binary: "opencode", version: null });- if (existsSync48(paths.configJsonc))+ if (existsSync50(paths.configJsonc))return paths.configJsonc;- if (existsSync48(paths.configJson))+ if (existsSync50(paths.configJson))return paths.configJson;return null;}@@ -104444,7 +105246,7 @@ function getPluginInfo() {};}try {- const content = readFileSync29(configPath, "utf-8");+ const content = readFileSync32(configPath, "utf-8");const parsedConfig = parseJsonc(content);const pluginEntry = findPluginEntry2(parsedConfig.plugin ?? []);if (!pluginEntry) {@@ -104486,39 +105288,39 @@ init_file_utils2();init_checker();init_auto_update_checker();init_package_json_locator();-import { existsSync as existsSync49, readFileSync as readFileSync30, readdirSync as readdirSync11 } from "fs";+import { existsSync as existsSync51, readFileSync as readFileSync33, readdirSync as readdirSync12 } from "fs";import { createRequire } from "module";-import { homedir as homedir16 } from "os";-import { join as join77 } from "path";+import { homedir as homedir17 } from "os";+import { join as join80 } from "path";import { fileURLToPath as fileURLToPath6 } from "url";init_shared();function getPlatformDefaultCacheDir(platform = process.platform) {if (platform === "darwin")- return join77(homedir16(), "Library", "Caches");+ return join80(homedir17(), "Library", "Caches");if (platform === "win32")- return process.env.LOCALAPPDATA ?? join77(homedir16(), "AppData", "Local");- return join77(homedir16(), ".cache");+ return process.env.LOCALAPPDATA ?? join80(homedir17(), "AppData", "Local");+ return join80(homedir17(), ".cache");}function resolveOpenCodeCacheDir() {const xdgCacheHome = process.env.XDG_CACHE_HOME;if (xdgCacheHome)- return join77(xdgCacheHome, "opencode");+ return join80(xdgCacheHome, "opencode");const fromShared = getOpenCodeCacheDir();- const platformDefault = join77(getPlatformDefaultCacheDir(), "opencode");- if (existsSync49(fromShared) || !existsSync49(platformDefault))+ const platformDefault = join80(getPlatformDefaultCacheDir(), "opencode");+ if (existsSync51(fromShared) || !existsSync51(platformDefault))return fromShared;return platformDefault;}function resolveExistingDir(dirPath) {- if (!existsSync49(dirPath))+ if (!existsSync51(dirPath))return dirPath;return resolveSymlink(dirPath);}function readPackageJson(filePath) {- if (!existsSync49(filePath))+ if (!existsSync51(filePath))return null;try {- const content = readFileSync30(filePath, "utf-8");+ const content = readFileSync33(filePath, "utf-8");return parseJsonc(content);} catch (error) {if (!(error instanceof Error)) {@@ -104536,26 +105338,26 @@ function normalizeVersion(value) {function createPackageCandidates(rootDir) {return ACCEPTED_PACKAGE_NAMES.map((packageName) => ({packageName,- installedPackagePath: join77(rootDir, "node_modules", packageName, "package.json")+ installedPackagePath: join80(rootDir, "node_modules", packageName, "package.json")}));}function createTaggedInstallCandidates(rootDir) {- const packagesDir = join77(rootDir, "packages");- if (!existsSync49(packagesDir))+ const packagesDir = join80(rootDir, "packages");+ if (!existsSync51(packagesDir))return [];const candidates = [];- for (const entryName of readdirSync11(packagesDir).sort()) {+ for (const entryName of readdirSync12(packagesDir).sort()) {const packageName = ACCEPTED_PACKAGE_NAMES.find((name) => entryName.startsWith(`${name}@`));if (packageName === undefined)continue;- const installDir = join77(packagesDir, entryName);+ const installDir = join80(packagesDir, entryName);candidates.push({cacheDir: installDir,- cachePackagePath: join77(installDir, "package.json"),+ cachePackagePath: join80(installDir, "package.json"),packageCandidates: [{packageName,- installedPackagePath: join77(installDir, "node_modules", packageName, "package.json")+ installedPackagePath: join80(installDir, "node_modules", packageName, "package.json")}]});@@ -104563,7 +105365,7 @@ function createTaggedInstallCandidates(rootDir) {return candidates;}function selectInstalledPackage(candidate) {- return candidate.packageCandidates.find((packageCandidate) => existsSync49(packageCandidate.installedPackagePath)) ?? candidate.packageCandidates[0];+ return candidate.packageCandidates.find((packageCandidate) => existsSync51(packageCandidate.installedPackagePath)) ?? candidate.packageCandidates[0];}function getExpectedVersion(cachePackage, packageName) {return normalizeVersion(cachePackage?.dependencies?.[packageName]) ?? normalizeVersion(cachePackage?.dependencies?.[PACKAGE_NAME]);@@ -104574,7 +105376,7 @@ function resolveInstalledPackageJsonPath() {for (const packageName of ACCEPTED_PACKAGE_NAMES) {try {const packageJsonPath = require2.resolve(`${packageName}/package.json`);- if (existsSync49(packageJsonPath)) {+ if (existsSync51(packageJsonPath)) {return { packageName, packageJsonPath };}} catch {@@ -104600,22 +105402,22 @@ function getLoadedPluginVersion() {const candidates = [{cacheDir: configDir,- cachePackagePath: join77(configDir, "package.json"),+ cachePackagePath: join80(configDir, "package.json"),packageCandidates: createPackageCandidates(configDir)},...createTaggedInstallCandidates(configDir),{cacheDir,- cachePackagePath: join77(cacheDir, "package.json"),+ cachePackagePath: join80(cacheDir, "package.json"),packageCandidates: createPackageCandidates(cacheDir)},...createTaggedInstallCandidates(cacheDir)];- const selectedCandidate = candidates.find((candidate) => candidate.packageCandidates.some((packageCandidate) => existsSync49(packageCandidate.installedPackagePath))) ?? candidates[0];+ const selectedCandidate = candidates.find((candidate) => candidate.packageCandidates.some((packageCandidate) => existsSync51(packageCandidate.installedPackagePath))) ?? candidates[0];const { cacheDir: selectedDir, cachePackagePath } = selectedCandidate;const selectedPackage = selectInstalledPackage(selectedCandidate);const candidateInstalledPath = selectedPackage.installedPackagePath;- const candidateExists = existsSync49(candidateInstalledPath);+ const candidateExists = existsSync51(candidateInstalledPath);const resolvedFallback = candidateExists ? null : resolveInstalledPackageJsonPath();const installedPackagePath = resolvedFallback?.packageJsonPath ?? candidateInstalledPath;const resolvedPackageName = resolvedFallback?.packageName ?? selectedPackage.packageName;@@ -104651,8 +105453,8 @@ var defaultDeps5 = {getLoadedPluginVersion,getLatestPluginVersion,getSuggestedInstallTag,- configExists: existsSync50,- readConfigFile: (path) => readFileSync31(path, "utf-8"),+ configExists: existsSync52,+ readConfigFile: (path) => readFileSync34(path, "utf-8"),parseConfigContent: (content) => parseJsonc(content)};function isConfigValid(configPath, deps) {@@ -104797,26 +105599,26 @@ async function checkSystem(deps = defaultDeps5) {// packages/omo-opencode/src/cli/doctor/checks/model-resolution-cache.tsinit_shared();-import { existsSync as existsSync51, readFileSync as readFileSync32 } from "fs";-import { homedir as homedir17 } from "os";-import { join as join78 } from "path";+import { existsSync as existsSync53, readFileSync as readFileSync35 } from "fs";+import { homedir as homedir18 } from "os";+import { join as join81 } from "path";function getUserConfigDir2() {const xdgConfig = process.env.XDG_CONFIG_HOME;if (xdgConfig)- return join78(xdgConfig, "opencode");- return join78(homedir17(), ".config", "opencode");+ return join81(xdgConfig, "opencode");+ return join81(homedir18(), ".config", "opencode");}function loadCustomProviderNames() {const configDir = getUserConfigDir2();const candidatePaths = [- join78(configDir, "opencode.json"),- join78(configDir, "opencode.jsonc")+ join81(configDir, "opencode.json"),+ join81(configDir, "opencode.jsonc")];for (const configPath of candidatePaths) {- if (!existsSync51(configPath))+ if (!existsSync53(configPath))continue;try {- const content = readFileSync32(configPath, "utf-8");+ const content = readFileSync35(configPath, "utf-8");const data = parseJsonc(content);if (data?.provider && typeof data.provider === "object") {return Object.keys(data.provider);@@ -104831,16 +105633,16 @@ function loadCustomProviderNames() {return [];}function loadAvailableModelsFromCache() {- const cacheFile = join78(getOpenCodeCacheDir(), "models.json");+ const cacheFile = join81(getOpenCodeCacheDir(), "models.json");const customProviders = loadCustomProviderNames();- if (!existsSync51(cacheFile)) {+ if (!existsSync53(cacheFile)) {if (customProviders.length > 0) {return { providers: customProviders, modelCount: 0, cacheExists: true };}return { providers: [], modelCount: 0, cacheExists: false };}try {- const content = readFileSync32(cacheFile, "utf-8");+ const content = readFileSync35(cacheFile, "utf-8");const data = parseJsonc(content);const cacheProviders = Object.keys(data);let modelCount = 0;@@ -104893,7 +105695,7 @@ function loadOmoConfig2() {// packages/omo-opencode/src/cli/doctor/checks/model-resolution-details.tsinit_shared();-import { join as join79 } from "path";+import { join as join82 } from "path";// packages/omo-opencode/src/cli/doctor/checks/model-resolution-variant.tsfunction formatModelWithVariant(model, variant) {@@ -104935,7 +105737,7 @@ function formatCapabilityResolutionLabel(mode) {}function buildModelResolutionDetails(options) {const details = [];- const cacheFile = join79(getOpenCodeCacheDir(), "models.json");+ const cacheFile = join82(getOpenCodeCacheDir(), "models.json");details.push("\u2550\u2550\u2550 Available Models (from cache) \u2550\u2550\u2550");details.push("");if (options.available.cacheExists) {@@ -105091,9 +105893,9 @@ async function checkModels() {// packages/omo-opencode/src/cli/doctor/checks/legacy-config-leftovers.tsinit_config_migration();-import { posix as posix10, win32 as win326 } from "path";+import { posix as posix11, win32 as win327 } from "path";function findLegacyConfigLeftovers(options) {- const pathOperations = options.pathOperations ?? (process.platform === "win32" ? win326 : posix10);+ const pathOperations = options.pathOperations ?? (process.platform === "win32" ? win327 : posix11);const paths = createLegacyConfigMigrationPlans({cwd: options.cwd,environment: options.environment ?? process.env,@@ -105275,8 +106077,8 @@ async function checkBrowserProvider() {init_src4();init_main();init_config_migration();-import { existsSync as existsSync52, readFileSync as readFileSync33 } from "fs";-import { join as join80 } from "path";+import { existsSync as existsSync54, readFileSync as readFileSync36 } from "fs";+import { join as join83 } from "path";var CANONICAL_REPLACEMENT = new Map([["variant", "reasoning"],["reasoningEffort", "reasoning"],@@ -105337,16 +106139,16 @@ function userConfigPaths() {const home = process.env.HOME ?? process.env.USERPROFILE;if (home === undefined || home.length === 0)return [];- return [join80(home, ".omo", "omo.jsonc"), join80(home, ".omo", "omo.json")];+ return [join83(home, ".omo", "omo.jsonc"), join83(home, ".omo", "omo.json")];}async function checkDeprecatedReasoningKeys() {const issues = [];const scanned = [];for (const configPath of userConfigPaths()) {- if (!existsSync52(configPath))+ if (!existsSync54(configPath))continue;scanned.push(configPath);- const parsed = parse2(readFileSync33(configPath, "utf-8"));+ const parsed = parse2(readFileSync36(configPath, "utf-8"));issues.push(...collectIssues(configPath, parsed, "", migrateFixSuffix(parsed)));}return {@@ -105360,39 +106162,39 @@ async function checkDeprecatedReasoningKeys() {// packages/omo-opencode/src/cli/doctor/checks/dependencies.tsinit_src();-import { existsSync as existsSync53 } from "fs";+import { existsSync as existsSync55 } from "fs";import { createRequire as createRequire2 } from "module";-import { homedir as homedir19 } from "os";-import { dirname as dirname31, join as join83 } from "path";+import { homedir as homedir20 } from "os";+import { dirname as dirname33, join as join86 } from "path";// packages/omo-opencode/src/hooks/comment-checker/downloader.ts-import { join as join82 } from "path";-import { homedir as homedir18, tmpdir as tmpdir4 } from "os";+import { join as join85 } from "path";+import { homedir as homedir19, tmpdir as tmpdir4 } from "os";// packages/comment-checker-core/src/release.ts-import { join as join81 } from "path";+import { join as join84 } from "path";function commentCheckerBinaryName(platform) {return platform === "win32" ? "comment-checker.exe" : "comment-checker";}function commentCheckerCacheDir(input) {if (input.platform === "win32") {const localAppData = input.env.LOCALAPPDATA || input.env.APPDATA;- const base = localAppData || join81(input.homedir, "AppData", "Local");- return join81(base, input.cacheDirName, "bin");+ const base = localAppData || join84(input.homedir, "AppData", "Local");+ return join84(base, input.cacheDirName, "bin");}- const base = input.env.XDG_CACHE_HOME || join81(input.homedir, ".cache");- return join81(base, input.cacheDirName, "bin");+ const base = input.env.XDG_CACHE_HOME || join84(input.homedir, ".cache");+ return join84(base, input.cacheDirName, "bin");}// packages/omo-opencode/src/hooks/comment-checker/downloader.tsinit_binary_downloader();init_logger2();init_plugin_identity();var DEBUG = process.env.COMMENT_CHECKER_DEBUG === "1";-var DEBUG_FILE = join82(tmpdir4(), "comment-checker-debug.log");+var DEBUG_FILE = join85(tmpdir4(), "comment-checker-debug.log");function getCacheDir2() {return commentCheckerCacheDir({platform: process.platform,env: process.env,- homedir: homedir18(),+ homedir: homedir19(),cacheDirName: CACHE_DIR_NAME});}@@ -105444,7 +106246,7 @@ async function getBinaryVersion(binary) {}}async function checkAstGrepCli() {- const runtimeDir = astGrepRuntimeDir(join83(homedir19(), ".omo"));+ const runtimeDir = astGrepRuntimeDir(join86(homedir20(), ".omo"));const sgPath = findSgBinarySync({ runtimeDir });if (sgPath === null) {return {@@ -105473,12 +106275,12 @@ function findCommentCheckerPackageBinary(baseDirOverride, resolvePackageJsonPathconst binaryName = process.platform === "win32" ? "comment-checker.exe" : "comment-checker";const platformKey = `${process.platform}-${process.arch === "x64" ? "x64" : process.arch}`;try {- const packageDir = baseDirOverride ?? dirname31(resolvePackageJsonPath());- const vendorPath = join83(packageDir, "vendor", platformKey, binaryName);- if (existsSync53(vendorPath))+ const packageDir = baseDirOverride ?? dirname33(resolvePackageJsonPath());+ const vendorPath = join86(packageDir, "vendor", platformKey, binaryName);+ if (existsSync55(vendorPath))return vendorPath;- const binPath = join83(packageDir, "bin", binaryName);- if (existsSync53(binPath))+ const binPath = join86(packageDir, "bin", binaryName);+ if (existsSync55(binPath))return binPath;} catch (error) {if (!(error instanceof Error) && !isModuleResolutionFailure(error))@@ -105624,8 +106426,8 @@ async function getGhCliInfo(dependencies = {}) {// packages/omo-opencode/src/mcp/lsp.tsinit_zod();init_opencode_config_dir();-import { existsSync as existsSync54, readFileSync as readFileSync34 } from "fs";-import { delimiter as delimiter3, dirname as dirname32, resolve as resolve22 } from "path";+import { existsSync as existsSync56, readFileSync as readFileSync37 } from "fs";+import { delimiter as delimiter3, dirname as dirname34, resolve as resolve23 } from "path";import { fileURLToPath as fileURLToPath7 } from "url";// packages/omo-opencode/src/mcp/cli-suffix.ts@@ -105638,7 +106440,7 @@ function hasCliSuffix(candidatePath, suffix) {// packages/omo-opencode/src/mcp/runtime-executable.tsinit_bun_which_shim();-import { basename as basename10 } from "path";+import { basename as basename11 } from "path";var NODE_EXECUTABLE_NAMES = new Set(["node", "node.exe"]);function isUnsafeCommandName2(commandName) {if (commandName.length === 0)@@ -105654,7 +106456,7 @@ function isUnsafeCommandName2(commandName) {return false;}function isNodeExecPath(execPath) {- return NODE_EXECUTABLE_NAMES.has(basename10(execPath).toLowerCase());+ return NODE_EXECUTABLE_NAMES.has(basename11(execPath).toLowerCase());}function resolveRuntimeExecutable(commandName, options = {}) {if (isUnsafeCommandName2(commandName)) {@@ -105672,7 +106474,7 @@ function resolveRuntimeExecutable(commandName, options = {}) {}// packages/omo-opencode/src/mcp/shared/ancestor-cli-resolver.ts-import { resolve as resolve21 } from "path";+import { resolve as resolve22 } from "path";function resolveJavaScriptRuntime(resolveExecutable) {const node = resolveExecutable("node");return node.available ? node : resolveExecutable("bun");@@ -105680,9 +106482,9 @@ function resolveJavaScriptRuntime(resolveExecutable) {function createAncestorCliCandidates(options) {const candidates = [];const seenPaths = new Set;- let currentDirectory = resolve21(options.startDirectory);+ let currentDirectory = resolve22(options.startDirectory);while (true) {- const distCliPath = resolve21(currentDirectory, options.packageRel, options.distCliRel);+ const distCliPath = resolve22(currentDirectory, options.packageRel, options.distCliRel);if (!seenPaths.has(distCliPath)) {const runtime = resolveJavaScriptRuntime(options.resolveExecutable);seenPaths.add(distCliPath);@@ -105694,7 +106496,7 @@ function createAncestorCliCandidates(options) {runtimeAvailable: runtime.available});}- const sourceCliPath = resolve21(currentDirectory, options.packageRel, options.sourceCliRel);+ const sourceCliPath = resolve22(currentDirectory, options.packageRel, options.sourceCliRel);if (!seenPaths.has(sourceCliPath)) {const runtime = options.resolveExecutable("bun");const sourceCandidateAvailable = options.isSourceCandidateAvailable?.({@@ -105711,7 +106513,7 @@ function createAncestorCliCandidates(options) {runtimeAvailable: runtime.available});}- const parentDirectory = resolve21(currentDirectory, "..");+ const parentDirectory = resolve22(currentDirectory, "..");if (parentDirectory === currentDirectory)return candidates;currentDirectory = parentDirectory;@@ -105756,7 +106558,7 @@ var LSP_BOOTSTRAP_SCRIPT = [].join(";");function getModuleDirectory(moduleUrl) {try {- return dirname32(fileURLToPath7(moduleUrl));+ return dirname34(fileURLToPath7(moduleUrl));} catch (error) {if (!(error instanceof Error))throw error;@@ -105764,11 +106566,11 @@ function getModuleDirectory(moduleUrl) {}}function findBootstrapRoot(candidates, pathExists) {- return candidates.find((candidate) => pathExists(resolve22(candidate.root, "package.json")))?.root ?? process.cwd();+ return candidates.find((candidate) => pathExists(resolve23(candidate.root, "package.json")))?.root ?? process.cwd();}function readDaemonPackageVersion(root) {try {- const packageJson = JSON.parse(readFileSync34(resolve22(root, PACKAGE_REL, "package.json"), "utf-8"));+ const packageJson = JSON.parse(readFileSync37(resolve23(root, PACKAGE_REL, "package.json"), "utf-8"));return DaemonPackageSchema.parse(packageJson).version;} catch (error) {if (!(error instanceof Error))@@ -105780,17 +106582,17 @@ function createBootstrapCandidate(root, pathExists, resolveExecutable) {const runtime = resolveJavaScriptRuntime(resolveExecutable);const bun = resolveExecutable("bun");const npm = resolveExecutable("npm");- const packageManifestPath = resolve22(root, PACKAGE_REL, "package.json");+ const packageManifestPath = resolve23(root, PACKAGE_REL, "package.json");return {command: [runtime.command, "-e", LSP_BOOTSTRAP_SCRIPT, root, npm.command, bun.command],root,- path: resolve22(root, PACKAGE_REL, DIST_CLI_REL),+ path: resolve23(root, PACKAGE_REL, DIST_CLI_REL),exists: runtime.available && npm.available && pathExists(packageManifestPath),runtimeAvailable: runtime.available};}function resolveLspCommand(options = {}) {- const pathExists = options.exists ?? existsSync54;+ const pathExists = options.exists ?? existsSync56;const resolveExecutable = options.resolveExecutable ?? resolveRuntimeExecutable;const moduleDirectory = getModuleDirectory(options.moduleUrl ?? import.meta.url);const candidates = moduleDirectory ? createAncestorCliCandidates({@@ -105800,7 +106602,7 @@ function resolveLspCommand(options = {}) {sourceCliRel: SOURCE_CLI_REL,pathExists,resolveExecutable,- isSourceCandidateAvailable: ({ root }) => pathExists(resolve22(root, LSP_TOOLS_PACKAGE_REL, DIST_CLI_REL)) && readDaemonPackageVersion(root) !== null+ isSourceCandidateAvailable: ({ root }) => pathExists(resolve23(root, LSP_TOOLS_PACKAGE_REL, DIST_CLI_REL)) && readDaemonPackageVersion(root) !== null}) : [];const distCandidate = candidates.find((candidate) => hasCliSuffix(candidate.path, DIST_CLI_REL) && candidate.exists);if (distCandidate) {@@ -105814,7 +106616,7 @@ function resolveLspCommand(options = {}) {}function createLspMcpConfig(options = {}) {const resolvedCommand = resolveLspCommand(options);- const cwd = resolve22(options.cwd ?? process.cwd());+ const cwd = resolve23(options.cwd ?? process.cwd());const configDir = getOpenCodeConfigDir({ binary: "opencode" });const sourceVersion = hasCliSuffix(resolvedCommand.path, SOURCE_CLI_REL) ? readDaemonPackageVersion(resolvedCommand.root) : null;return {@@ -105824,9 +106626,9 @@ function createLspMcpConfig(options = {}) {cwd,environment: {LSP_TOOLS_MCP_CWD: cwd,- LSP_TOOLS_MCP_PROJECT_CONFIG: PROJECT_LSP_CONFIGS.map((configPath) => resolve22(cwd, configPath)).join(delimiter3),- LSP_TOOLS_MCP_USER_CONFIG: resolve22(configDir, "lsp.json"),- LSP_TOOLS_MCP_INSTALL_DECISIONS: resolve22(configDir, "lsp-install-decisions.json"),+ LSP_TOOLS_MCP_PROJECT_CONFIG: PROJECT_LSP_CONFIGS.map((configPath) => resolve23(cwd, configPath)).join(delimiter3),+ LSP_TOOLS_MCP_USER_CONFIG: resolve23(configDir, "lsp.json"),+ LSP_TOOLS_MCP_INSTALL_DECISIONS: resolve23(configDir, "lsp-install-decisions.json"),...sourceVersion ? {[OMO_LSP_DAEMON_CLI]: resolvedCommand.path,[OMO_LSP_DAEMON_VERSION]: sourceVersion@@ -105851,24 +106653,24 @@ function getInstalledLspServers(options = {}) {// packages/omo-opencode/src/cli/doctor/checks/tools-mcp.tsinit_shared();-import { existsSync as existsSync55, readFileSync as readFileSync35 } from "fs";-import { homedir as homedir20 } from "os";-import { join as join84 } from "path";+import { existsSync as existsSync57, readFileSync as readFileSync38 } from "fs";+import { homedir as homedir21 } from "os";+import { join as join87 } from "path";var BUILTIN_MCP_SERVERS = ["websearch", "context7", "grep_app", "lsp"];function getMcpConfigPaths() {return [- join84(homedir20(), ".claude", ".mcp.json"),- join84(process.cwd(), ".mcp.json"),- join84(process.cwd(), ".claude", ".mcp.json")+ join87(homedir21(), ".claude", ".mcp.json"),+ join87(process.cwd(), ".mcp.json"),+ join87(process.cwd(), ".claude", ".mcp.json")];}function loadUserMcpConfig() {const servers = {};for (const configPath of getMcpConfigPaths()) {- if (!existsSync55(configPath))+ if (!existsSync57(configPath))continue;try {- const content = readFileSync35(configPath, "utf-8");+ const content = readFileSync38(configPath, "utf-8");const config = parseJsonc(content);if (config.mcpServers) {Object.assign(servers, config.mcpServers);@@ -106003,17 +106805,17 @@ async function checkTools() {// packages/omo-opencode/src/cli/doctor/checks/telemetry.tsinit_src5();-import { existsSync as existsSync56, readFileSync as readFileSync36 } from "fs";+import { existsSync as existsSync58, readFileSync as readFileSync39 } from "fs";function isTelemetryState(value) {return value !== null && typeof value === "object" && !Array.isArray(value);}function readLastActiveDay(stateFilePath) {- if (!existsSync56(stateFilePath)) {+ if (!existsSync58(stateFilePath)) {return "never";}let parsed;try {- parsed = JSON.parse(readFileSync36(stateFilePath, "utf-8"));+ parsed = JSON.parse(readFileSync39(stateFilePath, "utf-8"));} catch (error) {if (error instanceof Error) {return "unreadable";@@ -106071,17 +106873,17 @@ async function probeBinary(cmd, args, spawnImpl) {}// packages/team-core/src/team-registry/paths.ts-import { homedir as homedir21 } from "os";+import { homedir as homedir22 } from "os";import path13 from "path";function resolveBaseDir(config) {- return expandHomeDirectory(config.base_dir ?? path13.join(homedir21(), ".omo"));+ return expandHomeDirectory(config.base_dir ?? path13.join(homedir22(), ".omo"));}function expandHomeDirectory(directoryPath) {if (directoryPath === "~") {- return homedir21();+ return homedir22();}if (directoryPath.startsWith("~/") || directoryPath.startsWith("~\\")) {- return path13.join(homedir21(), directoryPath.slice(2));+ return path13.join(homedir22(), directoryPath.slice(2));}return directoryPath;}@@ -106097,7 +106899,7 @@ async function checkTeamMode() {const deps = await checkTeamModeDependencies(teamModeConfig);const baseDir = resolveBaseDir(teamModeConfig);const [baseDirExists, teamCount, runtimeCount] = await Promise.all([- pathExists(baseDir),+ pathExists2(baseDir),safeCount(path14.join(baseDir, "teams")),safeCount(path14.join(baseDir, "runtime"))]);@@ -106124,7 +106926,7 @@ async function safeCount(dir) {throw error;}}-async function pathExists(dir) {+async function pathExists2(dir) {try {const stats = await fs10.stat(dir);return stats.isDirectory();@@ -106138,10 +106940,10 @@ async function pathExists(dir) {// packages/omo-opencode/src/cli/doctor/checks/codex.tsinit_src();-import { existsSync as existsSync57 } from "fs";+import { existsSync as existsSync59 } from "fs";import { lstat as lstat16, readdir as readdir14, readFile as readFile28 } from "fs/promises";-import { homedir as homedir22 } from "os";-import { basename as basename11, join as join85, resolve as resolve23 } from "path";+import { homedir as homedir23 } from "os";+import { basename as basename12, join as join88, resolve as resolve24 } from "path";// packages/omo-opencode/package.jsonvar package_default3 = {name: "@oh-my-opencode/omo-opencode",@@ -106211,13 +107013,13 @@ var CODEX_BIN_NAMES = ["omo-git-bash-hook"];async function gatherCodexSummary(deps = {}) {- const codexHome = resolve23(deps.codexHome ?? process.env.CODEX_HOME ?? join85(homedir22(), ".codex"));+ const codexHome = resolve24(deps.codexHome ?? process.env.CODEX_HOME ?? join88(homedir23(), ".codex"));const binDir = resolveCodexInstallerBinDir({ binDir: deps.binDir, codexHome, env: process.env });const detection = await (deps.detectCodexInstallation ?? detectCodexInstallation)();const pluginRoot = await resolveInstalledPluginRoot(codexHome);- const manifest = pluginRoot === null ? null : await readJson(join85(pluginRoot, ".codex-plugin", "plugin.json"));- const installSnapshot = pluginRoot === null ? null : await readJson(join85(pluginRoot, "lazycodex-install.json"));- const configPath = join85(codexHome, "config.toml");+ const manifest = pluginRoot === null ? null : await readJson(join88(pluginRoot, ".codex-plugin", "plugin.json"));+ const installSnapshot = pluginRoot === null ? null : await readJson(join88(pluginRoot, "lazycodex-install.json"));+ const configPath = join88(codexHome, "config.toml");const pluginVersion = stringField(manifest, "version");return {codexPath: detection.found && "path" in detection ? detection.path : null,@@ -106274,7 +107076,7 @@ function buildCodexIssues(summary) {if (summary.pluginRoot === null) {issues.push({title: "OMO Codex plugin is not installed",- description: `Expected cached plugin at ${join85("plugins", "cache", MARKETPLACE_NAME, PLUGIN_NAME2, DEFAULT_PLUGIN_VERSION)} under CODEX_HOME.`,+ description: `Expected cached plugin at ${join88("plugins", "cache", MARKETPLACE_NAME, PLUGIN_NAME2, DEFAULT_PLUGIN_VERSION)} under CODEX_HOME.`,fix: "Run: npx lazycodex-ai install",severity: "error",affects: ["plugin loading"]@@ -106339,15 +107141,15 @@ function buildCodexIssues(summary) {return issues;}async function resolveInstalledPluginRoot(codexHome) {- const pluginRoot = join85(codexHome, "plugins", "cache", MARKETPLACE_NAME, PLUGIN_NAME2);- if (!existsSync57(pluginRoot))+ const pluginRoot = join88(codexHome, "plugins", "cache", MARKETPLACE_NAME, PLUGIN_NAME2);+ if (!existsSync59(pluginRoot))return null;const versions = await readdir14(pluginRoot, { withFileTypes: true });const candidates = versions.filter((entry) => entry.isDirectory()).map((entry) => entry.name).sort(compareVersionsDescending);- return candidates.length === 0 ? null : join85(pluginRoot, candidates[0] ?? DEFAULT_PLUGIN_VERSION);+ return candidates.length === 0 ? null : join88(pluginRoot, candidates[0] ?? DEFAULT_PLUGIN_VERSION);}async function readCodexConfigSummary(configPath) {- if (!existsSync57(configPath)) {+ if (!existsSync59(configPath)) {return {exists: false,marketplaceConfigured: false,@@ -106372,17 +107174,17 @@ async function readCodexConfigSummary(configPath) {async function readLinkedBins(binDir) {const linked = [];for (const name of CODEX_BIN_NAMES) {- if (await pathExists2(join85(binDir, process.platform === "win32" ? `${name}.cmd` : name)))+ if (await pathExists3(join88(binDir, process.platform === "win32" ? `${name}.cmd` : name)))linked.push(name);}return linked;}async function readLinkedAgents(codexHome) {- const agentsDir = join85(codexHome, "agents");- if (!existsSync57(agentsDir))+ const agentsDir = join88(codexHome, "agents");+ if (!existsSync59(agentsDir))return [];const entries = await readdir14(agentsDir, { withFileTypes: true });- return entries.filter((entry) => entry.isFile() || entry.isSymbolicLink()).map((entry) => basename11(entry.name, ".toml")).sort();+ return entries.filter((entry) => entry.isFile() || entry.isSymbolicLink()).map((entry) => basename12(entry.name, ".toml")).sort();}async function readJson(path) {try {@@ -106479,7 +107281,7 @@ function compareVersionsDescending(left, right) {}return right.localeCompare(left);}-async function pathExists2(path) {+async function pathExists3(path) {try {await lstat16(path);return true;@@ -106511,8 +107313,8 @@ function resolveLatestVersion(input) {// packages/omo-opencode/src/cli/doctor/checks/codex-components.tsinit_src();import { readdir as readdir15, readFile as readFile29, stat as stat7 } from "fs/promises";-import { homedir as homedir23 } from "os";-import { dirname as dirname33, isAbsolute as isAbsolute13, join as join86, relative as relative9, resolve as resolve24, sep as sep9 } from "path";+import { homedir as homedir24 } from "os";+import { dirname as dirname35, isAbsolute as isAbsolute14, join as join89, relative as relative9, resolve as resolve25, sep as sep9 } from "path";var CODEX_COMPONENTS_CHECK_ID = "codex-components";var CODEX_COMPONENTS_CHECK_NAME = "codex-components";var PLUGIN_DATA_DIR_NAME = "omo-sisyphuslabs";@@ -106522,7 +107324,7 @@ async function checkCodexComponents(deps = {}) {const env = deps.env ?? process.env;const platform = deps.platform ?? process.platform;const arch = deps.arch ?? process.arch;- const codexHome = resolve24(deps.codexHome ?? env["CODEX_HOME"] ?? join86(homedir23(), ".codex"));+ const codexHome = resolve25(deps.codexHome ?? env["CODEX_HOME"] ?? join89(homedir24(), ".codex"));const summary = await gatherCodexSummary({ ...deps, codexHome });if (summary.pluginRoot === null) {return {@@ -106547,7 +107349,7 @@ async function checkCodexComponents(deps = {}) {});}const runtimeSgDir = runtimeSgDirectory(codexHome, platform, arch);- const runtimeSgPath = join86(runtimeSgDir, sgBinaryName(platform));+ const runtimeSgPath = join89(runtimeSgDir, sgBinaryName(platform));const sg = findSgBinarySync({arch,env,@@ -106586,8 +107388,8 @@ async function auditBundleTargets(pluginRoot) {const manifest = await readJson2(manifestPath);if (manifest === null || !isRecord18(manifest["mcpServers"]))continue;- const manifestRoot = dirname33(manifestPath);- const isRootManifest = resolve24(manifestRoot) === resolve24(pluginRoot);+ const manifestRoot = dirname35(manifestPath);+ const isRootManifest = resolve25(manifestRoot) === resolve25(pluginRoot);for (const server of Object.values(manifest["mcpServers"])) {if (!isRecord18(server) || !Array.isArray(server["args"]))continue;@@ -106607,7 +107409,7 @@ async function auditBundleTargets(pluginRoot) {continue;const commands = [];collectHookCommands(manifest, commands);- const hookPluginRoot = dirname33(dirname33(hookManifestPath));+ const hookPluginRoot = dirname35(dirname35(hookManifestPath));for (const command of commands) {for (const relativePath of extractPluginRootPaths(command)) {referencedCount += 1;@@ -106629,8 +107431,8 @@ function recordBrokenTarget(broken, classified, origin) {broken.push(entry);}async function classifyBundleTarget(bundleRoot, baseRoot, relativePath, allowEscape) {- const targetPath = resolve24(baseRoot, relativePath);- const bundleRootPath = resolve24(bundleRoot);+ const targetPath = resolve25(baseRoot, relativePath);+ const bundleRootPath = resolve25(bundleRoot);const bundleRootPrefix = bundleRootPath.endsWith(sep9) ? bundleRootPath : `${bundleRootPath}${sep9}`;if (targetPath !== bundleRootPath && !targetPath.startsWith(bundleRootPrefix)) {if (allowEscape)@@ -106646,7 +107448,7 @@ async function classifyBundleTarget(bundleRoot, baseRoot, relativePath, allowEsc}async function findHookManifestPaths(root) {const paths = await findManifestPaths(root, "hooks.json");- return paths.filter((path) => dirname33(path).endsWith(`${sep9}hooks`));+ return paths.filter((path) => dirname35(path).endsWith(`${sep9}hooks`));}async function findManifestPaths(root, manifestName) {let entries;@@ -106659,7 +107461,7 @@ async function findManifestPaths(root, manifestName) {for (const entry of entries) {if (entry.name === "node_modules" || entry.name === ".git")continue;- const entryPath = join86(root, entry.name);+ const entryPath = join89(root, entry.name);if (entry.isDirectory()) {paths.push(...await findManifestPaths(entryPath, manifestName));continue;@@ -106700,21 +107502,21 @@ function extractPluginRootPaths(command) {}function isPluginRuntimePathArg(arg) {const normalized = normalizePathSeparators(arg);- return normalized.endsWith(".js") && normalized.includes("/dist/") && (normalized.startsWith("./") || normalized.startsWith("../") || normalized.startsWith("components/") || normalized.startsWith("/") || isAbsolute13(arg));+ return normalized.endsWith(".js") && normalized.includes("/dist/") && (normalized.startsWith("./") || normalized.startsWith("../") || normalized.startsWith("components/") || normalized.startsWith("/") || isAbsolute14(arg));}function runtimeSgDirectory(codexHome, platform, arch) {- return join86(codexHome, "runtime", "ast-grep", runtimeSlug(platform, arch));+ return join89(codexHome, "runtime", "ast-grep", runtimeSlug(platform, arch));}function describeSgSource(sgPath, env, runtimeSgDir, platform) {const override = env[SG_PATH_ENV_KEY]?.trim();if (override !== undefined && override.length > 0 && sgPath === override)return `env override ${SG_PATH_ENV_KEY}`;- if (sgPath === join86(runtimeSgDir, sgBinaryName(platform)))+ if (sgPath === join89(runtimeSgDir, sgBinaryName(platform)))return "runtime dir";return "PATH";}async function readBootstrapStateSummary(codexHome) {- const statePath = join86(codexHome, "plugins", "data", PLUGIN_DATA_DIR_NAME, "bootstrap", "state.json");+ const statePath = join89(codexHome, "plugins", "data", PLUGIN_DATA_DIR_NAME, "bootstrap", "state.json");const raw = await readJson2(statePath);if (raw === null)return null;@@ -106790,24 +107592,24 @@ function isRecord18(value) {}// packages/omo-opencode/src/cli/doctor/checks/codex-runtime-wrapper.ts-import { existsSync as existsSync58 } from "fs";+import { existsSync as existsSync60 } from "fs";import { readFile as readFile30 } from "fs/promises";-import { homedir as homedir24 } from "os";-import { join as join87, resolve as resolve25 } from "path";+import { homedir as homedir25 } from "os";+import { join as join90, resolve as resolve26 } from "path";var RUNTIME_WRAPPER_MARKER2 = "OMO_GENERATED_RUNTIME_WRAPPER";var CHECK_NAME = "codex-runtime-wrapper";var REINSTALL_COMMAND = "npx --yes lazycodex-ai@latest install --no-tui";async function checkCodexRuntimeWrapper(deps = {}) {- const codexHome = resolve25(deps.codexHome ?? process.env.CODEX_HOME ?? join87(homedir24(), ".codex"));+ const codexHome = resolve26(deps.codexHome ?? process.env.CODEX_HOME ?? join90(homedir25(), ".codex"));const binDir = resolveCodexInstallerBinDir({ binDir: deps.binDir, codexHome, env: process.env });const platform = deps.platform ?? process.platform;- const wrapperPath = join87(binDir, platform === "win32" ? "omo-agent-toolkit.cmd" : "omo-agent-toolkit");- const legacyWrapperPath = join87(binDir, platform === "win32" ? "omo.cmd" : "omo");+ const wrapperPath = join90(binDir, platform === "win32" ? "omo-agent-toolkit.cmd" : "omo-agent-toolkit");+ const legacyWrapperPath = join90(binDir, platform === "win32" ? "omo.cmd" : "omo");const [wrapper, legacyWrapper] = await Promise.all([readRuntimeWrapper(wrapperPath), readRuntimeWrapper(legacyWrapperPath)]);const issues = [];if (wrapper?.includes(RUNTIME_WRAPPER_MARKER2) === true) {const targetPath = parseRuntimeTargetPath(wrapper);- if (targetPath !== null && !existsSync58(targetPath)) {+ if (targetPath !== null && !existsSync60(targetPath)) {issues.push({title: "omo-agent-toolkit runtime wrapper target is missing",description: `Generated omo-agent-toolkit runtime wrapper at ${wrapperPath} points to missing target ${targetPath}.`,@@ -107330,26 +108132,26 @@ Doctor failed unexpectedly: ${message}`];import { createHash as createHash7 } from "crypto";import {chmodSync as chmodSync5,- existsSync as existsSync61,- mkdirSync as mkdirSync16,- readdirSync as readdirSync12,- readFileSync as readFileSync38,- renameSync as renameSync7,+ existsSync as existsSync63,+ mkdirSync as mkdirSync17,+ readdirSync as readdirSync13,+ readFileSync as readFileSync41,+ renameSync as renameSync8,unlinkSync as unlinkSync9,- writeFileSync as writeFileSync12+ writeFileSync as writeFileSync13} from "fs";-import { basename as basename12, dirname as dirname34, join as join90 } from "path";+import { basename as basename13, dirname as dirname36, join as join93 } from "path";// packages/mcp-client-core/src/config-dir.ts-import { existsSync as existsSync59, realpathSync as realpathSync8 } from "fs";-import { homedir as homedir25 } from "os";-import { join as join88, resolve as resolve26 } from "path";+import { existsSync as existsSync61, realpathSync as realpathSync10 } from "fs";+import { homedir as homedir26 } from "os";+import { join as join91, resolve as resolve27 } from "path";function resolveConfigPath2(pathValue) {- const resolvedPath = resolve26(pathValue);- if (!existsSync59(resolvedPath))+ const resolvedPath = resolve27(pathValue);+ if (!existsSync61(resolvedPath))return resolvedPath;try {- return realpathSync8(resolvedPath);+ return realpathSync10(resolvedPath);} catch (error) {if (!(error instanceof Error))throw error;@@ -107361,13 +108163,13 @@ function getOpenCodeCliConfigDir(env = process.env) {if (customConfigDir) {return resolveConfigPath2(customConfigDir);}- const xdgConfigDir = env["XDG_CONFIG_HOME"]?.trim() || join88(homedir25(), ".config");- return resolveConfigPath2(join88(xdgConfigDir, "opencode"));+ const xdgConfigDir = env["XDG_CONFIG_HOME"]?.trim() || join91(homedir26(), ".config");+ return resolveConfigPath2(join91(xdgConfigDir, "opencode"));}// packages/mcp-client-core/src/mcp-oauth/storage-index.ts-import { chmodSync as chmodSync4, existsSync as existsSync60, readFileSync as readFileSync37, renameSync as renameSync6, writeFileSync as writeFileSync11 } from "fs";-import { join as join89 } from "path";+import { chmodSync as chmodSync4, existsSync as existsSync62, readFileSync as readFileSync40, renameSync as renameSync7, writeFileSync as writeFileSync12 } from "fs";+import { join as join92 } from "path";var INDEX_FILE_NAME = "index.json";function isTokenIndex(value) {if (typeof value !== "object" || value === null || Array.isArray(value))@@ -107375,14 +108177,14 @@ function isTokenIndex(value) {return Object.values(value).every((entry) => typeof entry === "string");}function getIndexPath(storageDir) {- return join89(storageDir, INDEX_FILE_NAME);+ return join92(storageDir, INDEX_FILE_NAME);}function readTokenIndex(storageDir) {const indexPath = getIndexPath(storageDir);- if (!existsSync60(indexPath))+ if (!existsSync62(indexPath))return {};try {- const parsed = JSON.parse(readFileSync37(indexPath, "utf-8"));+ const parsed = JSON.parse(readFileSync40(indexPath, "utf-8"));return isTokenIndex(parsed) ? parsed : {};} catch (readError) {if (!(readError instanceof Error))@@ -107394,9 +108196,9 @@ function writeTokenIndex(storageDir, index) {try {const indexPath = getIndexPath(storageDir);const tempPath = `${indexPath}.tmp.${Date.now()}`;- writeFileSync11(tempPath, JSON.stringify(index, null, 2), { encoding: "utf-8", mode: 384 });+ writeFileSync12(tempPath, JSON.stringify(index, null, 2), { encoding: "utf-8", mode: 384 });chmodSync4(tempPath, 384);- renameSync6(tempPath, indexPath);+ renameSync7(tempPath, indexPath);return true;} catch (writeError) {if (!(writeError instanceof Error))@@ -107419,16 +108221,16 @@ function deleteTokenIndexEntry(storageDir, hash) {var STORAGE_DIR_NAME = "mcp-oauth";var LEGACY_STORAGE_FILE_NAME = "mcp-oauth.json";function getMcpOauthStorageDir() {- return join90(getOpenCodeCliConfigDir(), STORAGE_DIR_NAME);+ return join93(getOpenCodeCliConfigDir(), STORAGE_DIR_NAME);}function getMcpOauthServerHash(serverHost, resource) {return createHash7("sha256").update(buildKey(serverHost, resource)).digest("hex").slice(0, 32);}function getMcpOauthStoragePath(serverHost, resource) {- return join90(getMcpOauthStorageDir(), `${getMcpOauthServerHash(serverHost, resource)}.json`);+ return join93(getMcpOauthStorageDir(), `${getMcpOauthServerHash(serverHost, resource)}.json`);}function getLegacyStoragePath() {- return join90(getOpenCodeCliConfigDir(), LEGACY_STORAGE_FILE_NAME);+ return join93(getOpenCodeCliConfigDir(), LEGACY_STORAGE_FILE_NAME);}function normalizeHost2(serverHost) {let host = serverHost.trim();@@ -107489,10 +108291,10 @@ function isOAuthTokenData(value) {return clientSecret === undefined || typeof clientSecret === "string";}function readTokenFile(filePath) {- if (!existsSync61(filePath))+ if (!existsSync63(filePath))return null;try {- const parsed = JSON.parse(readFileSync38(filePath, "utf-8"));+ const parsed = JSON.parse(readFileSync41(filePath, "utf-8"));return isOAuthTokenData(parsed) ? parsed : null;} catch (readError) {if (!(readError instanceof Error))@@ -107502,10 +108304,10 @@ function readTokenFile(filePath) {}function readLegacyStore() {const filePath = getLegacyStoragePath();- if (!existsSync61(filePath))+ if (!existsSync63(filePath))return null;try {- const parsed = JSON.parse(readFileSync38(filePath, "utf-8"));+ const parsed = JSON.parse(readFileSync41(filePath, "utf-8"));if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))return null;const result = {};@@ -107522,14 +108324,14 @@ function readLegacyStore() {}function writeTokenFile(filePath, token) {try {- const dir = dirname34(filePath);- if (!existsSync61(dir)) {- mkdirSync16(dir, { recursive: true });+ const dir = dirname36(filePath);+ if (!existsSync63(dir)) {+ mkdirSync17(dir, { recursive: true });}const tempPath = `${filePath}.tmp.${Date.now()}`;- writeFileSync12(tempPath, JSON.stringify(token, null, 2), { encoding: "utf-8", mode: 384 });+ writeFileSync13(tempPath, JSON.stringify(token, null, 2), { encoding: "utf-8", mode: 384 });chmodSync5(tempPath, 384);- renameSync7(tempPath, filePath);+ renameSync8(tempPath, filePath);return true;} catch (writeError) {if (!(writeError instanceof Error))@@ -107547,7 +108349,7 @@ function saveToken(serverHost, resource, token) {}function deleteToken(serverHost, resource) {const filePath = getMcpOauthStoragePath(serverHost, resource);- if (!existsSync61(filePath))+ if (!existsSync63(filePath))return deleteLegacyToken(serverHost, resource);try {unlinkSync9(filePath);@@ -107569,7 +108371,7 @@ function deleteLegacyToken(serverHost, resource) {if (Object.keys(store).length === 0) {try {const filePath = getLegacyStoragePath();- if (existsSync61(filePath))+ if (existsSync63(filePath))unlinkSync9(filePath);return true;} catch (deleteError) {@@ -107583,7 +108385,7 @@ function deleteLegacyToken(serverHost, resource) {function writeLegacyStore(store) {try {const filePath = getLegacyStoragePath();- writeFileSync12(filePath, JSON.stringify(store, null, 2), { encoding: "utf-8", mode: 384 });+ writeFileSync13(filePath, JSON.stringify(store, null, 2), { encoding: "utf-8", mode: 384 });chmodSync5(filePath, 384);return true;} catch (writeError) {@@ -107607,7 +108409,7 @@ function listTokensByHost(serverHost) {for (const [hash, indexedKey] of Object.entries(index)) {if (!indexedKey.startsWith(prefix))continue;- const indexedToken = readTokenFile(join90(getMcpOauthStorageDir(), `${hash}.json`));+ const indexedToken = readTokenFile(join93(getMcpOauthStorageDir(), `${hash}.json`));if (indexedToken)result[indexedKey] = indexedToken;}@@ -107616,14 +108418,14 @@ function listTokensByHost(serverHost) {function listAllTokens() {const result = { ...readLegacyStore() ?? {} };const dir = getMcpOauthStorageDir();- if (!existsSync61(dir))+ if (!existsSync63(dir))return result;const index = readTokenIndex(dir);- for (const entry of readdirSync12(dir, { withFileTypes: true })) {+ for (const entry of readdirSync13(dir, { withFileTypes: true })) {if (!entry.isFile() || !entry.name.endsWith(".json") || entry.name === "index.json")continue;- const token = readTokenFile(join90(dir, entry.name));- const hash = basename12(entry.name, ".json");+ const token = readTokenFile(join93(dir, entry.name));+ const hash = basename13(entry.name, ".json");if (token)result[index[hash] ?? hash] = token;}@@ -108188,7 +108990,7 @@ function createMcpOAuthCommand() {}// packages/omo-opencode/src/cli/boulder/boulder.ts-import { existsSync as existsSync62 } from "fs";+import { existsSync as existsSync64 } from "fs";// packages/omo-opencode/src/cli/boulder/formatter.tsvar import_picocolors22 = __toESM(require_picocolors(), 1);@@ -108325,10 +109127,10 @@ async function boulder(options) {const boulderFilePath = getBoulderFilePath(directory);const state = readBoulderState(directory);if (!state) {- const message = existsSync62(boulderFilePath) ? formatReadErrorMessage(options.json) : formatNoBoulderMessage(options.json);+ const message = existsSync64(boulderFilePath) ? formatReadErrorMessage(options.json) : formatNoBoulderMessage(options.json);process.stderr.write(`${message}`);- return existsSync62(boulderFilePath) ? 2 : 1;+ return existsSync64(boulderFilePath) ? 2 : 1;}const works = getBoulderWorks(state);const filteredWorks = options.workId ? works.filter((work) => work.work_id === options.workId) : works;@@ -108346,12 +109148,12 @@ async function boulder(options) {}// packages/omo-opencode/src/cli/codex-ulw-loop.tsimport { spawn as spawn5 } from "child_process";-import { existsSync as existsSync63, readFileSync as readFileSync39, realpathSync as realpathSync9 } from "fs";-import { homedir as homedir26 } from "os";+import { existsSync as existsSync65, readFileSync as readFileSync42, realpathSync as realpathSync11 } from "fs";+import { homedir as homedir27 } from "os";var ULW_LOOP_DELEGATION_SENTINEL = "OMO_ULW_LOOP_DELEGATED";function resolveCodexUlwLoopCommand(input = {}) {const env = input.env ?? process.env;- const homeDir = input.homeDir ?? homedir26();+ const homeDir = input.homeDir ?? homedir27();const localComponentBin = resolveLocalUlwLoopBin(env, homeDir);if (localComponentBin !== null)return { executable: localComponentBin, argsPrefix: [] };@@ -108388,15 +109190,15 @@ async function codexUlwLoop(args) {}function resolveLocalUlwLoopBin(env, homeDir) {const candidates = resolveCodexComponentBinCandidates({ executableName: "omo-ulw-loop", env, homeDir });- return candidates.find((candidate) => existsSync63(candidate)) ?? null;+ return candidates.find((candidate) => existsSync65(candidate)) ?? null;}function resolveLegacyLocalOmoBin(env, homeDir, currentExecutablePaths) {const candidates = resolveCodexComponentBinCandidates({ executableName: "omo", env, homeDir });- return candidates.find((candidate) => existsSync63(candidate) && !isCurrentExecutable(candidate, currentExecutablePaths) && !isGeneratedRuntimeWrapper(candidate)) ?? null;+ return candidates.find((candidate) => existsSync65(candidate) && !isCurrentExecutable(candidate, currentExecutablePaths) && !isGeneratedRuntimeWrapper(candidate)) ?? null;}function isGeneratedRuntimeWrapper(candidate) {try {- return readFileSync39(candidate, "utf8").includes(RUNTIME_WRAPPER_MARKER);+ return readFileSync42(candidate, "utf8").includes(RUNTIME_WRAPPER_MARKER);} catch (error) {if (error instanceof Error)return false;@@ -108409,7 +109211,7 @@ function isCurrentExecutable(candidate, currentExecutablePaths) {}function realpathOrSelf2(path) {try {- return realpathSync9(path);+ return realpathSync11(path);} catch (error) {if (error instanceof Error)return path;@@ -108591,7 +109393,7 @@ function linkedWorktrees(records) {return records.slice(1);}// packages/omo-opencode/src/cli/worktree-sweep/sweep.ts-import { existsSync as existsSync64 } from "fs";+import { existsSync as existsSync66 } from "fs";import { stat as stat8 } from "fs/promises";import os7 from "os";import { normalize as normalize2 } from "path";@@ -108682,7 +109484,7 @@ async function isOlderThan(worktreePath, days, now) {}}async function classifyRecord(repo, record, defaultBranch, options) {- const pathExists = existsSync64(record.path);+ const pathExists = existsSync66(record.path);const external = isExcludedPath(record.path, options.excludePrefixes, options.home);if (record.locked || !pathExists || external) {return classifyWorktree({@@ -108832,7 +109634,7 @@ removes with 'git worktree remove' (never --force) and then prunes.// packages/omo-opencode/src/cli/config-migrate.tsinit_startup_migration();-import { posix as posix11 } from "path";+import { posix as posix12 } from "path";function reports(result) {return result.results.map((entry) => ({diagnostics: entry.diagnostics,@@ -108863,7 +109665,7 @@ function runConfigMigrate(options = {}) {dryRun: options.dryRun ?? false,environment,...homeDir === undefined ? {} : { env: { HOME: homeDir }, homeDir },- pathOperations: posix11+ pathOperations: posix12});const report = reports(result);const response = {diff --git a/plugins/omo/hooks/post-compact-resetting-git-bash-mcp-reminder.json b/plugins/omo/hooks/post-compact-resetting-git-bash-mcp-reminder.jsonindex 65cab303..585016cf 100644--- a/plugins/omo/hooks/post-compact-resetting-git-bash-mcp-reminder.json+++ b/plugins/omo/hooks/post-compact-resetting-git-bash-mcp-reminder.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/git-bash/dist/cli.js\" hook post-compact","timeout": 5,- "statusMessage": "(OmO 5.0.0-beta.89) Resetting Git Bash MCP Reminder",+ "statusMessage": "(OmO 5.0.0-beta.90) Resetting Git Bash MCP Reminder","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\git-bash\\dist\\cli.js\" hook post-compact"}],diff --git a/plugins/omo/hooks/post-compact-resetting-lsp-diagnostics-cache.json b/plugins/omo/hooks/post-compact-resetting-lsp-diagnostics-cache.jsonindex 397e1806..356fb417 100644--- a/plugins/omo/hooks/post-compact-resetting-lsp-diagnostics-cache.json+++ b/plugins/omo/hooks/post-compact-resetting-lsp-diagnostics-cache.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/lsp/dist/cli.js\" hook post-compact","timeout": 5,- "statusMessage": "(OmO 5.0.0-beta.89) Resetting LSP Diagnostics Cache",+ "statusMessage": "(OmO 5.0.0-beta.90) Resetting LSP Diagnostics Cache","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\lsp\\dist\\cli.js\" hook post-compact"}],diff --git a/plugins/omo/hooks/post-compact-resetting-project-rule-cache.json b/plugins/omo/hooks/post-compact-resetting-project-rule-cache.jsonindex d3247279..dfbffee9 100644--- a/plugins/omo/hooks/post-compact-resetting-project-rule-cache.json+++ b/plugins/omo/hooks/post-compact-resetting-project-rule-cache.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook post-compact","timeout": 10,- "statusMessage": "(OmO 5.0.0-beta.89) Resetting Project Rule Cache",+ "statusMessage": "(OmO 5.0.0-beta.90) Resetting Project Rule Cache","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\rules\\dist\\cli.js\" hook post-compact"}],diff --git a/plugins/omo/hooks/post-tool-use-checking-comments.json b/plugins/omo/hooks/post-tool-use-checking-comments.jsonindex a7f11f41..28881e22 100644--- a/plugins/omo/hooks/post-tool-use-checking-comments.json+++ b/plugins/omo/hooks/post-tool-use-checking-comments.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/comment-checker/dist/cli.js\" hook post-tool-use","timeout": 30,- "statusMessage": "(OmO 5.0.0-beta.89) Checking Comments",+ "statusMessage": "(OmO 5.0.0-beta.90) Checking Comments","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\comment-checker\\dist\\cli.js\" hook post-tool-use"}],diff --git a/plugins/omo/hooks/post-tool-use-checking-lsp-diagnostics.json b/plugins/omo/hooks/post-tool-use-checking-lsp-diagnostics.jsonindex 84878406..c9a44dd5 100644--- a/plugins/omo/hooks/post-tool-use-checking-lsp-diagnostics.json+++ b/plugins/omo/hooks/post-tool-use-checking-lsp-diagnostics.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/lsp/dist/cli.js\" hook post-tool-use","timeout": 60,- "statusMessage": "(OmO 5.0.0-beta.89) Checking LSP Diagnostics",+ "statusMessage": "(OmO 5.0.0-beta.90) Checking LSP Diagnostics","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\lsp\\dist\\cli.js\" hook post-tool-use"}],diff --git a/plugins/omo/hooks/post-tool-use-checking-thread-title-hygiene.json b/plugins/omo/hooks/post-tool-use-checking-thread-title-hygiene.jsonindex 1a4de378..aa013088 100644--- a/plugins/omo/hooks/post-tool-use-checking-thread-title-hygiene.json+++ b/plugins/omo/hooks/post-tool-use-checking-thread-title-hygiene.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/teammode/dist/cli.js\" hook post-tool-use","timeout": 10,- "statusMessage": "(OmO 5.0.0-beta.89) Checking Thread Title Hygiene",+ "statusMessage": "(OmO 5.0.0-beta.90) Checking Thread Title Hygiene","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\teammode\\dist\\cli.js\" hook post-tool-use"}]diff --git a/plugins/omo/hooks/post-tool-use-matching-project-rules.json b/plugins/omo/hooks/post-tool-use-matching-project-rules.jsonindex 513ef895..c5e24050 100644--- a/plugins/omo/hooks/post-tool-use-matching-project-rules.json+++ b/plugins/omo/hooks/post-tool-use-matching-project-rules.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook post-tool-use","timeout": 10,- "statusMessage": "(OmO 5.0.0-beta.89) Matching Project Rules",+ "statusMessage": "(OmO 5.0.0-beta.90) Matching Project Rules","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\rules\\dist\\cli.js\" hook post-tool-use"}],diff --git a/plugins/omo/hooks/post-tool-use-recording-spawn-admission.json b/plugins/omo/hooks/post-tool-use-recording-spawn-admission.jsonindex b435e663..fc821814 100644--- a/plugins/omo/hooks/post-tool-use-recording-spawn-admission.json+++ b/plugins/omo/hooks/post-tool-use-recording-spawn-admission.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook post-tool-use-spawn","timeout": 5,- "statusMessage": "(OmO 5.0.0-beta.89) Recording Spawn Admission",+ "statusMessage": "(OmO 5.0.0-beta.90) Recording Spawn Admission","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook post-tool-use-spawn"}]diff --git a/plugins/omo/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json b/plugins/omo/hooks/pre-tool-use-enforcing-unlimited-goal-budget.jsonindex bc8601b3..0968d961 100644--- a/plugins/omo/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json+++ b/plugins/omo/hooks/pre-tool-use-enforcing-unlimited-goal-budget.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook pre-tool-use","timeout": 5,- "statusMessage": "(OmO 5.0.0-beta.89) Enforcing Unlimited Goal Budget",+ "statusMessage": "(OmO 5.0.0-beta.90) Enforcing Unlimited Goal Budget","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook pre-tool-use"}],diff --git a/plugins/omo/hooks/pre-tool-use-guarding-ulw-loop-spawns.json b/plugins/omo/hooks/pre-tool-use-guarding-ulw-loop-spawns.jsonindex 753d4699..20b47e44 100644--- a/plugins/omo/hooks/pre-tool-use-guarding-ulw-loop-spawns.json+++ b/plugins/omo/hooks/pre-tool-use-guarding-ulw-loop-spawns.json@@ -8,7 +8,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook pre-tool-use-spawn","timeout": 5,- "statusMessage": "(OmO 5.0.0-beta.89) Guarding Ulw-Loop Spawns",+ "statusMessage": "(OmO 5.0.0-beta.90) Guarding Ulw-Loop Spawns","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook pre-tool-use-spawn"}]diff --git a/plugins/omo/hooks/pre-tool-use-recommending-git-bash-mcp.json b/plugins/omo/hooks/pre-tool-use-recommending-git-bash-mcp.jsonindex 3e72e262..1b616dd2 100644--- a/plugins/omo/hooks/pre-tool-use-recommending-git-bash-mcp.json+++ b/plugins/omo/hooks/pre-tool-use-recommending-git-bash-mcp.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/git-bash/dist/cli.js\" hook pre-tool-use","timeout": 5,- "statusMessage": "(OmO 5.0.0-beta.89) Recommending Git Bash MCP",+ "statusMessage": "(OmO 5.0.0-beta.90) Recommending Git Bash MCP","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\git-bash\\dist\\cli.js\" hook pre-tool-use"}],diff --git a/plugins/omo/hooks/session-start-checking-auto-update.json b/plugins/omo/hooks/session-start-checking-auto-update.jsonindex e10a6365..8d1f591b 100644--- a/plugins/omo/hooks/session-start-checking-auto-update.json+++ b/plugins/omo/hooks/session-start-checking-auto-update.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/scripts/auto-update.mjs\" hook session-start","timeout": 15,- "statusMessage": "(OmO 5.0.0-beta.89) Checking Auto Update",+ "statusMessage": "(OmO 5.0.0-beta.90) Checking Auto Update","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\scripts\\auto-update.mjs\" hook session-start"}],diff --git a/plugins/omo/hooks/session-start-checking-bootstrap-provisioning.json b/plugins/omo/hooks/session-start-checking-bootstrap-provisioning.jsonindex a8273257..68be7b06 100644--- a/plugins/omo/hooks/session-start-checking-bootstrap-provisioning.json+++ b/plugins/omo/hooks/session-start-checking-bootstrap-provisioning.json@@ -8,7 +8,7 @@"command": "node \"${PLUGIN_ROOT}/components/bootstrap/dist/cli.js\" hook session-start","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\bootstrap.ps1\"","timeout": 30,- "statusMessage": "(OmO 5.0.0-beta.89) Checking Bootstrap Provisioning"+ "statusMessage": "(OmO 5.0.0-beta.90) Checking Bootstrap Provisioning"}]}diff --git a/plugins/omo/hooks/session-start-loading-project-rules.json b/plugins/omo/hooks/session-start-loading-project-rules.jsonindex 7a60c1c0..8df16bfc 100644--- a/plugins/omo/hooks/session-start-loading-project-rules.json+++ b/plugins/omo/hooks/session-start-loading-project-rules.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook session-start","timeout": 10,- "statusMessage": "(OmO 5.0.0-beta.89) Loading Project Rules",+ "statusMessage": "(OmO 5.0.0-beta.90) Loading Project Rules","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\rules\\dist\\cli.js\" hook session-start"}]diff --git a/plugins/omo/hooks/session-start-recording-session-telemetry.json b/plugins/omo/hooks/session-start-recording-session-telemetry.jsonindex fcf92da9..3e98967f 100644--- a/plugins/omo/hooks/session-start-recording-session-telemetry.json+++ b/plugins/omo/hooks/session-start-recording-session-telemetry.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/telemetry/dist/cli.js\" hook session-start","timeout": 15,- "statusMessage": "(OmO 5.0.0-beta.89) Recording Session Telemetry",+ "statusMessage": "(OmO 5.0.0-beta.90) Recording Session Telemetry","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\telemetry\\dist\\cli.js\" hook session-start"}]diff --git a/plugins/omo/hooks/stop-checking-ulw-execute-continuation.json b/plugins/omo/hooks/stop-checking-ulw-execute-continuation.jsonindex 5a0e2047..bc72edde 100644--- a/plugins/omo/hooks/stop-checking-ulw-execute-continuation.json+++ b/plugins/omo/hooks/stop-checking-ulw-execute-continuation.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ulw-execute-continuation/dist/cli.js\" hook stop","timeout": 10,- "statusMessage": "(OmO 5.0.0-beta.89) Checking Ulw-Execute Continuation",+ "statusMessage": "(OmO 5.0.0-beta.90) Checking Ulw-Execute Continuation","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-execute-continuation\\dist\\cli.js\" hook stop"}]diff --git a/plugins/omo/hooks/stop-checking-ulw-loop-resume.json b/plugins/omo/hooks/stop-checking-ulw-loop-resume.jsonindex 0ac91195..a384cb94 100644--- a/plugins/omo/hooks/stop-checking-ulw-loop-resume.json+++ b/plugins/omo/hooks/stop-checking-ulw-loop-resume.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook stop","timeout": 10,- "statusMessage": "(OmO 5.0.0-beta.89) Checking Ulw-Loop Resume",+ "statusMessage": "(OmO 5.0.0-beta.90) Checking Ulw-Loop Resume","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook stop"}]diff --git a/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json b/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.jsonindex 03af1898..ad73ce4c 100644--- a/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json+++ b/plugins/omo/hooks/subagent-stop-verifying-lazycodex-executor-evidence.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/lazycodex-executor-verify/dist/cli.js\" hook subagent-stop","timeout": 10,- "statusMessage": "(OmO 5.0.0-beta.89) Verifying LazyCodex Executor Evidence",+ "statusMessage": "(OmO 5.0.0-beta.90) Verifying LazyCodex Executor Evidence","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\lazycodex-executor-verify\\dist\\cli.js\" hook subagent-stop"}],diff --git a/plugins/omo/hooks/user-prompt-submit-checking-ultrawork-trigger.json b/plugins/omo/hooks/user-prompt-submit-checking-ultrawork-trigger.jsonindex 6a87fc14..da8b86b6 100644--- a/plugins/omo/hooks/user-prompt-submit-checking-ultrawork-trigger.json+++ b/plugins/omo/hooks/user-prompt-submit-checking-ultrawork-trigger.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ultrawork/dist/cli.js\" hook user-prompt-submit","timeout": 5,- "statusMessage": "(OmO 5.0.0-beta.89) Checking Ultrawork Trigger",+ "statusMessage": "(OmO 5.0.0-beta.90) Checking Ultrawork Trigger","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ultrawork\\dist\\cli.js\" hook user-prompt-submit"}]diff --git a/plugins/omo/hooks/user-prompt-submit-checking-ulw-loop-steering.json b/plugins/omo/hooks/user-prompt-submit-checking-ulw-loop-steering.jsonindex 0b5456e8..10c70c1c 100644--- a/plugins/omo/hooks/user-prompt-submit-checking-ulw-loop-steering.json+++ b/plugins/omo/hooks/user-prompt-submit-checking-ulw-loop-steering.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/ulw-loop/dist/cli.js\" hook user-prompt-submit","timeout": 10,- "statusMessage": "(OmO 5.0.0-beta.89) Checking Ulw-Loop Steering",+ "statusMessage": "(OmO 5.0.0-beta.90) Checking Ulw-Loop Steering","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\ulw-loop\\dist\\cli.js\" hook user-prompt-submit"}]diff --git a/plugins/omo/hooks/user-prompt-submit-loading-project-rules.json b/plugins/omo/hooks/user-prompt-submit-loading-project-rules.jsonindex e6a437c9..98f51c18 100644--- a/plugins/omo/hooks/user-prompt-submit-loading-project-rules.json+++ b/plugins/omo/hooks/user-prompt-submit-loading-project-rules.json@@ -7,7 +7,7 @@"type": "command","command": "node \"${PLUGIN_ROOT}/components/rules/dist/cli.js\" hook user-prompt-submit","timeout": 10,- "statusMessage": "(OmO 5.0.0-beta.89) Loading Project Rules",+ "statusMessage": "(OmO 5.0.0-beta.90) Loading Project Rules","commandWindows": "powershell -NoProfile -ExecutionPolicy Bypass -File \"${PLUGIN_ROOT}\\components\\bootstrap\\scripts\\node-dispatch.ps1\" \"${PLUGIN_ROOT}\\components\\rules\\dist\\cli.js\" hook user-prompt-submit"}]diff --git a/plugins/omo/package-lock.json b/plugins/omo/package-lock.jsonindex 8bcf40bc..3df02a67 100644--- a/plugins/omo/package-lock.json+++ b/plugins/omo/package-lock.json@@ -1,12 +1,12 @@{"name": "@sisyphuslabs/omo-codex-plugin",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@sisyphuslabs/omo-codex-plugin",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","workspaces": ["components/comment-checker","components/git-bash",@@ -95,7 +95,7 @@},"components/comment-checker": {"name": "@code-yeongyu/codex-comment-checker",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","license": "MIT","bin": {"omo-comment-checker": "dist/cli.js"@@ -117,7 +117,7 @@},"components/git-bash": {"name": "@sisyphuslabs/codex-git-bash-hook",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","bin": {"omo-git-bash-hook": "dist/cli.js"},@@ -131,7 +131,7 @@},"components/lazycodex-executor-verify": {"name": "@code-yeongyu/codex-lazycodex-executor-verify",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","license": "MIT","bin": {"lazycodex-executor-verify": "dist/cli.js"@@ -149,7 +149,7 @@},"components/lsp": {"name": "@code-yeongyu/codex-lsp",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","license": "MIT","dependencies": {"@code-yeongyu/lsp-daemon": "file:../../../../lsp-daemon",@@ -171,7 +171,7 @@},"components/rules": {"name": "@code-yeongyu/codex-rules",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","license": "MIT","dependencies": {"picomatch": "^4.0.7"@@ -194,7 +194,7 @@},"components/teammode": {"name": "@sisyphuslabs/codex-teammode",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","devDependencies": {"@types/node": "^26.6.2","@vitest/coverage-v8": "5.0.1",@@ -208,7 +208,7 @@},"components/telemetry": {"name": "@code-yeongyu/codex-telemetry",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","license": "MIT","bin": {"omo-telemetry": "dist/cli.js"@@ -227,7 +227,7 @@},"components/ultrawork": {"name": "@code-yeongyu/codex-ultrawork",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","license": "MIT","bin": {"omo-ultrawork": "dist/cli.js"@@ -246,7 +246,7 @@},"components/ulw-execute-continuation": {"name": "@code-yeongyu/codex-ulw-execute-continuation",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","license": "MIT","bin": {"omo-ulw-execute-continuation": "dist/cli.js"@@ -264,7 +264,7 @@},"components/ulw-loop": {"name": "@code-yeongyu/codex-ulw-loop",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","license": "MIT","bin": {"omo-ulw-loop": "dist/cli.js",diff --git a/plugins/omo/package.json b/plugins/omo/package.jsonindex 29166a00..1ab35044 100644--- a/plugins/omo/package.json+++ b/plugins/omo/package.json@@ -1,6 +1,6 @@{"name": "@sisyphuslabs/omo-codex-plugin",- "version": "5.0.0-beta.89",+ "version": "5.0.0-beta.90","description": "Aggregate Codex plugin root for OMO components.","type": "module","packageManager": "[email protected]",diff --git a/plugins/omo/scripts/sync-skills.mjs b/plugins/omo/scripts/sync-skills.mjsindex 257eae6c..ea61ca7c 100644--- a/plugins/omo/scripts/sync-skills.mjs+++ b/plugins/omo/scripts/sync-skills.mjs@@ -171,8 +171,8 @@ private logs, or PII; summarize with lengths, hashes, and short non-sensitiveprefixes when identity is needed.`;-const ulwResearchOriginalDeliveryGates = "### The delivery gates \u2014 every gate must PASS, in order\n\nNothing reaches the user until the gates pass:\n\n1. **Visual QA (always).** Render the produced artifact back to images \u2014 PDF pages to PNG, the HTML in a real browser \u2014 and look at them: missing or broken figures, images stretched or spilling their containers, diagram or chart text rendered off the spec's font or palette, clipped tables, overflowing CJK text, blank pages, unlabeled chart values, wrong page breaks. Fix and re-render until the pages are clean. Reading the source markup is not visual QA; inspect the pixels.\n2. **Proofread gate \u2014 `task(category=\"writing\", ...)`.** Hand the final text to a dedicated `writing` worker whose only job is language: grammar, spelling, punctuation, terminology consistency, and whether the prose reads NATIVELY in the report's own language. It returns a defect list; fix every item and re-run the gate on the delta. Deliver only on a clean pass \u2014 this gate runs BEFORE the first delivery, not after the user finds the typo.";-const ulwResearchCodexDeliveryGate = "### The delivery gate \u2014 visual QA must PASS\n\nNothing reaches the user until the gate passes:\n\n**Visual QA (always).** Render the produced artifact back to images \u2014 PDF pages to PNG, the HTML in a real browser \u2014 and look at them: missing or broken figures, images stretched or spilling their containers, diagram or chart text rendered off the spec's font or palette, clipped tables, overflowing CJK text, blank pages, unlabeled chart values, wrong page breaks. Fix and re-render until the pages are clean. Reading the source markup is not visual QA; inspect the pixels.";+const ulwResearchOriginalDeliveryGates = "Reading the source markup is not visual QA; inspect the pixels.\n4. **Proofread gate \u2014 `task(category=\"writing\", ...)`.** Hand the final text to a dedicated `writing` worker whose only job is language: grammar, spelling, punctuation, terminology consistency, and whether the prose reads NATIVELY in the report's own language. It proofreads only and never composes. It returns a defect list; fix every item and re-run the gate on the delta. Deliver only on a clean pass \u2014 this gate runs BEFORE the first delivery, not after the user finds the typo.";+const ulwResearchCodexDeliveryGate = "Reading the source markup is not visual QA; inspect the pixels.";export const ulwExecuteOriginalCompletion = ["When all top-level checkboxes in `## TODOs` and `## Final Verification Wave` are complete:",diff --git a/plugins/omo/skills/browser/SKILL.md b/plugins/omo/skills/browser/SKILL.mdindex f68d0e1f..d74d09c4 100644--- a/plugins/omo/skills/browser/SKILL.md+++ b/plugins/omo/skills/browser/SKILL.md@@ -32,9 +32,16 @@ node "<skill-root>/scripts/browser-doctor.mjs" --json| State | Meaning | Next ||---|---|---|| `ready` | CLI, daemon and a connected browser | start a session |-| `no-cli` / `no-daemon` / `no-extension` | something is missing | `node "<skill-root>/scripts/browser-install.mjs"` prepares everything it can, then prints the **single** step only the user can do (relaunch the browser and click **Enable**); relay it verbatim, wait, re-run the doctor |+| `no-cli` / `no-daemon` / `no-extension` | something is missing | `node "<skill-root>/scripts/browser-install.mjs" [--browser=<id>]` prepares everything it can for **the browser the user uses**, then prints the **single** step only the user can do (relaunch that browser and click **Enable**); relay it verbatim, wait, re-run the doctor |+| `choose-browser` | the signals do not single out one browser (Safari/Firefox default, an idle default while another browser runs, several in use) | nothing was installed; take the browser from memory or ask the user, then `browser-install.mjs --browser=<id>` || `no-browser-support` | no Chromium-family profile on this machine | say so and stop |+**Install into the browser the user actually uses, never into whatever happens to be on disk.** Before+installing, check your memory for the user's browser; otherwise read the doctor's `browser` (picked+from the OS default browser, running apps and recent use — `candidates` shows the evidence). If memory+and the doctor disagree, or the doctor says `choose-browser`, ask the user. Pass the answer as+`--browser=<id>` and record it in memory. A Chrome that is merely installed is not their browser.+**Never launch a headless browser because the attached one is missing.** It has none of theuser's sessions, so every login turns into a ladder you should not be climbing. Say which stateyou hit and ask.diff --git a/plugins/omo/skills/browser/references/install.md b/plugins/omo/skills/browser/references/install.mdindex 637cb989..1f758da9 100644--- a/plugins/omo/skills/browser/references/install.md+++ b/plugins/omo/skills/browser/references/install.md@@ -13,18 +13,46 @@ Three pieces. The onboarding script prepares all three; a human finishes exactly| | ||---|---|| Operating systems | macOS (Apple Silicon and Intel), Linux (x64, ARM64), Windows x64 |-| Browsers | Chrome, Microsoft Edge, Brave, Chromium — any profile the doctor lists under `browsersDetected` |+| Browsers | Chrome, Microsoft Edge, Brave, Chromium, Arc, Dia, Vivaldi, Opera, Comet, Naver Whale — whichever the doctor lists under `candidates` |++## Which browser++The extension goes into exactly one browser: the one the user works in. Installed is not the same as+used — a Chrome launched once keeps its profile directory forever — so the scripts rank candidates by:++| Signal | Where it comes from |+|---|---|+| Default browser | macOS LaunchServices `https` handler, Linux `xdg-settings`, Windows `UserChoice` ProgId |+| Running now | the app in `/Applications` (macOS), the process table elsewhere |+| Used in the last 7 days | the profile's `Local State` / `History` modification time |++Order of authority:++1. **Your memory.** If you recorded the user's browser before, pass it: `--browser=<id>`.+2. **`--browser=<id>` / `OMOWRIGHT_BROWSER`** set by the user.+3. **The default browser, when it is also in use** (or nothing else is).+4. **The only browser in use** when no default can be read.++Anything else is `choose-browser` (doctor) / `needsChoice: true` (install): nothing is registered and+`candidates` lists every browser with its signals. Ask the user which one they use, run the install+with `--browser=<id>`, and save the answer to memory so the next session does not ask again. When+the default browser is Safari or Firefox, BrowserSkill cannot drive it — say so and ask which+Chromium-family browser to use.++The doctor also lists `registeredElsewhere`: browsers that still carry an entry from an older+onboarding. They are not removed automatically (removing the entry uninstalls an extension the user+may have enabled); remove one only when the user asks, with omowright's `unregisterExternalExtension`.## One command```bash-node "<skill-root>/scripts/browser-install.mjs" [--json] [--wait-ms=180000]+node "<skill-root>/scripts/browser-install.mjs" [--browser=<id>] [--json] [--wait-ms=180000]```In order it: runs upstream's official `install.sh` / `install.ps1` into `~/.local/bin` (any PATHline the installer appends to a shell rc file is reverted — the library calls the binary by-absolute path); starts the daemon with `bsk status`; and, for every Chromium-family profile it-finds, registers the Web Store listing as an external extension:+absolute path); starts the daemon with `bsk status`; and, for **the one browser the user actually+uses**, registers the Web Store listing as an external extension:| Platform | Where the entry goes | The user's one step ||---|---|---|@@ -32,6 +60,7 @@ finds, registers the Web Store listing as an external extension:| Windows | `HKCU\Software\<vendor>\<browser>\Extensions\<id>` (`reg add`, no admin) | click **Enable** on the toolbar badge; no restart || Linux (Chromium) | `<user data dir>/External Extensions/<id>.json` | relaunch; installs without a prompt || Linux (Chrome / Edge / Brave) | `/opt/google/chrome/extensions/<id>.json` and siblings — root only | otherwise open the store link it prints and click **Add** |+| Opera, and Vivaldi / Whale off macOS | no external-extension path | open the store link it prints in that browser and click **Add** |The script prints that step as `humanStep`. **Relay it verbatim and wait**; with `--wait-ms` itkeeps polling the daemon until the extension connects. An empty `browsersConnected` afterwards is@@ -57,7 +86,7 @@ engine, one of them shadowing the one that knows about omowright and this packag## Diagnosing```bash-node "<skill-root>/scripts/browser-doctor.mjs" --json # this package's view: cli, daemon, profiles, registrations, connections+node "<skill-root>/scripts/browser-doctor.mjs" --json # this package's view: cli, daemon, the user's browser + candidates, registrations, connectionsbsk doctor # upstream's own checksbsk logs # daemon log```diff --git a/plugins/omo/skills/browser/runtime/omowright/index.js b/plugins/omo/skills/browser/runtime/omowright/index.jsindex 4af7d19d..eaab9fcb 100644--- a/plugins/omo/skills/browser/runtime/omowright/index.js+++ b/plugins/omo/skills/browser/runtime/omowright/index.js@@ -1530,5 +1530,5 @@ ${snapshot.tree}`}}var DEFAULT_TIMEOUT_MS=30000;var JSON_MIME=/^application\/jsoconst css = {};for (const ref of Object.keys(result.refs || {})) css[ref] = cssPath(api.elementRegistry.get(ref));return { tree: result.tree, refs: result.refs || {}, css, error: result.error };-})()`}async function bskSnapshot(session,{tabId,timeoutMs,...snapshotOptions}={}){const reply=await session.evaluate(buildSnapshotExpression(snapshotOptions),{tabId,timeoutMs,awaitPromise:false,returnByValue:true});if(!reply||reply.ok===false){const text=reply?.error?.text??"unknown error";throw new Error(`bskSnapshot failed inside the page: ${text}`)}const value=reply.value;if(!value||typeof value.tree!=="string")throw new Error("bskSnapshot: page returned no tree");if(value.error)throw new Error(`bskSnapshot: ${value.error}`);return{tree:value.tree,refs:value.refs,css:value.css}}import{existsSync as existsSync4,mkdirSync as mkdirSync2,readFileSync as readFileSync4,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{spawn as spawn4}from"node:child_process";import path11 from"node:path";import{existsSync as existsSync3}from"node:fs";import{homedir as homedir3}from"node:os";import path10 from"node:path";var BROWSERSKILL_EXTENSION_IDS=Object.freeze({chrome:"hhcmgoofomhgciiibhipgmgkgnoenaoi",edge:"emacgiaaaiojkkpkddmmdfhmokgmnikg"});var STORE_UPDATE_URLS=Object.freeze({chrome:"https://clients2.google.com/service/update2/crx",edge:"https://edge.microsoft.com/extensionwebstorebase/v1/crx"});var STORE_PAGE_URLS=Object.freeze({chrome:`https://chromewebstore.google.com/detail/${BROWSERSKILL_EXTENSION_IDS.chrome}`,edge:`https://microsoftedge.microsoft.com/addons/detail/browserskill/${BROWSERSKILL_EXTENSION_IDS.edge}`});var MAC=[{id:"chrome",store:"chrome",userData:"Library/Application Support/Google/Chrome",binary:"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",bundleId:"com.google.Chrome"},{id:"edge",store:"edge",userData:"Library/Application Support/Microsoft Edge",binary:"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",bundleId:"com.microsoft.edgemac"},{id:"brave",store:"chrome",userData:"Library/Application Support/BraveSoftware/Brave-Browser",binary:"/Applications/Brave Browser.app/Contents/MacOS/Brave Browser",bundleId:"com.brave.Browser"},{id:"chromium",store:"chrome",userData:"Library/Application Support/Chromium",binary:"/Applications/Chromium.app/Contents/MacOS/Chromium",bundleId:"org.chromium.Chromium"}];var LINUX=[{id:"chrome",store:"chrome",userData:".config/google-chrome",binaries:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/opt/google/chrome/chrome"],externalDir:"/opt/google/chrome/extensions",userExternalDir:false},{id:"chromium",store:"chrome",userData:".config/chromium",binaries:["/usr/bin/chromium","/usr/bin/chromium-browser","/snap/bin/chromium"],externalDir:"/usr/share/chromium/extensions",userExternalDir:true},{id:"edge",store:"edge",userData:".config/microsoft-edge",binaries:["/usr/bin/microsoft-edge","/opt/microsoft/msedge/msedge"],externalDir:"/usr/share/microsoft-edge/extensions",userExternalDir:false},{id:"brave",store:"chrome",userData:".config/BraveSoftware/Brave-Browser",binaries:["/usr/bin/brave-browser","/opt/brave.com/brave/brave"],externalDir:"/usr/share/brave/extensions",userExternalDir:false}];var WINDOWS=[{id:"chrome",store:"chrome",userData:"Google/Chrome/User Data",registryKey:"HKCU\\Software\\Google\\Chrome\\Extensions",binaryRel:"Google/Chrome/Application/chrome.exe"},{id:"edge",store:"edge",userData:"Microsoft/Edge/User Data",registryKey:"HKCU\\Software\\Microsoft\\Edge\\Extensions",binaryRel:"Microsoft/Edge/Application/msedge.exe"},{id:"brave",store:"chrome",userData:"BraveSoftware/Brave-Browser/User Data",registryKey:"HKCU\\Software\\BraveSoftware\\Brave-Browser\\Extensions",binaryRel:"BraveSoftware/Brave-Browser/Application/brave.exe"}];function detectBrowsers({platform=process.platform,home=homedir3(),env=process.env,exists=existsSync3}={}){if(platform==="darwin"){return MAC.filter((b)=>exists(path10.join(home,b.userData))).map((b)=>({id:b.id,store:b.store,userDataDir:path10.join(home,b.userData),binary:b.binary,bundleId:b.bundleId}))}if(platform==="linux"){return LINUX.filter((b)=>exists(path10.join(home,b.userData))).map((b)=>({id:b.id,store:b.store,userDataDir:path10.join(home,b.userData),binary:b.binaries.find((p)=>exists(p))??null,externalDir:b.externalDir,userExternalDir:b.userExternalDir}))}if(platform==="win32"){const localAppData=env.LOCALAPPDATA??path10.join(home,"AppData","Local");const programFiles=[env.PROGRAMFILES,env["PROGRAMFILES(X86)"],"C:\\Program Files","C:\\Program Files (x86)"].filter(Boolean);return WINDOWS.filter((b)=>exists(path10.join(localAppData,b.userData))).map((b)=>({id:b.id,store:b.store,userDataDir:path10.join(localAppData,b.userData),registryKey:b.registryKey,binary:programFiles.map((root)=>path10.join(root,b.binaryRel)).find((p)=>exists(p))??null}))}return[]}var ENABLE_STEP=(browser)=>`Quit ${browser} completely and open it again; a dialog offers to enable "BrowserSkill" — click Enable.`;var BADGE_STEP=(browser)=>`In ${browser}, open the menu (the badge on the toolbar) and enable "BrowserSkill" when prompted; no restart is needed.`;function externalExtensionEntry({platform=process.platform,browser}){const id=BROWSERSKILL_EXTENSION_IDS[browser.store];const updateUrl=STORE_UPDATE_URLS[browser.store];const label=browser.id.charAt(0).toUpperCase()+browser.id.slice(1);if(platform==="win32"){const key=`${browser.registryKey}\\${id}`;return{kind:"registry",key,needsRestart:false,storeUrl:STORE_PAGE_URLS[browser.store],regAddArgs:["add",key,"/v","update_url","/t","REG_SZ","/d",updateUrl,"/f"],regDeleteArgs:["delete",key,"/f"],humanStep:BADGE_STEP(label)}}const content=JSON.stringify({external_update_url:updateUrl},null,2)+`-`;if(platform==="linux"&&!browser.userExternalDir){return{kind:"file",path:path11.join(browser.externalDir,`${id}.json`),content,needsRestart:true,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:`Quit ${label} completely and open it again; the extension installs without a prompt.`}}return{kind:"file",path:path11.join(browser.userDataDir,"External Extensions",`${id}.json`),content,needsRestart:true,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:platform==="linux"?`Quit ${label} completely and open it again; the extension installs without a prompt.`:ENABLE_STEP(label)}}function isBlocklisted(browser,id,{readFile=readFileSync4}={}){if(!browser.userDataDir)return false;for(const profile of["Default","Profile 1","Profile 2","Profile 3"]){const file=path11.join(browser.userDataDir,profile,"Preferences");let prefs;try{prefs=JSON.parse(readFile(file,"utf8"))}catch{continue}if(Array.isArray(prefs?.extensions?.external_uninstalls)&&prefs.extensions.external_uninstalls.includes(id))return true}return false}function runRegDefault(args){return new Promise((resolve)=>{const child=spawn4("reg",args,{stdio:["ignore","ignore","pipe"],windowsHide:true});let stderr="";child.stderr.on("data",(c)=>{stderr+=c});child.on("error",(error)=>resolve({code:-1,stderr:error.message}));child.on("exit",(code)=>resolve({code,stderr}))})}async function registerExternalExtension({platform=process.platform,browser,writeFile=writeFileSync2,readFile=readFileSync4,runReg=runRegDefault}={}){const entry=externalExtensionEntry({platform,browser});const id=BROWSERSKILL_EXTENSION_IDS[browser.store];const storeStep=`Open ${entry.storeUrl} in ${browser.id} and click "Add to ${browser.store==="edge"?"Edge":"Chrome"}".`;if(isBlocklisted(browser,id,{readFile})){return{...entry,registered:false,alreadyPresent:false,reason:"blocklisted",humanStep:`The extension was removed from ${browser.id} before, so external registration is ignored. ${storeStep}`}}if(entry.kind==="registry"){const result=await runReg(entry.regAddArgs);if(result.code!==0)return{...entry,registered:false,alreadyPresent:false,reason:"reg_failed",detail:result.stderr,humanStep:storeStep};return{...entry,registered:true,alreadyPresent:false}}let alreadyPresent=false;try{alreadyPresent=readFile(entry.path,"utf8")===entry.content}catch{}if(alreadyPresent)return{...entry,registered:true,alreadyPresent:true};try{mkdirSync2(path11.dirname(entry.path),{recursive:true});writeFile(entry.path,entry.content)}catch(error){if(error.code==="EACCES"||error.code==="EPERM"||error.code==="EROFS"){return{...entry,registered:false,alreadyPresent:false,reason:"not_writable",humanStep:`${entry.path} is not writable without administrator rights. ${storeStep}`}}throw error}return{...entry,registered:true,alreadyPresent:false}}async function unregisterExternalExtension({platform=process.platform,browser,runReg=runRegDefault}={}){const entry=externalExtensionEntry({platform,browser});if(entry.kind==="registry"){const result=await runReg(entry.regDeleteArgs);return{...entry,removed:result.code===0,detail:result.stderr}}const present=existsSync4(entry.path);if(present)rmSync2(entry.path,{force:true});return{...entry,removed:present}}import{existsSync as existsSync5,readFileSync as readFileSync5,rmSync as rmSync3,writeFileSync as writeFileSync3}from"node:fs";import{homedir as homedir4}from"node:os";import path12 from"node:path";import{spawn as spawn5}from"node:child_process";var INSTALL_SH="https://raw.githubusercontent.com/Tencent/BrowserSkill/main/install.sh";var INSTALL_PS1="https://raw.githubusercontent.com/Tencent/BrowserSkill/main/install.ps1";var RC_FILES=[".zshrc",".bashrc",".profile"];function cliInstallCommand({platform=process.platform,installDir,version}={}){const env={BSK_INSTALL_DIR:installDir};if(version)env.BSK_VERSION=version;if(platform==="win32"){return{command:"powershell",args:["-NoProfile","-ExecutionPolicy","Bypass","-Command",`irm ${INSTALL_PS1} | iex`],env}}return{command:"sh",args:["-c",`curl -fsSL ${INSTALL_SH} | sh`],env}}function runDefault(command,args,env){return new Promise((resolve)=>{const child=spawn5(command,args,{env:{...process.env,...env},stdio:["ignore","pipe","pipe"],windowsHide:true});let stdout="",stderr="";child.stdout.on("data",(c)=>{stdout=(stdout+c).slice(-8192)});child.stderr.on("data",(c)=>{stderr=(stderr+c).slice(-8192)});child.on("error",(error)=>resolve({code:-1,stdout,stderr:error.message}));child.on("exit",(code)=>resolve({code,stdout,stderr}))})}function snapshotRcFiles(home){const snapshot=new Map;for(const name of RC_FILES){const file=path12.join(home,name);snapshot.set(file,existsSync5(file)?readFileSync5(file):null)}return snapshot}function restoreRcFiles(snapshot){const restored=[];for(const[file,before]of snapshot){const after=existsSync5(file)?readFileSync5(file):null;if(before===null&&after===null)continue;if(before!==null&&after!==null&&before.equals(after))continue;if(before===null)rmSync3(file,{force:true});else writeFileSync3(file,before);restored.push(file)}return restored}async function installBskCli({platform=process.platform,home=homedir4(),installDir=path12.join(home,".local","bin"),version,run=runDefault}={}){const spec=cliInstallCommand({platform,installDir,version});const rcBefore=platform==="win32"?new Map:snapshotRcFiles(home);const result=await run(spec.command,spec.args,spec.env);const restoredRcFiles=restoreRcFiles(rcBefore);const bskBin=path12.join(installDir,platform==="win32"?"bsk.exe":"bsk");const installed=result.code===0&&existsSync5(bskBin);return{installed,bskBin:installed?bskBin:null,code:result.code,stdout:result.stdout,stderr:result.stderr,restoredRcFiles}}function cliVersionDefault(bskBin){return new Promise((resolve)=>{const child=spawn5(bskBin,["--version"],{stdio:["ignore","pipe","ignore"],windowsHide:true});let out="";child.stdout.on("data",(c)=>{out+=c});child.on("error",()=>resolve(null));child.on("exit",(code)=>resolve(code===0?out.trim():null))})}import{homedir as homedir5}from"node:os";import{existsSync as existsSync6,readFileSync as readFileSync6}from"node:fs";var DEFAULT_WAIT_TOTAL_MS=180000;function resolveBskBin(bskBin,env){if(bskBin===null)return null;return bskBin??findBskBinary(env)}async function cliReport({bskBin,env,cliVersion}){const bin=resolveBskBin(bskBin,env);if(!bin)return{installed:false,bskBin:null,version:null};const raw=await cliVersion(bin);return raw?{installed:true,bskBin:bin,version:raw.replace(/^bsk\s+/,"")}:{installed:false,bskBin:bin,version:null}}async function daemonReport(client,waitForBrowserMs){try{const status=await client.call("system.status",waitForBrowserMs>0?{wait_for_browser_ms:waitForBrowserMs}:{},{idPrefix:"status"});return{running:true,version:status.daemon_version,protocolVersion:status.protocol_version,browsers:status.browsers??[],sessions:status.sessions??[]}}catch(error){return{running:false,error:error.message,code:error.code,browsers:[],sessions:[]}}}function browserRows({platform,home,env}){return detectBrowsers({platform,home,env}).map((browser)=>{const entry=externalExtensionEntry({platform,browser});const extensionRegistered=entry.kind==="file"&&existsSync6(entry.path)&&readFileSync6(entry.path,"utf8")===entry.content;return{...browser,registration:entry,extensionRegistered}})}function nextStepFor({cli,daemon,browsers,browsersConnected}){if(browsersConnected.length>0)return null;if(!cli.installed)return"Install the bsk CLI (bskOnboard() runs the official installer).";if(!daemon.running)return"Start the BrowserSkill daemon: run `bsk status` once, or `bsk daemon start` in the environment that owns it.";if(browsers.length===0)return`No Chromium-family browser profile was found; install Chrome or Edge and add the extension from ${STORE_PAGE_URLS.chrome}.`;const unregistered=browsers.find((b)=>!b.extensionRegistered);if(unregistered)return`Register the BrowserSkill extension for ${unregistered.id} (bskOnboard() does this), then let the user enable it.`;return browsers[0].registration.humanStep}async function bskDoctor({platform=process.platform,home=homedir5(),env=process.env,client,bskBin,cliVersion=cliVersionDefault,waitForBrowserMs=0}={}){const cli=await cliReport({bskBin,env,cliVersion});const ipc=client??new BskIpcClient({env,bskBin:cli.bskBin??undefined,autoStart:false});const daemon=await daemonReport(ipc,waitForBrowserMs);const browsers=browserRows({platform,home,env});const browsersConnected=daemon.browsers;const report={cli,daemon,browsers,browsersConnected,ready:browsersConnected.length>0};report.nextStep=nextStepFor(report);return report}async function bskOnboard({platform=process.platform,home=homedir5(),env=process.env,client,bskBin,installDir,installCli=installBskCli,cliVersion=cliVersionDefault,onHumanStep=()=>{},waitForBrowserMs=15000,waitTotalMs=DEFAULT_WAIT_TOTAL_MS}={}){let cli=await cliReport({bskBin,env,cliVersion});let install=null;if(!cli.installed){install=await installCli({platform,home,installDir});cli=install.installed?await cliReport({bskBin:install.bskBin,env,cliVersion}):cli}const ipc=client??new BskIpcClient({env,bskBin:cli.bskBin??undefined,autoStart:true});let daemon=await daemonReport(ipc,0);const browsers=browserRows({platform,home,env});const registrations=[];let humanStep=null;if(daemon.browsers.length===0){for(const browser of browsers){const registration=await registerExternalExtension({platform,browser});registrations.push({browser:browser.id,...registration});if(!humanStep)humanStep=registration.humanStep;onHumanStep({browser:browser.id,step:registration.humanStep,registered:registration.registered,needsRestart:registration.needsRestart})}if(browsers.length===0)humanStep=`No Chromium-family browser profile was found. Install Chrome or Edge, then add the extension from ${STORE_PAGE_URLS.chrome}.`}const deadline=Date.now()+waitTotalMs;let browsersConnected=daemon.browsers;while(browsersConnected.length===0&&daemon.running&&Date.now()<deadline){browsersConnected=await listBrowsers(ipc,{waitForBrowserMs});if(waitForBrowserMs===0)break}daemon={...daemon,browsers:browsersConnected};const ready=browsersConnected.length>0;return{cli,install,daemon,browsers,registrations,humanStep:ready?null:humanStep,browsersConnected,ready}}export{AgentTabManager,BROWSERSKILL_EXTENSION_IDS,BROWSER_EVENT_NAMES,BridgeProtocolError,BridgeUnavailableError,BrowserCdpCommandError,BrowserConnection,BskIpcClient,BskRpcError,BskSession,CdpClient,CommandSchema,DEFAULT_AGENT_VIEWPORT,DEVICE_PRESETS,ElementHandle,EventSchema,ExtensionHelloSchema,FrameLocator,FrameManager,HostHelloSchema,Locator,ModifierState,OmOKeyboard,OmOMouse,OmOPage,PipeCdpClient,ResponseSchema,STORE_PAGE_URLS,SessionManager,TabRepository,UnsupportedOperationError,bskDoctor,bskOnboard,bskSnapshot,buildCloakBrowserArgs,buildSnapshotExpression,collectWhileScrolling,compactSnapshot,connect,connectBrowserSkill,connectCloakProfile,connectPipe,createAgentTabs,createBridgeClient,createCaptcha,createChromeApi2 as createChromeApi,createCua,createEvents,createNativeMessagingHost,createNetworkSnoop,createRoutes,createTrace,decodeFrames,describeLayers,detectBrowsers,emulate,encodeFrame,externalExtensionEntry,findCloakBrowserPath,injectCookies,installBskCli,installNativeMessagingHost,layersHeader,listBrowsers,macOSVisionOcr,normalizeDialogPolicy,pageBundle,readDaemonInfo,reconcileFrames,registerExternalExtension,repinViewport,requestHuman,resolveBskHome,resolveCloakProfile,resolveDialogAction,sanitizeCookies,snapshotTokens,snapshotWithFrames,snapshotWithLayers,takeSnapshot,toHar,toolSchemas,unregisterExternalExtension};+})()`}async function bskSnapshot(session,{tabId,timeoutMs,...snapshotOptions}={}){const reply=await session.evaluate(buildSnapshotExpression(snapshotOptions),{tabId,timeoutMs,awaitPromise:false,returnByValue:true});if(!reply||reply.ok===false){const text=reply?.error?.text??"unknown error";throw new Error(`bskSnapshot failed inside the page: ${text}`)}const value=reply.value;if(!value||typeof value.tree!=="string")throw new Error("bskSnapshot: page returned no tree");if(value.error)throw new Error(`bskSnapshot: ${value.error}`);return{tree:value.tree,refs:value.refs,css:value.css}}import{existsSync as existsSync4,mkdirSync as mkdirSync2,readFileSync as readFileSync4,rmSync as rmSync2,writeFileSync as writeFileSync2}from"node:fs";import{spawn as spawn4}from"node:child_process";import path11 from"node:path";import{existsSync as existsSync3}from"node:fs";import{homedir as homedir3}from"node:os";import path10 from"node:path";var BROWSERSKILL_EXTENSION_IDS=Object.freeze({chrome:"hhcmgoofomhgciiibhipgmgkgnoenaoi",edge:"emacgiaaaiojkkpkddmmdfhmokgmnikg"});var STORE_UPDATE_URLS=Object.freeze({chrome:"https://clients2.google.com/service/update2/crx",edge:"https://edge.microsoft.com/extensionwebstorebase/v1/crx"});var STORE_PAGE_URLS=Object.freeze({chrome:`https://chromewebstore.google.com/detail/${BROWSERSKILL_EXTENSION_IDS.chrome}`,edge:`https://microsoftedge.microsoft.com/addons/detail/browserskill/${BROWSERSKILL_EXTENSION_IDS.edge}`});var NON_CHROMIUM_DEFAULTS=Object.freeze([{id:"safari",label:"Safari",match:["com.apple.safari","safarihtml"]},{id:"firefox",label:"Firefox",match:["org.mozilla.firefox","firefox.desktop","firefoxurl","firefoxhtml"]},{id:"zen",label:"Zen",match:["app.zen-browser.zen","zen.desktop","zenhtml"]},{id:"orion",label:"Orion",match:["com.kagi.kagimacos"]}]);var MAC=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:"Library/Application Support/Google/Chrome",app:"Google Chrome",bundleId:"com.google.Chrome"},{id:"edge",label:"Microsoft Edge",store:"edge",userData:"Library/Application Support/Microsoft Edge",app:"Microsoft Edge",bundleId:"com.microsoft.edgemac"},{id:"brave",label:"Brave",store:"chrome",userData:"Library/Application Support/BraveSoftware/Brave-Browser",app:"Brave Browser",bundleId:"com.brave.Browser"},{id:"chromium",label:"Chromium",store:"chrome",userData:"Library/Application Support/Chromium",app:"Chromium",bundleId:"org.chromium.Chromium"},{id:"arc",label:"Arc",store:"chrome",userData:"Library/Application Support/Arc/User Data",app:"Arc",bundleId:"company.thebrowser.Browser"},{id:"dia",label:"Dia",store:"chrome",userData:"Library/Application Support/Dia/User Data",app:"Dia",bundleId:"company.thebrowser.dia"},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:"Library/Application Support/Vivaldi",app:"Vivaldi",bundleId:"com.vivaldi.Vivaldi"},{id:"opera",label:"Opera",store:"chrome",userData:"Library/Application Support/com.operasoftware.Opera",app:"Opera",bundleId:"com.operasoftware.Opera",externalExtensions:false},{id:"comet",label:"Comet",store:"chrome",userData:"Library/Application Support/Comet",app:"Comet",bundleId:"ai.perplexity.comet"},{id:"aside",label:"Aside",store:"chrome",userData:"Library/Application Support/Aside",app:"Aside",bundleId:"at.studio.AsideBrowser"},{id:"whale",label:"Naver Whale",store:"chrome",userData:"Library/Application Support/Naver/Whale",app:"Naver Whale",bundleId:"com.naver.Whale"}];var LINUX=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:".config/google-chrome",binaries:["/usr/bin/google-chrome","/usr/bin/google-chrome-stable","/opt/google/chrome/chrome"],externalDir:"/opt/google/chrome/extensions",userExternalDir:false,desktopIds:["google-chrome.desktop","google-chrome-stable.desktop","com.google.Chrome.desktop"],processNames:["chrome","google-chrome"]},{id:"chromium",label:"Chromium",store:"chrome",userData:".config/chromium",binaries:["/usr/bin/chromium","/usr/bin/chromium-browser","/snap/bin/chromium"],externalDir:"/usr/share/chromium/extensions",userExternalDir:true,desktopIds:["chromium.desktop","chromium-browser.desktop","chromium_chromium.desktop","org.chromium.Chromium.desktop"],processNames:["chromium","chromium-browse"]},{id:"edge",label:"Microsoft Edge",store:"edge",userData:".config/microsoft-edge",binaries:["/usr/bin/microsoft-edge","/opt/microsoft/msedge/msedge"],externalDir:"/usr/share/microsoft-edge/extensions",userExternalDir:false,desktopIds:["microsoft-edge.desktop","microsoft-edge-stable.desktop","com.microsoft.Edge.desktop"],processNames:["msedge"]},{id:"brave",label:"Brave",store:"chrome",userData:".config/BraveSoftware/Brave-Browser",binaries:["/usr/bin/brave-browser","/opt/brave.com/brave/brave"],externalDir:"/usr/share/brave/extensions",userExternalDir:false,desktopIds:["brave-browser.desktop","com.brave.Browser.desktop"],processNames:["brave"]},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:".config/vivaldi",binaries:["/usr/bin/vivaldi","/opt/vivaldi/vivaldi"],externalDir:null,userExternalDir:false,externalExtensions:false,desktopIds:["vivaldi-stable.desktop","vivaldi.desktop"],processNames:["vivaldi-bin"]},{id:"opera",label:"Opera",store:"chrome",userData:".config/opera",binaries:["/usr/bin/opera"],externalDir:null,userExternalDir:false,externalExtensions:false,desktopIds:["opera.desktop"],processNames:["opera"]}];var WINDOWS=[{id:"chrome",label:"Google Chrome",store:"chrome",userData:"Google/Chrome/User Data",registryKey:"HKCU\\Software\\Google\\Chrome\\Extensions",binaryRel:"Google/Chrome/Application/chrome.exe",progIds:["chromehtml"],processNames:["chrome.exe"]},{id:"edge",label:"Microsoft Edge",store:"edge",userData:"Microsoft/Edge/User Data",registryKey:"HKCU\\Software\\Microsoft\\Edge\\Extensions",binaryRel:"Microsoft/Edge/Application/msedge.exe",progIds:["msedgehtm"],processNames:["msedge.exe"]},{id:"brave",label:"Brave",store:"chrome",userData:"BraveSoftware/Brave-Browser/User Data",registryKey:"HKCU\\Software\\BraveSoftware\\Brave-Browser\\Extensions",binaryRel:"BraveSoftware/Brave-Browser/Application/brave.exe",progIds:["bravehtml"],processNames:["brave.exe"]},{id:"chromium",label:"Chromium",store:"chrome",userData:"Chromium/User Data",registryKey:"HKCU\\Software\\Chromium\\Extensions",binaryRel:"Chromium/Application/chrome.exe",progIds:["chromiumhtm"],processNames:[]},{id:"vivaldi",label:"Vivaldi",store:"chrome",userData:"Vivaldi/User Data",registryKey:null,externalExtensions:false,binaryRel:"Vivaldi/Application/vivaldi.exe",progIds:["vivaldihtm"],processNames:["vivaldi.exe"]},{id:"whale",label:"Naver Whale",store:"chrome",userData:"Naver/Naver Whale/User Data",registryKey:null,externalExtensions:false,binaryRel:"Naver/Naver Whale/Application/whale.exe",progIds:["whalehtml"],processNames:["whale.exe"]}];var BROWSER_IDS=Object.freeze([...new Set([...MAC,...LINUX,...WINDOWS].map((b)=>b.id))]);function macRow(b,home,exists){const apps=[path10.join("/Applications",`${b.app}.app`),path10.join(home,"Applications",`${b.app}.app`)];const appPath=apps.find((p)=>exists(p))??null;const userDataDir=path10.join(home,b.userData);return{id:b.id,label:b.label,store:b.store,userDataDir,binary:path10.join(appPath??apps[0],"Contents","MacOS",b.app),bundleId:b.bundleId,processNames:apps.map((a)=>path10.join(a,"Contents","MacOS",b.app)),defaultIds:[b.bundleId.toLowerCase()],externalExtensions:b.externalExtensions!==false,installed:appPath!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function linuxRow(b,home,exists){const userDataDir=path10.join(home,b.userData);const binary=b.binaries.find((p)=>exists(p))??null;return{id:b.id,label:b.label,store:b.store,userDataDir,binary,externalDir:b.externalDir,userExternalDir:b.userExternalDir,processNames:b.processNames,defaultIds:b.desktopIds.map((d)=>d.toLowerCase()),externalExtensions:b.externalExtensions!==false,installed:binary!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function windowsRow(b,env,home,exists){const localAppData=env.LOCALAPPDATA??path10.join(home,"AppData","Local");const programFiles=[localAppData,env.PROGRAMFILES,env["PROGRAMFILES(X86)"],"C:\\Program Files","C:\\Program Files (x86)"].filter(Boolean);const userDataDir=path10.join(localAppData,b.userData);const binary=programFiles.map((root)=>path10.join(root,b.binaryRel)).find((p)=>exists(p))??null;return{id:b.id,label:b.label,store:b.store,userDataDir,registryKey:b.registryKey,binary,processNames:b.processNames,defaultIds:b.progIds,externalExtensions:b.externalExtensions!==false,installed:binary!==null||exists(userDataDir),hasProfile:exists(userDataDir)}}function catalogBrowsers({platform=process.platform,home=homedir3(),env=process.env,exists=existsSync3}={}){if(platform==="darwin")return MAC.map((b)=>macRow(b,home,exists));if(platform==="linux")return LINUX.map((b)=>linuxRow(b,home,exists));if(platform==="win32")return WINDOWS.map((b)=>windowsRow(b,env,home,exists));return[]}function detectBrowsers(options={}){return catalogBrowsers(options).filter((b)=>b.installed)}var ENABLE_STEP=(browser)=>`Quit ${browser} completely and open it again; a dialog offers to enable "BrowserSkill" — click Enable.`;var BADGE_STEP=(browser)=>`In ${browser}, open the menu (the badge on the toolbar) and enable "BrowserSkill" when prompted; no restart is needed.`;var storeStep=(browser,label)=>`Open ${STORE_PAGE_URLS[browser.store]} in ${label} and click the "Add" button.`;function externalExtensionEntry({platform=process.platform,browser}){const id=BROWSERSKILL_EXTENSION_IDS[browser.store];const updateUrl=STORE_UPDATE_URLS[browser.store];const label=browser.label??browser.id.charAt(0).toUpperCase()+browser.id.slice(1);if(browser.externalExtensions===false){return{kind:"store",needsRestart:false,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:storeStep(browser,label)}}if(platform==="win32"){const key=`${browser.registryKey}\\${id}`;return{kind:"registry",key,needsRestart:false,storeUrl:STORE_PAGE_URLS[browser.store],regAddArgs:["add",key,"/v","update_url","/t","REG_SZ","/d",updateUrl,"/f"],regDeleteArgs:["delete",key,"/f"],humanStep:BADGE_STEP(label)}}const content=JSON.stringify({external_update_url:updateUrl},null,2)+`+`;if(platform==="linux"&&!browser.userExternalDir){return{kind:"file",path:path11.join(browser.externalDir,`${id}.json`),content,needsRestart:true,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:`Quit ${label} completely and open it again; the extension installs without a prompt.`}}return{kind:"file",path:path11.join(browser.userDataDir,"External Extensions",`${id}.json`),content,needsRestart:true,storeUrl:STORE_PAGE_URLS[browser.store],humanStep:platform==="linux"?`Quit ${label} completely and open it again; the extension installs without a prompt.`:ENABLE_STEP(label)}}function isBlocklisted(browser,id,{readFile=readFileSync4}={}){if(!browser.userDataDir)return false;for(const profile of["Default","Profile 1","Profile 2","Profile 3"]){const file=path11.join(browser.userDataDir,profile,"Preferences");let prefs;try{prefs=JSON.parse(readFile(file,"utf8"))}catch{continue}if(Array.isArray(prefs?.extensions?.external_uninstalls)&&prefs.extensions.external_uninstalls.includes(id))return true}return false}function runRegDefault(args){return new Promise((resolve)=>{const child=spawn4("reg",args,{stdio:["ignore","ignore","pipe"],windowsHide:true});let stderr="";child.stderr.on("data",(c)=>{stderr+=c});child.on("error",(error)=>resolve({code:-1,stderr:error.message}));child.on("exit",(code)=>resolve({code,stderr}))})}async function registerExternalExtension({platform=process.platform,browser,writeFile=writeFileSync2,readFile=readFileSync4,runReg=runRegDefault}={}){const entry=externalExtensionEntry({platform,browser});const id=BROWSERSKILL_EXTENSION_IDS[browser.store];const label=browser.label??browser.id;const storeStep=`Open ${entry.storeUrl} in ${label} and click the "Add" button.`;if(entry.kind==="store")return{...entry,registered:false,alreadyPresent:false,reason:"store_only"};if(isBlocklisted(browser,id,{readFile})){return{...entry,registered:false,alreadyPresent:false,reason:"blocklisted",humanStep:`The extension was removed from ${label} before, so external registration is ignored. ${storeStep}`}}if(entry.kind==="registry"){const result=await runReg(entry.regAddArgs);if(result.code!==0)return{...entry,registered:false,alreadyPresent:false,reason:"reg_failed",detail:result.stderr,humanStep:storeStep};return{...entry,registered:true,alreadyPresent:false}}let alreadyPresent=false;try{alreadyPresent=readFile(entry.path,"utf8")===entry.content}catch{}if(alreadyPresent)return{...entry,registered:true,alreadyPresent:true};try{mkdirSync2(path11.dirname(entry.path),{recursive:true});writeFile(entry.path,entry.content)}catch(error){if(error.code==="EACCES"||error.code==="EPERM"||error.code==="EROFS"){return{...entry,registered:false,alreadyPresent:false,reason:"not_writable",humanStep:`${entry.path} is not writable without administrator rights. ${storeStep}`}}throw error}return{...entry,registered:true,alreadyPresent:false}}async function unregisterExternalExtension({platform=process.platform,browser,runReg=runRegDefault}={}){const entry=externalExtensionEntry({platform,browser});if(entry.kind==="store")return{...entry,removed:false};if(entry.kind==="registry"){const result=await runReg(entry.regDeleteArgs);return{...entry,removed:result.code===0,detail:result.stderr}}const present=existsSync4(entry.path);if(present)rmSync2(entry.path,{force:true});return{...entry,removed:present}}import{execFile}from"node:child_process";import{statSync}from"node:fs";import{homedir as homedir4}from"node:os";import path12 from"node:path";var PROBE_TIMEOUT_MS=3000;function runDefault(command,args){return new Promise((resolve)=>{execFile(command,args,{timeout:PROBE_TIMEOUT_MS,windowsHide:true,maxBuffer:8*1024*1024},(error,stdout)=>{resolve(error?null:String(stdout))})})}function parseMacDefaultBrowser(plistJson){let handlers;try{handlers=JSON.parse(plistJson)?.LSHandlers}catch{return null}if(!Array.isArray(handlers))return null;const pick=(scheme)=>handlers.find((h)=>h?.LSHandlerURLScheme===scheme&&typeof h.LSHandlerRoleAll==="string");const handler=pick("https")??pick("http");return handler?handler.LSHandlerRoleAll.toLowerCase():"com.apple.safari"}function parseWindowsProgId(regOutput){const match=/ProgId\s+REG_SZ\s+(\S+)/i.exec(regOutput??"");return match?match[1].toLowerCase():null}function parseProcessNames(platform,output){const names=new Set;for(const raw of String(output??"").split(/\r?\n/)){const line=raw.trim();if(!line)continue;if(platform==="win32"){const image=/^"([^"]+)"/.exec(line)?.[1];if(image)names.add(image.toLowerCase())}else if(platform==="darwin"){if(/\.app\/Contents\/MacOS\/[^/]+$/.test(line))names.add(line)}else{names.add(path12.basename(line))}}return[...names]}async function probeDefault({platform,home,run}){if(platform==="darwin"){const plist=path12.join(home,"Library/Preferences/com.apple.LaunchServices/com.apple.launchservices.secure.plist");const json=await run("plutil",["-convert","json","-o","-",plist]);return json===null?null:parseMacDefaultBrowser(json)}if(platform==="linux"){const out=await run("xdg-settings",["get","default-web-browser"]);return out?.trim()?out.trim().toLowerCase():null}if(platform==="win32"){const key="HKCU\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\https\\UserChoice";return parseWindowsProgId(await run("reg",["query",key,"/v","ProgId"]))}return null}async function probeRunning({platform,run}){const out=platform==="win32"?await run("tasklist",["/fo","csv","/nh"]):await run("ps",platform==="darwin"?["-axo","comm="]:["-eo","comm="]);return out===null?null:parseProcessNames(platform,out)}function lastUsedAt(browser,stat){let latest=null;for(const rel of["Local State",path12.join("Default","History"),path12.join("Default","Preferences")]){try{const mtime=stat(path12.join(browser.userDataDir,rel)).mtimeMs;if(latest===null||mtime>latest)latest=mtime}catch{}}return latest}async function probeBrowserSignals({platform=process.platform,home=homedir4(),browsers=[],run=runDefault,stat=statSync}={}){const[defaultBrowser,running]=await Promise.all([probeDefault({platform,home,run}),probeRunning({platform,run})]);const lastUsed=Object.fromEntries(browsers.map((b)=>[b.id,lastUsedAt(b,stat)]));return{defaultBrowser,running,lastUsed}}var RECENT_USE_MS=7*24*60*60*1000;function matchesDefault(browser,defaultId){if(!defaultId)return false;return browser.defaultIds.some((id)=>defaultId===id||defaultId.startsWith(id))}function describeDefault(defaultId,catalog){if(defaultId===null||defaultId===undefined)return{raw:null,id:null,label:null,supported:null};const hit=catalog.find((b)=>matchesDefault(b,defaultId));if(hit)return{raw:defaultId,id:hit.id,label:hit.label,supported:true};const other=NON_CHROMIUM_DEFAULTS.find((b)=>b.match.some((m)=>defaultId===m||defaultId.startsWith(m)));return other?{raw:defaultId,id:other.id,label:other.label,supported:false}:{raw:defaultId,id:null,label:defaultId,supported:false}}function candidateRow(browser,{defaultBrowser,running,lastUsed},now){const isDefault=defaultBrowser.id===browser.id;const isRunning=Array.isArray(running)?browser.processNames.some((n)=>running.includes(n)||running.includes(n.toLowerCase())):null;const last=lastUsed?.[browser.id]??null;const recentlyUsed=last!==null&&now-last<=RECENT_USE_MS;const signals=[isDefault&&"default browser",isRunning&&"running now",recentlyUsed&&"used in the last 7 days"].filter(Boolean);return{id:browser.id,label:browser.label,installed:browser.installed,isDefault,running:isRunning,lastUsedAt:last===null?null:new Date(last).toISOString(),recentlyUsed,signals,browser}}function choose(candidates,primary,confidence,reason,defaultBrowser){return{primary:primary.browser,primaryId:primary.id,confidence,needsChoice:false,reason,defaultBrowser,candidates:candidates.map(({browser,...row})=>row)}}function ask(candidates,reason,defaultBrowser,suggested=null){return{primary:null,primaryId:null,confidence:null,needsChoice:true,reason,suggested,defaultBrowser,candidates:candidates.map(({browser,...row})=>row)}}function identifyBrowser({catalog,signals={},explicit=null,now=Date.now()}){const defaultBrowser=describeDefault(signals.defaultBrowser??null,catalog);const installed=catalog.filter((b)=>b.installed||b.id===explicit);const candidates=installed.map((b)=>candidateRow(b,{defaultBrowser,running:signals.running??null,lastUsed:signals.lastUsed},now));if(explicit){const hit=candidates.find((c)=>c.id===explicit);if(hit)return choose(candidates,hit,"explicit",`${hit.label} was chosen explicitly`,defaultBrowser);return ask(candidates,`"${explicit}" is not a Chromium-family browser this library knows; pick one of the candidates`,defaultBrowser)}if(candidates.length===0)return ask(candidates,"no Chromium-family browser is installed",defaultBrowser);const inUse=candidates.filter((c)=>c.running||c.recentlyUsed);const def=candidates.find((c)=>c.isDefault);if(def&&(def.running||def.recentlyUsed))return choose(candidates,def,"default-and-in-use",`${def.label} is the default browser and ${def.signals.slice(1).join(", ")}`,defaultBrowser);if(def&&inUse.length===0)return choose(candidates,def,"default",`${def.label} is the default browser`,defaultBrowser);if(def)return ask(candidates,`${def.label} is the default browser, but ${inUse.map((c)=>c.label).join(" and ")} ${inUse.length===1?"is":"are"} the one in use`,defaultBrowser);if(defaultBrowser.supported===false){const suggested=inUse.length===1?inUse[0].id:null;return ask(candidates,`the default browser is ${defaultBrowser.label}, which BrowserSkill cannot drive; the user has to name the Chromium browser to use`,defaultBrowser,suggested)}const runningNow=inUse.filter((c)=>c.running);if(inUse.length===1)return choose(candidates,inUse[0],"only-in-use",`${inUse[0].label} is the only browser ${inUse[0].signals.join(", ")}`,defaultBrowser);if(runningNow.length===1)return choose(candidates,runningNow[0],"only-running",`${runningNow[0].label} is the only browser running now`,defaultBrowser);if(inUse.length===0&&candidates.length===1)return choose(candidates,candidates[0],"only-installed",`${candidates[0].label} is the only Chromium-family browser installed`,defaultBrowser);return ask(candidates,inUse.length>1?`several browsers are in use (${inUse.map((c)=>c.label).join(", ")})`:"no browser shows recent use",defaultBrowser)}import{existsSync as existsSync5,readFileSync as readFileSync5,rmSync as rmSync3,writeFileSync as writeFileSync3}from"node:fs";import{homedir as homedir5}from"node:os";import path13 from"node:path";import{spawn as spawn5}from"node:child_process";var INSTALL_SH="https://raw.githubusercontent.com/Tencent/BrowserSkill/main/install.sh";var INSTALL_PS1="https://raw.githubusercontent.com/Tencent/BrowserSkill/main/install.ps1";var RC_FILES=[".zshrc",".bashrc",".profile"];function cliInstallCommand({platform=process.platform,installDir,version}={}){const env={BSK_INSTALL_DIR:installDir};if(version)env.BSK_VERSION=version;if(platform==="win32"){return{command:"powershell",args:["-NoProfile","-ExecutionPolicy","Bypass","-Command",`irm ${INSTALL_PS1} | iex`],env}}return{command:"sh",args:["-c",`curl -fsSL ${INSTALL_SH} | sh`],env}}function runDefault2(command,args,env){return new Promise((resolve)=>{const child=spawn5(command,args,{env:{...process.env,...env},stdio:["ignore","pipe","pipe"],windowsHide:true});let stdout="",stderr="";child.stdout.on("data",(c)=>{stdout=(stdout+c).slice(-8192)});child.stderr.on("data",(c)=>{stderr=(stderr+c).slice(-8192)});child.on("error",(error)=>resolve({code:-1,stdout,stderr:error.message}));child.on("exit",(code)=>resolve({code,stdout,stderr}))})}function snapshotRcFiles(home){const snapshot=new Map;for(const name of RC_FILES){const file=path13.join(home,name);snapshot.set(file,existsSync5(file)?readFileSync5(file):null)}return snapshot}function restoreRcFiles(snapshot){const restored=[];for(const[file,before]of snapshot){const after=existsSync5(file)?readFileSync5(file):null;if(before===null&&after===null)continue;if(before!==null&&after!==null&&before.equals(after))continue;if(before===null)rmSync3(file,{force:true});else writeFileSync3(file,before);restored.push(file)}return restored}async function installBskCli({platform=process.platform,home=homedir5(),installDir=path13.join(home,".local","bin"),version,run=runDefault2}={}){const spec=cliInstallCommand({platform,installDir,version});const rcBefore=platform==="win32"?new Map:snapshotRcFiles(home);const result=await run(spec.command,spec.args,spec.env);const restoredRcFiles=restoreRcFiles(rcBefore);const bskBin=path13.join(installDir,platform==="win32"?"bsk.exe":"bsk");const installed=result.code===0&&existsSync5(bskBin);return{installed,bskBin:installed?bskBin:null,code:result.code,stdout:result.stdout,stderr:result.stderr,restoredRcFiles}}function cliVersionDefault(bskBin){return new Promise((resolve)=>{const child=spawn5(bskBin,["--version"],{stdio:["ignore","pipe","ignore"],windowsHide:true});let out="";child.stdout.on("data",(c)=>{out+=c});child.on("error",()=>resolve(null));child.on("exit",(code)=>resolve(code===0?out.trim():null))})}import{homedir as homedir6}from"node:os";import{existsSync as existsSync6,readFileSync as readFileSync6}from"node:fs";var DEFAULT_WAIT_TOTAL_MS=180000;function resolveBskBin(bskBin,env){if(bskBin===null)return null;return bskBin??findBskBinary(env)}async function cliReport({bskBin,env,cliVersion}){const bin=resolveBskBin(bskBin,env);if(!bin)return{installed:false,bskBin:null,version:null};const raw=await cliVersion(bin);return raw?{installed:true,bskBin:bin,version:raw.replace(/^bsk\s+/,"")}:{installed:false,bskBin:bin,version:null}}async function daemonReport(client,waitForBrowserMs){try{const status=await client.call("system.status",waitForBrowserMs>0?{wait_for_browser_ms:waitForBrowserMs}:{},{idPrefix:"status"});return{running:true,version:status.daemon_version,protocolVersion:status.protocol_version,browsers:status.browsers??[],sessions:status.sessions??[]}}catch(error){return{running:false,error:error.message,code:error.code,browsers:[],sessions:[]}}}var NO_BROWSER_STEP=`No Chromium-family browser was found. Install one (Chrome, Edge, Brave, Arc, ...), then add the extension from ${STORE_PAGE_URLS.chrome}.`;function withRegistration(platform,browser){const entry=externalExtensionEntry({platform,browser});const extensionRegistered=entry.kind==="file"&&existsSync6(entry.path)&&readFileSync6(entry.path,"utf8")===entry.content;return{...browser,registration:entry,extensionRegistered}}async function identify({platform,home,env,exists,browser,signals,probeSignals,now}){const catalog=catalogBrowsers({platform,home,env,exists}).map((b)=>withRegistration(platform,b));const observed=signals??await probeSignals({platform,home,browsers:catalog.filter((b)=>b.hasProfile)});const explicit=browser??env.OMOWRIGHT_BROWSER??null;const{primary,...identification}=identifyBrowser({catalog,signals:observed,explicit:explicit||null,now});const browsers=catalog.filter((b)=>b.installed);const registeredElsewhere=browsers.filter((b)=>b.extensionRegistered&&b.id!==identification.primaryId).map((b)=>b.id);return{browsers,identification:{...identification,registeredElsewhere},primary}}function choiceStep(identification){const listed=identification.candidates.map((c)=>`${c.label} [${c.id}]${c.signals.length?` — ${c.signals.join(", ")}`:""}`).join("; ");const hint=identification.suggested?` Likely ${identification.suggested}, but confirm first.`:"";return`Ask the user which browser they actually use (${identification.reason}). Candidates: ${listed}.${hint} Then re-run with browser: "<id>"; register nothing until they answer.`}function nextStepFor({cli,daemon,browsers,browsersConnected,identification,primary}){if(browsersConnected.length>0)return null;if(!cli.installed)return"Install the bsk CLI (bskOnboard() runs the official installer).";if(!daemon.running)return"Start the BrowserSkill daemon: run `bsk status` once, or `bsk daemon start` in the environment that owns it.";if(browsers.length===0&&!primary)return NO_BROWSER_STEP;if(identification.needsChoice)return choiceStep(identification);if(!primary.extensionRegistered&&primary.registration.kind!=="store")return`Register the BrowserSkill extension for ${primary.label} (bskOnboard() does this), then let the user enable it.`;return primary.registration.humanStep}async function bskDoctor({platform=process.platform,home=homedir6(),env=process.env,client,bskBin,cliVersion=cliVersionDefault,waitForBrowserMs=0,exists=existsSync6,browser,signals,probeSignals=probeBrowserSignals,now=Date.now()}={}){const cli=await cliReport({bskBin,env,cliVersion});const ipc=client??new BskIpcClient({env,bskBin:cli.bskBin??undefined,autoStart:false});const daemon=await daemonReport(ipc,waitForBrowserMs);const{browsers,identification,primary}=await identify({platform,home,env,exists,browser,signals,probeSignals,now});const browsersConnected=daemon.browsers;const report={cli,daemon,browsers,primary:primary??null,identification,browsersConnected,ready:browsersConnected.length>0};report.nextStep=nextStepFor(report);return report}async function bskOnboard({platform=process.platform,home=homedir6(),env=process.env,client,bskBin,installDir,installCli=installBskCli,cliVersion=cliVersionDefault,onHumanStep=()=>{},waitForBrowserMs=15000,waitTotalMs=DEFAULT_WAIT_TOTAL_MS,exists=existsSync6,browser,signals,probeSignals=probeBrowserSignals,now=Date.now()}={}){let cli=await cliReport({bskBin,env,cliVersion});let install=null;if(!cli.installed){install=await installCli({platform,home,installDir});cli=install.installed?await cliReport({bskBin:install.bskBin,env,cliVersion}):cli}const ipc=client??new BskIpcClient({env,bskBin:cli.bskBin??undefined,autoStart:true});let daemon=await daemonReport(ipc,0);const{browsers,identification,primary}=await identify({platform,home,env,exists,browser,signals,probeSignals,now});const registrations=[];let humanStep=null;let needsChoice=false;if(daemon.browsers.length===0){if(browsers.length===0&&!primary){humanStep=NO_BROWSER_STEP}else if(identification.needsChoice){needsChoice=true;humanStep=choiceStep(identification)}else{const registration=await registerExternalExtension({platform,browser:primary});registrations.push({browser:primary.id,...registration});humanStep=registration.humanStep;onHumanStep({browser:primary.id,step:registration.humanStep,registered:registration.registered,needsRestart:registration.needsRestart})}}const deadline=Date.now()+waitTotalMs;let browsersConnected=daemon.browsers;while(!needsChoice&&browsersConnected.length===0&&daemon.running&&Date.now()<deadline){browsersConnected=await listBrowsers(ipc,{waitForBrowserMs});if(waitForBrowserMs===0)break}daemon={...daemon,browsers:browsersConnected};const ready=browsersConnected.length>0;return{cli,install,daemon,browsers,primary:primary??null,identification,needsChoice,registrations,humanStep:ready?null:humanStep,browsersConnected,ready}}export{AgentTabManager,BROWSERSKILL_EXTENSION_IDS,BROWSER_EVENT_NAMES,BridgeProtocolError,BridgeUnavailableError,BrowserCdpCommandError,BrowserConnection,BskIpcClient,BskRpcError,BskSession,CdpClient,CommandSchema,DEFAULT_AGENT_VIEWPORT,DEVICE_PRESETS,ElementHandle,EventSchema,ExtensionHelloSchema,FrameLocator,FrameManager,HostHelloSchema,Locator,ModifierState,OmOKeyboard,OmOMouse,OmOPage,PipeCdpClient,ResponseSchema,STORE_PAGE_URLS,SessionManager,TabRepository,UnsupportedOperationError,bskDoctor,bskOnboard,bskSnapshot,buildCloakBrowserArgs,buildSnapshotExpression,catalogBrowsers,collectWhileScrolling,compactSnapshot,connect,connectBrowserSkill,connectCloakProfile,connectPipe,createAgentTabs,createBridgeClient,createCaptcha,createChromeApi2 as createChromeApi,createCua,createEvents,createNativeMessagingHost,createNetworkSnoop,createRoutes,createTrace,decodeFrames,describeLayers,detectBrowsers,emulate,encodeFrame,externalExtensionEntry,findCloakBrowserPath,identifyBrowser,injectCookies,installBskCli,installNativeMessagingHost,layersHeader,listBrowsers,macOSVisionOcr,normalizeDialogPolicy,pageBundle,probeBrowserSignals,readDaemonInfo,reconcileFrames,registerExternalExtension,repinViewport,requestHuman,resolveBskHome,resolveCloakProfile,resolveDialogAction,sanitizeCookies,snapshotTokens,snapshotWithFrames,snapshotWithLayers,takeSnapshot,toHar,toolSchemas,unregisterExternalExtension};diff --git a/plugins/omo/skills/browser/runtime/omowright/manifest.json b/plugins/omo/skills/browser/runtime/omowright/manifest.jsonindex bbed968c..32e25bee 100644--- a/plugins/omo/skills/browser/runtime/omowright/manifest.json+++ b/plugins/omo/skills/browser/runtime/omowright/manifest.json@@ -1,9 +1,9 @@{"version": "0.0.1",- "sourceDigest": "d7a2321ffe176d23eca65e5cc9b25e161e904479e6515fc585ae4d3544d26469",+ "sourceDigest": "167dcc331041e909a54c6e9695ea8d09bbb96bc351d62333d7ac628f780b83f6","files": {- "index.js": "50c5bfd675ab5c42a7497e5fe3411e52e764277a5c50342a872d917f3f22777c",+ "index.js": "b6b064fab277031c6c51f5a58b84b31040f9960bf767bf646adc0540c1d25c1b","page-bundle.js": "bfd51e8383cf47200d57387bbbed258bce5a3a3d00c38fc108034d2888e23f0c"},- "stagedAtUtc": "2026-09-24T07:16:04.853Z"+ "stagedAtUtc": "2026-09-24T23:46:09.282Z"}diff --git a/plugins/omo/skills/browser/scripts/browser-doctor.mjs b/plugins/omo/skills/browser/scripts/browser-doctor.mjsindex 2d4c84bf..277c137d 100755--- a/plugins/omo/skills/browser/scripts/browser-doctor.mjs+++ b/plugins/omo/skills/browser/scripts/browser-doctor.mjs@@ -2,7 +2,8 @@import { loadOmowright } from "./omowright.mjs"const { entry, omowright } = await loadOmowright()-const report = await omowright.bskDoctor({ waitForBrowserMs: 0 })+const browserArg = process.argv.find((arg) => arg.startsWith("--browser="))+const report = await omowright.bskDoctor({ waitForBrowserMs: 0, browser: browserArg ? browserArg.slice("--browser=".length) : undefined })const state = report.ready? "ready"@@ -10,15 +11,18 @@ const state = report.ready? "no-cli": !report.daemon.running? "no-daemon"- : report.browsers.length === 0+ : report.browsers.length === 0 && !report.primary? "no-browser-support"- : "no-extension"+ : report.identification.needsChoice+ ? "choose-browser"+ : "no-extension"const REMEDIES = {ready: "Attached engine is live: const { connectBrowserSkill } = await import(omowrightEntry); const session = await connectBrowserSkill({ name: \"<task>\", focused: false })","no-cli": "Run node \"<skill-root>/scripts/browser-install.mjs\" — it installs the CLI, starts the daemon and registers the extension; then tell the user the single step it prints.","no-daemon": "Run node \"<skill-root>/scripts/browser-install.mjs\" (it starts the daemon through `bsk status`), then re-run this doctor.","no-extension": report.nextStep ?? "Register the extension with browser-install.mjs, then relay its human step to the user and re-run this doctor.",+ "choose-browser": `Do not install anything yet. First check your memory for the browser this user works in; if it names one of the candidates, re-run with --browser=<id>. Otherwise ask the user which browser they actually use (${report.identification.reason}), record the answer in memory, then run node "<skill-root>/scripts/browser-install.mjs" --browser=<id>.`,"no-browser-support": "No Chromium-family browser profile was found on this machine. Say so and stop; do not substitute another engine.",}@@ -27,6 +31,10 @@ const summary = {omowright: entry,cli: report.cli,daemon: { running: report.daemon.running, version: report.daemon.version ?? null, protocolVersion: report.daemon.protocolVersion ?? null, error: report.daemon.error ?? null },+ browser: report.primary ? { id: report.primary.id, label: report.primary.label, confidence: report.identification.confidence, reason: report.identification.reason } : null,+ candidates: report.identification.candidates.map((c) => ({ id: c.id, label: c.label, signals: c.signals })),+ defaultBrowser: report.identification.defaultBrowser,+ registeredElsewhere: report.identification.registeredElsewhere,browsersDetected: report.browsers.map((browser) => ({ id: browser.id, userDataDir: browser.userDataDir, extensionRegistered: browser.extensionRegistered })),browsersConnected: report.browsersConnected.map((browser) => ({ instanceId: browser.instance_id, name: browser.browser_name, version: browser.browser_version })),nextStep: report.nextStep,@@ -40,6 +48,9 @@ if (process.argv.includes("--json")) {console.log(`omowright: ${entry}`)console.log(`cli: ${report.cli.installed ? `${report.cli.bskBin} (${report.cli.version})` : "not installed"}`)console.log(`daemon: ${report.daemon.running ? `running (${report.daemon.version}, protocol ${report.daemon.protocolVersion})` : `not running${report.daemon.error ? ` — ${report.daemon.error}` : ""}`}`)+ console.log(`browser the user uses: ${summary.browser ? `${summary.browser.label} [${summary.browser.id}] (${summary.browser.reason})` : `not identified (${report.identification.reason})`}`)+ console.log(`candidates: ${summary.candidates.map((c) => `${c.id}${c.signals.length ? ` (${c.signals.join(", ")})` : ""}`).join(", ") || "none"}`)+ if (summary.registeredElsewhere.length > 0) console.log(`extension entries left in other browsers: ${summary.registeredElsewhere.join(", ")} (not removed automatically)`)console.log(`browsers detected: ${summary.browsersDetected.map((b) => `${b.id}${b.extensionRegistered ? " (extension registered)" : ""}`).join(", ") || "none"}`)console.log(`browsers connected: ${summary.browsersConnected.map((b) => `${b.name} ${b.version} [${b.instanceId}]`).join(", ") || "none"}`)console.log(`\n${REMEDIES[state]}`)diff --git a/plugins/omo/skills/browser/scripts/browser-install.mjs b/plugins/omo/skills/browser/scripts/browser-install.mjsindex 2ad554c3..be02ddb4 100755--- a/plugins/omo/skills/browser/scripts/browser-install.mjs+++ b/plugins/omo/skills/browser/scripts/browser-install.mjs@@ -4,10 +4,13 @@ import { loadOmowright } from "./omowright.mjs"const json = process.argv.includes("--json")const waitArg = process.argv.find((arg) => arg.startsWith("--wait-ms="))const waitTotalMs = waitArg ? Number(waitArg.slice("--wait-ms=".length)) : 0+const browserArg = process.argv.find((arg) => arg.startsWith("--browser="))+const browser = browserArg ? browserArg.slice("--browser=".length) : undefinedconst { omowright } = await loadOmowright()const steps = []const result = await omowright.bskOnboard({+ browser,onHumanStep: (step) => steps.push(step),waitForBrowserMs: waitTotalMs > 0 ? Math.min(15_000, waitTotalMs) : 0,waitTotalMs,@@ -18,6 +21,10 @@ const summary = {cli: result.cli,installerRan: result.install !== null,daemon: { running: result.daemon.running, version: result.daemon.version ?? null, error: result.daemon.error ?? null },+ browser: result.primary ? { id: result.primary.id, label: result.primary.label, confidence: result.identification.confidence, reason: result.identification.reason } : null,+ needsChoice: result.needsChoice,+ candidates: result.identification.candidates.map((c) => ({ id: c.id, label: c.label, signals: c.signals })),+ registeredElsewhere: result.identification.registeredElsewhere,registrations: result.registrations.map((r) => ({ browser: r.browser, registered: r.registered, alreadyPresent: r.alreadyPresent ?? false, reason: r.reason ?? null, needsRestart: r.needsRestart ?? null, humanStep: r.humanStep ?? null })),browsersConnected: result.browsersConnected.map((b) => ({ instanceId: b.instance_id, name: b.browser_name, version: b.browser_version })),humanStep: result.humanStep,@@ -30,9 +37,14 @@ if (json) {} else {console.log(`cli: ${result.cli.installed ? `${result.cli.bskBin} (${result.cli.version})` : "install failed"}`)console.log(`daemon: ${result.daemon.running ? "running" : `not running${result.daemon.error ? ` — ${result.daemon.error}` : ""}`}`)+ console.log(summary.browser ? `browser: ${summary.browser.label} [${summary.browser.id}] (${summary.browser.reason})` : `browser: not identified (${result.identification.reason})`)for (const r of summary.registrations) {console.log(`extension for ${r.browser}: ${r.registered ? (r.alreadyPresent ? "already registered" : "registered") : `not registered (${r.reason})`}`)}- console.log(`\nTell the user exactly this, then re-run browser-doctor.mjs:\n ${result.humanStep}`)+ if (result.needsChoice) {+ console.log(`\nNothing was registered. ${result.humanStep}\nRe-run: node "<skill-root>/scripts/browser-install.mjs" --browser=<id>`)+ } else {+ console.log(`\nTell the user exactly this, then re-run browser-doctor.mjs:\n ${result.humanStep}`)+ }}process.exitCode = result.ready ? 0 : 2diff --git a/plugins/omo/skills/ultrawork/SKILL.md b/plugins/omo/skills/ultrawork/SKILL.mdindex 039107f5..96672963 100644--- a/plugins/omo/skills/ultrawork/SKILL.md+++ b/plugins/omo/skills/ultrawork/SKILL.md@@ -13,7 +13,7 @@ metadata:[CODE RED] Maximum precision. Outcome-first. Evidence-driven.# Role-Expert coding agent. Ship verified work. No process narration.+Expert coding agent. Ship verified work; report at handoffs, not between them.# GoalDeliver EXACTLY what the user asked, end-to-end working, proven by@@ -445,8 +445,12 @@ commits this session — then stage + draft the message instead.# Output discipline- First line literally: `ULTRAWORK MODE ENABLED!`- After bootstrap: 1-2 paragraph plan summary + notepad path.-- During execution: surface only state changes (existing tests read,- scenario PASS/FAIL with evidence paths, reviewer verdict).+- During execution: at every handoff - todo phase change, blocker,+ plan change, before a long pass - one handoff block composed after+ weighing what the user asked and needs to know now:+ `[Outcome so far] toward [ask + wanted]. You need: [ledger,+ evidence paths, PASS/FAIL, reviewer verdict]. Now: [todo in+ progress]. Next: [next open todo].`; nothing between handoffs.- Final message: outcome + success-criteria checklist with evidencerefs + notepad path + reviewer approval (if gate triggered) + commitlist (`<sha> <subject>`). No file-by-file changelog unless asked.diff --git a/plugins/omo/skills/ulw-research/AGENTS.md b/plugins/omo/skills/ulw-research/AGENTS.mdnew file mode 100644index 00000000..cdb74b9f--- /dev/null+++ b/plugins/omo/skills/ulw-research/AGENTS.md@@ -0,0 +1,63 @@+# ulw-research — Research Orchestration + report-tools Runtime++## OVERVIEW++`SKILL.md` is the research orchestration contract (team-first saturation, claim graph, convergence, delivery). `scripts/` is the deliverable runtime that contract calls: `report-tools.mjs`, a zero-dependency Node CLI for the deliverable phase (outcome manifest, static and layout gates, bounded repair, format extraction). `references/` holds the edition-neutral deliverable contract and the defect glossary. Earned this file: the only shared skill whose runtime is overlaid into a second, separately authored edition (the senpi native skill) at sync time.++## STRUCTURE++```+ulw-research/+├── SKILL.md # shared-edition prose contract (router to the references)+├── references/+│ ├── deliverable-phase.md # lanes, state, destination defaults, interview, memory episodes, design spec, gates, repair, manifest, command reference+│ ├── report-gates.md # one row per defect code: severity, integrity, what it detects, how to fix+│ └── latex-report.md+└── scripts/+ ├── report-tools.mjs # CLI entry + dispatcher (COMMANDS, run, main)+ ├── report-tools-commands.mjs # one function per subcommand+ ├── cli-support.mjs / entry-guard.mjs # flags, CliError, exit codes, atomic JSON, symlink-safe entry check+ ├── contracts.mjs # frozen vocabulary: DEFECT_CODES (severity lives only here), enums, manifest + repair-state validators+ ├── outcome.mjs # outcome.json manifest, deliverable state, verify, closing briefing+ ├── repair-tracker.mjs # bounded repair decisions (attempts, plateau, oscillation, wall clock, integrity codes)+ ├── html-lite.mjs / entities.mjs # HTML tokenizer, selector paths, prose text+ ├── css-lite.mjs / design-spec.mjs # CSS scanning, palette + lineage parsing, design-spec rendering+ ├── gates-static.mjs + gates-text.mjs / gates-figures.mjs / gates-structure.mjs # static gates G1-G15+ ├── layout-probe.mjs / gates-layout.mjs # in-page probe source + layout gates L1-L5 over its output+ ├── format-extract.mjs / format-extract-css.mjs # design-spec draft from a pointed-at HTML or Markdown document+ ├── *.test.ts # co-located bun tests, one per module (unshipped)+ └── tests/fixtures/ # good/bad reports, boxes.json, reference docs (unshipped)+```++## SURFACE++`node "$SKILL_DIR/scripts/report-tools.mjs" <command>`: `check`, `layout-probe`, `repair decide`, `outcome init`, `outcome set`, `outcome gate`, `outcome render`, `outcome state`, `outcome verify`, `outcome finish`, `outcome briefing`, `format-extract`, `--help --json`. Exit codes: `0` pass, `1` semantic failure (blockers, a failed verify, a blocked repair), `2` usage or IO. JSON on stdout, one summary line on stderr. Flags per command: `references/deliverable-phase.md` section 10.++## CONVENTIONS++- Zero runtime dependencies: plain ESM `.mjs`, `node:` builtins and sibling imports only, no `Bun.*`. Runs under Node >= 20 or Bun 1.4 (global `fetch` for `format-extract --from-url`).+- Each `.mjs` stays at or under 250 lines; split by responsibility, never by size.+- The CLI never launches a browser. The layout probe is printed as one async expression; the orchestrator evaluates it through the browser skill's owned headless engine and passes the result back with `check --layout`.+- Time is always injected (`--now`, `startedAt`); no module reads the clock inside a decision.+- Tests are co-located given/when/then bun tests; CLI tests spawn `node` with bun removed from `PATH`. Fixtures live only under `scripts/tests/fixtures/`, are depersonalized, and never ship.+- The senpi source dir (`packages/omo-senpi/skills/ulw-research/`) intentionally has no `scripts/`, `references/report-gates.md`, or `references/deliverable-phase.md`: the senpi sync overlays them from here byte-for-byte (`sharedAssets` in `packages/omo-senpi/plugin/scripts/native-skill-sources.mjs`), and both editions' sync suites assert the shipped copies equal these sources.+- References and scripts carry no Hangul (Korean match strings are `\u` escapes) and never three consecutive newlines (the senpi sync normalizes those and would break byte equality).++## ANTI-PATTERNS++- NEVER hand-edit a shipped copy under `packages/omo-senpi/plugin/skills/` or the packaged plugin tree; edit here and re-sync.+- NEVER add a severity override or a caller-supplied severity. The only sanctioned exception is `unsourced_number` following the design spec's `Lineage:` mode.+- Never let a gate or the repair loop silently skip: an unrunnable gate is recorded `not_run`, and an integrity code blocks delivery.+- Never name a browser library in the references or `SKILL.md`; route through the browser skill.+- Never test prose: pin machine-consumed values (CLI JSON, exit codes, extractor output, tracker decisions, defect-code vocabulary) and shipped-copy equality only.++## COMMANDS++```bash+# from the repository root+bun test --timeout 20000 packages/shared-skills/skills/ulw-research/scripts+node packages/shared-skills/skills/ulw-research/scripts/report-tools.mjs --help --json+node packages/omo-senpi/plugin/scripts/sync-skills.mjs && bun test packages/omo-senpi/src/skills-sync.test.ts+```++- Parent: [`packages/shared-skills/AGENTS.md`](../../AGENTS.md).diff --git a/plugins/omo/skills/ulw-research/SKILL.md b/plugins/omo/skills/ulw-research/SKILL.mdindex e1506cb8..83f4396c 100644--- a/plugins/omo/skills/ulw-research/SKILL.md+++ b/plugins/omo/skills/ulw-research/SKILL.md@@ -54,10 +54,10 @@ The research is done when all of these hold:- Claims that were contested, undocumented, or performance-shaped were proven or refuted by executed code.- Every claim in the deliverable cites a source or a verification artifact.- Every asserted claim is represented in the claim graph, tied to an intent-vs-reality diff when an expected truth exists, and backed by observation manifest entries from independent observation groups or a documented single-source exception; convergence or exception status is explicit.-- The format-proposal gate was asked and answered BEFORE the first wave, and the final materials match that answer.-- The delivered artifact passed every delivery gate for this harness: visual QA on the rendered pages always, plus the proofread pass where the harness provides one (Phase 5).+- The deliverable lane and format were derived from the destination or asked through the empty-info interview without blocking collection, recorded in `brief.md` with `answered_by`, and the final materials match that record.+- The delivered artifact passed the delivery gates in order (static gates, layout gates, visual QA, and the proofread pass where the harness provides one), each status is in `outcome.json`, and `outcome verify` passed.- Every excursion opened during the run was closed by an EXIT rule, folded back into the claim or axis that triggered it, and recorded in both `excursion-log.md` and the ulw-loop ledger.-- The delivery message carries the closing briefing: how many sources the answer rests on (total + unique domains) and how many minutes the run took.+- The delivery message carries the closing briefing printed by `outcome briefing`: sources (total + unique domains), elapsed minutes, every promised deliverable with its status, and any residual defects.- The session journal reconstructs what was searched, found, and expanded, wave by wave, and it was written in real time rather than reconstructed at the end.## Epistemic instrumentation@@ -134,6 +134,8 @@ mkdir -p .omo/ulw-research/$(date +%Y%m%d-%H%M%S)This is `$SESSION_DIR`. The orchestrator owns the journal: you write every file in it; workers never do. Maintain:+- `brief.md` — the analysis block, the axis list, the expected truths, and the `## Deliverable` record from the interview below (lane, state, formats, each field with `answered_by`).+- `sources-ledger.md` — one line per source the moment it is read: `[S<n>] <url> — <what it is>`. The closing briefing counts sources and domains from this file.- `wave-<N>-<kind>-<axis>.md` — your digest of each worker return: key findings, sources with URLs, and the worker's EXPAND markers verbatim.- `expansion-log.md` — per wave: workers spawned, markers gained, leads opened and closed.- `excursion-log.md` — one ENTER row and one EXIT row per excursion: `excursion_id`, parent claim or axis, ENTER trigger, depth, workers spent, the EXIT rule that closed it, what it changed in the top-level answer (`none` is a valid, required answer), and the ulw-loop steer/evidence id it was mirrored into.@@ -150,20 +152,20 @@ Append each digest the moment its worker returns, not in a batch at the end —ulw-loop is ON by default for this mode: when the `ulw-loop` skill is available, register the research axes as loop goals so the run has durable state and survives a compaction. The session directory's timestamp is the run's start clock — the closing briefing is computed from it, so create it once and never rename it. From that point every finding, source, quote, number, and lead is written into `$SESSION_DIR` **the instant it lands** — never held in the conversation for an end-of-run dump. After any context loss, re-read the brief and the journal before doing anything else, then resume from the open wave.-### Format-proposal gate — ALWAYS ask, before the first wave+### Deliverable lane, format, and the empty-info interview-Never guess the shape of the deliverable. After the decomposition and before spawning wave 1, propose the final materials and WAIT for the user's answer:+Never block collection on the shape of the deliverable, and never guess it either. Read [references/deliverable-phase.md](references/deliverable-phase.md) sections 1-6 before writing the brief, then:-- **Default pair: PDF + DOCX.** Offer both as the baseline for any report/document request.-- Name the alternatives that actually fit THIS domain — slides for a briefing, standalone HTML for a living page, Markdown for a working note, several at once when the audience differs.-- Propose the TEMPLATE too, chosen from the domain and the user's own context: section skeleton, citation style, length target, language, and any house style they have used before. A prior document the user points at is the strongest template signal — read it and mirror its structure and tagging.-- Ask once, compactly: proposed format + proposed template + what each option costs. Then stop and wait. Guessing here wastes the entire assembly pass.+1. **Derive first.** Name the lane (`template-strict`, `template-vibe`, `no-format`, `edit-existing`) and the promised formats from the request and its destination (the reference's section 3). When the request refers to an existing deliverable, decide its state with `node "$SKILL_DIR/scripts/report-tools.mjs" outcome state --deliverable <path> --session-dir "$SESSION_DIR"`: `partial` resumes the skeleton on disk, `complete` means edit-existing and never a regenerated report. `$SKILL_DIR` is this skill's own directory, the folder containing this SKILL.md.+2. **Read the requester's format memory** with the memory tool when the harness exposes one: the pointer `system/human/report-style.md`, then `reference/human-report-style.md`; take the choice recorded for the most similar context (same destination kind and audience) as the first option.+3. **Ask only what is still missing**: at most the reference's three questions (destination and format, audience and length, template lineage) in one call to the harness question tool (`ask_user_question` or `request_user_input`), non-blocking where the harness supports it, each with its default first, a free-text "describe the format" path, and "don't care, you decide". Collection starts without waiting; a late answer is folded in until the assembly worker starts, and after that it becomes a re-render request.+4. **Record it.** Write `## Deliverable` into `brief.md` (lane, state, formats, destination, audience, template, format description, each with `answered_by: user|default|request`) and open the manifest in the same step: `node "$SKILL_DIR/scripts/report-tools.mjs" outcome init --promised <formats> --lane <lane> --session-dir "$SESSION_DIR"`.-Record the answer in the journal; Phase 5 opens by turning it into `design-spec.md`.+Phase 5 opens by turning the recorded fields into `design-spec.md`.## Phase 1 — Saturation wave-**When the user asked for MASS research, the wave is sized by the topic's angles, not by the roster ceiling.** "mass ulw research", "mulw research", "ulw mass research" — in any language — order over-collection that a team of 8 cannot produce. Where the harness has a dependency-graph surface (the `mass-ulw` skill and its `references/planning.md`), run collection through it instead: a 60+ node opening wave covering every angle the topic has, routed across the whole difficulty ladder in one graph — mechanical sweeps and per-item harvest batches on the cheapest tier, judgment-shaped angles a step up, cross-territory angles a step above that, and the deepest tier reserved for genuinely hairy contradictions. Each wave's EXPAND leads define the next wave's nodes, and the synthesis reduces through several parallel architect-tier nodes into ONE architect-tier reducer (the strongest reasoning tier substitutes wherever no architect tier exists). Absent that surface, hold the same shape with background workers in batched waves. Everything else in this skill still binds: the format gate, the journal, the claim graph, the convergence rules, and the delivery gates.+**When the user asked for MASS research, the wave is sized by the topic's angles, not by the roster ceiling.** "mass ulw research", "mulw research", "ulw mass research" — in any language — order over-collection that a team of 8 cannot produce. Where the harness has a dependency-graph surface (the `mass-ulw` skill and its `references/planning.md`), run collection through it instead: a 60+ node opening wave covering every angle the topic has, routed across the whole difficulty ladder in one graph — mechanical sweeps and per-item harvest batches on the cheapest tier, judgment-shaped angles a step up, cross-territory angles a step above that, and the deepest tier reserved for genuinely hairy contradictions. Each wave's EXPAND leads define the next wave's nodes, and the synthesis reduces through several parallel architect-tier nodes into ONE architect-tier reducer (the strongest reasoning tier substitutes wherever no architect tier exists). Absent that surface, hold the same shape with background workers in batched waves. Everything else in this skill still binds: the deliverable interview, the journal, the claim graph, the convergence rules, and the delivery gates.Otherwise launch the entire first wave in one turn — every axis at once, as team members if you formed a team, else as background workers. Sequential launches and "start with one and see" defeat the mode.@@ -305,7 +307,7 @@ Workers: <total> · Waves: <count> · Excursions: <count> · Sources: <count> (<`SYNTHESIS.md` is the citation source of truth for final materials: every claim carries inline `[Source N]` citations, and every high-risk non-code claim you assert must be a verified-claims row from Phase 3b. Assert nothing the gate left in the unresolved/refuted annex.-**Write the skeleton early and fill it as claims lock.** The moment the format gate is answered, create the deliverable file with its approved section headings and a `STATUS: draft — <n> sections open` line at the top. An interrupted run must leave a partial report on disk, never an empty directory and a lost conversation.+**Write the skeleton early and fill it as claims lock.** The moment the brief records the deliverable, create the deliverable file with its section headings and a `STATUS: draft — <n> sections open` line as line 2 (an HTML comment in HTML); that line is the partial-state marker `outcome state` reads, removed only when the deliverable is complete. An interrupted run must leave a partial report on disk, never an empty directory and a lost conversation.**Keep sourced numbers, assumptions, and derived results visibly apart.** Every quantitative claim carries its lineage: `MEASURED` (a number a source states, cited), `ASSUMED` (a coefficient, distribution, or scope you chose — say why), `DERIVED` (computed from those, showing the formula), plus a sensitivity line whenever the assumption moves the answer. Presenting a derived estimate with the confidence of a measured one is the most damaging thing this mode can ship.@@ -313,7 +315,7 @@ Workers: <total> · Waves: <count> · Excursions: <count> · Sources: <count> (<## Phase 5 — Final materials-The format answered at the Phase 0 gate is binding. Absent an explicit user override, render **both PDF and DOCX**:+The promised formats recorded in `brief.md` and `outcome.json` are binding; `pdf` + `docx` is the default pair only when a document was asked for with no format word and no destination:| Target | How ||---|---|@@ -322,7 +324,7 @@ The format answered at the Phase 0 gate is binding. Absent an explicit user over| Slides / deck | `uv run --with python-pptx python` — one claim per slide, a chart or diagram per claim. || Standalone HTML / Markdown | The authored source itself. |-**Write `design-spec.md` the moment the format gate is answered — before any asset worker spawns.** It is the one design contract every asset and assembly worker receives: template family (a document the user pointed at is the strongest signal — mirror its structure and register; absent one, default to the clean analyst-report register — restrained accent palette, generous margins, styled section headings, no emoji, no clipart), accent palette, body/heading fonts (a real CJK webfont — Pretendard, Noto Sans KR — when the report language needs one), and the figure standard below. One font family and one palette govern prose, charts, Mermaid, and generated images alike; a diagram rendering in a random default font inside a styled report is a defect, not a style choice.+**Write `design-spec.md` the moment the deliverable is recorded — before any asset worker spawns.** When a document was pointed at, extract it instead of retyping its stylesheet: `node "$SKILL_DIR/scripts/report-tools.mjs" format-extract <reference> --out "$SESSION_DIR/design-spec.md"` (`--from-url` for a URL), then fill every `TODO: ask` from the interview answers, never by guessing. It is the one design contract every asset and assembly worker receives: template family (absent a reference, the clean analyst-report register — one accent over neutral tones, generous margins, styled section headings, no emoji, no clipart), palette tokens, body/heading fonts (a real gothic CJK webfont — Pretendard, Noto Sans KR — when the report language needs one, with `word-break: keep-all` for Korean), responsive breakpoints and HTML/CSS charts for web deliverables, the figure standard below, and the lineage mode on its own line: `Lineage: inline` (analyst default: every unit-bearing number tagged MEASURED / ASSUMED / DERIVED or cited in the same element) or `Lineage: section` (web and blog register: every section cited, lineage in the figure captions). The reference's section 6 lists the full defaults. One font family and one palette govern prose, charts, Mermaid, and generated images alike; a diagram rendering in a random default font inside a styled report is a defect, not a style choice.**The figure standard — binding for every image, chart, and diagram.** Each figure sits in a fixed-size container styled from the spec (border, background, caption); the image scales to fit entirely inside it with its original aspect ratio preserved — object-fit: contain semantics — never stretched, never cropped, never spilling out. Every chart carries a title, axis labels, units, and value labels in the report's language; a bare number the reader cannot name is a defect.@@ -337,23 +339,28 @@ Asset workers (background, parallel, each fed `design-spec.md`) — visuals areAssembly worker — `task(category="deep-low", load_skills=["frontend", "visual-qa", "open-design", "data-scientist", "imagegen", "ulw-loop"], run_in_background=true, ...)`: before writing, read every available design and visualization skill and apply it — the report is a designed artifact, not a text dump; the worker's prompt carries `design-spec.md`. Use the template the user approved; absent a stronger house style the default skeleton is executive summary → key findings by theme → detailed analysis (quotes under 20 words with attribution, charts, Mermaid graphs, generated visuals, SHA-pinned permalinks, verification results) → comparative analysis when options compete → numbered sources with access dates → methodology appendix (workers, waves, searches, verifications, debate rounds) → correction log naming what verification overturned. Write it long and specific: every claim cites `[Source N]`, and the sources section lists every source the run actually used rather than a curated few.-### The delivery gate — visual QA must PASS+### The delivery gates — every gate for the QA tier must PASS, in order-Nothing reaches the user until the gate passes:+Nothing reaches the user until the gates pass. Record each result with `node "$SKILL_DIR/scripts/report-tools.mjs" outcome gate <static|layout|visual|proofread> <pass|fail|not_run> --session-dir "$SESSION_DIR"`; a gate this harness does not provide is recorded `not_run`. A chat or post answer (light tier) runs the static gates and one render; every paginated or web deliverable runs them all (the reference's sections 3 and 7).-**Visual QA (always).** Render the produced artifact back to images — PDF pages to PNG, the HTML in a real browser — and look at them: missing or broken figures, images stretched or spilling their containers, diagram or chart text rendered off the spec's font or palette, clipped tables, overflowing CJK text, blank pages, unlabeled chart values, wrong page breaks. Fix and re-render until the pages are clean. Reading the source markup is not visual QA; inspect the pixels.+1. **Static gates (always, before anyone looks at pixels).** `node "$SKILL_DIR/scripts/report-tools.mjs" check "$SESSION_DIR/report.html" --design-spec "$SESSION_DIR/design-spec.md" > "$SESSION_DIR/defects.json"`: keep-all, palette tokens, emoji, em dashes, heading length, unsourced numbers, figure containers, chart text, gothic-only fonts, citations, the closing and sources sections, broken assets. Codes and fixes: [references/report-gates.md](references/report-gates.md).+2. **Layout gates.** Print the probe with `node "$SKILL_DIR/scripts/report-tools.mjs" layout-probe --json`, evaluate its `source` in the rendered page through the `browser` skill's owned headless engine, save the result as `$SESSION_DIR/boxes.json`, and re-run `check` with `--layout "$SESSION_DIR/boxes.json"` (overflow, clipped text, distorted images, overlapping siblings).+3. **Visual QA.** Render the produced artifact back to images — PDF pages to PNG, the HTML through the browser skill at desktop and phone widths — and look at them: missing or broken figures, images stretched or spilling their containers, diagram or chart text rendered off the spec's font or palette, clipped tables, overflowing CJK text, blank pages, unlabeled chart values, wrong page breaks. Reading the source markup is not visual QA; inspect the pixels.-Then deliver: the artifact plus a compact chat-readable summary of what it says — the answer in a few sentences, the numbers that matter, and what to look at first. The document is the deliverable; the summary is what gets it read.+**Repair is bounded.** After every gate run that found defects, ask `node "$SKILL_DIR/scripts/report-tools.mjs" repair decide --state "$SESSION_DIR/repair-state.json" --defects "$SESSION_DIR/defects.json" --artifact-bytes <bytes> --renders <pages> --session-dir "$SESSION_DIR"` and obey it: `repair` means fix and re-run; `deliver` means stop and ship with the residual defects the manifest now lists; `block` means a content-integrity defect remains (or there is no usable artifact), so do not deliver: tell the user what blocks it and record the row as `failed` with the reason. Never repair past a stop decision (3 attempts, a 2-attempt plateau, an oscillation, or 15 minutes; the reference's section 8).++Then resolve every manifest row (`outcome set <format> delivered --path <file>` or `blocked_capability` / `skipped` / `failed` with `--reason`) and deliver: the artifact plus a compact chat-readable summary of what it says — the answer in a few sentences, the numbers that matter, and what to look at first. The document is the deliverable; the summary is what gets it read.### The closing briefing — every run ends with itThe last thing the user reads states, in one compact block, what the answer is made of:-- **Sources.** How many sources the answer rests on and how many distinct domains they come from, counted from the journal's source ledger, not estimated. Name how many were primary sources and how many claims went to the unresolved/refuted annex.-- **Effort.** Workers, waves, excursions, and verifications — the same counters as the `SYNTHESIS.md` header.-- **Elapsed time, always.** Minutes from the run's start to delivery, derived from the session directory's own timestamp so it cannot be guessed: `python3 -c "import datetime,os,sys; s=datetime.datetime.strptime(os.path.basename(sys.argv[1]),'%Y%m%d-%H%M%S'); print(round((datetime.datetime.now()-s).total_seconds()/60))" "$SESSION_DIR"`.+- **The printed block.** `node "$SKILL_DIR/scripts/report-tools.mjs" outcome verify --session-dir "$SESSION_DIR" && node "$SKILL_DIR/scripts/report-tools.mjs" outcome finish --session-dir "$SESSION_DIR" && node "$SKILL_DIR/scripts/report-tools.mjs" outcome briefing --session-dir "$SESSION_DIR"`: sources and distinct domains counted from `sources-ledger.md`, elapsed minutes from the session directory's own timestamp, every promised deliverable with its status, the gate results, the residual defects, and the repair summary. A failing `verify` means the run is not done.+- **Effort.** Workers, waves, excursions, and verifications — the same counters as the `SYNTHESIS.md` header — plus how many sources were primary and how many claims went to the unresolved/refuted annex.++Never ship the artifact without this block, and never fill it from memory — paste the printed block and read the rest off the journal.-Never ship the artifact without this block, and never fill it from memory — every number in it is read off the journal.+**Record the format choice.** After delivery, when the harness exposes a memory tool and the run qualifies (the user declared a preference, or made the same unsolicited choice on 2+ runs), append one episode line to `reference/human-report-style.md` in the grammar of the reference's section 5, and update the `system/human/report-style.md` pointer when a generalization changed.If you stood up a team, disband it and confirm every worker is terminal before the final answer.## Search craft@@ -387,7 +394,8 @@ High-yield combinations: official docs (`site:<docs domain>`), GitHub implementa| A `Browsing: yes` run whose roster carries no browsing worker, or a browsing worker spawned without `ultimate-browsing` | The browsing column is binding — name the angle in the brief and spawn it, armed with the skill, in the first wave before any lead is chased || Contested claim settled by judgment | Phase 3 — run code, capture output, verdict || Deliverable claims without citations | Every claim cites a source or a verification artifact |-| Guessing the deliverable format instead of asking | The format gate is unconditional: propose PDF+DOCX plus the domain-fitting alternatives and the template, then wait before wave 1 |+| Guessing the deliverable format | Derive it from the request and destination; ask the empty-info interview only for what is still missing, and record `answered_by` for every field |+| Blocking the collection wave on the format question | Ask non-blocking and start collecting; unanswered fields run on the shown defaults || A roster smaller than the harness ceiling | Fill every member slot; split the broadest axis until the team is full || One tier across the whole roster | Mixed tiers by design — cheap breadth, premium attack || Silently re-routing a "quick"/"fast" instruction | Routing words are literal; journal requested -> spawned -> fallback per slot |@@ -396,10 +404,14 @@ High-yield combinations: official docs (`site:<docs domain>`), GitHub implementa| Batching findings into an end-of-run journal dump | Journal each return as it lands; the journal is what survives a compaction || Ending the run because every worker finished | Reserve the final fifth of the run for synthesis and materials || A derived estimate presented as a measured number | MEASURED / ASSUMED / DERIVED lineage on every quantitative claim, plus a sensitivity line |-| Delivering before the delivery gates pass | Visual QA on rendered pages always, plus the harness's proofread gate — a typo the user finds means a gate did not run |+| Delivering before the delivery gates pass | Static and layout gates, visual QA on rendered pages, plus the harness's proofread gate — a typo the user finds means a gate did not run |+| Skipping the static gates | `report-tools check` runs before any pixel review; its defects are cheaper than a visual pass |+| Delivering with a pending manifest row | `outcome verify` must pass; every promised format ends `delivered`, `blocked_capability`, `skipped`, or `failed` with a reason |+| Repairing past the tracker's stop decision | `repair decide` owns the budget; `deliver` ships with the residual list, `block` stops delivery |+| Guessing a design-spec value the extractor marked `TODO: ask` | Fill it from the interview answers or the reference's defaults, never by guessing || Referencing an asset that is not on disk | Verify the asset manifest before rendering; re-render whatever is missing || A figure stretched, cropped, or styled off the report's design language | `design-spec.md` binds every asset: fixed containers, contain-fit with aspect preserved, spec fonts and palette in charts and Mermaid || Chasing an interesting find with no ENTER trigger | Excursions need a named trigger; everything else stays a queued lead || An excursion that never came back, or drifted into a new mission | EXIT rules are unconditional; depth 3 means promote it to an axis or record it as a gap || An excursion whose result was never folded back | Every EXIT writes what it changed in the top-level answer, `none` included, and mirrors into the loop ledger |-| Delivering without the closing briefing | Source count, unique domains, and elapsed minutes are read off the journal and stated every time |+| Delivering without the closing briefing | Paste the block `outcome briefing` prints; never compute or recall its numbers by hand |diff --git a/plugins/omo/skills/ulw-research/references/deliverable-phase.md b/plugins/omo/skills/ulw-research/references/deliverable-phase.mdnew file mode 100644index 00000000..82b9fa88--- /dev/null+++ b/plugins/omo/skills/ulw-research/references/deliverable-phase.md@@ -0,0 +1,187 @@+# ulw-research - deliverable phase contract++Read this before the brief is written and again before Phase 6. It replaces the old blocking format question with a contract that never stalls collection: the deliverable is derived from the request and its destination, the requester is asked only what is genuinely missing, and every promise made about the output is tracked in a manifest until it is delivered, skipped, or blocked with a reason.++Every helper named here is one command of the dispatcher:++```bash+node "$SKILL_DIR/scripts/report-tools.mjs" <command> ...+```++`$SKILL_DIR` is the directory of the skill's `SKILL.md`. The helpers are plain `.mjs` files with no dependencies and run under `node` or `bun` on macOS, Linux, and Windows. They never launch a browser. Exit codes: `0` pass, `1` semantic failure (blockers found, a failed verify, a blocked repair), `2` usage or IO error. JSON goes to stdout and a one-line summary to stderr. Always pass `--session-dir "$SESSION_DIR"` explicitly; `SESSION_DIR` in the environment is only a fallback.++## 1. Lanes++The brief names exactly one lane. The lane decides how much the requester is asked, what the design spec starts from, and how strict the gates are.++| Lane | Definition | How to say it to the requester |+| --- | --- | --- |+| `template-strict` | The requester pointed at a document (a prior report, a page, a house template). Its structure, tokens, citation style, and figure standard are copied mechanically and not reinterpreted. | "I will match the document you pointed at: same structure, colors, fonts, and citation style." |+| `template-vibe` | The requester named a register or feeling ("like a consulting deck", "a clean blog post") without a document to copy. The design spec is written from the defaults in section 6 and the register. | "I will write it in that style using the default report design; point me at an example if you want an exact match." |+| `no-format` | Nothing about the shape was said and the destination implies it (a chat answer, a thread post, a quick note). No interview about format. | "I will answer in the shape this destination expects." |+| `edit-existing` | A complete deliverable for this question already exists (section 2). The run edits it in place. It never regenerates it. | "I will update the existing report rather than write a new one." |++## 2. Deliverable state++Before the brief is written, decide the state of any deliverable the request refers to:++```bash+node "$SKILL_DIR/scripts/report-tools.mjs" outcome state --deliverable <path> --session-dir "$SESSION_DIR"+```++| State | Meaning | What it opens |+| --- | --- | --- |+| `none` | No file, or an empty one. | A fresh run in the lane the request implies. |+| `partial` | The file carries a `STATUS: draft` line in its first 5 lines, or its manifest still has a `pending` row. | Resume the on-disk skeleton: keep the sections that exist, fill the missing ones, and never start over. |+| `complete` | The manifest says every promised row is resolved and the file is present and non-empty. | `edit-existing` only. A complete report is never regenerated from scratch. |++## 3. Destination-derived defaults++The request and its destination usually answer the format question already. Derive the defaults first; the interview (section 4) only covers what this table leaves open.++| Request or destination signal | Default format set | Lane | QA tier |+| --- | --- | --- | --- |+| A question answered in chat, with no document asked for | `post` (the answer itself, Markdown) | `no-format` | light |+| A thread, channel, or messenger post | `post` | `no-format` | light |+| A web page URL as the destination, or "blog", "page" | `html` | `template-vibe` | full |+| The words "PDF", "DOCX", "slides", or "LaTeX" in the request | exactly the named formats (`pdf`, `docx`, `slides`, `latex`) | `template-vibe` | full |+| "Report", "document", "write-up" with no format word and no destination | `pdf` + `docx` | `template-vibe` | full |+| A pointed-at document (a file, a URL, a prior report) | the reference's own format | `template-strict` | full |+| A prior report of the same kind in this workspace, not pointed at | that report's format, offered as the Q1 default | `template-vibe` | full |+| A complete existing deliverable for this question (section 2) | its existing format | `edit-existing` | the original's tier |++QA tiers: **light** runs the static gates and one render check of the answer. **Full** runs the static gates, the layout gates, visual QA of every page, and the proofread gate (section 7).++## 4. The empty-info interview++The interview has exactly three questions, asked together through the harness question tool without waiting for the answer. A question is **skipped** when the request, the destination, a pointed-at document, or a declared memory episode already answers it; when all three are answered, nothing is asked.++- **Q1 - destination and format.** Options in this order: the memory hit (the choice recorded for the most similar prior context, section 5) when there is one; the derived default from section 3; "describe the format in your own words" (free text, which becomes the brief for the design spec); "don't care, you decide" (resolves to the derived default).+- **Q2 - audience and length.** Who reads it, and a length band: `short` (a page or a post), `standard` (a report of about 5 to 12 pages), or `deep` (a full dossier). The derived default is first.+- **Q3 - template lineage.** The pointed-at document, the last report of the same kind, or the clean analyst register (section 6). The derived default is first.++Non-blocking rule: ask, do not wait, and start collection. Write `brief.md` at once with every field and who answered it; the unanswered fields carry their defaults. A late answer is folded in until the assembly lane starts; after that it becomes a re-render request, handled like any other repair.++Recorded fields, under `## Deliverable` in `brief.md`:++```text+lane: template-vibe+state: none+formats: pdf, docx (answered_by: request)+destination: internal review document (answered_by: default)+audience: engineering leads, standard (answered_by: user)+template: clean analyst register (answered_by: default)+format description: none+```++`answered_by` is one of `user`, `default`, `request`. Run `outcome init` (section 9) in the same step, with the formats as the promised list.++## 5. Report-format memory episodes++When the memory tool is present, the requester's report-format choices are kept as an append-only episode log, so a repeat requester is not asked the same question twice. When no memory tool is present, skip this section silently.++- Pointer: `system/human/report-style.md`, projected every session. One line naming the log, plus the generalizations currently in force.+- Episode log: `reference/human-report-style.md`, one line per episode, newest last:++```text+- [YYYY-MM-DD] <destination kind> · <audience> - <format and template chosen, one line> <!-- src: <session-id>; pattern: observed|declared; confidence: low|medium|high -->+```++Qualification (write after delivery, only when one of these holds): `declared` - the requester stated the preference outright ("always PDF only"); `observed` - the requester made the same unsolicited choice on 2 or more runs (read the log first). Record format and template choices only, never report content, subjects, names, or findings. Append; never rewrite an existing line.++Read-time generalization (before the interview): a similar context is one with the same destination kind and audience. Consistent similar episodes supply Q1's first option; a `declared` similar episode skips the question it answers. One session never flips a default: a single `observed` episode that disagrees with the rest changes nothing.++Pruning: keep the log near 15 lines. When it grows past that, prune the oldest episodes that agree with the majority for their context first. Never prune a `declared` episode or a minority episode (the only one recording a different choice for its context). Update the pointer in the same memory commit when a generalization changes.++## 6. design-spec.md++Write `$SESSION_DIR/design-spec.md` the moment the deliverable fields are known, before any asset lane starts. Every asset and assembly lane receives it.++1. When a document was pointed at, extract it first. Do not retype its stylesheet:+ ```bash+ node "$SKILL_DIR/scripts/report-tools.mjs" format-extract <reference.html|reference.md> --out "$SESSION_DIR/design-spec.md"+ node "$SKILL_DIR/scripts/report-tools.mjs" format-extract <https://...> --from-url --out "$SESSION_DIR/design-spec.md"+ ```+ The extractor copies the CSS custom properties (light and dark), font stacks by role, the most-used colors, px breakpoints, the section skeleton, the heading numbering, the citation marker style, the lineage mode, and the figure containers, under the fixed sections `Extracted from`, `Tokens`, `Typography`, `Layout`, `Structure`, `Figures`, `Citations`, `Open questions`. A field it cannot determine reads `TODO: ask`. A PDF reference is unsupported: ask for its HTML or Markdown source.+2. Fill every `TODO: ask` from the interview answers, then from the clean analyst register below. Never guess a value.+3. Apply the binding figure standard and the defaults:+ - Every figure sits in a fixed-size container with a caption; the image scales inside it with contain-fit, its aspect ratio preserved, never stretched, cropped, or spilling out. Every chart carries a title, axis labels, units, and value labels as real text, with deterministic ticks (round values computed from the data range, never left to a renderer's auto-scaling).+ - One accent color over neutral background, text, and rule tones. Every color in prose, charts, and diagrams is a spec token.+ - For web deliverables, HTML/CSS bars and inline SVG are preferred over image charts, and the page has responsive breakpoints so it reads on a phone, a tablet, and a desktop.+ - Gothic (sans) type only, as a real embedded webfont for the report language; Korean text uses `word-break: keep-all; overflow-wrap: anywhere`.+ - A closing section on how the report was made (method, sources, members and waves, the gates it passed, what verification overturned) and a numbered sources section with access dates.+4. Declare the lineage mode on its own line in the spec:+ - `Lineage: inline` (the analyst default): every unit-bearing number carries `MEASURED`, `ASSUMED`, or `DERIVED` inline or in a `data-lineage` attribute, or a `[S<n>]` citation in the same element. The gate reports an untagged number as a major defect.+ - `Lineage: section` (web and blog register): sources are bracketed source-label links at sentence end (the report language's word for "source"), lineage distinctions live in the figure captions, and every section is cited. The gate reports an untagged number as an advisory minor defect; the section-citation gate carries the weight.++## 7. Delivery gates, in order++Nothing reaches the requester until the gates for its QA tier pass, in this order. Each gate writes its status into the manifest with `outcome gate <gate> <pass|fail|not_run> --session-dir "$SESSION_DIR"`.++1. **Static gates.** `check` on the rendered HTML:+ ```bash+ node "$SKILL_DIR/scripts/report-tools.mjs" check "$SESSION_DIR/report.html" --design-spec "$SESSION_DIR/design-spec.md" > "$SESSION_DIR/defects.json"+ ```+ It checks keep-all, palette tokens, emoji, em dashes in prose (en dashes outside numeric ranges are advisory), heading length and generic headings, unsourced numbers (section 6), figure containers and captions, chart SVG text, Korean serif fonts, sections without citations, the closing section, the sources section, broken local assets, and any `--require-section <regex>` the brief requires. Every code, severity, and fix is in [report-gates.md](report-gates.md).+2. **Layout gates.** Print the probe, evaluate it in the rendered page through the browser skill's owned headless engine, save the returned object as `$SESSION_DIR/boxes.json`, and re-run `check` with `--layout "$SESSION_DIR/boxes.json"`. It adds overflow past the container, clipped text, scroll containers, distorted images, and overlapping siblings.+ ```bash+ node "$SKILL_DIR/scripts/report-tools.mjs" layout-probe --json # .source is one async expression+ ```+3. **Visual QA.** Render the artifact to images (PDF pages to PNG, the HTML in the browser skill's engine at desktop and phone widths) and look at the pixels for what a machine cannot see: composition, hierarchy, page breaks, figure legibility.+4. **Proofread.** A dedicated writing lane proofreads the final text only (grammar, spelling, punctuation, terminology, native register); it never composes or rewrites content.++The light tier runs gate 1 and one render (recorded as `visual`) and records `layout` and `proofread` as `not_run`. The full tier runs all four.++## 8. Bounded repair loop++After every gate run that produced defects, ask the tracker what to do next:++```bash+node "$SKILL_DIR/scripts/report-tools.mjs" repair decide --state "$SESSION_DIR/repair-state.json" --defects "$SESSION_DIR/defects.json" --artifact-bytes <report bytes> --renders <rendered page count> --session-dir "$SESSION_DIR"+```++- `action: repair`: fix the listed defects, re-render, re-run the gate, and ask again.+- `action: deliver`: stop repairing and deliver. `reason` is `clean` or the stop condition that fired; the residual defects are written into the manifest and listed in the closing briefing.+- `action: block` (exit `1`): do not deliver. Either a content-integrity defect remains (`missing_closing_section`, `missing_citation_section`, `broken_asset_reference`, `missing_required_section`, `missing_promised_deliverable`), or a stop fired without proof of a usable artifact (`--artifact-bytes` and `--renders`). Tell the requester what blocks delivery and record the affected rows as `failed` with the reason.++Defaults: 3 repair attempts, a plateau of 2 consecutive attempts that do not improve the (blocker, major, minor) counts compared in that order, and 15 minutes of wall clock from the first decision. A defect set that repeats an earlier attempt exactly stops the loop as an oscillation. When several conditions hold at once the reported reason follows `clean`, `blocking`, `oscillation`, `plateau`, `max_attempts`, `wall_clock`.++## 9. Outcome manifest and closing briefing++`$SESSION_DIR/outcome.json` tracks every promise made about the output, so a promised format is never silently dropped.++```bash+node "$SKILL_DIR/scripts/report-tools.mjs" outcome init --promised pdf,docx --lane template-vibe --session-dir "$SESSION_DIR"+node "$SKILL_DIR/scripts/report-tools.mjs" outcome set pdf delivered --path "$SESSION_DIR/report.pdf" --pages 12 --session-dir "$SESSION_DIR"+node "$SKILL_DIR/scripts/report-tools.mjs" outcome set docx blocked_capability --reason "no document converter in this session" --session-dir "$SESSION_DIR"+node "$SKILL_DIR/scripts/report-tools.mjs" outcome render "$SESSION_DIR/renders/page-01.png" --page 1 --session-dir "$SESSION_DIR"+node "$SKILL_DIR/scripts/report-tools.mjs" outcome verify --session-dir "$SESSION_DIR"+node "$SKILL_DIR/scripts/report-tools.mjs" outcome finish --session-dir "$SESSION_DIR"+node "$SKILL_DIR/scripts/report-tools.mjs" outcome briefing --session-dir "$SESSION_DIR"+```++- `init` runs when the brief is written (section 4): one `pending` row per promised format (`pdf`, `docx`, `html`, `md`, `latex`, `slides`, `post`).+- `set` resolves a row: `delivered` (absolute path; bytes are read from disk; pages when paginated), `blocked_capability` (this session cannot produce it), `skipped` (the requester or the lane dropped it), or `failed`. Every status except `delivered` needs `--reason`.+- `verify` runs before delivery and exits `1` while a row is `pending`, a status lacks its reason, or a delivered file is missing or empty.+- `finish` stamps the finish time, the elapsed minutes from the session directory's start stamp, and the source and domain counts from `sources-ledger.md`.+- `briefing` prints the closing block from the manifest and the ledger: sources and distinct domains, elapsed minutes, every deliverable with its status, the gate results, the residual defects, and the repair summary. That text is the closing briefing, pasted as printed, never filled in from memory.++## 10. Command reference++Invoke every command as `node "$SKILL_DIR/scripts/report-tools.mjs" <command>`. Exit codes for all of them: `0` pass, `1` semantic failure, `2` usage or IO error.++| Command | Flags | Exit `1` when |+| --- | --- | --- |+| `check <report.html>` | `--design-spec <spec>` (required), `--layout <boxes.json>`, `--require-section <regex>` (repeatable), `--max-defects N` | any blocker defect |+| `layout-probe` | `--cap N` (default 400), `--root <selector>` (default `main, article`), `--json` | never |+| `repair decide` | `--state <file>` and `--defects <json>` (required), `--artifact-bytes N`, `--renders N`, `--session-dir <dir>`, `--max-attempts N`, `--plateau-limit N`, `--wall-clock-ms N`, `--now <ISO>` | the decision is `block` |+| `outcome init` | `--promised <list>` (required), `--lane <lane>`, `--session-dir <dir>`, `--now <ISO>` | never |+| `outcome set <format> <status>` | `--path <file>`, `--pages N`, `--reason <text>`, `--session-dir <dir>`, `--now <ISO>` | never |+| `outcome gate <gate> <status>` | `--session-dir <dir>` | never |+| `outcome render <png>` | `--page N` (required), `--session-dir <dir>` | never |+| `outcome state` | `--deliverable <path>` (required), `--session-dir <dir>` | never |+| `outcome verify` | `--session-dir <dir>` | a promise is unresolved or a delivered file is missing or empty |+| `outcome finish` | `--ledger <file>`, `--session-dir <dir>`, `--now <ISO>` | never |+| `outcome briefing` | `--json`, `--ledger <file>`, `--session-dir <dir>`, `--now <ISO>` | never |+| `format-extract <reference>` | `--out <design-spec.md>` (required), `--from-url` | never (an unsupported reference exits `2`) |+| `--help` | `--json` | never |diff --git a/plugins/omo/skills/ulw-research/references/report-gates.md b/plugins/omo/skills/ulw-research/references/report-gates.mdnew file mode 100644index 00000000..0b0986c3--- /dev/null+++ b/plugins/omo/skills/ulw-research/references/report-gates.md@@ -0,0 +1,66 @@+# Report-Gates Defect Glossary++This reference catalogs every defect code the report gates (`static`, `layout`, `visual`, `proofread`) can raise, their severity and impact, and how to repair them.++## Defect Codes by Category++### Static Gate (Content & Structure)++| Code | Severity | Integrity | What It Detects | How to Fix |+|------|----------|-----------|-----------------|-----------|+| `korean_no_keep_all` | major | false | Text containing Hangul uses default word breaking, causing character-level wrapping and orphaned characters on mobile or narrow containers. | Add "word-break: keep-all; overflow-wrap: anywhere" to the body or the slide text container. |+| `palette_off_token` | minor | false | Color values are hardcoded literals (hex, rgb) instead of design-system tokens or are missing from the design spec palette. | Replace the literal color with a design-spec token (var(--...)) or add the color to the spec palette. |+| `emoji_in_prose` | major | false | Emoji characters appear in body text, headings, or figure captions. Emoji render at inconsistent sizes and lack semantic meaning. | Remove the emoji; use an inline SVG icon or plain text. |+| `em_dash_in_prose` | major | false | Em dashes (—) are used in body text for sentence breaks or parenthetical asides. Readability and accessibility suffer without a rewrite. | Rewrite the sentence with a comma, colon, or period instead of an em dash. |+| `en_dash_in_prose` | minor | false | En dashes (–) are used incorrectly outside of numeric ranges. Only numeric ranges (e.g., "pages 5–10") should use en dashes. | Use a hyphen for compounds; keep the en dash only between numbers. |+| `heading_too_long` | minor | false | A heading exceeds one visual line: 26 Korean characters (52 display width units) or 12 English words. | Shorten the heading to one line (26 Korean characters or 12 English words). |+| `heading_generic` | minor | false | A heading uses generic labels (e.g., "Introduction", "Background") without conveying the section's specific claim or finding. | Make the heading carry the section's claim instead of a generic label. |+| `unsourced_number` | major | false | A numeric value (percentage, count, duration, ratio) appears without a source attribution, measurement tag, or derivation chain. | Tag the number MEASURED / ASSUMED / DERIVED or cite its source in the same paragraph. |+| `chart_without_figure` | major | false | An image or chart lacks a figure wrapper with a caption. Uncaptioned charts isolate visuals from narrative flow. | Wrap the image or chart in a figure container with a caption. |+| `chart_svg_no_text` | major | false | An SVG chart or diagram lacks a title, axis labels, units, or value labels. Visuals cannot stand alone without text guidance. | Give the chart a title, axis labels, units, and value labels as SVG text. |+| `chart_svg_missing_labels` | minor | false | An SVG chart has some labels (e.g., title) but is missing others (e.g., axis ticks or unit). | Add the missing title, axis ticks, or unit label to the chart. |+| `korean_serif_font` | major | false | A serif or brush Korean font family is applied to Korean text. The design spec mandates gothic (sans) Korean typefaces. | Use a gothic (sans) Korean family; serif and brush families are banned by the design spec. |+| `section_without_citation` | major | false | A major section or subsection contains no in-text citations or reference marks. Source attribution is missing. | Cite at least one source inside this section or merge it into a cited one. |+| `missing_closing_section` | blocker | true | The report lacks a closing section explaining the methodology, sources, and gate outcomes. Delivery is incomplete without narrative closure. | Add the closing section that explains how the report was made (method, sources, gates). |+| `missing_citation_section` | blocker | true | The report has no sources, references, or citation definitions (e.g., [S1], [S2]). Attribution is impossible. | Add a sources or references section, or [S<n>] definition lines. |+| `broken_asset_reference` | blocker | true | An asset file (image, diagram, spreadsheet) is missing or unreadable. The deliverable cannot be rendered or is incomplete. | Re-render or restore the missing asset file before delivery. |+| `missing_required_section` | blocker | true | A section explicitly required by the brief (e.g., via `--require-section`) is absent. | Add the section the brief requires (matched by --require-section). |+| `missing_promised_deliverable` | blocker | true | A deliverable (e.g., a slide deck, a chart, a data file) is promised in the brief but not delivered, not marked blocked_capability, and not skipped with a reason. | Produce the promised deliverable or record it as blocked_capability or skipped with a reason. |++### Layout Gate (Rendering & Presentation)++| Code | Severity | Integrity | What It Detects | How to Fix |+|------|----------|-----------|-----------------|-----------|+| `layout_overflow` | major | false | An element exceeds its container width or height, causing horizontal scroll or content spillage in PDF, DOCX, or slide renders. | Constrain the element to its container (max-width: 100%, overflow-wrap: anywhere, or a narrower measure). |+| `layout_text_clipped` | major | false | Text is clipped or hidden by `overflow: hidden` or a fixed container height. Content is lost or unreadable. | Remove the overflow: hidden clip or give the text room to wrap. |+| `layout_scroll_container` | minor | false | A table or list is wrapped in a scrollable container for HTML deliverables. Scrolling content prints clipped in PDF or DOCX. | Scrolling content prints clipped; make the content fit or wrap the table in a scroll wrapper only for HTML deliverables. |+| `layout_image_distorted` | major | false | An image is distorted, stretched, or squeezed (aspect ratio is not preserved). The visual information is misrepresented. | Preserve the image aspect ratio (object-fit: contain inside a fixed container). |+| `layout_sibling_overlap` | major | false | Two adjacent block elements overlap (via negative margins, absolute positioning, or grid collision). Layout is broken. | Separate the overlapping elements (margins, grid, or a slide split). |++## Exit Codes++Gates emit a manifest-level outcome with one of three statuses:++| Status | Meaning |+|--------|---------|+| `pass` | All checks passed; no defects raised. |+| `fail` | One or more defects raised (blocker, major, or minor severity). Repair is required before delivery. |+| `not_run` | The gate was not invoked (e.g., no probe file provided for layout, no visual inspection conducted). |++### Layout Gate Probe File Requirement++The `layout` gate only runs when a probe file (a rendering artifact: PDF, PNG, or HTML snapshot) is provided alongside the manifest. If no probe file is available, the manifest records `layout: not_run` and the gate does not emit defects.++## Lineage and Citation Markers++Defect codes and their hints are delivered via the outcome manifest under `residualDefects` (if repair did not exhaust). Each defect entry includes:++- **code**: A string key from the table above (e.g., `"em_dash_in_prose"`)+- **message**: A human-readable narrative or location hint describing where the defect was found (e.g., "Line 42: em dash found in paragraph 2")++Citations within reports follow one of two lineage modes:++- **inline**: Source marks appear as `[Sn]` or `[Rn]` hyperlinks inline with the cited text.+- **section**: Sources are listed in a dedicated section with numbered entries ([S1], [S2], etc.).++Both modes are valid; choose based on the report's narrative flow.diff --git a/plugins/omo/skills/ulw-research/scripts/cli-support.mjs b/plugins/omo/skills/ulw-research/scripts/cli-support.mjsnew file mode 100644index 00000000..1fec8f53--- /dev/null+++ b/plugins/omo/skills/ulw-research/scripts/cli-support.mjs@@ -0,0 +1,102 @@+// cli-support.mjs - argument parsing, typed usage errors, exit-code mapping, and JSON file IO+// shared by every report-tools subcommand. node: builtins only.++import { readFileSync, renameSync, writeFileSync } from "node:fs"+import { basename, dirname, join } from "node:path"++/** A usage or input error: always exit code 2. */+export class CliError extends Error {+ constructor(message) {+ super(message)+ this.name = "CliError"+ }+}++const IO_CODES = new Set(["ENOENT", "EACCES", "EISDIR", "ENOTDIR", "EPERM"])++/** 0 pass, 1 semantic failure (result.exitCode), 2 usage or IO error. */+export function exitCodeFor(resultOrError) {+ if (resultOrError instanceof CliError) return 2+ if (resultOrError instanceof Error) return IO_CODES.has(resultOrError.code) ? 2 : 1+ return resultOrError?.exitCode === 1 ? 1 : 0+}++/**+ * Parse `--name value`, `--name=value`, boolean flags, and repeatable flags.+ * @param {readonly string[]} argv+ * @param {{ repeatable?: string[], booleans?: string[] }} spec+ */+export function parseArgs(argv, { repeatable = [], booleans = [] } = {}) {+ const repeat = new Set(repeatable)+ const bools = new Set(booleans)+ const positionals = []+ const flags = {}+ for (let index = 0; index < argv.length; index += 1) {+ const arg = argv[index]+ if (!arg.startsWith("--")) {+ positionals.push(arg)+ continue+ }+ const eq = arg.indexOf("=")+ const name = eq === -1 ? arg.slice(2) : arg.slice(2, eq)+ let value+ if (bools.has(name) && eq === -1) value = true+ else if (eq !== -1) value = arg.slice(eq + 1)+ else {+ value = argv[index + 1]+ if (value === undefined || value.startsWith("--")) throw new CliError(`--${name} requires a value`)+ index += 1+ }+ if (repeat.has(name)) flags[name] = [...(flags[name] ?? []), value]+ else flags[name] = value+ }+ return {+ positionals,+ flags,+ /** @param {string} name @param {number} [fallback] */+ int(name, fallback) {+ if (flags[name] === undefined) {+ if (fallback === undefined) throw new CliError(`--${name} is required`)+ return fallback+ }+ const parsed = Number(flags[name])+ if (!Number.isInteger(parsed) || parsed <= 0) throw new CliError(`--${name} requires a positive integer`)+ return parsed+ },+ /** @param {string} name */+ required(name) {+ const value = flags[name]+ if (value === undefined || value === true) throw new CliError(`--${name} is required`)+ return value+ },+ }+}++/** Read and parse a JSON file; a missing or malformed file is a CliError naming the path. */+export function readJsonFile(path) {+ let text+ try {+ text = readFileSync(path, "utf8")+ } catch (error) {+ throw new CliError(`cannot read ${path}: ${error.code ?? error.message}`)+ }+ try {+ return JSON.parse(text)+ } catch (error) {+ throw new CliError(`${path} is not valid JSON: ${error.message}`)+ }+}++/** Write JSON through a sibling temp file + rename, so a crash never leaves a half-written file. */+export function writeJsonAtomic(path, value) {+ const temp = join(dirname(path), `.${basename(path)}.${process.pid}.${Date.now()}.tmp`)+ writeFileSync(temp, `${JSON.stringify(value, null, 2)}\n`)+ renameSync(temp, path)+}++/** Print a result: JSON on stdout, one summary line on stderr. */+export function emit(result, { stdout = process.stdout, stderr = process.stderr } = {}) {+ if (typeof result.text === "string") stdout.write(result.text.endsWith("\n") ? result.text : `${result.text}\n`)+ else stdout.write(`${JSON.stringify(result.json ?? result, null, 2)}\n`)+ if (result.summary) stderr.write(`${result.summary}\n`)+}diff --git a/plugins/omo/skills/ulw-research/scripts/contracts.mjs b/plugins/omo/skills/ulw-research/scripts/contracts.mjsnew file mode 100644index 00000000..c6c334ba--- /dev/null+++ b/plugins/omo/skills/ulw-research/scripts/contracts.mjs@@ -0,0 +1,162 @@+// contracts.mjs - the fixed vocabulary every report-tools module shares.+//+// Severities live here and nowhere else: no module exports a way to change them, so a+// content-integrity defect can never be demoted by a caller. Plain Node ESM, node: builtins+// only, runnable by `node` and `bun` alike.++export const SCHEMA_VERSION = 1++function deepFreeze(value) {+ if (value === null || typeof value !== "object") return value+ for (const key of Object.keys(value)) deepFreeze(value[key])+ return Object.freeze(value)+}++/** code -> { severity, integrity, hint }. integrity = blocks delivery even on repair exhaustion. */+export const DEFECT_CODES = deepFreeze({+ korean_no_keep_all: { severity: "major", integrity: false, hint: 'Add "word-break: keep-all; overflow-wrap: anywhere" to the body or the slide text container.' },+ palette_off_token: { severity: "minor", integrity: false, hint: "Replace the literal color with a design-spec token (var(--...)) or add the color to the spec palette." },+ emoji_in_prose: { severity: "major", integrity: false, hint: "Remove the emoji; use an inline SVG icon or plain text." },+ em_dash_in_prose: { severity: "major", integrity: false, hint: "Rewrite the sentence with a comma, colon, or period instead of an em dash." },+ en_dash_in_prose: { severity: "minor", integrity: false, hint: "Use a hyphen for compounds; keep the en dash only between numbers." },+ heading_too_long: { severity: "minor", integrity: false, hint: "Shorten the heading to one line (26 Korean characters or 12 English words)." },+ heading_generic: { severity: "minor", integrity: false, hint: "Make the heading carry the section's claim instead of a generic label." },+ unsourced_number: { severity: "major", integrity: false, hint: "Tag the number MEASURED / ASSUMED / DERIVED or cite its source in the same paragraph." },+ chart_without_figure: { severity: "major", integrity: false, hint: "Wrap the image or chart in a figure container with a caption." },+ chart_svg_no_text: { severity: "major", integrity: false, hint: "Give the chart a title, axis labels, units, and value labels as SVG text." },+ chart_svg_missing_labels: { severity: "minor", integrity: false, hint: "Add the missing title, axis ticks, or unit label to the chart." },+ korean_serif_font: { severity: "major", integrity: false, hint: "Use a gothic (sans) Korean family; serif and brush families are banned by the design spec." },+ section_without_citation: { severity: "major", integrity: false, hint: "Cite at least one source inside this section or merge it into a cited one." },+ missing_closing_section: { severity: "blocker", integrity: true, hint: "Add the closing section that explains how the report was made (method, sources, gates)." },+ missing_citation_section: { severity: "blocker", integrity: true, hint: "Add a sources or references section, or [S<n>] definition lines." },+ broken_asset_reference: { severity: "blocker", integrity: true, hint: "Re-render or restore the missing asset file before delivery." },+ missing_required_section: { severity: "blocker", integrity: true, hint: "Add the section the brief requires (matched by --require-section)." },+ missing_promised_deliverable: { severity: "blocker", integrity: true, hint: "Produce the promised deliverable or record it as blocked_capability or skipped with a reason." },+ layout_overflow: { severity: "major", integrity: false, hint: "Constrain the element to its container (max-width: 100%, overflow-wrap: anywhere, or a narrower measure)." },+ layout_text_clipped: { severity: "major", integrity: false, hint: "Remove the overflow: hidden clip or give the text room to wrap." },+ layout_scroll_container: { severity: "minor", integrity: false, hint: "Scrolling content prints clipped; make the content fit or wrap the table in a scroll wrapper only for HTML deliverables." },+ layout_image_distorted: { severity: "major", integrity: false, hint: "Preserve the image aspect ratio (object-fit: contain inside a fixed container)." },+ layout_sibling_overlap: { severity: "major", integrity: false, hint: "Separate the overlapping elements (margins, grid, or a slide split)." },+})++const LAYOUT_PREFIX = "layout_"+/** Codes checkStatic can raise (G1-G15). */+export const STATIC_CODES = Object.freeze(+ Object.keys(DEFECT_CODES).filter((code) => !code.startsWith(LAYOUT_PREFIX) && code !== "missing_promised_deliverable"),+)+/** Codes checkLayout can raise (L1-L5). */+export const LAYOUT_CODES = Object.freeze(Object.keys(DEFECT_CODES).filter((code) => code.startsWith(LAYOUT_PREFIX)))+/** Codes only the outcome manifest verifier raises. */+export const MANIFEST_CODES = Object.freeze(["missing_promised_deliverable"])++export const INTEGRITY_CODES = Object.freeze(+ new Set(Object.entries(DEFECT_CODES).filter(([, entry]) => entry.integrity).map(([code]) => code)),+)++export const LANES = Object.freeze(["template-strict", "template-vibe", "no-format", "edit-existing"])+export const STATES = Object.freeze(["none", "partial", "complete"])+export const DELIVERABLE_FORMATS = Object.freeze(["pdf", "docx", "html", "md", "latex", "slides", "post"])+export const DELIVERABLE_STATUSES = Object.freeze(["pending", "delivered", "blocked_capability", "skipped", "failed"])+export const GATE_NAMES = Object.freeze(["static", "layout", "visual", "proofread"])+export const GATE_STATUSES = Object.freeze(["pass", "fail", "not_run"])+export const LINEAGE_MODES = Object.freeze(["inline", "section"])+export const ANSWERED_BY = Object.freeze(["user", "default", "request"])+export const REPAIR_DEFAULTS = Object.freeze({ maxAttempts: 3, plateauLimit: 2, wallClockMs: 15 * 60 * 1000 })+export const DESIGN_SPEC_SECTIONS = Object.freeze([+ "Extracted from",+ "Tokens",+ "Typography",+ "Layout",+ "Structure",+ "Figures",+ "Citations",+ "Open questions",+])++const ISO_DATE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/++function isObject(value) {+ return value !== null && typeof value === "object" && !Array.isArray(value)+}++function check(errors, condition, message) {+ if (!condition) errors.push(message)+}++function validateDeliverable(row, index, errors) {+ const at = `deliverables[${index}]`+ if (!isObject(row)) return errors.push(`${at} must be an object`)+ check(errors, DELIVERABLE_FORMATS.includes(row.format), `${at}.format must be one of ${DELIVERABLE_FORMATS.join(", ")}`)+ check(errors, DELIVERABLE_STATUSES.includes(row.status), `${at}.status must be one of ${DELIVERABLE_STATUSES.join(", ")}`)+ check(errors, typeof row.promised === "boolean", `${at}.promised must be a boolean`)+ check(errors, typeof row.updatedAt === "string" && ISO_DATE.test(row.updatedAt), `${at}.updatedAt must be an ISO timestamp`)+ for (const key of ["path", "reason"]) {+ if (row[key] !== undefined) check(errors, typeof row[key] === "string", `${at}.${key} must be a string`)+ }+ for (const key of ["bytes", "pages"]) {+ if (row[key] !== undefined) check(errors, Number.isInteger(row[key]) && row[key] >= 0, `${at}.${key} must be a non-negative integer`)+ }+}++function validateDefect(defect, at, errors) {+ if (!isObject(defect)) return errors.push(`${at} must be an object`)+ check(errors, Object.hasOwn(DEFECT_CODES, defect.code), `${at}.code is not a known defect code`)+ check(errors, typeof defect.message === "string", `${at}.message must be a string`)+}++/** @returns {{ ok: boolean, errors: string[] }} */+export function validateOutcomeManifest(manifest) {+ const errors = []+ if (!isObject(manifest)) return { ok: false, errors: ["manifest must be an object (schemaVersion missing)"] }+ check(errors, manifest.schemaVersion === SCHEMA_VERSION, `schemaVersion must be ${SCHEMA_VERSION}`)+ check(errors, typeof manifest.sessionDir === "string" && manifest.sessionDir.length > 0, "sessionDir must be a non-empty string")+ check(errors, typeof manifest.startedAt === "string" && ISO_DATE.test(manifest.startedAt), "startedAt must be an ISO timestamp")+ check(errors, manifest.finishedAt === null || (typeof manifest.finishedAt === "string" && ISO_DATE.test(manifest.finishedAt)), "finishedAt must be null or an ISO timestamp")+ check(errors, manifest.elapsedMinutes === null || (Number.isFinite(manifest.elapsedMinutes) && manifest.elapsedMinutes >= 0), "elapsedMinutes must be null or a non-negative number")+ check(errors, manifest.lane === null || LANES.includes(manifest.lane), `lane must be null or one of ${LANES.join(", ")}`)+ check(errors, manifest.interview === null || isObject(manifest.interview), "interview must be null or an object")+ if (Array.isArray(manifest.deliverables)) manifest.deliverables.forEach((row, index) => validateDeliverable(row, index, errors))+ else errors.push("deliverables must be an array")+ if (Array.isArray(manifest.renders)) {+ manifest.renders.forEach((render, index) => {+ check(errors, isObject(render) && typeof render.path === "string" && Number.isInteger(render.page) && render.page >= 1, `renders[${index}] must be { path: string, page: integer >= 1 }`)+ })+ } else errors.push("renders must be an array")+ if (isObject(manifest.gates)) {+ for (const gate of GATE_NAMES) check(errors, GATE_STATUSES.includes(manifest.gates[gate]), `gates.${gate} must be one of ${GATE_STATUSES.join(", ")}`)+ } else errors.push("gates must be an object")+ if (Array.isArray(manifest.residualDefects)) manifest.residualDefects.forEach((defect, index) => validateDefect(defect, `residualDefects[${index}]`, errors))+ else errors.push("residualDefects must be an array")+ check(errors, manifest.repair === null || isObject(manifest.repair), "repair must be null or an object")+ check(errors, manifest.sources === null || isObject(manifest.sources), "sources must be null or an object")+ return { ok: errors.length === 0, errors }+}++function isMeasure(value) {+ return Array.isArray(value) && value.length === 3 && value.every((n) => Number.isInteger(n) && n >= 0)+}++/** @returns {{ ok: boolean, errors: string[] }} */+export function validateRepairState(state) {+ const errors = []+ if (!isObject(state)) return { ok: false, errors: ["repair state must be an object (schemaVersion missing)"] }+ check(errors, state.schemaVersion === SCHEMA_VERSION, `schemaVersion must be ${SCHEMA_VERSION}`)+ check(errors, typeof state.startedAt === "string" && ISO_DATE.test(state.startedAt), "startedAt must be an ISO timestamp")+ if (isObject(state.budget)) {+ for (const key of ["maxAttempts", "plateauLimit", "wallClockMs"]) {+ check(errors, Number.isInteger(state.budget[key]) && state.budget[key] > 0, `budget.${key} must be a positive integer`)+ }+ } else errors.push("budget must be an object")+ if (Array.isArray(state.attempts)) {+ state.attempts.forEach((attempt, index) => {+ const at = `attempts[${index}]`+ if (!isObject(attempt)) return errors.push(`${at} must be an object`)+ check(errors, typeof attempt.at === "string" && ISO_DATE.test(attempt.at), `${at}.at must be an ISO timestamp`)+ check(errors, isMeasure(attempt.measure), `${at}.measure must be [blocker, major, minor] counts`)+ check(errors, typeof attempt.signature === "string", `${at}.signature must be a string`)+ })+ } else errors.push("attempts must be an array")+ check(errors, Number.isInteger(state.consecutiveNonProgress) && state.consecutiveNonProgress >= 0, "consecutiveNonProgress must be a non-negative integer")+ check(errors, Array.isArray(state.seenSignatures) && state.seenSignatures.every((s) => typeof s === "string"), "seenSignatures must be an array of strings")+ return { ok: errors.length === 0, errors }+}diff --git a/plugins/omo/skills/ulw-research/scripts/css-lite.mjs b/plugins/omo/skills/ulw-research/scripts/css-lite.mjsnew file mode 100644index 00000000..f2fc0c59--- /dev/null+++ b/plugins/omo/skills/ulw-research/scripts/css-lite.mjs@@ -0,0 +1,204 @@+// css-lite.mjs - a tolerant, dependency-free CSS scanner for report gates and spec extraction.+//+// Never throws on malformed input: an unbalanced stylesheet yields the rules closed so far.+// Plain Node ESM, no imports.++const GROUP_AT = /^@(?:-[a-z]+-)?(?:media|supports|container|layer|document|scope|starting-style|keyframes)\b/i+const HEX = /(?<![\w&])#([0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{4}|[0-9a-f]{3})(?![\w-])/gi+const DARK_MEDIA = /prefers-color-scheme\s*:\s*dark/i+const DARK_THEME = /\[data-theme\s*=\s*["']?dark/i+const TOKEN_SCOPE = /(?:^|[\s,>])(?::root|html)\b|^\[data-theme/i++function stripComments(css) {+ return css.replace(/\/\*[\s\S]*?(?:\*\/|$)/g, "")+}++/** Split on `separator` outside quotes and parentheses. */+function splitTopLevel(text, separator) {+ const parts = []+ let depth = 0+ let quote = null+ let current = ""+ for (let i = 0; i < text.length; i++) {+ const ch = text[i]+ if (quote) {+ if (ch === "\\") current += ch + (text[++i] ?? "")+ else {+ if (ch === quote) quote = null+ current += ch+ }+ continue+ }+ if (ch === '"' || ch === "'") quote = ch+ else if (ch === "(") depth+++ else if (ch === ")") depth = Math.max(0, depth - 1)+ else if (ch === separator && depth === 0) {+ parts.push(current)+ current = ""+ continue+ }+ current += ch+ }+ parts.push(current)+ return parts+}++function parseDeclarations(text) {+ const declarations = []+ for (const piece of splitTopLevel(text, ";")) {+ const colon = piece.indexOf(":")+ if (colon <= 0) continue+ const rawProp = piece.slice(0, colon).trim()+ const value = piece.slice(colon + 1).trim()+ if (!rawProp || /[\s{}]/.test(rawProp)) continue+ declarations.push({ prop: rawProp.startsWith("--") ? rawProp : rawProp.toLowerCase(), value })+ }+ return declarations+}++/**+ * @returns {{ selector: string, declarations: { prop: string, value: string }[], atRule?: string }[]}+ * atRule is the chain of enclosing grouping at-rule preludes joined by a space.+ */+export function scanRules(css) {+ if (typeof css !== "string") return []+ const src = stripComments(css)+ const slots = []+ const stack = []+ let buffer = ""+ for (let i = 0; i < src.length; i++) {+ const ch = src[i]+ if (ch === '"' || ch === "'") {+ let end = i + 1+ while (end < src.length && src[end] !== ch) end += src[end] === "\\" ? 2 : 1+ buffer += src.slice(i, end + 1)+ i = end+ } else if (ch === "{") {+ const pieces = splitTopLevel(buffer, ";")+ const prelude = pieces.pop().trim()+ const frame = stack.at(-1)+ if (frame && pieces.length) frame.body += `${pieces.join(";")};`+ const group = GROUP_AT.test(prelude)+ const slot = group ? -1 : slots.push(null) - 1+ stack.push({ prelude, group, slot, body: "" })+ buffer = ""+ } else if (ch === "}") {+ const frame = stack.pop()+ if (frame && !frame.group) {+ const atChain = stack.filter((entry) => entry.group).map((entry) => entry.prelude)+ const rule = { selector: frame.prelude, declarations: parseDeclarations(frame.body + buffer) }+ if (atChain.length) rule.atRule = atChain.join(" ")+ slots[frame.slot] = rule+ }+ buffer = ""+ } else if (ch === ";" && stack.length === 0) {+ buffer = ""+ } else {+ buffer += ch+ }+ }+ return slots.filter(Boolean)+}++function isDarkRule(rule) {+ if (rule.atRule && DARK_MEDIA.test(rule.atRule)) return true+ return DARK_THEME.test(rule.selector.replace(/:not\([^)]*\)/gi, ""))+}++/**+ * Global design tokens from `:root`, `html`, and `[data-theme]` rules. Dark = inside+ * `@media (prefers-color-scheme: dark)` or on a `[data-theme="dark"]` selector. Last value wins.+ * @returns {{ light: Map<string, string>, dark: Map<string, string> }}+ */+export function customProperties(css) {+ const light = new Map()+ const dark = new Map()+ for (const rule of scanRules(css)) {+ if (!rule.selector.split(",").some((part) => TOKEN_SCOPE.test(part.trim()))) continue+ const target = isDarkRule(rule) ? dark : light+ for (const { prop, value } of rule.declarations) if (prop.startsWith("--")) target.set(prop, value)+ }+ return { light, dark }+}++function splitFamilies(value) {+ return splitTopLevel(value, ",")+ .map((family) => family.trim().replace(/^(["'])(.*)\1$/, "$2").trim())+ .filter(Boolean)+}++/** Font stack after the size token of a `font` shorthand, or null when the shorthand has none. */+function shorthandFamilies(value) {+ const match = /(?:^|\s)[\d.]+(?:px|em|rem|pt|%|vw|vh|ch|ex)(?:\s*\/\s*\S+)?\s+(.+)$/i.exec(value)+ return match ? match[1] : null+}++/** @returns {{ selector: string, families: string[] }[]} var() references resolve against light tokens. */+export function fontFamilies(css) {+ const props = customProperties(css).light+ const result = []+ for (const rule of scanRules(css)) {+ for (const { prop, value } of rule.declarations) {+ const resolved = resolveVar(value, props)+ const stack = prop === "font-family" ? resolved : prop === "font" ? shorthandFamilies(resolved) : null+ if (stack === null) continue+ const families = splitFamilies(stack)+ if (families.length) result.push({ selector: rule.selector, families })+ }+ }+ return result+}++/** #abc / #abcd / #aabbcc / #aabbccdd -> #aabbcc (lowercase, alpha dropped); anything else -> null. */+export function normalizeHex(hex) {+ const match = /^#([0-9a-f]{3,8})$/i.exec(String(hex).trim())+ if (!match || ![3, 4, 6, 8].includes(match[1].length)) return null+ const digits = match[1].toLowerCase()+ const six = digits.length <= 4 ? [...digits.slice(0, 3)].map((d) => d + d).join("") : digits.slice(0, 6)+ return `#${six}`+}++/** Every hex color in `text`, normalized, in order of appearance, repeats kept. */+export function hexColors(text) {+ if (typeof text !== "string") return []+ return [...text.matchAll(HEX)].map((match) => normalizeHex(match[0]))+}++/** Unique px widths named in @media preludes (min-/max-width and range syntax), ascending. */+export function mediaBreakpoints(css) {+ if (typeof css !== "string") return []+ const widths = new Set()+ for (const media of stripComments(css).matchAll(/@media\b([^{;]*)/gi)) {+ for (const match of media[1].matchAll(/\b(?:min-|max-)?width\s*(?::|[<>]=?|=)\s*(\d+(?:\.\d+)?)px/gi)) {+ widths.add(Number(match[1]))+ }+ }+ return [...widths].sort((a, b) => a - b)+}++function lookup(props, name) {+ if (props instanceof Map) return props.get(name)+ return props && Object.hasOwn(props, name) ? props[name] : undefined+}++/** Substitute var(--name[, fallback]) from `props` (Map or object); unresolvable references keep their text. */+export function resolveVar(value, props, depth = 0) {+ if (typeof value !== "string" || depth > 10) return value+ let out = ""+ let cursor = 0+ for (;;) {+ const start = value.indexOf("var(", cursor)+ if (start === -1) return out + value.slice(cursor)+ let end = start + 4+ for (let open = 1; end < value.length && open > 0; end++) {+ if (value[end] === "(") open+++ else if (value[end] === ")") open--+ }+ const [name, ...rest] = splitTopLevel(value.slice(start + 4, end - 1), ",")+ const fallback = rest.length ? rest.join(",").trim() : undefined+ const replacement = lookup(props, name.trim()) ?? fallback+ const original = value.slice(start, end)+ out += value.slice(cursor, start) + (replacement === undefined ? original : resolveVar(replacement, props, depth + 1))+ cursor = end+ }+}diff --git a/plugins/omo/skills/ulw-research/scripts/design-spec.mjs b/plugins/omo/skills/ulw-research/scripts/design-spec.mjsnew file mode 100644index 00000000..8db91ee2--- /dev/null+++ b/plugins/omo/skills/ulw-research/scripts/design-spec.mjs@@ -0,0 +1,161 @@+// design-spec.mjs - read the palette and lineage mode out of design-spec.md, and render a+// design-spec.md draft from a format extract. Nothing is guessed: every value the extract+// does not carry is written `TODO: ask` and listed under Open questions.+// Plain Node ESM, node: builtins and siblings only.++import { DESIGN_SPEC_SECTIONS, LINEAGE_MODES } from "./contracts.mjs"+import { hexColors } from "./css-lite.mjs"++const TODO = "TODO: ask"+// English and Korean section names (the requester writes specs in either language).+const PALETTE_HEADING = /^(palette|tokens|colou?rs?|\uD1A0\uD070|\uD314\uB808\uD2B8|\uC0C9\uC0C1|\uCEEC\uB7EC)/i+const FENCE = /^\s{0,3}(`{3,}|~{3,})/+const HEADING = /^(#{1,6})\s+(.*?)\s*#*\s*$/+const TOKEN_DECLARATION = /--[\w-]+\s*:\s*([^;]*)/g+const FIGURE_STANDARD =+ "Each figure sits in a fixed-size container with a caption; the image scales to fit with its aspect ratio preserved (object-fit: contain), never stretched, cropped, or spilling out. Every chart carries a title, axis labels, units, and value labels."++/**+ * Walk markdown lines with fence awareness.+ * visit(line, { fenced, heading: { level, text } | null })+ */+function walkLines(markdown, visit) {+ let fence = null+ for (const line of String(markdown ?? "").split(/\r?\n/)) {+ const fenceMatch = FENCE.exec(line)+ if (fence) {+ const closes = fenceMatch && fenceMatch[1][0] === fence[0] && fenceMatch[1].length >= fence.length && line.trim() === fenceMatch[1]+ if (closes) fence = null+ else visit(line, { fenced: true, heading: null })+ continue+ }+ if (fenceMatch) {+ fence = fenceMatch[1]+ continue+ }+ const heading = HEADING.exec(line)+ visit(line, { fenced: false, heading: heading ? { level: heading[1].length, text: heading[2].replace(/^[\d.\s]+/, "") } : null })+ }+}++/**+ * Palette = hex values of every `--x: #hex` inside any fenced code block, plus every hex+ * anywhere under a heading named Palette / Tokens / Colors / Colours or their Korean equivalents (subheadings included).+ * @returns {Set<string>} normalized #rrggbb values+ */+export function parsePalette(specMarkdown) {+ const palette = new Set()+ let paletteLevel = 0+ walkLines(specMarkdown, (line, { fenced, heading }) => {+ if (heading) {+ if (paletteLevel && heading.level > paletteLevel) return+ paletteLevel = PALETTE_HEADING.test(heading.text) ? heading.level : 0+ return+ }+ if (fenced) for (const match of line.matchAll(TOKEN_DECLARATION)) for (const hex of hexColors(match[1])) palette.add(hex)+ if (paletteLevel) for (const hex of hexColors(line)) palette.add(hex)+ })+ return palette+}++/** `Lineage: inline|section` under the Citations heading; absent or unrecognized -> "inline". */+export function parseLineageMode(specMarkdown) {+ let citationsLevel = 0+ let mode = null+ walkLines(specMarkdown, (line, { fenced, heading }) => {+ if (mode || fenced) return+ if (heading) {+ if (citationsLevel && heading.level > citationsLevel) return+ citationsLevel = /^citations\b/i.test(heading.text) ? heading.level : 0+ return+ }+ const match = citationsLevel ? /^\s*(?:[-*]\s+)?lineage\s*:\s*(\S+)/i.exec(line) : null+ if (match && LINEAGE_MODES.includes(match[1].toLowerCase())) mode = match[1].toLowerCase()+ })+ return mode ?? "inline"+}++function entriesOf(value) {+ if (value instanceof Map) return [...value]+ return value !== null && typeof value === "object" ? Object.entries(value) : []+}++function isKnown(value) {+ if (value === undefined || value === null || value === "" || value === "unknown") return false+ if (Array.isArray(value)) return value.length > 0+ return true+}++function tokenFence(entries, dark) {+ const lines = entries.map(([name, value]) => `${dark ? " " : " "}${name}: ${value};`)+ const body = dark ? ["@media (prefers-color-scheme: dark) {", " :root {", ...lines, " }", "}"] : [":root {", ...lines, "}"]+ return ["```css", ...body, "```"]+}++/**+ * Render a design-spec.md draft. `extract` follows the format-extract shape+ * ({ origin, bytes, date?, tokens: { light, dark }, fonts, colors, breakpoints, headingNumbering,+ * citationStyle, lineageMode, figureContainers, skeleton, measure, notes }); every field is optional.+ * @returns {string}+ */+export function renderDesignSpec(extract = {}) {+ const source = extract ?? {}+ const open = []+ const field = (label, value, format = String) => {+ if (isKnown(value)) return format(value)+ open.push(label)+ return TODO+ }+ const fonts = source.fonts ?? {}+ const measure = source.measure ?? {}+ const light = entriesOf(source.tokens?.light)+ const dark = entriesOf(source.tokens?.dark)+ const colors = Array.isArray(source.colors) ? source.colors : []+ const skeleton = Array.isArray(source.skeleton) ? source.skeleton : []+ const notes = Array.isArray(source.notes) ? source.notes : []++ const sections = {+ "Extracted from": [+ `- Source: ${field("Source path or URL", source.origin)}`,+ `- Bytes: ${field("Source byte count", source.bytes)}`,+ `- Date: ${source.date ?? new Date().toISOString().slice(0, 10)}`,+ ...notes.map((note) => `- Note: ${note}`),+ ],+ Tokens: [+ ...(light.length ? tokenFence(light, false) : [`- Light tokens: ${field("Light tokens", null)}`]),+ ...(dark.length ? tokenFence(dark, true) : [`- Dark tokens: ${field("Dark tokens", null)}`]),+ ...(colors.length+ ? ["- Top colors:", ...colors.map((c) => ` - ${c.hex}${c.count ? ` (${c.count} uses${c.roles?.length ? `; ${c.roles.join(", ")}` : ""})` : ""}`)]+ : [`- Top colors: ${field("Top colors", null)}`]),+ ],+ Typography: [+ `- Body font: ${field("Body font", fonts.body)}`,+ `- Heading font: ${field("Heading font", fonts.heading)}`,+ `- Mono font: ${field("Mono font", fonts.mono)}`,+ `- Body size: ${field("Body size", measure.fontSize)}`,+ `- Line height: ${field("Line height", measure.lineHeight)}`,+ ],+ Layout: [+ `- Breakpoints: ${field("Breakpoints", source.breakpoints, (list) => list.map((px) => `${px}px`).join(", "))}`,+ `- Measure (max width): ${field("Measure", measure.maxWidth)}`,+ ],+ Structure: [+ `- Heading numbering: ${field("Heading numbering", source.headingNumbering)}`,+ skeleton.length ? "- Skeleton:" : `- Skeleton: ${field("Section skeleton", null)}`,+ ...skeleton.map((entry) => `${" ".repeat(Math.max(1, entry.level))}- ${entry.text}`),+ ],+ Figures: [+ `- Containers: ${field("Figure containers", source.figureContainers, (list) => list.join(", "))}`,+ `- Standard: ${FIGURE_STANDARD}`,+ ],+ Citations: [+ `- Style: ${field("Citation style", source.citationStyle)}`,+ `- Lineage: ${field("Lineage mode", LINEAGE_MODES.includes(source.lineageMode) ? source.lineageMode : null)}`,+ ],+ }+ sections["Open questions"] = open.length ? open.map((label) => `- ${label}: ${TODO}`) : ["- None"]++ const out = ["# Design spec", ""]+ for (const heading of DESIGN_SPEC_SECTIONS) out.push(`## ${heading}`, ...(sections[heading] ?? [`- ${TODO}`]), "")+ return out.join("\n")+}diff --git a/plugins/omo/skills/ulw-research/scripts/entities.mjs b/plugins/omo/skills/ulw-research/scripts/entities.mjsnew file mode 100644index 00000000..7d6c8bcd--- /dev/null+++ b/plugins/omo/skills/ulw-research/scripts/entities.mjs@@ -0,0 +1,39 @@+// entities.mjs - HTML character reference decoding for html-lite.mjs.+//+// Supports a fixed set of named entities plus decimal and hex numeric references. Unknown or+// malformed references stay verbatim. Single indexOf scan; plain Node ESM, no dependencies.++const NAMED_ENTITIES = {+ amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: "\u00a0", mdash: "\u2014", ndash: "\u2013",+ hellip: "\u2026", copy: "\u00a9", reg: "\u00ae", times: "\u00d7", middot: "\u00b7",+}++function decodeOne(body) {+ if (Object.hasOwn(NAMED_ENTITIES, body)) return NAMED_ENTITIES[body]+ if (body[0] !== "#") return null+ const hex = body[1] === "x" || body[1] === "X"+ const digits = body.slice(hex ? 2 : 1)+ if (!(hex ? /^[0-9a-fA-F]{1,6}$/ : /^[0-9]{1,7}$/).test(digits)) return null+ const cp = Number.parseInt(digits, hex ? 16 : 10)+ return cp > 0 && cp <= 0x10ffff && (cp < 0xd800 || cp > 0xdfff) ? String.fromCodePoint(cp) : "\ufffd"+}++/** Decode the supported named entities plus decimal/hex numeric references; unknown ones stay verbatim. */+export function decodeEntities(text) {+ const source = String(text)+ let out = ""+ let last = 0+ let at = source.indexOf("&")+ while (at !== -1) {+ const semi = source.indexOf(";", at + 1)+ const decoded = semi !== -1 && semi - at <= 12 ? decodeOne(source.slice(at + 1, semi)) : null+ if (decoded !== null) {+ out += source.slice(last, at) + decoded+ last = semi + 1+ at = source.indexOf("&", last)+ } else {+ at = source.indexOf("&", at + 1)+ }+ }+ return out + source.slice(last)+}diff --git a/plugins/omo/skills/ulw-research/scripts/entry-guard.mjs b/plugins/omo/skills/ulw-research/scripts/entry-guard.mjsnew file mode 100644index 00000000..3e25cb3e--- /dev/null+++ b/plugins/omo/skills/ulw-research/scripts/entry-guard.mjs@@ -0,0 +1,21 @@+import { realpathSync } from "node:fs"+import { pathToFileURL } from "node:url"++/**+ * True when the module at `importMetaUrl` is the process entrypoint (`node <script>`).+ * Compares against the realpath too: Node resolves import.meta.url through symlinks while+ * process.argv[1] keeps the symlinked spelling, so a plain equality check silently skips the CLI+ * body when the skill is reached through a symlinked plugin directory.+ *+ * @param {string} importMetaUrl the caller's import.meta.url+ */+export function isCliEntry(importMetaUrl) {+ const argv1 = process.argv[1]+ if (argv1 === undefined) return false+ if (importMetaUrl === pathToFileURL(argv1).href) return true+ try {+ return importMetaUrl === pathToFileURL(realpathSync(argv1)).href+ } catch {+ return false+ }+}diff --git a/plugins/omo/skills/ulw-research/scripts/format-extract-css.mjs b/plugins/omo/skills/ulw-research/scripts/format-extract-css.mjsnew file mode 100644index 00000000..e98e2294--- /dev/null+++ b/plugins/omo/skills/ulw-research/scripts/format-extract-css.mjs@@ -0,0 +1,122 @@+// format-extract-css.mjs - the CSS half of format-extract: tokens, font stacks, ranked colors,+// breakpoints, and the reading measure. Only values the stylesheet states are returned; a+// missing value stays undefined so the renderer writes `TODO: ask`.+// Plain Node ESM, node: builtins and siblings only.++import { customProperties, fontFamilies, hexColors, mediaBreakpoints, resolveVar, scanRules } from "./css-lite.mjs"++const ROLE_ORDER = ["body", "heading", "link", "background", "border", "accent"]+const TOP_COLORS = 8+const ABSOLUTE_LENGTH = /^\d+(?:\.\d+)?(?:px|rem|em|ch)$/i++/** Last compound of each comma-separated selector part, pseudo-classes and attributes dropped. */+function subjects(selector) {+ return selector.split(",").map((part) => {+ const compounds = part.trim().split(/\s*[\s>+~]\s*/)+ return (compounds.at(-1) ?? "").replace(/(?:::?[\w-]+(?:\([^)]*\))?|\[[^\]]*\])+$/g, "").toLowerCase()+ })+}++const isBodySubject = (subject) => subject === "body" || subject === "html" || subject === ":root"+const isHeadingSubject = (subject) => /^h[1-6](?![\w-])/.test(subject)+const isMonoSubject = (subject) => /^(?:code|pre|kbd|samp)(?![\w-])/.test(subject)+const isLinkSubject = (subject) => /^a(?![\w-])/.test(subject)++function formatStack(families) {+ return families.map((family) => (/^-?[A-Za-z_][\w-]*$/.test(family) ? family : JSON.stringify(family))).join(", ")+}++/** { body?, heading?, mono? } from font-family / font declarations, var() resolved. */+export function fontStacks(css) {+ const fonts = {}+ const entries = fontFamilies(css)+ const pick = (test) => entries.find((entry) => subjects(entry.selector).some(test))+ const body = pick(isBodySubject)+ const heading = pick(isHeadingSubject)+ const mono = pick(isMonoSubject) ?? entries.find((entry) => entry.families.at(-1)?.toLowerCase() === "monospace")+ if (body) fonts.body = formatStack(body.families)+ if (heading) fonts.heading = formatStack(heading.families)+ if (mono) fonts.mono = formatStack(mono.families)+ return fonts+}++function tokenRoles(name) {+ const roles = []+ if (/accent|primary|brand/i.test(name)) roles.push("accent")+ if (/(?:^--|-)bg(?:-|$)|background|surface/i.test(name)) roles.push("background")+ if (/border|(?:^--|-)rule(?:-|$)/i.test(name)) roles.push("border")+ return roles+}++function declarationRoles(selector, prop) {+ if (prop.startsWith("--")) return tokenRoles(prop)+ if (prop.startsWith("background")) return ["background"]+ if (prop.startsWith("border") || prop.startsWith("outline")) return ["border"]+ if (prop !== "color") return []+ const parts = subjects(selector)+ const roles = []+ if (parts.some(isLinkSubject)) roles.push("link")+ if (parts.some(isHeadingSubject)) roles.push("heading")+ if (parts.some(isBodySubject)) roles.push("body")+ return roles+}++/**+ * Top hex colors by use count (ties keep first appearance): each token definition counts once,+ * and each other declaration counts once per hex it resolves to (var() against light tokens).+ * Roles are guessed from the selector and property where the color is used.+ */+export function rankColors(css, lightTokens) {+ const table = new Map()+ for (const rule of scanRules(css)) {+ for (const { prop, value } of rule.declarations) {+ const roles = declarationRoles(rule.selector, prop)+ for (const hex of hexColors(prop.startsWith("--") ? value : resolveVar(value, lightTokens))) {+ const entry = table.get(hex) ?? { hex, count: 0, roles: new Set() }+ entry.count+++ for (const role of roles) entry.roles.add(role)+ table.set(hex, entry)+ }+ }+ }+ return [...table.values()]+ .sort((a, b) => b.count - a.count)+ .slice(0, TOP_COLORS)+ .map((entry) => ({ hex: entry.hex, count: entry.count, roles: ROLE_ORDER.filter((role) => entry.roles.has(role)) }))+}++/** { fontSize?, lineHeight?, maxWidth? }: body size and leading, plus the most used absolute max width. */+export function readingMeasure(css, lightTokens) {+ const measure = {}+ const rules = scanRules(css).filter((rule) => !rule.atRule)+ for (const rule of rules) {+ if (!subjects(rule.selector).some(isBodySubject)) continue+ for (const { prop, value } of rule.declarations) {+ if (prop === "font-size" && !measure.fontSize) measure.fontSize = resolveVar(value, lightTokens)+ if (prop === "line-height" && !measure.lineHeight) measure.lineHeight = resolveVar(value, lightTokens)+ }+ }+ const widths = new Map()+ for (const rule of rules) {+ for (const { prop, value } of rule.declarations) {+ if (prop !== "max-width" && prop !== "max-inline-size") continue+ const resolved = resolveVar(value, lightTokens).trim()+ if (ABSOLUTE_LENGTH.test(resolved)) widths.set(resolved, (widths.get(resolved) ?? 0) + 1)+ }+ }+ const widest = [...widths].sort((a, b) => b[1] - a[1])[0]+ if (widest) measure.maxWidth = widest[0]+ return measure+}++/** Every CSS-derived Extract field from one concatenated stylesheet. */+export function cssFacts(css) {+ const tokens = customProperties(css)+ return {+ tokens,+ fonts: fontStacks(css),+ colors: rankColors(css, tokens.light),+ breakpoints: mediaBreakpoints(css),+ measure: readingMeasure(css, tokens.light),+ }+}diff --git a/plugins/omo/skills/ulw-research/scripts/format-extract.mjs b/plugins/omo/skills/ulw-research/scripts/format-extract.mjsnew file mode 100644index 00000000..7bb75239--- /dev/null+++ b/plugins/omo/skills/ulw-research/scripts/format-extract.mjs@@ -0,0 +1,229 @@+// format-extract.mjs - read a pointed-at HTML or Markdown document and return the facts a+// design-spec.md draft needs (render with design-spec.renderDesignSpec). Nothing is guessed:+// a value the document does not state is left out, and the renderer writes `TODO: ask`.+//+// Static input only. fetchHtml downloads exactly the given URL with plain fetch; external+// stylesheets are never followed (each is recorded as a note). A page that renders its+// content client-side is the orchestrator's job: render it with the browser skill, save the+// HTML, and pass the saved file. PDF input is rejected with UnsupportedFormatError.+// Plain Node ESM, node: builtins and siblings only.++import { readFileSync } from "node:fs"+import { extname } from "node:path"++import { cssFacts } from "./format-extract-css.mjs"+import { parseHtml, proseText } from "./html-lite.mjs"++export const UNSUPPORTED_MESSAGE = "unsupported: point at the HTML or Markdown source"+export const FETCH_TIMEOUT_MS = 15_000++const S_MARKER = /\[S\d+\]/+const SOURCE_ANCHOR = /\[(?:\uCD9C\uCC98|source(?:\s*\d+)?)\]/i+const LINEAGE_TOKEN = /\b(?:MEASURED|ASSUMED|DERIVED)\b/+const MD_FOOTNOTE = /\[\^[^\]\s]+\]/+const HEADING_NUMBER = /^(\d{1,3}(?:\.\d{1,3})*)\.?(?=\s|$)/+const FENCE = /^\s{0,3}(`{3,}|~{3,})/+const MD_HEADING = /^(#{1,6})\s+(.*?)\s*#*\s*$/+/**+ * @typedef {{ hex: string, count: number, roles: string[] }} ExtractColor+ * @typedef {{+ * origin: string | undefined, bytes: number,+ * tokens: { light: Map<string, string>, dark: Map<string, string> },+ * fonts: { body?: string, heading?: string, mono?: string }, colors: ExtractColor[], breakpoints: number[],+ * headingNumbering: "double-digit" | "decimal" | "none" | "unknown",+ * citationStyle: "bracket-S" | "bracket-source" | "footnote" | "unknown",+ * lineageMode: "inline" | "section" | "unknown", figureContainers: string[],+ * skeleton: { level: number, text: string }[],+ * measure: { fontSize?: string, lineHeight?: string, maxWidth?: string }, notes: string[],+ * }} Extract+ */++const HTML_EXTENSIONS = new Set([".html", ".htm", ".xhtml"])+const MD_EXTENSIONS = new Set([".md", ".markdown"])++export class UnsupportedFormatError extends Error {+ constructor(detail) {+ super(UNSUPPORTED_MESSAGE)+ this.name = "UnsupportedFormatError"+ this.code = "unsupported"+ this.detail = detail+ }+}++function rejectPdf(source, origin) {+ if (/\.pdf$/i.test(String(origin ?? ""))) throw new UnsupportedFormatError(`pdf origin: ${origin}`)+ if (String(source).trimStart().startsWith("%PDF-")) throw new UnsupportedFormatError("pdf bytes")+}++/** @returns {Extract} */+function baseExtract(source, origin) {+ return {+ origin,+ bytes: Buffer.byteLength(String(source), "utf8"),+ tokens: { light: new Map(), dark: new Map() },+ fonts: {},+ colors: [],+ breakpoints: [],+ headingNumbering: "unknown",+ citationStyle: "unknown",+ lineageMode: "unknown",+ figureContainers: [],+ skeleton: [],+ measure: {},+ notes: [],+ }+}++/** h2 numbers ("01", "1.2", or null) -> double-digit when every numbered h2 uses two digits. */+function classifyNumbering(numbers) {+ if (!numbers.length) return "unknown"+ const numbered = numbers.filter(Boolean)+ if (numbered.length * 2 < numbers.length) return "none"+ return numbered.every((number) => /^\d{2}$/.test(number)) ? "double-digit" : "decimal"+}++function headingNumber(text) {+ return HEADING_NUMBER.exec(text)?.[1] ?? null+}++function citationFacts(text, hasFootnotes, hasLineageAttribute) {+ const style = S_MARKER.test(text) ? "bracket-S" : SOURCE_ANCHOR.test(text) ? "bracket-source" : hasFootnotes ? "footnote" : "unknown"+ let lineage = "unknown"+ if (hasLineageAttribute || LINEAGE_TOKEN.test(text) || S_MARKER.test(text)) lineage = "inline"+ else if (SOURCE_ANCHOR.test(text)) lineage = "section"+ return { style, lineage }+}++function walk(node, visit) {+ for (const child of node.children) {+ visit(child)+ walk(child, visit)+ }+}++function classesOf(node) {+ return String(node.attrs.class ?? "").split(/\s+/).filter(Boolean)+}++/** Previous element sibling whose whole text is a heading number (a `.sec-no` style eyebrow). */+function eyebrowNumber(heading) {+ const siblings = heading.parent.children.filter((child) => child.tag !== "#text" || child.text.trim())+ const previous = siblings[siblings.indexOf(heading) - 1]+ if (!previous || previous.tag === "#text" || /^h[1-6]$/.test(previous.tag)) return null+ const text = proseText(previous)+ return HEADING_NUMBER.test(text) && headingNumber(text) === text.replace(/\.$/, "") ? headingNumber(text) : null+}++/** Nearest `<figure>` or fig/chart-classed ancestor of an img or svg. */+function figureContainer(node) {+ for (let cur = node.parent; cur && cur.tag !== "body"; cur = cur.parent) {+ const classes = classesOf(cur)+ if (cur.tag === "figure" || classes.some((name) => /fig|chart/i.test(name))) return cur+ }+ return null+}++function rankByCount(names) {+ const counts = new Map()+ for (const name of names) counts.set(name, (counts.get(name) ?? 0) + 1)+ return [...counts].sort((a, b) => b[1] - a[1]).map(([name]) => name)+}++/** @returns {Extract} throws UnsupportedFormatError on PDF input. */+export function extractFromHtml(source, { origin } = {}) {+ rejectPdf(source, origin)+ const extract = baseExtract(source, origin)+ const root = parseHtml(source)+ const styles = []+ const headings = []+ const containers = []+ let hasFootnotes = false+ let hasLineageAttribute = false+ let scripts = 0+ walk(root, (node) => {+ if (node.tag === "style") styles.push(node.raw ?? "")+ else if (node.tag === "script") scripts+++ else if (node.tag === "link" && /(?:^|\s)stylesheet(?:\s|$)/i.test(node.attrs.rel ?? "")) {+ extract.notes.push(`skipped external stylesheet: ${node.attrs.href ?? "(no href)"}`)+ } else if (/^h[1-6]$/.test(node.tag)) headings.push(node)+ else if (node.tag === "img" || node.tag === "svg") {+ const container = figureContainer(node)+ if (container) containers.push(...classesOf(container))+ } else if (node.tag === "sup" && node.children.some((child) => child.tag === "a" && /^#/.test(child.attrs.href ?? ""))) hasFootnotes = true+ else if (node.attrs?.role === "doc-noteref") hasFootnotes = true+ if (node.attrs && Object.hasOwn(node.attrs, "data-lineage")) hasLineageAttribute = true+ })+ const css = styles.join("\n")+ for (const match of css.matchAll(/@import\s+(?:url\()?\s*["']?([^"')\s;]+)/gi)) extract.notes.push(`skipped @import: ${match[1]}`)+ if (styles.length > 1) extract.notes.push(`${styles.length} <style> blocks concatenated`)+ if (css.trim()) Object.assign(extract, cssFacts(css))+ if (!extract.fonts.heading && extract.fonts.body) extract.notes.push("no heading font-family rule; headings inherit the body stack")++ const body = root.children.find((child) => child.tag === "html")?.children.find((child) => child.tag === "body")+ ?? root.children.find((child) => child.tag === "body")+ ?? root+ const text = proseText(body)+ if (scripts && text.length < 200) {+ extract.notes.push(`little static text with ${scripts} <script> tags: if the page renders client-side, render it with the browser skill and pass the saved HTML`)+ }+ const citation = citationFacts(text, hasFootnotes, hasLineageAttribute)+ extract.citationStyle = citation.style+ extract.lineageMode = citation.lineage+ const h2 = headings.filter((node) => node.tag === "h2")+ extract.headingNumbering = classifyNumbering(h2.map((node) => headingNumber(proseText(node)) ?? eyebrowNumber(node)))+ extract.skeleton = headings+ .filter((node) => node.tag === "h1" || node.tag === "h2")+ .map((node) => ({ level: Number(node.tag[1]), text: proseText(node) }))+ extract.figureContainers = rankByCount(containers)+ return extract+}++/** Markdown carries structure only: skeleton, heading numbering, citation style. @returns {Extract} */+export function extractFromMarkdown(source, { origin } = {}) {+ rejectPdf(source, origin)+ const extract = baseExtract(source, origin)+ const prose = []+ let fence = null+ for (const line of String(source).split(/\r?\n/)) {+ const fenceMatch = FENCE.exec(line)+ if (fence) {+ if (fenceMatch && fenceMatch[1][0] === fence[0] && fenceMatch[1].length >= fence.length && line.trim() === fenceMatch[1]) fence = null+ continue+ }+ if (fenceMatch) {+ fence = fenceMatch[1]+ continue+ }+ prose.push(line.replace(/`[^`]*`/g, ""))+ const heading = MD_HEADING.exec(line)+ if (heading && heading[1].length <= 2) extract.skeleton.push({ level: heading[1].length, text: heading[2] })+ }+ const text = prose.join("\n")+ extract.citationStyle = citationFacts(text, MD_FOOTNOTE.test(text), false).style+ extract.headingNumbering = classifyNumbering(extract.skeleton.filter((entry) => entry.level === 2).map((entry) => headingNumber(entry.text)))+ extract.notes.push("markdown source: tokens, fonts, colors, breakpoints, figures, and measure are not carried by Markdown")+ return extract+}++/** Dispatch on the file extension: .html/.htm/.xhtml, .md/.markdown; anything else (PDF included) is unsupported. @returns {Extract} */+export function extractFromPath(filePath) {+ const extension = extname(filePath).toLowerCase()+ if (HTML_EXTENSIONS.has(extension)) return extractFromHtml(readFileSync(filePath, "utf8"), { origin: filePath })+ if (MD_EXTENSIONS.has(extension)) return extractFromMarkdown(readFileSync(filePath, "utf8"), { origin: filePath })+ throw new UnsupportedFormatError(`extension ${extension || "(none)"}: ${filePath}`)+}++/** GET exactly `url` (plain fetch, 15 s timeout, no browser) and return the body text. */+export async function fetchHtml(url) {+ if (/\.pdf$/i.test(new URL(url).pathname)) throw new UnsupportedFormatError(`pdf url: ${url}`)+ const response = await fetch(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) })+ const type = response.headers.get("content-type") ?? ""+ if (!response.ok || /pdf/i.test(type)) {+ await response.body?.cancel()+ if (!response.ok) throw new Error(`fetch failed: HTTP ${response.status} for ${url}`)+ throw new UnsupportedFormatError(`pdf response: ${url}`)+ }+ const text = await response.text()+ if (text.trimStart().startsWith("%PDF-")) throw new UnsupportedFormatError(`pdf bytes: ${url}`)+ return text+}diff --git a/plugins/omo/skills/ulw-research/scripts/gates-figures.mjs b/plugins/omo/skills/ulw-research/scripts/gates-figures.mjsnew file mode 100644index 00000000..8bb9d4d0--- /dev/null+++ b/plugins/omo/skills/ulw-research/scripts/gates-figures.mjs@@ -0,0 +1,173 @@+// gates-figures.mjs - visual gates: G2 palette, G8 chart without figure, G9 chart svg text,+// G10 Korean serif/brush fonts.+//+// Each gate is { codes, skip?(ctx), run(ctx) -> Defect[] } over the context built by+// gates-static.mjs. Plain Node ESM, sibling imports only.++import { fontFamilies, hexColors, normalizeHex, resolveVar } from "./css-lite.mjs"+import { decodeEntities, proseText } from "./html-lite.mjs"++const ALWAYS_ALLOWED = new Set(["#ffffff", "#000000"])+const MAX_PALETTE = 20+const SVG_PAINT = /(?:fill|stroke|stop-color|flood-color|lighting-color)\s*(?:=\s*["']?|:\s*)(#[0-9a-f]{3,8})(?![\w-])/gi+const SVG_FONT = /font-family\s*(?:=\s*("[^"]*"|'[^']*')|:\s*([^;"'>]+))/gi+const ICON_MAX = 32+const CHART_MIN = 200+const ICON_NAME = /icon|logo/i+const ICON_HOSTS = new Set(["a", "button", "nav", "header", "footer", "h1", "h2", "h3", "h4", "h5", "h6"])+const CAPTION_CLASS = /^(?:caption|fig-?cap(?:tion)?)$/+const DEFAULT_FONT_SIZE = 16+const MIN_TITLE_CHARS = 4+const MIN_TICKS = 3+const NUMERIC = /^[-+\u2212]?[$\u20AC\u00A3\u00A5\u20A9]?\d[\d,.:]*\s?(?:%|[a-z\uAC00-\uD7A3]{0,3})$/i+const SERIF_FAMILY = /nanummyeongjo|applemyungjo|gungsuh|batang|nanumbrush|nanumpen|\uAD81\uC11C|\uBC14\uD0D5|\uBA85\uC870/++function pixels(value) {+ const match = /^\s*(\d+(?:\.\d+)?)\s*(?:px)?\s*$/i.exec(value ?? "")+ return match ? Number(match[1]) : null+}++/** Largest declared dimension: width/height attributes or style, else the viewBox. */+function declaredSize(node) {+ const style = node.attrs.style ?? ""+ const fromStyle = (prop) => pixels(new RegExp(`(?:^|;)\\s*${prop}\\s*:\\s*([^;]+)`, "i").exec(style)?.[1])+ const sizes = [pixels(node.attrs.width), pixels(node.attrs.height), fromStyle("width"), fromStyle("height")].filter((n) => n !== null)+ if (sizes.length) return Math.max(...sizes)+ const box = String(node.attrs.viewbox ?? "").trim().split(/[\s,]+/).map(Number)+ return box.length === 4 && box.every(Number.isFinite) ? Math.max(box[2], box[3]) : null+}++function isIcon(ctx, node) {+ const size = declaredSize(node)+ if (size !== null && size <= ICON_MAX) return true+ if (ICON_NAME.test(`${node.attrs.class ?? ""} ${node.attrs.id ?? ""}`)) return true+ return Boolean(ctx.util.closest(node, (cur) => ICON_HOSTS.has(cur.tag)))+}++const isFigure = (ctx) => (cur) => cur.tag === "figure" || ctx.util.classTokens(cur).includes("fig")++function hasCaption(ctx, figure) {+ return ctx.util.descendants(figure).some((node) => (node.tag === "figcaption" || ctx.util.classTokens(node).some((token) => CAPTION_CLASS.test(token))) && proseText(node).length > 0)+}++function visuals(ctx) {+ return ctx.elements.map(({ node }) => node).filter((node) => (node.tag === "img" || node.tag === "svg") && !isIcon(ctx, node))+}++function label(node) {+ if (node.tag === "img") {+ const src = node.attrs.src ?? ""+ return `<img src="${src.length > 48 ? `${src.slice(0, 48)}...` : src}">`+ }+ return `<svg${node.attrs.width ? ` width="${node.attrs.width}"` : ""}${node.attrs.height ? ` height="${node.attrs.height}"` : ""}>`+}++function svgTexts(raw) {+ return [...raw.matchAll(/<text\b([^>]*)>([\s\S]*?)<\/text\s*>/gi)]+ .map((match) => ({+ size: Number(/font-size\s*(?:=\s*["']?|:\s*)(\d+(?:\.\d+)?)/i.exec(match[1])?.[1] ?? DEFAULT_FONT_SIZE),+ value: decodeEntities(match[2].replace(/<[^>]*>/g, "")).replace(/\s+/g, " ").trim(),+ }))+ .filter((text) => text.value)+}++function missingChartLabels(raw) {+ const texts = svgTexts(raw)+ const title = decodeEntities(/<title\b[^>]*>([\s\S]*?)<\/title\s*>/i.exec(raw)?.[1] ?? "").trim()+ if (!texts.length && !title) return null+ const maxSize = Math.max(0, ...texts.map((text) => text.size))+ const missing = []+ if (!title && !texts.some((text) => text.size === maxSize && [...text.value].length >= MIN_TITLE_CHARS)) missing.push("title")+ const ticks = texts.filter((text) => NUMERIC.test(text.value)).length+ if (ticks < MIN_TICKS) missing.push(`numeric ticks (${ticks} < ${MIN_TICKS})`)+ if (!texts.some((text) => /\p{L}/u.test(text.value) && !NUMERIC.test(text.value))) missing.push("text label")+ return missing+}++function colorUses(ctx) {+ const uses = new Map()+ const add = (hex, node) => {+ const color = normalizeHex(hex)+ if (!color) return+ const entry = uses.get(color) ?? { node, count: 0 }+ entry.count+++ uses.set(color, entry)+ }+ for (const { node, css } of [...ctx.styleBlocks, ...ctx.styleAttrs]) for (const hex of hexColors(css)) add(hex, node)+ for (const node of ctx.all) {+ if (node.tag !== "svg") continue+ for (const key of ["fill", "stroke", "stop-color"]) if (node.attrs[key]) add(node.attrs[key], node)+ for (const match of (node.raw ?? "").matchAll(SVG_PAINT)) add(match[1], node)+ }+ return uses+}++function fontDeclarations(ctx) {+ const found = []+ for (const { node, css } of ctx.styleBlocks) for (const { families } of fontFamilies(css)) found.push({ node, families })+ for (const { node, css } of ctx.styleAttrs) for (const { families } of fontFamilies(`x{${resolveVar(css, ctx.tokens)}}`)) found.push({ node, families })+ for (const node of ctx.all) {+ if (node.tag !== "svg") continue+ const values = [node.attrs["font-family"], ...[...(node.raw ?? "").matchAll(SVG_FONT)].map((m) => m[1] ?? m[2])].filter(Boolean)+ for (const value of values) for (const { families } of fontFamilies(`x{font-family:${value}}`)) found.push({ node, families })+ }+ return found+}++export const figureGates = [+ {+ codes: ["palette_off_token"],+ skip: (ctx) => ctx.palette.size === 0,+ run(ctx) {+ const palette = new Set([...ctx.palette].map(normalizeHex))+ const defects = []+ for (const [color, { node, count }] of colorUses(ctx)) {+ if (defects.length >= MAX_PALETTE) break+ if (palette.has(color) || ALWAYS_ALLOWED.has(color)) continue+ defects.push(ctx.defect("palette_off_token", node, `color ${color} is not in the design-spec palette (${count} use${count === 1 ? "" : "s"})`))+ }+ return defects+ },+ },+ {+ codes: ["chart_without_figure"],+ run(ctx) {+ return visuals(ctx)+ .filter((node) => {+ const figure = ctx.util.closest(node, isFigure(ctx))+ return !figure || !hasCaption(ctx, figure)+ })+ .map((node) => ctx.defect("chart_without_figure", node, `${label(node)} has no figure container with a non-empty caption`))+ },+ },+ {+ codes: ["chart_svg_no_text", "chart_svg_missing_labels"],+ run(ctx) {+ const defects = []+ for (const node of visuals(ctx)) {+ if (node.tag !== "svg") continue+ if (!((declaredSize(node) ?? 0) >= CHART_MIN || ctx.util.closest(node, isFigure(ctx)))) continue+ const missing = missingChartLabels(node.raw ?? "")+ if (missing === null) defects.push(ctx.defect("chart_svg_no_text", node, `${label(node)} chart has no <text> and no <title>`))+ else if (missing.length) defects.push(ctx.defect("chart_svg_missing_labels", node, `${label(node)} chart is missing: ${missing.join(", ")}`))+ }+ return defects+ },+ },+ {+ codes: ["korean_serif_font"],+ run(ctx) {+ const defects = []+ const seen = new Set()+ for (const { node, families } of fontDeclarations(ctx)) {+ for (const family of families) {+ const key = family.toLowerCase().replace(/[\s"'_-]/g, "")+ if (!SERIF_FAMILY.test(key) || seen.has(key)) continue+ seen.add(key)+ defects.push(ctx.defect("korean_serif_font", node, `serif or brush Korean font family "${family}"`))+ }+ }+ return defects+ },+ },+]diff --git a/plugins/omo/skills/ulw-research/scripts/gates-layout.mjs b/plugins/omo/skills/ulw-research/scripts/gates-layout.mjsnew file mode 100644index 00000000..2c6ff8c6--- /dev/null+++ b/plugins/omo/skills/ulw-research/scripts/gates-layout.mjs@@ -0,0 +1,146 @@+// gates-layout.mjs - L1-L5 geometric gates over the layout probe output (boxes.json).+//+// Pure functions over the object layout-probe.mjs returns: no browser, no DOM, and selectors are+// taken verbatim from the probe (the probe already built them with the html-lite rule). Severities+// and hints are read from contracts.DEFECT_CODES, never set here. Measured pixel amounts are+// rounded to 0.1px (the probe's own precision) before a threshold compare, so float noise such as+// 2.000000000000001 never crosses a 2px limit.++import { DEFECT_CODES } from "./contracts.mjs"+import { PROBE_VERSION, ProbeError } from "./layout-probe.mjs"++/** Thresholds (draft D10): rounding tolerances, not taste. */+export const OVERFLOW_PX = 2+export const SCROLL_SLACK_PX = 2+export const ASPECT_DRIFT = 0.03+export const OVERLAP_PX = 12++const OUT_OF_FLOW = new Set(["absolute", "fixed"])+const IN_FLOW = new Set(["static", "relative"])+const CLIPPING = new Set(["hidden", "clip"])+const SCROLLING = new Set(["auto", "scroll"])+const ASPECT_SAFE_FITS = new Set(["cover", "contain", "scale-down"])++const r1 = (n) => Math.round(n * 10) / 10++/**+ * @typedef {{ code: string, severity: string, selector: string, line: null, message: string, hint: string }} Defect+ */+function defect(code, selector, message) {+ const { severity, hint } = DEFECT_CODES[code]+ return { code, severity, selector, line: null, message, hint }+}++// L1: the largest spill of the child rect past any side of its parent rect. A parent that scrolls+// on the spill axis makes it intentional scrolling (the advisory scroll container); a parent that+// clips on that axis hides the spilled content (text clipped).+function checkOverflow(box) {+ if (!box.parentRect || OUT_OF_FLOW.has(box.position)) return null+ const c = box.rect+ const p = box.parentRect+ const sides = [+ ["left", p.x - c.x],+ ["top", p.y - c.y],+ ["right", c.x + c.w - (p.x + p.w)],+ ["bottom", c.y + c.h - (p.y + p.h)],+ ].map(([side, px]) => [side, r1(px)])+ const [side, px] = sides.reduce((worst, entry) => (entry[1] > worst[1] ? entry : worst))+ if (px <= OVERFLOW_PX) return null+ const parentMode = box.parentOverflow?.[side === "left" || side === "right" ? "x" : "y"]+ if (SCROLLING.has(parentMode)) {+ return defect("layout_scroll_container", box.selector, `${box.tag} is ${px}px wider than ${box.parentSelector}, which scrolls (overflow: ${parentMode})`)+ }+ if (CLIPPING.has(parentMode)) {+ return defect("layout_text_clipped", box.selector, `${box.tag} spills ${px}px past the ${side} edge of ${box.parentSelector}, which clips it (overflow: ${parentMode})`)+ }+ return defect("layout_overflow", box.selector, `${box.tag} spills ${px}px past the ${side} edge of ${box.parentSelector}`)+}++// L2/L3: content larger than the box on an axis whose computed overflow clips or scrolls.+function checkScroll(box) {+ const { sw, cw, sh, ch } = box.scroll+ const axes = [+ ["x", sw - cw, box.overflow.x],+ ["y", sh - ch, box.overflow.y],+ ].filter(([, excess]) => r1(excess) > SCROLL_SLACK_PX)+ const clipped = axes.find(([, , mode]) => CLIPPING.has(mode))+ if (clipped) {+ const [axis, excess, mode] = clipped+ return defect("layout_text_clipped", box.selector, `${box.tag} content exceeds its box by ${r1(excess)}px on ${axis} under overflow: ${mode}`)+ }+ const scrolled = axes.find(([, , mode]) => SCROLLING.has(mode))+ if (scrolled) {+ const [axis, excess, mode] = scrolled+ return defect("layout_scroll_container", box.selector, `${box.tag} scrolls ${r1(excess)}px on ${axis} under overflow: ${mode}`)+ }+ return null+}++// L4: rendered aspect ratio drifting from the natural one without an aspect-preserving fit.+function checkAspect(box) {+ if (box.tag !== "img" || !box.natural) return null+ const { w, h } = box.rect+ const { w: nw, h: nh } = box.natural+ if (!(w > 0 && h > 0 && nw > 0 && nh > 0)) return null+ const fit = box.objectFit ?? "fill"+ if (ASPECT_SAFE_FITS.has(fit)) return null+ const drift = Math.abs(w / h / (nw / nh) - 1)+ if (drift <= ASPECT_DRIFT) return null+ const percent = (drift * 100).toFixed(1)+ return defect("layout_image_distorted", box.selector, `img rendered ${w}x${h} from natural ${nw}x${nh} distorts the aspect ratio by ${percent}% (object-fit: ${fit})`)+}++function intersection(a, b) {+ const ix = Math.min(a.x + a.w, b.x + b.w) - Math.max(a.x, b.x)+ const iy = Math.min(a.y + a.h, b.y + b.h) - Math.max(a.y, b.y)+ return { ix: r1(ix), iy: r1(iy) }+}++// L5: in-flow siblings (same parentSelector) whose rects intersect by more than 12px on both axes.+function checkSiblings(boxes) {+ const groups = new Map()+ for (const box of boxes) {+ if (box.parentSelector === null || box.parentSelector === undefined || !IN_FLOW.has(box.position)) continue+ const group = groups.get(box.parentSelector) ?? []+ group.push(box)+ groups.set(box.parentSelector, group)+ }+ const defects = []+ for (const group of groups.values()) {+ for (let i = 0; i < group.length; i += 1) {+ for (let j = i + 1; j < group.length; j += 1) {+ const { ix, iy } = intersection(group[i].rect, group[j].rect)+ if (Math.min(ix, iy) <= OVERLAP_PX) continue+ defects.push(defect("layout_sibling_overlap", group[i].selector, `${group[i].selector} and ${group[j].selector} overlap by ${ix}x${iy}px`))+ }+ }+ }+ return defects+}++function validateProbe(probe) {+ if (probe === null || typeof probe !== "object") throw new ProbeError("invalid_probe", "layout probe must be an object")+ if (probe.probe_version !== PROBE_VERSION) {+ throw new ProbeError("unsupported_probe_version", `layout probe_version must be ${PROBE_VERSION}, got ${probe.probe_version}`)+ }+ if (!Array.isArray(probe.boxes)) throw new ProbeError("invalid_probe", "layout probe boxes must be an array")+}++/**+ * @param {{ probe_version: number, count?: number, truncated?: boolean, boxes: object[] }} probe+ * @returns {{ defects: Defect[], summary: string }}+ */+export function checkLayout(probe) {+ validateProbe(probe)+ const defects = []+ for (const box of probe.boxes) {+ for (const rule of [checkOverflow, checkScroll, checkAspect]) {+ const found = rule(box)+ if (found) defects.push(found)+ }+ }+ defects.push(...checkSiblings(probe.boxes))+ let summary = `layout: ${probe.boxes.length} boxes checked, ${defects.length} defects`+ if (probe.truncated) summary += `; layout sample truncated`+ return { defects, summary }+}diff --git a/plugins/omo/skills/ulw-research/scripts/gates-static.mjs b/plugins/omo/skills/ulw-research/scripts/gates-static.mjsnew file mode 100644index 00000000..d24b1328--- /dev/null+++ b/plugins/omo/skills/ulw-research/scripts/gates-static.mjs@@ -0,0 +1,167 @@+// gates-static.mjs - deterministic static gates (G1-G15) over a parsed report.+//+// Builds one document context (a document-order walk with h2 sections, citation helpers and a+// defect factory) and hands it to the text, figure and structure gate modules. Every severity+// comes from contracts.DEFECT_CODES; the single override is unsourced_number under+// `Lineage: section`, derived from the spec mode passed in, never from a caller-supplied+// severity. Plain Node ESM, node: builtins and siblings only.++import * as nodeFs from "node:fs"++import { DEFECT_CODES, LINEAGE_MODES } from "./contracts.mjs"+import { customProperties } from "./css-lite.mjs"+import { figureGates } from "./gates-figures.mjs"+import { structureGates } from "./gates-structure.mjs"+import { textGates } from "./gates-text.mjs"+import { PROSE_TAGS, proseText, selectorPath } from "./html-lite.mjs"++const CITATION_MARKER = /\[S\d+\]|\[Source\s*\d+\]|\[\uCD9C\uCC98[^\]]*\]|\[\^\d+\]/i+const ANCHOR_HREF = /^#(?:s|src|source|ref|fn)/i+const ANCHOR_TEXT = /^\[(?:\uCD9C\uCC98|Source\s*\d+|S\d+)\]$/i+/** Closing ("how this report was made") heading; Korean alternates cover the same register. */+export const CLOSING_HEADING = /\b(?:method(?:ology)?|how)\b|\uB4B7\uBA74|\uBC29\uBC95|\uC5B4\uB5BB\uAC8C|\uB9CC\uB4E4\uC5B4/i+export const SOURCES_HEADING = /references|sources|bibliography|\uCD9C\uCC98|\uCC38\uACE0\s*(?:\uBB38\uD5CC|\uC790\uB8CC)/i+const OTHER_KINDS = [+ ["toc", /\b(?:contents|toc)\b|\uBAA9\uCC28/i],+ ["appendix", /appendix|\uBD80\uB85D/i],+ ["glossary", /glossary|\uC6A9\uC5B4/i],+]+const TEXT_SKIP = new Set(["code", "pre", "kbd", "samp", "script", "style", "svg", "template", "noscript"])+const HEADING_TAG = /^h[1-6]$/+/** The one sanctioned severity override: section-level lineage demotes unsourced_number. */+const SECTION_LINEAGE_SEVERITY = "minor"++const GATES = [...textGates, ...figureGates, ...structureGates]++function classTokens(node) {+ return String(node.attrs.class ?? "").toLowerCase().split(/\s+/).filter(Boolean)+}++function closest(node, predicate) {+ for (let cur = node.parent; cur; cur = cur.parent) if (predicate(cur)) return cur+ return null+}++function descendants(node, out = []) {+ for (const child of node.children) {+ if (child.tag === "#text") continue+ out.push(child)+ descendants(child, out)+ }+ return out+}++function isCitationAnchor(node) {+ return node.tag === "a" && (ANCHOR_HREF.test(node.attrs.href ?? "") || ANCHOR_TEXT.test(proseText(node)))+}++/** A citation marker in the element's prose or a citation anchor below it. */+function hasCitation(node) {+ return CITATION_MARKER.test(proseText(node)) || descendants(node).some(isCitationAnchor)+}++function toRegExp(pattern) {+ const re = pattern instanceof RegExp ? pattern : new RegExp(String(pattern), "i")+ return new RegExp(re.source, re.flags.replace(/[gy]/g, ""))+}++function findBody(doc) {+ const stack = [doc]+ while (stack.length) {+ const node = stack.pop()+ if (node.tag === "body") return node+ for (const child of node.children) if (child.tag !== "#text") stack.push(child)+ }+ return doc+}++function sectionKind(text, closingTest) {+ if (SOURCES_HEADING.test(text)) return "sources"+ if (closingTest(text)) return "closing"+ return OTHER_KINDS.find(([, re]) => re.test(text))?.[0] ?? null+}++/** Document-order walk of body: element scopes, prose text entries with owners, h2 sections. */+function walkBody(ctx, node, state) {+ for (const child of node.children) {+ if (child.tag === "#text") {+ if (state.skip) continue+ ctx.texts.push({ node: child, owner: state.owner ?? node, cell: state.cell, scope: ctx.scope })+ if (ctx.scope.section && !state.heading) ctx.scope.section.prose.push(child.text)+ continue+ }+ if (child.tag === "h2") {+ const section = { heading: child, kind: sectionKind(proseText(child), ctx.isClosing), prose: [], anchors: 0 }+ ctx.sections.push(section)+ ctx.scope = { section, closingH3: false }+ } else if (child.tag === "h3") {+ ctx.scope = { section: ctx.scope.section, closingH3: ctx.isClosing(proseText(child)) }+ }+ ctx.elements.push({ node: child, scope: ctx.scope })+ if (ctx.scope.section && isCitationAnchor(child)) ctx.scope.section.anchors+++ walkBody(ctx, child, {+ skip: state.skip || TEXT_SKIP.has(child.tag),+ owner: PROSE_TAGS.has(child.tag) ? child : state.owner,+ cell: state.cell || child.tag === "td" || child.tag === "th",+ heading: state.heading || HEADING_TAG.test(child.tag),+ })+ }+}++function buildContext(doc, options) {+ const lineageMode = options.lineageMode ?? "inline"+ if (!LINEAGE_MODES.includes(lineageMode)) throw new TypeError(`lineageMode must be one of ${LINEAGE_MODES.join(", ")}`)+ const closingPattern = options.closingPattern ? toRegExp(options.closingPattern) : null+ const all = descendants(doc)+ const styleBlocks = all.filter((node) => node.tag === "style").map((node) => ({ node, css: node.raw ?? "" }))+ const styleAttrs = all.filter((node) => node.attrs.style).map((node) => ({ node, css: node.attrs.style }))+ const ctx = {+ doc,+ body: findBody(doc),+ all,+ elements: [],+ texts: [],+ sections: [],+ scope: { section: null, closingH3: false },+ styleBlocks,+ styleAttrs,+ tokens: customProperties(styleBlocks.map((entry) => entry.css).join("\n")).light,+ palette: new Set(options.palette ?? []),+ requireSections: (options.requireSections ?? []).map(toRegExp),+ baseDir: options.baseDir ?? null,+ fs: options.fs ?? nodeFs,+ isClosing: (text) => CLOSING_HEADING.test(text) || Boolean(closingPattern?.test(text)),+ util: { classTokens, closest, descendants, hasCitation, citationMarker: CITATION_MARKER },+ kindOf: (scope) => (scope.closingH3 ? "closing" : (scope.section?.kind ?? null)),+ defect(code, node, message) {+ const entry = DEFECT_CODES[code]+ const severity = code === "unsourced_number" && lineageMode === "section" ? SECTION_LINEAGE_SEVERITY : entry.severity+ return { code, severity, selector: selectorPath(node) || node.tag, line: node.line, message, hint: entry.hint }+ },+ }+ walkBody(ctx, ctx.body, { skip: false, owner: null, cell: false, heading: false })+ return ctx+}++/**+ * Run G1-G15 over a parsed report (html-lite root).+ * @param {object} doc parseHtml(...) result+ * @param {{ palette?: Set<string>, lineageMode?: "inline"|"section", requireSections?: (RegExp|string)[],+ * baseDir?: string, fs?: { statSync(path: string): { size: number } }, closingPattern?: RegExp|string }} options+ * @returns {{ defects: object[], gatesRun: string[], gatesSkipped: string[] }}+ */+export function checkStatic(doc, options = {}) {+ const ctx = buildContext(doc, options)+ const defects = []+ const gatesRun = []+ const gatesSkipped = []+ for (const gate of GATES) {+ if (gate.skip?.(ctx)) {+ gatesSkipped.push(...gate.codes)+ continue+ }+ gatesRun.push(...gate.codes)+ defects.push(...gate.run(ctx))+ }+ return { defects, gatesRun, gatesSkipped }+}diff --git a/plugins/omo/skills/ulw-research/scripts/gates-structure.mjs b/plugins/omo/skills/ulw-research/scripts/gates-structure.mjsnew file mode 100644index 00000000..b7e5474e--- /dev/null+++ b/plugins/omo/skills/ulw-research/scripts/gates-structure.mjs@@ -0,0 +1,118 @@+// gates-structure.mjs - structure gates: G11 section without citation, G12 closing section,+// G13 citation section, G14 broken asset reference, G15 required sections.+//+// Each gate is { codes, skip?(ctx), run(ctx) -> Defect[] } over the context built by+// gates-static.mjs. Plain Node ESM, node: builtins and siblings only.++import { join } from "node:path"++import { proseText } from "./html-lite.mjs"++const MIN_SECTION_PROSE = 120+const UNCHECKED_KINDS = new Set(["closing", "sources", "toc", "appendix", "glossary"])+const DEFINITION_TAGS = new Set(["p", "li", "dd", "dt", "td"])+const DEFINITION_LINE = /^\[(S|Source\s*)(\d+)\]/i+const MIN_DEFINITIONS = 3+const NOT_RELATIVE = /^(?:[a-z][a-z\d+.-]*:|\/\/|\/|#)/i++function headingNodes(ctx, tags) {+ return ctx.elements.map(({ node }) => node).filter((node) => tags.includes(node.tag))+}++/** Local references an asset gate checks: img src, source srcset, stylesheet href, script src. */+function assetReferences(ctx) {+ const refs = []+ for (const node of ctx.all) {+ const { attrs } = node+ if (node.tag === "img" && attrs.src) refs.push({ node, url: attrs.src })+ else if (node.tag === "script" && attrs.src) refs.push({ node, url: attrs.src })+ else if (node.tag === "link" && attrs.href && /(?:^|\s)stylesheet(?:\s|$)/i.test(attrs.rel ?? "")) refs.push({ node, url: attrs.href })+ else if (node.tag === "source" && attrs.srcset) {+ for (const candidate of attrs.srcset.split(",")) {+ const url = candidate.trim().split(/\s+/)[0]+ if (url) refs.push({ node, url })+ }+ }+ }+ return refs.filter(({ url }) => url.trim() && !NOT_RELATIVE.test(url.trim()))+}++function localPath(baseDir, url) {+ const bare = url.trim().replace(/[?#].*$/, "")+ let decoded = bare+ try {+ decoded = decodeURIComponent(bare)+ } catch {+ // a malformed %-escape is kept verbatim; the stat below reports it as missing+ }+ return join(baseDir, ...decoded.split("/"))+}++function assetProblem(fs, file) {+ try {+ const stat = fs.statSync(file)+ return stat.size === 0 ? "is 0 bytes" : null+ } catch (error) {+ return `is missing (${error?.code ?? "stat failed"})`+ }+}++export const structureGates = [+ {+ codes: ["section_without_citation"],+ run(ctx) {+ const defects = []+ for (const section of ctx.sections) {+ if (UNCHECKED_KINDS.has(section.kind)) continue+ const prose = section.prose.join(" ").replace(/\s+/g, " ").trim()+ if (prose.length < MIN_SECTION_PROSE || section.anchors > 0 || ctx.util.citationMarker.test(prose)) continue+ const title = proseText(section.heading)+ defects.push(ctx.defect("section_without_citation", section.heading, `section "${title}" has ${prose.length} prose characters and no citation marker or anchor`))+ }+ return defects+ },+ },+ {+ codes: ["missing_closing_section"],+ run(ctx) {+ if (headingNodes(ctx, ["h2", "h3"]).some((node) => ctx.isClosing(proseText(node)))) return []+ return [ctx.defect("missing_closing_section", ctx.body, "no h2/h3 heading names how the report was made (method / how)")]+ },+ },+ {+ codes: ["missing_citation_section"],+ run(ctx) {+ if (ctx.sections.some((section) => section.kind === "sources")) return []+ const ids = new Set()+ for (const { node } of ctx.elements) {+ if (!DEFINITION_TAGS.has(node.tag)) continue+ const match = DEFINITION_LINE.exec(proseText(node))+ if (match) ids.add(`${match[1].trim().toLowerCase()}${match[2]}`)+ }+ if (ids.size >= MIN_DEFINITIONS) return []+ return [ctx.defect("missing_citation_section", ctx.body, `no references/sources h2 and ${ids.size} [S<n>] definition line(s) (< ${MIN_DEFINITIONS})`)]+ },+ },+ {+ codes: ["broken_asset_reference"],+ skip: (ctx) => !ctx.baseDir,+ run(ctx) {+ const defects = []+ for (const { node, url } of assetReferences(ctx)) {+ const problem = assetProblem(ctx.fs, localPath(ctx.baseDir, url))+ if (problem) defects.push(ctx.defect("broken_asset_reference", node, `<${node.tag}> asset "${url}" ${problem}`))+ }+ return defects+ },+ },+ {+ codes: ["missing_required_section"],+ skip: (ctx) => ctx.requireSections.length === 0,+ run(ctx) {+ const titles = headingNodes(ctx, ["h1", "h2", "h3", "h4", "h5", "h6"]).map((node) => proseText(node))+ return ctx.requireSections+ .filter((re) => !titles.some((title) => re.test(title)))+ .map((re) => ctx.defect("missing_required_section", ctx.body, `no heading matches the required section ${re}`))+ },+ },+]diff --git a/plugins/omo/skills/ulw-research/scripts/gates-text.mjs b/plugins/omo/skills/ulw-research/scripts/gates-text.mjsnew file mode 100644index 00000000..01c44700--- /dev/null+++ b/plugins/omo/skills/ulw-research/scripts/gates-text.mjs@@ -0,0 +1,190 @@+// gates-text.mjs - prose gates: G1 keep-all, G3 emoji, G4 dashes, G5/G6 headings, G7 unsourced numbers.+//+// Each gate is { codes, run(ctx) -> Defect[] } over the context built by gates-static.mjs.+// Plain Node ESM, sibling imports only.++import { proseText } from "./html-lite.mjs"++const HANGUL = /[\uAC00-\uD7A3]/g+const KEEP_ALL = /word-break\s*:\s*keep-all/i+const MIN_HANGUL = 20+/** Dingbats (2700-27BF) that render as emoji without FE0F (Emoji_Presentation=Yes). */+const DINGBAT_EMOJI = new Set([0x2705, 0x270a, 0x270b, 0x2728, 0x274c, 0x274e, 0x2753, 0x2754, 0x2755, 0x2757, 0x2795, 0x2796, 0x2797, 0x27b0, 0x27bf])+const EM_DASH = "\u2014"+const EN_DASH = "\u2013"+const HEADING_NUMBER = /^\s*(?:\d+(?:[.-]\d+)*[.):]?|[IVXLC]+[.)]|[A-Z][.)])\s+/+const GENERIC = new Set(["overview", "introduction", "background", "summary", "conclusion", "conclusions", "results", "discussion", "methodology"])+const MAX_HEADING_HANGUL = 26+const MAX_HEADING_WORDS = 12+const LINEAGE_TOKEN = /\b(?:MEASURED|ASSUMED|DERIVED)\b/+const NUMBER_CONTAINERS = new Set(["figure", "table", "nav", "header", "footer"])+const MAX_UNSOURCED = 50+const MONTH = "(?:jan|feb|mar|apr|may|jun|jul|aug|sep|sept|oct|nov|dec)[a-z]*\\.?"+/** Stripped before claim detection: dates, versions, figure refs, times, bare years. */+const NOT_CLAIMS = [+ /\b\d{4}[-./]\d{1,2}(?:[-./]\d{1,2})?\b/g,+ /\b\d{2}\.\d{2}\.\d{2}\b/g,+ /\d{2,4}\s*\uB144\s*\d{1,2}\s*\uC6D4(?:\s*\d{1,2}\s*\uC77C)?/g,+ /\d{1,2}\s*\uC6D4(?:\s*\d{1,2}\s*\uC77C)?/g,+ /(?:19|20)\d{2}\s*\uB144/g,+ new RegExp(`\\b${MONTH}\\s+\\d{1,2}(?:st|nd|rd|th)?(?:,?\\s+\\d{4})?`, "gi"),+ new RegExp(`\\b\\d{1,2}(?:st|nd|rd|th)?\\s+${MONTH}(?:\\s+\\d{4})?`, "gi"),+ /\bv\d+(?:\.\d+)*\b|\b\d+(?:\.\d+){2,}\b/gi,+ /\b(?:version|ver\.?|release)\s*\d+(?:\.\d+)*/gi,+ /\b(?:fig(?:ure)?\.?|table|chart|section|step|phase|wave|part)\s*\d+(?:\.\d+)*/gi,+ /(?:\uADF8\uB9BC|\uB3C4\uD45C|\uD45C|\uBC84\uC804)\s*\d+(?:\.\d+)*/g,+ /\b\d{1,2}:\d{2}\b/g,+ /\b(?:19|20)\d{2}s?\b/g,+]+const NUM = "(?<![\\p{L}\\d.,])\\d+(?:[.,]\\d+)*"+const UNIT =+ "(?:%|\\u2030|\\u00D7|\\uD37C\\uC13C\\uD2B8|\\uB2EC\\uB7EC|\\uC720\\uB85C|\\uC5D4|\\uC6D0|\\uB9CC|\\uC5B5|\\uC870|\\uCC9C|\\uCD08|\\uBD84|\\uC2DC\\uAC04|\\uC77C|\\uC8FC|\\uAC1C\\uC6D4|\\uB144|\\uBA85|\\uAC74|\\uAC1C|\\uD68C|\\uBC88|\\uBC30" ++ "|(?:percent|pp|bps?|x|k|m|b|bn|million|billion|thousand|trillion|usd|krw|eur|ms|s|secs?|seconds?|mins?|minutes?|h|hrs?|hours?|days?|weeks?|months?|years?|kb|mb|gb|tb|users?|people|employees|engineers|tokens?|requests?|stars?|downloads?|customers?)(?![\\p{L}\\d]))"+const CLAIMS = [+ new RegExp(`[$\\u20AC\\u00A3\\u00A5\\u20A9]\\s?${NUM}`, "u"),+ new RegExp(`${NUM}\\s?${UNIT}`, "iu"),+ /(?<![\d.,])\d{1,3}(?:,\d{3})+(?![\d,])/,+ /(?<![\d.])\d+\.\d+(?![\d.])/,+]++function snippet(text, index, span = 24) {+ return text.slice(Math.max(0, index - span), index + span).trim()+}++/** Concatenated prose per owning element, in document order; `keep` filters text entries. */+function ownerTexts(ctx, keep) {+ const byOwner = new Map()+ for (const entry of ctx.texts) {+ if (!keep(entry)) continue+ byOwner.set(entry.owner, (byOwner.get(entry.owner) ?? "") + entry.node.text)+ }+ return [...byOwner].map(([owner, text]) => ({ owner, text: text.replace(/\s+/g, " ") }))+}++function firstEmoji(text) {+ const chars = [...text]+ for (let i = 0; i < chars.length; i++) {+ const cp = chars[i].codePointAt(0)+ if (chars[i + 1] === "\uFE0F" && cp !== 0xfe0f) return chars[i] + chars[i + 1]+ if ((cp >= 0x1f000 && cp <= 0x1faff) || (cp >= 0x2600 && cp <= 0x26ff) || DINGBAT_EMOJI.has(cp)) return chars[i]+ }+ return null+}++const isDigit = (ch) => ch >= "0" && ch <= "9"++/** En dash allowed only when both neighbors (one optional space) are digits. */+function badEnDash(text) {+ for (let at = text.indexOf(EN_DASH); at !== -1; at = text.indexOf(EN_DASH, at + 1)) {+ const before = text[at - 1] === " " ? text[at - 2] : text[at - 1]+ const after = text[at + 1] === " " ? text[at + 2] : text[at + 1]+ if (!isDigit(before ?? "") || !isDigit(after ?? "")) return at+ }+ return -1+}++const stripNumbering = (text) => text.replace(HEADING_NUMBER, "").trim()++function headings(ctx, max) {+ return ctx.elements.filter(({ node }) => /^h[1-6]$/.test(node.tag) && Number(node.tag[1]) <= max).map(({ node }) => node)+}++/** Citation markers need no stripping: an element carrying one is skipped before this runs. */+function claimIn(text) {+ let rest = text+ for (const re of NOT_CLAIMS) rest = rest.replace(re, " ")+ for (const re of CLAIMS) {+ const match = re.exec(rest)+ if (match) return match[0].trim()+ }+ return null+}++function numberCandidates(ctx) {+ const { closest, classTokens, descendants } = ctx.util+ return ctx.elements.filter(({ node, scope }) => {+ if (node.tag !== "p" && node.tag !== "li") return false+ if (node.tag === "li" && descendants(node).some((child) => child.tag === "p" || child.tag === "li")) return false+ const kind = ctx.kindOf(scope)+ if (kind === "closing" || kind === "sources") return false+ return !closest(node, (cur) => NUMBER_CONTAINERS.has(cur.tag) || classTokens(cur).includes("fig"))+ })+}++export const textGates = [+ {+ codes: ["korean_no_keep_all"],+ run(ctx) {+ const syllables = ctx.texts.reduce((sum, entry) => sum + (entry.node.text.match(HANGUL)?.length ?? 0), 0)+ if (syllables < MIN_HANGUL) return []+ if ([...ctx.styleBlocks, ...ctx.styleAttrs].some((entry) => KEEP_ALL.test(entry.css))) return []+ return [ctx.defect("korean_no_keep_all", ctx.body, `${syllables} Hangul syllables in prose and no "word-break: keep-all" in any style block or style attribute`)]+ },+ },+ {+ codes: ["emoji_in_prose"],+ run(ctx) {+ const defects = []+ for (const { owner, text } of ownerTexts(ctx, () => true)) {+ const emoji = firstEmoji(text)+ if (emoji) defects.push(ctx.defect("emoji_in_prose", owner, `emoji "${emoji}" in <${owner.tag}>: "${snippet(text, text.indexOf(emoji))}"`))+ }+ return defects+ },+ },+ {+ codes: ["em_dash_in_prose", "en_dash_in_prose"],+ run(ctx) {+ const defects = []+ const inScope = (entry) => !entry.cell && ctx.kindOf(entry.scope) !== "sources"+ for (const { owner, text } of ownerTexts(ctx, inScope)) {+ const em = text.indexOf(EM_DASH)+ if (em !== -1) defects.push(ctx.defect("em_dash_in_prose", owner, `em dash "${EM_DASH}" in <${owner.tag}>: "${snippet(text, em)}"`))+ const en = badEnDash(text)+ if (en !== -1) defects.push(ctx.defect("en_dash_in_prose", owner, `en dash "${EN_DASH}" outside a numeric range in <${owner.tag}>: "${snippet(text, en)}"`))+ }+ return defects+ },+ },+ {+ codes: ["heading_too_long"],+ run(ctx) {+ const defects = []+ for (const node of headings(ctx, 4)) {+ const text = stripNumbering(proseText(node))+ const hangul = /[\uAC00-\uD7A3]/.test(text)+ const size = hangul ? [...text].length : text.split(/\s+/).filter(Boolean).length+ if (size > (hangul ? MAX_HEADING_HANGUL : MAX_HEADING_WORDS)) {+ defects.push(ctx.defect("heading_too_long", node, `<${node.tag}> "${text}" is ${size} ${hangul ? "characters (> 26)" : "words (> 12)"}`))+ }+ }+ return defects+ },+ },+ {+ codes: ["heading_generic"],+ run(ctx) {+ const defects = []+ for (const node of headings(ctx, 3)) {+ const text = stripNumbering(proseText(node))+ if (GENERIC.has(text.toLowerCase().replace(/[.:]+$/, ""))) defects.push(ctx.defect("heading_generic", node, `generic <${node.tag}> "${text}"`))+ }+ return defects+ },+ },+ {+ codes: ["unsourced_number"],+ run(ctx) {+ const defects = []+ for (const { node } of numberCandidates(ctx)) {+ if (defects.length >= MAX_UNSOURCED) break+ const text = proseText(node)+ if (LINEAGE_TOKEN.test(text) || ctx.util.hasCitation(node)) continue+ if (node.attrs["data-lineage"] !== undefined || ctx.util.descendants(node).some((child) => child.attrs["data-lineage"] !== undefined)) continue+ const claim = claimIn(text)+ if (claim) defects.push(ctx.defect("unsourced_number", node, `number "${claim}" without a lineage tag or citation: "${snippet(text, text.indexOf(claim))}"`))+ }+ return defects+ },+ },+]diff --git a/plugins/omo/skills/ulw-research/scripts/html-lite.mjs b/plugins/omo/skills/ulw-research/scripts/html-lite.mjsnew file mode 100644index 00000000..64e64532--- /dev/null+++ b/plugins/omo/skills/ulw-research/scripts/html-lite.mjs@@ -0,0 +1,239 @@+// html-lite.mjs - a dependency-free HTML tokenizer for report checks.+//+// Single forward scan with indexOf (no whole-document regex, no backtracking). Produces a+// LiteNode tree: { tag, attrs, children, parent, line, text, raw }. Text nodes carry+// tag "#text"; <style>/<script>/<svg> keep their inner source in `raw` and have no parsed+// children. The "#document" root also carries `ids` (id -> occurrence count) so+// selectorPath can tell whether an id is unique. Plain Node ESM, no dependencies.++import { decodeEntities } from "./entities.mjs"++export { decodeEntities }++const VOID_TAGS = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"])+const RAW_TAGS = new Set(["style", "script", "svg"])+const HEADINGS = ["h1", "h2", "h3", "h4", "h5", "h6"]+const P_CLOSERS = new Set([+ "address", "article", "blockquote", "details", "div", "dl", "fieldset", "figcaption", "figure", "footer",+ "form", "header", "hr", "main", "menu", "nav", "ol", "p", "pre", "section", "table", "ul", ...HEADINGS,+])+const P_SCOPE = new Set(["td", "th", "caption", "button", "body", "html"])+const LI_SCOPE = new Set(["ul", "ol", "menu", "body", "html"])+const PROSE_SKIP = new Set(["code", "pre", "kbd", "samp", "script", "style", "svg"])+const SAFE_ID = /^[A-Za-z_][\w-]*$/++export const PROSE_TAGS = new Set(["p", "li", ...HEADINGS, "td", "th", "figcaption", "blockquote", "dd", "dt"])+const PROSE_BREAKS = new Set([...P_CLOSERS, ...PROSE_TAGS, "br", "tr"])++function makeNode(tag, attrs, parent, line) {+ return { tag, attrs, children: [], parent, line, text: "", raw: null }+}++function lineStarts(source) {+ const starts = [0]+ for (let at = source.indexOf("\n"); at !== -1; at = source.indexOf("\n", at + 1)) starts.push(at + 1)+ return starts+}++function lineAt(starts, offset) {+ let lo = 0+ let hi = starts.length - 1+ while (lo < hi) {+ const mid = (lo + hi + 1) >> 1+ if (starts[mid] <= offset) lo = mid+ else hi = mid - 1+ }+ return lo + 1+}++const isSpace = (ch) => ch === " " || ch === "\n" || ch === "\t" || ch === "\r" || ch === "\f"+const isLetter = (ch) => (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z")++function skipSpaces(source, at) {+ while (at < source.length && isSpace(source[at])) at+++ return at+}++/** Read `<name attrs...>` starting just after `<`. */+function readTag(source, start) {+ const end = source.length+ let at = start+ while (at < end && !isSpace(source[at]) && source[at] !== ">" && source[at] !== "/") at+++ const name = source.slice(start, at).toLowerCase()+ const attrs = {}+ let selfClosing = false+ while (at < end) {+ const ch = source[at]+ if (isSpace(ch)) { at++; continue }+ if (ch === ">") return { name, attrs, end: at + 1, selfClosing }+ selfClosing = ch === "/" && source[at + 1] === ">"+ if (ch === "/") { at++; continue }+ let stop = at + 1+ while (stop < end && !isSpace(source[stop]) && source[stop] !== "/" && source[stop] !== ">" && source[stop] !== "=") stop+++ const key = source.slice(at, stop).toLowerCase()+ at = skipSpaces(source, stop)+ let value = ""+ if (source[at] === "=") {+ at = skipSpaces(source, at + 1)+ const quote = source[at]+ if (quote === '"' || quote === "'") {+ const close = source.indexOf(quote, at + 1)+ const valueEnd = close === -1 ? end : close+ value = source.slice(at + 1, valueEnd)+ at = valueEnd + 1+ } else {+ let valueEnd = at+ while (valueEnd < end && !isSpace(source[valueEnd]) && source[valueEnd] !== ">") valueEnd+++ value = source.slice(at, valueEnd)+ at = valueEnd+ }+ }+ if (key !== "__proto__" && !Object.hasOwn(attrs, key)) attrs[key] = decodeEntities(value)+ }+ return { name, attrs, end, selfClosing }+}++function tagNameAt(source, at, tag) {+ if (source.slice(at, at + tag.length).toLowerCase() !== tag) return false+ const next = source[at + tag.length] ?? ">"+ return isSpace(next) || next === ">" || next === "/"+}++/** Find the close of a raw element; nested <svg> is depth-counted. Returns [innerEnd, resumeAt]. */+function findRawClose(source, from, tag) {+ let depth = 0+ for (let lt = source.indexOf("<", from); lt !== -1; lt = source.indexOf("<", lt + 1)) {+ if (source[lt + 1] === "/" && tagNameAt(source, lt + 2, tag)) {+ if (depth === 0) {+ const gt = source.indexOf(">", lt)+ return [lt, gt === -1 ? source.length : gt + 1]+ }+ depth--+ } else if (tag === "svg" && tagNameAt(source, lt + 1, tag)) {+ depth+++ }+ }+ return [source.length, source.length]+}++/** Parse an HTML string into a LiteNode tree rooted at "#document"; never throws on malformed input. */+export function parseHtml(source) {+ const src = String(source)+ const starts = lineStarts(src)+ const root = makeNode("#document", {}, null, 1)+ root.ids = new Map()+ const stack = [root]+ let sawBody = false+ let textStart = 0+ let at = 0+ const top = () => stack[stack.length - 1]+ const flushText = (to) => {+ if (to > textStart) {+ const node = makeNode("#text", {}, top(), lineAt(starts, textStart))+ node.text = decodeEntities(src.slice(textStart, to))+ top().children.push(node)+ }+ }+ const closeWithin = (tag, scope) => {+ for (let k = stack.length - 1; k > 0; k--) {+ if (stack[k].tag === tag) { stack.length = k; return }+ if (scope.has(stack[k].tag)) return+ }+ }+ while (at < src.length) {+ const lt = src.indexOf("<", at)+ if (lt === -1) break+ const next = src[lt + 1] ?? ""+ if (src.startsWith("<!--", lt)) {+ flushText(lt)+ const close = src.indexOf("-->", lt + 4)+ at = textStart = close === -1 ? src.length : close + 3+ } else if (next === "!" || next === "?") {+ flushText(lt)+ const close = src.indexOf(">", lt)+ at = textStart = close === -1 ? src.length : close + 1+ } else if (next === "/" && isLetter(src[lt + 2] ?? "")) {+ flushText(lt)+ const tag = readTag(src, lt + 2)+ if (tag.name !== "body" && tag.name !== "html") {+ for (let k = stack.length - 1; k > 0; k--) {+ if (stack[k].tag === tag.name) { stack.length = k; break }+ }+ }+ at = textStart = tag.end+ } else if (isLetter(next)) {+ flushText(lt)+ const tag = readTag(src, lt + 1)+ at = textStart = tag.end+ if ((tag.name === "html" || tag.name === "body" || tag.name === "head") && stack.some((n) => n.tag === tag.name)) continue+ if (P_CLOSERS.has(tag.name)) closeWithin("p", P_SCOPE)+ if (tag.name === "li") closeWithin("li", LI_SCOPE)+ const node = makeNode(tag.name, tag.attrs, top(), lineAt(starts, lt))+ top().children.push(node)+ if (tag.name === "body") sawBody = true+ if (tag.attrs.id) root.ids.set(tag.attrs.id, (root.ids.get(tag.attrs.id) ?? 0) + 1)+ if (RAW_TAGS.has(tag.name)) {+ node.raw = ""+ if (!tag.selfClosing) {+ const [innerEnd, resume] = findRawClose(src, tag.end, tag.name)+ node.raw = src.slice(tag.end, innerEnd)+ at = textStart = resume+ }+ } else if (!VOID_TAGS.has(tag.name)) {+ stack.push(node)+ }+ } else {+ at = lt + 1+ }+ }+ flushText(src.length)+ if (!sawBody) wrapInBody(root)+ return root+}++/** Fragments without <body>: move everything except <head> under a synthesized body. */+function wrapInBody(root) {+ const host = root.children.find((child) => child.tag === "html") ?? root+ const kept = host.children.filter((child) => child.tag === "head")+ const moved = host.children.filter((child) => child.tag !== "head")+ const body = makeNode("body", {}, host, moved[0]?.line ?? 1)+ for (const child of moved) child.parent = body+ body.children = moved+ host.children = [...kept, body]+}++function segment(node) {+ const same = node.parent.children.filter((child) => child.tag === node.tag)+ return same.length > 1 ? `${node.tag}:nth-of-type(${same.indexOf(node) + 1})` : node.tag+}++/** CSS selector for a node: nearest unique-id anchor, else `body > tag:nth-of-type(k) > ...`. */+export function selectorPath(node) {+ let root = node+ while (root.parent) root = root.parent+ const ids = root.ids ?? new Map()+ const segments = []+ for (let cur = node.tag === "#text" ? node.parent : node; cur?.parent; cur = cur.parent) {+ const id = cur.attrs.id+ if (id && SAFE_ID.test(id) && ids.get(id) === 1) return [`#${id}`, ...segments].join(" > ")+ if (cur.tag === "body") return ["body", ...segments].join(" > ")+ if (cur.tag === "html") break+ segments.unshift(segment(cur))+ }+ return segments.join(" > ")+}++/** Descendant text minus code/pre/kbd/samp/script/style/svg, whitespace collapsed. */+export function proseText(node) {+ const parts = []+ const walk = (cur) => {+ if (cur.tag === "#text") { parts.push(cur.text); return }+ if (PROSE_SKIP.has(cur.tag)) return+ const breaks = PROSE_BREAKS.has(cur.tag)+ if (breaks) parts.push(" ")+ for (const child of cur.children) walk(child)+ if (breaks) parts.push(" ")+ }+ for (const child of node.children) walk(child)+ return parts.join("").replace(/\s+/g, " ").trim()+}diff --git a/plugins/omo/skills/ulw-research/scripts/layout-probe.mjs b/plugins/omo/skills/ulw-research/scripts/layout-probe.mjsnew file mode 100644index 00000000..70b963ad--- /dev/null+++ b/plugins/omo/skills/ulw-research/scripts/layout-probe.mjs@@ -0,0 +1,83 @@+// layout-probe.mjs - the in-page probe the layout gates consume.+//+// buildProbeSource() returns ONE async IIFE expression (the engine's evaluate awaits it): it first+// forces lazy images to load eagerly and awaits their decode (bounded), so natural sizes are real. The orchestrator evaluates it in the rendered+// report through the browser skill's owned headless engine and writes the result to boxes.json;+// gates-layout.mjs reads that file. This module never launches a browser.+//+// Selector paths use the SAME rule as html-lite.selectorPath (a unique safe #id anchors the path,+// otherwise tag segments with :nth-of-type(k) only when the parent has more than one child of that+// tag, prefixed "body"), so a layout defect can be mapped back to the static tree. The rule lives in+// PATH_FUNCTION_SOURCE, embedded verbatim in the probe and exercised by the parity test.++export const PROBE_VERSION = 1+export const SAMPLED_SELECTOR = "figure, .fig, img, svg, table, h1, h2, h3, p, pre"+export const EXCLUDED_ANCESTORS = Object.freeze(["svg", "nav", "header", "footer"])++/** In-page path rule. idCount(id) returns how many elements carry that id. */+export const PATH_FUNCTION_SOURCE = `function ulwSelectorPath(el, idCount) {+ const SAFE_ID = /^[A-Za-z_][\\w-]*$/;+ const segments = [];+ for (let cur = el; cur && cur.parentElement; cur = cur.parentElement) {+ const tag = cur.tagName.toLowerCase();+ const id = cur.id;+ if (id && SAFE_ID.test(id) && idCount(id) === 1) return ["#" + id].concat(segments).join(" > ");+ if (tag === "body") return ["body"].concat(segments).join(" > ");+ if (tag === "html") break;+ const same = Array.from(cur.parentElement.children).filter((c) => c.tagName === cur.tagName);+ segments.unshift(same.length > 1 ? tag + ":nth-of-type(" + (same.indexOf(cur) + 1) + ")" : tag);+ }+ return segments.join(" > ");+}`++export class ProbeError extends Error {+ constructor(code, message) {+ super(message)+ this.name = "ProbeError"+ this.code = code+ }+}++/** @param {{ cap?: number, root?: string }} [options] */+export function buildProbeSource({ cap = 400, root = "main, article" } = {}) {+ if (!Number.isInteger(cap) || cap <= 0) throw new ProbeError("invalid_cap", `--cap requires a positive integer, got ${cap}`)+ if (typeof root !== "string" || root.trim().length === 0) throw new ProbeError("invalid_root", "--root requires a non-empty CSS selector")+ return `(async () => {+ const CAP = ${cap};+ const IMAGE_WAIT_MS = 5000;+ const ROOT = document.querySelector(${JSON.stringify(root)}) || document.body;+ const EXCLUDED = ${JSON.stringify(EXCLUDED_ANCESTORS)};+ const images = Array.from(document.images);+ for (const img of images) if (img.loading === "lazy") img.loading = "eager";+ const settle = Promise.all(images.map((img) => (img.complete && img.naturalWidth > 0 ? null : img.decode().catch(() => null))));+ await Promise.race([settle, new Promise((resolve) => setTimeout(resolve, IMAGE_WAIT_MS))]);+ ${PATH_FUNCTION_SOURCE}+ const idCount = (id) => document.querySelectorAll("#" + CSS.escape(id)).length;+ const path = (el) => ulwSelectorPath(el, idCount);+ const r1 = (n) => Math.round(n * 10) / 10;+ const rect = (el) => { const b = el.getBoundingClientRect(); return { x: r1(b.left + scrollX), y: r1(b.top + scrollY), w: r1(b.width), h: r1(b.height) }; };+ const excluded = (el) => { for (let p = el.parentElement; p; p = p.parentElement) if (EXCLUDED.includes(p.tagName.toLowerCase())) return true; return false; };+ const all = Array.from(ROOT.querySelectorAll(${JSON.stringify(SAMPLED_SELECTOR)})).filter((el) => {+ if (excluded(el)) return false;+ const b = el.getBoundingClientRect();+ return b.width > 0 || b.height > 0;+ });+ const boxes = all.slice(0, CAP).map((el) => {+ const cs = getComputedStyle(el);+ const parent = el.parentElement;+ const box = {+ selector: path(el), tag: el.tagName.toLowerCase(), rect: rect(el),+ parentSelector: parent ? path(parent) : null, parentRect: parent ? rect(parent) : null,+ parentOverflow: parent ? { x: getComputedStyle(parent).overflowX, y: getComputedStyle(parent).overflowY } : null,+ scroll: { sw: el.scrollWidth, cw: el.clientWidth, sh: el.scrollHeight, ch: el.clientHeight },+ overflow: { x: cs.overflowX, y: cs.overflowY }, position: cs.position,+ textLen: (el.textContent || "").trim().length,+ };+ if (el.tagName === "IMG") { box.objectFit = cs.objectFit; box.natural = { w: el.naturalWidth, h: el.naturalHeight }; }+ return box;+ });+ return { probe_version: ${PROBE_VERSION}, viewport: { w: innerWidth, h: innerHeight },+ document: { w: document.documentElement.scrollWidth, h: document.documentElement.scrollHeight },+ count: all.length, truncated: all.length > CAP, boxes };+})()`+}diff --git a/plugins/omo/skills/ulw-research/scripts/outcome.mjs b/plugins/omo/skills/ulw-research/scripts/outcome.mjsnew file mode 100644index 00000000..dfba2264--- /dev/null+++ b/plugins/omo/skills/ulw-research/scripts/outcome.mjs@@ -0,0 +1,250 @@+// outcome.mjs - the per-run outcome manifest (`outcome.json`) and the closing briefing.+// Manifest functions are pure (they return a new manifest); the briefing reads only the+// manifest, the sources-ledger text, and an injected `now`. node: builtins only.++import * as nodeFs from "node:fs"+import { basename, dirname, join } from "node:path"++import { DELIVERABLE_FORMATS, DELIVERABLE_STATUSES, GATE_NAMES, GATE_STATUSES, LANES } from "./contracts.mjs"+import { MANIFEST_CODES, SCHEMA_VERSION, validateOutcomeManifest } from "./contracts.mjs"++export const MANIFEST_FILENAME = "outcome.json"+const MISSING = MANIFEST_CODES[0]+const SESSION_STAMP = /^(\d{4})(\d{2})(\d{2})-(\d{2})(\d{2})(\d{2})$/+const SOURCE_LINE = /^\[(S|Source )\d+\]/+const URL_PATTERN = /https?:\/\/[^\s)<>\]"'`]+/g+const DRAFT_MARKER = "STATUS: draft"+const DRAFT_SCAN_LINES = 5+const REASON_REQUIRED = new Set(["blocked_capability", "skipped", "failed"])++export class OutcomeError extends Error {+ /** @param {string} code @param {string} message @param {readonly string[]} [allowed] */+ constructor(code, message, allowed) {+ super(message)+ this.name = "OutcomeError"+ this.code = code+ if (allowed) this.allowed = [...allowed]+ }+}++function assertOneOf(code, label, value, allowed) {+ if (!allowed.includes(value)) {+ throw new OutcomeError(code, `unknown ${label} ${JSON.stringify(value)}; allowed: ${allowed.join(", ")}`, allowed)+ }+}++const clone = (manifest) => structuredClone(manifest)+const isMissing = (error) => error?.code === "ENOENT" || error?.code === "ENOTDIR"++function stamp(now) {+ return (now ?? new Date()).toISOString()+}++/** Local wall-clock start time from a `YYYYMMDD-HHMMSS` session dir basename. */+export function parseSessionStart(sessionDir) {+ const match = SESSION_STAMP.exec(basename(sessionDir))+ if (!match) throw new OutcomeError("invalid_session_dir", `session dir basename must be YYYYMMDD-HHMMSS: ${sessionDir}`)+ const [y, mo, d, h, mi, s] = match.slice(1).map(Number)+ const date = new Date(y, mo - 1, d, h, mi, s)+ if (date.getMonth() !== mo - 1 || date.getDate() !== d || date.getHours() !== h) {+ throw new OutcomeError("invalid_session_dir", `session dir basename is not a real local time: ${sessionDir}`)+ }+ return date+}++/** @param {{ sessionDir: string, promised: string[], lane: string|null, interview?: object|null, now?: Date }} input */+export function initManifest({ sessionDir, promised, lane, interview = null, now }) {+ const startedAt = parseSessionStart(sessionDir).toISOString()+ if (lane !== null && lane !== undefined) assertOneOf("unknown_lane", "lane", lane, LANES)+ const formats = [...new Set(promised)]+ for (const format of formats) assertOneOf("unknown_format", "deliverable format", format, DELIVERABLE_FORMATS)+ const updatedAt = stamp(now)+ return {+ schemaVersion: SCHEMA_VERSION,+ sessionDir,+ startedAt,+ finishedAt: null,+ elapsedMinutes: null,+ lane: lane ?? null,+ interview,+ deliverables: formats.map((format) => ({ format, status: "pending", promised: true, updatedAt })),+ renders: [],+ gates: Object.fromEntries(GATE_NAMES.map((gate) => [gate, "not_run"])),+ residualDefects: [],+ repair: null,+ sources: null,+ }+}++/**+ * Set one format's row; every other row is kept as is. An unpromised format gets a new+ * row with promised=false. The row's detail fields are replaced by the ones given.+ * @param {{ path?: string, reason?: string, pages?: number, bytes?: number, now?: Date }} [detail]+ */+export function setDeliverable(manifest, format, status, detail = {}) {+ assertOneOf("unknown_format", "deliverable format", format, DELIVERABLE_FORMATS)+ assertOneOf("unknown_status", "deliverable status", status, DELIVERABLE_STATUSES)+ const next = clone(manifest)+ const index = next.deliverables.findIndex((row) => row.format === format)+ const row = { format, status, promised: index >= 0 ? next.deliverables[index].promised : false, updatedAt: stamp(detail.now) }+ for (const key of ["path", "reason", "pages", "bytes"]) {+ if (detail[key] !== undefined) row[key] = detail[key]+ }+ if (index >= 0) next.deliverables[index] = row+ else next.deliverables.push(row)+ return next+}++export function setGate(manifest, gate, status) {+ assertOneOf("unknown_gate", "gate", gate, GATE_NAMES)+ assertOneOf("unknown_gate_status", "gate status", status, GATE_STATUSES)+ const next = clone(manifest)+ next.gates[gate] = status+ return next+}++export function addRender(manifest, path, page) {+ if (typeof path !== "string" || path.length === 0) throw new OutcomeError("invalid_render", "render path must be a non-empty string")+ if (!Number.isInteger(page) || page < 1) throw new OutcomeError("invalid_render", `render page must be an integer >= 1, got ${page}`)+ const next = clone(manifest)+ if (!next.renders.some((render) => render.path === path && render.page === page)) next.renders.push({ path, page })+ return next+}++function fileSize(fs, path) {+ try {+ const stat = fs.statSync(path)+ return stat.isFile() ? stat.size : null+ } catch (error) {+ if (isMissing(error)) return null+ throw error+ }+}++/**+ * @param {object} manifest+ * @param {{ statSync: typeof nodeFs.statSync }} [fs]+ * @returns {{ ok: boolean, problems: { code: string, format: string, message: string, path?: string }[] }}+ */+export function verifyManifest(manifest, fs = nodeFs) {+ const problems = []+ for (const row of manifest.deliverables) {+ const problem = (message, path) => problems.push({ code: MISSING, format: row.format, message, ...(path ? { path } : {}) })+ if (row.status === "pending") problem(`${row.format} is still pending`)+ else if (row.status === "delivered") {+ if (!row.path) problem(`${row.format} is delivered without a path`)+ else {+ const size = fileSize(fs, row.path)+ if (size === null) problem(`${row.format} delivered file is missing: ${row.path}`, row.path)+ else if (size === 0) problem(`${row.format} delivered file is empty: ${row.path}`, row.path)+ }+ } else if (REASON_REQUIRED.has(row.status) && !row.reason) problem(`${row.format} is ${row.status} without a reason`)+ }+ return { ok: problems.length === 0, problems }+}++/**+ * none = missing or empty file; partial = `STATUS: draft` in the first 5 lines, or the+ * manifest (given, else a sibling outcome.json) still has a pending row; else complete.+ * @returns {"none"|"partial"|"complete"}+ */+export function deliverableState(deliverablePath, manifestOrNull) {+ let text+ try {+ text = nodeFs.readFileSync(deliverablePath, "utf8")+ } catch (error) {+ if (isMissing(error)) return "none"+ throw error+ }+ if (text.trim() === "") return "none"+ if (text.split(/\r?\n/, DRAFT_SCAN_LINES).some((line) => line.includes(DRAFT_MARKER))) return "partial"+ const sibling = join(dirname(deliverablePath), MANIFEST_FILENAME)+ const manifest = manifestOrNull ?? (nodeFs.existsSync(sibling) ? readManifest(sibling) : null)+ if (manifest && manifest.deliverables.some((row) => row.status === "pending")) return "partial"+ return "complete"+}++/** Hostname without a leading `www.`; null for a string URL cannot parse (not a source host). */+function hostOf(url) {+ return URL.canParse(url) ? new URL(url).hostname.toLowerCase().replace(/^www\./, "") : null+}++function repairSummary(repair) {+ if (!repair) return null+ const attempts = Array.isArray(repair.attempts) ? repair.attempts.length : repair.attempts ?? null+ return { attempts, action: repair.decision?.action ?? repair.action ?? null, reason: repair.decision?.reason ?? repair.reason ?? null }+}++/** The briefing numbers, from the manifest + ledger text + injected `now` only. */+export function briefingFacts(manifest, sourcesLedgerText, now) {+ const sourceLines = String(sourcesLedgerText ?? "").split(/\r?\n/).filter((line) => SOURCE_LINE.test(line))+ const hosts = new Set()+ for (const line of sourceLines) {+ for (const url of line.match(URL_PATTERN) ?? []) {+ const host = hostOf(url)+ if (host) hosts.add(host)+ }+ }+ const elapsedMs = now.getTime() - new Date(manifest.startedAt).getTime()+ return {+ sources: sourceLines.length,+ domains: hosts.size,+ hosts: [...hosts].sort(),+ minutes: Math.max(0, Math.round(elapsedMs / 60000)),+ deliverables: manifest.deliverables.map((row) => ({ format: row.format, status: row.status, reason: row.reason ?? null, path: row.path ?? null })),+ gates: { ...manifest.gates },+ residualDefects: manifest.residualDefects.length,+ repair: repairSummary(manifest.repair),+ }+}++/** The closing briefing block as plain text. */+export function buildBriefing(manifest, sourcesLedgerText, now) {+ const facts = briefingFacts(manifest, sourcesLedgerText, now)+ const repair = facts.repair+ ? `${facts.repair.attempts ?? "?"} attempt(s), last decision ${facts.repair.action ?? "?"} (${facts.repair.reason ?? "?"})`+ : "not run"+ return [+ "Closing briefing",+ `- Sources: ${facts.sources} from ${facts.domains} distinct domain(s), counted from the sources ledger.`,+ `- Elapsed: ${facts.minutes} minute(s) since ${manifest.startedAt}.`,+ "- Deliverables:",+ " | format | status | detail |",+ " |---|---|---|",+ ...facts.deliverables.map((row) => ` | ${row.format} | ${row.status} | ${row.reason ?? row.path ?? ""} |`),+ `- Gates: ${GATE_NAMES.map((gate) => `${gate} ${facts.gates[gate]}`).join(", ")}.`,+ `- Residual defects: ${facts.residualDefects}.`,+ `- Repair: ${repair}.`,+ ].join("\n")+}++function assertValid(manifest, where) {+ const { ok, errors } = validateOutcomeManifest(manifest)+ if (!ok) throw new OutcomeError("invalid_manifest", `${where}: ${errors.join("; ")}`)+}++export function readManifest(file) {+ let manifest+ try {+ manifest = JSON.parse(nodeFs.readFileSync(file, "utf8"))+ } catch (error) {+ if (error instanceof SyntaxError) throw new OutcomeError("invalid_manifest", `${file}: not valid JSON (${error.message})`)+ throw error+ }+ assertValid(manifest, file)+ return manifest+}++/** Validate, then write atomically (temp file in the same dir + rename). */+export function writeManifest(file, manifest) {+ assertValid(manifest, file)+ const temp = join(dirname(file), `.${basename(file)}.${process.pid}.${Date.now()}.tmp`)+ try {+ nodeFs.writeFileSync(temp, `${JSON.stringify(manifest, null, "\t")}\n`, "utf8")+ nodeFs.renameSync(temp, file)+ } catch (error) {+ nodeFs.rmSync(temp, { force: true })+ throw error+ }+ return file+}diff --git a/plugins/omo/skills/ulw-research/scripts/repair-tracker.mjs b/plugins/omo/skills/ulw-research/scripts/repair-tracker.mjsnew file mode 100644index 00000000..ee9ee1cc--- /dev/null+++ b/plugins/omo/skills/ulw-research/scripts/repair-tracker.mjs@@ -0,0 +1,171 @@+// repair-tracker.mjs - the bounded repair loop as a pure state machine.+//+// Every decide() call is one check of the current artifact: the first call is attempt 0 (the+// initial check), each later call follows one repair already taken. The loop stops on max+// attempts, a measure plateau, a repeated defect signature (oscillation), or the wall clock.+// On a stop the artifact is delivered with its residual defects unless a content-integrity+// code remains, which blocks delivery. Time is always injected; this module never reads a+// clock. Severities come from contracts.mjs only, so no caller can demote a defect.++import { DEFECT_CODES, INTEGRITY_CODES, REPAIR_DEFAULTS, SCHEMA_VERSION, validateRepairState } from "./contracts.mjs"++/**+ * @typedef {{ code: string, message?: string }} Defect+ * @typedef {{ at: string, measure: number[], signature: string, action: string }} Attempt+ * @typedef {{ schemaVersion: number, startedAt: string, budget: { maxAttempts: number, plateauLimit: number, wallClockMs: number }, integrityCodes: string[], attempts: Attempt[], consecutiveNonProgress: number, seenSignatures: string[] }} RepairState+ * @typedef {{ action: "repair"|"deliver"|"block", reason: string|null, residual: Defect[], blocking: Defect[] }} Decision+ */++const SEVERITY_INDEX = Object.freeze({ blocker: 0, major: 1, minor: 2 })+const MIN_ARTIFACT_BYTES = 512+const MIN_RENDERS = 1++export class RepairTrackerError extends Error {+ /** @param {string} code @param {string} message */+ constructor(code, message) {+ super(message)+ this.name = "RepairTrackerError"+ this.code = code+ }+}++function toIso(value, label) {+ const date = value instanceof Date ? value : typeof value === "string" || typeof value === "number" ? new Date(value) : null+ if (date === null || !Number.isFinite(date.getTime())) {+ throw new RepairTrackerError("invalid_time", `${label} must be a Date, an ISO timestamp, or epoch milliseconds`)+ }+ return date.toISOString()+}++function assertKnownCode(code, label) {+ if (typeof code !== "string" || !Object.hasOwn(DEFECT_CODES, code)) {+ throw new RepairTrackerError("unknown_defect_code", `${label} ${JSON.stringify(code)} is not a known defect code`)+ }+}++/** Callers may add integrity codes; the contract set is always included, so none can be removed. */+function integritySet(extra) {+ return new Set([...INTEGRITY_CODES, ...(extra ?? [])])+}++/**+ * @param {{ maxAttempts?: number, plateauLimit?: number, wallClockMs?: number, integrityCodes?: Iterable<string>, startedAt: Date|string|number }} options+ * @returns {RepairState}+ */+export function createTracker({ maxAttempts, plateauLimit, wallClockMs, integrityCodes, startedAt }) {+ if (startedAt === undefined) throw new RepairTrackerError("invalid_time", "startedAt is required (the tracker never reads the clock)")+ const codes = [...integritySet(integrityCodes)].sort()+ for (const code of codes) assertKnownCode(code, "integrity code")+ const state = {+ schemaVersion: SCHEMA_VERSION,+ startedAt: toIso(startedAt, "startedAt"),+ budget: {+ maxAttempts: maxAttempts ?? REPAIR_DEFAULTS.maxAttempts,+ plateauLimit: plateauLimit ?? REPAIR_DEFAULTS.plateauLimit,+ wallClockMs: wallClockMs ?? REPAIR_DEFAULTS.wallClockMs,+ },+ integrityCodes: codes,+ attempts: [],+ consecutiveNonProgress: 0,+ seenSignatures: [],+ }+ assertValid(state)+ return state+}++/** The artifact is worth delivering with residual defects only when it exists and was rendered. */+export function isArtifactOk({ bytes, renders }) {+ return Number.isFinite(bytes) && bytes >= MIN_ARTIFACT_BYTES && Number.isFinite(renders) && renders >= MIN_RENDERS+}++export function measureOf(defects) {+ const measure = [0, 0, 0]+ for (const defect of defects) measure[SEVERITY_INDEX[DEFECT_CODES[defect.code].severity]] += 1+ return measure+}++export function signatureOf(defects) {+ return [...new Set(defects.map((defect) => defect.code))].sort().join("|")+}++function lessThan(a, b) {+ for (let i = 0; i < a.length; i += 1) {+ if (a[i] !== b[i]) return a[i] < b[i]+ }+ return false+}++function stopReason(state, { signature, consecutiveNonProgress, repairsTaken, elapsedMs }) {+ const { maxAttempts, plateauLimit, wallClockMs } = state.budget+ if (state.seenSignatures.includes(signature)) return "oscillation"+ if (consecutiveNonProgress >= plateauLimit) return "plateau"+ if (repairsTaken >= maxAttempts) return "max_attempts"+ if (elapsedMs >= wallClockMs) return "wall_clock"+ return null+}++/**+ * @param {RepairState} state a tracker state (createTracker or deserializeState)+ * @param {Defect[]} defects the current check's defects+ * @param {Date|string|number} now injected time of this check+ * @param {{ artifactOk?: boolean }} [artifact] caller-supplied; see isArtifactOk+ * @returns {{ state: RepairState, decision: Decision }}+ */+export function decide(state, defects, now, { artifactOk = false } = {}) {+ if (!Array.isArray(defects)) throw new RepairTrackerError("invalid_defects", "defects must be an array")+ defects.forEach((defect, index) => assertKnownCode(defect?.code, `defects[${index}].code`))+ const at = toIso(now, "now")+ const measure = measureOf(defects)+ const signature = signatureOf(defects)+ const previous = state.attempts.at(-1)+ const consecutiveNonProgress = previous && !lessThan(measure, previous.measure) ? state.consecutiveNonProgress + 1 : 0+ const repairsTaken = state.attempts.filter((attempt) => attempt.action === "repair").length+ const integrity = integritySet(state.integrityCodes)+ const blocking = defects.filter((defect) => integrity.has(defect.code))++ /** @type {Decision} */+ let decision+ if (defects.length === 0) decision = { action: "deliver", reason: "clean", residual: [], blocking: [] }+ else {+ const elapsedMs = Date.parse(at) - Date.parse(state.startedAt)+ const reason = stopReason(state, { signature, consecutiveNonProgress, repairsTaken, elapsedMs })+ if (reason === null) decision = { action: "repair", reason: null, residual: [...defects], blocking }+ else if (blocking.length > 0) decision = { action: "block", reason: "blocking", residual: [...defects], blocking }+ else decision = { action: artifactOk ? "deliver" : "block", reason, residual: [...defects], blocking }+ }++ const next = {+ ...state,+ budget: { ...state.budget },+ integrityCodes: [...state.integrityCodes],+ attempts: [...state.attempts, { at, measure, signature, action: decision.action }],+ consecutiveNonProgress,+ seenSignatures: state.seenSignatures.includes(signature) ? [...state.seenSignatures] : [...state.seenSignatures, signature],+ }+ return { state: next, decision }+}++function assertValid(state) {+ const { ok, errors } = validateRepairState(state)+ if (!ok) throw new RepairTrackerError("invalid_repair_state", `invalid repair state: ${errors.join("; ")}`)+ if (!Array.isArray(state.integrityCodes)) throw new RepairTrackerError("invalid_repair_state", "integrityCodes must be an array")+ for (const code of state.integrityCodes) assertKnownCode(code, "integrity code")+}++/** @returns {string} the repair-state.json text */+export function serializeState(state) {+ assertValid(state)+ return `${JSON.stringify(state, null, 2)}\n`+}++/** @param {string} text repair-state.json contents @returns {RepairState} */+export function deserializeState(text) {+ let state+ try {+ state = JSON.parse(text)+ } catch (error) {+ throw new RepairTrackerError("invalid_repair_state", `repair state is not JSON: ${error.message}`)+ }+ assertValid(state)+ return state+}diff --git a/plugins/omo/skills/ulw-research/scripts/report-tools-commands.mjs b/plugins/omo/skills/ulw-research/scripts/report-tools-commands.mjsnew file mode 100644index 00000000..c95bfddf--- /dev/null+++ b/plugins/omo/skills/ulw-research/scripts/report-tools-commands.mjs@@ -0,0 +1,214 @@+// report-tools-commands.mjs - one function per report-tools subcommand. Each returns+// { json | text, summary?, exitCode } and never exits the process; report-tools.mjs dispatches.++import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs"+import { dirname, join, resolve } from "node:path"++import { CliError, parseArgs, readJsonFile, writeJsonAtomic } from "./cli-support.mjs"+import { REPAIR_DEFAULTS } from "./contracts.mjs"+import { parseLineageMode, parsePalette, renderDesignSpec } from "./design-spec.mjs"+import { extractFromHtml, extractFromPath, fetchHtml } from "./format-extract.mjs"+import { checkLayout } from "./gates-layout.mjs"+import { checkStatic } from "./gates-static.mjs"+import { parseHtml } from "./html-lite.mjs"+import { buildProbeSource } from "./layout-probe.mjs"+import * as outcome from "./outcome.mjs"+import { createTracker, decide, deserializeState, isArtifactOk, serializeState } from "./repair-tracker.mjs"++const SEVERITY_ORDER = { blocker: 0, major: 1, minor: 2 }++function readText(path) {+ try {+ return readFileSync(path, "utf8")+ } catch (error) {+ throw new CliError(`cannot read ${path}: ${error.code ?? error.message}`)+ }+}++function nowFrom(flags) {+ if (flags.now === undefined) return new Date()+ const date = new Date(flags.now)+ if (Number.isNaN(date.getTime())) throw new CliError("--now requires an ISO timestamp")+ return date+}++function sessionDirFrom(flags) {+ const dir = flags["session-dir"] ?? process.env.SESSION_DIR+ if (!dir) throw new CliError("--session-dir is required (or set SESSION_DIR)")+ return resolve(dir)+}++export function runCheck(argv) {+ const args = parseArgs(argv, { repeatable: ["require-section"] })+ const reportPath = args.positionals[0]+ if (!reportPath) throw new CliError("usage: check <report.html> --design-spec <design-spec.md> [--layout <boxes.json>] [--require-section <regex>]... [--max-defects N]")+ const specText = readText(args.required("design-spec"))+ const doc = parseHtml(readText(reportPath))+ const requireSections = (args.flags["require-section"] ?? []).map((source) => new RegExp(source, "i"))+ const result = checkStatic(doc, {+ palette: parsePalette(specText),+ lineageMode: parseLineageMode(specText),+ requireSections,+ baseDir: dirname(resolve(reportPath)),+ })+ const defects = [...result.defects]+ const gatesRun = [...result.gatesRun]+ let layout = "not_run"+ if (args.flags.layout !== undefined) {+ const layoutResult = checkLayout(readJsonFile(args.flags.layout))+ defects.push(...layoutResult.defects)+ gatesRun.push("layout")+ layout = layoutResult.defects.some((d) => d.severity === "blocker") ? "fail" : "pass"+ }+ defects.sort((a, b) => SEVERITY_ORDER[a.severity] - SEVERITY_ORDER[b.severity] || (a.line ?? 0) - (b.line ?? 0) || a.code.localeCompare(b.code))+ const counts = { blocker: 0, major: 0, minor: 0, total: defects.length }+ for (const defect of defects) counts[defect.severity] += 1+ const max = args.int("max-defects", 200)+ const status = counts.blocker > 0 ? "fail" : "pass"+ const exitCode = status === "fail" ? 1 : 0+ return {+ json: { command: "check", status, exitCode, layout, defects: defects.slice(0, max), counts, gatesRun, gatesSkipped: result.gatesSkipped },+ summary: `check: ${status.toUpperCase()} - ${counts.blocker} blocker, ${counts.major} major, ${counts.minor} minor; layout ${layout}`,+ exitCode,+ }+}++export function runLayoutProbe(argv) {+ const args = parseArgs(argv, { booleans: ["json"] })+ const source = buildProbeSource({ cap: args.int("cap", 400), root: args.flags.root ?? "main, article" })+ return args.flags.json ? { json: { command: "layout-probe", source }, exitCode: 0 } : { text: source, exitCode: 0 }+}++export function runRepairDecide(argv) {+ const args = parseArgs(argv)+ const statePath = args.required("state")+ const now = nowFrom(args.flags)+ const defectsInput = readJsonFile(args.required("defects"))+ const defects = Array.isArray(defectsInput) ? defectsInput : defectsInput.defects+ if (!Array.isArray(defects)) throw new CliError("--defects must be a JSON array or a check result with a defects array")+ const state = existsSync(statePath)+ ? deserializeState(readText(statePath))+ : createTracker({+ maxAttempts: args.int("max-attempts", REPAIR_DEFAULTS.maxAttempts),+ plateauLimit: args.int("plateau-limit", REPAIR_DEFAULTS.plateauLimit),+ wallClockMs: args.int("wall-clock-ms", REPAIR_DEFAULTS.wallClockMs),+ startedAt: now,+ })+ // Fail closed: deliver-on-exhaustion needs proof of a usable artifact (bytes and renders).+ const artifactOk =+ args.flags["artifact-bytes"] !== undefined && args.flags.renders !== undefined+ ? isArtifactOk({ bytes: Number(args.flags["artifact-bytes"]), renders: Number(args.flags.renders) })+ : false+ const { state: next, decision } = decide(state, defects, now, { artifactOk })+ writeFileSync(statePath, serializeState(next))+ recordRepair(args.flags, next, decision)+ const exitCode = decision.action === "block" ? 1 : 0+ return { json: { command: "repair decide", decision }, summary: `repair: ${decision.action}${decision.reason ? ` (${decision.reason})` : ""}`, exitCode }+}++/** With a session dir that holds outcome.json, the repair summary and residual list land in the manifest. */+function recordRepair(flags, state, decision) {+ const dir = flags["session-dir"] ?? process.env.SESSION_DIR+ if (!dir) return+ const file = join(resolve(dir), outcome.MANIFEST_FILENAME)+ if (!existsSync(file)) return+ const manifest = outcome.readManifest(file)+ manifest.repair = { attempts: state.attempts.length, action: decision.action, reason: decision.reason }+ if (decision.action !== "repair") manifest.residualDefects = decision.residual.map((defect) => ({ ...defect, message: defect.message ?? defect.code }))+ outcome.writeManifest(file, manifest)+}++function manifestPath(flags) {+ return join(sessionDirFrom(flags), outcome.MANIFEST_FILENAME)+}++export function runOutcome(argv) {+ const [sub, ...rest] = argv+ const args = parseArgs(rest, { booleans: ["json"] })+ const file = sub === "state" ? null : manifestPath(args.flags)+ switch (sub) {+ case "init": {+ const promised = args.required("promised").split(",").map((s) => s.trim()).filter(Boolean)+ const manifest = outcome.initManifest({ sessionDir: sessionDirFrom(args.flags), promised, lane: args.flags.lane ?? null, now: nowFrom(args.flags) })+ outcome.writeManifest(file, manifest)+ return { json: { command: "outcome init", path: file, deliverables: manifest.deliverables }, exitCode: 0 }+ }+ case "set": {+ const [format, status] = args.positionals+ if (!format || !status) throw new CliError("usage: outcome set <format> <status> [--path p] [--reason r] [--pages n]")+ const manifest = outcome.readManifest(file)+ const detail = {}+ if (args.flags.path !== undefined) {+ detail.path = resolve(args.flags.path)+ if (existsSync(detail.path)) detail.bytes = statSync(detail.path).size+ }+ if (args.flags.reason !== undefined) detail.reason = args.flags.reason+ if (args.flags.pages !== undefined) detail.pages = args.int("pages")+ outcome.writeManifest(file, outcome.setDeliverable(manifest, format, status, { ...detail, now: nowFrom(args.flags) }))+ return { json: { command: "outcome set", format, status }, exitCode: 0 }+ }+ case "gate": {+ const [gate, status] = args.positionals+ if (!gate || !status) throw new CliError("usage: outcome gate <static|layout|visual|proofread> <pass|fail|not_run>")+ outcome.writeManifest(file, outcome.setGate(outcome.readManifest(file), gate, status))+ return { json: { command: "outcome gate", gate, status }, exitCode: 0 }+ }+ case "render": {+ const [path] = args.positionals+ if (!path) throw new CliError("usage: outcome render <path> --page N")+ outcome.writeManifest(file, outcome.addRender(outcome.readManifest(file), resolve(path), args.int("page")))+ return { json: { command: "outcome render", path: resolve(path) }, exitCode: 0 }+ }+ case "state": {+ const deliverable = args.required("deliverable")+ const sibling = join(dirname(resolve(deliverable)), outcome.MANIFEST_FILENAME)+ const dir = args.flags["session-dir"] ?? process.env.SESSION_DIR+ const candidate = dir ? join(resolve(dir), outcome.MANIFEST_FILENAME) : sibling+ const manifest = existsSync(candidate) ? outcome.readManifest(candidate) : null+ const state = outcome.deliverableState(resolve(deliverable), manifest)+ return { json: { command: "outcome state", state }, summary: `state: ${state}`, exitCode: 0 }+ }+ case "verify": {+ const result = outcome.verifyManifest(outcome.readManifest(file))+ return { json: { command: "outcome verify", ...result }, summary: `verify: ${result.ok ? "OK" : `${result.problems.length} problem(s)`}`, exitCode: result.ok ? 0 : 1 }+ }+ case "finish": {+ const manifest = outcome.readManifest(file)+ const ledgerPath = args.flags.ledger ?? join(sessionDirFrom(args.flags), "sources-ledger.md")+ const now = nowFrom(args.flags)+ const facts = outcome.briefingFacts(manifest, existsSync(ledgerPath) ? readText(ledgerPath) : "", now)+ manifest.finishedAt = now.toISOString()+ manifest.elapsedMinutes = facts.minutes+ manifest.sources = { total: facts.sources, domains: facts.domains }+ outcome.writeManifest(file, manifest)+ return { json: { command: "outcome finish", finishedAt: manifest.finishedAt, elapsedMinutes: facts.minutes, sources: manifest.sources }, exitCode: 0 }+ }+ case "briefing": {+ const manifest = outcome.readManifest(file)+ const ledgerPath = args.flags.ledger ?? join(sessionDirFrom(args.flags), "sources-ledger.md")+ const ledger = existsSync(ledgerPath) ? readText(ledgerPath) : ""+ const now = nowFrom(args.flags)+ if (args.flags.json) return { json: { command: "outcome briefing", ...outcome.briefingFacts(manifest, ledger, now) }, exitCode: 0 }+ return { text: outcome.buildBriefing(manifest, ledger, now), exitCode: 0 }+ }+ default:+ throw new CliError("usage: outcome <init|set|gate|render|state|verify|finish|briefing> ...")+ }+}++export async function runFormatExtract(argv) {+ const args = parseArgs(argv, { booleans: ["from-url"] })+ const [reference] = args.positionals+ if (!reference) throw new CliError("usage: format-extract <reference> --out <design-spec.md> [--from-url]")+ const out = args.required("out")+ let extract+ try {+ extract = args.flags["from-url"] ? extractFromHtml(await fetchHtml(reference), { origin: reference }) : extractFromPath(reference)+ } catch (error) {+ // An unsupported, unreadable, or unreachable reference is an input problem (exit 2), not a gate result.+ throw new CliError(`format-extract ${reference}: ${error.message}`)+ }+ writeJsonAtomic(`${out}.extract.json`, { ...extract, tokens: { light: Object.fromEntries(extract.tokens?.light ?? []), dark: Object.fromEntries(extract.tokens?.dark ?? []) } })+ writeFileSync(out, renderDesignSpec(extract))+ return { json: { command: "format-extract", out: resolve(out), origin: extract.origin, lineageMode: extract.lineageMode, notes: extract.notes ?? [] }, summary: `format-extract: wrote ${out}`, exitCode: 0 }+}diff --git a/plugins/omo/skills/ulw-research/scripts/report-tools.mjs b/plugins/omo/skills/ulw-research/scripts/report-tools.mjsnew file mode 100644index 00000000..4ffa27d1--- /dev/null+++ b/plugins/omo/skills/ulw-research/scripts/report-tools.mjs@@ -0,0 +1,61 @@+#!/usr/bin/env node+// report-tools.mjs - the ulw-research deliverable CLI. Invoked as+// node "$SKILL_DIR/scripts/report-tools.mjs" <command> ...+// Exit codes: 0 pass, 1 semantic failure (blockers, a failed verify, a blocked repair), 2 usage or IO.++import { CliError, emit, exitCodeFor } from "./cli-support.mjs"+import { isCliEntry } from "./entry-guard.mjs"+import { runCheck, runFormatExtract, runLayoutProbe, runOutcome, runRepairDecide } from "./report-tools-commands.mjs"++export const COMMANDS = Object.freeze([+ "check",+ "layout-probe",+ "repair decide",+ "outcome init",+ "outcome set",+ "outcome gate",+ "outcome render",+ "outcome state",+ "outcome verify",+ "outcome finish",+ "outcome briefing",+ "format-extract",+])++export async function run(argv) {+ const [command, ...rest] = argv+ switch (command) {+ case "check":+ return runCheck(rest)+ case "layout-probe":+ return runLayoutProbe(rest)+ case "repair":+ if (rest[0] !== "decide") throw new CliError("usage: repair decide --state <file> --defects <json>")+ return runRepairDecide(rest.slice(1))+ case "outcome":+ return runOutcome(rest)+ case "format-extract":+ return runFormatExtract(rest)+ case "--help":+ case "help":+ if (rest.includes("--json")) return { json: { commands: COMMANDS }, exitCode: 0 }+ return { text: `report-tools <command>\n${COMMANDS.map((name) => ` ${name}`).join("\n")}`, exitCode: 0 }+ default:+ throw new CliError(`usage: report-tools <${COMMANDS.join(" | ")}> (run --help)`)+ }+}++export async function main(argv = process.argv.slice(2)) {+ try {+ const result = await run(argv)+ emit(result)+ return exitCodeFor(result)+ } catch (error) {+ process.stderr.write(`report-tools: ${error.message}\n`)+ return exitCodeFor(error)+ }+}++if (isCliEntry(import.meta.url)) {+ process.exitCode = await main()+}diff --git a/plugins/omo/skills/visual-qa/references/browser-setup.md b/plugins/omo/skills/visual-qa/references/browser-setup.mdindex 2860d8ee..a4cbaf87 100644--- a/plugins/omo/skills/visual-qa/references/browser-setup.md+++ b/plugins/omo/skills/visual-qa/references/browser-setup.md@@ -58,7 +58,9 @@ try {NEVER launch anything against, or clear cookies/cache/site data from, the user's live profile;the attached engine is the only sanctioned way to a signed-in page. If no extension is connected,-run the `browser` skill's `scripts/browser-install.mjs`, relay its one human step, and wait — do+run the `browser` skill's `scripts/browser-install.mjs` for the browser the user actually uses+(from memory, or its detection; on `needsChoice` ask them and pass `--browser=<id>`), relay its+one human step, and wait — donot fall back to the owned engine for an authenticated criterion.## Capture a screenshot at a fixed viewportdiff --git a/plugins/omo/test/sync-skills-codex-compatibility.test.mjs b/plugins/omo/test/sync-skills-codex-compatibility.test.mjsindex ec1fdb1a..a61b0d04 100644--- a/plugins/omo/test/sync-skills-codex-compatibility.test.mjs+++ b/plugins/omo/test/sync-skills-codex-compatibility.test.mjs@@ -166,3 +166,14 @@ test("#given the flattened plugin cache the Codex installer produces #when sync-await rm(codexHome, { recursive: true, force: true });}});++test("#given the shared ulw-research skill #when the Codex overlay runs #then the overlay applies", async () => {+ // given+ const shared = await readFile(join(sharedSkillsRoot, "ulw-research", "SKILL.md"), "utf8");++ // when+ const actual = applyCodexSkillOverlays("ulw-research", shared);++ // then+ assert.notEqual(actual, shared, "the ulw-research overlay anchor no longer matches the shared SKILL.md");+});diff --git a/plugins/omo/test/sync-skills-test-support.mjs b/plugins/omo/test/sync-skills-test-support.mjsindex c34316ca..befb4527 100644--- a/plugins/omo/test/sync-skills-test-support.mjs+++ b/plugins/omo/test/sync-skills-test-support.mjs@@ -158,8 +158,8 @@ prefixes when identity is needed.`;const reviewWorkCodexGatePattern = new RegExp(reviewWorkCodexGate.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));-const ulwResearchOriginalDeliveryGates = "### The delivery gates \u2014 every gate must PASS, in order\n\nNothing reaches the user until the gates pass:\n\n1. **Visual QA (always).** Render the produced artifact back to images \u2014 PDF pages to PNG, the HTML in a real browser \u2014 and look at them: missing or broken figures, images stretched or spilling their containers, diagram or chart text rendered off the spec's font or palette, clipped tables, overflowing CJK text, blank pages, unlabeled chart values, wrong page breaks. Fix and re-render until the pages are clean. Reading the source markup is not visual QA; inspect the pixels.\n2. **Proofread gate \u2014 `task(category=\"writing\", ...)`.** Hand the final text to a dedicated `writing` worker whose only job is language: grammar, spelling, punctuation, terminology consistency, and whether the prose reads NATIVELY in the report's own language. It returns a defect list; fix every item and re-run the gate on the delta. Deliver only on a clean pass \u2014 this gate runs BEFORE the first delivery, not after the user finds the typo.";-const ulwResearchCodexDeliveryGate = "### The delivery gate \u2014 visual QA must PASS\n\nNothing reaches the user until the gate passes:\n\n**Visual QA (always).** Render the produced artifact back to images \u2014 PDF pages to PNG, the HTML in a real browser \u2014 and look at them: missing or broken figures, images stretched or spilling their containers, diagram or chart text rendered off the spec's font or palette, clipped tables, overflowing CJK text, blank pages, unlabeled chart values, wrong page breaks. Fix and re-render until the pages are clean. Reading the source markup is not visual QA; inspect the pixels.";+const ulwResearchOriginalDeliveryGates = "Reading the source markup is not visual QA; inspect the pixels.\n4. **Proofread gate \u2014 `task(category=\"writing\", ...)`.** Hand the final text to a dedicated `writing` worker whose only job is language: grammar, spelling, punctuation, terminology consistency, and whether the prose reads NATIVELY in the report's own language. It proofreads only and never composes. It returns a defect list; fix every item and re-run the gate on the delta. Deliver only on a clean pass \u2014 this gate runs BEFORE the first delivery, not after the user finds the typo.";+const ulwResearchCodexDeliveryGate = "Reading the source markup is not visual QA; inspect the pixels.";export function removeCodexSkillOverlays(skillName, content) {if (skillName === "ulw-research") {diff --git a/plugins/omo/test/sync-skills.test.mjs b/plugins/omo/test/sync-skills.test.mjsindex 34a18028..4cb58e3d 100644--- a/plugins/omo/test/sync-skills.test.mjs+++ b/plugins/omo/test/sync-skills.test.mjs@@ -4,6 +4,7 @@ import { dirname, join } from "node:path";import test from "node:test";import { fileURLToPath } from "node:url";import { sharedSkillsRootPath } from "@oh-my-opencode/shared-skills";+import { createSkillSourceCopyFilter } from "@oh-my-opencode/shared-skills/skill-source-filter";import {canonicalUltraworkDirectiveRelativePath,componentSkillSources,@@ -260,3 +261,22 @@ test("#given packaged Codex ulw-plan surfaces #when inspected #then dangerous saassert.doesNotMatch(packagedWorkflow.content, dangerousBypassPattern, `${packagedWorkflow.path} ships unsafe Codex bypass guidance`);assert.doesNotMatch(componentWorkflow.content, dangerousBypassPattern, `${componentWorkflow.path} ships unsafe Codex bypass guidance`);});++test("#given the shared ulw-research runtime and references #when aggregate Codex skills are inspected #then every packaged file is byte-equal to its shared source", async () => {+ // given+ const sharedSkillRoot = join(sharedSkillsRootPath(), "ulw-research");+ const packagedSkillRoot = join(root, "skills", "ulw-research");+ const keep = createSkillSourceCopyFilter(sharedSkillRoot);+ const inAssetDirs = (file) => /^(scripts|references)\//.test(file.replaceAll("\\", "/"));+ const sharedFiles = (await listSkillFiles(sharedSkillRoot)).filter(inAssetDirs).filter((file) => keep(join(sharedSkillRoot, file))).sort();++ // when+ const packagedFiles = (await listSkillFiles(packagedSkillRoot)).filter(inAssetDirs).sort();++ // then+ assert.deepEqual(packagedFiles, sharedFiles);+ for (const file of sharedFiles) {+ const [packaged, shared] = await Promise.all([readFile(join(packagedSkillRoot, file)), readFile(join(sharedSkillRoot, file))]);+ assert.ok(packaged.equals(shared), `ulw-research/${file} must ship the shared bytes`);+ }+});