@itsaplan/runner 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.
Files changed (4) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +284 -0
  3. package/dist/cli.js +240 -0
  4. package/package.json +56 -0
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 VIBE DEV SPACE LLC
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,284 @@
1
+ # @itsaplan/runner
2
+
3
+ [It's a Plan](https://itsaplan.dev) is self-hosted, open-source project management and
4
+ issue tracking where AI agents work like teammates: they have a role, permissions, and
5
+ issues assigned to them.
6
+
7
+ This package runs the tasks of one such agent on your own machine. It takes one queued
8
+ task at a time, passes it to a command you choose, and sends the result back. The
9
+ command is yours: Claude Code, Codex, a shell script, anything that reads stdin.
10
+
11
+ ## Quick start
12
+
13
+ **1. Get the agent's key.** In your project: Settings, AI agents, create one of kind
14
+ External. The key is shown once, at creation.
15
+
16
+ **2. Write `itsaplan-runner.json`** in the folder you want the agent to work in:
17
+
18
+ ```json
19
+ {
20
+ "url": "http://localhost:3000",
21
+ "apiKey": "the key you just copied",
22
+ "command": "claude -p"
23
+ }
24
+ ```
25
+
26
+ **3. Start it:**
27
+
28
+ ```bash
29
+ npx -y @itsaplan/runner
30
+ ```
31
+
32
+ The agent goes online in the project within a few seconds. Delegate an issue to it or
33
+ mention it in a comment, and the task lands in your terminal.
34
+
35
+ `Ctrl-C` stops the runner once the tasks in flight are done. Anything still queued
36
+ waits for the next runner.
37
+
38
+ ## Settings
39
+
40
+ The runner reads `./itsaplan-runner.json`, or the path you give it as an argument or in
41
+ `ITSAPLAN_RUNNER_CONFIG`:
42
+
43
+ ```bash
44
+ npx -y @itsaplan/runner /path/to/config.json
45
+ ```
46
+
47
+ Environment variables win over the file:
48
+
49
+ | Field | Environment variable | Default | What it does |
50
+ | ---------------- | --------------------------- | ------------------ | ----------------------------------- |
51
+ | `url` | `ITSAPLAN_URL` | required | Your Itsaplan instance |
52
+ | `apiKey` | `ITSAPLAN_API_KEY` | required | The external agent's key |
53
+ | `command` | `ITSAPLAN_COMMAND` | required | The command that handles one task |
54
+ | `cwd` | `ITSAPLAN_CWD` | where you start it | Working directory for the command |
55
+ | `env` | | `{}` | Extra variables for the command |
56
+ | `concurrency` | `ITSAPLAN_CONCURRENCY` | `1` | How many tasks may run at once |
57
+ | `pollIntervalMs` | `ITSAPLAN_POLL_INTERVAL_MS` | `3000` | Wait after an empty queue, at least 1000 |
58
+ | `timeoutMs` | `ITSAPLAN_TIMEOUT_MS` | `1800000` | When a task is killed as stuck |
59
+
60
+ Which is how the key stays out of any file:
61
+
62
+ ```bash
63
+ export ITSAPLAN_API_KEY=…
64
+ npx -y @itsaplan/runner
65
+ ```
66
+
67
+ ## What your command receives
68
+
69
+ The task text arrives on **stdin**. The rest of the run arrives in the environment:
70
+
71
+ | Variable | What it holds |
72
+ | ------------------------ | ------------------------------------------------------ |
73
+ | `ITSAPLAN_URL` | the instance the task came from |
74
+ | `ITSAPLAN_API_KEY` | the agent's key, for the API and the MCP server |
75
+ | `ITSAPLAN_RUN_ID` | the run's id |
76
+ | `ITSAPLAN_TRIGGER` | `mention`, `delegation`, `schedule`, or `manual` |
77
+ | `ITSAPLAN_SYSTEM_PROMPT` | context about the run, for commands that take a system prompt |
78
+ | `ITSAPLAN_ISSUE` | the issue key, e.g. `MKT-42` (empty when there is none) |
79
+ | `ITSAPLAN_ISSUE_ID` | the issue's numeric id |
80
+
81
+ The task on stdin is written by the server: what happened, what to do, and to post the
82
+ result as a comment on the issue. The agent reads everything else through the MCP
83
+ server at `$ITSAPLAN_URL/mcp`, with `$ITSAPLAN_API_KEY` as a bearer token, acting as
84
+ its own user under its role. Enable MCP in the project settings.
85
+
86
+ Exit code `0` is a success, anything else a failure with the tail of stderr as the
87
+ error. Stdout becomes the run's output either way.
88
+
89
+ ## Claude Code
90
+
91
+ `mcp.json`, next to the runner config:
92
+
93
+ ```json
94
+ {
95
+ "mcpServers": {
96
+ "itsaplan": {
97
+ "type": "http",
98
+ "url": "http://localhost:3000/mcp",
99
+ "headers": { "Authorization": "Bearer ${ITSAPLAN_API_KEY}" }
100
+ }
101
+ }
102
+ }
103
+ ```
104
+
105
+ `itsaplan-runner.json`:
106
+
107
+ ```json
108
+ {
109
+ "url": "http://localhost:3000",
110
+ "apiKey": "the key you copied on creation",
111
+ "command": "claude -p --mcp-config ./mcp.json --append-system-prompt \"$ITSAPLAN_SYSTEM_PROMPT\" --permission-mode auto --output-format text",
112
+ "cwd": "/Users/me/work/my-repo"
113
+ }
114
+ ```
115
+
116
+ - `--mcp-config` adds this instance's server on top of what the machine already has,
117
+ so your own MCP servers, skills, and memory stay in the run. Drop it if the server is
118
+ already in the repository's `.mcp.json` or was added with `claude mcp add`.
119
+ - `--permission-mode auto` covers permissions: nobody is there to answer a prompt, so a
120
+ classifier reviews each action instead, MCP tool calls included.
121
+
122
+ ## Codex
123
+
124
+ Codex reads its MCP servers from `~/.codex/config.toml`, and `bearer_token_env_var`
125
+ takes the key from the environment the runner already sets:
126
+
127
+ ```toml
128
+ [mcp_servers.itsaplan]
129
+ url = "http://localhost:3000/mcp"
130
+ bearer_token_env_var = "ITSAPLAN_API_KEY"
131
+ ```
132
+
133
+ `itsaplan-runner.json`:
134
+
135
+ ```json
136
+ {
137
+ "url": "http://localhost:3000",
138
+ "apiKey": "the key you copied on creation",
139
+ "command": "printf '%s\\n\\n%s' \"$ITSAPLAN_SYSTEM_PROMPT\" \"$(cat)\" | codex exec --sandbox workspace-write --skip-git-repo-check -",
140
+ "cwd": "/path/to/working-dir"
141
+ }
142
+ ```
143
+
144
+ - Codex has no system-prompt flag, so `printf` puts the system prompt in front of the
145
+ task, and the trailing `-` tells Codex to read all of it from stdin.
146
+ - `--sandbox workspace-write` bounds what it may change: writes stay inside the working
147
+ directory.
148
+ - `--skip-git-repo-check` is only needed when that directory is not a git repository.
149
+
150
+ ## Gemini CLI
151
+
152
+ `.gemini/settings.json` in the working directory. Gemini expands `$VARS` in it, so the
153
+ key comes from the environment, and `trust` skips the tool confirmation a headless run
154
+ cannot answer:
155
+
156
+ ```json
157
+ {
158
+ "mcpServers": {
159
+ "itsaplan": {
160
+ "httpUrl": "http://localhost:3000/mcp",
161
+ "headers": { "Authorization": "Bearer $ITSAPLAN_API_KEY" },
162
+ "trust": true
163
+ }
164
+ }
165
+ }
166
+ ```
167
+
168
+ `itsaplan-runner.json`:
169
+
170
+ ```json
171
+ {
172
+ "url": "http://localhost:3000",
173
+ "apiKey": "the key you copied on creation",
174
+ "command": "printf '%s\\n\\n%s' \"$ITSAPLAN_SYSTEM_PROMPT\" \"$(cat)\" | gemini --approval-mode yolo",
175
+ "cwd": "/path/to/working-dir"
176
+ }
177
+ ```
178
+
179
+ - Gemini has no system-prompt flag either, and reads the piped prompt on stdin, so the
180
+ command is shaped like the Codex one.
181
+ - `--approval-mode yolo` approves every tool call, which a headless run needs.
182
+ `auto_edit` is the narrower option: file edits only.
183
+
184
+ ## GitHub Copilot CLI
185
+
186
+ `.mcp.json` in the working directory. Copilot's headers take no variable
187
+ interpolation, so the key goes in as it stands:
188
+
189
+ ```json
190
+ {
191
+ "mcpServers": {
192
+ "itsaplan": {
193
+ "type": "http",
194
+ "url": "http://localhost:3000/mcp",
195
+ "headers": { "Authorization": "Bearer the-agent-key" },
196
+ "tools": ["*"]
197
+ }
198
+ }
199
+ }
200
+ ```
201
+
202
+ `itsaplan-runner.json`:
203
+
204
+ ```json
205
+ {
206
+ "url": "http://localhost:3000",
207
+ "apiKey": "the key you copied on creation",
208
+ "command": "copilot -p \"$(printf '%s\\n\\n%s' \"$ITSAPLAN_SYSTEM_PROMPT\" \"$(cat)\")\" --allow-all-tools --no-ask-user",
209
+ "cwd": "/path/to/working-dir"
210
+ }
211
+ ```
212
+
213
+ - Copilot takes neither a system-prompt flag nor a prompt on stdin, so both go in as
214
+ one `-p` argument.
215
+ - `--allow-all-tools` and `--no-ask-user` keep it from waiting for an approval it
216
+ cannot get.
217
+
218
+ ## opencode
219
+
220
+ `opencode.json` in the working directory. opencode interpolates `{env:VAR}`, so the key
221
+ stays out of the file:
222
+
223
+ ```json
224
+ {
225
+ "$schema": "https://opencode.ai/config.json",
226
+ "model": "anthropic/claude-sonnet-5",
227
+ "mcp": {
228
+ "itsaplan": {
229
+ "type": "remote",
230
+ "url": "http://localhost:3000/mcp",
231
+ "enabled": true,
232
+ "headers": { "Authorization": "Bearer {env:ITSAPLAN_API_KEY}" }
233
+ }
234
+ }
235
+ }
236
+ ```
237
+
238
+ `itsaplan-runner.json`:
239
+
240
+ ```json
241
+ {
242
+ "url": "http://localhost:3000",
243
+ "apiKey": "the key you copied on creation",
244
+ "command": "opencode run \"$(printf '%s\\n\\n%s' \"$ITSAPLAN_SYSTEM_PROMPT\" \"$(cat)\")\"",
245
+ "cwd": "/path/to/working-dir"
246
+ }
247
+ ```
248
+
249
+ - `opencode run` takes the prompt as an argument and never reads stdin, so the task is
250
+ passed the same way as with Copilot.
251
+ - Pin `model` as `provider/model`. opencode is provider agnostic, and without that key
252
+ a run falls back to whatever model was picked interactively last. `opencode auth
253
+ login` is what makes a provider available in the first place.
254
+
255
+ ## Requirements
256
+
257
+ Node 20 or newer, an It's a Plan instance on 0.10.0 or newer, and an **external** agent in
258
+ your project. Its API key is what the runner authenticates with.
259
+
260
+ The coding agent you point the runner at has to be installed and signed in on the same
261
+ machine — the runner starts it as you and cannot sign in for you.
262
+
263
+ On macOS and Linux there is nothing else to it. The runner hands every task to `sh -c`,
264
+ so the commands in this file are POSIX shell.
265
+
266
+ Windows needs WSL2, because `cmd.exe` and PowerShell have no `sh`:
267
+
268
+ ```powershell
269
+ wsl --install # installs Ubuntu, then reboot
270
+ ```
271
+
272
+ Everything after that happens inside WSL: Node, the coding agent, the config file, and
273
+ `npx -y @itsaplan/runner`. Two things worth knowing there:
274
+
275
+ - Keep the working directory in the WSL file system (`~/work/repo`) rather than under
276
+ `/mnt/c/...`. File access across that boundary is slow enough to notice on a repo.
277
+ - An instance running on the Windows host is reachable from WSL2 as
278
+ `http://localhost:3000`.
279
+
280
+ ## License
281
+
282
+ Copyright © 2026 VIBE DEV SPACE LLC.
283
+
284
+ [Apache-2.0](LICENSE).
package/dist/cli.js ADDED
@@ -0,0 +1,240 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli.ts
4
+ import { setTimeout as sleep } from "node:timers/promises";
5
+
6
+ // src/client.ts
7
+ var REQUEST_TIMEOUT_MS = 30000;
8
+
9
+ class RequestError extends Error {
10
+ status;
11
+ constructor(status, message) {
12
+ super(message);
13
+ this.status = status;
14
+ }
15
+ }
16
+
17
+ class Client {
18
+ config;
19
+ constructor(config) {
20
+ this.config = config;
21
+ }
22
+ async post(path, body) {
23
+ const res = await fetch(`${this.config.url}${path}`, {
24
+ method: "POST",
25
+ headers: {
26
+ "x-api-key": this.config.apiKey,
27
+ ...body === undefined ? {} : { "content-type": "application/json" }
28
+ },
29
+ body: body === undefined ? undefined : JSON.stringify(body),
30
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
31
+ });
32
+ if (!res.ok) {
33
+ throw new RequestError(res.status, `POST ${path} failed with ${res.status}: ${(await res.text()).slice(0, 200)}`);
34
+ }
35
+ return res;
36
+ }
37
+ async claim() {
38
+ const res = await this.post("/agent-runs/claim");
39
+ const body = await res.json();
40
+ return body.run;
41
+ }
42
+ async heartbeat(runId) {
43
+ await this.post(`/agent-runs/${runId}/heartbeat`);
44
+ }
45
+ async report(runId, result) {
46
+ await this.post(`/agent-runs/${runId}/result`, result);
47
+ }
48
+ }
49
+
50
+ // src/config.ts
51
+ import { readFile } from "node:fs/promises";
52
+ var DEFAULTS = {
53
+ concurrency: 1,
54
+ pollIntervalMs: 3000,
55
+ timeoutMs: 30 * 60 * 1000
56
+ };
57
+ var MIN_POLL_INTERVAL_MS = 1000;
58
+ function intFrom(value, fallback) {
59
+ const parsed = typeof value === "string" ? Number.parseInt(value, 10) : value;
60
+ return typeof parsed === "number" && Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
61
+ }
62
+ function required(value, field) {
63
+ const text = typeof value === "string" ? value.trim() : "";
64
+ if (!text)
65
+ throw new Error(`${field} is required — set it in the config file or the environment`);
66
+ return text;
67
+ }
68
+ async function readConfigFile(path) {
69
+ let text;
70
+ try {
71
+ text = await readFile(path, "utf8");
72
+ } catch (err) {
73
+ if (err.code === "ENOENT")
74
+ return {};
75
+ throw err;
76
+ }
77
+ try {
78
+ return JSON.parse(text);
79
+ } catch {
80
+ throw new Error(`${path} is not valid JSON`);
81
+ }
82
+ }
83
+ async function loadConfig(path) {
84
+ const raw = await readConfigFile(path);
85
+ const env = process.env;
86
+ return {
87
+ url: required(env.ITSAPLAN_URL ?? raw.url, "url").replace(/\/+$/, ""),
88
+ apiKey: required(env.ITSAPLAN_API_KEY ?? raw.apiKey, "apiKey"),
89
+ command: required(env.ITSAPLAN_COMMAND ?? raw.command, "command"),
90
+ cwd: (env.ITSAPLAN_CWD ?? raw.cwd)?.replace(/^~/, env.HOME ?? "~"),
91
+ env: raw.env ?? {},
92
+ concurrency: intFrom(env.ITSAPLAN_CONCURRENCY ?? raw.concurrency, DEFAULTS.concurrency),
93
+ pollIntervalMs: Math.max(intFrom(env.ITSAPLAN_POLL_INTERVAL_MS ?? raw.pollIntervalMs, DEFAULTS.pollIntervalMs), MIN_POLL_INTERVAL_MS),
94
+ timeoutMs: intFrom(env.ITSAPLAN_TIMEOUT_MS ?? raw.timeoutMs, DEFAULTS.timeoutMs)
95
+ };
96
+ }
97
+
98
+ // src/execute.ts
99
+ import { spawn } from "node:child_process";
100
+ var OUTPUT_LIMIT = 8000;
101
+ var ERROR_LIMIT = 400;
102
+ function tail(text, limit) {
103
+ return text.length <= limit ? text : `…${text.slice(-limit)}`;
104
+ }
105
+ function childEnv(config, run) {
106
+ return {
107
+ ...process.env,
108
+ ...config.env,
109
+ ITSAPLAN_URL: config.url,
110
+ ITSAPLAN_API_KEY: config.apiKey,
111
+ ITSAPLAN_RUN_ID: String(run.id),
112
+ ITSAPLAN_TRIGGER: run.trigger,
113
+ ITSAPLAN_SYSTEM_PROMPT: run.systemPrompt,
114
+ ITSAPLAN_ISSUE: run.issueIdentifier ?? "",
115
+ ITSAPLAN_ISSUE_ID: run.issueId == null ? "" : String(run.issueId)
116
+ };
117
+ }
118
+ function killGroup(pid) {
119
+ try {
120
+ process.kill(-pid, "SIGKILL");
121
+ } catch {}
122
+ }
123
+ async function execute(config, run) {
124
+ const child = spawn("sh", ["-c", config.command], {
125
+ cwd: config.cwd,
126
+ env: childEnv(config, run),
127
+ detached: true
128
+ });
129
+ let timedOut = false;
130
+ const timer = setTimeout(() => {
131
+ timedOut = true;
132
+ if (child.pid !== undefined)
133
+ killGroup(child.pid);
134
+ }, config.timeoutMs);
135
+ let stdout = "";
136
+ let stderr = "";
137
+ child.stdout.setEncoding("utf8");
138
+ child.stderr.setEncoding("utf8");
139
+ child.stdout.on("data", (chunk) => {
140
+ stdout = tail(stdout + chunk, OUTPUT_LIMIT);
141
+ });
142
+ child.stderr.on("data", (chunk) => {
143
+ stderr = tail(stderr + chunk, ERROR_LIMIT);
144
+ });
145
+ child.stdin.on("error", () => {});
146
+ child.stdin.end(run.prompt);
147
+ const exited = new Promise((resolve, reject) => {
148
+ child.on("error", reject);
149
+ child.on("close", (exitCode, exitSignal) => resolve({ code: exitCode, signal: exitSignal }));
150
+ });
151
+ let code;
152
+ let signal;
153
+ try {
154
+ ({ code, signal } = await exited);
155
+ } finally {
156
+ clearTimeout(timer);
157
+ }
158
+ const output = stdout.trim();
159
+ if (code === 0)
160
+ return { status: "success", output };
161
+ if (timedOut)
162
+ return { status: "failed", output, error: `Timed out after ${config.timeoutMs}ms` };
163
+ return {
164
+ status: "failed",
165
+ output,
166
+ error: stderr.trim() || (signal ? `Command killed by ${signal}` : `Command exited with ${code}`)
167
+ };
168
+ }
169
+
170
+ // src/cli.ts
171
+ var HEARTBEAT_MS = 60000;
172
+ function log(message) {
173
+ console.log(`[itsaplan-runner] ${message}`);
174
+ }
175
+ async function withHeartbeat(client, runId, work) {
176
+ const timer = setInterval(() => {
177
+ client.heartbeat(runId).catch((err) => log(`heartbeat failed: ${String(err)}`));
178
+ }, HEARTBEAT_MS);
179
+ try {
180
+ return await work;
181
+ } finally {
182
+ clearInterval(timer);
183
+ }
184
+ }
185
+ async function handle(config, client, run) {
186
+ const label = run.issueIdentifier ?? `run ${run.id}`;
187
+ log(`${label}: started (${run.trigger})`);
188
+ try {
189
+ const outcome = await withHeartbeat(client, run.id, execute(config, run));
190
+ await client.report(run.id, outcome);
191
+ log(`${label}: ${outcome.status}${outcome.error ? ` — ${outcome.error}` : ""}`);
192
+ } catch (err) {
193
+ const message = err instanceof Error ? err.message : String(err);
194
+ log(`${label}: runner error — ${message}`);
195
+ await client.report(run.id, { status: "failed", error: message }).catch(() => {});
196
+ }
197
+ }
198
+ async function main() {
199
+ const configPath = process.argv[2] ?? process.env.ITSAPLAN_RUNNER_CONFIG ?? "./itsaplan-runner.json";
200
+ const config = await loadConfig(configPath);
201
+ const client = new Client(config);
202
+ const active = new Set;
203
+ let stopping = false;
204
+ for (const signal of ["SIGINT", "SIGTERM"]) {
205
+ process.on(signal, () => {
206
+ if (stopping) {
207
+ log("quitting now — the commands in flight keep running, their runs are retried");
208
+ process.exit(1);
209
+ }
210
+ stopping = true;
211
+ log("stopping — finishing the tasks in flight, press again to quit now");
212
+ });
213
+ }
214
+ log(`polling ${config.url} every ${config.pollIntervalMs}ms, up to ${config.concurrency} at once`);
215
+ while (!stopping) {
216
+ if (active.size >= config.concurrency) {
217
+ await Promise.race(active);
218
+ continue;
219
+ }
220
+ let run = null;
221
+ try {
222
+ run = await client.claim();
223
+ } catch (err) {
224
+ if (err instanceof RequestError && (err.status === 401 || err.status === 403))
225
+ throw err;
226
+ log(`claim failed: ${String(err)}`);
227
+ }
228
+ if (!run) {
229
+ await sleep(config.pollIntervalMs);
230
+ continue;
231
+ }
232
+ const task = handle(config, client, run).finally(() => active.delete(task));
233
+ active.add(task);
234
+ }
235
+ await Promise.all(active);
236
+ }
237
+ main().catch((err) => {
238
+ console.error(`[itsaplan-runner] ${err instanceof Error ? err.message : String(err)}`);
239
+ process.exit(1);
240
+ });
package/package.json ADDED
@@ -0,0 +1,56 @@
1
+ {
2
+ "name": "@itsaplan/runner",
3
+ "version": "0.1.0",
4
+ "description": "Runs an Itsaplan external agent's queued tasks on your own machine",
5
+ "keywords": [
6
+ "itsaplan",
7
+ "ai-agents",
8
+ "agentic",
9
+ "agent",
10
+ "runner",
11
+ "cli",
12
+ "self-hosted",
13
+ "open-source",
14
+ "project-management",
15
+ "issue-tracker",
16
+ "jira-alternative",
17
+ "linear-alternative",
18
+ "claude-code",
19
+ "codex",
20
+ "gemini-cli",
21
+ "opencode"
22
+ ],
23
+ "homepage": "https://github.com/croffasia/itsaplan/tree/main/packages/runner#readme",
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "git+https://github.com/croffasia/itsaplan.git",
27
+ "directory": "packages/runner"
28
+ },
29
+ "bugs": "https://github.com/croffasia/itsaplan/issues",
30
+ "license": "Apache-2.0",
31
+ "type": "module",
32
+ "bin": {
33
+ "itsaplan-runner": "./dist/cli.js"
34
+ },
35
+ "files": [
36
+ "dist"
37
+ ],
38
+ "engines": {
39
+ "node": ">=20"
40
+ },
41
+ "publishConfig": {
42
+ "access": "public"
43
+ },
44
+ "scripts": {
45
+ "build": "bun build src/cli.ts --target=node --outfile dist/cli.js",
46
+ "prepublishOnly": "bun run build",
47
+ "lint": "eslint .",
48
+ "typecheck": "tsc --noEmit"
49
+ },
50
+ "devDependencies": {
51
+ "@repo/eslint-config": "workspace:*",
52
+ "@types/node": "^26.2.0",
53
+ "eslint": "^9.39.0",
54
+ "typescript": "^6.0.3"
55
+ }
56
+ }