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.
package/lib/home.mjs ADDED
@@ -0,0 +1,265 @@
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 { LOGO, formatDuration, hostOf, relativeTime, style, tildePath, truncate } from "./ui.mjs"
9
+
10
+ /**
11
+ * The live home screen behind a bare `pacework`: where this machine is
12
+ * connected, whether the runner is working, what it is doing now and did
13
+ * recently, and one key per action. Redraws every second in the terminal's
14
+ * alternate screen, so leaving it restores the shell as it was.
15
+ */
16
+ const KEYS = [
17
+ ["s", "start/stop"],
18
+ ["l", "logs"],
19
+ ["w", "switch"],
20
+ ["r", "repo"],
21
+ ["e", "AI tool"],
22
+ ["o", "open"],
23
+ ["d", "doctor"],
24
+ ["?", "help"],
25
+ ["q", "quit"],
26
+ ]
27
+
28
+ const HELP = [
29
+ ["s", "Start or stop the background runner"],
30
+ ["l", "Show the live runner log"],
31
+ ["w", "Switch to another pacework server or workspace (signs in again)"],
32
+ ["r", "Change the folder agents work in"],
33
+ ["e", "Change the AI tool agents use"],
34
+ ["o", "Open this workspace in your browser"],
35
+ ["d", "Run the health check"],
36
+ ["q", "Quit this screen; the runner keeps working in the background"],
37
+ ]
38
+
39
+ const PLAIN_COMMANDS = [
40
+ ["pacework status [--json]", "Is the runner up, and what is it doing"],
41
+ ["pacework start | stop", "Start or stop the background runner"],
42
+ ["pacework logs", "Follow the runner log"],
43
+ ["pacework login | logout", "Sign in to a pacework, or sign out"],
44
+ ["pacework doctor", "Check this machine's setup"],
45
+ ["pacework triage", "Run only triage, in the foreground"],
46
+ ]
47
+
48
+ function runCtl(ctlScript, args) {
49
+ return new Promise((resolve) => {
50
+ const child = spawn(process.execPath, [ctlScript, ...args], { stdio: ["ignore", "pipe", "pipe"], env: process.env })
51
+ let output = ""
52
+ child.stdout.on("data", (chunk) => { output += chunk })
53
+ child.stderr.on("data", (chunk) => { output += chunk })
54
+ child.on("error", () => resolve({ ok: false, output }))
55
+ child.on("close", (code) => resolve({ ok: code === 0, output: output.replace(/\x1b\[[0-9;]*m/g, "").trim() }))
56
+ })
57
+ }
58
+
59
+ function runCtlInteractive(ctlScript, args) {
60
+ return new Promise((resolve) => {
61
+ const child = spawn(process.execPath, [ctlScript, ...args], { stdio: "inherit", env: process.env })
62
+ child.on("close", () => resolve())
63
+ child.on("error", () => resolve())
64
+ })
65
+ }
66
+
67
+ function lastLine(text) {
68
+ return String(text ?? "").split("\n").map((line) => line.trim()).filter(Boolean).pop() ?? ""
69
+ }
70
+
71
+ function jobLine(job, width) {
72
+ const id = style.bold((job.identifier ?? "").padEnd(9))
73
+ if (job.status === "running") {
74
+ const elapsed = job.startedAt ? formatDuration(Date.now() - new Date(job.startedAt).getTime()) : ""
75
+ return ` ${style.brand("▸")} ${id} ${truncate(job.title ?? "Working", width - 26)} ${style.gray(elapsed)}`
76
+ }
77
+ const mark = job.status === "completed" ? style.green("✓") : job.status === "error" ? style.red("✗") : style.gray("–")
78
+ const outcome = job.status === "completed"
79
+ ? formatDuration(job.durationMs)
80
+ : job.status === "error" ? `failed${job.message ? `: ${job.message}` : ""}` : job.status
81
+ const when = relativeTime(job.finishedAt)
82
+ const title = truncate(job.title ?? "", Math.max(10, width - 44))
83
+ return ` ${mark} ${id} ${title} ${style.gray(truncate(`${outcome}${when ? ` · ${when}` : ""}`, 34))}`
84
+ }
85
+
86
+ export async function runHome({ ctlScript, version }) {
87
+ const stdin = process.stdin
88
+ const stdout = process.stdout
89
+ let mode = "home"
90
+ let flash = null
91
+ let busy = false
92
+ let timer = null
93
+
94
+ const setFlash = (text, tone = "info") => { flash = { text, tone, until: Date.now() + 6000 } }
95
+
96
+ const render = () => {
97
+ const width = Math.max(40, stdout.columns || 80)
98
+ const height = Math.max(12, stdout.rows || 24)
99
+ const snapshot = readRunnerSnapshot({ logLines: 400 })
100
+ const config = readConfig()
101
+ const lines = []
102
+
103
+ lines.push(` ${LOGO} ${style.gray(`v${version ?? "?"}`)}`)
104
+ lines.push(` ${style.gray(`${hostOf(snapshot.appUrl)} · ${snapshot.workspace ?? "no workspace"}`)}`)
105
+ const state = snapshot.running ? `${style.green("●")} running` : `${style.gray("○")} stopped`
106
+ const tool = executorLabel(snapshot.executor)
107
+ const work = TRIAGE_EXECUTORS.includes(snapshot.executor) ? "development + triage" : "development"
108
+ lines.push(` ${state} ${tildePath(snapshot.repoRoot) || style.yellow("no folder set")} ${style.gray("·")} ${tool} ${style.gray("·")} ${style.gray(work)}`)
109
+ lines.push("")
110
+
111
+ if (mode === "logs") {
112
+ lines.push(` ${style.bold("Log")} ${style.gray("live · press l or Esc to go back")}`)
113
+ const room = height - lines.length - 2
114
+ for (const entry of snapshot.logs.slice(-room)) {
115
+ const time = entry.ts ? new Date(entry.ts).toLocaleTimeString() : " "
116
+ const level = entry.level === "error" ? style.red("error") : entry.level === "warn" ? style.yellow("warn ") : style.gray("info ")
117
+ lines.push(` ${style.gray(time)} ${level} ${truncate(entry.message || entry.event || "", width - 22)}`)
118
+ }
119
+ } else if (mode === "help") {
120
+ lines.push(` ${style.bold("Keys")}`)
121
+ for (const [key, description] of HELP) lines.push(` ${style.bold(key)} ${description}`)
122
+ lines.push("")
123
+ lines.push(` ${style.bold("Commands")} ${style.gray("for scripts and other terminals")}`)
124
+ for (const [command, description] of PLAIN_COMMANDS) lines.push(` ${command.padEnd(28)} ${style.gray(description)}`)
125
+ lines.push("")
126
+ lines.push(` ${style.gray("Press ? or Esc to go back.")}`)
127
+ } else {
128
+ // A job the log shows as started but never finished, while the runner
129
+ // is stopped, was cut off by the stop or a crash; it is not running.
130
+ const jobs = snapshot.jobs.map((job) => (!snapshot.running && job.status === "running"
131
+ ? { ...job, status: "interrupted", finishedAt: job.startedAt }
132
+ : job))
133
+ const running = jobs.filter((job) => job.status === "running")
134
+ const recent = jobs.filter((job) => job.status !== "running" && job.status !== "pending")
135
+ lines.push(` ${style.bold("Now")}`)
136
+ if (running.length) for (const job of running) lines.push(jobLine(job, width))
137
+ else lines.push(style.gray(snapshot.running
138
+ ? " Nothing in progress. Assign an issue to an agent in pacework and it starts here."
139
+ : " The runner is stopped. Press s to start it."))
140
+ lines.push("")
141
+ lines.push(` ${style.bold("Recent")}`)
142
+ const room = Math.max(1, height - lines.length - 3)
143
+ if (recent.length) for (const job of recent.slice(0, room)) lines.push(jobLine(job, width))
144
+ else lines.push(style.gray(" No finished jobs yet."))
145
+ if (!config.apiKey) {
146
+ lines.push("")
147
+ lines.push(` ${style.yellow("Not signed in.")} Press w to connect to a pacework.`)
148
+ }
149
+ }
150
+
151
+ while (lines.length < height - 2) lines.push("")
152
+ if (flash && flash.until < Date.now()) flash = null
153
+ const flashText = busy ? style.brand(`${busy}…`) : flash ? (flash.tone === "error" ? style.red(flash.text) : style.green(flash.text)) : ""
154
+ lines.push(` ${truncate(flashText, width + 20)}`)
155
+ lines.push(` ${KEYS.map(([key, label]) => `${style.bold(key)} ${style.gray(label)}`).join(" ")}`)
156
+
157
+ stdout.write(`\x1b[H${lines.slice(0, height).map((line) => `${line}\x1b[K`).join("\n")}\x1b[J`)
158
+ }
159
+
160
+ const enter = () => {
161
+ stdout.write("\x1b[?1049h\x1b[?25l")
162
+ readline.emitKeypressEvents(stdin)
163
+ if (stdin.isTTY) stdin.setRawMode(true)
164
+ stdin.resume()
165
+ stdin.on("keypress", onKey)
166
+ stdout.on("resize", render)
167
+ timer = setInterval(render, 1000)
168
+ render()
169
+ }
170
+
171
+ const leave = () => {
172
+ clearInterval(timer)
173
+ stdin.off("keypress", onKey)
174
+ stdout.off("resize", render)
175
+ if (stdin.isTTY) stdin.setRawMode(false)
176
+ stdout.write("\x1b[?25h\x1b[?1049l")
177
+ }
178
+
179
+ /** Hands the terminal to a prompt or child command, then takes it back. */
180
+ const suspend = async (fn) => {
181
+ leave()
182
+ try {
183
+ return await fn()
184
+ } finally {
185
+ enter()
186
+ }
187
+ }
188
+
189
+ const withBusy = async (label, fn) => {
190
+ busy = label
191
+ render()
192
+ try {
193
+ return await fn()
194
+ } finally {
195
+ busy = false
196
+ render()
197
+ }
198
+ }
199
+
200
+ const restartIfRunning = async () => {
201
+ if (!readRunnerSnapshot({ logLines: 1 }).running) return
202
+ await withBusy("Restarting the runner", async () => {
203
+ await runCtl(ctlScript, ["stop"])
204
+ const result = await runCtl(ctlScript, ["start"])
205
+ setFlash(result.ok ? "Runner restarted with the new settings." : `Restart failed: ${lastLine(result.output)}`, result.ok ? "info" : "error")
206
+ })
207
+ }
208
+
209
+ const quit = () => {
210
+ leave()
211
+ const running = readRunnerSnapshot({ logLines: 1 }).running
212
+ console.log(running
213
+ ? `${LOGO} The runner keeps working in the background. ${style.gray("pacework stop")} stops it.`
214
+ : `${LOGO} The runner is stopped. ${style.gray("pacework start")} starts it.`)
215
+ process.exit(0)
216
+ }
217
+
218
+ async function onKey(text, key = {}) {
219
+ if (key.ctrl && key.name === "c") return quit()
220
+ if (busy) return
221
+ const name = key.name ?? text
222
+ if (mode !== "home" && (name === "escape" || (mode === "logs" && name === "l") || (mode === "help" && text === "?"))) {
223
+ mode = "home"
224
+ return render()
225
+ }
226
+ if (name === "q") return quit()
227
+ if (name === "l") { mode = "logs"; return render() }
228
+ if (text === "?") { mode = "help"; return render() }
229
+ if (name === "s") {
230
+ const running = readRunnerSnapshot({ logLines: 1 }).running
231
+ return withBusy(running ? "Stopping the runner" : "Starting the runner", async () => {
232
+ const result = await runCtl(ctlScript, [running ? "stop" : "start"])
233
+ setFlash(result.ok ? (running ? "Runner stopped." : "Runner started.") : lastLine(result.output) || "That did not work; see the log (l).", result.ok ? "info" : "error")
234
+ })
235
+ }
236
+ if (name === "o") {
237
+ const snapshot = readRunnerSnapshot({ logLines: 1 })
238
+ const url = `${snapshot.appUrl}/${readConfig().workspaceSlug ?? ""}`
239
+ setFlash(openInBrowser(url) ? `Opened ${url}` : `Open ${url}`)
240
+ return render()
241
+ }
242
+ if (name === "d") {
243
+ return suspend(async () => {
244
+ await runCtlInteractive(ctlScript, ["doctor"])
245
+ await new Promise((resolve) => {
246
+ process.stdout.write("\nPress any key to go back.")
247
+ if (stdin.isTTY) stdin.setRawMode(true)
248
+ stdin.resume()
249
+ stdin.once("data", () => resolve())
250
+ })
251
+ })
252
+ }
253
+ const settings = { w: switchServer, r: changeRepo, e: changeExecutor }
254
+ if (settings[name]) {
255
+ const changed = await suspend(() => settings[name]())
256
+ if (changed) {
257
+ setFlash("Saved.")
258
+ await restartIfRunning()
259
+ }
260
+ return render()
261
+ }
262
+ }
263
+
264
+ enter()
265
+ }
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
+ }
package/lib/service.mjs CHANGED
@@ -55,7 +55,7 @@ export function isServiceInstalled() {
55
55
  }
56
56
 
57
57
  /**
58
- * Copy the runner package (it has no dependencies) to a stable location and
58
+ * Copy the runner package and its dependencies to a stable location and
59
59
  * return the path of the control script inside it.
60
60
  */
61
61
  export function installStableCopy(sourceRoot, version) {
@@ -66,10 +66,41 @@ export function installStableCopy(sourceRoot, version) {
66
66
  for (const entry of ["bin", "lib", "package.json"]) {
67
67
  fs.cpSync(path.join(sourceRoot, entry), path.join(target, entry), { recursive: true })
68
68
  }
69
+ copyDependencies(sourceRoot, target)
69
70
  }
70
71
  return path.join(target, "bin", "pacework-runner-ctl.mjs")
71
72
  }
72
73
 
74
+ /** Where Node would find `name` from `fromDir`: the nearest node_modules up the tree. */
75
+ function findPackageDir(name, fromDir) {
76
+ for (let dir = fromDir; ; dir = path.dirname(dir)) {
77
+ const candidate = path.join(dir, "node_modules", name)
78
+ if (fs.existsSync(path.join(candidate, "package.json"))) return candidate
79
+ if (path.dirname(dir) === dir) return null
80
+ }
81
+ }
82
+
83
+ /**
84
+ * npm installs a package's dependencies beside it (often hoisted), not inside
85
+ * it, so copying the package folder alone loses them. Copy each dependency,
86
+ * and theirs, into the copy's own node_modules.
87
+ */
88
+ function copyDependencies(sourceRoot, target) {
89
+ const copied = new Set()
90
+ const visit = (packageDir) => {
91
+ const manifest = JSON.parse(fs.readFileSync(path.join(packageDir, "package.json"), "utf8"))
92
+ for (const name of Object.keys(manifest.dependencies ?? {})) {
93
+ if (copied.has(name)) continue
94
+ const dependencyDir = findPackageDir(name, packageDir)
95
+ if (!dependencyDir) continue
96
+ copied.add(name)
97
+ fs.cpSync(dependencyDir, path.join(target, "node_modules", name), { recursive: true, dereference: true })
98
+ visit(dependencyDir)
99
+ }
100
+ }
101
+ visit(sourceRoot)
102
+ }
103
+
73
104
  const SHIM_MARKER = "# pacework launcher (written by pacework up)"
74
105
 
75
106
  /**
package/lib/setup.mjs ADDED
@@ -0,0 +1,222 @@
1
+ import fs from "node:fs"
2
+ import path from "node:path"
3
+ import { execSync } from "node:child_process"
4
+ import * as prompt from "@clack/prompts"
5
+ import { readConfig, writeConfig } from "./control-state.mjs"
6
+ import { EXECUTORS, EXECUTOR_DEFAULT_NAMES, checkBinaryExists, executorLabel } from "./executors.mjs"
7
+ import { openInBrowser, startLogin, waitForApproval } from "./login.mjs"
8
+ import { hostOf, normalizeAppUrl, style, tildePath } from "./ui.mjs"
9
+
10
+ /**
11
+ * Guided setup for the interactive CLI: which pacework, sign in, which folder,
12
+ * which AI tool. Each step is also exported on its own so the home screen can
13
+ * change one thing without repeating the rest. Only loaded in a terminal, so the
14
+ * background service never depends on the prompt library.
15
+ */
16
+ export const DEFAULT_APP_URL = process.env.PACEWORK_DEFAULT_APP_URL || "https://pacework.io"
17
+
18
+ class SetupCancelled extends Error {}
19
+
20
+ function unlessCancelled(value) {
21
+ if (prompt.isCancel(value)) throw new SetupCancelled()
22
+ return value
23
+ }
24
+
25
+ /** Runs a step; on Esc/Ctrl-C or an error, reports it and returns null instead of exiting. */
26
+ export async function step(fn) {
27
+ try {
28
+ return await fn()
29
+ } catch (error) {
30
+ if (error instanceof SetupCancelled) prompt.cancel("Nothing changed.")
31
+ else prompt.cancel(error instanceof Error ? error.message : String(error))
32
+ return null
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Pick a server and sign in to it. A wrong or unreachable address is the usual
38
+ * first mistake, so a failed sign-in goes back to the server choice instead of ending setup.
39
+ */
40
+ async function chooseServerAndSignIn(savedUrl) {
41
+ let suggested = savedUrl
42
+ for (;;) {
43
+ const appUrl = await chooseServer(suggested)
44
+ try {
45
+ return { appUrl, session: await signIn(appUrl) }
46
+ } catch (error) {
47
+ prompt.log.error(error instanceof Error ? error.message : String(error))
48
+ suggested = appUrl
49
+ }
50
+ }
51
+ }
52
+
53
+ export async function chooseServer(savedUrl) {
54
+ const options = []
55
+ if (savedUrl) options.push({ value: savedUrl, label: hostOf(savedUrl), hint: "current" })
56
+ if (savedUrl !== DEFAULT_APP_URL) options.push({ value: DEFAULT_APP_URL, label: hostOf(DEFAULT_APP_URL), hint: "pacework cloud" })
57
+ options.push({ value: "other", label: "Another address…", hint: "your own server or local development" })
58
+
59
+ const choice = unlessCancelled(await prompt.select({
60
+ message: "Which pacework do you want to connect to?",
61
+ options,
62
+ initialValue: savedUrl ?? DEFAULT_APP_URL,
63
+ }))
64
+ if (choice !== "other") return choice
65
+ const typed = unlessCancelled(await prompt.text({
66
+ message: "Address",
67
+ placeholder: "app.example.com or http://localhost:3000",
68
+ validate: (value) => (normalizeAppUrl(value) ? undefined : "Enter an address"),
69
+ }))
70
+ return normalizeAppUrl(typed)
71
+ }
72
+
73
+ /** Browser sign-in; resolves with the approved session. */
74
+ export async function signIn(appUrl) {
75
+ const { token, loginUrl } = await startLogin(appUrl)
76
+ const opened = openInBrowser(loginUrl)
77
+ prompt.log.info(opened
78
+ ? `Approve this machine in the browser window that just opened.\n${style.dim(loginUrl)}`
79
+ : `Open this link to approve this machine:\n${loginUrl}`)
80
+ const spinner = prompt.spinner()
81
+ spinner.start("Waiting for approval")
82
+ try {
83
+ const session = await waitForApproval({ appUrl, token })
84
+ spinner.stop(`Signed in${session.userEmail ? ` as ${session.userEmail}` : ""} · workspace ${style.bold(session.workspaceSlug ?? session.workspaceId)}`)
85
+ return session
86
+ } catch (error) {
87
+ spinner.error("Sign-in did not finish")
88
+ throw error
89
+ }
90
+ }
91
+
92
+ function gitRoot(dir) {
93
+ try {
94
+ return execSync("git rev-parse --show-toplevel", { cwd: dir, stdio: ["ignore", "pipe", "ignore"] }).toString().trim() || null
95
+ } catch {
96
+ return null
97
+ }
98
+ }
99
+
100
+ export async function chooseRepo(savedRepo) {
101
+ const here = gitRoot(process.cwd())
102
+ const options = []
103
+ if (here) options.push({ value: here, label: tildePath(here), hint: here === savedRepo ? "current · this folder" : "this folder" })
104
+ if (savedRepo && savedRepo !== here) options.push({ value: savedRepo, label: tildePath(savedRepo), hint: "current" })
105
+ options.push({ value: "other", label: "Another folder…" })
106
+
107
+ const choice = unlessCancelled(await prompt.select({
108
+ message: "Which folder should agents work in?",
109
+ options,
110
+ initialValue: savedRepo ?? here ?? "other",
111
+ }))
112
+ if (choice !== "other") return choice
113
+ const typed = unlessCancelled(await prompt.text({
114
+ message: "Folder path",
115
+ placeholder: "~/code/my-project",
116
+ validate: (value) => {
117
+ const resolved = resolvePath(value)
118
+ if (!resolved) return "Enter a path"
119
+ if (!fs.existsSync(resolved)) return "That folder does not exist"
120
+ return undefined
121
+ },
122
+ }))
123
+ const resolved = resolvePath(typed)
124
+ if (!gitRoot(resolved)) prompt.log.warn("That folder is not a git repository. Agents can still work there, but cannot open pull requests from it.")
125
+ return resolved
126
+ }
127
+
128
+ function resolvePath(value) {
129
+ const trimmed = String(value ?? "").trim()
130
+ if (!trimmed) return null
131
+ const expanded = trimmed.startsWith("~") ? path.join(process.env.HOME ?? "", trimmed.slice(1)) : trimmed
132
+ return path.resolve(expanded)
133
+ }
134
+
135
+ export async function chooseExecutor(savedExecutor) {
136
+ const tools = EXECUTORS.map((tool) => ({ ...tool, installed: checkBinaryExists(tool.bin) }))
137
+ const firstInstalled = tools.find((tool) => tool.installed)?.id
138
+ const choice = unlessCancelled(await prompt.select({
139
+ message: "Which AI tool should run the agents?",
140
+ options: tools.map((tool) => ({
141
+ value: tool.id,
142
+ label: tool.label,
143
+ hint: tool.installed ? (tool.id === savedExecutor ? "current · installed" : "installed") : `not found (\`${tool.bin}\`)`,
144
+ })),
145
+ initialValue: savedExecutor ?? firstInstalled ?? "claude_code",
146
+ }))
147
+ const picked = tools.find((tool) => tool.id === choice)
148
+ if (!picked.installed) prompt.log.warn(`\`${picked.bin}\` is not on your PATH yet. Install ${picked.label} before agents start working.`)
149
+ return choice
150
+ }
151
+
152
+ function saveSession(appUrl, session) {
153
+ const config = readConfig()
154
+ config.appUrl = appUrl
155
+ config.workspaceId = session.workspaceId
156
+ config.workspaceSlug = session.workspaceSlug
157
+ config.apiKey = session.apiKey
158
+ if (session.userName) config.userName = session.userName
159
+ if (session.userEmail) config.userEmail = session.userEmail
160
+ writeConfig(config)
161
+ }
162
+
163
+ function updateConfig(patch) {
164
+ writeConfig({ ...readConfig(), ...patch })
165
+ }
166
+
167
+ /**
168
+ * First run: four steps, then the runner starts in the background.
169
+ * `startRunner()` is supplied by the caller (it shells out to `pacework start`).
170
+ */
171
+ export async function runSetup({ startRunner }) {
172
+ const saved = readConfig()
173
+ prompt.intro(`${style.inverse(" pacework ")} Connect this machine`)
174
+ prompt.note(
175
+ "Agents in pacework pick up issues and work on them on this machine,\nin a folder you choose, with your own AI coding tool.",
176
+ "How it works",
177
+ )
178
+ const done = await step(async () => {
179
+ const { appUrl, session } = await chooseServerAndSignIn(saved.appUrl)
180
+ saveSession(appUrl, session)
181
+ const repoRoot = await chooseRepo(saved.repoRoot)
182
+ const executor = await chooseExecutor(saved.executor)
183
+ updateConfig({ repoRoot, executor, runnerName: saved.runnerName || EXECUTOR_DEFAULT_NAMES[executor] || "My Runner" })
184
+ return { appUrl, session, repoRoot, executor }
185
+ })
186
+ if (!done) return false
187
+
188
+ const spinner = prompt.spinner()
189
+ spinner.start("Starting the runner in the background")
190
+ const started = await startRunner()
191
+ if (started) spinner.stop("Runner is running")
192
+ else spinner.error("The runner did not start; see `pacework logs`")
193
+ prompt.outro(started
194
+ ? `Ready. Assign an issue to an agent in ${hostOf(done.appUrl)}; it will show up here.`
195
+ : "Setup is saved. Fix the problem above, then run `pacework start`.")
196
+ return true
197
+ }
198
+
199
+ /** Home screen actions: each changes one setting and reports whether it did. */
200
+ export async function switchServer() {
201
+ return await step(async () => {
202
+ const { appUrl, session } = await chooseServerAndSignIn(readConfig().appUrl)
203
+ saveSession(appUrl, session)
204
+ return true
205
+ }) ?? false
206
+ }
207
+
208
+ export async function changeRepo() {
209
+ return await step(async () => {
210
+ updateConfig({ repoRoot: await chooseRepo(readConfig().repoRoot) })
211
+ return true
212
+ }) ?? false
213
+ }
214
+
215
+ export async function changeExecutor() {
216
+ return await step(async () => {
217
+ const executor = await chooseExecutor(readConfig().executor)
218
+ updateConfig({ executor })
219
+ prompt.log.success(`Agents will use ${executorLabel(executor)}.`)
220
+ return true
221
+ }) ?? false
222
+ }