pacework 1.0.2 → 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.
@@ -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,78 @@
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 used everywhere except the first-run banner. */
23
+ export const LOGO = style.bold(style.brand("pacework"))
24
+
25
+ export function visibleLength(text) {
26
+ return String(text).replace(/\x1b\[[0-9;]*m/g, "").length
27
+ }
28
+
29
+ /** Cuts plain text to `width` columns, ending in an ellipsis when shortened. */
30
+ export function truncate(text, width) {
31
+ const value = String(text ?? "")
32
+ if (width <= 0) return ""
33
+ return value.length > width ? `${value.slice(0, Math.max(0, width - 1))}…` : value
34
+ }
35
+
36
+ export function tildePath(value) {
37
+ if (!value) return ""
38
+ const home = os.homedir()
39
+ return value.startsWith(home) ? `~${value.slice(home.length)}` : value
40
+ }
41
+
42
+ export function relativeTime(iso) {
43
+ if (!iso) return ""
44
+ const seconds = Math.max(0, Math.floor((Date.now() - new Date(iso).getTime()) / 1000))
45
+ if (seconds < 60) return "just now"
46
+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ago`
47
+ if (seconds < 86400) return `${Math.floor(seconds / 3600)}h ago`
48
+ return `${Math.floor(seconds / 86400)}d ago`
49
+ }
50
+
51
+ export function formatDuration(ms) {
52
+ if (!ms || ms < 0) return ""
53
+ const seconds = Math.floor(ms / 1000)
54
+ if (seconds < 60) return `${seconds}s`
55
+ const minutes = Math.floor(seconds / 60)
56
+ if (minutes < 60) return `${minutes}m ${seconds % 60}s`
57
+ return `${Math.floor(minutes / 60)}h ${minutes % 60}m`
58
+ }
59
+
60
+ /**
61
+ * "app.example.com" → https://app.example.com; "localhost:3000" → http://localhost:3000
62
+ * (local development servers do not serve https). No trailing slash.
63
+ */
64
+ export function normalizeAppUrl(input) {
65
+ const trimmed = String(input ?? "").trim().replace(/\/+$/, "")
66
+ if (!trimmed) return ""
67
+ if (/^https?:\/\//i.test(trimmed)) return trimmed
68
+ const local = /^(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|[^/:]+\.local)(:\d+)?(\/|$)/i.test(trimmed)
69
+ return `${local ? "http" : "https"}://${trimmed}`
70
+ }
71
+
72
+ export function hostOf(url) {
73
+ try {
74
+ return new URL(url).host
75
+ } catch {
76
+ return String(url ?? "")
77
+ }
78
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pacework",
3
- "version": "1.0.2",
3
+ "version": "1.1.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
  }