@heretyc/subagent-mcp 2.9.2 → 2.10.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +201 -201
- package/NOTICE +5 -5
- package/README.md +184 -190
- package/dist/concurrency.js +108 -0
- package/dist/config-scaffold.js +2 -0
- package/dist/global-concurrency.jsonc +28 -0
- package/dist/hooks/orchestration-codex.js +9 -6
- package/dist/index.js +337 -77
- package/dist/orchestration/hook-core.js +35 -4
- package/dist/orchestration/pretool.js +9 -4
- package/dist/setup.js +1 -0
- package/dist/status-helpers.js +2 -2
- package/dist/wait-helpers.js +1 -1
- package/dist/zombie.js +189 -0
- package/package.json +7 -6
package/README.md
CHANGED
|
@@ -1,193 +1,187 @@
|
|
|
1
|
-
# subagent-mcp
|
|
2
|
-
|
|
3
|
-
[](https://www.npmjs.com/package/@heretyc/subagent-mcp)
|
|
4
|
-
[](LICENSE)
|
|
5
|
-
[](https://www.npmjs.com/package/@heretyc/subagent-mcp)
|
|
6
|
-
[](https://github.com/Heretyc/subagent-mcp/actions/workflows/claude-routine.yml)
|
|
7
|
-
|
|
8
|
-
MCP server that launches and manages always-interactive Claude Code and Codex sub-agent sessions — on macOS, Linux, and Windows. No direct API calls. No API keys.
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
```
|
|
29
|
-
|
|
30
|
-
```
|
|
31
|
-
|
|
1
|
+
# subagent-mcp
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@heretyc/subagent-mcp)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
[](https://www.npmjs.com/package/@heretyc/subagent-mcp)
|
|
6
|
+
[](https://github.com/Heretyc/subagent-mcp/actions/workflows/claude-routine.yml)
|
|
7
|
+
|
|
8
|
+
MCP server that launches and manages always-interactive Claude Code and Codex sub-agent sessions — on macOS, Linux, and Windows. No direct API calls. No API keys.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
### Prerequisites (runtime)
|
|
13
|
+
|
|
14
|
+
To run the published CLI you need:
|
|
15
|
+
|
|
16
|
+
- Node.js >= 18 (`node --version`)
|
|
17
|
+
- `claude` CLI — globally installed and authenticated (`claude --version`)
|
|
18
|
+
- `codex` CLI — globally installed and authenticated (`codex --version`; optional if you only use Claude paths)
|
|
19
|
+
|
|
20
|
+
Building from source needs additional developer tooling — see [CONTRIBUTING.md § Prerequisites](CONTRIBUTING.md#prerequisites).
|
|
21
|
+
|
|
22
|
+
### npmjs (default)
|
|
23
|
+
|
|
24
|
+
No authentication, no `.npmrc` configuration, and no PAT required. The package is publicly available on [npmjs.com](https://www.npmjs.com/package/@heretyc/subagent-mcp).
|
|
25
|
+
|
|
26
|
+
```bash
|
|
27
|
+
npm install -g @heretyc/subagent-mcp
|
|
28
|
+
```
|
|
29
|
+
|
|
32
30
|
**Use this path for all standard installs.**
|
|
33
31
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
Use this path when your organization's `.npmrc` already routes the `@heretyc` scope through GitHub Packages, when you need supply-chain audit tracing against the org-internal artifact, or when you run inside a GitHub Actions workflow whose `GITHUB_TOKEN` carries `read:packages`. Otherwise prefer npmjs above — it is simpler and needs no credentials.
|
|
37
|
-
|
|
38
|
-
```bash
|
|
39
|
-
# One-time machine setup
|
|
40
|
-
echo "@heretyc:registry=https://npm.pkg.github.com" >> ~/.npmrc
|
|
41
|
-
echo "//npm.pkg.github.com/:_authToken=YOUR_GITHUB_PAT" >> ~/.npmrc
|
|
42
|
-
# PAT must be a classic PAT with the read:packages scope
|
|
43
|
-
|
|
44
|
-
npm install -g @heretyc/subagent-mcp
|
|
45
|
-
```
|
|
46
|
-
|
|
47
|
-
> **Note:** GitHub Packages requires authentication even for public packages. If you see `401 Unauthorized`, verify your PAT has the `read:packages` scope and has not expired. GitHub Packages does not render a README page — the live documentation appears on [npmjs.com](https://www.npmjs.com/package/@heretyc/subagent-mcp).
|
|
48
|
-
|
|
49
|
-
---
|
|
50
|
-
|
|
51
|
-
## Quick Start
|
|
52
|
-
|
|
53
|
-
**1. Install** (see [Install](#install) above):
|
|
54
|
-
|
|
55
|
-
```bash
|
|
56
|
-
npm install -g @heretyc/subagent-mcp
|
|
57
|
-
```
|
|
58
|
-
|
|
59
|
-
**2. Register the MCP server + orchestration hooks:**
|
|
60
|
-
|
|
61
|
-
```bash
|
|
62
|
-
subagent-mcp setup
|
|
63
|
-
```
|
|
64
|
-
|
|
65
|
-
Installing the package only ships the binary — it does **not** auto-wire anything. `subagent-mcp setup` auto-detects Claude Code / Codex and registers the MCP server plus the per-turn orchestration-mode hooks. Preview with `subagent-mcp setup --dry-run`.
|
|
66
|
-
|
|
67
|
-
**3. Restart your host.**
|
|
68
|
-
|
|
69
|
-
Restart your Claude Code or Codex session so it picks up the new binary. On Codex, run `/hooks` and trust the new hook.
|
|
70
|
-
|
|
71
|
-
**4. Initialize the orchestration invariant (recommended):**
|
|
72
|
-
|
|
73
|
-
```bash
|
|
74
|
-
subagent-mcp init --global
|
|
75
|
-
```
|
|
76
|
-
|
|
77
|
-
`init --global` writes the managed invariant block into the providers' official global user-config files — `~/.claude/CLAUDE.md`, `~/.codex/AGENTS.md`, `~/.gemini/GEMINI.md` — set up once, works across every project. For a single project instead, use `subagent-mcp init --root /path/to/project` to write into that project's instruction files. `--global` and `--root` are mutually exclusive.
|
|
78
|
-
|
|
79
|
-
For manual wiring, Gemini CLI, Claude Desktop, and developer install from source, see [docs/registration.md](docs/registration.md).
|
|
80
|
-
|
|
81
|
-
---
|
|
82
|
-
|
|
83
|
-
## Features
|
|
32
|
+
`subagent-mcp update` always refreshes from npmjs, even on machines whose `.npmrc` routes `@heretyc` packages through GitHub Packages.
|
|
84
33
|
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
**
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
**
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
|
164
|
-
|
|
165
|
-
| `
|
|
166
|
-
| `
|
|
167
|
-
| `
|
|
168
|
-
| `
|
|
169
|
-
| `
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
34
|
+
### GitHub Packages (org-internal pin / supply-chain auditing)
|
|
35
|
+
|
|
36
|
+
Use this path when your organization's `.npmrc` already routes the `@heretyc` scope through GitHub Packages, when you need supply-chain audit tracing against the org-internal artifact, or when you run inside a GitHub Actions workflow whose `GITHUB_TOKEN` carries `read:packages`. Otherwise prefer npmjs above — it is simpler and needs no credentials.
|
|
37
|
+
|
|
38
|
+
```bash
|
|
39
|
+
# One-time machine setup
|
|
40
|
+
echo "@heretyc:registry=https://npm.pkg.github.com" >> ~/.npmrc
|
|
41
|
+
echo "//npm.pkg.github.com/:_authToken=YOUR_GITHUB_PAT" >> ~/.npmrc
|
|
42
|
+
# PAT must be a classic PAT with the read:packages scope
|
|
43
|
+
|
|
44
|
+
npm install -g @heretyc/subagent-mcp
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
> **Note:** GitHub Packages requires authentication even for public packages. If you see `401 Unauthorized`, verify your PAT has the `read:packages` scope and has not expired. GitHub Packages does not render a README page — the live documentation appears on [npmjs.com](https://www.npmjs.com/package/@heretyc/subagent-mcp).
|
|
48
|
+
|
|
49
|
+
## Quick Start
|
|
50
|
+
|
|
51
|
+
**1. Install** (see [Install](#install) above):
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
npm install -g @heretyc/subagent-mcp
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
**2. Register the MCP server + orchestration hooks:**
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
subagent-mcp setup
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Installing the package only ships the binary — it does **not** auto-wire anything. `subagent-mcp setup` auto-detects Claude Code / Codex and registers the MCP server plus the per-turn orchestration-mode hooks. Preview with `subagent-mcp setup --dry-run`.
|
|
64
|
+
|
|
65
|
+
**3. Restart your host.**
|
|
66
|
+
|
|
67
|
+
Restart your Claude Code or Codex session so it picks up the new binary. On Codex, run `/hooks` and trust the new hook.
|
|
68
|
+
|
|
69
|
+
**4. Initialize the orchestration invariant (recommended):**
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
subagent-mcp init --global
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
`init --global` writes the managed invariant block into the providers' official global user-config files — `~/.claude/CLAUDE.md`, `~/.codex/AGENTS.md`, `~/.gemini/GEMINI.md` — set up once, works across every project. For a single project instead, use `subagent-mcp init --root /path/to/project` to write into that project's instruction files. `--global` and `--root` are mutually exclusive.
|
|
76
|
+
|
|
77
|
+
For manual wiring, Gemini CLI, Claude Desktop, and developer install from source, see [docs/registration.md](docs/registration.md).
|
|
78
|
+
|
|
79
|
+
## Features
|
|
80
|
+
|
|
81
|
+
- Start Claude or Codex interactive sessions as managed sub-agents from any MCP host
|
|
82
|
+
- Poll status, stream stdout/stderr tails, and enqueue follow-up messages to live sessions
|
|
83
|
+
- Concurrency caps: 5 concurrent Claude + 5 concurrent Codex agents (only `processing` agents count toward the cap; `stalled` agents do not hold a slot)
|
|
84
|
+
- Liveness tracking via the visible provider stream (Claude SDK events, Codex app-server JSONL): agents with no parsed visible provider stream item for 10 minutes enter `stalled` state (still alive, just quiet — thinking or awaiting a temp-file handoff), and recover to `processing` if the visible stream resumes
|
|
85
|
+
- Ultracode mode for Opus 4.8 via `--settings {"ultracode":true}` — see [docs/usage.md](docs/usage.md)
|
|
86
|
+
- Cross-platform exe resolution (Windows: npm-prefix .exe paths; macOS/Linux: PATH + Homebrew/usr-local fallbacks); immediate `taskkill /t /f` (Windows) / `SIGKILL` (POSIX) force-kill; no graceful shutdown period
|
|
87
|
+
- stdio MCP transport; built with `@modelcontextprotocol/sdk` + `zod`
|
|
88
|
+
- `orchestration-mode` tool — toggles orchestrator directives injected by bundled Claude Code / Codex hooks; Claude also gets a deterministic `PreToolUse` gate
|
|
89
|
+
|
|
90
|
+
## Orchestration Mode
|
|
91
|
+
|
|
92
|
+
**ON:** the agent operates as an orchestrator — hook injection governs each session turn, preventing inline reads or writes, and all work is delegated through sub-agent tools.
|
|
93
|
+
|
|
94
|
+
**OFF:** the agent operates normally, with no orchestration constraints.
|
|
95
|
+
|
|
96
|
+
Toggle with the `orchestration-mode` tool. Desktop hosts toggle the mode but receive no hook injection. See [docs/spec/dev-loop/orchestration-directive-architecture.md](docs/spec/dev-loop/orchestration-directive-architecture.md) for full semantics.
|
|
97
|
+
|
|
98
|
+
## Auto Mode
|
|
99
|
+
|
|
100
|
+
`launch_agent` supports **auto mode**: pass `prompt` + `task_category` and the server picks the best provider/model/effort for that category from its routing table, silently falling back to the next-best candidate on any launch-time failure.
|
|
101
|
+
|
|
102
|
+
`provider`, `model`, and `effort` are optional overrides — omit them to get the auto-selected best combination. Rules: passing `model` requires `provider`; passing `effort` requires both `provider` and `model`.
|
|
103
|
+
|
|
104
|
+
**task_category** (required) — pick one:
|
|
105
|
+
|
|
106
|
+
| Category | What it is |
|
|
107
|
+
|---|---|
|
|
108
|
+
| `math_proof` | deliverable is a proof/derivation/formally-checkable result |
|
|
109
|
+
| `security_review` | security verdict, threat assessment, or demonstrated exploit |
|
|
110
|
+
| `debugging` | verified fix/root-cause; requires an observed failure as precondition |
|
|
111
|
+
| `quality_review` | evaluative verdict on existing artifact (review, A-vs-B, validate-vs-spec) |
|
|
112
|
+
| `architecture` | cross-module design/plan, no code, no execution loop |
|
|
113
|
+
| `agentic_execution` | end-state via act/observe/adapt loop (run/deploy/provision/browse) |
|
|
114
|
+
| `data_analysis` | empirical finding about structured dataset (query, stat, model) |
|
|
115
|
+
| `coding` | bounded runnable code artifact, one-pass (implement, test, refactor) |
|
|
116
|
+
| `knowledge_synthesis` | novel integrated prose over sources (synthesize, summarize, draft) |
|
|
117
|
+
| `mechanical` | deterministic single-pass transform, exact-match checkable (grep, rename, reformat) |
|
|
118
|
+
| `prompt_engineering` | designed/optimized prompt or prompt-system steering an LLM/agent (composite-inferred) |
|
|
119
|
+
| `vulnerability_research` | discovery + PoC of a novel vulnerability (composite-inferred) |
|
|
120
|
+
| `molecular_biology` | reasoned molecular/computational-biology result over sequences, structures, or -omics data (composite-inferred) |
|
|
121
|
+
| `ml_accelerator_design` | hardware/software design for ML acceleration — dataflow, kernel, roofline (composite-inferred) |
|
|
122
|
+
| `fallback_default` | no category matches with confidence; prefer splitting work instead |
|
|
123
|
+
|
|
124
|
+
The last four are **composite-inferred**: they carry no dedicated benchmark and their routing competency is composed from parent categories rather than measured directly.
|
|
125
|
+
|
|
126
|
+
**Atomic-split guidance:** if you are unsure which category fits, do NOT submit one large amorphous task. Break the work into smaller atomic steps each mapping to a single category and launch one agent per step.
|
|
127
|
+
|
|
128
|
+
## Configuration
|
|
129
|
+
|
|
130
|
+
### Global concurrent-subagent cap
|
|
131
|
+
|
|
132
|
+
subagent-mcp enforces a machine-global cap on the number of **live concurrent subagents** across all agentic sessions and MCP server processes on the machine. The count includes agents started by other active sessions and the whole recursive descendant tree; slots free as agents finish or are killed.
|
|
133
|
+
|
|
134
|
+
The cap is configured in `global-concurrency.jsonc`, a dedicated dist-sibling file in the install directory. It is separate from the advanced routing directives file, ships as a commented template, and is retained across installs and updates by the same preserve-user-edits mechanism as the advanced routing directives.
|
|
135
|
+
|
|
136
|
+
Set `globalConcurrentSubagents` in that file. The default is `20`; the minimum valid value is `10`. Validation is forced: `0`, unset, missing, or invalid values reset to `20`, and values `1` through `9` are pinned up to `10`. There is no environment-variable override; the file is the sole source of truth. The file is re-read on every `launch_agent` call, so edits take effect on the next launch with no server restart.
|
|
137
|
+
|
|
138
|
+
When the cap is reached, `launch_agent` is rejected immediately; it never queues. Before cap checks, hooks and tool calls run default zombie culling with no config knob: live agents idle for more than 6 minutes and terminal-but-alive agents idle for more than 30 seconds are terminated process-tree-first, then force-killed after 20 seconds if needed. Reports include `zombies`, and `poll_agent` keeps the tail with `zombie_killed` when culling terminates an agent.
|
|
139
|
+
|
|
140
|
+
## Tools
|
|
141
|
+
|
|
142
|
+
Eight tools are exposed over the stdio MCP transport.
|
|
143
|
+
|
|
144
|
+
| Tool | Description |
|
|
145
|
+
|---|---|
|
|
146
|
+
| `launch_agent` | Start a new sub-agent session with a prompt and optional task category / overrides |
|
|
147
|
+
| `poll_agent` | Check status and stream tail output for a running agent |
|
|
148
|
+
| `kill_agent` | Terminate a running or stalled agent |
|
|
149
|
+
| `send_message` | Enqueue a message into a running agent's stdin |
|
|
150
|
+
| `list_agents` | List all tracked agents and their current status |
|
|
151
|
+
| `wait` | Block until a specific agent reaches a terminal state |
|
|
152
|
+
| `orchestration-mode` | Toggle orchestration-mode ON/OFF; controls whether hook directives are injected into agent sessions |
|
|
153
|
+
| `model-selection-mode` | Control model selection: `smart` (auto-pick) or `user-approved-overrides` (30-min override window) |
|
|
154
|
+
|
|
155
|
+
Full parameters, return shapes, and the `alive` / `idle_seconds` / `hint` / `recent_stream` fields are in [docs/tools.md](docs/tools.md).
|
|
156
|
+
|
|
157
|
+
## Agent Lifecycle
|
|
158
|
+
|
|
159
|
+
Each agent transitions through these states:
|
|
160
|
+
|
|
161
|
+
| Status | Meaning |
|
|
162
|
+
|---|---|
|
|
163
|
+
| `processing` | Driver alive with a visible provider-stream heartbeat in the last 10 minutes — actively working. Launch time counts as the initial heartbeat |
|
|
164
|
+
| `stalled` | Driver STILL ALIVE but no parsed visible provider stream item for >= 10 minutes — working, thinking, or awaiting a temp-file handoff (not a failure). Recovers to `processing` if the visible stream resumes |
|
|
165
|
+
| `finished` | Current turn completed, or driver exited with code 0 |
|
|
166
|
+
| `errored` | Process exited with non-zero code |
|
|
167
|
+
| `stopped` | Terminated by `kill_agent` |
|
|
168
|
+
|
|
169
|
+
`processing` and `stalled` are live. `stalled` means the driver is alive but quiet (>= 10 min no visible stream); it recovers automatically and is never auto-killed — do not `kill_agent` a stalled agent. `wait` does not return on `stalled`. Full semantics: [docs/reference/status-lifecycle.md](docs/reference/status-lifecycle.md).
|
|
170
|
+
|
|
171
|
+
## Documentation
|
|
172
|
+
|
|
173
|
+
| Document | Contents |
|
|
174
|
+
|---|---|
|
|
175
|
+
| [docs/registration.md](docs/registration.md) | Per-platform setup: Claude Code, Codex, Gemini CLI, Claude Desktop; manual wiring; developer install from source |
|
|
176
|
+
| [docs/tools.md](docs/tools.md) | Full tool reference — all eight tools, parameters, return shapes |
|
|
177
|
+
| [docs/usage.md](docs/usage.md) | Model & effort matrix, ultracode mode, CLI invocations, usage examples |
|
|
178
|
+
| [docs/SPEC.md](docs/SPEC.md) | Full technical specification — architecture, schemas, status lifecycle, error catalogue |
|
|
179
|
+
| [docs/spec/interactive-drivers.md](docs/spec/interactive-drivers.md) | Always-interactive Claude/Codex driver model |
|
|
180
|
+
| [docs/release-notes.md](docs/release-notes.md) | Operator-facing release notes |
|
|
181
|
+
| [CONTRIBUTING.md](CONTRIBUTING.md) | Contributor guide — dev environment, build, test, publish |
|
|
182
|
+
|
|
183
|
+
## License
|
|
184
|
+
|
|
185
|
+
Apache-2.0 — Copyright 2026 Lexi Blackburn
|
|
186
|
+
|
|
187
|
+
See [LICENSE](LICENSE).
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { platform } from "node:os";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { CONCURRENCY_SCAFFOLD } from "./config-scaffold.js";
|
|
6
|
+
import { cullStaleSlots, ZOMBIE_FORCE_GRACE_MS, ZOMBIE_LIVE_IDLE_MS, ZOMBIE_TERMINAL_IDLE_MS, buildProcessTreeKillCommands, drainZombieIntents, drainZombieReports, parseSlotMetadata, readSlotMetadata, slotPathForAgent, writeSlotMetadata, } from "./zombie.js";
|
|
7
|
+
export const DEFAULT_CAP = 20;
|
|
8
|
+
export const MIN_CAP = 10;
|
|
9
|
+
export const CONFIG_FILENAME = "global-concurrency.jsonc";
|
|
10
|
+
export { cullStaleSlots, ZOMBIE_FORCE_GRACE_MS, ZOMBIE_LIVE_IDLE_MS, ZOMBIE_TERMINAL_IDLE_MS, buildProcessTreeKillCommands, drainZombieIntents, drainZombieReports, parseSlotMetadata, readSlotMetadata, slotPathForAgent, writeSlotMetadata, };
|
|
11
|
+
export function clampCap(raw) {
|
|
12
|
+
if (!Number.isInteger(raw))
|
|
13
|
+
return DEFAULT_CAP;
|
|
14
|
+
const v = raw;
|
|
15
|
+
if (v <= 0)
|
|
16
|
+
return DEFAULT_CAP;
|
|
17
|
+
if (v < MIN_CAP)
|
|
18
|
+
return MIN_CAP;
|
|
19
|
+
return v;
|
|
20
|
+
}
|
|
21
|
+
export function stripJsoncComments(text) {
|
|
22
|
+
return text.replace(/^\s*\/\/.*$/gm, "");
|
|
23
|
+
}
|
|
24
|
+
export function parseConcurrencyConfig(text) {
|
|
25
|
+
let raw;
|
|
26
|
+
try {
|
|
27
|
+
raw = JSON.parse(stripJsoncComments(text))?.globalConcurrentSubagents;
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
raw = undefined;
|
|
31
|
+
}
|
|
32
|
+
return clampCap(raw);
|
|
33
|
+
}
|
|
34
|
+
export function defaultConfigPath() {
|
|
35
|
+
return fileURLToPath(new URL("./" + CONFIG_FILENAME, import.meta.url));
|
|
36
|
+
}
|
|
37
|
+
export function ensureConcurrencyConfig(path = defaultConfigPath()) {
|
|
38
|
+
try {
|
|
39
|
+
if (existsSync(path))
|
|
40
|
+
return;
|
|
41
|
+
writeFileSync(path, CONCURRENCY_SCAFFOLD);
|
|
42
|
+
}
|
|
43
|
+
catch { }
|
|
44
|
+
}
|
|
45
|
+
export function readGlobalCap(path = defaultConfigPath()) {
|
|
46
|
+
try {
|
|
47
|
+
ensureConcurrencyConfig(path);
|
|
48
|
+
return parseConcurrencyConfig(readFileSync(path, "utf8"));
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return DEFAULT_CAP;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
export function slotDir() {
|
|
55
|
+
if (process.env.SUBAGENT_SLOT_DIR)
|
|
56
|
+
return process.env.SUBAGENT_SLOT_DIR;
|
|
57
|
+
if (platform() === "win32") {
|
|
58
|
+
return join(process.env.ProgramData || process.env.ALLUSERSPROFILE || "C:\\ProgramData", "subagent-mcp", "slots");
|
|
59
|
+
}
|
|
60
|
+
return "/tmp/subagent-mcp/slots";
|
|
61
|
+
}
|
|
62
|
+
export function countSlots(dir = slotDir()) {
|
|
63
|
+
try {
|
|
64
|
+
return readdirSync(dir).filter((f) => f.startsWith("slot-")).length;
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return 0;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
export function scheduleForceKill(ms, kill) {
|
|
71
|
+
const timer = setTimeout(kill, ms);
|
|
72
|
+
timer.unref();
|
|
73
|
+
}
|
|
74
|
+
export const NONBLOCKING_CULL_DEPS = {
|
|
75
|
+
scheduleForceKill,
|
|
76
|
+
};
|
|
77
|
+
export function reserveSlot(agentId, max, dir = slotDir(), cullDeps) {
|
|
78
|
+
try {
|
|
79
|
+
mkdirSync(dir, { recursive: true, mode: 0o1777 });
|
|
80
|
+
cullStaleSlots(dir, cullDeps);
|
|
81
|
+
const slotPath = slotPathForAgent(dir, agentId);
|
|
82
|
+
writeSlotMetadata(slotPath, { agent_id: agentId });
|
|
83
|
+
const n = countSlots(dir);
|
|
84
|
+
if (n > max) {
|
|
85
|
+
try {
|
|
86
|
+
unlinkSync(slotPath);
|
|
87
|
+
}
|
|
88
|
+
catch { }
|
|
89
|
+
return { ok: false, current: n - 1, max };
|
|
90
|
+
}
|
|
91
|
+
return { ok: true, slotPath, current: n, max };
|
|
92
|
+
}
|
|
93
|
+
catch (e) {
|
|
94
|
+
console.error(`[concurrency] reserve failed, failing open: ${e instanceof Error ? e.message : String(e)}`);
|
|
95
|
+
return { ok: true, current: 0, max, slotPath: null };
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
export function releaseSlot(slotPath) {
|
|
99
|
+
if (!slotPath)
|
|
100
|
+
return;
|
|
101
|
+
try {
|
|
102
|
+
unlinkSync(slotPath);
|
|
103
|
+
}
|
|
104
|
+
catch { }
|
|
105
|
+
}
|
|
106
|
+
export function globalCapMessage(current, max, configPath = defaultConfigPath()) {
|
|
107
|
+
return `Global concurrent-subagent limit reached: ${current} of ${max} live subagents are already running across all sessions on this machine. This global count includes agents started by OTHER active agentic sessions and the ENTIRE recursive descendant tree, not just this session's direct children. launch_agent was REJECTED — this cap never queues or blocks; no slot frees itself by waiting. Free a slot manually first: call list_agents to see live agents, then kill_agent to terminate ones you no longer need, and retry. The limit is "globalConcurrentSubagents" in ${configPath} (default 20, minimum 10).`;
|
|
108
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// GENERATED by scripts/gen-ruleset-scaffold.mjs from src/global-concurrency.jsonc — DO NOT EDIT.
|
|
2
|
+
export const CONCURRENCY_SCAFFOLD = "// subagent-mcp — Global Concurrent Subagent Cap\r\n// ------------------------------------------------------------------\r\n// SOLE source of truth for the machine-wide limit on how many subagents\r\n// may be ALIVE AT ONCE across EVERY session, process, and user on this\r\n// machine. There is NO environment-variable override.\r\n//\r\n// The whole recursive descendant tree counts toward this ONE number: a\r\n// subagent that itself launches subagents adds to the same machine-wide\r\n// total, and OTHER active agentic sessions count too.\r\n//\r\n// RE-READ on every launch_agent call — edits take effect immediately, no\r\n// server restart required.\r\n//\r\n// Value rules (forcibly applied to the number below):\r\n// - missing / unset / non-integer / 0 / negative -> reset to default 20\r\n// - 1 through 9 -> forced UP to minimum 10\r\n// - 10 or greater -> used as-is\r\n//\r\n// Zombie culling is always enabled. There is no config knob. Before cap\r\n// rejection, launch/tool/hook paths cull stale live agents idle for 6min and\r\n// terminal-but-alive agents idle for 30s. Culling gracefully terminates the\r\n// full process tree, then force-kills after 20s when needed.\r\n//\r\n// When the cap is reached after culling, launch_agent is REJECTED (never\r\n// queued). Free a slot with list_agents + kill_agent, then retry.\r\n{\r\n \"globalConcurrentSubagents\": 20\r\n}\r\n";
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
// subagent-mcp — Global Concurrent Subagent Cap
|
|
2
|
+
// ------------------------------------------------------------------
|
|
3
|
+
// SOLE source of truth for the machine-wide limit on how many subagents
|
|
4
|
+
// may be ALIVE AT ONCE across EVERY session, process, and user on this
|
|
5
|
+
// machine. There is NO environment-variable override.
|
|
6
|
+
//
|
|
7
|
+
// The whole recursive descendant tree counts toward this ONE number: a
|
|
8
|
+
// subagent that itself launches subagents adds to the same machine-wide
|
|
9
|
+
// total, and OTHER active agentic sessions count too.
|
|
10
|
+
//
|
|
11
|
+
// RE-READ on every launch_agent call — edits take effect immediately, no
|
|
12
|
+
// server restart required.
|
|
13
|
+
//
|
|
14
|
+
// Value rules (forcibly applied to the number below):
|
|
15
|
+
// - missing / unset / non-integer / 0 / negative -> reset to default 20
|
|
16
|
+
// - 1 through 9 -> forced UP to minimum 10
|
|
17
|
+
// - 10 or greater -> used as-is
|
|
18
|
+
//
|
|
19
|
+
// Zombie culling is always enabled. There is no config knob. Before cap
|
|
20
|
+
// rejection, launch/tool/hook paths cull stale live agents idle for 6min and
|
|
21
|
+
// terminal-but-alive agents idle for 30s. Culling gracefully terminates the
|
|
22
|
+
// full process tree, then force-kills after 20s when needed.
|
|
23
|
+
//
|
|
24
|
+
// When the cap is reached after culling, launch_agent is REJECTED (never
|
|
25
|
+
// queued). Free a slot with list_agents + kill_agent, then retry.
|
|
26
|
+
{
|
|
27
|
+
"globalConcurrentSubagents": 20
|
|
28
|
+
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { realpathSync } from "node:fs";
|
|
2
2
|
import { pathToFileURL } from "node:url";
|
|
3
|
-
import { claimAndEmit, classifyClaim, countJsonlType, runHook, sessionKey, } from "../orchestration/hook-core.js";
|
|
3
|
+
import { claimAndEmit, appendHookZombieReport, classifyClaim, countJsonlType, cullHookZombies, runHook, sessionKey, } from "../orchestration/hook-core.js";
|
|
4
4
|
import * as marker from "../orchestration/marker.js";
|
|
5
5
|
/**
|
|
6
6
|
* Codex CLI hook entry. Branches on payload.hook_event_name:
|
|
@@ -80,11 +80,14 @@ export const codexAdapter = {
|
|
|
80
80
|
export function runCodexHook(payload, env, adapter = codexAdapter) {
|
|
81
81
|
try {
|
|
82
82
|
if (payload.hook_event_name === "SessionStart") {
|
|
83
|
-
|
|
84
|
-
|
|
83
|
+
const zombieRecords = cullHookZombies();
|
|
84
|
+
if (adapter.isSubagent(payload, env)) {
|
|
85
|
+
return appendHookZombieReport("", zombieRecords);
|
|
86
|
+
}
|
|
85
87
|
const cwd = payload.cwd || process.cwd();
|
|
86
|
-
if (!marker.isActive(cwd))
|
|
87
|
-
return "";
|
|
88
|
+
if (!marker.isActive(cwd)) {
|
|
89
|
+
return appendHookZombieReport("", zombieRecords);
|
|
90
|
+
}
|
|
88
91
|
const current = sessionKey(payload);
|
|
89
92
|
const turn = adapter.currentTurn(payload.transcript_path);
|
|
90
93
|
const m = marker.readMarker(cwd);
|
|
@@ -93,7 +96,7 @@ export function runCodexHook(payload, env, adapter = codexAdapter) {
|
|
|
93
96
|
// semantics — FULL + ON reminder, ack-latched CARRYOVER prepend, counter
|
|
94
97
|
// re-baseline). SessionStart claims even on SAME-SESSION (resume) so
|
|
95
98
|
// turn 0 is always covered.
|
|
96
|
-
return claimAndEmit(cwd, current, turn, m, kind, env, adapter);
|
|
99
|
+
return appendHookZombieReport(claimAndEmit(cwd, current, turn, m, kind, env, adapter), zombieRecords);
|
|
97
100
|
}
|
|
98
101
|
// UserPromptSubmit (and any other event) -> normal cadence.
|
|
99
102
|
return runHook(payload, env, adapter);
|