pacework 0.0.0-stage → 1.0.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.
@@ -0,0 +1,3475 @@
1
+ #!/usr/bin/env node
2
+ // Must run before anything reads the environment (see the file).
3
+ import "../lib/legacy-env.mjs"
4
+ /**
5
+ * pacework-runner-ctl — CLI for the pacework local agent runner
6
+ *
7
+ * Commands: login, logout, connect, start, stop, status, logs,
8
+ * use, config, doctor, jobs
9
+ */
10
+
11
+ import fs from "node:fs"
12
+ import os from "node:os"
13
+ import path from "node:path"
14
+ import process from "node:process"
15
+ import readline from "node:readline"
16
+ import { spawn, execFileSync, execSync } from "node:child_process"
17
+ import { fileURLToPath } from "node:url"
18
+ import { agentSecretsFrom, detectSetupCommand } from "../lib/environment.mjs"
19
+ import {
20
+ PACEWORK_DIR,
21
+ STATE_DIR,
22
+ PID_FILE,
23
+ LOG_FILE,
24
+ CMD_FILE,
25
+ JOBS_FILE,
26
+ CONFIG_FILE,
27
+ ensureStateDir,
28
+ readPid,
29
+ isRunning,
30
+ clearPid,
31
+ readConfig,
32
+ writeConfig,
33
+ } from "../lib/control-state.mjs"
34
+ import {
35
+ installService,
36
+ installStableCopy,
37
+ installCommandLauncher,
38
+ isServiceInstalled,
39
+ isServiceRunning,
40
+ privacyProtectedFolder,
41
+ serviceKind,
42
+ startService,
43
+ stopService,
44
+ uninstallService,
45
+ } from "../lib/service.mjs"
46
+
47
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
48
+
49
+ // ── version ───────────────────────────────────────────────────────────────────
50
+
51
+ const LOCAL_VERSION = (() => {
52
+ try {
53
+ const pkg = JSON.parse(fs.readFileSync(path.resolve(__dirname, "..", "package.json"), "utf8"))
54
+ return pkg.version ?? null
55
+ } catch { return null }
56
+ })()
57
+
58
+ async function checkForUpdate() {
59
+ if (!LOCAL_VERSION) return
60
+ try {
61
+ const res = await fetch("https://registry.npmjs.org/pacework-runner/latest", { signal: AbortSignal.timeout(4000) })
62
+ if (!res.ok) return
63
+ const { version: latest } = await res.json()
64
+ if (latest && latest !== LOCAL_VERSION) {
65
+ console.log(`\n⚠ Update available: pacework-runner ${LOCAL_VERSION} → ${latest}`)
66
+ console.log(` Run: npm install -g pacework\n`)
67
+ }
68
+ } catch {}
69
+ }
70
+
71
+ // ── ascii banner ──────────────────────────────────────────────────────────────
72
+
73
+ const BANNER = `\x1b[38;5;39m ██████╗ █████╗ ██████╗███████╗██╗ ██╗ ██████╗ ██████╗ ██╗ ██╗
74
+ ██╔══██╗██╔══██╗██╔════╝██╔════╝██║ ██║██╔═══██╗██╔══██╗██║ ██╔╝
75
+ ██████╔╝███████║██║ █████╗ ██║ █╗ ██║██║ ██║██████╔╝█████╔╝
76
+ ██╔═══╝ ██╔══██║██║ ██╔══╝ ██║███╗██║██║ ██║██╔══██╗██╔═██╗
77
+ ██║ ██║ ██║╚██████╗███████╗╚███╔███╔╝╚██████╔╝██║ ██║██║ ██╗
78
+ ╚═╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝ ╚══╝╚══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝\x1b[0m`
79
+
80
+ function printBanner(config) {
81
+ const cols = process.stdout.columns || 80
82
+ const W = Math.min(cols - 4, 72)
83
+ const div = ` \x1b[38;5;237m${"─".repeat(W)}\x1b[0m`
84
+ const kv = (label, val) => ` \x1b[2m${label}\x1b[0m \x1b[1m${val}\x1b[0m`
85
+
86
+ console.log("")
87
+ console.log(BANNER)
88
+ console.log("")
89
+
90
+ if (!config) { console.log(""); return }
91
+
92
+ const key = config.apiKey ?? config.workspaceApiKey
93
+ const ws = config.workspaceSlug ?? config.workspaceId
94
+ const exe = executorLabel(config.executor ?? "")
95
+ const displayName = config.userName ?? config.userEmail?.split("@")[0] ?? null
96
+
97
+ console.log(div)
98
+
99
+ if (key && ws) {
100
+ // greeting row — left: welcome, right: version
101
+ const greeting = ` \x1b[1mWelcome back${displayName ? `, ${displayName}` : ""}!\x1b[0m`
102
+ const version = `\x1b[38;5;240mv${LOCAL_VERSION ?? "?"}\x1b[0m`
103
+ const gLen = greeting.replace(/\x1b\[[0-9;]*m/g, "").length
104
+ const vLen = version.replace(/\x1b\[[0-9;]*m/g, "").length
105
+ const gap = Math.max(1, W + 2 - gLen - vLen)
106
+ console.log(`${greeting}${" ".repeat(gap)}${version}`)
107
+ console.log(div)
108
+
109
+ // info rows
110
+ const pid = readPid()
111
+ const running = pid && isRunning(pid)
112
+ const runDot = running ? `\x1b[32m●\x1b[0m` : `\x1b[38;5;240m○\x1b[0m`
113
+ const runLbl = running ? `\x1b[32mrunning\x1b[0m` : `\x1b[38;5;240mstopped\x1b[0m`
114
+
115
+ console.log(`${kv("workspace", ws)} ${kv("executor", exe)}${config.runnerName ? ` ${kv("runner", config.runnerName)}` : ""}`)
116
+ console.log(` ${runDot} ${runLbl}${config.repoRoot ? ` \x1b[2m${config.repoRoot.replace(os.homedir(), "~")}\x1b[0m` : ""}`)
117
+ } else {
118
+ console.log(` \x1b[33m⚠ Not logged in\x1b[0m — run \x1b[36m/login\x1b[0m to connect`)
119
+ }
120
+
121
+ console.log(div)
122
+ console.log("")
123
+ }
124
+
125
+ // ── helpers ───────────────────────────────────────────────────────────────────
126
+
127
+ function promptLine(question) {
128
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
129
+ return new Promise(resolve => rl.question(question, ans => { rl.close(); resolve(ans.trim()) }))
130
+ }
131
+
132
+ function relTime(iso) {
133
+ if (!iso) return "never"
134
+ const diff = Date.now() - new Date(iso).getTime()
135
+ const s = Math.floor(diff / 1000)
136
+ if (s < 60) return `${s}s ago`
137
+ if (s < 3600) return `${Math.floor(s / 60)}m ago`
138
+ if (s < 86400) return `${Math.floor(s / 3600)}h ago`
139
+ return `${Math.floor(s / 86400)}d ago`
140
+ }
141
+
142
+ function fmtDuration(ms) {
143
+ if (!ms || ms < 0) return ""
144
+ const s = Math.floor(ms / 1000)
145
+ if (s < 60) return `${s}s`
146
+ return `${Math.floor(s / 60)}m${s % 60}s`
147
+ }
148
+
149
+ // ── executors ─────────────────────────────────────────────────────────────────
150
+
151
+ const EXECUTORS = [
152
+ { id: "claude_code", label: "Claude Code", bin: "claude" },
153
+ { id: "codex", label: "Codex (OpenAI)", bin: "codex" },
154
+ { id: "gemini", label: "Gemini CLI", bin: "gemini" },
155
+ { id: "cursor_agent", label: "Cursor Agent", bin: "cursor" },
156
+ { id: "github_copilot", label: "GitHub Copilot", bin: "gh" },
157
+ ]
158
+
159
+ const EXECUTOR_DEFAULT_NAMES = {
160
+ claude_code: "Claude Dev",
161
+ codex: "Codex Dev",
162
+ gemini: "Gemini Dev",
163
+ cursor_agent: "Cursor Dev",
164
+ github_copilot: "Copilot Dev",
165
+ }
166
+
167
+ function checkBinaryExists(bin) {
168
+ try {
169
+ execFileSync(process.platform === "win32" ? "where" : "which", [bin], { stdio: "ignore" })
170
+ return true
171
+ } catch { return false }
172
+ }
173
+
174
+ function executorLabel(id) {
175
+ return EXECUTORS.find(e => e.id === id)?.label ?? id
176
+ }
177
+
178
+ // ── login setup prompts ───────────────────────────────────────────────────────
179
+
180
+ async function promptExecutorSetup() {
181
+ console.log("\nWhich AI executor does this runner use?")
182
+ const available = EXECUTORS.map(e => ({ ...e, installed: checkBinaryExists(e.bin) }))
183
+ available.forEach((e, i) => {
184
+ const tag = e.installed ? "\x1b[32m ✓\x1b[0m" : "\x1b[33m (not found in PATH)\x1b[0m"
185
+ console.log(` ${i + 1}. ${e.label}${tag}`)
186
+ })
187
+
188
+ let executor = null
189
+ while (!executor) {
190
+ const ans = await promptLine("Enter number (default 1): ")
191
+ const idx = ans === "" ? 0 : parseInt(ans, 10) - 1
192
+ if (idx >= 0 && idx < available.length) {
193
+ const chosen = available[idx]
194
+ if (!chosen.installed) {
195
+ const force = await promptLine(` "${chosen.label}" was not found (${chosen.bin}). Continue anyway? (y/N): `)
196
+ if (force.toLowerCase() !== "y") continue
197
+ }
198
+ executor = chosen.id
199
+ } else {
200
+ console.log(" Invalid choice, try again.")
201
+ }
202
+ }
203
+
204
+ const defaultName = EXECUTOR_DEFAULT_NAMES[executor] ?? "My Runner"
205
+ const nameAns = await promptLine(`Runner name (default: "${defaultName}"): `)
206
+ const runnerName = nameAns || defaultName
207
+
208
+ // detect git root from cwd, fall back to cwd itself
209
+ let detectedRepo = process.cwd()
210
+ try {
211
+ const { execSync } = await import("node:child_process")
212
+ detectedRepo = execSync("git rev-parse --show-toplevel", { cwd: process.cwd(), stdio: ["ignore","pipe","ignore"] }).toString().trim()
213
+ } catch {}
214
+
215
+ // auto-accept detected repo root — only prompt if it's invalid
216
+ let repoRoot = detectedRepo
217
+ if (!path.isAbsolute(repoRoot) || !fs.existsSync(repoRoot)) {
218
+ while (!repoRoot) {
219
+ const repoAns = await promptLine(`Repo root: `)
220
+ const candidate = repoAns.trim()
221
+ if (!path.isAbsolute(candidate)) {
222
+ console.log(" Please enter an absolute path (e.g. /Users/you/myproject).")
223
+ continue
224
+ }
225
+ if (!fs.existsSync(candidate)) {
226
+ console.log(` Path not found: ${candidate}`)
227
+ continue
228
+ }
229
+ repoRoot = candidate
230
+ }
231
+ } else {
232
+ console.log(` \x1b[2mRepo root: ${repoRoot}\x1b[0m \x1b[32m✓\x1b[0m`)
233
+ }
234
+
235
+ return { executor, runnerName, repoRoot }
236
+ }
237
+
238
+ // ── arg parsing ───────────────────────────────────────────────────────────────
239
+
240
+ function parseCliArgs(argv) {
241
+ const result = {}
242
+ for (let i = 0; i < argv.length; i++) {
243
+ const token = argv[i]
244
+ if (token.startsWith("--")) {
245
+ const key = token.slice(2)
246
+ const next = argv[i + 1]
247
+ if (next && !next.startsWith("--")) { result[key] = next; i++ }
248
+ else result[key] = "true"
249
+ }
250
+ }
251
+ return result
252
+ }
253
+
254
+ const invokedAs = path.basename(process.argv[1] ?? "", ".mjs")
255
+ const isPacework = invokedAs === "pacework"
256
+
257
+ // `pacework` with no args → guided interactive menu (REPL stays at `pacework shell`)
258
+ if (!process.argv[2] && isPacework) process.argv.splice(2, 0, process.stdin.isTTY ? "menu" : "shell")
259
+
260
+ const command = process.argv[2]
261
+ const restArgs = process.argv.slice(3)
262
+ const parsedArgs = parseCliArgs(restArgs)
263
+
264
+ // ── help ──────────────────────────────────────────────────────────────────────
265
+
266
+ if (!command || command === "--help" || command === "-h") {
267
+ printBanner()
268
+ console.log(`\x1b[1mCommands:\x1b[0m
269
+ \x1b[36mup\x1b[0m --token CODE One-command setup: sign in, detect your coding tool, install as a service
270
+ \x1b[36mdown\x1b[0m Remove the runner service from this machine
271
+ \x1b[36mlogin\x1b[0m [--app-url URL] Authenticate via browser and save credentials
272
+ \x1b[36mlogout\x1b[0m Revoke saved API key and clear credentials
273
+ \x1b[36mconnect\x1b[0m [flags] Run the runner in the foreground (interactive)
274
+ \x1b[36mstart\x1b[0m [flags] Start the runner as a background daemon
275
+ \x1b[36mstop\x1b[0m Stop the background runner
276
+ \x1b[36mstatus\x1b[0m Show runner and config status
277
+ \x1b[36mlogs\x1b[0m [--lines N] [--raw] Tail the runner log (default: 50 lines)
278
+ \x1b[36muse\x1b[0m <executor> Switch executor without re-logging in
279
+ \x1b[36mconfig\x1b[0m [key] [value] View or set config values
280
+ \x1b[36mdoctor\x1b[0m Check that everything is set up correctly
281
+ \x1b[36mjobs\x1b[0m [--lines N] Show recent job history
282
+ \x1b[36mmenu\x1b[0m Guided interactive mode — pick actions from questions (default for bare \x1b[36mpacework\x1b[0m)
283
+ \x1b[36mtriage\x1b[0m [--once] [--model M] Run pacework Intelligence triage jobs locally via your executor CLI
284
+ \x1b[36mshell\x1b[0m Interactive REPL with tab completion
285
+
286
+ \x1b[1mExecutors:\x1b[0m claude_code · codex · gemini · cursor_agent · github_copilot
287
+
288
+ \x1b[1mFlags:\x1b[0m
289
+ --app-url pacework app URL (default: https://pacework.io)
290
+ --workspace-id Workspace UUID (saved after login)
291
+ --workspace-api-key API key (saved after login)
292
+ --repo-root Absolute path to your git repo (default: cwd)
293
+ --executor AI executor (default: codex)
294
+ --name Runner display name
295
+ --max-parallel-runs Max concurrent jobs (default: 1)
296
+ --sandbox Confine agents to their checkout; network only to package registries and GitHub
297
+
298
+ \x1b[1mQuick start:\x1b[0m
299
+ Copy the command from pacework → Agents → Connect a runner, then run it inside your repo:
300
+ npx pacework@latest up --app-url https://pacework.io --token <code>
301
+
302
+ \x1b[1mManual setup:\x1b[0m
303
+ npm install -g pacework
304
+ pacework login \x1b[2m# opens browser, picks executor, saves config\x1b[0m
305
+ pacework connect \x1b[2m# run interactively\x1b[0m
306
+ pacework start \x1b[2m# run as background daemon\x1b[0m
307
+ `)
308
+ process.exit(0)
309
+ }
310
+
311
+ // ── login ─────────────────────────────────────────────────────────────────────
312
+
313
+ if (command === "login") {
314
+ printBanner()
315
+ const appUrl = parsedArgs["app-url"] || readConfig().appUrl || "https://pacework.io"
316
+ console.log("Opening browser for authentication…")
317
+
318
+ let token, loginUrl
319
+ try {
320
+ const res = await fetch(`${appUrl}/api/cli/login`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" })
321
+ if (!res.ok) throw new Error(`Server returned ${res.status}`)
322
+ const body = await res.json()
323
+ token = body.token
324
+ loginUrl = body.loginUrl
325
+ } catch (err) {
326
+ console.error(`\x1b[31mFailed to start login session: ${err.message}\x1b[0m`)
327
+ console.error(`Make sure pacework is running at ${appUrl}`)
328
+ process.exit(1)
329
+ }
330
+
331
+ const openCmd = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open"
332
+ try { execFileSync(openCmd, [loginUrl], { stdio: "ignore" }) } catch {}
333
+ console.log(`\n \x1b[2mAuthorize here:\x1b[0m \x1b[36m${loginUrl}\x1b[0m\n`)
334
+ console.log("Waiting for browser confirmation…")
335
+
336
+ const startedAt = Date.now()
337
+ const timeout = 10 * 60 * 1000
338
+ while (Date.now() - startedAt < timeout) {
339
+ await new Promise(r => setTimeout(r, 2000))
340
+ let poll
341
+ try {
342
+ const res = await fetch(`${appUrl}/api/cli/login?token=${token}`)
343
+ poll = await res.json()
344
+ } catch { continue }
345
+
346
+ if (poll.status === "authorized") {
347
+ console.log("")
348
+ const { executor, runnerName, repoRoot } = await promptExecutorSetup()
349
+
350
+ const config = readConfig()
351
+ config.appUrl = appUrl
352
+ config.workspaceId = parsedArgs["workspace-id"] || poll.workspaceId
353
+ config.workspaceSlug = poll.workspaceSlug
354
+ config.apiKey = poll.apiKey
355
+ config.executor = executor
356
+ config.runnerName = runnerName
357
+ config.repoRoot = repoRoot
358
+ if (poll.userName) config.userName = poll.userName
359
+ if (poll.userEmail) config.userEmail = poll.userEmail
360
+ writeConfig(config)
361
+
362
+ console.log(`
363
+ \x1b[32m✓ Logged in!\x1b[0m
364
+ Workspace : \x1b[1m${poll.workspaceSlug ?? poll.workspaceId}\x1b[0m
365
+ Executor : \x1b[1m${executorLabel(executor)}\x1b[0m
366
+ Name : \x1b[1m${runnerName}\x1b[0m
367
+ Repo root : \x1b[2m${repoRoot}\x1b[0m
368
+ Config : \x1b[2m${CONFIG_FILE}\x1b[0m
369
+
370
+ Start the runner:
371
+ \x1b[36mpacework-runner connect\x1b[0m \x1b[2m# foreground\x1b[0m
372
+ \x1b[36mpacework-runner start\x1b[0m \x1b[2m# background daemon\x1b[0m
373
+ `)
374
+ process.exit(0)
375
+ }
376
+
377
+ if (poll.status === "expired") {
378
+ console.error("\x1b[31mLogin session expired. Run login again.\x1b[0m")
379
+ process.exit(1)
380
+ }
381
+
382
+ process.stdout.write(".")
383
+ }
384
+
385
+ console.error("\n\x1b[31mLogin timed out.\x1b[0m")
386
+ process.exit(1)
387
+ }
388
+
389
+ // ── logout ────────────────────────────────────────────────────────────────────
390
+
391
+ if (command === "logout") {
392
+ const config = readConfig()
393
+ if (!config.apiKey) { console.log("Not logged in."); process.exit(0) }
394
+
395
+ const appUrl = config.appUrl || "https://pacework.io"
396
+ console.log("Revoking API key…")
397
+ try {
398
+ const res = await fetch(`${appUrl}/api/cli/login`, {
399
+ method: "DELETE",
400
+ headers: { "content-type": "application/json" },
401
+ body: JSON.stringify({ apiKey: config.apiKey }),
402
+ })
403
+ if (res.ok) console.log("\x1b[32m✓ API key revoked\x1b[0m")
404
+ else {
405
+ const body = await res.json().catch(() => ({}))
406
+ console.warn(` Warning: server said: ${body.error ?? res.status} (continuing anyway)`)
407
+ }
408
+ } catch (err) {
409
+ console.warn(` Warning: could not reach server (${err.message}) — clearing local config anyway`)
410
+ }
411
+
412
+ writeConfig({})
413
+ clearPid()
414
+ console.log("\x1b[32m✓ Logged out. Config cleared.\x1b[0m")
415
+ process.exit(0)
416
+ }
417
+
418
+ // ── use ───────────────────────────────────────────────────────────────────────
419
+
420
+ if (command === "use") {
421
+ const target = restArgs[0]
422
+ const valid = EXECUTORS.map(e => e.id)
423
+
424
+ if (!target || !valid.includes(target)) {
425
+ console.log(`Usage: pacework-runner use <executor>\n\nAvailable executors:`)
426
+ EXECUTORS.forEach(e => {
427
+ const installed = checkBinaryExists(e.bin)
428
+ const tag = installed ? "\x1b[32m✓\x1b[0m" : "\x1b[33m✗ not found\x1b[0m"
429
+ console.log(` ${tag} ${e.id.padEnd(16)} ${e.label}`)
430
+ })
431
+ process.exit(target ? 1 : 0)
432
+ }
433
+
434
+ const exe = EXECUTORS.find(e => e.id === target)
435
+ if (!checkBinaryExists(exe.bin)) {
436
+ const force = await promptLine(`\x1b[33m"${exe.label}" binary (${exe.bin}) not found in PATH. Switch anyway? (y/N):\x1b[0m `)
437
+ if (force.toLowerCase() !== "y") { console.log("Aborted."); process.exit(1) }
438
+ }
439
+
440
+ const config = readConfig()
441
+ const prev = config.executor ?? "codex"
442
+ config.executor = target
443
+ // Update default runner name only if it still matches the old default
444
+ if (config.runnerName === EXECUTOR_DEFAULT_NAMES[prev]) {
445
+ config.runnerName = EXECUTOR_DEFAULT_NAMES[target] ?? config.runnerName
446
+ }
447
+ writeConfig(config)
448
+
449
+ console.log(`\x1b[32m✓ Executor switched:\x1b[0m ${executorLabel(prev)} → \x1b[1m${executorLabel(target)}\x1b[0m`)
450
+ console.log(` Restart the runner to apply: \x1b[36mpacework-runner connect\x1b[0m`)
451
+ process.exit(0)
452
+ }
453
+
454
+ // ── config ────────────────────────────────────────────────────────────────────
455
+
456
+ if (command === "config") {
457
+ const KEY_ALIASES = {
458
+ "executor": "executor",
459
+ "name": "runnerName",
460
+ "runner-name": "runnerName",
461
+ "repo-root": "repoRoot",
462
+ "app-url": "appUrl",
463
+ "workspace-id": "workspaceId",
464
+ }
465
+
466
+ const config = readConfig()
467
+ const key = restArgs[0]
468
+ const value = restArgs[1]
469
+
470
+ if (!key) {
471
+ console.log(`\x1b[1mCurrent config\x1b[0m \x1b[2m(${CONFIG_FILE})\x1b[0m\n`)
472
+ const rows = [
473
+ ["workspace", config.workspaceSlug ?? config.workspaceId ?? "\x1b[2mnot set\x1b[0m"],
474
+ ["executor", config.executor ? `\x1b[1m${executorLabel(config.executor)}\x1b[0m (${config.executor})` : "\x1b[2mnot set\x1b[0m"],
475
+ ["name", config.runnerName ?? "\x1b[2mnot set\x1b[0m"],
476
+ ["repo-root", config.repoRoot ?? "\x1b[2mnot set\x1b[0m"],
477
+ ["app-url", config.appUrl ?? "https://pacework.io"],
478
+ ["api-key", config.apiKey ? `\x1b[2m${config.apiKey.slice(0, 12)}…\x1b[0m` : "\x1b[2mnot set\x1b[0m"],
479
+ ]
480
+ rows.forEach(([k, v]) => console.log(` ${k.padEnd(12)} ${v}`))
481
+ console.log(`\nTo set: \x1b[36mpacework-runner config <key> <value>\x1b[0m`)
482
+ console.log(`Keys: ${Object.keys(KEY_ALIASES).join(", ")}`)
483
+ process.exit(0)
484
+ }
485
+
486
+ const configKey = KEY_ALIASES[key]
487
+ if (!configKey) {
488
+ console.error(`Unknown config key: ${key}`)
489
+ console.error(`Valid keys: ${Object.keys(KEY_ALIASES).join(", ")}`)
490
+ process.exit(1)
491
+ }
492
+
493
+ if (!value) {
494
+ const current = config[configKey] ?? "\x1b[2mnot set\x1b[0m"
495
+ console.log(`${key}: ${current}`)
496
+ process.exit(0)
497
+ }
498
+
499
+ if (key === "executor" && !EXECUTORS.find(e => e.id === value)) {
500
+ console.error(`Invalid executor: ${value}`)
501
+ console.error(`Valid: ${EXECUTORS.map(e => e.id).join(", ")}`)
502
+ process.exit(1)
503
+ }
504
+
505
+ config[configKey] = value
506
+ writeConfig(config)
507
+ console.log(`\x1b[32m✓\x1b[0m ${key} = \x1b[1m${value}\x1b[0m`)
508
+ process.exit(0)
509
+ }
510
+
511
+ // ── doctor ────────────────────────────────────────────────────────────────────
512
+
513
+ if (command === "doctor") {
514
+ printBanner()
515
+ console.log("\x1b[1mRunning diagnostics…\x1b[0m\n")
516
+
517
+ const ok = (msg) => console.log(` \x1b[32m✓\x1b[0m ${msg}`)
518
+ const err = (msg) => console.log(` \x1b[31m✗\x1b[0m ${msg}`)
519
+ const warn = (msg) => console.log(` \x1b[33m⚠\x1b[0m ${msg}`)
520
+ const info = (msg) => console.log(` \x1b[2m·\x1b[0m ${msg}`)
521
+
522
+ let issues = 0
523
+
524
+ // Node version
525
+ const nodeVer = process.versions.node
526
+ const nodeMaj = parseInt(nodeVer.split(".")[0], 10)
527
+ if (nodeMaj >= 18) ok(`Node.js ${nodeVer}`)
528
+ else { err(`Node.js ${nodeVer} — requires 18+`); issues++ }
529
+
530
+ // Config
531
+ const config = readConfig()
532
+ if (config.apiKey) ok(`Config found (${CONFIG_FILE})`)
533
+ else { err(`Not logged in — run \x1b[36mpacework-runner login\x1b[0m`); issues++ }
534
+
535
+ if (config.workspaceSlug || config.workspaceId) ok(`Workspace: ${config.workspaceSlug ?? config.workspaceId}`)
536
+ else { err("No workspace saved"); issues++ }
537
+
538
+ if (config.repoRoot) {
539
+ if (fs.existsSync(config.repoRoot)) ok(`Repo root: ${config.repoRoot}`)
540
+ else { err(`Repo root not found: ${config.repoRoot}`); issues++ }
541
+ } else warn("No repo root saved — will use cwd when connecting")
542
+
543
+ // Executor
544
+ const executor = config.executor ?? "codex"
545
+ const exeEntry = EXECUTORS.find(e => e.id === executor)
546
+ if (exeEntry) {
547
+ if (checkBinaryExists(exeEntry.bin)) ok(`Executor: ${exeEntry.label} (${exeEntry.bin} found in PATH)`)
548
+ else { err(`Executor: ${exeEntry.label} (${exeEntry.bin} \x1b[31mnot found in PATH\x1b[0m)`); issues++ }
549
+ } else { err(`Unknown executor: ${executor}`); issues++ }
550
+
551
+ // All executors
552
+ console.log("")
553
+ info("Checking all executors:")
554
+ for (const e of EXECUTORS) {
555
+ if (checkBinaryExists(e.bin)) ok(` ${e.label.padEnd(18)} ${e.bin}`)
556
+ else info(` ${e.label.padEnd(18)} \x1b[2mnot installed\x1b[0m`)
557
+ }
558
+
559
+ // Server reachability
560
+ console.log("")
561
+ const appUrl = config.appUrl || "https://pacework.io"
562
+ try {
563
+ const res = await fetch(`${appUrl}/api/health`, { signal: AbortSignal.timeout(4000) })
564
+ if (res.ok || res.status === 404) ok(`Server reachable (${appUrl})`)
565
+ else warn(`Server responded ${res.status} (${appUrl})`)
566
+ } catch {
567
+ err(`Server not reachable (${appUrl})`); issues++
568
+ }
569
+
570
+ // API key validity
571
+ if (config.apiKey && config.workspaceId) {
572
+ try {
573
+ const res = await fetch(`${appUrl}/api/workspaces/${config.workspaceId}/agent-runners`, {
574
+ headers: { Authorization: `Bearer ${config.apiKey}` },
575
+ signal: AbortSignal.timeout(4000),
576
+ })
577
+ if (res.ok) ok("API key valid")
578
+ else { err(`API key rejected (${res.status}) — run \x1b[36mpacework-runner login\x1b[0m`); issues++ }
579
+ } catch { warn("Could not verify API key (server unreachable)") }
580
+ }
581
+
582
+ // Runner process
583
+ console.log("")
584
+ const pid = readPid()
585
+ if (pid && isRunning(pid)) ok(`Runner process running (PID ${pid})`)
586
+ else info("Runner is not running")
587
+
588
+ // Summary
589
+ console.log("")
590
+ if (issues === 0) console.log("\x1b[32m All checks passed.\x1b[0m")
591
+ else console.log(`\x1b[31m ${issues} issue${issues === 1 ? "" : "s"} found.\x1b[0m`)
592
+ console.log("")
593
+
594
+ process.exit(issues > 0 ? 1 : 0)
595
+ }
596
+
597
+ // ── jobs ──────────────────────────────────────────────────────────────────────
598
+
599
+ if (command === "jobs") {
600
+ const linesArg = restArgs.indexOf("--lines")
601
+ const limit = linesArg !== -1 ? parseInt(restArgs[linesArg + 1], 10) || 20 : 20
602
+
603
+ const STATE_GLYPH = {
604
+ completed: "\x1b[32m✓\x1b[0m",
605
+ error: "\x1b[31m✗\x1b[0m",
606
+ running: "\x1b[34m▶\x1b[0m",
607
+ pending: "\x1b[2m·\x1b[0m",
608
+ canceled: "\x1b[2m■\x1b[0m",
609
+ }
610
+
611
+ // Parse jobs from runner log (look for job events in the JSON log stream)
612
+ try {
613
+ const raw = fs.readFileSync(LOG_FILE, "utf8")
614
+ const jobs = []
615
+ for (const line of raw.split("\n")) {
616
+ if (!line.trim()) continue
617
+ try {
618
+ const entry = JSON.parse(line)
619
+ if (entry.event === "runner.job.start" || entry.event === "runner.job.complete" || entry.event === "runner.job.error") {
620
+ jobs.push(entry)
621
+ }
622
+ } catch {}
623
+ }
624
+
625
+ if (!jobs.length) {
626
+ console.log("No job history found in logs.")
627
+ console.log(`(Log file: ${LOG_FILE})`)
628
+ process.exit(0)
629
+ }
630
+
631
+ // Group by run_id
632
+ const byRun = new Map()
633
+ for (const j of jobs) {
634
+ const id = j.run_id ?? j.meta?.run_id ?? "unknown"
635
+ if (!byRun.has(id)) byRun.set(id, { id, start: null, end: null, status: "pending", meta: j.meta ?? {} })
636
+ const entry = byRun.get(id)
637
+ if (j.event === "runner.job.start") { entry.start = j.ts; entry.status = "running" }
638
+ if (j.event === "runner.job.complete") { entry.end = j.ts; entry.status = "completed" }
639
+ if (j.event === "runner.job.error") { entry.end = j.ts; entry.status = "error"; entry.error = j.msg }
640
+ }
641
+
642
+ const runs = Array.from(byRun.values()).slice(-limit).reverse()
643
+ console.log(`\x1b[1mRecent jobs\x1b[0m \x1b[2m(last ${runs.length})\x1b[0m\n`)
644
+ for (const r of runs) {
645
+ const glyph = STATE_GLYPH[r.status] ?? "·"
646
+ const title = r.meta?.task_title ?? r.meta?.task_identifier ?? r.id.slice(0, 8)
647
+ const executor = r.meta?.local_executor ?? ""
648
+ const dur = (r.start && r.end) ? fmtDuration(new Date(r.end) - new Date(r.start)) : ""
649
+ const when = relTime(r.start ?? r.end)
650
+ console.log(` ${glyph} \x1b[1m${title}\x1b[0m \x1b[2m${executor} ${dur ? dur + " " : ""}${when}\x1b[0m`)
651
+ if (r.status === "error" && r.error) console.log(` \x1b[31m${r.error}\x1b[0m`)
652
+ }
653
+ console.log("")
654
+ } catch {
655
+ console.log(`No log file found at ${LOG_FILE}`)
656
+ console.log("Start the runner first: pacework start")
657
+ }
658
+ process.exit(0)
659
+ }
660
+
661
+ // ── build runner args ─────────────────────────────────────────────────────────
662
+
663
+ function buildRunnerArgs(extraArgs) {
664
+ const config = readConfig()
665
+ const appUrl = parsedArgs["app-url"] || config.appUrl || "https://pacework.io"
666
+ const workspaceId = parsedArgs["workspace-id"] || config.workspaceId
667
+ const apiKey = parsedArgs["workspace-api-key"] || config.apiKey
668
+ const repoRoot = parsedArgs["repo-root"] || config.repoRoot || process.cwd()
669
+ const executor = parsedArgs["executor"] || config.executor || "codex"
670
+ const runnerName = parsedArgs["name"] || config.runnerName
671
+
672
+ if (!workspaceId) { console.error("\x1b[31mNo workspace ID. Run: pacework login\x1b[0m"); process.exit(1) }
673
+ if (!apiKey) { console.error("\x1b[31mNo API key. Run: pacework login\x1b[0m"); process.exit(1) }
674
+
675
+ // The API key goes to the runner through its environment (runnerEnv), not
676
+ // argv, so it does not show up in `ps` or in a service file.
677
+ const base = [
678
+ "--app-url", appUrl,
679
+ "--workspace-id", workspaceId,
680
+ "--repo-root", repoRoot,
681
+ "--executor", executor,
682
+ ]
683
+ if (runnerName) base.push("--name", runnerName)
684
+ const maxParallelRuns = parsedArgs["max-parallel-runs"] || config.maxParallelRuns
685
+ if (maxParallelRuns) base.push("--max-parallel-runs", String(maxParallelRuns))
686
+ const sandbox = parsedArgs.sandbox !== undefined
687
+ ? !["false", "0", "no"].includes(String(parsedArgs.sandbox))
688
+ : config.sandbox === true
689
+ if (sandbox) base.push("--sandbox", "true")
690
+
691
+ const consumed = new Set(["app-url", "workspace-id", "workspace-api-key", "repo-root", "executor", "name", "max-parallel-runs", "token", "sandbox"])
692
+ for (let i = 0; i < extraArgs.length; i++) {
693
+ const arg = extraArgs[i]
694
+ if (arg.startsWith("--")) {
695
+ const key = arg.slice(2)
696
+ if (!consumed.has(key)) base.push(arg)
697
+ } else {
698
+ base.push(arg)
699
+ }
700
+ }
701
+ return base
702
+ }
703
+
704
+ /** Environment for the runner process: the caller's, plus the workspace key. */
705
+ function runnerEnv() {
706
+ const config = readConfig()
707
+ const apiKey = parsedArgs["workspace-api-key"] || config.apiKey
708
+ return { ...process.env, PATH: process.env.PATH || "", WORKSPACE_API_KEY: apiKey }
709
+ }
710
+
711
+ // ── readable log formatter ────────────────────────────────────────────────────
712
+
713
+ function findStrayRunnerPids(excludePid) {
714
+ // Runner processes that survived the watchdog being killed. Without this a
715
+ // stopped runner keeps claiming jobs and fights the next one for them.
716
+ // Matches only node actually executing the script, so shells and greps that
717
+ // merely mention the path are never killed.
718
+ try {
719
+ const out = execSync("ps -eo pid,command", { encoding: "utf8" })
720
+ return out
721
+ .split(String.fromCharCode(10))
722
+ .filter((line) => /\bnode\b[^\n]*\/(pacework-runner|watchdog)\.mjs(\s|$)/.test(line))
723
+ .map((line) => Number(line.trim().split(/[ \t]+/)[0]))
724
+ .filter((pid) => Number.isFinite(pid) && pid !== excludePid && pid !== process.pid)
725
+ } catch {
726
+ return []
727
+ }
728
+ }
729
+
730
+ function formatLogLine(raw) {
731
+ let entry
732
+ try { entry = JSON.parse(raw) } catch { return null }
733
+
734
+ const ts = entry.ts ? new Date(entry.ts).toLocaleTimeString() : ""
735
+ const event = entry.event ?? ""
736
+ const msg = entry.msg ?? ""
737
+
738
+ const dim = "\x1b[2m"
739
+ const reset = "\x1b[0m"
740
+ const green = "\x1b[32m"
741
+ const red = "\x1b[31m"
742
+ const blue = "\x1b[34m"
743
+ const amber = "\x1b[33m"
744
+ const bold = "\x1b[1m"
745
+
746
+ const prefix = `${dim}[${ts}]${reset}`
747
+
748
+ if (event === "runner.ready") return `${prefix} ${green}●${reset} Runner ready ${dim}${entry.meta?.local_executor ?? ""} ${entry.meta?.machine_name ?? ""}${reset}`
749
+ if (event === "runner.job.start") return `${prefix} ${blue}▶${reset} ${bold}${entry.meta?.task_identifier ?? ""}${reset} ${entry.meta?.task_title ?? msg} ${dim}${entry.meta?.local_executor ?? ""}${reset}`
750
+ if (event === "runner.job.complete") return `${prefix} ${green}✓${reset} ${bold}${entry.meta?.task_identifier ?? ""}${reset} completed ${dim}${fmtDuration(entry.meta?.duration_ms)}${reset}`
751
+ if (event === "runner.job.error") return `${prefix} ${red}✗${reset} ${bold}${entry.meta?.task_identifier ?? ""}${reset} ${red}${msg}${reset}`
752
+ if (event === "runner.job.cancel") return `${prefix} ${dim}■ ${entry.meta?.task_identifier ?? ""} canceled${reset}`
753
+ if (event === "runner.heartbeat") return null // skip noise
754
+ if (entry.level === "fatal" || entry.level === "error") return `${prefix} ${red}✗${reset} ${red}${msg}${reset}`
755
+ if (entry.level === "warn") return `${prefix} ${amber}⚠${reset} ${msg}`
756
+
757
+ return null // suppress all other structured lines in readable mode
758
+ }
759
+
760
+ /**
761
+ * Wait for the runner to log "runner.ready" after `logOffset`, so a runner stuck
762
+ * in a crash loop is not reported as started.
763
+ */
764
+ async function waitForRunnerReady({ logOffset, timeoutMs }) {
765
+ const deadline = Date.now() + timeoutMs
766
+ let lastError = null
767
+ while (Date.now() < deadline) {
768
+ await new Promise((r) => setTimeout(r, 500))
769
+ const tail = (() => {
770
+ try { return fs.readFileSync(LOG_FILE, "utf8").slice(logOffset) } catch { return "" }
771
+ })()
772
+ if (tail.includes("runner.ready")) return { ready: true, lastError: null }
773
+ for (const line of tail.split("\n")) {
774
+ let entry = null
775
+ try { entry = JSON.parse(line) } catch {}
776
+ if (entry && (entry.level === "error" || entry.level === "fatal") && entry.msg) {
777
+ lastError = entry.msg
778
+ continue
779
+ }
780
+ const crash = line.match(/Error \[?([A-Z_]+)\]?: (.{0,140})/)
781
+ if (crash) lastError = `${crash[1]}: ${crash[2]}`
782
+ }
783
+ }
784
+ return { ready: false, lastError }
785
+ }
786
+
787
+ // ── connect (foreground, readable output + watchdog) ─────────────────────────
788
+
789
+ if (command === "connect") {
790
+ printBanner()
791
+ const config = readConfig()
792
+ const executor = parsedArgs["executor"] || config.executor || "codex"
793
+ console.log(`\x1b[2mWorkspace:\x1b[0m ${config.workspaceSlug ?? config.workspaceId ?? "unknown"}`)
794
+ console.log(`\x1b[2mExecutor: \x1b[0m ${executorLabel(executor)}`)
795
+ console.log(`\x1b[2mName: \x1b[0m ${parsedArgs["name"] || (config.runnerName ?? "unnamed")}`)
796
+ console.log(`\x1b[2mRepo: \x1b[0m ${parsedArgs["repo-root"] || config.repoRoot || process.cwd()}`)
797
+ console.log(`\nPress \x1b[1mCtrl+C\x1b[0m to stop.\n`)
798
+
799
+ void checkForUpdate()
800
+
801
+ const runnerScript = path.resolve(__dirname, "pacework-runner.mjs")
802
+ const runnerArgs = buildRunnerArgs(restArgs)
803
+ const rawMode = parsedArgs["raw"] === "true"
804
+
805
+ let stopping = false
806
+ let currentChild = null
807
+ let restartDelay = 2000
808
+ const MAX_DELAY = 30000
809
+
810
+ process.on("SIGINT", () => { stopping = true; currentChild?.kill("SIGINT") })
811
+ process.on("SIGTERM", () => { stopping = true; currentChild?.kill("SIGTERM") })
812
+
813
+ async function runOnce() {
814
+ return new Promise(resolve => {
815
+ const child = spawn(process.execPath, [runnerScript, ...runnerArgs], {
816
+ stdio: rawMode ? "inherit" : ["inherit", "pipe", "pipe"],
817
+ env: runnerEnv(),
818
+ })
819
+ currentChild = child
820
+
821
+ if (!rawMode) {
822
+ const handleStream = (stream) => {
823
+ let buf = ""
824
+ stream.on("data", chunk => {
825
+ buf += chunk.toString()
826
+ const lines = buf.split("\n")
827
+ buf = lines.pop()
828
+ for (const line of lines) {
829
+ const formatted = formatLogLine(line)
830
+ if (formatted) console.log(formatted)
831
+ // else silently drop
832
+ }
833
+ })
834
+ }
835
+ handleStream(child.stdout)
836
+ handleStream(child.stderr)
837
+ }
838
+
839
+ child.on("exit", (code) => resolve(code ?? 0))
840
+ })
841
+ }
842
+
843
+ while (true) {
844
+ const code = await runOnce()
845
+ if (stopping) process.exit(0)
846
+ if (code === 0) process.exit(0)
847
+ console.error(`\x1b[33m\nRunner exited (code ${code}). Restarting in ${restartDelay / 1000}s… (Ctrl+C to stop)\x1b[0m`)
848
+ await new Promise(r => setTimeout(r, restartDelay))
849
+ restartDelay = Math.min(restartDelay * 2, MAX_DELAY)
850
+ }
851
+ }
852
+
853
+ // ── start (background daemon) ────────────────────────────────────────────────
854
+
855
+ else if (command === "start") {
856
+ ensureStateDir()
857
+
858
+ if (isServiceInstalled()) {
859
+ const logOffset = (() => { try { return fs.statSync(LOG_FILE).size } catch { return 0 } })()
860
+ if (!isServiceRunning()) {
861
+ try { startService() } catch (err) { console.error(`Could not start the runner service: ${err.message}`); process.exit(1) }
862
+ }
863
+ process.stdout.write(" starting… ")
864
+ const { ready, lastError } = await waitForRunnerReady({ logOffset, timeoutMs: 20000 })
865
+ console.log(ready ? "\x1b[32m✓ Runner service running\x1b[0m" : `\x1b[33mservice started, not ready yet${lastError ? ` (${lastError})` : ""}\x1b[0m — pacework logs`)
866
+ process.exit(ready ? 0 : 1)
867
+ }
868
+
869
+ const pid = readPid()
870
+ if (pid && isRunning(pid)) {
871
+ console.log(`Runner is already running (PID ${pid})`)
872
+ console.log(` logs: pacework logs`)
873
+ console.log(` stop: pacework stop`)
874
+ process.exit(0)
875
+ }
876
+ clearPid()
877
+ void checkForUpdate()
878
+
879
+ const runnerScript = path.resolve(__dirname, "pacework-runner.mjs")
880
+ const runnerArgs = buildRunnerArgs(restArgs)
881
+
882
+ // Rotate log if over 5 MB
883
+ try {
884
+ const stat = fs.statSync(LOG_FILE)
885
+ if (stat.size > 5 * 1024 * 1024) {
886
+ const rotated = LOG_FILE + ".1"
887
+ try { fs.unlinkSync(rotated) } catch {}
888
+ fs.renameSync(LOG_FILE, rotated)
889
+ }
890
+ } catch {}
891
+ const logStream = fs.openSync(LOG_FILE, "a")
892
+
893
+ const WATCHDOG_FILE = path.join(STATE_DIR, "watchdog.mjs")
894
+ const escapedScript = JSON.stringify(runnerScript)
895
+ const escapedArgs = JSON.stringify(runnerArgs)
896
+ fs.writeFileSync(WATCHDOG_FILE, `
897
+ import { spawn } from "node:child_process"
898
+ import process from "node:process"
899
+
900
+ let delay = 2000
901
+
902
+ async function run() {
903
+ while (true) {
904
+ const code = await new Promise(r => {
905
+ const c = spawn(process.execPath, [${escapedScript}, ...${escapedArgs}], { stdio: "inherit" })
906
+ c.on("exit", r)
907
+ })
908
+ if (code === 0) process.exit(0)
909
+ process.stderr.write("Runner exited (" + code + "), restarting in " + (delay/1000) + "s\\n")
910
+ await new Promise(r => setTimeout(r, delay))
911
+ delay = Math.min(delay * 2, 30000)
912
+ }
913
+ }
914
+ run()
915
+ `.trim(), "utf8")
916
+
917
+ const child = spawn(process.execPath, [WATCHDOG_FILE], {
918
+ detached: true,
919
+ stdio: ["ignore", logStream, logStream],
920
+ env: runnerEnv(),
921
+ })
922
+
923
+ child.unref()
924
+ fs.closeSync(logStream)
925
+
926
+ fs.writeFileSync(PID_FILE, String(child.pid), "utf8")
927
+ fs.writeFileSync(CMD_FILE, JSON.stringify({ args: runnerArgs, startedAt: new Date().toISOString() }, null, 2), "utf8")
928
+
929
+ // The watchdog restarts the runner when it dies, so a crash-looping runner
930
+ // leaves a live watchdog pid and looks healthy. Confirm the worker actually
931
+ // came up before reporting success.
932
+ process.stdout.write(" starting… ")
933
+ // Only look at output written after this start; an earlier run's "runner.ready"
934
+ // would otherwise make a crash-looping runner look healthy.
935
+ const logOffset = (() => {
936
+ try { return fs.statSync(LOG_FILE).size } catch { return 0 }
937
+ })()
938
+ const readyDeadline = Date.now() + 15000
939
+ let ready = false
940
+ let lastError = null
941
+
942
+ while (Date.now() < readyDeadline) {
943
+ await new Promise((r) => setTimeout(r, 500))
944
+
945
+ const tail = (() => {
946
+ try { return fs.readFileSync(LOG_FILE, "utf8").slice(logOffset) } catch { return "" }
947
+ })()
948
+
949
+ if (tail.includes("runner.ready")) { ready = true; break }
950
+
951
+ const crash = tail.match(/Error \[?([A-Z_]+)\]?: ([^\n]{0,140})/)
952
+ if (crash) lastError = `${crash[1]}: ${crash[2]}`
953
+ if (!isRunning(child.pid)) break
954
+ }
955
+
956
+ if (ready) {
957
+ console.log(`\x1b[32m✓ Runner started\x1b[0m (PID ${child.pid}) — connected and waiting for work`)
958
+ console.log(` logs: pacework logs`)
959
+ console.log(` stop: pacework stop`)
960
+ process.exit(0)
961
+ }
962
+
963
+ console.log(`\x1b[31m✗\x1b[0m`)
964
+ console.log(`\x1b[31mThe runner started but did not come up.\x1b[0m`)
965
+ if (lastError) console.log(` ${lastError}`)
966
+ console.log(`\n It will keep retrying in the background. To investigate:`)
967
+ console.log(` pacework logs`)
968
+ console.log(` pacework connect (runs in the foreground and shows errors directly)`)
969
+ process.exit(1)
970
+ }
971
+
972
+ // ── stop ─────────────────────────────────────────────────────────────────────
973
+
974
+ else if (command === "stop") {
975
+ // With a login service, stop it first; otherwise it restarts the runner the
976
+ // moment the process below is killed.
977
+ const hadService = isServiceInstalled()
978
+ if (hadService) stopService()
979
+ const pid = readPid()
980
+
981
+ // Kill every runner/watchdog process, retrying because the watchdog's child can
982
+ // outlive the first sweep and then be orphaned. Previously stop sent one SIGTERM
983
+ // and reported success immediately, so survivors kept claiming jobs and competed
984
+ // with the next runner.
985
+ const sweepStrays = async (excludePid) => {
986
+ let killed = 0
987
+ for (let attempt = 0; attempt < 5; attempt++) {
988
+ const strays = findStrayRunnerPids(excludePid ?? 0)
989
+ if (strays.length === 0) break
990
+ for (const stray of strays) {
991
+ try { process.kill(stray, "SIGKILL"); killed += 1 } catch {}
992
+ }
993
+ await new Promise((r) => setTimeout(r, 400))
994
+ }
995
+ return killed
996
+ }
997
+
998
+ if (!pid || !isRunning(pid)) {
999
+ const orphaned = await sweepStrays(0)
1000
+ clearPid()
1001
+ console.log(orphaned > 0
1002
+ ? `\x1b[32m✓\x1b[0m Cleaned up ${orphaned} orphaned runner process(es).`
1003
+ : "Runner is not running.")
1004
+ process.exit(0)
1005
+ }
1006
+ try {
1007
+ process.kill(pid, "SIGTERM")
1008
+
1009
+ const deadline = Date.now() + 5000
1010
+ while (isRunning(pid) && Date.now() < deadline) {
1011
+ await new Promise((r) => setTimeout(r, 200))
1012
+ }
1013
+ if (isRunning(pid)) process.kill(pid, "SIGKILL")
1014
+
1015
+ const orphaned = await sweepStrays(pid)
1016
+ clearPid()
1017
+ const extra = orphaned > 0 ? ` (+${orphaned} orphaned)` : ""
1018
+ console.log(`\x1b[32m✓ Runner stopped\x1b[0m (PID ${pid})${extra}`)
1019
+ } catch (err) {
1020
+ console.error(`\x1b[31mFailed to stop runner: ${err.message}\x1b[0m`)
1021
+ process.exit(1)
1022
+ }
1023
+ process.exit(0)
1024
+ }
1025
+
1026
+ // ── status ────────────────────────────────────────────────────────────────────
1027
+
1028
+ else if (command === "status") {
1029
+ const pid = readPid()
1030
+ const config = readConfig()
1031
+
1032
+ console.log("")
1033
+ if (pid && isRunning(pid)) {
1034
+ let startedAt = ""
1035
+ try {
1036
+ const cmd = JSON.parse(fs.readFileSync(CMD_FILE, "utf8"))
1037
+ startedAt = ` started ${relTime(cmd.startedAt)}`
1038
+ } catch {}
1039
+ console.log(` \x1b[32m●\x1b[0m Runner is \x1b[1mrunning\x1b[0m (PID ${pid}${startedAt})`)
1040
+ } else {
1041
+ clearPid()
1042
+ console.log(` \x1b[2m○\x1b[0m Runner is \x1b[2mstopped\x1b[0m`)
1043
+ }
1044
+
1045
+ if (isServiceInstalled()) {
1046
+ console.log(` \x1b[2mservice installed (${serviceKind()}) — starts with your computer${isServiceRunning() ? "" : ", currently stopped"}\x1b[0m`)
1047
+ }
1048
+
1049
+ console.log("")
1050
+ if (config.workspaceSlug || config.workspaceId) console.log(` workspace ${config.workspaceSlug ?? config.workspaceId}`)
1051
+ if (config.executor) console.log(` executor ${executorLabel(config.executor)} (${config.executor})`)
1052
+ if (config.runnerName) console.log(` name ${config.runnerName}`)
1053
+ if (config.repoRoot) console.log(` repo root ${config.repoRoot}`)
1054
+ if (config.appUrl) console.log(` app url ${config.appUrl}`)
1055
+ if (config.apiKey) console.log(` api key \x1b[2m${config.apiKey.slice(0, 16)}…\x1b[0m`)
1056
+ else console.log(` \x1b[33m⚠ not logged in — run: pacework login\x1b[0m`)
1057
+ console.log("")
1058
+ process.exit(0)
1059
+ }
1060
+
1061
+ // ── logs ──────────────────────────────────────────────────────────────────────
1062
+
1063
+ else if (command === "logs") {
1064
+ const linesArg = restArgs.indexOf("--lines")
1065
+ const lines = linesArg !== -1 ? parseInt(restArgs[linesArg + 1], 10) || 50 : 50
1066
+ const rawMode = restArgs.includes("--raw")
1067
+
1068
+ try {
1069
+ const content = fs.readFileSync(LOG_FILE, "utf8")
1070
+ const all = content.split("\n").filter(Boolean)
1071
+ const tail = all.slice(-lines)
1072
+
1073
+ if (rawMode) {
1074
+ console.log(tail.join("\n"))
1075
+ } else {
1076
+ const formatted = tail.map(formatLogLine).filter(Boolean)
1077
+ if (formatted.length) console.log(formatted.join("\n"))
1078
+ else console.log(tail.join("\n")) // fallback to raw if nothing parsed
1079
+ }
1080
+
1081
+ console.log(`\n\x1b[2m— ${tail.length} lines from ${LOG_FILE}\x1b[0m`)
1082
+ const rotatedLog = LOG_FILE + ".1"
1083
+ if (fs.existsSync(rotatedLog)) console.log(`\x1b[2m(older logs at ${rotatedLog})\x1b[0m`)
1084
+ } catch {
1085
+ console.log(`No log file found at ${LOG_FILE}`)
1086
+ console.log("Start the runner first: pacework start")
1087
+ }
1088
+ process.exit(0)
1089
+ }
1090
+
1091
+ // ── triage (pacework Intelligence local runner) ────────────────────────────────
1092
+ // Polls the workspace for pending triage jobs and executes them with the local
1093
+ // `claude` CLI (billed to the user's Claude subscription). The backend owns
1094
+ // retrieval, prompting, and sanitising; this loop only turns prompts into
1095
+ // completions. Docs: docs/triage-local-runner.md
1096
+
1097
+ else if (command === "triage") {
1098
+ const config = readConfig()
1099
+ const appUrl = String(parsedArgs["app-url"] || process.env.PACEWORK_APP_URL || config.appUrl || "").trim().replace(/\/$/, "")
1100
+ const apiKey = String(parsedArgs["api-key"] || process.env.PACEWORK_API_KEY || config.apiKey || "").trim()
1101
+ if (!appUrl || !apiKey) {
1102
+ console.error("\x1b[31mNot logged in.\x1b[0m Run \x1b[36mpacework login\x1b[0m first (or pass --app-url and --api-key).")
1103
+ process.exit(1)
1104
+ }
1105
+
1106
+ const pollIntervalMs = Math.max(2000, Number(parsedArgs["poll-interval-ms"] || process.env.TRIAGE_RUNNER_POLL_INTERVAL_MS || 5000))
1107
+ const claudeTimeoutMs = Math.max(30_000, Number(parsedArgs["claude-timeout-ms"] || process.env.TRIAGE_RUNNER_CLAUDE_TIMEOUT_MS || 240_000))
1108
+ const claudeBinary = parsedArgs["claude-bin"] || process.env.TRIAGE_RUNNER_CLAUDE_BIN || "claude"
1109
+ const claudeModel = parsedArgs.model || process.env.TRIAGE_RUNNER_CLAUDE_MODEL || null
1110
+ const triageRunnerName = parsedArgs.name || process.env.TRIAGE_RUNNER_NAME || `${os.hostname()} triage`
1111
+ const runOnce = (parsedArgs.once || "").toLowerCase() === "true"
1112
+ // Executor: same choice the agent runner uses (pacework login saves it).
1113
+ // claude_code and codex use the subscription-billed CLI; gemini its own.
1114
+ const triageExecutor = (parsedArgs.executor || config.executor || "claude_code").trim()
1115
+ const codexBinary = parsedArgs["codex-bin"] || process.env.CODEX_BIN || "codex"
1116
+ const geminiBinary = parsedArgs["gemini-bin"] || process.env.GEMINI_BIN || "gemini"
1117
+
1118
+ const triageLog = (message) => console.log(`\x1b[2m[${new Date().toISOString()}]\x1b[0m ${message}`)
1119
+
1120
+ const triageApi = async (route, body) => {
1121
+ const res = await fetch(`${appUrl}${route}`, {
1122
+ method: "POST",
1123
+ headers: { "content-type": "application/json", authorization: `Bearer ${apiKey}` },
1124
+ body: JSON.stringify(body),
1125
+ })
1126
+ const text = await res.text()
1127
+ let payload = null
1128
+ try { payload = text ? JSON.parse(text) : null } catch { payload = { error: text.slice(0, 300) } }
1129
+ return { status: res.status, payload }
1130
+ }
1131
+
1132
+ const buildTriageExecSpec = (prompt) => {
1133
+ if (triageExecutor === "codex") {
1134
+ const outputFile = path.join(os.tmpdir(), `pacework-triage-${Date.now()}-${Math.random().toString(36).slice(2)}.txt`)
1135
+ // Completion jobs must only return text to the pacework tool loop.
1136
+ // Loading the user's normal Codex config also loads their MCP
1137
+ // servers, allowing this interpreter process to execute mutations
1138
+ // itself (and potentially call a stale/remote pacework endpoint).
1139
+ const cliArgs = ["exec", "--ignore-user-config", "--ignore-rules", "--sandbox", "read-only"]
1140
+ if (claudeModel) cliArgs.push("-m", claudeModel)
1141
+ cliArgs.push(
1142
+ "--ephemeral",
1143
+ "--color", "never",
1144
+ "--skip-git-repo-check",
1145
+ "--output-last-message", outputFile,
1146
+ "-",
1147
+ )
1148
+ return { command: codexBinary, args: cliArgs, stdinPayload: prompt, outputFile }
1149
+ }
1150
+ if (triageExecutor === "gemini") {
1151
+ const cliArgs = ["-p", prompt, "--output-format", "text"]
1152
+ if (claudeModel) cliArgs.push("--model", claudeModel)
1153
+ return { command: geminiBinary, args: cliArgs, stdinPayload: null, outputFile: null }
1154
+ }
1155
+ // claude_code (default)
1156
+ // As above, give completion jobs no tools and an explicitly empty MCP
1157
+ // config. The outer pacework Slack agent owns all tool execution.
1158
+ const cliArgs = [
1159
+ "-p",
1160
+ "--output-format", "text",
1161
+ "--strict-mcp-config",
1162
+ "--mcp-config", '{"mcpServers":{}}',
1163
+ "--tools", "",
1164
+ ]
1165
+ if (claudeModel) cliArgs.push("--model", claudeModel)
1166
+ return { command: claudeBinary, args: cliArgs, stdinPayload: prompt, outputFile: null }
1167
+ }
1168
+
1169
+ const runExecutorPrompt = (prompt) => new Promise((resolve, reject) => {
1170
+ const spec = buildTriageExecSpec(prompt)
1171
+ const child = spawn(spec.command, spec.args, { stdio: ["pipe", "pipe", "pipe"], env: process.env })
1172
+ let stdout = ""
1173
+ let stderr = ""
1174
+ const timer = setTimeout(() => {
1175
+ child.kill("SIGKILL")
1176
+ reject(new Error(`${spec.command} timed out after ${Math.round(claudeTimeoutMs / 1000)}s`))
1177
+ }, claudeTimeoutMs)
1178
+ const readResult = () => {
1179
+ // Codex writes the final answer to a file; the others stream stdout.
1180
+ if (spec.outputFile) {
1181
+ try {
1182
+ const fileText = fs.readFileSync(spec.outputFile, "utf8").trim()
1183
+ fs.unlinkSync(spec.outputFile)
1184
+ return fileText
1185
+ } catch {
1186
+ return ""
1187
+ }
1188
+ }
1189
+ return stdout.trim()
1190
+ }
1191
+ child.stdout.on("data", (chunk) => { stdout += chunk })
1192
+ child.stderr.on("data", (chunk) => { stderr += chunk })
1193
+ child.on("error", (error) => {
1194
+ clearTimeout(timer)
1195
+ reject(error.code === "ENOENT"
1196
+ ? new Error(`Could not find the "${spec.command}" CLI for executor ${triageExecutor}. Install it or pass --claude-bin/--codex-bin/--gemini-bin.`)
1197
+ : error)
1198
+ })
1199
+ child.on("close", (code) => {
1200
+ clearTimeout(timer)
1201
+ const text = code === 0 ? readResult() : ""
1202
+ if (code === 0 && text) resolve(text)
1203
+ else reject(new Error(`${spec.command} exited with code ${code}: ${stderr.trim().slice(0, 400) || "no output"}`))
1204
+ })
1205
+ if (spec.stdinPayload !== null) child.stdin.write(spec.stdinPayload)
1206
+ child.stdin.end()
1207
+ })
1208
+
1209
+ const processTriageJob = async (job) => {
1210
+ triageLog(`Job ${job.id} claimed; running ${triageExecutor}${claudeModel ? ` (${claudeModel})` : ""}...`)
1211
+ try {
1212
+ const text = await runExecutorPrompt(job.prompt)
1213
+ const complete = await triageApi(`/api/triage-runner/jobs/${job.id}/complete`, {
1214
+ text,
1215
+ model: `${triageExecutor}${claudeModel ? `:${claudeModel}` : ""}`,
1216
+ })
1217
+ if (complete.status >= 400) {
1218
+ triageLog(`\x1b[31mJob ${job.id}: server rejected completion (${complete.status}): ${JSON.stringify(complete.payload)}\x1b[0m`)
1219
+ } else {
1220
+ triageLog(`\x1b[32mJob ${job.id} completed\x1b[0m (confidence: ${complete.payload?.confidence ?? "n/a"})`)
1221
+ }
1222
+ } catch (error) {
1223
+ const message = error instanceof Error ? error.message : String(error)
1224
+ triageLog(`\x1b[31mJob ${job.id} failed: ${message}\x1b[0m`)
1225
+ await triageApi(`/api/triage-runner/jobs/${job.id}/fail`, { error: message }).catch(() => {})
1226
+ }
1227
+ }
1228
+
1229
+ triageLog(`Triage runner "${triageRunnerName}" polling ${appUrl} every ${pollIntervalMs / 1000}s (executor: ${triageExecutor})`)
1230
+ let triageStopping = false
1231
+ process.on("SIGINT", () => { triageStopping = true; triageLog("Stopping after current poll...") })
1232
+ process.on("SIGTERM", () => { triageStopping = true })
1233
+
1234
+ while (!triageStopping) {
1235
+ try {
1236
+ const claim = await triageApi("/api/triage-runner/claim", { runner_name: triageRunnerName })
1237
+ if (claim.status === 401 || claim.status === 403) {
1238
+ console.error(`\x1b[31mAuthentication failed (${claim.status}).\x1b[0m Run \x1b[36mpacework login\x1b[0m again.`)
1239
+ process.exit(1)
1240
+ }
1241
+ if (claim.status >= 400) {
1242
+ triageLog(`Claim failed (${claim.status}): ${JSON.stringify(claim.payload)}`)
1243
+ } else if (claim.payload?.job) {
1244
+ await processTriageJob(claim.payload.job)
1245
+ if (runOnce) break
1246
+ continue
1247
+ }
1248
+ } catch (error) {
1249
+ triageLog(`Poll error: ${error instanceof Error ? error.message : String(error)}`)
1250
+ }
1251
+ if (runOnce) break
1252
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs))
1253
+ }
1254
+ process.exit(0)
1255
+ }
1256
+
1257
+ // ── shell (interactive REPL) ──────────────────────────────────────────────────
1258
+
1259
+ // ── menu (guided interactive mode) ────────────────────────────────────────────
1260
+ // Question-driven UX: numbered choices instead of remembering commands/flags.
1261
+ // Every action shells out to this same CLI, so menu and commands never drift.
1262
+
1263
+ else if (command === "menu") {
1264
+ const runChild = (childArgs) => new Promise((resolve) => {
1265
+ const child = spawn(process.execPath, [process.argv[1], ...childArgs], { stdio: "inherit" })
1266
+ child.on("close", () => resolve())
1267
+ child.on("error", () => resolve())
1268
+ })
1269
+
1270
+ const choose = async (question, options, defaultIndex = 0) => {
1271
+ console.log("")
1272
+ options.forEach((option, index) => {
1273
+ const marker = index === defaultIndex ? "\x1b[36m" : ""
1274
+ console.log(` ${marker}${index + 1}. ${option}\x1b[0m`)
1275
+ })
1276
+ const answer = (await promptLine(`${question} (default ${defaultIndex + 1}, q to cancel): `)).trim()
1277
+ if (/^q(uit)?$/i.test(answer)) return -1
1278
+ const picked = answer ? Number(answer) - 1 : defaultIndex
1279
+ return Number.isInteger(picked) && picked >= 0 && picked < options.length ? picked : defaultIndex
1280
+ }
1281
+
1282
+ const TRIAGE_MODELS = {
1283
+ claude_code: ["CLI default", "haiku", "sonnet", "opus"],
1284
+ codex: ["CLI default", "gpt-5.5", "gpt-5.5-pro"],
1285
+ gemini: ["CLI default", "gemini-2.5-flash", "gemini-2.5-pro"],
1286
+ }
1287
+
1288
+ const guidedTriage = async (config) => {
1289
+ const executors = ["claude_code", "codex", "gemini"]
1290
+ const executorLabels = {
1291
+ claude_code: "Claude Code (Claude subscription)",
1292
+ codex: "Codex (ChatGPT subscription)",
1293
+ gemini: "Gemini CLI",
1294
+ }
1295
+ const defaultExecutorIndex = Math.max(0, executors.indexOf(config.executor))
1296
+ const executorIndex = await choose(
1297
+ "Which AI runs triage jobs?",
1298
+ executors.map((name) => executorLabels[name]),
1299
+ defaultExecutorIndex,
1300
+ )
1301
+ if (executorIndex < 0) return
1302
+ const executor = executors[executorIndex]
1303
+
1304
+ const models = TRIAGE_MODELS[executor] ?? ["CLI default"]
1305
+ const modelIndex = await choose("Which model?", models, 0)
1306
+ if (modelIndex < 0) return
1307
+ const model = modelIndex === 0 ? null : models[modelIndex]
1308
+
1309
+ const modeIndex = await choose("How should it run?", [
1310
+ "Keep running (poll for jobs until Ctrl-C)",
1311
+ "Process one job, then exit",
1312
+ ], 0)
1313
+ if (modeIndex < 0) return
1314
+
1315
+ const childArgs = ["triage", "--executor", executor]
1316
+ if (model) childArgs.push("--model", model)
1317
+ if (modeIndex === 1) childArgs.push("--once", "true")
1318
+ console.log(`\n\x1b[2m→ pacework triage ${childArgs.slice(1).join(" ")}\x1b[0m\n`)
1319
+ await runChild(childArgs)
1320
+ }
1321
+
1322
+ const guidedAgentRunner = async () => {
1323
+ const modeIndex = await choose("How should the agent runner run?", [
1324
+ "Background daemon (keeps running after this menu closes)",
1325
+ "Foreground (watch output, Ctrl-C to stop)",
1326
+ ], 0)
1327
+ if (modeIndex < 0) return
1328
+ await runChild([modeIndex === 0 ? "start" : "connect"])
1329
+ }
1330
+
1331
+ let menuRunning = true
1332
+ while (menuRunning) {
1333
+ const config = readConfig()
1334
+ console.clear()
1335
+ printBanner(config)
1336
+ if (config.apiKey) {
1337
+ console.log(` Workspace: \x1b[1m${config.workspaceSlug ?? config.workspaceId ?? "?"}\x1b[0m Executor: \x1b[1m${executorLabel(config.executor) ?? config.executor ?? "not set"}\x1b[0m`)
1338
+ } else {
1339
+ console.log(" \x1b[33mNot logged in yet — pick “Log in” to get started.\x1b[0m")
1340
+ }
1341
+
1342
+ const loggedIn = Boolean(config.apiKey)
1343
+ const entries = loggedIn
1344
+ ? [
1345
+ { label: "Run triage (pacework Intelligence on this machine)", action: () => guidedTriage(config) },
1346
+ { label: "Run the agent runner (works on issues)", action: guidedAgentRunner },
1347
+ { label: "Status", action: () => runChild(["status"]) },
1348
+ { label: "Recent jobs", action: () => runChild(["jobs"]) },
1349
+ { label: "Tail runner logs", action: () => runChild(["logs"]) },
1350
+ { label: "Stop background runner", action: () => runChild(["stop"]) },
1351
+ { label: "Health check (doctor)", action: () => runChild(["doctor"]) },
1352
+ { label: "Switch executor", action: async () => {
1353
+ const executorIndex = await choose(
1354
+ "Which executor?",
1355
+ EXECUTORS.map((executor) => `${executor.label}${checkBinaryExists(executor.bin) ? "" : " (not installed)"}`),
1356
+ Math.max(0, EXECUTORS.findIndex((executor) => executor.id === config.executor)),
1357
+ )
1358
+ if (executorIndex < 0) return
1359
+ await runChild(["use", EXECUTORS[executorIndex].id])
1360
+ } },
1361
+ { label: "Log in again / switch workspace", action: () => runChild(["login"]) },
1362
+ { label: "Log out", action: () => runChild(["logout"]) },
1363
+ { label: "Quit", action: null },
1364
+ ]
1365
+ : [
1366
+ { label: "Log in (opens your browser)", action: () => runChild(["login"]) },
1367
+ { label: "Status", action: () => runChild(["status"]) },
1368
+ { label: "Quit", action: null },
1369
+ ]
1370
+
1371
+ const pickedIndex = await choose("What do you want to do?", entries.map((entry) => entry.label), 0)
1372
+ const picked = pickedIndex < 0 ? entries[entries.length - 1] : entries[pickedIndex]
1373
+ if (!picked.action) {
1374
+ menuRunning = false
1375
+ break
1376
+ }
1377
+ await picked.action()
1378
+ if (menuRunning) {
1379
+ await promptLine("\n\x1b[2mPress Enter to return to the menu…\x1b[0m")
1380
+ }
1381
+ }
1382
+ process.exit(0)
1383
+ }
1384
+
1385
+ else if (command === "shell" || command === "sh") {
1386
+ printBanner(readConfig())
1387
+
1388
+ const SHELL_COMMANDS = ["status", "jobs", "logs", "tail", "config", "use", "doctor", "start", "stop", "restart", "connect", "login", "logout", "whoami", "rename", "open", "update", "help", "exit", "quit", "clear"]
1389
+
1390
+ // ── fetch active runs from API ──────────────────────────────────────────────
1391
+ async function fetchActiveRuns(config) {
1392
+ const key = config.apiKey ?? config.workspaceApiKey
1393
+ const appUrl = config.appUrl ?? "https://pacework.io"
1394
+ const wsId = config.workspaceId
1395
+ if (!key || !wsId) return null
1396
+ try {
1397
+ const res = await fetch(`${appUrl}/api/workspaces/${wsId}/agent-runner/runs?limit=8`, {
1398
+ headers: { "x-workspace-api-key": key },
1399
+ signal: AbortSignal.timeout(3000),
1400
+ })
1401
+ if (!res.ok) return null
1402
+ return await res.json()
1403
+ } catch { return null }
1404
+ }
1405
+
1406
+ function printJobsTable(runs) {
1407
+ if (!runs?.length) return
1408
+ const STATUS_COLORS = {
1409
+ running: "\x1b[34m",
1410
+ queued: "\x1b[33m",
1411
+ pending: "\x1b[33m",
1412
+ completed: "\x1b[32m",
1413
+ failed: "\x1b[31m",
1414
+ error: "\x1b[31m",
1415
+ cancelled: "\x1b[2m",
1416
+ }
1417
+ const STATUS_GLYPH = {
1418
+ running: "▶",
1419
+ queued: "◌",
1420
+ pending: "◌",
1421
+ completed: "✓",
1422
+ failed: "✗",
1423
+ error: "✗",
1424
+ cancelled: "–",
1425
+ }
1426
+ // column widths
1427
+ const COL_STATUS = 10
1428
+ const COL_TITLE = 34
1429
+ const COL_AGE = 10
1430
+ const COL_DUR = 8
1431
+ const hr = ` ${"─".repeat(COL_STATUS + COL_TITLE + COL_AGE + COL_DUR + 6)}`
1432
+ console.log(`\x1b[1mActive runs\x1b[0m`)
1433
+ console.log(hr)
1434
+ console.log(` \x1b[2m${"STATUS".padEnd(COL_STATUS)} ${"TASK".padEnd(COL_TITLE)} ${"AGE".padEnd(COL_AGE)} ${"DURATION".padEnd(COL_DUR)}\x1b[0m`)
1435
+ console.log(hr)
1436
+ for (const r of runs) {
1437
+ const status = (r.status ?? "unknown").toLowerCase()
1438
+ const col = STATUS_COLORS[status] ?? ""
1439
+ const glyph = STATUS_GLYPH[status] ?? "·"
1440
+ const label = `${glyph} ${status}`.padEnd(COL_STATUS)
1441
+ const title = (r.task_title ?? r.task_identifier ?? r.id?.slice(0, 8) ?? "—").slice(0, COL_TITLE).padEnd(COL_TITLE)
1442
+ const age = relTime(r.started_at ?? r.created_at).padEnd(COL_AGE)
1443
+ const dur = r.started_at && r.completed_at
1444
+ ? fmtDuration(new Date(r.completed_at) - new Date(r.started_at)).padEnd(COL_DUR)
1445
+ : r.started_at ? fmtDuration(Date.now() - new Date(r.started_at)).padEnd(COL_DUR) : "".padEnd(COL_DUR)
1446
+ console.log(` ${col}${label}\x1b[0m \x1b[1m${title}\x1b[0m \x1b[2m${age} ${dur}\x1b[0m`)
1447
+ }
1448
+ console.log(hr)
1449
+ console.log("")
1450
+ }
1451
+
1452
+ async function printWelcome() {
1453
+ const config = readConfig()
1454
+ const pid = readPid()
1455
+ const running = pid && isRunning(pid)
1456
+ const loggedIn = !!(config.apiKey || config.workspaceApiKey)
1457
+ const cols = process.stdout.columns || 80
1458
+ const W = Math.min(cols - 4, 72)
1459
+ const div = ` \x1b[38;5;237m${"─".repeat(W)}\x1b[0m`
1460
+
1461
+ if (!loggedIn) {
1462
+ console.log(` \x1b[33m⚠ Not logged in\x1b[0m — run \x1b[36m/login\x1b[0m to connect\n`)
1463
+ } else {
1464
+ const runs = await fetchActiveRuns(config)
1465
+ if (runs?.length) {
1466
+ printJobsTable(runs)
1467
+ } else {
1468
+ console.log(` \x1b[2mNo active runs\x1b[0m`)
1469
+ console.log("")
1470
+ }
1471
+ }
1472
+
1473
+ console.log(div)
1474
+ console.log(` \x1b[2m/\x1b[0m browse commands \x1b[2m↑↓\x1b[0m navigate \x1b[2mTab\x1b[0m complete \x1b[2m/help\x1b[0m full list`)
1475
+ console.log(div)
1476
+ console.log("")
1477
+ }
1478
+
1479
+ await printWelcome()
1480
+
1481
+ // ── auto-start runner if logged in but not running ────────────────────────
1482
+ {
1483
+ const cfg = readConfig()
1484
+ const pid = readPid()
1485
+ const loggedIn = !!(cfg.apiKey || cfg.workspaceApiKey)
1486
+ if (loggedIn && (!pid || !isRunning(pid))) {
1487
+ console.log(`\x1b[2mStarting runner in background…\x1b[0m`)
1488
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), "start"], {
1489
+ stdio: "inherit",
1490
+ env: { ...process.env, PATH: process.env.PATH || "" },
1491
+ })
1492
+ await new Promise(r => child.on("exit", r))
1493
+ }
1494
+ }
1495
+
1496
+ function shellPrompt(config) {
1497
+ const ws = config.workspaceSlug ?? config.workspaceId ?? "?"
1498
+ const exe = config.executor ?? "?"
1499
+ const pid = readPid()
1500
+ const running = pid && isRunning(pid)
1501
+ const runnerStatus = running ? `\x1b[32m●\x1b[0m` : `\x1b[2m○\x1b[0m`
1502
+ return `${runnerStatus} \x1b[2m${ws} · ${exe}\x1b[0m \x1b[36m>\x1b[0m `
1503
+ }
1504
+
1505
+ // ── orchestrator helpers ──────────────────────────────────────────────────
1506
+
1507
+ function readRunnerId(config) {
1508
+ try {
1509
+ const stateFile = path.join(config.repoRoot ?? process.cwd(), ".agent", "runners", `${config.workspaceId}-${config.executor ?? "claude_code"}.json`)
1510
+ const state = JSON.parse(fs.readFileSync(stateFile, "utf8"))
1511
+ return state.runner_id ?? null
1512
+ } catch { return null }
1513
+ }
1514
+
1515
+ async function runnerControlCommand(config, action, extra = {}) {
1516
+ const key = config.apiKey ?? config.workspaceApiKey
1517
+ const wsId = config.workspaceId
1518
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
1519
+ if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); return }
1520
+
1521
+ const runnerId = readRunnerId(config)
1522
+ if (!runnerId) {
1523
+ console.log(`\n \x1b[33m⚠\x1b[0m Runner ID not found. Start the runner first (/start) so it registers.\n`)
1524
+ return
1525
+ }
1526
+
1527
+ const labels = { pause: "Pausing", resume: "Resuming", set_capacity: "Updating capacity" }
1528
+ console.log(`\n \x1b[2m${labels[action] ?? action} runner ${runnerId.slice(0,8)}…\x1b[0m`)
1529
+ try {
1530
+ const res = await fetch(`${appUrl}/api/workspaces/${wsId}/agent-runners/${runnerId}/control`, {
1531
+ method: "POST",
1532
+ headers: { "content-type": "application/json", "x-workspace-api-key": key },
1533
+ body: JSON.stringify({ action, ...extra }),
1534
+ signal: AbortSignal.timeout(5000),
1535
+ })
1536
+ if (res.ok) {
1537
+ const msgs = { pause: "Runner paused — no new jobs will be picked up", resume: "Runner resumed", set_capacity: `Max parallel runs set to ${extra.max_parallel_runs}` }
1538
+ console.log(` \x1b[32m✓\x1b[0m ${msgs[action] ?? "Done"}`)
1539
+ } else {
1540
+ const b = await res.json().catch(() => ({}))
1541
+ console.log(` \x1b[31m✗\x1b[0m Failed (${res.status}): ${b.message ?? b.error ?? ""}`)
1542
+ }
1543
+ } catch (e) { console.log(` \x1b[31mFailed: ${e.message}\x1b[0m`) }
1544
+ console.log("")
1545
+ }
1546
+
1547
+ async function fetchMcpServerList(config) {
1548
+ const key = config.apiKey ?? config.workspaceApiKey
1549
+ const wsId = config.workspaceId
1550
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
1551
+ const runnerId = readRunnerId(config)
1552
+ if (!key || !wsId || !runnerId) return null
1553
+ try {
1554
+ const res = await fetch(`${appUrl}/api/agent-runners/mcp-servers?workspace_id=${encodeURIComponent(wsId)}&runner_id=${encodeURIComponent(runnerId)}`, {
1555
+ headers: { Authorization: `Bearer ${key}` },
1556
+ signal: AbortSignal.timeout(4000),
1557
+ })
1558
+ if (!res.ok) return null
1559
+ const data = await res.json()
1560
+ return Array.isArray(data?.mcp_servers) ? data.mcp_servers : null
1561
+ } catch { return null }
1562
+ }
1563
+
1564
+ async function runShellCommand(input) {
1565
+ const parts = input.trim().split(/\s+/)
1566
+ const cmd = parts[0]
1567
+ const args = parts.slice(1)
1568
+
1569
+ switch (cmd) {
1570
+ case "help": {
1571
+ const cols = process.stdout.columns || 80
1572
+ const W = Math.min(cols - 4, 72)
1573
+ const div = ` \x1b[38;5;237m${"─".repeat(W)}\x1b[0m`
1574
+ const sec = (label) => `\n \x1b[38;5;240m${label}\x1b[0m`
1575
+ const cmd = (c, d) => ` \x1b[36m${c.padEnd(18)}\x1b[0m \x1b[2m${d}\x1b[0m`
1576
+ console.log("")
1577
+ console.log(div)
1578
+ console.log(sec("RUNNER"))
1579
+ console.log(cmd("start", "Start runner as background daemon"))
1580
+ console.log(cmd("stop", "Stop the background daemon"))
1581
+ console.log(cmd("restart", "Stop then start daemon"))
1582
+ console.log(cmd("connect", "Run runner in foreground"))
1583
+ console.log(cmd("pause", "Pause — no new jobs picked up"))
1584
+ console.log(cmd("resume", "Resume a paused runner"))
1585
+ console.log(cmd("capacity <n>", "Set max parallel jobs"))
1586
+ console.log(sec("JOBS"))
1587
+ console.log(cmd("jobs", "Active runs + recent history"))
1588
+ console.log(cmd("watch", "Auto-refresh jobs every 3s"))
1589
+ console.log(cmd("run <issue-id>", "Dispatch issue to this runner"))
1590
+ console.log(cmd("cancel <run-id>","Cancel a running job"))
1591
+ console.log(cmd("retry <run-id>", "Retry a failed job"))
1592
+ console.log(cmd("stats", "Throughput metrics"))
1593
+ console.log(sec("ISSUES & AGENTS"))
1594
+ console.log(cmd("issues", "List issues (open / active / all / in_progress …)"))
1595
+ console.log(cmd("mine", "Issues assigned to you"))
1596
+ console.log(cmd("issue <id>", "View issue detail, description, comments"))
1597
+ console.log(cmd("agents", "List agents and their skill profiles"))
1598
+ console.log(cmd("dashboard", "Orchestration status — runs, queue, review"))
1599
+ console.log(cmd("logtail <run-id>","Stream live log of a running job"))
1600
+ console.log(cmd("open [id]", "Open workspace (or specific issue) in browser"))
1601
+ console.log(sec("MCP & EXECUTOR"))
1602
+ console.log(cmd("mcp install", "Inject pacework MCP into executor config"))
1603
+ console.log(cmd("mcp status", "Show configured MCP servers"))
1604
+ console.log(cmd("mcp test", "Ping MCP servers"))
1605
+ console.log(cmd("executor test", "Smoke-test the executor binary"))
1606
+ console.log(sec("LOGS"))
1607
+ console.log(cmd("tail", "Live-stream the runner log"))
1608
+ console.log(cmd("logs [n]", "Tail last N log lines"))
1609
+ console.log(sec("CONFIG & AUTH"))
1610
+ console.log(cmd("status", "Runner status and config"))
1611
+ console.log(cmd("whoami", "Workspace and key info"))
1612
+ console.log(cmd("config", "View or set config values"))
1613
+ console.log(cmd("use <executor>", "Switch executor"))
1614
+ console.log(cmd("rename <name>", "Set runner display name"))
1615
+ console.log(cmd("doctor", "Check all dependencies"))
1616
+ console.log(cmd("update", "Upgrade pacework-runner"))
1617
+ console.log(cmd("login", "Authenticate via browser"))
1618
+ console.log(cmd("logout", "Revoke API key and clear credentials"))
1619
+ console.log(sec("SHELL"))
1620
+ console.log(cmd("clear", "Clear screen"))
1621
+ console.log(cmd("exit", "Exit the shell"))
1622
+ console.log("")
1623
+ console.log(div)
1624
+ console.log("")
1625
+ break
1626
+ }
1627
+ case "clear": {
1628
+ process.stdout.write("\x1b[2J\x1b[0f")
1629
+ printBanner(readConfig())
1630
+ await printWelcome()
1631
+ break
1632
+ }
1633
+ case "exit":
1634
+ case "quit": {
1635
+ console.log("Bye.")
1636
+ process.exit(0)
1637
+ }
1638
+ case "status": {
1639
+ const config = readConfig()
1640
+ const pid = readPid()
1641
+ const running = pid && isRunning(pid)
1642
+ console.log("")
1643
+ if (running) {
1644
+ let startedAt = ""
1645
+ try { const c = JSON.parse(fs.readFileSync(CMD_FILE, "utf8")); startedAt = ` started ${relTime(c.startedAt)}` } catch {}
1646
+ console.log(` \x1b[32m●\x1b[0m Running (PID ${pid}${startedAt})`)
1647
+ } else {
1648
+ console.log(` \x1b[2m○\x1b[0m Stopped`)
1649
+ }
1650
+ if (config.workspaceSlug) console.log(` workspace ${config.workspaceSlug}`)
1651
+ if (config.executor) console.log(` executor ${executorLabel(config.executor)}`)
1652
+ if (config.runnerName) console.log(` name ${config.runnerName}`)
1653
+ if (config.repoRoot) console.log(` repo ${config.repoRoot}`)
1654
+ console.log("")
1655
+ break
1656
+ }
1657
+ case "use": {
1658
+ const target = args[0]
1659
+ const valid = EXECUTORS.map(e => e.id)
1660
+ if (!target || !valid.includes(target)) {
1661
+ console.log(`Usage: use <executor>\nAvailable: ${valid.join(", ")}`)
1662
+ break
1663
+ }
1664
+ const config = readConfig()
1665
+ const prev = config.executor ?? "codex"
1666
+ if (!checkBinaryExists(EXECUTORS.find(e => e.id === target).bin)) {
1667
+ console.log(`\x1b[33m⚠ ${target} binary not found in PATH — switching anyway\x1b[0m`)
1668
+ }
1669
+ config.executor = target
1670
+ if (config.runnerName === EXECUTOR_DEFAULT_NAMES[prev]) config.runnerName = EXECUTOR_DEFAULT_NAMES[target] ?? config.runnerName
1671
+ writeConfig(config)
1672
+ console.log(`\x1b[32m✓\x1b[0m Switched to \x1b[1m${executorLabel(target)}\x1b[0m — restart runner to apply`)
1673
+ break
1674
+ }
1675
+ case "config": {
1676
+ const KEY_ALIASES = { "executor": "executor", "name": "runnerName", "runner-name": "runnerName", "repo-root": "repoRoot", "app-url": "appUrl", "workspace-id": "workspaceId" }
1677
+ const config = readConfig()
1678
+ const key = args[0]
1679
+ const value = args[1]
1680
+ if (!key) {
1681
+ console.log("")
1682
+ const rows = [
1683
+ ["workspace", config.workspaceSlug ?? config.workspaceId ?? "\x1b[2mnot set\x1b[0m"],
1684
+ ["executor", config.executor ? `${executorLabel(config.executor)} (${config.executor})` : "\x1b[2mnot set\x1b[0m"],
1685
+ ["name", config.runnerName ?? "\x1b[2mnot set\x1b[0m"],
1686
+ ["repo-root", config.repoRoot ?? "\x1b[2mnot set\x1b[0m"],
1687
+ ["app-url", config.appUrl ?? "https://pacework.io"],
1688
+ ["api-key", config.apiKey ? `\x1b[2m${config.apiKey.slice(0, 16)}…\x1b[0m` : "\x1b[2mnot set\x1b[0m"],
1689
+ ]
1690
+ rows.forEach(([k, v]) => console.log(` ${k.padEnd(12)} ${v}`))
1691
+ console.log("")
1692
+ } else {
1693
+ const configKey = KEY_ALIASES[key]
1694
+ if (!configKey) { console.log(`Unknown key: ${key}. Valid: ${Object.keys(KEY_ALIASES).join(", ")}`); break }
1695
+ if (!value) { console.log(`${key}: ${config[configKey] ?? "\x1b[2mnot set\x1b[0m"}`); break }
1696
+ config[configKey] = value
1697
+ writeConfig(config)
1698
+ console.log(`\x1b[32m✓\x1b[0m ${key} = \x1b[1m${value}\x1b[0m`)
1699
+ }
1700
+ break
1701
+ }
1702
+ case "jobs": {
1703
+ const limit = parseInt(args[0], 10) || 20
1704
+ const config = readConfig()
1705
+ console.log("")
1706
+
1707
+ // ── active runs from API ──────────────────────────────────────
1708
+ const apiRuns = await fetchActiveRuns(config)
1709
+ const activeIds = new Set()
1710
+ if (apiRuns?.length) {
1711
+ printJobsTable(apiRuns)
1712
+ for (const r of apiRuns) if (r.id) activeIds.add(r.id)
1713
+ } else {
1714
+ console.log(` \x1b[2mNo active runs.\x1b[0m\n`)
1715
+ }
1716
+
1717
+ // ── recent history from log ───────────────────────────────────
1718
+ try {
1719
+ const raw = fs.readFileSync(LOG_FILE, "utf8")
1720
+ const events = []
1721
+ for (const line of raw.split("\n")) {
1722
+ if (!line.trim()) continue
1723
+ try {
1724
+ const e = JSON.parse(line)
1725
+ if (["runner.job.start","runner.job.complete","runner.job.error"].includes(e.event)) events.push(e)
1726
+ } catch {}
1727
+ }
1728
+ const byRun = new Map()
1729
+ for (const j of events) {
1730
+ const id = j.run_id ?? j.meta?.run_id ?? "unknown"
1731
+ if (!byRun.has(id)) byRun.set(id, { id, task_title: j.meta?.task_title ?? j.meta?.task_identifier ?? id.slice(0, 8), started_at: null, completed_at: null, status: "pending", error: null })
1732
+ const entry = byRun.get(id)
1733
+ if (j.event === "runner.job.start") { entry.started_at = j.ts; entry.status = "running" }
1734
+ if (j.event === "runner.job.complete") { entry.completed_at = j.ts; entry.status = "completed" }
1735
+ if (j.event === "runner.job.error") { entry.completed_at = j.ts; entry.status = "error"; entry.error = j.msg }
1736
+ }
1737
+ const history = Array.from(byRun.values())
1738
+ .filter(r => !activeIds.has(r.id))
1739
+ .slice(-limit).reverse()
1740
+ if (history.length) {
1741
+ console.log(`\x1b[1mHistory\x1b[0m \x1b[2m(last ${history.length})\x1b[0m`)
1742
+ printJobsTable(history)
1743
+ }
1744
+ } catch {}
1745
+ break
1746
+ }
1747
+ case "logs": {
1748
+ const n = parseInt(args[0], 10) || 20
1749
+ try {
1750
+ const content = fs.readFileSync(LOG_FILE, "utf8")
1751
+ const tail = content.split("\n").filter(Boolean).slice(-n)
1752
+ console.log("")
1753
+ const formatted = tail.map(formatLogLine).filter(Boolean)
1754
+ console.log(formatted.length ? formatted.join("\n") : tail.join("\n"))
1755
+ console.log("")
1756
+ } catch { console.log("No log file found.") }
1757
+ break
1758
+ }
1759
+ case "start": {
1760
+ const pid = readPid()
1761
+ if (pid && isRunning(pid)) { console.log(`Runner already running (PID ${pid})`); break }
1762
+ console.log("Starting runner in background…")
1763
+ // Spawn this ctl with start args so it picks up config
1764
+ const child = spawn(process.execPath, [fileURLToPath(import.meta.url), "start"], {
1765
+ stdio: "inherit",
1766
+ env: { ...process.env, PATH: process.env.PATH || "" },
1767
+ })
1768
+ await new Promise(r => child.on("exit", r))
1769
+ break
1770
+ }
1771
+ case "stop": {
1772
+ const pid = readPid()
1773
+ if (!pid || !isRunning(pid)) {
1774
+ // Still sweep: a previous stop can leave an orphan whose parent
1775
+ // died after the sweep ran, and the pid file no longer names it.
1776
+ let orphaned = 0
1777
+ for (let attempt = 0; attempt < 5; attempt++) {
1778
+ const strays = findStrayRunnerPids(pid ?? 0)
1779
+ if (strays.length === 0) break
1780
+ for (const stray of strays) {
1781
+ try { process.kill(stray, "SIGKILL"); orphaned += 1 } catch {}
1782
+ }
1783
+ await new Promise(r => setTimeout(r, 400))
1784
+ }
1785
+ clearPid()
1786
+ console.log(orphaned > 0
1787
+ ? `\x1b[32m✓\x1b[0m Cleaned up ${orphaned} orphaned runner process(es).`
1788
+ : "Runner is not running.")
1789
+ break
1790
+ }
1791
+ try {
1792
+ process.kill(pid, "SIGTERM")
1793
+
1794
+ // SIGTERM was previously fire-and-forget: it reported success
1795
+ // immediately, so a runner that ignored it kept running and
1796
+ // competed with the next one for jobs. Wait, then escalate.
1797
+ const deadline = Date.now() + 5000
1798
+ while (isRunning(pid) && Date.now() < deadline) {
1799
+ await new Promise(r => setTimeout(r, 200))
1800
+ }
1801
+ if (isRunning(pid)) {
1802
+ process.kill(pid, "SIGKILL")
1803
+ await new Promise(r => setTimeout(r, 500))
1804
+ }
1805
+
1806
+ // The watchdog spawns the runner as a separate process, so
1807
+ // killing the watchdog alone can leave the runner orphaned. The
1808
+ // child can also outlive the first sweep, so this repeats until
1809
+ // nothing is left.
1810
+ let killed = 0
1811
+ for (let attempt = 0; attempt < 5; attempt++) {
1812
+ const strays = findStrayRunnerPids(pid)
1813
+ if (strays.length === 0) break
1814
+ for (const stray of strays) {
1815
+ try { process.kill(stray, "SIGKILL"); killed += 1 } catch {}
1816
+ }
1817
+ await new Promise(r => setTimeout(r, 400))
1818
+ }
1819
+
1820
+ clearPid()
1821
+ const extra = killed > 0 ? ` (+${killed} orphaned)` : ""
1822
+ console.log(`\x1b[32m✓\x1b[0m Stopped (PID ${pid})${extra}`)
1823
+ }
1824
+ catch (e) { console.log(`\x1b[31mFailed: ${e.message}\x1b[0m`) }
1825
+ break
1826
+ }
1827
+ case "doctor": {
1828
+ const config = readConfig()
1829
+ const ok = (msg) => console.log(` \x1b[32m✓\x1b[0m ${msg}`)
1830
+ const err = (msg) => console.log(` \x1b[31m✗\x1b[0m ${msg}`)
1831
+ const wrn = (msg) => console.log(` \x1b[33m⚠\x1b[0m ${msg}`)
1832
+ console.log(`\n\x1b[1mDiagnostics\x1b[0m\n`)
1833
+
1834
+ // Node version
1835
+ const nodeVer = process.versions.node
1836
+ const [nodeMaj] = nodeVer.split(".").map(Number)
1837
+ nodeMaj >= 18 ? ok(`Node.js ${nodeVer}`) : err(`Node.js ${nodeVer} — requires ≥18`)
1838
+
1839
+ // Auth
1840
+ const key = config.apiKey ?? config.workspaceApiKey
1841
+ key ? ok(`API key set \x1b[2m(${key.slice(0,16)}…)\x1b[0m`) : err(`No API key — run /login`)
1842
+ config.workspaceSlug ? ok(`Workspace: ${config.workspaceSlug}`) : err(`No workspace — run /login`)
1843
+
1844
+ // App URL reachability
1845
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
1846
+ try {
1847
+ const t0 = Date.now()
1848
+ const r = await fetch(`${appUrl}/api/health`, { signal: AbortSignal.timeout(3000) })
1849
+ const ms = Date.now() - t0
1850
+ r.ok ? ok(`App reachable: ${appUrl} \x1b[2m(${ms}ms)\x1b[0m`) : wrn(`App returned ${r.status}: ${appUrl}`)
1851
+ } catch { err(`Cannot reach app: ${appUrl}`) }
1852
+
1853
+ // Executor binary
1854
+ const exe = EXECUTORS.find(e => e.id === (config.executor ?? "codex"))
1855
+ if (exe) {
1856
+ checkBinaryExists(exe.bin)
1857
+ ? ok(`Executor: ${exe.label} \x1b[2m(${exe.bin})\x1b[0m`)
1858
+ : err(`Executor binary not found: ${exe.bin} — install ${exe.label} or run /use to switch`)
1859
+ }
1860
+
1861
+ // Repo root
1862
+ if (config.repoRoot) {
1863
+ try {
1864
+ fs.accessSync(config.repoRoot)
1865
+ ok(`Repo root: ${config.repoRoot}`)
1866
+ } catch { err(`Repo root not found: ${config.repoRoot} — run /config repo-root <path>`) }
1867
+ } else {
1868
+ wrn(`Repo root not set — run /config repo-root <path>`)
1869
+ }
1870
+
1871
+ // Runner daemon
1872
+ const dpid = readPid()
1873
+ dpid && isRunning(dpid)
1874
+ ? ok(`Runner daemon running \x1b[2m(PID ${dpid})\x1b[0m`)
1875
+ : wrn(`Runner daemon not running — run /start`)
1876
+
1877
+ // pacework version
1878
+ ok(`pacework-runner v${LOCAL_VERSION ?? "unknown"}`)
1879
+
1880
+ console.log("")
1881
+ break
1882
+ }
1883
+ case "restart": {
1884
+ const pid = readPid()
1885
+ if (pid && isRunning(pid)) {
1886
+ try { process.kill(pid, "SIGTERM"); clearPid(); console.log(`\x1b[32m✓\x1b[0m Stopped (PID ${pid})`) }
1887
+ catch (e) { console.log(`\x1b[31mStop failed: ${e.message}\x1b[0m`); break }
1888
+ await new Promise(r => setTimeout(r, 800))
1889
+ }
1890
+ console.log("Starting runner in background…")
1891
+ const rchild = spawn(process.execPath, [fileURLToPath(import.meta.url), "start"], {
1892
+ stdio: "inherit",
1893
+ env: { ...process.env, PATH: process.env.PATH || "" },
1894
+ })
1895
+ await new Promise(r => rchild.on("exit", r))
1896
+ break
1897
+ }
1898
+ case "tail": {
1899
+ console.log(`\x1b[2mStreaming log — press Ctrl+C to stop\x1b[0m\n`)
1900
+ try {
1901
+ const tail = spawn("tail", ["-f", "-n", "40", LOG_FILE], { stdio: ["ignore", "pipe", "ignore"] })
1902
+ tail.stdout.on("data", chunk => {
1903
+ const lines = chunk.toString().split("\n")
1904
+ for (const l of lines) {
1905
+ const fmt = formatLogLine(l)
1906
+ if (fmt) process.stdout.write(fmt + "\n")
1907
+ }
1908
+ })
1909
+ await new Promise(resolve => {
1910
+ process.once("SIGINT", () => { tail.kill(); resolve() })
1911
+ tail.on("exit", resolve)
1912
+ })
1913
+ console.log("")
1914
+ } catch { console.log("No log file yet.") }
1915
+ break
1916
+ }
1917
+ case "watch": {
1918
+ const config = readConfig()
1919
+ let watching = true
1920
+ let watchLines = 0
1921
+ const stopWatch = () => { watching = false }
1922
+ process.once("SIGINT", stopWatch)
1923
+ const watchRunIds = new Set()
1924
+
1925
+ const renderWatch = async () => {
1926
+ const runs = await fetchActiveRuns(config)
1927
+ // bell notification when a previously-seen run is no longer active
1928
+ const currentIds = new Set((runs ?? []).map(r => r.id).filter(Boolean))
1929
+ for (const prevId of watchRunIds) {
1930
+ if (!currentIds.has(prevId)) process.stdout.write("\x07")
1931
+ }
1932
+ watchRunIds.clear()
1933
+ for (const r of (runs ?? [])) if (r.id && r.status === "running") watchRunIds.add(r.id)
1934
+ const pid2 = readPid()
1935
+ const running2 = pid2 && isRunning(pid2)
1936
+ const dot = running2 ? `\x1b[32m● Running\x1b[0m` : `\x1b[2m○ Stopped\x1b[0m`
1937
+
1938
+ // build output lines in a buffer so we can measure
1939
+ const lines = []
1940
+ lines.push(` ${dot} \x1b[2m${new Date().toLocaleTimeString()} — Ctrl+C to stop\x1b[0m`)
1941
+ lines.push("")
1942
+ if (runs?.length) {
1943
+ const COL_STATUS = 10, COL_TITLE = 34, COL_AGE = 10, COL_DUR = 8
1944
+ const hr = ` ${"─".repeat(COL_STATUS + COL_TITLE + COL_AGE + COL_DUR + 6)}`
1945
+ const STATUS_COLORS = { running:"\x1b[34m", queued:"\x1b[33m", pending:"\x1b[33m", completed:"\x1b[32m", failed:"\x1b[31m", error:"\x1b[31m", cancelled:"\x1b[2m" }
1946
+ const STATUS_GLYPH = { running:"▶", queued:"◌", pending:"◌", completed:"✓", failed:"✗", error:"✗", cancelled:"–" }
1947
+ lines.push(`\x1b[1mActive runs\x1b[0m`)
1948
+ lines.push(hr)
1949
+ lines.push(` \x1b[2m${"STATUS".padEnd(COL_STATUS)} ${"TASK".padEnd(COL_TITLE)} ${"AGE".padEnd(COL_AGE)} ${"DURATION".padEnd(COL_DUR)}\x1b[0m`)
1950
+ lines.push(hr)
1951
+ for (const r of runs) {
1952
+ const status = (r.status ?? "unknown").toLowerCase()
1953
+ const label = `${STATUS_GLYPH[status] ?? "·"} ${status}`.padEnd(COL_STATUS)
1954
+ const title = (r.task_title ?? r.task_identifier ?? r.id?.slice(0,8) ?? "—").slice(0,COL_TITLE).padEnd(COL_TITLE)
1955
+ const age = relTime(r.started_at ?? r.created_at).padEnd(COL_AGE)
1956
+ const dur = r.started_at && r.completed_at ? fmtDuration(new Date(r.completed_at)-new Date(r.started_at)).padEnd(COL_DUR) : r.started_at ? fmtDuration(Date.now()-new Date(r.started_at)).padEnd(COL_DUR) : "".padEnd(COL_DUR)
1957
+ lines.push(` ${STATUS_COLORS[status]??""}}${label}\x1b[0m \x1b[1m${title}\x1b[0m \x1b[2m${age} ${dur}\x1b[0m`)
1958
+ }
1959
+ lines.push(hr)
1960
+ } else {
1961
+ lines.push(` \x1b[2mNo active runs.\x1b[0m`)
1962
+ }
1963
+
1964
+ // erase previous render in-place
1965
+ if (watchLines > 0) {
1966
+ process.stdout.write(`\x1b[${watchLines}A\x1b[J`)
1967
+ }
1968
+ process.stdout.write(lines.join("\n") + "\n")
1969
+ watchLines = lines.length
1970
+ }
1971
+
1972
+ await renderWatch()
1973
+ while (watching) {
1974
+ await new Promise(r => setTimeout(r, 3000))
1975
+ if (!watching) break
1976
+ await renderWatch()
1977
+ }
1978
+ process.removeListener("SIGINT", stopWatch)
1979
+ console.log("\x1b[2mStopped watch.\x1b[0m\n")
1980
+ break
1981
+ }
1982
+ case "stats": {
1983
+ console.log("")
1984
+ try {
1985
+ const raw = fs.readFileSync(LOG_FILE, "utf8")
1986
+ const events = []
1987
+ for (const line of raw.split("\n")) {
1988
+ if (!line.trim()) continue
1989
+ try { const e = JSON.parse(line); if (e.event && e.ts) events.push(e) } catch {}
1990
+ }
1991
+ const starts = events.filter(e => e.event === "runner.job.start")
1992
+ const completes = events.filter(e => e.event === "runner.job.complete")
1993
+ const errors = events.filter(e => e.event === "runner.job.error")
1994
+ const todayStart = new Date(); todayStart.setHours(0,0,0,0)
1995
+ const todayStarts = starts.filter(e => new Date(e.ts) >= todayStart)
1996
+
1997
+ const durations = []
1998
+ for (const c of completes) {
1999
+ const id = c.run_id ?? c.meta?.run_id
2000
+ const s = starts.find(e => (e.run_id ?? e.meta?.run_id) === id)
2001
+ if (s) durations.push(new Date(c.ts) - new Date(s.ts))
2002
+ }
2003
+ const avgDur = durations.length ? durations.reduce((a,b) => a+b, 0) / durations.length : 0
2004
+ const total = starts.length
2005
+ const success = completes.length
2006
+ const failed = errors.length
2007
+ const rate = total ? Math.round((success / total) * 100) : 0
2008
+
2009
+ const config = readConfig()
2010
+ const apiRuns = await fetchActiveRuns(config)
2011
+ const activeCount = apiRuns?.filter(r => r.status === "running").length ?? 0
2012
+ const queuedCount = apiRuns?.filter(r => ["queued","pending"].includes(r.status)).length ?? 0
2013
+
2014
+ console.log(` \x1b[1mRunner stats\x1b[0m\n`)
2015
+ console.log(` ${"Today's runs".padEnd(20)} \x1b[1m${todayStarts.length}\x1b[0m`)
2016
+ console.log(` ${"Total runs".padEnd(20)} \x1b[1m${total}\x1b[0m`)
2017
+ console.log(` ${"Completed".padEnd(20)} \x1b[32m${success}\x1b[0m`)
2018
+ console.log(` ${"Failed".padEnd(20)} ${failed > 0 ? `\x1b[31m${failed}\x1b[0m` : `\x1b[2m${failed}\x1b[0m`}`)
2019
+ console.log(` ${"Success rate".padEnd(20)} \x1b[1m${rate}%\x1b[0m`)
2020
+ console.log(` ${"Avg duration".padEnd(20)} \x1b[2m${avgDur ? fmtDuration(avgDur) : "—"}\x1b[0m`)
2021
+ console.log(` ${"Active now".padEnd(20)} ${activeCount > 0 ? `\x1b[34m${activeCount}\x1b[0m` : "\x1b[2m0\x1b[0m"}`)
2022
+ console.log(` ${"Queued".padEnd(20)} ${queuedCount > 0 ? `\x1b[33m${queuedCount}\x1b[0m` : "\x1b[2m0\x1b[0m"}`)
2023
+ console.log("")
2024
+ } catch { console.log(" No log data yet. Start the runner and run some jobs first.\n") }
2025
+ break
2026
+ }
2027
+ case "issues": {
2028
+ const config = readConfig()
2029
+ const key = config.apiKey ?? config.workspaceApiKey
2030
+ const wsId = config.workspaceId
2031
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2032
+ if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); break }
2033
+ console.log(`\n\x1b[2mFetching issues…\x1b[0m`)
2034
+ try {
2035
+ const filter = args[0] ?? "open" // open | all | in_progress
2036
+ const res = await fetch(`${appUrl}/api/workspaces/${wsId}/cli/issues?status=${filter}&limit=20`, {
2037
+ headers: { "x-workspace-api-key": key },
2038
+ signal: AbortSignal.timeout(5000),
2039
+ })
2040
+ if (!res.ok) { console.log(` \x1b[31mAPI error: ${res.status}\x1b[0m\n`); break }
2041
+ const data = await res.json()
2042
+ const issues = data.issues ?? data ?? []
2043
+ if (!issues.length) { console.log(` \x1b[2mNo ${filter} issues found.\x1b[0m\n`); break }
2044
+
2045
+ const STATUS_COLOR = { open:"\x1b[32m", in_progress:"\x1b[34m", in_review:"\x1b[33m", done:"\x1b[2m", cancelled:"\x1b[2m" }
2046
+ const COL_ID = 10, COL_STATUS = 14, COL_TITLE = 48
2047
+ const hr = ` ${"─".repeat(COL_ID + COL_STATUS + COL_TITLE + 4)}`
2048
+ console.log(`\n\x1b[1mIssues\x1b[0m \x1b[2m(${filter})\x1b[0m`)
2049
+ console.log(hr)
2050
+ console.log(` \x1b[2m${"ID".padEnd(COL_ID)} ${"STATUS".padEnd(COL_STATUS)} ${"TITLE".padEnd(COL_TITLE)}\x1b[0m`)
2051
+ console.log(hr)
2052
+ for (const i of issues) {
2053
+ const status = (i.status ?? "open").toLowerCase()
2054
+ const col = STATUS_COLOR[status] ?? ""
2055
+ const id = (i.identifier ?? i.id?.slice(0,8) ?? "—").padEnd(COL_ID)
2056
+ const st = status.padEnd(COL_STATUS)
2057
+ const title = (i.title ?? "—").slice(0, COL_TITLE).padEnd(COL_TITLE)
2058
+ console.log(` \x1b[2m${id}\x1b[0m ${col}${st}\x1b[0m ${title}`)
2059
+ }
2060
+ console.log(hr)
2061
+ console.log(` \x1b[2mTip: /issues in_progress · /issues all\x1b[0m\n`)
2062
+ } catch (e) { console.log(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
2063
+ break
2064
+ }
2065
+ // ── issue detail ──────────────────────────────────────────────────
2066
+ case "issue": {
2067
+ const config = readConfig()
2068
+ const key = config.apiKey ?? config.workspaceApiKey
2069
+ const wsId = config.workspaceId
2070
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2071
+ if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); break }
2072
+
2073
+ const id = args[0]
2074
+ if (!id) { console.log(`\n Usage: /issue <identifier> e.g. /issue PLT-42\n`); break }
2075
+
2076
+ try {
2077
+ const res = await fetch(`${appUrl}/api/workspaces/${wsId}/cli/issue/${encodeURIComponent(id.toUpperCase())}`, {
2078
+ headers: { "x-workspace-api-key": key },
2079
+ signal: AbortSignal.timeout(5000),
2080
+ })
2081
+ if (res.status === 404) { console.log(`\n \x1b[31mIssue not found: ${id}\x1b[0m\n`); break }
2082
+ if (!res.ok) { console.log(` \x1b[31mAPI error: ${res.status}\x1b[0m\n`); break }
2083
+ const { issue, comments } = await res.json()
2084
+
2085
+ const STATUS_COLOR = { backlog:"\x1b[2m", todo:"\x1b[37m", in_progress:"\x1b[34m", in_review:"\x1b[33m", done:"\x1b[32m", canceled:"\x1b[2m", cancelled:"\x1b[2m" }
2086
+ const PRIORITY_LABEL = { urgent:"\x1b[31m⚡ urgent\x1b[0m", high:"\x1b[33m↑ high\x1b[0m", medium:"\x1b[37m· medium\x1b[0m", low:"\x1b[2m↓ low\x1b[0m" }
2087
+ const statusCol = STATUS_COLOR[issue.status] ?? ""
2088
+ const cols = Math.min(process.stdout.columns || 80, 80)
2089
+ const div = ` \x1b[38;5;237m${"─".repeat(cols - 4)}\x1b[0m`
2090
+
2091
+ console.log("")
2092
+ console.log(div)
2093
+ console.log(` \x1b[2m${issue.identifier}\x1b[0m \x1b[1m${issue.title}\x1b[0m`)
2094
+ console.log(div)
2095
+ const meta = [
2096
+ `Status: ${statusCol}${issue.status}\x1b[0m`,
2097
+ issue.priority ? `Priority: ${PRIORITY_LABEL[issue.priority] ?? issue.priority}` : null,
2098
+ issue.assignee_name ? `Assignee: \x1b[1m${issue.assignee_name}\x1b[0m` : null,
2099
+ issue.project_name ? `Project: \x1b[2m${issue.project_name}\x1b[0m` : null,
2100
+ ].filter(Boolean).join(" · ")
2101
+ console.log(` ${meta}`)
2102
+ if (issue.description) {
2103
+ console.log("")
2104
+ const lines = issue.description.replace(/\r\n/g, "\n").split("\n").slice(0, 12)
2105
+ for (const l of lines) console.log(` \x1b[2m${l.slice(0, cols - 4)}\x1b[0m`)
2106
+ }
2107
+ if (comments?.length) {
2108
+ console.log(`\n \x1b[2mComments (${comments.length})\x1b[0m`)
2109
+ for (const c of comments) {
2110
+ console.log(` \x1b[36m${c.author ?? "agent"}\x1b[0m \x1b[2m${relTime(c.created_at)}\x1b[0m`)
2111
+ const body = c.body.replace(/\r\n/g, "\n").split("\n").slice(0, 4)
2112
+ for (const l of body) console.log(` \x1b[2m${l.slice(0, cols - 6)}\x1b[0m`)
2113
+ }
2114
+ }
2115
+ console.log(div)
2116
+ const ws = config.workspaceSlug ?? config.workspaceId ?? ""
2117
+ if (ws) console.log(` \x1b[2m${appUrl}/${ws}/issues/${issue.identifier} · /open ${issue.identifier}\x1b[0m`)
2118
+ console.log("")
2119
+ } catch (e) { console.log(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
2120
+ break
2121
+ }
2122
+ // ── my issues ─────────────────────────────────────────────────────
2123
+ case "mine": {
2124
+ const config = readConfig()
2125
+ const key = config.apiKey ?? config.workspaceApiKey
2126
+ const wsId = config.workspaceId
2127
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2128
+ if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); break }
2129
+
2130
+ console.log(`\n\x1b[2mFetching your issues…\x1b[0m`)
2131
+ try {
2132
+ const res = await fetch(`${appUrl}/api/workspaces/${wsId}/cli/my-issues?limit=30`, {
2133
+ headers: { "x-workspace-api-key": key },
2134
+ signal: AbortSignal.timeout(5000),
2135
+ })
2136
+ if (!res.ok) { console.log(` \x1b[31mAPI error: ${res.status}\x1b[0m\n`); break }
2137
+ const { issues } = await res.json()
2138
+ if (!issues?.length) { console.log(` \x1b[2mNo issues assigned to you.\x1b[0m\n`); break }
2139
+
2140
+ const STATUS_COLOR = { backlog:"\x1b[2m", todo:"\x1b[37m", in_progress:"\x1b[34m", in_review:"\x1b[33m" }
2141
+ const COL_ID = 10, COL_STATUS = 14, COL_TITLE = 46
2142
+ const hr = ` ${"─".repeat(COL_ID + COL_STATUS + COL_TITLE + 4)}`
2143
+ console.log(`\n\x1b[1mMy issues\x1b[0m \x1b[2m(${issues.length})\x1b[0m`)
2144
+ console.log(hr)
2145
+ console.log(` \x1b[2m${"ID".padEnd(COL_ID)} ${"STATUS".padEnd(COL_STATUS)} ${"TITLE".padEnd(COL_TITLE)}\x1b[0m`)
2146
+ console.log(hr)
2147
+ for (const i of issues) {
2148
+ const status = (i.status ?? "").toLowerCase()
2149
+ const col = STATUS_COLOR[status] ?? ""
2150
+ const id = (i.identifier ?? i.id?.slice(0,8) ?? "—").padEnd(COL_ID)
2151
+ const st = status.padEnd(COL_STATUS)
2152
+ const title = (i.title ?? "—").slice(0, COL_TITLE).padEnd(COL_TITLE)
2153
+ console.log(` \x1b[2m${id}\x1b[0m ${col}${st}\x1b[0m ${title}`)
2154
+ }
2155
+ console.log(hr)
2156
+ console.log(` \x1b[2mTip: /issue <id> to view details · /run <id> to dispatch\x1b[0m\n`)
2157
+ } catch (e) { console.log(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
2158
+ break
2159
+ }
2160
+ // ── agents list ───────────────────────────────────────────────────
2161
+ case "agents": {
2162
+ const config = readConfig()
2163
+ const key = config.apiKey ?? config.workspaceApiKey
2164
+ const wsId = config.workspaceId
2165
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2166
+ if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); break }
2167
+
2168
+ console.log(`\n\x1b[2mFetching agents…\x1b[0m`)
2169
+ try {
2170
+ const res = await fetch(`${appUrl}/api/workspaces/${wsId}/cli/agents`, {
2171
+ headers: { "x-workspace-api-key": key },
2172
+ signal: AbortSignal.timeout(5000),
2173
+ })
2174
+ if (!res.ok) { console.log(` \x1b[31mAPI error: ${res.status}\x1b[0m\n`); break }
2175
+ const { agents } = await res.json()
2176
+ if (!agents?.length) { console.log(` \x1b[2mNo agents configured.\x1b[0m\n`); break }
2177
+
2178
+ const SKILL_COLOR = { reviewer:"\x1b[33m", implementer:"\x1b[34m", planner:"\x1b[35m" }
2179
+ const COL_NAME = 22, COL_SKILL = 16, COL_EXE = 14
2180
+ const hr = ` ${"─".repeat(COL_NAME + COL_SKILL + COL_EXE + 4)}`
2181
+ console.log(`\n\x1b[1mAgents\x1b[0m \x1b[2m(${agents.length})\x1b[0m`)
2182
+ console.log(hr)
2183
+ console.log(` \x1b[2m${"NAME".padEnd(COL_NAME)} ${"SKILL".padEnd(COL_SKILL)} ${"EXECUTOR".padEnd(COL_EXE)}\x1b[0m`)
2184
+ console.log(hr)
2185
+ for (const a of agents) {
2186
+ const skill = (a.skill_profile_label ?? a.skill_profile_slug ?? "—").toLowerCase()
2187
+ const skillCol = SKILL_COLOR[a.skill_profile_slug] ?? "\x1b[2m"
2188
+ const name = (a.name ?? a.slug ?? a.id.slice(0,8)).slice(0, COL_NAME).padEnd(COL_NAME)
2189
+ const skillStr = skill.slice(0, COL_SKILL).padEnd(COL_SKILL)
2190
+ const exe = executorLabel(a.local_executor ?? "").slice(0, COL_EXE).padEnd(COL_EXE)
2191
+ console.log(` \x1b[1m${name}\x1b[0m ${skillCol}${skillStr}\x1b[0m \x1b[2m${exe}\x1b[0m`)
2192
+ }
2193
+ console.log(hr)
2194
+ console.log(` \x1b[2mTip: /run <issue-id> to dispatch with agent picker\x1b[0m\n`)
2195
+ } catch (e) { console.log(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
2196
+ break
2197
+ }
2198
+ // ── orchestration status dashboard ────────────────────────────────
2199
+ case "dashboard": {
2200
+ const config = readConfig()
2201
+ const key = config.apiKey ?? config.workspaceApiKey
2202
+ const wsId = config.workspaceId
2203
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2204
+ if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); break }
2205
+
2206
+ try {
2207
+ const [orchRes, runsRes] = await Promise.all([
2208
+ fetch(`${appUrl}/api/workspaces/${wsId}/cli/orchestration`, {
2209
+ headers: { "x-workspace-api-key": key },
2210
+ signal: AbortSignal.timeout(5000),
2211
+ }),
2212
+ fetchActiveRuns(config),
2213
+ ])
2214
+ const orch = orchRes.ok ? await orchRes.json() : null
2215
+ const pid = readPid()
2216
+ const running = pid && isRunning(pid)
2217
+ const dot = running ? `\x1b[32m● Runner running\x1b[0m` : `\x1b[2m○ Runner stopped\x1b[0m`
2218
+ const cols = Math.min(process.stdout.columns || 80, 80)
2219
+ const div = ` \x1b[38;5;237m${"─".repeat(cols - 4)}\x1b[0m`
2220
+
2221
+ console.log("")
2222
+ console.log(div)
2223
+ console.log(` ${dot}`)
2224
+ console.log(div)
2225
+
2226
+ if (orch) {
2227
+ const r = orch.runs
2228
+ const i = orch.issues
2229
+ const stat = (label, val, col = "") => console.log(` ${col}${label.padEnd(22)}\x1b[0m \x1b[1m${val}\x1b[0m`)
2230
+ stat("Active runs", r.running, r.running > 0 ? "\x1b[34m" : "\x1b[2m")
2231
+ stat("Queued runs", r.queued, r.queued > 0 ? "\x1b[33m" : "\x1b[2m")
2232
+ stat("Completed today", r.completed_today, r.completed_today > 0 ? "\x1b[32m" : "\x1b[2m")
2233
+ stat("Failed today", r.failed_today, r.failed_today > 0 ? "\x1b[31m" : "\x1b[2m")
2234
+ console.log(div)
2235
+ stat("In review", i.in_review, i.in_review > 0 ? "\x1b[33m" : "\x1b[2m")
2236
+ stat("In progress", i.in_progress, i.in_progress > 0 ? "\x1b[34m" : "\x1b[2m")
2237
+ stat("Todo", i.todo, "\x1b[2m")
2238
+ }
2239
+
2240
+ if (runsRes?.length) {
2241
+ console.log(div)
2242
+ console.log(` \x1b[1mActive\x1b[0m`)
2243
+ for (const r of runsRes.slice(0, 5)) {
2244
+ const status = (r.status ?? "").toLowerCase()
2245
+ const age = relTime(r.started_at ?? r.created_at)
2246
+ console.log(` \x1b[34m▶\x1b[0m \x1b[1m${(r.task_title ?? r.task_identifier ?? r.id?.slice(0,8) ?? "—").slice(0, 40)}\x1b[0m \x1b[2m${age}\x1b[0m`)
2247
+ }
2248
+ }
2249
+ console.log(div)
2250
+ console.log(` \x1b[2mTip: /watch to auto-refresh · /logtail <run-id> to stream a run\x1b[0m`)
2251
+ console.log("")
2252
+ } catch (e) { console.log(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
2253
+ break
2254
+ }
2255
+ // ── stream run log ────────────────────────────────────────────────
2256
+ case "logtail": {
2257
+ const config = readConfig()
2258
+ const key = config.apiKey ?? config.workspaceApiKey
2259
+ const wsId = config.workspaceId
2260
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2261
+ if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); break }
2262
+
2263
+ const runId = args[0]
2264
+ if (!runId) { console.log(`\n Usage: /logtail <run-id> (from /jobs or /watch)\n`); break }
2265
+
2266
+ console.log(`\n \x1b[2mStreaming log for run ${runId.slice(0,8)}… (Ctrl+C to stop)\x1b[0m\n`)
2267
+ let lastLen = 0
2268
+ let done = false
2269
+ let stopping = false
2270
+ const stop = () => { stopping = true }
2271
+ process.once("SIGINT", stop)
2272
+
2273
+ while (!stopping) {
2274
+ try {
2275
+ const res = await fetch(`${appUrl}/api/workspaces/${wsId}/cli/runs/${runId}/log`, {
2276
+ headers: { "x-workspace-api-key": key },
2277
+ signal: AbortSignal.timeout(5000),
2278
+ })
2279
+ if (!res.ok) { console.log(` \x1b[31mAPI error: ${res.status}\x1b[0m\n`); break }
2280
+ const data = await res.json()
2281
+ const log = data.log_tail ?? ""
2282
+ if (log.length > lastLen) {
2283
+ const newContent = log.slice(lastLen)
2284
+ process.stdout.write(newContent)
2285
+ if (!newContent.endsWith("\n")) process.stdout.write("\n")
2286
+ lastLen = log.length
2287
+ }
2288
+ if (["completed", "error", "cancelled"].includes(data.status)) {
2289
+ const col = data.status === "completed" ? "\x1b[32m" : "\x1b[31m"
2290
+ console.log(`\n ${col}Run ${data.status}\x1b[0m\n`)
2291
+ done = true
2292
+ break
2293
+ }
2294
+ } catch {}
2295
+ await new Promise(r => setTimeout(r, 3000))
2296
+ }
2297
+ process.removeListener("SIGINT", stop)
2298
+ if (!done && stopping) console.log("\n \x1b[2mStopped.\x1b[0m\n")
2299
+ break
2300
+ }
2301
+ // ── orchestrator commands ─────────────────────────────────────────
2302
+ case "run": {
2303
+ // /run <issue-identifier> e.g. /run PLT-42
2304
+ const config = readConfig()
2305
+ const key = config.apiKey ?? config.workspaceApiKey
2306
+ const wsId = config.workspaceId
2307
+ const appUrl = (config.appUrl ?? "https://pacework.io ").replace(/\/$/, "")
2308
+ if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); break }
2309
+
2310
+ const issueRef = args[0]
2311
+ if (!issueRef) { console.log(`\n Usage: /run <issue-identifier> e.g. /run PLT-42\n`); break }
2312
+
2313
+ console.log(`\n \x1b[2mLooking up issue and agents…\x1b[0m`)
2314
+ try {
2315
+ // fetch issue + agents in parallel
2316
+ const [issuesRes, agentsRes] = await Promise.all([
2317
+ fetch(`${appUrl}/api/workspaces/${wsId}/cli/issues?status=all&limit=100`, {
2318
+ headers: { "x-workspace-api-key": key },
2319
+ signal: AbortSignal.timeout(5000),
2320
+ }),
2321
+ fetch(`${appUrl}/api/workspaces/${wsId}/cli/agents`, {
2322
+ headers: { "x-workspace-api-key": key },
2323
+ signal: AbortSignal.timeout(5000),
2324
+ }),
2325
+ ])
2326
+
2327
+ if (!issuesRes.ok) { console.log(` \x1b[31mAPI error: ${issuesRes.status}\x1b[0m\n`); break }
2328
+ const { issues } = await issuesRes.json()
2329
+ const issue = issues?.find(i => i.identifier?.toUpperCase() === issueRef.toUpperCase())
2330
+ if (!issue) { console.log(` \x1b[31mIssue not found: ${issueRef}\x1b[0m\n`); break }
2331
+
2332
+ // agents list (may fail gracefully)
2333
+ let agents = []
2334
+ if (agentsRes.ok) {
2335
+ const agentData = await agentsRes.json().catch(() => ({}))
2336
+ agents = Array.isArray(agentData) ? agentData : (agentData.agents ?? agentData.data ?? [])
2337
+ }
2338
+
2339
+ // show issue summary
2340
+ console.log(`\n \x1b[1m${issue.identifier}\x1b[0m ${issue.title}`)
2341
+ console.log(` \x1b[2mStatus: ${issue.status}${issue.priority ? ` · Priority: ${issue.priority}` : ""}\x1b[0m\n`)
2342
+
2343
+ // agent picker
2344
+ let chosenAgentId = issue.agent_id ?? null
2345
+
2346
+ if (agents.length > 0) {
2347
+ const defaultIdx = agents.findIndex(a => a.id === chosenAgentId)
2348
+ console.log(` \x1b[1mPick an agent:\x1b[0m \x1b[2m(Enter to use default)\x1b[0m\n`)
2349
+ agents.forEach((a, i) => {
2350
+ const isDefault = a.id === chosenAgentId
2351
+ const tag = isDefault ? ` \x1b[32m← default\x1b[0m` : ""
2352
+ const executor = a.local_executor ? ` \x1b[2m${executorLabel(a.local_executor)}\x1b[0m` : ""
2353
+ console.log(` \x1b[36m${i + 1}.\x1b[0m \x1b[1m${a.name ?? a.slug ?? a.id.slice(0,8)}\x1b[0m${executor}${tag}`)
2354
+ })
2355
+ console.log("")
2356
+
2357
+ // pause raw mode for a simple line read
2358
+ process.stdin.setRawMode(false)
2359
+ const answer = await new Promise(resolve => {
2360
+ process.stdout.write(` \x1b[36mAgent number (default ${defaultIdx >= 0 ? defaultIdx + 1 : "issue default"}):\x1b[0m `)
2361
+ let buf = ""
2362
+ const onData = (chunk) => {
2363
+ const s = chunk.toString()
2364
+ if (s === "\n" || s === "\r") {
2365
+ process.stdin.removeListener("data", onData)
2366
+ process.stdout.write("\n")
2367
+ resolve(buf.trim())
2368
+ } else if (s === "\x7f" && buf.length) {
2369
+ buf = buf.slice(0, -1)
2370
+ process.stdout.write("\b \b")
2371
+ } else if (s >= " ") {
2372
+ buf += s
2373
+ process.stdout.write(s)
2374
+ }
2375
+ }
2376
+ process.stdin.on("data", onData)
2377
+ })
2378
+ process.stdin.setRawMode(true)
2379
+
2380
+ if (answer !== "") {
2381
+ const idx = parseInt(answer, 10) - 1
2382
+ if (idx >= 0 && idx < agents.length) {
2383
+ chosenAgentId = agents[idx].id
2384
+ console.log(` \x1b[2mUsing agent: ${agents[idx].name ?? agents[idx].slug}\x1b[0m`)
2385
+ } else {
2386
+ console.log(` \x1b[33m⚠\x1b[0m Invalid choice — using issue default`)
2387
+ }
2388
+ } else {
2389
+ const def = agents[defaultIdx]
2390
+ if (def) console.log(` \x1b[2mUsing default agent: ${def.name ?? def.slug}\x1b[0m`)
2391
+ }
2392
+ } else if (chosenAgentId) {
2393
+ console.log(` \x1b[2mNo agents list available — using issue's assigned agent\x1b[0m`)
2394
+ }
2395
+
2396
+ console.log(`\n \x1b[2mDispatching…\x1b[0m`)
2397
+ const dispatchBody = { task_id: issue.id, workspace_id: wsId }
2398
+ if (chosenAgentId) dispatchBody.agent_id = chosenAgentId
2399
+
2400
+ const dispatch = await fetch(`${appUrl}/api/agent-planner/dispatch`, {
2401
+ method: "POST",
2402
+ headers: { "content-type": "application/json", Authorization: `Bearer ${key}` },
2403
+ body: JSON.stringify(dispatchBody),
2404
+ signal: AbortSignal.timeout(8000),
2405
+ })
2406
+ const body = await dispatch.json().catch(() => ({}))
2407
+ if (dispatch.ok) {
2408
+ const statusLabel = body.status === "already_queued" ? "already queued" : body.status === "resumed" ? "resumed" : "dispatched"
2409
+ console.log(` \x1b[32m✓\x1b[0m \x1b[1m${issue.identifier}\x1b[0m ${statusLabel}${body.run_id ? ` \x1b[2mrun ${body.run_id.slice(0,8)}\x1b[0m` : ""}`)
2410
+ } else {
2411
+ console.log(` \x1b[31m✗\x1b[0m Dispatch failed (${dispatch.status}): ${body.message ?? body.error ?? "unknown"}`)
2412
+ }
2413
+ console.log("")
2414
+ } catch (e) { console.log(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
2415
+ break
2416
+ }
2417
+ case "cancel": {
2418
+ const config = readConfig()
2419
+ const key = config.apiKey ?? config.workspaceApiKey
2420
+ const wsId = config.workspaceId
2421
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2422
+ if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); break }
2423
+
2424
+ const runId = args[0]
2425
+ if (!runId) { console.log(`\n Usage: /cancel <run-id> (from /jobs)\n`); break }
2426
+
2427
+ try {
2428
+ console.log(`\n \x1b[2mCancelling run ${runId.slice(0,8)}…\x1b[0m`)
2429
+ const res = await fetch(`${appUrl}/api/workspaces/${wsId}/agent-runs/${runId}/cancel`, {
2430
+ method: "POST",
2431
+ headers: { "content-type": "application/json", "x-workspace-api-key": key },
2432
+ signal: AbortSignal.timeout(5000),
2433
+ })
2434
+ if (res.ok) console.log(` \x1b[32m✓\x1b[0m Run cancelled`)
2435
+ else { const b = await res.json().catch(() => ({})); console.log(` \x1b[31m✗\x1b[0m Failed (${res.status}): ${b.message ?? b.error ?? ""}`) }
2436
+ console.log("")
2437
+ } catch (e) { console.log(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
2438
+ break
2439
+ }
2440
+ case "retry": {
2441
+ const config = readConfig()
2442
+ const key = config.apiKey ?? config.workspaceApiKey
2443
+ const wsId = config.workspaceId
2444
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2445
+ if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); break }
2446
+
2447
+ const runId = args[0]
2448
+ if (!runId) { console.log(`\n Usage: /retry <run-id> (from /jobs)\n`); break }
2449
+
2450
+ try {
2451
+ console.log(`\n \x1b[2mRetrying run ${runId.slice(0,8)}…\x1b[0m`)
2452
+ const res = await fetch(`${appUrl}/api/workspaces/${wsId}/agent-runs/${runId}/retry`, {
2453
+ method: "POST",
2454
+ headers: { "content-type": "application/json", "x-workspace-api-key": key },
2455
+ signal: AbortSignal.timeout(5000),
2456
+ })
2457
+ if (res.ok) {
2458
+ const b = await res.json().catch(() => ({}))
2459
+ console.log(` \x1b[32m✓\x1b[0m Run retried${b.run_id ? ` \x1b[2mnew run ${b.run_id.slice(0,8)}\x1b[0m` : ""}`)
2460
+ } else {
2461
+ const b = await res.json().catch(() => ({}))
2462
+ console.log(` \x1b[31m✗\x1b[0m Failed (${res.status}): ${b.message ?? b.error ?? ""}`)
2463
+ }
2464
+ console.log("")
2465
+ } catch (e) { console.log(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
2466
+ break
2467
+ }
2468
+ case "pause": {
2469
+ const config = readConfig()
2470
+ await runnerControlCommand(config, "pause")
2471
+ break
2472
+ }
2473
+ case "resume": {
2474
+ const config = readConfig()
2475
+ await runnerControlCommand(config, "resume")
2476
+ break
2477
+ }
2478
+ case "capacity": {
2479
+ const config = readConfig()
2480
+ const n = parseInt(args[0], 10)
2481
+ if (!n || n < 1 || n > 20) { console.log(`\n Usage: /capacity <1-20> — set max parallel jobs\n`); break }
2482
+ await runnerControlCommand(config, "set_capacity", { max_parallel_runs: n })
2483
+ break
2484
+ }
2485
+ case "mcp": {
2486
+ const config = readConfig()
2487
+ const key = config.apiKey ?? config.workspaceApiKey
2488
+ const wsId = config.workspaceId
2489
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2490
+ const executor = config.executor ?? "claude_code"
2491
+ const repoRoot = config.repoRoot ?? process.cwd()
2492
+ const sub = args[0] ?? ""
2493
+
2494
+ if (!sub || sub === "help") {
2495
+ console.log(`\n \x1b[1m/mcp\x1b[0m — manage MCP server connections\n`)
2496
+ console.log(` \x1b[36m/mcp install\x1b[0m \x1b[2m— inject pacework MCP into your executor's config\x1b[0m`)
2497
+ console.log(` \x1b[36m/mcp status \x1b[0m \x1b[2m— show configured MCP servers\x1b[0m`)
2498
+ console.log(` \x1b[36m/mcp test \x1b[0m \x1b[2m— ping each MCP server\x1b[0m\n`)
2499
+ break
2500
+ }
2501
+
2502
+ if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); break }
2503
+
2504
+ if (sub === "install") {
2505
+ console.log(`\n \x1b[2mConfiguring MCP for ${executorLabel(executor)}…\x1b[0m`)
2506
+ const mcpUrl = `${appUrl}/api/mcp`
2507
+
2508
+ // Prefer the runner's dedicated MCP key from the state file — it's
2509
+ // scoped specifically for MCP access. Fall back to workspace API key.
2510
+ let mcpKey = key
2511
+ try {
2512
+ const stateFile = path.join(repoRoot, ".agent", "runners", `${wsId}-${executor}.json`)
2513
+ const runnerState = JSON.parse(fs.readFileSync(stateFile, "utf8"))
2514
+ if (runnerState.runner_mcp_key) {
2515
+ mcpKey = runnerState.runner_mcp_key
2516
+ console.log(` \x1b[2mUsing runner MCP key from state file\x1b[0m`)
2517
+ }
2518
+ } catch {
2519
+ console.log(` \x1b[2mRunner not started yet — using workspace API key as MCP token\x1b[0m`)
2520
+ }
2521
+ const authHeader = `Bearer ${mcpKey}`
2522
+
2523
+ if (executor === "claude_code") {
2524
+ const claudeDir = path.join(repoRoot, ".agent", "claude-home")
2525
+ fs.mkdirSync(claudeDir, { recursive: true })
2526
+ const claudeJson = path.join(claudeDir, ".claude.json")
2527
+ let existing = {}
2528
+ try { existing = JSON.parse(fs.readFileSync(claudeJson, "utf8")) } catch {}
2529
+ existing.mcpServers = { ...existing.mcpServers, kentral_local: { type: "http", url: mcpUrl, headers: { Authorization: authHeader } } }
2530
+ fs.writeFileSync(claudeJson, JSON.stringify(existing, null, 2))
2531
+ console.log(` \x1b[32m✓\x1b[0m Claude Code MCP written to \x1b[2m${claudeJson}\x1b[0m`)
2532
+ } else if (executor === "gemini") {
2533
+ const geminiDir = path.join(os.homedir(), ".gemini")
2534
+ fs.mkdirSync(geminiDir, { recursive: true })
2535
+ const settingsPath = path.join(geminiDir, "settings.json")
2536
+ let existing = {}
2537
+ try { existing = JSON.parse(fs.readFileSync(settingsPath, "utf8")) } catch {}
2538
+ existing.mcpServers = { ...existing.mcpServers, kentral_local: { httpUrl: mcpUrl, headers: { Authorization: authHeader } } }
2539
+ fs.writeFileSync(settingsPath, JSON.stringify(existing, null, 2))
2540
+ console.log(` \x1b[32m✓\x1b[0m Gemini MCP written to \x1b[2m${settingsPath}\x1b[0m`)
2541
+ } else if (executor === "cursor_agent") {
2542
+ const cursorDir = path.join(os.homedir(), ".cursor")
2543
+ fs.mkdirSync(cursorDir, { recursive: true })
2544
+ const mcpPath = path.join(cursorDir, "mcp.json")
2545
+ let existing = {}
2546
+ try { existing = JSON.parse(fs.readFileSync(mcpPath, "utf8")) } catch {}
2547
+ existing.mcpServers = { ...existing.mcpServers, kentral_local: { url: mcpUrl, headers: { Authorization: authHeader } } }
2548
+ fs.writeFileSync(mcpPath, JSON.stringify(existing, null, 2))
2549
+ console.log(` \x1b[32m✓\x1b[0m Cursor MCP written to \x1b[2m${mcpPath}\x1b[0m`)
2550
+ } else if (executor === "codex") {
2551
+ const codexHome = process.env.CODEX_HOME ?? path.join(os.homedir(), ".codex")
2552
+ const configPath = path.join(codexHome, "config.toml")
2553
+ let toml = ""
2554
+ try { toml = fs.readFileSync(configPath, "utf8") } catch {}
2555
+ if (!toml.includes("[mcp_servers.kentral_local]")) {
2556
+ toml += `\n[mcp_servers.kentral_local]\nenabled = true\nurl = "${mcpUrl}"\n\n[mcp_servers.kentral_local.http_headers]\nAuthorization = "${authHeader}"\n`
2557
+ fs.mkdirSync(codexHome, { recursive: true })
2558
+ fs.writeFileSync(configPath, toml)
2559
+ console.log(` \x1b[32m✓\x1b[0m Codex MCP written to \x1b[2m${configPath}\x1b[0m`)
2560
+ } else {
2561
+ console.log(` \x1b[33m⚠\x1b[0m kentral_local already in \x1b[2m${configPath}\x1b[0m — update manually if needed`)
2562
+ }
2563
+ } else {
2564
+ console.log(` \x1b[33m⚠\x1b[0m MCP install not yet implemented for executor: ${executor}`)
2565
+ }
2566
+ console.log(` \x1b[2mMCP endpoint: ${mcpUrl}\x1b[0m`)
2567
+ console.log(` \x1b[2mRestart your executor to pick up the new config.\x1b[0m\n`)
2568
+
2569
+ } else if (sub === "status") {
2570
+ console.log(`\n \x1b[1mMCP servers\x1b[0m \x1b[2m(executor: ${executorLabel(executor)})\x1b[0m\n`)
2571
+ const servers = await fetchMcpServerList(config)
2572
+ if (!servers?.length) {
2573
+ console.log(` \x1b[2mNo MCP servers configured in workspace.\x1b[0m`)
2574
+ console.log(` The pacework MCP server is always available at:\x1b[0m`)
2575
+ console.log(` \x1b[2m${appUrl}/api/mcp\x1b[0m\n`)
2576
+ } else {
2577
+ for (const s of servers) {
2578
+ console.log(` \x1b[36m${s.name ?? s.id}\x1b[0m \x1b[2m${s.url ?? s.transport ?? "stdio"}\x1b[0m`)
2579
+ }
2580
+ console.log("")
2581
+ }
2582
+
2583
+ } else if (sub === "test") {
2584
+ console.log(`\n \x1b[2mPinging MCP servers…\x1b[0m\n`)
2585
+ const servers = await fetchMcpServerList(config)
2586
+ // always include kentral_local
2587
+ const allServers = [
2588
+ { name: "kentral_local", url: `${appUrl}/api/mcp` },
2589
+ ...(servers ?? []).filter(s => s.url),
2590
+ ]
2591
+ for (const s of allServers) {
2592
+ const t0 = Date.now()
2593
+ try {
2594
+ const r = await fetch(s.url, { method: "GET", headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(4000) })
2595
+ const ms = Date.now() - t0
2596
+ const ok2 = r.ok || r.status === 405 // MCP endpoints often don't support GET
2597
+ console.log(` ${ok2 ? "\x1b[32m✓\x1b[0m" : "\x1b[33m⚠\x1b[0m"} \x1b[1m${s.name}\x1b[0m \x1b[2m${ms}ms ${s.url}\x1b[0m`)
2598
+ } catch (e) {
2599
+ console.log(` \x1b[31m✗\x1b[0m \x1b[1m${s.name}\x1b[0m \x1b[31munreachable\x1b[0m \x1b[2m${s.url}\x1b[0m`)
2600
+ }
2601
+ }
2602
+ console.log("")
2603
+ } else {
2604
+ console.log(`\n Unknown subcommand: /mcp ${sub} (use: install | status | test)\n`)
2605
+ }
2606
+ break
2607
+ }
2608
+ case "executor": {
2609
+ const config = readConfig()
2610
+ const key = config.apiKey ?? config.workspaceApiKey
2611
+ const executor = config.executor ?? "claude_code"
2612
+ const sub = args[0] ?? ""
2613
+
2614
+ if (sub === "test") {
2615
+ const exeEntry = EXECUTORS.find(e => e.id === executor)
2616
+ if (!exeEntry) { console.log(`\n Unknown executor: ${executor}\n`); break }
2617
+ if (!checkBinaryExists(exeEntry.bin)) {
2618
+ console.log(`\n \x1b[31m✗\x1b[0m ${exeEntry.label} binary (\x1b[1m${exeEntry.bin}\x1b[0m) not found in PATH\n`)
2619
+ break
2620
+ }
2621
+ console.log(`\n \x1b[2mSmoke-testing ${exeEntry.label}…\x1b[0m`)
2622
+ const t0 = Date.now()
2623
+ try {
2624
+ const versionFlag = executor === "gemini" ? "--version" : "--version"
2625
+ const result = execFileSync(exeEntry.bin, [versionFlag], { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "pipe"] }).trim()
2626
+ const ms = Date.now() - t0
2627
+ console.log(` \x1b[32m✓\x1b[0m ${exeEntry.label} is working \x1b[2m${result.split("\n")[0]} ${ms}ms\x1b[0m`)
2628
+ } catch (e) {
2629
+ console.log(` \x1b[31m✗\x1b[0m ${exeEntry.label} returned error: \x1b[2m${e.message?.split("\n")[0] ?? e.message}\x1b[0m`)
2630
+ }
2631
+ console.log("")
2632
+ } else {
2633
+ console.log(`\n \x1b[1m/executor\x1b[0m — executor tools\n`)
2634
+ console.log(` \x1b[36m/executor test\x1b[0m \x1b[2m— smoke-test the configured executor binary\x1b[0m\n`)
2635
+ }
2636
+ break
2637
+ }
2638
+ case "whoami": {
2639
+ const config = readConfig()
2640
+ console.log("")
2641
+ const key = config.apiKey ?? config.workspaceApiKey
2642
+ console.log(` workspace \x1b[1m${config.workspaceSlug ?? config.workspaceId ?? "\x1b[2mnot set\x1b[0m"}\x1b[0m`)
2643
+ console.log(` runner \x1b[1m${config.runnerName ?? "\x1b[2mnot set\x1b[0m"}\x1b[0m`)
2644
+ console.log(` executor \x1b[1m${executorLabel(config.executor ?? "?")}\x1b[0m`)
2645
+ console.log(` api key \x1b[2m${key ? key.slice(0, 20) + "…" : "not set"}\x1b[0m`)
2646
+ console.log(` app url \x1b[2m${config.appUrl ?? "https://pacework.io"}\x1b[0m`)
2647
+ console.log("")
2648
+ break
2649
+ }
2650
+ case "rename": {
2651
+ const newName = args.join(" ").trim()
2652
+ if (!newName) { console.log(`Usage: rename <new name>`); break }
2653
+ const config = readConfig()
2654
+ config.runnerName = newName
2655
+ writeConfig(config)
2656
+ console.log(`\x1b[32m✓\x1b[0m Runner name set to \x1b[1m${newName}\x1b[0m — restart runner to push to dashboard`)
2657
+ break
2658
+ }
2659
+ case "open": {
2660
+ const config = readConfig()
2661
+ const base = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2662
+ const slug = config.workspaceSlug ?? config.workspaceId ?? ""
2663
+ const issueId = args[0]
2664
+ const url = issueId
2665
+ ? (slug ? `${base}/${slug}/issues/${issueId.toUpperCase()}` : base)
2666
+ : (slug ? `${base}/${slug}` : base)
2667
+ console.log(`Opening \x1b[36m${url}\x1b[0m`)
2668
+ const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open"
2669
+ try { spawn(opener, [url], { stdio: "ignore", detached: true }).unref() }
2670
+ catch { console.log(`Could not open browser automatically.`) }
2671
+ break
2672
+ }
2673
+ case "update": {
2674
+ console.log("Checking for updates…")
2675
+ try {
2676
+ const res = await fetch("https://registry.npmjs.org/pacework-runner/latest", { signal: AbortSignal.timeout(4000) })
2677
+ const { version: latest } = await res.json()
2678
+ if (latest === LOCAL_VERSION) {
2679
+ console.log(`\x1b[32m✓\x1b[0m Already on latest (\x1b[1m${LOCAL_VERSION}\x1b[0m)`)
2680
+ } else {
2681
+ console.log(`Updating ${LOCAL_VERSION} → \x1b[1m${latest}\x1b[0m…`)
2682
+ const child = spawn("npm", ["install", "-g", "pacework-runner"], { stdio: "inherit" })
2683
+ await new Promise(r => child.on("exit", r))
2684
+ }
2685
+ } catch { console.log("\x1b[31mCould not reach npm registry.\x1b[0m") }
2686
+ break
2687
+ }
2688
+ case "login": {
2689
+ const config = readConfig()
2690
+ const key = config.apiKey ?? config.workspaceApiKey
2691
+ const ws = config.workspaceSlug ?? config.workspaceId
2692
+
2693
+ if (key && ws) {
2694
+ const user = config.userName ?? config.userEmail ?? "unknown"
2695
+ console.log(`\n \x1b[32m✓\x1b[0m Already logged in as \x1b[1m${user}\x1b[0m on \x1b[1m${ws}\x1b[0m`)
2696
+ console.log(` Switch accounts? This will revoke the current API key.\n`)
2697
+ // raw-mode y/n
2698
+ const answer = await new Promise(resolve => {
2699
+ process.stdout.write(` \x1b[36m[y/N]\x1b[0m `)
2700
+ process.stdin.once("data", k => { process.stdout.write("\n"); resolve(k.toString().trim().toLowerCase()) })
2701
+ })
2702
+ if (answer !== "y") { console.log(" Keeping current session.\n"); break }
2703
+
2704
+ // revoke existing key then fall through to login
2705
+ try {
2706
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2707
+ await fetch(`${appUrl}/api/cli/login`, {
2708
+ method: "DELETE",
2709
+ headers: { "content-type": "application/json" },
2710
+ body: JSON.stringify({ apiKey: key }),
2711
+ })
2712
+ } catch {}
2713
+ const fresh = {}
2714
+ // stop daemon before switching accounts
2715
+ const pid2 = readPid()
2716
+ if (pid2 && isRunning(pid2)) { try { process.kill(pid2, "SIGTERM"); clearPid() } catch {} }
2717
+ writeConfig({ appUrl: config.appUrl })
2718
+ console.log(` \x1b[32m✓\x1b[0m Logged out. Starting login flow…\n`)
2719
+ }
2720
+
2721
+ // pause raw mode, run login as child, resume
2722
+ process.stdin.setRawMode(false)
2723
+ process.stdin.pause()
2724
+ const loginChild = spawn(process.execPath, [fileURLToPath(import.meta.url), "login"], {
2725
+ stdio: "inherit",
2726
+ env: { ...process.env, PATH: process.env.PATH || "" },
2727
+ })
2728
+ await new Promise(r => loginChild.on("exit", r))
2729
+ process.stdin.setRawMode(true)
2730
+ process.stdin.resume()
2731
+ // re-render to show new account
2732
+ process.stdout.write("\x1b[2J\x1b[H")
2733
+ printBanner(readConfig())
2734
+ await printWelcome()
2735
+ break
2736
+ }
2737
+ case "logout": {
2738
+ const config = readConfig()
2739
+ const key = config.apiKey ?? config.workspaceApiKey
2740
+ if (!key) { console.log("\n Not logged in.\n"); break }
2741
+ console.log(`\n Revoking API key and clearing credentials…`)
2742
+
2743
+ // stop running daemon first
2744
+ const pid = readPid()
2745
+ if (pid && isRunning(pid)) {
2746
+ try { process.kill(pid, "SIGTERM"); clearPid(); console.log(` \x1b[32m✓\x1b[0m Runner stopped`) }
2747
+ catch {}
2748
+ }
2749
+
2750
+ try {
2751
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2752
+ const res = await fetch(`${appUrl}/api/cli/login`, {
2753
+ method: "DELETE",
2754
+ headers: { "content-type": "application/json" },
2755
+ body: JSON.stringify({ apiKey: key }),
2756
+ })
2757
+ if (res.ok) console.log(` \x1b[32m✓\x1b[0m API key revoked`)
2758
+ else console.log(` \x1b[33m⚠\x1b[0m Server returned ${res.status} — clearing locally anyway`)
2759
+ } catch { console.log(` \x1b[33m⚠\x1b[0m Could not reach server — clearing locally`) }
2760
+
2761
+ // write a clean config — delete auth fields entirely
2762
+ const clean = { appUrl: config.appUrl }
2763
+ writeConfig(clean)
2764
+ console.log(` \x1b[32m✓\x1b[0m Logged out\n`)
2765
+
2766
+ // re-render banner + welcome to reflect logged-out state
2767
+ process.stdout.write("\x1b[2J\x1b[H")
2768
+ printBanner(readConfig())
2769
+ await printWelcome()
2770
+ break
2771
+ }
2772
+ case "connect": {
2773
+ const config = readConfig()
2774
+ const key = config.apiKey ?? config.workspaceApiKey
2775
+ if (!key) { console.log("\n Not logged in — run /login first.\n"); break }
2776
+ console.log(`\x1b[2mStarting runner in foreground — Ctrl+C to stop\x1b[0m\n`)
2777
+ process.stdin.setRawMode(false)
2778
+ process.stdin.pause()
2779
+ const runnerArgs = buildRunnerArgs([])
2780
+ const connChild = spawn(process.execPath, [path.resolve(__dirname, "pacework-runner.mjs"), ...runnerArgs], {
2781
+ stdio: ["ignore", "pipe", "pipe"],
2782
+ env: { ...process.env, PATH: process.env.PATH || "" },
2783
+ })
2784
+ const handleStream = (stream) => {
2785
+ let buf = ""
2786
+ stream.on("data", chunk => {
2787
+ buf += chunk.toString()
2788
+ const lines = buf.split("\n"); buf = lines.pop()
2789
+ for (const l of lines) { const f = formatLogLine(l); if (f) process.stdout.write(f + "\n") }
2790
+ })
2791
+ }
2792
+ handleStream(connChild.stdout)
2793
+ handleStream(connChild.stderr)
2794
+ const stopConn = () => connChild.kill("SIGTERM")
2795
+ process.once("SIGINT", stopConn)
2796
+ await new Promise(r => connChild.on("exit", r))
2797
+ process.removeListener("SIGINT", stopConn)
2798
+ process.stdin.setRawMode(true)
2799
+ process.stdin.resume()
2800
+ console.log("\x1b[2mRunner stopped.\x1b[0m\n")
2801
+ break
2802
+ }
2803
+ case "pid": {
2804
+ const pid = readPid()
2805
+ if (pid && isRunning(pid)) {
2806
+ let startedAt = ""
2807
+ try { const c = JSON.parse(fs.readFileSync(CMD_FILE, "utf8")); startedAt = ` started ${relTime(c.startedAt)}` } catch {}
2808
+ console.log(`\n \x1b[32m●\x1b[0m Runner PID \x1b[1m${pid}\x1b[0m${startedAt}\n`)
2809
+ } else {
2810
+ console.log(`\n \x1b[2m○ Runner is not running\x1b[0m\n`)
2811
+ }
2812
+ break
2813
+ }
2814
+ case "": break
2815
+ default: {
2816
+ console.log(`\x1b[31mUnknown command: ${cmd}\x1b[0m Type \x1b[36mhelp\x1b[0m for available commands.`)
2817
+ }
2818
+ }
2819
+ }
2820
+
2821
+ // ── raw TTY input loop with / dropdown ───────────────────────────────────
2822
+
2823
+ const SLASH_COMMANDS = [
2824
+ { name: "status", desc: "Show runner status and config" },
2825
+ { name: "jobs", desc: "Active runs + recent history" },
2826
+ { name: "watch", desc: "Auto-refresh jobs table every 3s in-place (Ctrl+C to stop)" },
2827
+ { name: "issues", desc: "List open issues in the workspace" },
2828
+ { name: "run", desc: "Dispatch an issue to this runner (e.g. /run PLT-42)" },
2829
+ { name: "cancel", desc: "Cancel a running job (e.g. /cancel <run-id>)" },
2830
+ { name: "retry", desc: "Retry a failed job (e.g. /retry <run-id>)" },
2831
+ { name: "pause", desc: "Pause this runner (maintenance mode)" },
2832
+ { name: "resume", desc: "Resume a paused runner" },
2833
+ { name: "capacity", desc: "Set max parallel jobs (e.g. /capacity 3)" },
2834
+ { name: "mcp", desc: "MCP tools — /mcp install | status | test" },
2835
+ { name: "executor", desc: "Executor tools — /executor test" },
2836
+ { name: "stats", desc: "Job throughput — runs today, success rate, avg duration" },
2837
+ { name: "tail", desc: "Live-stream the runner log" },
2838
+ { name: "logs", desc: "Tail last N log lines" },
2839
+ { name: "start", desc: "Start runner as background daemon" },
2840
+ { name: "stop", desc: "Stop the background daemon" },
2841
+ { name: "restart", desc: "Stop then start daemon" },
2842
+ { name: "connect", desc: "Run runner in foreground (exit shell first)" },
2843
+ { name: "use", desc: "Switch executor (e.g. /use gemini)" },
2844
+ { name: "rename", desc: "Set runner display name" },
2845
+ { name: "whoami", desc: "Show workspace and key info" },
2846
+ { name: "open", desc: "Open workspace in browser" },
2847
+ { name: "config", desc: "View or set config values" },
2848
+ { name: "doctor", desc: "Check dependencies" },
2849
+ { name: "update", desc: "Upgrade pacework-runner" },
2850
+ { name: "login", desc: "Authenticate via browser" },
2851
+ { name: "logout", desc: "Revoke API key and clear credentials" },
2852
+ { name: "help", desc: "Show this help screen" },
2853
+ { name: "clear", desc: "Clear screen" },
2854
+ { name: "pid", desc: "Show runner process ID" },
2855
+ { name: "exit", desc: "Exit the shell" },
2856
+ ]
2857
+
2858
+ // subcommand hints shown after "<cmd> "
2859
+ const SUBCOMMANDS = {
2860
+ issues: [
2861
+ { name: "open", desc: "backlog + todo (default)" },
2862
+ { name: "active", desc: "todo + in_progress + in_review" },
2863
+ { name: "in_progress", desc: "currently being worked on" },
2864
+ { name: "in_review", desc: "awaiting review / approval" },
2865
+ { name: "todo", desc: "ready to start" },
2866
+ { name: "backlog", desc: "not yet scheduled" },
2867
+ { name: "done", desc: "completed issues" },
2868
+ { name: "all", desc: "every status" },
2869
+ ],
2870
+ mcp: [
2871
+ { name: "install", desc: "inject pacework MCP into executor config" },
2872
+ { name: "status", desc: "show configured MCP servers" },
2873
+ { name: "test", desc: "ping each MCP server" },
2874
+ ],
2875
+ executor: [
2876
+ { name: "test", desc: "smoke-test the executor binary" },
2877
+ ],
2878
+ use: EXECUTORS.map(e => ({ name: e.id, desc: e.label })),
2879
+ open: [
2880
+ { name: "<issue-id>", desc: "open specific issue in browser e.g. /open PLT-42" },
2881
+ ],
2882
+ }
2883
+
2884
+ const MAX_DROPDOWN = 8 // visible rows at once
2885
+
2886
+ let dropdownActive = false
2887
+ let dropdownItems = []
2888
+ let dropdownIndex = 0
2889
+ let dropdownOffset = 0 // scroll offset
2890
+ let inputBuffer = ""
2891
+ let cursorPos = 0
2892
+
2893
+ function renderPrompt() {
2894
+ const cfg = readConfig()
2895
+ const pid = readPid()
2896
+ const running = pid && isRunning(pid)
2897
+ const dot = running ? `\x1b[32m●\x1b[0m` : `\x1b[2m○\x1b[0m`
2898
+ const ws = cfg.workspaceSlug ?? cfg.workspaceId ?? "?"
2899
+ const exe = cfg.executor ?? "?"
2900
+ return `${dot} \x1b[2m${ws} · ${exe}\x1b[0m \x1b[36m>\x1b[0m `
2901
+ }
2902
+
2903
+ function clearDropdown(rowCount) {
2904
+ if (!rowCount) return
2905
+ // move up rowCount lines and clear each
2906
+ for (let i = 0; i < rowCount; i++) {
2907
+ process.stdout.write("\x1b[A\x1b[2K")
2908
+ }
2909
+ }
2910
+
2911
+ function drawDropdown() {
2912
+ if (!dropdownActive || !dropdownItems.length) return 0
2913
+ const visible = dropdownItems.slice(dropdownOffset, dropdownOffset + MAX_DROPDOWN)
2914
+ const nameW = Math.max(...visible.map(i => i.name.length), 8)
2915
+ let rows = 0
2916
+
2917
+ // separator line
2918
+ process.stdout.write(`\n\x1b[38;5;238m${"─".repeat(60)}\x1b[0m\x1b[K`)
2919
+ rows++
2920
+
2921
+ // up arrow if scrolled down
2922
+ if (dropdownOffset > 0) {
2923
+ process.stdout.write(`\n\x1b[2m ▲ more above\x1b[0m\x1b[K`)
2924
+ rows++
2925
+ }
2926
+
2927
+ visible.forEach((item, idx) => {
2928
+ const absIdx = dropdownOffset + idx
2929
+ const selected = absIdx === dropdownIndex
2930
+ const bg = selected ? "\x1b[48;5;238m" : ""
2931
+ const rst = "\x1b[0m"
2932
+ const name = selected
2933
+ ? `\x1b[1;36m${item.name.padEnd(nameW)}\x1b[0m`
2934
+ : `\x1b[36m${item.name.padEnd(nameW)}\x1b[0m`
2935
+ const desc = selected ? `${item.desc}` : `\x1b[2m${item.desc}\x1b[0m`
2936
+ process.stdout.write(`\n${bg} ${name} ${desc}${rst}\x1b[K`)
2937
+ rows++
2938
+ })
2939
+
2940
+ // down arrow if more below
2941
+ if (dropdownOffset + MAX_DROPDOWN < dropdownItems.length) {
2942
+ process.stdout.write(`\n\x1b[2m ▼ more below\x1b[0m\x1b[K`)
2943
+ rows++
2944
+ }
2945
+
2946
+ return rows
2947
+ }
2948
+
2949
+ let lastDropdownRows = 0
2950
+
2951
+ function redraw() {
2952
+ // Step 1: erase everything we drew last time.
2953
+ if (lastDropdownRows > 0) {
2954
+ process.stdout.write(`\x1b[${lastDropdownRows}B`)
2955
+ for (let i = 0; i < lastDropdownRows; i++) {
2956
+ process.stdout.write(`\x1b[2K\x1b[A`)
2957
+ }
2958
+ }
2959
+
2960
+ // Step 2: rewrite the prompt + buffer on current line
2961
+ process.stdout.write(`\r\x1b[2K${renderPrompt()}${inputBuffer}`)
2962
+
2963
+ // Step 3: draw dropdown on lines below (cursor is at end of buffer)
2964
+ if (dropdownActive && dropdownItems.length) {
2965
+ process.stdout.write(`\x1b7`)
2966
+ lastDropdownRows = drawDropdown() ?? 0
2967
+ process.stdout.write(`\x1b8`)
2968
+ } else {
2969
+ lastDropdownRows = 0
2970
+ }
2971
+
2972
+ // Step 4: reposition cursor within the input buffer
2973
+ if (cursorPos < inputBuffer.length) {
2974
+ process.stdout.write(`\x1b[${inputBuffer.length - cursorPos}D`)
2975
+ }
2976
+
2977
+ // Step 5: re-pin footer (save/restore so cursor stays on prompt line)
2978
+ drawFooter()
2979
+ }
2980
+
2981
+ function renderPromptPlain() {
2982
+ const cfg = readConfig()
2983
+ const pid = readPid()
2984
+ const running = pid && isRunning(pid)
2985
+ const dot = running ? "● " : "○ "
2986
+ const ws = cfg.workspaceSlug ?? cfg.workspaceId ?? "?"
2987
+ const exe = cfg.executor ?? "?"
2988
+ return `${dot}${ws} · ${exe} > `
2989
+ }
2990
+
2991
+ function drawFooter() {} // no-op — footer removed
2992
+
2993
+ function updateDropdownForBuffer() {
2994
+ const withoutSlash = inputBuffer.slice(1) // "issues in_pro"
2995
+ const spaceIdx = withoutSlash.indexOf(" ")
2996
+
2997
+ if (spaceIdx === -1) {
2998
+ // still typing the command word
2999
+ openDropdown(withoutSlash)
3000
+ } else {
3001
+ const cmdWord = withoutSlash.slice(0, spaceIdx) // "issues"
3002
+ const argSoFar = withoutSlash.slice(spaceIdx + 1) // "in_pro"
3003
+ const subs = SUBCOMMANDS[cmdWord]
3004
+ if (subs) {
3005
+ const filtered = subs.filter(s => s.name.startsWith(argSoFar))
3006
+ if (filtered.length) {
3007
+ dropdownActive = true
3008
+ dropdownItems = filtered
3009
+ dropdownIndex = 0
3010
+ dropdownOffset = 0
3011
+ } else {
3012
+ closeDropdown()
3013
+ }
3014
+ } else {
3015
+ closeDropdown()
3016
+ }
3017
+ }
3018
+ }
3019
+
3020
+ function openDropdown(filter) {
3021
+ dropdownActive = true
3022
+ dropdownItems = SLASH_COMMANDS.filter(c => c.name.startsWith(filter))
3023
+ dropdownIndex = 0
3024
+ dropdownOffset = 0
3025
+ }
3026
+
3027
+ function closeDropdown() {
3028
+ dropdownActive = false
3029
+ dropdownItems = []
3030
+ dropdownIndex = 0
3031
+ dropdownOffset = 0
3032
+ }
3033
+
3034
+ function acceptDropdownItem() {
3035
+ if (!dropdownActive || !dropdownItems.length) return
3036
+ const chosen = dropdownItems[dropdownIndex]
3037
+ // if we're in subcommand mode (buffer already has a space), append the subcommand
3038
+ if (inputBuffer.includes(" ")) {
3039
+ const base = inputBuffer.slice(0, inputBuffer.lastIndexOf(" ") + 1)
3040
+ inputBuffer = base + chosen.name + " "
3041
+ } else {
3042
+ inputBuffer = `/${chosen.name} `
3043
+ }
3044
+ cursorPos = inputBuffer.length
3045
+ closeDropdown()
3046
+ }
3047
+
3048
+ process.stdin.setRawMode(true)
3049
+ process.stdin.resume()
3050
+ process.stdin.setEncoding("utf8")
3051
+
3052
+ // initial prompt
3053
+ process.stdout.write(renderPrompt())
3054
+
3055
+ process.stdin.on("data", async (key) => {
3056
+ // Ctrl+C / Ctrl+D
3057
+ if (key === "\x03" || key === "\x04") {
3058
+ if (lastDropdownRows) clearDropdown(lastDropdownRows + 1)
3059
+ console.log("\nBye.")
3060
+ process.exit(0)
3061
+ }
3062
+
3063
+ // Enter
3064
+ if (key === "\r" || key === "\n") {
3065
+ if (dropdownActive && dropdownItems.length) {
3066
+ acceptDropdownItem()
3067
+ redraw()
3068
+ return
3069
+ }
3070
+ // submit — erase any open dropdown then newline
3071
+ if (lastDropdownRows > 0) {
3072
+ process.stdout.write(`\x1b[${lastDropdownRows}B`)
3073
+ for (let i = 0; i < lastDropdownRows; i++) process.stdout.write(`\x1b[2K\x1b[A`)
3074
+ lastDropdownRows = 0
3075
+ }
3076
+ process.stdout.write("\n")
3077
+ const line = inputBuffer.trim()
3078
+ inputBuffer = ""
3079
+ cursorPos = 0
3080
+ closeDropdown()
3081
+ if (line) {
3082
+ // strip leading /
3083
+ const clean = line.startsWith("/") ? line.slice(1) : line
3084
+ await runShellCommand(clean)
3085
+ }
3086
+ drawFooter()
3087
+ process.stdout.write(renderPrompt())
3088
+ return
3089
+ }
3090
+
3091
+ // Escape — close dropdown
3092
+ if (key === "\x1b" && !key[1]) {
3093
+ closeDropdown()
3094
+ redraw()
3095
+ return
3096
+ }
3097
+
3098
+ // Arrow keys: \x1b[A up, \x1b[B down
3099
+ if (key === "\x1b[A") {
3100
+ if (dropdownActive && dropdownItems.length) {
3101
+ if (dropdownIndex > 0) {
3102
+ dropdownIndex--
3103
+ if (dropdownIndex < dropdownOffset) dropdownOffset = dropdownIndex
3104
+ }
3105
+ redraw()
3106
+ }
3107
+ return
3108
+ }
3109
+ if (key === "\x1b[B") {
3110
+ if (dropdownActive && dropdownItems.length) {
3111
+ if (dropdownIndex < dropdownItems.length - 1) {
3112
+ dropdownIndex++
3113
+ if (dropdownIndex >= dropdownOffset + MAX_DROPDOWN) dropdownOffset++
3114
+ }
3115
+ redraw()
3116
+ }
3117
+ return
3118
+ }
3119
+
3120
+ // Left / Right arrows
3121
+ if (key === "\x1b[C") { if (cursorPos < inputBuffer.length) { cursorPos++; redraw() }; return }
3122
+ if (key === "\x1b[D") { if (cursorPos > 0) { cursorPos--; redraw() }; return }
3123
+
3124
+ // Backspace
3125
+ if (key === "\x7f" || key === "\b") {
3126
+ if (cursorPos > 0) {
3127
+ inputBuffer = inputBuffer.slice(0, cursorPos - 1) + inputBuffer.slice(cursorPos)
3128
+ cursorPos--
3129
+ }
3130
+ if (inputBuffer.startsWith("/")) {
3131
+ updateDropdownForBuffer()
3132
+ } else {
3133
+ closeDropdown()
3134
+ }
3135
+ redraw()
3136
+ return
3137
+ }
3138
+
3139
+ // Printable character
3140
+ if (key >= " " || key === "\t") {
3141
+ // Tab: if dropdown open, accept; else open
3142
+ if (key === "\t") {
3143
+ if (dropdownActive && dropdownItems.length) {
3144
+ acceptDropdownItem()
3145
+ } else if (inputBuffer === "" || inputBuffer === "/") {
3146
+ if (inputBuffer === "") inputBuffer = "/"
3147
+ openDropdown("")
3148
+ }
3149
+ redraw()
3150
+ return
3151
+ }
3152
+ inputBuffer = inputBuffer.slice(0, cursorPos) + key + inputBuffer.slice(cursorPos)
3153
+ cursorPos++
3154
+ if (inputBuffer.startsWith("/")) {
3155
+ updateDropdownForBuffer()
3156
+ } else {
3157
+ closeDropdown()
3158
+ }
3159
+ redraw()
3160
+ return
3161
+ }
3162
+ })
3163
+ }
3164
+
3165
+ // ── up (one-command setup) ─────────────────────────────────────────────────────
3166
+ // The app shows: npx pacework@latest up --app-url URL --token CODE
3167
+ // One command signs in with a one-time code, picks the coding tool installed on
3168
+ // this machine, uses the current repository, and installs the runner as a login
3169
+ // service (launchd / systemd) so it keeps running across restarts.
3170
+
3171
+ else if (command === "up") {
3172
+ printBanner()
3173
+ ensureStateDir()
3174
+ const config = readConfig()
3175
+ const appUrl = String(parsedArgs["app-url"] || config.appUrl || "https://pacework.io").replace(/\/$/, "")
3176
+
3177
+ // 1. Credentials: redeem the one-time code, or reuse a saved login.
3178
+ if (parsedArgs.token && parsedArgs.token !== "true") {
3179
+ process.stdout.write(" signing in… ")
3180
+ let session = null
3181
+ try {
3182
+ const res = await fetch(`${appUrl}/api/cli/login?token=${encodeURIComponent(parsedArgs.token)}`)
3183
+ session = await res.json()
3184
+ } catch (err) {
3185
+ console.log("\x1b[31m✗\x1b[0m")
3186
+ console.error(` Could not reach pacework at ${appUrl}: ${err.message}`)
3187
+ process.exit(1)
3188
+ }
3189
+ if (session?.status !== "authorized" || !session.apiKey) {
3190
+ console.log("\x1b[31m✗\x1b[0m")
3191
+ console.error(" This connect code has expired or was already used. Copy a fresh command from pacework (Agents → Connect a runner).")
3192
+ process.exit(1)
3193
+ }
3194
+ config.appUrl = appUrl
3195
+ config.apiKey = session.apiKey
3196
+ config.workspaceId = session.workspaceId
3197
+ config.workspaceSlug = session.workspaceSlug
3198
+ if (session.userName) config.userName = session.userName
3199
+ if (session.userEmail) config.userEmail = session.userEmail
3200
+ console.log(`\x1b[32m✓\x1b[0m ${session.workspaceSlug ?? session.workspaceId}`)
3201
+ } else if (!config.apiKey || !config.workspaceId) {
3202
+ console.error(" Not signed in. Copy the connect command from pacework (Agents → Connect a runner), or run: pacework login")
3203
+ process.exit(1)
3204
+ }
3205
+
3206
+ // 2. Coding tool: the one asked for, the one used before, or the first installed.
3207
+ const preferred = parsedArgs.executor || config.executor
3208
+ const installed = EXECUTORS.filter((e) => e.id !== "github_copilot" && checkBinaryExists(e.bin))
3209
+ const executor = preferred && EXECUTORS.some((e) => e.id === preferred) ? preferred : installed[0]?.id
3210
+ if (!executor) {
3211
+ console.error(" No coding tool found on this machine. Install Claude Code (npm i -g @anthropic-ai/claude-code) or Codex (npm i -g @openai/codex), sign in to it, and run this again.")
3212
+ process.exit(1)
3213
+ }
3214
+ const executorEntry = EXECUTORS.find((e) => e.id === executor)
3215
+ if (executorEntry && !checkBinaryExists(executorEntry.bin)) {
3216
+ console.error(` ${executorEntry.label} (${executorEntry.bin}) is not installed or not on PATH.`)
3217
+ process.exit(1)
3218
+ }
3219
+ console.log(` coding tool \x1b[1m${executorLabel(executor)}\x1b[0m`)
3220
+
3221
+ // 3. Repository: where the command is run.
3222
+ let repoRoot = parsedArgs["repo-root"] && parsedArgs["repo-root"] !== "true" ? path.resolve(parsedArgs["repo-root"]) : null
3223
+ if (!repoRoot) {
3224
+ try {
3225
+ repoRoot = execSync("git rev-parse --show-toplevel", { cwd: process.cwd(), stdio: ["ignore", "pipe", "ignore"] }).toString().trim()
3226
+ } catch {
3227
+ console.error(" Run this inside the git repository the agents should work on (or pass --repo-root).")
3228
+ process.exit(1)
3229
+ }
3230
+ }
3231
+ console.log(` repository \x1b[2m${repoRoot}\x1b[0m`)
3232
+ const protectedFolder = privacyProtectedFolder(repoRoot)
3233
+ if (protectedFolder) {
3234
+ console.log(` \x1b[33m⚠ This repository is in your ${protectedFolder} folder. macOS asks before a background\x1b[0m`)
3235
+ console.log(` \x1b[33m service may read it — if a "node would like to access…" dialog appears, click Allow.\x1b[0m`)
3236
+ }
3237
+
3238
+ config.executor = executor
3239
+ config.repoRoot = repoRoot
3240
+ config.runnerName = (parsedArgs.name && parsedArgs.name !== "true") ? parsedArgs.name : (config.runnerName || `${os.hostname().replace(/\.local$/, "")} · ${executorLabel(executor)}`)
3241
+ // Gemini and Cursor share one config file per machine, so one run at a time.
3242
+ const singleRun = executor === "gemini" || executor === "cursor_agent"
3243
+ config.maxParallelRuns = singleRun ? 1 : Number(parsedArgs["max-parallel-runs"]) || config.maxParallelRuns || 2
3244
+ if (parsedArgs.sandbox !== undefined) config.sandbox = !["false", "0", "no"].includes(String(parsedArgs.sandbox))
3245
+ writeConfig(config)
3246
+ console.log(` runner \x1b[1m${config.runnerName}\x1b[0m (${config.maxParallelRuns} at a time${config.sandbox ? ", sandboxed" : ""})`)
3247
+
3248
+ // 4. Replace any runner already going on this machine.
3249
+ if (isServiceInstalled()) stopService()
3250
+ const oldPid = readPid()
3251
+ if (oldPid && isRunning(oldPid)) { try { process.kill(oldPid, "SIGTERM") } catch {} }
3252
+ for (const stray of findStrayRunnerPids(0)) { try { process.kill(stray, "SIGKILL") } catch {} }
3253
+ clearPid()
3254
+
3255
+ // 5. Install and start the service from a stable copy of this package.
3256
+ const logOffset = (() => { try { return fs.statSync(LOG_FILE).size } catch { return 0 } })()
3257
+ const ctlPath = installStableCopy(path.resolve(__dirname, ".."), LOCAL_VERSION)
3258
+ const cli = (() => { try { return installCommandLauncher(ctlPath) } catch { return `node ${ctlPath}` } })()
3259
+ let service = null
3260
+ try {
3261
+ service = installService({ ctlPath })
3262
+ } catch (err) {
3263
+ console.error(` Could not install the login service: ${err.message}`)
3264
+ }
3265
+
3266
+ if (!service) {
3267
+ console.log(" \x1b[33mNo login service on this system — starting in the background instead.\x1b[0m")
3268
+ const started = spawn(process.execPath, [ctlPath, "start"], { stdio: "inherit", env: process.env })
3269
+ started.on("exit", (code) => process.exit(code ?? 0))
3270
+ } else {
3271
+ process.stdout.write(" starting… ")
3272
+ const { ready, lastError } = await waitForRunnerReady({ logOffset, timeoutMs: 30000 })
3273
+ if (!ready) {
3274
+ console.log("\x1b[31m✗\x1b[0m")
3275
+ if (lastError) console.log(` ${lastError}`)
3276
+ if (protectedFolder) {
3277
+ console.log(` Most likely macOS has not allowed it to read your ${protectedFolder} folder yet. Allow "node" in`)
3278
+ console.log(" System Settings → Privacy & Security → Files and Folders (or Full Disk Access), or move the")
3279
+ console.log(" repository somewhere like ~/code and run this again. The runner starts by itself once it can read it.")
3280
+ }
3281
+ console.log(` The service keeps retrying. See what is wrong with: ${cli} logs`)
3282
+ process.exit(1)
3283
+ }
3284
+ console.log(`\x1b[32m✓\x1b[0m
3285
+
3286
+ \x1b[32mRunner is up\x1b[0m and waiting for work. It starts with your computer and restarts on its own.
3287
+ status ${cli} status
3288
+ logs ${cli} logs
3289
+ pause ${cli} stop
3290
+ remove ${cli} down`)
3291
+ if (service.kind === "systemd") {
3292
+ console.log(` \x1b[2mTo keep it running after you log out: loginctl enable-linger ${os.userInfo().username}\x1b[0m`)
3293
+ }
3294
+ process.exit(0)
3295
+ }
3296
+ }
3297
+
3298
+ // ── down (remove the login service) ───────────────────────────────────────────
3299
+
3300
+ else if (command === "down") {
3301
+ if (!isServiceInstalled()) {
3302
+ console.log("No runner service is installed.")
3303
+ process.exit(0)
3304
+ }
3305
+ uninstallService()
3306
+ for (const stray of findStrayRunnerPids(0)) { try { process.kill(stray, "SIGKILL") } catch {} }
3307
+ clearPid()
3308
+ console.log("\x1b[32m✓ Runner service removed.\x1b[0m It will not start again until you run: pacework up")
3309
+ process.exit(0)
3310
+ }
3311
+
3312
+ // ── service-run (what the login service executes) ─────────────────────────────
3313
+ // Reads the saved config and runs the runner in the foreground; the OS restarts
3314
+ // it when it exits. Not meant to be run by hand.
3315
+
3316
+ else if (command === "run-cloud") {
3317
+ // Inside a GitHub Actions job (.github/workflows/pacework-agent.yml): trade
3318
+ // the one-time ticket for a registration bound to this run, then run it once.
3319
+ const appUrl = String(process.env.PACEWORK_APP_URL || "").replace(/\/$/, "")
3320
+ const ticket = process.env.PACEWORK_CLOUD_TICKET || ""
3321
+ if (!appUrl || !ticket) {
3322
+ console.error("run-cloud needs PACEWORK_APP_URL and PACEWORK_CLOUD_TICKET (set by the pacework workflow).")
3323
+ process.exit(1)
3324
+ }
3325
+ const res = await fetch(`${appUrl}/api/agent-runners/cloud/redeem`, {
3326
+ method: "POST",
3327
+ headers: { "content-type": "application/json" },
3328
+ body: JSON.stringify({ ticket }),
3329
+ }).catch((error) => ({ ok: false, status: 0, text: async () => String(error) }))
3330
+ if (!res.ok) {
3331
+ console.error(`pacework did not accept this job's ticket (${res.status}): ${(await res.text()).slice(0, 300)}`)
3332
+ process.exit(1)
3333
+ }
3334
+ const registration = await res.json()
3335
+ if (registration.self_test) {
3336
+ // "Test cloud setup": reaching this line already proves the job started and
3337
+ // reached pacework. Check the rest a real run needs, report, and stop.
3338
+ const check = (bin, checkArgs) => {
3339
+ try {
3340
+ return execFileSync(bin, checkArgs, { stdio: ["ignore", "pipe", "ignore"] }).toString().trim().split("\n")[0]
3341
+ } catch {
3342
+ return null
3343
+ }
3344
+ }
3345
+ const workspace = process.env.GITHUB_WORKSPACE || process.cwd()
3346
+ const details = {
3347
+ node: process.version,
3348
+ claude_code: check("claude", ["--version"]),
3349
+ docker: check("docker", ["--version"]),
3350
+ setup_command: detectSetupCommand(workspace),
3351
+ agent_secrets: Object.keys(agentSecretsFrom(process.env.PACEWORK_SECRETS)),
3352
+ }
3353
+ details.ok = Boolean(details.claude_code)
3354
+ if (!details.ok) details.problem = "The coding tool did not install in the job."
3355
+ await fetch(`${appUrl}/api/agent-runners/cloud/self-test`, {
3356
+ method: "POST",
3357
+ headers: { "content-type": "application/json" },
3358
+ body: JSON.stringify({ ticket, details }),
3359
+ }).catch(() => {})
3360
+ console.log(`pacework cloud self-test: ${details.ok ? "passed" : "failed"} ${JSON.stringify(details)}`)
3361
+ process.exit(details.ok ? 0 : 1)
3362
+ }
3363
+ const executor = registration.local_executor || process.env.RUNNER_EXECUTOR || "claude_code"
3364
+
3365
+ // A fresh GitHub machine has no git identity, and its checkout records no
3366
+ // origin/HEAD. Without the first, agents invented a committer; without the
3367
+ // second, comparing against the base branch failed.
3368
+ const workspace = process.env.GITHUB_WORKSPACE || process.cwd()
3369
+ const git = (...gitArgs) => { try { execFileSync("git", ["-C", workspace, ...gitArgs], { stdio: "ignore" }) } catch {} }
3370
+ git("config", "--global", "user.name", "pacework Agent")
3371
+ git("config", "--global", "user.email", "pacework-agent@users.noreply.github.com")
3372
+ try {
3373
+ const branch = execFileSync("git", ["-C", workspace, "branch", "--show-current"]).toString().trim()
3374
+ if (branch) git("symbolic-ref", "refs/remotes/origin/HEAD", `refs/remotes/origin/${branch}`)
3375
+ } catch {}
3376
+ const runnerScript = path.resolve(__dirname, "pacework-runner.mjs")
3377
+ const child = spawn(process.execPath, [
3378
+ runnerScript,
3379
+ "--app-url", appUrl,
3380
+ "--workspace-id", registration.workspace_id,
3381
+ "--repo-root", process.env.GITHUB_WORKSPACE || process.cwd(),
3382
+ "--executor", executor,
3383
+ "--name", "GitHub Actions",
3384
+ "--max-parallel-runs", "1",
3385
+ ], {
3386
+ stdio: "inherit",
3387
+ env: {
3388
+ // All of the repository's secrets arrive as one JSON value; the agent
3389
+ // gets only the PACEWORK_ENV_* ones, and nothing gets the rest.
3390
+ ...Object.fromEntries(Object.entries(process.env).filter(([key]) => key !== "PACEWORK_SECRETS")),
3391
+ PACEWORK_AGENT_ENV: JSON.stringify(agentSecretsFrom(process.env.PACEWORK_SECRETS)),
3392
+ PACEWORK_CLOUD_STATE: JSON.stringify({
3393
+ runner_id: registration.runner_id,
3394
+ runner_secret: registration.runner_secret,
3395
+ runner_mcp_key: registration.runner_mcp_key,
3396
+ workspace_id: registration.workspace_id,
3397
+ local_executor: executor,
3398
+ }),
3399
+ },
3400
+ })
3401
+ child.on("exit", (code) => process.exit(code ?? 1))
3402
+ }
3403
+
3404
+ else if (command === "service-run") {
3405
+ ensureStateDir()
3406
+ fs.writeFileSync(PID_FILE, String(process.pid), "utf8")
3407
+ fs.writeFileSync(CMD_FILE, JSON.stringify({ service: true, startedAt: new Date().toISOString() }, null, 2), "utf8")
3408
+
3409
+ // On macOS, reading a repository in Desktop/Documents/Downloads blocks until
3410
+ // the user grants access, and a blocked read hangs the whole process. Probe in
3411
+ // a child with a timeout, and explain the fix in the log while waiting.
3412
+ const repoRoot = readConfig().repoRoot
3413
+ const logLine = (level, event, msg) => process.stdout.write(`${JSON.stringify({ ts: new Date().toISOString(), level, event, msg })}\n`)
3414
+ const repoReadable = () => new Promise((resolve) => {
3415
+ const probe = spawn(process.execPath, ["-e", `require("fs").readdirSync(${JSON.stringify(repoRoot || ".")})`], { stdio: "ignore" })
3416
+ const timer = setTimeout(() => { probe.kill("SIGKILL"); resolve(false) }, 5000)
3417
+ probe.on("exit", (code) => { clearTimeout(timer); resolve(code === 0) })
3418
+ })
3419
+ let warned = false
3420
+ while (repoRoot && !(await repoReadable())) {
3421
+ if (!warned) {
3422
+ const folder = privacyProtectedFolder(repoRoot)
3423
+ logLine("error", "runner.repo_access_blocked", folder
3424
+ ? `Cannot read ${repoRoot}: macOS has not allowed background access to your ${folder} folder. Allow "node" in System Settings → Privacy & Security → Files and Folders (or Full Disk Access), or move the repository out of ${folder}. Retrying every 30s.`
3425
+ : `Cannot read ${repoRoot}. Check that it exists and is readable. Retrying every 30s.`)
3426
+ warned = true
3427
+ }
3428
+ await new Promise((resolve) => setTimeout(resolve, 30_000))
3429
+ }
3430
+
3431
+ const runnerScript = path.resolve(__dirname, "pacework-runner.mjs")
3432
+ const child = spawn(process.execPath, [runnerScript, ...buildRunnerArgs([])], {
3433
+ stdio: "inherit",
3434
+ env: runnerEnv(),
3435
+ })
3436
+
3437
+ // pacework Intelligence triage set to "Local runner" needs its own loop. It
3438
+ // used to be a separate `pacework-runner triage` nobody knew to start, so
3439
+ // triage jobs sat unprocessed. Run it here too; with nothing to do it only
3440
+ // polls. If it stops, start it again — the agent runner is what this service
3441
+ // lives and dies with.
3442
+ let stopping = false
3443
+ let triage = null
3444
+ const startTriage = () => {
3445
+ if (stopping) return
3446
+ triage = spawn(process.execPath, [fileURLToPath(import.meta.url), "triage"], { stdio: "inherit", env: runnerEnv() })
3447
+ triage.on("exit", () => {
3448
+ triage = null
3449
+ if (!stopping) setTimeout(startTriage, 30_000)
3450
+ })
3451
+ }
3452
+ startTriage()
3453
+
3454
+ const forward = (signal) => () => {
3455
+ stopping = true
3456
+ try { child.kill(signal) } catch {}
3457
+ try { triage?.kill(signal) } catch {}
3458
+ }
3459
+ process.on("SIGTERM", forward("SIGTERM"))
3460
+ process.on("SIGINT", forward("SIGINT"))
3461
+ child.on("exit", (code) => {
3462
+ stopping = true
3463
+ try { triage?.kill("SIGTERM") } catch {}
3464
+ clearPid()
3465
+ process.exit(code ?? 1)
3466
+ })
3467
+ }
3468
+
3469
+ // ── unknown ───────────────────────────────────────────────────────────────────
3470
+
3471
+ else {
3472
+ console.error(`\x1b[31mUnknown command: ${command}\x1b[0m`)
3473
+ console.error(`Run 'pacework --help' for usage.`)
3474
+ process.exit(1)
3475
+ }