pacework 1.7.14 → 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.
@@ -21,6 +21,7 @@ import { describeTriageJob, runTriageLoop } from "../lib/triage-worker.mjs"
21
21
  import { NPM_PACKAGE, isNewerVersion, latestPublishedVersion } from "../lib/version.mjs"
22
22
  import { EXECUTORS, EXECUTOR_DEFAULT_NAMES, checkBinaryExists, executorLabel } from "../lib/executors.mjs"
23
23
  import { SHELL_COMMANDS, parseShellInput } from "../lib/shell-commands.mjs"
24
+ import { createShellHandlers, runCommandLine } from "../lib/shell-handlers.mjs"
24
25
  import { BANNER_LINES } from "../lib/ui.mjs"
25
26
  import {
26
27
  PACEWORK_DIR,
@@ -56,6 +57,23 @@ import {
56
57
 
57
58
  const __dirname = path.dirname(fileURLToPath(import.meta.url))
58
59
 
60
+ /** What the shared shell handlers need from this script. */
61
+ function shellHandlerContext() {
62
+ return {
63
+ ctlScript: fileURLToPath(import.meta.url),
64
+ runnerScript: path.resolve(__dirname, "pacework-runner.mjs"),
65
+ version: LOCAL_VERSION,
66
+ printBanner,
67
+ updateRunner,
68
+ relTime,
69
+ fmtDuration,
70
+ buildRunnerArgs,
71
+ findStrayRunnerPids,
72
+ formatLogLine,
73
+ readRunnerId,
74
+ }
75
+ }
76
+
59
77
  function readRunnerId(config) {
60
78
  try {
61
79
  const stateFile = path.join(config.repoRoot ?? process.cwd(), ".agent", "runners", `${config.workspaceId}-${config.executor ?? "claude_code"}.json`)
@@ -1332,74 +1350,14 @@ else if (command === "menu") {
1332
1350
  if (!readConfig().apiKey) {
1333
1351
  if (!await runSetup({ startRunner })) process.exit(0)
1334
1352
  }
1335
- await runHome({ ctlScript, version: LOCAL_VERSION })
1353
+ await runHome({ ctlScript, version: LOCAL_VERSION, runCommand: (input) => runCommandLine(input, shellHandlerContext()) })
1336
1354
  }
1337
1355
 
1338
1356
  else if (command === "shell" || command === "sh") {
1339
1357
  const oneShot = process.argv[3] === "--command" ? process.argv[4] ?? "" : null
1340
1358
  if (oneShot === null) printBanner(readConfig())
1341
1359
 
1342
- // ── fetch active runs from API ──────────────────────────────────────────────
1343
- async function fetchActiveRuns(config) {
1344
- const key = config.apiKey ?? config.workspaceApiKey
1345
- const appUrl = config.appUrl ?? "https://pacework.io"
1346
- const wsId = config.workspaceId
1347
- if (!key || !wsId) return null
1348
- try {
1349
- const res = await fetch(`${appUrl}/api/workspaces/${wsId}/agent-runner/runs?limit=8`, {
1350
- headers: { "x-workspace-api-key": key },
1351
- signal: AbortSignal.timeout(3000),
1352
- })
1353
- if (!res.ok) return null
1354
- return await res.json()
1355
- } catch { return null }
1356
- }
1357
-
1358
- function printJobsTable(runs) {
1359
- if (!runs?.length) return
1360
- const STATUS_COLORS = {
1361
- running: "\x1b[34m",
1362
- queued: "\x1b[33m",
1363
- pending: "\x1b[33m",
1364
- completed: "\x1b[32m",
1365
- failed: "\x1b[31m",
1366
- error: "\x1b[31m",
1367
- cancelled: "\x1b[2m",
1368
- }
1369
- const STATUS_GLYPH = {
1370
- running: "▶",
1371
- queued: "◌",
1372
- pending: "◌",
1373
- completed: "✓",
1374
- failed: "✗",
1375
- error: "✗",
1376
- cancelled: "–",
1377
- }
1378
- // column widths
1379
- const COL_STATUS = 10
1380
- const COL_TITLE = 34
1381
- const COL_AGE = 10
1382
- const COL_DUR = 8
1383
- const hr = ` ${"─".repeat(COL_STATUS + COL_TITLE + COL_AGE + COL_DUR + 6)}`
1384
- console.log(`\x1b[1mActive runs\x1b[0m`)
1385
- console.log(hr)
1386
- console.log(` \x1b[2m${"STATUS".padEnd(COL_STATUS)} ${"TASK".padEnd(COL_TITLE)} ${"AGE".padEnd(COL_AGE)} ${"DURATION".padEnd(COL_DUR)}\x1b[0m`)
1387
- console.log(hr)
1388
- for (const r of runs) {
1389
- const status = (r.status ?? "unknown").toLowerCase()
1390
- const col = STATUS_COLORS[status] ?? ""
1391
- const glyph = STATUS_GLYPH[status] ?? "·"
1392
- const label = `${glyph} ${status}`.padEnd(COL_STATUS)
1393
- const title = (r.task_title ?? r.task_identifier ?? r.id?.slice(0, 8) ?? "—").slice(0, COL_TITLE).padEnd(COL_TITLE)
1394
- const age = relTime(r.started_at ?? r.created_at).padEnd(COL_AGE)
1395
- const dur = r.started_at && r.completed_at
1396
- ? fmtDuration(new Date(r.completed_at) - new Date(r.started_at)).padEnd(COL_DUR)
1397
- : r.started_at ? fmtDuration(Date.now() - new Date(r.started_at)).padEnd(COL_DUR) : "".padEnd(COL_DUR)
1398
- console.log(` ${col}${label}\x1b[0m \x1b[1m${title}\x1b[0m \x1b[2m${age} ${dur}\x1b[0m`)
1399
- }
1400
- console.log(hr)
1401
- console.log("")
1402
- }
1360
+ const { fetchActiveRuns, printJobsTable, fetchMcpServerList, runShellCommand, run: runShell } = createShellHandlers(shellHandlerContext())
1403
1361
 
1404
1362
  async function printWelcome() {
1405
1363
  const config = readConfig()
@@ -1453,1269 +1411,14 @@ else if (command === "shell" || command === "sh") {
1453
1411
  return `${runnerStatus} \x1b[2m${ws} · ${exe}\x1b[0m \x1b[36m>\x1b[0m `
1454
1412
  }
1455
1413
 
1456
- // ── orchestrator helpers ──────────────────────────────────────────────────
1457
-
1458
- async function fetchMcpServerList(config) {
1459
- const key = config.apiKey ?? config.workspaceApiKey
1460
- const wsId = config.workspaceId
1461
- const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
1462
- const runnerId = readRunnerId(config)
1463
- if (!key || !wsId || !runnerId) return null
1464
- try {
1465
- const res = await fetch(`${appUrl}/api/agent-runners/mcp-servers?workspace_id=${encodeURIComponent(wsId)}&runner_id=${encodeURIComponent(runnerId)}`, {
1466
- headers: { Authorization: `Bearer ${key}` },
1467
- signal: AbortSignal.timeout(4000),
1468
- })
1469
- if (!res.ok) return null
1470
- const data = await res.json()
1471
- return Array.isArray(data?.mcp_servers) ? data.mcp_servers : null
1472
- } catch { return null }
1473
- }
1474
-
1475
- async function runShellCommand(input) {
1476
- const { command: cmd, args } = parseShellInput(input)
1477
-
1478
- switch (cmd) {
1479
- case "help": {
1480
- const cols = process.stdout.columns || 80
1481
- const W = Math.min(cols - 4, 72)
1482
- const div = ` \x1b[38;5;237m${"─".repeat(W)}\x1b[0m`
1483
- const sec = (label) => `\n \x1b[38;5;240m${label}\x1b[0m`
1484
- const cmd = (c, d) => ` \x1b[36m${c.padEnd(18)}\x1b[0m \x1b[2m${d}\x1b[0m`
1485
- console.log("")
1486
- console.log(div)
1487
- console.log(sec("RUNNER"))
1488
- console.log(cmd("start", "Start runner as background daemon"))
1489
- console.log(cmd("stop", "Stop the background daemon"))
1490
- console.log(cmd("restart", "Stop then start daemon"))
1491
- console.log(cmd("connect", "Run runner in foreground"))
1492
- console.log(cmd("pause", "Pause — no new jobs picked up"))
1493
- console.log(cmd("resume", "Resume a paused runner"))
1494
- console.log(cmd("capacity <n>", "Set max parallel jobs"))
1495
- console.log(sec("JOBS"))
1496
- console.log(cmd("jobs", "Active runs + recent history"))
1497
- console.log(cmd("watch", "Auto-refresh jobs every 3s"))
1498
- console.log(cmd("run <issue-id>", "Dispatch issue to this runner"))
1499
- console.log(cmd("cancel <run-id>","Cancel a running job"))
1500
- console.log(cmd("retry <run-id>", "Retry a failed job"))
1501
- console.log(cmd("stats", "Throughput metrics"))
1502
- console.log(sec("ISSUES & AGENTS"))
1503
- console.log(cmd("issues", "List issues (open / active / all / in_progress …)"))
1504
- console.log(cmd("mine", "Issues assigned to you"))
1505
- console.log(cmd("issue <id>", "View issue detail, description, comments"))
1506
- console.log(cmd("agents", "List agents and their skill profiles"))
1507
- console.log(cmd("dashboard", "Orchestration status — runs, queue, review"))
1508
- console.log(cmd("logtail <run-id>","Stream live log of a running job"))
1509
- console.log(cmd("open [id]", "Open workspace (or specific issue) in browser"))
1510
- console.log(sec("MCP & EXECUTOR"))
1511
- console.log(cmd("mcp install", "Inject pacework MCP into executor config"))
1512
- console.log(cmd("mcp status", "Show configured MCP servers"))
1513
- console.log(cmd("mcp test", "Ping MCP servers"))
1514
- console.log(cmd("executor test", "Smoke-test the executor binary"))
1515
- console.log(sec("LOGS"))
1516
- console.log(cmd("tail", "Live-stream the runner log"))
1517
- console.log(cmd("logs [n]", "Tail last N log lines"))
1518
- console.log(sec("CONFIG & AUTH"))
1519
- console.log(cmd("status", "Runner status and config"))
1520
- console.log(cmd("whoami", "Workspace and key info"))
1521
- console.log(cmd("config", "View or set config values"))
1522
- console.log(cmd("use <executor>", "Switch executor"))
1523
- console.log(cmd("rename <name>", "Set runner display name"))
1524
- console.log(cmd("doctor", "Check all dependencies"))
1525
- console.log(cmd("update", "Upgrade pacework to the latest version"))
1526
- console.log(cmd("login", "Authenticate via browser"))
1527
- console.log(cmd("logout", "Revoke API key and clear credentials"))
1528
- console.log(sec("SHELL"))
1529
- console.log(cmd("clear", "Clear screen"))
1530
- console.log(cmd("exit", "Exit the shell"))
1531
- console.log("")
1532
- console.log(div)
1533
- console.log("")
1534
- break
1535
- }
1536
- case "clear": {
1537
- process.stdout.write("\x1b[2J\x1b[0f")
1538
- printBanner(readConfig())
1539
- await printWelcome()
1540
- break
1541
- }
1542
- case "exit":
1543
- case "quit": {
1544
- console.log("Bye.")
1545
- process.exit(0)
1546
- }
1547
- case "status": {
1548
- const config = readConfig()
1549
- const pid = readPid()
1550
- const running = pid && isRunning(pid)
1551
- console.log("")
1552
- if (running) {
1553
- let startedAt = ""
1554
- try { const c = JSON.parse(fs.readFileSync(CMD_FILE, "utf8")); startedAt = ` started ${relTime(c.startedAt)}` } catch {}
1555
- console.log(` \x1b[32m●\x1b[0m Running (PID ${pid}${startedAt})`)
1556
- } else {
1557
- console.log(` \x1b[2m○\x1b[0m Stopped`)
1558
- }
1559
- if (config.workspaceSlug) console.log(` workspace ${config.workspaceSlug}`)
1560
- if (config.executor) console.log(` executor ${executorLabel(config.executor)}`)
1561
- if (config.runnerName) console.log(` name ${config.runnerName}`)
1562
- if (config.repoRoot) console.log(` repo ${config.repoRoot}`)
1563
- console.log("")
1564
- break
1565
- }
1566
- case "use": {
1567
- const target = args[0]
1568
- const valid = EXECUTORS.map(e => e.id)
1569
- if (!target || !valid.includes(target)) {
1570
- console.log(`Usage: use <executor>\nAvailable: ${valid.join(", ")}`)
1571
- break
1572
- }
1573
- const config = readConfig()
1574
- const prev = config.executor ?? "codex"
1575
- if (!checkBinaryExists(EXECUTORS.find(e => e.id === target).bin)) {
1576
- console.log(`\x1b[33m⚠ ${target} binary not found in PATH — switching anyway\x1b[0m`)
1577
- }
1578
- config.executor = target
1579
- if (config.runnerName === EXECUTOR_DEFAULT_NAMES[prev]) config.runnerName = EXECUTOR_DEFAULT_NAMES[target] ?? config.runnerName
1580
- writeConfig(config)
1581
- console.log(`\x1b[32m✓\x1b[0m Switched to \x1b[1m${executorLabel(target)}\x1b[0m — restart runner to apply`)
1582
- break
1583
- }
1584
- case "config": {
1585
- const KEY_ALIASES = { "executor": "executor", "name": "runnerName", "runner-name": "runnerName", "repo-root": "repoRoot", "app-url": "appUrl", "workspace-id": "workspaceId" }
1586
- const config = readConfig()
1587
- const key = args[0]
1588
- const value = args[1]
1589
- if (!key) {
1590
- console.log("")
1591
- const rows = [
1592
- ["workspace", config.workspaceSlug ?? config.workspaceId ?? "\x1b[2mnot set\x1b[0m"],
1593
- ["executor", config.executor ? `${executorLabel(config.executor)} (${config.executor})` : "\x1b[2mnot set\x1b[0m"],
1594
- ["name", config.runnerName ?? "\x1b[2mnot set\x1b[0m"],
1595
- ["repo-root", config.repoRoot ?? "\x1b[2mnot set\x1b[0m"],
1596
- ["app-url", config.appUrl ?? "https://pacework.io"],
1597
- ["api-key", config.apiKey ? `\x1b[2m${config.apiKey.slice(0, 16)}…\x1b[0m` : "\x1b[2mnot set\x1b[0m"],
1598
- ]
1599
- rows.forEach(([k, v]) => console.log(` ${k.padEnd(12)} ${v}`))
1600
- console.log("")
1601
- } else {
1602
- const configKey = KEY_ALIASES[key]
1603
- if (!configKey) { console.log(`Unknown key: ${key}. Valid: ${Object.keys(KEY_ALIASES).join(", ")}`); break }
1604
- if (!value) { console.log(`${key}: ${config[configKey] ?? "\x1b[2mnot set\x1b[0m"}`); break }
1605
- config[configKey] = value
1606
- writeConfig(config)
1607
- console.log(`\x1b[32m✓\x1b[0m ${key} = \x1b[1m${value}\x1b[0m`)
1608
- }
1609
- break
1610
- }
1611
- case "jobs": {
1612
- const limit = parseInt(args[0], 10) || 20
1613
- const config = readConfig()
1614
- console.log("")
1615
-
1616
- // ── active runs from API ──────────────────────────────────────
1617
- const apiRuns = await fetchActiveRuns(config)
1618
- const activeIds = new Set()
1619
- if (apiRuns?.length) {
1620
- printJobsTable(apiRuns)
1621
- for (const r of apiRuns) if (r.id) activeIds.add(r.id)
1622
- } else {
1623
- console.log(` \x1b[2mNo active runs.\x1b[0m\n`)
1624
- }
1625
-
1626
- // ── recent history from log ───────────────────────────────────
1627
- try {
1628
- const raw = fs.readFileSync(LOG_FILE, "utf8")
1629
- const events = []
1630
- for (const line of raw.split("\n")) {
1631
- if (!line.trim()) continue
1632
- try {
1633
- const e = JSON.parse(line)
1634
- if (["runner.job.start","runner.job.complete","runner.job.error"].includes(e.event)) events.push(e)
1635
- } catch {}
1636
- }
1637
- const byRun = new Map()
1638
- for (const j of events) {
1639
- const id = j.run_id ?? j.meta?.run_id ?? "unknown"
1640
- 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 })
1641
- const entry = byRun.get(id)
1642
- if (j.event === "runner.job.start") { entry.started_at = j.ts; entry.status = "running" }
1643
- if (j.event === "runner.job.complete") { entry.completed_at = j.ts; entry.status = "completed" }
1644
- if (j.event === "runner.job.error") { entry.completed_at = j.ts; entry.status = "error"; entry.error = j.msg }
1645
- }
1646
- const history = Array.from(byRun.values())
1647
- .filter(r => !activeIds.has(r.id))
1648
- .slice(-limit).reverse()
1649
- if (history.length) {
1650
- console.log(`\x1b[1mHistory\x1b[0m \x1b[2m(last ${history.length})\x1b[0m`)
1651
- printJobsTable(history)
1652
- }
1653
- } catch {}
1654
- break
1655
- }
1656
- case "logs": {
1657
- const n = parseInt(args[0], 10) || 20
1658
- try {
1659
- const content = fs.readFileSync(LOG_FILE, "utf8")
1660
- const tail = content.split("\n").filter(Boolean).slice(-n)
1661
- console.log("")
1662
- const formatted = tail.map(formatLogLine).filter(Boolean)
1663
- console.log(formatted.length ? formatted.join("\n") : tail.join("\n"))
1664
- console.log("")
1665
- } catch { console.log("No log file found.") }
1666
- break
1667
- }
1668
- case "start": {
1669
- const pid = readPid()
1670
- if (pid && isRunning(pid)) { console.log(`Runner already running (PID ${pid})`); break }
1671
- console.log("Starting runner in background…")
1672
- // Spawn this ctl with start args so it picks up config
1673
- const child = spawn(process.execPath, [fileURLToPath(import.meta.url), "start"], {
1674
- stdio: "inherit",
1675
- env: { ...process.env, PATH: process.env.PATH || "" },
1676
- })
1677
- await new Promise(r => child.on("exit", r))
1678
- break
1679
- }
1680
- case "stop": {
1681
- const pid = readPid()
1682
- if (!pid || !isRunning(pid)) {
1683
- // Still sweep: a previous stop can leave an orphan whose parent
1684
- // died after the sweep ran, and the pid file no longer names it.
1685
- let orphaned = 0
1686
- for (let attempt = 0; attempt < 5; attempt++) {
1687
- const strays = findStrayRunnerPids(pid ?? 0)
1688
- if (strays.length === 0) break
1689
- for (const stray of strays) {
1690
- try { process.kill(stray, "SIGKILL"); orphaned += 1 } catch {}
1691
- }
1692
- await new Promise(r => setTimeout(r, 400))
1693
- }
1694
- clearPid()
1695
- console.log(orphaned > 0
1696
- ? `\x1b[32m✓\x1b[0m Cleaned up ${orphaned} orphaned runner process(es).`
1697
- : "Runner is not running.")
1698
- break
1699
- }
1700
- try {
1701
- process.kill(pid, "SIGTERM")
1702
-
1703
- // SIGTERM was previously fire-and-forget: it reported success
1704
- // immediately, so a runner that ignored it kept running and
1705
- // competed with the next one for jobs. Wait, then escalate.
1706
- const deadline = Date.now() + 5000
1707
- while (isRunning(pid) && Date.now() < deadline) {
1708
- await new Promise(r => setTimeout(r, 200))
1709
- }
1710
- if (isRunning(pid)) {
1711
- process.kill(pid, "SIGKILL")
1712
- await new Promise(r => setTimeout(r, 500))
1713
- }
1714
-
1715
- // The watchdog spawns the runner as a separate process, so
1716
- // killing the watchdog alone can leave the runner orphaned. The
1717
- // child can also outlive the first sweep, so this repeats until
1718
- // nothing is left.
1719
- let killed = 0
1720
- for (let attempt = 0; attempt < 5; attempt++) {
1721
- const strays = findStrayRunnerPids(pid)
1722
- if (strays.length === 0) break
1723
- for (const stray of strays) {
1724
- try { process.kill(stray, "SIGKILL"); killed += 1 } catch {}
1725
- }
1726
- await new Promise(r => setTimeout(r, 400))
1727
- }
1728
-
1729
- clearPid()
1730
- const extra = killed > 0 ? ` (+${killed} orphaned)` : ""
1731
- console.log(`\x1b[32m✓\x1b[0m Stopped (PID ${pid})${extra}`)
1732
- }
1733
- catch (e) { console.log(`\x1b[31mFailed: ${e.message}\x1b[0m`) }
1734
- break
1735
- }
1736
- case "doctor": {
1737
- const config = readConfig()
1738
- const ok = (msg) => console.log(` \x1b[32m✓\x1b[0m ${msg}`)
1739
- const err = (msg) => console.log(` \x1b[31m✗\x1b[0m ${msg}`)
1740
- const wrn = (msg) => console.log(` \x1b[33m⚠\x1b[0m ${msg}`)
1741
- console.log(`\n\x1b[1mDiagnostics\x1b[0m\n`)
1742
-
1743
- // Node version
1744
- const nodeVer = process.versions.node
1745
- const [nodeMaj] = nodeVer.split(".").map(Number)
1746
- nodeMaj >= 18 ? ok(`Node.js ${nodeVer}`) : err(`Node.js ${nodeVer} — requires ≥18`)
1747
-
1748
- // Auth
1749
- const key = config.apiKey ?? config.workspaceApiKey
1750
- key ? ok(`API key set \x1b[2m(${key.slice(0,16)}…)\x1b[0m`) : err(`No API key — run /login`)
1751
- config.workspaceSlug ? ok(`Workspace: ${config.workspaceSlug}`) : err(`No workspace — run /login`)
1752
-
1753
- // App URL reachability
1754
- const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
1755
- try {
1756
- const t0 = Date.now()
1757
- const r = await fetch(`${appUrl}/api/health`, { signal: AbortSignal.timeout(3000) })
1758
- const ms = Date.now() - t0
1759
- r.ok ? ok(`App reachable: ${appUrl} \x1b[2m(${ms}ms)\x1b[0m`) : wrn(`App returned ${r.status}: ${appUrl}`)
1760
- } catch { err(`Cannot reach app: ${appUrl}`) }
1761
-
1762
- // Executor binary
1763
- const exe = EXECUTORS.find(e => e.id === (config.executor ?? "codex"))
1764
- if (exe) {
1765
- checkBinaryExists(exe.bin)
1766
- ? ok(`Executor: ${exe.label} \x1b[2m(${exe.bin})\x1b[0m`)
1767
- : err(`Executor binary not found: ${exe.bin} — install ${exe.label} or run /use to switch`)
1768
- }
1769
-
1770
- // Repo root
1771
- if (config.repoRoot) {
1772
- try {
1773
- fs.accessSync(config.repoRoot)
1774
- ok(`Repo root: ${config.repoRoot}`)
1775
- } catch { err(`Repo root not found: ${config.repoRoot} — run /config repo-root <path>`) }
1776
- } else {
1777
- wrn(`Repo root not set — run /config repo-root <path>`)
1778
- }
1779
-
1780
- // Runner daemon
1781
- const dpid = readPid()
1782
- dpid && isRunning(dpid)
1783
- ? ok(`Runner daemon running \x1b[2m(PID ${dpid})\x1b[0m`)
1784
- : wrn(`Runner daemon not running — run /start`)
1785
-
1786
- // pacework version
1787
- ok(`pacework-runner v${LOCAL_VERSION ?? "unknown"}`)
1788
-
1789
- console.log("")
1790
- break
1791
- }
1792
- case "restart": {
1793
- const pid = readPid()
1794
- if (pid && isRunning(pid)) {
1795
- try { process.kill(pid, "SIGTERM"); clearPid(); console.log(`\x1b[32m✓\x1b[0m Stopped (PID ${pid})`) }
1796
- catch (e) { console.log(`\x1b[31mStop failed: ${e.message}\x1b[0m`); break }
1797
- await new Promise(r => setTimeout(r, 800))
1798
- }
1799
- console.log("Starting runner in background…")
1800
- const rchild = spawn(process.execPath, [fileURLToPath(import.meta.url), "start"], {
1801
- stdio: "inherit",
1802
- env: { ...process.env, PATH: process.env.PATH || "" },
1803
- })
1804
- await new Promise(r => rchild.on("exit", r))
1805
- break
1806
- }
1807
- case "tail": {
1808
- console.log(`\x1b[2mStreaming log — press Ctrl+C to stop\x1b[0m\n`)
1809
- try {
1810
- const tail = spawn("tail", ["-f", "-n", "40", LOG_FILE], { stdio: ["ignore", "pipe", "ignore"] })
1811
- tail.stdout.on("data", chunk => {
1812
- const lines = chunk.toString().split("\n")
1813
- for (const l of lines) {
1814
- const fmt = formatLogLine(l)
1815
- if (fmt) process.stdout.write(fmt + "\n")
1816
- }
1817
- })
1818
- await new Promise(resolve => {
1819
- process.once("SIGINT", () => { tail.kill(); resolve() })
1820
- tail.on("exit", resolve)
1821
- })
1822
- console.log("")
1823
- } catch { console.log("No log file yet.") }
1824
- break
1825
- }
1826
- case "watch": {
1827
- const config = readConfig()
1828
- let watching = true
1829
- let watchLines = 0
1830
- const stopWatch = () => { watching = false }
1831
- process.once("SIGINT", stopWatch)
1832
- const watchRunIds = new Set()
1833
-
1834
- const renderWatch = async () => {
1835
- const runs = await fetchActiveRuns(config)
1836
- // bell notification when a previously-seen run is no longer active
1837
- const currentIds = new Set((runs ?? []).map(r => r.id).filter(Boolean))
1838
- for (const prevId of watchRunIds) {
1839
- if (!currentIds.has(prevId)) process.stdout.write("\x07")
1840
- }
1841
- watchRunIds.clear()
1842
- for (const r of (runs ?? [])) if (r.id && r.status === "running") watchRunIds.add(r.id)
1843
- const pid2 = readPid()
1844
- const running2 = pid2 && isRunning(pid2)
1845
- const dot = running2 ? `\x1b[32m● Running\x1b[0m` : `\x1b[2m○ Stopped\x1b[0m`
1846
-
1847
- // build output lines in a buffer so we can measure
1848
- const lines = []
1849
- lines.push(` ${dot} \x1b[2m${new Date().toLocaleTimeString()} — Ctrl+C to stop\x1b[0m`)
1850
- lines.push("")
1851
- if (runs?.length) {
1852
- const COL_STATUS = 10, COL_TITLE = 34, COL_AGE = 10, COL_DUR = 8
1853
- const hr = ` ${"─".repeat(COL_STATUS + COL_TITLE + COL_AGE + COL_DUR + 6)}`
1854
- const STATUS_COLORS = { running:"\x1b[34m", queued:"\x1b[33m", pending:"\x1b[33m", completed:"\x1b[32m", failed:"\x1b[31m", error:"\x1b[31m", cancelled:"\x1b[2m" }
1855
- const STATUS_GLYPH = { running:"▶", queued:"◌", pending:"◌", completed:"✓", failed:"✗", error:"✗", cancelled:"–" }
1856
- lines.push(`\x1b[1mActive runs\x1b[0m`)
1857
- lines.push(hr)
1858
- lines.push(` \x1b[2m${"STATUS".padEnd(COL_STATUS)} ${"TASK".padEnd(COL_TITLE)} ${"AGE".padEnd(COL_AGE)} ${"DURATION".padEnd(COL_DUR)}\x1b[0m`)
1859
- lines.push(hr)
1860
- for (const r of runs) {
1861
- const status = (r.status ?? "unknown").toLowerCase()
1862
- const label = `${STATUS_GLYPH[status] ?? "·"} ${status}`.padEnd(COL_STATUS)
1863
- const title = (r.task_title ?? r.task_identifier ?? r.id?.slice(0,8) ?? "—").slice(0,COL_TITLE).padEnd(COL_TITLE)
1864
- const age = relTime(r.started_at ?? r.created_at).padEnd(COL_AGE)
1865
- 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)
1866
- lines.push(` ${STATUS_COLORS[status]??""}}${label}\x1b[0m \x1b[1m${title}\x1b[0m \x1b[2m${age} ${dur}\x1b[0m`)
1867
- }
1868
- lines.push(hr)
1869
- } else {
1870
- lines.push(` \x1b[2mNo active runs.\x1b[0m`)
1871
- }
1872
-
1873
- // erase previous render in-place
1874
- if (watchLines > 0) {
1875
- process.stdout.write(`\x1b[${watchLines}A\x1b[J`)
1876
- }
1877
- process.stdout.write(lines.join("\n") + "\n")
1878
- watchLines = lines.length
1879
- }
1880
-
1881
- await renderWatch()
1882
- while (watching) {
1883
- await new Promise(r => setTimeout(r, 3000))
1884
- if (!watching) break
1885
- await renderWatch()
1886
- }
1887
- process.removeListener("SIGINT", stopWatch)
1888
- console.log("\x1b[2mStopped watch.\x1b[0m\n")
1889
- break
1890
- }
1891
- case "stats": {
1892
- console.log("")
1893
- try {
1894
- const raw = fs.readFileSync(LOG_FILE, "utf8")
1895
- const events = []
1896
- for (const line of raw.split("\n")) {
1897
- if (!line.trim()) continue
1898
- try { const e = JSON.parse(line); if (e.event && e.ts) events.push(e) } catch {}
1899
- }
1900
- const starts = events.filter(e => e.event === "runner.job.start")
1901
- const completes = events.filter(e => e.event === "runner.job.complete")
1902
- const errors = events.filter(e => e.event === "runner.job.error")
1903
- const todayStart = new Date(); todayStart.setHours(0,0,0,0)
1904
- const todayStarts = starts.filter(e => new Date(e.ts) >= todayStart)
1905
-
1906
- const durations = []
1907
- for (const c of completes) {
1908
- const id = c.run_id ?? c.meta?.run_id
1909
- const s = starts.find(e => (e.run_id ?? e.meta?.run_id) === id)
1910
- if (s) durations.push(new Date(c.ts) - new Date(s.ts))
1911
- }
1912
- const avgDur = durations.length ? durations.reduce((a,b) => a+b, 0) / durations.length : 0
1913
- const total = starts.length
1914
- const success = completes.length
1915
- const failed = errors.length
1916
- const rate = total ? Math.round((success / total) * 100) : 0
1917
-
1918
- const config = readConfig()
1919
- const apiRuns = await fetchActiveRuns(config)
1920
- const activeCount = apiRuns?.filter(r => r.status === "running").length ?? 0
1921
- const queuedCount = apiRuns?.filter(r => ["queued","pending"].includes(r.status)).length ?? 0
1922
-
1923
- console.log(` \x1b[1mRunner stats\x1b[0m\n`)
1924
- console.log(` ${"Today's runs".padEnd(20)} \x1b[1m${todayStarts.length}\x1b[0m`)
1925
- console.log(` ${"Total runs".padEnd(20)} \x1b[1m${total}\x1b[0m`)
1926
- console.log(` ${"Completed".padEnd(20)} \x1b[32m${success}\x1b[0m`)
1927
- console.log(` ${"Failed".padEnd(20)} ${failed > 0 ? `\x1b[31m${failed}\x1b[0m` : `\x1b[2m${failed}\x1b[0m`}`)
1928
- console.log(` ${"Success rate".padEnd(20)} \x1b[1m${rate}%\x1b[0m`)
1929
- console.log(` ${"Avg duration".padEnd(20)} \x1b[2m${avgDur ? fmtDuration(avgDur) : "—"}\x1b[0m`)
1930
- console.log(` ${"Active now".padEnd(20)} ${activeCount > 0 ? `\x1b[34m${activeCount}\x1b[0m` : "\x1b[2m0\x1b[0m"}`)
1931
- console.log(` ${"Queued".padEnd(20)} ${queuedCount > 0 ? `\x1b[33m${queuedCount}\x1b[0m` : "\x1b[2m0\x1b[0m"}`)
1932
- console.log("")
1933
- } catch { console.log(" No log data yet. Start the runner and run some jobs first.\n") }
1934
- break
1935
- }
1936
- case "issues": {
1937
- const config = readConfig()
1938
- const key = config.apiKey ?? config.workspaceApiKey
1939
- const wsId = config.workspaceId
1940
- const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
1941
- if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); break }
1942
- console.log(`\n\x1b[2mFetching issues…\x1b[0m`)
1943
- try {
1944
- const filter = args[0] ?? "open" // open | all | in_progress
1945
- const res = await fetch(`${appUrl}/api/workspaces/${wsId}/cli/issues?status=${filter}&limit=20`, {
1946
- headers: { "x-workspace-api-key": key },
1947
- signal: AbortSignal.timeout(5000),
1948
- })
1949
- if (!res.ok) { console.log(` \x1b[31mAPI error: ${res.status}\x1b[0m\n`); break }
1950
- const data = await res.json()
1951
- const issues = data.issues ?? data ?? []
1952
- if (!issues.length) { console.log(` \x1b[2mNo ${filter} issues found.\x1b[0m\n`); break }
1953
-
1954
- const STATUS_COLOR = { open:"\x1b[32m", in_progress:"\x1b[34m", in_review:"\x1b[33m", done:"\x1b[2m", cancelled:"\x1b[2m" }
1955
- const COL_ID = 10, COL_STATUS = 14, COL_TITLE = 48
1956
- const hr = ` ${"─".repeat(COL_ID + COL_STATUS + COL_TITLE + 4)}`
1957
- console.log(`\n\x1b[1mIssues\x1b[0m \x1b[2m(${filter})\x1b[0m`)
1958
- console.log(hr)
1959
- console.log(` \x1b[2m${"ID".padEnd(COL_ID)} ${"STATUS".padEnd(COL_STATUS)} ${"TITLE".padEnd(COL_TITLE)}\x1b[0m`)
1960
- console.log(hr)
1961
- for (const i of issues) {
1962
- const status = (i.status ?? "open").toLowerCase()
1963
- const col = STATUS_COLOR[status] ?? ""
1964
- const id = (i.identifier ?? i.id?.slice(0,8) ?? "—").padEnd(COL_ID)
1965
- const st = status.padEnd(COL_STATUS)
1966
- const title = (i.title ?? "—").slice(0, COL_TITLE).padEnd(COL_TITLE)
1967
- console.log(` \x1b[2m${id}\x1b[0m ${col}${st}\x1b[0m ${title}`)
1968
- }
1969
- console.log(hr)
1970
- console.log(` \x1b[2mTip: /issues in_progress · /issues all\x1b[0m\n`)
1971
- } catch (e) { console.log(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
1972
- break
1973
- }
1974
- // ── issue detail ──────────────────────────────────────────────────
1975
- case "issue": {
1976
- const config = readConfig()
1977
- const key = config.apiKey ?? config.workspaceApiKey
1978
- const wsId = config.workspaceId
1979
- const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
1980
- if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); break }
1981
-
1982
- const id = args[0]
1983
- if (!id) { console.log(`\n Usage: /issue <identifier> e.g. /issue PLT-42\n`); break }
1984
-
1985
- try {
1986
- const res = await fetch(`${appUrl}/api/workspaces/${wsId}/cli/issue/${encodeURIComponent(id.toUpperCase())}`, {
1987
- headers: { "x-workspace-api-key": key },
1988
- signal: AbortSignal.timeout(5000),
1989
- })
1990
- if (res.status === 404) { console.log(`\n \x1b[31mIssue not found: ${id}\x1b[0m\n`); break }
1991
- if (!res.ok) { console.log(` \x1b[31mAPI error: ${res.status}\x1b[0m\n`); break }
1992
- const { issue, comments } = await res.json()
1993
-
1994
- 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" }
1995
- 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" }
1996
- const statusCol = STATUS_COLOR[issue.status] ?? ""
1997
- const cols = Math.min(process.stdout.columns || 80, 80)
1998
- const div = ` \x1b[38;5;237m${"─".repeat(cols - 4)}\x1b[0m`
1999
-
2000
- console.log("")
2001
- console.log(div)
2002
- console.log(` \x1b[2m${issue.identifier}\x1b[0m \x1b[1m${issue.title}\x1b[0m`)
2003
- console.log(div)
2004
- const meta = [
2005
- `Status: ${statusCol}${issue.status}\x1b[0m`,
2006
- issue.priority ? `Priority: ${PRIORITY_LABEL[issue.priority] ?? issue.priority}` : null,
2007
- issue.assignee_name ? `Assignee: \x1b[1m${issue.assignee_name}\x1b[0m` : null,
2008
- issue.project_name ? `Project: \x1b[2m${issue.project_name}\x1b[0m` : null,
2009
- ].filter(Boolean).join(" · ")
2010
- console.log(` ${meta}`)
2011
- if (issue.description) {
2012
- console.log("")
2013
- const lines = issue.description.replace(/\r\n/g, "\n").split("\n").slice(0, 12)
2014
- for (const l of lines) console.log(` \x1b[2m${l.slice(0, cols - 4)}\x1b[0m`)
2015
- }
2016
- if (comments?.length) {
2017
- console.log(`\n \x1b[2mComments (${comments.length})\x1b[0m`)
2018
- for (const c of comments) {
2019
- console.log(` \x1b[36m${c.author ?? "agent"}\x1b[0m \x1b[2m${relTime(c.created_at)}\x1b[0m`)
2020
- const body = c.body.replace(/\r\n/g, "\n").split("\n").slice(0, 4)
2021
- for (const l of body) console.log(` \x1b[2m${l.slice(0, cols - 6)}\x1b[0m`)
2022
- }
2023
- }
2024
- console.log(div)
2025
- const ws = config.workspaceSlug ?? config.workspaceId ?? ""
2026
- if (ws) console.log(` \x1b[2m${appUrl}/${ws}/issues/${issue.identifier} · /open ${issue.identifier}\x1b[0m`)
2027
- console.log("")
2028
- } catch (e) { console.log(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
2029
- break
2030
- }
2031
- // ── my issues ─────────────────────────────────────────────────────
2032
- case "mine": {
2033
- const config = readConfig()
2034
- const key = config.apiKey ?? config.workspaceApiKey
2035
- const wsId = config.workspaceId
2036
- const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2037
- if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); break }
2038
-
2039
- console.log(`\n\x1b[2mFetching your issues…\x1b[0m`)
2040
- try {
2041
- const res = await fetch(`${appUrl}/api/workspaces/${wsId}/cli/my-issues?limit=30`, {
2042
- headers: { "x-workspace-api-key": key },
2043
- signal: AbortSignal.timeout(5000),
2044
- })
2045
- if (!res.ok) { console.log(` \x1b[31mAPI error: ${res.status}\x1b[0m\n`); break }
2046
- const { issues } = await res.json()
2047
- if (!issues?.length) { console.log(` \x1b[2mNo issues assigned to you.\x1b[0m\n`); break }
2048
-
2049
- const STATUS_COLOR = { backlog:"\x1b[2m", todo:"\x1b[37m", in_progress:"\x1b[34m", in_review:"\x1b[33m" }
2050
- const COL_ID = 10, COL_STATUS = 14, COL_TITLE = 46
2051
- const hr = ` ${"─".repeat(COL_ID + COL_STATUS + COL_TITLE + 4)}`
2052
- console.log(`\n\x1b[1mMy issues\x1b[0m \x1b[2m(${issues.length})\x1b[0m`)
2053
- console.log(hr)
2054
- console.log(` \x1b[2m${"ID".padEnd(COL_ID)} ${"STATUS".padEnd(COL_STATUS)} ${"TITLE".padEnd(COL_TITLE)}\x1b[0m`)
2055
- console.log(hr)
2056
- for (const i of issues) {
2057
- const status = (i.status ?? "").toLowerCase()
2058
- const col = STATUS_COLOR[status] ?? ""
2059
- const id = (i.identifier ?? i.id?.slice(0,8) ?? "—").padEnd(COL_ID)
2060
- const st = status.padEnd(COL_STATUS)
2061
- const title = (i.title ?? "—").slice(0, COL_TITLE).padEnd(COL_TITLE)
2062
- console.log(` \x1b[2m${id}\x1b[0m ${col}${st}\x1b[0m ${title}`)
2063
- }
2064
- console.log(hr)
2065
- console.log(` \x1b[2mTip: /issue <id> to view details · /run <id> to dispatch\x1b[0m\n`)
2066
- } catch (e) { console.log(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
2067
- break
2068
- }
2069
- // ── agents list ───────────────────────────────────────────────────
2070
- case "agents": {
2071
- const config = readConfig()
2072
- const key = config.apiKey ?? config.workspaceApiKey
2073
- const wsId = config.workspaceId
2074
- const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2075
- if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); break }
2076
-
2077
- console.log(`\n\x1b[2mFetching agents…\x1b[0m`)
2078
- try {
2079
- const res = await fetch(`${appUrl}/api/workspaces/${wsId}/cli/agents`, {
2080
- headers: { "x-workspace-api-key": key },
2081
- signal: AbortSignal.timeout(5000),
2082
- })
2083
- if (!res.ok) { console.log(` \x1b[31mAPI error: ${res.status}\x1b[0m\n`); break }
2084
- const { agents } = await res.json()
2085
- if (!agents?.length) { console.log(` \x1b[2mNo agents configured.\x1b[0m\n`); break }
2086
-
2087
- const SKILL_COLOR = { reviewer:"\x1b[33m", implementer:"\x1b[34m", planner:"\x1b[35m" }
2088
- const COL_NAME = 22, COL_SKILL = 16, COL_EXE = 14
2089
- const hr = ` ${"─".repeat(COL_NAME + COL_SKILL + COL_EXE + 4)}`
2090
- console.log(`\n\x1b[1mAgents\x1b[0m \x1b[2m(${agents.length})\x1b[0m`)
2091
- console.log(hr)
2092
- console.log(` \x1b[2m${"NAME".padEnd(COL_NAME)} ${"SKILL".padEnd(COL_SKILL)} ${"EXECUTOR".padEnd(COL_EXE)}\x1b[0m`)
2093
- console.log(hr)
2094
- for (const a of agents) {
2095
- const skill = (a.skill_profile_label ?? a.skill_profile_slug ?? "—").toLowerCase()
2096
- const skillCol = SKILL_COLOR[a.skill_profile_slug] ?? "\x1b[2m"
2097
- const name = (a.name ?? a.slug ?? a.id.slice(0,8)).slice(0, COL_NAME).padEnd(COL_NAME)
2098
- const skillStr = skill.slice(0, COL_SKILL).padEnd(COL_SKILL)
2099
- const exe = executorLabel(a.local_executor ?? "").slice(0, COL_EXE).padEnd(COL_EXE)
2100
- console.log(` \x1b[1m${name}\x1b[0m ${skillCol}${skillStr}\x1b[0m \x1b[2m${exe}\x1b[0m`)
2101
- }
2102
- console.log(hr)
2103
- console.log(` \x1b[2mTip: /run <issue-id> to dispatch with agent picker\x1b[0m\n`)
2104
- } catch (e) { console.log(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
2105
- break
2106
- }
2107
- // ── orchestration status dashboard ────────────────────────────────
2108
- case "dashboard": {
2109
- const config = readConfig()
2110
- const key = config.apiKey ?? config.workspaceApiKey
2111
- const wsId = config.workspaceId
2112
- const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2113
- if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); break }
2114
-
2115
- try {
2116
- const [orchRes, runsRes] = await Promise.all([
2117
- fetch(`${appUrl}/api/workspaces/${wsId}/cli/orchestration`, {
2118
- headers: { "x-workspace-api-key": key },
2119
- signal: AbortSignal.timeout(5000),
2120
- }),
2121
- fetchActiveRuns(config),
2122
- ])
2123
- const orch = orchRes.ok ? await orchRes.json() : null
2124
- const pid = readPid()
2125
- const running = pid && isRunning(pid)
2126
- const dot = running ? `\x1b[32m● Runner running\x1b[0m` : `\x1b[2m○ Runner stopped\x1b[0m`
2127
- const cols = Math.min(process.stdout.columns || 80, 80)
2128
- const div = ` \x1b[38;5;237m${"─".repeat(cols - 4)}\x1b[0m`
2129
-
2130
- console.log("")
2131
- console.log(div)
2132
- console.log(` ${dot}`)
2133
- console.log(div)
2134
-
2135
- if (orch) {
2136
- const r = orch.runs
2137
- const i = orch.issues
2138
- const stat = (label, val, col = "") => console.log(` ${col}${label.padEnd(22)}\x1b[0m \x1b[1m${val}\x1b[0m`)
2139
- stat("Active runs", r.running, r.running > 0 ? "\x1b[34m" : "\x1b[2m")
2140
- stat("Queued runs", r.queued, r.queued > 0 ? "\x1b[33m" : "\x1b[2m")
2141
- stat("Completed today", r.completed_today, r.completed_today > 0 ? "\x1b[32m" : "\x1b[2m")
2142
- stat("Failed today", r.failed_today, r.failed_today > 0 ? "\x1b[31m" : "\x1b[2m")
2143
- console.log(div)
2144
- stat("In review", i.in_review, i.in_review > 0 ? "\x1b[33m" : "\x1b[2m")
2145
- stat("In progress", i.in_progress, i.in_progress > 0 ? "\x1b[34m" : "\x1b[2m")
2146
- stat("Todo", i.todo, "\x1b[2m")
2147
- }
2148
-
2149
- if (runsRes?.length) {
2150
- console.log(div)
2151
- console.log(` \x1b[1mActive\x1b[0m`)
2152
- for (const r of runsRes.slice(0, 5)) {
2153
- const status = (r.status ?? "").toLowerCase()
2154
- const age = relTime(r.started_at ?? r.created_at)
2155
- 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`)
2156
- }
2157
- }
2158
- console.log(div)
2159
- console.log(` \x1b[2mTip: /watch to auto-refresh · /logtail <run-id> to stream a run\x1b[0m`)
2160
- console.log("")
2161
- } catch (e) { console.log(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
2162
- break
2163
- }
2164
- // ── stream run log ────────────────────────────────────────────────
2165
- case "logtail": {
2166
- const config = readConfig()
2167
- const key = config.apiKey ?? config.workspaceApiKey
2168
- const wsId = config.workspaceId
2169
- const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2170
- if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); break }
2171
-
2172
- const runId = args[0]
2173
- if (!runId) { console.log(`\n Usage: /logtail <run-id> (from /jobs or /watch)\n`); break }
2174
-
2175
- console.log(`\n \x1b[2mStreaming log for run ${runId.slice(0,8)}… (Ctrl+C to stop)\x1b[0m\n`)
2176
- let lastLen = 0
2177
- let done = false
2178
- let stopping = false
2179
- const stop = () => { stopping = true }
2180
- process.once("SIGINT", stop)
2181
-
2182
- while (!stopping) {
2183
- try {
2184
- const res = await fetch(`${appUrl}/api/workspaces/${wsId}/cli/runs/${runId}/log`, {
2185
- headers: { "x-workspace-api-key": key },
2186
- signal: AbortSignal.timeout(5000),
2187
- })
2188
- if (!res.ok) { console.log(` \x1b[31mAPI error: ${res.status}\x1b[0m\n`); break }
2189
- const data = await res.json()
2190
- const log = data.log_tail ?? ""
2191
- if (log.length > lastLen) {
2192
- const newContent = log.slice(lastLen)
2193
- process.stdout.write(newContent)
2194
- if (!newContent.endsWith("\n")) process.stdout.write("\n")
2195
- lastLen = log.length
2196
- }
2197
- if (["completed", "error", "cancelled"].includes(data.status)) {
2198
- const col = data.status === "completed" ? "\x1b[32m" : "\x1b[31m"
2199
- console.log(`\n ${col}Run ${data.status}\x1b[0m\n`)
2200
- done = true
2201
- break
2202
- }
2203
- } catch {}
2204
- await new Promise(r => setTimeout(r, 3000))
2205
- }
2206
- process.removeListener("SIGINT", stop)
2207
- if (!done && stopping) console.log("\n \x1b[2mStopped.\x1b[0m\n")
2208
- break
2209
- }
2210
- // ── orchestrator commands ─────────────────────────────────────────
2211
- case "run": {
2212
- // /run <issue-identifier> e.g. /run PLT-42
2213
- const config = readConfig()
2214
- const key = config.apiKey ?? config.workspaceApiKey
2215
- const wsId = config.workspaceId
2216
- const appUrl = (config.appUrl ?? "https://pacework.io ").replace(/\/$/, "")
2217
- if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); break }
2218
-
2219
- const issueRef = args[0]
2220
- if (!issueRef) { console.log(`\n Usage: /run <issue-identifier> e.g. /run PLT-42\n`); break }
2221
-
2222
- console.log(`\n \x1b[2mLooking up issue and agents…\x1b[0m`)
2223
- try {
2224
- // fetch issue + agents in parallel
2225
- const [issuesRes, agentsRes] = await Promise.all([
2226
- fetch(`${appUrl}/api/workspaces/${wsId}/cli/issues?status=all&limit=100`, {
2227
- headers: { "x-workspace-api-key": key },
2228
- signal: AbortSignal.timeout(5000),
2229
- }),
2230
- fetch(`${appUrl}/api/workspaces/${wsId}/cli/agents`, {
2231
- headers: { "x-workspace-api-key": key },
2232
- signal: AbortSignal.timeout(5000),
2233
- }),
2234
- ])
2235
-
2236
- if (!issuesRes.ok) { console.log(` \x1b[31mAPI error: ${issuesRes.status}\x1b[0m\n`); break }
2237
- const { issues } = await issuesRes.json()
2238
- const issue = issues?.find(i => i.identifier?.toUpperCase() === issueRef.toUpperCase())
2239
- if (!issue) { console.log(` \x1b[31mIssue not found: ${issueRef}\x1b[0m\n`); break }
2240
-
2241
- // agents list (may fail gracefully)
2242
- let agents = []
2243
- if (agentsRes.ok) {
2244
- const agentData = await agentsRes.json().catch(() => ({}))
2245
- agents = Array.isArray(agentData) ? agentData : (agentData.agents ?? agentData.data ?? [])
2246
- }
2247
-
2248
- // show issue summary
2249
- console.log(`\n \x1b[1m${issue.identifier}\x1b[0m ${issue.title}`)
2250
- console.log(` \x1b[2mStatus: ${issue.status}${issue.priority ? ` · Priority: ${issue.priority}` : ""}\x1b[0m\n`)
2251
-
2252
- // agent picker
2253
- let chosenAgentId = issue.agent_id ?? null
2254
-
2255
- if (agents.length > 0) {
2256
- const defaultIdx = agents.findIndex(a => a.id === chosenAgentId)
2257
- console.log(` \x1b[1mPick an agent:\x1b[0m \x1b[2m(Enter to use default)\x1b[0m\n`)
2258
- agents.forEach((a, i) => {
2259
- const isDefault = a.id === chosenAgentId
2260
- const tag = isDefault ? ` \x1b[32m← default\x1b[0m` : ""
2261
- const executor = a.local_executor ? ` \x1b[2m${executorLabel(a.local_executor)}\x1b[0m` : ""
2262
- console.log(` \x1b[36m${i + 1}.\x1b[0m \x1b[1m${a.name ?? a.slug ?? a.id.slice(0,8)}\x1b[0m${executor}${tag}`)
2263
- })
2264
- console.log("")
2265
-
2266
- // pause raw mode for a simple line read
2267
- process.stdin.setRawMode(false)
2268
- const answer = await new Promise(resolve => {
2269
- process.stdout.write(` \x1b[36mAgent number (default ${defaultIdx >= 0 ? defaultIdx + 1 : "issue default"}):\x1b[0m `)
2270
- let buf = ""
2271
- const onData = (chunk) => {
2272
- const s = chunk.toString()
2273
- if (s === "\n" || s === "\r") {
2274
- process.stdin.removeListener("data", onData)
2275
- process.stdout.write("\n")
2276
- resolve(buf.trim())
2277
- } else if (s === "\x7f" && buf.length) {
2278
- buf = buf.slice(0, -1)
2279
- process.stdout.write("\b \b")
2280
- } else if (s >= " ") {
2281
- buf += s
2282
- process.stdout.write(s)
2283
- }
2284
- }
2285
- process.stdin.on("data", onData)
2286
- })
2287
- process.stdin.setRawMode(true)
2288
-
2289
- if (answer !== "") {
2290
- const idx = parseInt(answer, 10) - 1
2291
- if (idx >= 0 && idx < agents.length) {
2292
- chosenAgentId = agents[idx].id
2293
- console.log(` \x1b[2mUsing agent: ${agents[idx].name ?? agents[idx].slug}\x1b[0m`)
2294
- } else {
2295
- console.log(` \x1b[33m⚠\x1b[0m Invalid choice — using issue default`)
2296
- }
2297
- } else {
2298
- const def = agents[defaultIdx]
2299
- if (def) console.log(` \x1b[2mUsing default agent: ${def.name ?? def.slug}\x1b[0m`)
2300
- }
2301
- } else if (chosenAgentId) {
2302
- console.log(` \x1b[2mNo agents list available — using issue's assigned agent\x1b[0m`)
2303
- }
2304
-
2305
- console.log(`\n \x1b[2mDispatching…\x1b[0m`)
2306
- const dispatchBody = { task_id: issue.id, workspace_id: wsId }
2307
- if (chosenAgentId) dispatchBody.agent_id = chosenAgentId
2308
-
2309
- const dispatch = await fetch(`${appUrl}/api/agent-planner/dispatch`, {
2310
- method: "POST",
2311
- headers: { "content-type": "application/json", Authorization: `Bearer ${key}` },
2312
- body: JSON.stringify(dispatchBody),
2313
- signal: AbortSignal.timeout(8000),
2314
- })
2315
- const body = await dispatch.json().catch(() => ({}))
2316
- if (dispatch.ok) {
2317
- const statusLabel = body.status === "already_queued" ? "already queued" : body.status === "resumed" ? "resumed" : "dispatched"
2318
- 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` : ""}`)
2319
- } else {
2320
- console.log(` \x1b[31m✗\x1b[0m Dispatch failed (${dispatch.status}): ${body.message ?? body.error ?? "unknown"}`)
2321
- }
2322
- console.log("")
2323
- } catch (e) { console.log(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
2324
- break
2325
- }
2326
- case "cancel": {
2327
- const config = readConfig()
2328
- const key = config.apiKey ?? config.workspaceApiKey
2329
- const wsId = config.workspaceId
2330
- const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2331
- if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); break }
2332
-
2333
- const runId = args[0]
2334
- if (!runId) { console.log(`\n Usage: /cancel <run-id> (from /jobs)\n`); break }
2335
-
2336
- try {
2337
- console.log(`\n \x1b[2mCancelling run ${runId.slice(0,8)}…\x1b[0m`)
2338
- const res = await fetch(`${appUrl}/api/workspaces/${wsId}/agent-runs/${runId}/cancel`, {
2339
- method: "POST",
2340
- headers: { "content-type": "application/json", "x-workspace-api-key": key },
2341
- signal: AbortSignal.timeout(5000),
2342
- })
2343
- if (res.ok) console.log(` \x1b[32m✓\x1b[0m Run cancelled`)
2344
- else { const b = await res.json().catch(() => ({})); console.log(` \x1b[31m✗\x1b[0m Failed (${res.status}): ${b.message ?? b.error ?? ""}`) }
2345
- console.log("")
2346
- } catch (e) { console.log(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
2347
- break
2348
- }
2349
- case "retry": {
2350
- const config = readConfig()
2351
- const key = config.apiKey ?? config.workspaceApiKey
2352
- const wsId = config.workspaceId
2353
- const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2354
- if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); break }
2355
-
2356
- const runId = args[0]
2357
- if (!runId) { console.log(`\n Usage: /retry <run-id> (from /jobs)\n`); break }
2358
-
2359
- try {
2360
- console.log(`\n \x1b[2mRetrying run ${runId.slice(0,8)}…\x1b[0m`)
2361
- const res = await fetch(`${appUrl}/api/workspaces/${wsId}/agent-runs/${runId}/retry`, {
2362
- method: "POST",
2363
- headers: { "content-type": "application/json", "x-workspace-api-key": key },
2364
- signal: AbortSignal.timeout(5000),
2365
- })
2366
- if (res.ok) {
2367
- const b = await res.json().catch(() => ({}))
2368
- console.log(` \x1b[32m✓\x1b[0m Run retried${b.run_id ? ` \x1b[2mnew run ${b.run_id.slice(0,8)}\x1b[0m` : ""}`)
2369
- } else {
2370
- const b = await res.json().catch(() => ({}))
2371
- console.log(` \x1b[31m✗\x1b[0m Failed (${res.status}): ${b.message ?? b.error ?? ""}`)
2372
- }
2373
- console.log("")
2374
- } catch (e) { console.log(` \x1b[31mFailed: ${e.message}\x1b[0m\n`) }
2375
- break
2376
- }
2377
- case "pause":
2378
- case "resume":
2379
- case "capacity": {
2380
- const config = readConfig()
2381
- const result = await runRunnerControlCommand(config, readRunnerId(config), cmd, args)
2382
- const symbol = result.ok ? "\x1b[32m✓" : "\x1b[31m✗"
2383
- console.log(` ${symbol}\x1b[0m ${result.message}\n`)
2384
- if (oneShot !== null && !result.ok) process.exitCode = 1
2385
- break
2386
- }
2387
- case "mcp": {
2388
- const config = readConfig()
2389
- const key = config.apiKey ?? config.workspaceApiKey
2390
- const wsId = config.workspaceId
2391
- const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2392
- const executor = config.executor ?? "claude_code"
2393
- const repoRoot = config.repoRoot ?? process.cwd()
2394
- const sub = args[0] ?? ""
2395
-
2396
- if (!sub || sub === "help") {
2397
- console.log(`\n \x1b[1m/mcp\x1b[0m — manage MCP server connections\n`)
2398
- console.log(` \x1b[36m/mcp install\x1b[0m \x1b[2m— inject pacework MCP into your executor's config\x1b[0m`)
2399
- console.log(` \x1b[36m/mcp status \x1b[0m \x1b[2m— show configured MCP servers\x1b[0m`)
2400
- console.log(` \x1b[36m/mcp test \x1b[0m \x1b[2m— ping each MCP server\x1b[0m\n`)
2401
- break
2402
- }
2403
-
2404
- if (!key || !wsId) { console.log("\n Not logged in — run /login first.\n"); break }
2405
-
2406
- if (sub === "install") {
2407
- console.log(`\n \x1b[2mConfiguring MCP for ${executorLabel(executor)}…\x1b[0m`)
2408
- const mcpUrl = `${appUrl}/api/mcp`
2409
-
2410
- // Prefer the runner's dedicated MCP key from the state file — it's
2411
- // scoped specifically for MCP access. Fall back to workspace API key.
2412
- let mcpKey = key
2413
- try {
2414
- const stateFile = path.join(repoRoot, ".agent", "runners", `${wsId}-${executor}.json`)
2415
- const runnerState = JSON.parse(fs.readFileSync(stateFile, "utf8"))
2416
- if (runnerState.runner_mcp_key) {
2417
- mcpKey = runnerState.runner_mcp_key
2418
- console.log(` \x1b[2mUsing runner MCP key from state file\x1b[0m`)
2419
- }
2420
- } catch {
2421
- console.log(` \x1b[2mRunner not started yet — using workspace API key as MCP token\x1b[0m`)
2422
- }
2423
- const authHeader = `Bearer ${mcpKey}`
2424
-
2425
- if (executor === "claude_code") {
2426
- const claudeDir = path.join(repoRoot, ".agent", "claude-home")
2427
- fs.mkdirSync(claudeDir, { recursive: true })
2428
- const claudeJson = path.join(claudeDir, ".claude.json")
2429
- let existing = {}
2430
- try { existing = JSON.parse(fs.readFileSync(claudeJson, "utf8")) } catch {}
2431
- existing.mcpServers = { ...existing.mcpServers, kentral_local: { type: "http", url: mcpUrl, headers: { Authorization: authHeader } } }
2432
- fs.writeFileSync(claudeJson, JSON.stringify(existing, null, 2))
2433
- console.log(` \x1b[32m✓\x1b[0m Claude Code MCP written to \x1b[2m${claudeJson}\x1b[0m`)
2434
- } else if (executor === "gemini") {
2435
- const geminiDir = path.join(os.homedir(), ".gemini")
2436
- fs.mkdirSync(geminiDir, { recursive: true })
2437
- const settingsPath = path.join(geminiDir, "settings.json")
2438
- let existing = {}
2439
- try { existing = JSON.parse(fs.readFileSync(settingsPath, "utf8")) } catch {}
2440
- existing.mcpServers = { ...existing.mcpServers, kentral_local: { httpUrl: mcpUrl, headers: { Authorization: authHeader } } }
2441
- fs.writeFileSync(settingsPath, JSON.stringify(existing, null, 2))
2442
- console.log(` \x1b[32m✓\x1b[0m Gemini MCP written to \x1b[2m${settingsPath}\x1b[0m`)
2443
- } else if (executor === "cursor_agent") {
2444
- const cursorDir = path.join(os.homedir(), ".cursor")
2445
- fs.mkdirSync(cursorDir, { recursive: true })
2446
- const mcpPath = path.join(cursorDir, "mcp.json")
2447
- let existing = {}
2448
- try { existing = JSON.parse(fs.readFileSync(mcpPath, "utf8")) } catch {}
2449
- existing.mcpServers = { ...existing.mcpServers, kentral_local: { url: mcpUrl, headers: { Authorization: authHeader } } }
2450
- fs.writeFileSync(mcpPath, JSON.stringify(existing, null, 2))
2451
- console.log(` \x1b[32m✓\x1b[0m Cursor MCP written to \x1b[2m${mcpPath}\x1b[0m`)
2452
- } else if (executor === "codex") {
2453
- const codexHome = process.env.CODEX_HOME ?? path.join(os.homedir(), ".codex")
2454
- const configPath = path.join(codexHome, "config.toml")
2455
- let toml = ""
2456
- try { toml = fs.readFileSync(configPath, "utf8") } catch {}
2457
- if (!toml.includes("[mcp_servers.kentral_local]")) {
2458
- toml += `\n[mcp_servers.kentral_local]\nenabled = true\nurl = "${mcpUrl}"\n\n[mcp_servers.kentral_local.http_headers]\nAuthorization = "${authHeader}"\n`
2459
- fs.mkdirSync(codexHome, { recursive: true })
2460
- fs.writeFileSync(configPath, toml)
2461
- console.log(` \x1b[32m✓\x1b[0m Codex MCP written to \x1b[2m${configPath}\x1b[0m`)
2462
- } else {
2463
- console.log(` \x1b[33m⚠\x1b[0m kentral_local already in \x1b[2m${configPath}\x1b[0m — update manually if needed`)
2464
- }
2465
- } else {
2466
- console.log(` \x1b[33m⚠\x1b[0m MCP install not yet implemented for executor: ${executor}`)
2467
- }
2468
- console.log(` \x1b[2mMCP endpoint: ${mcpUrl}\x1b[0m`)
2469
- console.log(` \x1b[2mRestart your executor to pick up the new config.\x1b[0m\n`)
2470
-
2471
- } else if (sub === "status") {
2472
- console.log(`\n \x1b[1mMCP servers\x1b[0m \x1b[2m(executor: ${executorLabel(executor)})\x1b[0m\n`)
2473
- const servers = await fetchMcpServerList(config)
2474
- if (!servers?.length) {
2475
- console.log(` \x1b[2mNo MCP servers configured in workspace.\x1b[0m`)
2476
- console.log(` The pacework MCP server is always available at:\x1b[0m`)
2477
- console.log(` \x1b[2m${appUrl}/api/mcp\x1b[0m\n`)
2478
- } else {
2479
- for (const s of servers) {
2480
- console.log(` \x1b[36m${s.name ?? s.id}\x1b[0m \x1b[2m${s.url ?? s.transport ?? "stdio"}\x1b[0m`)
2481
- }
2482
- console.log("")
2483
- }
2484
-
2485
- } else if (sub === "test") {
2486
- console.log(`\n \x1b[2mPinging MCP servers…\x1b[0m\n`)
2487
- const servers = await fetchMcpServerList(config)
2488
- // always include kentral_local
2489
- const allServers = [
2490
- { name: "kentral_local", url: `${appUrl}/api/mcp` },
2491
- ...(servers ?? []).filter(s => s.url),
2492
- ]
2493
- for (const s of allServers) {
2494
- const t0 = Date.now()
2495
- try {
2496
- const r = await fetch(s.url, { method: "GET", headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(4000) })
2497
- const ms = Date.now() - t0
2498
- const ok2 = r.ok || r.status === 405 // MCP endpoints often don't support GET
2499
- 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`)
2500
- } catch (e) {
2501
- console.log(` \x1b[31m✗\x1b[0m \x1b[1m${s.name}\x1b[0m \x1b[31munreachable\x1b[0m \x1b[2m${s.url}\x1b[0m`)
2502
- }
2503
- }
2504
- console.log("")
2505
- } else {
2506
- console.log(`\n Unknown subcommand: /mcp ${sub} (use: install | status | test)\n`)
2507
- }
2508
- break
2509
- }
2510
- case "executor": {
2511
- const config = readConfig()
2512
- const key = config.apiKey ?? config.workspaceApiKey
2513
- const executor = config.executor ?? "claude_code"
2514
- const sub = args[0] ?? ""
2515
-
2516
- if (sub === "test") {
2517
- const exeEntry = EXECUTORS.find(e => e.id === executor)
2518
- if (!exeEntry) { console.log(`\n Unknown executor: ${executor}\n`); break }
2519
- if (!checkBinaryExists(exeEntry.bin)) {
2520
- console.log(`\n \x1b[31m✗\x1b[0m ${exeEntry.label} binary (\x1b[1m${exeEntry.bin}\x1b[0m) not found in PATH\n`)
2521
- break
2522
- }
2523
- console.log(`\n \x1b[2mSmoke-testing ${exeEntry.label}…\x1b[0m`)
2524
- const t0 = Date.now()
2525
- try {
2526
- const versionFlag = executor === "gemini" ? "--version" : "--version"
2527
- const result = execFileSync(exeEntry.bin, [versionFlag], { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "pipe"] }).trim()
2528
- const ms = Date.now() - t0
2529
- console.log(` \x1b[32m✓\x1b[0m ${exeEntry.label} is working \x1b[2m${result.split("\n")[0]} ${ms}ms\x1b[0m`)
2530
- } catch (e) {
2531
- console.log(` \x1b[31m✗\x1b[0m ${exeEntry.label} returned error: \x1b[2m${e.message?.split("\n")[0] ?? e.message}\x1b[0m`)
2532
- }
2533
- console.log("")
2534
- } else {
2535
- console.log(`\n \x1b[1m/executor\x1b[0m — executor tools\n`)
2536
- console.log(` \x1b[36m/executor test\x1b[0m \x1b[2m— smoke-test the configured executor binary\x1b[0m\n`)
2537
- }
2538
- break
2539
- }
2540
- case "whoami": {
2541
- const config = readConfig()
2542
- console.log("")
2543
- const key = config.apiKey ?? config.workspaceApiKey
2544
- console.log(` workspace \x1b[1m${config.workspaceSlug ?? config.workspaceId ?? "\x1b[2mnot set\x1b[0m"}\x1b[0m`)
2545
- console.log(` runner \x1b[1m${config.runnerName ?? "\x1b[2mnot set\x1b[0m"}\x1b[0m`)
2546
- console.log(` executor \x1b[1m${executorLabel(config.executor ?? "?")}\x1b[0m`)
2547
- console.log(` api key \x1b[2m${key ? key.slice(0, 20) + "…" : "not set"}\x1b[0m`)
2548
- console.log(` app url \x1b[2m${config.appUrl ?? "https://pacework.io"}\x1b[0m`)
2549
- console.log("")
2550
- break
2551
- }
2552
- case "rename": {
2553
- const newName = args.join(" ").trim()
2554
- if (!newName) { console.log(`Usage: rename <new name>`); break }
2555
- const config = readConfig()
2556
- config.runnerName = newName
2557
- writeConfig(config)
2558
- console.log(`\x1b[32m✓\x1b[0m Runner name set to \x1b[1m${newName}\x1b[0m — restart runner to push to dashboard`)
2559
- break
2560
- }
2561
- case "open": {
2562
- const config = readConfig()
2563
- const base = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2564
- const slug = config.workspaceSlug ?? config.workspaceId ?? ""
2565
- const issueId = args[0]
2566
- const url = issueId
2567
- ? (slug ? `${base}/${slug}/issue/${issueId.toUpperCase()}` : base)
2568
- : (slug ? `${base}/${slug}` : base)
2569
- console.log(`Opening \x1b[36m${url}\x1b[0m`)
2570
- const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open"
2571
- try { spawn(opener, [url], { stdio: "ignore", detached: true }).unref() }
2572
- catch { console.log(`Could not open browser automatically.`) }
2573
- break
2574
- }
2575
- case "update": {
2576
- await updateRunner()
2577
- break
2578
- }
2579
- case "login": {
2580
- const config = readConfig()
2581
- const key = config.apiKey ?? config.workspaceApiKey
2582
- const ws = config.workspaceSlug ?? config.workspaceId
2583
-
2584
- if (key && ws) {
2585
- const user = config.userName ?? config.userEmail ?? "unknown"
2586
- console.log(`\n \x1b[32m✓\x1b[0m Already logged in as \x1b[1m${user}\x1b[0m on \x1b[1m${ws}\x1b[0m`)
2587
- console.log(` Switch accounts? This will revoke the current API key.\n`)
2588
- // raw-mode y/n
2589
- const answer = await new Promise(resolve => {
2590
- process.stdout.write(` \x1b[36m[y/N]\x1b[0m `)
2591
- process.stdin.once("data", k => { process.stdout.write("\n"); resolve(k.toString().trim().toLowerCase()) })
2592
- })
2593
- if (answer !== "y") { console.log(" Keeping current session.\n"); break }
2594
-
2595
- // revoke existing key then fall through to login
2596
- try {
2597
- const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2598
- await fetch(`${appUrl}/api/cli/login`, {
2599
- method: "DELETE",
2600
- headers: { "content-type": "application/json" },
2601
- body: JSON.stringify({ apiKey: key }),
2602
- })
2603
- } catch {}
2604
- const fresh = {}
2605
- // stop daemon before switching accounts
2606
- const pid2 = readPid()
2607
- if (pid2 && isRunning(pid2)) { try { process.kill(pid2, "SIGTERM"); clearPid() } catch {} }
2608
- writeConfig({ appUrl: config.appUrl })
2609
- console.log(` \x1b[32m✓\x1b[0m Logged out. Starting login flow…\n`)
2610
- }
2611
-
2612
- // pause raw mode, run login as child, resume
2613
- process.stdin.setRawMode(false)
2614
- process.stdin.pause()
2615
- const loginChild = spawn(process.execPath, [fileURLToPath(import.meta.url), "login"], {
2616
- stdio: "inherit",
2617
- env: { ...process.env, PATH: process.env.PATH || "" },
2618
- })
2619
- await new Promise(r => loginChild.on("exit", r))
2620
- process.stdin.setRawMode(true)
2621
- process.stdin.resume()
2622
- // re-render to show new account
2623
- process.stdout.write("\x1b[2J\x1b[H")
2624
- printBanner(readConfig())
2625
- await printWelcome()
2626
- break
2627
- }
2628
- case "logout": {
2629
- const config = readConfig()
2630
- const key = config.apiKey ?? config.workspaceApiKey
2631
- if (!key) { console.log("\n Not logged in.\n"); break }
2632
- console.log(`\n Revoking API key and clearing credentials…`)
2633
-
2634
- // stop running daemon first
2635
- const pid = readPid()
2636
- if (pid && isRunning(pid)) {
2637
- try { process.kill(pid, "SIGTERM"); clearPid(); console.log(` \x1b[32m✓\x1b[0m Runner stopped`) }
2638
- catch {}
2639
- }
2640
-
2641
- try {
2642
- const appUrl = (config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
2643
- const res = await fetch(`${appUrl}/api/cli/login`, {
2644
- method: "DELETE",
2645
- headers: { "content-type": "application/json" },
2646
- body: JSON.stringify({ apiKey: key }),
2647
- })
2648
- if (res.ok) console.log(` \x1b[32m✓\x1b[0m API key revoked`)
2649
- else console.log(` \x1b[33m⚠\x1b[0m Server returned ${res.status} — clearing locally anyway`)
2650
- } catch { console.log(` \x1b[33m⚠\x1b[0m Could not reach server — clearing locally`) }
2651
-
2652
- // write a clean config — delete auth fields entirely
2653
- const clean = { appUrl: config.appUrl }
2654
- writeConfig(clean)
2655
- console.log(` \x1b[32m✓\x1b[0m Logged out\n`)
2656
-
2657
- // re-render banner + welcome to reflect logged-out state
2658
- process.stdout.write("\x1b[2J\x1b[H")
2659
- printBanner(readConfig())
2660
- await printWelcome()
2661
- break
2662
- }
2663
- case "connect": {
2664
- const config = readConfig()
2665
- const key = config.apiKey ?? config.workspaceApiKey
2666
- if (!key) { console.log("\n Not logged in — run /login first.\n"); break }
2667
- console.log(`\x1b[2mStarting runner in foreground — Ctrl+C to stop\x1b[0m\n`)
2668
- process.stdin.setRawMode(false)
2669
- process.stdin.pause()
2670
- const runnerArgs = buildRunnerArgs([])
2671
- const connChild = spawn(process.execPath, [path.resolve(__dirname, "pacework-runner.mjs"), ...runnerArgs], {
2672
- stdio: ["ignore", "pipe", "pipe"],
2673
- env: { ...process.env, PATH: process.env.PATH || "" },
2674
- })
2675
- const handleStream = (stream) => {
2676
- let buf = ""
2677
- stream.on("data", chunk => {
2678
- buf += chunk.toString()
2679
- const lines = buf.split("\n"); buf = lines.pop()
2680
- for (const l of lines) { const f = formatLogLine(l); if (f) process.stdout.write(f + "\n") }
2681
- })
2682
- }
2683
- handleStream(connChild.stdout)
2684
- handleStream(connChild.stderr)
2685
- const stopConn = () => connChild.kill("SIGTERM")
2686
- process.once("SIGINT", stopConn)
2687
- await new Promise(r => connChild.on("exit", r))
2688
- process.removeListener("SIGINT", stopConn)
2689
- process.stdin.setRawMode(true)
2690
- process.stdin.resume()
2691
- console.log("\x1b[2mRunner stopped.\x1b[0m\n")
2692
- break
2693
- }
2694
- case "pid": {
2695
- const pid = readPid()
2696
- if (pid && isRunning(pid)) {
2697
- let startedAt = ""
2698
- try { const c = JSON.parse(fs.readFileSync(CMD_FILE, "utf8")); startedAt = ` started ${relTime(c.startedAt)}` } catch {}
2699
- console.log(`\n \x1b[32m●\x1b[0m Runner PID \x1b[1m${pid}\x1b[0m${startedAt}\n`)
2700
- } else {
2701
- console.log(`\n \x1b[2m○ Runner is not running\x1b[0m\n`)
2702
- }
2703
- break
2704
- }
2705
- case "": break
2706
- default: {
2707
- console.log(`\x1b[31mUnknown command: ${cmd}\x1b[0m Type \x1b[36mhelp\x1b[0m for available commands.`)
2708
- }
2709
- }
2710
- }
2711
-
2712
1414
  if (oneShot !== null) {
2713
1415
  if (process.stdin.isTTY && parseShellInput(oneShot).command === "login") {
2714
1416
  process.stdin.setRawMode(true)
2715
1417
  process.stdin.resume()
2716
1418
  }
2717
1419
  try {
2718
- await runShellCommand(oneShot)
1420
+ const { ok } = await runShell(oneShot)
1421
+ if (!ok) process.exitCode = 1
2719
1422
  } finally {
2720
1423
  if (process.stdin.isTTY) process.stdin.setRawMode(false)
2721
1424
  process.stdin.pause()