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.
@@ -0,0 +1,177 @@
1
+ import { spawnSync } from "node:child_process"
2
+ import * as prompt from "@clack/prompts"
3
+ import { mcpStatus, mcpTools, mcpUrlFor, resolveToolIds } from "./mcp-connect.mjs"
4
+ import { currentSession } from "./workspace-api.mjs"
5
+ import { LOGO, style } from "./ui.mjs"
6
+
7
+ /**
8
+ * The `pacework mcp` subcommands. In a terminal, `add` and `remove` let you pick
9
+ * tools with the arrow keys; with tool names (or --all) they run without asking.
10
+ * Returns the exit code.
11
+ */
12
+ export async function runMcpCommand(sub, names, flags) {
13
+ let session
14
+ try {
15
+ session = currentSession()
16
+ } catch (error) {
17
+ console.error(error.message)
18
+ return 1
19
+ }
20
+ const url = mcpUrlFor(session.appUrl)
21
+
22
+ if (sub === "status" || sub === "list") {
23
+ printStatus(url)
24
+ return 0
25
+ }
26
+ if (sub === "add" || sub === "connect") return await add(url, names, flags)
27
+ if (sub === "remove" || sub === "disconnect") return await remove(names, flags)
28
+ console.log(`Usage: pacework mcp [add|status|remove] [tool…] [--all]\nTools: ${mcpTools().map((tool) => tool.id).join(", ")}`)
29
+ return sub === "help" ? 0 : 1
30
+ }
31
+
32
+ function printStatus(url) {
33
+ const entries = mcpStatus()
34
+ const width = Math.max(...entries.map((entry) => entry.tool.label.length))
35
+ console.log(`\n ${LOGO} ${style.bold("AI tools")} ${style.gray(`connected to ${url}`)}\n`)
36
+ for (const { tool, installed, connected } of entries) {
37
+ const mark = !installed ? style.gray("·") : connected ? style.green("✓") : style.gray("○")
38
+ const note = !installed ? style.gray("not installed") : connected ? "connected" : style.gray("not connected")
39
+ console.log(` ${mark} ${tool.label.padEnd(width)} ${note}`)
40
+ }
41
+ const unconnected = entries.filter((entry) => entry.installed && !entry.connected).length
42
+ console.log(style.gray(`\n ${unconnected ? "pacework mcp add connect the others" : "pacework mcp remove disconnect a tool"}\n`))
43
+ }
44
+
45
+ async function pickTools({ message, candidates, initial }) {
46
+ if (!candidates.length) return []
47
+ const picked = await prompt.multiselect({
48
+ message,
49
+ options: candidates.map(({ tool, connected }) => ({ value: tool.id, label: tool.label, hint: connected ? "already connected" : undefined })),
50
+ initialValues: initial,
51
+ required: false,
52
+ })
53
+ return prompt.isCancel(picked) ? null : picked
54
+ }
55
+
56
+ /** Name the tools for a sentence: "Claude Code", "Claude Code and Codex", "A, B and C". */
57
+ function listNames(names) {
58
+ return names.length <= 1 ? (names[0] ?? "") : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`
59
+ }
60
+
61
+ async function add(url, names, flags) {
62
+ const status = mcpStatus()
63
+ const interactive = process.stdin.isTTY && !names.length && !flags.all
64
+ let ids
65
+ if (flags.all) ids = status.filter((entry) => entry.installed).map((entry) => entry.tool.id)
66
+ else if (names.length) {
67
+ const { ids: resolved, unknown } = resolveToolIds(names)
68
+ if (unknown.length) console.error(`Unknown tool: ${unknown.join(", ")}. Known: ${mcpTools().map((tool) => tool.id).join(", ")}`)
69
+ ids = resolved
70
+ } else if (interactive) {
71
+ prompt.intro(`${style.inverse(" pacework ")} Connect your AI tools`)
72
+ prompt.log.message("Your AI tools get pacework's tools, so you can ask them about your\nissues, update them, or create new ones, right where you work.")
73
+ const installed = status.filter((entry) => entry.installed)
74
+ const missing = status.filter((entry) => !entry.installed)
75
+ if (!installed.length) {
76
+ prompt.outro(`None of ${listNames(status.map((entry) => entry.tool.label))} is installed on this machine.`)
77
+ return 1
78
+ }
79
+ ids = await pickTools({
80
+ message: "Which tools should use pacework?",
81
+ candidates: installed,
82
+ initial: installed.filter((entry) => !entry.connected).map((entry) => entry.tool.id),
83
+ })
84
+ if (ids === null) {
85
+ prompt.cancel("Nothing changed.")
86
+ return 0
87
+ }
88
+ if (missing.length) prompt.log.message(style.gray(`Not installed here: ${listNames(missing.map((entry) => entry.tool.label))}.`))
89
+ if (!ids.length) {
90
+ prompt.outro("No tools selected; nothing changed.")
91
+ return 0
92
+ }
93
+ } else {
94
+ console.error("Name the tools to connect (e.g. `pacework mcp add claude cursor`) or pass --all.")
95
+ return 1
96
+ }
97
+
98
+ const connected = []
99
+ let failed = 0
100
+ for (const id of ids) {
101
+ const entry = status.find((candidate) => candidate.tool.id === id)
102
+ if (!entry.installed) {
103
+ if (interactive) prompt.log.warn(`${entry.tool.label} is not installed here; skipped.`)
104
+ else console.log(` ! ${entry.tool.label} is not installed here; skipped.`)
105
+ continue
106
+ }
107
+ const spinner = interactive ? prompt.spinner() : null
108
+ spinner?.start(`Connecting ${entry.tool.label}`)
109
+ try {
110
+ entry.tool.connect(url)
111
+ connected.push(entry.tool)
112
+ if (spinner) spinner.stop(`${entry.tool.label} connected`)
113
+ else console.log(` ✓ ${entry.tool.label}: ${entry.tool.signIn}`)
114
+ } catch (error) {
115
+ failed++
116
+ if (spinner) spinner.error(`${entry.tool.label}: ${error.message}`)
117
+ else console.log(` ✗ ${entry.tool.label}: ${error.message}`)
118
+ }
119
+ }
120
+ if (!interactive) return failed ? 1 : 0
121
+ if (!connected.length) {
122
+ prompt.outro("Nothing was connected. See the messages above.")
123
+ return 1
124
+ }
125
+
126
+ // One short list of how each tool signs in, instead of a hint per line.
127
+ const width = Math.max(...connected.map((tool) => tool.label.length))
128
+ prompt.note(connected.map((tool) => `${tool.label.padEnd(width)} ${style.gray(tool.signIn)}`).join("\n"), "Next: sign in once per tool")
129
+
130
+ // Codex signs in with a command rather than on first use; offer to run it now.
131
+ for (const tool of connected.filter((candidate) => candidate.loginCommand)) {
132
+ const now = await prompt.confirm({ message: `Sign ${tool.label} in now? (opens your browser)`, initialValue: true })
133
+ if (prompt.isCancel(now) || !now) continue
134
+ prompt.log.step(`${tool.label} sign-in`)
135
+ const [command, args] = tool.loginCommand
136
+ const result = spawnSync(command, args, { stdio: "inherit" })
137
+ if (result.status === 0) prompt.log.success(`${tool.label} is signed in.`)
138
+ else prompt.log.warn(`${tool.label} sign-in did not finish. Run it later: ${[command, ...args].join(" ")}`)
139
+ }
140
+
141
+ const example = connected.find((tool) => tool.tryIt)
142
+ prompt.outro(failed
143
+ ? `Connected ${listNames(connected.map((tool) => tool.label))}; see the error above for the rest.`
144
+ : `Done. Try it${example ? `: run \`${example.tryIt}\` and` : ","} ask "What's assigned to me in pacework?"`)
145
+ return failed ? 1 : 0
146
+ }
147
+
148
+ async function remove(names, flags) {
149
+ const status = mcpStatus()
150
+ let ids
151
+ if (flags.all) ids = status.filter((entry) => entry.connected).map((entry) => entry.tool.id)
152
+ else if (names.length) ids = resolveToolIds(names).ids
153
+ else if (process.stdin.isTTY) {
154
+ const connected = status.filter((entry) => entry.connected)
155
+ if (!connected.length) {
156
+ console.log("No AI tool is connected to pacework.")
157
+ return 0
158
+ }
159
+ ids = await pickTools({ message: "Disconnect which tools?", candidates: connected, initial: [] })
160
+ if (ids === null) return 0
161
+ } else {
162
+ console.error("Name the tools to disconnect, or pass --all.")
163
+ return 1
164
+ }
165
+ let failed = 0
166
+ for (const id of ids) {
167
+ const entry = status.find((candidate) => candidate.tool.id === id)
168
+ try {
169
+ entry.tool.disconnect()
170
+ console.log(` ${style.green("✓")} ${entry.tool.label} disconnected`)
171
+ } catch (error) {
172
+ failed++
173
+ console.log(` ${style.red("✗")} ${entry.tool.label}: ${error.message}`)
174
+ }
175
+ }
176
+ return failed ? 1 : 0
177
+ }
@@ -0,0 +1,159 @@
1
+ import fs from "node:fs"
2
+ import os from "node:os"
3
+ import path from "node:path"
4
+ import { spawnSync } from "node:child_process"
5
+ import { checkBinaryExists } from "./executors.mjs"
6
+
7
+ /**
8
+ * `pacework mcp`: register pacework's MCP server in the AI tools on this
9
+ * machine, so they can read and update issues from the editor or terminal. No
10
+ * key is written anywhere: the server asks each tool to sign in with OAuth the
11
+ * first time it connects. Tools with an `mcp` command are configured through
12
+ * it; the others through their config file.
13
+ */
14
+ export const SERVER_NAME = "pacework"
15
+
16
+ export function mcpUrlFor(appUrl) {
17
+ return `${String(appUrl).replace(/\/$/, "")}/api/mcp`
18
+ }
19
+
20
+ function run(command, args) {
21
+ const result = spawnSync(command, args, { encoding: "utf8", timeout: 30_000 })
22
+ return { ok: result.status === 0, output: `${result.stdout ?? ""}${result.stderr ?? ""}`.trim() }
23
+ }
24
+
25
+ function readJsonFile(file) {
26
+ if (!fs.existsSync(file)) return {}
27
+ const text = fs.readFileSync(file, "utf8")
28
+ if (!text.trim()) return {}
29
+ try {
30
+ return JSON.parse(text)
31
+ } catch {
32
+ // VS Code and Cursor accept comments in these files; rewriting one would drop them.
33
+ throw new Error(`${file} could not be read as plain JSON (it may contain comments), so it was left alone.`)
34
+ }
35
+ }
36
+
37
+ function writeJsonFile(file, data) {
38
+ fs.mkdirSync(path.dirname(file), { recursive: true })
39
+ fs.writeFileSync(file, `${JSON.stringify(data, null, 2)}\n`)
40
+ }
41
+
42
+ /** A tool configured through a JSON file: `section` holds the servers, `entry(url)` one server. */
43
+ function jsonFileTool({ id, label, file, section, entry, detect, signIn }) {
44
+ return {
45
+ id,
46
+ label,
47
+ signIn,
48
+ detect,
49
+ connected: () => {
50
+ try {
51
+ return Boolean(readJsonFile(file)?.[section]?.[SERVER_NAME])
52
+ } catch {
53
+ return false
54
+ }
55
+ },
56
+ connect: (url) => {
57
+ const data = readJsonFile(file)
58
+ data[section] = { ...(data[section] ?? {}), [SERVER_NAME]: entry(url) }
59
+ writeJsonFile(file, data)
60
+ },
61
+ disconnect: () => {
62
+ const data = readJsonFile(file)
63
+ if (!data[section]?.[SERVER_NAME]) return
64
+ delete data[section][SERVER_NAME]
65
+ writeJsonFile(file, data)
66
+ },
67
+ }
68
+ }
69
+
70
+ function vscodeUserDir() {
71
+ if (process.platform === "darwin") return path.join(os.homedir(), "Library", "Application Support", "Code", "User")
72
+ if (process.platform === "win32") return path.join(process.env.APPDATA ?? path.join(os.homedir(), "AppData", "Roaming"), "Code", "User")
73
+ return path.join(os.homedir(), ".config", "Code", "User")
74
+ }
75
+
76
+ function commandResult(result, action) {
77
+ if (!result.ok) throw new Error(`${action} failed: ${result.output.split("\n").pop() || "no output"}`)
78
+ }
79
+
80
+ export function mcpTools() {
81
+ return [
82
+ {
83
+ id: "claude",
84
+ label: "Claude Code",
85
+ signIn: "signs in the first time you ask it about pacework",
86
+ tryIt: "claude",
87
+ detect: () => checkBinaryExists("claude"),
88
+ connected: () => run("claude", ["mcp", "get", SERVER_NAME]).ok,
89
+ connect: (url) => {
90
+ run("claude", ["mcp", "remove", SERVER_NAME, "--scope", "user"])
91
+ commandResult(run("claude", ["mcp", "add", "--transport", "http", "--scope", "user", SERVER_NAME, url]), "claude mcp add")
92
+ },
93
+ disconnect: () => commandResult(run("claude", ["mcp", "remove", SERVER_NAME, "--scope", "user"]), "claude mcp remove"),
94
+ },
95
+ {
96
+ id: "codex",
97
+ label: "Codex",
98
+ signIn: "needs one sign-in: codex mcp login pacework",
99
+ tryIt: "codex",
100
+ loginCommand: ["codex", ["mcp", "login", SERVER_NAME]],
101
+ detect: () => checkBinaryExists("codex"),
102
+ connected: () => run("codex", ["mcp", "get", SERVER_NAME]).ok,
103
+ connect: (url) => {
104
+ run("codex", ["mcp", "remove", SERVER_NAME])
105
+ commandResult(run("codex", ["mcp", "add", SERVER_NAME, "--url", url]), "codex mcp add")
106
+ },
107
+ disconnect: () => commandResult(run("codex", ["mcp", "remove", SERVER_NAME]), "codex mcp remove"),
108
+ },
109
+ jsonFileTool({
110
+ id: "gemini",
111
+ label: "Gemini CLI",
112
+ file: path.join(os.homedir(), ".gemini", "settings.json"),
113
+ section: "mcpServers",
114
+ entry: (url) => ({ httpUrl: url }),
115
+ detect: () => checkBinaryExists("gemini") || fs.existsSync(path.join(os.homedir(), ".gemini")),
116
+ signIn: "signs in the first time you ask it about pacework",
117
+ }),
118
+ jsonFileTool({
119
+ id: "cursor",
120
+ label: "Cursor",
121
+ file: path.join(os.homedir(), ".cursor", "mcp.json"),
122
+ section: "mcpServers",
123
+ entry: (url) => ({ url }),
124
+ detect: () => checkBinaryExists("cursor") || fs.existsSync(path.join(os.homedir(), ".cursor")),
125
+ signIn: "click Connect next to pacework in Settings → MCP",
126
+ }),
127
+ jsonFileTool({
128
+ id: "vscode",
129
+ label: "VS Code",
130
+ file: path.join(vscodeUserDir(), "mcp.json"),
131
+ section: "servers",
132
+ entry: (url) => ({ type: "http", url }),
133
+ detect: () => checkBinaryExists("code") || fs.existsSync(vscodeUserDir()),
134
+ signIn: "signs in the first time Copilot uses pacework",
135
+ }),
136
+ ]
137
+ }
138
+
139
+ /** Every known tool with whether it is installed and already connected. */
140
+ export function mcpStatus() {
141
+ return mcpTools().map((tool) => {
142
+ const installed = tool.detect()
143
+ return { tool, installed, connected: installed ? tool.connected() : false }
144
+ })
145
+ }
146
+
147
+ /** Tool ids from user input ("claude", "Claude Code", "vs-code"), unknown ones reported. */
148
+ export function resolveToolIds(names) {
149
+ const tools = mcpTools()
150
+ const normalize = (value) => String(value).toLowerCase().replace(/[^a-z]/g, "")
151
+ const found = []
152
+ const unknown = []
153
+ for (const name of names) {
154
+ const match = tools.find((tool) => normalize(tool.id) === normalize(name) || normalize(tool.label) === normalize(name) || normalize(tool.label).startsWith(normalize(name)))
155
+ if (match) found.push(match.id)
156
+ else unknown.push(name)
157
+ }
158
+ return { ids: [...new Set(found)], unknown }
159
+ }
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
+ }