@mergeline/agent 0.0.0-stage → 0.4.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 +21 -0
- package/README.md +125 -2
- package/dist/cli.js +396 -0
- package/dist/credentials.js +96 -0
- package/dist/index.js +5 -0
- package/dist/init.js +225 -0
- package/dist/mcp.js +133 -0
- package/dist/pb.js +25 -0
- package/dist/repo.js +86 -0
- package/dist/service.js +316 -0
- package/dist/watch.js +243 -0
- package/kit/claude-settings.json +39 -0
- package/kit/done.md +22 -0
- package/kit/pick.md +34 -0
- package/kit/rules.md +31 -0
- package/package.json +51 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 frontender-ua
|
|
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,126 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mergeline/agent
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The agent's side of a [Mergeline](https://mergeline.app) board: the board
|
|
4
|
+
MCP server and the `board` CLI. An agent needs only the board's address and the key a human got when
|
|
5
|
+
adding the agent on the board; it works in its own repository, with its
|
|
6
|
+
own AI account. The board never sees the AI account.
|
|
7
|
+
|
|
8
|
+
## Set up with your AI assistant
|
|
9
|
+
|
|
10
|
+
The board's "Connect" window has a **Copy setup prompt** button: paste the
|
|
11
|
+
prompt into Claude Code (or Codex) opened in your repository, and the
|
|
12
|
+
assistant runs the steps below for you, explains each one and asks before
|
|
13
|
+
committing. Nothing technical is needed from the person.
|
|
14
|
+
|
|
15
|
+
## By hand
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
npx -y @mergeline/agent init --claude --url https://acme.mergeline.app # once per repository; commit what it adds
|
|
19
|
+
npx -y @mergeline/agent login fe-1 --url https://acme.mergeline.app --key ab_... # once per agent and machine
|
|
20
|
+
npx -y @mergeline/agent start fe-1 # every session; then /pick
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
`init --url` writes the board's address into `.mergeline.json` (no
|
|
24
|
+
secrets; commit it), so in that repository, and in the agents' worktrees of
|
|
25
|
+
it, the commands below use that board. The file also holds the kit's
|
|
26
|
+
version, which every claim sends with the package's: when the board expects
|
|
27
|
+
a newer kit, the claim's answer says to run
|
|
28
|
+
`npx -y @mergeline/agent@latest init --claude` again. `login` checks the key with the
|
|
29
|
+
board and saves it in `~/.config/mergeline/credentials.json` (readable only
|
|
30
|
+
by you, outside any repository), per board and agent: `fe-1` on two boards
|
|
31
|
+
is two saved keys. In a repository with `.mergeline.json`, `--url` can be
|
|
32
|
+
left out. Several agents can be saved and work from the same repository:
|
|
33
|
+
`board start qa-1` in another terminal. `board agents` lists them with their
|
|
34
|
+
boards, `board logout <name>` forgets one (`--url <board>` when the name is
|
|
35
|
+
saved for several). `board start <name> -- codex` starts another tool the
|
|
36
|
+
same way; `--agent <name>` makes any command act as a saved agent. The board
|
|
37
|
+
in use is `BOARD_URL` when it is set, else the repository's
|
|
38
|
+
`.mergeline.json`.
|
|
39
|
+
|
|
40
|
+
Environment variables still work and win over saved keys:
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
export BOARD_URL=https://board.example.com
|
|
44
|
+
export BOARD_AGENT_KEY=ab_... # shown once when the agent is added
|
|
45
|
+
|
|
46
|
+
npx @mergeline/agent whoami # check the connection
|
|
47
|
+
npx @mergeline/agent mcp # MCP server on stdio, for tools that speak MCP
|
|
48
|
+
npx @mergeline/agent claim # or the same calls as commands
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
Install the agent kit into the work repository (run it in the repository):
|
|
52
|
+
|
|
53
|
+
```sh
|
|
54
|
+
npx @mergeline/agent init # AGENTS.md: the board rules (Codex and others read it)
|
|
55
|
+
npx @mergeline/agent init --url <board> # also .mergeline.json: this repository's board
|
|
56
|
+
npx @mergeline/agent init --claude # also CLAUDE.md, /pick, /done, .claude/settings.json, .mcp.json
|
|
57
|
+
npx @mergeline/agent init --codex # also /prompts:pick and /prompts:done in ~/.codex/prompts
|
|
58
|
+
npx @mergeline/agent init --dry-run # show what would change
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
`init` adds one section between `mergeline` markers to `AGENTS.md` and
|
|
62
|
+
`CLAUDE.md` and leaves the rest of each file alone; running it again updates
|
|
63
|
+
only that section. It writes `/pick` and `/done` only where no file of that
|
|
64
|
+
name exists or where the file still carries the kit's marker line, adds its
|
|
65
|
+
permissions to `.claude/settings.json` without removing any (plus the
|
|
66
|
+
repository's own package manager: install and its test, lint and typecheck
|
|
67
|
+
scripts, from the lockfile and `package.json`), and adds a `board` server to
|
|
68
|
+
`.mcp.json` that reads `${BOARD_URL}` and `${BOARD_AGENT_KEY}` from the
|
|
69
|
+
environment, or else the key `login` saved: the key is never written to the
|
|
70
|
+
repository.
|
|
71
|
+
|
|
72
|
+
MCP config (Claude Code `--mcp-config`, Codex, other MCP clients):
|
|
73
|
+
|
|
74
|
+
```json
|
|
75
|
+
{
|
|
76
|
+
"mcpServers": {
|
|
77
|
+
"board": {
|
|
78
|
+
"command": "npx",
|
|
79
|
+
"args": ["-y", "@mergeline/agent", "mcp"],
|
|
80
|
+
"env": { "BOARD_URL": "https://board.example.com", "BOARD_AGENT_KEY": "ab_..." }
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Run the agent whenever its queue has work (on your machine, with your AI
|
|
87
|
+
account; one run at a time):
|
|
88
|
+
|
|
89
|
+
```sh
|
|
90
|
+
board watch --agent fe-1 --usage-from claude-json -- \
|
|
91
|
+
claude -p "/pick" --permission-mode auto --output-format json \
|
|
92
|
+
--setting-sources project,local # Claude Code, headless, with cost
|
|
93
|
+
board watch -- codex exec "/prompts:pick" # Codex CLI
|
|
94
|
+
board watch --follow --interval 60 -- <command> # keep waiting for new tickets
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
With `--usage-from claude-json` (and `claude -p --output-format json`), the
|
|
98
|
+
watcher reads each run's tokens and cost from Claude Code's final JSON and
|
|
99
|
+
reports them on the ticket the run worked on; `board usage <ticket> --usage
|
|
100
|
+
<json>` does the same by hand. The board stores usage only for agents whose
|
|
101
|
+
"Report usage" is on.
|
|
102
|
+
|
|
103
|
+
Unattended, nobody answers a permission prompt: run it in a repository
|
|
104
|
+
Claude Code trusts (run `claude` there once), and keep personal `ask` rules
|
|
105
|
+
out with `--setting-sources project,local`, or an `ask` rule for `git push`
|
|
106
|
+
stalls the agent at its first push.
|
|
107
|
+
|
|
108
|
+
It stops when the queue is empty (unless `--follow`), after `--max-runs`
|
|
109
|
+
(default 10), after 2 runs that changed nothing in the queue, or after 3
|
|
110
|
+
failed runs in a row. One watcher per agent and machine.
|
|
111
|
+
|
|
112
|
+
A board that is paused (asleep until a person opens it; it answers HTTP 503
|
|
113
|
+
with `{"code": "board_paused"}`) is not a failure: tools and commands say
|
|
114
|
+
"board paused: ...", and `watch` waits, checking every `--interval`, then
|
|
115
|
+
goes on.
|
|
116
|
+
|
|
117
|
+
Commands: `init`, `watch`, `whoami`, `list`, `claim`, `heartbeat <ticket> [note]`,
|
|
118
|
+
`log <ticket> <plan|progress|warn> <text>`, `record-spec <ticket> <sha>`,
|
|
119
|
+
`ask <ticket> <question>`, `submit <ticket> <pr-url> <summary> [--usage <json>]`,
|
|
120
|
+
`release <ticket> <reason> [--usage <json>]`. `board help` shows the details.
|
|
121
|
+
Results are JSON on stdout; a failure is one line on stderr and exit code 1.
|
|
122
|
+
|
|
123
|
+
The board ties a claimed ticket to one session of the agent. `board claim`
|
|
124
|
+
starts a new session and saves its id under `BOARD_STATE_DIR` (default
|
|
125
|
+
`~/.local/state/mergeline`) for the following commands; set
|
|
126
|
+
`BOARD_SESSION` to manage it yourself.
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,396 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// `board`: the agent's side of the board from the command line.
|
|
3
|
+
//
|
|
4
|
+
// board mcp run the MCP server on stdio (for tools that speak MCP)
|
|
5
|
+
// board <command> [args] the same calls as the MCP tools, one per run
|
|
6
|
+
//
|
|
7
|
+
// Connection: BOARD_URL and BOARD_AGENT_KEY (or BOARD_AGENT_EMAIL and
|
|
8
|
+
// BOARD_AGENT_PASSWORD), as for the MCP server; without them, a key saved by
|
|
9
|
+
// `board login <name>` (credentials.ts) for the board in use (BOARD_URL, or
|
|
10
|
+
// the repository's .mergeline.json written by `board init --url`: repo.ts),
|
|
11
|
+
// picked with --agent <name> or BOARD_AGENT, or the only one saved. `board start <name>` runs the agent's
|
|
12
|
+
// tool (claude by default) with that agent's address and key. Results are JSON on stdout;
|
|
13
|
+
// a failure is one plain line on stderr and exit code 1.
|
|
14
|
+
//
|
|
15
|
+
// Sessions: the board ties a claimed ticket to the session that claimed it,
|
|
16
|
+
// so another session of the same agent cannot work it at the same time. An
|
|
17
|
+
// MCP server is one session for its whole life; a CLI run lasts one call. So
|
|
18
|
+
// `board claim` starts a new session and, when it gets a ticket, saves the
|
|
19
|
+
// session id in a state file (BOARD_STATE_DIR, default
|
|
20
|
+
// ~/.local/state/mergeline); later commands reuse it. BOARD_SESSION, when
|
|
21
|
+
// set, is used instead and nothing is saved.
|
|
22
|
+
import { spawn } from "node:child_process";
|
|
23
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
24
|
+
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
25
|
+
import { homedir } from "node:os";
|
|
26
|
+
import { join, resolve } from "node:path";
|
|
27
|
+
import { init } from "./init.js";
|
|
28
|
+
import { runMcpServer } from "./mcp.js";
|
|
29
|
+
import { watch } from "./watch.js";
|
|
30
|
+
import { forgetAgent, pickSaved, saveAgent, savedAgents } from "./credentials.js";
|
|
31
|
+
import { agentCredentialsFromEnv } from "./pb.js";
|
|
32
|
+
import { boardInContext, normalizeBoardUrl, REPO_FILE } from "./repo.js";
|
|
33
|
+
import { BoardError, TicketService } from "./service.js";
|
|
34
|
+
const HELP = `board: a Mergeline board from the command line
|
|
35
|
+
|
|
36
|
+
Usage:
|
|
37
|
+
board init [--url <board>] [--claude] [--codex] [--dir <repo>] [--dry-run] [--no-npx]
|
|
38
|
+
install the agent kit into a work repository:
|
|
39
|
+
a section in AGENTS.md; with --claude also CLAUDE.md,
|
|
40
|
+
/pick and /done, .claude/settings.json, .mcp.json;
|
|
41
|
+
with --codex the prompts in ~/.codex/prompts. --url: the
|
|
42
|
+
board's address in .mergeline.json (no secrets; commit it),
|
|
43
|
+
so the commands below pick that board in this repository.
|
|
44
|
+
Never overwrites what it did not write. --no-npx: MCP
|
|
45
|
+
configs run "board mcp" (package installed globally).
|
|
46
|
+
board login <name> [--url <board>] --key <key>
|
|
47
|
+
check the key with the board and save it on this machine
|
|
48
|
+
(~/.config/mergeline, outside any repository), per board and
|
|
49
|
+
agent; --url defaults to the repository's board. Key "-"
|
|
50
|
+
reads it from stdin. Once per agent and machine
|
|
51
|
+
board start [<name>] [-- <command...>] start the agent's tool (default: claude) with that agent's
|
|
52
|
+
board address and key; then /pick. Name optional when
|
|
53
|
+
only one agent is saved for the board in use
|
|
54
|
+
board agents agents saved on this machine, with their boards
|
|
55
|
+
board logout <name> [--url <board>] forget an agent's saved key
|
|
56
|
+
board mcp run the board MCP server on stdio
|
|
57
|
+
board watch [--follow] [--interval <s>] [--max-runs <n>] [--usage-from claude-json] -- <agent command...>
|
|
58
|
+
run the agent command whenever this agent's queue has
|
|
59
|
+
work, one run at a time; stops when the queue is empty
|
|
60
|
+
(--follow: keeps checking every --interval, default 30s),
|
|
61
|
+
after --max-runs (default 10), after 2 runs that changed
|
|
62
|
+
nothing or 3 failed runs in a row. --usage-from claude-json
|
|
63
|
+
reports each run's tokens and cost from Claude Code's JSON
|
|
64
|
+
board whoami check the connection and show the agent
|
|
65
|
+
board list tickets assigned to you that are not done
|
|
66
|
+
board claim take your next ticket (or {"ticket": null})
|
|
67
|
+
board heartbeat <ticket> [note] keep the lease alive; a note is logged
|
|
68
|
+
board log <ticket> <plan|progress|warn> <text>
|
|
69
|
+
board record-spec <ticket> <sha> the spec commit you read
|
|
70
|
+
board ask <ticket> <question> ask the human; then stop working on it
|
|
71
|
+
board submit <ticket> <pr-url> <summary> [--usage <json>]
|
|
72
|
+
board release <ticket> <reason> [--usage <json>]
|
|
73
|
+
board usage <ticket> --usage <json> what the work on a ticket cost, after the fact
|
|
74
|
+
(stored only if the agent reports usage on the board)
|
|
75
|
+
|
|
76
|
+
Every command takes --agent <name> to act as a saved agent. The board in use is BOARD_URL,
|
|
77
|
+
else the repository's .mergeline.json (board init --url); a saved agent is looked up there.
|
|
78
|
+
A text argument of "-" is read from stdin (for a multi-line plan).
|
|
79
|
+
--usage is optional JSON: {"input_tokens":..,"output_tokens":..,"cost":..,"currency":"USD","source":".."}
|
|
80
|
+
|
|
81
|
+
Environment:
|
|
82
|
+
BOARD_URL the board (default: the repository's .mergeline.json, else http://127.0.0.1:8090)
|
|
83
|
+
BOARD_AGENT_KEY the agent key shown when a human added the agent
|
|
84
|
+
BOARD_AGENT a saved agent's name, used when BOARD_AGENT_KEY is not set
|
|
85
|
+
BOARD_CONFIG_DIR where board login saves keys (default ~/.config/mergeline)
|
|
86
|
+
BOARD_SESSION optional session id; otherwise claim saves one in BOARD_STATE_DIR
|
|
87
|
+
BOARD_STATE_DIR default ~/.local/state/mergeline
|
|
88
|
+
`;
|
|
89
|
+
class UsageError extends Error {
|
|
90
|
+
}
|
|
91
|
+
const COMMANDS = ["watch", "usage", "whoami", "list", "claim", "heartbeat", "log", "record-spec", "ask", "submit", "release"];
|
|
92
|
+
function stateFile(creds) {
|
|
93
|
+
const dir = process.env.BOARD_STATE_DIR || join(process.env.XDG_STATE_HOME || join(homedir(), ".local", "state"), "mergeline");
|
|
94
|
+
const who = "key" in creds ? creds.key.split("_").slice(0, 2).join("_") : creds.email;
|
|
95
|
+
const id = createHash("sha256").update(`${creds.url}\n${who}`).digest("hex").slice(0, 16);
|
|
96
|
+
return join(dir, `session-${id}.json`);
|
|
97
|
+
}
|
|
98
|
+
function readSession(file) {
|
|
99
|
+
try {
|
|
100
|
+
return String(JSON.parse(readFileSync(file, "utf8")).session || "");
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
return "";
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function saveSession(file, session, ticket) {
|
|
107
|
+
mkdirSync(join(file, ".."), { recursive: true, mode: 0o700 });
|
|
108
|
+
writeFileSync(file, JSON.stringify({ session, ticket, at: new Date().toISOString() }) + "\n", { mode: 0o600 });
|
|
109
|
+
}
|
|
110
|
+
function readStdin() {
|
|
111
|
+
return readFileSync(0, "utf8").replace(/\s+$/, "");
|
|
112
|
+
}
|
|
113
|
+
function text(arg, name) {
|
|
114
|
+
if (arg === undefined || arg === "")
|
|
115
|
+
throw new UsageError(`${name} is required`);
|
|
116
|
+
return arg === "-" ? readStdin() : arg;
|
|
117
|
+
}
|
|
118
|
+
/** Splits --usage <json> out of the arguments. */
|
|
119
|
+
function takeUsage(args) {
|
|
120
|
+
const i = args.indexOf("--usage");
|
|
121
|
+
if (i < 0)
|
|
122
|
+
return { rest: args };
|
|
123
|
+
const raw = args[i + 1];
|
|
124
|
+
if (!raw)
|
|
125
|
+
throw new UsageError("--usage needs a JSON object");
|
|
126
|
+
let usage;
|
|
127
|
+
try {
|
|
128
|
+
usage = JSON.parse(raw);
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
throw new UsageError("--usage must be JSON, e.g. '{\"input_tokens\":1200,\"output_tokens\":300}'");
|
|
132
|
+
}
|
|
133
|
+
return { rest: [...args.slice(0, i), ...args.slice(i + 2)], usage };
|
|
134
|
+
}
|
|
135
|
+
function runInit(args) {
|
|
136
|
+
const known = new Set(["--claude", "--codex", "--dry-run", "--dir", "--no-npx", "--url"]);
|
|
137
|
+
const unknown = args.filter((a, i) => a.startsWith("--") && !known.has(a) && args[i - 1] !== "--dir" && args[i - 1] !== "--url");
|
|
138
|
+
if (unknown.length)
|
|
139
|
+
throw new UsageError(`unknown option ${unknown[0]}; run board help`);
|
|
140
|
+
const di = args.indexOf("--dir");
|
|
141
|
+
if (di >= 0 && !args[di + 1])
|
|
142
|
+
throw new UsageError("--dir needs a path");
|
|
143
|
+
const dir = resolve(di >= 0 ? args[di + 1] : process.cwd());
|
|
144
|
+
if (!existsSync(dir))
|
|
145
|
+
throw new UsageError(`${dir} does not exist`);
|
|
146
|
+
const rawUrl = option(args, "--url");
|
|
147
|
+
let url;
|
|
148
|
+
try {
|
|
149
|
+
url = rawUrl === undefined ? undefined : normalizeBoardUrl(rawUrl);
|
|
150
|
+
}
|
|
151
|
+
catch (err) {
|
|
152
|
+
throw new UsageError(err instanceof Error ? err.message : String(err));
|
|
153
|
+
}
|
|
154
|
+
const dryRun = args.includes("--dry-run");
|
|
155
|
+
const result = init({
|
|
156
|
+
dir,
|
|
157
|
+
url,
|
|
158
|
+
claude: args.includes("--claude"),
|
|
159
|
+
codex: args.includes("--codex"),
|
|
160
|
+
dryRun,
|
|
161
|
+
noNpx: args.includes("--no-npx"),
|
|
162
|
+
});
|
|
163
|
+
const out = process.stdout;
|
|
164
|
+
out.write(`${dryRun ? "Would change" : "Agent kit"} in ${dir}:\n`);
|
|
165
|
+
for (const a of result.actions)
|
|
166
|
+
out.write(` ${a.kind.padEnd(9)} ${a.path}${a.note ? ` (${a.note})` : ""}\n`);
|
|
167
|
+
if (result.projectCommands.length) {
|
|
168
|
+
out.write(`\nClaude Code may run this project's commands without asking: ${result.projectCommands.join(", ")}\n`);
|
|
169
|
+
}
|
|
170
|
+
if (result.codexConfig) {
|
|
171
|
+
out.write("\nAdd the board MCP server to ~/.codex/config.toml (init does not edit it):\n\n");
|
|
172
|
+
out.write(result.codexConfig + "\n");
|
|
173
|
+
}
|
|
174
|
+
out.write("\nThen, once per agent and machine, save its key (shown when the agent was added on the board):\n" +
|
|
175
|
+
` board login <agent name> ${result.board ? "" : "--url <board address> "}--key <key>` +
|
|
176
|
+
(result.board ? ` (the board: ${result.board}, from ${REPO_FILE})` : "") + "\n" +
|
|
177
|
+
"and start each session with: board start <agent name>" + (args.includes("--codex") ? " -- codex" : "") + "\n" +
|
|
178
|
+
"Commit AGENTS.md" + (args.includes("--claude") ? ", CLAUDE.md, .claude/, .mcp.json" : "") + `, ${REPO_FILE}` +
|
|
179
|
+
" so every checkout has the kit; the key is not in any of them.\n");
|
|
180
|
+
if (args.includes("--claude")) {
|
|
181
|
+
out.write("Claude Code applies .claude/settings.json (the board's permissions) only in a trusted folder:\n" +
|
|
182
|
+
"run `claude` here once and accept the trust dialog, also before `board watch` in a fresh clone.\n");
|
|
183
|
+
}
|
|
184
|
+
return undefined;
|
|
185
|
+
}
|
|
186
|
+
/** --agent <name> anywhere before "--": act as that saved agent. */
|
|
187
|
+
function takeAgent(argv) {
|
|
188
|
+
const end = argv.indexOf("--") < 0 ? argv.length : argv.indexOf("--");
|
|
189
|
+
const i = argv.slice(0, end).indexOf("--agent");
|
|
190
|
+
if (i < 0)
|
|
191
|
+
return argv;
|
|
192
|
+
const name = argv[i + 1];
|
|
193
|
+
if (!name || name.startsWith("-"))
|
|
194
|
+
throw new UsageError("--agent needs a saved agent's name");
|
|
195
|
+
const saved = pickSaved(name, boardInContext());
|
|
196
|
+
process.env.BOARD_URL = saved.url;
|
|
197
|
+
process.env.BOARD_AGENT_KEY = saved.key;
|
|
198
|
+
process.env.BOARD_AGENT = name;
|
|
199
|
+
return [...argv.slice(0, i), ...argv.slice(i + 2)];
|
|
200
|
+
}
|
|
201
|
+
function option(args, flag) {
|
|
202
|
+
const i = args.indexOf(flag);
|
|
203
|
+
if (i < 0)
|
|
204
|
+
return undefined;
|
|
205
|
+
const v = args[i + 1];
|
|
206
|
+
if (!v || (v.startsWith("--") && v !== "-"))
|
|
207
|
+
throw new UsageError(`${flag} needs a value`);
|
|
208
|
+
return v;
|
|
209
|
+
}
|
|
210
|
+
async function runLogin(args) {
|
|
211
|
+
const name = args[0];
|
|
212
|
+
if (!name || name.startsWith("-"))
|
|
213
|
+
throw new UsageError("board login needs the agent's name: board login <name> --url <board> --key <key>");
|
|
214
|
+
const given = option(args, "--url");
|
|
215
|
+
let url;
|
|
216
|
+
try {
|
|
217
|
+
url = given === undefined ? boardInContext()?.url : normalizeBoardUrl(given);
|
|
218
|
+
}
|
|
219
|
+
catch (err) {
|
|
220
|
+
throw new UsageError(err instanceof Error ? err.message : String(err));
|
|
221
|
+
}
|
|
222
|
+
let key = option(args, "--key");
|
|
223
|
+
if (!url)
|
|
224
|
+
throw new UsageError(`--url is required: the board's address, as shown on the board (or run it in a repository with ${REPO_FILE}: board init --url <board>)`);
|
|
225
|
+
if (!key)
|
|
226
|
+
throw new UsageError("--key is required: the key shown when the agent was added (or - to read it from stdin)");
|
|
227
|
+
if (key === "-")
|
|
228
|
+
key = readStdin();
|
|
229
|
+
const b = new TicketService({ url, key: key.trim() });
|
|
230
|
+
await b.login();
|
|
231
|
+
if (b.agentName !== name)
|
|
232
|
+
throw new BoardError(`this key belongs to agent ${b.agentName}, not ${name}`);
|
|
233
|
+
const file = saveAgent(name, url, key.trim());
|
|
234
|
+
return { agent: name, board: url, saved: file };
|
|
235
|
+
}
|
|
236
|
+
async function runStart(args) {
|
|
237
|
+
const sep = args.indexOf("--");
|
|
238
|
+
const head = sep < 0 ? args : args.slice(0, sep);
|
|
239
|
+
const command = sep < 0 ? ["claude"] : args.slice(sep + 1);
|
|
240
|
+
if (command.length === 0)
|
|
241
|
+
throw new UsageError("board start needs a command after --, or none for claude");
|
|
242
|
+
const board = boardInContext();
|
|
243
|
+
const saved = pickSaved(head[0], board);
|
|
244
|
+
if (!saved) {
|
|
245
|
+
throw new UsageError(`no agent saved on this machine${board ? ` for ${board.url}` : ""}: run board login <name> --url ${board?.url ?? "<board>"} --key <key> first`);
|
|
246
|
+
}
|
|
247
|
+
const b = new TicketService({ url: saved.url, key: saved.key });
|
|
248
|
+
await b.login();
|
|
249
|
+
process.stderr.write(`board: ${command[0]} as ${saved.name} on ${saved.url}${command[0] === "claude" ? "; type /pick to take a ticket" : ""}\n`);
|
|
250
|
+
const child = spawn(command[0], command.slice(1), {
|
|
251
|
+
stdio: "inherit",
|
|
252
|
+
env: { ...process.env, BOARD_URL: saved.url, BOARD_AGENT_KEY: saved.key, BOARD_AGENT: saved.name },
|
|
253
|
+
});
|
|
254
|
+
const code = await new Promise((res) => {
|
|
255
|
+
child.on("exit", (c, signal) => res(c ?? (signal ? 1 : 0)));
|
|
256
|
+
child.on("error", (err) => {
|
|
257
|
+
process.stderr.write(`board: could not start ${command[0]}: ${err.message}\n`);
|
|
258
|
+
res(127);
|
|
259
|
+
});
|
|
260
|
+
});
|
|
261
|
+
process.exitCode = code;
|
|
262
|
+
return undefined;
|
|
263
|
+
}
|
|
264
|
+
async function main(argvIn) {
|
|
265
|
+
const argv = takeAgent(argvIn);
|
|
266
|
+
const [command, ...rawArgs] = argv;
|
|
267
|
+
if (!command || command === "help" || command === "--help" || command === "-h") {
|
|
268
|
+
process.stdout.write(HELP);
|
|
269
|
+
return undefined;
|
|
270
|
+
}
|
|
271
|
+
if (command === "mcp") {
|
|
272
|
+
await runMcpServer();
|
|
273
|
+
return undefined;
|
|
274
|
+
}
|
|
275
|
+
if (command === "init")
|
|
276
|
+
return runInit(rawArgs);
|
|
277
|
+
if (command === "login")
|
|
278
|
+
return runLogin(rawArgs);
|
|
279
|
+
if (command === "start")
|
|
280
|
+
return runStart(rawArgs);
|
|
281
|
+
if (command === "agents") {
|
|
282
|
+
return savedAgents().map((a) => ({ name: a.name, board: a.url, key: `••••${a.key.slice(-4)}`, saved: a.saved }));
|
|
283
|
+
}
|
|
284
|
+
if (command === "logout") {
|
|
285
|
+
const name = rawArgs[0];
|
|
286
|
+
if (!name || name.startsWith("-"))
|
|
287
|
+
throw new UsageError("board logout needs the agent's name: board logout <name> [--url <board>]");
|
|
288
|
+
const given = option(rawArgs, "--url");
|
|
289
|
+
const board = given === undefined ? boardInContext() : { url: normalizeBoardUrl(given), from: "--url" };
|
|
290
|
+
const named = savedAgents().filter((a) => a.name === name && (!board || a.url === board.url));
|
|
291
|
+
if (named.length > 1) {
|
|
292
|
+
throw new UsageError(`agent ${name} is saved for several boards (${named.map((a) => a.url).join(", ")}); say which: board logout ${name} --url <board>`);
|
|
293
|
+
}
|
|
294
|
+
return { agent: name, board: named[0]?.url ?? board?.url ?? null, forgotten: named.length === 1 && forgetAgent(name, named[0].url) };
|
|
295
|
+
}
|
|
296
|
+
if (!COMMANDS.includes(command))
|
|
297
|
+
throw new UsageError(`unknown command "${command}"; run board help`);
|
|
298
|
+
const creds = agentCredentialsFromEnv();
|
|
299
|
+
const file = stateFile(creds);
|
|
300
|
+
const fixed = process.env.BOARD_SESSION?.trim();
|
|
301
|
+
const { rest: args, usage } = takeUsage(rawArgs);
|
|
302
|
+
const board = (session) => new TicketService(creds, session);
|
|
303
|
+
const current = () => board(fixed || readSession(file) || undefined);
|
|
304
|
+
const done = (result) => {
|
|
305
|
+
if (!fixed)
|
|
306
|
+
rmSync(file, { force: true });
|
|
307
|
+
return result;
|
|
308
|
+
};
|
|
309
|
+
switch (command) {
|
|
310
|
+
case "watch": {
|
|
311
|
+
const sep = rawArgs.indexOf("--");
|
|
312
|
+
const opts = sep < 0 ? rawArgs : rawArgs.slice(0, sep);
|
|
313
|
+
const agentCommand = sep < 0 ? [] : rawArgs.slice(sep + 1);
|
|
314
|
+
if (agentCommand.length === 0) {
|
|
315
|
+
throw new UsageError('board watch needs the agent command after --, e.g. board watch -- claude -p "/pick"');
|
|
316
|
+
}
|
|
317
|
+
const num = (flag, fallback) => {
|
|
318
|
+
const i = opts.indexOf(flag);
|
|
319
|
+
if (i < 0)
|
|
320
|
+
return fallback;
|
|
321
|
+
const n = Number(opts[i + 1]);
|
|
322
|
+
if (!Number.isInteger(n) || n < 1)
|
|
323
|
+
throw new UsageError(`${flag} needs a whole number, 1 or more`);
|
|
324
|
+
return n;
|
|
325
|
+
};
|
|
326
|
+
const known = new Set(["--follow", "--interval", "--max-runs", "--usage-from"]);
|
|
327
|
+
const valued = ["--interval", "--max-runs", "--usage-from"];
|
|
328
|
+
const unknown = opts.find((a, i) => a.startsWith("--") && !known.has(a) && !valued.includes(opts[i - 1] ?? ""));
|
|
329
|
+
const ui = opts.indexOf("--usage-from");
|
|
330
|
+
const usageFrom = ui < 0 ? undefined : opts[ui + 1];
|
|
331
|
+
if (ui >= 0 && usageFrom !== "claude-json")
|
|
332
|
+
throw new UsageError("--usage-from supports claude-json (claude -p --output-format json)");
|
|
333
|
+
if (unknown)
|
|
334
|
+
throw new UsageError(`unknown option ${unknown}; run board help`);
|
|
335
|
+
const code = await watch({
|
|
336
|
+
board: board(fixed || undefined),
|
|
337
|
+
command: agentCommand,
|
|
338
|
+
maxRuns: num("--max-runs", 10),
|
|
339
|
+
follow: opts.includes("--follow"),
|
|
340
|
+
intervalSec: num("--interval", 30),
|
|
341
|
+
lockFile: file.replace(/session-([^/\\]+)\.json$/, "watch-$1.lock"),
|
|
342
|
+
log: (line) => process.stderr.write(`board watch: ${line}\n`),
|
|
343
|
+
usageFrom: usageFrom,
|
|
344
|
+
});
|
|
345
|
+
process.exitCode = code;
|
|
346
|
+
return undefined;
|
|
347
|
+
}
|
|
348
|
+
case "whoami": {
|
|
349
|
+
const b = current();
|
|
350
|
+
await b.login();
|
|
351
|
+
return { agent: b.agentName, id: b.agentId, board: creds.url, session: fixed || readSession(file) || null };
|
|
352
|
+
}
|
|
353
|
+
case "list":
|
|
354
|
+
return current().listMine();
|
|
355
|
+
case "claim": {
|
|
356
|
+
// A new session for every claim: after a crash it resumes the ticket
|
|
357
|
+
// (once the old session has gone quiet); while another session of the
|
|
358
|
+
// agent is alive it is refused, and the saved session stays theirs.
|
|
359
|
+
const session = fixed || randomUUID();
|
|
360
|
+
const result = await board(session).claim();
|
|
361
|
+
if (result.ticket && !fixed)
|
|
362
|
+
saveSession(file, session, result.ticket.id);
|
|
363
|
+
return result;
|
|
364
|
+
}
|
|
365
|
+
case "heartbeat":
|
|
366
|
+
return current().heartbeat(text(args[0], "ticket"), args[1] === undefined ? undefined : text(args[1], "note"));
|
|
367
|
+
case "log": {
|
|
368
|
+
const kind = args[1];
|
|
369
|
+
if (!["plan", "progress", "warn"].includes(kind))
|
|
370
|
+
throw new UsageError("kind must be plan, progress or warn");
|
|
371
|
+
return current().logEvent(text(args[0], "ticket"), kind, text(args[2], "text"));
|
|
372
|
+
}
|
|
373
|
+
case "record-spec":
|
|
374
|
+
return current().recordSpec(text(args[0], "ticket"), text(args[1], "sha"));
|
|
375
|
+
case "ask":
|
|
376
|
+
return done(await current().askHuman(text(args[0], "ticket"), text(args[1], "question")));
|
|
377
|
+
case "submit":
|
|
378
|
+
return done(await current().submitForReview(text(args[0], "ticket"), text(args[1], "pr-url"), text(args[2], "summary"), usage));
|
|
379
|
+
case "usage":
|
|
380
|
+
if (!usage)
|
|
381
|
+
throw new UsageError("board usage needs --usage <json>");
|
|
382
|
+
return current().reportUsage(text(args[0], "ticket"), usage);
|
|
383
|
+
case "release":
|
|
384
|
+
return done(await current().release(text(args[0], "ticket"), text(args[1], "reason"), usage));
|
|
385
|
+
default:
|
|
386
|
+
throw new UsageError(`unknown command "${command}"; run board help`);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
main(process.argv.slice(2)).then((result) => {
|
|
390
|
+
if (result !== undefined)
|
|
391
|
+
process.stdout.write(JSON.stringify(result, null, 2) + "\n");
|
|
392
|
+
}, (err) => {
|
|
393
|
+
const message = err instanceof BoardError || err instanceof UsageError || err instanceof Error ? err.message : String(err);
|
|
394
|
+
process.stderr.write(`board: ${message.split("\n")[0]}\n`);
|
|
395
|
+
process.exit(err instanceof UsageError ? 2 : 1);
|
|
396
|
+
});
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// Agent keys saved on this machine by `board login <name>`, so a person runs
|
|
2
|
+
// `board start <name>` instead of exporting BOARD_URL and BOARD_AGENT_KEY in
|
|
3
|
+
// every session. One file per user, outside any repository, readable only by
|
|
4
|
+
// its owner; one entry per board and agent name, so one person can work with
|
|
5
|
+
// several boards, and several agents can work from the same repository.
|
|
6
|
+
//
|
|
7
|
+
// $BOARD_CONFIG_DIR/credentials.json (default ~/.config/mergeline)
|
|
8
|
+
// { "boards": { "<board url>": { "<agent name>": { "key": "ab_...", "saved": "<ISO time>" } } } }
|
|
9
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
10
|
+
import { homedir } from "node:os";
|
|
11
|
+
import { join } from "node:path";
|
|
12
|
+
import { normalizeBoardUrl } from "./repo.js";
|
|
13
|
+
export function credentialsFile(env = process.env) {
|
|
14
|
+
const dir = env.BOARD_CONFIG_DIR || join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "mergeline");
|
|
15
|
+
return join(dir, "credentials.json");
|
|
16
|
+
}
|
|
17
|
+
function read(file) {
|
|
18
|
+
if (!existsSync(file))
|
|
19
|
+
return { boards: {} };
|
|
20
|
+
try {
|
|
21
|
+
const data = JSON.parse(readFileSync(file, "utf8"));
|
|
22
|
+
return { boards: data && typeof data.boards === "object" && data.boards ? data.boards : {} };
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
throw new Error(`${file} is not valid JSON; fix or remove it`);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function write(file, store) {
|
|
29
|
+
mkdirSync(join(file, ".."), { recursive: true, mode: 0o700 });
|
|
30
|
+
writeFileSync(file, JSON.stringify(store, null, 2) + "\n", { mode: 0o600 });
|
|
31
|
+
chmodSync(file, 0o600);
|
|
32
|
+
}
|
|
33
|
+
/** Every saved agent, board by board. */
|
|
34
|
+
export function savedAgents(env = process.env) {
|
|
35
|
+
const { boards } = read(credentialsFile(env));
|
|
36
|
+
return Object.entries(boards).flatMap(([url, agents]) => Object.entries(agents ?? {}).map(([name, a]) => ({ name, url, key: a.key, saved: a.saved })));
|
|
37
|
+
}
|
|
38
|
+
export function saveAgent(name, url, key, env = process.env) {
|
|
39
|
+
const file = credentialsFile(env);
|
|
40
|
+
const store = read(file);
|
|
41
|
+
const board = normalizeBoardUrl(url);
|
|
42
|
+
store.boards[board] = { ...store.boards[board], [name]: { key, saved: new Date().toISOString() } };
|
|
43
|
+
write(file, store);
|
|
44
|
+
return file;
|
|
45
|
+
}
|
|
46
|
+
export function forgetAgent(name, url, env = process.env) {
|
|
47
|
+
const file = credentialsFile(env);
|
|
48
|
+
const store = read(file);
|
|
49
|
+
const board = normalizeBoardUrl(url);
|
|
50
|
+
if (!store.boards[board]?.[name])
|
|
51
|
+
return false;
|
|
52
|
+
delete store.boards[board][name];
|
|
53
|
+
if (Object.keys(store.boards[board]).length === 0)
|
|
54
|
+
delete store.boards[board];
|
|
55
|
+
write(file, store);
|
|
56
|
+
return true;
|
|
57
|
+
}
|
|
58
|
+
/** "fe-1, qa-1", or "fe-1 on <board>, ..." when they are on different boards. */
|
|
59
|
+
function labels(agents) {
|
|
60
|
+
const boards = new Set(agents.map((a) => a.url)).size;
|
|
61
|
+
return agents.map((a) => (boards > 1 ? `${a.name} on ${a.url}` : a.name)).join(", ");
|
|
62
|
+
}
|
|
63
|
+
const where = (board) => (board.from === "BOARD_URL" ? board.url : `${board.url} (from ${board.from})`);
|
|
64
|
+
/**
|
|
65
|
+
* The saved agent to use on the board in use (BOARD_URL or the repository's
|
|
66
|
+
* .mergeline.json), or on any board when none is: the one named, else the
|
|
67
|
+
* only one saved. Null when nothing is saved there; an error when the name is
|
|
68
|
+
* not saved there, is saved for several boards and none is in use, or several
|
|
69
|
+
* agents are saved and none is named.
|
|
70
|
+
*/
|
|
71
|
+
export function pickSaved(name, board, env = process.env) {
|
|
72
|
+
const all = savedAgents(env);
|
|
73
|
+
const here = board ? all.filter((a) => a.url === board.url) : all;
|
|
74
|
+
if (name) {
|
|
75
|
+
const named = here.filter((a) => a.name === name);
|
|
76
|
+
if (named.length === 1)
|
|
77
|
+
return named[0];
|
|
78
|
+
if (named.length > 1) {
|
|
79
|
+
throw new Error(`agent ${name} is saved for several boards (${named.map((a) => a.url).join(", ")}); ` +
|
|
80
|
+
"run it in a repository set up with board init --url <board>, or set BOARD_URL=<board>");
|
|
81
|
+
}
|
|
82
|
+
if (board) {
|
|
83
|
+
const elsewhere = all.filter((a) => a.name === name).map((a) => a.url);
|
|
84
|
+
throw new Error(`no saved key for agent ${name} on ${where(board)}` +
|
|
85
|
+
`${elsewhere.length ? ` (it is saved for ${elsewhere.join(", ")})` : ""}; run board login ${name} --url ${board.url} --key <key>`);
|
|
86
|
+
}
|
|
87
|
+
throw new Error(`no saved key for agent ${name}${all.length ? ` (saved: ${labels(all)})` : ""}; run board login ${name} --url <board> --key <key>`);
|
|
88
|
+
}
|
|
89
|
+
if (here.length === 0)
|
|
90
|
+
return null;
|
|
91
|
+
if (here.length > 1) {
|
|
92
|
+
throw new Error(`several agents are saved ${board ? `for ${where(board)}` : "here"} (${labels(here)}); ` +
|
|
93
|
+
"say which: board start <name>, or BOARD_AGENT=<name>");
|
|
94
|
+
}
|
|
95
|
+
return here[0];
|
|
96
|
+
}
|