Skip to content
Back to search

omc

MarketplaceWorks with Claude CodeGitHub

Claude Code native multi-agent orchestration - intelligent model routing across agents and skills

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/Yeachan-Heo/oh-my-claudecode with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/Yeachan-Heo/oh-my-claudecode'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/yeachan-heo-oh-my-claudecode/badge.svg)](/listings/yeachan-heo-oh-my-claudecode)

HTML

<a href="/listings/yeachan-heo-oh-my-claudecode"><img src="/api/listings/yeachan-heo-oh-my-claudecode/badge.svg" alt="findsafeskills safety rating" /></a>

Install

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

**Step 1: Install**

Marketplace/plugin install (recommended for most Claude Code users). These are Claude Code slash commands — enter them **one at a time** (pasting both lines at once will fail):

/plugin marketplace add https://github.com/Yeachan-Heo/oh-my-claudecode

Then:

/plugin install oh-my-claudecode

If you prefer the npm CLI/runtime path instead of the marketplace flow:

npm i -g oh-my-claude-sisyphus@latest

> **Known npm warning:** npm may print `deprecated prebuild-install@7.1.3` during the CLI install. > This currently comes from the upstream `better-sqlite3` native-addon dependency > (`better-sqlite3 -> prebuild-install`); `prebuild-install@7.1.3` is still the latest > published version, so there is no safe repo-side dependency bump or override to remove > the warning yet. The warning is tracked in [#2913](https://github.com/Yeachan-Heo/oh-my-claudecode/issues/2913) > and does not by itself mean the OMC CLI install failed.

**Step 2: Setup**

# Inside a Claude Code / OMC session
/omc-setup

# From your terminal
omc setup

If you run OMC via `omc --plugin-dir <path>` or `claude --plugin-dir <path>`, add `--plugin-dir-mode` to `omc setup` (or export `OMC_PLUGIN_ROOT` before running it) so the installer doesn't duplicate skills/agents that the plugin already provides at runtime. See the [Plugin directory flags section in REFERENCE.md](./docs/REFERENCE.md#plugin-directory-flags) for a complete decision matrix and all available flags.

**Step 3: Build something**

# Inside a Claude Code / OMC session
/autopilot "build a REST API for managing tasks"

# Natural-language in-session shortcut
autopilot: build a REST API for managing tasks

Named autopilot stage profiles (v1)

Select a configured stage profile only through `/autopilot --workflow <name> <task>`:

/autopilot --workflow plan-build-qa "build a REST API for managing tasks"

Profiles are configured under `autopilot.workflows` in `.claude/omc.jsonc` (project) or `~/.config/claude-omc/config.jsonc` (user). A v1 profile contains only `version: 1` and `stages`:

{
  "autopilot": {
    "workflows": {
      "plan-build-qa": {
        "version": 1,
        "stages": ["ralplan", "execution", "qa"]
      }
    }
  }
}

The admitted sequences are `[ralplan, execution]`, `[ralplan, execution, ralph]`, `[ralplan, execution, qa]`, and `[ralplan, execution, ralph, qa]`. A project profile of the same name wholly replaces the user profile; different names coexist. Environment variables cannot define profiles. Profiles remain within autopilot's existing state, cancel, resume, Stop, and HUD lifecycle; legacy invocations without `--workflow` remain compatible.

Named profiles currently require Linux with the `flock` utility because their transcript evidence boundary uses Linux no-follow file-descriptor traversal and their recoverable mutation lock uses kernel advisory locking. Unsupported environments reject explicit `--workflow` invocation before creating or changing autopilot state; legacy autopilot remains available.

V1 intentionally excludes model fields or routing (`stageModels`), inline execution, dynamic commands/modes/state, arbitrary stages or plugins, and the separate custom-skill frontmatter parser mismatch. See [Named Autopilot Stage Profiles ADR](docs/adr/03487-named-autopilot-stage-profiles.md) and [Reference](docs/REFERENCE.md#named-autopilot-stage-profiles-v1).

That's it. Everything else is automatic.

CLI Commands vs In-Session Skills

OMC exposes two different surfaces:

- **Terminal CLI commands**: run `omc ...` from your shell after installing the npm/runtime path (`npm i -g oh-my-claude-sisyphus@latest`) or from a local checkout. - **In-session skills**: run `/...` inside a Claude Code session after installing the plugin/setup flow.

About

Found in: claude-skills-marketplace

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 31 lines
  1. {
  2. "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
  3. "name": "omc",
  4. "description": "Claude Code native multi-agent orchestration - intelligent model routing across agents and skills",
  5. "owner": {
  6. "name": "Yeachan Heo",
  7. "email": "hurrc04@gmail.com"
  8. },
  9. "plugins": [
  10. {
  11. "name": "oh-my-claudecode",
  12. "description": "Claude Code native multi-agent orchestration with intelligent model routing across agents and skills. Zero learning curve. Maximum power.",
  13. "version": "5.8.6",
  14. "author": {
  15. "name": "Yeachan Heo",
  16. "email": "hurrc04@gmail.com"
  17. },
  18. "source": "./",
  19. "category": "productivity",
  20. "homepage": "https://github.com/Yeachan-Heo/oh-my-claudecode",
  21. "tags": [
  22. "multi-agent",
  23. "orchestration",
  24. "delegation",
  25. "todo-management",
  26. "team"
  27. ]
  28. }
  29. ],
  30. "version": "5.8.6"
  31. }
README.md · README · 718 lines
  1. English | [한국어](README.ko.md) | [中文](README.zh.md) | [日本語](README.ja.md) | [Español](README.es.md) | [Tiếng Việt](README.vi.md) | [Português](README.pt.md)
  2. # oh-my-claudecode
  3. [![npm version](https://img.shields.io/npm/v/oh-my-claude-sisyphus?color=cb3837)](https://www.npmjs.com/package/oh-my-claude-sisyphus)
  4. [![npm downloads](https://img.shields.io/npm/dm/oh-my-claude-sisyphus?color=blue)](https://www.npmjs.com/package/oh-my-claude-sisyphus)
  5. [![GitHub stars](https://img.shields.io/github/stars/Yeachan-Heo/oh-my-claudecode?style=flat&color=yellow)](https://github.com/Yeachan-Heo/oh-my-claudecode/stargazers)
  6. [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)
  7. [![Sponsor](https://img.shields.io/badge/Sponsor-❤️-red?style=flat&logo=github)](https://github.com/sponsors/Yeachan-Heo)
  8. [![Discord](https://img.shields.io/discord/1452487457085063218?color=5865F2&logo=discord&logoColor=white&label=Discord)](https://discord.gg/wSyUQYfhAw)
  9. > **For Codex users:** Check out [oh-my-codex](https://github.com/Yeachan-Heo/oh-my-codex) — the same orchestration experience for OpenAI Codex CLI.
  10. > **Liked OmC but found it a bit overkill? Try [gajae-code](https://github.com/Yeachan-Heo/gajae-code).**
  11. > Keeps Claude OAuth as-is while being faster, cheaper, simpler, and more powerful — with an SDK-based integration path built for OpenClaw, Hermes, Grokbot, and similar agent runtimes.
  12. **Multi-agent orchestration for Claude Code. Zero learning curve.**
  13. _Don't learn Claude Code. Just use OMC._
  14. [Get Started](#quick-start) • [Documentation](https://yeachan-heo.github.io/oh-my-claudecode-website) • [CLI Reference](https://yeachan-heo.github.io/oh-my-claudecode-website/docs/#cli-reference) • [Workflows](https://yeachan-heo.github.io/oh-my-claudecode-website/docs/#workflows) • [Migration Guide](docs/MIGRATION.md) • [Discord](https://discord.gg/wSyUQYfhAw)
  15. ---
  16. ## Core Maintainers
  17. | Role | Name | GitHub |
  18. | -------------- | ----------- | ---------------------------------------------- |
  19. | Creator & Lead | Yeachan Heo | [@Yeachan-Heo](https://github.com/Yeachan-Heo) |
  20. ## Ambassadors
  21. | Name | GitHub |
  22. | ---------- | ------------------------------------------------ |
  23. | Sigrid Jin | [@sigridjineth](https://github.com/sigridjineth) |
  24. ## Document Specialists
  25. | Name | GitHub |
  26. | ------- | -------------------------------------- |
  27. | devswha | [@devswha](https://github.com/devswha) |
  28. ## Top Collaborators
  29. | Name | GitHub | Commits |
  30. | -------------- | ---------------------------------------------- | ------- |
  31. | JunghwanNA | [@shaun0927](https://github.com/shaun0927) | 65 |
  32. | riftzen-bit | [@riftzen-bit](https://github.com/riftzen-bit) | 52 |
  33. | Seunggwan Song | [@Nathan-Song](https://github.com/Nathan-Song) | 20 |
  34. | BLUE | [@blue-int](https://github.com/blue-int) | 20 |
  35. | Junho Yeo | [@junhoyeo](https://github.com/junhoyeo) | 15 |
  36. ## Quick Start
  37. **Step 1: Install**
  38. Marketplace/plugin install (recommended for most Claude Code users).
  39. These are Claude Code slash commands — enter them **one at a time** (pasting both lines at once will fail):
  40. ```bash
  41. /plugin marketplace add https://github.com/Yeachan-Heo/oh-my-claudecode
  42. ```
  43. Then:
  44. ```bash
  45. /plugin install oh-my-claudecode
  46. ```
  47. If you prefer the npm CLI/runtime path instead of the marketplace flow:
  48. ```bash
  49. npm i -g oh-my-claude-sisyphus@latest
  50. ```
  51. > **Known npm warning:** npm may print `deprecated prebuild-install@7.1.3` during the CLI install.
  52. > This currently comes from the upstream `better-sqlite3` native-addon dependency
  53. > (`better-sqlite3 -> prebuild-install`); `prebuild-install@7.1.3` is still the latest
  54. > published version, so there is no safe repo-side dependency bump or override to remove
  55. > the warning yet. The warning is tracked in [#2913](https://github.com/Yeachan-Heo/oh-my-claudecode/issues/2913)
  56. > and does not by itself mean the OMC CLI install failed.
  57. **Step 2: Setup**
  58. ```bash
  59. # Inside a Claude Code / OMC session
  60. /omc-setup
  61. # From your terminal
  62. omc setup
  63. ```
  64. If you run OMC via `omc --plugin-dir <path>` or `claude --plugin-dir <path>`, add `--plugin-dir-mode` to `omc setup` (or export `OMC_PLUGIN_ROOT` before running it) so the installer doesn't duplicate skills/agents that the plugin already provides at runtime. See the [Plugin directory flags section in REFERENCE.md](./docs/REFERENCE.md#plugin-directory-flags) for a complete decision matrix and all available flags.
  65. **Step 3: Build something**
  66. ```bash
  67. # Inside a Claude Code / OMC session
  68. /autopilot "build a REST API for managing tasks"
  69. # Natural-language in-session shortcut
  70. autopilot: build a REST API for managing tasks
  71. ```
  72. #### Named autopilot stage profiles (v1)
  73. Select a configured stage profile only through `/autopilot --workflow <name> <task>`:
  74. ```text
  75. /autopilot --workflow plan-build-qa "build a REST API for managing tasks"
  76. ```
  77. Profiles are configured under `autopilot.workflows` in `.claude/omc.jsonc` (project) or `~/.config/claude-omc/config.jsonc` (user). A v1 profile contains only `version: 1` and `stages`:
  78. ```jsonc
  79. {
  80. "autopilot": {
  81. "workflows": {
  82. "plan-build-qa": {
  83. "version": 1,
  84. "stages": ["ralplan", "execution", "qa"]
  85. }
  86. }
  87. }
  88. }
  89. ```
  90. The admitted sequences are `[ralplan, execution]`, `[ralplan, execution, ralph]`, `[ralplan, execution, qa]`, and `[ralplan, execution, ralph, qa]`. A project profile of the same name wholly replaces the user profile; different names coexist. Environment variables cannot define profiles. Profiles remain within autopilot's existing state, cancel, resume, Stop, and HUD lifecycle; legacy invocations without `--workflow` remain compatible.
  91. Named profiles currently require Linux with the `flock` utility because their transcript evidence boundary uses Linux no-follow file-descriptor traversal and their recoverable mutation lock uses kernel advisory locking. Unsupported environments reject explicit `--workflow` invocation before creating or changing autopilot state; legacy autopilot remains available.
  92. V1 intentionally excludes model fields or routing (`stageModels`), inline execution, dynamic commands/modes/state, arbitrary stages or plugins, and the separate custom-skill frontmatter parser mismatch. See [Named Autopilot Stage Profiles ADR](docs/adr/03487-named-autopilot-stage-profiles.md) and [Reference](docs/REFERENCE.md#named-autopilot-stage-profiles-v1).
  93. That's it. Everything else is automatic.
  94. ### CLI Commands vs In-Session Skills
  95. OMC exposes two different surfaces:
  96. - **Terminal CLI commands**: run `omc ...` from your shell after installing the npm/runtime path (`npm i -g oh-my-claude-sisyphus@latest`) or from a local checkout.
  97. - **In-session skills**: run `/...` inside a Claude Code session after installing the plugin/setup flow.
  98. | Feature | Terminal CLI | In-session skill | Notes |
  99. | ---------------------------------------------- | --------------------------------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
  100. | Setup | `omc setup` | `/omc-setup` | Both are real entrypoints. |
  101. | Ask providers | `omc ask codex "review this patch"` | `/ask codex "review this patch"` | Both route through the same advisor flow. Providers: `claude`, `codex`, `gemini`, `antigravity`, `grok`, `cursor`, `muse`. |
  102. | Team orchestration | `omc team 2:codex "review auth flow"` | `/team 3:executor "fix all TypeScript errors"` | Both exist, but they are different runtimes: `omc team` launches tmux CLI workers; `/team` runs the in-session native team workflow. |
  103. | Pre-flight danger scan | `omc lookout scan --brief "..." [--json] [--strict]` | — | Advisory only: scans the task briefing and workspace before an unattended run and reports danger findings (findings/severity contract). Exit codes: 0 for successful non-strict scans (and strict scans without high-risk signals), 1 `--strict` with high-risk signals, 2 usage/scan error. |
  104. | Autopilot / Ralph / Execute / Deep Interview | — | `/autopilot ...`, `/ralph ...`, `/execute ...`, `/deep-interview ...` | These are in-session skills. There is no `omc autopilot` / `omc ralph` / `omc execute` CLI subcommand in this repo. |
  105. | Autoresearch | `omc autoresearch` (**hard-deprecated shim**) | `/deep-interview --autoresearch ...` + `/oh-my-claudecode:autoresearch` | Setup stays in deep-interview; execution now belongs to the stateful skill. |
  106. ### VS Code, Agent SDK, and automation scope
  107. - **VS Code / IDE extension**: OMC does not ship a VS Code extension and does not document extension-specific install or automation flows. Use the Claude Code plugin or terminal CLI surfaces above; IDE integrations are only an optional way to access Claude Code itself.
  108. - **Agent SDK / programmatic usage**: the npm package exports TypeScript helpers such as `createOmcSession()` and prompt expansion utilities for local Node.js programs using `@anthropic-ai/claude-agent-sdk`. This is a library surface, not a replacement for the Claude Code plugin UI.
  109. - **CI/CD and headless automation**: prefer deterministic terminal commands (`omc setup`, `omc ask`, `omc session search`, repository scripts such as `npm run sync-metadata:verify`) and set `ANTHROPIC_API_KEY` or provider-specific CLI auth in the runner environment. Do not rely on interactive slash commands (`/autopilot`, `/ralph`, `/execute`, `/team`) in CI; they require an active Claude Code session.
  110. ### Not Sure Where to Start?
  111. If you're uncertain about requirements, have a vague idea, or want to micromanage the design:
  112. ```
  113. /deep-interview "I want to build a task management app"
  114. ```
  115. The deep interview uses Socratic questioning to clarify your thinking before any code is written. It exposes hidden assumptions and measures clarity across weighted dimensions, ensuring you know exactly what to build before execution begins.
  116. ## Team Mode (Recommended)
  117. Starting in **v4.1.7**, **Team** is the canonical orchestration surface in OMC. The legacy `swarm` keyword/skill has been removed; use `team` directly.
  118. ```bash
  119. /team 3:executor "fix all TypeScript errors"
  120. ```
  121. Use `/team ...` when you want Claude Code's in-session native team workflow. Use `omc team ...` when you want terminal-launched tmux CLI workers (`claude` / `codex` / `gemini` panes).
  122. Team runs as a staged pipeline:
  123. `team-plan → team-prd → team-exec → team-verify → team-fix (loop)`
  124. Enable Claude Code native teams in `~/.claude/settings.json`:
  125. ```json
  126. {
  127. "env": {
  128. "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
  129. }
  130. }
  131. ```
  132. > If teams are disabled, OMC will warn you and fall back to non-team execution where possible.
  133. ### tmux CLI Workers — Codex, Gemini & Antigravity (v4.4.0+)
  134. **v4.4.0 removes the Codex/Gemini MCP servers** (`x`, `g` providers). Use the CLI-first Team runtime (`omc team ...`) to spawn real tmux worker panes:
  135. ```bash
  136. omc team 2:codex "review auth module for security issues"
  137. omc team 2:gemini "redesign UI components for accessibility"
  138. omc team 2:antigravity "redesign UI components for accessibility"
  139. omc team 1:claude "implement the payment flow"
  140. omc team 1:cursor "implement the payment flow"
  141. omc team status auth-review
  142. omc team shutdown auth-review
  143. ```
  144. For mixed Codex + Antigravity work in one command, run `/ask codex` and `/ask antigravity` and have Claude synthesize the results (Gemini remains available as an enterprise/API-key fallback):
  145. ```bash
  146. /ask codex "Review this PR — architecture"
  147. /ask antigravity "Review this PR — UI components"
  148. ```
  149. | Surface | Workers | Best For |
  150. | ------------------------------- | ----------------------------- | -------------------------------------------- |
  151. | `omc team N:codex "..."` | N Codex CLI panes | Code review, security analysis, architecture |
  152. | `omc team N:gemini "..."` | N Gemini CLI panes | UI/UX design, docs, large-context tasks (enterprise/API-key) |
  153. | `omc team N:antigravity "..."` | N Antigravity (`agy`) panes | UI/UX design, docs, large-context tasks |
  154. | `omc team N:grok "..."` | N Grok Build CLI panes | Code review, analysis cross-check |
  155. | `omc team N:cursor "..."` | N Cursor agent panes | Implementation and reviewer-style tasks |
  156. | `omc team N:claude "..."` | N Claude CLI panes | General tasks via Claude CLI in tmux |
  157. | `/ask codex` + `/ask antigravity` | Tri-model advisor synthesis | Mixed Codex + Antigravity review in one pass |
  158. Workers spawn on-demand and die when their task completes — no idle resource usage. Requires the selected CLI (`codex`, `gemini`, `agy` (antigravity), `grok`, or `cursor-agent`) installed/authenticated and an active tmux session.
  159. Autopilot can prefer Cursor executor workers during team execution via `.claude/omc.jsonc`:
  160. ```jsonc
  161. {
  162. "autopilot": {
  163. "execution": "team",
  164. "team": { "agentTypes": ["cursor"] }
  165. }
  166. }
  167. ```
  168. This config makes the autopilot execution stage use `omc team 1:cursor "..."` or `/team 1:cursor "..."` for implementation work. Cursor also supports reviewer-style roles (`critic`, `code-reviewer`, `security-reviewer`, `test-engineer`): those workers emit the structured verdict file the team leader consumes to transition the task, and final approval stays a lead-session responsibility. Cursor requires an installed/authenticated `cursor-agent`.
  169. Pin a Cursor model with the `OMC_EXTERNAL_MODELS_DEFAULT_CURSOR_MODEL` environment variable, or per role with `team.roleRouting.<role>.model`. `externalModels.defaults.cursorModel` applies to workers routed through `team.roleRouting`. Ids come from `cursor-agent --list-models`, for example `cursor-grok-4.6-high` or `composer-2.5`. Left unset, `cursor-agent` chooses its own model.
  170. Native team worker worktrees are being added behind an opt-in/config gate. See [Native Team Worktree Mode](docs/TEAM-WORKTREE-MODE.md) for the workspace contract, canonical state-root rules, dirty-worktree preservation policy, and verification checklist.
  171. > **Note: Package naming** — The project is branded as **oh-my-claudecode** (repo, plugin, commands), but the npm package is published as [`oh-my-claude-sisyphus`](https://www.npmjs.com/package/oh-my-claude-sisyphus). If you install or upgrade the CLI tools via npm/bun, use `npm i -g oh-my-claude-sisyphus@latest`; the package installs both `oh-my-claudecode` and the short `omc` command aliases.
  172. ### Updating
  173. If you installed OMC via npm, upgrade with the published package name:
  174. ```bash
  175. npm i -g oh-my-claude-sisyphus@latest
  176. ```
  177. > **Package naming note:** the repo, plugin, and commands are branded **oh-my-claudecode**, but the published npm package name remains `oh-my-claude-sisyphus`. npm installs expose both `oh-my-claudecode` and `omc`; examples prefer `omc` for brevity.
  178. If you installed OMC via the Claude Code marketplace/plugin flow, update with:
  179. ```bash
  180. # 1. Update the marketplace clone
  181. /plugin marketplace update omc
  182. # 2. Re-run setup to refresh configuration
  183. /omc-setup
  184. ```
  185. If you are developing from a local checkout or git worktree, update the checkout first, then re-run setup from that worktree so the active runtime matches the code you are testing.
  186. > **Note:** If marketplace auto-update is not enabled, you must manually run `/plugin marketplace update omc` to sync the latest version before running setup.
  187. If you experience issues after updating, clear the old plugin cache:
  188. ```bash
  189. /omc-doctor
  190. ```
  191. <h1 align="center">Your Claude Just Have been Steroided.</h1>
  192. <p align="center">
  193. <img src="assets/omc-character.jpg" alt="oh-my-claudecode" width="400" />
  194. </p>
  195. ---
  196. ## Why oh-my-claudecode?
  197. - **Zero configuration required** - Works out of the box with intelligent defaults
  198. - **Team-first orchestration** - Team is the canonical multi-agent surface
  199. - **Natural language interface** - No commands to memorize, just describe what you want
  200. - **Automatic parallelization** - Complex tasks distributed across specialized agents
  201. - **Persistent execution** - Won't give up until the job is verified complete
  202. - **Cost optimization** - Smart model routing saves 30-50% on tokens
  203. - **Learn from experience** - Automatically extracts and reuses problem-solving patterns
  204. - **Real-time visibility** - HUD statusline shows what's happening under the hood
  205. ---
  206. ## Features
  207. ### Orchestration Modes
  208. Multiple strategies for different use cases — from Team-backed orchestration to token-efficient refactoring. [Learn more →](https://yeachan-heo.github.io/oh-my-claudecode-website/docs/#execution-modes)
  209. | Mode | What it is | Use For |
  210. | --------------------------- | --------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
  211. | **Team (recommended)** | Canonical staged pipeline (`team-plan → team-prd → team-exec → team-verify → team-fix`) | Coordinated Claude agents on a shared task list |
  212. | **omc team (CLI)** | tmux CLI workers — real `claude`/`codex`/`gemini`/`antigravity`/`grok`/`cursor-agent` processes in split-panes | Codex/Gemini/Antigravity/Grok/Cursor CLI tasks; on-demand spawn, die when done |
  213. | **Tri-model advisor (`/ask codex` + `/ask antigravity`)** | Claude synthesizes both advisors' output | Mixed backend+UI work needing both Codex and Antigravity |
  214. | **Autopilot** | Autonomous execution (single lead agent) | End-to-end feature work with minimal ceremony |
  215. | **Execute** | Persistent execution with verify/fix loops, from plan to working code | Tasks that must complete fully (no silent partials) |
  216. | **Verify** | Evidence-based completion checks until tests/build/lint/typecheck goals pass | Quality gates that need repeat diagnose/fix cycles |
  217. | **Claude Code `/goal`** | Native Claude Code cross-turn goal loop | One measurable session completion condition; not an OMC evidence ledger |
  218. | **Artifact-only Ultragoal** | Durable goal/checkpoint/evidence artifacts without starting a loop | Handoffs, audits, or unavailable/conflicting loop runtimes |
  219. ### Goal Workflow Guidance
  220. Use only one primary loop authority in a session. Claude Code `/goal` is useful for a native cross-turn completion condition, while Execute owns single-agent verified completion, Team owns parallel staged execution, and Verify owns repeated quality-gate cycling. Artifact-only Ultragoal is the safe fallback when you need durable goal artifacts and evidence without starting another loop.
  221. For `/goal` behavior, rely on Claude Code/Anthropic sources: the [Claude Code `/goal` docs](https://code.claude.com/docs/en/goal) and [Anthropic Claude Code changelog](https://raw.githubusercontent.com/anthropics/claude-code/main/CHANGELOG.md). Do **not** claim the `/goal` evaluator independently runs commands or reads files; surface test output, diffs, and review evidence in the conversation before treating a goal as proven.
  222. ### Intelligent Orchestration
  223. - **19 specialized agents** (with tier variants) for architecture, research, design, testing, data analysis
  224. - **Smart model routing** - Haiku for simple tasks, Opus for complex reasoning
  225. - **Automatic delegation** - Right agent for the job, every time
  226. - **[Model × Agent Compatibility Matrix](docs/agents/model-compatibility.md)** - Which model to pair with each agent, with premium/balanced/budget presets
  227. ### Developer Experience
  228. - **Prompt triggers** - `ralph`, `ralplan`; Team stays explicit via `/team`
  229. - **HUD statusline** - Real-time orchestration metrics in your status bar
  230. - If you launch Claude Code directly with `claude --plugin-dir <path>` (bypassing the `omc` shim), export `OMC_PLUGIN_ROOT=<path>` in your shell so the HUD bundle resolves to the same checkout as the plugin loader. See the [Plugin directory flags section in REFERENCE.md](./docs/REFERENCE.md#plugin-directory-flags) for details.
  231. - **Skill learning** - Extract reusable patterns from your sessions
  232. - **Analytics & cost tracking** - Understand token usage across all sessions
  233. ### Contributing
  234. Want to contribute to OMC? See [CONTRIBUTING.md](./CONTRIBUTING.md) for the full developer guide, including how to fork, set up a local checkout, link it as your active plugin, run tests, and submit PRs.
  235. ### Custom Skills
  236. Learn once, reuse forever. OMC extracts hard-won debugging knowledge into portable skill files that auto-inject when relevant.
  237. | | Project Scope | User Scope |
  238. | --------------- | -------------------------------------------------------- | ----------------- |
  239. | **Path** | `.omc/skills/` | `~/.omc/skills/` |
  240. | **Shared with** | Team (commit the skill file to keep it across worktrees) | All your projects |
  241. | **Priority** | Higher (overrides user) | Lower (fallback) |
  242. ```yaml
  243. # .omc/skills/fix-proxy-crash.md
  244. ---
  245. name: Fix Proxy Crash
  246. description: aiohttp proxy crashes on ClientDisconnectedError
  247. triggers: ["proxy", "aiohttp", "disconnected"]
  248. source: extracted
  249. ---
  250. Wrap handler at server.py:42 in try/except ClientDisconnectedError...
  251. ```
  252. **Manage skills:** `/skill list | add | remove | edit | search`
  253. **Skillify:** `/skillify` extracts reusable patterns with strict quality gates
  254. **Auto-inject:** Matching skills load into context automatically — no manual recall needed
  255. Project-scoped OMC-authored skills are stored in `.omc/skills/` and are intended to be committed when you want them shared. During slash/skill execution OMC also reads Claude Code workspace skills from `.claude/skills/` and compatibility skills from `.agents/skills/`, so existing workspace-local `SKILL.md` packages remain callable without copying them into user-global skills. If you create project-local skills inside a linked git worktree and do not commit them, they disappear when that worktree is removed.
  256. ### `.omc/` state and git
  257. OMC writes runtime state, session data, plans, logs, handoffs, research notes, and local artifacts under `.omc/` by default. The repository `.gitignore` keeps that runtime data local with one intentional exception: `.omc/skills/**` remains committable for project-scoped skills you want to share with the team. Treat everything else under `.omc/` as local operational state that may contain prompts, transcripts, or machine-specific paths.
  258. For linked git worktrees, the default `.omc/` directory lives inside that worktree, so deleting the worktree deletes its local OMC state. Set `OMC_STATE_DIR` if you want state to survive worktree deletion, or add a `.omc-workspace` marker when several independent repos should share one parent-level state root. See [OMC state, gitignore, worktree, and workspace contract](docs/REFERENCE.md#omc-state-gitignore-worktree-and-workspace-contract).
  259. Outside a git repository, OMC uses one canonical safe state root at `~/.omc/` (or `$OMC_STATE_DIR/non-git` when centralized state is configured); it does not create a new state root for every cwd or write state into sensitive directories such as `~/.ssh`, `~/Downloads`, or descendants of the system temp root. Legacy cwd-local state is untouched until explicitly migrated with `state_migrate_non_git`. State MCP tools honor an explicit `workingDirectory` while retaining repository-boundary checks for git-backed sessions.
  260. [Full feature list →](docs/REFERENCE.md)
  261. ### Multi-repo workspaces
  262. When several independent git repos share a parent directory, drop a `.omc-workspace` marker at the parent so all sub-repos share one `.omc/` state root:
  263. ```bash
  264. cd /path/to/parent-dir-with-many-repos
  265. echo '{"id":"my-workspace"}' > .omc-workspace
  266. # Sessions inside any sub-repo now share /path/.omc/
  267. # For parallel ultragoal runs:
  268. cd repo-A && omc ultragoal create-goals --auto-plan-id --brief "..."
  269. cd ../repo-B && omc ultragoal create-goals --auto-plan-id --brief "..."
  270. ```
  271. See [Multi-repo workspaces in REFERENCE.md](docs/REFERENCE.md#multi-repo-workspaces-with-omc-workspace) for resolution order, `OMC_STATE_DIR`, and workspace identifier options.
  272. ---
  273. ## In-session shortcuts
  274. These shortcuts run **inside a Claude Code / OMC session**, not as terminal CLI commands. For shell commands, use the `omc ...` forms shown above. Team mode is explicit: use `/team ...` in-session or `omc team ...` from your shell rather than expecting a bare `team` keyword trigger.
  275. | In-session form | Kind | Effect | Example |
  276. | -------------------------- | ---------------------- | -------------------------------------- | ---------------------------------------------- |
  277. | `/team` | Slash skill | Canonical Team orchestration | `/team 3:executor "fix all TypeScript errors"` |
  278. | `/autopilot` / `autopilot` | Skill / prompt trigger | Full autonomous execution | `/autopilot "build a todo app"` |
  279. | `/execute` | Slash skill | Carry an approved task through to verified code | `/execute "refactor auth"` |
  280. | `/ralph` / `ralph` | Skill / prompt trigger | Persistence mode | `/ralph "refactor auth"` |
  281. | `/ralplan` / `ralplan` | Skill / prompt trigger | Iterative planning consensus | `/ralplan "plan this feature"` |
  282. | `/deep-interview` | Slash skill | Socratic requirements clarification | `/deep-interview "vague idea"` |
  283. | `deepsearch` | Prompt trigger | Codebase-focused search routing | `deepsearch for auth middleware` |
  284. | `ultrathink` | Prompt trigger | Deep reasoning mode | `ultrathink about this architecture` |
  285. | `cancelomc`, `stopomc` | Prompt trigger | Stop active OMC modes | `stopomc` |
  286. **Notes:**
  287. - **Parallel work uses Team or executor delegation**: choose `/team` for coordinated lanes or delegate implementation tasks to executors; use Ralph when persistence until verified completion is the priority.
  288. - `swarm` compatibility alias has been removed; migrate existing prompts to `/team` syntax.
  289. - `plan this` / `plan the` keyword triggers were removed; use `ralplan` or explicit `/oh-my-claudecode:plan`.
  290. ## Utilities
  291. ### Provider Advisor (`omc ask` / `/ask`)
  292. Run local provider CLIs and save a markdown artifact under `.omc/artifacts/ask/`.
  293. ```bash
  294. # Terminal CLI
  295. omc ask claude "review this migration plan"
  296. omc ask codex --prompt "identify architecture risks"
  297. omc ask gemini --prompt "propose UI polish ideas"
  298. omc ask antigravity --prompt "propose UI polish ideas"
  299. omc ask grok --prompt "cross-check this code review"
  300. omc ask cursor --prompt "apply this implementation plan"
  301. omc ask muse --agent-prompt critic --prompt "review this plan"
  302. omc ask claude --agent-prompt executor --prompt "draft implementation steps"
  303. # Inside a Claude Code / OMC session
  304. /ask claude "review this migration plan"
  305. /ask codex "identify architecture risks"
  306. /ask antigravity "propose UI polish ideas"
  307. /ask cursor "apply this implementation plan"
  308. /ask muse --agent-prompt critic "review this plan"
  309. ```
  310. Canonical env vars:
  311. - `OMC_ASK_ADVISOR_SCRIPT`
  312. - `OMC_ASK_ORIGINAL_TASK`
  313. Phase-1 aliases `OMX_ASK_ADVISOR_SCRIPT` and `OMX_ASK_ORIGINAL_TASK` are accepted with deprecation warnings.
  314. ### Autoresearch (stateful skill)
  315. `omc autoresearch` is now a **hard-deprecated shim**. The authoritative workflow is:
  316. ```bash
  317. /deep-interview --autoresearch improve startup performance
  318. /oh-my-claudecode:autoresearch
  319. ```
  320. - `deep-interview --autoresearch` generates/sets up the mission and evaluator
  321. - `autoresearch` runs the bounded, single-mission stateful loop
  322. - each iteration records evaluation JSON plus markdown decision logs
  323. - non-passing iterations continue
  324. - strict stopping is controlled by an explicit max-runtime ceiling
  325. ### Rate Limit Wait
  326. Auto-resume Claude Code sessions when rate limits reset.
  327. ```bash
  328. omc wait # Check status, get guidance
  329. omc wait --start # Enable auto-resume daemon
  330. omc wait --stop # Disable daemon
  331. ```
  332. **Requires:** tmux (for session detection)
  333. ### Monitoring & Observability
  334. Use the HUD for live observability and the current session/replay artifacts for post-session inspection:
  335. - HUD preset: `/oh-my-claudecode:hud setup` then use a supported preset such as `"omcHud": { "preset": "focused" }`
  336. - Session summaries: `.omc/sessions/*.json`
  337. - Replay logs: `.omc/state/agent-replay-*.jsonl`
  338. - Live HUD rendering: `omc hud`
  339. - Local friction reports: `omc session friction report --since 24h` summarizes context-bloat and operator-friction signals from local session artifacts without printing raw prompts or tool output; add `--json` for automation.
  340. ### Jev Judgment Configuration
  341. **Jev** brings calibrated decision-making to OMC's orchestration. Enable it with environment variables:
  342. ```bash
  343. export TYPESAFE_API_KEY="sk-..." # Jev API key (required)
  344. export OMC_JEV="all:active" # All judgment points active
  345. export OMC_JEV_TIMEOUT_MS="2000" # Per-call timeout (default: 2000ms)
  346. ```
  347. **Modes:**
  348. - `shadow` (default): Jev is queried but heuristics decide; answers logged for analysis
  349. - `active`: Jev's answer overrides the heuristic; adds latency (bounded by `OMC_JEV_TIMEOUT_MS`)
  350. - `off`: No Jev queries sent (zero egress)
  351. Jev decides skill triggering, model routing, loop continuation, context pruning, task sizing, and completion verdicts. On timeout, HTTP error, or parse failure, active mode degrades to the heuristic without blocking. Defaults to zero egress: without configuration, nothing is sent to the API. See **[Jev Judgment Points](docs/HOOKS.md#jev-judgment-points)** in HOOKS.md for the full configuration reference and point registry.
  352. ### Notification Tags (Telegram/Discord/Slack)
  353. You can configure who gets tagged when stop callbacks send session summaries.
  354. ```bash
  355. # Set/replace tag list
  356. omc config-stop-callback telegram --enable --token <bot_token> --chat <chat_id> --tag-list "@alice,bob"
  357. omc config-stop-callback discord --enable --webhook <url> --tag-list "@here,123456789012345678,role:987654321098765432"
  358. omc config-stop-callback slack --enable --webhook <url> --tag-list "<!here>,<@U1234567890>"
  359. # Incremental updates
  360. omc config-stop-callback telegram --add-tag charlie
  361. omc config-stop-callback discord --remove-tag @here
  362. omc config-stop-callback discord --clear-tags
  363. ```
  364. Tag behavior:
  365. - Telegram: `alice` becomes `@alice`
  366. - Discord: supports `@here`, `@everyone`, numeric user IDs, and `role:<id>`
  367. - Slack: supports `<@MEMBER_ID>`, `<!channel>`, `<!here>`, `<!everyone>`, `<!subteam^GROUP_ID>`
  368. - `file` callbacks ignore tag options
  369. ### OpenClaw Integration
  370. Forward Claude Code session events to an [OpenClaw](https://openclaw.ai/) gateway to enable automated responses and workflows via your OpenClaw agent.
  371. **Quick setup (recommended):**
  372. ```bash
  373. /oh-my-claudecode:configure-notifications
  374. # → When prompted, type "openclaw" → choose "OpenClaw Gateway"
  375. ```
  376. **Manual setup:** create `~/.claude/omc_config.openclaw.json`:
  377. ```json
  378. {
  379. "enabled": true,
  380. "gateways": {
  381. "my-gateway": {
  382. "url": "https://your-gateway.example.com/wake",
  383. "headers": { "Authorization": "Bearer YOUR_TOKEN" },
  384. "method": "POST",
  385. "timeout": 10000
  386. }
  387. },
  388. "hooks": {
  389. "session-start": {
  390. "gateway": "my-gateway",
  391. "instruction": "Session started for {{projectName}}",
  392. "enabled": true
  393. },
  394. "stop": {
  395. "gateway": "my-gateway",
  396. "instruction": "Session stopping for {{projectName}}",
  397. "enabled": true
  398. }
  399. }
  400. }
  401. ```
  402. **Environment variables:**
  403. | Variable | Description |
  404. | ------------------------------------------ | ------------------------- |
  405. | `OMC_OPENCLAW=1` | Enable OpenClaw |
  406. | `OMC_OPENCLAW_DEBUG=1` | Enable debug logging |
  407. | `OMC_OPENCLAW_CONFIG=/path/to/config.json` | Override config file path |
  408. **Supported hook events (6 active in bridge.ts):**
  409. | Event | Trigger | Key template variables |
  410. | ------------------- | --------------------------------------- | ----------------------------------------------------- |
  411. | `session-start` | Session begins | `{{sessionId}}`, `{{projectName}}`, `{{projectPath}}` |
  412. | `stop` | Claude response completes | `{{sessionId}}`, `{{projectName}}` |
  413. | `keyword-detector` | Every prompt submission | `{{prompt}}`, `{{sessionId}}` |
  414. | `ask-user-question` | Claude requests user input | `{{question}}`, `{{sessionId}}` |
  415. | `pre-tool-use` | Before tool invocation (high frequency) | `{{toolName}}`, `{{sessionId}}` |
  416. | `post-tool-use` | After tool invocation (high frequency) | `{{toolName}}`, `{{sessionId}}` |
  417. **Reply channel environment variables:**
  418. | Variable | Description |
  419. | ------------------------ | ------------------------------ |
  420. | `OPENCLAW_REPLY_CHANNEL` | Reply channel (e.g. `discord`) |
  421. | `OPENCLAW_REPLY_TARGET` | Channel ID |
  422. | `OPENCLAW_REPLY_THREAD` | Thread ID |
  423. See `scripts/openclaw-gateway-demo.mjs` for a reference gateway that relays OpenClaw payloads to a custom HTTPS automation endpoint.
  424. ---
  425. ## Documentation
  426. - **[Full Reference](docs/REFERENCE.md)** - Complete feature documentation
  427. - **[CLI Reference](https://yeachan-heo.github.io/oh-my-claudecode-website/docs/#cli-reference)** - All `omc` commands, flags, and tools
  428. - **[Notifications Guide](https://yeachan-heo.github.io/oh-my-claudecode-website/docs/#notifications)** - Discord, Telegram, Slack, and webhook setup
  429. - **[Recommended Workflows](https://yeachan-heo.github.io/oh-my-claudecode-website/docs/#workflows)** - Battle-tested skill chains for common tasks
  430. - **[Release Notes](https://yeachan-heo.github.io/oh-my-claudecode-website/docs/#release-notes)** - What's new in each version
  431. - **[Website](https://yeachan-heo.github.io/oh-my-claudecode-website)** - Interactive guides and examples
  432. - **[Migration Guide](docs/MIGRATION.md)** - Upgrade from v2.x
  433. - **[Architecture](docs/ARCHITECTURE.md)** - How it works under the hood
  434. - **[Performance Monitoring](docs/PERFORMANCE-MONITORING.md)** - Agent tracking, debugging, and optimization
  435. - **[Model × Agent Compatibility Matrix](docs/agents/model-compatibility.md)** - Which model to pair with each agent (premium / balanced / budget presets)
  436. - **[Security Guide](SECURITY.md)** - Enterprise deployment and hardening
  437. ---
  438. ## Requirements
  439. - [Claude Code](https://docs.anthropic.com/claude-code) CLI
  440. - Claude Max/Pro subscription OR Anthropic API key
  441. ### Platform & tmux
  442. OMC features like `omc team` and rate-limit detection require **tmux**:
  443. | Platform | tmux provider | Install |
  444. | -------------- | ----------------------------------------------------- | ----------------------- |
  445. | macOS | [tmux](https://github.com/tmux/tmux) | `brew install tmux` |
  446. | Ubuntu/Debian | tmux | `sudo apt install tmux` |
  447. | Fedora | tmux | `sudo dnf install tmux` |
  448. | Arch | tmux | `sudo pacman -S tmux` |
  449. | Windows | [psmux](https://github.com/marlocarlo/psmux) (native) | `winget install psmux` |
  450. | Windows (WSL2) | tmux (inside WSL) | `sudo apt install tmux` |
  451. > **Windows users:** [psmux](https://github.com/marlocarlo/psmux) provides a native `tmux` binary for Windows with 76 tmux-compatible commands. No WSL required.
  452. >
  453. > **Windows Node.js version (provider spawns):** On Windows, **Node 22+ (or 21.7+)** is recommended for provider spawns. Node 20's libuv 1.46 may resolve bare-name child process executables from the current working directory, which can cause unexpected behavior. See [#4746](https://github.com/Yeachan-Heo/oh-my-claudecode/issues/4746) for details.
  454. ### Optional: Multi-AI Orchestration
  455. OMC can optionally orchestrate external AI providers for cross-validation and design consistency. These are **not required** — OMC works fully without them.
  456. | Provider | Install | What it enables |
  457. | ----------------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------- |
  458. | [Antigravity CLI](https://antigravity.google) (`agy`) | Install per the [official instructions](https://antigravity.google) (provides the `agy` binary) | Design review, UI consistency — Google's successor to the Gemini CLI |
  459. | [Gemini CLI](https://github.com/google-gemini/gemini-cli) | `npm install -g @google/gemini-cli` | Design review, UI consistency (1M token context) — enterprise/API-key access unaffected |
  460. | [Codex CLI](https://github.com/openai/codex) | `npm install -g @openai/codex` | Architecture validation, code review cross-check |
  461. | [Grok Build](https://build.grok.com) | Download from build.grok.com (`grok` at `~/.grok/bin/grok`) | Code review, analysis cross-check |
  462. > **Migrating from Gemini CLI:** Per Google's announcement, the Gemini CLI is being superseded by the Antigravity CLI (`agy`); see the [official Antigravity docs](https://antigravity.google). Use `omc team N:antigravity` and `omc ask antigravity` wherever you previously used `gemini`. Windows headless support for `agy` is unknown/untested — report issues upstream.
  463. **Cost:** 3 Pro plans (Claude + Antigravity/Gemini + ChatGPT) cover everything for ~$60/month.
  464. ---
  465. ## License
  466. MIT
  467. ---
  468. <div align="center">
  469. **Inspired by:** [oh-my-opencode](https://github.com/code-yeongyu/oh-my-opencode) • [claude-hud](https://github.com/ryanjoachim/claude-hud) • [Superpowers](https://github.com/obra/superpowers) • [everything-claude-code](https://github.com/affaan-m/everything-claude-code) • [Ouroboros](https://github.com/Q00/ouroboros)
  470. **Zero learning curve. Maximum power.**
  471. </div>
  472. <!-- OMC:FEATURED-CONTRIBUTORS:START -->
  473. ## Featured by OmC Contributors
  474. Top personal non-fork, non-archived repos from all-time OMC contributors (100+ GitHub stars).
  475. - [@Yeachan-Heo](https://github.com/Yeachan-Heo) — [oh-my-claudecode](https://github.com/Yeachan-Heo/oh-my-claudecode) (⭐ 40k)
  476. - [@junhoyeo](https://github.com/junhoyeo) — [tokscale](https://github.com/junhoyeo/tokscale) (⭐ 5.8k)
  477. - [@psmux](https://github.com/psmux) — [psmux](https://github.com/psmux/psmux) (⭐ 3.8k)
  478. - [@devswha](https://github.com/devswha) — [ovis](https://github.com/devswha/ovis) (⭐ 1.6k)
  479. - [@MeroZemory](https://github.com/MeroZemory) — [ida-multi-mcp](https://github.com/MeroZemory/ida-multi-mcp) (⭐ 467)
  480. - [@GeiserX](https://github.com/GeiserX) — [awesome-spain](https://github.com/GeiserX/awesome-spain) (⭐ 362)
  481. - [@BowTiedSwan](https://github.com/BowTiedSwan) — [buildflow](https://github.com/BowTiedSwan/buildflow) (⭐ 296)
  482. - [@J-Pster](https://github.com/J-Pster) — [Psters_AI_Workflow](https://github.com/J-Pster/Psters_AI_Workflow) (⭐ 289)
  483. - [@alohays](https://github.com/alohays) — [awesome-visual-representation-learning-with-transformers](https://github.com/alohays/awesome-visual-representation-learning-with-transformers) (⭐ 271)
  484. - [@HaD0Yun](https://github.com/HaD0Yun) — [Doyunha-Gopeak](https://github.com/HaD0Yun/Doyunha-Gopeak) (⭐ 270)
  485. - [@changeroa](https://github.com/changeroa) — [StyleGallery](https://github.com/changeroa/StyleGallery) (⭐ 265)
  486. - [@jcwleo](https://github.com/jcwleo) — [random-network-distillation-pytorch](https://github.com/jcwleo/random-network-distillation-pytorch) (⭐ 264)
  487. - [@HwangTaehyun](https://github.com/HwangTaehyun) — [github-repository-contribution-stats](https://github.com/HwangTaehyun/github-repository-contribution-stats) (⭐ 241)
  488. - [@shaun0927](https://github.com/shaun0927) — [openchrome](https://github.com/shaun0927/openchrome) (⭐ 235)
  489. - [@emgeee](https://github.com/emgeee) — [mean-tutorial](https://github.com/emgeee/mean-tutorial) (⭐ 199)
  490. - [@anduinnn](https://github.com/anduinnn) — [HiFiNi-Auto-CheckIn](https://github.com/anduinnn/HiFiNi-Auto-CheckIn) (⭐ 172)
  491. - [@Znuff](https://github.com/Znuff) — [consolas-powerline](https://github.com/Znuff/consolas-powerline) (⭐ 146)
  492. <!-- OMC:FEATURED-CONTRIBUTORS:END -->
  493. ## Star History
  494. [![Star History Chart](https://api.star-history.com/svg?repos=Yeachan-Heo/oh-my-claudecode&type=date&legend=top-left)](https://www.star-history.com/#Yeachan-Heo/oh-my-claudecode&type=date&legend=top-left)
  495. ## 💖 Support This Project
  496. If Oh-My-ClaudeCode helps your workflow, consider sponsoring:
  497. [![Sponsor on GitHub](https://img.shields.io/badge/Sponsor-❤️-red?style=for-the-badge&logo=github)](https://github.com/sponsors/Yeachan-Heo)
  498. ### Why sponsor?
  499. - Keep development active
  500. - Priority support for sponsors
  501. - Influence roadmap & features
  502. - Help maintain free & open source
  503. ### Other ways to help
  504. - ⭐ Star the repo
  505. - 🐛 Report bugs
  506. - 💡 Suggest features
  507. - 📝 Contribute code
  508. ## GEO visibility benchmark
  509. OmC includes a [`geobench`](https://github.com/NomaDamas/geobench) product spec for measuring LLM hit rate, MRR, share of voice, and citations.
  510. - Spec: [`geobench/oh-my-claudecode.yaml`](geobench/oh-my-claudecode.yaml)
  511. - Runbook: [`docs/geobench.md`](docs/geobench.md)
hooks/jev-compaction.mjs · Bundled script · 1,506 lines · 1 finding marked
  1. /* global crypto, TextEncoder */
  2. /**
  3. * Jev compaction: a Claude Code hooks module ("mod") for the judgment point `compaction`.
  4. *
  5. * Opt-in by name only. `all` and `all:active` never enable this point: it runs only when OMC_JEV
  6. * names it (`compaction` for shadow, `compaction:active` for active) and TYPESAFE_API_KEY is set.
  7. * Without that every handler passes the event on unchanged and the module reads nothing but its
  8. * configuration: no request, no file, no output (mirror of NAMED_ONLY_POINTS in
  9. * scripts/jev-resolve.mjs and src/hooks/jev/config.ts).
  10. *
  11. * session.compact (auto, /compact, a plugin's request; main loop and subagents). The first message,
  12. * the last KEEP_LAST messages, every user message and every assistant text stay word for word. Other
  13. * tool results are kept whole, shortened to SHORT_CHARS characters, or removed together with their
  14. * call; a removed call stays as a one-line trace (tool, input up to TRACE_INPUT_CHARS, size of the
  15. * removed result), so the model knows what it already did. Jev scores how much each result will still
  16. * be needed (the `compaction` score question in src/hooks/jev/points.ts, BATCH results per request,
  17. * up to MAX_REQUESTS requests in parallel). Results are ranked by score and kept while they fit the
  18. * target budget (OMC_JEV_COMPACT_TARGET of the characters before). In shadow mode the decision is
  19. * computed and logged, and the built-in summary runs.
  20. *
  21. * Assistant rows are rebuilt from their text, traces and kept calls (thinking and server blocks go, a
  22. * row left empty is dropped), so the host writes them with a new message.id and `--resume` cannot
  23. * join them with their rows from before the compaction. The rows of one API message become one
  24. * message with its results right after it, so the host neither joins a row to an earlier message nor
  25. * finds a call without its result. Between turns every assistant row is rebuilt; inside an open tool
  26. * loop the rows of the last assistant message keep their handles, which needs the API form of the
  27. * conversation ($.session.messages({ as: 'api' })) holding its calls, and no thinking row or server
  28. * block among them; otherwise the built-in summary runs.
  29. *
  30. * The built-in summary (next(e)) also runs when the conversation is too short or its tool results
  31. * are too small for the removal to matter, while requests are paused after an endpoint failure, when
  32. * OMC_JEV_MAX_REQUESTS is used up, while the shared breaker is open or the shared request limit is
  33. * used up, and when Jev fails, answers too little or does not answer in time.
  34. *
  35. * turn.complete. With OMC_JEV_COMPACT_AT_PERCENT (off when unset) the module asks the host to compact
  36. * once the context reaches that share of the compaction window: main loop only, at most once per
  37. * MIN_TURNS_BETWEEN turns, never during a compaction, never while requests are paused, and only when
  38. * the removable tool results are worth it (a request that would end in the built-in summary is not
  39. * made). After a compaction of the main loop (this module's or the built-in summary) it also waits
  40. * until the context has grown by OWN_MIN_GAIN of the window from the lowest usage since it (from the
  41. * threshold at most).
  42. *
  43. * What goes to the endpoint: the /compact instructions and the last USER_MESSAGES user messages
  44. * (together USER_CHARS characters), and for each scored result its tool, its input (STATE_INPUT_CHARS)
  45. * and the result's first STATE_HEAD_CHARS and last STATE_TAIL_CHARS characters, all after secret
  46. * masking, with every string bounded by OMC_JEV_EXCERPT_CHARS_COMPACTION (default
  47. * DEFAULT_EXCERPT_CHARS). Results of calls on secret paths (and on OMC_JEV_COMPACT_PRIVATE_PATHS)
  48. * and results without text are never sent.
  49. *
  50. * Shared breaker and request limit (OMC_JEV_BREAKER=1, OMC_JEV_MAX_RPM=<n>): the same files and rules as
  51. * the script side (scripts/lib/jev-breaker.mjs, see its header), under the same state directory and
  52. * scope. A hooks module cannot import Node, so the file work goes through $.fs; the rules are mirrors.
  53. * Before each request the module reads breaker.json (open: no request) and, with a limit, reserves a
  54. * slot in the UTC minute's rpm file at medium priority (a refused request takes no slot). A request
  55. * that fails opens the breaker by status alone (429 and 5xx; 401, 402, 403; Retry-After, for a 429
  56. * without one the retry time in its body), and the third request without a response within a minute
  57. * opens it too. $.fs can neither append nor delete: a line is added by writing the file whole and
  58. * reading it back, which can lose a line another process added in between (so the limit can be
  59. * exceeded when several sessions reserve in the same instant; this module's own file work is done one
  60. * step after the other), and the per-minute files of old minutes stay (the script side removes them
  61. * when it writes a new minute). Without these two variables nothing of this is read or written. The
  62. * module's own pause, its three-failures stop and OMC_JEV_MAX_REQUESTS stay as they were.
  63. *
  64. * Quiet: no $.ui.log; a toast only with OMC_JEV_COMPACT_TOAST=1. One JSON file per event goes to the
  65. * spool directory (<state dir>/compaction-spool, $.fs cannot append); the classic SessionStart hook
  66. * (scripts/lib/jev-compaction-state.mjs) moves those records to compaction.jsonl next to shadow.jsonl.
  67. *
  68. * A hooks module reaches files, the network and the environment only through `$`, may import only
  69. * plain files of its plugin, and its hooks must be functions declared at the top of the file (the host
  70. * checks this when it loads the module; `claude plugin validate` runs the same check). The masking is
  71. * shared (scripts/lib/jev-mask.mjs); the HTTP client, the OMC_JEV parse, boundExcerpts and the
  72. * question are mirrors, and src/__tests__/jev-compaction-module.test.mjs locks their parity.
  73. */
  74. import { maskSecrets } from '../scripts/lib/jev-mask.mjs';
  75. const POINT = 'compaction';
  76. // The last messages stay whole: the work in flight.
  77. const KEEP_LAST = 6;
  78. // Cap on the host call for the API form of the conversation: a call that never settles must not hold
  79. // the compaction.
  80. const HOST_MS = 2000;
  81. // Up to BATCH * MAX_REQUESTS = 240 results are scored per compaction. A 40-question request took
  82. // 1.4-2.9 s against the production endpoint; the deadlines leave room for a slow answer and keep the
  83. // whole decision under TOTAL_MS, after which the built-in summary runs instead.
  84. const BATCH = 40;
  85. const MAX_REQUESTS = 6;
  86. const REQUEST_MS = 6000;
  87. const TOTAL_MS = 8000;
  88. // Default share of the characters kept (OMC_JEV_COMPACT_TARGET, 0.1-0.9).
  89. const DEFAULT_TARGET = 0.5;
  90. // When removing every tool result would cut less than this share, a module compaction would free too
  91. // little room, so the built-in summary runs.
  92. const MIN_REDUCTION = 0.3;
  93. // The own threshold asks for a compaction only when the removable results are also worth this share
  94. // of the compaction window (about four characters per token).
  95. const OWN_MIN_GAIN = 0.1;
  96. const CHARS_PER_TOKEN = 4;
  97. const SHORT_CHARS = 300;
  98. const TRACE_INPUT_CHARS = 200;
  99. const STATE_INPUT_CHARS = 300;
  100. const STATE_HEAD_CHARS = 1000;
  101. const STATE_TAIL_CHARS = 500;
  102. const USER_CHARS = 4000;
  103. // Text is cut before masking so a huge result or message costs bounded time; the cut keeps this much more
  104. // than the part that is used, so a secret that starts inside the used part is still seen whole.
  105. const MASK_SLACK_CHARS = 20000;
  106. const USER_MESSAGES = 3;
  107. // Mirror of POINT_DEFAULT_EXCERPT_CHARS.compaction in src/hooks/jev/config.ts: the longest string the
  108. // state holds (USER_CHARS), so the default bounds nothing the limits above do not already bound.
  109. export const DEFAULT_EXCERPT_CHARS = 4000;
  110. const MIN_TURNS_BETWEEN = 5;
  111. const WINDOW_REFRESH_TURNS = 20;
  112. const CONFIG_TTL_MS = 30000;
  113. // A request batch counts when at least this share of its questions got a score; unanswered
  114. // questions get UNANSWERED_SCORE ("may be useful" is 2/3).
  115. const PARTIAL_OK = 0.5;
  116. const UNANSWERED_SCORE = 0.4;
  117. const PROBE_MAX_CHARS = 5_000_000;
  118. // A file or URL named in the last user messages counts as needed when its name has at least this
  119. // many characters (shorter names match too much text).
  120. const MENTION_MIN = 5;
  121. const DEFAULT_ENDPOINT = 'https://api.typesafe.ai/v1/systemone';
  122. const JEV_MODEL = 'jev-latest';
  123. // Pause after a failed request, by status only (a response body is read only for the retry time of a
  124. // 429 without a Retry-After, and only for the shared breaker): Retry-After when the response has it,
  125. // else these defaults; three requests without a response within a minute pause too.
  126. // Three failed compactions in a row stop the requests for the rest of the session, like the resolver's
  127. // per-point breaker.
  128. const PAUSE_DEFAULT_MS = 60_000;
  129. const PAUSE_AUTH_MS = 600_000;
  130. const PAUSE_MAX_MS = 1_800_000;
  131. const NO_RESPONSE_TO_PAUSE = 3;
  132. const NO_RESPONSE_WINDOW_MS = 60_000;
  133. const FAILURES_TO_OPEN = 3;
  134. // Shared breaker and request limit: mirrors of the constants in scripts/lib/jev-breaker.mjs
  135. // (src/__tests__/jev-compaction-module.test.mjs locks the parity, with that library on the same files).
  136. // Seconds a breaker stays open when the response gives no usable Retry-After; a Retry-After above the
  137. // maximum is capped.
  138. const BREAKER_SECONDS = { transient: 60, account: 600, noResponse: 60 };
  139. const BREAKER_MAX_SECONDS = 1800;
  140. // A recorded no-response time further ahead of the clock than this is a corrupt line or a clock set back.
  141. const NO_RESPONSE_SKEW_MS = 5000;
  142. const SAME_OUTAGE_GAP_MS = 15 * 60_000;
  143. const EXTEND_MIN_MS = 5000;
  144. // Pause after writing the breaker before it is read back (a concurrent opener may have replaced it).
  145. const SETTLE_MS = 50;
  146. const CLOCK_SLACK_MS = 60_000;
  147. // `compaction` is a medium-priority point: it may use this share of the minute's limit.
  148. const MEDIUM_SHARE = 0.85;
  149. const RETRY_BODY_MAX_CHARS = 2000;
  150. const APPEND_TRIES = 3;
  151. // One step of file work on the shared state may take this long before the request goes on without it.
  152. const SHARED_OP_MS = 3000;
  153. // Mirror of the `compaction` score question in src/hooks/jev/points.ts (criteria low to high).
  154. export const QUESTION_INSTRUCTIONS =
  155. "How much will the tool result described under this question's name in state.results still be needed for further work on the user's task (state.task)? " +
  156. 'Judge whether further work will use it, not whether it was needed before.';
  157. export const QUESTION_CRITERIA = [
  158. 'Not needed: the work it served is finished, or the result is easy to reproduce (a file listing, repository status, a write confirmation, a result repeated later).',
  159. 'Probably not needed: background from which further work needs at most a conclusion already written in the conversation.',
  160. 'May be useful: details that further work may come back to.',
  161. 'Needed: data that further work relies on and that is nowhere else in the conversation (file contents before an edit, numbers for later calculations, findings, an error to fix).',
  162. ];
  163. // Blocks the host or a hook adds to a user message; they stay in the conversation but are not the
  164. // user's words, so they are cut from the task sent to Jev.
  165. const HOST_BLOCK = /<(system-reminder|task-notification|teammate-message|command-name|command-message|command-args|local-command-stdout|local-command-stderr|local-command-caveat|bash-input|bash-stdout|bash-stderr)\b[^>]*>[\s\S]*?<\/\1>/g;
  166. const HOST_BLOCK_OPEN = /^<(?:system-reminder|task-notification|teammate-message|command-name|command-message|command-args|local-command-stdout|local-command-stderr|local-command-caveat|bash-input|bash-stdout|bash-stderr)\b/;
  167. // Messages that start with one of these are not the user's words either: skill and interruption
  168. // notices, the session summary, and the notices the Claude desktop app adds as entries of their own
  169. // (side-session and CI-monitor events, scheduled tasks, messages from another session: the same
  170. // desktop-app notices scripts/pre-tool-enforcer.mjs skips).
  171. const NOT_USER_PREFIXES = [
  172. 'Base directory for this skill:', 'Caveat:', '[Request interrupted', 'This session is being continued from a previous conversation',
  173. '<side-sessions-event>', '<ci-monitor-event>', '<scheduled-task', '<cross-session-message', 'Another Claude session sent a message:',
  174. ];
  175. // Secret paths in the path and command fields of a call (a mention in a prompt or a result does not
  176. // count): SSH keys, git and gh credentials, Claude Code credentials, AWS credentials, .netrc, .env and
  177. // .envrc files (.env.example is not a secret).
  178. const SECRET_PATH = /[\\/]\.ssh[\\/]+(?:id_[a-z0-9_]+|[^\s"'\\/]*_key)\b|\.git-credentials\b|[\\/]\.config[\\/]+gh[\\/]+hosts\.ya?ml\b|\.credentials\.json\b|[\\/]\.aws[\\/]+credentials\b|(?:^|[\s"'\\/=])\.netrc\b|(?:^|[\s"'\\/=;|&<>])\.env(?!\.example)(?:rc|\.[a-z0-9_-]+)?(?=$|[\s"';|&)<>])/i;
    • Warning: Reads a credential file in a script that also sends data over the network
    • Line 184 on GitHub
  179. // Fields that name a path or run a command, in any tool (built-in or MCP).
  180. const PATH_FIELDS = ['file_path', 'notebook_path', 'path', 'command'];
  181. const TOOL_PATH_FIELDS = { Glob: ['pattern'], Grep: ['glob'] };
  182. /** Mirror of parseJevEnv(POINT) in scripts/jev-resolve.mjs for a named-only point. */
  183. export function pointMode(raw, key) {
  184. const value = String(raw ?? '').trim();
  185. if (!key || value === 'off') return 'off';
  186. let listed = false;
  187. let active = false;
  188. let off = false;
  189. for (const entry of value.split(',')) {
  190. const token = entry.trim();
  191. if (!token) continue;
  192. const colon = token.lastIndexOf(':');
  193. const name = colon === -1 ? token : token.slice(0, colon);
  194. if (name !== POINT) continue;
  195. if (colon !== -1 && token.slice(colon + 1).trim().toLowerCase() === 'off') {
  196. off = true;
  197. active = false;
  198. continue;
  199. }
  200. off = false;
  201. listed = true;
  202. if (colon !== -1 && token.slice(colon + 1) === 'active') active = true;
  203. }
  204. if (off || !listed) return 'off';
  205. return active ? 'active' : 'shadow';
  206. }
  207. /** Mirror of boundExcerpts in src/hooks/jev/config.ts. */
  208. export function boundExcerpts(value, max) {
  209. if (typeof value === 'string') return value.length > max ? value.slice(0, max) : value;
  210. if (Array.isArray(value)) return value.map((item) => boundExcerpts(item, max));
  211. if (value !== null && typeof value === 'object') {
  212. const out = {};
  213. for (const [k, v] of Object.entries(value)) out[k] = boundExcerpts(v, max);
  214. return out;
  215. }
  216. return value;
  217. }
  218. /** Retry-After in milliseconds (delay seconds, a decimal value rounded up to whole seconds, or an HTTP date), else undefined. */
  219. export function retryAfterMs(value, now = Date.now()) {
  220. const text = String(value ?? '').trim();
  221. if (!text) return undefined;
  222. if (/^\d+(\.\d+)?$/.test(text)) return Math.ceil(Number(text)) * 1000;
  223. // The three HTTP-date forms (IMF-fixdate, RFC 850, asctime); any other text is not a Retry-After.
  224. const httpDate =
  225. /^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(text) ||
  226. /^[A-Za-z]{6,9}, \d{2}-[A-Za-z]{3}-\d{2} \d{2}:\d{2}:\d{2} GMT$/.test(text) ||
  227. /^[A-Za-z]{3} [A-Za-z]{3} [ \d]\d \d{2}:\d{2}:\d{2} \d{4}$/.test(text);
  228. if (!httpDate) return undefined;
  229. const at = Date.parse(/GMT$/.test(text) ? text : `${text} GMT`);
  230. return Number.isFinite(at) ? Math.max(0, at - now) : undefined;
  231. }
  232. /** A failed request: {kind, pauseMs?, noResponse?}. Status codes only; bodies are never read. */
  233. export function classifyFailure(result, now = Date.now()) {
  234. if (result.timeout) return { kind: 'timeout', noResponse: true };
  235. if (result.error?.invalid) return { kind: 'invalid_response' };
  236. const status = result.error && Number.isInteger(result.error.status) ? result.error.status : undefined;
  237. if (status === undefined) return { kind: 'no_response', noResponse: true };
  238. const header = retryAfterMs(result.error.retryAfter, now);
  239. const capped = (ms) => Math.min(Math.max(ms, 1000), PAUSE_MAX_MS);
  240. if (status === 429 || status >= 500) return { kind: `http_${status}`, pauseMs: capped(header ?? PAUSE_DEFAULT_MS) };
  241. if (status === 401 || status === 402 || status === 403) return { kind: `http_${status}`, pauseMs: capped(header ?? PAUSE_AUTH_MS) };
  242. return { kind: `http_${status}` };
  243. }
  244. // First `head` and last `tail` characters of the masked text. A long text is masked only where those parts
  245. // come from (with MASK_SLACK_CHARS more on each side); the omitted count is of the original.
  246. function maskedHeadTail(text, head, tail) {
  247. if (text.length <= head + tail + 2 * MASK_SLACK_CHARS) return headTail(maskSecrets(text), head, tail);
  248. const first = maskSecrets(text.slice(0, head + MASK_SLACK_CHARS)).slice(0, head);
  249. const last = maskSecrets(text.slice(-(tail + MASK_SLACK_CHARS))).slice(-tail);
  250. return `${first}\n[... ${text.length - head - tail} chars omitted ...]\n${last}`;
  251. }
  252. const oneLine = (text) => String(text ?? '').replace(/\s+/g, ' ').trim();
  253. const clip = (text, max) => (text.length > max ? text.slice(0, max) : text);
  254. const headTail = (text, head, tail) =>
  255. text.length <= head + tail ? text : `${text.slice(0, head)}\n[... ${text.length - head - tail} chars omitted ...]\n${text.slice(-tail)}`;
  256. const randomId = () => Math.random().toString(36).slice(2, 10) + Math.random().toString(36).slice(2, 6);
  257. const isoNow = () => new Date().toISOString();
  258. const slash = (p) => String(p).replace(/\\/g, '/').replace(/\/+$/, '');
  259. const safeName = (s) => String(s ?? '').replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 80);
  260. const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  261. function inputJson(input) {
  262. try { return JSON.stringify(input ?? {}); } catch { return ''; }
  263. }
  264. const fraction = (raw, fallback, min, max) => {
  265. const text = String(raw ?? '').trim();
  266. const n = Number(text);
  267. return text !== '' && Number.isFinite(n) && n >= min && n <= max ? n : fallback;
  268. };
  269. // Mirror of positiveInt in scripts/jev-resolve.mjs.
  270. function positiveInt(raw, fallback) {
  271. if (typeof raw !== 'string' || !/^[1-9]\d*$/.test(raw)) return fallback;
  272. const parsed = Number(raw);
  273. return Number.isSafeInteger(parsed) ? parsed : fallback;
  274. }
  275. // Session state. A Claude Code process loads the module once per session and calls register once.
  276. function freshState() {
  277. return {
  278. sharedQueue: Promise.resolve(), compacting: 0, pausedUntil: 0, pauseReason: null, failedInRow: 0, noResponseAt: [], requests: 0,
  279. turnCount: 0, lastAttempt: -Infinity, hostCannot: false, compactWindow: undefined, windowTurn: -Infinity,
  280. cachedConfig: undefined, cachedAt: -Infinity, growthArmed: false, growthBase: undefined,
  281. };
  282. }
  283. let session = freshState();
  284. // Configuration from the process environment, with the settings' env as a fallback for a host that did
  285. // not put it into its environment. $.env.get takes literal names only. Without a state directory
  286. // nothing is written.
  287. async function readConfig($) {
  288. const env = {
  289. OMC_JEV: await $.env.get('OMC_JEV'),
  290. TYPESAFE_API_KEY: await $.env.get('TYPESAFE_API_KEY'),
  291. OMC_JEV_ENDPOINT: await $.env.get('OMC_JEV_ENDPOINT'),
  292. OMC_JEV_LOG_DIR: await $.env.get('OMC_JEV_LOG_DIR'),
  293. OMC_JEV_MAX_REQUESTS: await $.env.get('OMC_JEV_MAX_REQUESTS'),
  294. OMC_JEV_EXCERPT_CHARS_COMPACTION: await $.env.get('OMC_JEV_EXCERPT_CHARS_COMPACTION'),
  295. OMC_JEV_COMPACT_AT_PERCENT: await $.env.get('OMC_JEV_COMPACT_AT_PERCENT'),
  296. OMC_JEV_COMPACT_TARGET: await $.env.get('OMC_JEV_COMPACT_TARGET'),
  297. OMC_JEV_COMPACT_TOAST: await $.env.get('OMC_JEV_COMPACT_TOAST'),
  298. OMC_JEV_COMPACT_PRIVATE_PATHS: await $.env.get('OMC_JEV_COMPACT_PRIVATE_PATHS'),
  299. OMC_JEV_BREAKER: await $.env.get('OMC_JEV_BREAKER'),
  300. OMC_JEV_MAX_RPM: await $.env.get('OMC_JEV_MAX_RPM'),
  301. OMC_JEV_BREAKER_DIR: await $.env.get('OMC_JEV_BREAKER_DIR'),
  302. OS: await $.env.get('OS'),
  303. USERPROFILE: await $.env.get('USERPROFILE'),
  304. HOME: await $.env.get('HOME'),
  305. };
  306. // Read settings to fill activation values (OMC_JEV, TYPESAFE_API_KEY) and shared settings
  307. // (OMC_JEV_BREAKER, OMC_JEV_MAX_RPM), but only if they're needed. With a deadline to prevent stalls.
  308. if (env.OMC_JEV === undefined || env.TYPESAFE_API_KEY === undefined) {
  309. try {
  310. const result = await withDeadline($, $.settings.read({ key: 'env' }), CONFIG_TTL_MS);
  311. const fromSettings = result && typeof result === 'object' ? (result.value || result) : result;
  312. if (fromSettings && typeof fromSettings === 'object') {
  313. for (const name of Object.keys(env)) if (env[name] === undefined && typeof fromSettings[name] === 'string') env[name] = fromSettings[name];
  314. }
  315. } catch { /* no settings: the process environment stands */ }
  316. }
  317. // Short-circuit: if mode is 'off' after filling from settings, don't read breaker/rpm settings.
  318. const mode = pointMode(env.OMC_JEV, env.TYPESAFE_API_KEY);
  319. if (mode !== 'off' && (env.OMC_JEV_BREAKER === undefined || env.OMC_JEV_MAX_RPM === undefined)) {
  320. try {
  321. const result = await withDeadline($, $.settings.read({ key: 'env' }), 1000);
  322. const fromSettings = result && typeof result === 'object' ? (result.value || result) : result;
  323. if (fromSettings && typeof fromSettings === 'object') {
  324. for (const name of Object.keys(env)) if (env[name] === undefined && typeof fromSettings[name] === 'string') env[name] = fromSettings[name];
  325. }
  326. } catch { /* no settings: the process environment stands */ }
  327. }
  328. // Home for shared-state directory: HOME on POSIX (matching jev-breaker.mjs, which uses os.homedir()),
  329. // USERPROFILE on Windows. On POSIX, do not use USERPROFILE as a fallback when HOME is unset,
  330. // because os.homedir() does not use USERPROFILE and the breaker state would be in a different location.
  331. // Home for private-path expansion: preserve USERPROFILE for Windows compatibility.
  332. const homeForState = env.OS === 'Windows_NT' ? env.USERPROFILE || env.HOME : env.HOME;
  333. const homeForPrivatePaths = env.USERPROFILE || env.HOME;
  334. const stateDir = env.OMC_JEV_LOG_DIR ? slash(env.OMC_JEV_LOG_DIR) : homeForState ? `${slash(homeForState)}/.omc/state/jev` : undefined;
  335. const privatePaths = String(env.OMC_JEV_COMPACT_PRIVATE_PATHS ?? '')
  336. .split(',')
  337. .map((p) => p.trim())
  338. .filter(Boolean)
  339. // A leading ~ matches both as written (in a command) and expanded to the home directory.
  340. .flatMap((p) => (homeForPrivatePaths && /^~(?=$|[\\/])/.test(p) ? [p, slash(homeForPrivatePaths) + p.slice(1)] : [p]))
  341. .map((p) => slash(p).toLowerCase());
  342. const endpoint = env.OMC_JEV_ENDPOINT || DEFAULT_ENDPOINT;
  343. return {
  344. mode,
  345. key: env.TYPESAFE_API_KEY,
  346. endpoint,
  347. shared: mode === 'off' ? undefined : await sharedSettings(env, endpoint, homeForState),
  348. spoolDir: stateDir ? `${stateDir}/compaction-spool` : undefined,
  349. maxRequests: positiveInt(env.OMC_JEV_MAX_REQUESTS, 0),
  350. excerptChars: positiveInt(env.OMC_JEV_EXCERPT_CHARS_COMPACTION, DEFAULT_EXCERPT_CHARS),
  351. atPercent: fraction(env.OMC_JEV_COMPACT_AT_PERCENT, undefined, 1, 99),
  352. target: fraction(env.OMC_JEV_COMPACT_TARGET, DEFAULT_TARGET, 0.1, 0.9),
  353. toast: String(env.OMC_JEV_COMPACT_TOAST ?? '').trim() === '1',
  354. privatePaths,
  355. };
  356. }
  357. // --- shared breaker and request limit ----------------------------------------------------------
  358. // Mirrors of scripts/lib/jev-breaker.mjs (same files, same rules) through $.fs. Every function is
  359. // fail-open: a file system error never holds a request back and never throws.
  360. /** Mirror of parseMaxRpm: OMC_JEV_MAX_RPM as a positive integer, else undefined (no limit). */
  361. export function parseMaxRpm(raw) {
  362. if (typeof raw !== 'string' || !/^[1-9]\d*$/.test(raw.trim())) return undefined;
  363. const parsed = Number(raw.trim());
  364. return Number.isSafeInteger(parsed) ? parsed : undefined;
  365. }
  366. /** Mirror of thresholdFor(limit, 'compaction'): a medium-priority point. */
  367. export function mediumThreshold(limit) {
  368. return Math.max(1, Math.round(limit * MEDIUM_SHARE));
  369. }
  370. // {breaker, maxRpm, dir} for this endpoint and key, or undefined when neither OMC_JEV_BREAKER=1 nor
  371. // OMC_JEV_MAX_RPM is set. dir is <base>/<scope>, the scope the first 16 hex digits of the SHA-256 of
  372. // the endpoint, a newline and the key; the key itself is never written.
  373. async function sharedSettings(env, endpoint, home) {
  374. const breaker = String(env.OMC_JEV_BREAKER ?? '').trim() === '1';
  375. const maxRpm = parseMaxRpm(env.OMC_JEV_MAX_RPM);
  376. if (!env.TYPESAFE_API_KEY || (!breaker && maxRpm === undefined)) return undefined;
  377. // Asked for but not usable (no home directory, no crypto): nothing is shared and the record says so.
  378. const unavailable = { unavailable: true, breaker: false, maxRpm: undefined, dir: undefined };
  379. const base = env.OMC_JEV_BREAKER_DIR ? slash(env.OMC_JEV_BREAKER_DIR) : home ? `${slash(home)}/.omc/state/jev/breaker` : undefined;
  380. if (!base) return unavailable;
  381. try {
  382. const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(`${endpoint}\n${env.TYPESAFE_API_KEY}`));
  383. const scope = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('').slice(0, 16);
  384. return { breaker, maxRpm, dir: `${base}/${scope}` };
  385. } catch {
  386. return unavailable;
  387. }
  388. }
  389. // One step of file work on the shared state after the other (this module writes whole files, so two
  390. // steps at once would lose each other's lines). A step that takes longer than SHARED_OP_MS (or throws)
  391. // returns `fallback`, but retains its place until the underlying work settles. Queue waiting counts
  392. // toward the deadline too; a step that expires before starting must not do stale file work later.
  393. function sharedStep($, work, fallback, ms = SHARED_OP_MS) {
  394. const deadline = Date.now() + ms;
  395. let expired = false;
  396. const pending = session.sharedQueue.then(() => expired || Date.now() >= deadline ? fallback : work());
  397. session.sharedQueue = pending.then(() => undefined, () => undefined);
  398. return withDeadline($, pending, ms).then((r) => {
  399. expired = true;
  400. return 'value' in r ? r.value : fallback;
  401. });
  402. }
  403. const minuteKey = (now) => new Date(now).toISOString().replace(/[-:T]/g, '').slice(0, 12);
  404. const pause = ($, ms) => new Promise((resolve) => { try { $.clock.after(ms, () => resolve(undefined)); } catch { resolve(undefined); } });
  405. async function readText($, path) {
  406. try { return await $.fs.read(path); } catch { return undefined; }
  407. }
  408. // Reads text distinguishing missing file from read error. Returns {missing: true}, {unreadable: true},
  409. // or {text: ...}. Unreadable errors are fail-open: don't overwrite shared state.
  410. async function readTextSafe($, path) {
  411. try {
  412. return { text: await $.fs.read(path) };
  413. } catch (err) {
  414. try {
  415. const exists = await $.fs.exists(path);
  416. if (!exists) return { missing: true };
  417. } catch {
  418. // Cannot check existence; assume unreadable.
  419. }
  420. return { unreadable: true };
  421. }
  422. }
  423. // Adds one line to a file. $.fs cannot append, so the file is written whole and read back; a line
  424. // another process added between the read and the write is lost, and ours is written again when a
  425. // concurrent write took it away (at most APPEND_TRIES writes). Returns the text read last.
  426. // Before appending on retry, check if the line is already present (idempotent retry).
  427. async function appendLine($, path, line) {
  428. let text = '';
  429. for (let attempt = 0; attempt < APPEND_TRIES; attempt++) {
  430. const current = (await readText($, path)) ?? '';
  431. // Idempotent: if the line is already present, don't write again.
  432. if (current.split('\n').includes(line)) return current;
  433. await $.fs.write(path, `${current === '' || current.endsWith('\n') ? current : `${current}\n`}${line}\n`);
  434. text = (await readText($, path)) ?? '';
  435. if (text.split('\n').includes(line)) return text;
  436. }
  437. return text;
  438. }
  439. // breaker.json as written, whatever its times; undefined when missing or unreadable. A partial text
  440. // (a write landing) is read again.
  441. async function readBreakerFile($, shared) {
  442. const path = `${shared.dir}/breaker.json`;
  443. for (let attempt = 0; attempt < 4; attempt++) {
  444. const text = await readText($, path);
  445. if (text === undefined) {
  446. // Missing: closed. Present but unreadable (a rename landing): read again shortly.
  447. let present = false;
  448. try { present = await $.fs.exists(path); } catch { /* not there, or no check */ }
  449. if (!present) return undefined;
  450. if (attempt < 3) await pause($, 3);
  451. continue;
  452. }
  453. try {
  454. const state = JSON.parse(text);
  455. return state && typeof state === 'object' ? state : undefined;
  456. } catch {
  457. if (attempt < 3) await pause($, 3);
  458. }
  459. }
  460. return undefined;
  461. }
  462. // The open breaker {until, reason, since} (epoch ms), or undefined when it is closed, expired,
  463. // unreadable, corrupt, or OMC_JEV_BREAKER is not set.
  464. async function readSharedBreaker($, shared, now) {
  465. if (!shared?.breaker) return undefined;
  466. try {
  467. const state = await readBreakerFile($, shared);
  468. if (!state || !Number.isFinite(state.until) || state.until <= now) return undefined;
  469. if (state.until > now + BREAKER_MAX_SECONDS * 1000 + CLOCK_SLACK_MS) return undefined;
  470. const since = Number.isFinite(state.since) ? state.since : now;
  471. if (since < 0 || since > now + CLOCK_SLACK_MS) return undefined;
  472. return { until: state.until, reason: String(state.reason ?? ''), since: Math.min(since, now) };
  473. } catch {
  474. return undefined;
  475. }
  476. }
  477. // Opens the breaker for `seconds`, or keeps it open at least that long; an open breaker is never
  478. // shortened. After each write the module pauses SETTLE_MS and reads the file again, and writes the
  479. // later end again when a concurrent opener replaced it with an earlier one (at most 3 writes).
  480. // `since` stays the start of the outage while it is extended or opens again within 15 minutes.
  481. async function openSharedBreaker($, shared, seconds, reason, now) {
  482. try {
  483. const until = now + Math.max(1, Math.min(seconds, BREAKER_MAX_SECONDS)) * 1000;
  484. let since = now;
  485. const previous = await readBreakerFile($, shared);
  486. if (
  487. previous &&
  488. Number.isFinite(previous.until) &&
  489. Number.isFinite(previous.since) &&
  490. previous.since >= 0 &&
  491. previous.since <= now &&
  492. now - previous.until < SAME_OUTAGE_GAP_MS
  493. ) {
  494. since = previous.since;
  495. }
  496. for (let attempt = 0; attempt < 3; attempt++) {
  497. if (attempt > 0) await pause($, SETTLE_MS);
  498. const current = await readSharedBreaker($, shared, now);
  499. if (current && current.until >= until - EXTEND_MIN_MS) return current;
  500. await $.fs.write(`${shared.dir}/breaker.json`, JSON.stringify({ until, reason, since: current ? Math.min(current.since, since) : since }));
  501. }
  502. await pause($, SETTLE_MS);
  503. return await readSharedBreaker($, shared, now);
  504. } catch {
  505. return undefined;
  506. }
  507. }
  508. /** Mirror of retryAfterFromBody: the wait a 429 body states in words ("retry after 30 seconds", "Retry after ~178s"), else undefined. */
  509. export function retryAfterFromBody(text) {
  510. if (typeof text !== 'string') return undefined;
  511. const match = /\bretry[\s_-]*after\b\s*[:=]?\s*~?\s*(\d+(?:\.\d+)?)\s*(?:s|secs?|seconds?)\b/i.exec(text.slice(0, RETRY_BODY_MAX_CHARS));
  512. return match ? Math.max(1, Math.ceil(Number(match[1]))) : undefined;
  513. }
  514. /**
  515. * Mirror of classifyFailure of the shared breaker: {reason, opens, seconds?} for a failed request
  516. * {status?, retryAfter?, body?, noResponse?}, or undefined when the failure says nothing about the
  517. * endpoint (another 4xx, an invalid 2xx body).
  518. */
  519. export function sharedFailureClass(failure, now = Date.now()) {
  520. const status = Number.isInteger(failure?.status) ? failure.status : undefined;
  521. if (status === undefined) return failure?.noResponse ? { reason: 'no-response', opens: false } : undefined;
  522. let seconds;
  523. if (status === 429 || (status >= 500 && status <= 599)) seconds = BREAKER_SECONDS.transient;
  524. else if (status === 401 || status === 402 || status === 403) seconds = BREAKER_SECONDS.account;
  525. else return undefined;
  526. const header = retryAfterMs(failure.retryAfter, now);
  527. const retry = header !== undefined ? Math.max(1, Math.ceil(header / 1000)) : status === 429 ? retryAfterFromBody(failure.body) : undefined;
  528. return { reason: `http-${status}`, opens: true, seconds: Math.min(retry ?? seconds, BREAKER_MAX_SECONDS) };
  529. }
  530. // Requests without a response within the window, this one included, and the newest time recorded.
  531. // The window ends at the newest time, not at this clock (concurrent processes sample their clocks
  532. // before they append).
  533. async function noteNoResponse($, shared, now) {
  534. try {
  535. await appendLine($, `${shared.dir}/noresp-${minuteKey(now)}`, String(now));
  536. const times = [];
  537. for (const key of [minuteKey(now - 60_000), minuteKey(now), minuteKey(now + 60_000)]) {
  538. const text = await readText($, `${shared.dir}/noresp-${key}`);
  539. if (text === undefined) continue;
  540. for (const line of text.split('\n')) {
  541. const time = Number(line);
  542. if (line && Number.isFinite(time) && time <= now + NO_RESPONSE_SKEW_MS) times.push(time);
  543. }
  544. }
  545. const newest = times.reduce((latest, time) => Math.max(latest, time), now);
  546. return { count: times.filter((time) => time > newest - NO_RESPONSE_WINDOW_MS).length, newest };
  547. } catch {
  548. return { count: 0, newest: now };
  549. }
  550. }
  551. // Records a failed request (a sharedFailureClass result): opens or extends the breaker, or counts a
  552. // request without a response; the third within a minute opens it for a minute from the newest one.
  553. async function recordSharedFailureClass($, shared, failure, now) {
  554. if (!shared?.breaker || !failure) return undefined;
  555. if (failure.opens) return openSharedBreaker($, shared, failure.seconds, failure.reason, now);
  556. if (failure.reason === 'no-response') {
  557. const { count, newest } = await noteNoResponse($, shared, now);
  558. if (count >= NO_RESPONSE_TO_PAUSE) return openSharedBreaker($, shared, BREAKER_SECONDS.noResponse, 'no-response', newest);
  559. }
  560. return undefined;
  561. }
  562. // A request that ended without a value (withDeadline's {timeout} or {error}), recorded with the shared
  563. // breaker, as one step of file work after the other.
  564. function recordSharedFailure($, cfg, result) {
  565. if (!cfg.shared?.breaker || result.value) return Promise.resolve();
  566. return sharedStep($, () => writeSharedFailure($, cfg, result), undefined);
  567. }
  568. async function writeSharedFailure($, cfg, result) {
  569. try {
  570. // A request that had less than a second because of the compaction's own deadline says nothing about the endpoint.
  571. if (result.timeout && result.short) return;
  572. const error = result.error;
  573. let failure;
  574. if (result.timeout) failure = { noResponse: true };
  575. else if (error?.invalid) failure = undefined;
  576. else if (error && Number.isInteger(error.status)) failure = { status: error.status, retryAfter: error.retryAfter, body: error.body };
  577. else failure = { noResponse: true };
  578. const now = Date.now();
  579. await recordSharedFailureClass($, cfg.shared, sharedFailureClass(failure, now), now);
  580. } catch { /* the breaker never breaks a compaction */ }
  581. }
  582. // Folds a minute file: a line "<token> <threshold>" is granted when fewer than <threshold> lines were
  583. // granted before it. With `token` the fold stops at that line. Returns {granted, ok} (ok undefined
  584. // when the token is absent or not given).
  585. function foldMinute(text, token) {
  586. let granted = 0;
  587. for (const line of String(text ?? '').split('\n')) {
  588. const [lineToken, thresholdText] = line.split(' ');
  589. if (!lineToken || thresholdText === undefined) continue;
  590. const ok = granted < Number(thresholdText);
  591. if (ok) granted += 1;
  592. if (token !== undefined && lineToken === token) return { granted, ok };
  593. }
  594. return { granted, ok: undefined };
  595. }
  596. // Reserves one request in the current UTC minute: refused without writing anything when the minute
  597. // already reached the threshold; otherwise the line is added and the file folded again. ok is true
  598. // without a limit and whenever the files cannot be used. A read that outlives the decision deadline
  599. // returns {expired: true} without writing: the caller already gave up, so no request will use the slot.
  600. async function reserveRequest($, shared, now, deadline) {
  601. const limit = shared.maxRpm;
  602. if (limit === undefined) return { ok: true };
  603. const threshold = mediumThreshold(limit);
  604. try {
  605. if (Date.now() >= deadline) return { expired: true };
  606. const path = `${shared.dir}/rpm-${minuteKey(now)}`;
  607. const readResult = await readTextSafe($, path);
  608. if (Date.now() >= deadline) return { expired: true };
  609. // Fail-open on unreadable: an error reading the RPM file is not grounds to block a request.
  610. if (readResult.unreadable) return { ok: true };
  611. const before = foldMinute(readResult.text ?? '');
  612. if (before.granted >= threshold) return { ok: false, count: before.granted, threshold, limit };
  613. const token = randomId();
  614. const { granted, ok } = foldMinute(await appendLine($, path, `${token} ${threshold}`), token);
  615. if (ok === undefined) return { ok: true };
  616. return { ok, count: granted, threshold, limit };
  617. } catch {
  618. return { ok: true };
  619. }
  620. }
  621. // Admission of one request, right before the HTTP call: reserve the process cap atomically before
  622. // awaiting shared state, and release it if the breaker or shared limit refuses the request.
  623. // Returns {skip: {mode: 'circuit-open', breaker}} or {skip: {mode: 'cap', count, threshold, limit}}
  624. // when the request must not go out, {} otherwise.
  625. async function admitRequest($, cfg, deadline) {
  626. if (Date.now() >= deadline) return { skip: { mode: 'deadline' } };
  627. if (cfg.maxRequests && session.requests >= cfg.maxRequests) return { skip: { mode: 'process-cap' } };
  628. session.requests++;
  629. const admission = cfg.shared ? await sharedStep($, () => admitNow($, cfg.shared, deadline), {}, Math.min(SHARED_OP_MS, deadline - Date.now())) : {};
  630. if (Date.now() >= deadline) {
  631. session.requests--;
  632. return { skip: { mode: 'deadline' } };
  633. }
  634. if (admission.skip) session.requests--;
  635. return admission;
  636. }
  637. async function admitNow($, shared, deadline) {
  638. const now = Date.now();
  639. const open = await readSharedBreaker($, shared, now);
  640. if (open) return { skip: { mode: 'circuit-open', breaker: open } };
  641. // Recheck deadline after I/O to avoid writing reservations after the compaction deadline has passed.
  642. if (Date.now() >= deadline) return { skip: { mode: 'deadline' } };
  643. const slot = await reserveRequest($, shared, now, deadline);
  644. if (slot.expired) return { skip: { mode: 'deadline' } };
  645. if (!slot.ok) return { skip: { mode: 'cap', count: slot.count, threshold: slot.threshold, limit: slot.limit } };
  646. return {};
  647. }
  648. // Check if RPM capacity is available without reserving it (non-reserving peek).
  649. async function rpmCapacityAvailable($, shared, point, now) {
  650. if (!shared?.maxRpm) return true; // No limit.
  651. try {
  652. const threshold = mediumThreshold(shared.maxRpm);
  653. const path = `${shared.dir}/rpm-${minuteKey(now)}`;
  654. const before = foldMinute(await readText($, path));
  655. return before.granted < threshold;
  656. } catch {
  657. return true; // File system error: fail-open.
  658. }
  659. }
  660. // No request goes out: paused after a failure, breaker open, OMC_JEV_MAX_REQUESTS used up, the
  661. // shared breaker open, or RPM capacity exhausted.
  662. async function blockedReason($, cfg, now) {
  663. if (session.failedInRow >= FAILURES_TO_OPEN) return 'circuit_open';
  664. if (now < session.pausedUntil) return 'paused';
  665. if (cfg.maxRequests && session.requests >= cfg.maxRequests) return 'cap';
  666. // Bounded like admission: a stalled shared volume falls back to "not open" after SHARED_OP_MS.
  667. if (cfg.shared && (await sharedStep($, () => readSharedBreaker($, cfg.shared, now), undefined))) return 'breaker_open';
  668. // The capacity peek is bounded the same way and fails open. Skip the peek when RPM is not enabled.
  669. if (cfg.shared?.maxRpm && !(await sharedStep($, () => rpmCapacityAvailable($, cfg.shared, 'compaction', now), true))) return 'rpm';
  670. return undefined;
  671. }
  672. // The input of a call in a few words: the field that says what the call did, else its JSON. It stays
  673. // in the conversation only (the call was there already); what goes to Jev is masked separately.
  674. function inputSummary(tool, input) {
  675. const i = input && typeof input === 'object' ? input : {};
  676. const pick = (...keys) => keys.map((k) => (typeof i[k] === 'string' ? i[k] : undefined)).filter(Boolean).join(' ');
  677. let text = '';
  678. if (tool === 'Bash' || tool === 'PowerShell' || tool === 'Monitor') text = pick('command');
  679. else if (tool === 'Read' || tool === 'Write' || tool === 'Edit' || tool === 'MultiEdit' || tool === 'NotebookEdit') text = pick('file_path', 'notebook_path');
  680. else if (tool === 'Grep') text = pick('pattern', 'path', 'glob');
  681. else if (tool === 'Glob') text = pick('pattern', 'path');
  682. else if (tool === 'WebFetch') text = pick('url');
  683. else if (tool === 'WebSearch') text = pick('query');
  684. else if (tool === 'Agent' || tool === 'Task') text = pick('subagent_type', 'description');
  685. if (!text) text = inputJson(i);
  686. return oneLine(text);
  687. }
  688. function touchesSecretPath(tool, input, privatePaths) {
  689. if (!input || typeof input !== 'object') return false;
  690. const values = [];
  691. for (const f of [...PATH_FIELDS, ...(TOOL_PATH_FIELDS[tool] || [])]) if (typeof input[f] === 'string') values.push(input[f]);
  692. if (Array.isArray(input.paths)) for (const p of input.paths) if (typeof p === 'string') values.push(p);
  693. if (typeof input.url === 'string' && /^file:/i.test(input.url)) values.push(input.url);
  694. return values.some((v) => {
  695. if (SECRET_PATH.test(v)) return true;
  696. const value = slash(v).toLowerCase();
  697. return privatePaths.some((p) => value.includes(p));
  698. });
  699. }
  700. // A result the host can rebuild from its text alone: anything but an image or another binary record.
  701. const textOnlyMemo = new WeakMap();
  702. function textOnlyResult(r) {
  703. if (r && typeof r === 'object' && textOnlyMemo.has(r)) return textOnlyMemo.get(r);
  704. const v = textOnlyProbe(r);
  705. try { textOnlyMemo.set(r, v); } catch { /* not an object */ }
  706. return v;
  707. }
  708. function textOnlyProbe(r) {
  709. if (r.result === undefined || r.result === null || typeof r.result !== 'object') return true;
  710. let probe;
  711. try { probe = JSON.stringify(r.result); } catch { return false; }
  712. if (probe.length > PROBE_MAX_CHARS) return false;
  713. return !/"type"\s*:\s*"(?:image|document|file)"|"base64"|"media_type"/.test(probe);
  714. }
  715. function messageChars(m) {
  716. let n = (m.text || '').length;
  717. for (const u of m.toolUses || []) n += (u.tool || '').length + inputJson(u.input).length;
  718. for (const r of m.toolResults || []) n += (r.text || '').length;
  719. return n;
  720. }
  721. // The user's own words in a message: '' for tool results, host notices and summaries; host blocks
  722. // inside a message are cut out.
  723. function userWords(m) {
  724. if (m.role !== 'user' || (m.toolResults && m.toolResults.length) || !m.text) return '';
  725. const text = m.text.replace(HOST_BLOCK, '').trim();
  726. if (!text || HOST_BLOCK_OPEN.test(text) || NOT_USER_PREFIXES.some((p) => text.startsWith(p))) return '';
  727. return text;
  728. }
  729. // The task for the state: the /compact instructions first, then the last USER_MESSAGES user
  730. // messages, together USER_CHARS characters.
  731. function userTask(messages, instructions) {
  732. let left = USER_CHARS;
  733. const instr = instructions ? clip(maskSecrets(String(instructions).slice(0, left + MASK_SLACK_CHARS)), left) : undefined;
  734. if (instr) left -= instr.length;
  735. const picked = [];
  736. for (let i = messages.length - 1; i >= 0 && picked.length < USER_MESSAGES && left > 0; i--) {
  737. const words = userWords(messages[i]);
  738. if (!words) continue;
  739. const text = clip(maskSecrets(words.slice(0, left + MASK_SLACK_CHARS)), left);
  740. picked.unshift(text);
  741. left -= text.length;
  742. }
  743. return { task: picked, instructions: instr };
  744. }
  745. // Results the user names: a file (by its name) or a URL the call opened that one of the last user
  746. // messages or the /compact instructions mention as a whole word. Jev sees only the start and the end
  747. // of a long result, so a result the user said would be needed later could lose the part they meant.
  748. // Such a result counts as needed (score 1) and comes first for the budget; it is still cut or traced
  749. // when even it does not fit.
  750. function targetsOf(input) {
  751. const i = input && typeof input === 'object' ? input : {};
  752. const out = new Set();
  753. for (const k of ['file_path', 'notebook_path', 'path', 'url']) if (typeof i[k] === 'string') out.add(i[k]);
  754. if (typeof i.command === 'string') for (const m of i.command.matchAll(/[^\s"'`|;&<>()]+\.[A-Za-z0-9]{1,6}\b|https?:\/\/[^\s"'`]+/g)) out.add(m[0]);
  755. const names = new Set();
  756. for (const t of out) {
  757. if (/^https?:/i.test(t)) names.add(t.toLowerCase());
  758. const base = t.replace(/[\\/]+$/, '').split(/[\\/]/).pop().toLowerCase();
  759. if (base.length >= MENTION_MIN) names.add(base);
  760. }
  761. return names;
  762. }
  763. function mentions(text, name) {
  764. return new RegExp(`(?:^|[\\s"'\`(<\\[/\\\\=:])${escapeRegExp(name)}(?=$|[\\s"'\`)>\\],.;:!?])`).test(text);
  765. }
  766. function markMentioned(candidates, user) {
  767. const text = [user.instructions || '', ...user.task].join('\n').toLowerCase();
  768. let n = 0;
  769. for (const c of candidates) {
  770. if (c.secret || !c.textOnly) continue;
  771. for (const name of targetsOf(c.use.input)) {
  772. if (mentions(text, name)) { c.score = Math.max(c.score, 1); c.asked = true; n++; break; }
  773. }
  774. }
  775. return n;
  776. }
  777. function traceLine(c) {
  778. const what = !c.textOnly ? 'non-text result (image or file) removed' : `${c.res.isError ? 'error' : 'result'} of ${c.resultChars} chars removed`;
  779. return `[compacted] ${c.use.tool}(${clip(c.summary, TRACE_INPUT_CHARS)}) - ${what}`;
  780. }
  781. function shortText(c) {
  782. return `${c.res.text.slice(0, SHORT_CHARS)}\n[result shortened at compaction: kept ${SHORT_CHARS} of ${c.resultChars} chars]`;
  783. }
  784. // The task list stays: every TaskCreate and TaskUpdate call, the newest TodoWrite call and the newest
  785. // call of a plan tool (`update_plan`, as in the Claude desktop app) that carries the whole list
  786. // (`todos`, `items`), and every later call of that tool (a plan tool also takes incremental calls).
  787. const TASK_STEP = /^(?:TaskCreate|TaskUpdate)$/;
  788. const TASK_LIST = /^TodoWrite$|(?:^|__)update_plan$/;
  789. // Candidates: tool results outside the first message and the last KEEP_LAST messages whose call is
  790. // in an earlier assistant message.
  791. function findCandidates(messages, privatePaths) {
  792. const uses = new Map();
  793. messages.forEach((m, i) => { if (m.role === 'assistant') for (const u of m.toolUses || []) uses.set(u.tool_use_id, { i, u }); });
  794. const tailStart = Math.max(1, messages.length - KEEP_LAST);
  795. const out = [];
  796. for (let i = 1; i < tailStart; i++) {
  797. const m = messages[i];
  798. if (m.role !== 'user' || !m.toolResults || !m.toolResults.length) continue;
  799. for (const r of m.toolResults) {
  800. const found = uses.get(r.tool_use_id);
  801. if (!found || found.i >= i) continue;
  802. const c = {
  803. id: r.tool_use_id, resIdx: i, useIdx: found.i, use: found.u, res: r,
  804. summary: inputSummary(found.u.tool, found.u.input),
  805. inputChars: (found.u.tool || '').length + inputJson(found.u.input).length,
  806. resultChars: (r.text || '').length,
  807. secret: touchesSecretPath(found.u.tool, found.u.input, privatePaths),
  808. textOnly: textOnlyResult(r),
  809. score: 0, asked: false, answered: false,
  810. };
  811. c.trace = traceLine(c);
  812. c.fullCost = c.inputChars + c.resultChars;
  813. c.traceCost = c.trace.length + 1; // the newline that joins it to the assistant text
  814. c.shortCost = c.resultChars > SHORT_CHARS ? c.inputChars + shortText(c).length : c.fullCost;
  815. c.task = TASK_STEP.test(c.use.tool || '');
  816. out.push(c);
  817. }
  818. }
  819. const carriesList = (c) => Array.isArray(c.use.input?.todos) || Array.isArray(c.use.input?.items);
  820. const newestList = new Map();
  821. for (const c of out) {
  822. if (TASK_LIST.test(c.use.tool || '') && carriesList(c) && (!newestList.has(c.use.tool) || newestList.get(c.use.tool).resIdx < c.resIdx)) newestList.set(c.use.tool, c);
  823. }
  824. for (const c of out) {
  825. const list = newestList.get(c.use.tool);
  826. if (list && c.resIdx >= list.resIdx && TASK_LIST.test(c.use.tool || '')) c.task = true;
  827. }
  828. return out;
  829. }
  830. const removableChars = (candidates) => candidates.reduce((s, c) => s + Math.max(0, c.fullCost - c.traceCost), 0);
  831. // Rank and fill the budget: highest score first while the upgrade from a trace fits; a result that
  832. // does not fit whole and scores at least "may be useful" is cut to SHORT_CHARS when that fits; the rest
  833. // is traced. A result not asked about (secret path, no text, beyond the questions) is traced; a call
  834. // not longer than its trace and the task list stay whole.
  835. function allocate(candidates, before, target) {
  836. const fixed = before - candidates.reduce((s, c) => s + c.fullCost - c.traceCost, 0);
  837. let avail = Math.floor(before * target) - fixed;
  838. const ranked = [...candidates].sort((a, b) => b.score - a.score || b.resIdx - a.resIdx);
  839. for (const c of ranked) {
  840. const upFull = c.fullCost - c.traceCost;
  841. const upShort = c.shortCost - c.traceCost;
  842. if (c.secret || !c.textOnly) c.keep = 'trace';
  843. else if (upFull <= 0 || c.task) c.keep = 'full';
  844. else if (!c.asked) c.keep = 'trace';
  845. else if (upFull <= avail) { c.keep = 'full'; avail -= upFull; }
  846. else if (c.score >= 0.5 && c.shortCost < c.fullCost && upShort <= avail) { c.keep = 'short'; avail -= Math.max(0, upShort); }
  847. else c.keep = 'trace';
  848. }
  849. }
  850. // Claude Code writes one transcript row per content block, so one API message is several assistant
  851. // rows sharing a message.id. On `--resume` the host joins the assistant rows of one message.id from
  852. // the whole transcript, rows from before the compact boundary included, and repeats every block of
  853. // them but tool_use (measured on Claude Code 2.1.321: a repeated server_tool_use fails the request
  854. // with API 400 "server_tool_use ids must be unique per assistant turn", and a call that became a trace
  855. // comes back without its result). Before a request it joins the rows of one message.id the same way
  856. // (also across result-only user rows: a streamed tool run puts a result between rows of one message)
  857. // and then needs every call's result in the next message. A row kept by its handle is written after
  858. // the boundary with its message.id, one built without a handle gets a new one. So the rows of one API
  859. // message are rebuilt together: one message with their text, traces and kept calls, the result rows
  860. // after it (groupsOf, build). Only the last message with calls keeps its rows' handles, when the
  861. // conversation ends inside its tool loop (the API wants that message to begin with its thinking,
  862. // which a built message cannot carry); between turns no assistant row keeps its handle
  863. // (openLoopStart).
  864. // Rows of one API message: consecutive assistant rows; an assistant row after result-only user rows
  865. // while a call of the group still has no result (a valid transcript starts a new message only once
  866. // every call has its result); and, with the API form, groups whose calls belong to one API message (a
  867. // call whose result came back quickly). A user row with text ends a group, as it ends the host's
  868. // joining. Returns the group of every row (-1 for user rows).
  869. function groupsOf(messages, api) {
  870. const groupOf = new Array(messages.length).fill(-1);
  871. const parent = [];
  872. let cur = -1;
  873. let prevAssistant = false;
  874. let open = new Set();
  875. messages.forEach((m, i) => {
  876. if (m.role === 'assistant') {
  877. if (cur < 0 || !(prevAssistant || open.size)) { cur = parent.length; parent.push(cur); open = new Set(); }
  878. groupOf[i] = cur;
  879. for (const u of m.toolUses || []) open.add(u.tool_use_id);
  880. prevAssistant = true;
  881. return;
  882. }
  883. prevAssistant = false;
  884. const results = m.toolResults || [];
  885. if (m.text || !results.length) { cur = -1; open = new Set(); return; }
  886. for (const r of results) open.delete(r.tool_use_id);
  887. });
  888. const find = (g) => { while (parent[g] !== g) g = parent[g] = parent[parent[g]]; return g; };
  889. if (Array.isArray(api)) {
  890. const groupOfUse = new Map();
  891. messages.forEach((m, i) => { if (m.role === 'assistant') for (const u of m.toolUses || []) if (!groupOfUse.has(u.tool_use_id)) groupOfUse.set(u.tool_use_id, groupOf[i]); });
  892. for (const a of api) {
  893. if (!a || a.role !== 'assistant' || !Array.isArray(a.content)) continue;
  894. const gs = a.content.filter((b) => b && b.type === 'tool_use' && groupOfUse.has(b.id)).map((b) => find(groupOfUse.get(b.id)));
  895. // Joined only across result-only user rows (a user row with text ends the host's joining too).
  896. for (const g of gs.slice(1)) {
  897. const [x, y] = [find(gs[0]), find(g)].sort((p, q) => p - q);
  898. if (x !== y && sameRun(messages, groupOf, find, x, y)) parent[y] = x;
  899. }
  900. }
  901. }
  902. return messages.map((m, i) => (groupOf[i] < 0 ? -1 : find(groupOf[i])));
  903. }
  904. // Whether groups x < y stand in one stretch of the conversation with only assistant rows and
  905. // result-only user rows between them.
  906. function sameRun(messages, groupOf, find, x, y) {
  907. const first = groupOf.findIndex((g) => g >= 0 && find(g) === x);
  908. const last = groupOf.findIndex((g) => g >= 0 && find(g) === y);
  909. for (let i = first + 1; i < last; i++) {
  910. const m = messages[i];
  911. if (m.role === 'user' && (m.text || !(m.toolResults || []).length)) return false;
  912. }
  913. return true;
  914. }
  915. // The first row that keeps its handle: the first row of the last assistant group when that group has
  916. // calls (the conversation ends inside that message's tool loop), else messages.length (between turns,
  917. // after a final answer without calls, every assistant row is rebuilt). User rows after that group do
  918. // not end the loop: a message typed during the tool turn (queued, written as a separate row) joins the
  919. // result message in the API, and the API still wants the last assistant message to begin with its
  920. // thinking.
  921. function openLoopStart(messages, group) {
  922. for (let i = messages.length - 1; i >= 0; i--) {
  923. if (messages[i].role !== 'assistant') continue;
  924. const g = group[i];
  925. return messages.some((x, k) => group[k] === g && (x.toolUses || []).length) ? group.indexOf(g) : messages.length;
  926. }
  927. return messages.length;
  928. }
  929. // The API form of the conversation, or undefined: a list whose every entry has `content` as an array
  930. // or a string, with at least one assistant message whose content is an array (a host that ignores
  931. // `as: 'api'` answers the plain messages, which have neither).
  932. function apiFormOf(value) {
  933. if (!Array.isArray(value) || !value.length) return undefined;
  934. if (!value.every((a) => a && (Array.isArray(a.content) || typeof a.content === 'string'))) return undefined;
  935. return value.some((a) => a.role === 'assistant' && Array.isArray(a.content)) ? value : undefined;
  936. }
  937. // Whether every call of the rows that keep their handles (from keepFrom on) stands in the API form.
  938. function keptCallsIn(messages, keepFrom, api) {
  939. const ids = new Set();
  940. for (const a of api) if (a.role === 'assistant' && Array.isArray(a.content)) for (const b of a.content) if (b && b.type === 'tool_use') ids.add(b.id);
  941. return messages.every((m, i) => i < keepFrom || m.role !== 'assistant' || (m.toolUses || []).every((u) => ids.has(u.tool_use_id)));
  942. }
  943. // A block the API runs itself: server_tool_use, mcp_tool_use and their results
  944. // (advisor_tool_result, web_search_tool_result, ...).
  945. const isServerBlock = (b) => Boolean(b) && typeof b.type === 'string' && b.type !== 'tool_use' && b.type !== 'tool_result' && /_tool_(?:use|result)$/.test(b.type);
  946. // Assistant API messages with a server block, and whether one stands among the rows that keep their
  947. // handles (from keepFrom on). An API message is placed by its first call's row, else by a text block
  948. // equal to the text of a row at or after the row of the API message before it (a cursor in order); one
  949. // placed nowhere takes the row of the next placed message and counts as kept when that row is at or
  950. // after keepFrom (or, with none following, when any row keeps its handle). Without the API form
  951. // nothing is counted (count null).
  952. function serverBlocks(messages, api, keepFrom) {
  953. if (!api) return { count: null, inTail: false };
  954. const rowOfUse = new Map();
  955. messages.forEach((m, i) => { if (m.role === 'assistant') for (const u of m.toolUses || []) if (!rowOfUse.has(u.tool_use_id)) rowOfUse.set(u.tool_use_id, i); });
  956. const placed = [];
  957. let cursor = 0;
  958. for (const a of api) {
  959. if (!a || a.role !== 'assistant' || !Array.isArray(a.content)) continue;
  960. let row;
  961. for (const b of a.content) if (b && b.type === 'tool_use' && rowOfUse.has(b.id)) { row = rowOfUse.get(b.id); break; }
  962. if (row === undefined) {
  963. const texts = a.content.filter((b) => b && b.type === 'text' && typeof b.text === 'string' && b.text).map((b) => b.text);
  964. for (let i = cursor; i < messages.length && texts.length; i++) if (messages[i].role === 'assistant' && texts.includes(messages[i].text)) { row = i; break; }
  965. }
  966. if (row !== undefined) cursor = Math.max(cursor, row);
  967. placed.push({ row, server: a.content.some(isServerBlock) });
  968. }
  969. let next;
  970. for (let k = placed.length - 1; k >= 0; k--) { if (placed[k].row === undefined) placed[k].row = next; else next = placed[k].row; }
  971. let count = 0;
  972. let inTail = false;
  973. for (const p of placed) {
  974. if (!p.server) continue;
  975. count++;
  976. if (p.row === undefined ? keepFrom < messages.length : p.row >= keepFrom) inTail = true;
  977. }
  978. return { count, inTail };
  979. }
  980. // A user message with tool results kept by its engine handle is written after the compact boundary
  981. // with its original parent, which points before the boundary, so `--resume` (and every `-p` turn)
  982. // rebuilt the conversation from before the compaction (measured on Claude Code 2.1.318). Such a
  983. // message is therefore rebuilt from its own text, unchanged for the model, whenever all its results
  984. // are text. A message with an image or another non-text result in the last KEEP_LAST messages keeps
  985. // its handle (counted in kept_handle) and has that limit. Every assistant row before `keepFrom` is
  986. // rebuilt (text, traces and kept calls; thinking and server blocks dropped, an empty row removed) into
  987. // the one message of its group (groupsOf), placed at the group's first row with content, so the result
  988. // rows that follow pair with it and the host gives it a new message.id; from keepFrom on
  989. // (openLoopStart) the rows keep their handles.
  990. function build(messages, candidates, keepFrom, group, stats) {
  991. const byId = new Map();
  992. for (const c of candidates) byId.set(c.id, c);
  993. const out = [];
  994. stats.rebuiltUnchanged = 0;
  995. stats.keptHandle = 0;
  996. stats.rebuiltAssistant = 0;
  997. stats.droppedAssistant = 0;
  998. stats.joinedRows = 0;
  999. const merged = new Map();
  1000. for (const [i, m] of messages.entries()) {
  1001. if (m.role === 'assistant' && i < keepFrom) {
  1002. stats.rebuiltAssistant++;
  1003. const traces = [];
  1004. const kept = [];
  1005. for (const u of m.toolUses || []) {
  1006. const c = byId.get(u.tool_use_id);
  1007. if (c && c.keep === 'trace') traces.push(c.trace);
  1008. else kept.push({ tool_use_id: u.tool_use_id, tool: u.tool, input: u.input });
  1009. }
  1010. const text = [m.text || '', ...traces].filter(Boolean).join('\n');
  1011. if (!text && !kept.length) { stats.droppedAssistant++; continue; }
  1012. const at = merged.get(group[i]);
  1013. if (at !== undefined) {
  1014. const t = out[at];
  1015. out[at] = { role: 'assistant', text: [t.text, text].filter(Boolean).join('\n'), toolUses: [...t.toolUses, ...kept] };
  1016. stats.joinedRows++;
  1017. continue;
  1018. }
  1019. merged.set(group[i], out.length);
  1020. out.push({ role: 'assistant', text, toolUses: kept });
  1021. continue;
  1022. }
  1023. if (m.role === 'user' && (m.toolResults || []).length) {
  1024. const changed = m.toolResults.some((r) => byId.has(r.tool_use_id) && byId.get(r.tool_use_id).keep !== 'full');
  1025. if (!changed && !m.toolResults.every(textOnlyResult)) { stats.keptHandle++; out.push(m); continue; }
  1026. const results = [];
  1027. for (const r of m.toolResults) {
  1028. const c = byId.get(r.tool_use_id);
  1029. if (c && c.keep === 'trace') continue;
  1030. if (c && c.keep === 'short') results.push({ tool_use_id: r.tool_use_id, text: shortText(c), isError: Boolean(r.isError) });
  1031. else if (textOnlyResult(r)) results.push({ tool_use_id: r.tool_use_id, text: r.text || '', isError: Boolean(r.isError) });
  1032. else results.push({ tool_use_id: r.tool_use_id, text: '[non-text result (image or file) removed at compaction]', isError: Boolean(r.isError) });
  1033. }
  1034. if (!changed) stats.rebuiltUnchanged++;
  1035. if (!results.length && !m.text) continue;
  1036. out.push({ role: 'user', text: m.text || '', toolUses: [], toolResults: results });
  1037. continue;
  1038. }
  1039. out.push(m);
  1040. }
  1041. return out;
  1042. }
  1043. // The built list may not add results without a call or calls without a result to what the host gave.
  1044. // Calls and results of one id are always kept or removed together, so this guards against message
  1045. // shapes not foreseen here: an API request with an orphaned tool result would fail.
  1046. function pairing(messages) {
  1047. const open = new Set();
  1048. const seen = new Set();
  1049. const orphanResults = new Set();
  1050. for (const m of messages) {
  1051. for (const u of m.toolUses || []) { open.add(u.tool_use_id); seen.add(u.tool_use_id); }
  1052. for (const r of m.toolResults || []) {
  1053. if (!seen.has(r.tool_use_id)) orphanResults.add(r.tool_use_id);
  1054. open.delete(r.tool_use_id);
  1055. }
  1056. }
  1057. return { orphanResults, openCalls: open };
  1058. }
  1059. // Pairing as the host checks it before a request (measured on Claude Code 2.1.321). The host joins
  1060. // consecutive user rows, and joins an assistant row to an earlier assistant message of the same
  1061. // message.id while only result-only user rows stand between them; then every call of assistant
  1062. // message k needs its result in message k + 1, else the host puts "[Tool result missing due to
  1063. // internal error]" in its place and drops the real result. A row a hook built gets a new message.id,
  1064. // so it joins nothing; the rows with the engine's handle since the last user row with text are taken
  1065. // as one message, also across a built assistant row (the host keeps joining by message.id past it).
  1066. // Returns the ids of calls without a result in the next message (`u:<id>`) and of results without a
  1067. // call in the previous one (`r:<id>`).
  1068. function adjacencyBreaks(messages) {
  1069. const msgs = [];
  1070. let run = -1;
  1071. for (const m of messages) {
  1072. if (m.role === 'assistant') {
  1073. const uses = (m.toolUses || []).map((u) => u.tool_use_id);
  1074. if (m.handle && run >= 0) { msgs[run].uses.push(...uses); continue; }
  1075. msgs.push({ role: 'assistant', uses });
  1076. if (m.handle) run = msgs.length - 1;
  1077. continue;
  1078. }
  1079. const results = (m.toolResults || []).map((r) => r.tool_use_id);
  1080. if (m.text || !results.length) run = -1;
  1081. const last = msgs[msgs.length - 1];
  1082. if (last && last.role === 'user') last.results.push(...results);
  1083. else msgs.push({ role: 'user', results });
  1084. }
  1085. const breaks = new Set();
  1086. const seen = new Set();
  1087. msgs.forEach((mm, k) => {
  1088. if (mm.role !== 'assistant') return;
  1089. const uses = mm.uses.filter((id) => !seen.has(id));
  1090. for (const id of uses) seen.add(id);
  1091. const next = msgs[k + 1];
  1092. if (!next) return;
  1093. const got = new Set(next.role === 'user' ? next.results : []);
  1094. for (const id of uses) if (!got.has(id)) breaks.add(`u:${id}`);
  1095. for (const id of got) if (!mm.uses.includes(id)) breaks.add(`r:${id}`);
  1096. });
  1097. return breaks;
  1098. }
  1099. const subset = (x, y) => [...x].every((id) => y.has(id));
  1100. // Every break of the built list (by id) is already a break of the list the host handed over.
  1101. export function pairingOk(original, built) {
  1102. const a = pairing(original);
  1103. const b = pairing(built);
  1104. return subset(b.orphanResults, a.orphanResults) && subset(b.openCalls, a.openCalls) && subset(adjacencyBreaks(built), adjacencyBreaks(original));
  1105. }
  1106. // Resolves {value}, {timeout: true} or {error}; never rejects. $.clock.after is a timer, not the
  1107. // hook's own time (only $.clock.sleep would be), and $.http.fetch time does not count either.
  1108. function withDeadline($, promise, ms) {
  1109. return new Promise((resolve) => {
  1110. let settled = false;
  1111. let timer;
  1112. try {
  1113. timer = $.clock.after(ms, () => { if (!settled) { settled = true; resolve({ timeout: true }); } });
  1114. } catch { /* no timer: the request alone decides */ }
  1115. promise.then(
  1116. (value) => { if (!settled) { settled = true; try { timer?.cancel(); } catch { /* gone */ } resolve({ value }); } },
  1117. (error) => { if (!settled) { settled = true; try { timer?.cancel(); } catch { /* gone */ } resolve({ error }); } },
  1118. );
  1119. });
  1120. }
  1121. async function askJev($, cfg, state, questions) {
  1122. const response = await $.http.fetch(cfg.endpoint, {
  1123. method: 'POST',
  1124. headers: { 'content-type': 'application/json', authorization: `Bearer ${cfg.key}` },
  1125. body: JSON.stringify({ model: JEV_MODEL, state, questions }),
  1126. });
  1127. if (!response.ok) {
  1128. const failure = new Error(`HTTP ${response.status}`);
  1129. failure.status = response.status;
  1130. failure.retryAfter = response.headers?.['retry-after'];
  1131. // Only for the retry time of a 429 without a usable Retry-After, and only for the shared breaker.
  1132. if (cfg.shared?.breaker && response.status === 429 && retryAfterMs(failure.retryAfter) === undefined) {
  1133. failure.body = String(response.text ?? '').slice(0, RETRY_BODY_MAX_CHARS);
  1134. }
  1135. throw failure;
  1136. }
  1137. let body;
  1138. try { body = JSON.parse(response.text); } catch { body = undefined; }
  1139. if (!body || typeof body.answers !== 'object' || body.answers === null || Array.isArray(body.answers)) {
  1140. const invalid = new Error('invalid response: no answers');
  1141. invalid.invalid = true;
  1142. throw invalid;
  1143. }
  1144. return body.answers;
  1145. }
  1146. // Score 0-1 from an answer on the four levels (0-3), else undefined.
  1147. function scoreOf(answer) {
  1148. const s = answer && typeof answer === 'object' ? answer.score : undefined;
  1149. return typeof s === 'number' && Number.isFinite(s) && s >= 0 && s <= QUESTION_CRITERIA.length - 1 ? s / (QUESTION_CRITERIA.length - 1) : undefined;
  1150. }
  1151. async function writeRecord($, cfg, record) {
  1152. if (!cfg.spoolDir) return;
  1153. try {
  1154. await $.fs.write(`${cfg.spoolDir}/${safeName(record.session_id ?? 'unknown')}--${Date.now()}-${randomId()}.json`, JSON.stringify(record));
  1155. } catch { /* the log never breaks a compaction */ }
  1156. }
  1157. function noteFailures(failures, now) {
  1158. for (const f of failures) {
  1159. if (f.pauseMs && now + f.pauseMs > session.pausedUntil) { session.pausedUntil = now + f.pauseMs; session.pauseReason = f.kind; }
  1160. if (f.noResponse) session.noResponseAt.push(now);
  1161. }
  1162. session.noResponseAt = session.noResponseAt.filter((t) => now - t < NO_RESPONSE_WINDOW_MS);
  1163. if (session.noResponseAt.length >= NO_RESPONSE_TO_PAUSE && now + PAUSE_DEFAULT_MS > session.pausedUntil) {
  1164. session.pausedUntil = now + PAUSE_DEFAULT_MS;
  1165. session.pauseReason = 'no_response';
  1166. session.noResponseAt = [];
  1167. }
  1168. }
  1169. // Decides one compaction: {messages} to install or {fallback: reason}. Fills `record`; never calls next.
  1170. async function decide($, e, cfg, record, started) {
  1171. const messages = Array.isArray(e.messages) ? e.messages : [];
  1172. const before = messages.reduce((s, m) => s + messageChars(m), 0);
  1173. record.chars_before = before;
  1174. if (messages.length <= KEEP_LAST + 1) return { fallback: 'too_few_messages' };
  1175. // The rows of one API message are rebuilt together (groupsOf); only the last message of an open tool
  1176. // loop keeps its handles, and then the API form has to hold every call of it: without it a call whose
  1177. // result came back quickly starts a group of its own, and that message would be split.
  1178. const asApi = e.agentId === undefined ? { as: 'api' } : { as: 'api', agentId: e.agentId };
  1179. let api = apiFormOf((await withDeadline($, Promise.resolve().then(() => $.session.messages(asApi)), HOST_MS)).value);
  1180. const group = groupsOf(messages, api);
  1181. const keepFrom = openLoopStart(messages, group);
  1182. if (api && !keptCallsIn(messages, keepFrom, api)) api = undefined;
  1183. record.kept_from = messages.length - keepFrom;
  1184. if (!api && keepFrom < messages.length) return { fallback: 'no_api_form' };
  1185. const server = serverBlocks(messages, api, keepFrom);
  1186. record.server_blocks = server.count;
  1187. if (server.inTail) return { fallback: 'server_block_in_tail' };
  1188. // A kept row with neither text nor calls is thinking (or a server block). On `--resume` the host joins
  1189. // it with its copy from before the boundary, so the last assistant message would carry its signed
  1190. // thinking block twice, which the extended thinking documentation says fails with 400.
  1191. if (messages.some((m, i) => i >= keepFrom && m.role === 'assistant' && m.handle && !m.text && !(m.toolUses || []).length)) return { fallback: 'thinking_in_tail' };
  1192. // Results of the calls that keep their handles stay whole (a built row may not stand among them).
  1193. const candidates = findCandidates(messages, cfg.privatePaths).filter((c) => c.useIdx < keepFrom);
  1194. record.candidates = candidates.length;
  1195. const removable = removableChars(candidates);
  1196. record.max_reduction = before ? Math.round((removable / before) * 1000) / 1000 : 0;
  1197. if (!before || removable / before < MIN_REDUCTION) return { fallback: 'too_few_results' };
  1198. const blocked = await blockedReason($, cfg, Date.now());
  1199. if (blocked) {
  1200. if (blocked === 'paused') Object.assign(record, { paused_until: new Date(session.pausedUntil).toISOString(), pause_reason: session.pauseReason });
  1201. else if (blocked === 'rpm') Object.assign(record, { held: 'rpm' });
  1202. else if (blocked === 'breaker_open') Object.assign(record, { held: 'breaker' });
  1203. else if (blocked === 'cap') Object.assign(record, { held: 'cap' });
  1204. return { fallback: blocked };
  1205. }
  1206. // Newest results first; only text results of calls outside secret paths are asked about.
  1207. const askable = [...candidates].sort((a, b) => b.resIdx - a.resIdx).filter((c) => !c.secret && c.textOnly);
  1208. record.secret_skipped = candidates.filter((c) => c.secret).length;
  1209. record.non_text = candidates.filter((c) => !c.textOnly).length;
  1210. let left = cfg.maxRequests ? cfg.maxRequests - session.requests : MAX_REQUESTS;
  1211. if (left <= 0) {
  1212. Object.assign(record, { asked: 0, requests: 0, held: 'cap' });
  1213. return { fallback: 'cap' };
  1214. }
  1215. let asked = askable.slice(0, BATCH * Math.min(MAX_REQUESTS, left));
  1216. record.asked = asked.length;
  1217. const user = userTask(messages, typeof e.instructions === 'string' && e.instructions.trim() ? e.instructions : undefined);
  1218. const deadline = started + TOTAL_MS;
  1219. const runs = [];
  1220. let held;
  1221. for (let b = 0; b * BATCH < asked.length; b++) {
  1222. const admission = await admitRequest($, cfg, deadline);
  1223. if (admission.skip) { held = admission.skip; break; }
  1224. const batch = asked.slice(b * BATCH, (b + 1) * BATCH);
  1225. const results = {};
  1226. const questions = {};
  1227. batch.forEach((c, k) => {
  1228. c.question = `r${k + 1}`;
  1229. results[c.question] = {
  1230. tool: c.use.tool,
  1231. input: clip(oneLine(maskSecrets(inputJson(c.use.input).slice(0, STATE_INPUT_CHARS * 4 + MASK_SLACK_CHARS))), STATE_INPUT_CHARS),
  1232. result: maskedHeadTail(c.res.text || '', STATE_HEAD_CHARS, STATE_TAIL_CHARS),
  1233. chars: c.resultChars,
  1234. ...(c.res.isError ? { error: true } : {}),
  1235. };
  1236. questions[c.question] = { type: 'score', instructions: QUESTION_INSTRUCTIONS, criteria: QUESTION_CRITERIA };
  1237. });
  1238. const state = boundExcerpts({ task: user.task, ...(user.instructions ? { compact_instructions: user.instructions } : {}), results }, cfg.excerptChars);
  1239. const t0 = Date.now();
  1240. if (t0 >= deadline) { session.requests--; held = { mode: 'deadline' }; break; }
  1241. const timeoutMs = Math.min(REQUEST_MS, deadline - t0);
  1242. runs.push(
  1243. withDeadline($, askJev($, cfg, state, questions), timeoutMs).then(async (r) => {
  1244. // Shared failure bookkeeping may finish later, but cannot extend this decision's budget.
  1245. const recording = recordSharedFailure($, cfg, { ...r, short: timeoutMs < 1000 });
  1246. if (Date.now() < deadline) await withDeadline($, recording, deadline - Date.now());
  1247. return { ...r, batch, ms: Date.now() - t0 };
  1248. }),
  1249. );
  1250. }
  1251. if (held) {
  1252. // A request held back by the shared breaker or limit is no failure of the endpoint. The results it
  1253. // would have scored count as unanswered, as after a failed request: the budget decides about them.
  1254. const unscored = asked.slice(runs.length * BATCH);
  1255. for (const c of unscored) { c.asked = true; c.score = UNANSWERED_SCORE; }
  1256. record.unscored = unscored.length;
  1257. record.requests = runs.length;
  1258. if (held.mode === 'circuit-open') Object.assign(record, { held: 'breaker', breaker_until: new Date(held.breaker.until).toISOString(), breaker_reason: held.breaker.reason });
  1259. else if (held.mode === 'process-cap') record.held = 'cap';
  1260. else if (held.mode === 'deadline') record.held = 'deadline';
  1261. else Object.assign(record, { held: 'rpm', rpm: { count: held.count, threshold: held.threshold, limit: held.limit } });
  1262. if (!runs.length) return { fallback: held.mode === 'circuit-open' ? 'breaker_open' : held.mode === 'process-cap' ? 'cap' : held.mode === 'deadline' ? 'timeout' : 'rpm' };
  1263. }
  1264. record.requests = runs.length;
  1265. const results = await Promise.all(runs);
  1266. record.jev_ms = results.map((r) => r.ms);
  1267. let answered = 0;
  1268. const failures = [];
  1269. for (const r of results) {
  1270. for (const c of r.batch) {
  1271. c.asked = true;
  1272. const s = r.value ? scoreOf(r.value[c.question]) : undefined;
  1273. if (s === undefined) c.score = UNANSWERED_SCORE;
  1274. else { c.score = s; c.answered = true; answered++; }
  1275. }
  1276. if (!r.value) failures.push(classifyFailure(r));
  1277. }
  1278. record.requests_ok = results.filter((r) => r.value).length;
  1279. record.answered = answered;
  1280. if (failures.length) {
  1281. record.failure = failures.map((f) => f.kind).join(',');
  1282. noteFailures(failures, Date.now());
  1283. if (!asked.length || answered / asked.length < PARTIAL_OK) {
  1284. session.failedInRow++;
  1285. // A deadline hold still records the failures of the requests that did go out.
  1286. if (held?.mode === 'deadline') return { fallback: 'timeout' };
  1287. return { fallback: failures.every((f) => f.kind === 'timeout') ? 'timeout' : 'jev_error' };
  1288. }
  1289. }
  1290. session.failedInRow = 0;
  1291. if (held?.mode === 'deadline') return { fallback: 'timeout' };
  1292. record.mentioned = markMentioned(candidates, user);
  1293. allocate(candidates, before, cfg.target);
  1294. const stats = {};
  1295. const built = build(messages, candidates, keepFrom, group, stats);
  1296. if (!pairingOk(messages, built)) return { fallback: 'build_error' };
  1297. const after = built.reduce((s, m) => s + messageChars(m), 0);
  1298. const hist = [0, 0, 0, 0];
  1299. for (const c of asked) if (c.answered) hist[Math.min(3, Math.round(c.score * 3))]++;
  1300. Object.assign(record, {
  1301. messages_after: built.length,
  1302. chars_after: after,
  1303. reduction: before ? Math.round((1 - after / before) * 1000) / 1000 : 0,
  1304. kept_full: candidates.filter((c) => c.keep === 'full').length,
  1305. kept_short: candidates.filter((c) => c.keep === 'short').length,
  1306. traced: candidates.filter((c) => c.keep === 'trace').length,
  1307. rebuilt_unchanged: stats.rebuiltUnchanged,
  1308. kept_handle: stats.keptHandle,
  1309. rebuilt_assistant: stats.rebuiltAssistant,
  1310. dropped_assistant: stats.droppedAssistant,
  1311. joined_rows: stats.joinedRows,
  1312. score_hist: hist,
  1313. unanswered: asked.length - answered,
  1314. });
  1315. return { messages: built, before, after };
  1316. }
  1317. async function compact($, e, next) {
  1318. let cfg;
  1319. try { cfg = await readConfig($); } catch { return next(e); }
  1320. if (cfg.mode === 'off') return next(e);
  1321. // An active point replaces the summary, so a summary computed ahead of time would be wasted; while
  1322. // the breaker is open the summary will run, so the host may compute it ahead.
  1323. if (e.trigger === 'precompute') return cfg.mode === 'active' && !(await blockedReason($, cfg, Date.now())) ? { skip: 'jev-compaction replaces the summary' } : next(e);
  1324. const started = Date.now();
  1325. // Any compaction of the main loop that actually replaced the messages, this module's or the built-in
  1326. // summary, arms the own threshold's growth gate again (ownThreshold). A skip leaves the context as it
  1327. // was, so the gate stays as it was too.
  1328. const armGrowthGate = (out) => {
  1329. if (e.agentId === undefined && !out?.skip) { session.growthArmed = true; session.growthBase = undefined; }
  1330. return out;
  1331. };
  1332. session.compacting++;
  1333. try {
  1334. let sessionId;
  1335. try { sessionId = await $.session.id(); } catch { sessionId = undefined; }
  1336. const record = {
  1337. ts: isoNow(), point: POINT, event: 'compact', session_id: sessionId ?? null, agent_id: e.agentId ?? null,
  1338. trigger: e.trigger, mode: cfg.mode, messages_before: Array.isArray(e.messages) ? e.messages.length : 0,
  1339. chars_before: 0, target: cfg.target,
  1340. ...(cfg.shared?.unavailable ? { shared_unavailable: true } : {}),
  1341. };
  1342. let decision;
  1343. try {
  1344. decision = await decide($, e, cfg, record, started);
  1345. } catch (error) {
  1346. decision = { fallback: 'exception' };
  1347. record.error = clip(oneLine(maskSecrets(String(error?.message ?? error))), 200);
  1348. }
  1349. record.duration_ms = Date.now() - started;
  1350. if (decision.fallback) Object.assign(record, { result: 'fallback', reason: decision.fallback });
  1351. else record.result = cfg.mode === 'active' ? 'jev' : 'shadow';
  1352. // Written before next(e): the classic SessionStart:compact hook can run while the built-in summary
  1353. // is still being installed.
  1354. await writeRecord($, cfg, record);
  1355. if (decision.fallback || cfg.mode !== 'active') return armGrowthGate(await next(e));
  1356. if (cfg.toast) { try { $.ui.toast(`Jev compaction: ${decision.before} -> ${decision.after} chars`); } catch { /* optional */ } }
  1357. return armGrowthGate({ messages: decision.messages });
  1358. } finally {
  1359. session.compacting--;
  1360. }
  1361. }
  1362. async function ownThreshold($, e, next) {
  1363. const result = await next(e);
  1364. try {
  1365. if (e.agentId !== undefined || session.compacting > 0 || session.hostCannot) return result;
  1366. session.turnCount++;
  1367. // While the growth gate is armed every turn reads the usage, not only every MIN_TURNS_BETWEEN turns.
  1368. if (!session.growthArmed && session.turnCount - session.lastAttempt < MIN_TURNS_BETWEEN) return result;
  1369. if (!session.cachedConfig || Date.now() - session.cachedAt > CONFIG_TTL_MS) { session.cachedConfig = await readConfig($); session.cachedAt = Date.now(); }
  1370. // The base of the growth gate is the lowest usage since the compaction: the first reading may still
  1371. // count the request from before it. It is read before the pause check, so a compaction that ran
  1372. // while requests were paused still gets its base. The first reading never asks.
  1373. if (session.growthArmed && session.cachedConfig.mode === 'active' && session.cachedConfig.atPercent !== undefined) {
  1374. const reading = (await $.session.usage())?.context?.tokens;
  1375. if (!Number.isFinite(reading) || reading <= 0) return result;
  1376. const first = session.growthBase === undefined;
  1377. session.growthBase = first ? reading : Math.min(session.growthBase, reading);
  1378. if (first || session.turnCount - session.lastAttempt < MIN_TURNS_BETWEEN) return result;
  1379. }
  1380. const cfg = session.cachedConfig;
  1381. if (cfg.mode !== 'active' || cfg.atPercent === undefined || (await blockedReason($, cfg, Date.now()))) return result;
  1382. const usage = await $.session.usage();
  1383. const tokens = usage?.context?.tokens;
  1384. if (!Number.isFinite(tokens) || tokens <= 0) return result;
  1385. // context.percent counts from the model's window; the threshold counts from the window the host
  1386. // compacts at (rawMaxTokens).
  1387. if (session.compactWindow === undefined || session.turnCount - session.windowTurn >= WINDOW_REFRESH_TURNS) {
  1388. session.windowTurn = session.turnCount;
  1389. try {
  1390. const detail = await $.session.usage({ breakdown: 'summary' });
  1391. const raw = detail?.context?.breakdown?.rawMaxTokens;
  1392. session.compactWindow = Number.isFinite(raw) && raw > 0 ? raw : usage.context.window;
  1393. } catch { session.compactWindow = usage.context.window; }
  1394. }
  1395. const window = session.compactWindow;
  1396. if (!Number.isFinite(window) || window <= 0 || tokens * 100 < cfg.atPercent * window) return result;
  1397. // After a compaction the context has to grow by OWN_MIN_GAIN of the window first, counted from the
  1398. // lowest usage since it and at most from the threshold: a compaction that ends above the threshold
  1399. // would else be asked for again as soon as the turn gap allows (right away after /compact or the
  1400. // host's own compaction), and one that ends just below it after a few thousand tokens.
  1401. if (session.growthBase !== undefined && tokens - Math.min(session.growthBase, (cfg.atPercent * window) / 100) < OWN_MIN_GAIN * window) return result;
  1402. session.growthArmed = false;
  1403. // The tokens include the fixed prefix (system prompt, tools, instructions): ask only when the
  1404. // removable tool results are worth it, so the threshold never forces the built-in summary.
  1405. session.lastAttempt = session.turnCount;
  1406. const messages = await $.session.messages();
  1407. const before = messages.reduce((s, m) => s + messageChars(m), 0);
  1408. const removable = removableChars(findCandidates(messages, cfg.privatePaths));
  1409. if (!before || removable / before < MIN_REDUCTION || removable / CHARS_PER_TOKEN < OWN_MIN_GAIN * window) return result;
  1410. let reason;
  1411. let detailText = '';
  1412. try {
  1413. const done = await $.session.compact();
  1414. if (done && typeof done.skip === 'string') { reason = 'host_skipped'; detailText = done.skip; }
  1415. } catch (error) {
  1416. detailText = String(error?.message ?? error);
  1417. reason = /headless|sdk|-p\b/i.test(detailText) ? 'host_cannot_compact' : /turn|in flight|running/i.test(detailText) ? 'host_turn_running' : 'host_error';
  1418. if (reason === 'host_cannot_compact') session.hostCannot = true;
  1419. }
  1420. if (reason) {
  1421. let sessionId;
  1422. try { sessionId = await $.session.id(); } catch { sessionId = undefined; }
  1423. await writeRecord($, cfg, {
  1424. ts: isoNow(), point: POINT, event: 'own_threshold', session_id: sessionId ?? null, agent_id: null, result: 'rejected',
  1425. reason, tokens, window, at_percent: cfg.atPercent, detail: clip(oneLine(maskSecrets(detailText)), 200),
  1426. });
  1427. }
  1428. } catch { /* the threshold never breaks a turn */ }
  1429. return result;
  1430. }
  1431. /** Registers the handlers; the session state starts fresh. */
  1432. export function register(on) {
  1433. session = freshState();
  1434. on('session.compact', compact);
  1435. on('turn.complete', ownThreshold);
  1436. }
scripts/run-provider-advisor.js · Bundled script · 413 lines · 2 findings marked
  1. #!/usr/bin/env node
  2. import { hardenWindowsExeSearch } from './lib/windows-search.mjs';
  3. import { spawnSync } from 'child_process';
  4. import { mkdtempSync, rmSync, writeFileSync } from 'fs';
  5. import { mkdir, writeFile } from 'fs/promises';
  6. import { tmpdir } from 'os';
  7. import { join } from 'path';
  8. import process from 'process';
  9. import { resolveOmcStateRoot } from './lib/state-root.mjs';
  10. hardenWindowsExeSearch();
  11. const PROVIDER_BINARIES = {
  12. claude: 'claude',
  13. codex: 'codex',
  14. gemini: 'gemini',
  15. antigravity: 'agy',
  16. grok: 'grok',
  17. cursor: 'cursor-agent',
  18. muse: 'muse',
  19. };
  20. // muse and grok parse a prompt value that begins with `-` (e.g. the YAML
  21. // frontmatter `---` that every `--agent-prompt` role file starts with) as an
  22. // option and abort before calling the model, and grok reserves stdin for ACP
  23. // JSON-RPC. Both accept `--prompt-file`, so hand them the prompt in a private
  24. // temp file instead of argv or stdin.
  25. const PROMPT_FILE_PROVIDERS = new Set(['muse', 'grok']);
  26. const SHOULD_USE_WINDOWS_SHELL = process.platform === 'win32';
  27. // Antigravity (`agy`) headless print mode has a known upstream non-TTY bug
  28. // (google-antigravity/antigravity-cli#76) that, beyond the empty-exit-0 case,
  29. // can hang indefinitely — and agy's own `--print-timeout` flag is non-functional.
  30. // Bound the subprocess ourselves so a hang fails cleanly instead of blocking the
  31. // whole `omc ask` / `/ccg` flow forever. Generous so it never trips a real answer.
  32. // The kill MUST be SIGKILL: spawnSync does not return until the child exits, so a
  33. // catchable SIGTERM would let a signal-trapping agy hang past the timeout.
  34. const ANTIGRAVITY_TIMEOUT_DEFAULT_MS = 300000;
  35. const ANTIGRAVITY_TIMEOUT_KILL_SIGNAL = 'SIGKILL';
  36. const ANTIGRAVITY_TIMEOUT_MS = (() => {
  37. const raw = process.env.OMC_ANTIGRAVITY_TIMEOUT_MS;
  38. if (raw === undefined || raw === '') {
  39. return ANTIGRAVITY_TIMEOUT_DEFAULT_MS;
  40. }
  41. const parsed = Number(raw);
  42. // Require a finite, integer, >=1000ms value; clamp to <=1h. Otherwise warn and
  43. // fall back to the default so a bad override can't disable or distort the bound.
  44. if (!Number.isFinite(parsed) || !Number.isInteger(parsed) || parsed < 1000) {
  45. console.error(`[ask-antigravity] Ignoring invalid OMC_ANTIGRAVITY_TIMEOUT_MS="${raw}" (need an integer >= 1000); using ${ANTIGRAVITY_TIMEOUT_DEFAULT_MS}ms.`);
  46. return ANTIGRAVITY_TIMEOUT_DEFAULT_MS;
  47. }
  48. return Math.min(parsed, 3600000);
  49. })();
  50. /**
  51. * Build CLI args for a given provider.
  52. * - claude: `claude -p <prompt>` (or `claude -p` reading the prompt from stdin)
  53. * - codex: `codex exec --dangerously-bypass-approvals-and-sandbox <prompt>`
  54. * - gemini: `gemini -p <prompt> --yolo`
  55. * - antigravity: `agy --dangerously-skip-permissions -p <prompt>` (Antigravity CLI;
  56. * `-p` takes the prompt as its value and cannot read it from stdin, so the
  57. * prompt is always passed as an arg with approval flags first)
  58. * - grok: `grok --prompt-file <file> --always-approve` (single-turn headless
  59. * mode; grok's stdin is reserved for ACP JSON-RPC, never the prompt)
  60. * - cursor: `cursor-agent --print --force --trust --sandbox disabled <prompt>`
  61. * - muse: `muse exec --prompt-file <file> --approval-mode never --user-input-auto-resolve`
  62. * (headless; preserves Muse's configured sandbox behavior)
  63. */
  64. function buildProviderArgs(provider, prompt, { pipePromptViaStdin = false, promptFile } = {}) {
  65. if (provider === 'codex') {
  66. return ['exec', '--dangerously-bypass-approvals-and-sandbox', pipePromptViaStdin ? '-' : prompt];
  67. }
  68. if (provider === 'gemini') {
  69. return pipePromptViaStdin ? ['--yolo'] : ['-p', prompt, '--yolo'];
  70. }
  71. if (provider === 'antigravity') {
  72. // Antigravity (`agy`): `-p`/`--print` takes the prompt as its VALUE (next
  73. // token), not as a boolean, and it does NOT read the prompt from stdin
  74. // (`agy -p` with no value errors "flag needs an argument"). So always pass
  75. // the prompt as the `-p` value with approval flags first.
  76. // Verified on agy 1.0.10.
  77. return ['--dangerously-skip-permissions', '-p', prompt];
  78. }
  79. if (provider === 'grok') {
  80. // Grok's stdin is for ACP JSON-RPC, not the prompt, and `-p <prompt>` rejects
  81. // a dash-leading prompt, so the prompt always arrives via --prompt-file.
  82. return ['--prompt-file', promptFile, '--always-approve'];
  83. }
  84. if (provider === 'muse') {
  85. return ['exec', '--prompt-file', promptFile, '--approval-mode', 'never', '--user-input-auto-resolve'];
  86. }
  87. if (provider === 'cursor') {
  88. // Cursor Agent's print mode takes the prompt as a positional arg. Keep stdin
  89. // closed so it cannot interpret advisor prompt bytes as interactive input.
  90. return ['--print', '--force', '--trust', '--sandbox', 'disabled', prompt];
  91. }
  92. // claude: `claude -p` reads the prompt from stdin when no prompt arg is given.
  93. return pipePromptViaStdin ? ['-p'] : ['-p', prompt];
  94. }
  95. function shouldPipePromptViaStdin(provider, prompt) {
  96. if (provider === 'codex' || provider === 'gemini') {
  97. if (typeof prompt === 'string' && (prompt.includes('\n') || prompt.length > 500)) {
  98. return true;
  99. }
  100. return SHOULD_USE_WINDOWS_SHELL;
  101. }
  102. // antigravity (`agy`): `-p` requires its prompt as an arg value and errors if
  103. // the prompt is piped via stdin, so it never uses the stdin pipe path. Long /
  104. // multiline prompts are safe as a single argv value (spawn without a shell).
  105. // #3221: long/multiline/frontmatter prompts must not be passed to Claude as a
  106. // raw argv value. Claude's CLI parses a leading `-`/`--`/`---` (YAML
  107. // frontmatter) token as an option and either errors out or drops the prompt.
  108. // Route those over stdin (`claude -p` reads the prompt from stdin). Short,
  109. // single-line, non-option prompts keep the existing `-p <prompt>` behavior.
  110. if (provider === 'claude') {
  111. if (typeof prompt !== 'string') {
  112. return false;
  113. }
  114. return prompt.includes('\n') || prompt.length > 500 || /^\s*-/.test(prompt);
  115. }
  116. // grok and muse (prompt file), cursor-agent (interactive stdin), and any other
  117. // provider never pipe the prompt.
  118. return false;
  119. }
  120. const ASK_ORIGINAL_TASK_ENV = 'OMC_ASK_ORIGINAL_TASK';
  121. const ASK_ORIGINAL_TASK_ENV_ALIAS = 'OMX_ASK_ORIGINAL_TASK';
  122. function usage() {
  123. console.error('Usage: omc ask <claude|codex|gemini|antigravity|grok|cursor|muse> "<prompt>"');
  124. console.error('Legacy direct usage: node scripts/run-provider-advisor.js <claude|codex|gemini|antigravity|grok|cursor|muse> <prompt...>');
  125. console.error(' or: node scripts/run-provider-advisor.js claude --print "<prompt>"');
  126. console.error(' or: node scripts/run-provider-advisor.js gemini --prompt "<prompt>"');
  127. }
  128. function slugify(value) {
  129. return value
  130. .toLowerCase()
  131. .replace(/[^a-z0-9]+/g, '-')
  132. .replace(/^-+|-+$/g, '')
  133. .slice(0, 60) || 'task';
  134. }
  135. function timestampToken(date = new Date()) {
  136. return date.toISOString().replace(/[:.]/g, '-');
  137. }
  138. function parseArgs(argv) {
  139. const [providerRaw, ...rest] = argv;
  140. const provider = (providerRaw || '').toLowerCase();
  141. if (!provider || !(provider in PROVIDER_BINARIES)) {
  142. usage();
  143. process.exit(1);
  144. }
  145. if (rest.length === 0) {
  146. usage();
  147. process.exit(1);
  148. }
  149. if (rest[0] === '-p' || rest[0] === '--print' || rest[0] === '--prompt') {
  150. const prompt = rest.slice(1).join(' ').trim();
  151. if (!prompt) {
  152. usage();
  153. process.exit(1);
  154. }
  155. return { provider, prompt };
  156. }
  157. return { provider, prompt: rest.join(' ').trim() };
  158. }
  159. // Strip Claude session markers so provider advisors do not detect or inherit the active Claude Code session.
  160. const CLAUDE_SESSION_STRIPPED_ENV_VARS = new Set([
  161. 'CLAUDECODE',
  162. 'CLAUDE_SESSION_ID',
  163. 'CLAUDECODE_SESSION_ID',
  164. 'CLAUDE_CODE_ENTRYPOINT',
  165. ]);
  166. const CODEX_STRIPPED_ENV_VARS = new Set(['RUST_LOG', 'RUST_BACKTRACE', 'RUST_LIB_BACKTRACE']);
  167. function buildProviderEnv(provider, env = process.env) {
  168. const strippedEnvVars = provider === 'codex'
  169. ? new Set([...CLAUDE_SESSION_STRIPPED_ENV_VARS, ...CODEX_STRIPPED_ENV_VARS])
  170. : CLAUDE_SESSION_STRIPPED_ENV_VARS;
  171. return Object.fromEntries(
  172. Object.entries(env).filter(([key]) => !strippedEnvVars.has(key)),
  173. );
  174. }
  175. // Antigravity (`agy`) headless print mode requires the prompt as an argv value
  176. // (it cannot read the prompt from stdin). To avoid cmd.exe parsing issues on Windows,
  177. // spawn agy without a shell (shell: false) — agy is a real executable and does not
  178. // need shell preprocessing. This was fixed in agy 1.0.15/1.1.1 (closed upstream #76).
  179. function guardProviderPlatform(provider) {
  180. // No platform-specific blocks; all providers are supported.
  181. // The Windows spawn path uses shell: false for antigravity to pass the prompt safely.
  182. }
  183. function ensureBinary(provider, binary) {
  184. const probe = spawnSync(binary, ['--version'], {
  185. stdio: 'ignore',
  186. encoding: 'utf8',
  187. env: buildProviderEnv(provider),
  188. shell: SHOULD_USE_WINDOWS_SHELL,
  189. });
  190. const isMissingOnWindowsShell = SHOULD_USE_WINDOWS_SHELL
  191. && probe.status !== 0
  192. && (() => {
  193. const whereResult = spawnSync('where', [binary], {
  194. encoding: 'utf8',
  195. env: buildProviderEnv(provider),
  196. });
  197. return whereResult.status !== 0 || !whereResult.stdout?.trim();
  198. })();
  199. if ((probe.error && probe.error.code === 'ENOENT') || isMissingOnWindowsShell) {
  200. const verify = `${binary} --version`;
  201. console.error(`[ask-${binary}] Missing required local CLI binary: ${binary}`);
  202. console.error(`[ask-${binary}] Install/configure ${binary} CLI, then verify with: ${verify}`);
  203. process.exit(1);
  204. }
  205. }
  206. function buildSummary(exitCode, output) {
  207. if (exitCode === 0) {
  208. return 'Provider completed successfully. Review the raw output for details.';
  209. }
  210. const firstLine = output
  211. .split('\n')
  212. .map((line) => line.trim())
  213. .find(Boolean);
  214. return firstLine
  215. ? `Provider command failed (exit ${exitCode}): ${firstLine}`
  216. : `Provider command failed with exit code ${exitCode}.`;
  217. }
  218. function buildActionItems(exitCode) {
  219. if (exitCode === 0) {
  220. return [
  221. 'Review the response and extract decisions you want to apply.',
  222. 'Capture follow-up implementation tasks if needed.',
  223. ];
  224. }
  225. return [
  226. 'Inspect the raw output error details.',
  227. 'Fix CLI/auth/environment issues and rerun the command.',
  228. ];
  229. }
  230. function resolveOriginalTask(prompt) {
  231. const canonical = process.env[ASK_ORIGINAL_TASK_ENV];
  232. if (canonical && canonical.trim()) {
  233. return canonical;
  234. }
  235. const alias = process.env[ASK_ORIGINAL_TASK_ENV_ALIAS];
  236. if (alias && alias.trim()) {
  237. console.error(`[ask] DEPRECATED: ${ASK_ORIGINAL_TASK_ENV_ALIAS} is deprecated; use ${ASK_ORIGINAL_TASK_ENV} instead.`);
  238. return alias;
  239. }
  240. return prompt;
  241. }
  242. async function writeArtifact({ provider, originalTask, finalPrompt, rawOutput, exitCode }) {
  243. const root = process.cwd();
  244. const artifactDir = join(await resolveOmcStateRoot(root), 'artifacts', 'ask');
  245. const slug = slugify(originalTask);
  246. const timestamp = timestampToken();
  247. const artifactPath = join(artifactDir, `${provider}-${slug}-${timestamp}.md`);
  248. const summary = buildSummary(exitCode, rawOutput);
  249. const actionItems = buildActionItems(exitCode);
  250. const body = [
  251. `# ${provider} advisor artifact`,
  252. '',
  253. `- Provider: ${provider}`,
  254. `- Exit code: ${exitCode}`,
  255. `- Created at: ${new Date().toISOString()}`,
  256. '',
  257. '## Original task',
  258. '',
  259. originalTask,
  260. '',
  261. '## Final prompt',
  262. '',
  263. finalPrompt,
  264. '',
  265. '## Raw output',
  266. '',
  267. '```text',
  268. rawOutput || '(no output)',
  269. '```',
  270. '',
  271. '## Concise summary',
  272. '',
  273. summary,
  274. '',
  275. '## Action items',
  276. '',
  277. ...actionItems.map((item) => `- ${item}`),
  278. '',
  279. ].join('\n');
  280. await mkdir(artifactDir, { recursive: true });
  281. await writeFile(artifactPath, body, 'utf8');
  282. return artifactPath;
  283. }
  284. async function main() {
  285. const { provider, prompt } = parseArgs(process.argv.slice(2));
  286. const binary = PROVIDER_BINARIES[provider];
  287. guardProviderPlatform(provider);
  288. ensureBinary(provider, binary);
  289. const pipePromptViaStdin = shouldPipePromptViaStdin(provider, prompt);
  290. // Antigravity on Windows: spawn without a shell to avoid cmd.exe prompt parsing.
  291. // The `-p <prompt>` format is safe as a direct argv value when spawned without
  292. // shell preprocessing (agy is a real executable, not a shell function or alias).
  293. const useShell = provider === 'antigravity' ? false : SHOULD_USE_WINDOWS_SHELL;
  294. const promptDir = PROMPT_FILE_PROVIDERS.has(provider) ? mkdtempSync(join(tmpdir(), 'omc-ask-')) : null;
  295. let run;
  296. try {
  297. let promptFile;
  298. if (promptDir) {
  299. promptFile = join(promptDir, 'prompt.md');
  300. writeFileSync(promptFile, prompt, { encoding: 'utf8', mode: 0o600 });
  301. // A shell spawn joins argv with spaces unquoted, so quote the path in case
  302. // the temp dir contains spaces (e.g. a Windows profile like "John Smith").
  303. if (useShell) {
  304. promptFile = `"${promptFile}"`;
  305. }
  306. }
  307. const providerArgs = buildProviderArgs(provider, prompt, { pipePromptViaStdin, promptFile });
  308. run = spawnSync(binary, providerArgs, {
  309. encoding: 'utf8',
  310. maxBuffer: 10 * 1024 * 1024,
  311. env: buildProviderEnv(provider),
  312. shell: useShell,
  313. // Bound antigravity so an upstream non-TTY hang (#76) fails cleanly instead of
  314. // blocking forever; agy's own --print-timeout does not work. SIGKILL (not a
  315. // catchable SIGTERM) guarantees spawnSync returns even if agy traps signals.
  316. ...(provider === 'antigravity' ? { timeout: ANTIGRAVITY_TIMEOUT_MS, killSignal: ANTIGRAVITY_TIMEOUT_KILL_SIGNAL } : {}),
  317. ...(pipePromptViaStdin ? { input: prompt } : { stdio: ['ignore', 'pipe', 'pipe'] }),
  318. });
  319. } finally {
  320. if (promptDir) {
  321. rmSync(promptDir, { recursive: true, force: true });
  322. }
  323. }
  324. const stdout = run.stdout || '';
  325. const stderr = run.stderr || '';
  326. const rawOutput = [stdout, stderr].filter(Boolean).join(stdout && stderr ? '\n\n' : '');
  327. let exitCode = typeof run.status === 'number' ? run.status : 1;
  328. // Antigravity (#76): the headless non-TTY bug surfaces two ways — a clean
  329. // zero-exit with NO output (output dropped on flush), or an indefinite hang.
  330. // The timeout above turns a hang into a killed/non-zero run; here we also turn
  331. // a zero-exit empty result into a failure, so the advisor never records
  332. // "(no output)" and reports success. (Empirically agy 1.0.10 returns output
  333. // under pipe capture; this surfaces the regression/refusal cases instead of
  334. // masking them.) No silent success, no infinite wait — see #76 for why neither
  335. // a PTY wrapper nor agy's --print-timeout is a usable workaround.
  336. if (provider === 'antigravity' && (run.error?.code === 'ETIMEDOUT' || run.signal === ANTIGRAVITY_TIMEOUT_KILL_SIGNAL)) {
  337. console.error(`[ask-antigravity] agy timed out after ${ANTIGRAVITY_TIMEOUT_MS}ms with no completed response (see antigravity-cli#76).`);
  338. console.error('[ask-antigravity] agy headless print mode can hang on non-TTY; verify interactively with: agy -p "<prompt>"');
  339. exitCode = exitCode === 0 ? 1 : exitCode;
  340. } else if (provider === 'antigravity' && exitCode === 0 && rawOutput.trim() === '') {
  341. console.error('[ask-antigravity] agy exited 0 but produced no output under pipe capture.');
  342. console.error('[ask-antigravity] Treating as failure (see google-antigravity/antigravity-cli#76).');
  343. console.error('[ask-antigravity] Re-run, or verify interactively with: agy -p "<prompt>"');
  344. exitCode = 1;
  345. }
  346. const artifactPath = await writeArtifact({
  347. provider,
  348. originalTask: resolveOriginalTask(prompt),
  349. finalPrompt: prompt,
  350. rawOutput,
  351. exitCode,
  352. });
  353. console.log(artifactPath);
  354. if (run.error) {
  355. console.error(`[ask-${provider}] ${run.error.message}`);
  356. }
  357. if (exitCode !== 0) {
  358. process.exit(exitCode);
  359. }
  360. }
  361. main().catch((error) => {
  362. console.error(`[run-provider-advisor] ${error instanceof Error ? error.message : String(error)}`);
  363. process.exit(1);
  364. });
skills/project-session-manager/lib/tmux.sh · Bundled script · 241 lines · 1 finding marked
  1. #!/usr/bin/env bash
  2. # PSM Tmux Session Management
  3. # Check if tmux is available
  4. psm_has_tmux() {
  5. command -v tmux &> /dev/null
  6. }
  7. # Canonical tmux-safe session-name contract (issue #3528).
  8. # tmux reserves ':' and '.' in target names (the "session:window.pane" syntax)
  9. # and silently rewrites them inside session names, which orphans any PSM session
  10. # whose requested name still contained them. This is the single source of truth
  11. # for translating a PSM logical name into the name tmux will actually use; it
  12. # MUST be applied at every tmux boundary. Translation is idempotent, so it is
  13. # safe to call on names that are already tmux-safe (e.g. old registry entries).
  14. psm_tmux_safe_name() {
  15. local name="$1"
  16. printf '%s' "${name//[.:]/_}"
  17. }
  18. # Build the canonical tmux session name for a PSM public session id
  19. # (e.g. "omc:pr-123" -> "psm_omc_pr-123"). The colon-form id remains the
  20. # human-facing identifier in sessions.json and on the CLI.
  21. psm_tmux_name_from_id() {
  22. psm_tmux_safe_name "psm:${1}"
  23. }
  24. # Create a tmux session
  25. # Usage: psm_create_tmux_session <session_name> <working_dir>
  26. psm_create_tmux_session() {
  27. local session_name
  28. session_name=$(psm_tmux_safe_name "$1")
  29. local working_dir="$2"
  30. if ! psm_has_tmux; then
  31. echo "error|tmux not found"
  32. return 1
  33. fi
  34. # Check if session already exists
  35. if tmux has-session -t "$session_name" 2>/dev/null; then
  36. echo "exists|$session_name"
  37. return 1
  38. fi
  39. # Create detached session
  40. tmux new-session -d -s "$session_name" -c "$working_dir" 2>/dev/null || {
  41. echo "error|Failed to create tmux session"
  42. return 1
  43. }
  44. # Fail closed: verify the session exists under the exact name PSM will use
  45. # for later lookups (issue #3528). If tmux rewrote the name, every later
  46. # has-session / send-keys / kill / attach would silently miss.
  47. if ! tmux has-session -t "$session_name" 2>/dev/null; then
  48. echo "error|tmux session not found after create: $session_name"
  49. return 1
  50. fi
  51. echo "created|$session_name"
  52. return 0
  53. }
  54. # Launch Claude Code in tmux session, optionally injecting either a context-file
  55. # trigger prompt or a literal initial prompt.
  56. # Usage: psm_launch_claude <session_name> [initial_context]
  57. # initial_context may be either:
  58. # - a path relative to the worktree root (e.g. .psm/review.md), or
  59. # - a literal prompt string to send after Claude boots.
  60. #
  61. # Passes --dangerously-skip-permissions so the session does not stall on
  62. # directory-trust or repeated tool-approval prompts (issue #2508).
  63. # Set PSM_CLAUDE_STARTUP_DELAY (default: 5s) to tune literal-prompt delivery.
  64. psm_launch_claude() {
  65. local session_name
  66. session_name=$(psm_tmux_safe_name "$1")
  67. local initial_context="${2:-}"
  68. if ! tmux has-session -t "$session_name" 2>/dev/null; then
  69. echo "error|Session not found: $session_name"
  70. return 1
  71. fi
  72. # --dangerously-skip-permissions bypasses both the directory-trust prompt and
  73. # every per-tool approval prompt. Without this flag, unattended PSM sessions
  74. # can block indefinitely on the first tool call (issue #2508).
  75. tmux send-keys -t "$session_name" "claude --dangerously-skip-permissions" Enter
  76. if [[ -n "$initial_context" ]]; then
  77. local session_path=""
  78. session_path=$(tmux display-message -p -t "$session_name" '#{pane_current_path}' 2>/dev/null || true)
  79. # If the second arg resolves to a file in the worktree, preserve the
  80. # existing context-file flow. Otherwise treat it as a literal prompt.
  81. if [[ -n "$session_path" && -f "$session_path/$initial_context" ]]; then
  82. psm_inject_prompt "$session_name" "$initial_context"
  83. else
  84. local startup_delay="${PSM_CLAUDE_STARTUP_DELAY:-5}"
  85. (
  86. sleep "$startup_delay"
  87. tmux send-keys -t "$session_name" -l -- "$initial_context" 2>/dev/null || true
  88. tmux send-keys -t "$session_name" Enter 2>/dev/null || true
  89. ) &
  90. fi
  91. fi
  92. echo "launched|$session_name"
  93. return 0
  94. }
  95. # Render a PSM template file by substituting {{KEY}} placeholders.
  96. # Usage: psm_render_template <template_file> [KEY=VALUE ...]
  97. # Outputs rendered content to stdout; returns 1 if template not found.
  98. psm_render_template() {
  99. local template_file="$1"
  100. shift
  101. if [[ ! -f "$template_file" ]]; then
  102. echo "error|Template not found: $template_file" >&2
  103. return 1
  104. fi
  105. local content
  106. content=$(cat "$template_file")
  107. for assignment in "$@"; do
  108. local key="${assignment%%=*}"
  109. local value="${assignment#*=}"
  110. # Bash parameter expansion handles multiline values safely
  111. content="${content//\{\{${key}\}\}/$value}"
  112. done
  113. printf '%s\n' "$content"
  114. }
  115. # Returns 0 if the captured pane text shows Claude's interactive input prompt.
  116. # Matches '>' (standard prompt) or '?' (trust prompt) as the sole content of a line.
  117. # Usage: _psm_pane_has_claude_prompt <pane_text>
  118. _psm_pane_has_claude_prompt() {
  119. local pane_text="$1"
  120. printf '%s' "$pane_text" | grep -qE '^[[:space:]]*(>|\?)[[:space:]]*$'
  121. }
  122. # Poll the tmux pane until Claude's REPL prompt appears.
  123. # Usage: psm_wait_for_claude_prompt <session_name> [max_seconds]
  124. # Returns 0 when prompt detected; 1 on timeout.
  125. psm_wait_for_claude_prompt() {
  126. local session_name
  127. session_name=$(psm_tmux_safe_name "$1")
  128. local max_wait="${2:-30}"
  129. local waited=0
  130. while [[ $waited -lt $max_wait ]]; do
  131. local pane_content
  132. pane_content=$(tmux capture-pane -t "$session_name" -p 2>/dev/null) || return 1
  133. if _psm_pane_has_claude_prompt "$pane_content"; then
  134. return 0
  135. fi
  136. sleep 1
  137. (( waited++ )) || true
  138. done
  139. return 1
  140. }
  141. # Wait for Claude's REPL to be ready then inject a context-file trigger prompt.
  142. # Non-fatal: warns on timeout but does not fail the session creation.
  143. # Usage: psm_inject_prompt <session_name> <context_file_relative_path>
  144. psm_inject_prompt() {
  145. local session_name
  146. session_name=$(psm_tmux_safe_name "$1")
  147. local context_file="$2"
  148. if ! psm_wait_for_claude_prompt "$session_name"; then
  149. echo "warn|Timed out waiting for Claude prompt; task context not injected" >&2
  150. return 0
  151. fi
  152. local trigger="Read ${context_file} for full task context, then begin."
  153. # Use literal mode (-l) to prevent tmux from interpreting key names in the text
  154. tmux send-keys -t "$session_name" -l -- "$trigger"
  155. sleep 0.15
  156. tmux send-keys -t "$session_name" Enter
  157. return 0
  158. }
  159. # Kill a tmux session
  160. # Usage: psm_kill_tmux_session <session_name>
  161. psm_kill_tmux_session() {
  162. local session_name
  163. session_name=$(psm_tmux_safe_name "$1")
  164. if ! tmux has-session -t "$session_name" 2>/dev/null; then
  165. echo "not_found|$session_name"
  166. return 0
  167. fi
  168. tmux kill-session -t "$session_name" 2>/dev/null || {
  169. echo "error|Failed to kill session"
  170. return 1
  171. }
  172. echo "killed|$session_name"
  173. return 0
  174. }
  175. # List all PSM tmux sessions
  176. psm_list_tmux_sessions() {
  177. if ! psm_has_tmux; then
  178. return 0
  179. fi
  180. tmux list-sessions -F "#{session_name}|#{session_created}|#{session_attached}" 2>/dev/null | grep "^psm_" || true
  181. }
  182. # Check if a tmux session exists
  183. # Usage: psm_tmux_session_exists <session_name>
  184. psm_tmux_session_exists() {
  185. local session_name
  186. session_name=$(psm_tmux_safe_name "$1")
  187. tmux has-session -t "$session_name" 2>/dev/null
  188. }
  189. # Get current tmux session name
  190. psm_current_tmux_session() {
  191. if [[ -n "$TMUX" ]]; then
  192. tmux display-message -p "#{session_name}" 2>/dev/null
  193. fi
  194. }
  195. # Generate tmux session name
  196. # Usage: psm_tmux_session_name <alias> <type> <id>
  197. psm_tmux_session_name() {
  198. local alias="$1"
  199. local type="$2"
  200. local id="$3"
  201. psm_tmux_name_from_id "${alias}:${type}-${id}"
  202. }

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.