pacework 1.0.1 → 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() {
@@ -243,6 +219,11 @@ function parseCliArgs(argv) {
243
219
  const token = argv[i]
244
220
  if (token.startsWith("--")) {
245
221
  const key = token.slice(2)
222
+ if (key.includes("=")) {
223
+ const at = key.indexOf("=")
224
+ result[key.slice(0, at)] = key.slice(at + 1)
225
+ continue
226
+ }
246
227
  const next = argv[i + 1]
247
228
  if (next && !next.startsWith("--")) { result[key] = next; i++ }
248
229
  else result[key] = "true"
@@ -310,9 +291,29 @@ if (!command || command === "--help" || command === "-h") {
310
291
 
311
292
  // ── login ─────────────────────────────────────────────────────────────────────
312
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
+
313
306
  if (command === "login") {
314
307
  printBanner()
315
- const appUrl = parsedArgs["app-url"] || readConfig().appUrl || "https://pacework.io"
308
+ const savedUrl = readConfig().appUrl
309
+ let requestedUrl = parsedArgs["app-url"]
310
+ // A bare `login` (also what the menu runs) asks which server to use, so a
311
+ // saved URL, such as a local dev server, cannot pin every later login to it.
312
+ if (!requestedUrl && process.stdin.isTTY) {
313
+ requestedUrl = await promptLine(`pacework address [${savedUrl || "https://pacework.io"}]: `) || savedUrl
314
+ }
315
+ requestedUrl = String(requestedUrl || "https://pacework.io").trim().replace(/\/+$/, "")
316
+ const appUrl = /^https?:\/\//.test(requestedUrl) ? requestedUrl : `https://${requestedUrl}`
316
317
  console.log("Opening browser for authentication…")
317
318
 
318
319
  let token, loginUrl
@@ -368,8 +369,8 @@ if (command === "login") {
368
369
  Config : \x1b[2m${CONFIG_FILE}\x1b[0m
369
370
 
370
371
  Start the runner:
371
- \x1b[36mpacework-runner connect\x1b[0m \x1b[2m# foreground\x1b[0m
372
- \x1b[36mpacework-runner start\x1b[0m \x1b[2m# background daemon\x1b[0m
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
373
374
  `)
374
375
  process.exit(0)
375
376
  }
@@ -447,7 +448,7 @@ if (command === "use") {
447
448
  writeConfig(config)
448
449
 
449
450
  console.log(`\x1b[32m✓ Executor switched:\x1b[0m ${executorLabel(prev)} → \x1b[1m${executorLabel(target)}\x1b[0m`)
450
- console.log(` Restart the runner to apply: \x1b[36mpacework-runner connect\x1b[0m`)
451
+ console.log(` Restart the runner to apply: \x1b[36mpacework connect\x1b[0m`)
451
452
  process.exit(0)
452
453
  }
453
454
 
@@ -530,7 +531,7 @@ if (command === "doctor") {
530
531
  // Config
531
532
  const config = readConfig()
532
533
  if (config.apiKey) ok(`Config found (${CONFIG_FILE})`)
533
- 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++ }
534
535
 
535
536
  if (config.workspaceSlug || config.workspaceId) ok(`Workspace: ${config.workspaceSlug ?? config.workspaceId}`)
536
537
  else { err("No workspace saved"); issues++ }
@@ -575,7 +576,7 @@ if (command === "doctor") {
575
576
  signal: AbortSignal.timeout(4000),
576
577
  })
577
578
  if (res.ok) ok("API key valid")
578
- 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++ }
579
580
  } catch { warn("Could not verify API key (server unreachable)") }
580
581
  }
581
582
 
@@ -1026,6 +1027,12 @@ else if (command === "stop") {
1026
1027
  // ── status ────────────────────────────────────────────────────────────────────
1027
1028
 
1028
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
+ }
1029
1036
  const pid = readPid()
1030
1037
  const config = readConfig()
1031
1038
 
@@ -1102,155 +1109,42 @@ else if (command === "triage") {
1102
1109
  console.error("\x1b[31mNot logged in.\x1b[0m Run \x1b[36mpacework login\x1b[0m first (or pass --app-url and --api-key).")
1103
1110
  process.exit(1)
1104
1111
  }
1105
-
1106
- const pollIntervalMs = Math.max(2000, Number(parsedArgs["poll-interval-ms"] || process.env.TRIAGE_RUNNER_POLL_INTERVAL_MS || 5000))
1107
- const claudeTimeoutMs = Math.max(30_000, Number(parsedArgs["claude-timeout-ms"] || process.env.TRIAGE_RUNNER_CLAUDE_TIMEOUT_MS || 240_000))
1108
- const claudeBinary = parsedArgs["claude-bin"] || process.env.TRIAGE_RUNNER_CLAUDE_BIN || "claude"
1109
- const claudeModel = parsedArgs.model || process.env.TRIAGE_RUNNER_CLAUDE_MODEL || null
1110
- const triageRunnerName = parsedArgs.name || process.env.TRIAGE_RUNNER_NAME || `${os.hostname()} triage`
1111
- const runOnce = (parsedArgs.once || "").toLowerCase() === "true"
1112
- // Executor: same choice the agent runner uses (pacework login saves it).
1113
- // claude_code and codex use the subscription-billed CLI; gemini its own.
1114
- const triageExecutor = (parsedArgs.executor || config.executor || "claude_code").trim()
1115
- const codexBinary = parsedArgs["codex-bin"] || process.env.CODEX_BIN || "codex"
1116
- const geminiBinary = parsedArgs["gemini-bin"] || process.env.GEMINI_BIN || "gemini"
1117
-
1118
- const triageLog = (message) => console.log(`\x1b[2m[${new Date().toISOString()}]\x1b[0m ${message}`)
1119
-
1120
- const triageApi = async (route, body) => {
1121
- const res = await fetch(`${appUrl}${route}`, {
1122
- method: "POST",
1123
- headers: { "content-type": "application/json", authorization: `Bearer ${apiKey}` },
1124
- body: JSON.stringify(body),
1125
- })
1126
- const text = await res.text()
1127
- let payload = null
1128
- try { payload = text ? JSON.parse(text) : null } catch { payload = { error: text.slice(0, 300) } }
1129
- return { status: res.status, payload }
1130
- }
1131
-
1132
- const buildTriageExecSpec = (prompt) => {
1133
- if (triageExecutor === "codex") {
1134
- const outputFile = path.join(os.tmpdir(), `pacework-triage-${Date.now()}-${Math.random().toString(36).slice(2)}.txt`)
1135
- // Completion jobs must only return text to the pacework tool loop.
1136
- // Loading the user's normal Codex config also loads their MCP
1137
- // servers, allowing this interpreter process to execute mutations
1138
- // itself (and potentially call a stale/remote pacework endpoint).
1139
- const cliArgs = ["exec", "--ignore-user-config", "--ignore-rules", "--sandbox", "read-only"]
1140
- if (claudeModel) cliArgs.push("-m", claudeModel)
1141
- cliArgs.push(
1142
- "--ephemeral",
1143
- "--color", "never",
1144
- "--skip-git-repo-check",
1145
- "--output-last-message", outputFile,
1146
- "-",
1147
- )
1148
- return { command: codexBinary, args: cliArgs, stdinPayload: prompt, outputFile }
1149
- }
1150
- if (triageExecutor === "gemini") {
1151
- const cliArgs = ["-p", prompt, "--output-format", "text"]
1152
- if (claudeModel) cliArgs.push("--model", claudeModel)
1153
- return { command: geminiBinary, args: cliArgs, stdinPayload: null, outputFile: null }
1154
- }
1155
- // claude_code (default)
1156
- // As above, give completion jobs no tools and an explicitly empty MCP
1157
- // config. The outer pacework Slack agent owns all tool execution.
1158
- const cliArgs = [
1159
- "-p",
1160
- "--output-format", "text",
1161
- "--strict-mcp-config",
1162
- "--mcp-config", '{"mcpServers":{}}',
1163
- "--tools", "",
1164
- ]
1165
- if (claudeModel) cliArgs.push("--model", claudeModel)
1166
- return { command: claudeBinary, args: cliArgs, stdinPayload: prompt, outputFile: null }
1167
- }
1168
-
1169
- const runExecutorPrompt = (prompt) => new Promise((resolve, reject) => {
1170
- const spec = buildTriageExecSpec(prompt)
1171
- const child = spawn(spec.command, spec.args, { stdio: ["pipe", "pipe", "pipe"], env: process.env })
1172
- let stdout = ""
1173
- let stderr = ""
1174
- const timer = setTimeout(() => {
1175
- child.kill("SIGKILL")
1176
- reject(new Error(`${spec.command} timed out after ${Math.round(claudeTimeoutMs / 1000)}s`))
1177
- }, claudeTimeoutMs)
1178
- const readResult = () => {
1179
- // Codex writes the final answer to a file; the others stream stdout.
1180
- if (spec.outputFile) {
1181
- try {
1182
- const fileText = fs.readFileSync(spec.outputFile, "utf8").trim()
1183
- fs.unlinkSync(spec.outputFile)
1184
- return fileText
1185
- } catch {
1186
- return ""
1187
- }
1188
- }
1189
- return stdout.trim()
1190
- }
1191
- child.stdout.on("data", (chunk) => { stdout += chunk })
1192
- child.stderr.on("data", (chunk) => { stderr += chunk })
1193
- child.on("error", (error) => {
1194
- clearTimeout(timer)
1195
- reject(error.code === "ENOENT"
1196
- ? new Error(`Could not find the "${spec.command}" CLI for executor ${triageExecutor}. Install it or pass --claude-bin/--codex-bin/--gemini-bin.`)
1197
- : error)
1198
- })
1199
- child.on("close", (code) => {
1200
- clearTimeout(timer)
1201
- const text = code === 0 ? readResult() : ""
1202
- if (code === 0 && text) resolve(text)
1203
- else reject(new Error(`${spec.command} exited with code ${code}: ${stderr.trim().slice(0, 400) || "no output"}`))
1204
- })
1205
- if (spec.stdinPayload !== null) child.stdin.write(spec.stdinPayload)
1206
- child.stdin.end()
1207
- })
1208
-
1209
- const processTriageJob = async (job) => {
1210
- triageLog(`Job ${job.id} claimed; running ${triageExecutor}${claudeModel ? ` (${claudeModel})` : ""}...`)
1211
- try {
1212
- const text = await runExecutorPrompt(job.prompt)
1213
- const complete = await triageApi(`/api/triage-runner/jobs/${job.id}/complete`, {
1214
- text,
1215
- model: `${triageExecutor}${claudeModel ? `:${claudeModel}` : ""}`,
1216
- })
1217
- if (complete.status >= 400) {
1218
- triageLog(`\x1b[31mJob ${job.id}: server rejected completion (${complete.status}): ${JSON.stringify(complete.payload)}\x1b[0m`)
1219
- } else {
1220
- triageLog(`\x1b[32mJob ${job.id} completed\x1b[0m (confidence: ${complete.payload?.confidence ?? "n/a"})`)
1221
- }
1222
- } catch (error) {
1223
- const message = error instanceof Error ? error.message : String(error)
1224
- triageLog(`\x1b[31mJob ${job.id} failed: ${message}\x1b[0m`)
1225
- await triageApi(`/api/triage-runner/jobs/${job.id}/fail`, { error: message }).catch(() => {})
1226
- }
1227
- }
1228
-
1229
- triageLog(`Triage runner "${triageRunnerName}" polling ${appUrl} every ${pollIntervalMs / 1000}s (executor: ${triageExecutor})`)
1230
- let triageStopping = false
1231
- process.on("SIGINT", () => { triageStopping = true; triageLog("Stopping after current poll...") })
1232
- process.on("SIGTERM", () => { triageStopping = true })
1233
-
1234
- while (!triageStopping) {
1235
- try {
1236
- const claim = await triageApi("/api/triage-runner/claim", { runner_name: triageRunnerName })
1237
- if (claim.status === 401 || claim.status === 403) {
1238
- console.error(`\x1b[31mAuthentication failed (${claim.status}).\x1b[0m Run \x1b[36mpacework login\x1b[0m again.`)
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.`)
1239
1144
  process.exit(1)
1240
1145
  }
1241
- if (claim.status >= 400) {
1242
- triageLog(`Claim failed (${claim.status}): ${JSON.stringify(claim.payload)}`)
1243
- } else if (claim.payload?.job) {
1244
- await processTriageJob(claim.payload.job)
1245
- if (runOnce) break
1246
- continue
1247
- }
1248
- } catch (error) {
1249
- triageLog(`Poll error: ${error instanceof Error ? error.message : String(error)}`)
1250
- }
1251
- if (runOnce) break
1252
- await new Promise((resolve) => setTimeout(resolve, pollIntervalMs))
1253
- }
1146
+ },
1147
+ })
1254
1148
  process.exit(0)
1255
1149
  }
1256
1150
 
@@ -1261,125 +1155,21 @@ else if (command === "triage") {
1261
1155
  // Every action shells out to this same CLI, so menu and commands never drift.
1262
1156
 
1263
1157
  else if (command === "menu") {
1264
- const runChild = (childArgs) => new Promise((resolve) => {
1265
- const child = spawn(process.execPath, [process.argv[1], ...childArgs], { stdio: "inherit" })
1266
- child.on("close", () => resolve())
1267
- child.on("error", () => resolve())
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))
1268
1168
  })
1269
-
1270
- const choose = async (question, options, defaultIndex = 0) => {
1271
- console.log("")
1272
- options.forEach((option, index) => {
1273
- const marker = index === defaultIndex ? "\x1b[36m" : ""
1274
- console.log(` ${marker}${index + 1}. ${option}\x1b[0m`)
1275
- })
1276
- const answer = (await promptLine(`${question} (default ${defaultIndex + 1}, q to cancel): `)).trim()
1277
- if (/^q(uit)?$/i.test(answer)) return -1
1278
- const picked = answer ? Number(answer) - 1 : defaultIndex
1279
- return Number.isInteger(picked) && picked >= 0 && picked < options.length ? picked : defaultIndex
1169
+ if (!readConfig().apiKey) {
1170
+ if (!await runSetup({ startRunner })) process.exit(0)
1280
1171
  }
1281
-
1282
- const TRIAGE_MODELS = {
1283
- claude_code: ["CLI default", "haiku", "sonnet", "opus"],
1284
- codex: ["CLI default", "gpt-5.5", "gpt-5.5-pro"],
1285
- gemini: ["CLI default", "gemini-2.5-flash", "gemini-2.5-pro"],
1286
- }
1287
-
1288
- const guidedTriage = async (config) => {
1289
- const executors = ["claude_code", "codex", "gemini"]
1290
- const executorLabels = {
1291
- claude_code: "Claude Code (Claude subscription)",
1292
- codex: "Codex (ChatGPT subscription)",
1293
- gemini: "Gemini CLI",
1294
- }
1295
- const defaultExecutorIndex = Math.max(0, executors.indexOf(config.executor))
1296
- const executorIndex = await choose(
1297
- "Which AI runs triage jobs?",
1298
- executors.map((name) => executorLabels[name]),
1299
- defaultExecutorIndex,
1300
- )
1301
- if (executorIndex < 0) return
1302
- const executor = executors[executorIndex]
1303
-
1304
- const models = TRIAGE_MODELS[executor] ?? ["CLI default"]
1305
- const modelIndex = await choose("Which model?", models, 0)
1306
- if (modelIndex < 0) return
1307
- const model = modelIndex === 0 ? null : models[modelIndex]
1308
-
1309
- const modeIndex = await choose("How should it run?", [
1310
- "Keep running (poll for jobs until Ctrl-C)",
1311
- "Process one job, then exit",
1312
- ], 0)
1313
- if (modeIndex < 0) return
1314
-
1315
- const childArgs = ["triage", "--executor", executor]
1316
- if (model) childArgs.push("--model", model)
1317
- if (modeIndex === 1) childArgs.push("--once", "true")
1318
- console.log(`\n\x1b[2m→ pacework triage ${childArgs.slice(1).join(" ")}\x1b[0m\n`)
1319
- await runChild(childArgs)
1320
- }
1321
-
1322
- const guidedAgentRunner = async () => {
1323
- const modeIndex = await choose("How should the agent runner run?", [
1324
- "Background daemon (keeps running after this menu closes)",
1325
- "Foreground (watch output, Ctrl-C to stop)",
1326
- ], 0)
1327
- if (modeIndex < 0) return
1328
- await runChild([modeIndex === 0 ? "start" : "connect"])
1329
- }
1330
-
1331
- let menuRunning = true
1332
- while (menuRunning) {
1333
- const config = readConfig()
1334
- console.clear()
1335
- printBanner(config)
1336
- if (config.apiKey) {
1337
- console.log(` Workspace: \x1b[1m${config.workspaceSlug ?? config.workspaceId ?? "?"}\x1b[0m Executor: \x1b[1m${executorLabel(config.executor) ?? config.executor ?? "not set"}\x1b[0m`)
1338
- } else {
1339
- console.log(" \x1b[33mNot logged in yet — pick “Log in” to get started.\x1b[0m")
1340
- }
1341
-
1342
- const loggedIn = Boolean(config.apiKey)
1343
- const entries = loggedIn
1344
- ? [
1345
- { label: "Run triage (pacework Intelligence on this machine)", action: () => guidedTriage(config) },
1346
- { label: "Run the agent runner (works on issues)", action: guidedAgentRunner },
1347
- { label: "Status", action: () => runChild(["status"]) },
1348
- { label: "Recent jobs", action: () => runChild(["jobs"]) },
1349
- { label: "Tail runner logs", action: () => runChild(["logs"]) },
1350
- { label: "Stop background runner", action: () => runChild(["stop"]) },
1351
- { label: "Health check (doctor)", action: () => runChild(["doctor"]) },
1352
- { label: "Switch executor", action: async () => {
1353
- const executorIndex = await choose(
1354
- "Which executor?",
1355
- EXECUTORS.map((executor) => `${executor.label}${checkBinaryExists(executor.bin) ? "" : " (not installed)"}`),
1356
- Math.max(0, EXECUTORS.findIndex((executor) => executor.id === config.executor)),
1357
- )
1358
- if (executorIndex < 0) return
1359
- await runChild(["use", EXECUTORS[executorIndex].id])
1360
- } },
1361
- { label: "Log in again / switch workspace", action: () => runChild(["login"]) },
1362
- { label: "Log out", action: () => runChild(["logout"]) },
1363
- { label: "Quit", action: null },
1364
- ]
1365
- : [
1366
- { label: "Log in (opens your browser)", action: () => runChild(["login"]) },
1367
- { label: "Status", action: () => runChild(["status"]) },
1368
- { label: "Quit", action: null },
1369
- ]
1370
-
1371
- const pickedIndex = await choose("What do you want to do?", entries.map((entry) => entry.label), 0)
1372
- const picked = pickedIndex < 0 ? entries[entries.length - 1] : entries[pickedIndex]
1373
- if (!picked.action) {
1374
- menuRunning = false
1375
- break
1376
- }
1377
- await picked.action()
1378
- if (menuRunning) {
1379
- await promptLine("\n\x1b[2mPress Enter to return to the menu…\x1b[0m")
1380
- }
1381
- }
1382
- process.exit(0)
1172
+ await runHome({ ctlScript, version: LOCAL_VERSION })
1383
1173
  }
1384
1174
 
1385
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
+ }