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,155 @@
1
+ import fs from "node:fs"
2
+ import os from "node:os"
3
+ import path from "node:path"
4
+ import { spawn } from "node:child_process"
5
+
6
+ /**
7
+ * pacework Intelligence triage on this machine: claim a queued triage job, run
8
+ * the prompt through the user's AI CLI with no tools, and report the text back.
9
+ * Runs inside the background runner (alongside development work) and behind the
10
+ * standalone `pacework triage` command.
11
+ */
12
+ export const TRIAGE_EXECUTORS = ["claude_code", "codex", "gemini"]
13
+
14
+ function buildExecSpec({ executor, model, binaries }, prompt) {
15
+ if (executor === "codex") {
16
+ const outputFile = path.join(os.tmpdir(), `pacework-triage-${Date.now()}-${Math.random().toString(36).slice(2)}.txt`)
17
+ // Completion jobs must only return text to the pacework tool loop.
18
+ // Loading the user's normal Codex config also loads their MCP
19
+ // servers, allowing this interpreter process to execute mutations
20
+ // itself (and potentially call a stale/remote pacework endpoint).
21
+ const args = ["exec", "--ignore-user-config", "--ignore-rules", "--sandbox", "read-only"]
22
+ if (model) args.push("-m", model)
23
+ args.push("--ephemeral", "--color", "never", "--skip-git-repo-check", "--output-last-message", outputFile, "-")
24
+ return { command: binaries.codex, args, stdinPayload: prompt, outputFile }
25
+ }
26
+ if (executor === "gemini") {
27
+ const args = ["-p", prompt, "--output-format", "text"]
28
+ if (model) args.push("--model", model)
29
+ return { command: binaries.gemini, args, stdinPayload: null, outputFile: null }
30
+ }
31
+ // claude_code (default)
32
+ // As above, give completion jobs no tools and an explicitly empty MCP
33
+ // config. The outer pacework Slack agent owns all tool execution.
34
+ const args = ["-p", "--output-format", "text", "--strict-mcp-config", "--mcp-config", '{"mcpServers":{}}', "--tools", ""]
35
+ if (model) args.push("--model", model)
36
+ return { command: binaries.claude, args, stdinPayload: prompt, outputFile: null }
37
+ }
38
+
39
+ function runExecutorPrompt(options, prompt) {
40
+ return new Promise((resolve, reject) => {
41
+ const spec = buildExecSpec(options, prompt)
42
+ const child = spawn(spec.command, spec.args, { stdio: ["pipe", "pipe", "pipe"], env: process.env })
43
+ let stdout = ""
44
+ let stderr = ""
45
+ const timer = setTimeout(() => {
46
+ child.kill("SIGKILL")
47
+ reject(new Error(`${spec.command} timed out after ${Math.round(options.timeoutMs / 1000)}s`))
48
+ }, options.timeoutMs)
49
+ const readResult = () => {
50
+ // Codex writes the final answer to a file; the others stream stdout.
51
+ if (!spec.outputFile) return stdout.trim()
52
+ try {
53
+ const text = fs.readFileSync(spec.outputFile, "utf8").trim()
54
+ fs.unlinkSync(spec.outputFile)
55
+ return text
56
+ } catch {
57
+ return ""
58
+ }
59
+ }
60
+ child.stdout.on("data", (chunk) => { stdout += chunk })
61
+ child.stderr.on("data", (chunk) => { stderr += chunk })
62
+ child.on("error", (error) => {
63
+ clearTimeout(timer)
64
+ reject(error.code === "ENOENT"
65
+ ? new Error(`Could not find the "${spec.command}" CLI for ${options.executor}. Install it, or pass --claude-bin/--codex-bin/--gemini-bin.`)
66
+ : error)
67
+ })
68
+ child.on("close", (code) => {
69
+ clearTimeout(timer)
70
+ const text = code === 0 ? readResult() : ""
71
+ if (code === 0 && text) resolve(text)
72
+ else reject(new Error(`${spec.command} exited with code ${code}: ${stderr.trim().slice(0, 400) || "no output"}`))
73
+ })
74
+ if (spec.stdinPayload !== null) child.stdin.write(spec.stdinPayload)
75
+ child.stdin.end()
76
+ })
77
+ }
78
+
79
+ /**
80
+ * Polls until `shouldStop()` returns true (or after one job with `once`).
81
+ * `report(event, details)` receives: started, claimed, completed, failed,
82
+ * rejected, poll_error and auth_failed; callers turn those into log lines.
83
+ */
84
+ export async function runTriageLoop({
85
+ appUrl,
86
+ apiKey,
87
+ executor = "claude_code",
88
+ model = null,
89
+ runnerName = `${os.hostname()} triage`,
90
+ pollIntervalMs = 5000,
91
+ timeoutMs = 240_000,
92
+ binaries = {},
93
+ once = false,
94
+ shouldStop = () => false,
95
+ report = () => {},
96
+ }) {
97
+ const options = {
98
+ executor,
99
+ model,
100
+ timeoutMs,
101
+ binaries: { claude: binaries.claude || "claude", codex: binaries.codex || "codex", gemini: binaries.gemini || "gemini" },
102
+ }
103
+
104
+ const api = async (route, body) => {
105
+ const res = await fetch(`${appUrl}${route}`, {
106
+ method: "POST",
107
+ headers: { "content-type": "application/json", authorization: `Bearer ${apiKey}` },
108
+ body: JSON.stringify(body),
109
+ })
110
+ const text = await res.text()
111
+ let payload = null
112
+ try { payload = text ? JSON.parse(text) : null } catch { payload = { error: text.slice(0, 300) } }
113
+ return { status: res.status, payload }
114
+ }
115
+
116
+ const processJob = async (job) => {
117
+ const startedAt = Date.now()
118
+ report("claimed", { job })
119
+ try {
120
+ const text = await runExecutorPrompt(options, job.prompt)
121
+ const complete = await api(`/api/triage-runner/jobs/${job.id}/complete`, {
122
+ text,
123
+ model: `${executor}${model ? `:${model}` : ""}`,
124
+ })
125
+ if (complete.status >= 400) report("rejected", { job, status: complete.status, payload: complete.payload, durationMs: Date.now() - startedAt })
126
+ else report("completed", { job, confidence: complete.payload?.confidence ?? null, durationMs: Date.now() - startedAt })
127
+ } catch (error) {
128
+ const message = error instanceof Error ? error.message : String(error)
129
+ report("failed", { job, message, durationMs: Date.now() - startedAt })
130
+ await api(`/api/triage-runner/jobs/${job.id}/fail`, { error: message }).catch(() => {})
131
+ }
132
+ }
133
+
134
+ report("started", { runnerName, executor, model, pollIntervalMs })
135
+ while (!shouldStop()) {
136
+ try {
137
+ const claim = await api("/api/triage-runner/claim", { runner_name: runnerName })
138
+ if (claim.status === 401 || claim.status === 403) {
139
+ report("auth_failed", { status: claim.status })
140
+ return
141
+ }
142
+ if (claim.status >= 400) {
143
+ report("poll_error", { message: `claim failed (${claim.status}): ${JSON.stringify(claim.payload)}` })
144
+ } else if (claim.payload?.job) {
145
+ await processJob(claim.payload.job)
146
+ if (once) return
147
+ continue
148
+ }
149
+ } catch (error) {
150
+ report("poll_error", { message: error instanceof Error ? error.message : String(error) })
151
+ }
152
+ if (once) return
153
+ await new Promise((resolve) => setTimeout(resolve, pollIntervalMs))
154
+ }
155
+ }
package/lib/ui.mjs ADDED
@@ -0,0 +1,88 @@
1
+ import os from "node:os"
2
+
3
+ /**
4
+ * Terminal styling for the interactive CLI. Output stays plain when it is not a
5
+ * terminal or NO_COLOR is set, so piped and logged output carries no escape codes.
6
+ */
7
+ const colorEnabled = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR
8
+
9
+ const paint = (open, close) => (text) => colorEnabled ? `\x1b[${open}m${text}\x1b[${close}m` : String(text)
10
+
11
+ export const style = {
12
+ bold: paint(1, 22),
13
+ dim: paint(2, 22),
14
+ brand: paint("38;5;39", 39),
15
+ green: paint(32, 39),
16
+ red: paint(31, 39),
17
+ yellow: paint(33, 39),
18
+ gray: paint("38;5;244", 39),
19
+ inverse: paint(7, 27),
20
+ }
21
+
22
+ /** The one-line wordmark, for places too small for the banner. */
23
+ export const LOGO = style.bold(style.brand("pacework"))
24
+
25
+ /** The big PACEWORK banner (ANSI Shadow), 67 columns wide. */
26
+ export const BANNER_LINES = [
27
+ "██████╗ █████╗ ██████╗███████╗██╗ ██╗ ██████╗ ██████╗ ██╗ ██╗",
28
+ "██╔══██╗██╔══██╗██╔════╝██╔════╝██║ ██║██╔═══██╗██╔══██╗██║ ██╔╝",
29
+ "██████╔╝███████║██║ █████╗ ██║ █╗ ██║██║ ██║██████╔╝█████╔╝ ",
30
+ "██╔═══╝ ██╔══██║██║ ██╔══╝ ██║███╗██║██║ ██║██╔══██╗██╔═██╗ ",
31
+ "██║ ██║ ██║╚██████╗███████╗╚███╔███╔╝╚██████╔╝██║ ██║██║ ██╗",
32
+ "╚═╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝ ╚══╝╚══╝ ╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═╝",
33
+ ]
34
+
35
+ export function visibleLength(text) {
36
+ return String(text).replace(/\x1b\[[0-9;]*m/g, "").length
37
+ }
38
+
39
+ /** Cuts plain text to `width` columns, ending in an ellipsis when shortened. */
40
+ export function truncate(text, width) {
41
+ const value = String(text ?? "")
42
+ if (width <= 0) return ""
43
+ return value.length > width ? `${value.slice(0, Math.max(0, width - 1))}…` : value
44
+ }
45
+
46
+ export function tildePath(value) {
47
+ if (!value) return ""
48
+ const home = os.homedir()
49
+ return value.startsWith(home) ? `~${value.slice(home.length)}` : value
50
+ }
51
+
52
+ export function relativeTime(iso) {
53
+ if (!iso) return ""
54
+ const seconds = Math.max(0, Math.floor((Date.now() - new Date(iso).getTime()) / 1000))
55
+ if (seconds < 60) return "just now"
56
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`
57
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`
58
+ return `${Math.floor(seconds / 86400)}d ago`
59
+ }
60
+
61
+ export function formatDuration(ms) {
62
+ if (!ms || ms < 0) return ""
63
+ const seconds = Math.floor(ms / 1000)
64
+ if (seconds < 60) return `${seconds}s`
65
+ const minutes = Math.floor(seconds / 60)
66
+ if (minutes < 60) return `${minutes}m ${seconds % 60}s`
67
+ return `${Math.floor(minutes / 60)}h ${minutes % 60}m`
68
+ }
69
+
70
+ /**
71
+ * "app.example.com" → https://app.example.com; "localhost:3000" → http://localhost:3000
72
+ * (local development servers do not serve https). No trailing slash.
73
+ */
74
+ export function normalizeAppUrl(input) {
75
+ const trimmed = String(input ?? "").trim().replace(/\/+$/, "")
76
+ if (!trimmed) return ""
77
+ if (/^https?:\/\//i.test(trimmed)) return trimmed
78
+ const local = /^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|[^/:]+\.local)(:\d+)?(\/|$)/i.test(trimmed)
79
+ return `${local ? "http" : "https"}://${trimmed}`
80
+ }
81
+
82
+ export function hostOf(url) {
83
+ try {
84
+ return new URL(url).host
85
+ } catch {
86
+ return String(url ?? "")
87
+ }
88
+ }
@@ -0,0 +1,47 @@
1
+ import { readConfig } from "./control-state.mjs"
2
+
3
+ /**
4
+ * Calls to the signed-in workspace with the CLI's workspace API key. Errors
5
+ * carry a message that says what to do next, so commands can print it as is.
6
+ */
7
+ export class NotSignedInError extends Error {}
8
+
9
+ export function currentSession() {
10
+ const config = readConfig()
11
+ if (!config.apiKey || !config.workspaceId) throw new NotSignedInError("Not signed in. Run `pacework login`.")
12
+ return {
13
+ appUrl: String(config.appUrl || "https://pacework.io").replace(/\/$/, ""),
14
+ apiKey: config.apiKey,
15
+ workspaceId: config.workspaceId,
16
+ workspaceSlug: config.workspaceSlug ?? null,
17
+ userName: config.userName ?? null,
18
+ userEmail: config.userEmail ?? null,
19
+ }
20
+ }
21
+
22
+ export async function workspaceGet(route) {
23
+ const session = currentSession()
24
+ let res
25
+ try {
26
+ res = await fetch(`${session.appUrl}/api/workspaces/${session.workspaceId}${route}`, {
27
+ headers: { "x-workspace-api-key": session.apiKey },
28
+ })
29
+ } catch (error) {
30
+ throw new Error(`Could not reach ${session.appUrl} (${error instanceof Error ? error.message : error}).`)
31
+ }
32
+ if (res.status === 401) throw new NotSignedInError("Your sign-in is no longer valid. Run `pacework login`.")
33
+ const body = await res.json().catch(() => ({}))
34
+ if (!res.ok) {
35
+ const error = new Error(body.error || `${session.appUrl} answered ${res.status}.`)
36
+ error.status = res.status
37
+ throw error
38
+ }
39
+ return body
40
+ }
41
+
42
+ /** Web address of the workspace, or of one issue in it. */
43
+ export function workspaceUrl(issueIdentifier) {
44
+ const session = currentSession()
45
+ const base = `${session.appUrl}/${session.workspaceSlug ?? session.workspaceId}`
46
+ return issueIdentifier ? `${base}/issue/${encodeURIComponent(issueIdentifier.toUpperCase())}` : base
47
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pacework",
3
- "version": "1.0.2",
3
+ "version": "1.2.0",
4
4
  "description": "pacework CLI: connect this machine as a runner for pacework AI agents",
5
5
  "type": "module",
6
6
  "bin": {
@@ -16,6 +16,14 @@
16
16
  "engines": {
17
17
  "node": ">=18.0.0"
18
18
  },
19
- "keywords": ["pacework", "ai", "agent", "runner"],
20
- "license": "MIT"
19
+ "keywords": [
20
+ "pacework",
21
+ "ai",
22
+ "agent",
23
+ "runner"
24
+ ],
25
+ "license": "MIT",
26
+ "dependencies": {
27
+ "@clack/prompts": "1.8.1"
28
+ }
21
29
  }