master-orchestrator 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -0
- package/LICENSE +21 -0
- package/README.md +174 -2
- package/package.json +56 -4
- package/src/adapters/agy.ts +285 -0
- package/src/adapters/claude.ts +317 -0
- package/src/adapters/codex.ts +162 -0
- package/src/adapters/common.ts +211 -0
- package/src/adapters/cursor.ts +242 -0
- package/src/adapters/dsh.ts +356 -0
- package/src/adapters/fake-agent.mjs +50 -0
- package/src/adapters/fake.ts +88 -0
- package/src/adapters/gemini.ts +225 -0
- package/src/adapters/grok.ts +328 -0
- package/src/adapters/muse.ts +281 -0
- package/src/adapters/omp.ts +119 -0
- package/src/adapters/opencode.ts +228 -0
- package/src/adapters/pi.ts +284 -0
- package/src/adapters/registry.ts +31 -0
- package/src/adapters/types.ts +201 -0
- package/src/config/load.ts +290 -0
- package/src/config/profiles.ts +64 -0
- package/src/config/schema.ts +158 -0
- package/src/config/write.ts +83 -0
- package/src/engine/artifacts.ts +145 -0
- package/src/engine/baseline.ts +132 -0
- package/src/engine/execute.ts +437 -0
- package/src/engine/git.ts +32 -0
- package/src/engine/hostenv.ts +54 -0
- package/src/engine/registry.ts +280 -0
- package/src/engine/runner.ts +203 -0
- package/src/engine/types.ts +55 -0
- package/src/engine/verify.ts +100 -0
- package/src/index.ts +602 -0
- package/src/prompts/envelope.ts +29 -0
- package/src/prompts/templates.ts +389 -0
- package/src/ui/configure.ts +174 -0
- package/src/ui/dialogs.ts +88 -0
- package/src/ui/doctor.ts +120 -0
- package/src/ui/format.ts +94 -0
- package/src/ui/host.ts +100 -0
- package/src/ui/render.ts +86 -0
- package/src/ui/widget.ts +70 -0
- package/src/workflows/budget.ts +66 -0
- package/src/workflows/common.ts +100 -0
- package/src/workflows/debate.ts +488 -0
- package/src/workflows/host.ts +78 -0
- package/src/workflows/plan-exec.ts +807 -0
- package/src/workflows/plan.ts +407 -0
- package/src/workflows/planfile.ts +380 -0
- package/src/workflows/planstate.ts +229 -0
- package/src/workflows/verdict.ts +74 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 0.1.0
|
|
4
|
+
|
|
5
|
+
First release.
|
|
6
|
+
|
|
7
|
+
- `delegate_task` tool and `/delegate` command: one assignment to any of eleven coding agents, with a mechanical report of what changed, follow-ups in the same session, fallback chains and a workspace write lock.
|
|
8
|
+
- `/debate`: rounds of independent answers and revisions, convergence detection, participant drop-out, anonymized transcripts and a synthesis by pi.
|
|
9
|
+
- `/plan`: drafting, critique and revision, user approval and editing, block-by-block execution with review, `plan_verdict`, fix routing, per-block commits, pause and resume across restarts.
|
|
10
|
+
- `/orchestrator doctor | init | config | runs | cancel`.
|
|
11
|
+
- Adapters for Codex, Claude Code, OpenCode, pi, oh-my-pi, Antigravity, Grok Build, Muse Code, DeepSeek Harness, Gemini CLI and Cursor Agent. All are experimental until they pass the verification pass against real runs.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Diogo Soares Rodrigues
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,175 @@
|
|
|
1
|
-
#
|
|
1
|
+
# master-orchestrator
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A [pi](https://www.npmjs.com/package/@earendil-works/pi-coding-agent) package that turns pi into an orchestrator of other coding agents. Pi delegates assignments to Codex, Claude Code, OpenCode, pi, oh-my-pi, Antigravity, Grok Build, Muse Code, DeepSeek Harness, Gemini CLI and Cursor Agent, moderates debates between them, and plans and executes multi-step work with per-block review.
|
|
4
|
+
|
|
5
|
+
## Read this first: what the workers can do
|
|
6
|
+
|
|
7
|
+
**Every worker runs with unattended full access.** Each agent is started with all of its tools, no approval prompts and no sandbox, in both `analyze` and `implement` mode. A worker can read, write and execute anything your user account can, inside the workspace and outside it, and it can reach the network.
|
|
8
|
+
|
|
9
|
+
The package adds no restriction of its own. What it does instead:
|
|
10
|
+
|
|
11
|
+
- It states each assignment precisely (mode, editable scope, Git policy, no further delegation).
|
|
12
|
+
- It diffs the workspace before and after every run and reports what actually changed, including changes an `analyze` run should not have made and changes outside the scope of an `implement` run.
|
|
13
|
+
- It never reverts, resets, stashes or deletes to undo a worker's changes. It reports, and the decision stays with you.
|
|
14
|
+
- It bounds every run with a timeout, lets you cancel it, and allows one writer per workspace.
|
|
15
|
+
- It stops recursion: a worker that loads this package registers nothing.
|
|
16
|
+
- A debate or a plan starts only from a command you type, and shows its maximum number of agent runs before it starts.
|
|
17
|
+
|
|
18
|
+
Install it only where you would run those agents unattended yourself.
|
|
19
|
+
|
|
20
|
+
## Install
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
pi install npm:master-orchestrator
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Linux and macOS. Node 22.18 or newer (the version pi needs). The agents themselves are not installed by this package: install and log in to the ones you want, then run `/orchestrator doctor`.
|
|
27
|
+
|
|
28
|
+
## Use
|
|
29
|
+
|
|
30
|
+
### From the model: `delegate_task`
|
|
31
|
+
|
|
32
|
+
Pi's model can call `delegate_task` on its own:
|
|
33
|
+
|
|
34
|
+
| Parameter | Notes |
|
|
35
|
+
|---|---|
|
|
36
|
+
| `task` | Self-contained assignment; the worker sees none of the conversation |
|
|
37
|
+
| `profile` | Profile name or agent id (`codex`, `claude`, ...) |
|
|
38
|
+
| `role` | Alternative to `profile`: the role's fallback chain |
|
|
39
|
+
| `mode` | `analyze` (default) or `implement` |
|
|
40
|
+
| `scope` | Editable paths and globs for `implement` |
|
|
41
|
+
| `followUpRunId` | Continue the session of an earlier run |
|
|
42
|
+
|
|
43
|
+
The result contains the worker's final answer, the files it changed, any unexpected or out-of-scope changes, denied actions, usage and the path of the run's artifacts. Parallel `analyze` calls run concurrently, bounded by `defaults.maxParallel`. With `approval.implementFromTool: "ask"`, model-initiated `implement` runs need your confirmation.
|
|
44
|
+
|
|
45
|
+
### Commands
|
|
46
|
+
|
|
47
|
+
| Command | Purpose |
|
|
48
|
+
|---|---|
|
|
49
|
+
| `/delegate [profile] [--implement] <task>` | One assignment. Without arguments: pickers for profile and mode, an editor for the task |
|
|
50
|
+
| `/debate <question>` | Debate between the profiles of the `debater` role; pi moderates and writes the synthesis |
|
|
51
|
+
| `/plan <goal>` | Planning: draft, critique, revision, your approval, then execution block by block |
|
|
52
|
+
| `/plan resume [id]`, `/plan status`, `/plan abort [id]` | Control a plan |
|
|
53
|
+
| `/orchestrator doctor` | Installed agents, versions against the tested range, auth status, models, configuration |
|
|
54
|
+
| `/orchestrator init` | Write a starter configuration from the detected agents |
|
|
55
|
+
| `/orchestrator config` | Edit profiles and roles interactively |
|
|
56
|
+
| `/orchestrator runs` | Active and recent runs with their artifact paths |
|
|
57
|
+
| `/orchestrator cancel [runId\|all]` | Cancel runs or the active workflow |
|
|
58
|
+
|
|
59
|
+
Commands return immediately and work in the background; results arrive as messages in the session.
|
|
60
|
+
|
|
61
|
+
### Debate
|
|
62
|
+
|
|
63
|
+
Each participant answers the brief independently, then sees the others' answers (anonymized by default) and keeps or revises its position, for up to `debate.maxRounds` rounds or until positions converge. A participant that fails is dropped and the debate continues while at least `debate.minParticipants` remain. The full record is written to the run artifacts; pi writes the synthesis.
|
|
64
|
+
|
|
65
|
+
### Planning and execution
|
|
66
|
+
|
|
67
|
+
1. A planner drafts a plan document; critics review it; the planner revises (up to `planning.maxRevisions` times).
|
|
68
|
+
2. You approve, edit, ask for a revision, keep it as a draft, or discard it. The plan lives in `<project>/.pi/master-orchestrator/plans/<id>/` and is meant to be versioned.
|
|
69
|
+
3. Execution runs the steps of each block with the `implementer` role, then the `reviewer` reviews the block's whole change set, and pi's model gives the verdict with the `plan_verdict` tool (`accepted`, `needs_fix`, `blocked`). `needs_fix` routes the findings back to the step that owns the files, up to `maxFixAttempts` per block.
|
|
70
|
+
4. A failed or interrupted step pauses the plan and offers retry, skip, edit or abort. `/plan resume` continues after a restart, from the first step that is not done.
|
|
71
|
+
|
|
72
|
+
With `planning.execution.commit: "per-block"` each accepted block is committed with its title as the message. The default is `none`: committing is your decision.
|
|
73
|
+
|
|
74
|
+
## Configuration
|
|
75
|
+
|
|
76
|
+
Files, later ones override earlier ones (objects merge key by key, arrays replace):
|
|
77
|
+
|
|
78
|
+
1. Built-in defaults.
|
|
79
|
+
2. User: `~/.pi/agent/master-orchestrator.json`.
|
|
80
|
+
3. Project: `<project>/.pi/master-orchestrator.json`, only when the pi session trusts the project.
|
|
81
|
+
|
|
82
|
+
A project file cannot loosen `approval` and cannot set `agents.*.bin`, `agents.*.env`, `agents.*.extraArgs` or `profiles.*.options`: a repository must not choose which executable runs or with which flags. An invalid file disables delegation and workflows and reports the exact path and error; it never falls back to defaults silently. Comments (`//`, `/* */`) and trailing commas are accepted.
|
|
83
|
+
|
|
84
|
+
```jsonc
|
|
85
|
+
{
|
|
86
|
+
"agents": {
|
|
87
|
+
"codex": {
|
|
88
|
+
"enabled": true, // default: true when detected
|
|
89
|
+
"bin": "codex", // executable name or absolute path
|
|
90
|
+
"env": {}, // environment additions for every run
|
|
91
|
+
"extraArgs": [],
|
|
92
|
+
"allowUntestedVersion": true // run with a warning outside testedVersions
|
|
93
|
+
},
|
|
94
|
+
"grok": { "persistTrust": false } // pass --trust, which persists the grant in grok's configuration
|
|
95
|
+
},
|
|
96
|
+
"profiles": {
|
|
97
|
+
"codex-deep": { "agent": "codex", "model": "<model id>", "effort": "high" },
|
|
98
|
+
"claude-fast": { "agent": "claude", "model": "<model id>", "timeoutMinutes": 15 },
|
|
99
|
+
"dsh-route": { "agent": "dsh", "options": { "patchFile": "/abs/path/route.yml" } }
|
|
100
|
+
},
|
|
101
|
+
"roles": {
|
|
102
|
+
"planner": ["claude-fast", "codex-deep"], // ordered fallback chain
|
|
103
|
+
"critic": ["codex-deep"], // every listed profile takes part
|
|
104
|
+
"implementer": ["codex-deep", "claude-fast"], // ordered fallback chain
|
|
105
|
+
"reviewer": ["claude-fast"], // ordered fallback chain
|
|
106
|
+
"debater": ["codex-deep", "claude-fast"] // every listed profile takes part
|
|
107
|
+
},
|
|
108
|
+
"defaults": { "timeoutMinutes": 30, "maxParallel": 4, "artifactRetentionDays": 14 },
|
|
109
|
+
"approval": {
|
|
110
|
+
"implementFromTool": "auto", // "auto" | "ask"
|
|
111
|
+
"workflowStart": "ask" // "ask" | "auto": confirmation before a debate or plan
|
|
112
|
+
},
|
|
113
|
+
"debate": { "maxRounds": 2, "anonymize": true, "minParticipants": 2 },
|
|
114
|
+
"planning": {
|
|
115
|
+
"maxRevisions": 1,
|
|
116
|
+
"execution": {
|
|
117
|
+
"mode": "auto", // "auto": stop on failure | "block": confirm each block
|
|
118
|
+
"maxFixAttempts": 2,
|
|
119
|
+
"review": "per-block", // "per-block" | "none"
|
|
120
|
+
"commit": "none", // "none" | "per-block" (needs requireCleanTree)
|
|
121
|
+
"requireCleanTree": true
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
"prompts": { "dir": null } // directory with template overrides (<name>.md)
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
Bounds: `timeoutMinutes` 1–720, `maxParallel` 1–16, `artifactRetentionDays` 1–365, `debate.maxRounds` 0–5, `debate.minParticipants` 2–11, `planning.maxRevisions` 0–3, `maxFixAttempts` 0–5.
|
|
129
|
+
|
|
130
|
+
Every detected agent also has an implicit profile named after it, with no model or effort, so the agent uses its own defaults: a fresh install delegates with zero configuration. Roles have no built-in mapping; a workflow that needs an unconfigured role asks you to pick profiles and offers to save the choice. Models and effort levels are passed as configured, never invented.
|
|
131
|
+
|
|
132
|
+
## Supported agents
|
|
133
|
+
|
|
134
|
+
| Agent | Binary | Tested versions | Full-access invocation | Live-checked (2026-11-25) |
|
|
135
|
+
|---|---|---|---|---|
|
|
136
|
+
| Codex | `codex` | >=0.163.0 <0.200.0 | `-a never --sandbox danger-full-access` | 0.172.0: analyze, implement, follow-up, cancel, auth failure |
|
|
137
|
+
| Claude Code | `claude` | >=2.1.305 <2.2.0 | `--permission-mode bypassPermissions`, sandbox disabled through `--settings` | 2.1.328: analyze, implement, follow-up, cancel, auth failure |
|
|
138
|
+
| OpenCode | `opencode` | >=2.1.3 <2.4.0 | `--auto` | 2.3.0: analyze, implement, follow-up, cancel |
|
|
139
|
+
| pi | `pi` | >=1.4.0 <1.7.0 | none needed | 1.6.1: analyze, implement, follow-up, cancel, auth failure |
|
|
140
|
+
| oh-my-pi | `omp` | >=18.11.1 <20.0.0 | `--auto-approve` (a per-run overlay also turns off auto-resume) | 19.1.1: analyze, implement, follow-up, cancel, auth failure |
|
|
141
|
+
| Antigravity | `agy` | >=1.4.4 <1.6.0 | `--dangerously-skip-permissions` | 1.5.17: analyze, implement, follow-up, cancel |
|
|
142
|
+
| Grok Build | `grok` | >=1.0.62 <1.1.0 | `--always-approve`, `GROK_SANDBOX` unset | 1.0.77: analyze, implement, follow-up, cancel, auth failure |
|
|
143
|
+
| Muse Code | `muse` | >=1.4.11 <1.5.0 | `--permission-profile :unrestricted --disable-sandbox` | 1.4.25: auth and billing failures only |
|
|
144
|
+
| DeepSeek Harness | `dsh` | >=0.2.1-rc.3 <0.3.0-0 | `DSH_PERMISSION_MODE=danger-full-access` | 0.2.2-rc.3: analyze, implement, follow-up, cancel, auth failure |
|
|
145
|
+
| Gemini CLI | `gemini` | >=0.51.0 <0.60.0 | `--approval-mode yolo`, `GEMINI_SANDBOX=false` | 0.51.0: auth failure only |
|
|
146
|
+
| Cursor Agent | `cursor-agent` | >=2026.11.22 <2027.0.0 | `--force --sandbox disabled` | 2026.11.22: auth failure only |
|
|
147
|
+
|
|
148
|
+
Every adapter is still `experimental`: the verification pass also asks how a denial, a timeout and a quota failure appear, and those were not observed live for any agent. The recorded runs are in `test/fixtures/<agent>/live-*.json`. `/orchestrator doctor` shows what was checked, and every run on an experimental adapter carries a warning. Outside the tested range an agent still runs, with a warning, unless `allowUntestedVersion` is false.
|
|
149
|
+
|
|
150
|
+
DeepSeek Harness runs its `headless` profile, which has no model flag. A provider declared only in another dsh profile is not visible there: put its `llm-pi-ai` row in a patch file, point the profile's `options.patchFile` at it, and set `model` to `<provider>/<model>`.
|
|
151
|
+
|
|
152
|
+
What still applies inside a run is whatever you configured in the agent itself: deny rules, policies and hooks. A run can end on a denial, and the result reports it.
|
|
153
|
+
|
|
154
|
+
When the pi session trusts the project, adapters pass their agent's per-run trust flag so it loads project rules (`--approve` for pi, `--trust-workspace` for Muse Code, `--skip-trust` for Gemini CLI, `--trust` for Cursor Agent). Grok Build's `--trust` persists the grant in its configuration and is passed only with `agents.grok.persistTrust: true`.
|
|
155
|
+
|
|
156
|
+
## Data handling
|
|
157
|
+
|
|
158
|
+
Each run writes its artifacts under `~/.pi/agent/master-orchestrator/runs/<workspace hash>/<run id>/`: the assignment, the agent's event stream, stderr, the final answer and a `meta.json`. They can contain source code and anything the worker printed. They stay on your machine, nothing is uploaded by this package, and directories older than `defaults.artifactRetentionDays` are removed at session start. What each agent sends to its own provider is governed by that agent and its configuration.
|
|
159
|
+
|
|
160
|
+
No adapter reads credential files or prints environment values; diagnostics name the missing variable or the login command.
|
|
161
|
+
|
|
162
|
+
## Development
|
|
163
|
+
|
|
164
|
+
```bash
|
|
165
|
+
npm install
|
|
166
|
+
npm test # parser, invocation, engine, workflow and extension tests; no tokens spent
|
|
167
|
+
npm run check # tsc --noEmit
|
|
168
|
+
MO_LIVE_AGENTS=codex,claude node --test --experimental-strip-types test/live/smoke.test.ts # spends tokens
|
|
169
|
+
```
|
|
170
|
+
|
|
171
|
+
The specification is in [`docs/SPEC.md`](docs/SPEC.md).
|
|
172
|
+
|
|
173
|
+
## License
|
|
174
|
+
|
|
175
|
+
MIT
|
package/package.json
CHANGED
|
@@ -1,6 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "master-orchestrator",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Pi package that turns pi into an orchestrator of other coding agents: delegation, debate and planning",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"pi-package",
|
|
9
|
+
"pi",
|
|
10
|
+
"coding-agent",
|
|
11
|
+
"orchestrator",
|
|
12
|
+
"codex",
|
|
13
|
+
"claude-code",
|
|
14
|
+
"opencode"
|
|
15
|
+
],
|
|
16
|
+
"files": [
|
|
17
|
+
"src",
|
|
18
|
+
"README.md",
|
|
19
|
+
"CHANGELOG.md",
|
|
20
|
+
"LICENSE"
|
|
21
|
+
],
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=22.18"
|
|
24
|
+
},
|
|
25
|
+
"os": [
|
|
26
|
+
"linux",
|
|
27
|
+
"darwin"
|
|
28
|
+
],
|
|
29
|
+
"scripts": {
|
|
30
|
+
"test": "node --test --experimental-strip-types \"test/**/*.test.ts\"",
|
|
31
|
+
"check": "tsc --noEmit -p ."
|
|
32
|
+
},
|
|
33
|
+
"pi": {
|
|
34
|
+
"extensions": [
|
|
35
|
+
"./src/index.ts"
|
|
36
|
+
],
|
|
37
|
+
"changelogPath": "./CHANGELOG.md"
|
|
38
|
+
},
|
|
39
|
+
"peerDependencies": {
|
|
40
|
+
"@earendil-works/pi-ai": "*",
|
|
41
|
+
"@earendil-works/pi-coding-agent": "*",
|
|
42
|
+
"@earendil-works/pi-tui": "*",
|
|
43
|
+
"typebox": "*"
|
|
44
|
+
},
|
|
45
|
+
"dependencies": {
|
|
46
|
+
"semver": "7.8.5",
|
|
47
|
+
"yaml": "2.9.0"
|
|
48
|
+
},
|
|
49
|
+
"devDependencies": {
|
|
50
|
+
"@earendil-works/pi-ai": "1.6.1",
|
|
51
|
+
"@earendil-works/pi-coding-agent": "1.6.1",
|
|
52
|
+
"@earendil-works/pi-tui": "1.6.1",
|
|
53
|
+
"@types/node": "24.19.4",
|
|
54
|
+
"@types/semver": "7.7.1",
|
|
55
|
+
"typebox": "1.3.27",
|
|
56
|
+
"typescript": "5.9.3"
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import {
|
|
3
|
+
classifyFailureText,
|
|
4
|
+
clip,
|
|
5
|
+
detectByVersion,
|
|
6
|
+
getNumber,
|
|
7
|
+
getPath,
|
|
8
|
+
getString,
|
|
9
|
+
isObject,
|
|
10
|
+
parseJsonAnswer,
|
|
11
|
+
parseJsonLine,
|
|
12
|
+
recordDenied,
|
|
13
|
+
recordSession,
|
|
14
|
+
recordText,
|
|
15
|
+
recordUsage,
|
|
16
|
+
standardFinalize,
|
|
17
|
+
} from "./common.ts";
|
|
18
|
+
import type {
|
|
19
|
+
AdapterOutcome,
|
|
20
|
+
AgentAdapter,
|
|
21
|
+
HostEnv,
|
|
22
|
+
Invocation,
|
|
23
|
+
NormalizedEvent,
|
|
24
|
+
ParserState,
|
|
25
|
+
RawRunResult,
|
|
26
|
+
RunRequest,
|
|
27
|
+
RunStatus,
|
|
28
|
+
} from "./types.ts";
|
|
29
|
+
|
|
30
|
+
const EFFORT_LEVELS = ["low", "medium", "high", "xhigh", "max"] as const;
|
|
31
|
+
|
|
32
|
+
/** Failure texts the shared classifier does not recognize, in status precedence order. */
|
|
33
|
+
const AGY_FAILURE_PATTERNS: Array<{ status: RunStatus; code: string; pattern: RegExp }> = [
|
|
34
|
+
// Go's flag package rejects unknown flags with this message and exit code 2.
|
|
35
|
+
{ status: "unavailable", code: "unsupported_flag", pattern: /flag provided but not defined/i },
|
|
36
|
+
{ status: "unavailable", code: "unknown_agent", pattern: /unknown agent/i },
|
|
37
|
+
{ status: "unavailable", code: "model_unavailable", pattern: /no model configuration is available/i },
|
|
38
|
+
{
|
|
39
|
+
status: "auth_required",
|
|
40
|
+
code: "auth_required",
|
|
41
|
+
pattern: /UNAUTHENTICATED|authentication expired|log back in|sign-in update needed|run '[^']*' to log in/i,
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
status: "quota",
|
|
45
|
+
code: "quota",
|
|
46
|
+
pattern: /credits balance is too low|prepaid balance is insufficient|CAPACITY_EXHAUSTED|spend[- ]cap/i,
|
|
47
|
+
},
|
|
48
|
+
];
|
|
49
|
+
|
|
50
|
+
const PRINT_TIMEOUT = /print timeout after/i;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Antigravity CLI (`agy`) in print mode with stream-json input and output. One NDJSON user event on stdin runs one
|
|
54
|
+
* turn; stdout carries `init`, `step_update` and a terminal `result` event. A denied action ends the turn at once with
|
|
55
|
+
* `status: SUCCESS`, an empty `response` and `denied_actions`, exit 0. Interrupts on SIGINT (exit 1, `status: ERROR`).
|
|
56
|
+
*/
|
|
57
|
+
export const agyAdapter: AgentAdapter = {
|
|
58
|
+
id: "agy",
|
|
59
|
+
displayName: "Antigravity",
|
|
60
|
+
binary: "agy",
|
|
61
|
+
testedVersions: ">=1.4.4 <1.6.0",
|
|
62
|
+
stability: "experimental",
|
|
63
|
+
liveChecked: "1.5.17 on 2026-11-25: analyze, implement, follow-up, cancellation",
|
|
64
|
+
stopSignal: "SIGINT",
|
|
65
|
+
capabilities: {
|
|
66
|
+
resume: true,
|
|
67
|
+
structuredOutput: true,
|
|
68
|
+
listModels: false,
|
|
69
|
+
effortLevels: EFFORT_LEVELS,
|
|
70
|
+
reportsCost: false,
|
|
71
|
+
},
|
|
72
|
+
|
|
73
|
+
detect(env: HostEnv) {
|
|
74
|
+
return detectByVersion(env, this.testedVersions);
|
|
75
|
+
},
|
|
76
|
+
|
|
77
|
+
buildInvocation(req: RunRequest): Invocation {
|
|
78
|
+
const log = join(req.runDir, "agy.log");
|
|
79
|
+
const files = [];
|
|
80
|
+
// No working-directory flag: the workspace is the spawn cwd. Never `--sandbox`.
|
|
81
|
+
const args = [
|
|
82
|
+
"--disable-slash-commands",
|
|
83
|
+
"--input-format", "stream-json",
|
|
84
|
+
"--output-format", "stream-json",
|
|
85
|
+
"--log-file", log,
|
|
86
|
+
"--dangerously-skip-permissions",
|
|
87
|
+
];
|
|
88
|
+
if (req.sessionId) args.push("--conversation", req.sessionId);
|
|
89
|
+
if (req.model) args.push("--model", req.model);
|
|
90
|
+
if (req.effort) args.push("--effort", req.effort);
|
|
91
|
+
if (req.outputSchema) {
|
|
92
|
+
const schemaPath = join(req.runDir, "output-schema.json");
|
|
93
|
+
files.push({ path: schemaPath, content: JSON.stringify(req.outputSchema, null, 2) });
|
|
94
|
+
args.push("--json-schema", schemaPath);
|
|
95
|
+
}
|
|
96
|
+
args.push(...(req.extraArgs ?? []));
|
|
97
|
+
return {
|
|
98
|
+
args,
|
|
99
|
+
cwd: req.workspace,
|
|
100
|
+
env: req.env,
|
|
101
|
+
stdin: `${JSON.stringify({ event: "user", message: { content: req.prompt } })}\n`,
|
|
102
|
+
files,
|
|
103
|
+
outputFiles: { log },
|
|
104
|
+
};
|
|
105
|
+
},
|
|
106
|
+
|
|
107
|
+
parseEvent(line: string, state: ParserState): NormalizedEvent[] {
|
|
108
|
+
const event = parseJsonLine(line);
|
|
109
|
+
if (!event) {
|
|
110
|
+
if (line.trim()) state.nonJsonLines++;
|
|
111
|
+
return [];
|
|
112
|
+
}
|
|
113
|
+
switch (getString(event, "event")) {
|
|
114
|
+
case "init": {
|
|
115
|
+
const events = recordSession(state, getString(event, "conversation_id") ?? getString(event, "init", "conversation_id"));
|
|
116
|
+
const mode = getString(event, "init", "permission_mode");
|
|
117
|
+
if (mode && mode !== "always-proceed") {
|
|
118
|
+
const message = `permission_mode is ${mode}, not always-proceed: tool calls may be denied`;
|
|
119
|
+
state.warnings.push(message);
|
|
120
|
+
events.push({ type: "warning", message });
|
|
121
|
+
}
|
|
122
|
+
return events;
|
|
123
|
+
}
|
|
124
|
+
case "step_update":
|
|
125
|
+
return parseStep(event.step_update, state);
|
|
126
|
+
case "result":
|
|
127
|
+
return parseResult(event.result, state);
|
|
128
|
+
default:
|
|
129
|
+
return [];
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
|
|
133
|
+
finalize(raw: RawRunResult, state: ParserState): AdapterOutcome {
|
|
134
|
+
const timeoutLine = findLine(raw.stderr, PRINT_TIMEOUT);
|
|
135
|
+
let terminal = state.terminal;
|
|
136
|
+
if (!terminal && raw.exitCode === 0) {
|
|
137
|
+
terminal = { ok: false, reason: "the stream ended without a result event" };
|
|
138
|
+
} else if (terminal?.ok && timeoutLine) {
|
|
139
|
+
// Before 1.5.0 an expired --print-timeout returned partial output with status SUCCESS and exit 0.
|
|
140
|
+
terminal = { ok: false, reason: timeoutLine };
|
|
141
|
+
}
|
|
142
|
+
const effective: ParserState = { ...state, terminal, errors: [...state.errors, ...stderrErrors(raw.stderr)] };
|
|
143
|
+
let outcome = standardFinalize(raw, effective, { deniedEndsRun: true });
|
|
144
|
+
const primary = [...effective.errors, terminal?.reason ?? "", raw.stderr].join("\n");
|
|
145
|
+
let refined = refineFailure(outcome, primary);
|
|
146
|
+
if (refined === outcome) refined = refineFailure(outcome, logTail(raw.outputFiles.log));
|
|
147
|
+
outcome = refined;
|
|
148
|
+
if (outcome.status === "failed" && (state.extra.finishedReason === "print_timeout" || timeoutLine)) {
|
|
149
|
+
outcome.reason = `print_timeout: ${clip(timeoutLine ?? "--print-timeout expired; the response is partial", 200)}`;
|
|
150
|
+
}
|
|
151
|
+
const structured = state.extra.structuredOutput ?? parseJsonAnswer(outcome.finalText);
|
|
152
|
+
if (structured !== undefined) outcome.structuredOutput = structured;
|
|
153
|
+
return outcome;
|
|
154
|
+
},
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
function parseStep(step: unknown, state: ParserState): NormalizedEvent[] {
|
|
158
|
+
if (!isObject(step)) return [];
|
|
159
|
+
const stepType = getString(step, "step_type");
|
|
160
|
+
const stepState = getString(step, "state");
|
|
161
|
+
const key = String(getNumber(step, "step_index") ?? "?");
|
|
162
|
+
if (stepType === "agent_response") {
|
|
163
|
+
const buffers = bag<Record<string, string>>(state, "responseText", () => ({}));
|
|
164
|
+
const delta = getString(step, "text_delta");
|
|
165
|
+
if (delta) buffers[key] = (buffers[key] ?? "") + delta;
|
|
166
|
+
if (stepState !== "DONE" && stepState !== "ERROR") return [];
|
|
167
|
+
const text = buffers[key];
|
|
168
|
+
delete buffers[key];
|
|
169
|
+
return recordText(state, text);
|
|
170
|
+
}
|
|
171
|
+
if (stepType === "tool") {
|
|
172
|
+
const seen = bag<Set<string>>(state, "toolSteps", () => new Set());
|
|
173
|
+
if (seen.has(key)) return [];
|
|
174
|
+
seen.add(key);
|
|
175
|
+
const name = getString(step, "tool_name") ?? "tool";
|
|
176
|
+
const detail = firstShortString(getPath(step, ["tool_info", "parameters"]));
|
|
177
|
+
return [{ type: "activity", kind: "tool", summary: clip(detail ? `${name} ${detail}` : name, 100) }];
|
|
178
|
+
}
|
|
179
|
+
return [];
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function parseResult(result: unknown, state: ParserState): NormalizedEvent[] {
|
|
183
|
+
if (!isObject(result)) return [];
|
|
184
|
+
const events = recordSession(state, getString(result, "conversation_id"));
|
|
185
|
+
// The result's response is authoritative: an empty one must not fall back to an earlier intermediate text.
|
|
186
|
+
state.finalText = getString(result, "response") ?? "";
|
|
187
|
+
const denied = Array.isArray(result.denied_actions) ? result.denied_actions : [];
|
|
188
|
+
for (const action of denied) events.push(recordDenied(state, describeDenied(action)));
|
|
189
|
+
|
|
190
|
+
const status = getString(result, "status");
|
|
191
|
+
const finished = getString(result, "finished_reason");
|
|
192
|
+
if (finished) state.extra.finishedReason = finished;
|
|
193
|
+
const error = errorText(result.error);
|
|
194
|
+
if (error) {
|
|
195
|
+
state.errors.push(error);
|
|
196
|
+
events.push({ type: "warning", message: clip(error, 200) });
|
|
197
|
+
}
|
|
198
|
+
if (status === "SUCCESS" && !finished) {
|
|
199
|
+
state.terminal = { ok: true };
|
|
200
|
+
} else {
|
|
201
|
+
const parts = [finished ? `finished_reason ${finished}` : "", status && status !== "SUCCESS" ? `status ${status}` : "", error ?? ""];
|
|
202
|
+
state.terminal = { ok: false, reason: parts.filter(Boolean).join(": ") || "result without a status" };
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const input = getNumber(result, "usage", "input_tokens");
|
|
206
|
+
const output = getNumber(result, "usage", "output_tokens");
|
|
207
|
+
if (input !== undefined || output !== undefined) {
|
|
208
|
+
events.push(recordUsage(state, { inputTokens: input, outputTokens: output }, "replace"));
|
|
209
|
+
}
|
|
210
|
+
if (result.structured_output !== undefined && result.structured_output !== null) {
|
|
211
|
+
state.extra.structuredOutput = result.structured_output;
|
|
212
|
+
}
|
|
213
|
+
return events;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** `denied_actions` entries are objects in current builds; strings are accepted too. */
|
|
217
|
+
function describeDenied(action: unknown): string {
|
|
218
|
+
if (typeof action === "string") return clip(action, 200);
|
|
219
|
+
if (!isObject(action)) return "denied action";
|
|
220
|
+
const name = ["tool_name", "tool", "name", "action"].map((key) => getString(action, key)).find(Boolean);
|
|
221
|
+
const detail = ["command", "path", "target", "reason", "description", "message"]
|
|
222
|
+
.map((key) => getString(action, key))
|
|
223
|
+
.find(Boolean);
|
|
224
|
+
if (!name && !detail) return clip(JSON.stringify(action), 200);
|
|
225
|
+
return clip([name, detail].filter(Boolean).join(": "), 200);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** API failures mid-turn print `AGY_ERROR: {"short_error": "..."}` on stderr and exit 3. */
|
|
229
|
+
function stderrErrors(stderr: string): string[] {
|
|
230
|
+
const messages: string[] = [];
|
|
231
|
+
for (const line of stderr.split(/\r?\n/)) {
|
|
232
|
+
const match = line.match(/AGY_ERROR:\s*(\{.*\})\s*$/);
|
|
233
|
+
if (!match) continue;
|
|
234
|
+
const parsed = parseJsonLine(match[1]);
|
|
235
|
+
const message = getString(parsed, "short_error") ?? getString(parsed, "message");
|
|
236
|
+
if (message) messages.push(message);
|
|
237
|
+
}
|
|
238
|
+
return messages;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
function errorText(value: unknown): string | undefined {
|
|
242
|
+
if (typeof value === "string") return value.trim() || undefined;
|
|
243
|
+
if (!isObject(value)) return undefined;
|
|
244
|
+
return getString(value, "message") ?? getString(value, "short_error") ?? JSON.stringify(value);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/** Second classification pass for failures the shared patterns left as `failed` (or as an answerless denial). */
|
|
248
|
+
function refineFailure(outcome: AdapterOutcome, text: string): AdapterOutcome {
|
|
249
|
+
const unclassified = outcome.status === "failed" || (outcome.status === "denied" && !outcome.finalText);
|
|
250
|
+
if (!unclassified || !text.trim()) return outcome;
|
|
251
|
+
const lines = text.split(/\r?\n/).filter((line) => line.trim());
|
|
252
|
+
for (const { status, code, pattern } of AGY_FAILURE_PATTERNS) {
|
|
253
|
+
const line = lines.find((candidate) => pattern.test(candidate));
|
|
254
|
+
if (line) return { ...outcome, status, reason: `${code}: ${clip(line, 200)}` };
|
|
255
|
+
}
|
|
256
|
+
const cls = classifyFailureText(text);
|
|
257
|
+
return cls ? { ...outcome, status: cls.status, reason: `${cls.code}: ${cls.line}` } : outcome;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Last error-looking lines of the CLI log, used only when stdout and stderr do not explain a failure. */
|
|
261
|
+
function logTail(log: string | undefined): string {
|
|
262
|
+
if (!log) return "";
|
|
263
|
+
return log
|
|
264
|
+
.split(/\r?\n/)
|
|
265
|
+
.filter((line) => /error|fatal|fail/i.test(line))
|
|
266
|
+
.slice(-30)
|
|
267
|
+
.join("\n");
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
function findLine(text: string, pattern: RegExp): string | undefined {
|
|
271
|
+
return text.split(/\r?\n/).find((line) => pattern.test(line))?.trim();
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function firstShortString(value: unknown): string | undefined {
|
|
275
|
+
if (!isObject(value)) return undefined;
|
|
276
|
+
for (const candidate of Object.values(value)) {
|
|
277
|
+
if (typeof candidate === "string" && candidate.trim()) return clip(candidate, 80);
|
|
278
|
+
}
|
|
279
|
+
return undefined;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
function bag<T>(state: ParserState, key: string, init: () => T): T {
|
|
283
|
+
if (state.extra[key] === undefined) state.extra[key] = init();
|
|
284
|
+
return state.extra[key] as T;
|
|
285
|
+
}
|