pacework 1.1.0 → 1.4.1
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/bin/pacework-runner-ctl.mjs +91 -60
- package/bin/pacework-runner.mjs +628 -95
- package/lib/automation-limits.mjs +23 -0
- package/lib/git-lock.mjs +83 -0
- package/lib/home.mjs +63 -6
- package/lib/issues-cli.mjs +80 -0
- package/lib/mcp-cli.mjs +177 -0
- package/lib/mcp-connect.mjs +159 -0
- package/lib/pr-base-branch.mjs +84 -0
- package/lib/push-retry.mjs +108 -0
- package/lib/run-limits.mjs +302 -0
- package/lib/runner-control.mjs +55 -0
- package/lib/skills.mjs +130 -0
- package/lib/triage-worker.mjs +29 -4
- package/lib/ui.mjs +11 -1
- package/lib/usage-limit.mjs +23 -0
- package/lib/version.mjs +27 -0
- package/lib/workspace-api.mjs +47 -0
- package/package.json +1 -1
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What an automation's run may do (PWK-72), or null for other runs. Older
|
|
3
|
+
* servers send nothing, and the run keeps the agent's usual tools.
|
|
4
|
+
*/
|
|
5
|
+
export function automationLimits(run) {
|
|
6
|
+
const caps = run?.automation_capabilities
|
|
7
|
+
if (!caps || typeof caps !== "object") return null
|
|
8
|
+
return {
|
|
9
|
+
web: caps.web_access === true,
|
|
10
|
+
code: caps.code_access === "read" || caps.code_access === "write" ? caps.code_access : "none",
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Claude Code permission rules that keep an automation's run to its web and code access. */
|
|
15
|
+
export function automationDenyRules(run) {
|
|
16
|
+
const limits = automationLimits(run)
|
|
17
|
+
if (!limits) return []
|
|
18
|
+
const deny = []
|
|
19
|
+
if (!limits.web) deny.push("WebFetch", "WebSearch")
|
|
20
|
+
if (limits.code === "none") deny.push("Read", "Glob", "Grep", "Edit", "Write", "NotebookEdit", "Bash")
|
|
21
|
+
if (limits.code === "read") deny.push("Edit", "Write", "NotebookEdit", "Bash")
|
|
22
|
+
return deny
|
|
23
|
+
}
|
package/lib/git-lock.mjs
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Preparing checkouts for runs that start at the same moment.
|
|
5
|
+
*
|
|
6
|
+
* Several runs in one repository each add a worktree, fetch and create a
|
|
7
|
+
* branch. Git guards .git/config, refs and the index with lock files, so two
|
|
8
|
+
* of those at once fail with "could not lock config file .git/config: File
|
|
9
|
+
* exists" and the run errors before the agent starts. Within one runner the
|
|
10
|
+
* setup now takes turns per repository; a lock held by another process (a
|
|
11
|
+
* second runner, a person's git command) is waited out and retried. Pushing
|
|
12
|
+
* takes the same turn: it rewrites the shared remote URL around the push.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** Waits between attempts when git reports a held lock: five tries over about 10 seconds. */
|
|
16
|
+
export const GIT_LOCK_RETRY_DELAYS_MS = [500, 1_500, 3_000, 5_000]
|
|
17
|
+
|
|
18
|
+
const LOCK_PATTERNS = [
|
|
19
|
+
/could not lock config file/i,
|
|
20
|
+
/unable to write upstream branch configuration/i,
|
|
21
|
+
/Unable to create '[^']*\.lock': File exists/i,
|
|
22
|
+
/cannot lock ref/i,
|
|
23
|
+
/another git process seems to be running/i,
|
|
24
|
+
]
|
|
25
|
+
|
|
26
|
+
/** Whether a git failure is a lock collision that waiting would clear. */
|
|
27
|
+
export function isGitLockError(error) {
|
|
28
|
+
const text = error instanceof Error ? error.message : String(error ?? "")
|
|
29
|
+
return LOCK_PATTERNS.some((pattern) => pattern.test(text))
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const queues = new Map()
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The key for a repository's lock: its shared .git directory, which every
|
|
36
|
+
* worktree of it writes to (config, refs). Falls back to the path itself.
|
|
37
|
+
*/
|
|
38
|
+
export function repoLockKey(dir) {
|
|
39
|
+
try {
|
|
40
|
+
return execFileSync("git", ["-C", dir, "rev-parse", "--path-format=absolute", "--git-common-dir"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim() || dir
|
|
41
|
+
} catch {
|
|
42
|
+
return dir
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Run `fn` after every earlier call for the same repository has finished. */
|
|
47
|
+
export function withRepoLock(repo, fn) {
|
|
48
|
+
const previous = queues.get(repo) ?? Promise.resolve()
|
|
49
|
+
const result = previous.then(fn, fn)
|
|
50
|
+
// The next caller waits for this one to settle, whether it failed or not.
|
|
51
|
+
const settled = result.then(() => undefined, () => undefined)
|
|
52
|
+
queues.set(repo, settled)
|
|
53
|
+
settled.then(() => { if (queues.get(repo) === settled) queues.delete(repo) })
|
|
54
|
+
return result
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Run `fn`, retrying while git reports a held lock. `fn` must be safe to run
|
|
59
|
+
* again after a partial failure. A collision that outlasts the retries is
|
|
60
|
+
* rethrown with a message that says what happened.
|
|
61
|
+
*/
|
|
62
|
+
export async function retryGitLock(fn, { delays = GIT_LOCK_RETRY_DELAYS_MS, sleep = defaultSleep, onRetry = () => {} } = {}) {
|
|
63
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
64
|
+
try {
|
|
65
|
+
return await fn()
|
|
66
|
+
} catch (error) {
|
|
67
|
+
if (!isGitLockError(error)) throw error
|
|
68
|
+
if (attempt >= delays.length) {
|
|
69
|
+
const detail = error instanceof Error ? error.message : String(error)
|
|
70
|
+
throw new Error(
|
|
71
|
+
`Another git process kept the repository locked while this run's checkout was prepared (${attempt + 1} tries). ` +
|
|
72
|
+
`This is a timing collision, not a problem with the issue: re-run the agent.\n${detail}`,
|
|
73
|
+
)
|
|
74
|
+
}
|
|
75
|
+
onRetry(attempt + 1, error)
|
|
76
|
+
await sleep(delays[attempt])
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function defaultSleep(ms) {
|
|
82
|
+
return new Promise((resolve) => setTimeout(resolve, ms))
|
|
83
|
+
}
|
package/lib/home.mjs
CHANGED
|
@@ -5,7 +5,9 @@ import { executorLabel } from "./executors.mjs"
|
|
|
5
5
|
import { openInBrowser } from "./login.mjs"
|
|
6
6
|
import { changeExecutor, changeRepo, switchServer } from "./setup.mjs"
|
|
7
7
|
import { TRIAGE_EXECUTORS } from "./triage-worker.mjs"
|
|
8
|
-
import { LOGO, formatDuration, hostOf, relativeTime, style, tildePath, truncate } from "./ui.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"
|
|
9
11
|
|
|
10
12
|
/**
|
|
11
13
|
* The live home screen behind a bare `pacework`: where this machine is
|
|
@@ -15,10 +17,12 @@ import { LOGO, formatDuration, hostOf, relativeTime, style, tildePath, truncate
|
|
|
15
17
|
*/
|
|
16
18
|
const KEYS = [
|
|
17
19
|
["s", "start/stop"],
|
|
20
|
+
["i", "issues"],
|
|
21
|
+
["m", "MCP"],
|
|
18
22
|
["l", "logs"],
|
|
19
23
|
["w", "switch"],
|
|
20
24
|
["r", "repo"],
|
|
21
|
-
["e", "AI
|
|
25
|
+
["e", "agent AI"],
|
|
22
26
|
["o", "open"],
|
|
23
27
|
["d", "doctor"],
|
|
24
28
|
["?", "help"],
|
|
@@ -27,16 +31,20 @@ const KEYS = [
|
|
|
27
31
|
|
|
28
32
|
const HELP = [
|
|
29
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"],
|
|
30
36
|
["l", "Show the live runner log"],
|
|
31
37
|
["w", "Switch to another pacework server or workspace (signs in again)"],
|
|
32
38
|
["r", "Change the folder agents work in"],
|
|
33
|
-
["e", "Change the AI tool agents
|
|
39
|
+
["e", "Change the AI tool agents run on (Claude Code, Codex, …)"],
|
|
34
40
|
["o", "Open this workspace in your browser"],
|
|
35
41
|
["d", "Run the health check"],
|
|
36
42
|
["q", "Quit this screen; the runner keeps working in the background"],
|
|
37
43
|
]
|
|
38
44
|
|
|
39
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"],
|
|
40
48
|
["pacework status [--json]", "Is the runner up, and what is it doing"],
|
|
41
49
|
["pacework start | stop", "Start or stop the background runner"],
|
|
42
50
|
["pacework logs", "Follow the runner log"],
|
|
@@ -87,6 +95,7 @@ export async function runHome({ ctlScript, version }) {
|
|
|
87
95
|
const stdin = process.stdin
|
|
88
96
|
const stdout = process.stdout
|
|
89
97
|
let mode = "home"
|
|
98
|
+
let issues = { state: "idle", items: [], selected: 0, error: null }
|
|
90
99
|
let flash = null
|
|
91
100
|
let busy = false
|
|
92
101
|
let timer = null
|
|
@@ -100,7 +109,13 @@ export async function runHome({ ctlScript, version }) {
|
|
|
100
109
|
const config = readConfig()
|
|
101
110
|
const lines = []
|
|
102
111
|
|
|
103
|
-
|
|
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
|
+
}
|
|
104
119
|
lines.push(` ${style.gray(`${hostOf(snapshot.appUrl)} · ${snapshot.workspace ?? "no workspace"}`)}`)
|
|
105
120
|
const state = snapshot.running ? `${style.green("●")} running` : `${style.gray("○")} stopped`
|
|
106
121
|
const tool = executorLabel(snapshot.executor)
|
|
@@ -108,7 +123,19 @@ export async function runHome({ ctlScript, version }) {
|
|
|
108
123
|
lines.push(` ${state} ${tildePath(snapshot.repoRoot) || style.yellow("no folder set")} ${style.gray("·")} ${tool} ${style.gray("·")} ${style.gray(work)}`)
|
|
109
124
|
lines.push("")
|
|
110
125
|
|
|
111
|
-
if (mode === "
|
|
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") {
|
|
112
139
|
lines.push(` ${style.bold("Log")} ${style.gray("live · press l or Esc to go back")}`)
|
|
113
140
|
const room = height - lines.length - 2
|
|
114
141
|
for (const entry of snapshot.logs.slice(-room)) {
|
|
@@ -152,7 +179,7 @@ export async function runHome({ ctlScript, version }) {
|
|
|
152
179
|
if (flash && flash.until < Date.now()) flash = null
|
|
153
180
|
const flashText = busy ? style.brand(`${busy}…`) : flash ? (flash.tone === "error" ? style.red(flash.text) : style.green(flash.text)) : ""
|
|
154
181
|
lines.push(` ${truncate(flashText, width + 20)}`)
|
|
155
|
-
lines.push(` ${KEYS.map(([key, label]) => `${style.bold(key)} ${style.gray(label)}`).join("
|
|
182
|
+
lines.push(` ${KEYS.map(([key, label]) => `${style.bold(key)} ${style.gray(label)}`).join(" ")}`)
|
|
156
183
|
|
|
157
184
|
stdout.write(`\x1b[H${lines.slice(0, height).map((line) => `${line}\x1b[K`).join("\n")}\x1b[J`)
|
|
158
185
|
}
|
|
@@ -215,16 +242,46 @@ export async function runHome({ ctlScript, version }) {
|
|
|
215
242
|
process.exit(0)
|
|
216
243
|
}
|
|
217
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
|
+
|
|
218
257
|
async function onKey(text, key = {}) {
|
|
219
258
|
if (key.ctrl && key.name === "c") return quit()
|
|
220
259
|
if (busy) return
|
|
221
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
|
+
}
|
|
222
272
|
if (mode !== "home" && (name === "escape" || (mode === "logs" && name === "l") || (mode === "help" && text === "?"))) {
|
|
223
273
|
mode = "home"
|
|
224
274
|
return render()
|
|
225
275
|
}
|
|
226
276
|
if (name === "q") return quit()
|
|
227
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
|
+
}
|
|
228
285
|
if (text === "?") { mode = "help"; return render() }
|
|
229
286
|
if (name === "s") {
|
|
230
287
|
const running = readRunnerSnapshot({ logLines: 1 }).running
|
|
@@ -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/mcp-cli.mjs
ADDED
|
@@ -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
|
+
}
|