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,270 @@
1
+ import fs from "node:fs"
2
+ import os from "node:os"
3
+ import path from "node:path"
4
+ import process from "node:process"
5
+ import { execFileSync } from "node:child_process"
6
+ import { PACEWORK_DIR, LOG_FILE, USES_LEGACY_DIR } from "./control-state.mjs"
7
+
8
+ /**
9
+ * Run the runner as an OS-managed login service, so it starts at login, restarts
10
+ * when it dies, and survives reboots — the background daemon from `start` did
11
+ * none of that. macOS uses launchd, Linux a systemd user unit. Other platforms
12
+ * get null back and fall back to `start`.
13
+ */
14
+
15
+ // A service installed before the rename keeps its name, so `stop` and `status` still find it.
16
+ const LABEL = USES_LEGACY_DIR ? "io.kentral.runner" : "io.pacework.runner"
17
+ const UNIT = USES_LEGACY_DIR ? "kentral-runner.service" : "pacework-runner.service"
18
+
19
+ /** Where `up` keeps a stable copy of the runner; npx's cache can vanish. */
20
+ export const INSTALL_ROOT = path.join(PACEWORK_DIR, "runner-app")
21
+
22
+ export function serviceKind() {
23
+ if (process.platform === "darwin") return "launchd"
24
+ if (process.platform === "linux" && hasSystemdUser()) return "systemd"
25
+ return null
26
+ }
27
+
28
+ function hasSystemdUser() {
29
+ try {
30
+ execFileSync("systemctl", ["--user", "--version"], { stdio: "ignore" })
31
+ return true
32
+ } catch {
33
+ return false
34
+ }
35
+ }
36
+
37
+ function launchdPlistPath() {
38
+ return path.join(os.homedir(), "Library", "LaunchAgents", `${LABEL}.plist`)
39
+ }
40
+
41
+ function systemdUnitPath() {
42
+ return path.join(os.homedir(), ".config", "systemd", "user", UNIT)
43
+ }
44
+
45
+ export function serviceFilePath() {
46
+ const kind = serviceKind()
47
+ if (kind === "launchd") return launchdPlistPath()
48
+ if (kind === "systemd") return systemdUnitPath()
49
+ return null
50
+ }
51
+
52
+ export function isServiceInstalled() {
53
+ const file = serviceFilePath()
54
+ return Boolean(file && fs.existsSync(file))
55
+ }
56
+
57
+ /**
58
+ * Copy the runner package (it has no dependencies) to a stable location and
59
+ * return the path of the control script inside it.
60
+ */
61
+ export function installStableCopy(sourceRoot, version) {
62
+ const target = path.join(INSTALL_ROOT, version || "current")
63
+ if (path.resolve(sourceRoot) !== path.resolve(target)) {
64
+ fs.rmSync(target, { recursive: true, force: true })
65
+ fs.mkdirSync(target, { recursive: true })
66
+ for (const entry of ["bin", "lib", "package.json"]) {
67
+ fs.cpSync(path.join(sourceRoot, entry), path.join(target, entry), { recursive: true })
68
+ }
69
+ }
70
+ return path.join(target, "bin", "pacework-runner-ctl.mjs")
71
+ }
72
+
73
+ const SHIM_MARKER = "# pacework launcher (written by pacework up)"
74
+
75
+ /**
76
+ * Put a `pacework` command on PATH that runs this installed copy.
77
+ *
78
+ * Run through npx, the package installs no command, yet `up` told people to use
79
+ * `pacework logs` — "command not found". The launcher goes in the first
80
+ * writable folder on PATH (preferring the one `node` is in), never over a
81
+ * `pacework` someone else put there. Returns how to invoke it: the bare
82
+ * name when it is on PATH, otherwise the launcher's full path.
83
+ */
84
+ export function installCommandLauncher(ctlPath) {
85
+ const launcher = `#!/bin/sh\n${SHIM_MARKER}\nexec "${process.execPath}" "${ctlPath}" "$@"\n`
86
+ const own = path.join(PACEWORK_DIR, "bin", "pacework")
87
+ fs.mkdirSync(path.dirname(own), { recursive: true })
88
+ fs.writeFileSync(own, launcher, { mode: 0o755 })
89
+ if (process.platform === "win32") return own
90
+
91
+ const onPath = (process.env.PATH || "").split(path.delimiter).filter(Boolean)
92
+ const candidates = [path.dirname(process.execPath), path.join(os.homedir(), ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin"]
93
+ .filter((dir, i, all) => onPath.includes(dir) && all.indexOf(dir) === i)
94
+
95
+ for (const dir of onPath) {
96
+ const existing = path.join(dir, "pacework")
97
+ if (!fs.existsSync(existing)) continue
98
+ // Something already answers to the name. Ours: refresh it. Someone else's
99
+ // (a global npm install): leave it, it is a working command.
100
+ let content = ""
101
+ try { content = fs.readFileSync(existing, "utf8") } catch {}
102
+ if (!content.includes(SHIM_MARKER)) return "pacework"
103
+ try { fs.writeFileSync(existing, launcher, { mode: 0o755 }); return "pacework" } catch { break }
104
+ }
105
+ for (const dir of candidates) {
106
+ try {
107
+ fs.accessSync(dir, fs.constants.W_OK)
108
+ fs.writeFileSync(path.join(dir, "pacework"), launcher, { mode: 0o755 })
109
+ return "pacework"
110
+ } catch {
111
+ // not writable; try the next
112
+ }
113
+ }
114
+ return own
115
+ }
116
+
117
+ function xmlEscape(value) {
118
+ return String(value)
119
+ .replace(/&/g, "&")
120
+ .replace(/</g, "&lt;")
121
+ .replace(/>/g, "&gt;")
122
+ .replace(/"/g, "&quot;")
123
+ }
124
+
125
+ /**
126
+ * Install and start the service. `ctlPath` is the stable control script; the
127
+ * service runs `pacework-runner-ctl service-run`, which reads the saved config so
128
+ * the API key never appears in the service file or the process list.
129
+ */
130
+ export function installService({ ctlPath }) {
131
+ // Start in ~/.pacework, never in the repository: on macOS a background service
132
+ // whose working directory is in Desktop, Documents or Downloads hangs inside
133
+ // Node's own startup until privacy access is granted. The runner is told the
134
+ // repository explicitly and checks access itself (see service-run).
135
+ const workingDirectory = PACEWORK_DIR
136
+ const kind = serviceKind()
137
+ if (!kind) return null
138
+
139
+ fs.mkdirSync(path.dirname(LOG_FILE), { recursive: true })
140
+ // The coding CLIs (claude, codex) are found through PATH; services start with
141
+ // a minimal one, so the PATH of the shell running `up` is carried over.
142
+ const envPath = process.env.PATH || "/usr/local/bin:/usr/bin:/bin"
143
+
144
+ if (kind === "launchd") {
145
+ const plist = `<?xml version="1.0" encoding="UTF-8"?>
146
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
147
+ <plist version="1.0">
148
+ <dict>
149
+ <key>Label</key><string>${LABEL}</string>
150
+ <key>ProgramArguments</key>
151
+ <array>
152
+ <string>${xmlEscape(process.execPath)}</string>
153
+ <string>${xmlEscape(ctlPath)}</string>
154
+ <string>service-run</string>
155
+ </array>
156
+ <key>WorkingDirectory</key><string>${xmlEscape(workingDirectory)}</string>
157
+ <key>EnvironmentVariables</key>
158
+ <dict>
159
+ <key>PATH</key><string>${xmlEscape(envPath)}</string>
160
+ <key>HOME</key><string>${xmlEscape(os.homedir())}</string>
161
+ </dict>
162
+ <key>RunAtLoad</key><true/>
163
+ <key>KeepAlive</key><true/>
164
+ <key>ThrottleInterval</key><integer>10</integer>
165
+ <key>StandardOutPath</key><string>${xmlEscape(LOG_FILE)}</string>
166
+ <key>StandardErrorPath</key><string>${xmlEscape(LOG_FILE)}</string>
167
+ </dict>
168
+ </plist>
169
+ `
170
+ const file = launchdPlistPath()
171
+ fs.mkdirSync(path.dirname(file), { recursive: true })
172
+ fs.writeFileSync(file, plist, { encoding: "utf8", mode: 0o644 })
173
+ stopService()
174
+ execFileSync("launchctl", ["bootstrap", `gui/${process.getuid()}`, file], { stdio: "ignore" })
175
+ return { kind, file }
176
+ }
177
+
178
+ const unit = `[Unit]
179
+ Description=pacework agent runner
180
+ After=network-online.target
181
+
182
+ [Service]
183
+ ExecStart=${process.execPath} ${ctlPath} service-run
184
+ WorkingDirectory=${workingDirectory}
185
+ Environment=PATH=${envPath}
186
+ Restart=always
187
+ RestartSec=10
188
+ StandardOutput=append:${LOG_FILE}
189
+ StandardError=append:${LOG_FILE}
190
+
191
+ [Install]
192
+ WantedBy=default.target
193
+ `
194
+ const file = systemdUnitPath()
195
+ fs.mkdirSync(path.dirname(file), { recursive: true })
196
+ fs.writeFileSync(file, unit, "utf8")
197
+ execFileSync("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" })
198
+ execFileSync("systemctl", ["--user", "enable", "--now", UNIT], { stdio: "ignore" })
199
+ return { kind, file }
200
+ }
201
+
202
+ /** Start an installed service that was stopped. */
203
+ export function startService() {
204
+ const kind = serviceKind()
205
+ if (kind === "launchd") {
206
+ execFileSync("launchctl", ["bootstrap", `gui/${process.getuid()}`, launchdPlistPath()], { stdio: "ignore" })
207
+ } else if (kind === "systemd") {
208
+ execFileSync("systemctl", ["--user", "start", UNIT], { stdio: "ignore" })
209
+ }
210
+ }
211
+
212
+ /** Stop the service until the next start or login. Never throws. */
213
+ export function stopService() {
214
+ const kind = serviceKind()
215
+ try {
216
+ if (kind === "launchd") {
217
+ execFileSync("launchctl", ["bootout", `gui/${process.getuid()}/${LABEL}`], { stdio: "ignore" })
218
+ } else if (kind === "systemd") {
219
+ execFileSync("systemctl", ["--user", "stop", UNIT], { stdio: "ignore" })
220
+ }
221
+ } catch {
222
+ // not loaded
223
+ }
224
+ }
225
+
226
+ /** Stop and remove the service entirely. */
227
+ export function uninstallService() {
228
+ const kind = serviceKind()
229
+ stopService()
230
+ if (kind === "systemd") {
231
+ try { execFileSync("systemctl", ["--user", "disable", UNIT], { stdio: "ignore" }) } catch {}
232
+ }
233
+ const file = serviceFilePath()
234
+ if (file) fs.rmSync(file, { force: true })
235
+ if (kind === "systemd") {
236
+ try { execFileSync("systemctl", ["--user", "daemon-reload"], { stdio: "ignore" }) } catch {}
237
+ }
238
+ }
239
+
240
+ export function isServiceRunning() {
241
+ const kind = serviceKind()
242
+ try {
243
+ if (kind === "launchd") {
244
+ const out = execFileSync("launchctl", ["print", `gui/${process.getuid()}/${LABEL}`], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] })
245
+ return /state = running/.test(out)
246
+ }
247
+ if (kind === "systemd") {
248
+ execFileSync("systemctl", ["--user", "is-active", "--quiet", UNIT], { stdio: "ignore" })
249
+ return true
250
+ }
251
+ } catch {
252
+ return false
253
+ }
254
+ return false
255
+ }
256
+
257
+ /**
258
+ * macOS folders a background service cannot read without the user's consent
259
+ * (System Settings → Privacy & Security → Files and Folders).
260
+ */
261
+ export function privacyProtectedFolder(repoRoot) {
262
+ if (process.platform !== "darwin") return null
263
+ const home = os.homedir()
264
+ for (const name of ["Desktop", "Documents", "Downloads"]) {
265
+ const folder = path.join(home, name)
266
+ if (repoRoot === folder || repoRoot.startsWith(folder + path.sep)) return name
267
+ }
268
+ if (repoRoot.includes(`${path.sep}Library${path.sep}Mobile Documents${path.sep}`)) return "iCloud Drive"
269
+ return null
270
+ }
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Recognise an executor's "usage limit reached" message and when it lifts.
3
+ *
4
+ * Claude Code and Codex stop mid-run when the account's plan limit is hit. The
5
+ * run is not broken — it can resume once the limit resets — so the runner pauses
6
+ * until then instead of failing run after run against the same wall.
7
+ */
8
+
9
+ // Phrases the executors use for their plan limit. A bare "rate limit" is left
10
+ // out: an agent working on rate limiting says it all the time.
11
+ const LIMIT_PATTERN = /usage limit|hit your (?:usage )?limit|limit reached|quota exceeded|insufficient_quota|credit balance is too low|\b429\b[^\n]{0,40}rate.?limit|rate.?limit[^\n]{0,40}\b429\b/i
12
+
13
+ /** When the limit is not stated, wait this long before trying again. */
14
+ export const DEFAULT_LIMIT_WAIT_MS = 30 * 60_000
15
+
16
+ const UNIT_MS = { second: 1_000, minute: 60_000, hour: 3_600_000, day: 86_400_000 }
17
+
18
+ /**
19
+ * @returns {{ resetAt: Date, stated: boolean } | null} null when the text is not a
20
+ * usage limit; `stated` is false when the reset time had to be guessed.
21
+ */
22
+ export function detectUsageLimit(text, now = new Date()) {
23
+ // The limit message is what the executor printed last.
24
+ const source = String(text || "").slice(-2000)
25
+ if (!LIMIT_PATTERN.test(source)) return null
26
+ const resetAt = parseResetTime(source, now)
27
+ return resetAt
28
+ ? { resetAt, stated: true }
29
+ : { resetAt: new Date(now.getTime() + DEFAULT_LIMIT_WAIT_MS), stated: false }
30
+ }
31
+
32
+ function parseResetTime(text, now) {
33
+ // Claude Code: "Claude AI usage limit reached|1761058800" (epoch seconds).
34
+ const epoch = text.match(/limit reached\|(\d{10})\b/i)
35
+ if (epoch) return new Date(Number(epoch[1]) * 1000)
36
+
37
+ // "try again in 2 hours 5 minutes", "resets in 3 days"
38
+ const relative = text.match(/(?:try again|resets?|available)\s+in\s+((?:\d+\s*(?:second|minute|hour|day)s?[\s,and]*)+)/i)
39
+ if (relative) {
40
+ let ms = 0
41
+ for (const [, amount, unit] of relative[1].matchAll(/(\d+)\s*(second|minute|hour|day)/gi)) {
42
+ ms += Number(amount) * UNIT_MS[unit.toLowerCase()]
43
+ }
44
+ if (ms > 0) return new Date(now.getTime() + ms)
45
+ }
46
+
47
+ // "resets 3pm (Europe/Berlin)", "resets at 15:30", "try again at 3:04 PM"
48
+ const clock = text.match(/(?:resets?|try again)(?:\s+at)?\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)?(?:\s*\(([^)]+)\))?/i)
49
+ if (clock && (clock[2] || clock[3])) {
50
+ let hour = Number(clock[1]) % 12
51
+ if (!clock[3]) hour = Number(clock[1])
52
+ else if (clock[3].toLowerCase() === "pm") hour += 12
53
+ const minute = Number(clock[2] || 0)
54
+ if (hour < 24 && minute < 60) return nextWallClock(hour, minute, validTimeZone(clock[4]), now)
55
+ }
56
+
57
+ return null
58
+ }
59
+
60
+ function validTimeZone(value) {
61
+ if (!value) return undefined
62
+ try {
63
+ new Intl.DateTimeFormat("en-US", { timeZone: value.trim() })
64
+ return value.trim()
65
+ } catch {
66
+ return undefined
67
+ }
68
+ }
69
+
70
+ /** The next moment the clock in `timeZone` (default: this machine's) reads hour:minute. */
71
+ function nextWallClock(hour, minute, timeZone, now) {
72
+ const format = new Intl.DateTimeFormat("en-GB", { timeZone, hour: "2-digit", minute: "2-digit", hourCycle: "h23" })
73
+ const target = `${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")}`
74
+ const start = Math.ceil(now.getTime() / 60_000) * 60_000
75
+ for (let t = start; t < start + 48 * 3_600_000; t += 60_000) {
76
+ if (format.format(new Date(t)) === target) return new Date(t)
77
+ }
78
+ return null
79
+ }
package/package.json CHANGED
@@ -1,6 +1,21 @@
1
1
  {
2
2
  "name": "pacework",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "pacework CLI: connect this machine as a runner for pacework AI agents",
5
+ "type": "module",
6
+ "bin": {
7
+ "pacework": "./bin/pacework-runner-ctl.mjs"
8
+ },
9
+ "files": [
10
+ "bin/",
11
+ "lib/"
12
+ ],
13
+ "scripts": {
14
+ "test": "node --test test/*.test.mjs"
15
+ },
16
+ "engines": {
17
+ "node": ">=18.0.0"
18
+ },
19
+ "keywords": ["pacework", "ai", "agent", "runner"],
20
+ "license": "MIT"
21
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.