pacework 1.0.2 → 1.2.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.
@@ -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
+ }
package/lib/home.mjs ADDED
@@ -0,0 +1,322 @@
1
+ import readline from "node:readline"
2
+ import { spawn } from "node:child_process"
3
+ import { readConfig, readRunnerSnapshot } from "./control-state.mjs"
4
+ import { executorLabel } from "./executors.mjs"
5
+ import { openInBrowser } from "./login.mjs"
6
+ import { changeExecutor, changeRepo, switchServer } from "./setup.mjs"
7
+ import { TRIAGE_EXECUTORS } from "./triage-worker.mjs"
8
+ import { BANNER_LINES, LOGO, formatDuration, hostOf, relativeTime, style, tildePath, truncate } from "./ui.mjs"
9
+ import { formatIssueRows, listIssues } from "./issues-cli.mjs"
10
+ import { workspaceUrl } from "./workspace-api.mjs"
11
+
12
+ /**
13
+ * The live home screen behind a bare `pacework`: where this machine is
14
+ * connected, whether the runner is working, what it is doing now and did
15
+ * recently, and one key per action. Redraws every second in the terminal's
16
+ * alternate screen, so leaving it restores the shell as it was.
17
+ */
18
+ const KEYS = [
19
+ ["s", "start/stop"],
20
+ ["i", "issues"],
21
+ ["m", "MCP"],
22
+ ["l", "logs"],
23
+ ["w", "switch"],
24
+ ["r", "repo"],
25
+ ["e", "agent AI"],
26
+ ["o", "open"],
27
+ ["d", "doctor"],
28
+ ["?", "help"],
29
+ ["q", "quit"],
30
+ ]
31
+
32
+ const HELP = [
33
+ ["s", "Start or stop the background runner"],
34
+ ["i", "Your issues; ↑/↓ to choose, Enter to open in the browser"],
35
+ ["m", "Connect your AI tools to pacework over MCP, so they can read and update issues"],
36
+ ["l", "Show the live runner log"],
37
+ ["w", "Switch to another pacework server or workspace (signs in again)"],
38
+ ["r", "Change the folder agents work in"],
39
+ ["e", "Change the AI tool agents run on (Claude Code, Codex, …)"],
40
+ ["o", "Open this workspace in your browser"],
41
+ ["d", "Run the health check"],
42
+ ["q", "Quit this screen; the runner keeps working in the background"],
43
+ ]
44
+
45
+ const PLAIN_COMMANDS = [
46
+ ["pacework issues [--mine]", "List issues; pacework issue ENG-42 for one"],
47
+ ["pacework mcp add | status", "Connect AI tools to pacework"],
48
+ ["pacework status [--json]", "Is the runner up, and what is it doing"],
49
+ ["pacework start | stop", "Start or stop the background runner"],
50
+ ["pacework logs", "Follow the runner log"],
51
+ ["pacework login | logout", "Sign in to a pacework, or sign out"],
52
+ ["pacework doctor", "Check this machine's setup"],
53
+ ["pacework triage", "Run only triage, in the foreground"],
54
+ ]
55
+
56
+ function runCtl(ctlScript, args) {
57
+ return new Promise((resolve) => {
58
+ const child = spawn(process.execPath, [ctlScript, ...args], { stdio: ["ignore", "pipe", "pipe"], env: process.env })
59
+ let output = ""
60
+ child.stdout.on("data", (chunk) => { output += chunk })
61
+ child.stderr.on("data", (chunk) => { output += chunk })
62
+ child.on("error", () => resolve({ ok: false, output }))
63
+ child.on("close", (code) => resolve({ ok: code === 0, output: output.replace(/\x1b\[[0-9;]*m/g, "").trim() }))
64
+ })
65
+ }
66
+
67
+ function runCtlInteractive(ctlScript, args) {
68
+ return new Promise((resolve) => {
69
+ const child = spawn(process.execPath, [ctlScript, ...args], { stdio: "inherit", env: process.env })
70
+ child.on("close", () => resolve())
71
+ child.on("error", () => resolve())
72
+ })
73
+ }
74
+
75
+ function lastLine(text) {
76
+ return String(text ?? "").split("\n").map((line) => line.trim()).filter(Boolean).pop() ?? ""
77
+ }
78
+
79
+ function jobLine(job, width) {
80
+ const id = style.bold((job.identifier ?? "").padEnd(9))
81
+ if (job.status === "running") {
82
+ const elapsed = job.startedAt ? formatDuration(Date.now() - new Date(job.startedAt).getTime()) : ""
83
+ return ` ${style.brand("▸")} ${id} ${truncate(job.title ?? "Working", width - 26)} ${style.gray(elapsed)}`
84
+ }
85
+ const mark = job.status === "completed" ? style.green("✓") : job.status === "error" ? style.red("✗") : style.gray("–")
86
+ const outcome = job.status === "completed"
87
+ ? formatDuration(job.durationMs)
88
+ : job.status === "error" ? `failed${job.message ? `: ${job.message}` : ""}` : job.status
89
+ const when = relativeTime(job.finishedAt)
90
+ const title = truncate(job.title ?? "", Math.max(10, width - 44))
91
+ return ` ${mark} ${id} ${title} ${style.gray(truncate(`${outcome}${when ? ` · ${when}` : ""}`, 34))}`
92
+ }
93
+
94
+ export async function runHome({ ctlScript, version }) {
95
+ const stdin = process.stdin
96
+ const stdout = process.stdout
97
+ let mode = "home"
98
+ let issues = { state: "idle", items: [], selected: 0, error: null }
99
+ let flash = null
100
+ let busy = false
101
+ let timer = null
102
+
103
+ const setFlash = (text, tone = "info") => { flash = { text, tone, until: Date.now() + 6000 } }
104
+
105
+ const render = () => {
106
+ const width = Math.max(40, stdout.columns || 80)
107
+ const height = Math.max(12, stdout.rows || 24)
108
+ const snapshot = readRunnerSnapshot({ logLines: 400 })
109
+ const config = readConfig()
110
+ const lines = []
111
+
112
+ // The banner when there is room for it and the jobs below; the wordmark otherwise.
113
+ if (height >= 30 && width >= 72) {
114
+ for (const line of BANNER_LINES) lines.push(` ${style.brand(line)}`)
115
+ lines.push(` ${style.gray(`v${version ?? "?"}`)}`)
116
+ } else {
117
+ lines.push(` ${LOGO} ${style.gray(`v${version ?? "?"}`)}`)
118
+ }
119
+ lines.push(` ${style.gray(`${hostOf(snapshot.appUrl)} · ${snapshot.workspace ?? "no workspace"}`)}`)
120
+ const state = snapshot.running ? `${style.green("●")} running` : `${style.gray("○")} stopped`
121
+ const tool = executorLabel(snapshot.executor)
122
+ const work = TRIAGE_EXECUTORS.includes(snapshot.executor) ? "development + triage" : "development"
123
+ lines.push(` ${state} ${tildePath(snapshot.repoRoot) || style.yellow("no folder set")} ${style.gray("·")} ${tool} ${style.gray("·")} ${style.gray(work)}`)
124
+ lines.push("")
125
+
126
+ if (mode === "issues") {
127
+ lines.push(` ${style.bold("Assigned to you")} ${style.gray("↑/↓ choose · Enter open · r refresh · Esc back")}`)
128
+ if (issues.state === "loading") lines.push(style.gray(" Loading…"))
129
+ else if (issues.state === "error") lines.push(` ${style.red(issues.error)}`)
130
+ else if (!issues.items.length) lines.push(style.gray(" Nothing assigned to you."))
131
+ else {
132
+ const room = Math.max(1, height - lines.length - 3)
133
+ const start = Math.max(0, Math.min(issues.selected - room + 1, issues.items.length - room))
134
+ formatIssueRows(issues.items, width).slice(start, start + room).forEach((row, index) => {
135
+ lines.push(start + index === issues.selected ? `${style.brand("❯")}${row.slice(1)}` : row)
136
+ })
137
+ }
138
+ } else if (mode === "logs") {
139
+ lines.push(` ${style.bold("Log")} ${style.gray("live · press l or Esc to go back")}`)
140
+ const room = height - lines.length - 2
141
+ for (const entry of snapshot.logs.slice(-room)) {
142
+ const time = entry.ts ? new Date(entry.ts).toLocaleTimeString() : " "
143
+ const level = entry.level === "error" ? style.red("error") : entry.level === "warn" ? style.yellow("warn ") : style.gray("info ")
144
+ lines.push(` ${style.gray(time)} ${level} ${truncate(entry.message || entry.event || "", width - 22)}`)
145
+ }
146
+ } else if (mode === "help") {
147
+ lines.push(` ${style.bold("Keys")}`)
148
+ for (const [key, description] of HELP) lines.push(` ${style.bold(key)} ${description}`)
149
+ lines.push("")
150
+ lines.push(` ${style.bold("Commands")} ${style.gray("for scripts and other terminals")}`)
151
+ for (const [command, description] of PLAIN_COMMANDS) lines.push(` ${command.padEnd(28)} ${style.gray(description)}`)
152
+ lines.push("")
153
+ lines.push(` ${style.gray("Press ? or Esc to go back.")}`)
154
+ } else {
155
+ // A job the log shows as started but never finished, while the runner
156
+ // is stopped, was cut off by the stop or a crash; it is not running.
157
+ const jobs = snapshot.jobs.map((job) => (!snapshot.running && job.status === "running"
158
+ ? { ...job, status: "interrupted", finishedAt: job.startedAt }
159
+ : job))
160
+ const running = jobs.filter((job) => job.status === "running")
161
+ const recent = jobs.filter((job) => job.status !== "running" && job.status !== "pending")
162
+ lines.push(` ${style.bold("Now")}`)
163
+ if (running.length) for (const job of running) lines.push(jobLine(job, width))
164
+ else lines.push(style.gray(snapshot.running
165
+ ? " Nothing in progress. Assign an issue to an agent in pacework and it starts here."
166
+ : " The runner is stopped. Press s to start it."))
167
+ lines.push("")
168
+ lines.push(` ${style.bold("Recent")}`)
169
+ const room = Math.max(1, height - lines.length - 3)
170
+ if (recent.length) for (const job of recent.slice(0, room)) lines.push(jobLine(job, width))
171
+ else lines.push(style.gray(" No finished jobs yet."))
172
+ if (!config.apiKey) {
173
+ lines.push("")
174
+ lines.push(` ${style.yellow("Not signed in.")} Press w to connect to a pacework.`)
175
+ }
176
+ }
177
+
178
+ while (lines.length < height - 2) lines.push("")
179
+ if (flash && flash.until < Date.now()) flash = null
180
+ const flashText = busy ? style.brand(`${busy}…`) : flash ? (flash.tone === "error" ? style.red(flash.text) : style.green(flash.text)) : ""
181
+ lines.push(` ${truncate(flashText, width + 20)}`)
182
+ lines.push(` ${KEYS.map(([key, label]) => `${style.bold(key)} ${style.gray(label)}`).join(" ")}`)
183
+
184
+ stdout.write(`\x1b[H${lines.slice(0, height).map((line) => `${line}\x1b[K`).join("\n")}\x1b[J`)
185
+ }
186
+
187
+ const enter = () => {
188
+ stdout.write("\x1b[?1049h\x1b[?25l")
189
+ readline.emitKeypressEvents(stdin)
190
+ if (stdin.isTTY) stdin.setRawMode(true)
191
+ stdin.resume()
192
+ stdin.on("keypress", onKey)
193
+ stdout.on("resize", render)
194
+ timer = setInterval(render, 1000)
195
+ render()
196
+ }
197
+
198
+ const leave = () => {
199
+ clearInterval(timer)
200
+ stdin.off("keypress", onKey)
201
+ stdout.off("resize", render)
202
+ if (stdin.isTTY) stdin.setRawMode(false)
203
+ stdout.write("\x1b[?25h\x1b[?1049l")
204
+ }
205
+
206
+ /** Hands the terminal to a prompt or child command, then takes it back. */
207
+ const suspend = async (fn) => {
208
+ leave()
209
+ try {
210
+ return await fn()
211
+ } finally {
212
+ enter()
213
+ }
214
+ }
215
+
216
+ const withBusy = async (label, fn) => {
217
+ busy = label
218
+ render()
219
+ try {
220
+ return await fn()
221
+ } finally {
222
+ busy = false
223
+ render()
224
+ }
225
+ }
226
+
227
+ const restartIfRunning = async () => {
228
+ if (!readRunnerSnapshot({ logLines: 1 }).running) return
229
+ await withBusy("Restarting the runner", async () => {
230
+ await runCtl(ctlScript, ["stop"])
231
+ const result = await runCtl(ctlScript, ["start"])
232
+ setFlash(result.ok ? "Runner restarted with the new settings." : `Restart failed: ${lastLine(result.output)}`, result.ok ? "info" : "error")
233
+ })
234
+ }
235
+
236
+ const quit = () => {
237
+ leave()
238
+ const running = readRunnerSnapshot({ logLines: 1 }).running
239
+ console.log(running
240
+ ? `${LOGO} The runner keeps working in the background. ${style.gray("pacework stop")} stops it.`
241
+ : `${LOGO} The runner is stopped. ${style.gray("pacework start")} starts it.`)
242
+ process.exit(0)
243
+ }
244
+
245
+ const loadIssues = async () => {
246
+ issues = { ...issues, state: "loading", error: null }
247
+ render()
248
+ try {
249
+ const items = await listIssues({ mine: true, limit: 50 })
250
+ issues = { state: "ready", items, selected: Math.min(issues.selected, Math.max(0, items.length - 1)), error: null }
251
+ } catch (error) {
252
+ issues = { ...issues, state: "error", error: error instanceof Error ? error.message : String(error) }
253
+ }
254
+ render()
255
+ }
256
+
257
+ async function onKey(text, key = {}) {
258
+ if (key.ctrl && key.name === "c") return quit()
259
+ if (busy) return
260
+ const name = key.name ?? text
261
+ if (mode === "issues") {
262
+ if (name === "escape" || name === "i" || name === "q") { mode = "home"; return render() }
263
+ if (name === "up") issues.selected = Math.max(0, issues.selected - 1)
264
+ else if (name === "down") issues.selected = Math.min(issues.items.length - 1, issues.selected + 1)
265
+ else if (name === "r") return loadIssues()
266
+ else if (name === "return" && issues.items[issues.selected]) {
267
+ const url = workspaceUrl(issues.items[issues.selected].identifier)
268
+ setFlash(openInBrowser(url) ? `Opened ${url}` : `Open ${url}`)
269
+ }
270
+ return render()
271
+ }
272
+ if (mode !== "home" && (name === "escape" || (mode === "logs" && name === "l") || (mode === "help" && text === "?"))) {
273
+ mode = "home"
274
+ return render()
275
+ }
276
+ if (name === "q") return quit()
277
+ if (name === "l") { mode = "logs"; return render() }
278
+ if (name === "i") { mode = "issues"; return loadIssues() }
279
+ if (name === "m") {
280
+ return suspend(async () => {
281
+ const { runMcpCommand } = await import("./mcp-cli.mjs")
282
+ await runMcpCommand("add", [], {})
283
+ })
284
+ }
285
+ if (text === "?") { mode = "help"; return render() }
286
+ if (name === "s") {
287
+ const running = readRunnerSnapshot({ logLines: 1 }).running
288
+ return withBusy(running ? "Stopping the runner" : "Starting the runner", async () => {
289
+ const result = await runCtl(ctlScript, [running ? "stop" : "start"])
290
+ setFlash(result.ok ? (running ? "Runner stopped." : "Runner started.") : lastLine(result.output) || "That did not work; see the log (l).", result.ok ? "info" : "error")
291
+ })
292
+ }
293
+ if (name === "o") {
294
+ const snapshot = readRunnerSnapshot({ logLines: 1 })
295
+ const url = `${snapshot.appUrl}/${readConfig().workspaceSlug ?? ""}`
296
+ setFlash(openInBrowser(url) ? `Opened ${url}` : `Open ${url}`)
297
+ return render()
298
+ }
299
+ if (name === "d") {
300
+ return suspend(async () => {
301
+ await runCtlInteractive(ctlScript, ["doctor"])
302
+ await new Promise((resolve) => {
303
+ process.stdout.write("\nPress any key to go back.")
304
+ if (stdin.isTTY) stdin.setRawMode(true)
305
+ stdin.resume()
306
+ stdin.once("data", () => resolve())
307
+ })
308
+ })
309
+ }
310
+ const settings = { w: switchServer, r: changeRepo, e: changeExecutor }
311
+ if (settings[name]) {
312
+ const changed = await suspend(() => settings[name]())
313
+ if (changed) {
314
+ setFlash("Saved.")
315
+ await restartIfRunning()
316
+ }
317
+ return render()
318
+ }
319
+ }
320
+
321
+ enter()
322
+ }
@@ -0,0 +1,80 @@
1
+ import { workspaceGet } from "./workspace-api.mjs"
2
+ import { relativeTime, style, truncate } from "./ui.mjs"
3
+
4
+ /** `pacework issues` and `pacework issue <ID>`: read-only views of the workspace. */
5
+ const STATUS_STYLE = {
6
+ backlog: style.gray,
7
+ todo: (text) => text,
8
+ in_progress: style.brand,
9
+ in_review: style.yellow,
10
+ done: style.green,
11
+ canceled: style.gray,
12
+ cancelled: style.gray,
13
+ }
14
+
15
+ export const ISSUE_FILTERS = ["open", "backlog", "todo", "in_progress", "in_review", "done", "canceled"]
16
+
17
+ function statusLabel(status) {
18
+ const value = String(status ?? "").toLowerCase()
19
+ return (STATUS_STYLE[value] ?? ((text) => text))(value.replace(/_/g, " ").padEnd(11))
20
+ }
21
+
22
+ export function formatIssueRows(issues, width = process.stdout.columns || 100) {
23
+ return issues.map((issue) => {
24
+ const priority = issue.priority && issue.priority !== "none" ? style.gray(issue.priority) : ""
25
+ return ` ${style.bold(String(issue.identifier ?? "").padEnd(9))} ${statusLabel(issue.status)} ${truncate(issue.title ?? "", Math.max(20, width - 40))} ${priority}`
26
+ })
27
+ }
28
+
29
+ export async function listIssues({ mine = false, status = "open", limit = 30 } = {}) {
30
+ const route = mine ? `/cli/my-issues?limit=${limit}` : `/cli/issues?status=${encodeURIComponent(status)}&limit=${limit}`
31
+ const { issues = [] } = await workspaceGet(route)
32
+ return issues
33
+ }
34
+
35
+ export async function printIssues(options) {
36
+ const issues = await listIssues(options)
37
+ const heading = options.mine ? "Assigned to you" : `Issues · ${String(options.status ?? "open").replace(/_/g, " ")}`
38
+ console.log(`\n ${style.bold(heading)} ${style.gray(`${issues.length}`)}`)
39
+ if (!issues.length) {
40
+ console.log(style.gray(options.mine ? " Nothing assigned to you." : " No issues with that status."))
41
+ } else {
42
+ for (const row of formatIssueRows(issues)) console.log(row)
43
+ }
44
+ console.log("")
45
+ }
46
+
47
+ export async function printIssue(identifier) {
48
+ let body
49
+ try {
50
+ body = await workspaceGet(`/cli/issue/${encodeURIComponent(identifier.toUpperCase())}`)
51
+ } catch (error) {
52
+ if (error.status === 404) throw new Error(`No issue ${identifier.toUpperCase()} in this workspace.`)
53
+ throw error
54
+ }
55
+ const { issue, comments = [] } = body
56
+ console.log("")
57
+ console.log(` ${style.gray(issue.identifier)} ${style.bold(issue.title)}`)
58
+ const facts = [
59
+ statusLabel(issue.status).trim(),
60
+ issue.priority && issue.priority !== "none" ? `priority ${issue.priority}` : null,
61
+ issue.assignee_name ? `assigned to ${issue.assignee_name}` : "unassigned",
62
+ issue.project_name ? `in ${issue.project_name}` : null,
63
+ `updated ${relativeTime(issue.updated_at)}`,
64
+ ].filter(Boolean)
65
+ console.log(` ${facts.join(style.gray(" · "))}`)
66
+ if (issue.description) {
67
+ console.log("")
68
+ for (const line of String(issue.description).replace(/<[^>]+>/g, "").trim().split("\n").slice(0, 30)) console.log(` ${line}`)
69
+ }
70
+ if (comments.length) {
71
+ console.log(`\n ${style.bold("Recent comments")}`)
72
+ // The API returns the oldest first; the latest few are what matter here.
73
+ for (const comment of comments.slice(-5)) {
74
+ const author = comment.author ?? "someone"
75
+ const text = String(comment.body ?? "").replace(/<[^>]+>/g, "").replace(/\s+/g, " ").trim()
76
+ console.log(` ${style.gray(`${author} · ${relativeTime(comment.created_at)}`)} ${truncate(text, (process.stdout.columns || 100) - 30)}`)
77
+ }
78
+ }
79
+ console.log("")
80
+ }
package/lib/login.mjs ADDED
@@ -0,0 +1,50 @@
1
+ import { execFileSync } from "node:child_process"
2
+
3
+ /**
4
+ * Browser sign-in: the server issues a one-time token and a page to approve it
5
+ * on; the CLI polls until the page is approved, then receives a workspace API
6
+ * key. Shared by guided setup and the plain `login` command.
7
+ */
8
+ export async function startLogin(appUrl) {
9
+ let res
10
+ try {
11
+ res = await fetch(`${appUrl}/api/cli/login`, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" })
12
+ } catch (error) {
13
+ throw new Error(`Could not reach ${appUrl} (${error instanceof Error ? error.message : error}). Check the address and your connection.`)
14
+ }
15
+ if (!res.ok) throw new Error(`${appUrl} answered ${res.status}. Is this a pacework address?`)
16
+ const body = await res.json()
17
+ if (!body.token || !body.loginUrl) throw new Error(`${appUrl} did not return a sign-in link. Is this a pacework address?`)
18
+ return { token: body.token, loginUrl: body.loginUrl }
19
+ }
20
+
21
+ /**
22
+ * Resolves with the approved session ({ apiKey, workspaceId, workspaceSlug,
23
+ * userName, userEmail }) or throws when the link expires or time runs out.
24
+ */
25
+ export async function waitForApproval({ appUrl, token, onTick = () => {}, timeoutMs = 10 * 60 * 1000 }) {
26
+ const startedAt = Date.now()
27
+ while (Date.now() - startedAt < timeoutMs) {
28
+ await new Promise((resolve) => setTimeout(resolve, 2000))
29
+ let poll
30
+ try {
31
+ poll = await (await fetch(`${appUrl}/api/cli/login?token=${encodeURIComponent(token)}`)).json()
32
+ } catch {
33
+ continue
34
+ }
35
+ if (poll.status === "authorized") return poll
36
+ if (poll.status === "expired") throw new Error("The sign-in link expired. Start again.")
37
+ onTick()
38
+ }
39
+ throw new Error("Sign-in timed out after 10 minutes. Start again.")
40
+ }
41
+
42
+ export function openInBrowser(url) {
43
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "start" : "xdg-open"
44
+ try {
45
+ execFileSync(command, [url], { stdio: "ignore" })
46
+ return true
47
+ } catch {
48
+ return false
49
+ }
50
+ }