pacework 1.7.15 → 1.7.16

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,1413 @@
1
+ /**
2
+ * The commands of `pacework shell` and of the prompt on the main screen: one
3
+ * set of handlers for both. They write through `out` instead of printing, so
4
+ * the shell shows output as it comes and the main screen can collect it.
5
+ * Moved out of bin/pacework-runner-ctl.mjs; the ctl script passes in the few
6
+ * helpers that live there.
7
+ */
8
+
9
+ import fs from "node:fs"
10
+ import os from "node:os"
11
+ import path from "node:path"
12
+ import process from "node:process"
13
+ import { format, stripVTControlCharacters } from "node:util"
14
+ import { spawn, execFileSync } from "node:child_process"
15
+ import { runRunnerControlCommand } from "./runner-control.mjs"
16
+ import { EXECUTORS, EXECUTOR_DEFAULT_NAMES, checkBinaryExists, executorLabel } from "./executors.mjs"
17
+ import { SHELL_COMMANDS, closestShellCommand, parseShellInput } from "./shell-commands.mjs"
18
+ import { LOG_FILE, CMD_FILE, readPid, isRunning, clearPid, readConfig, writeConfig } from "./control-state.mjs"
19
+
20
+ /**
21
+ * The terminal as output: what `pacework shell` always printed to. Failures
22
+ * go to stdout too, as they always did; `error` only marks the run as failed.
23
+ */
24
+ export const consoleOutput = {
25
+ log: (...args) => console.log(...args),
26
+ error: (...args) => console.log(...args),
27
+ write: (text) => process.stdout.write(text),
28
+ }
29
+
30
+ /** An output that keeps the lines instead of printing them, without colours. */
31
+ export function collectingOutput() {
32
+ let text = ""
33
+ return {
34
+ log: (...args) => { text += `${format(...args)}\n` },
35
+ error: (...args) => { text += `${format(...args)}\n` },
36
+ write: (chunk) => { text += String(chunk) },
37
+ lines: () => stripVTControlCharacters(text).replace(/\n+$/, "").split("\n"),
38
+ }
39
+ }
40
+
41
+ /**
42
+ * Run one command line and return what it said and whether it worked:
43
+ * `{ ok, lines }`. An unknown command suggests the closest one. This is what
44
+ * the main screen's prompt calls; the shell prints the same handlers' output
45
+ * as it comes.
46
+ */
47
+ export async function runCommandLine(input, context) {
48
+ const { command } = parseShellInput(input)
49
+ if (!command) return { ok: true, lines: [] }
50
+ if (!SHELL_COMMANDS.some(({ name }) => name === command)) {
51
+ const closest = closestShellCommand(command)
52
+ return { ok: false, lines: [`Unknown command: ${command}.${closest ? ` Try /${closest}.` : " Use /help to list commands."}`] }
53
+ }
54
+ const output = collectingOutput()
55
+ // The banner decorates the shell only; on the main screen it would print over it.
56
+ const { run } = createShellHandlers({ printBanner: () => {}, ...context, out: output })
57
+ try {
58
+ const { ok } = await run(input)
59
+ return { ok, lines: output.lines() }
60
+ } catch (error) {
61
+ output.error(error instanceof Error ? error.message : String(error))
62
+ return { ok: false, lines: output.lines() }
63
+ }
64
+ }
65
+
66
+ export function createShellHandlers({
67
+ ctlScript,
68
+ runnerScript,
69
+ version: LOCAL_VERSION,
70
+ printBanner,
71
+ updateRunner,
72
+ relTime,
73
+ fmtDuration,
74
+ buildRunnerArgs,
75
+ findStrayRunnerPids,
76
+ formatLogLine,
77
+ readRunnerId,
78
+ out: target = consoleOutput,
79
+ }) {
80
+ // Handlers write failures with out.error, which marks the command as failed.
81
+ let failed = false
82
+ const out = {
83
+ log: (...args) => target.log(...args),
84
+ write: (text) => target.write(text),
85
+ error: (...args) => { failed = true; target.error(...args) },
86
+ }
87
+
88
+ /** Run one command line; `ok` is false when the handler reported a failure. */
89
+ async function run(input) {
90
+ failed = false
91
+ const result = await runShellCommand(input)
92
+ return { ok: typeof result?.ok === "boolean" ? result.ok : !failed }
93
+ }
94
+
95
+ // ── fetch active runs from API ──────────────────────────────────────────────
96
+ async function fetchActiveRuns(config) {
97
+ const key = config.apiKey ?? config.workspaceApiKey
98
+ const appUrl = config.appUrl ?? "https://pacework.io"
99
+ const wsId = config.workspaceId
100
+ if (!key || !wsId) return null
101
+ try {
102
+ const res = await fetch(`${appUrl}/api/workspaces/${wsId}/agent-runner/runs?limit=8`, {
103
+ headers: { "x-workspace-api-key": key },
104
+ signal: AbortSignal.timeout(3000),
105
+ })
106
+ if (!res.ok) return null
107
+ return await res.json()
108
+ } catch { return null }
109
+ }
110
+
111
+ function printJobsTable(runs) {
112
+ if (!runs?.length) return
113
+ const STATUS_COLORS = {
114
+ running: "\x1b[34m",
115
+ queued: "\x1b[33m",
116
+ pending: "\x1b[33m",
117
+ completed: "\x1b[32m",
118
+ failed: "\x1b[31m",
119
+ error: "\x1b[31m",
120
+ cancelled: "\x1b[2m",
121
+ }
122
+ const STATUS_GLYPH = {
123
+ running: "▶",
124
+ queued: "◌",
125
+ pending: "◌",
126
+ completed: "✓",
127
+ failed: "✗",
128
+ error: "✗",
129
+ cancelled: "–",
130
+ }
131
+ // column widths
132
+ const COL_STATUS = 10
133
+ const COL_TITLE = 34
134
+ const COL_AGE = 10
135
+ const COL_DUR = 8
136
+ const hr = ` ${"─".repeat(COL_STATUS + COL_TITLE + COL_AGE + COL_DUR + 6)}`
137
+ out.log(`\x1b[1mActive runs\x1b[0m`)
138
+ out.log(hr)
139
+ out.log(` \x1b[2m${"STATUS".padEnd(COL_STATUS)} ${"TASK".padEnd(COL_TITLE)} ${"AGE".padEnd(COL_AGE)} ${"DURATION".padEnd(COL_DUR)}\x1b[0m`)
140
+ out.log(hr)
141
+ for (const r of runs) {
142
+ const status = (r.status ?? "unknown").toLowerCase()
143
+ const col = STATUS_COLORS[status] ?? ""
144
+ const glyph = STATUS_GLYPH[status] ?? "·"
145
+ const label = `${glyph} ${status}`.padEnd(COL_STATUS)
146
+ const title = (r.task_title ?? r.task_identifier ?? r.id?.slice(0, 8) ?? "—").slice(0, COL_TITLE).padEnd(COL_TITLE)
147
+ const age = relTime(r.started_at ?? r.created_at).padEnd(COL_AGE)
148
+ const dur = r.started_at && r.completed_at
149
+ ? fmtDuration(new Date(r.completed_at) - new Date(r.started_at)).padEnd(COL_DUR)
150
+ : r.started_at ? fmtDuration(Date.now() - new Date(r.started_at)).padEnd(COL_DUR) : "".padEnd(COL_DUR)
151
+ out.log(` ${col}${label}\x1b[0m \x1b[1m${title}\x1b[0m \x1b[2m${age} ${dur}\x1b[0m`)
152
+ }
153
+ out.log(hr)
154
+ out.log("")
155
+ }
156
+
157
+ // ── orchestrator helpers ──────────────────────────────────────────────────
158
+
159
+ async function fetchMcpServerList(config) {
160
+ const key = config.apiKey ?? config.workspaceApiKey
161
+ const wsId = config.workspaceId
162
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
163
+ const runnerId = readRunnerId(config)
164
+ if (!key || !wsId || !runnerId) return null
165
+ try {
166
+ const res = await fetch(`${appUrl}/api/agent-runners/mcp-servers?workspace_id=${encodeURIComponent(wsId)}&runner_id=${encodeURIComponent(runnerId)}`, {
167
+ headers: { Authorization: `Bearer ${key}` },
168
+ signal: AbortSignal.timeout(4000),
169
+ })
170
+ if (!res.ok) return null
171
+ const data = await res.json()
172
+ return Array.isArray(data?.mcp_servers) ? data.mcp_servers : null
173
+ } catch { return null }
174
+ }
175
+
176
+ async function runShellCommand(input) {
177
+ const { command: cmd, args } = parseShellInput(input)
178
+
179
+ switch (cmd) {
180
+ case "help": {
181
+ const cols = process.stdout.columns || 80
182
+ const W = Math.min(cols - 4, 72)
183
+ const div = ` \x1b[38;5;237m${"─".repeat(W)}\x1b[0m`
184
+ const sec = (label) => `\n \x1b[38;5;240m${label}\x1b[0m`
185
+ const cmd = (c, d) => ` \x1b[36m${c.padEnd(18)}\x1b[0m \x1b[2m${d}\x1b[0m`
186
+ out.log("")
187
+ out.log(div)
188
+ out.log(sec("RUNNER"))
189
+ out.log(cmd("start", "Start runner as background daemon"))
190
+ out.log(cmd("stop", "Stop the background daemon"))
191
+ out.log(cmd("restart", "Stop then start daemon"))
192
+ out.log(cmd("connect", "Run runner in foreground"))
193
+ out.log(cmd("pause", "Pause — no new jobs picked up"))
194
+ out.log(cmd("resume", "Resume a paused runner"))
195
+ out.log(cmd("capacity <n>", "Set max parallel jobs"))
196
+ out.log(sec("JOBS"))
197
+ out.log(cmd("jobs", "Active runs + recent history"))
198
+ out.log(cmd("watch", "Auto-refresh jobs every 3s"))
199
+ out.log(cmd("run <issue-id>", "Dispatch issue to this runner"))
200
+ out.log(cmd("cancel <run-id>","Cancel a running job"))
201
+ out.log(cmd("retry <run-id>", "Retry a failed job"))
202
+ out.log(cmd("stats", "Throughput metrics"))
203
+ out.log(sec("ISSUES & AGENTS"))
204
+ out.log(cmd("issues", "List issues (open / active / all / in_progress …)"))
205
+ out.log(cmd("mine", "Issues assigned to you"))
206
+ out.log(cmd("issue <id>", "View issue detail, description, comments"))
207
+ out.log(cmd("agents", "List agents and their skill profiles"))
208
+ out.log(cmd("dashboard", "Orchestration status — runs, queue, review"))
209
+ out.log(cmd("logtail <run-id>","Stream live log of a running job"))
210
+ out.log(cmd("open [id]", "Open workspace (or specific issue) in browser"))
211
+ out.log(sec("MCP & EXECUTOR"))
212
+ out.log(cmd("mcp install", "Inject pacework MCP into executor config"))
213
+ out.log(cmd("mcp status", "Show configured MCP servers"))
214
+ out.log(cmd("mcp test", "Ping MCP servers"))
215
+ out.log(cmd("executor test", "Smoke-test the executor binary"))
216
+ out.log(sec("LOGS"))
217
+ out.log(cmd("tail", "Live-stream the runner log"))
218
+ out.log(cmd("logs [n]", "Tail last N log lines"))
219
+ out.log(sec("CONFIG & AUTH"))
220
+ out.log(cmd("status", "Runner status and config"))
221
+ out.log(cmd("whoami", "Workspace and key info"))
222
+ out.log(cmd("config", "View or set config values"))
223
+ out.log(cmd("use <executor>", "Switch executor"))
224
+ out.log(cmd("rename <name>", "Set runner display name"))
225
+ out.log(cmd("doctor", "Check all dependencies"))
226
+ out.log(cmd("update", "Upgrade pacework to the latest version"))
227
+ out.log(cmd("login", "Authenticate via browser"))
228
+ out.log(cmd("logout", "Revoke API key and clear credentials"))
229
+ out.log(sec("SHELL"))
230
+ out.log(cmd("clear", "Clear screen"))
231
+ out.log(cmd("exit", "Exit the shell"))
232
+ out.log("")
233
+ out.log(div)
234
+ out.log("")
235
+ break
236
+ }
237
+ case "clear": {
238
+ out.write("\x1b[2J\x1b[0f")
239
+ printBanner(readConfig())
240
+ await printWelcome()
241
+ break
242
+ }
243
+ case "exit":
244
+ case "quit": {
245
+ out.log("Bye.")
246
+ process.exit(0)
247
+ }
248
+ case "status": {
249
+ const config = readConfig()
250
+ const pid = readPid()
251
+ const running = pid && isRunning(pid)
252
+ out.log("")
253
+ if (running) {
254
+ let startedAt = ""
255
+ try { const c = JSON.parse(fs.readFileSync(CMD_FILE, "utf8")); startedAt = ` started ${relTime(c.startedAt)}` } catch {}
256
+ out.log(` \x1b[32m●\x1b[0m Running (PID ${pid}${startedAt})`)
257
+ } else {
258
+ out.log(` \x1b[2m○\x1b[0m Stopped`)
259
+ }
260
+ if (config.workspaceSlug) out.log(` workspace ${config.workspaceSlug}`)
261
+ if (config.executor) out.log(` executor ${executorLabel(config.executor)}`)
262
+ if (config.runnerName) out.log(` name ${config.runnerName}`)
263
+ if (config.repoRoot) out.log(` repo ${config.repoRoot}`)
264
+ out.log("")
265
+ break
266
+ }
267
+ case "use": {
268
+ const target = args[0]
269
+ const valid = EXECUTORS.map(e => e.id)
270
+ if (!target || !valid.includes(target)) {
271
+ out.log(`Usage: use <executor>\nAvailable: ${valid.join(", ")}`)
272
+ break
273
+ }
274
+ const config = readConfig()
275
+ const prev = config.executor ?? "codex"
276
+ if (!checkBinaryExists(EXECUTORS.find(e => e.id === target).bin)) {
277
+ out.log(`\x1b[33m⚠ ${target} binary not found in PATH — switching anyway\x1b[0m`)
278
+ }
279
+ config.executor = target
280
+ if (config.runnerName === EXECUTOR_DEFAULT_NAMES[prev]) config.runnerName = EXECUTOR_DEFAULT_NAMES[target] ?? config.runnerName
281
+ writeConfig(config)
282
+ out.log(`\x1b[32m✓\x1b[0m Switched to \x1b[1m${executorLabel(target)}\x1b[0m — restart runner to apply`)
283
+ break
284
+ }
285
+ case "config": {
286
+ const KEY_ALIASES = { "executor": "executor", "name": "runnerName", "runner-name": "runnerName", "repo-root": "repoRoot", "app-url": "appUrl", "workspace-id": "workspaceId" }
287
+ const config = readConfig()
288
+ const key = args[0]
289
+ const value = args[1]
290
+ if (!key) {
291
+ out.log("")
292
+ const rows = [
293
+ ["workspace", config.workspaceSlug ?? config.workspaceId ?? "\x1b[2mnot set\x1b[0m"],
294
+ ["executor", config.executor ? `${executorLabel(config.executor)} (${config.executor})` : "\x1b[2mnot set\x1b[0m"],
295
+ ["name", config.runnerName ?? "\x1b[2mnot set\x1b[0m"],
296
+ ["repo-root", config.repoRoot ?? "\x1b[2mnot set\x1b[0m"],
297
+ ["app-url", config.appUrl ?? "https://pacework.io"],
298
+ ["api-key", config.apiKey ? `\x1b[2m${config.apiKey.slice(0, 16)}…\x1b[0m` : "\x1b[2mnot set\x1b[0m"],
299
+ ]
300
+ rows.forEach(([k, v]) => out.log(` ${k.padEnd(12)} ${v}`))
301
+ out.log("")
302
+ } else {
303
+ const configKey = KEY_ALIASES[key]
304
+ if (!configKey) { out.log(`Unknown key: ${key}. Valid: ${Object.keys(KEY_ALIASES).join(", ")}`); break }
305
+ if (!value) { out.log(`${key}: ${config[configKey] ?? "\x1b[2mnot set\x1b[0m"}`); break }
306
+ config[configKey] = value
307
+ writeConfig(config)
308
+ out.log(`\x1b[32m✓\x1b[0m ${key} = \x1b[1m${value}\x1b[0m`)
309
+ }
310
+ break
311
+ }
312
+ case "jobs": {
313
+ const limit = parseInt(args[0], 10) || 20
314
+ const config = readConfig()
315
+ out.log("")
316
+
317
+ // ── active runs from API ──────────────────────────────────────
318
+ const apiRuns = await fetchActiveRuns(config)
319
+ const activeIds = new Set()
320
+ if (apiRuns?.length) {
321
+ printJobsTable(apiRuns)
322
+ for (const r of apiRuns) if (r.id) activeIds.add(r.id)
323
+ } else {
324
+ out.log(` \x1b[2mNo active runs.\x1b[0m\n`)
325
+ }
326
+
327
+ // ── recent history from log ───────────────────────────────────
328
+ try {
329
+ const raw = fs.readFileSync(LOG_FILE, "utf8")
330
+ const events = []
331
+ for (const line of raw.split("\n")) {
332
+ if (!line.trim()) continue
333
+ try {
334
+ const e = JSON.parse(line)
335
+ if (["runner.job.start","runner.job.complete","runner.job.error"].includes(e.event)) events.push(e)
336
+ } catch {}
337
+ }
338
+ const byRun = new Map()
339
+ for (const j of events) {
340
+ const id = j.run_id ?? j.meta?.run_id ?? "unknown"
341
+ 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 })
342
+ const entry = byRun.get(id)
343
+ if (j.event === "runner.job.start") { entry.started_at = j.ts; entry.status = "running" }
344
+ if (j.event === "runner.job.complete") { entry.completed_at = j.ts; entry.status = "completed" }
345
+ if (j.event === "runner.job.error") { entry.completed_at = j.ts; entry.status = "error"; entry.error = j.msg }
346
+ }
347
+ const history = Array.from(byRun.values())
348
+ .filter(r => !activeIds.has(r.id))
349
+ .slice(-limit).reverse()
350
+ if (history.length) {
351
+ out.log(`\x1b[1mHistory\x1b[0m \x1b[2m(last ${history.length})\x1b[0m`)
352
+ printJobsTable(history)
353
+ }
354
+ } catch {}
355
+ break
356
+ }
357
+ case "logs": {
358
+ const n = parseInt(args[0], 10) || 20
359
+ try {
360
+ const content = fs.readFileSync(LOG_FILE, "utf8")
361
+ const tail = content.split("\n").filter(Boolean).slice(-n)
362
+ out.log("")
363
+ const formatted = tail.map(formatLogLine).filter(Boolean)
364
+ out.log(formatted.length ? formatted.join("\n") : tail.join("\n"))
365
+ out.log("")
366
+ } catch { out.log("No log file found.") }
367
+ break
368
+ }
369
+ case "start": {
370
+ const pid = readPid()
371
+ if (pid && isRunning(pid)) { out.log(`Runner already running (PID ${pid})`); break }
372
+ out.log("Starting runner in background…")
373
+ // Spawn this ctl with start args so it picks up config
374
+ const child = spawn(process.execPath, [ctlScript, "start"], {
375
+ stdio: "inherit",
376
+ env: { ...process.env, PATH: process.env.PATH || "" },
377
+ })
378
+ await new Promise(r => child.on("exit", r))
379
+ break
380
+ }
381
+ case "stop": {
382
+ const pid = readPid()
383
+ if (!pid || !isRunning(pid)) {
384
+ // Still sweep: a previous stop can leave an orphan whose parent
385
+ // died after the sweep ran, and the pid file no longer names it.
386
+ let orphaned = 0
387
+ for (let attempt = 0; attempt < 5; attempt++) {
388
+ const strays = findStrayRunnerPids(pid ?? 0)
389
+ if (strays.length === 0) break
390
+ for (const stray of strays) {
391
+ try { process.kill(stray, "SIGKILL"); orphaned += 1 } catch {}
392
+ }
393
+ await new Promise(r => setTimeout(r, 400))
394
+ }
395
+ clearPid()
396
+ out.log(orphaned > 0
397
+ ? `\x1b[32m✓\x1b[0m Cleaned up ${orphaned} orphaned runner process(es).`
398
+ : "Runner is not running.")
399
+ break
400
+ }
401
+ try {
402
+ process.kill(pid, "SIGTERM")
403
+
404
+ // SIGTERM was previously fire-and-forget: it reported success
405
+ // immediately, so a runner that ignored it kept running and
406
+ // competed with the next one for jobs. Wait, then escalate.
407
+ const deadline = Date.now() + 5000
408
+ while (isRunning(pid) && Date.now() < deadline) {
409
+ await new Promise(r => setTimeout(r, 200))
410
+ }
411
+ if (isRunning(pid)) {
412
+ process.kill(pid, "SIGKILL")
413
+ await new Promise(r => setTimeout(r, 500))
414
+ }
415
+
416
+ // The watchdog spawns the runner as a separate process, so
417
+ // killing the watchdog alone can leave the runner orphaned. The
418
+ // child can also outlive the first sweep, so this repeats until
419
+ // nothing is left.
420
+ let killed = 0
421
+ for (let attempt = 0; attempt < 5; attempt++) {
422
+ const strays = findStrayRunnerPids(pid)
423
+ if (strays.length === 0) break
424
+ for (const stray of strays) {
425
+ try { process.kill(stray, "SIGKILL"); killed += 1 } catch {}
426
+ }
427
+ await new Promise(r => setTimeout(r, 400))
428
+ }
429
+
430
+ clearPid()
431
+ const extra = killed > 0 ? ` (+${killed} orphaned)` : ""
432
+ out.log(`\x1b[32m✓\x1b[0m Stopped (PID ${pid})${extra}`)
433
+ }
434
+ catch (e) { out.error(`\x1b[31mFailed: ${e.message}\x1b[0m`) }
435
+ break
436
+ }
437
+ case "doctor": {
438
+ const config = readConfig()
439
+ const ok = (msg) => out.log(` \x1b[32m✓\x1b[0m ${msg}`)
440
+ const err = (msg) => out.error(` \x1b[31m✗\x1b[0m ${msg}`)
441
+ const wrn = (msg) => out.log(` \x1b[33m⚠\x1b[0m ${msg}`)
442
+ out.log(`\n\x1b[1mDiagnostics\x1b[0m\n`)
443
+
444
+ // Node version
445
+ const nodeVer = process.versions.node
446
+ const [nodeMaj] = nodeVer.split(".").map(Number)
447
+ nodeMaj >= 18 ? ok(`Node.js ${nodeVer}`) : err(`Node.js ${nodeVer} — requires ≥18`)
448
+
449
+ // Auth
450
+ const key = config.apiKey ?? config.workspaceApiKey
451
+ key ? ok(`API key set \x1b[2m(${key.slice(0,16)}…)\x1b[0m`) : err(`No API key — run /login`)
452
+ config.workspaceSlug ? ok(`Workspace: ${config.workspaceSlug}`) : err(`No workspace — run /login`)
453
+
454
+ // App URL reachability
455
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
456
+ try {
457
+ const t0 = Date.now()
458
+ const r = await fetch(`${appUrl}/api/health`, { signal: AbortSignal.timeout(3000) })
459
+ const ms = Date.now() - t0
460
+ r.ok ? ok(`App reachable: ${appUrl} \x1b[2m(${ms}ms)\x1b[0m`) : wrn(`App returned ${r.status}: ${appUrl}`)
461
+ } catch { err(`Cannot reach app: ${appUrl}`) }
462
+
463
+ // Executor binary
464
+ const exe = EXECUTORS.find(e => e.id === (config.executor ?? "codex"))
465
+ if (exe) {
466
+ checkBinaryExists(exe.bin)
467
+ ? ok(`Executor: ${exe.label} \x1b[2m(${exe.bin})\x1b[0m`)
468
+ : err(`Executor binary not found: ${exe.bin} — install ${exe.label} or run /use to switch`)
469
+ }
470
+
471
+ // Repo root
472
+ if (config.repoRoot) {
473
+ try {
474
+ fs.accessSync(config.repoRoot)
475
+ ok(`Repo root: ${config.repoRoot}`)
476
+ } catch { err(`Repo root not found: ${config.repoRoot} — run /config repo-root <path>`) }
477
+ } else {
478
+ wrn(`Repo root not set — run /config repo-root <path>`)
479
+ }
480
+
481
+ // Runner daemon
482
+ const dpid = readPid()
483
+ dpid && isRunning(dpid)
484
+ ? ok(`Runner daemon running \x1b[2m(PID ${dpid})\x1b[0m`)
485
+ : wrn(`Runner daemon not running — run /start`)
486
+
487
+ // pacework version
488
+ ok(`pacework-runner v${LOCAL_VERSION ?? "unknown"}`)
489
+
490
+ out.log("")
491
+ break
492
+ }
493
+ case "restart": {
494
+ const pid = readPid()
495
+ if (pid && isRunning(pid)) {
496
+ try { process.kill(pid, "SIGTERM"); clearPid(); out.log(`\x1b[32m✓\x1b[0m Stopped (PID ${pid})`) }
497
+ catch (e) { out.error(`\x1b[31mStop failed: ${e.message}\x1b[0m`); break }
498
+ await new Promise(r => setTimeout(r, 800))
499
+ }
500
+ out.log("Starting runner in background…")
501
+ const rchild = spawn(process.execPath, [ctlScript, "start"], {
502
+ stdio: "inherit",
503
+ env: { ...process.env, PATH: process.env.PATH || "" },
504
+ })
505
+ await new Promise(r => rchild.on("exit", r))
506
+ break
507
+ }
508
+ case "tail": {
509
+ out.log(`\x1b[2mStreaming log — press Ctrl+C to stop\x1b[0m\n`)
510
+ try {
511
+ const tail = spawn("tail", ["-f", "-n", "40", LOG_FILE], { stdio: ["ignore", "pipe", "ignore"] })
512
+ tail.stdout.on("data", chunk => {
513
+ const lines = chunk.toString().split("\n")
514
+ for (const l of lines) {
515
+ const fmt = formatLogLine(l)
516
+ if (fmt) out.write(fmt + "\n")
517
+ }
518
+ })
519
+ await new Promise(resolve => {
520
+ process.once("SIGINT", () => { tail.kill(); resolve() })
521
+ tail.on("exit", resolve)
522
+ })
523
+ out.log("")
524
+ } catch { out.log("No log file yet.") }
525
+ break
526
+ }
527
+ case "watch": {
528
+ const config = readConfig()
529
+ let watching = true
530
+ let watchLines = 0
531
+ const stopWatch = () => { watching = false }
532
+ process.once("SIGINT", stopWatch)
533
+ const watchRunIds = new Set()
534
+
535
+ const renderWatch = async () => {
536
+ const runs = await fetchActiveRuns(config)
537
+ // bell notification when a previously-seen run is no longer active
538
+ const currentIds = new Set((runs ?? []).map(r => r.id).filter(Boolean))
539
+ for (const prevId of watchRunIds) {
540
+ if (!currentIds.has(prevId)) out.write("\x07")
541
+ }
542
+ watchRunIds.clear()
543
+ for (const r of (runs ?? [])) if (r.id && r.status === "running") watchRunIds.add(r.id)
544
+ const pid2 = readPid()
545
+ const running2 = pid2 && isRunning(pid2)
546
+ const dot = running2 ? `\x1b[32m● Running\x1b[0m` : `\x1b[2m○ Stopped\x1b[0m`
547
+
548
+ // build output lines in a buffer so we can measure
549
+ const lines = []
550
+ lines.push(` ${dot} \x1b[2m${new Date().toLocaleTimeString()} — Ctrl+C to stop\x1b[0m`)
551
+ lines.push("")
552
+ if (runs?.length) {
553
+ const COL_STATUS = 10, COL_TITLE = 34, COL_AGE = 10, COL_DUR = 8
554
+ const hr = ` ${"─".repeat(COL_STATUS + COL_TITLE + COL_AGE + COL_DUR + 6)}`
555
+ const STATUS_COLORS = { running:"\x1b[34m", queued:"\x1b[33m", pending:"\x1b[33m", completed:"\x1b[32m", failed:"\x1b[31m", error:"\x1b[31m", cancelled:"\x1b[2m" }
556
+ const STATUS_GLYPH = { running:"▶", queued:"◌", pending:"◌", completed:"✓", failed:"✗", error:"✗", cancelled:"–" }
557
+ lines.push(`\x1b[1mActive runs\x1b[0m`)
558
+ lines.push(hr)
559
+ lines.push(` \x1b[2m${"STATUS".padEnd(COL_STATUS)} ${"TASK".padEnd(COL_TITLE)} ${"AGE".padEnd(COL_AGE)} ${"DURATION".padEnd(COL_DUR)}\x1b[0m`)
560
+ lines.push(hr)
561
+ for (const r of runs) {
562
+ const status = (r.status ?? "unknown").toLowerCase()
563
+ const label = `${STATUS_GLYPH[status] ?? "·"} ${status}`.padEnd(COL_STATUS)
564
+ const title = (r.task_title ?? r.task_identifier ?? r.id?.slice(0,8) ?? "—").slice(0,COL_TITLE).padEnd(COL_TITLE)
565
+ const age = relTime(r.started_at ?? r.created_at).padEnd(COL_AGE)
566
+ 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)
567
+ lines.push(` ${STATUS_COLORS[status]??""}}${label}\x1b[0m \x1b[1m${title}\x1b[0m \x1b[2m${age} ${dur}\x1b[0m`)
568
+ }
569
+ lines.push(hr)
570
+ } else {
571
+ lines.push(` \x1b[2mNo active runs.\x1b[0m`)
572
+ }
573
+
574
+ // erase previous render in-place
575
+ if (watchLines > 0) {
576
+ out.write(`\x1b[${watchLines}A\x1b[J`)
577
+ }
578
+ out.write(lines.join("\n") + "\n")
579
+ watchLines = lines.length
580
+ }
581
+
582
+ await renderWatch()
583
+ while (watching) {
584
+ await new Promise(r => setTimeout(r, 3000))
585
+ if (!watching) break
586
+ await renderWatch()
587
+ }
588
+ process.removeListener("SIGINT", stopWatch)
589
+ out.log("\x1b[2mStopped watch.\x1b[0m\n")
590
+ break
591
+ }
592
+ case "stats": {
593
+ out.log("")
594
+ try {
595
+ const raw = fs.readFileSync(LOG_FILE, "utf8")
596
+ const events = []
597
+ for (const line of raw.split("\n")) {
598
+ if (!line.trim()) continue
599
+ try { const e = JSON.parse(line); if (e.event && e.ts) events.push(e) } catch {}
600
+ }
601
+ const starts = events.filter(e => e.event === "runner.job.start")
602
+ const completes = events.filter(e => e.event === "runner.job.complete")
603
+ const errors = events.filter(e => e.event === "runner.job.error")
604
+ const todayStart = new Date(); todayStart.setHours(0,0,0,0)
605
+ const todayStarts = starts.filter(e => new Date(e.ts) >= todayStart)
606
+
607
+ const durations = []
608
+ for (const c of completes) {
609
+ const id = c.run_id ?? c.meta?.run_id
610
+ const s = starts.find(e => (e.run_id ?? e.meta?.run_id) === id)
611
+ if (s) durations.push(new Date(c.ts) - new Date(s.ts))
612
+ }
613
+ const avgDur = durations.length ? durations.reduce((a,b) => a+b, 0) / durations.length : 0
614
+ const total = starts.length
615
+ const success = completes.length
616
+ const failed = errors.length
617
+ const rate = total ? Math.round((success / total) * 100) : 0
618
+
619
+ const config = readConfig()
620
+ const apiRuns = await fetchActiveRuns(config)
621
+ const activeCount = apiRuns?.filter(r => r.status === "running").length ?? 0
622
+ const queuedCount = apiRuns?.filter(r => ["queued","pending"].includes(r.status)).length ?? 0
623
+
624
+ out.log(` \x1b[1mRunner stats\x1b[0m\n`)
625
+ out.log(` ${"Today's runs".padEnd(20)} \x1b[1m${todayStarts.length}\x1b[0m`)
626
+ out.log(` ${"Total runs".padEnd(20)} \x1b[1m${total}\x1b[0m`)
627
+ out.log(` ${"Completed".padEnd(20)} \x1b[32m${success}\x1b[0m`)
628
+ out.log(` ${"Failed".padEnd(20)} ${failed > 0 ? `\x1b[31m${failed}\x1b[0m` : `\x1b[2m${failed}\x1b[0m`}`)
629
+ out.log(` ${"Success rate".padEnd(20)} \x1b[1m${rate}%\x1b[0m`)
630
+ out.log(` ${"Avg duration".padEnd(20)} \x1b[2m${avgDur ? fmtDuration(avgDur) : "—"}\x1b[0m`)
631
+ out.log(` ${"Active now".padEnd(20)} ${activeCount > 0 ? `\x1b[34m${activeCount}\x1b[0m` : "\x1b[2m0\x1b[0m"}`)
632
+ out.log(` ${"Queued".padEnd(20)} ${queuedCount > 0 ? `\x1b[33m${queuedCount}\x1b[0m` : "\x1b[2m0\x1b[0m"}`)
633
+ out.log("")
634
+ } catch { out.log(" No log data yet. Start the runner and run some jobs first.\n") }
635
+ break
636
+ }
637
+ case "issues": {
638
+ const config = readConfig()
639
+ const key = config.apiKey ?? config.workspaceApiKey
640
+ const wsId = config.workspaceId
641
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
642
+ if (!key || !wsId) { out.error("\n Not logged in — run /login first.\n"); break }
643
+ out.log(`\n\x1b[2mFetching issues…\x1b[0m`)
644
+ try {
645
+ const filter = args[0] ?? "open" // open | all | in_progress
646
+ const res = await fetch(`${appUrl}/api/workspaces/${wsId}/cli/issues?status=${filter}&limit=20`, {
647
+ headers: { "x-workspace-api-key": key },
648
+ signal: AbortSignal.timeout(5000),
649
+ })
650
+ if (!res.ok) { out.error(` \x1b[31mAPI error: ${res.status}\x1b[0m\n`); break }
651
+ const data = await res.json()
652
+ const issues = data.issues ?? data ?? []
653
+ if (!issues.length) { out.log(` \x1b[2mNo ${filter} issues found.\x1b[0m\n`); break }
654
+
655
+ const STATUS_COLOR = { open:"\x1b[32m", in_progress:"\x1b[34m", in_review:"\x1b[33m", done:"\x1b[2m", cancelled:"\x1b[2m" }
656
+ const COL_ID = 10, COL_STATUS = 14, COL_TITLE = 48
657
+ const hr = ` ${"─".repeat(COL_ID + COL_STATUS + COL_TITLE + 4)}`
658
+ out.log(`\n\x1b[1mIssues\x1b[0m \x1b[2m(${filter})\x1b[0m`)
659
+ out.log(hr)
660
+ out.log(` \x1b[2m${"ID".padEnd(COL_ID)} ${"STATUS".padEnd(COL_STATUS)} ${"TITLE".padEnd(COL_TITLE)}\x1b[0m`)
661
+ out.log(hr)
662
+ for (const i of issues) {
663
+ const status = (i.status ?? "open").toLowerCase()
664
+ const col = STATUS_COLOR[status] ?? ""
665
+ const id = (i.identifier ?? i.id?.slice(0,8) ?? "—").padEnd(COL_ID)
666
+ const st = status.padEnd(COL_STATUS)
667
+ const title = (i.title ?? "—").slice(0, COL_TITLE).padEnd(COL_TITLE)
668
+ out.log(` \x1b[2m${id}\x1b[0m ${col}${st}\x1b[0m ${title}`)
669
+ }
670
+ out.log(hr)
671
+ out.log(` \x1b[2mTip: /issues in_progress · /issues all\x1b[0m\n`)
672
+ } catch (e) { out.error(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
673
+ break
674
+ }
675
+ // ── issue detail ──────────────────────────────────────────────────
676
+ case "issue": {
677
+ const config = readConfig()
678
+ const key = config.apiKey ?? config.workspaceApiKey
679
+ const wsId = config.workspaceId
680
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
681
+ if (!key || !wsId) { out.error("\n Not logged in — run /login first.\n"); break }
682
+
683
+ const id = args[0]
684
+ if (!id) { out.log(`\n Usage: /issue <identifier> e.g. /issue PLT-42\n`); break }
685
+
686
+ try {
687
+ const res = await fetch(`${appUrl}/api/workspaces/${wsId}/cli/issue/${encodeURIComponent(id.toUpperCase())}`, {
688
+ headers: { "x-workspace-api-key": key },
689
+ signal: AbortSignal.timeout(5000),
690
+ })
691
+ if (res.status === 404) { out.error(`\n \x1b[31mIssue not found: ${id}\x1b[0m\n`); break }
692
+ if (!res.ok) { out.error(` \x1b[31mAPI error: ${res.status}\x1b[0m\n`); break }
693
+ const { issue, comments } = await res.json()
694
+
695
+ 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" }
696
+ 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" }
697
+ const statusCol = STATUS_COLOR[issue.status] ?? ""
698
+ const cols = Math.min(process.stdout.columns || 80, 80)
699
+ const div = ` \x1b[38;5;237m${"─".repeat(cols - 4)}\x1b[0m`
700
+
701
+ out.log("")
702
+ out.log(div)
703
+ out.log(` \x1b[2m${issue.identifier}\x1b[0m \x1b[1m${issue.title}\x1b[0m`)
704
+ out.log(div)
705
+ const meta = [
706
+ `Status: ${statusCol}${issue.status}\x1b[0m`,
707
+ issue.priority ? `Priority: ${PRIORITY_LABEL[issue.priority] ?? issue.priority}` : null,
708
+ issue.assignee_name ? `Assignee: \x1b[1m${issue.assignee_name}\x1b[0m` : null,
709
+ issue.project_name ? `Project: \x1b[2m${issue.project_name}\x1b[0m` : null,
710
+ ].filter(Boolean).join(" · ")
711
+ out.log(` ${meta}`)
712
+ if (issue.description) {
713
+ out.log("")
714
+ const lines = issue.description.replace(/\r\n/g, "\n").split("\n").slice(0, 12)
715
+ for (const l of lines) out.log(` \x1b[2m${l.slice(0, cols - 4)}\x1b[0m`)
716
+ }
717
+ if (comments?.length) {
718
+ out.log(`\n \x1b[2mComments (${comments.length})\x1b[0m`)
719
+ for (const c of comments) {
720
+ out.log(` \x1b[36m${c.author ?? "agent"}\x1b[0m \x1b[2m${relTime(c.created_at)}\x1b[0m`)
721
+ const body = c.body.replace(/\r\n/g, "\n").split("\n").slice(0, 4)
722
+ for (const l of body) out.log(` \x1b[2m${l.slice(0, cols - 6)}\x1b[0m`)
723
+ }
724
+ }
725
+ out.log(div)
726
+ const ws = config.workspaceSlug ?? config.workspaceId ?? ""
727
+ if (ws) out.log(` \x1b[2m${appUrl}/${ws}/issues/${issue.identifier} · /open ${issue.identifier}\x1b[0m`)
728
+ out.log("")
729
+ } catch (e) { out.error(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
730
+ break
731
+ }
732
+ // ── my issues ─────────────────────────────────────────────────────
733
+ case "mine": {
734
+ const config = readConfig()
735
+ const key = config.apiKey ?? config.workspaceApiKey
736
+ const wsId = config.workspaceId
737
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
738
+ if (!key || !wsId) { out.error("\n Not logged in — run /login first.\n"); break }
739
+
740
+ out.log(`\n\x1b[2mFetching your issues…\x1b[0m`)
741
+ try {
742
+ const res = await fetch(`${appUrl}/api/workspaces/${wsId}/cli/my-issues?limit=30`, {
743
+ headers: { "x-workspace-api-key": key },
744
+ signal: AbortSignal.timeout(5000),
745
+ })
746
+ if (!res.ok) { out.error(` \x1b[31mAPI error: ${res.status}\x1b[0m\n`); break }
747
+ const { issues } = await res.json()
748
+ if (!issues?.length) { out.log(` \x1b[2mNo issues assigned to you.\x1b[0m\n`); break }
749
+
750
+ const STATUS_COLOR = { backlog:"\x1b[2m", todo:"\x1b[37m", in_progress:"\x1b[34m", in_review:"\x1b[33m" }
751
+ const COL_ID = 10, COL_STATUS = 14, COL_TITLE = 46
752
+ const hr = ` ${"─".repeat(COL_ID + COL_STATUS + COL_TITLE + 4)}`
753
+ out.log(`\n\x1b[1mMy issues\x1b[0m \x1b[2m(${issues.length})\x1b[0m`)
754
+ out.log(hr)
755
+ out.log(` \x1b[2m${"ID".padEnd(COL_ID)} ${"STATUS".padEnd(COL_STATUS)} ${"TITLE".padEnd(COL_TITLE)}\x1b[0m`)
756
+ out.log(hr)
757
+ for (const i of issues) {
758
+ const status = (i.status ?? "").toLowerCase()
759
+ const col = STATUS_COLOR[status] ?? ""
760
+ const id = (i.identifier ?? i.id?.slice(0,8) ?? "—").padEnd(COL_ID)
761
+ const st = status.padEnd(COL_STATUS)
762
+ const title = (i.title ?? "—").slice(0, COL_TITLE).padEnd(COL_TITLE)
763
+ out.log(` \x1b[2m${id}\x1b[0m ${col}${st}\x1b[0m ${title}`)
764
+ }
765
+ out.log(hr)
766
+ out.log(` \x1b[2mTip: /issue <id> to view details · /run <id> to dispatch\x1b[0m\n`)
767
+ } catch (e) { out.error(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
768
+ break
769
+ }
770
+ // ── agents list ───────────────────────────────────────────────────
771
+ case "agents": {
772
+ const config = readConfig()
773
+ const key = config.apiKey ?? config.workspaceApiKey
774
+ const wsId = config.workspaceId
775
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
776
+ if (!key || !wsId) { out.error("\n Not logged in — run /login first.\n"); break }
777
+
778
+ out.log(`\n\x1b[2mFetching agents…\x1b[0m`)
779
+ try {
780
+ const res = await fetch(`${appUrl}/api/workspaces/${wsId}/cli/agents`, {
781
+ headers: { "x-workspace-api-key": key },
782
+ signal: AbortSignal.timeout(5000),
783
+ })
784
+ if (!res.ok) { out.error(` \x1b[31mAPI error: ${res.status}\x1b[0m\n`); break }
785
+ const { agents } = await res.json()
786
+ if (!agents?.length) { out.log(` \x1b[2mNo agents configured.\x1b[0m\n`); break }
787
+
788
+ const SKILL_COLOR = { reviewer:"\x1b[33m", implementer:"\x1b[34m", planner:"\x1b[35m" }
789
+ const COL_NAME = 22, COL_SKILL = 16, COL_EXE = 14
790
+ const hr = ` ${"─".repeat(COL_NAME + COL_SKILL + COL_EXE + 4)}`
791
+ out.log(`\n\x1b[1mAgents\x1b[0m \x1b[2m(${agents.length})\x1b[0m`)
792
+ out.log(hr)
793
+ out.log(` \x1b[2m${"NAME".padEnd(COL_NAME)} ${"SKILL".padEnd(COL_SKILL)} ${"EXECUTOR".padEnd(COL_EXE)}\x1b[0m`)
794
+ out.log(hr)
795
+ for (const a of agents) {
796
+ const skill = (a.skill_profile_label ?? a.skill_profile_slug ?? "—").toLowerCase()
797
+ const skillCol = SKILL_COLOR[a.skill_profile_slug] ?? "\x1b[2m"
798
+ const name = (a.name ?? a.slug ?? a.id.slice(0,8)).slice(0, COL_NAME).padEnd(COL_NAME)
799
+ const skillStr = skill.slice(0, COL_SKILL).padEnd(COL_SKILL)
800
+ const exe = executorLabel(a.local_executor ?? "").slice(0, COL_EXE).padEnd(COL_EXE)
801
+ out.log(` \x1b[1m${name}\x1b[0m ${skillCol}${skillStr}\x1b[0m \x1b[2m${exe}\x1b[0m`)
802
+ }
803
+ out.log(hr)
804
+ out.log(` \x1b[2mTip: /run <issue-id> to dispatch with agent picker\x1b[0m\n`)
805
+ } catch (e) { out.error(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
806
+ break
807
+ }
808
+ // ── orchestration status dashboard ────────────────────────────────
809
+ case "dashboard": {
810
+ const config = readConfig()
811
+ const key = config.apiKey ?? config.workspaceApiKey
812
+ const wsId = config.workspaceId
813
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
814
+ if (!key || !wsId) { out.error("\n Not logged in — run /login first.\n"); break }
815
+
816
+ try {
817
+ const [orchRes, runsRes] = await Promise.all([
818
+ fetch(`${appUrl}/api/workspaces/${wsId}/cli/orchestration`, {
819
+ headers: { "x-workspace-api-key": key },
820
+ signal: AbortSignal.timeout(5000),
821
+ }),
822
+ fetchActiveRuns(config),
823
+ ])
824
+ const orch = orchRes.ok ? await orchRes.json() : null
825
+ const pid = readPid()
826
+ const running = pid && isRunning(pid)
827
+ const dot = running ? `\x1b[32m● Runner running\x1b[0m` : `\x1b[2m○ Runner stopped\x1b[0m`
828
+ const cols = Math.min(process.stdout.columns || 80, 80)
829
+ const div = ` \x1b[38;5;237m${"─".repeat(cols - 4)}\x1b[0m`
830
+
831
+ out.log("")
832
+ out.log(div)
833
+ out.log(` ${dot}`)
834
+ out.log(div)
835
+
836
+ if (orch) {
837
+ const r = orch.runs
838
+ const i = orch.issues
839
+ const stat = (label, val, col = "") => out.log(` ${col}${label.padEnd(22)}\x1b[0m \x1b[1m${val}\x1b[0m`)
840
+ stat("Active runs", r.running, r.running > 0 ? "\x1b[34m" : "\x1b[2m")
841
+ stat("Queued runs", r.queued, r.queued > 0 ? "\x1b[33m" : "\x1b[2m")
842
+ stat("Completed today", r.completed_today, r.completed_today > 0 ? "\x1b[32m" : "\x1b[2m")
843
+ stat("Failed today", r.failed_today, r.failed_today > 0 ? "\x1b[31m" : "\x1b[2m")
844
+ out.log(div)
845
+ stat("In review", i.in_review, i.in_review > 0 ? "\x1b[33m" : "\x1b[2m")
846
+ stat("In progress", i.in_progress, i.in_progress > 0 ? "\x1b[34m" : "\x1b[2m")
847
+ stat("Todo", i.todo, "\x1b[2m")
848
+ }
849
+
850
+ if (runsRes?.length) {
851
+ out.log(div)
852
+ out.log(` \x1b[1mActive\x1b[0m`)
853
+ for (const r of runsRes.slice(0, 5)) {
854
+ const status = (r.status ?? "").toLowerCase()
855
+ const age = relTime(r.started_at ?? r.created_at)
856
+ out.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`)
857
+ }
858
+ }
859
+ out.log(div)
860
+ out.log(` \x1b[2mTip: /watch to auto-refresh · /logtail <run-id> to stream a run\x1b[0m`)
861
+ out.log("")
862
+ } catch (e) { out.error(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
863
+ break
864
+ }
865
+ // ── stream run log ────────────────────────────────────────────────
866
+ case "logtail": {
867
+ const config = readConfig()
868
+ const key = config.apiKey ?? config.workspaceApiKey
869
+ const wsId = config.workspaceId
870
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
871
+ if (!key || !wsId) { out.error("\n Not logged in — run /login first.\n"); break }
872
+
873
+ const runId = args[0]
874
+ if (!runId) { out.log(`\n Usage: /logtail <run-id> (from /jobs or /watch)\n`); break }
875
+
876
+ out.log(`\n \x1b[2mStreaming log for run ${runId.slice(0,8)}… (Ctrl+C to stop)\x1b[0m\n`)
877
+ let lastLen = 0
878
+ let done = false
879
+ let stopping = false
880
+ const stop = () => { stopping = true }
881
+ process.once("SIGINT", stop)
882
+
883
+ while (!stopping) {
884
+ try {
885
+ const res = await fetch(`${appUrl}/api/workspaces/${wsId}/cli/runs/${runId}/log`, {
886
+ headers: { "x-workspace-api-key": key },
887
+ signal: AbortSignal.timeout(5000),
888
+ })
889
+ if (!res.ok) { out.error(` \x1b[31mAPI error: ${res.status}\x1b[0m\n`); break }
890
+ const data = await res.json()
891
+ const log = data.log_tail ?? ""
892
+ if (log.length > lastLen) {
893
+ const newContent = log.slice(lastLen)
894
+ out.write(newContent)
895
+ if (!newContent.endsWith("\n")) out.write("\n")
896
+ lastLen = log.length
897
+ }
898
+ if (["completed", "error", "cancelled"].includes(data.status)) {
899
+ const col = data.status === "completed" ? "\x1b[32m" : "\x1b[31m"
900
+ out.log(`\n ${col}Run ${data.status}\x1b[0m\n`)
901
+ done = true
902
+ break
903
+ }
904
+ } catch {}
905
+ await new Promise(r => setTimeout(r, 3000))
906
+ }
907
+ process.removeListener("SIGINT", stop)
908
+ if (!done && stopping) out.log("\n \x1b[2mStopped.\x1b[0m\n")
909
+ break
910
+ }
911
+ // ── orchestrator commands ─────────────────────────────────────────
912
+ case "run": {
913
+ // /run <issue-identifier> e.g. /run PLT-42
914
+ const config = readConfig()
915
+ const key = config.apiKey ?? config.workspaceApiKey
916
+ const wsId = config.workspaceId
917
+ const appUrl = (config.appUrl ?? "https://pacework.io ").replace(/\/$/, "")
918
+ if (!key || !wsId) { out.error("\n Not logged in — run /login first.\n"); break }
919
+
920
+ const issueRef = args[0]
921
+ if (!issueRef) { out.log(`\n Usage: /run <issue-identifier> e.g. /run PLT-42\n`); break }
922
+
923
+ out.log(`\n \x1b[2mLooking up issue and agents…\x1b[0m`)
924
+ try {
925
+ // fetch issue + agents in parallel
926
+ const [issuesRes, agentsRes] = await Promise.all([
927
+ fetch(`${appUrl}/api/workspaces/${wsId}/cli/issues?status=all&limit=100`, {
928
+ headers: { "x-workspace-api-key": key },
929
+ signal: AbortSignal.timeout(5000),
930
+ }),
931
+ fetch(`${appUrl}/api/workspaces/${wsId}/cli/agents`, {
932
+ headers: { "x-workspace-api-key": key },
933
+ signal: AbortSignal.timeout(5000),
934
+ }),
935
+ ])
936
+
937
+ if (!issuesRes.ok) { out.error(` \x1b[31mAPI error: ${issuesRes.status}\x1b[0m\n`); break }
938
+ const { issues } = await issuesRes.json()
939
+ const issue = issues?.find(i => i.identifier?.toUpperCase() === issueRef.toUpperCase())
940
+ if (!issue) { out.error(` \x1b[31mIssue not found: ${issueRef}\x1b[0m\n`); break }
941
+
942
+ // agents list (may fail gracefully)
943
+ let agents = []
944
+ if (agentsRes.ok) {
945
+ const agentData = await agentsRes.json().catch(() => ({}))
946
+ agents = Array.isArray(agentData) ? agentData : (agentData.agents ?? agentData.data ?? [])
947
+ }
948
+
949
+ // show issue summary
950
+ out.log(`\n \x1b[1m${issue.identifier}\x1b[0m ${issue.title}`)
951
+ out.log(` \x1b[2mStatus: ${issue.status}${issue.priority ? ` · Priority: ${issue.priority}` : ""}\x1b[0m\n`)
952
+
953
+ // agent picker
954
+ let chosenAgentId = issue.agent_id ?? null
955
+
956
+ if (agents.length > 0) {
957
+ const defaultIdx = agents.findIndex(a => a.id === chosenAgentId)
958
+ out.log(` \x1b[1mPick an agent:\x1b[0m \x1b[2m(Enter to use default)\x1b[0m\n`)
959
+ agents.forEach((a, i) => {
960
+ const isDefault = a.id === chosenAgentId
961
+ const tag = isDefault ? ` \x1b[32m← default\x1b[0m` : ""
962
+ const executor = a.local_executor ? ` \x1b[2m${executorLabel(a.local_executor)}\x1b[0m` : ""
963
+ out.log(` \x1b[36m${i + 1}.\x1b[0m \x1b[1m${a.name ?? a.slug ?? a.id.slice(0,8)}\x1b[0m${executor}${tag}`)
964
+ })
965
+ out.log("")
966
+
967
+ // pause raw mode for a simple line read
968
+ process.stdin.setRawMode(false)
969
+ const answer = await new Promise(resolve => {
970
+ out.write(` \x1b[36mAgent number (default ${defaultIdx >= 0 ? defaultIdx + 1 : "issue default"}):\x1b[0m `)
971
+ let buf = ""
972
+ const onData = (chunk) => {
973
+ const s = chunk.toString()
974
+ if (s === "\n" || s === "\r") {
975
+ process.stdin.removeListener("data", onData)
976
+ out.write("\n")
977
+ resolve(buf.trim())
978
+ } else if (s === "\x7f" && buf.length) {
979
+ buf = buf.slice(0, -1)
980
+ out.write("\b \b")
981
+ } else if (s >= " ") {
982
+ buf += s
983
+ out.write(s)
984
+ }
985
+ }
986
+ process.stdin.on("data", onData)
987
+ })
988
+ process.stdin.setRawMode(true)
989
+
990
+ if (answer !== "") {
991
+ const idx = parseInt(answer, 10) - 1
992
+ if (idx >= 0 && idx < agents.length) {
993
+ chosenAgentId = agents[idx].id
994
+ out.log(` \x1b[2mUsing agent: ${agents[idx].name ?? agents[idx].slug}\x1b[0m`)
995
+ } else {
996
+ out.log(` \x1b[33m⚠\x1b[0m Invalid choice — using issue default`)
997
+ }
998
+ } else {
999
+ const def = agents[defaultIdx]
1000
+ if (def) out.log(` \x1b[2mUsing default agent: ${def.name ?? def.slug}\x1b[0m`)
1001
+ }
1002
+ } else if (chosenAgentId) {
1003
+ out.log(` \x1b[2mNo agents list available — using issue's assigned agent\x1b[0m`)
1004
+ }
1005
+
1006
+ out.log(`\n \x1b[2mDispatching…\x1b[0m`)
1007
+ const dispatchBody = { task_id: issue.id, workspace_id: wsId }
1008
+ if (chosenAgentId) dispatchBody.agent_id = chosenAgentId
1009
+
1010
+ const dispatch = await fetch(`${appUrl}/api/agent-planner/dispatch`, {
1011
+ method: "POST",
1012
+ headers: { "content-type": "application/json", Authorization: `Bearer ${key}` },
1013
+ body: JSON.stringify(dispatchBody),
1014
+ signal: AbortSignal.timeout(8000),
1015
+ })
1016
+ const body = await dispatch.json().catch(() => ({}))
1017
+ if (dispatch.ok) {
1018
+ const statusLabel = body.status === "already_queued" ? "already queued" : body.status === "resumed" ? "resumed" : "dispatched"
1019
+ out.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` : ""}`)
1020
+ } else {
1021
+ out.error(` \x1b[31m✗\x1b[0m Dispatch failed (${dispatch.status}): ${body.message ?? body.error ?? "unknown"}`)
1022
+ }
1023
+ out.log("")
1024
+ } catch (e) { out.error(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
1025
+ break
1026
+ }
1027
+ case "cancel": {
1028
+ const config = readConfig()
1029
+ const key = config.apiKey ?? config.workspaceApiKey
1030
+ const wsId = config.workspaceId
1031
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
1032
+ if (!key || !wsId) { out.error("\n Not logged in — run /login first.\n"); break }
1033
+
1034
+ const runId = args[0]
1035
+ if (!runId) { out.log(`\n Usage: /cancel <run-id> (from /jobs)\n`); break }
1036
+
1037
+ try {
1038
+ out.log(`\n \x1b[2mCancelling run ${runId.slice(0,8)}…\x1b[0m`)
1039
+ const res = await fetch(`${appUrl}/api/workspaces/${wsId}/agent-runs/${runId}/cancel`, {
1040
+ method: "POST",
1041
+ headers: { "content-type": "application/json", "x-workspace-api-key": key },
1042
+ signal: AbortSignal.timeout(5000),
1043
+ })
1044
+ if (res.ok) out.log(` \x1b[32m✓\x1b[0m Run cancelled`)
1045
+ else { const b = await res.json().catch(() => ({})); out.error(` \x1b[31m✗\x1b[0m Failed (${res.status}): ${b.message ?? b.error ?? ""}`) }
1046
+ out.log("")
1047
+ } catch (e) { out.error(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
1048
+ break
1049
+ }
1050
+ case "retry": {
1051
+ const config = readConfig()
1052
+ const key = config.apiKey ?? config.workspaceApiKey
1053
+ const wsId = config.workspaceId
1054
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
1055
+ if (!key || !wsId) { out.error("\n Not logged in — run /login first.\n"); break }
1056
+
1057
+ const runId = args[0]
1058
+ if (!runId) { out.log(`\n Usage: /retry <run-id> (from /jobs)\n`); break }
1059
+
1060
+ try {
1061
+ out.log(`\n \x1b[2mRetrying run ${runId.slice(0,8)}…\x1b[0m`)
1062
+ const res = await fetch(`${appUrl}/api/workspaces/${wsId}/agent-runs/${runId}/retry`, {
1063
+ method: "POST",
1064
+ headers: { "content-type": "application/json", "x-workspace-api-key": key },
1065
+ signal: AbortSignal.timeout(5000),
1066
+ })
1067
+ if (res.ok) {
1068
+ const b = await res.json().catch(() => ({}))
1069
+ out.log(` \x1b[32m✓\x1b[0m Run retried${b.run_id ? ` \x1b[2mnew run ${b.run_id.slice(0,8)}\x1b[0m` : ""}`)
1070
+ } else {
1071
+ const b = await res.json().catch(() => ({}))
1072
+ out.error(` \x1b[31m✗\x1b[0m Failed (${res.status}): ${b.message ?? b.error ?? ""}`)
1073
+ }
1074
+ out.log("")
1075
+ } catch (e) { out.error(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
1076
+ break
1077
+ }
1078
+ case "pause":
1079
+ case "resume":
1080
+ case "capacity": {
1081
+ const config = readConfig()
1082
+ const result = await runRunnerControlCommand(config, readRunnerId(config), cmd, args)
1083
+ const symbol = result.ok ? "\x1b[32m✓" : "\x1b[31m✗"
1084
+ out.log(` ${symbol}\x1b[0m ${result.message}\n`)
1085
+ return { ok: result.ok }
1086
+ }
1087
+ case "mcp": {
1088
+ const config = readConfig()
1089
+ const key = config.apiKey ?? config.workspaceApiKey
1090
+ const wsId = config.workspaceId
1091
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
1092
+ const executor = config.executor ?? "claude_code"
1093
+ const repoRoot = config.repoRoot ?? process.cwd()
1094
+ const sub = args[0] ?? ""
1095
+
1096
+ if (!sub || sub === "help") {
1097
+ out.log(`\n \x1b[1m/mcp\x1b[0m — manage MCP server connections\n`)
1098
+ out.log(` \x1b[36m/mcp install\x1b[0m \x1b[2m— inject pacework MCP into your executor's config\x1b[0m`)
1099
+ out.log(` \x1b[36m/mcp status \x1b[0m \x1b[2m— show configured MCP servers\x1b[0m`)
1100
+ out.log(` \x1b[36m/mcp test \x1b[0m \x1b[2m— ping each MCP server\x1b[0m\n`)
1101
+ break
1102
+ }
1103
+
1104
+ if (!key || !wsId) { out.error("\n Not logged in — run /login first.\n"); break }
1105
+
1106
+ if (sub === "install") {
1107
+ out.log(`\n \x1b[2mConfiguring MCP for ${executorLabel(executor)}…\x1b[0m`)
1108
+ const mcpUrl = `${appUrl}/api/mcp`
1109
+
1110
+ // Prefer the runner's dedicated MCP key from the state file — it's
1111
+ // scoped specifically for MCP access. Fall back to workspace API key.
1112
+ let mcpKey = key
1113
+ try {
1114
+ const stateFile = path.join(repoRoot, ".agent", "runners", `${wsId}-${executor}.json`)
1115
+ const runnerState = JSON.parse(fs.readFileSync(stateFile, "utf8"))
1116
+ if (runnerState.runner_mcp_key) {
1117
+ mcpKey = runnerState.runner_mcp_key
1118
+ out.log(` \x1b[2mUsing runner MCP key from state file\x1b[0m`)
1119
+ }
1120
+ } catch {
1121
+ out.log(` \x1b[2mRunner not started yet — using workspace API key as MCP token\x1b[0m`)
1122
+ }
1123
+ const authHeader = `Bearer ${mcpKey}`
1124
+
1125
+ if (executor === "claude_code") {
1126
+ const claudeDir = path.join(repoRoot, ".agent", "claude-home")
1127
+ fs.mkdirSync(claudeDir, { recursive: true })
1128
+ const claudeJson = path.join(claudeDir, ".claude.json")
1129
+ let existing = {}
1130
+ try { existing = JSON.parse(fs.readFileSync(claudeJson, "utf8")) } catch {}
1131
+ existing.mcpServers = { ...existing.mcpServers, kentral_local: { type: "http", url: mcpUrl, headers: { Authorization: authHeader } } }
1132
+ fs.writeFileSync(claudeJson, JSON.stringify(existing, null, 2))
1133
+ out.log(` \x1b[32m✓\x1b[0m Claude Code MCP written to \x1b[2m${claudeJson}\x1b[0m`)
1134
+ } else if (executor === "gemini") {
1135
+ const geminiDir = path.join(os.homedir(), ".gemini")
1136
+ fs.mkdirSync(geminiDir, { recursive: true })
1137
+ const settingsPath = path.join(geminiDir, "settings.json")
1138
+ let existing = {}
1139
+ try { existing = JSON.parse(fs.readFileSync(settingsPath, "utf8")) } catch {}
1140
+ existing.mcpServers = { ...existing.mcpServers, kentral_local: { httpUrl: mcpUrl, headers: { Authorization: authHeader } } }
1141
+ fs.writeFileSync(settingsPath, JSON.stringify(existing, null, 2))
1142
+ out.log(` \x1b[32m✓\x1b[0m Gemini MCP written to \x1b[2m${settingsPath}\x1b[0m`)
1143
+ } else if (executor === "cursor_agent") {
1144
+ const cursorDir = path.join(os.homedir(), ".cursor")
1145
+ fs.mkdirSync(cursorDir, { recursive: true })
1146
+ const mcpPath = path.join(cursorDir, "mcp.json")
1147
+ let existing = {}
1148
+ try { existing = JSON.parse(fs.readFileSync(mcpPath, "utf8")) } catch {}
1149
+ existing.mcpServers = { ...existing.mcpServers, kentral_local: { url: mcpUrl, headers: { Authorization: authHeader } } }
1150
+ fs.writeFileSync(mcpPath, JSON.stringify(existing, null, 2))
1151
+ out.log(` \x1b[32m✓\x1b[0m Cursor MCP written to \x1b[2m${mcpPath}\x1b[0m`)
1152
+ } else if (executor === "codex") {
1153
+ const codexHome = process.env.CODEX_HOME ?? path.join(os.homedir(), ".codex")
1154
+ const configPath = path.join(codexHome, "config.toml")
1155
+ let toml = ""
1156
+ try { toml = fs.readFileSync(configPath, "utf8") } catch {}
1157
+ if (!toml.includes("[mcp_servers.kentral_local]")) {
1158
+ toml += `\n[mcp_servers.kentral_local]\nenabled = true\nurl = "${mcpUrl}"\n\n[mcp_servers.kentral_local.http_headers]\nAuthorization = "${authHeader}"\n`
1159
+ fs.mkdirSync(codexHome, { recursive: true })
1160
+ fs.writeFileSync(configPath, toml)
1161
+ out.log(` \x1b[32m✓\x1b[0m Codex MCP written to \x1b[2m${configPath}\x1b[0m`)
1162
+ } else {
1163
+ out.log(` \x1b[33m⚠\x1b[0m kentral_local already in \x1b[2m${configPath}\x1b[0m — update manually if needed`)
1164
+ }
1165
+ } else {
1166
+ out.log(` \x1b[33m⚠\x1b[0m MCP install not yet implemented for executor: ${executor}`)
1167
+ }
1168
+ out.log(` \x1b[2mMCP endpoint: ${mcpUrl}\x1b[0m`)
1169
+ out.log(` \x1b[2mRestart your executor to pick up the new config.\x1b[0m\n`)
1170
+
1171
+ } else if (sub === "status") {
1172
+ out.log(`\n \x1b[1mMCP servers\x1b[0m \x1b[2m(executor: ${executorLabel(executor)})\x1b[0m\n`)
1173
+ const servers = await fetchMcpServerList(config)
1174
+ if (!servers?.length) {
1175
+ out.log(` \x1b[2mNo MCP servers configured in workspace.\x1b[0m`)
1176
+ out.log(` The pacework MCP server is always available at:\x1b[0m`)
1177
+ out.log(` \x1b[2m${appUrl}/api/mcp\x1b[0m\n`)
1178
+ } else {
1179
+ for (const s of servers) {
1180
+ out.log(` \x1b[36m${s.name ?? s.id}\x1b[0m \x1b[2m${s.url ?? s.transport ?? "stdio"}\x1b[0m`)
1181
+ }
1182
+ out.log("")
1183
+ }
1184
+
1185
+ } else if (sub === "test") {
1186
+ out.log(`\n \x1b[2mPinging MCP servers…\x1b[0m\n`)
1187
+ const servers = await fetchMcpServerList(config)
1188
+ // always include kentral_local
1189
+ const allServers = [
1190
+ { name: "kentral_local", url: `${appUrl}/api/mcp` },
1191
+ ...(servers ?? []).filter(s => s.url),
1192
+ ]
1193
+ for (const s of allServers) {
1194
+ const t0 = Date.now()
1195
+ try {
1196
+ const r = await fetch(s.url, { method: "GET", headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(4000) })
1197
+ const ms = Date.now() - t0
1198
+ const ok2 = r.ok || r.status === 405 // MCP endpoints often don't support GET
1199
+ out.log(` ${ok2 ? "\x1b[32m✓\x1b[0m" : "\x1b[33m⚠\x1b[0m"} \x1b[1m${s.name}\x1b[0m \x1b[2m${ms}ms ${s.url}\x1b[0m`)
1200
+ } catch (e) {
1201
+ out.error(` \x1b[31m✗\x1b[0m \x1b[1m${s.name}\x1b[0m \x1b[31munreachable\x1b[0m \x1b[2m${s.url}\x1b[0m`)
1202
+ }
1203
+ }
1204
+ out.log("")
1205
+ } else {
1206
+ out.log(`\n Unknown subcommand: /mcp ${sub} (use: install | status | test)\n`)
1207
+ }
1208
+ break
1209
+ }
1210
+ case "executor": {
1211
+ const config = readConfig()
1212
+ const key = config.apiKey ?? config.workspaceApiKey
1213
+ const executor = config.executor ?? "claude_code"
1214
+ const sub = args[0] ?? ""
1215
+
1216
+ if (sub === "test") {
1217
+ const exeEntry = EXECUTORS.find(e => e.id === executor)
1218
+ if (!exeEntry) { out.log(`\n Unknown executor: ${executor}\n`); break }
1219
+ if (!checkBinaryExists(exeEntry.bin)) {
1220
+ out.error(`\n \x1b[31m✗\x1b[0m ${exeEntry.label} binary (\x1b[1m${exeEntry.bin}\x1b[0m) not found in PATH\n`)
1221
+ break
1222
+ }
1223
+ out.log(`\n \x1b[2mSmoke-testing ${exeEntry.label}…\x1b[0m`)
1224
+ const t0 = Date.now()
1225
+ try {
1226
+ const versionFlag = executor === "gemini" ? "--version" : "--version"
1227
+ const result = execFileSync(exeEntry.bin, [versionFlag], { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "pipe"] }).trim()
1228
+ const ms = Date.now() - t0
1229
+ out.log(` \x1b[32m✓\x1b[0m ${exeEntry.label} is working \x1b[2m${result.split("\n")[0]} ${ms}ms\x1b[0m`)
1230
+ } catch (e) {
1231
+ out.error(` \x1b[31m✗\x1b[0m ${exeEntry.label} returned error: \x1b[2m${e.message?.split("\n")[0] ?? e.message}\x1b[0m`)
1232
+ }
1233
+ out.log("")
1234
+ } else {
1235
+ out.log(`\n \x1b[1m/executor\x1b[0m — executor tools\n`)
1236
+ out.log(` \x1b[36m/executor test\x1b[0m \x1b[2m— smoke-test the configured executor binary\x1b[0m\n`)
1237
+ }
1238
+ break
1239
+ }
1240
+ case "whoami": {
1241
+ const config = readConfig()
1242
+ out.log("")
1243
+ const key = config.apiKey ?? config.workspaceApiKey
1244
+ out.log(` workspace \x1b[1m${config.workspaceSlug ?? config.workspaceId ?? "\x1b[2mnot set\x1b[0m"}\x1b[0m`)
1245
+ out.log(` runner \x1b[1m${config.runnerName ?? "\x1b[2mnot set\x1b[0m"}\x1b[0m`)
1246
+ out.log(` executor \x1b[1m${executorLabel(config.executor ?? "?")}\x1b[0m`)
1247
+ out.log(` api key \x1b[2m${key ? key.slice(0, 20) + "…" : "not set"}\x1b[0m`)
1248
+ out.log(` app url \x1b[2m${config.appUrl ?? "https://pacework.io"}\x1b[0m`)
1249
+ out.log("")
1250
+ break
1251
+ }
1252
+ case "rename": {
1253
+ const newName = args.join(" ").trim()
1254
+ if (!newName) { out.log(`Usage: rename <new name>`); break }
1255
+ const config = readConfig()
1256
+ config.runnerName = newName
1257
+ writeConfig(config)
1258
+ out.log(`\x1b[32m✓\x1b[0m Runner name set to \x1b[1m${newName}\x1b[0m — restart runner to push to dashboard`)
1259
+ break
1260
+ }
1261
+ case "open": {
1262
+ const config = readConfig()
1263
+ const base = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
1264
+ const slug = config.workspaceSlug ?? config.workspaceId ?? ""
1265
+ const issueId = args[0]
1266
+ const url = issueId
1267
+ ? (slug ? `${base}/${slug}/issue/${issueId.toUpperCase()}` : base)
1268
+ : (slug ? `${base}/${slug}` : base)
1269
+ out.log(`Opening \x1b[36m${url}\x1b[0m`)
1270
+ const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open"
1271
+ try { spawn(opener, [url], { stdio: "ignore", detached: true }).unref() }
1272
+ catch { out.log(`Could not open browser automatically.`) }
1273
+ break
1274
+ }
1275
+ case "update": {
1276
+ await updateRunner()
1277
+ break
1278
+ }
1279
+ case "login": {
1280
+ const config = readConfig()
1281
+ const key = config.apiKey ?? config.workspaceApiKey
1282
+ const ws = config.workspaceSlug ?? config.workspaceId
1283
+
1284
+ if (key && ws) {
1285
+ const user = config.userName ?? config.userEmail ?? "unknown"
1286
+ out.log(`\n \x1b[32m✓\x1b[0m Already logged in as \x1b[1m${user}\x1b[0m on \x1b[1m${ws}\x1b[0m`)
1287
+ out.log(` Switch accounts? This will revoke the current API key.\n`)
1288
+ // raw-mode y/n
1289
+ const answer = await new Promise(resolve => {
1290
+ out.write(` \x1b[36m[y/N]\x1b[0m `)
1291
+ process.stdin.once("data", k => { out.write("\n"); resolve(k.toString().trim().toLowerCase()) })
1292
+ })
1293
+ if (answer !== "y") { out.log(" Keeping current session.\n"); break }
1294
+
1295
+ // revoke existing key then fall through to login
1296
+ try {
1297
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
1298
+ await fetch(`${appUrl}/api/cli/login`, {
1299
+ method: "DELETE",
1300
+ headers: { "content-type": "application/json" },
1301
+ body: JSON.stringify({ apiKey: key }),
1302
+ })
1303
+ } catch {}
1304
+ const fresh = {}
1305
+ // stop daemon before switching accounts
1306
+ const pid2 = readPid()
1307
+ if (pid2 && isRunning(pid2)) { try { process.kill(pid2, "SIGTERM"); clearPid() } catch {} }
1308
+ writeConfig({ appUrl: config.appUrl })
1309
+ out.log(` \x1b[32m✓\x1b[0m Logged out. Starting login flow…\n`)
1310
+ }
1311
+
1312
+ // pause raw mode, run login as child, resume
1313
+ process.stdin.setRawMode(false)
1314
+ process.stdin.pause()
1315
+ const loginChild = spawn(process.execPath, [ctlScript, "login"], {
1316
+ stdio: "inherit",
1317
+ env: { ...process.env, PATH: process.env.PATH || "" },
1318
+ })
1319
+ await new Promise(r => loginChild.on("exit", r))
1320
+ process.stdin.setRawMode(true)
1321
+ process.stdin.resume()
1322
+ // re-render to show new account
1323
+ out.write("\x1b[2J\x1b[H")
1324
+ printBanner(readConfig())
1325
+ await printWelcome()
1326
+ break
1327
+ }
1328
+ case "logout": {
1329
+ const config = readConfig()
1330
+ const key = config.apiKey ?? config.workspaceApiKey
1331
+ if (!key) { out.log("\n Not logged in.\n"); break }
1332
+ out.log(`\n Revoking API key and clearing credentials…`)
1333
+
1334
+ // stop running daemon first
1335
+ const pid = readPid()
1336
+ if (pid && isRunning(pid)) {
1337
+ try { process.kill(pid, "SIGTERM"); clearPid(); out.log(` \x1b[32m✓\x1b[0m Runner stopped`) }
1338
+ catch {}
1339
+ }
1340
+
1341
+ try {
1342
+ const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
1343
+ const res = await fetch(`${appUrl}/api/cli/login`, {
1344
+ method: "DELETE",
1345
+ headers: { "content-type": "application/json" },
1346
+ body: JSON.stringify({ apiKey: key }),
1347
+ })
1348
+ if (res.ok) out.log(` \x1b[32m✓\x1b[0m API key revoked`)
1349
+ else out.log(` \x1b[33m⚠\x1b[0m Server returned ${res.status} — clearing locally anyway`)
1350
+ } catch { out.log(` \x1b[33m⚠\x1b[0m Could not reach server — clearing locally`) }
1351
+
1352
+ // write a clean config — delete auth fields entirely
1353
+ const clean = { appUrl: config.appUrl }
1354
+ writeConfig(clean)
1355
+ out.log(` \x1b[32m✓\x1b[0m Logged out\n`)
1356
+
1357
+ // re-render banner + welcome to reflect logged-out state
1358
+ out.write("\x1b[2J\x1b[H")
1359
+ printBanner(readConfig())
1360
+ await printWelcome()
1361
+ break
1362
+ }
1363
+ case "connect": {
1364
+ const config = readConfig()
1365
+ const key = config.apiKey ?? config.workspaceApiKey
1366
+ if (!key) { out.error("\n Not logged in — run /login first.\n"); break }
1367
+ out.log(`\x1b[2mStarting runner in foreground — Ctrl+C to stop\x1b[0m\n`)
1368
+ process.stdin.setRawMode(false)
1369
+ process.stdin.pause()
1370
+ const runnerArgs = buildRunnerArgs([])
1371
+ const connChild = spawn(process.execPath, [runnerScript, ...runnerArgs], {
1372
+ stdio: ["ignore", "pipe", "pipe"],
1373
+ env: { ...process.env, PATH: process.env.PATH || "" },
1374
+ })
1375
+ const handleStream = (stream) => {
1376
+ let buf = ""
1377
+ stream.on("data", chunk => {
1378
+ buf += chunk.toString()
1379
+ const lines = buf.split("\n"); buf = lines.pop()
1380
+ for (const l of lines) { const f = formatLogLine(l); if (f) out.write(f + "\n") }
1381
+ })
1382
+ }
1383
+ handleStream(connChild.stdout)
1384
+ handleStream(connChild.stderr)
1385
+ const stopConn = () => connChild.kill("SIGTERM")
1386
+ process.once("SIGINT", stopConn)
1387
+ await new Promise(r => connChild.on("exit", r))
1388
+ process.removeListener("SIGINT", stopConn)
1389
+ process.stdin.setRawMode(true)
1390
+ process.stdin.resume()
1391
+ out.log("\x1b[2mRunner stopped.\x1b[0m\n")
1392
+ break
1393
+ }
1394
+ case "pid": {
1395
+ const pid = readPid()
1396
+ if (pid && isRunning(pid)) {
1397
+ let startedAt = ""
1398
+ try { const c = JSON.parse(fs.readFileSync(CMD_FILE, "utf8")); startedAt = ` started ${relTime(c.startedAt)}` } catch {}
1399
+ out.log(`\n \x1b[32m●\x1b[0m Runner PID \x1b[1m${pid}\x1b[0m${startedAt}\n`)
1400
+ } else {
1401
+ out.log(`\n \x1b[2m○ Runner is not running\x1b[0m\n`)
1402
+ }
1403
+ break
1404
+ }
1405
+ case "": break
1406
+ default: {
1407
+ out.error(`\x1b[31mUnknown command: ${cmd}\x1b[0m Type \x1b[36mhelp\x1b[0m for available commands.`)
1408
+ }
1409
+ }
1410
+ }
1411
+
1412
+ return { fetchActiveRuns, printJobsTable, fetchMcpServerList, runShellCommand, run }
1413
+ }