pacework 0.0.0-stage → 1.0.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,260 @@
1
+ #!/usr/bin/env node
2
+ // Must run before anything reads the environment (see the file).
3
+ import "../lib/legacy-env.mjs"
4
+
5
+ import fs from "node:fs"
6
+ import path from "node:path"
7
+ import process from "node:process"
8
+ import { spawnSync } from "node:child_process"
9
+ import { fileURLToPath } from "node:url"
10
+ import {
11
+ isRunning,
12
+ readConfig,
13
+ readPid,
14
+ readRunnerSnapshot,
15
+ writeConfig,
16
+ } from "../lib/control-state.mjs"
17
+
18
+ const command = process.argv[2] ?? "snapshot"
19
+ const args = process.argv.slice(3)
20
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
21
+ const ctlScript = path.join(__dirname, "pacework-runner-ctl.mjs")
22
+
23
+ function respond(payload, exitCode = 0) {
24
+ process.stdout.write(`${JSON.stringify(payload)}\n`)
25
+ process.exit(exitCode)
26
+ }
27
+
28
+ function stripAnsi(value) {
29
+ return String(value ?? "").replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").trim()
30
+ }
31
+
32
+ function runCtl(ctlArgs, timeout = 30_000) {
33
+ const result = spawnSync(process.execPath, [ctlScript, ...ctlArgs], {
34
+ encoding: "utf8",
35
+ env: process.env,
36
+ timeout,
37
+ })
38
+ const output = stripAnsi([result.stdout, result.stderr].filter(Boolean).join("\n"))
39
+ return {
40
+ ok: !result.error && result.status === 0,
41
+ output,
42
+ error: result.error?.message ?? (result.status === 0 ? null : output || `Command exited with ${result.status}`),
43
+ }
44
+ }
45
+
46
+ function connection() {
47
+ const config = readConfig()
48
+ const key = config.apiKey ?? config.workspaceApiKey
49
+ const workspaceId = config.workspaceId
50
+ const appUrl = String(config.appUrl ?? "https://pacework.io").replace(/\/$/, "")
51
+ if (!key || !workspaceId) throw new Error("This Mac is not connected. Run pacework login first.")
52
+ return { config, key, workspaceId, appUrl }
53
+ }
54
+
55
+ function readRunnerId(config) {
56
+ try {
57
+ const file = path.join(config.repoRoot ?? process.cwd(), ".agent", "runners", `${config.workspaceId}-${config.executor ?? "codex"}.json`)
58
+ return JSON.parse(fs.readFileSync(file, "utf8")).runner_id ?? null
59
+ } catch {
60
+ return null
61
+ }
62
+ }
63
+
64
+ async function requestJson(route, options = {}) {
65
+ const { key, appUrl } = connection()
66
+ const response = await fetch(`${appUrl}${route}`, {
67
+ ...options,
68
+ headers: {
69
+ "content-type": "application/json",
70
+ "x-workspace-api-key": key,
71
+ Authorization: `Bearer ${key}`,
72
+ ...options.headers,
73
+ },
74
+ signal: AbortSignal.timeout(8_000),
75
+ })
76
+ const body = await response.json().catch(() => ({}))
77
+ if (!response.ok) throw new Error(body.message ?? body.error ?? `pacework returned ${response.status}`)
78
+ return body
79
+ }
80
+
81
+ async function diagnostics() {
82
+ const config = readConfig()
83
+ const executorBins = {
84
+ claude_code: "claude",
85
+ codex: "codex",
86
+ gemini: "gemini",
87
+ cursor_agent: "cursor",
88
+ github_copilot: "gh",
89
+ }
90
+ const checks = []
91
+ const add = (id, label, status, detail) => checks.push({ id, label, status, detail })
92
+ add("node", "Node.js runtime", Number(process.versions.node.split(".")[0]) >= 18 ? "pass" : "fail", `v${process.versions.node}`)
93
+ add("auth", "Workspace authentication", config.apiKey && config.workspaceId ? "pass" : "fail", config.workspaceSlug ?? config.workspaceId ?? "Not connected")
94
+ add("repo", "Repository", config.repoRoot && fs.existsSync(config.repoRoot) ? "pass" : "fail", config.repoRoot ?? "Not configured")
95
+ const executor = config.executor ?? "codex"
96
+ const executorBin = executorBins[executor] ?? executor
97
+ const binary = spawnSync("/usr/bin/env", ["which", executorBin], { encoding: "utf8" })
98
+ add("executor", "Executor binary", binary.status === 0 ? "pass" : "fail", binary.status === 0 ? binary.stdout.trim() : `${executorBin} not found`)
99
+ const pid = readPid()
100
+ add("process", "Runner process", pid && isRunning(pid) ? "pass" : "info", pid && isRunning(pid) ? `PID ${pid}` : "Stopped")
101
+ if (config.appUrl) {
102
+ try {
103
+ const response = await fetch(`${String(config.appUrl).replace(/\/$/, "")}/api/health`, { signal: AbortSignal.timeout(4_000) })
104
+ add("server", "pacework server", response.ok || response.status === 404 ? "pass" : "warn", `${config.appUrl} · HTTP ${response.status}`)
105
+ } catch (error) {
106
+ add("server", "pacework server", "fail", error.message)
107
+ }
108
+ }
109
+ return checks
110
+ }
111
+
112
+ if (command === "snapshot") {
113
+ respond({ ok: true, snapshot: readRunnerSnapshot() })
114
+ }
115
+
116
+ if (["start", "stop", "restart"].includes(command)) {
117
+ const commands = command === "restart" ? ["stop", "start"] : [command]
118
+ const output = []
119
+ for (const runnerCommand of commands) {
120
+ const result = runCtl([runnerCommand])
121
+ output.push(result.output)
122
+ if (!result.ok) respond({ ok: false, error: result.error, snapshot: readRunnerSnapshot() }, 1)
123
+ }
124
+ respond({ ok: true, output: output.filter(Boolean).join("\n"), snapshot: readRunnerSnapshot() })
125
+ }
126
+
127
+ if (command === "doctor") {
128
+ try {
129
+ respond({ ok: true, checks: await diagnostics(), snapshot: readRunnerSnapshot() })
130
+ } catch (error) {
131
+ respond({ ok: false, error: error.message, snapshot: readRunnerSnapshot() }, 1)
132
+ }
133
+ }
134
+
135
+ if (command === "login-start") {
136
+ try {
137
+ const appUrl = String(args[0] || readConfig().appUrl || "https://pacework.io").replace(/\/$/, "")
138
+ const response = await fetch(`${appUrl}/api/cli/login`, {
139
+ method: "POST",
140
+ headers: { "content-type": "application/json" },
141
+ body: "{}",
142
+ signal: AbortSignal.timeout(8_000),
143
+ })
144
+ const data = await response.json().catch(() => ({}))
145
+ if (!response.ok) throw new Error(data.message ?? data.error ?? `pacework returned ${response.status}`)
146
+ respond({ ok: true, data: { ...data, appUrl } })
147
+ } catch (error) {
148
+ respond({ ok: false, error: error.message }, 1)
149
+ }
150
+ }
151
+
152
+ if (command === "login-poll") {
153
+ try {
154
+ const appUrl = String(args[0] || "https://pacework.io").replace(/\/$/, "")
155
+ const token = args[1]
156
+ if (!token) throw new Error("Missing login token")
157
+ const response = await fetch(`${appUrl}/api/cli/login?token=${encodeURIComponent(token)}`, { signal: AbortSignal.timeout(8_000) })
158
+ const data = await response.json().catch(() => ({}))
159
+ if (!response.ok) throw new Error(data.message ?? data.error ?? `pacework returned ${response.status}`)
160
+ if (data.status === "authorized") {
161
+ const config = readConfig()
162
+ writeConfig({
163
+ ...config,
164
+ appUrl,
165
+ workspaceId: data.workspaceId,
166
+ workspaceSlug: data.workspaceSlug,
167
+ apiKey: data.apiKey,
168
+ userName: data.userName ?? config.userName,
169
+ userEmail: data.userEmail ?? config.userEmail,
170
+ executor: config.executor ?? "codex",
171
+ runnerName: config.runnerName ?? "Codex Dev",
172
+ })
173
+ }
174
+ respond({ ok: true, data, snapshot: readRunnerSnapshot() })
175
+ } catch (error) {
176
+ respond({ ok: false, error: error.message }, 1)
177
+ }
178
+ }
179
+
180
+ if (command === "logout") {
181
+ const result = runCtl(["logout"])
182
+ respond({ ...result, snapshot: readRunnerSnapshot() }, result.ok ? 0 : 1)
183
+ }
184
+
185
+ if (command === "cli") {
186
+ const allowed = new Set(["status", "jobs", "logs", "doctor", "config", "use"])
187
+ if (!allowed.has(args[0])) respond({ ok: false, error: `Desktop command not allowed: ${args[0] ?? ""}` }, 2)
188
+ const ctlArgs = args[0] === "use" ? ["config", "executor", args[1]] : args
189
+ const result = runCtl(ctlArgs)
190
+ respond({ ...result, snapshot: readRunnerSnapshot() }, result.ok ? 0 : 1)
191
+ }
192
+
193
+ if (command === "query") {
194
+ try {
195
+ const { workspaceId } = connection()
196
+ const kind = args[0]
197
+ const value = args[1]
198
+ let data
199
+ if (kind === "issues") data = await requestJson(`/api/workspaces/${workspaceId}/cli/issues?status=${encodeURIComponent(value || "open")}&limit=100`)
200
+ else if (kind === "mine") data = await requestJson(`/api/workspaces/${workspaceId}/cli/my-issues?limit=100`)
201
+ else if (kind === "issue") data = await requestJson(`/api/workspaces/${workspaceId}/cli/issue/${encodeURIComponent(String(value || "").toUpperCase())}`)
202
+ else if (kind === "agents") data = await requestJson(`/api/workspaces/${workspaceId}/cli/agents`)
203
+ else if (kind === "dashboard") data = await requestJson(`/api/workspaces/${workspaceId}/cli/orchestration`)
204
+ else throw new Error(`Unsupported query: ${kind}`)
205
+ respond({ ok: true, data })
206
+ } catch (error) {
207
+ respond({ ok: false, error: error.message }, 1)
208
+ }
209
+ }
210
+
211
+ if (command === "control") {
212
+ try {
213
+ const { config, workspaceId } = connection()
214
+ const runnerId = readRunnerId(config)
215
+ if (!runnerId) throw new Error("Runner ID not found. Start the runner once so it can register.")
216
+ const action = args[0]
217
+ const payload = action === "capacity"
218
+ ? { action: "set_capacity", max_parallel_runs: Math.max(1, Math.min(20, Number(args[1]) || 1)) }
219
+ : { action }
220
+ const data = await requestJson(`/api/workspaces/${workspaceId}/agent-runners/${runnerId}/control`, {
221
+ method: "POST",
222
+ body: JSON.stringify(payload),
223
+ })
224
+ respond({ ok: true, data, snapshot: readRunnerSnapshot() })
225
+ } catch (error) {
226
+ respond({ ok: false, error: error.message, snapshot: readRunnerSnapshot() }, 1)
227
+ }
228
+ }
229
+
230
+ if (command === "run-action") {
231
+ try {
232
+ const { workspaceId } = connection()
233
+ const action = args[0]
234
+ const runId = args[1]
235
+ if (!runId || !["cancel", "retry"].includes(action)) throw new Error("A valid run action and run ID are required.")
236
+ const data = await requestJson(`/api/workspaces/${workspaceId}/agent-runs/${encodeURIComponent(runId)}/${action}`, { method: "POST", body: "{}" })
237
+ respond({ ok: true, data })
238
+ } catch (error) {
239
+ respond({ ok: false, error: error.message }, 1)
240
+ }
241
+ }
242
+
243
+ if (command === "dispatch") {
244
+ try {
245
+ const { workspaceId } = connection()
246
+ const issueRef = String(args[0] ?? "").toUpperCase()
247
+ const issueData = await requestJson(`/api/workspaces/${workspaceId}/cli/issues?status=all&limit=100`)
248
+ const issues = issueData.issues ?? issueData.data ?? []
249
+ const issue = issues.find(item => String(item.identifier).toUpperCase() === issueRef)
250
+ if (!issue) throw new Error(`Issue not found: ${issueRef}`)
251
+ const payload = { task_id: issue.id, workspace_id: workspaceId }
252
+ if (args[1]) payload.agent_id = args[1]
253
+ const data = await requestJson("/api/agent-planner/dispatch", { method: "POST", body: JSON.stringify(payload) })
254
+ respond({ ok: true, data, issue })
255
+ } catch (error) {
256
+ respond({ ok: false, error: error.message }, 1)
257
+ }
258
+ }
259
+
260
+ respond({ ok: false, error: `Unsupported desktop bridge command: ${command}` }, 2)