omc
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.
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
Markdown
[](/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-marketplaceWhat 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
- {
- "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
- "name": "omc",
- "description": "Claude Code native multi-agent orchestration - intelligent model routing across agents and skills",
- "owner": {
- "name": "Yeachan Heo",
- "email": "hurrc04@gmail.com"
- },
- "plugins": [
- {
- "name": "oh-my-claudecode",
- "description": "Claude Code native multi-agent orchestration with intelligent model routing across agents and skills. Zero learning curve. Maximum power.",
- "version": "5.8.6",
- "author": {
- "name": "Yeachan Heo",
- "email": "hurrc04@gmail.com"
- },
- "source": "./",
- "category": "productivity",
- "homepage": "https://github.com/Yeachan-Heo/oh-my-claudecode",
- "tags": [
- "multi-agent",
- "orchestration",
- "delegation",
- "todo-management",
- "team"
- ]
- }
- ],
- "version": "5.8.6"
- }
README.md · README · 718 lines
- 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)
- # oh-my-claudecode
- [](https://www.npmjs.com/package/oh-my-claude-sisyphus)
- [](https://www.npmjs.com/package/oh-my-claude-sisyphus)
- [](https://github.com/Yeachan-Heo/oh-my-claudecode/stargazers)
- [](https://opensource.org/licenses/MIT)
- [](https://github.com/sponsors/Yeachan-Heo)
- [](https://discord.gg/wSyUQYfhAw)
- > **For Codex users:** Check out [oh-my-codex](https://github.com/Yeachan-Heo/oh-my-codex) — the same orchestration experience for OpenAI Codex CLI.
- > **Liked OmC but found it a bit overkill? Try [gajae-code](https://github.com/Yeachan-Heo/gajae-code).**
- > 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.
- **Multi-agent orchestration for Claude Code. Zero learning curve.**
- _Don't learn Claude Code. Just use OMC._
- [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)
- ---
- ## Core Maintainers
- | Role | Name | GitHub |
- | -------------- | ----------- | ---------------------------------------------- |
- | Creator & Lead | Yeachan Heo | [@Yeachan-Heo](https://github.com/Yeachan-Heo) |
- ## Ambassadors
- | Name | GitHub |
- | ---------- | ------------------------------------------------ |
- | Sigrid Jin | [@sigridjineth](https://github.com/sigridjineth) |
- ## Document Specialists
- | Name | GitHub |
- | ------- | -------------------------------------- |
- | devswha | [@devswha](https://github.com/devswha) |
- ## Top Collaborators
- | Name | GitHub | Commits |
- | -------------- | ---------------------------------------------- | ------- |
- | JunghwanNA | [@shaun0927](https://github.com/shaun0927) | 65 |
- | riftzen-bit | [@riftzen-bit](https://github.com/riftzen-bit) | 52 |
- | Seunggwan Song | [@Nathan-Song](https://github.com/Nathan-Song) | 20 |
- | BLUE | [@blue-int](https://github.com/blue-int) | 20 |
- | Junho Yeo | [@junhoyeo](https://github.com/junhoyeo) | 15 |
- ## Quick Start
- **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):
- ```bash
- /plugin marketplace add https://github.com/Yeachan-Heo/oh-my-claudecode
- ```
- Then:
- ```bash
- /plugin install oh-my-claudecode
- ```
- If you prefer the npm CLI/runtime path instead of the marketplace flow:
- ```bash
- 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**
- ```bash
- # 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**
- ```bash
- # 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>`:
- ```text
- /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`:
- ```jsonc
- {
- "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.
- | Feature | Terminal CLI | In-session skill | Notes |
- | ---------------------------------------------- | --------------------------------------------- | ----------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
- | Setup | `omc setup` | `/omc-setup` | Both are real entrypoints. |
- | 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`. |
- | 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. |
- | 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. |
- | 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. |
- | 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. |
- ### VS Code, Agent SDK, and automation scope
- - **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.
- - **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.
- - **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.
- ### Not Sure Where to Start?
- If you're uncertain about requirements, have a vague idea, or want to micromanage the design:
- ```
- /deep-interview "I want to build a task management app"
- ```
- 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.
- ## Team Mode (Recommended)
- Starting in **v4.1.7**, **Team** is the canonical orchestration surface in OMC. The legacy `swarm` keyword/skill has been removed; use `team` directly.
- ```bash
- /team 3:executor "fix all TypeScript errors"
- ```
- 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).
- Team runs as a staged pipeline:
- `team-plan → team-prd → team-exec → team-verify → team-fix (loop)`
- Enable Claude Code native teams in `~/.claude/settings.json`:
- ```json
- {
- "env": {
- "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1"
- }
- }
- ```
- > If teams are disabled, OMC will warn you and fall back to non-team execution where possible.
- ### tmux CLI Workers — Codex, Gemini & Antigravity (v4.4.0+)
- **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:
- ```bash
- omc team 2:codex "review auth module for security issues"
- omc team 2:gemini "redesign UI components for accessibility"
- omc team 2:antigravity "redesign UI components for accessibility"
- omc team 1:claude "implement the payment flow"
- omc team 1:cursor "implement the payment flow"
- omc team status auth-review
- omc team shutdown auth-review
- ```
- 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):
- ```bash
- /ask codex "Review this PR — architecture"
- /ask antigravity "Review this PR — UI components"
- ```
- | Surface | Workers | Best For |
- | ------------------------------- | ----------------------------- | -------------------------------------------- |
- | `omc team N:codex "..."` | N Codex CLI panes | Code review, security analysis, architecture |
- | `omc team N:gemini "..."` | N Gemini CLI panes | UI/UX design, docs, large-context tasks (enterprise/API-key) |
- | `omc team N:antigravity "..."` | N Antigravity (`agy`) panes | UI/UX design, docs, large-context tasks |
- | `omc team N:grok "..."` | N Grok Build CLI panes | Code review, analysis cross-check |
- | `omc team N:cursor "..."` | N Cursor agent panes | Implementation and reviewer-style tasks |
- | `omc team N:claude "..."` | N Claude CLI panes | General tasks via Claude CLI in tmux |
- | `/ask codex` + `/ask antigravity` | Tri-model advisor synthesis | Mixed Codex + Antigravity review in one pass |
- 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.
- Autopilot can prefer Cursor executor workers during team execution via `.claude/omc.jsonc`:
- ```jsonc
- {
- "autopilot": {
- "execution": "team",
- "team": { "agentTypes": ["cursor"] }
- }
- }
- ```
- 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`.
- 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.
- 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.
- > **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.
- ### Updating
- If you installed OMC via npm, upgrade with the published package name:
- ```bash
- npm i -g oh-my-claude-sisyphus@latest
- ```
- > **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.
- If you installed OMC via the Claude Code marketplace/plugin flow, update with:
- ```bash
- # 1. Update the marketplace clone
- /plugin marketplace update omc
- # 2. Re-run setup to refresh configuration
- /omc-setup
- ```
- 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.
- > **Note:** If marketplace auto-update is not enabled, you must manually run `/plugin marketplace update omc` to sync the latest version before running setup.
- If you experience issues after updating, clear the old plugin cache:
- ```bash
- /omc-doctor
- ```
- <h1 align="center">Your Claude Just Have been Steroided.</h1>
- <p align="center">
- <img src="assets/omc-character.jpg" alt="oh-my-claudecode" width="400" />
- </p>
- ---
- ## Why oh-my-claudecode?
- - **Zero configuration required** - Works out of the box with intelligent defaults
- - **Team-first orchestration** - Team is the canonical multi-agent surface
- - **Natural language interface** - No commands to memorize, just describe what you want
- - **Automatic parallelization** - Complex tasks distributed across specialized agents
- - **Persistent execution** - Won't give up until the job is verified complete
- - **Cost optimization** - Smart model routing saves 30-50% on tokens
- - **Learn from experience** - Automatically extracts and reuses problem-solving patterns
- - **Real-time visibility** - HUD statusline shows what's happening under the hood
- ---
- ## Features
- ### Orchestration Modes
- 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)
- | Mode | What it is | Use For |
- | --------------------------- | --------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
- | **Team (recommended)** | Canonical staged pipeline (`team-plan → team-prd → team-exec → team-verify → team-fix`) | Coordinated Claude agents on a shared task list |
- | **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 |
- | **Tri-model advisor (`/ask codex` + `/ask antigravity`)** | Claude synthesizes both advisors' output | Mixed backend+UI work needing both Codex and Antigravity |
- | **Autopilot** | Autonomous execution (single lead agent) | End-to-end feature work with minimal ceremony |
- | **Execute** | Persistent execution with verify/fix loops, from plan to working code | Tasks that must complete fully (no silent partials) |
- | **Verify** | Evidence-based completion checks until tests/build/lint/typecheck goals pass | Quality gates that need repeat diagnose/fix cycles |
- | **Claude Code `/goal`** | Native Claude Code cross-turn goal loop | One measurable session completion condition; not an OMC evidence ledger |
- | **Artifact-only Ultragoal** | Durable goal/checkpoint/evidence artifacts without starting a loop | Handoffs, audits, or unavailable/conflicting loop runtimes |
- ### Goal Workflow Guidance
- 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.
- 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.
- ### Intelligent Orchestration
- - **19 specialized agents** (with tier variants) for architecture, research, design, testing, data analysis
- - **Smart model routing** - Haiku for simple tasks, Opus for complex reasoning
- - **Automatic delegation** - Right agent for the job, every time
- - **[Model × Agent Compatibility Matrix](docs/agents/model-compatibility.md)** - Which model to pair with each agent, with premium/balanced/budget presets
- ### Developer Experience
- - **Prompt triggers** - `ralph`, `ralplan`; Team stays explicit via `/team`
- - **HUD statusline** - Real-time orchestration metrics in your status bar
- - 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.
- - **Skill learning** - Extract reusable patterns from your sessions
- - **Analytics & cost tracking** - Understand token usage across all sessions
- ### Contributing
- 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.
- ### Custom Skills
- Learn once, reuse forever. OMC extracts hard-won debugging knowledge into portable skill files that auto-inject when relevant.
- | | Project Scope | User Scope |
- | --------------- | -------------------------------------------------------- | ----------------- |
- | **Path** | `.omc/skills/` | `~/.omc/skills/` |
- | **Shared with** | Team (commit the skill file to keep it across worktrees) | All your projects |
- | **Priority** | Higher (overrides user) | Lower (fallback) |
- ```yaml
- # .omc/skills/fix-proxy-crash.md
- ---
- name: Fix Proxy Crash
- description: aiohttp proxy crashes on ClientDisconnectedError
- triggers: ["proxy", "aiohttp", "disconnected"]
- source: extracted
- ---
- Wrap handler at server.py:42 in try/except ClientDisconnectedError...
- ```
- **Manage skills:** `/skill list | add | remove | edit | search`
- **Skillify:** `/skillify` extracts reusable patterns with strict quality gates
- **Auto-inject:** Matching skills load into context automatically — no manual recall needed
- 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.
- ### `.omc/` state and git
- 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.
- 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).
- 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.
- [Full feature list →](docs/REFERENCE.md)
- ### Multi-repo workspaces
- 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:
- ```bash
- cd /path/to/parent-dir-with-many-repos
- echo '{"id":"my-workspace"}' > .omc-workspace
- # Sessions inside any sub-repo now share /path/.omc/
- # For parallel ultragoal runs:
- cd repo-A && omc ultragoal create-goals --auto-plan-id --brief "..."
- cd ../repo-B && omc ultragoal create-goals --auto-plan-id --brief "..."
- ```
- 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.
- ---
- ## In-session shortcuts
- 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.
- | In-session form | Kind | Effect | Example |
- | -------------------------- | ---------------------- | -------------------------------------- | ---------------------------------------------- |
- | `/team` | Slash skill | Canonical Team orchestration | `/team 3:executor "fix all TypeScript errors"` |
- | `/autopilot` / `autopilot` | Skill / prompt trigger | Full autonomous execution | `/autopilot "build a todo app"` |
- | `/execute` | Slash skill | Carry an approved task through to verified code | `/execute "refactor auth"` |
- | `/ralph` / `ralph` | Skill / prompt trigger | Persistence mode | `/ralph "refactor auth"` |
- | `/ralplan` / `ralplan` | Skill / prompt trigger | Iterative planning consensus | `/ralplan "plan this feature"` |
- | `/deep-interview` | Slash skill | Socratic requirements clarification | `/deep-interview "vague idea"` |
- | `deepsearch` | Prompt trigger | Codebase-focused search routing | `deepsearch for auth middleware` |
- | `ultrathink` | Prompt trigger | Deep reasoning mode | `ultrathink about this architecture` |
- | `cancelomc`, `stopomc` | Prompt trigger | Stop active OMC modes | `stopomc` |
- **Notes:**
- - **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.
- - `swarm` compatibility alias has been removed; migrate existing prompts to `/team` syntax.
- - `plan this` / `plan the` keyword triggers were removed; use `ralplan` or explicit `/oh-my-claudecode:plan`.
- ## Utilities
- ### Provider Advisor (`omc ask` / `/ask`)
- Run local provider CLIs and save a markdown artifact under `.omc/artifacts/ask/`.
- ```bash
- # Terminal CLI
- omc ask claude "review this migration plan"
- omc ask codex --prompt "identify architecture risks"
- omc ask gemini --prompt "propose UI polish ideas"
- omc ask antigravity --prompt "propose UI polish ideas"
- omc ask grok --prompt "cross-check this code review"
- omc ask cursor --prompt "apply this implementation plan"
- omc ask muse --agent-prompt critic --prompt "review this plan"
- omc ask claude --agent-prompt executor --prompt "draft implementation steps"
- # Inside a Claude Code / OMC session
- /ask claude "review this migration plan"
- /ask codex "identify architecture risks"
- /ask antigravity "propose UI polish ideas"
- /ask cursor "apply this implementation plan"
- /ask muse --agent-prompt critic "review this plan"
- ```
- Canonical env vars:
- - `OMC_ASK_ADVISOR_SCRIPT`
- - `OMC_ASK_ORIGINAL_TASK`
- Phase-1 aliases `OMX_ASK_ADVISOR_SCRIPT` and `OMX_ASK_ORIGINAL_TASK` are accepted with deprecation warnings.
- ### Autoresearch (stateful skill)
- `omc autoresearch` is now a **hard-deprecated shim**. The authoritative workflow is:
- ```bash
- /deep-interview --autoresearch improve startup performance
- /oh-my-claudecode:autoresearch
- ```
- - `deep-interview --autoresearch` generates/sets up the mission and evaluator
- - `autoresearch` runs the bounded, single-mission stateful loop
- - each iteration records evaluation JSON plus markdown decision logs
- - non-passing iterations continue
- - strict stopping is controlled by an explicit max-runtime ceiling
- ### Rate Limit Wait
- Auto-resume Claude Code sessions when rate limits reset.
- ```bash
- omc wait # Check status, get guidance
- omc wait --start # Enable auto-resume daemon
- omc wait --stop # Disable daemon
- ```
- **Requires:** tmux (for session detection)
- ### Monitoring & Observability
- Use the HUD for live observability and the current session/replay artifacts for post-session inspection:
- - HUD preset: `/oh-my-claudecode:hud setup` then use a supported preset such as `"omcHud": { "preset": "focused" }`
- - Session summaries: `.omc/sessions/*.json`
- - Replay logs: `.omc/state/agent-replay-*.jsonl`
- - Live HUD rendering: `omc hud`
- - 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.
- ### Jev Judgment Configuration
- **Jev** brings calibrated decision-making to OMC's orchestration. Enable it with environment variables:
- ```bash
- export TYPESAFE_API_KEY="sk-..." # Jev API key (required)
- export OMC_JEV="all:active" # All judgment points active
- export OMC_JEV_TIMEOUT_MS="2000" # Per-call timeout (default: 2000ms)
- ```
- **Modes:**
- - `shadow` (default): Jev is queried but heuristics decide; answers logged for analysis
- - `active`: Jev's answer overrides the heuristic; adds latency (bounded by `OMC_JEV_TIMEOUT_MS`)
- - `off`: No Jev queries sent (zero egress)
- 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.
- ### Notification Tags (Telegram/Discord/Slack)
- You can configure who gets tagged when stop callbacks send session summaries.
- ```bash
- # Set/replace tag list
- omc config-stop-callback telegram --enable --token <bot_token> --chat <chat_id> --tag-list "@alice,bob"
- omc config-stop-callback discord --enable --webhook <url> --tag-list "@here,123456789012345678,role:987654321098765432"
- omc config-stop-callback slack --enable --webhook <url> --tag-list "<!here>,<@U1234567890>"
- # Incremental updates
- omc config-stop-callback telegram --add-tag charlie
- omc config-stop-callback discord --remove-tag @here
- omc config-stop-callback discord --clear-tags
- ```
- Tag behavior:
- - Telegram: `alice` becomes `@alice`
- - Discord: supports `@here`, `@everyone`, numeric user IDs, and `role:<id>`
- - Slack: supports `<@MEMBER_ID>`, `<!channel>`, `<!here>`, `<!everyone>`, `<!subteam^GROUP_ID>`
- - `file` callbacks ignore tag options
- ### OpenClaw Integration
- Forward Claude Code session events to an [OpenClaw](https://openclaw.ai/) gateway to enable automated responses and workflows via your OpenClaw agent.
- **Quick setup (recommended):**
- ```bash
- /oh-my-claudecode:configure-notifications
- # → When prompted, type "openclaw" → choose "OpenClaw Gateway"
- ```
- **Manual setup:** create `~/.claude/omc_config.openclaw.json`:
- ```json
- {
- "enabled": true,
- "gateways": {
- "my-gateway": {
- "url": "https://your-gateway.example.com/wake",
- "headers": { "Authorization": "Bearer YOUR_TOKEN" },
- "method": "POST",
- "timeout": 10000
- }
- },
- "hooks": {
- "session-start": {
- "gateway": "my-gateway",
- "instruction": "Session started for {{projectName}}",
- "enabled": true
- },
- "stop": {
- "gateway": "my-gateway",
- "instruction": "Session stopping for {{projectName}}",
- "enabled": true
- }
- }
- }
- ```
- **Environment variables:**
- | Variable | Description |
- | ------------------------------------------ | ------------------------- |
- | `OMC_OPENCLAW=1` | Enable OpenClaw |
- | `OMC_OPENCLAW_DEBUG=1` | Enable debug logging |
- | `OMC_OPENCLAW_CONFIG=/path/to/config.json` | Override config file path |
- **Supported hook events (6 active in bridge.ts):**
- | Event | Trigger | Key template variables |
- | ------------------- | --------------------------------------- | ----------------------------------------------------- |
- | `session-start` | Session begins | `{{sessionId}}`, `{{projectName}}`, `{{projectPath}}` |
- | `stop` | Claude response completes | `{{sessionId}}`, `{{projectName}}` |
- | `keyword-detector` | Every prompt submission | `{{prompt}}`, `{{sessionId}}` |
- | `ask-user-question` | Claude requests user input | `{{question}}`, `{{sessionId}}` |
- | `pre-tool-use` | Before tool invocation (high frequency) | `{{toolName}}`, `{{sessionId}}` |
- | `post-tool-use` | After tool invocation (high frequency) | `{{toolName}}`, `{{sessionId}}` |
- **Reply channel environment variables:**
- | Variable | Description |
- | ------------------------ | ------------------------------ |
- | `OPENCLAW_REPLY_CHANNEL` | Reply channel (e.g. `discord`) |
- | `OPENCLAW_REPLY_TARGET` | Channel ID |
- | `OPENCLAW_REPLY_THREAD` | Thread ID |
- See `scripts/openclaw-gateway-demo.mjs` for a reference gateway that relays OpenClaw payloads to a custom HTTPS automation endpoint.
- ---
- ## Documentation
- - **[Full Reference](docs/REFERENCE.md)** - Complete feature documentation
- - **[CLI Reference](https://yeachan-heo.github.io/oh-my-claudecode-website/docs/#cli-reference)** - All `omc` commands, flags, and tools
- - **[Notifications Guide](https://yeachan-heo.github.io/oh-my-claudecode-website/docs/#notifications)** - Discord, Telegram, Slack, and webhook setup
- - **[Recommended Workflows](https://yeachan-heo.github.io/oh-my-claudecode-website/docs/#workflows)** - Battle-tested skill chains for common tasks
- - **[Release Notes](https://yeachan-heo.github.io/oh-my-claudecode-website/docs/#release-notes)** - What's new in each version
- - **[Website](https://yeachan-heo.github.io/oh-my-claudecode-website)** - Interactive guides and examples
- - **[Migration Guide](docs/MIGRATION.md)** - Upgrade from v2.x
- - **[Architecture](docs/ARCHITECTURE.md)** - How it works under the hood
- - **[Performance Monitoring](docs/PERFORMANCE-MONITORING.md)** - Agent tracking, debugging, and optimization
- - **[Model × Agent Compatibility Matrix](docs/agents/model-compatibility.md)** - Which model to pair with each agent (premium / balanced / budget presets)
- - **[Security Guide](SECURITY.md)** - Enterprise deployment and hardening
- ---
- ## Requirements
- - [Claude Code](https://docs.anthropic.com/claude-code) CLI
- - Claude Max/Pro subscription OR Anthropic API key
- ### Platform & tmux
- OMC features like `omc team` and rate-limit detection require **tmux**:
- | Platform | tmux provider | Install |
- | -------------- | ----------------------------------------------------- | ----------------------- |
- | macOS | [tmux](https://github.com/tmux/tmux) | `brew install tmux` |
- | Ubuntu/Debian | tmux | `sudo apt install tmux` |
- | Fedora | tmux | `sudo dnf install tmux` |
- | Arch | tmux | `sudo pacman -S tmux` |
- | Windows | [psmux](https://github.com/marlocarlo/psmux) (native) | `winget install psmux` |
- | Windows (WSL2) | tmux (inside WSL) | `sudo apt install tmux` |
- > **Windows users:** [psmux](https://github.com/marlocarlo/psmux) provides a native `tmux` binary for Windows with 76 tmux-compatible commands. No WSL required.
- >
- > **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.
- ### Optional: Multi-AI Orchestration
- OMC can optionally orchestrate external AI providers for cross-validation and design consistency. These are **not required** — OMC works fully without them.
- | Provider | Install | What it enables |
- | ----------------------------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------------------- |
- | [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 |
- | [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 |
- | [Codex CLI](https://github.com/openai/codex) | `npm install -g @openai/codex` | Architecture validation, code review cross-check |
- | [Grok Build](https://build.grok.com) | Download from build.grok.com (`grok` at `~/.grok/bin/grok`) | Code review, analysis cross-check |
- > **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.
- **Cost:** 3 Pro plans (Claude + Antigravity/Gemini + ChatGPT) cover everything for ~$60/month.
- ---
- ## License
- MIT
- ---
- <div align="center">
- **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)
- **Zero learning curve. Maximum power.**
- </div>
- <!-- OMC:FEATURED-CONTRIBUTORS:START -->
- ## Featured by OmC Contributors
- Top personal non-fork, non-archived repos from all-time OMC contributors (100+ GitHub stars).
- - [@Yeachan-Heo](https://github.com/Yeachan-Heo) — [oh-my-claudecode](https://github.com/Yeachan-Heo/oh-my-claudecode) (⭐ 40k)
- - [@junhoyeo](https://github.com/junhoyeo) — [tokscale](https://github.com/junhoyeo/tokscale) (⭐ 5.8k)
- - [@psmux](https://github.com/psmux) — [psmux](https://github.com/psmux/psmux) (⭐ 3.8k)
- - [@devswha](https://github.com/devswha) — [ovis](https://github.com/devswha/ovis) (⭐ 1.6k)
- - [@MeroZemory](https://github.com/MeroZemory) — [ida-multi-mcp](https://github.com/MeroZemory/ida-multi-mcp) (⭐ 467)
- - [@GeiserX](https://github.com/GeiserX) — [awesome-spain](https://github.com/GeiserX/awesome-spain) (⭐ 362)
- - [@BowTiedSwan](https://github.com/BowTiedSwan) — [buildflow](https://github.com/BowTiedSwan/buildflow) (⭐ 296)
- - [@J-Pster](https://github.com/J-Pster) — [Psters_AI_Workflow](https://github.com/J-Pster/Psters_AI_Workflow) (⭐ 289)
- - [@alohays](https://github.com/alohays) — [awesome-visual-representation-learning-with-transformers](https://github.com/alohays/awesome-visual-representation-learning-with-transformers) (⭐ 271)
- - [@HaD0Yun](https://github.com/HaD0Yun) — [Doyunha-Gopeak](https://github.com/HaD0Yun/Doyunha-Gopeak) (⭐ 270)
- - [@changeroa](https://github.com/changeroa) — [StyleGallery](https://github.com/changeroa/StyleGallery) (⭐ 265)
- - [@jcwleo](https://github.com/jcwleo) — [random-network-distillation-pytorch](https://github.com/jcwleo/random-network-distillation-pytorch) (⭐ 264)
- - [@HwangTaehyun](https://github.com/HwangTaehyun) — [github-repository-contribution-stats](https://github.com/HwangTaehyun/github-repository-contribution-stats) (⭐ 241)
- - [@shaun0927](https://github.com/shaun0927) — [openchrome](https://github.com/shaun0927/openchrome) (⭐ 235)
- - [@emgeee](https://github.com/emgeee) — [mean-tutorial](https://github.com/emgeee/mean-tutorial) (⭐ 199)
- - [@anduinnn](https://github.com/anduinnn) — [HiFiNi-Auto-CheckIn](https://github.com/anduinnn/HiFiNi-Auto-CheckIn) (⭐ 172)
- - [@Znuff](https://github.com/Znuff) — [consolas-powerline](https://github.com/Znuff/consolas-powerline) (⭐ 146)
- <!-- OMC:FEATURED-CONTRIBUTORS:END -->
- ## Star History
- [](https://www.star-history.com/#Yeachan-Heo/oh-my-claudecode&type=date&legend=top-left)
- ## 💖 Support This Project
- If Oh-My-ClaudeCode helps your workflow, consider sponsoring:
- [](https://github.com/sponsors/Yeachan-Heo)
- ### Why sponsor?
- - Keep development active
- - Priority support for sponsors
- - Influence roadmap & features
- - Help maintain free & open source
- ### Other ways to help
- - ⭐ Star the repo
- - 🐛 Report bugs
- - 💡 Suggest features
- - 📝 Contribute code
- ## GEO visibility benchmark
- OmC includes a [`geobench`](https://github.com/NomaDamas/geobench) product spec for measuring LLM hit rate, MRR, share of voice, and citations.
- - Spec: [`geobench/oh-my-claudecode.yaml`](geobench/oh-my-claudecode.yaml)
- - Runbook: [`docs/geobench.md`](docs/geobench.md)
hooks/jev-compaction.mjs · Bundled script · 1,506 lines · 1 finding marked
- /* global crypto, TextEncoder */
- /**
- * Jev compaction: a Claude Code hooks module ("mod") for the judgment point `compaction`.
- *
- * Opt-in by name only. `all` and `all:active` never enable this point: it runs only when OMC_JEV
- * names it (`compaction` for shadow, `compaction:active` for active) and TYPESAFE_API_KEY is set.
- * Without that every handler passes the event on unchanged and the module reads nothing but its
- * configuration: no request, no file, no output (mirror of NAMED_ONLY_POINTS in
- * scripts/jev-resolve.mjs and src/hooks/jev/config.ts).
- *
- * session.compact (auto, /compact, a plugin's request; main loop and subagents). The first message,
- * the last KEEP_LAST messages, every user message and every assistant text stay word for word. Other
- * tool results are kept whole, shortened to SHORT_CHARS characters, or removed together with their
- * call; a removed call stays as a one-line trace (tool, input up to TRACE_INPUT_CHARS, size of the
- * removed result), so the model knows what it already did. Jev scores how much each result will still
- * be needed (the `compaction` score question in src/hooks/jev/points.ts, BATCH results per request,
- * up to MAX_REQUESTS requests in parallel). Results are ranked by score and kept while they fit the
- * target budget (OMC_JEV_COMPACT_TARGET of the characters before). In shadow mode the decision is
- * computed and logged, and the built-in summary runs.
- *
- * Assistant rows are rebuilt from their text, traces and kept calls (thinking and server blocks go, a
- * row left empty is dropped), so the host writes them with a new message.id and `--resume` cannot
- * join them with their rows from before the compaction. The rows of one API message become one
- * message with its results right after it, so the host neither joins a row to an earlier message nor
- * finds a call without its result. Between turns every assistant row is rebuilt; inside an open tool
- * loop the rows of the last assistant message keep their handles, which needs the API form of the
- * conversation ($.session.messages({ as: 'api' })) holding its calls, and no thinking row or server
- * block among them; otherwise the built-in summary runs.
- *
- * The built-in summary (next(e)) also runs when the conversation is too short or its tool results
- * are too small for the removal to matter, while requests are paused after an endpoint failure, when
- * OMC_JEV_MAX_REQUESTS is used up, while the shared breaker is open or the shared request limit is
- * used up, and when Jev fails, answers too little or does not answer in time.
- *
- * turn.complete. With OMC_JEV_COMPACT_AT_PERCENT (off when unset) the module asks the host to compact
- * once the context reaches that share of the compaction window: main loop only, at most once per
- * MIN_TURNS_BETWEEN turns, never during a compaction, never while requests are paused, and only when
- * the removable tool results are worth it (a request that would end in the built-in summary is not
- * made). After a compaction of the main loop (this module's or the built-in summary) it also waits
- * until the context has grown by OWN_MIN_GAIN of the window from the lowest usage since it (from the
- * threshold at most).
- *
- * What goes to the endpoint: the /compact instructions and the last USER_MESSAGES user messages
- * (together USER_CHARS characters), and for each scored result its tool, its input (STATE_INPUT_CHARS)
- * and the result's first STATE_HEAD_CHARS and last STATE_TAIL_CHARS characters, all after secret
- * masking, with every string bounded by OMC_JEV_EXCERPT_CHARS_COMPACTION (default
- * DEFAULT_EXCERPT_CHARS). Results of calls on secret paths (and on OMC_JEV_COMPACT_PRIVATE_PATHS)
- * and results without text are never sent.
- *
- * Shared breaker and request limit (OMC_JEV_BREAKER=1, OMC_JEV_MAX_RPM=<n>): the same files and rules as
- * the script side (scripts/lib/jev-breaker.mjs, see its header), under the same state directory and
- * scope. A hooks module cannot import Node, so the file work goes through $.fs; the rules are mirrors.
- * Before each request the module reads breaker.json (open: no request) and, with a limit, reserves a
- * slot in the UTC minute's rpm file at medium priority (a refused request takes no slot). A request
- * that fails opens the breaker by status alone (429 and 5xx; 401, 402, 403; Retry-After, for a 429
- * without one the retry time in its body), and the third request without a response within a minute
- * opens it too. $.fs can neither append nor delete: a line is added by writing the file whole and
- * reading it back, which can lose a line another process added in between (so the limit can be
- * exceeded when several sessions reserve in the same instant; this module's own file work is done one
- * step after the other), and the per-minute files of old minutes stay (the script side removes them
- * when it writes a new minute). Without these two variables nothing of this is read or written. The
- * module's own pause, its three-failures stop and OMC_JEV_MAX_REQUESTS stay as they were.
- *
- * Quiet: no $.ui.log; a toast only with OMC_JEV_COMPACT_TOAST=1. One JSON file per event goes to the
- * spool directory (<state dir>/compaction-spool, $.fs cannot append); the classic SessionStart hook
- * (scripts/lib/jev-compaction-state.mjs) moves those records to compaction.jsonl next to shadow.jsonl.
- *
- * A hooks module reaches files, the network and the environment only through `$`, may import only
- * plain files of its plugin, and its hooks must be functions declared at the top of the file (the host
- * checks this when it loads the module; `claude plugin validate` runs the same check). The masking is
- * shared (scripts/lib/jev-mask.mjs); the HTTP client, the OMC_JEV parse, boundExcerpts and the
- * question are mirrors, and src/__tests__/jev-compaction-module.test.mjs locks their parity.
- */
- import { maskSecrets } from '../scripts/lib/jev-mask.mjs';
- const POINT = 'compaction';
- // The last messages stay whole: the work in flight.
- const KEEP_LAST = 6;
- // Cap on the host call for the API form of the conversation: a call that never settles must not hold
- // the compaction.
- const HOST_MS = 2000;
- // Up to BATCH * MAX_REQUESTS = 240 results are scored per compaction. A 40-question request took
- // 1.4-2.9 s against the production endpoint; the deadlines leave room for a slow answer and keep the
- // whole decision under TOTAL_MS, after which the built-in summary runs instead.
- const BATCH = 40;
- const MAX_REQUESTS = 6;
- const REQUEST_MS = 6000;
- const TOTAL_MS = 8000;
- // Default share of the characters kept (OMC_JEV_COMPACT_TARGET, 0.1-0.9).
- const DEFAULT_TARGET = 0.5;
- // When removing every tool result would cut less than this share, a module compaction would free too
- // little room, so the built-in summary runs.
- const MIN_REDUCTION = 0.3;
- // The own threshold asks for a compaction only when the removable results are also worth this share
- // of the compaction window (about four characters per token).
- const OWN_MIN_GAIN = 0.1;
- const CHARS_PER_TOKEN = 4;
- const SHORT_CHARS = 300;
- const TRACE_INPUT_CHARS = 200;
- const STATE_INPUT_CHARS = 300;
- const STATE_HEAD_CHARS = 1000;
- const STATE_TAIL_CHARS = 500;
- const USER_CHARS = 4000;
- // Text is cut before masking so a huge result or message costs bounded time; the cut keeps this much more
- // than the part that is used, so a secret that starts inside the used part is still seen whole.
- const MASK_SLACK_CHARS = 20000;
- const USER_MESSAGES = 3;
- // Mirror of POINT_DEFAULT_EXCERPT_CHARS.compaction in src/hooks/jev/config.ts: the longest string the
- // state holds (USER_CHARS), so the default bounds nothing the limits above do not already bound.
- export const DEFAULT_EXCERPT_CHARS = 4000;
- const MIN_TURNS_BETWEEN = 5;
- const WINDOW_REFRESH_TURNS = 20;
- const CONFIG_TTL_MS = 30000;
- // A request batch counts when at least this share of its questions got a score; unanswered
- // questions get UNANSWERED_SCORE ("may be useful" is 2/3).
- const PARTIAL_OK = 0.5;
- const UNANSWERED_SCORE = 0.4;
- const PROBE_MAX_CHARS = 5_000_000;
- // A file or URL named in the last user messages counts as needed when its name has at least this
- // many characters (shorter names match too much text).
- const MENTION_MIN = 5;
- const DEFAULT_ENDPOINT = 'https://api.typesafe.ai/v1/systemone';
- const JEV_MODEL = 'jev-latest';
- // Pause after a failed request, by status only (a response body is read only for the retry time of a
- // 429 without a Retry-After, and only for the shared breaker): Retry-After when the response has it,
- // else these defaults; three requests without a response within a minute pause too.
- // Three failed compactions in a row stop the requests for the rest of the session, like the resolver's
- // per-point breaker.
- const PAUSE_DEFAULT_MS = 60_000;
- const PAUSE_AUTH_MS = 600_000;
- const PAUSE_MAX_MS = 1_800_000;
- const NO_RESPONSE_TO_PAUSE = 3;
- const NO_RESPONSE_WINDOW_MS = 60_000;
- const FAILURES_TO_OPEN = 3;
- // Shared breaker and request limit: mirrors of the constants in scripts/lib/jev-breaker.mjs
- // (src/__tests__/jev-compaction-module.test.mjs locks the parity, with that library on the same files).
- // Seconds a breaker stays open when the response gives no usable Retry-After; a Retry-After above the
- // maximum is capped.
- const BREAKER_SECONDS = { transient: 60, account: 600, noResponse: 60 };
- const BREAKER_MAX_SECONDS = 1800;
- // A recorded no-response time further ahead of the clock than this is a corrupt line or a clock set back.
- const NO_RESPONSE_SKEW_MS = 5000;
- const SAME_OUTAGE_GAP_MS = 15 * 60_000;
- const EXTEND_MIN_MS = 5000;
- // Pause after writing the breaker before it is read back (a concurrent opener may have replaced it).
- const SETTLE_MS = 50;
- const CLOCK_SLACK_MS = 60_000;
- // `compaction` is a medium-priority point: it may use this share of the minute's limit.
- const MEDIUM_SHARE = 0.85;
- const RETRY_BODY_MAX_CHARS = 2000;
- const APPEND_TRIES = 3;
- // One step of file work on the shared state may take this long before the request goes on without it.
- const SHARED_OP_MS = 3000;
- // Mirror of the `compaction` score question in src/hooks/jev/points.ts (criteria low to high).
- export const QUESTION_INSTRUCTIONS =
- "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)? " +
- 'Judge whether further work will use it, not whether it was needed before.';
- export const QUESTION_CRITERIA = [
- '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).',
- 'Probably not needed: background from which further work needs at most a conclusion already written in the conversation.',
- 'May be useful: details that further work may come back to.',
- '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).',
- ];
- // Blocks the host or a hook adds to a user message; they stay in the conversation but are not the
- // user's words, so they are cut from the task sent to Jev.
- 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;
- 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/;
- // Messages that start with one of these are not the user's words either: skill and interruption
- // notices, the session summary, and the notices the Claude desktop app adds as entries of their own
- // (side-session and CI-monitor events, scheduled tasks, messages from another session: the same
- // desktop-app notices scripts/pre-tool-enforcer.mjs skips).
- const NOT_USER_PREFIXES = [
- 'Base directory for this skill:', 'Caveat:', '[Request interrupted', 'This session is being continued from a previous conversation',
- '<side-sessions-event>', '<ci-monitor-event>', '<scheduled-task', '<cross-session-message', 'Another Claude session sent a message:',
- ];
- // Secret paths in the path and command fields of a call (a mention in a prompt or a result does not
- // count): SSH keys, git and gh credentials, Claude Code credentials, AWS credentials, .netrc, .env and
- // .envrc files (.env.example is not a secret).
- 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
- // Fields that name a path or run a command, in any tool (built-in or MCP).
- const PATH_FIELDS = ['file_path', 'notebook_path', 'path', 'command'];
- const TOOL_PATH_FIELDS = { Glob: ['pattern'], Grep: ['glob'] };
- /** Mirror of parseJevEnv(POINT) in scripts/jev-resolve.mjs for a named-only point. */
- export function pointMode(raw, key) {
- const value = String(raw ?? '').trim();
- if (!key || value === 'off') return 'off';
- let listed = false;
- let active = false;
- let off = false;
- for (const entry of value.split(',')) {
- const token = entry.trim();
- if (!token) continue;
- const colon = token.lastIndexOf(':');
- const name = colon === -1 ? token : token.slice(0, colon);
- if (name !== POINT) continue;
- if (colon !== -1 && token.slice(colon + 1).trim().toLowerCase() === 'off') {
- off = true;
- active = false;
- continue;
- }
- off = false;
- listed = true;
- if (colon !== -1 && token.slice(colon + 1) === 'active') active = true;
- }
- if (off || !listed) return 'off';
- return active ? 'active' : 'shadow';
- }
- /** Mirror of boundExcerpts in src/hooks/jev/config.ts. */
- export function boundExcerpts(value, max) {
- if (typeof value === 'string') return value.length > max ? value.slice(0, max) : value;
- if (Array.isArray(value)) return value.map((item) => boundExcerpts(item, max));
- if (value !== null && typeof value === 'object') {
- const out = {};
- for (const [k, v] of Object.entries(value)) out[k] = boundExcerpts(v, max);
- return out;
- }
- return value;
- }
- /** Retry-After in milliseconds (delay seconds, a decimal value rounded up to whole seconds, or an HTTP date), else undefined. */
- export function retryAfterMs(value, now = Date.now()) {
- const text = String(value ?? '').trim();
- if (!text) return undefined;
- if (/^\d+(\.\d+)?$/.test(text)) return Math.ceil(Number(text)) * 1000;
- // The three HTTP-date forms (IMF-fixdate, RFC 850, asctime); any other text is not a Retry-After.
- const httpDate =
- /^[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT$/.test(text) ||
- /^[A-Za-z]{6,9}, \d{2}-[A-Za-z]{3}-\d{2} \d{2}:\d{2}:\d{2} GMT$/.test(text) ||
- /^[A-Za-z]{3} [A-Za-z]{3} [ \d]\d \d{2}:\d{2}:\d{2} \d{4}$/.test(text);
- if (!httpDate) return undefined;
- const at = Date.parse(/GMT$/.test(text) ? text : `${text} GMT`);
- return Number.isFinite(at) ? Math.max(0, at - now) : undefined;
- }
- /** A failed request: {kind, pauseMs?, noResponse?}. Status codes only; bodies are never read. */
- export function classifyFailure(result, now = Date.now()) {
- if (result.timeout) return { kind: 'timeout', noResponse: true };
- if (result.error?.invalid) return { kind: 'invalid_response' };
- const status = result.error && Number.isInteger(result.error.status) ? result.error.status : undefined;
- if (status === undefined) return { kind: 'no_response', noResponse: true };
- const header = retryAfterMs(result.error.retryAfter, now);
- const capped = (ms) => Math.min(Math.max(ms, 1000), PAUSE_MAX_MS);
- if (status === 429 || status >= 500) return { kind: `http_${status}`, pauseMs: capped(header ?? PAUSE_DEFAULT_MS) };
- if (status === 401 || status === 402 || status === 403) return { kind: `http_${status}`, pauseMs: capped(header ?? PAUSE_AUTH_MS) };
- return { kind: `http_${status}` };
- }
- // First `head` and last `tail` characters of the masked text. A long text is masked only where those parts
- // come from (with MASK_SLACK_CHARS more on each side); the omitted count is of the original.
- function maskedHeadTail(text, head, tail) {
- if (text.length <= head + tail + 2 * MASK_SLACK_CHARS) return headTail(maskSecrets(text), head, tail);
- const first = maskSecrets(text.slice(0, head + MASK_SLACK_CHARS)).slice(0, head);
- const last = maskSecrets(text.slice(-(tail + MASK_SLACK_CHARS))).slice(-tail);
- return `${first}\n[... ${text.length - head - tail} chars omitted ...]\n${last}`;
- }
- const oneLine = (text) => String(text ?? '').replace(/\s+/g, ' ').trim();
- const clip = (text, max) => (text.length > max ? text.slice(0, max) : text);
- const headTail = (text, head, tail) =>
- text.length <= head + tail ? text : `${text.slice(0, head)}\n[... ${text.length - head - tail} chars omitted ...]\n${text.slice(-tail)}`;
- const randomId = () => Math.random().toString(36).slice(2, 10) + Math.random().toString(36).slice(2, 6);
- const isoNow = () => new Date().toISOString();
- const slash = (p) => String(p).replace(/\\/g, '/').replace(/\/+$/, '');
- const safeName = (s) => String(s ?? '').replace(/[^A-Za-z0-9_-]/g, '_').slice(0, 80);
- const escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
- function inputJson(input) {
- try { return JSON.stringify(input ?? {}); } catch { return ''; }
- }
- const fraction = (raw, fallback, min, max) => {
- const text = String(raw ?? '').trim();
- const n = Number(text);
- return text !== '' && Number.isFinite(n) && n >= min && n <= max ? n : fallback;
- };
- // Mirror of positiveInt in scripts/jev-resolve.mjs.
- function positiveInt(raw, fallback) {
- if (typeof raw !== 'string' || !/^[1-9]\d*$/.test(raw)) return fallback;
- const parsed = Number(raw);
- return Number.isSafeInteger(parsed) ? parsed : fallback;
- }
- // Session state. A Claude Code process loads the module once per session and calls register once.
- function freshState() {
- return {
- sharedQueue: Promise.resolve(), compacting: 0, pausedUntil: 0, pauseReason: null, failedInRow: 0, noResponseAt: [], requests: 0,
- turnCount: 0, lastAttempt: -Infinity, hostCannot: false, compactWindow: undefined, windowTurn: -Infinity,
- cachedConfig: undefined, cachedAt: -Infinity, growthArmed: false, growthBase: undefined,
- };
- }
- let session = freshState();
- // Configuration from the process environment, with the settings' env as a fallback for a host that did
- // not put it into its environment. $.env.get takes literal names only. Without a state directory
- // nothing is written.
- async function readConfig($) {
- const env = {
- OMC_JEV: await $.env.get('OMC_JEV'),
- TYPESAFE_API_KEY: await $.env.get('TYPESAFE_API_KEY'),
- OMC_JEV_ENDPOINT: await $.env.get('OMC_JEV_ENDPOINT'),
- OMC_JEV_LOG_DIR: await $.env.get('OMC_JEV_LOG_DIR'),
- OMC_JEV_MAX_REQUESTS: await $.env.get('OMC_JEV_MAX_REQUESTS'),
- OMC_JEV_EXCERPT_CHARS_COMPACTION: await $.env.get('OMC_JEV_EXCERPT_CHARS_COMPACTION'),
- OMC_JEV_COMPACT_AT_PERCENT: await $.env.get('OMC_JEV_COMPACT_AT_PERCENT'),
- OMC_JEV_COMPACT_TARGET: await $.env.get('OMC_JEV_COMPACT_TARGET'),
- OMC_JEV_COMPACT_TOAST: await $.env.get('OMC_JEV_COMPACT_TOAST'),
- OMC_JEV_COMPACT_PRIVATE_PATHS: await $.env.get('OMC_JEV_COMPACT_PRIVATE_PATHS'),
- OMC_JEV_BREAKER: await $.env.get('OMC_JEV_BREAKER'),
- OMC_JEV_MAX_RPM: await $.env.get('OMC_JEV_MAX_RPM'),
- OMC_JEV_BREAKER_DIR: await $.env.get('OMC_JEV_BREAKER_DIR'),
- OS: await $.env.get('OS'),
- USERPROFILE: await $.env.get('USERPROFILE'),
- HOME: await $.env.get('HOME'),
- };
- // Read settings to fill activation values (OMC_JEV, TYPESAFE_API_KEY) and shared settings
- // (OMC_JEV_BREAKER, OMC_JEV_MAX_RPM), but only if they're needed. With a deadline to prevent stalls.
- if (env.OMC_JEV === undefined || env.TYPESAFE_API_KEY === undefined) {
- try {
- const result = await withDeadline($, $.settings.read({ key: 'env' }), CONFIG_TTL_MS);
- const fromSettings = result && typeof result === 'object' ? (result.value || result) : result;
- if (fromSettings && typeof fromSettings === 'object') {
- for (const name of Object.keys(env)) if (env[name] === undefined && typeof fromSettings[name] === 'string') env[name] = fromSettings[name];
- }
- } catch { /* no settings: the process environment stands */ }
- }
- // Short-circuit: if mode is 'off' after filling from settings, don't read breaker/rpm settings.
- const mode = pointMode(env.OMC_JEV, env.TYPESAFE_API_KEY);
- if (mode !== 'off' && (env.OMC_JEV_BREAKER === undefined || env.OMC_JEV_MAX_RPM === undefined)) {
- try {
- const result = await withDeadline($, $.settings.read({ key: 'env' }), 1000);
- const fromSettings = result && typeof result === 'object' ? (result.value || result) : result;
- if (fromSettings && typeof fromSettings === 'object') {
- for (const name of Object.keys(env)) if (env[name] === undefined && typeof fromSettings[name] === 'string') env[name] = fromSettings[name];
- }
- } catch { /* no settings: the process environment stands */ }
- }
- // Home for shared-state directory: HOME on POSIX (matching jev-breaker.mjs, which uses os.homedir()),
- // USERPROFILE on Windows. On POSIX, do not use USERPROFILE as a fallback when HOME is unset,
- // because os.homedir() does not use USERPROFILE and the breaker state would be in a different location.
- // Home for private-path expansion: preserve USERPROFILE for Windows compatibility.
- const homeForState = env.OS === 'Windows_NT' ? env.USERPROFILE || env.HOME : env.HOME;
- const homeForPrivatePaths = env.USERPROFILE || env.HOME;
- const stateDir = env.OMC_JEV_LOG_DIR ? slash(env.OMC_JEV_LOG_DIR) : homeForState ? `${slash(homeForState)}/.omc/state/jev` : undefined;
- const privatePaths = String(env.OMC_JEV_COMPACT_PRIVATE_PATHS ?? '')
- .split(',')
- .map((p) => p.trim())
- .filter(Boolean)
- // A leading ~ matches both as written (in a command) and expanded to the home directory.
- .flatMap((p) => (homeForPrivatePaths && /^~(?=$|[\\/])/.test(p) ? [p, slash(homeForPrivatePaths) + p.slice(1)] : [p]))
- .map((p) => slash(p).toLowerCase());
- const endpoint = env.OMC_JEV_ENDPOINT || DEFAULT_ENDPOINT;
- return {
- mode,
- key: env.TYPESAFE_API_KEY,
- endpoint,
- shared: mode === 'off' ? undefined : await sharedSettings(env, endpoint, homeForState),
- spoolDir: stateDir ? `${stateDir}/compaction-spool` : undefined,
- maxRequests: positiveInt(env.OMC_JEV_MAX_REQUESTS, 0),
- excerptChars: positiveInt(env.OMC_JEV_EXCERPT_CHARS_COMPACTION, DEFAULT_EXCERPT_CHARS),
- atPercent: fraction(env.OMC_JEV_COMPACT_AT_PERCENT, undefined, 1, 99),
- target: fraction(env.OMC_JEV_COMPACT_TARGET, DEFAULT_TARGET, 0.1, 0.9),
- toast: String(env.OMC_JEV_COMPACT_TOAST ?? '').trim() === '1',
- privatePaths,
- };
- }
- // --- shared breaker and request limit ----------------------------------------------------------
- // Mirrors of scripts/lib/jev-breaker.mjs (same files, same rules) through $.fs. Every function is
- // fail-open: a file system error never holds a request back and never throws.
- /** Mirror of parseMaxRpm: OMC_JEV_MAX_RPM as a positive integer, else undefined (no limit). */
- export function parseMaxRpm(raw) {
- if (typeof raw !== 'string' || !/^[1-9]\d*$/.test(raw.trim())) return undefined;
- const parsed = Number(raw.trim());
- return Number.isSafeInteger(parsed) ? parsed : undefined;
- }
- /** Mirror of thresholdFor(limit, 'compaction'): a medium-priority point. */
- export function mediumThreshold(limit) {
- return Math.max(1, Math.round(limit * MEDIUM_SHARE));
- }
- // {breaker, maxRpm, dir} for this endpoint and key, or undefined when neither OMC_JEV_BREAKER=1 nor
- // OMC_JEV_MAX_RPM is set. dir is <base>/<scope>, the scope the first 16 hex digits of the SHA-256 of
- // the endpoint, a newline and the key; the key itself is never written.
- async function sharedSettings(env, endpoint, home) {
- const breaker = String(env.OMC_JEV_BREAKER ?? '').trim() === '1';
- const maxRpm = parseMaxRpm(env.OMC_JEV_MAX_RPM);
- if (!env.TYPESAFE_API_KEY || (!breaker && maxRpm === undefined)) return undefined;
- // Asked for but not usable (no home directory, no crypto): nothing is shared and the record says so.
- const unavailable = { unavailable: true, breaker: false, maxRpm: undefined, dir: undefined };
- const base = env.OMC_JEV_BREAKER_DIR ? slash(env.OMC_JEV_BREAKER_DIR) : home ? `${slash(home)}/.omc/state/jev/breaker` : undefined;
- if (!base) return unavailable;
- try {
- const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(`${endpoint}\n${env.TYPESAFE_API_KEY}`));
- const scope = Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('').slice(0, 16);
- return { breaker, maxRpm, dir: `${base}/${scope}` };
- } catch {
- return unavailable;
- }
- }
- // One step of file work on the shared state after the other (this module writes whole files, so two
- // steps at once would lose each other's lines). A step that takes longer than SHARED_OP_MS (or throws)
- // returns `fallback`, but retains its place until the underlying work settles. Queue waiting counts
- // toward the deadline too; a step that expires before starting must not do stale file work later.
- function sharedStep($, work, fallback, ms = SHARED_OP_MS) {
- const deadline = Date.now() + ms;
- let expired = false;
- const pending = session.sharedQueue.then(() => expired || Date.now() >= deadline ? fallback : work());
- session.sharedQueue = pending.then(() => undefined, () => undefined);
- return withDeadline($, pending, ms).then((r) => {
- expired = true;
- return 'value' in r ? r.value : fallback;
- });
- }
- const minuteKey = (now) => new Date(now).toISOString().replace(/[-:T]/g, '').slice(0, 12);
- const pause = ($, ms) => new Promise((resolve) => { try { $.clock.after(ms, () => resolve(undefined)); } catch { resolve(undefined); } });
- async function readText($, path) {
- try { return await $.fs.read(path); } catch { return undefined; }
- }
- // Reads text distinguishing missing file from read error. Returns {missing: true}, {unreadable: true},
- // or {text: ...}. Unreadable errors are fail-open: don't overwrite shared state.
- async function readTextSafe($, path) {
- try {
- return { text: await $.fs.read(path) };
- } catch (err) {
- try {
- const exists = await $.fs.exists(path);
- if (!exists) return { missing: true };
- } catch {
- // Cannot check existence; assume unreadable.
- }
- return { unreadable: true };
- }
- }
- // Adds one line to a file. $.fs cannot append, so the file is written whole and read back; a line
- // another process added between the read and the write is lost, and ours is written again when a
- // concurrent write took it away (at most APPEND_TRIES writes). Returns the text read last.
- // Before appending on retry, check if the line is already present (idempotent retry).
- async function appendLine($, path, line) {
- let text = '';
- for (let attempt = 0; attempt < APPEND_TRIES; attempt++) {
- const current = (await readText($, path)) ?? '';
- // Idempotent: if the line is already present, don't write again.
- if (current.split('\n').includes(line)) return current;
- await $.fs.write(path, `${current === '' || current.endsWith('\n') ? current : `${current}\n`}${line}\n`);
- text = (await readText($, path)) ?? '';
- if (text.split('\n').includes(line)) return text;
- }
- return text;
- }
- // breaker.json as written, whatever its times; undefined when missing or unreadable. A partial text
- // (a write landing) is read again.
- async function readBreakerFile($, shared) {
- const path = `${shared.dir}/breaker.json`;
- for (let attempt = 0; attempt < 4; attempt++) {
- const text = await readText($, path);
- if (text === undefined) {
- // Missing: closed. Present but unreadable (a rename landing): read again shortly.
- let present = false;
- try { present = await $.fs.exists(path); } catch { /* not there, or no check */ }
- if (!present) return undefined;
- if (attempt < 3) await pause($, 3);
- continue;
- }
- try {
- const state = JSON.parse(text);
- return state && typeof state === 'object' ? state : undefined;
- } catch {
- if (attempt < 3) await pause($, 3);
- }
- }
- return undefined;
- }
- // The open breaker {until, reason, since} (epoch ms), or undefined when it is closed, expired,
- // unreadable, corrupt, or OMC_JEV_BREAKER is not set.
- async function readSharedBreaker($, shared, now) {
- if (!shared?.breaker) return undefined;
- try {
- const state = await readBreakerFile($, shared);
- if (!state || !Number.isFinite(state.until) || state.until <= now) return undefined;
- if (state.until > now + BREAKER_MAX_SECONDS * 1000 + CLOCK_SLACK_MS) return undefined;
- const since = Number.isFinite(state.since) ? state.since : now;
- if (since < 0 || since > now + CLOCK_SLACK_MS) return undefined;
- return { until: state.until, reason: String(state.reason ?? ''), since: Math.min(since, now) };
- } catch {
- return undefined;
- }
- }
- // Opens the breaker for `seconds`, or keeps it open at least that long; an open breaker is never
- // shortened. After each write the module pauses SETTLE_MS and reads the file again, and writes the
- // later end again when a concurrent opener replaced it with an earlier one (at most 3 writes).
- // `since` stays the start of the outage while it is extended or opens again within 15 minutes.
- async function openSharedBreaker($, shared, seconds, reason, now) {
- try {
- const until = now + Math.max(1, Math.min(seconds, BREAKER_MAX_SECONDS)) * 1000;
- let since = now;
- const previous = await readBreakerFile($, shared);
- if (
- previous &&
- Number.isFinite(previous.until) &&
- Number.isFinite(previous.since) &&
- previous.since >= 0 &&
- previous.since <= now &&
- now - previous.until < SAME_OUTAGE_GAP_MS
- ) {
- since = previous.since;
- }
- for (let attempt = 0; attempt < 3; attempt++) {
- if (attempt > 0) await pause($, SETTLE_MS);
- const current = await readSharedBreaker($, shared, now);
- if (current && current.until >= until - EXTEND_MIN_MS) return current;
- await $.fs.write(`${shared.dir}/breaker.json`, JSON.stringify({ until, reason, since: current ? Math.min(current.since, since) : since }));
- }
- await pause($, SETTLE_MS);
- return await readSharedBreaker($, shared, now);
- } catch {
- return undefined;
- }
- }
- /** Mirror of retryAfterFromBody: the wait a 429 body states in words ("retry after 30 seconds", "Retry after ~178s"), else undefined. */
- export function retryAfterFromBody(text) {
- if (typeof text !== 'string') return undefined;
- 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));
- return match ? Math.max(1, Math.ceil(Number(match[1]))) : undefined;
- }
- /**
- * Mirror of classifyFailure of the shared breaker: {reason, opens, seconds?} for a failed request
- * {status?, retryAfter?, body?, noResponse?}, or undefined when the failure says nothing about the
- * endpoint (another 4xx, an invalid 2xx body).
- */
- export function sharedFailureClass(failure, now = Date.now()) {
- const status = Number.isInteger(failure?.status) ? failure.status : undefined;
- if (status === undefined) return failure?.noResponse ? { reason: 'no-response', opens: false } : undefined;
- let seconds;
- if (status === 429 || (status >= 500 && status <= 599)) seconds = BREAKER_SECONDS.transient;
- else if (status === 401 || status === 402 || status === 403) seconds = BREAKER_SECONDS.account;
- else return undefined;
- const header = retryAfterMs(failure.retryAfter, now);
- const retry = header !== undefined ? Math.max(1, Math.ceil(header / 1000)) : status === 429 ? retryAfterFromBody(failure.body) : undefined;
- return { reason: `http-${status}`, opens: true, seconds: Math.min(retry ?? seconds, BREAKER_MAX_SECONDS) };
- }
- // Requests without a response within the window, this one included, and the newest time recorded.
- // The window ends at the newest time, not at this clock (concurrent processes sample their clocks
- // before they append).
- async function noteNoResponse($, shared, now) {
- try {
- await appendLine($, `${shared.dir}/noresp-${minuteKey(now)}`, String(now));
- const times = [];
- for (const key of [minuteKey(now - 60_000), minuteKey(now), minuteKey(now + 60_000)]) {
- const text = await readText($, `${shared.dir}/noresp-${key}`);
- if (text === undefined) continue;
- for (const line of text.split('\n')) {
- const time = Number(line);
- if (line && Number.isFinite(time) && time <= now + NO_RESPONSE_SKEW_MS) times.push(time);
- }
- }
- const newest = times.reduce((latest, time) => Math.max(latest, time), now);
- return { count: times.filter((time) => time > newest - NO_RESPONSE_WINDOW_MS).length, newest };
- } catch {
- return { count: 0, newest: now };
- }
- }
- // Records a failed request (a sharedFailureClass result): opens or extends the breaker, or counts a
- // request without a response; the third within a minute opens it for a minute from the newest one.
- async function recordSharedFailureClass($, shared, failure, now) {
- if (!shared?.breaker || !failure) return undefined;
- if (failure.opens) return openSharedBreaker($, shared, failure.seconds, failure.reason, now);
- if (failure.reason === 'no-response') {
- const { count, newest } = await noteNoResponse($, shared, now);
- if (count >= NO_RESPONSE_TO_PAUSE) return openSharedBreaker($, shared, BREAKER_SECONDS.noResponse, 'no-response', newest);
- }
- return undefined;
- }
- // A request that ended without a value (withDeadline's {timeout} or {error}), recorded with the shared
- // breaker, as one step of file work after the other.
- function recordSharedFailure($, cfg, result) {
- if (!cfg.shared?.breaker || result.value) return Promise.resolve();
- return sharedStep($, () => writeSharedFailure($, cfg, result), undefined);
- }
- async function writeSharedFailure($, cfg, result) {
- try {
- // A request that had less than a second because of the compaction's own deadline says nothing about the endpoint.
- if (result.timeout && result.short) return;
- const error = result.error;
- let failure;
- if (result.timeout) failure = { noResponse: true };
- else if (error?.invalid) failure = undefined;
- else if (error && Number.isInteger(error.status)) failure = { status: error.status, retryAfter: error.retryAfter, body: error.body };
- else failure = { noResponse: true };
- const now = Date.now();
- await recordSharedFailureClass($, cfg.shared, sharedFailureClass(failure, now), now);
- } catch { /* the breaker never breaks a compaction */ }
- }
- // Folds a minute file: a line "<token> <threshold>" is granted when fewer than <threshold> lines were
- // granted before it. With `token` the fold stops at that line. Returns {granted, ok} (ok undefined
- // when the token is absent or not given).
- function foldMinute(text, token) {
- let granted = 0;
- for (const line of String(text ?? '').split('\n')) {
- const [lineToken, thresholdText] = line.split(' ');
- if (!lineToken || thresholdText === undefined) continue;
- const ok = granted < Number(thresholdText);
- if (ok) granted += 1;
- if (token !== undefined && lineToken === token) return { granted, ok };
- }
- return { granted, ok: undefined };
- }
- // Reserves one request in the current UTC minute: refused without writing anything when the minute
- // already reached the threshold; otherwise the line is added and the file folded again. ok is true
- // without a limit and whenever the files cannot be used. A read that outlives the decision deadline
- // returns {expired: true} without writing: the caller already gave up, so no request will use the slot.
- async function reserveRequest($, shared, now, deadline) {
- const limit = shared.maxRpm;
- if (limit === undefined) return { ok: true };
- const threshold = mediumThreshold(limit);
- try {
- if (Date.now() >= deadline) return { expired: true };
- const path = `${shared.dir}/rpm-${minuteKey(now)}`;
- const readResult = await readTextSafe($, path);
- if (Date.now() >= deadline) return { expired: true };
- // Fail-open on unreadable: an error reading the RPM file is not grounds to block a request.
- if (readResult.unreadable) return { ok: true };
- const before = foldMinute(readResult.text ?? '');
- if (before.granted >= threshold) return { ok: false, count: before.granted, threshold, limit };
- const token = randomId();
- const { granted, ok } = foldMinute(await appendLine($, path, `${token} ${threshold}`), token);
- if (ok === undefined) return { ok: true };
- return { ok, count: granted, threshold, limit };
- } catch {
- return { ok: true };
- }
- }
- // Admission of one request, right before the HTTP call: reserve the process cap atomically before
- // awaiting shared state, and release it if the breaker or shared limit refuses the request.
- // Returns {skip: {mode: 'circuit-open', breaker}} or {skip: {mode: 'cap', count, threshold, limit}}
- // when the request must not go out, {} otherwise.
- async function admitRequest($, cfg, deadline) {
- if (Date.now() >= deadline) return { skip: { mode: 'deadline' } };
- if (cfg.maxRequests && session.requests >= cfg.maxRequests) return { skip: { mode: 'process-cap' } };
- session.requests++;
- const admission = cfg.shared ? await sharedStep($, () => admitNow($, cfg.shared, deadline), {}, Math.min(SHARED_OP_MS, deadline - Date.now())) : {};
- if (Date.now() >= deadline) {
- session.requests--;
- return { skip: { mode: 'deadline' } };
- }
- if (admission.skip) session.requests--;
- return admission;
- }
- async function admitNow($, shared, deadline) {
- const now = Date.now();
- const open = await readSharedBreaker($, shared, now);
- if (open) return { skip: { mode: 'circuit-open', breaker: open } };
- // Recheck deadline after I/O to avoid writing reservations after the compaction deadline has passed.
- if (Date.now() >= deadline) return { skip: { mode: 'deadline' } };
- const slot = await reserveRequest($, shared, now, deadline);
- if (slot.expired) return { skip: { mode: 'deadline' } };
- if (!slot.ok) return { skip: { mode: 'cap', count: slot.count, threshold: slot.threshold, limit: slot.limit } };
- return {};
- }
- // Check if RPM capacity is available without reserving it (non-reserving peek).
- async function rpmCapacityAvailable($, shared, point, now) {
- if (!shared?.maxRpm) return true; // No limit.
- try {
- const threshold = mediumThreshold(shared.maxRpm);
- const path = `${shared.dir}/rpm-${minuteKey(now)}`;
- const before = foldMinute(await readText($, path));
- return before.granted < threshold;
- } catch {
- return true; // File system error: fail-open.
- }
- }
- // No request goes out: paused after a failure, breaker open, OMC_JEV_MAX_REQUESTS used up, the
- // shared breaker open, or RPM capacity exhausted.
- async function blockedReason($, cfg, now) {
- if (session.failedInRow >= FAILURES_TO_OPEN) return 'circuit_open';
- if (now < session.pausedUntil) return 'paused';
- if (cfg.maxRequests && session.requests >= cfg.maxRequests) return 'cap';
- // Bounded like admission: a stalled shared volume falls back to "not open" after SHARED_OP_MS.
- if (cfg.shared && (await sharedStep($, () => readSharedBreaker($, cfg.shared, now), undefined))) return 'breaker_open';
- // The capacity peek is bounded the same way and fails open. Skip the peek when RPM is not enabled.
- if (cfg.shared?.maxRpm && !(await sharedStep($, () => rpmCapacityAvailable($, cfg.shared, 'compaction', now), true))) return 'rpm';
- return undefined;
- }
- // The input of a call in a few words: the field that says what the call did, else its JSON. It stays
- // in the conversation only (the call was there already); what goes to Jev is masked separately.
- function inputSummary(tool, input) {
- const i = input && typeof input === 'object' ? input : {};
- const pick = (...keys) => keys.map((k) => (typeof i[k] === 'string' ? i[k] : undefined)).filter(Boolean).join(' ');
- let text = '';
- if (tool === 'Bash' || tool === 'PowerShell' || tool === 'Monitor') text = pick('command');
- else if (tool === 'Read' || tool === 'Write' || tool === 'Edit' || tool === 'MultiEdit' || tool === 'NotebookEdit') text = pick('file_path', 'notebook_path');
- else if (tool === 'Grep') text = pick('pattern', 'path', 'glob');
- else if (tool === 'Glob') text = pick('pattern', 'path');
- else if (tool === 'WebFetch') text = pick('url');
- else if (tool === 'WebSearch') text = pick('query');
- else if (tool === 'Agent' || tool === 'Task') text = pick('subagent_type', 'description');
- if (!text) text = inputJson(i);
- return oneLine(text);
- }
- function touchesSecretPath(tool, input, privatePaths) {
- if (!input || typeof input !== 'object') return false;
- const values = [];
- for (const f of [...PATH_FIELDS, ...(TOOL_PATH_FIELDS[tool] || [])]) if (typeof input[f] === 'string') values.push(input[f]);
- if (Array.isArray(input.paths)) for (const p of input.paths) if (typeof p === 'string') values.push(p);
- if (typeof input.url === 'string' && /^file:/i.test(input.url)) values.push(input.url);
- return values.some((v) => {
- if (SECRET_PATH.test(v)) return true;
- const value = slash(v).toLowerCase();
- return privatePaths.some((p) => value.includes(p));
- });
- }
- // A result the host can rebuild from its text alone: anything but an image or another binary record.
- const textOnlyMemo = new WeakMap();
- function textOnlyResult(r) {
- if (r && typeof r === 'object' && textOnlyMemo.has(r)) return textOnlyMemo.get(r);
- const v = textOnlyProbe(r);
- try { textOnlyMemo.set(r, v); } catch { /* not an object */ }
- return v;
- }
- function textOnlyProbe(r) {
- if (r.result === undefined || r.result === null || typeof r.result !== 'object') return true;
- let probe;
- try { probe = JSON.stringify(r.result); } catch { return false; }
- if (probe.length > PROBE_MAX_CHARS) return false;
- return !/"type"\s*:\s*"(?:image|document|file)"|"base64"|"media_type"/.test(probe);
- }
- function messageChars(m) {
- let n = (m.text || '').length;
- for (const u of m.toolUses || []) n += (u.tool || '').length + inputJson(u.input).length;
- for (const r of m.toolResults || []) n += (r.text || '').length;
- return n;
- }
- // The user's own words in a message: '' for tool results, host notices and summaries; host blocks
- // inside a message are cut out.
- function userWords(m) {
- if (m.role !== 'user' || (m.toolResults && m.toolResults.length) || !m.text) return '';
- const text = m.text.replace(HOST_BLOCK, '').trim();
- if (!text || HOST_BLOCK_OPEN.test(text) || NOT_USER_PREFIXES.some((p) => text.startsWith(p))) return '';
- return text;
- }
- // The task for the state: the /compact instructions first, then the last USER_MESSAGES user
- // messages, together USER_CHARS characters.
- function userTask(messages, instructions) {
- let left = USER_CHARS;
- const instr = instructions ? clip(maskSecrets(String(instructions).slice(0, left + MASK_SLACK_CHARS)), left) : undefined;
- if (instr) left -= instr.length;
- const picked = [];
- for (let i = messages.length - 1; i >= 0 && picked.length < USER_MESSAGES && left > 0; i--) {
- const words = userWords(messages[i]);
- if (!words) continue;
- const text = clip(maskSecrets(words.slice(0, left + MASK_SLACK_CHARS)), left);
- picked.unshift(text);
- left -= text.length;
- }
- return { task: picked, instructions: instr };
- }
- // Results the user names: a file (by its name) or a URL the call opened that one of the last user
- // messages or the /compact instructions mention as a whole word. Jev sees only the start and the end
- // of a long result, so a result the user said would be needed later could lose the part they meant.
- // Such a result counts as needed (score 1) and comes first for the budget; it is still cut or traced
- // when even it does not fit.
- function targetsOf(input) {
- const i = input && typeof input === 'object' ? input : {};
- const out = new Set();
- for (const k of ['file_path', 'notebook_path', 'path', 'url']) if (typeof i[k] === 'string') out.add(i[k]);
- 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]);
- const names = new Set();
- for (const t of out) {
- if (/^https?:/i.test(t)) names.add(t.toLowerCase());
- const base = t.replace(/[\\/]+$/, '').split(/[\\/]/).pop().toLowerCase();
- if (base.length >= MENTION_MIN) names.add(base);
- }
- return names;
- }
- function mentions(text, name) {
- return new RegExp(`(?:^|[\\s"'\`(<\\[/\\\\=:])${escapeRegExp(name)}(?=$|[\\s"'\`)>\\],.;:!?])`).test(text);
- }
- function markMentioned(candidates, user) {
- const text = [user.instructions || '', ...user.task].join('\n').toLowerCase();
- let n = 0;
- for (const c of candidates) {
- if (c.secret || !c.textOnly) continue;
- for (const name of targetsOf(c.use.input)) {
- if (mentions(text, name)) { c.score = Math.max(c.score, 1); c.asked = true; n++; break; }
- }
- }
- return n;
- }
- function traceLine(c) {
- const what = !c.textOnly ? 'non-text result (image or file) removed' : `${c.res.isError ? 'error' : 'result'} of ${c.resultChars} chars removed`;
- return `[compacted] ${c.use.tool}(${clip(c.summary, TRACE_INPUT_CHARS)}) - ${what}`;
- }
- function shortText(c) {
- return `${c.res.text.slice(0, SHORT_CHARS)}\n[result shortened at compaction: kept ${SHORT_CHARS} of ${c.resultChars} chars]`;
- }
- // The task list stays: every TaskCreate and TaskUpdate call, the newest TodoWrite call and the newest
- // call of a plan tool (`update_plan`, as in the Claude desktop app) that carries the whole list
- // (`todos`, `items`), and every later call of that tool (a plan tool also takes incremental calls).
- const TASK_STEP = /^(?:TaskCreate|TaskUpdate)$/;
- const TASK_LIST = /^TodoWrite$|(?:^|__)update_plan$/;
- // Candidates: tool results outside the first message and the last KEEP_LAST messages whose call is
- // in an earlier assistant message.
- function findCandidates(messages, privatePaths) {
- const uses = new Map();
- messages.forEach((m, i) => { if (m.role === 'assistant') for (const u of m.toolUses || []) uses.set(u.tool_use_id, { i, u }); });
- const tailStart = Math.max(1, messages.length - KEEP_LAST);
- const out = [];
- for (let i = 1; i < tailStart; i++) {
- const m = messages[i];
- if (m.role !== 'user' || !m.toolResults || !m.toolResults.length) continue;
- for (const r of m.toolResults) {
- const found = uses.get(r.tool_use_id);
- if (!found || found.i >= i) continue;
- const c = {
- id: r.tool_use_id, resIdx: i, useIdx: found.i, use: found.u, res: r,
- summary: inputSummary(found.u.tool, found.u.input),
- inputChars: (found.u.tool || '').length + inputJson(found.u.input).length,
- resultChars: (r.text || '').length,
- secret: touchesSecretPath(found.u.tool, found.u.input, privatePaths),
- textOnly: textOnlyResult(r),
- score: 0, asked: false, answered: false,
- };
- c.trace = traceLine(c);
- c.fullCost = c.inputChars + c.resultChars;
- c.traceCost = c.trace.length + 1; // the newline that joins it to the assistant text
- c.shortCost = c.resultChars > SHORT_CHARS ? c.inputChars + shortText(c).length : c.fullCost;
- c.task = TASK_STEP.test(c.use.tool || '');
- out.push(c);
- }
- }
- const carriesList = (c) => Array.isArray(c.use.input?.todos) || Array.isArray(c.use.input?.items);
- const newestList = new Map();
- for (const c of out) {
- 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);
- }
- for (const c of out) {
- const list = newestList.get(c.use.tool);
- if (list && c.resIdx >= list.resIdx && TASK_LIST.test(c.use.tool || '')) c.task = true;
- }
- return out;
- }
- const removableChars = (candidates) => candidates.reduce((s, c) => s + Math.max(0, c.fullCost - c.traceCost), 0);
- // Rank and fill the budget: highest score first while the upgrade from a trace fits; a result that
- // does not fit whole and scores at least "may be useful" is cut to SHORT_CHARS when that fits; the rest
- // is traced. A result not asked about (secret path, no text, beyond the questions) is traced; a call
- // not longer than its trace and the task list stay whole.
- function allocate(candidates, before, target) {
- const fixed = before - candidates.reduce((s, c) => s + c.fullCost - c.traceCost, 0);
- let avail = Math.floor(before * target) - fixed;
- const ranked = [...candidates].sort((a, b) => b.score - a.score || b.resIdx - a.resIdx);
- for (const c of ranked) {
- const upFull = c.fullCost - c.traceCost;
- const upShort = c.shortCost - c.traceCost;
- if (c.secret || !c.textOnly) c.keep = 'trace';
- else if (upFull <= 0 || c.task) c.keep = 'full';
- else if (!c.asked) c.keep = 'trace';
- else if (upFull <= avail) { c.keep = 'full'; avail -= upFull; }
- else if (c.score >= 0.5 && c.shortCost < c.fullCost && upShort <= avail) { c.keep = 'short'; avail -= Math.max(0, upShort); }
- else c.keep = 'trace';
- }
- }
- // Claude Code writes one transcript row per content block, so one API message is several assistant
- // rows sharing a message.id. On `--resume` the host joins the assistant rows of one message.id from
- // the whole transcript, rows from before the compact boundary included, and repeats every block of
- // them but tool_use (measured on Claude Code 2.1.321: a repeated server_tool_use fails the request
- // with API 400 "server_tool_use ids must be unique per assistant turn", and a call that became a trace
- // comes back without its result). Before a request it joins the rows of one message.id the same way
- // (also across result-only user rows: a streamed tool run puts a result between rows of one message)
- // and then needs every call's result in the next message. A row kept by its handle is written after
- // the boundary with its message.id, one built without a handle gets a new one. So the rows of one API
- // message are rebuilt together: one message with their text, traces and kept calls, the result rows
- // after it (groupsOf, build). Only the last message with calls keeps its rows' handles, when the
- // conversation ends inside its tool loop (the API wants that message to begin with its thinking,
- // which a built message cannot carry); between turns no assistant row keeps its handle
- // (openLoopStart).
- // Rows of one API message: consecutive assistant rows; an assistant row after result-only user rows
- // while a call of the group still has no result (a valid transcript starts a new message only once
- // every call has its result); and, with the API form, groups whose calls belong to one API message (a
- // call whose result came back quickly). A user row with text ends a group, as it ends the host's
- // joining. Returns the group of every row (-1 for user rows).
- function groupsOf(messages, api) {
- const groupOf = new Array(messages.length).fill(-1);
- const parent = [];
- let cur = -1;
- let prevAssistant = false;
- let open = new Set();
- messages.forEach((m, i) => {
- if (m.role === 'assistant') {
- if (cur < 0 || !(prevAssistant || open.size)) { cur = parent.length; parent.push(cur); open = new Set(); }
- groupOf[i] = cur;
- for (const u of m.toolUses || []) open.add(u.tool_use_id);
- prevAssistant = true;
- return;
- }
- prevAssistant = false;
- const results = m.toolResults || [];
- if (m.text || !results.length) { cur = -1; open = new Set(); return; }
- for (const r of results) open.delete(r.tool_use_id);
- });
- const find = (g) => { while (parent[g] !== g) g = parent[g] = parent[parent[g]]; return g; };
- if (Array.isArray(api)) {
- const groupOfUse = new Map();
- 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]); });
- for (const a of api) {
- if (!a || a.role !== 'assistant' || !Array.isArray(a.content)) continue;
- const gs = a.content.filter((b) => b && b.type === 'tool_use' && groupOfUse.has(b.id)).map((b) => find(groupOfUse.get(b.id)));
- // Joined only across result-only user rows (a user row with text ends the host's joining too).
- for (const g of gs.slice(1)) {
- const [x, y] = [find(gs[0]), find(g)].sort((p, q) => p - q);
- if (x !== y && sameRun(messages, groupOf, find, x, y)) parent[y] = x;
- }
- }
- }
- return messages.map((m, i) => (groupOf[i] < 0 ? -1 : find(groupOf[i])));
- }
- // Whether groups x < y stand in one stretch of the conversation with only assistant rows and
- // result-only user rows between them.
- function sameRun(messages, groupOf, find, x, y) {
- const first = groupOf.findIndex((g) => g >= 0 && find(g) === x);
- const last = groupOf.findIndex((g) => g >= 0 && find(g) === y);
- for (let i = first + 1; i < last; i++) {
- const m = messages[i];
- if (m.role === 'user' && (m.text || !(m.toolResults || []).length)) return false;
- }
- return true;
- }
- // The first row that keeps its handle: the first row of the last assistant group when that group has
- // calls (the conversation ends inside that message's tool loop), else messages.length (between turns,
- // after a final answer without calls, every assistant row is rebuilt). User rows after that group do
- // not end the loop: a message typed during the tool turn (queued, written as a separate row) joins the
- // result message in the API, and the API still wants the last assistant message to begin with its
- // thinking.
- function openLoopStart(messages, group) {
- for (let i = messages.length - 1; i >= 0; i--) {
- if (messages[i].role !== 'assistant') continue;
- const g = group[i];
- return messages.some((x, k) => group[k] === g && (x.toolUses || []).length) ? group.indexOf(g) : messages.length;
- }
- return messages.length;
- }
- // The API form of the conversation, or undefined: a list whose every entry has `content` as an array
- // or a string, with at least one assistant message whose content is an array (a host that ignores
- // `as: 'api'` answers the plain messages, which have neither).
- function apiFormOf(value) {
- if (!Array.isArray(value) || !value.length) return undefined;
- if (!value.every((a) => a && (Array.isArray(a.content) || typeof a.content === 'string'))) return undefined;
- return value.some((a) => a.role === 'assistant' && Array.isArray(a.content)) ? value : undefined;
- }
- // Whether every call of the rows that keep their handles (from keepFrom on) stands in the API form.
- function keptCallsIn(messages, keepFrom, api) {
- const ids = new Set();
- 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);
- return messages.every((m, i) => i < keepFrom || m.role !== 'assistant' || (m.toolUses || []).every((u) => ids.has(u.tool_use_id)));
- }
- // A block the API runs itself: server_tool_use, mcp_tool_use and their results
- // (advisor_tool_result, web_search_tool_result, ...).
- const isServerBlock = (b) => Boolean(b) && typeof b.type === 'string' && b.type !== 'tool_use' && b.type !== 'tool_result' && /_tool_(?:use|result)$/.test(b.type);
- // Assistant API messages with a server block, and whether one stands among the rows that keep their
- // handles (from keepFrom on). An API message is placed by its first call's row, else by a text block
- // equal to the text of a row at or after the row of the API message before it (a cursor in order); one
- // placed nowhere takes the row of the next placed message and counts as kept when that row is at or
- // after keepFrom (or, with none following, when any row keeps its handle). Without the API form
- // nothing is counted (count null).
- function serverBlocks(messages, api, keepFrom) {
- if (!api) return { count: null, inTail: false };
- const rowOfUse = new Map();
- 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); });
- const placed = [];
- let cursor = 0;
- for (const a of api) {
- if (!a || a.role !== 'assistant' || !Array.isArray(a.content)) continue;
- let row;
- for (const b of a.content) if (b && b.type === 'tool_use' && rowOfUse.has(b.id)) { row = rowOfUse.get(b.id); break; }
- if (row === undefined) {
- const texts = a.content.filter((b) => b && b.type === 'text' && typeof b.text === 'string' && b.text).map((b) => b.text);
- for (let i = cursor; i < messages.length && texts.length; i++) if (messages[i].role === 'assistant' && texts.includes(messages[i].text)) { row = i; break; }
- }
- if (row !== undefined) cursor = Math.max(cursor, row);
- placed.push({ row, server: a.content.some(isServerBlock) });
- }
- let next;
- for (let k = placed.length - 1; k >= 0; k--) { if (placed[k].row === undefined) placed[k].row = next; else next = placed[k].row; }
- let count = 0;
- let inTail = false;
- for (const p of placed) {
- if (!p.server) continue;
- count++;
- if (p.row === undefined ? keepFrom < messages.length : p.row >= keepFrom) inTail = true;
- }
- return { count, inTail };
- }
- // A user message with tool results kept by its engine handle is written after the compact boundary
- // with its original parent, which points before the boundary, so `--resume` (and every `-p` turn)
- // rebuilt the conversation from before the compaction (measured on Claude Code 2.1.318). Such a
- // message is therefore rebuilt from its own text, unchanged for the model, whenever all its results
- // are text. A message with an image or another non-text result in the last KEEP_LAST messages keeps
- // its handle (counted in kept_handle) and has that limit. Every assistant row before `keepFrom` is
- // rebuilt (text, traces and kept calls; thinking and server blocks dropped, an empty row removed) into
- // the one message of its group (groupsOf), placed at the group's first row with content, so the result
- // rows that follow pair with it and the host gives it a new message.id; from keepFrom on
- // (openLoopStart) the rows keep their handles.
- function build(messages, candidates, keepFrom, group, stats) {
- const byId = new Map();
- for (const c of candidates) byId.set(c.id, c);
- const out = [];
- stats.rebuiltUnchanged = 0;
- stats.keptHandle = 0;
- stats.rebuiltAssistant = 0;
- stats.droppedAssistant = 0;
- stats.joinedRows = 0;
- const merged = new Map();
- for (const [i, m] of messages.entries()) {
- if (m.role === 'assistant' && i < keepFrom) {
- stats.rebuiltAssistant++;
- const traces = [];
- const kept = [];
- for (const u of m.toolUses || []) {
- const c = byId.get(u.tool_use_id);
- if (c && c.keep === 'trace') traces.push(c.trace);
- else kept.push({ tool_use_id: u.tool_use_id, tool: u.tool, input: u.input });
- }
- const text = [m.text || '', ...traces].filter(Boolean).join('\n');
- if (!text && !kept.length) { stats.droppedAssistant++; continue; }
- const at = merged.get(group[i]);
- if (at !== undefined) {
- const t = out[at];
- out[at] = { role: 'assistant', text: [t.text, text].filter(Boolean).join('\n'), toolUses: [...t.toolUses, ...kept] };
- stats.joinedRows++;
- continue;
- }
- merged.set(group[i], out.length);
- out.push({ role: 'assistant', text, toolUses: kept });
- continue;
- }
- if (m.role === 'user' && (m.toolResults || []).length) {
- const changed = m.toolResults.some((r) => byId.has(r.tool_use_id) && byId.get(r.tool_use_id).keep !== 'full');
- if (!changed && !m.toolResults.every(textOnlyResult)) { stats.keptHandle++; out.push(m); continue; }
- const results = [];
- for (const r of m.toolResults) {
- const c = byId.get(r.tool_use_id);
- if (c && c.keep === 'trace') continue;
- if (c && c.keep === 'short') results.push({ tool_use_id: r.tool_use_id, text: shortText(c), isError: Boolean(r.isError) });
- else if (textOnlyResult(r)) results.push({ tool_use_id: r.tool_use_id, text: r.text || '', isError: Boolean(r.isError) });
- else results.push({ tool_use_id: r.tool_use_id, text: '[non-text result (image or file) removed at compaction]', isError: Boolean(r.isError) });
- }
- if (!changed) stats.rebuiltUnchanged++;
- if (!results.length && !m.text) continue;
- out.push({ role: 'user', text: m.text || '', toolUses: [], toolResults: results });
- continue;
- }
- out.push(m);
- }
- return out;
- }
- // The built list may not add results without a call or calls without a result to what the host gave.
- // Calls and results of one id are always kept or removed together, so this guards against message
- // shapes not foreseen here: an API request with an orphaned tool result would fail.
- function pairing(messages) {
- const open = new Set();
- const seen = new Set();
- const orphanResults = new Set();
- for (const m of messages) {
- for (const u of m.toolUses || []) { open.add(u.tool_use_id); seen.add(u.tool_use_id); }
- for (const r of m.toolResults || []) {
- if (!seen.has(r.tool_use_id)) orphanResults.add(r.tool_use_id);
- open.delete(r.tool_use_id);
- }
- }
- return { orphanResults, openCalls: open };
- }
- // Pairing as the host checks it before a request (measured on Claude Code 2.1.321). The host joins
- // consecutive user rows, and joins an assistant row to an earlier assistant message of the same
- // message.id while only result-only user rows stand between them; then every call of assistant
- // message k needs its result in message k + 1, else the host puts "[Tool result missing due to
- // internal error]" in its place and drops the real result. A row a hook built gets a new message.id,
- // so it joins nothing; the rows with the engine's handle since the last user row with text are taken
- // as one message, also across a built assistant row (the host keeps joining by message.id past it).
- // Returns the ids of calls without a result in the next message (`u:<id>`) and of results without a
- // call in the previous one (`r:<id>`).
- function adjacencyBreaks(messages) {
- const msgs = [];
- let run = -1;
- for (const m of messages) {
- if (m.role === 'assistant') {
- const uses = (m.toolUses || []).map((u) => u.tool_use_id);
- if (m.handle && run >= 0) { msgs[run].uses.push(...uses); continue; }
- msgs.push({ role: 'assistant', uses });
- if (m.handle) run = msgs.length - 1;
- continue;
- }
- const results = (m.toolResults || []).map((r) => r.tool_use_id);
- if (m.text || !results.length) run = -1;
- const last = msgs[msgs.length - 1];
- if (last && last.role === 'user') last.results.push(...results);
- else msgs.push({ role: 'user', results });
- }
- const breaks = new Set();
- const seen = new Set();
- msgs.forEach((mm, k) => {
- if (mm.role !== 'assistant') return;
- const uses = mm.uses.filter((id) => !seen.has(id));
- for (const id of uses) seen.add(id);
- const next = msgs[k + 1];
- if (!next) return;
- const got = new Set(next.role === 'user' ? next.results : []);
- for (const id of uses) if (!got.has(id)) breaks.add(`u:${id}`);
- for (const id of got) if (!mm.uses.includes(id)) breaks.add(`r:${id}`);
- });
- return breaks;
- }
- const subset = (x, y) => [...x].every((id) => y.has(id));
- // Every break of the built list (by id) is already a break of the list the host handed over.
- export function pairingOk(original, built) {
- const a = pairing(original);
- const b = pairing(built);
- return subset(b.orphanResults, a.orphanResults) && subset(b.openCalls, a.openCalls) && subset(adjacencyBreaks(built), adjacencyBreaks(original));
- }
- // Resolves {value}, {timeout: true} or {error}; never rejects. $.clock.after is a timer, not the
- // hook's own time (only $.clock.sleep would be), and $.http.fetch time does not count either.
- function withDeadline($, promise, ms) {
- return new Promise((resolve) => {
- let settled = false;
- let timer;
- try {
- timer = $.clock.after(ms, () => { if (!settled) { settled = true; resolve({ timeout: true }); } });
- } catch { /* no timer: the request alone decides */ }
- promise.then(
- (value) => { if (!settled) { settled = true; try { timer?.cancel(); } catch { /* gone */ } resolve({ value }); } },
- (error) => { if (!settled) { settled = true; try { timer?.cancel(); } catch { /* gone */ } resolve({ error }); } },
- );
- });
- }
- async function askJev($, cfg, state, questions) {
- const response = await $.http.fetch(cfg.endpoint, {
- method: 'POST',
- headers: { 'content-type': 'application/json', authorization: `Bearer ${cfg.key}` },
- body: JSON.stringify({ model: JEV_MODEL, state, questions }),
- });
- if (!response.ok) {
- const failure = new Error(`HTTP ${response.status}`);
- failure.status = response.status;
- failure.retryAfter = response.headers?.['retry-after'];
- // Only for the retry time of a 429 without a usable Retry-After, and only for the shared breaker.
- if (cfg.shared?.breaker && response.status === 429 && retryAfterMs(failure.retryAfter) === undefined) {
- failure.body = String(response.text ?? '').slice(0, RETRY_BODY_MAX_CHARS);
- }
- throw failure;
- }
- let body;
- try { body = JSON.parse(response.text); } catch { body = undefined; }
- if (!body || typeof body.answers !== 'object' || body.answers === null || Array.isArray(body.answers)) {
- const invalid = new Error('invalid response: no answers');
- invalid.invalid = true;
- throw invalid;
- }
- return body.answers;
- }
- // Score 0-1 from an answer on the four levels (0-3), else undefined.
- function scoreOf(answer) {
- const s = answer && typeof answer === 'object' ? answer.score : undefined;
- return typeof s === 'number' && Number.isFinite(s) && s >= 0 && s <= QUESTION_CRITERIA.length - 1 ? s / (QUESTION_CRITERIA.length - 1) : undefined;
- }
- async function writeRecord($, cfg, record) {
- if (!cfg.spoolDir) return;
- try {
- await $.fs.write(`${cfg.spoolDir}/${safeName(record.session_id ?? 'unknown')}--${Date.now()}-${randomId()}.json`, JSON.stringify(record));
- } catch { /* the log never breaks a compaction */ }
- }
- function noteFailures(failures, now) {
- for (const f of failures) {
- if (f.pauseMs && now + f.pauseMs > session.pausedUntil) { session.pausedUntil = now + f.pauseMs; session.pauseReason = f.kind; }
- if (f.noResponse) session.noResponseAt.push(now);
- }
- session.noResponseAt = session.noResponseAt.filter((t) => now - t < NO_RESPONSE_WINDOW_MS);
- if (session.noResponseAt.length >= NO_RESPONSE_TO_PAUSE && now + PAUSE_DEFAULT_MS > session.pausedUntil) {
- session.pausedUntil = now + PAUSE_DEFAULT_MS;
- session.pauseReason = 'no_response';
- session.noResponseAt = [];
- }
- }
- // Decides one compaction: {messages} to install or {fallback: reason}. Fills `record`; never calls next.
- async function decide($, e, cfg, record, started) {
- const messages = Array.isArray(e.messages) ? e.messages : [];
- const before = messages.reduce((s, m) => s + messageChars(m), 0);
- record.chars_before = before;
- if (messages.length <= KEEP_LAST + 1) return { fallback: 'too_few_messages' };
- // The rows of one API message are rebuilt together (groupsOf); only the last message of an open tool
- // loop keeps its handles, and then the API form has to hold every call of it: without it a call whose
- // result came back quickly starts a group of its own, and that message would be split.
- const asApi = e.agentId === undefined ? { as: 'api' } : { as: 'api', agentId: e.agentId };
- let api = apiFormOf((await withDeadline($, Promise.resolve().then(() => $.session.messages(asApi)), HOST_MS)).value);
- const group = groupsOf(messages, api);
- const keepFrom = openLoopStart(messages, group);
- if (api && !keptCallsIn(messages, keepFrom, api)) api = undefined;
- record.kept_from = messages.length - keepFrom;
- if (!api && keepFrom < messages.length) return { fallback: 'no_api_form' };
- const server = serverBlocks(messages, api, keepFrom);
- record.server_blocks = server.count;
- if (server.inTail) return { fallback: 'server_block_in_tail' };
- // A kept row with neither text nor calls is thinking (or a server block). On `--resume` the host joins
- // it with its copy from before the boundary, so the last assistant message would carry its signed
- // thinking block twice, which the extended thinking documentation says fails with 400.
- if (messages.some((m, i) => i >= keepFrom && m.role === 'assistant' && m.handle && !m.text && !(m.toolUses || []).length)) return { fallback: 'thinking_in_tail' };
- // Results of the calls that keep their handles stay whole (a built row may not stand among them).
- const candidates = findCandidates(messages, cfg.privatePaths).filter((c) => c.useIdx < keepFrom);
- record.candidates = candidates.length;
- const removable = removableChars(candidates);
- record.max_reduction = before ? Math.round((removable / before) * 1000) / 1000 : 0;
- if (!before || removable / before < MIN_REDUCTION) return { fallback: 'too_few_results' };
- const blocked = await blockedReason($, cfg, Date.now());
- if (blocked) {
- if (blocked === 'paused') Object.assign(record, { paused_until: new Date(session.pausedUntil).toISOString(), pause_reason: session.pauseReason });
- else if (blocked === 'rpm') Object.assign(record, { held: 'rpm' });
- else if (blocked === 'breaker_open') Object.assign(record, { held: 'breaker' });
- else if (blocked === 'cap') Object.assign(record, { held: 'cap' });
- return { fallback: blocked };
- }
- // Newest results first; only text results of calls outside secret paths are asked about.
- const askable = [...candidates].sort((a, b) => b.resIdx - a.resIdx).filter((c) => !c.secret && c.textOnly);
- record.secret_skipped = candidates.filter((c) => c.secret).length;
- record.non_text = candidates.filter((c) => !c.textOnly).length;
- let left = cfg.maxRequests ? cfg.maxRequests - session.requests : MAX_REQUESTS;
- if (left <= 0) {
- Object.assign(record, { asked: 0, requests: 0, held: 'cap' });
- return { fallback: 'cap' };
- }
- let asked = askable.slice(0, BATCH * Math.min(MAX_REQUESTS, left));
- record.asked = asked.length;
- const user = userTask(messages, typeof e.instructions === 'string' && e.instructions.trim() ? e.instructions : undefined);
- const deadline = started + TOTAL_MS;
- const runs = [];
- let held;
- for (let b = 0; b * BATCH < asked.length; b++) {
- const admission = await admitRequest($, cfg, deadline);
- if (admission.skip) { held = admission.skip; break; }
- const batch = asked.slice(b * BATCH, (b + 1) * BATCH);
- const results = {};
- const questions = {};
- batch.forEach((c, k) => {
- c.question = `r${k + 1}`;
- results[c.question] = {
- tool: c.use.tool,
- input: clip(oneLine(maskSecrets(inputJson(c.use.input).slice(0, STATE_INPUT_CHARS * 4 + MASK_SLACK_CHARS))), STATE_INPUT_CHARS),
- result: maskedHeadTail(c.res.text || '', STATE_HEAD_CHARS, STATE_TAIL_CHARS),
- chars: c.resultChars,
- ...(c.res.isError ? { error: true } : {}),
- };
- questions[c.question] = { type: 'score', instructions: QUESTION_INSTRUCTIONS, criteria: QUESTION_CRITERIA };
- });
- const state = boundExcerpts({ task: user.task, ...(user.instructions ? { compact_instructions: user.instructions } : {}), results }, cfg.excerptChars);
- const t0 = Date.now();
- if (t0 >= deadline) { session.requests--; held = { mode: 'deadline' }; break; }
- const timeoutMs = Math.min(REQUEST_MS, deadline - t0);
- runs.push(
- withDeadline($, askJev($, cfg, state, questions), timeoutMs).then(async (r) => {
- // Shared failure bookkeeping may finish later, but cannot extend this decision's budget.
- const recording = recordSharedFailure($, cfg, { ...r, short: timeoutMs < 1000 });
- if (Date.now() < deadline) await withDeadline($, recording, deadline - Date.now());
- return { ...r, batch, ms: Date.now() - t0 };
- }),
- );
- }
- if (held) {
- // A request held back by the shared breaker or limit is no failure of the endpoint. The results it
- // would have scored count as unanswered, as after a failed request: the budget decides about them.
- const unscored = asked.slice(runs.length * BATCH);
- for (const c of unscored) { c.asked = true; c.score = UNANSWERED_SCORE; }
- record.unscored = unscored.length;
- record.requests = runs.length;
- if (held.mode === 'circuit-open') Object.assign(record, { held: 'breaker', breaker_until: new Date(held.breaker.until).toISOString(), breaker_reason: held.breaker.reason });
- else if (held.mode === 'process-cap') record.held = 'cap';
- else if (held.mode === 'deadline') record.held = 'deadline';
- else Object.assign(record, { held: 'rpm', rpm: { count: held.count, threshold: held.threshold, limit: held.limit } });
- if (!runs.length) return { fallback: held.mode === 'circuit-open' ? 'breaker_open' : held.mode === 'process-cap' ? 'cap' : held.mode === 'deadline' ? 'timeout' : 'rpm' };
- }
- record.requests = runs.length;
- const results = await Promise.all(runs);
- record.jev_ms = results.map((r) => r.ms);
- let answered = 0;
- const failures = [];
- for (const r of results) {
- for (const c of r.batch) {
- c.asked = true;
- const s = r.value ? scoreOf(r.value[c.question]) : undefined;
- if (s === undefined) c.score = UNANSWERED_SCORE;
- else { c.score = s; c.answered = true; answered++; }
- }
- if (!r.value) failures.push(classifyFailure(r));
- }
- record.requests_ok = results.filter((r) => r.value).length;
- record.answered = answered;
- if (failures.length) {
- record.failure = failures.map((f) => f.kind).join(',');
- noteFailures(failures, Date.now());
- if (!asked.length || answered / asked.length < PARTIAL_OK) {
- session.failedInRow++;
- // A deadline hold still records the failures of the requests that did go out.
- if (held?.mode === 'deadline') return { fallback: 'timeout' };
- return { fallback: failures.every((f) => f.kind === 'timeout') ? 'timeout' : 'jev_error' };
- }
- }
- session.failedInRow = 0;
- if (held?.mode === 'deadline') return { fallback: 'timeout' };
- record.mentioned = markMentioned(candidates, user);
- allocate(candidates, before, cfg.target);
- const stats = {};
- const built = build(messages, candidates, keepFrom, group, stats);
- if (!pairingOk(messages, built)) return { fallback: 'build_error' };
- const after = built.reduce((s, m) => s + messageChars(m), 0);
- const hist = [0, 0, 0, 0];
- for (const c of asked) if (c.answered) hist[Math.min(3, Math.round(c.score * 3))]++;
- Object.assign(record, {
- messages_after: built.length,
- chars_after: after,
- reduction: before ? Math.round((1 - after / before) * 1000) / 1000 : 0,
- kept_full: candidates.filter((c) => c.keep === 'full').length,
- kept_short: candidates.filter((c) => c.keep === 'short').length,
- traced: candidates.filter((c) => c.keep === 'trace').length,
- rebuilt_unchanged: stats.rebuiltUnchanged,
- kept_handle: stats.keptHandle,
- rebuilt_assistant: stats.rebuiltAssistant,
- dropped_assistant: stats.droppedAssistant,
- joined_rows: stats.joinedRows,
- score_hist: hist,
- unanswered: asked.length - answered,
- });
- return { messages: built, before, after };
- }
- async function compact($, e, next) {
- let cfg;
- try { cfg = await readConfig($); } catch { return next(e); }
- if (cfg.mode === 'off') return next(e);
- // An active point replaces the summary, so a summary computed ahead of time would be wasted; while
- // the breaker is open the summary will run, so the host may compute it ahead.
- if (e.trigger === 'precompute') return cfg.mode === 'active' && !(await blockedReason($, cfg, Date.now())) ? { skip: 'jev-compaction replaces the summary' } : next(e);
- const started = Date.now();
- // Any compaction of the main loop that actually replaced the messages, this module's or the built-in
- // summary, arms the own threshold's growth gate again (ownThreshold). A skip leaves the context as it
- // was, so the gate stays as it was too.
- const armGrowthGate = (out) => {
- if (e.agentId === undefined && !out?.skip) { session.growthArmed = true; session.growthBase = undefined; }
- return out;
- };
- session.compacting++;
- try {
- let sessionId;
- try { sessionId = await $.session.id(); } catch { sessionId = undefined; }
- const record = {
- ts: isoNow(), point: POINT, event: 'compact', session_id: sessionId ?? null, agent_id: e.agentId ?? null,
- trigger: e.trigger, mode: cfg.mode, messages_before: Array.isArray(e.messages) ? e.messages.length : 0,
- chars_before: 0, target: cfg.target,
- ...(cfg.shared?.unavailable ? { shared_unavailable: true } : {}),
- };
- let decision;
- try {
- decision = await decide($, e, cfg, record, started);
- } catch (error) {
- decision = { fallback: 'exception' };
- record.error = clip(oneLine(maskSecrets(String(error?.message ?? error))), 200);
- }
- record.duration_ms = Date.now() - started;
- if (decision.fallback) Object.assign(record, { result: 'fallback', reason: decision.fallback });
- else record.result = cfg.mode === 'active' ? 'jev' : 'shadow';
- // Written before next(e): the classic SessionStart:compact hook can run while the built-in summary
- // is still being installed.
- await writeRecord($, cfg, record);
- if (decision.fallback || cfg.mode !== 'active') return armGrowthGate(await next(e));
- if (cfg.toast) { try { $.ui.toast(`Jev compaction: ${decision.before} -> ${decision.after} chars`); } catch { /* optional */ } }
- return armGrowthGate({ messages: decision.messages });
- } finally {
- session.compacting--;
- }
- }
- async function ownThreshold($, e, next) {
- const result = await next(e);
- try {
- if (e.agentId !== undefined || session.compacting > 0 || session.hostCannot) return result;
- session.turnCount++;
- // While the growth gate is armed every turn reads the usage, not only every MIN_TURNS_BETWEEN turns.
- if (!session.growthArmed && session.turnCount - session.lastAttempt < MIN_TURNS_BETWEEN) return result;
- if (!session.cachedConfig || Date.now() - session.cachedAt > CONFIG_TTL_MS) { session.cachedConfig = await readConfig($); session.cachedAt = Date.now(); }
- // The base of the growth gate is the lowest usage since the compaction: the first reading may still
- // count the request from before it. It is read before the pause check, so a compaction that ran
- // while requests were paused still gets its base. The first reading never asks.
- if (session.growthArmed && session.cachedConfig.mode === 'active' && session.cachedConfig.atPercent !== undefined) {
- const reading = (await $.session.usage())?.context?.tokens;
- if (!Number.isFinite(reading) || reading <= 0) return result;
- const first = session.growthBase === undefined;
- session.growthBase = first ? reading : Math.min(session.growthBase, reading);
- if (first || session.turnCount - session.lastAttempt < MIN_TURNS_BETWEEN) return result;
- }
- const cfg = session.cachedConfig;
- if (cfg.mode !== 'active' || cfg.atPercent === undefined || (await blockedReason($, cfg, Date.now()))) return result;
- const usage = await $.session.usage();
- const tokens = usage?.context?.tokens;
- if (!Number.isFinite(tokens) || tokens <= 0) return result;
- // context.percent counts from the model's window; the threshold counts from the window the host
- // compacts at (rawMaxTokens).
- if (session.compactWindow === undefined || session.turnCount - session.windowTurn >= WINDOW_REFRESH_TURNS) {
- session.windowTurn = session.turnCount;
- try {
- const detail = await $.session.usage({ breakdown: 'summary' });
- const raw = detail?.context?.breakdown?.rawMaxTokens;
- session.compactWindow = Number.isFinite(raw) && raw > 0 ? raw : usage.context.window;
- } catch { session.compactWindow = usage.context.window; }
- }
- const window = session.compactWindow;
- if (!Number.isFinite(window) || window <= 0 || tokens * 100 < cfg.atPercent * window) return result;
- // After a compaction the context has to grow by OWN_MIN_GAIN of the window first, counted from the
- // lowest usage since it and at most from the threshold: a compaction that ends above the threshold
- // would else be asked for again as soon as the turn gap allows (right away after /compact or the
- // host's own compaction), and one that ends just below it after a few thousand tokens.
- if (session.growthBase !== undefined && tokens - Math.min(session.growthBase, (cfg.atPercent * window) / 100) < OWN_MIN_GAIN * window) return result;
- session.growthArmed = false;
- // The tokens include the fixed prefix (system prompt, tools, instructions): ask only when the
- // removable tool results are worth it, so the threshold never forces the built-in summary.
- session.lastAttempt = session.turnCount;
- const messages = await $.session.messages();
- const before = messages.reduce((s, m) => s + messageChars(m), 0);
- const removable = removableChars(findCandidates(messages, cfg.privatePaths));
- if (!before || removable / before < MIN_REDUCTION || removable / CHARS_PER_TOKEN < OWN_MIN_GAIN * window) return result;
- let reason;
- let detailText = '';
- try {
- const done = await $.session.compact();
- if (done && typeof done.skip === 'string') { reason = 'host_skipped'; detailText = done.skip; }
- } catch (error) {
- detailText = String(error?.message ?? error);
- reason = /headless|sdk|-p\b/i.test(detailText) ? 'host_cannot_compact' : /turn|in flight|running/i.test(detailText) ? 'host_turn_running' : 'host_error';
- if (reason === 'host_cannot_compact') session.hostCannot = true;
- }
- if (reason) {
- let sessionId;
- try { sessionId = await $.session.id(); } catch { sessionId = undefined; }
- await writeRecord($, cfg, {
- ts: isoNow(), point: POINT, event: 'own_threshold', session_id: sessionId ?? null, agent_id: null, result: 'rejected',
- reason, tokens, window, at_percent: cfg.atPercent, detail: clip(oneLine(maskSecrets(detailText)), 200),
- });
- }
- } catch { /* the threshold never breaks a turn */ }
- return result;
- }
- /** Registers the handlers; the session state starts fresh. */
- export function register(on) {
- session = freshState();
- on('session.compact', compact);
- on('turn.complete', ownThreshold);
- }
scripts/run-provider-advisor.js · Bundled script · 413 lines · 2 findings marked
- #!/usr/bin/env node
- import { hardenWindowsExeSearch } from './lib/windows-search.mjs';
- import { spawnSync } from 'child_process';
- import { mkdtempSync, rmSync, writeFileSync } from 'fs';
- import { mkdir, writeFile } from 'fs/promises';
- import { tmpdir } from 'os';
- import { join } from 'path';
- import process from 'process';
- import { resolveOmcStateRoot } from './lib/state-root.mjs';
- hardenWindowsExeSearch();
- const PROVIDER_BINARIES = {
- claude: 'claude',
- codex: 'codex',
- gemini: 'gemini',
- antigravity: 'agy',
- grok: 'grok',
- cursor: 'cursor-agent',
- muse: 'muse',
- };
- // muse and grok parse a prompt value that begins with `-` (e.g. the YAML
- // frontmatter `---` that every `--agent-prompt` role file starts with) as an
- // option and abort before calling the model, and grok reserves stdin for ACP
- // JSON-RPC. Both accept `--prompt-file`, so hand them the prompt in a private
- // temp file instead of argv or stdin.
- const PROMPT_FILE_PROVIDERS = new Set(['muse', 'grok']);
- const SHOULD_USE_WINDOWS_SHELL = process.platform === 'win32';
- // Antigravity (`agy`) headless print mode has a known upstream non-TTY bug
- // (google-antigravity/antigravity-cli#76) that, beyond the empty-exit-0 case,
- // can hang indefinitely — and agy's own `--print-timeout` flag is non-functional.
- // Bound the subprocess ourselves so a hang fails cleanly instead of blocking the
- // whole `omc ask` / `/ccg` flow forever. Generous so it never trips a real answer.
- // The kill MUST be SIGKILL: spawnSync does not return until the child exits, so a
- // catchable SIGTERM would let a signal-trapping agy hang past the timeout.
- const ANTIGRAVITY_TIMEOUT_DEFAULT_MS = 300000;
- const ANTIGRAVITY_TIMEOUT_KILL_SIGNAL = 'SIGKILL';
- const ANTIGRAVITY_TIMEOUT_MS = (() => {
- const raw = process.env.OMC_ANTIGRAVITY_TIMEOUT_MS;
- if (raw === undefined || raw === '') {
- return ANTIGRAVITY_TIMEOUT_DEFAULT_MS;
- }
- const parsed = Number(raw);
- // Require a finite, integer, >=1000ms value; clamp to <=1h. Otherwise warn and
- // fall back to the default so a bad override can't disable or distort the bound.
- if (!Number.isFinite(parsed) || !Number.isInteger(parsed) || parsed < 1000) {
- console.error(`[ask-antigravity] Ignoring invalid OMC_ANTIGRAVITY_TIMEOUT_MS="${raw}" (need an integer >= 1000); using ${ANTIGRAVITY_TIMEOUT_DEFAULT_MS}ms.`);
- return ANTIGRAVITY_TIMEOUT_DEFAULT_MS;
- }
- return Math.min(parsed, 3600000);
- })();
- /**
- * Build CLI args for a given provider.
- * - claude: `claude -p <prompt>` (or `claude -p` reading the prompt from stdin)
- * - codex: `codex exec --dangerously-bypass-approvals-and-sandbox <prompt>`
- Note: Starts a coding agent with its permission prompts off
- Line 58 on GitHub
- * - gemini: `gemini -p <prompt> --yolo`
- Note: Starts a coding agent with its permission prompts off
- Line 59 on GitHub
- * - antigravity: `agy --dangerously-skip-permissions -p <prompt>` (Antigravity CLI;
- * `-p` takes the prompt as its value and cannot read it from stdin, so the
- * prompt is always passed as an arg with approval flags first)
- * - grok: `grok --prompt-file <file> --always-approve` (single-turn headless
- * mode; grok's stdin is reserved for ACP JSON-RPC, never the prompt)
- * - cursor: `cursor-agent --print --force --trust --sandbox disabled <prompt>`
- * - muse: `muse exec --prompt-file <file> --approval-mode never --user-input-auto-resolve`
- * (headless; preserves Muse's configured sandbox behavior)
- */
- function buildProviderArgs(provider, prompt, { pipePromptViaStdin = false, promptFile } = {}) {
- if (provider === 'codex') {
- return ['exec', '--dangerously-bypass-approvals-and-sandbox', pipePromptViaStdin ? '-' : prompt];
- }
- if (provider === 'gemini') {
- return pipePromptViaStdin ? ['--yolo'] : ['-p', prompt, '--yolo'];
- }
- if (provider === 'antigravity') {
- // Antigravity (`agy`): `-p`/`--print` takes the prompt as its VALUE (next
- // token), not as a boolean, and it does NOT read the prompt from stdin
- // (`agy -p` with no value errors "flag needs an argument"). So always pass
- // the prompt as the `-p` value with approval flags first.
- // Verified on agy 1.0.10.
- return ['--dangerously-skip-permissions', '-p', prompt];
- }
- if (provider === 'grok') {
- // Grok's stdin is for ACP JSON-RPC, not the prompt, and `-p <prompt>` rejects
- // a dash-leading prompt, so the prompt always arrives via --prompt-file.
- return ['--prompt-file', promptFile, '--always-approve'];
- }
- if (provider === 'muse') {
- return ['exec', '--prompt-file', promptFile, '--approval-mode', 'never', '--user-input-auto-resolve'];
- }
- if (provider === 'cursor') {
- // Cursor Agent's print mode takes the prompt as a positional arg. Keep stdin
- // closed so it cannot interpret advisor prompt bytes as interactive input.
- return ['--print', '--force', '--trust', '--sandbox', 'disabled', prompt];
- }
- // claude: `claude -p` reads the prompt from stdin when no prompt arg is given.
- return pipePromptViaStdin ? ['-p'] : ['-p', prompt];
- }
- function shouldPipePromptViaStdin(provider, prompt) {
- if (provider === 'codex' || provider === 'gemini') {
- if (typeof prompt === 'string' && (prompt.includes('\n') || prompt.length > 500)) {
- return true;
- }
- return SHOULD_USE_WINDOWS_SHELL;
- }
- // antigravity (`agy`): `-p` requires its prompt as an arg value and errors if
- // the prompt is piped via stdin, so it never uses the stdin pipe path. Long /
- // multiline prompts are safe as a single argv value (spawn without a shell).
- // #3221: long/multiline/frontmatter prompts must not be passed to Claude as a
- // raw argv value. Claude's CLI parses a leading `-`/`--`/`---` (YAML
- // frontmatter) token as an option and either errors out or drops the prompt.
- // Route those over stdin (`claude -p` reads the prompt from stdin). Short,
- // single-line, non-option prompts keep the existing `-p <prompt>` behavior.
- if (provider === 'claude') {
- if (typeof prompt !== 'string') {
- return false;
- }
- return prompt.includes('\n') || prompt.length > 500 || /^\s*-/.test(prompt);
- }
- // grok and muse (prompt file), cursor-agent (interactive stdin), and any other
- // provider never pipe the prompt.
- return false;
- }
- const ASK_ORIGINAL_TASK_ENV = 'OMC_ASK_ORIGINAL_TASK';
- const ASK_ORIGINAL_TASK_ENV_ALIAS = 'OMX_ASK_ORIGINAL_TASK';
- function usage() {
- console.error('Usage: omc ask <claude|codex|gemini|antigravity|grok|cursor|muse> "<prompt>"');
- console.error('Legacy direct usage: node scripts/run-provider-advisor.js <claude|codex|gemini|antigravity|grok|cursor|muse> <prompt...>');
- console.error(' or: node scripts/run-provider-advisor.js claude --print "<prompt>"');
- console.error(' or: node scripts/run-provider-advisor.js gemini --prompt "<prompt>"');
- }
- function slugify(value) {
- return value
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, '-')
- .replace(/^-+|-+$/g, '')
- .slice(0, 60) || 'task';
- }
- function timestampToken(date = new Date()) {
- return date.toISOString().replace(/[:.]/g, '-');
- }
- function parseArgs(argv) {
- const [providerRaw, ...rest] = argv;
- const provider = (providerRaw || '').toLowerCase();
- if (!provider || !(provider in PROVIDER_BINARIES)) {
- usage();
- process.exit(1);
- }
- if (rest.length === 0) {
- usage();
- process.exit(1);
- }
- if (rest[0] === '-p' || rest[0] === '--print' || rest[0] === '--prompt') {
- const prompt = rest.slice(1).join(' ').trim();
- if (!prompt) {
- usage();
- process.exit(1);
- }
- return { provider, prompt };
- }
- return { provider, prompt: rest.join(' ').trim() };
- }
- // Strip Claude session markers so provider advisors do not detect or inherit the active Claude Code session.
- const CLAUDE_SESSION_STRIPPED_ENV_VARS = new Set([
- 'CLAUDECODE',
- 'CLAUDE_SESSION_ID',
- 'CLAUDECODE_SESSION_ID',
- 'CLAUDE_CODE_ENTRYPOINT',
- ]);
- const CODEX_STRIPPED_ENV_VARS = new Set(['RUST_LOG', 'RUST_BACKTRACE', 'RUST_LIB_BACKTRACE']);
- function buildProviderEnv(provider, env = process.env) {
- const strippedEnvVars = provider === 'codex'
- ? new Set([...CLAUDE_SESSION_STRIPPED_ENV_VARS, ...CODEX_STRIPPED_ENV_VARS])
- : CLAUDE_SESSION_STRIPPED_ENV_VARS;
- return Object.fromEntries(
- Object.entries(env).filter(([key]) => !strippedEnvVars.has(key)),
- );
- }
- // Antigravity (`agy`) headless print mode requires the prompt as an argv value
- // (it cannot read the prompt from stdin). To avoid cmd.exe parsing issues on Windows,
- // spawn agy without a shell (shell: false) — agy is a real executable and does not
- // need shell preprocessing. This was fixed in agy 1.0.15/1.1.1 (closed upstream #76).
- function guardProviderPlatform(provider) {
- // No platform-specific blocks; all providers are supported.
- // The Windows spawn path uses shell: false for antigravity to pass the prompt safely.
- }
- function ensureBinary(provider, binary) {
- const probe = spawnSync(binary, ['--version'], {
- stdio: 'ignore',
- encoding: 'utf8',
- env: buildProviderEnv(provider),
- shell: SHOULD_USE_WINDOWS_SHELL,
- });
- const isMissingOnWindowsShell = SHOULD_USE_WINDOWS_SHELL
- && probe.status !== 0
- && (() => {
- const whereResult = spawnSync('where', [binary], {
- encoding: 'utf8',
- env: buildProviderEnv(provider),
- });
- return whereResult.status !== 0 || !whereResult.stdout?.trim();
- })();
- if ((probe.error && probe.error.code === 'ENOENT') || isMissingOnWindowsShell) {
- const verify = `${binary} --version`;
- console.error(`[ask-${binary}] Missing required local CLI binary: ${binary}`);
- console.error(`[ask-${binary}] Install/configure ${binary} CLI, then verify with: ${verify}`);
- process.exit(1);
- }
- }
- function buildSummary(exitCode, output) {
- if (exitCode === 0) {
- return 'Provider completed successfully. Review the raw output for details.';
- }
- const firstLine = output
- .split('\n')
- .map((line) => line.trim())
- .find(Boolean);
- return firstLine
- ? `Provider command failed (exit ${exitCode}): ${firstLine}`
- : `Provider command failed with exit code ${exitCode}.`;
- }
- function buildActionItems(exitCode) {
- if (exitCode === 0) {
- return [
- 'Review the response and extract decisions you want to apply.',
- 'Capture follow-up implementation tasks if needed.',
- ];
- }
- return [
- 'Inspect the raw output error details.',
- 'Fix CLI/auth/environment issues and rerun the command.',
- ];
- }
- function resolveOriginalTask(prompt) {
- const canonical = process.env[ASK_ORIGINAL_TASK_ENV];
- if (canonical && canonical.trim()) {
- return canonical;
- }
- const alias = process.env[ASK_ORIGINAL_TASK_ENV_ALIAS];
- if (alias && alias.trim()) {
- console.error(`[ask] DEPRECATED: ${ASK_ORIGINAL_TASK_ENV_ALIAS} is deprecated; use ${ASK_ORIGINAL_TASK_ENV} instead.`);
- return alias;
- }
- return prompt;
- }
- async function writeArtifact({ provider, originalTask, finalPrompt, rawOutput, exitCode }) {
- const root = process.cwd();
- const artifactDir = join(await resolveOmcStateRoot(root), 'artifacts', 'ask');
- const slug = slugify(originalTask);
- const timestamp = timestampToken();
- const artifactPath = join(artifactDir, `${provider}-${slug}-${timestamp}.md`);
- const summary = buildSummary(exitCode, rawOutput);
- const actionItems = buildActionItems(exitCode);
- const body = [
- `# ${provider} advisor artifact`,
- '',
- `- Provider: ${provider}`,
- `- Exit code: ${exitCode}`,
- `- Created at: ${new Date().toISOString()}`,
- '',
- '## Original task',
- '',
- originalTask,
- '',
- '## Final prompt',
- '',
- finalPrompt,
- '',
- '## Raw output',
- '',
- '```text',
- rawOutput || '(no output)',
- '```',
- '',
- '## Concise summary',
- '',
- summary,
- '',
- '## Action items',
- '',
- ...actionItems.map((item) => `- ${item}`),
- '',
- ].join('\n');
- await mkdir(artifactDir, { recursive: true });
- await writeFile(artifactPath, body, 'utf8');
- return artifactPath;
- }
- async function main() {
- const { provider, prompt } = parseArgs(process.argv.slice(2));
- const binary = PROVIDER_BINARIES[provider];
- guardProviderPlatform(provider);
- ensureBinary(provider, binary);
- const pipePromptViaStdin = shouldPipePromptViaStdin(provider, prompt);
- // Antigravity on Windows: spawn without a shell to avoid cmd.exe prompt parsing.
- // The `-p <prompt>` format is safe as a direct argv value when spawned without
- // shell preprocessing (agy is a real executable, not a shell function or alias).
- const useShell = provider === 'antigravity' ? false : SHOULD_USE_WINDOWS_SHELL;
- const promptDir = PROMPT_FILE_PROVIDERS.has(provider) ? mkdtempSync(join(tmpdir(), 'omc-ask-')) : null;
- let run;
- try {
- let promptFile;
- if (promptDir) {
- promptFile = join(promptDir, 'prompt.md');
- writeFileSync(promptFile, prompt, { encoding: 'utf8', mode: 0o600 });
- // A shell spawn joins argv with spaces unquoted, so quote the path in case
- // the temp dir contains spaces (e.g. a Windows profile like "John Smith").
- if (useShell) {
- promptFile = `"${promptFile}"`;
- }
- }
- const providerArgs = buildProviderArgs(provider, prompt, { pipePromptViaStdin, promptFile });
- run = spawnSync(binary, providerArgs, {
- encoding: 'utf8',
- maxBuffer: 10 * 1024 * 1024,
- env: buildProviderEnv(provider),
- shell: useShell,
- // Bound antigravity so an upstream non-TTY hang (#76) fails cleanly instead of
- // blocking forever; agy's own --print-timeout does not work. SIGKILL (not a
- // catchable SIGTERM) guarantees spawnSync returns even if agy traps signals.
- ...(provider === 'antigravity' ? { timeout: ANTIGRAVITY_TIMEOUT_MS, killSignal: ANTIGRAVITY_TIMEOUT_KILL_SIGNAL } : {}),
- ...(pipePromptViaStdin ? { input: prompt } : { stdio: ['ignore', 'pipe', 'pipe'] }),
- });
- } finally {
- if (promptDir) {
- rmSync(promptDir, { recursive: true, force: true });
- }
- }
- const stdout = run.stdout || '';
- const stderr = run.stderr || '';
- const rawOutput = [stdout, stderr].filter(Boolean).join(stdout && stderr ? '\n\n' : '');
- let exitCode = typeof run.status === 'number' ? run.status : 1;
- // Antigravity (#76): the headless non-TTY bug surfaces two ways — a clean
- // zero-exit with NO output (output dropped on flush), or an indefinite hang.
- // The timeout above turns a hang into a killed/non-zero run; here we also turn
- // a zero-exit empty result into a failure, so the advisor never records
- // "(no output)" and reports success. (Empirically agy 1.0.10 returns output
- // under pipe capture; this surfaces the regression/refusal cases instead of
- // masking them.) No silent success, no infinite wait — see #76 for why neither
- // a PTY wrapper nor agy's --print-timeout is a usable workaround.
- if (provider === 'antigravity' && (run.error?.code === 'ETIMEDOUT' || run.signal === ANTIGRAVITY_TIMEOUT_KILL_SIGNAL)) {
- console.error(`[ask-antigravity] agy timed out after ${ANTIGRAVITY_TIMEOUT_MS}ms with no completed response (see antigravity-cli#76).`);
- console.error('[ask-antigravity] agy headless print mode can hang on non-TTY; verify interactively with: agy -p "<prompt>"');
- exitCode = exitCode === 0 ? 1 : exitCode;
- } else if (provider === 'antigravity' && exitCode === 0 && rawOutput.trim() === '') {
- console.error('[ask-antigravity] agy exited 0 but produced no output under pipe capture.');
- console.error('[ask-antigravity] Treating as failure (see google-antigravity/antigravity-cli#76).');
- console.error('[ask-antigravity] Re-run, or verify interactively with: agy -p "<prompt>"');
- exitCode = 1;
- }
- const artifactPath = await writeArtifact({
- provider,
- originalTask: resolveOriginalTask(prompt),
- finalPrompt: prompt,
- rawOutput,
- exitCode,
- });
- console.log(artifactPath);
- if (run.error) {
- console.error(`[ask-${provider}] ${run.error.message}`);
- }
- if (exitCode !== 0) {
- process.exit(exitCode);
- }
- }
- main().catch((error) => {
- console.error(`[run-provider-advisor] ${error instanceof Error ? error.message : String(error)}`);
- process.exit(1);
- });
skills/project-session-manager/lib/tmux.sh · Bundled script · 241 lines · 1 finding marked
- #!/usr/bin/env bash
- # PSM Tmux Session Management
- # Check if tmux is available
- psm_has_tmux() {
- command -v tmux &> /dev/null
- }
- # Canonical tmux-safe session-name contract (issue #3528).
- # tmux reserves ':' and '.' in target names (the "session:window.pane" syntax)
- # and silently rewrites them inside session names, which orphans any PSM session
- # whose requested name still contained them. This is the single source of truth
- # for translating a PSM logical name into the name tmux will actually use; it
- # MUST be applied at every tmux boundary. Translation is idempotent, so it is
- # safe to call on names that are already tmux-safe (e.g. old registry entries).
- psm_tmux_safe_name() {
- local name="$1"
- printf '%s' "${name//[.:]/_}"
- }
- # Build the canonical tmux session name for a PSM public session id
- # (e.g. "omc:pr-123" -> "psm_omc_pr-123"). The colon-form id remains the
- # human-facing identifier in sessions.json and on the CLI.
- psm_tmux_name_from_id() {
- psm_tmux_safe_name "psm:${1}"
- }
- # Create a tmux session
- # Usage: psm_create_tmux_session <session_name> <working_dir>
- psm_create_tmux_session() {
- local session_name
- session_name=$(psm_tmux_safe_name "$1")
- local working_dir="$2"
- if ! psm_has_tmux; then
- echo "error|tmux not found"
- return 1
- fi
- # Check if session already exists
- if tmux has-session -t "$session_name" 2>/dev/null; then
- echo "exists|$session_name"
- return 1
- fi
- # Create detached session
- tmux new-session -d -s "$session_name" -c "$working_dir" 2>/dev/null || {
- echo "error|Failed to create tmux session"
- return 1
- }
- # Fail closed: verify the session exists under the exact name PSM will use
- # for later lookups (issue #3528). If tmux rewrote the name, every later
- # has-session / send-keys / kill / attach would silently miss.
- if ! tmux has-session -t "$session_name" 2>/dev/null; then
- echo "error|tmux session not found after create: $session_name"
- return 1
- fi
- echo "created|$session_name"
- return 0
- }
- # Launch Claude Code in tmux session, optionally injecting either a context-file
- # trigger prompt or a literal initial prompt.
- # Usage: psm_launch_claude <session_name> [initial_context]
- # initial_context may be either:
- # - a path relative to the worktree root (e.g. .psm/review.md), or
- # - a literal prompt string to send after Claude boots.
- #
- # Passes --dangerously-skip-permissions so the session does not stall on
- # directory-trust or repeated tool-approval prompts (issue #2508).
- # Set PSM_CLAUDE_STARTUP_DELAY (default: 5s) to tune literal-prompt delivery.
- psm_launch_claude() {
- local session_name
- session_name=$(psm_tmux_safe_name "$1")
- local initial_context="${2:-}"
- if ! tmux has-session -t "$session_name" 2>/dev/null; then
- echo "error|Session not found: $session_name"
- return 1
- fi
- # --dangerously-skip-permissions bypasses both the directory-trust prompt and
- # every per-tool approval prompt. Without this flag, unattended PSM sessions
- # can block indefinitely on the first tool call (issue #2508).
- tmux send-keys -t "$session_name" "claude --dangerously-skip-permissions" Enter
- Note: Starts a coding agent with its permission prompts off
- Line 87 on GitHub
- if [[ -n "$initial_context" ]]; then
- local session_path=""
- session_path=$(tmux display-message -p -t "$session_name" '#{pane_current_path}' 2>/dev/null || true)
- # If the second arg resolves to a file in the worktree, preserve the
- # existing context-file flow. Otherwise treat it as a literal prompt.
- if [[ -n "$session_path" && -f "$session_path/$initial_context" ]]; then
- psm_inject_prompt "$session_name" "$initial_context"
- else
- local startup_delay="${PSM_CLAUDE_STARTUP_DELAY:-5}"
- (
- sleep "$startup_delay"
- tmux send-keys -t "$session_name" -l -- "$initial_context" 2>/dev/null || true
- tmux send-keys -t "$session_name" Enter 2>/dev/null || true
- ) &
- fi
- fi
- echo "launched|$session_name"
- return 0
- }
- # Render a PSM template file by substituting {{KEY}} placeholders.
- # Usage: psm_render_template <template_file> [KEY=VALUE ...]
- # Outputs rendered content to stdout; returns 1 if template not found.
- psm_render_template() {
- local template_file="$1"
- shift
- if [[ ! -f "$template_file" ]]; then
- echo "error|Template not found: $template_file" >&2
- return 1
- fi
- local content
- content=$(cat "$template_file")
- for assignment in "$@"; do
- local key="${assignment%%=*}"
- local value="${assignment#*=}"
- # Bash parameter expansion handles multiline values safely
- content="${content//\{\{${key}\}\}/$value}"
- done
- printf '%s\n' "$content"
- }
- # Returns 0 if the captured pane text shows Claude's interactive input prompt.
- # Matches '>' (standard prompt) or '?' (trust prompt) as the sole content of a line.
- # Usage: _psm_pane_has_claude_prompt <pane_text>
- _psm_pane_has_claude_prompt() {
- local pane_text="$1"
- printf '%s' "$pane_text" | grep -qE '^[[:space:]]*(>|\?)[[:space:]]*$'
- }
- # Poll the tmux pane until Claude's REPL prompt appears.
- # Usage: psm_wait_for_claude_prompt <session_name> [max_seconds]
- # Returns 0 when prompt detected; 1 on timeout.
- psm_wait_for_claude_prompt() {
- local session_name
- session_name=$(psm_tmux_safe_name "$1")
- local max_wait="${2:-30}"
- local waited=0
- while [[ $waited -lt $max_wait ]]; do
- local pane_content
- pane_content=$(tmux capture-pane -t "$session_name" -p 2>/dev/null) || return 1
- if _psm_pane_has_claude_prompt "$pane_content"; then
- return 0
- fi
- sleep 1
- (( waited++ )) || true
- done
- return 1
- }
- # Wait for Claude's REPL to be ready then inject a context-file trigger prompt.
- # Non-fatal: warns on timeout but does not fail the session creation.
- # Usage: psm_inject_prompt <session_name> <context_file_relative_path>
- psm_inject_prompt() {
- local session_name
- session_name=$(psm_tmux_safe_name "$1")
- local context_file="$2"
- if ! psm_wait_for_claude_prompt "$session_name"; then
- echo "warn|Timed out waiting for Claude prompt; task context not injected" >&2
- return 0
- fi
- local trigger="Read ${context_file} for full task context, then begin."
- # Use literal mode (-l) to prevent tmux from interpreting key names in the text
- tmux send-keys -t "$session_name" -l -- "$trigger"
- sleep 0.15
- tmux send-keys -t "$session_name" Enter
- return 0
- }
- # Kill a tmux session
- # Usage: psm_kill_tmux_session <session_name>
- psm_kill_tmux_session() {
- local session_name
- session_name=$(psm_tmux_safe_name "$1")
- if ! tmux has-session -t "$session_name" 2>/dev/null; then
- echo "not_found|$session_name"
- return 0
- fi
- tmux kill-session -t "$session_name" 2>/dev/null || {
- echo "error|Failed to kill session"
- return 1
- }
- echo "killed|$session_name"
- return 0
- }
- # List all PSM tmux sessions
- psm_list_tmux_sessions() {
- if ! psm_has_tmux; then
- return 0
- fi
- tmux list-sessions -F "#{session_name}|#{session_created}|#{session_attached}" 2>/dev/null | grep "^psm_" || true
- }
- # Check if a tmux session exists
- # Usage: psm_tmux_session_exists <session_name>
- psm_tmux_session_exists() {
- local session_name
- session_name=$(psm_tmux_safe_name "$1")
- tmux has-session -t "$session_name" 2>/dev/null
- }
- # Get current tmux session name
- psm_current_tmux_session() {
- if [[ -n "$TMUX" ]]; then
- tmux display-message -p "#{session_name}" 2>/dev/null
- fi
- }
- # Generate tmux session name
- # Usage: psm_tmux_session_name <alias> <type> <id>
- psm_tmux_session_name() {
- local alias="$1"
- local type="$2"
- local id="$3"
- psm_tmux_name_from_id "${alias}:${type}-${id}"
- }
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.