@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/bin/broco ADDED
@@ -0,0 +1,1077 @@
1
+ #!/usr/bin/env node
2
+ import { execFileSync } from 'node:child_process'
3
+ import { existsSync, lstatSync, readFileSync, realpathSync, statSync } from 'node:fs'
4
+ import { createInterface } from 'node:readline/promises'
5
+ import { dirname, join, resolve, sep } from 'node:path'
6
+ import { DatabaseSync } from 'node:sqlite'
7
+ import { setTimeout as sleep } from 'node:timers/promises'
8
+ import { chooseAllow, chooseDefault } from '../lib/worker-policy.mjs'
9
+ import { rosterOutput, rosterText } from '../lib/roster-output.mjs'
10
+ import { parseCommand } from '../lib/cli-args.mjs'
11
+ import { directoryOption, expandHome } from '../lib/directories.mjs'
12
+ import { modelVariables } from '../lib/model-env.mjs'
13
+ import {
14
+ FIRST_RUN_PROMPT,
15
+ detectLegacyMigration,
16
+ formatSetupRoster,
17
+ migrateLegacyCcBro,
18
+ probeSetupWorkers,
19
+ readGlobalPolicy,
20
+ saveGlobalAllowlist,
21
+ setupInfo
22
+ } from '../lib/setup.mjs'
23
+ import { call, probeReady, ready, shutdown, shutdownEffect } from '../lib/client.mjs'
24
+ import { platform } from '../lib/platform/index.mjs'
25
+ import { Store, formatQueuedActivity } from '../lib/store.mjs'
26
+ import { batchDetail, isBatch, listBatches } from '../lib/map.mjs'
27
+ import { hint } from '../lib/problems.mjs'
28
+ import { windowLabel } from '../lib/quota.mjs'
29
+ import { statsText } from '../lib/stats.mjs'
30
+ import { credentialValue } from '../lib/credential-source.mjs'
31
+ import { proxyConfig } from '../lib/credential-proxy.mjs'
32
+ import { formatDateTime, resolvedTimeZone } from '../lib/time.mjs'
33
+ import { home, repo } from '../lib/paths.mjs'
34
+
35
+ const CONFIG_COMMANDS = new Set(['defaults', 'note', 'set', 'allow', 'deny', 'rules', 'hide', 'unhide', 'audit', 'undo'])
36
+ const TICKET_STATUSES = new Set(['queued', 'working', 'review', 'done', 'active'])
37
+
38
+ let jsonPrinted = false
39
+ function printJson(value) {
40
+ jsonPrinted = true
41
+ console.log(JSON.stringify(value))
42
+ }
43
+
44
+ function versionInfo() {
45
+ const pkg = JSON.parse(readFileSync(join(repo, 'package.json'), 'utf8'))
46
+ let commit = null
47
+ if (existsSync(join(repo, '.git'))) {
48
+ try {
49
+ commit = execFileSync('git', ['-C', repo, 'rev-parse', '--short', 'HEAD'], {
50
+ encoding: 'utf8',
51
+ stdio: ['ignore', 'pipe', 'ignore'],
52
+ timeout: 2000
53
+ }).trim() || null
54
+ } catch { commit = null }
55
+ }
56
+ return { version: pkg.version, commit }
57
+ }
58
+
59
+ function table(store) {
60
+ const rows = store.list()
61
+ function seconds(r) {
62
+ return r.started ? Math.max(0, Math.floor(((r.finished ?? Date.now()) - r.started) / 1000)) : 0
63
+ }
64
+ return ['NAME\tMODEL\tDIRECTORY\tSTATUS\tTURN\tELAPSED\tACTIVITY', ...rows.map(r =>
65
+ [r.name, r.model, r.cwd, r.status, r.turn, seconds(r) + 's', r.activity].join('\t'))].join('\n')
66
+ }
67
+
68
+ function problemLine(problem) {
69
+ const text = hint(problem)
70
+ return text ? 'Problem: ' + problem.class + ' · ' + text : null
71
+ }
72
+
73
+ function spentLine(quota) {
74
+ if (!quota?.spent?.length) return null
75
+ return 'Quota spent this turn: ' + quota.spent.map(s => windowLabel(s.minutes) + ' ' + s.percent + '%').join(' · ')
76
+ }
77
+
78
+ function convo(store, name) {
79
+ const c = store.byName(name)
80
+ if (!c) throw new Error('Unknown conversation: ' + name)
81
+ return c
82
+ }
83
+
84
+ function formatBatchText(detail, { full = false } = {}) {
85
+ const c = detail.counts
86
+ const header = 'Batch ' + detail.prefix + ' · ' + detail.count + ' shards (' +
87
+ ['queued=' + c.queued, 'working=' + c.working, 'review=' + c.review, 'done=' + c.done, 'error=' + c.error, 'stopped=' + c.stopped].join(', ') + ')' +
88
+ (detail.shards.length !== detail.count ? ' [showing ' + detail.shards.length + ']' : '')
89
+ const rows = detail.shards.map(s => {
90
+ const body = full && s.reply ? s.reply.replace(/\s+/g, ' ').trim() : null
91
+ const summary = body ?? s.replyPreview ?? (s.problem ? s.problem.class + ': ' + s.problem.message : s.activity)
92
+ return [s.name, s.status, s.turn, s.input, summary].join('\t')
93
+ })
94
+ return [header, 'SHARD\tSTATUS\tTURN\tINPUT\tSUMMARY', ...rows].join('\n')
95
+ }
96
+
97
+ function formatStatusText(status) {
98
+ const r = status.runner
99
+ const runnerLine = r.online
100
+ ? (r.incompatible
101
+ ? 'Runner: online (pid ' + r.pid + ', incompatible protocol ' + r.protocol + '; run broco shutdown to upgrade)'
102
+ : 'Runner: online (pid ' + r.pid + ', protocol ' + r.protocol + ', up ' + r.uptimeSec + 's' + (r.startedLocal ? ', since ' + r.startedLocal : '') + ')')
103
+ : 'Runner: offline' + (r.lastStopReason ? ' · last stop: ' + r.lastStopReason : '')
104
+ const lines = [
105
+ runnerLine,
106
+ r.webUrl ? 'Board: ' + r.webUrl : null,
107
+ r.activeProxies ? 'Credential proxies: ' + r.activeProxies + ' active' : null
108
+ ]
109
+ const p = status.project
110
+ if (p) {
111
+ const c = p.counts ?? { queued: 0, working: 0, review: 0, done: 0 }
112
+ lines.push(
113
+ 'Project: ' + p.name + ' (' + p.repoPath + ')' + (p.implicit ? ' [L0]' : '') + ' · bro=' + (p.worker || 'none') + ' · concurrency=' + p.concurrency,
114
+ 'Tickets: running=' + (p.runningCount ?? 0) + ', queued=' + c.queued + ', review=' + c.review + ', done=' + c.done +
115
+ (p.errorCount ? ', error=' + p.errorCount : '') + (p.stoppedCount ? ', stopped=' + p.stoppedCount : '') +
116
+ (p.activeNames?.length ? ' · active: ' + p.activeNames.join(', ') : ''),
117
+ p.activeBatches?.length ? 'Active batches: ' + p.activeBatches.map(b => b.prefix + ' (' + (b.counts.done + b.counts.review) + '/' + b.count + ')').join(', ') : null,
118
+ p.retainedWorktrees ? 'Worktrees: ' + p.retainedWorktrees + ' retained (' + p.cleanableWorktrees + ' cleanable with broco clean)' : null
119
+ )
120
+ } else {
121
+ lines.push('Project: unregistered directory (' + status.totals.projects + ' registered projects; running=' + status.totals.running + ', queued=' + status.totals.queued + ', review=' + status.totals.review + ')')
122
+ }
123
+ if (status.projects?.length > 1 || (!p && status.projects?.length)) {
124
+ lines.push(
125
+ 'PROJECTS\tCONCURRENCY\tRUNNING\tQUEUED\tREVIEW\tDONE\tATTENTION',
126
+ ...status.projects.map(s => [s.name, s.concurrency, s.runningCount ?? 0, s.counts.queued, s.counts.review, s.counts.done, s.attention].join('\t'))
127
+ )
128
+ }
129
+ return lines.filter(Boolean).join('\n')
130
+ }
131
+
132
+ function offlineStatus(targetCwd, probe, all) {
133
+ const regPath = join(home, 'registry-v2.sqlite')
134
+ if (!existsSync(regPath)) {
135
+ return {
136
+ runner: {
137
+ online: probe.online,
138
+ compatible: !probe.incompatible,
139
+ ...(probe.incompatible ? { incompatible: true } : {}),
140
+ ...(probe.legacySocket ? { legacySocket: true } : {}),
141
+ pid: probe.runner?.pid ?? null,
142
+ protocol: probe.runner?.protocol ?? null,
143
+ startedAt: null,
144
+ startedLocal: null,
145
+ uptimeSec: 0,
146
+ lastStopReason: null,
147
+ webUrl: null,
148
+ activeProxies: 0,
149
+ proxies: []
150
+ },
151
+ project: null,
152
+ projects: [],
153
+ totals: { projects: 0, running: 0, queued: 0, review: 0, done: 0, attention: 0 }
154
+ }
155
+ }
156
+ const db = new DatabaseSync(regPath, { readOnly: true })
157
+ try {
158
+ const hasTable = name => Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(name))
159
+ const rs = hasTable('runner_state') ? (db.prepare('SELECT * FROM runner_state WHERE id=1').get() ?? null) : null
160
+ const rawProjects = hasTable('projects') ? db.prepare('SELECT * FROM projects ORDER BY created').all() : []
161
+ const settingsMap = new Map()
162
+ if (hasTable('roster_settings')) {
163
+ for (const row of db.prepare('SELECT scope, data FROM roster_settings').all()) {
164
+ settingsMap.set(row.scope, JSON.parse(row.data))
165
+ }
166
+ }
167
+ const globalCfg = settingsMap.get('global') ?? {}
168
+ const envConc = Number.isSafeInteger(Number(process.env.BROCO_CONCURRENCY ?? 3)) && Number(process.env.BROCO_CONCURRENCY ?? 3) >= 1
169
+ ? Number(process.env.BROCO_CONCURRENCY ?? 3)
170
+ : 3
171
+
172
+ const inspectProject = row => {
173
+ const local = settingsMap.get(row.id) ?? {}
174
+ const allow = local.inheritPolicy ? (globalCfg.allow ?? []) : JSON.parse(row.allow || '[]')
175
+ const worker = local.inheritPolicy ? (globalCfg.worker ?? '') : (row.worker ?? '')
176
+ const concurrency = local.concurrency ?? row.concurrency ?? globalCfg.concurrency ?? envConc
177
+ const counts = { queued: 0, working: 0, review: 0, done: 0 }
178
+ let attention = 0, runningCount = 0, errorCount = 0, stoppedCount = 0, updated = row.created
179
+ let activeNames = [], queuedNames = [], batches = [], retainedWorktrees = 0, cleanableWorktrees = 0
180
+ const tPath = join(home, 'projects', row.id, 'tickets.sqlite')
181
+ if (existsSync(tPath)) {
182
+ const store = new Store(true, tPath)
183
+ try {
184
+ for (const r of store.stmt('SELECT stage,flag,count(*) AS n,max(updated) AS updated FROM tickets GROUP BY stage,flag').all()) {
185
+ counts[r.stage] += r.n
186
+ if (r.stage === 'working' && !r.flag) runningCount += r.n
187
+ if (r.flag === 'error') errorCount += r.n
188
+ if (r.flag === 'stopped') stoppedCount += r.n
189
+ if (r.flag || r.stage === 'review') attention += r.n
190
+ updated = Math.max(updated, r.updated)
191
+ }
192
+ activeNames = store.stmt("SELECT name FROM conversations WHERE status='running' ORDER BY name").all().map(r => r.name)
193
+ queuedNames = store.stmt("SELECT c.name FROM conversations c LEFT JOIN turns r ON r.cid=c.id AND r.turn=c.turn WHERE c.status='queued' ORDER BY r.started ASC, r.rowid ASC, c.rowid ASC").all().map(r => r.name)
194
+ batches = listBatches(store).map(b => ({ prefix: b.prefix, title: b.title, count: b.count, counts: b.counts, finished: b.finished }))
195
+ for (const wr of store.stmt('SELECT m.worktree, t.stage FROM collaboration m JOIN tickets t ON t.cid=m.cid WHERE m.worktree IS NOT NULL').all()) {
196
+ if (existsSync(wr.worktree)) {
197
+ retainedWorktrees += 1
198
+ if (wr.stage === 'done') cleanableWorktrees += 1
199
+ }
200
+ }
201
+ } finally { store.db.close() }
202
+ }
203
+ const summary = {
204
+ id: row.id,
205
+ name: row.name,
206
+ repoPath: row.repoPath,
207
+ implicit: Boolean(row.implicit),
208
+ allow,
209
+ worker,
210
+ concurrency,
211
+ counts,
212
+ runningCount,
213
+ attention,
214
+ updatedAt: new Date(updated).toISOString()
215
+ }
216
+ const detailed = {
217
+ ...summary,
218
+ errorCount,
219
+ stoppedCount,
220
+ activeNames,
221
+ queuedNames,
222
+ batches,
223
+ activeBatches: batches.filter(b => !b.finished),
224
+ retainedWorktrees,
225
+ cleanableWorktrees
226
+ }
227
+ return { summary, detailed }
228
+ }
229
+
230
+ const inspected = rawProjects.map(inspectProject)
231
+ const byId = new Map(inspected.map(x => [x.summary.id, x]))
232
+ let resolvedId = null
233
+ if (targetCwd && existsSync(targetCwd)) {
234
+ const real = realpathSync.native(targetCwd)
235
+ for (let root = real; ; root = dirname(root)) {
236
+ const marker = [join(root, '.broco', 'project-id'), join(root, '.cc-bro', 'project-id')]
237
+ .find(p => lstatSync(p, { throwIfNoEntry: false })?.isFile())
238
+ if (marker) {
239
+ const candidate = readFileSync(marker, 'utf8').trim()
240
+ if (byId.has(candidate)) { resolvedId = candidate; break }
241
+ }
242
+ if (dirname(root) === root) break
243
+ }
244
+ if (!resolvedId) {
245
+ const prefixMatch = rawProjects
246
+ .filter(p => real === p.repoPath || real.startsWith(p.repoPath + sep))
247
+ .sort((a, b) => b.repoPath.length - a.repoPath.length)[0]
248
+ if (prefixMatch) resolvedId = prefixMatch.id
249
+ }
250
+ }
251
+ const summaries = inspected.map(x => x.summary)
252
+ return {
253
+ runner: {
254
+ online: probe.online,
255
+ compatible: !probe.incompatible,
256
+ ...(probe.incompatible ? { incompatible: true } : {}),
257
+ ...(probe.legacySocket ? { legacySocket: true } : {}),
258
+ pid: probe.runner?.pid ?? null,
259
+ protocol: probe.runner?.protocol ?? null,
260
+ startedAt: rs?.started ? new Date(rs.started).toISOString() : null,
261
+ startedLocal: rs?.started ? formatDateTime(rs.started) : null,
262
+ uptimeSec: 0,
263
+ lastStopReason: rs?.stop_reason ?? null,
264
+ webUrl: null,
265
+ activeProxies: 0,
266
+ proxies: []
267
+ },
268
+ project: resolvedId ? byId.get(resolvedId).detailed : null,
269
+ projects: all ? inspected.map(x => x.detailed) : summaries,
270
+ totals: {
271
+ projects: summaries.length,
272
+ running: summaries.reduce((n, s) => n + s.runningCount, 0),
273
+ queued: summaries.reduce((n, s) => n + s.counts.queued, 0),
274
+ review: summaries.reduce((n, s) => n + s.counts.review, 0),
275
+ done: summaries.reduce((n, s) => n + s.counts.done, 0),
276
+ attention: summaries.reduce((n, s) => n + s.attention, 0)
277
+ }
278
+ }
279
+ } finally {
280
+ db.close()
281
+ }
282
+ }
283
+
284
+ function readTextSource(pathOrDash, labelName) {
285
+ if (pathOrDash === '-') return readFileSync(0, 'utf8')
286
+ const file = resolve(expandHome(pathOrDash))
287
+ if (!existsSync(file) || !statSync(file).isFile()) throw new Error(labelName + ' file not found: ' + pathOrDash)
288
+ return readFileSync(file, 'utf8')
289
+ }
290
+
291
+ function readSayText(argument, opt) {
292
+ if (opt.file !== undefined && opt['brief-file'] !== undefined) {
293
+ throw new Error('Specify either --file or --brief-file, not both')
294
+ }
295
+ const fileOpt = opt.file ?? opt['brief-file']
296
+ if (fileOpt !== undefined && argument !== undefined) {
297
+ throw new Error('Specify either <message> or --file, not both')
298
+ }
299
+ if (fileOpt !== undefined) return readTextSource(fileOpt, 'Prompt')
300
+ if (argument === '-') return readFileSync(0, 'utf8')
301
+ if (argument !== undefined) return argument
302
+ if (!process.stdin.isTTY) {
303
+ try {
304
+ const piped = readFileSync(0, 'utf8')
305
+ if (piped.trim()) return piped
306
+ } catch {}
307
+ }
308
+ throw new Error('Supply <message>, --file <path>, or pipe prompt text via stdin')
309
+ }
310
+
311
+ function collectMapInputs(opt, trailing) {
312
+ const raw = []
313
+ for (const item of opt.input ?? []) raw.push(item)
314
+ if (opt['inputs-file'] !== undefined) {
315
+ const content = readTextSource(opt['inputs-file'], 'Inputs')
316
+ const trimmed = content.trim()
317
+ if (trimmed.startsWith('[')) {
318
+ const parsed = JSON.parse(trimmed)
319
+ if (!Array.isArray(parsed)) throw new Error('Expected JSON array in --inputs-file')
320
+ for (const item of parsed) raw.push(String(item))
321
+ } else {
322
+ for (const line of content.split(/\r?\n/).map(s => s.trim()).filter(Boolean)) raw.push(line)
323
+ }
324
+ }
325
+ for (const group of opt.inputs ?? []) {
326
+ const expandedGroup = expandHome(group)
327
+ if (group.includes(',') && !existsSync(resolve(expandedGroup))) {
328
+ for (const part of group.split(',').map(s => s.trim()).filter(Boolean)) raw.push(part)
329
+ } else {
330
+ raw.push(group)
331
+ }
332
+ }
333
+ for (const item of trailing) raw.push(item)
334
+ if (!raw.length) throw new Error('Expected at least one shard input (pass [inputs...], --inputs, --input, or --inputs-file)')
335
+ return raw.map(item => {
336
+ const abs = resolve(expandHome(item))
337
+ return existsSync(abs) ? abs : item
338
+ })
339
+ }
340
+
341
+ function readMapBrief(opt) {
342
+ if (opt.brief !== undefined && opt['brief-file'] !== undefined) {
343
+ throw new Error('Specify either --brief or --brief-file, not both')
344
+ }
345
+ if (opt['brief-file'] !== undefined) {
346
+ return readTextSource(opt['brief-file'], 'Brief')
347
+ }
348
+ if (opt.brief !== undefined) {
349
+ const trimmed = opt.brief.trim()
350
+ const candidate = resolve(expandHome(trimmed))
351
+ if (/^\S+\.(?:md|txt|prompt)$/i.test(trimmed)) {
352
+ if (!existsSync(candidate) || !statSync(candidate).isFile()) {
353
+ throw new Error('Brief file not found: ' + opt.brief)
354
+ }
355
+ return readFileSync(candidate, 'utf8')
356
+ }
357
+ return opt.brief
358
+ }
359
+ throw new Error('Supply --brief or --brief-file')
360
+ }
361
+
362
+ async function recoverIfDead(runner) {
363
+ try { process.kill(runner.pid, 0); return runner }
364
+ catch (err) {
365
+ if (err.code !== 'ESRCH') throw err
366
+ return ready()
367
+ }
368
+ }
369
+
370
+ async function waitRemote(projectId, payload, runner) {
371
+ for (;;) {
372
+ try {
373
+ const res = await call('/wait', { projectId, ...payload, timeoutMs: 25000 })
374
+ if (res && res.waiting) {
375
+ runner = await recoverIfDead(runner)
376
+ continue
377
+ }
378
+ return res
379
+ } catch (err) {
380
+ if (['ENOENT', 'ECONNREFUSED', 'ECONNRESET', 'EPIPE', 'ETIMEDOUT'].includes(err.code) || /Runner is shutting down/.test(err.message)) {
381
+ runner = await recoverIfDead(runner)
382
+ await sleep(60)
383
+ continue
384
+ }
385
+ throw err
386
+ }
387
+ }
388
+ }
389
+
390
+ async function watch(store, runner) {
391
+ const initial = store.transaction(() => ({
392
+ cursor: store.stmt('SELECT coalesce(max(id),0) AS id FROM events').get().id,
393
+ board: table(store)
394
+ }))
395
+ let cursor = initial.cursor
396
+ console.log(initial.board)
397
+ for (;;) {
398
+ await sleep(140)
399
+ const batch = store.stmt('SELECT e.id,c.name,e.turn,e.summary FROM events e JOIN conversations c ON e.cid=c.id WHERE e.id>? ORDER BY e.id LIMIT 512').all(cursor)
400
+ if (!batch.length) {
401
+ if (store.stmt("SELECT 1 FROM conversations WHERE status='running' LIMIT 1").get()) runner = await recoverIfDead(runner)
402
+ continue
403
+ }
404
+ cursor = batch.at(-1).id
405
+ const events = batch.filter(e => e.summary)
406
+ if (!events.length) continue
407
+ if (process.stdout.isTTY) process.stdout.write('\x1b[2J\x1b[H' + table(store) + '\n\n')
408
+ for (const e of events) console.log(e.name + ' #' + e.turn + ' ' + e.summary)
409
+ }
410
+ }
411
+
412
+ function auditSuffix(res) {
413
+ return ' (audit #' + res.auditId + '; undo: broco undo ' + res.auditId + ')'
414
+ }
415
+
416
+ async function runSetup(opt) {
417
+ let migration
418
+ if (opt['migrate-cc-bro']) {
419
+ migration = await migrateLegacyCcBro()
420
+ } else {
421
+ migration = detectLegacyMigration()
422
+ }
423
+
424
+ const install = setupInfo()
425
+ const detected = await probeSetupWorkers({ cwd: process.cwd() })
426
+ const existing = readGlobalPolicy()
427
+ const loggedInIds = detected.filter(w => w.loggedIn).map(w => w.id)
428
+
429
+ if (!opt.json) {
430
+ console.log('Skills installed:')
431
+ for (const h of install.hosts) {
432
+ console.log(' - ' + h.id + ': ' + h.skillPath)
433
+ }
434
+ console.log('Launcher: ' + install.launcher)
435
+ if (migration.migrated) {
436
+ console.log('Migrated legacy data from ' + migration.legacyDir + ' -> ' + migration.targetDir + ' (original preserved)')
437
+ }
438
+ console.log('')
439
+ console.log('Detected CLIs & live quota:')
440
+ console.log(formatSetupRoster(detected, existing.allow, existing.defaultWorker))
441
+ }
442
+
443
+ let allowlist = {
444
+ configured: existing.configured,
445
+ changed: false,
446
+ confirmedBy: null,
447
+ allow: existing.allow,
448
+ defaultWorker: existing.defaultWorker,
449
+ recommended: loggedInIds,
450
+ hint: null
451
+ }
452
+
453
+ if (opt.allow !== undefined) {
454
+ const saved = await saveGlobalAllowlist(opt.allow, { defaultWorker: opt['default-worker'] })
455
+ allowlist = {
456
+ configured: true,
457
+ changed: true,
458
+ confirmedBy: 'flag',
459
+ allow: saved.allow,
460
+ defaultWorker: saved.defaultWorker,
461
+ auditId: saved.auditId,
462
+ recommended: loggedInIds,
463
+ hint: null
464
+ }
465
+ } else if (opt.yes) {
466
+ if (loggedInIds.length) {
467
+ const saved = await saveGlobalAllowlist(loggedInIds, { defaultWorker: opt['default-worker'] })
468
+ allowlist = {
469
+ configured: true,
470
+ changed: true,
471
+ confirmedBy: 'yes',
472
+ allow: saved.allow,
473
+ defaultWorker: saved.defaultWorker,
474
+ auditId: saved.auditId,
475
+ recommended: loggedInIds,
476
+ hint: null
477
+ }
478
+ } else {
479
+ allowlist.hint = 'No logged-in worker CLIs detected. Sign in to a CLI and run broco allow <ids> --global.'
480
+ }
481
+ } else if (process.stdin.isTTY && !opt.json) {
482
+ const recommended = existing.configured ? existing.allow : loggedInIds
483
+ if (recommended.length) {
484
+ const reader = createInterface({ input: process.stdin, output: process.stderr })
485
+ let answer
486
+ try {
487
+ answer = (await reader.question('\nAllow global workers [' + recommended.join(',') + ']? Press Enter to confirm, enter comma-separated IDs, or type "skip": ')).trim()
488
+ } finally {
489
+ reader.close()
490
+ }
491
+ if (/^(?:skip|none|n|no)$/i.test(answer)) {
492
+ if (!existing.configured) {
493
+ allowlist.hint = 'Global allowlist not set. Run: broco allow ' + recommended.join(',') + ' --global'
494
+ }
495
+ } else {
496
+ const chosen = answer ? answer : recommended
497
+ const saved = await saveGlobalAllowlist(chosen, { defaultWorker: opt['default-worker'] })
498
+ allowlist = {
499
+ configured: true,
500
+ changed: true,
501
+ confirmedBy: 'prompt',
502
+ allow: saved.allow,
503
+ defaultWorker: saved.defaultWorker,
504
+ auditId: saved.auditId,
505
+ recommended: loggedInIds,
506
+ hint: null
507
+ }
508
+ }
509
+ } else if (!existing.configured) {
510
+ allowlist.hint = 'No logged-in worker CLIs detected. Sign in to a CLI and run broco allow <ids> --global.'
511
+ }
512
+ } else if (!existing.configured) {
513
+ const suggested = loggedInIds.length ? loggedInIds.join(',') : '<ids>'
514
+ allowlist.hint = 'Global allowlist is not configured yet (never auto-enabled without confirmation). Run: broco allow ' + suggested + ' --global (or broco setup --allow ' + suggested + ' / broco setup --yes)'
515
+ }
516
+
517
+ const out = {
518
+ ...install,
519
+ detected,
520
+ allowlist,
521
+ migration,
522
+ firstRunPrompt: FIRST_RUN_PROMPT
523
+ }
524
+ if (opt.json) return printJson(out)
525
+
526
+ console.log('')
527
+ if (allowlist.configured) {
528
+ console.log('Global allowlist: ' + allowlist.allow.join(', ') + ' (default: ' + allowlist.defaultWorker + ')' + (allowlist.changed ? ' [saved]' : ' [unchanged]'))
529
+ } else if (allowlist.hint) {
530
+ console.log(allowlist.hint)
531
+ }
532
+ if (migration.available) {
533
+ console.log('Legacy ~/.cc-bro data detected at ' + migration.legacyDir + '. Run `broco setup --migrate-cc-bro` to copy it safely without deleting ~/.cc-bro.')
534
+ }
535
+ console.log('')
536
+ console.log('Try asking your coding agent:')
537
+ console.log(' "' + FIRST_RUN_PROMPT + '"')
538
+ }
539
+
540
+ async function main() {
541
+ const { cmd, opt, positionals, help } = parseCommand(process.argv.slice(2))
542
+ if (help) return console.log(help)
543
+ if (cmd === 'version') {
544
+ const info = versionInfo()
545
+ return opt.json ? printJson(info) : console.log(info.commit ? info.version + ' (' + info.commit + ')' : info.version)
546
+ }
547
+ if (cmd === 'setup') {
548
+ return runSetup(opt)
549
+ }
550
+ if (['say', 'review', 'map', 'retry'].includes(cmd) && process.env.BROCO_IN_WORKER === '1' && !opt['allow-nested']) {
551
+ throw new Error('Refusing nested broco ' + cmd + ' inside a worker session (BROCO_IN_WORKER=1). Return your result to the caller instead, or pass --allow-nested to override explicitly.')
552
+ }
553
+ if (opt.cwd !== undefined && opt.worktree) throw new Error('--cwd cannot be combined with --worktree')
554
+ if (opt.global && opt.project !== undefined) throw new Error('--global cannot be combined with --project')
555
+ if (cmd === 'audit' && opt.all && (opt.global || opt.project !== undefined)) {
556
+ throw new Error('--all cannot be combined with --global or --project')
557
+ }
558
+ const projectPath = directoryOption(opt.project, '--project')
559
+ const cwd = directoryOption(opt.cwd, '--cwd')
560
+ const [name, argument] = positionals
561
+
562
+ if (cmd === 'status') {
563
+ const targetCwd = projectPath ?? process.cwd()
564
+ const probe = await probeReady()
565
+ const status = probe.online && !probe.incompatible
566
+ ? await call('/status', { cwd: targetCwd, all: !!opt.all })
567
+ : offlineStatus(targetCwd, probe, !!opt.all)
568
+ return opt.json ? printJson(status) : console.log(formatStatusText(status))
569
+ }
570
+
571
+ if (cmd === 'set' && !['concurrency', 'default-worker'].includes(name)) {
572
+ throw new Error('Unsupported setting key: ' + name + ' (expected concurrency or default-worker)')
573
+ }
574
+ if (cmd === 'note') {
575
+ if (!opt.clear && argument === undefined) throw new Error('Supply note text or --clear')
576
+ if (opt.clear && argument !== undefined) throw new Error('Cannot combine note text with --clear')
577
+ if (!opt.clear && !argument.trim()) throw new Error('Note is empty; pass --clear to clear')
578
+ }
579
+ let sayText
580
+ if (cmd === 'say') {
581
+ sayText = readSayText(argument, opt)
582
+ }
583
+ let mapBrief, mapInputs
584
+ if (cmd === 'map') {
585
+ mapBrief = readMapBrief(opt)
586
+ mapInputs = collectMapInputs(opt, positionals.slice(1))
587
+ }
588
+ if (cmd === 'shutdown') {
589
+ if (!opt.json) console.error(shutdownEffect)
590
+ await shutdown()
591
+ return opt.json ? printJson({ status: 'offline' }) : console.log('Runner stopped')
592
+ }
593
+ let proxyInput
594
+ if (cmd === 'proxy-open') {
595
+ proxyInput = { upstream: opt.upstream, paths: opt.path, header: opt.header, valuePrefix: opt['value-prefix'], maxRequests: opt['max-requests'], ttl: opt.ttl }
596
+ proxyConfig(proxyInput)
597
+ proxyInput.value = await credentialValue(opt)
598
+ }
599
+ const runner = await ready()
600
+ if (['proxy-open', 'proxy-list', 'proxy-close'].includes(cmd)) {
601
+ if (!runner.credentialProxy) throw new Error('This runner does not support credential proxies. Run broco shutdown after finishing active work, then retry.')
602
+ const reply = await call('/' + cmd, proxyInput || (cmd === 'proxy-close' ? { id: name } : {}))
603
+ if (opt.json) return printJson(reply)
604
+ if (cmd === 'proxy-close') return console.log(reply.id + ' closed')
605
+ const rows = cmd === 'proxy-open' ? [reply] : reply
606
+ return console.log(['ID\tURL\tREQUESTS\tEXPIRES (' + resolvedTimeZone() + ')', ...rows.map(r => [r.id, r.url,
607
+ r.requests + '/' + r.maxRequests, formatDateTime(r.expiresAt)].join('\t'))].join('\n'))
608
+ }
609
+ if (cmd === 'init') {
610
+ const skipAgentsMd = Boolean(opt['no-agents-md'] || opt['no-claude-md'])
611
+ const input = {
612
+ cwd: projectPath ?? process.cwd(),
613
+ allow: opt.allow,
614
+ worker: opt['default-worker'],
615
+ concurrency: opt.concurrency,
616
+ agentsMd: !skipAgentsMd,
617
+ claudeMd: !skipAgentsMd,
618
+ host: opt.host,
619
+ managerMode: !!opt['manager-mode']
620
+ }
621
+ let p
622
+ for (;;) {
623
+ try { p = await call('/register', input); break } catch (err) {
624
+ if (!process.stdin.isTTY || ![chooseAllow, chooseDefault].includes(err.message)) throw err
625
+ const reader = createInterface({ input: process.stdin, output: process.stderr })
626
+ try {
627
+ if (err.message === chooseAllow) input.allow = await reader.question('Allowed workers (claude, codex, agy, cursor-agent, pi:<provider>, custom:<name>; comma-separated): ')
628
+ else input.worker = await reader.question('Default worker from the allowed list: ')
629
+ } finally { reader.close() }
630
+ }
631
+ }
632
+ if (opt.json) return printJson(p)
633
+ const doc = p.agentsMd ?? p.claudeMd
634
+ const lines = [
635
+ p.name + ': ' + p.allow.join(', ') + ' (default: ' + p.worker + ', concurrency: ' + p.concurrency + ')',
636
+ doc ? (doc.file || 'AGENTS.md') + ': ' + doc.action + ' (' + doc.path + ')' : null
637
+ ].filter(Boolean)
638
+ return console.log(lines.join('\n'))
639
+ }
640
+ if (cmd === 'uninit') {
641
+ const skipAgentsMd = Boolean(opt['no-agents-md'] || opt['no-claude-md'])
642
+ const res = await call('/unregister', { cwd: projectPath ?? process.cwd(), agentsMd: !skipAgentsMd, claudeMd: !skipAgentsMd, host: opt.host })
643
+ if (opt.json) return printJson(res)
644
+ const doc = res.agentsMd ?? res.claudeMd
645
+ const lines = [
646
+ res.unregistered ? 'Unregistered project at ' + res.repoPath : 'No registered project at ' + res.repoPath,
647
+ res.markerRemoved ? 'Removed .broco marker' : null,
648
+ doc ? (doc.file || 'AGENTS.md') + ': ' + doc.action + ' (' + doc.path + ')' : null
649
+ ].filter(Boolean)
650
+ return console.log(lines.join('\n'))
651
+ }
652
+ if (cmd === 'ui') {
653
+ const { url } = await call('/ui', {})
654
+ if (!opt['no-open']) await platform.openBrowser(url)
655
+ return opt.json ? printJson({ url }) : console.log(url)
656
+ }
657
+ if (CONFIG_COMMANDS.has(cmd)) {
658
+ const readOnlyConfig = cmd === 'audit' || (cmd === 'rules' && !(opt.add?.length || opt.rm?.length || opt.clear || opt.override)) || cmd === 'undo'
659
+ let scope
660
+ if (cmd === 'audit' && opt.all) scope = 'all'
661
+ else if (opt.global) scope = 'global'
662
+ else if (cmd === 'undo' && name !== undefined && opt.project === undefined) scope = null
663
+ else if (readOnlyConfig) {
664
+ const ctx = await call('/context', { cwd: projectPath ?? process.cwd(), createImplicit: false, optional: true })
665
+ scope = ctx.projectId ?? null
666
+ } else scope = (await call('/context', { cwd: projectPath ?? process.cwd() })).projectId
667
+
668
+ if (cmd === 'defaults') {
669
+ const res = await call('/defaults-set', { scope, worker: name, model: opt.model, effort: opt.effort, clear: !!opt.clear })
670
+ if (opt.json) return printJson(res)
671
+ return console.log(res.summary + ' · effective model=' + (res.defaults.model || 'CLI default') + ', effort=' + (res.defaults.effort || 'CLI default') + auditSuffix(res))
672
+ }
673
+ if (cmd === 'note') {
674
+ const res = await call('/note-set', { scope, worker: name, note: opt.clear ? '' : argument })
675
+ return opt.json ? printJson(res) : console.log(res.summary + auditSuffix(res))
676
+ }
677
+ if (cmd === 'set') {
678
+ if (name === 'concurrency') {
679
+ const res = await call('/concurrency-set', { scope, concurrency: argument })
680
+ return opt.json ? printJson(res) : console.log(res.summary + ' · effective concurrency=' + res.concurrency + auditSuffix(res))
681
+ }
682
+ const res = await call('/allow-set', { scope, defaultWorker: argument })
683
+ return opt.json ? printJson(res) : console.log(res.summary + auditSuffix(res))
684
+ }
685
+ if (cmd === 'allow') {
686
+ const workers = name.split(',').map(s => s.trim()).filter(Boolean)
687
+ if (!workers.length) throw new Error('Specify at least one worker')
688
+ const res = await call('/allow-set', { scope, add: workers, defaultWorker: opt['default-worker'] })
689
+ return opt.json ? printJson(res) : console.log(res.summary + auditSuffix(res))
690
+ }
691
+ if (cmd === 'deny') {
692
+ const workers = name.split(',').map(s => s.trim()).filter(Boolean)
693
+ if (!workers.length) throw new Error('Specify at least one worker')
694
+ const res = await call('/allow-set', { scope, remove: workers })
695
+ return opt.json ? printJson(res) : console.log(res.summary + auditSuffix(res))
696
+ }
697
+ if (cmd === 'rules') {
698
+ const mutating = Boolean(opt.add?.length || opt.rm?.length || opt.clear || opt.override)
699
+ if (!mutating) {
700
+ const res = await call('/rules-get', { scope: scope ?? 'global', worker: opt.worker ?? null })
701
+ if (opt.json) return printJson(res)
702
+ if (opt.worker) {
703
+ return console.log(res.workerRules.length ? res.workerRules.map(r => 'Rule (' + opt.worker + '): ' + r).join('\n') : 'No active rules for ' + opt.worker)
704
+ }
705
+ const lines = [
706
+ ...res.rules.map(r => 'Rule: ' + r),
707
+ ...Object.entries(res.workerRules ?? {}).flatMap(([w, list]) => list.map(r => 'Rule (' + w + '): ' + r))
708
+ ]
709
+ return console.log(lines.length ? lines.join('\n') : 'No active rules')
710
+ }
711
+ const res = await call('/rules-set', {
712
+ scope,
713
+ add: opt.add ?? [],
714
+ remove: opt.rm ?? [],
715
+ clear: !!opt.clear,
716
+ worker: opt.worker ?? null,
717
+ ...(opt.override ? { rulesOverride: true } : opt.clear ? { rulesOverride: false } : {})
718
+ })
719
+ return opt.json ? printJson(res) : console.log(res.summary + auditSuffix(res))
720
+ }
721
+ if (cmd === 'hide' || cmd === 'unhide') {
722
+ const models = argument.split(',').map(s => s.trim()).filter(Boolean)
723
+ if (!models.length) throw new Error('Specify at least one model ID or family')
724
+ const res = await call('/hidden-models-set', {
725
+ scope,
726
+ worker: name,
727
+ ...(cmd === 'hide' ? { hide: models } : { unhide: models })
728
+ })
729
+ return opt.json ? printJson(res) : console.log(res.summary + auditSuffix(res))
730
+ }
731
+ if (cmd === 'audit') {
732
+ let limit = 30
733
+ if (opt.limit !== undefined) {
734
+ if (!/^\d+$/.test(opt.limit) || Number(opt.limit) < 1 || Number(opt.limit) > 500) {
735
+ throw new Error('Expected --limit between 1 and 500')
736
+ }
737
+ limit = Number(opt.limit)
738
+ }
739
+ const rows = scope === null ? [] : await call('/audit-list', { scope, limit })
740
+ if (opt.json) return printJson(rows)
741
+ return console.log([
742
+ 'ID\tTIME (' + resolvedTimeZone() + ')\tSCOPE\tACTOR\tACTION\tSTATUS\tSUMMARY',
743
+ ...rows.map(r => ['#' + r.id, r.atLocal ?? r.atAsia, r.scopeName || r.scope, r.actor, r.action, r.revertedAt ? 'reverted' : 'active', r.summary].join('\t'))
744
+ ].join('\n'))
745
+ }
746
+ if (cmd === 'undo') {
747
+ let auditId = null
748
+ if (name !== undefined) {
749
+ if (!/^\d+$/.test(name) || Number(name) < 1) throw new Error('Expected a positive integer audit ID')
750
+ auditId = Number(name)
751
+ } else if (scope === null) {
752
+ throw new Error('Nothing to undo for this directory')
753
+ }
754
+ const res = await call('/audit-undo', { id: auditId, scope, actor: 'agent' })
755
+ return opt.json ? printJson(res) : console.log(res.summary + ' (audit #' + res.auditId + ')')
756
+ }
757
+ }
758
+
759
+ if (cmd === 'stats') {
760
+ if (opt.project !== undefined) {
761
+ const ctx = await call('/context', { cwd: projectPath, createImplicit: false, optional: true })
762
+ if (!ctx.projectId) return opt.json ? printJson([]) : console.log(statsText([]))
763
+ const groups = await call('/stats', { projectId: ctx.projectId })
764
+ return opt.json ? printJson(groups) : console.log(statsText(groups))
765
+ }
766
+ const groups = await call('/stats', {})
767
+ return opt.json ? printJson(groups) : console.log(statsText(groups))
768
+ }
769
+
770
+ if (cmd === 'roster') {
771
+ if (opt.global) {
772
+ const roster = rosterOutput(await call('/roster', { global: true, refresh: !!opt.refresh }), { full: opt.full, worker: opt.worker })
773
+ return opt.json ? printJson(roster) : console.log(rosterText(roster))
774
+ }
775
+ const ctx = await call('/context', { cwd: projectPath ?? process.cwd(), createImplicit: false, optional: true })
776
+ if (!ctx.projectId) {
777
+ if (!ctx.globalConfigured) {
778
+ throw new Error('Project is not registered and no global worker allowlist is configured. Run broco setup, broco allow <workers> --global, or broco init in the project root (or pass --global to inspect detected CLIs).')
779
+ }
780
+ const roster = rosterOutput(await call('/roster', { global: true, refresh: !!opt.refresh }), { full: opt.full, worker: opt.worker })
781
+ return opt.json ? printJson(roster) : console.log(rosterText(roster))
782
+ }
783
+ const roster = rosterOutput(await call('/roster', { projectId: ctx.projectId, refresh: !!opt.refresh }), { full: opt.full, worker: opt.worker })
784
+ return opt.json ? printJson(roster) : console.log(rosterText(roster))
785
+ }
786
+
787
+ const needsCreate = cmd === 'say' || cmd === 'map'
788
+ const context = await call('/context', {
789
+ cwd: projectPath ?? process.cwd(),
790
+ ...(needsCreate ? {} : { createImplicit: false, optional: true })
791
+ })
792
+ if (!context.projectId) {
793
+ if (!context.globalConfigured) {
794
+ throw new Error('Project is not registered and no global worker allowlist is configured. Run broco setup, broco allow <workers> --global, or broco init in the project root.')
795
+ }
796
+ if (cmd === 'ls') {
797
+ return opt.json ? printJson([]) : console.log('TICKET\tTITLE\tSTATUS\tFLAG\tMODEL\tACTIVITY')
798
+ }
799
+ if (cmd === 'clean') {
800
+ const empty = { cleaned: [], skipped: [], attachments: { removed: 0, freedBytes: 0, files: [] } }
801
+ return opt.json ? printJson(empty) : console.log('Worktrees cleaned: 0, skipped: 0')
802
+ }
803
+ if (cmd === 'watch') {
804
+ throw new Error('No tickets in this directory yet. Dispatch a ticket with broco say or broco map first.')
805
+ }
806
+ throw new Error('Unknown conversation: ' + name)
807
+ }
808
+ const { projectId, database, defaultCwd } = context
809
+
810
+ if (cmd === 'diff') {
811
+ const res = await call('/diff', { projectId, name, statOnly: !!opt.stat })
812
+ if (opt.json) return printJson(res)
813
+ return console.log((opt.stat ? res.stat : res.patch) || 'No changes')
814
+ }
815
+
816
+ if (cmd === 'clean') {
817
+ const res = await call('/clean', {
818
+ projectId,
819
+ name: name ?? null,
820
+ dryRun: !!opt['dry-run'],
821
+ deleteBranch: !!opt['delete-branch'],
822
+ force: !!opt.force
823
+ })
824
+ if (opt.json) return printJson(res)
825
+ const header = (opt['dry-run'] ? '[dry-run] ' : '') + 'Worktrees cleaned: ' + res.cleaned.length + ', skipped: ' + res.skipped.length +
826
+ (res.attachments?.removed ? ' · attachments removed: ' + res.attachments.removed : '')
827
+ return console.log([
828
+ header,
829
+ ...res.cleaned.map(c => ' cleaned ' + c.name + ' (' + c.worktree + ')' + (c.branchDeleted ? ' [branch deleted]' : c.branchRetainedReason ? ' [' + c.branchRetainedReason + ']' : '')),
830
+ ...res.skipped.map(s => ' skipped ' + s.name + ' (' + s.reason + ')')
831
+ ].join('\n'))
832
+ }
833
+
834
+ if (cmd === 'ls' || cmd === 'show' || cmd === 'watch') {
835
+ const store = new Store(true, database)
836
+ try {
837
+ if (cmd === 'ls') {
838
+ let tickets = store.ticketRows()
839
+ if (opt.active) tickets = tickets.filter(t => t.status !== 'done')
840
+ if (opt.status !== undefined) {
841
+ const requested = opt.status.split(',').map(s => s.trim()).filter(Boolean)
842
+ if (!requested.length || requested.some(s => !TICKET_STATUSES.has(s))) {
843
+ throw new Error('Expected --status from queued,working,review,done,active')
844
+ }
845
+ const allowed = new Set()
846
+ for (const s of requested) {
847
+ if (s === 'active') { allowed.add('queued'); allowed.add('working'); allowed.add('review') }
848
+ else allowed.add(s)
849
+ }
850
+ tickets = tickets.filter(t => allowed.has(t.status))
851
+ }
852
+ if (opt.flag !== undefined) {
853
+ const flags = new Set(opt.flag.split(',').map(s => s.trim()).filter(Boolean))
854
+ tickets = tickets.filter(t => t.flag && flags.has(t.flag))
855
+ }
856
+ if (opt.batch !== undefined) {
857
+ const prefix = opt.batch.trim()
858
+ tickets = tickets.filter(t => t.batch?.prefix === prefix)
859
+ }
860
+ if (opt.limit !== undefined) {
861
+ if (!/^\d+$/.test(opt.limit) || Number(opt.limit) < 1 || Number(opt.limit) > 1000) {
862
+ throw new Error('Expected --limit between 1 and 1000')
863
+ }
864
+ tickets = tickets.slice(-Number(opt.limit))
865
+ }
866
+ return opt.json
867
+ ? printJson(tickets)
868
+ : console.log(['TICKET\tTITLE\tSTATUS\tFLAG\tMODEL\tACTIVITY', ...tickets.map(t =>
869
+ [t.id, t.title, t.status, t.flag ? t.flag + (t.problem && t.flag === 'error' ? '/' + t.problem.class : '') : '-', t.model, t.activity].join('\t'))].join('\n'))
870
+ }
871
+ if (cmd === 'watch') return await watch(store, runner)
872
+ if (cmd === 'show') {
873
+ if (isBatch(store, name)) {
874
+ const detail = batchDetail(store, name, { full: !!opt.full, status: opt.status ?? null })
875
+ return opt.json ? printJson(detail) : console.log(formatBatchText(detail, { full: !!opt.full }))
876
+ }
877
+ const c = convo(store, name)
878
+ if (opt.all) {
879
+ const rows = store.history(c.id)
880
+ const warning = store.contextWarning(c.id, c.turn)
881
+ if (warning && !opt.json) console.error(warning.message)
882
+ return opt.json ? printJson(rows) : console.log(rows.map(m =>
883
+ '[' + m.turn + '] ' + m.kind + (m.number ? ' #' + m.number : '') + ': ' + m.content + (m.error ? ' [' + m.error + ']' : '')).join('\n'))
884
+ }
885
+ let targetTurn = c.turn
886
+ if (opt.turn !== undefined) {
887
+ targetTurn = Number(opt.turn)
888
+ if (!Number.isSafeInteger(targetTurn) || targetTurn < 1) throw new Error('Expected a positive --turn number')
889
+ }
890
+ const result = store.result(c.id, targetTurn)
891
+ const { lastReply, timeline, ...detailRest } = store.detail(name)
892
+ const sessionWarning = c.turn >= 1 && !['running', 'queued'].includes(c.status) && !c.native_id
893
+ ? 'No native session bound yet: use broco retry ' + name + ' (or resend the full prompt on say).'
894
+ : null
895
+ const out = {
896
+ ...detailRest,
897
+ ...(opt.compact ? { timelineCount: timeline.length } : { timeline }),
898
+ name,
899
+ provider: c.provider,
900
+ session: c.native_id,
901
+ transport: c.transport,
902
+ ...(sessionWarning ? { sessionWarning } : {}),
903
+ ...result
904
+ }
905
+ const stepInfo = c.status === 'running' && out.progress?.currentStep ? 'Current step: ' + out.progress.currentStep : null
906
+ return opt.json ? printJson(out) : console.log([
907
+ result.contextWarning?.message,
908
+ sessionWarning,
909
+ stepInfo,
910
+ ...out.tasks.map(t => 'Task ' + t.task + ' · turns ' + t.startTurn + '–' + t.endTurn + ' · ' + t.title + ' · ' + (t.outcome ?? 'unrecorded') + (t.outcomeReason ? ': ' + t.outcomeReason : '')),
911
+ problemLine(result.problem),
912
+ result.reply ?? result.error ?? out.activity ?? c.activity,
913
+ result.cachedInputTokens === null ? null : 'Cached input: ' + result.cachedInputTokens + ' tokens',
914
+ spentLine(result.quota)
915
+ ].filter(Boolean).join('\n'))
916
+ }
917
+ } finally { store.db.close() }
918
+ }
919
+
920
+ if (cmd === 'done') {
921
+ const ticket = await call('/done', { name, projectId, result: opt.result, why: opt.why, task: opt.task === undefined ? undefined : Number(opt.task) })
922
+ if (ticket.closed !== undefined) {
923
+ return opt.json ? printJson(ticket) : console.log([
924
+ 'Batch ' + ticket.prefix + ': closed ' + ticket.closed.length + ', skipped ' + ticket.skipped.length,
925
+ ...ticket.closed.map(s => ' ' + s.name + ' · ' + s.outcome + ' (task ' + s.task + ')'),
926
+ ...ticket.skipped.map(s => ' ' + s.name + ' · skipped (' + s.reason + ')')
927
+ ].join('\n'))
928
+ }
929
+ return opt.json ? printJson(ticket) : console.log([name + ' ' + (['fail', 'blocked'].includes(ticket.outcome) ? 'closed' : 'accepted') + ' · ' + ticket.outcome + (opt.result ? '' : ' (inferred; pass --result to record it explicitly)'), 'Task ' + ticket.task + ' · turns ' + ticket.startTurn + '–' + ticket.endTurn, ticket.cleanupHint].filter(Boolean).join('\n'))
930
+ }
931
+
932
+ if (cmd === 'stop') {
933
+ const result = await call('/stop', { name, projectId })
934
+ if (Array.isArray(result.stopped)) {
935
+ return opt.json ? printJson(result) : console.log([
936
+ 'Batch ' + result.prefix + ': stopped ' + result.stopped.length + ', skipped ' + result.skipped.length,
937
+ ...result.stopped.map(s => ' ' + s.name + ' stopped' + (s.forced ? ' (forced)' : ''))
938
+ ].join('\n'))
939
+ }
940
+ return opt.json ? printJson(result) : console.log(name + ' stopped; processes verified' + (result.forced ? ' (forced)' : ''))
941
+ }
942
+
943
+ if (cmd === 'map') {
944
+ const mapReceipt = await call('/map', {
945
+ projectId,
946
+ prefix: name,
947
+ brief: mapBrief,
948
+ inputs: mapInputs,
949
+ worker: opt.worker,
950
+ model: opt.model,
951
+ effort: opt.effort,
952
+ cwd,
953
+ worktree: opt.worktree,
954
+ title: opt.title,
955
+ env: modelVariables(process.env)
956
+ })
957
+ const runningCount = mapReceipt.shards.filter(s => s.status === 'working').length
958
+ const queuedCount = mapReceipt.shards.filter(s => s.status === 'queued').length
959
+ const ack = mapReceipt.prefix + ' dispatched ' + mapReceipt.count + ' shards (' + runningCount + ' running, ' + queuedCount + ' queued)'
960
+ if (opt.bg) {
961
+ return opt.json ? printJson(mapReceipt) : console.log([
962
+ ack,
963
+ ...mapReceipt.shards.map(s => ' ' + s.name + '\t' + (s.queue ? formatQueuedActivity(s.queue) : s.status) + '\t' + s.worker + '/' + s.model + '\t' + s.input)
964
+ ].join('\n'))
965
+ }
966
+ if (!opt.json) console.error(ack)
967
+ const detail = await waitRemote(projectId, { name: mapReceipt.prefix }, runner)
968
+ if (opt.json) printJson(detail)
969
+ else console.log(formatBatchText(detail))
970
+ if (detail.counts.error > 0 || detail.counts.stopped > 0) {
971
+ throw new Error((detail.counts.error + detail.counts.stopped) + ' of ' + detail.count + ' shards failed or stopped in batch ' + detail.prefix)
972
+ }
973
+ return
974
+ }
975
+
976
+ let receipt
977
+ if (cmd === 'say' || cmd === 'review' || cmd === 'retry') {
978
+ if (cmd === 'review') {
979
+ receipt = await call('/review', { name, by: opt.by || null, model: opt.model, effort: opt.effort, projectId, env: modelVariables(process.env) })
980
+ } else if (cmd === 'retry') {
981
+ receipt = await call('/retry', { name, model: opt.model, effort: opt.effort, worker: opt.worker, projectId, env: modelVariables(process.env) })
982
+ if (receipt.isBatch) {
983
+ const ack = 'Batch ' + receipt.prefix + ': retried ' + receipt.retried.length + ', skipped ' + receipt.skipped.length
984
+ if (opt.bg || !receipt.retried.length) {
985
+ return opt.json ? printJson(receipt) : console.log([
986
+ ack,
987
+ ...receipt.retried.map(s => ' ' + s.name + ' -> turn ' + s.turn + ' (' + s.worker + '/' + s.model + ')')
988
+ ].join('\n'))
989
+ }
990
+ if (!opt.json) console.error(ack)
991
+ const detail = await waitRemote(projectId, { name: receipt.prefix }, runner)
992
+ if (opt.json) printJson(detail)
993
+ else console.log(formatBatchText(detail))
994
+ if (detail.counts.error > 0 || detail.counts.stopped > 0) {
995
+ throw new Error((detail.counts.error + detail.counts.stopped) + ' of ' + detail.count + ' shards failed or stopped in batch ' + detail.prefix)
996
+ }
997
+ return
998
+ }
999
+ } else {
1000
+ receipt = await call('/say', {
1001
+ name,
1002
+ projectId,
1003
+ env: modelVariables(process.env),
1004
+ title: opt.title,
1005
+ from: opt.from,
1006
+ text: sayText,
1007
+ attachments: opt.attach?.map(p => resolve(expandHome(p))),
1008
+ model: opt.model,
1009
+ effort: opt.effort,
1010
+ worker: opt.worker,
1011
+ defaultCwd,
1012
+ cwd,
1013
+ worktree: opt.worktree,
1014
+ newTask: opt['new-task']
1015
+ })
1016
+ }
1017
+ const labels = { injected: '已注入 / injected', queued: '排到下一轮 / queued for next turn', rejected: '被拒 / rejected' }
1018
+ const statusLabel = labels[receipt.outcome] || (receipt.kind === 'queued' ? 'queued' : 'prompt accepted')
1019
+ const ack = [
1020
+ receipt.name + ' task ' + receipt.task + ' message #' + receipt.number + ', turn ' + receipt.turn + ' (' + statusLabel + ')' + (receipt.retriedTurn ? ' [retry of turn ' + receipt.retriedTurn + ']' : '') + (receipt.reason ? ': ' + receipt.reason : ''),
1021
+ receipt.worker + ' · ' + receipt.model + (receipt.effort ? ' · ' + receipt.effort : ''),
1022
+ receipt.queue ? formatQueuedActivity(receipt.queue) : null,
1023
+ receipt.note ? 'Note: ' + receipt.note : null,
1024
+ ...(receipt.reminders ?? []),
1025
+ receipt.sessionWarning && !receipt.reminders?.includes(receipt.sessionWarning) ? receipt.sessionWarning : null,
1026
+ receipt.contextWarning ? receipt.contextWarning.message : null
1027
+ ].filter(Boolean).join('\n')
1028
+ if (receipt.outcome === 'rejected') {
1029
+ process.exitCode = 1
1030
+ return opt.json ? printJson(receipt) : console.log(ack)
1031
+ }
1032
+ if (opt.bg) return opt.json ? printJson(receipt) : console.log(ack)
1033
+ if (!opt.json) console.error(ack)
1034
+ }
1035
+
1036
+ let turnArg = null
1037
+ if (receipt?.turn !== undefined) {
1038
+ turnArg = receipt.turn
1039
+ } else if (argument !== undefined) {
1040
+ turnArg = Number(argument)
1041
+ if (!Number.isSafeInteger(turnArg) || turnArg < 1) throw new Error('Expected a positive turn number')
1042
+ }
1043
+
1044
+ const waited = await waitRemote(projectId, {
1045
+ name: receipt?.name ?? name,
1046
+ ...(turnArg !== null ? { turn: turnArg } : {}),
1047
+ ...(receipt?.number ? { number: receipt.number } : {})
1048
+ }, runner)
1049
+
1050
+ if (waited.isBatch) {
1051
+ if (opt.json) printJson(waited)
1052
+ else console.log(formatBatchText(waited))
1053
+ if (waited.counts.error > 0 || waited.counts.stopped > 0) {
1054
+ throw new Error((waited.counts.error + waited.counts.stopped) + ' of ' + waited.count + ' shards failed or stopped in batch ' + waited.prefix)
1055
+ }
1056
+ return
1057
+ }
1058
+
1059
+ if (opt.json) printJson({ name, ...receipt, ...waited })
1060
+ else {
1061
+ if (waited.contextWarning) console.log(waited.contextWarning.message)
1062
+ if (waited.reply) console.log(waited.reply)
1063
+ }
1064
+ if (waited.status !== 'done') {
1065
+ throw new Error([problemLine(waited.problem), waited.error || waited.status].filter(Boolean).join('\n'))
1066
+ }
1067
+ }
1068
+
1069
+ process.stdout.on('error', err => { if (err.code === 'EPIPE') process.exit(0); throw err })
1070
+ const wantJsonError = process.argv.slice(2).includes('--json')
1071
+ main().catch(err => {
1072
+ if (wantJsonError && !jsonPrinted) {
1073
+ console.log(JSON.stringify({ error: err.message }))
1074
+ }
1075
+ console.error(err.message)
1076
+ process.exitCode = 1
1077
+ })