pacework 1.0.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -16,6 +16,8 @@ import readline from "node:readline"
16
16
  import { spawn, execFileSync, execSync } from "node:child_process"
17
17
  import { fileURLToPath } from "node:url"
18
18
  import { agentSecretsFrom, detectSetupCommand } from "../lib/environment.mjs"
19
+ import { runTriageLoop } from "../lib/triage-worker.mjs"
20
+ import { EXECUTORS, EXECUTOR_DEFAULT_NAMES, checkBinaryExists, executorLabel } from "../lib/executors.mjs"
19
21
  import {
20
22
  PACEWORK_DIR,
21
23
  STATE_DIR,
@@ -30,6 +32,7 @@ import {
30
32
  clearPid,
31
33
  readConfig,
32
34
  writeConfig,
35
+ readRunnerSnapshot,
33
36
  } from "../lib/control-state.mjs"
34
37
  import {
35
38
  installService,
@@ -84,7 +87,9 @@ function printBanner(config) {
84
87
  const kv = (label, val) => ` \x1b[2m${label}\x1b[0m \x1b[1m${val}\x1b[0m`
85
88
 
86
89
  console.log("")
87
- console.log(BANNER)
90
+ // The big banner greets a machine that is not signed in yet; after that a
91
+ // one-line logo is enough, so status output stays short.
92
+ console.log(readConfig().apiKey ? ` \x1b[1m\x1b[38;5;39mpacework\x1b[0m \x1b[38;5;240mv${LOCAL_VERSION ?? "?"}\x1b[0m` : BANNER)
88
93
  console.log("")
89
94
 
90
95
  if (!config) { console.log(""); return }
@@ -146,35 +151,6 @@ function fmtDuration(ms) {
146
151
  return `${Math.floor(s / 60)}m${s % 60}s`
147
152
  }
148
153
 
149
- // ── executors ─────────────────────────────────────────────────────────────────
150
-
151
- const EXECUTORS = [
152
- { id: "claude_code", label: "Claude Code", bin: "claude" },
153
- { id: "codex", label: "Codex (OpenAI)", bin: "codex" },
154
- { id: "gemini", label: "Gemini CLI", bin: "gemini" },
155
- { id: "cursor_agent", label: "Cursor Agent", bin: "cursor" },
156
- { id: "github_copilot", label: "GitHub Copilot", bin: "gh" },
157
- ]
158
-
159
- const EXECUTOR_DEFAULT_NAMES = {
160
- claude_code: "Claude Dev",
161
- codex: "Codex Dev",
162
- gemini: "Gemini Dev",
163
- cursor_agent: "Cursor Dev",
164
- github_copilot: "Copilot Dev",
165
- }
166
-
167
- function checkBinaryExists(bin) {
168
- try {
169
- execFileSync(process.platform === "win32" ? "where" : "which", [bin], { stdio: "ignore" })
170
- return true
171
- } catch { return false }
172
- }
173
-
174
- function executorLabel(id) {
175
- return EXECUTORS.find(e => e.id === id)?.label ?? id
176
- }
177
-
178
154
  // ── login setup prompts ───────────────────────────────────────────────────────
179
155
 
180
156
  async function promptExecutorSetup() {
@@ -315,6 +291,18 @@ if (!command || command === "--help" || command === "-h") {
315
291
 
316
292
  // ── login ─────────────────────────────────────────────────────────────────────
317
293
 
294
+ if (command === "login" && process.stdin.isTTY && !parsedArgs["app-url"] && !parsedArgs["workspace-id"]) {
295
+ // Interactive: pick the server with arrow keys, sign in, and only ask for
296
+ // the folder and AI tool if they were never set.
297
+ const setup = await import("../lib/setup.mjs")
298
+ const { LOGO } = await import("../lib/ui.mjs")
299
+ if (!await setup.switchServer()) process.exit(0)
300
+ if (!readConfig().repoRoot) await setup.changeRepo()
301
+ if (!readConfig().executor) await setup.changeExecutor()
302
+ console.log(`\n${LOGO} Signed in. Run \x1b[1mpacework\x1b[0m to see the runner, or \x1b[1mpacework start\x1b[0m to start it.`)
303
+ process.exit(0)
304
+ }
305
+
318
306
  if (command === "login") {
319
307
  printBanner()
320
308
  const savedUrl = readConfig().appUrl
@@ -381,8 +369,8 @@ if (command === "login") {
381
369
  Config : \x1b[2m${CONFIG_FILE}\x1b[0m
382
370
 
383
371
  Start the runner:
384
- \x1b[36mpacework-runner connect\x1b[0m \x1b[2m# foreground\x1b[0m
385
- \x1b[36mpacework-runner start\x1b[0m \x1b[2m# background daemon\x1b[0m
372
+ \x1b[36mpacework start\x1b[0m \x1b[2m# in the background\x1b[0m
373
+ \x1b[36mpacework connect\x1b[0m \x1b[2m# in this terminal\x1b[0m
386
374
  `)
387
375
  process.exit(0)
388
376
  }
@@ -460,7 +448,7 @@ if (command === "use") {
460
448
  writeConfig(config)
461
449
 
462
450
  console.log(`\x1b[32m✓ Executor switched:\x1b[0m ${executorLabel(prev)} → \x1b[1m${executorLabel(target)}\x1b[0m`)
463
- console.log(` Restart the runner to apply: \x1b[36mpacework-runner connect\x1b[0m`)
451
+ console.log(` Restart the runner to apply: \x1b[36mpacework connect\x1b[0m`)
464
452
  process.exit(0)
465
453
  }
466
454
 
@@ -543,7 +531,7 @@ if (command === "doctor") {
543
531
  // Config
544
532
  const config = readConfig()
545
533
  if (config.apiKey) ok(`Config found (${CONFIG_FILE})`)
546
- else { err(`Not logged in — run \x1b[36mpacework-runner login\x1b[0m`); issues++ }
534
+ else { err(`Not logged in — run \x1b[36mpacework login\x1b[0m`); issues++ }
547
535
 
548
536
  if (config.workspaceSlug || config.workspaceId) ok(`Workspace: ${config.workspaceSlug ?? config.workspaceId}`)
549
537
  else { err("No workspace saved"); issues++ }
@@ -588,7 +576,7 @@ if (command === "doctor") {
588
576
  signal: AbortSignal.timeout(4000),
589
577
  })
590
578
  if (res.ok) ok("API key valid")
591
- else { err(`API key rejected (${res.status}) — run \x1b[36mpacework-runner login\x1b[0m`); issues++ }
579
+ else { err(`API key rejected (${res.status}) — run \x1b[36mpacework login\x1b[0m`); issues++ }
592
580
  } catch { warn("Could not verify API key (server unreachable)") }
593
581
  }
594
582
 
@@ -1039,6 +1027,12 @@ else if (command === "stop") {
1039
1027
  // ── status ────────────────────────────────────────────────────────────────────
1040
1028
 
1041
1029
  else if (command === "status") {
1030
+ if (parsedArgs.json) {
1031
+ // For scripts: the same facts as the home screen, without the raw log or the key.
1032
+ const { logs, ...snapshot } = readRunnerSnapshot({ logLines: 400 })
1033
+ console.log(JSON.stringify({ ...snapshot, signedIn: Boolean(readConfig().apiKey), serviceInstalled: isServiceInstalled(), version: LOCAL_VERSION ?? null }, null, 2))
1034
+ process.exit(0)
1035
+ }
1042
1036
  const pid = readPid()
1043
1037
  const config = readConfig()
1044
1038
 
@@ -1115,155 +1109,42 @@ else if (command === "triage") {
1115
1109
  console.error("\x1b[31mNot logged in.\x1b[0m Run \x1b[36mpacework login\x1b[0m first (or pass --app-url and --api-key).")
1116
1110
  process.exit(1)
1117
1111
  }
1118
-
1119
- const pollIntervalMs = Math.max(2000, Number(parsedArgs["poll-interval-ms"] || process.env.TRIAGE_RUNNER_POLL_INTERVAL_MS || 5000))
1120
- const claudeTimeoutMs = Math.max(30_000, Number(parsedArgs["claude-timeout-ms"] || process.env.TRIAGE_RUNNER_CLAUDE_TIMEOUT_MS || 240_000))
1121
- const claudeBinary = parsedArgs["claude-bin"] || process.env.TRIAGE_RUNNER_CLAUDE_BIN || "claude"
1122
- const claudeModel = parsedArgs.model || process.env.TRIAGE_RUNNER_CLAUDE_MODEL || null
1123
- const triageRunnerName = parsedArgs.name || process.env.TRIAGE_RUNNER_NAME || `${os.hostname()} triage`
1124
- const runOnce = (parsedArgs.once || "").toLowerCase() === "true"
1125
- // Executor: same choice the agent runner uses (pacework login saves it).
1126
- // claude_code and codex use the subscription-billed CLI; gemini its own.
1127
- const triageExecutor = (parsedArgs.executor || config.executor || "claude_code").trim()
1128
- const codexBinary = parsedArgs["codex-bin"] || process.env.CODEX_BIN || "codex"
1129
- const geminiBinary = parsedArgs["gemini-bin"] || process.env.GEMINI_BIN || "gemini"
1130
-
1131
- const triageLog = (message) => console.log(`\x1b[2m[${new Date().toISOString()}]\x1b[0m ${message}`)
1132
-
1133
- const triageApi = async (route, body) => {
1134
- const res = await fetch(`${appUrl}${route}`, {
1135
- method: "POST",
1136
- headers: { "content-type": "application/json", authorization: `Bearer ${apiKey}` },
1137
- body: JSON.stringify(body),
1138
- })
1139
- const text = await res.text()
1140
- let payload = null
1141
- try { payload = text ? JSON.parse(text) : null } catch { payload = { error: text.slice(0, 300) } }
1142
- return { status: res.status, payload }
1143
- }
1144
-
1145
- const buildTriageExecSpec = (prompt) => {
1146
- if (triageExecutor === "codex") {
1147
- const outputFile = path.join(os.tmpdir(), `pacework-triage-${Date.now()}-${Math.random().toString(36).slice(2)}.txt`)
1148
- // Completion jobs must only return text to the pacework tool loop.
1149
- // Loading the user's normal Codex config also loads their MCP
1150
- // servers, allowing this interpreter process to execute mutations
1151
- // itself (and potentially call a stale/remote pacework endpoint).
1152
- const cliArgs = ["exec", "--ignore-user-config", "--ignore-rules", "--sandbox", "read-only"]
1153
- if (claudeModel) cliArgs.push("-m", claudeModel)
1154
- cliArgs.push(
1155
- "--ephemeral",
1156
- "--color", "never",
1157
- "--skip-git-repo-check",
1158
- "--output-last-message", outputFile,
1159
- "-",
1160
- )
1161
- return { command: codexBinary, args: cliArgs, stdinPayload: prompt, outputFile }
1162
- }
1163
- if (triageExecutor === "gemini") {
1164
- const cliArgs = ["-p", prompt, "--output-format", "text"]
1165
- if (claudeModel) cliArgs.push("--model", claudeModel)
1166
- return { command: geminiBinary, args: cliArgs, stdinPayload: null, outputFile: null }
1167
- }
1168
- // claude_code (default)
1169
- // As above, give completion jobs no tools and an explicitly empty MCP
1170
- // config. The outer pacework Slack agent owns all tool execution.
1171
- const cliArgs = [
1172
- "-p",
1173
- "--output-format", "text",
1174
- "--strict-mcp-config",
1175
- "--mcp-config", '{"mcpServers":{}}',
1176
- "--tools", "",
1177
- ]
1178
- if (claudeModel) cliArgs.push("--model", claudeModel)
1179
- return { command: claudeBinary, args: cliArgs, stdinPayload: prompt, outputFile: null }
1180
- }
1181
-
1182
- const runExecutorPrompt = (prompt) => new Promise((resolve, reject) => {
1183
- const spec = buildTriageExecSpec(prompt)
1184
- const child = spawn(spec.command, spec.args, { stdio: ["pipe", "pipe", "pipe"], env: process.env })
1185
- let stdout = ""
1186
- let stderr = ""
1187
- const timer = setTimeout(() => {
1188
- child.kill("SIGKILL")
1189
- reject(new Error(`${spec.command} timed out after ${Math.round(claudeTimeoutMs / 1000)}s`))
1190
- }, claudeTimeoutMs)
1191
- const readResult = () => {
1192
- // Codex writes the final answer to a file; the others stream stdout.
1193
- if (spec.outputFile) {
1194
- try {
1195
- const fileText = fs.readFileSync(spec.outputFile, "utf8").trim()
1196
- fs.unlinkSync(spec.outputFile)
1197
- return fileText
1198
- } catch {
1199
- return ""
1200
- }
1201
- }
1202
- return stdout.trim()
1203
- }
1204
- child.stdout.on("data", (chunk) => { stdout += chunk })
1205
- child.stderr.on("data", (chunk) => { stderr += chunk })
1206
- child.on("error", (error) => {
1207
- clearTimeout(timer)
1208
- reject(error.code === "ENOENT"
1209
- ? new Error(`Could not find the "${spec.command}" CLI for executor ${triageExecutor}. Install it or pass --claude-bin/--codex-bin/--gemini-bin.`)
1210
- : error)
1211
- })
1212
- child.on("close", (code) => {
1213
- clearTimeout(timer)
1214
- const text = code === 0 ? readResult() : ""
1215
- if (code === 0 && text) resolve(text)
1216
- else reject(new Error(`${spec.command} exited with code ${code}: ${stderr.trim().slice(0, 400) || "no output"}`))
1217
- })
1218
- if (spec.stdinPayload !== null) child.stdin.write(spec.stdinPayload)
1219
- child.stdin.end()
1220
- })
1221
-
1222
- const processTriageJob = async (job) => {
1223
- triageLog(`Job ${job.id} claimed; running ${triageExecutor}${claudeModel ? ` (${claudeModel})` : ""}...`)
1224
- try {
1225
- const text = await runExecutorPrompt(job.prompt)
1226
- const complete = await triageApi(`/api/triage-runner/jobs/${job.id}/complete`, {
1227
- text,
1228
- model: `${triageExecutor}${claudeModel ? `:${claudeModel}` : ""}`,
1229
- })
1230
- if (complete.status >= 400) {
1231
- triageLog(`\x1b[31mJob ${job.id}: server rejected completion (${complete.status}): ${JSON.stringify(complete.payload)}\x1b[0m`)
1232
- } else {
1233
- triageLog(`\x1b[32mJob ${job.id} completed\x1b[0m (confidence: ${complete.payload?.confidence ?? "n/a"})`)
1234
- }
1235
- } catch (error) {
1236
- const message = error instanceof Error ? error.message : String(error)
1237
- triageLog(`\x1b[31mJob ${job.id} failed: ${message}\x1b[0m`)
1238
- await triageApi(`/api/triage-runner/jobs/${job.id}/fail`, { error: message }).catch(() => {})
1239
- }
1240
- }
1241
-
1242
- triageLog(`Triage runner "${triageRunnerName}" polling ${appUrl} every ${pollIntervalMs / 1000}s (executor: ${triageExecutor})`)
1243
- let triageStopping = false
1244
- process.on("SIGINT", () => { triageStopping = true; triageLog("Stopping after current poll...") })
1245
- process.on("SIGTERM", () => { triageStopping = true })
1246
-
1247
- while (!triageStopping) {
1248
- try {
1249
- const claim = await triageApi("/api/triage-runner/claim", { runner_name: triageRunnerName })
1250
- if (claim.status === 401 || claim.status === 403) {
1251
- console.error(`\x1b[31mAuthentication failed (${claim.status}).\x1b[0m Run \x1b[36mpacework login\x1b[0m again.`)
1112
+ // The background runner already does triage alongside development work;
1113
+ // this runs triage on its own, in the foreground.
1114
+ const executor = (parsedArgs.executor || config.executor || "claude_code").trim()
1115
+ const log = (message) => console.log(`\x1b[2m[${new Date().toISOString()}]\x1b[0m ${message}`)
1116
+ let stopping = false
1117
+ process.on("SIGINT", () => { stopping = true; log("Stopping after current poll...") })
1118
+ process.on("SIGTERM", () => { stopping = true })
1119
+
1120
+ await runTriageLoop({
1121
+ appUrl,
1122
+ apiKey,
1123
+ executor,
1124
+ model: parsedArgs.model || process.env.TRIAGE_RUNNER_CLAUDE_MODEL || null,
1125
+ runnerName: parsedArgs.name || process.env.TRIAGE_RUNNER_NAME || `${os.hostname()} triage`,
1126
+ pollIntervalMs: Math.max(2000, Number(parsedArgs["poll-interval-ms"] || process.env.TRIAGE_RUNNER_POLL_INTERVAL_MS || 5000)),
1127
+ timeoutMs: Math.max(30_000, Number(parsedArgs["claude-timeout-ms"] || process.env.TRIAGE_RUNNER_CLAUDE_TIMEOUT_MS || 240_000)),
1128
+ binaries: {
1129
+ claude: parsedArgs["claude-bin"] || process.env.TRIAGE_RUNNER_CLAUDE_BIN,
1130
+ codex: parsedArgs["codex-bin"] || process.env.CODEX_BIN,
1131
+ gemini: parsedArgs["gemini-bin"] || process.env.GEMINI_BIN,
1132
+ },
1133
+ once: (parsedArgs.once || "").toLowerCase() === "true",
1134
+ shouldStop: () => stopping,
1135
+ report: (event, details) => {
1136
+ if (event === "started") log(`Triage runner "${details.runnerName}" polling ${appUrl} every ${details.pollIntervalMs / 1000}s (executor: ${details.executor})`)
1137
+ else if (event === "claimed") log(`Job ${details.job.id} claimed; running ${executor}...`)
1138
+ else if (event === "completed") log(`\x1b[32mJob ${details.job.id} completed\x1b[0m (confidence: ${details.confidence ?? "n/a"})`)
1139
+ else if (event === "rejected") log(`\x1b[31mJob ${details.job.id}: server rejected completion (${details.status}): ${JSON.stringify(details.payload)}\x1b[0m`)
1140
+ else if (event === "failed") log(`\x1b[31mJob ${details.job.id} failed: ${details.message}\x1b[0m`)
1141
+ else if (event === "poll_error") log(`Poll error: ${details.message}`)
1142
+ else if (event === "auth_failed") {
1143
+ console.error(`\x1b[31mAuthentication failed (${details.status}).\x1b[0m Run \x1b[36mpacework login\x1b[0m again.`)
1252
1144
  process.exit(1)
1253
1145
  }
1254
- if (claim.status >= 400) {
1255
- triageLog(`Claim failed (${claim.status}): ${JSON.stringify(claim.payload)}`)
1256
- } else if (claim.payload?.job) {
1257
- await processTriageJob(claim.payload.job)
1258
- if (runOnce) break
1259
- continue
1260
- }
1261
- } catch (error) {
1262
- triageLog(`Poll error: ${error instanceof Error ? error.message : String(error)}`)
1263
- }
1264
- if (runOnce) break
1265
- await new Promise((resolve) => setTimeout(resolve, pollIntervalMs))
1266
- }
1146
+ },
1147
+ })
1267
1148
  process.exit(0)
1268
1149
  }
1269
1150
 
@@ -1274,125 +1155,21 @@ else if (command === "triage") {
1274
1155
  // Every action shells out to this same CLI, so menu and commands never drift.
1275
1156
 
1276
1157
  else if (command === "menu") {
1277
- const runChild = (childArgs) => new Promise((resolve) => {
1278
- const child = spawn(process.execPath, [process.argv[1], ...childArgs], { stdio: "inherit" })
1279
- child.on("close", () => resolve())
1280
- child.on("error", () => resolve())
1158
+ // `pacework` in a terminal: guided setup the first time, then the live home
1159
+ // screen. Both load the prompt library lazily, so the background service,
1160
+ // which never comes through here, does not depend on it.
1161
+ const { runSetup } = await import("../lib/setup.mjs")
1162
+ const { runHome } = await import("../lib/home.mjs")
1163
+ const ctlScript = fileURLToPath(import.meta.url)
1164
+ const startRunner = () => new Promise((resolve) => {
1165
+ const child = spawn(process.execPath, [ctlScript, "start"], { stdio: "ignore" })
1166
+ child.on("close", (code) => resolve(code === 0))
1167
+ child.on("error", () => resolve(false))
1281
1168
  })
1282
-
1283
- const choose = async (question, options, defaultIndex = 0) => {
1284
- console.log("")
1285
- options.forEach((option, index) => {
1286
- const marker = index === defaultIndex ? "\x1b[36m" : ""
1287
- console.log(` ${marker}${index + 1}. ${option}\x1b[0m`)
1288
- })
1289
- const answer = (await promptLine(`${question} (default ${defaultIndex + 1}, q to cancel): `)).trim()
1290
- if (/^q(uit)?$/i.test(answer)) return -1
1291
- const picked = answer ? Number(answer) - 1 : defaultIndex
1292
- return Number.isInteger(picked) && picked >= 0 && picked < options.length ? picked : defaultIndex
1293
- }
1294
-
1295
- const TRIAGE_MODELS = {
1296
- claude_code: ["CLI default", "haiku", "sonnet", "opus"],
1297
- codex: ["CLI default", "gpt-5.5", "gpt-5.5-pro"],
1298
- gemini: ["CLI default", "gemini-2.5-flash", "gemini-2.5-pro"],
1299
- }
1300
-
1301
- const guidedTriage = async (config) => {
1302
- const executors = ["claude_code", "codex", "gemini"]
1303
- const executorLabels = {
1304
- claude_code: "Claude Code (Claude subscription)",
1305
- codex: "Codex (ChatGPT subscription)",
1306
- gemini: "Gemini CLI",
1307
- }
1308
- const defaultExecutorIndex = Math.max(0, executors.indexOf(config.executor))
1309
- const executorIndex = await choose(
1310
- "Which AI runs triage jobs?",
1311
- executors.map((name) => executorLabels[name]),
1312
- defaultExecutorIndex,
1313
- )
1314
- if (executorIndex < 0) return
1315
- const executor = executors[executorIndex]
1316
-
1317
- const models = TRIAGE_MODELS[executor] ?? ["CLI default"]
1318
- const modelIndex = await choose("Which model?", models, 0)
1319
- if (modelIndex < 0) return
1320
- const model = modelIndex === 0 ? null : models[modelIndex]
1321
-
1322
- const modeIndex = await choose("How should it run?", [
1323
- "Keep running (poll for jobs until Ctrl-C)",
1324
- "Process one job, then exit",
1325
- ], 0)
1326
- if (modeIndex < 0) return
1327
-
1328
- const childArgs = ["triage", "--executor", executor]
1329
- if (model) childArgs.push("--model", model)
1330
- if (modeIndex === 1) childArgs.push("--once", "true")
1331
- console.log(`\n\x1b[2m→ pacework triage ${childArgs.slice(1).join(" ")}\x1b[0m\n`)
1332
- await runChild(childArgs)
1333
- }
1334
-
1335
- const guidedAgentRunner = async () => {
1336
- const modeIndex = await choose("How should the agent runner run?", [
1337
- "Background daemon (keeps running after this menu closes)",
1338
- "Foreground (watch output, Ctrl-C to stop)",
1339
- ], 0)
1340
- if (modeIndex < 0) return
1341
- await runChild([modeIndex === 0 ? "start" : "connect"])
1342
- }
1343
-
1344
- let menuRunning = true
1345
- while (menuRunning) {
1346
- const config = readConfig()
1347
- console.clear()
1348
- printBanner(config)
1349
- if (config.apiKey) {
1350
- console.log(` Workspace: \x1b[1m${config.workspaceSlug ?? config.workspaceId ?? "?"}\x1b[0m Executor: \x1b[1m${executorLabel(config.executor) ?? config.executor ?? "not set"}\x1b[0m`)
1351
- } else {
1352
- console.log(" \x1b[33mNot logged in yet — pick “Log in” to get started.\x1b[0m")
1353
- }
1354
-
1355
- const loggedIn = Boolean(config.apiKey)
1356
- const entries = loggedIn
1357
- ? [
1358
- { label: "Run triage (pacework Intelligence on this machine)", action: () => guidedTriage(config) },
1359
- { label: "Run the agent runner (works on issues)", action: guidedAgentRunner },
1360
- { label: "Status", action: () => runChild(["status"]) },
1361
- { label: "Recent jobs", action: () => runChild(["jobs"]) },
1362
- { label: "Tail runner logs", action: () => runChild(["logs"]) },
1363
- { label: "Stop background runner", action: () => runChild(["stop"]) },
1364
- { label: "Health check (doctor)", action: () => runChild(["doctor"]) },
1365
- { label: "Switch executor", action: async () => {
1366
- const executorIndex = await choose(
1367
- "Which executor?",
1368
- EXECUTORS.map((executor) => `${executor.label}${checkBinaryExists(executor.bin) ? "" : " (not installed)"}`),
1369
- Math.max(0, EXECUTORS.findIndex((executor) => executor.id === config.executor)),
1370
- )
1371
- if (executorIndex < 0) return
1372
- await runChild(["use", EXECUTORS[executorIndex].id])
1373
- } },
1374
- { label: "Log in again / switch server or workspace", action: () => runChild(["login"]) },
1375
- { label: "Log out", action: () => runChild(["logout"]) },
1376
- { label: "Quit", action: null },
1377
- ]
1378
- : [
1379
- { label: "Log in (opens your browser)", action: () => runChild(["login"]) },
1380
- { label: "Status", action: () => runChild(["status"]) },
1381
- { label: "Quit", action: null },
1382
- ]
1383
-
1384
- const pickedIndex = await choose("What do you want to do?", entries.map((entry) => entry.label), 0)
1385
- const picked = pickedIndex < 0 ? entries[entries.length - 1] : entries[pickedIndex]
1386
- if (!picked.action) {
1387
- menuRunning = false
1388
- break
1389
- }
1390
- await picked.action()
1391
- if (menuRunning) {
1392
- await promptLine("\n\x1b[2mPress Enter to return to the menu…\x1b[0m")
1393
- }
1169
+ if (!readConfig().apiKey) {
1170
+ if (!await runSetup({ startRunner })) process.exit(0)
1394
1171
  }
1395
- process.exit(0)
1172
+ await runHome({ ctlScript, version: LOCAL_VERSION })
1396
1173
  }
1397
1174
 
1398
1175
  else if (command === "shell" || command === "sh") {
@@ -11,6 +11,7 @@ import { AsyncLocalStorage } from "node:async_hooks"
11
11
  import { createLogger } from "../lib/logger.mjs"
12
12
  import { detectUsageLimit } from "../lib/usage-limit.mjs"
13
13
  import { prepareRunEnvironment } from "../lib/environment.mjs"
14
+ import { runTriageLoop, TRIAGE_EXECUTORS } from "../lib/triage-worker.mjs"
14
15
 
15
16
  function parseArgs(argv) {
16
17
  const args = {}
@@ -74,6 +75,8 @@ const SANDBOX_ALLOWED_DOMAINS = (args["sandbox-allow-domains"] || process.env.RU
74
75
  || "registry.npmjs.org,registry.yarnpkg.com,pypi.org,files.pythonhosted.org,github.com,api.github.com,codeload.github.com,objects.githubusercontent.com")
75
76
  .split(",").map((domain) => domain.trim()).filter(Boolean)
76
77
  const registerOnly = (args["register-only"] || "").toLowerCase() === "true"
78
+ /** Triage jobs run alongside development work unless turned off (--no-triage, RUNNER_TRIAGE=off). */
79
+ const triageEnabled = !args["no-triage"] && String(process.env.RUNNER_TRIAGE || "").toLowerCase() !== "off"
77
80
  /**
78
81
  * Set by `pacework run-cloud` in a GitHub Actions job: a registration bound
79
82
  * to the one run the job was started for. The runner uses it as is — no state
@@ -3692,6 +3695,34 @@ async function main() {
3692
3695
  process.on("SIGINT", stop)
3693
3696
  process.on("SIGTERM", stop)
3694
3697
 
3698
+ // One runner takes both kinds of work: development jobs in the loop below,
3699
+ // and pacework Intelligence triage beside it (short, tool-less prompts), so
3700
+ // what a job needs is decided by the agent on the server, not by which
3701
+ // process someone remembered to start.
3702
+ if (!cloudState && triageEnabled && workspaceApiKey) {
3703
+ const triageLogger = () => getRunnerLogger(state)
3704
+ if (TRIAGE_EXECUTORS.includes(defaultExecutor)) {
3705
+ const jobMeta = (job, extra = {}) => ({ meta: { run_id: job.id, task_identifier: "Triage", task_title: "Triage a request", request_id: job.request_id, ...extra } })
3706
+ runTriageLoop({
3707
+ appUrl,
3708
+ apiKey: workspaceApiKey,
3709
+ executor: defaultExecutor,
3710
+ runnerName: `${runnerName} (triage)`,
3711
+ shouldStop: () => shuttingDown,
3712
+ report: (event, details) => {
3713
+ if (event === "started") triageLogger().info("runner.triage.ready", "Taking triage jobs too")
3714
+ else if (event === "claimed") triageLogger().info("runner.job.start", "Triage job started", jobMeta(details.job))
3715
+ else if (event === "completed") triageLogger().info("runner.job.complete", "Triage job completed", jobMeta(details.job, { duration_ms: details.durationMs, confidence: details.confidence }))
3716
+ else if (event === "rejected") triageLogger().error("runner.job.error", `Triage result rejected (${details.status})`, jobMeta(details.job, { duration_ms: details.durationMs }))
3717
+ else if (event === "failed") triageLogger().error("runner.job.error", details.message, jobMeta(details.job, { duration_ms: details.durationMs }))
3718
+ else if (event === "auth_failed") triageLogger().warn("runner.triage.auth_failed", `Triage polling stopped: the server rejected this runner's key (${details.status})`)
3719
+ },
3720
+ }).catch((error) => triageLogger().warn("runner.triage.stopped", "Triage polling stopped", undefined, error))
3721
+ } else {
3722
+ triageLogger().info("runner.triage.unsupported", "Triage needs Claude Code, Codex or Gemini; this runner takes development jobs only")
3723
+ }
3724
+ }
3725
+
3695
3726
  while (!shuttingDown) {
3696
3727
  const runnerStatus = activeRuns.size > 0 ? "busy" : "online"
3697
3728
  await heartbeatAndSync(runnerStatus)
@@ -0,0 +1,29 @@
1
+ import { execFileSync } from "node:child_process"
2
+
3
+ /** The AI coding tools a runner can drive, and the command each one needs on PATH. */
4
+ export const EXECUTORS = [
5
+ { id: "claude_code", label: "Claude Code", bin: "claude" },
6
+ { id: "codex", label: "Codex (OpenAI)", bin: "codex" },
7
+ { id: "gemini", label: "Gemini CLI", bin: "gemini" },
8
+ { id: "cursor_agent", label: "Cursor Agent", bin: "cursor" },
9
+ { id: "github_copilot", label: "GitHub Copilot", bin: "gh" },
10
+ ]
11
+
12
+ export const EXECUTOR_DEFAULT_NAMES = {
13
+ claude_code: "Claude Dev",
14
+ codex: "Codex Dev",
15
+ gemini: "Gemini Dev",
16
+ cursor_agent: "Cursor Dev",
17
+ github_copilot: "Copilot Dev",
18
+ }
19
+
20
+ export function checkBinaryExists(bin) {
21
+ try {
22
+ execFileSync(process.platform === "win32" ? "where" : "which", [bin], { stdio: "ignore" })
23
+ return true
24
+ } catch { return false }
25
+ }
26
+
27
+ export function executorLabel(id) {
28
+ return EXECUTORS.find(e => e.id === id)?.label ?? id
29
+ }