@yanauto/broco 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.
Files changed (70) hide show
  1. package/CHANGELOG.md +209 -0
  2. package/LICENSE +202 -0
  3. package/README.md +188 -2
  4. package/README.zh-CN.md +187 -0
  5. package/assets/broco-board-icon-128.png +0 -0
  6. package/assets/broco-favicon-192.png +0 -0
  7. package/assets/broco-favicon-32.png +0 -0
  8. package/assets/broco-favicon-64.png +0 -0
  9. package/assets/broco-foreman-256.png +0 -0
  10. package/assets/broco-hero-1024.png +0 -0
  11. package/assets/broco-icon-512.png +0 -0
  12. package/assets/broco-readme-logo-dark.png +0 -0
  13. package/assets/broco-readme-logo-light.png +0 -0
  14. package/assets/broco-social-preview-1280x640.png +0 -0
  15. package/assets/favicon.ico +0 -0
  16. package/bin/broco +1077 -0
  17. package/bundle/board/assets/index-Bue0HpFh.css +1 -0
  18. package/bundle/board/assets/index-DTqMQtD9.js +16 -0
  19. package/bundle/board/broco-board-icon-128.png +0 -0
  20. package/bundle/board/broco-favicon-32.png +0 -0
  21. package/bundle/board/broco-favicon-64.png +0 -0
  22. package/bundle/board/broco-foreman-256.png +0 -0
  23. package/bundle/board/favicon.ico +0 -0
  24. package/bundle/board/fonts/instrument-sans-latin.woff2 +0 -0
  25. package/bundle/board/fonts/jetbrains-mono-latin.woff2 +0 -0
  26. package/bundle/board/index.html +18 -0
  27. package/lib/attachments.mjs +104 -0
  28. package/lib/claude-md.mjs +132 -0
  29. package/lib/cli-args.mjs +292 -0
  30. package/lib/cli-process.mjs +75 -0
  31. package/lib/client.mjs +198 -0
  32. package/lib/credential-proxy.mjs +165 -0
  33. package/lib/credential-source.mjs +23 -0
  34. package/lib/crew.mjs +947 -0
  35. package/lib/detect.mjs +279 -0
  36. package/lib/directories.mjs +32 -0
  37. package/lib/map.mjs +336 -0
  38. package/lib/model-catalog.json +864 -0
  39. package/lib/model-catalog.mjs +138 -0
  40. package/lib/model-env.mjs +11 -0
  41. package/lib/native.mjs +228 -0
  42. package/lib/paths.mjs +63 -0
  43. package/lib/pi-profile.mjs +29 -0
  44. package/lib/pi-secrets.mjs +48 -0
  45. package/lib/pi.mjs +232 -0
  46. package/lib/platform/index.mjs +13 -0
  47. package/lib/platform/launchd.mjs +138 -0
  48. package/lib/platform/linux.mjs +168 -0
  49. package/lib/platform/macos.mjs +29 -0
  50. package/lib/platform/processes.mjs +102 -0
  51. package/lib/problems.mjs +50 -0
  52. package/lib/projects.mjs +530 -0
  53. package/lib/quota.mjs +132 -0
  54. package/lib/roster-output.mjs +136 -0
  55. package/lib/roster.mjs +913 -0
  56. package/lib/runner.mjs +403 -0
  57. package/lib/settings-audit.mjs +104 -0
  58. package/lib/setup.mjs +416 -0
  59. package/lib/slots.mjs +177 -0
  60. package/lib/stats.mjs +92 -0
  61. package/lib/store.mjs +737 -0
  62. package/lib/stream-workers.mjs +464 -0
  63. package/lib/templates.mjs +173 -0
  64. package/lib/time.mjs +25 -0
  65. package/lib/web.mjs +260 -0
  66. package/lib/worker-policy.mjs +17 -0
  67. package/lib/worktree.mjs +269 -0
  68. package/package.json +50 -4
  69. package/scripts/package-board.mjs +53 -0
  70. package/skills/broco/SKILL.md +59 -0
package/lib/pi.mjs ADDED
@@ -0,0 +1,232 @@
1
+ import { execFile, spawn } from 'node:child_process'
2
+ import { createHash, randomUUID } from 'node:crypto'
3
+ import { closeSync, existsSync, mkdirSync, openSync, renameSync, rmSync, writeFileSync } from 'node:fs'
4
+ import { dirname, join } from 'node:path'
5
+ import { promisify } from 'node:util'
6
+ import { home, isolated, toolsPath } from './paths.mjs'
7
+ import { platform } from './platform/index.mjs'
8
+ import { sdkRoot } from './pi-profile.mjs'
9
+ import { mask, parseRedactedJson, redactStderr, secretsFrom } from './pi-secrets.mjs'
10
+ import { modelEnvironment } from './model-env.mjs'
11
+ import { HOST_SESSION_VARS } from './templates.mjs'
12
+
13
+ const exec = promisify(execFile)
14
+ const authKeyCache = new Map()
15
+
16
+ export function providerOf(model) {
17
+ const match = /^([a-z0-9][a-z0-9_.-]*)\/([^\s\x00-\x1f\x7f]+)$/.exec(model)
18
+ if (!match) throw new Error('Expected an exact --model provider/model-id')
19
+ return match[1]
20
+ }
21
+
22
+ function writeAtomic(path, content) {
23
+ const tmp = path + '.' + randomUUID()
24
+ try {
25
+ writeFileSync(tmp, content, { mode: 0o600 })
26
+ renameSync(tmp, path)
27
+ } finally {
28
+ rmSync(tmp, { force: true })
29
+ }
30
+ }
31
+
32
+ function writeConfig(path, data) {
33
+ writeAtomic(path, JSON.stringify(data))
34
+ }
35
+
36
+ async function credentialCommand(access, args, env) {
37
+ try {
38
+ const [file, ...argv] = platform.piCommand(['auth', ...args], access)
39
+ const { stdout } = await exec(file, argv, {
40
+ cwd: home, env, encoding: 'utf8', timeout: 20000
41
+ })
42
+ return stdout.trim()
43
+ } catch {
44
+ throw new Error('pi auth could not resolve an API key for ' + args[args.indexOf('--provider') + 1])
45
+ }
46
+ }
47
+
48
+ export function loginEnvironment() {
49
+ const env = { PATH: toolsPath, PI_CODING_AGENT_SESSION_DIR: join(home, 'sessions') }
50
+ if (isolated) {
51
+ Object.assign(env, { HOME: join(home, 'home'), TMPDIR: join(home, 'tmp'), PI_CODING_AGENT_DIR: join(home, 'login'), PI_TELEMETRY: '0' })
52
+ for (const dir of [env.HOME, env.TMPDIR, env.PI_CODING_AGENT_DIR]) mkdirSync(dir, { recursive: true })
53
+ } else if (process.env.PI_CODING_AGENT_DIR) env.PI_CODING_AGENT_DIR = process.env.PI_CODING_AGENT_DIR
54
+ mkdirSync(env.PI_CODING_AGENT_SESSION_DIR, { recursive: true })
55
+ return env
56
+ }
57
+
58
+ async function resolveIsolatedApiKey(provider, login, agentDir) {
59
+ const canary = process.env.BROCO_FIXTURE_CANARY || ''
60
+ const cacheKey = home + '\0' + provider + '\0' + canary
61
+ const now = Date.now()
62
+ const cached = !canary ? authKeyCache.get(cacheKey) : null
63
+ if (cached && now < cached.expiresAt) return cached.promise
64
+
65
+ const promise = (async () => {
66
+ mkdirSync(agentDir, { recursive: true })
67
+ writeConfig(join(agentDir, 'auth.json'), { [provider]: { type: 'api_key', key: '$BROCO_API_KEY' } })
68
+ writeConfig(join(agentDir, 'settings.json'), { shellCommandPrefix: 'unset BROCO_API_KEY; exec 19<"$BROCO_MARKER"' })
69
+
70
+ const check = ['check', '--no-refresh', '--json', '--provider', provider]
71
+ const lookup = { ...modelEnvironment(), ...login, PI_OFFLINE: '1' }
72
+ const status = await credentialCommand('isolated', check, lookup).then(JSON.parse).catch(() => null)
73
+ if (status?.authType !== 'api_key') throw new Error('No API-key credential for ' + provider)
74
+ const result = JSON.parse(await credentialCommand('isolated', [...check, '--credentials'], lookup))
75
+ if (result.authType !== 'api_key' || !result.credentials) throw new Error('API-key lookup failed for ' + provider)
76
+ const verifyEnv = { ...login, PI_OFFLINE: '1', PI_CODING_AGENT_DIR: agentDir, BROCO_API_KEY: result.credentials }
77
+ const key = await credentialCommand('isolated', ['print-api-key', '--provider', provider], verifyEnv)
78
+ if (!key || /[\r\n]/.test(key)) throw new Error('Invalid API-key export for ' + provider)
79
+ return key
80
+ })()
81
+
82
+ if (!canary) {
83
+ authKeyCache.set(cacheKey, { expiresAt: now + 5000, promise })
84
+ promise.catch(() => {
85
+ if (authKeyCache.get(cacheKey)?.promise === promise) authKeyCache.delete(cacheKey)
86
+ })
87
+ }
88
+ return promise
89
+ }
90
+
91
+ async function workerEnvironment(provider, marker) {
92
+ const login = loginEnvironment()
93
+ const configured = login.PI_CODING_AGENT_DIR && ['auth.json', 'models.json'].some(name => existsSync(join(login.PI_CODING_AGENT_DIR, name)))
94
+ if (!isolated || sdkRoot(toolsPath) || configured) {
95
+ const original = process.env.BASH_ENV || ''
96
+ const env = modelEnvironment()
97
+ for (const key of HOST_SESSION_VARS) delete env[key]
98
+ const credentialNames = Object.keys(env).filter(k => /^[A-Za-z_][A-Za-z0-9_]*(?:API_KEY|AUTH_KEY|PRIVATE_KEY|TOKEN|ACCESS_KEY|SECRET|PASSWORD|PASSWD)$/i.test(k))
99
+ const unset = isolated && credentialNames.length ? 'unset ' + credentialNames.join(' ') + '\n' : ''
100
+ const script = 'if [ -n "$BROCO_BASH_ENV" ]; then . "$BROCO_BASH_ENV"; fi\n' + unset + 'exec 19<"$BROCO_MARKER"\n'
101
+ const digest = createHash('sha256').update(script).digest('hex').slice(0, 16)
102
+ const prelude = join(home, 'bash-env.' + digest)
103
+ if (!existsSync(prelude)) {
104
+ mkdirSync(home, { recursive: true })
105
+ writeAtomic(prelude, script)
106
+ }
107
+ return { ...env, ...login, BROCO_MARKER: marker, BROCO_IN_WORKER: '1', BASH_ENV: prelude, BROCO_BASH_ENV: original }
108
+ }
109
+ if (['openai-codex', 'github-copilot', 'google-antigravity', 'google-gemini-cli'].includes(provider)) {
110
+ throw new Error('Sign in to this provider in the sandbox pi profile.')
111
+ }
112
+ const agentDir = join(home, 'agents', provider)
113
+ const env = { ...login, PI_OFFLINE: '1', PI_CODING_AGENT_DIR: agentDir }
114
+ for (const name of ['LANG', 'LC_ALL', 'TZ', 'HTTPS_PROXY', 'HTTP_PROXY', 'NO_PROXY', 'https_proxy', 'http_proxy', 'no_proxy', 'SSL_CERT_FILE', 'NODE_EXTRA_CA_CERTS']) {
115
+ if (process.env[name]) env[name] = process.env[name]
116
+ }
117
+ env.BROCO_API_KEY = await resolveIsolatedApiKey(provider, login, agentDir)
118
+ env.BROCO_MARKER = marker
119
+ env.BROCO_IN_WORKER = '1'
120
+ return env
121
+ }
122
+
123
+ export async function spawnPi(model, cwd, marker, args) {
124
+ const provider = model.startsWith('pi:') ? model.slice(3) : providerOf(model)
125
+ const env = await workerEnvironment(provider, marker)
126
+ env.BROCO_IN_WORKER = '1'
127
+ const sessionFlag = args.lastIndexOf('--session-dir')
128
+ if (sessionFlag !== -1) {
129
+ env.PI_CODING_AGENT_SESSION_DIR = args[sessionFlag + 1]
130
+ mkdirSync(env.PI_CODING_AGENT_SESSION_DIR, { recursive: true })
131
+ }
132
+ mkdirSync(dirname(marker), { recursive: true })
133
+ const fd = openSync(marker, 'a+', 0o600)
134
+ try {
135
+ const [file, ...argv] = platform.piCommand(args, isolated ? 'isolated' : null)
136
+ const child = spawn(file, argv, {
137
+ cwd, env, detached: true, stdio: ['pipe', 'pipe', 'pipe', fd]
138
+ })
139
+ let stderr = ''
140
+ child.stderr.on('data', part => { stderr = (stderr + part.toString('utf8')).slice(-4096) })
141
+ const rawSecrets = secretsFrom([], env)
142
+ const escapedSecrets = [...new Set(rawSecrets.flatMap(v => [JSON.stringify(v).slice(1, -1), v]).filter(v => v.length >= 4))].sort((a, b) => b.length - a.length)
143
+ return {
144
+ child,
145
+ redact: line => mask(line, escapedSecrets),
146
+ rawSecrets,
147
+ getStderr: () => redactStderr(stderr, env, rawSecrets)
148
+ }
149
+ } finally { closeSync(fd) }
150
+ }
151
+
152
+ export function onLine(stream, consume) {
153
+ let buffer = ''
154
+ stream.setEncoding('utf8')
155
+ stream.on('data', chunk => {
156
+ buffer += chunk
157
+ let lf
158
+ while ((lf = buffer.indexOf('\n')) !== -1) {
159
+ const line = buffer.slice(0, lf)
160
+ buffer = buffer.slice(lf + 1)
161
+ if (line.trim()) consume(line)
162
+ }
163
+ })
164
+ }
165
+
166
+ export class Pi {
167
+ static async launch(c, onRecord, onExit, sessions, marker) {
168
+ const provider = c.provider.slice(3)
169
+ const selector = c.model === c.provider ? ['--models', provider + '/*'] : ['--provider', provider, '--model', c.model.slice(provider.length + 1)]
170
+ const args = ['--mode', 'rpc', ...selector, '--session-dir', sessions, '--session-id', c.id, '--no-approve']
171
+ if (c.thinking) args.push('--thinking', c.thinking)
172
+ if (isolated) args.push('--no-extensions', '--no-mcp', '--no-skills', '--no-prompt-templates', '--no-themes', '--tools', 'read,bash,edit,write')
173
+ const { child, redact, rawSecrets, getStderr } = await spawnPi(c.model, c.cwd, marker, args)
174
+ return new Pi(child, redact, onRecord, onExit, rawSecrets, getStderr)
175
+ }
176
+
177
+ constructor(child, redact, onRecord, onExit, rawSecrets = [], getStderr = () => '') {
178
+ this.child = child
179
+ this.pending = new Map()
180
+ this.turn = 0
181
+ this.expectedExit = false
182
+ this.closed = new Promise(resolve => {
183
+ let problem
184
+ const fail = err => {
185
+ problem = err
186
+ child.kill('SIGKILL')
187
+ }
188
+ child.on('error', () => fail(new Error('Could not launch sandboxed pi')))
189
+ child.stdin.on('error', () => fail(new Error('Lost pi RPC stdin')))
190
+ onLine(child.stdout, line => {
191
+ if (problem) return
192
+ try {
193
+ const record = parseRedactedJson(redact(line), rawSecrets)
194
+ if (typeof record.type !== 'string') throw new Error()
195
+ onRecord(this, record)
196
+ const ack = record.type === 'response' && this.pending.get(record.id)
197
+ if (ack) {
198
+ this.pending.delete(record.id)
199
+ if (record.success) ack.resolve(record.data)
200
+ else ack.reject(Object.assign(new Error(record.error || 'pi rejected ' + record.command), { declined: true }))
201
+ }
202
+ } catch { fail(new Error('Could not read or persist pi RPC record')) }
203
+ })
204
+ child.once('close', (code, signal) => {
205
+ const detail = !problem && code !== 0 ? getStderr() : ''
206
+ const err = problem || new Error('pi exited (' + (signal || code) + ')' + (detail ? ': ' + detail : ''))
207
+ this.exited = true
208
+ for (const ack of this.pending.values()) ack.reject(err)
209
+ this.pending.clear()
210
+ onExit(this, err)
211
+ resolve()
212
+ })
213
+ })
214
+ }
215
+
216
+ command(type, args = {}, timeout = 25000) {
217
+ if (this.exited) return Promise.reject(new Error('pi is offline'))
218
+ const id = randomUUID()
219
+ let timer
220
+ const response = new Promise((resolve, reject) => {
221
+ this.pending.set(id, { resolve, reject })
222
+ timer = setTimeout(() => {
223
+ this.pending.delete(id)
224
+ this.child.kill('SIGKILL')
225
+ reject(new Error('Timed out waiting for pi ' + type))
226
+ }, timeout)
227
+ timer.unref?.()
228
+ this.child.stdin.write(JSON.stringify({ id, type, ...args }) + '\n')
229
+ })
230
+ return response.finally(() => clearTimeout(timer))
231
+ }
232
+ }
@@ -0,0 +1,13 @@
1
+ function unsupported() {
2
+ throw new Error('broco desktop integration currently requires macOS or Linux')
3
+ }
4
+
5
+ export const platform = process.platform === 'darwin'
6
+ ? await import('./macos.mjs')
7
+ : process.platform === 'linux'
8
+ ? await import('./linux.mjs')
9
+ : {
10
+ startService: unsupported, removeService: unsupported, removeLegacyService: unsupported, openTerminal: unsupported, pickFolder: unsupported,
11
+ openBrowser: unsupported, hasDesktop: async () => false, openDesktop: unsupported, reveal: unsupported,
12
+ piCommand: unsupported, owned: unsupported, reap: unsupported
13
+ }
@@ -0,0 +1,138 @@
1
+ import { execFile, spawn } from 'node:child_process'
2
+ import { randomUUID } from 'node:crypto'
3
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import { setTimeout as sleep } from 'node:timers/promises'
6
+ import { fileURLToPath } from 'node:url'
7
+ import { promisify } from 'node:util'
8
+ import { home, isolated, socketFor, socketPath } from '../paths.mjs'
9
+
10
+ const exec = promisify(execFile)
11
+ const runnerPath = fileURLToPath(new URL('../runner.mjs', import.meta.url))
12
+
13
+ export function serviceLabelFor(socket = socketPath) {
14
+ return 'me.yanauto.broco.' + socket.split('-').at(-1).replace('.sock', '')
15
+ }
16
+
17
+ export function legacyServiceLabelFor(socket = socketPath) {
18
+ return 'me.yanauto.cc-bro.' + socket.split('-').at(-1).replace('.sock', '')
19
+ }
20
+
21
+ const label = serviceLabelFor(socketPath)
22
+ const domain = 'gui/' + process.getuid()
23
+ const target = domain + '/' + label
24
+
25
+ function ctl(...args) {
26
+ return exec('/bin/launchctl', args, { timeout: 10000 })
27
+ }
28
+
29
+ function serviceEnv() {
30
+ return {
31
+ BROCO_HOME: home,
32
+ PATH: process.env.PATH,
33
+ HOME: process.env.HOME,
34
+ ...(process.env.BROCO_PORT ? { BROCO_PORT: process.env.BROCO_PORT } : {}),
35
+ ...(process.env.BROCO_CONCURRENCY ? { BROCO_CONCURRENCY: process.env.BROCO_CONCURRENCY } : {}),
36
+ ...(process.env.BROCO_TZ ? { BROCO_TZ: process.env.BROCO_TZ } : {}),
37
+ ...(process.env.TZ ? { TZ: process.env.TZ } : {}),
38
+ ...(isolated ? { PI_CODING_AGENT_DIR: join(home, 'login') } :
39
+ process.env.PI_CODING_AGENT_DIR ? { PI_CODING_AGENT_DIR: process.env.PI_CODING_AGENT_DIR } : {}),
40
+ PI_CODING_AGENT_SESSION_DIR: join(home, 'sessions')
41
+ }
42
+ }
43
+
44
+ function useDetachedRunner() {
45
+ return isolated && process.env.BROCO_FORCE_LAUNCHD !== '1'
46
+ }
47
+
48
+ function alive(pid) {
49
+ if (!Number.isSafeInteger(pid) || pid <= 1) return false
50
+ try { process.kill(pid, 0); return true }
51
+ catch (err) { return err.code === 'EPERM' }
52
+ }
53
+
54
+ export async function startService() {
55
+ if (useDetachedRunner()) {
56
+ mkdirSync(home, { recursive: true, mode: 0o700 })
57
+ const pidFile = join(home, 'runner.pid')
58
+ if (existsSync(pidFile)) {
59
+ const existing = Number(readFileSync(pidFile, 'utf8').trim())
60
+ if (alive(existing)) return
61
+ }
62
+ const child = spawn(process.execPath, [runnerPath], {
63
+ cwd: home,
64
+ env: { ...process.env, ...serviceEnv() },
65
+ detached: true,
66
+ stdio: 'ignore'
67
+ })
68
+ writeFileSync(pidFile, String(child.pid) + '\n', { mode: 0o600 })
69
+ child.unref()
70
+ return
71
+ }
72
+
73
+ mkdirSync(home, { recursive: true, mode: 0o700 })
74
+ const path = join(home, 'runner.plist')
75
+ const specPath = join(home, 'runner.spec.json')
76
+ const values = {
77
+ Label: label,
78
+ ThrottleInterval: 1,
79
+ ProgramArguments: [process.execPath, runnerPath],
80
+ EnvironmentVariables: serviceEnv()
81
+ }
82
+ const specJson = JSON.stringify(values)
83
+ const unchanged = existsSync(path) && existsSync(specPath) && readFileSync(specPath, 'utf8') === specJson
84
+ if (unchanged) {
85
+ try {
86
+ await ctl('kickstart', target)
87
+ return
88
+ } catch (err) {
89
+ if (err.code === 37) return
90
+ }
91
+ } else if (existsSync(path)) {
92
+ try { await ctl('bootout', target) } catch {}
93
+ }
94
+
95
+ const tmp = path + '.' + randomUUID()
96
+ writeFileSync(tmp, specJson, { mode: 0o600 })
97
+ try {
98
+ await exec('/usr/bin/plutil', ['-convert', 'xml1', tmp])
99
+ renameSync(tmp, path)
100
+ writeFileSync(specPath, specJson, { mode: 0o600 })
101
+ } finally { rmSync(tmp, { force: true }) }
102
+ try { await ctl('bootstrap', domain, path) } catch {}
103
+ try { await ctl('kickstart', target) }
104
+ catch (err) {
105
+ if (err.code === 37) return
106
+ throw new Error('Could not start the broco launchd service in ' + domain)
107
+ }
108
+ }
109
+
110
+ async function stopPidFile(dir) {
111
+ const pidFile = join(dir, 'runner.pid')
112
+ if (!existsSync(pidFile)) return
113
+ const pid = Number(readFileSync(pidFile, 'utf8').trim())
114
+ rmSync(pidFile, { force: true })
115
+ if (alive(pid)) {
116
+ try { process.kill(pid, 'SIGTERM') } catch {}
117
+ const deadline = Date.now() + 3000
118
+ while (Date.now() < deadline && alive(pid)) await sleep(50)
119
+ }
120
+ }
121
+
122
+ export async function removeService() {
123
+ if (useDetachedRunner()) {
124
+ await stopPidFile(home)
125
+ return
126
+ }
127
+ try { await ctl('bootout', target) }
128
+ catch (err) { if (![3, 36, 113].includes(err.code)) throw err }
129
+ }
130
+
131
+ export async function removeLegacyService(legacyDir) {
132
+ if (!legacyDir) return
133
+ await stopPidFile(legacyDir)
134
+ if (useDetachedRunner()) return
135
+ const legacyTarget = domain + '/' + legacyServiceLabelFor(socketFor(legacyDir))
136
+ try { await ctl('bootout', legacyTarget) }
137
+ catch (err) { if (![3, 36, 113].includes(err.code)) throw err }
138
+ }
@@ -0,0 +1,168 @@
1
+ import { execFile, spawn } from 'node:child_process'
2
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
3
+ import { join } from 'node:path'
4
+ import { setTimeout as sleep } from 'node:timers/promises'
5
+ import { fileURLToPath } from 'node:url'
6
+ import { promisify } from 'node:util'
7
+ import { home, isolated, toolsPath } from '../paths.mjs'
8
+
9
+ const exec = promisify(execFile)
10
+ const runnerPath = fileURLToPath(new URL('../runner.mjs', import.meta.url))
11
+
12
+ function serviceEnv() {
13
+ return {
14
+ BROCO_HOME: home,
15
+ PATH: process.env.PATH,
16
+ HOME: process.env.HOME,
17
+ ...(process.env.BROCO_PORT ? { BROCO_PORT: process.env.BROCO_PORT } : {}),
18
+ ...(process.env.BROCO_CONCURRENCY ? { BROCO_CONCURRENCY: process.env.BROCO_CONCURRENCY } : {}),
19
+ ...(process.env.BROCO_TZ ? { BROCO_TZ: process.env.BROCO_TZ } : {}),
20
+ ...(process.env.TZ ? { TZ: process.env.TZ } : {}),
21
+ ...(isolated ? { PI_CODING_AGENT_DIR: join(home, 'login') } :
22
+ process.env.PI_CODING_AGENT_DIR ? { PI_CODING_AGENT_DIR: process.env.PI_CODING_AGENT_DIR } : {}),
23
+ PI_CODING_AGENT_SESSION_DIR: join(home, 'sessions')
24
+ }
25
+ }
26
+
27
+ function alive(pid) {
28
+ if (!Number.isSafeInteger(pid) || pid <= 1) return false
29
+ try { process.kill(pid, 0); return true }
30
+ catch (err) { return err.code === 'EPERM' }
31
+ }
32
+
33
+ function parseProcStat(pidName) {
34
+ try {
35
+ const raw = readFileSync('/proc/' + pidName + '/stat', 'utf8')
36
+ const close = raw.lastIndexOf(')')
37
+ if (close < 0) return null
38
+ const pid = Number(raw.slice(0, raw.indexOf(' ')))
39
+ const rest = raw.slice(close + 2).trim().split(/\s+/)
40
+ const state = rest[0]
41
+ if (!Number.isSafeInteger(pid) || pid <= 1 || state === 'Z') return null
42
+ const parent = Number(rest[1])
43
+ const birth = rest[19] ?? ''
44
+ return { pid, parent, birth }
45
+ } catch {
46
+ return null
47
+ }
48
+ }
49
+
50
+ function processTable() {
51
+ if (!existsSync('/proc')) return []
52
+ const rows = []
53
+ for (const entry of readdirSync('/proc')) {
54
+ if (!/^\d+$/.test(entry)) continue
55
+ const parsed = parseProcStat(entry)
56
+ if (parsed) rows.push(parsed)
57
+ }
58
+ return rows
59
+ }
60
+
61
+ function holders(marker) {
62
+ const st = statSync(marker, { throwIfNoEntry: false })
63
+ if (!st || !existsSync('/proc')) return []
64
+ const pids = []
65
+ for (const entry of readdirSync('/proc')) {
66
+ if (!/^\d+$/.test(entry)) continue
67
+ const pid = Number(entry)
68
+ if (pid <= 1 || pid === process.pid) continue
69
+ let fds
70
+ try { fds = readdirSync('/proc/' + entry + '/fd') } catch { continue }
71
+ for (const fd of fds) {
72
+ try {
73
+ const fdStat = statSync('/proc/' + entry + '/fd/' + fd)
74
+ if (fdStat.dev === st.dev && fdStat.ino === st.ino) {
75
+ pids.push(pid)
76
+ break
77
+ }
78
+ } catch {}
79
+ }
80
+ }
81
+ return pids
82
+ }
83
+
84
+ export function owned(marker, known = [], childPid) {
85
+ const marked = new Set(holders(marker))
86
+ const table = processTable()
87
+ const old = new Map(known.map(p => [p.pid, p.birth]))
88
+ const roots = table.filter(p => marked.has(p.pid) || old.get(p.pid) === p.birth || (p.pid === childPid && p.parent === process.pid))
89
+ const ids = new Set(roots.map(p => p.pid))
90
+ let size
91
+ do {
92
+ size = ids.size
93
+ for (const p of table) if (ids.has(p.parent)) ids.add(p.pid)
94
+ } while (ids.size > size)
95
+ return table.filter(p => ids.has(p.pid))
96
+ }
97
+
98
+ export async function reap(marker, known = []) {
99
+ for (let i = 0; i < 24; i++) {
100
+ known = owned(marker, known)
101
+ if (!known.length) {
102
+ rmSync(marker, { force: true })
103
+ return
104
+ }
105
+ for (const p of known) {
106
+ try { process.kill(p.pid, i < 5 ? 'SIGTERM' : 'SIGKILL') }
107
+ catch (err) { if (err.code !== 'ESRCH') throw err }
108
+ }
109
+ await sleep(70)
110
+ }
111
+ throw new Error('Could not confirm that all owned processes exited')
112
+ }
113
+
114
+ export async function startService() {
115
+ mkdirSync(home, { recursive: true, mode: 0o700 })
116
+ const pidFile = join(home, 'runner.pid')
117
+ if (existsSync(pidFile)) {
118
+ const existing = Number(readFileSync(pidFile, 'utf8').trim())
119
+ if (alive(existing)) return
120
+ }
121
+ const child = spawn(process.execPath, [runnerPath], {
122
+ cwd: home,
123
+ env: { ...process.env, ...serviceEnv() },
124
+ detached: true,
125
+ stdio: 'ignore'
126
+ })
127
+ writeFileSync(pidFile, String(child.pid) + '\n', { mode: 0o600 })
128
+ child.unref()
129
+ }
130
+
131
+ async function stopPidFile(dir) {
132
+ const pidFile = join(dir, 'runner.pid')
133
+ if (!existsSync(pidFile)) return
134
+ const pid = Number(readFileSync(pidFile, 'utf8').trim())
135
+ rmSync(pidFile, { force: true })
136
+ if (alive(pid)) {
137
+ try { process.kill(pid, 'SIGTERM') } catch {}
138
+ const deadline = Date.now() + 3000
139
+ while (Date.now() < deadline && alive(pid)) await sleep(50)
140
+ }
141
+ }
142
+
143
+ export async function removeService() {
144
+ await stopPidFile(home)
145
+ }
146
+
147
+ export async function removeLegacyService(legacyDir) {
148
+ if (!legacyDir) return
149
+ await stopPidFile(legacyDir)
150
+ }
151
+
152
+ export function piCommand(args) {
153
+ return ['pi', ...args]
154
+ }
155
+
156
+ export async function openBrowser(url) {
157
+ await exec('xdg-open', [url])
158
+ }
159
+
160
+ export async function openTerminal(command, cwd) {
161
+ if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) {
162
+ throw new Error('No graphical display available on Linux; run directly: ' + command)
163
+ }
164
+ const quote = s => "'" + s.replaceAll("'", "'\\''") + "'"
165
+ const shellCmd = 'cd -- ' + quote(cwd) + ' && PATH=' + quote(toolsPath) + ' ' + command + '; exec "${SHELL:-/bin/sh}"'
166
+ await exec('x-terminal-emulator', ['-e', '/bin/sh', '-c', shellCmd])
167
+ return { status: 'opened', command, cwd }
168
+ }
@@ -0,0 +1,29 @@
1
+ import { execFile } from 'node:child_process'
2
+ import { promisify } from 'node:util'
3
+ import { personalPi } from '../paths.mjs'
4
+ import { toolsPath } from '../paths.mjs'
5
+ export { startService, removeService, removeLegacyService } from './launchd.mjs'
6
+ export { owned, reap } from './processes.mjs'
7
+
8
+ const exec = promisify(execFile)
9
+ export function piCommand(args, access) {
10
+ return protectedCommand(['pi', ...args],access)
11
+ }
12
+
13
+ export function protectedCommand(args, access) {
14
+ if (!access) return args
15
+ const deny = access === 'readonly' ? 'file-write*' : 'file-read* file-write*'
16
+ return ['/usr/bin/sandbox-exec', '-D', 'PERSONAL=' + personalPi, '-p',
17
+ '(version 1)(allow default)(deny ' + deny + ' (subpath (param "PERSONAL")))', ...args]
18
+ }
19
+
20
+ export async function openBrowser(url) {
21
+ await exec('/usr/bin/open', [url])
22
+ }
23
+
24
+ export async function openTerminal(command, cwd) {
25
+ const quote = s => "'" + s.replaceAll("'", "'\\''") + "'"
26
+ const script = 'on run argv\ntell application "Terminal"\nactivate\ndo script (item 1 of argv)\nend tell\nend run'
27
+ await exec('/usr/bin/osascript', ['-e', script, 'cd -- ' + quote(cwd) + ' && PATH=' + quote(toolsPath) + ' ' + command])
28
+ return { status: 'opened', command, cwd }
29
+ }
@@ -0,0 +1,102 @@
1
+ import { execFile, execFileSync } from 'node:child_process'
2
+ import { existsSync, rmSync } from 'node:fs'
3
+ import { setTimeout as sleep } from 'node:timers/promises'
4
+ import { promisify } from 'node:util'
5
+
6
+ const exec = promisify(execFile)
7
+
8
+ function parseProcessTable(output) {
9
+ const trimmed = output.trim()
10
+ if (!trimmed) return []
11
+ const rows = []
12
+ for (const line of trimmed.split('\n')) {
13
+ const match = line.trim().match(/^(\d+)\s+(\d+)\s+(\S+)\s+(.+?)\s*$/)
14
+ if (!match) continue
15
+ const [, pid, parent, state, birth] = match
16
+ if (state.startsWith('Z')) continue
17
+ rows.push({ pid: Number(pid), parent: Number(parent), birth })
18
+ }
19
+ return rows
20
+ }
21
+
22
+ function processTable() {
23
+ const output = execFileSync('/bin/ps', ['-axo', 'pid=,ppid=,state=,lstart='], { encoding: 'utf8', env: { ...process.env, LC_ALL: 'C' } })
24
+ return parseProcessTable(output)
25
+ }
26
+
27
+ async function processTableAsync() {
28
+ const { stdout } = await exec('/bin/ps', ['-axo', 'pid=,ppid=,state=,lstart='], { encoding: 'utf8', env: { ...process.env, LC_ALL: 'C' }, maxBuffer: 8 * 1024 * 1024 })
29
+ return parseProcessTable(stdout)
30
+ }
31
+
32
+ function parseHolders(output) {
33
+ const text = (output ?? '').trim()
34
+ if (!text) return []
35
+ const pids = text.split(/\s+/).map(Number)
36
+ if (pids.some(pid => !Number.isSafeInteger(pid) || pid <= 1 || pid === process.pid)) {
37
+ throw new Error('Invalid process identity')
38
+ }
39
+ return pids
40
+ }
41
+
42
+ function holders(marker) {
43
+ if (!existsSync(marker)) return []
44
+ try {
45
+ const output = execFileSync('/usr/sbin/lsof', ['-nP', '-t', '--', marker], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] })
46
+ return parseHolders(output)
47
+ } catch (err) {
48
+ if (!existsSync(marker) || /No such file or directory/i.test(err.stderr ?? '')) return []
49
+ if (err.status === 1 && !err.stdout?.trim() && !err.stderr?.trim()) return []
50
+ throw new Error('Cannot verify pi process ownership with lsof')
51
+ }
52
+ }
53
+
54
+ async function holdersAsync(marker) {
55
+ if (!existsSync(marker)) return []
56
+ try {
57
+ const { stdout } = await exec('/usr/sbin/lsof', ['-nP', '-t', '--', marker], { encoding: 'utf8', maxBuffer: 2 * 1024 * 1024 })
58
+ return parseHolders(stdout)
59
+ } catch (err) {
60
+ if (!existsSync(marker) || /No such file or directory/i.test(err.stderr ?? '')) return []
61
+ if (err.code === 1 && !err.stdout?.trim() && !err.stderr?.trim()) return []
62
+ throw new Error('Cannot verify pi process ownership with lsof')
63
+ }
64
+ }
65
+
66
+ function computeOwned(table, markedIds, known = [], childPid) {
67
+ const marked = new Set(markedIds)
68
+ const old = new Map(known.map(p => [p.pid, p.birth]))
69
+ const roots = table.filter(p => marked.has(p.pid) || old.get(p.pid) === p.birth || (p.pid === childPid && p.parent === process.pid))
70
+ const ids = new Set(roots.map(p => p.pid))
71
+ let size
72
+ do {
73
+ size = ids.size
74
+ for (const p of table) if (ids.has(p.parent)) ids.add(p.pid)
75
+ } while (ids.size > size)
76
+ return table.filter(p => ids.has(p.pid))
77
+ }
78
+
79
+ export function owned(marker, known = [], childPid) {
80
+ return computeOwned(processTable(), holders(marker), known, childPid)
81
+ }
82
+
83
+ export async function ownedAsync(marker, known = [], childPid) {
84
+ const [markedIds, table] = await Promise.all([holdersAsync(marker), processTableAsync()])
85
+ return computeOwned(table, markedIds, known, childPid)
86
+ }
87
+
88
+ export async function reap(marker, known = []) {
89
+ for (let i = 0; i < 24; i++) {
90
+ known = await ownedAsync(marker, known)
91
+ if (!known.length) {
92
+ rmSync(marker, { force: true })
93
+ return
94
+ }
95
+ for (const p of known) {
96
+ try { process.kill(p.pid, i < 5 ? 'SIGTERM' : 'SIGKILL') }
97
+ catch (err) { if (err.code !== 'ESRCH') throw err }
98
+ }
99
+ await sleep(70)
100
+ }
101
+ throw new Error('Could not confirm that all owned processes exited')
102
+ }