@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/crew.mjs ADDED
@@ -0,0 +1,947 @@
1
+ import { executable } from './cli-process.mjs'
2
+ import { detectCli } from './detect.mjs'
3
+ import { hiddenModel, matchModel, modelCapabilities } from './model-catalog.mjs'
4
+ import { describeAttachments, snapshotAttachments, piImages } from './attachments.mjs'
5
+ import { tight } from './quota.mjs'
6
+ import { supportedWorker } from './worker-policy.mjs'
7
+ import { randomUUID } from 'node:crypto'
8
+ import { existsSync } from 'node:fs'
9
+ import { baseline, changes, changesAsync, createTree, verifyTree } from './worktree.mjs'
10
+ import { directory } from './directories.mjs'
11
+ import { setTimeout as sleep } from 'node:timers/promises'
12
+ import { withModelEnvironment } from './model-env.mjs'
13
+ import { nativeTurn } from './native.mjs'
14
+ import { streamTurn } from './stream-workers.mjs'
15
+ import { Pi, providerOf } from './pi.mjs'
16
+ import { platform } from './platform/index.mjs'
17
+ import { cachedCatalog, formatQueuedActivity } from './store.mjs'
18
+
19
+ const { owned, reap } = platform
20
+
21
+ const SESSION_UNBOUND_WARNING = '上一轮未建立原生会话,工人看不到上一轮原题;请确认本次消息包含完整题目或用 retry 重跑 / No prior native session was established; worker cannot see earlier failed prompt unless resent.'
22
+
23
+ const PROVIDER_VENDORS = {
24
+ codex: 'openai',
25
+ claude: 'anthropic',
26
+ agy: 'google',
27
+ 'cursor-agent': 'cursor',
28
+ 'pi:openai': 'openai',
29
+ 'pi:openai-codex': 'openai',
30
+ 'pi:anthropic': 'anthropic',
31
+ 'pi:google': 'google',
32
+ 'pi:google-antigravity': 'google',
33
+ 'pi:google-gemini-cli': 'google',
34
+ 'pi:gemini': 'google',
35
+ 'pi:deepseek': 'deepseek',
36
+ 'pi:zai': 'zhipu',
37
+ 'pi:zai-coding-cn': 'zhipu',
38
+ 'pi:zhipu': 'zhipu',
39
+ 'pi:moonshot': 'moonshot',
40
+ 'pi:kimi': 'moonshot',
41
+ 'pi:xai': 'xai',
42
+ 'pi:alibaba': 'alibaba',
43
+ 'pi:qwen': 'alibaba',
44
+ 'pi:dashscope': 'alibaba',
45
+ 'custom:codex-json': 'openai',
46
+ 'custom:gemini': 'google'
47
+ }
48
+
49
+ export function workerVendor(workerId, model = null, catalog = cachedCatalog()) {
50
+ if (typeof model === 'string' && model && model !== workerId) {
51
+ const matched = matchModel(model, catalog)
52
+ if (matched?.vendor) return matched.vendor.toLowerCase()
53
+ }
54
+ if (typeof workerId !== 'string' || !workerId) return null
55
+ if (Object.hasOwn(PROVIDER_VENDORS, workerId)) return PROVIDER_VENDORS[workerId]
56
+ if (workerId.startsWith('pi:')) return workerId.slice(3).toLowerCase()
57
+ return workerId.toLowerCase()
58
+ }
59
+
60
+ function observedCooldown(store, provider) {
61
+ const row = store.stmt("SELECT t.problem,t.finished FROM turns t JOIN conversations c ON c.id=t.cid WHERE c.provider=? AND json_extract(t.problem,'$.class') IN ('quota','region','auth') ORDER BY t.finished DESC LIMIT 1").get(provider)
62
+ if (!row) return null
63
+ const recovered = store.stmt("SELECT coalesce(max(t.finished),0) AS at FROM turns t JOIN conversations c ON c.id=t.cid WHERE c.provider=? AND t.status='done'").get(provider)?.at ?? 0
64
+ if (recovered >= row.finished) return null
65
+ const problem = JSON.parse(row.problem)
66
+ const fresh = problem.resetsAt ? Date.parse(problem.resetsAt) > Date.now() : Date.now() - row.finished < 6 * 3600e3
67
+ return fresh ? problem : null
68
+ }
69
+
70
+ export function normalizeAgyModel(model, effort, listedIds = []) {
71
+ if (typeof model !== 'string' || !model || model === 'agy') return model
72
+ const base = model.replace(/-(?:off|none|minimal|low|medium|high|xhigh|extra-high|max|ultra)$/, '')
73
+ const hadSuffix = base !== model
74
+ const isGeminiFamily = /^gemini-/i.test(base) && !/^gemini-pro-orchestrator\b/i.test(base)
75
+ if (!effort) {
76
+ if (!isGeminiFamily || hadSuffix) return model
77
+ if (listedIds.includes(model)) return model
78
+ if (listedIds.length > 0) return listedIds.find(id => id === base + '-medium') ?? listedIds.find(id => id.startsWith(base + '-')) ?? (base + '-medium')
79
+ return base + '-medium'
80
+ }
81
+ const candidate = base + '-' + effort
82
+ if (listedIds.length > 0) {
83
+ if (listedIds.includes(candidate)) return candidate
84
+ if (listedIds.includes(model) && !hadSuffix) return model
85
+ }
86
+ if (hadSuffix || isGeminiFamily) return candidate
87
+ return model
88
+ }
89
+
90
+ export function activity(e) {
91
+ if (e.type === 'tool_execution_start') {
92
+ const target = e.args?.path ?? e.args?.command ?? ''
93
+ return e.toolName + (target ? ' ' + target : '')
94
+ }
95
+ if (e.type === 'tool_execution_end') return e.toolName + (e.isError ? ' failed' : ' finished')
96
+ if (e.type === 'auto_retry_start') return 'Retrying provider request'
97
+ if (e.type === 'auto_compaction_start') return 'Compacting history'
98
+ if (e.type === 'message_update') {
99
+ const delta = e.assistantMessageEvent?.type
100
+ if (delta === 'thinking_start' || delta === 'thinking_delta') return 'Thinking'
101
+ if (delta === 'text_start' || delta === 'text_delta') return 'Writing reply'
102
+ }
103
+ if (e.type === 'agent_start') return 'Working'
104
+ return ''
105
+ }
106
+
107
+ function messageText(message) {
108
+ if (typeof message.content === 'string') return message.content
109
+ return (message.content ?? []).filter(block => block.type === 'text').map(block => block.text).join('')
110
+ }
111
+
112
+ export class Crew {
113
+ constructor(store, slots, workerSettings = () => ({})) {
114
+ this.store = store
115
+ this.slots = slots
116
+ this.workerSettings = workerSettings
117
+ this.idleTimeoutMs = 10 * 60 * 1000
118
+ this.idleTimers = new Map()
119
+ this.refreshingFiles = new Set()
120
+ this.onQueueChange = cid => store.onChange?.(cid)
121
+ store.queueInfo = cid => slots?.queueInfo?.(cid) ?? null
122
+ store.onStaleFinish = (id, turn) => slots?.release?.(id, turn)
123
+ store.onDone = cid => {
124
+ this.clearIdleTimer(cid)
125
+ const w = this.workers.get(cid)
126
+ if (w && !w.active && !w.stopping) {
127
+ const c = store.stmt('SELECT * FROM conversations WHERE id=?').get(cid) ?? { id: cid }
128
+ this.release(c, w).catch(() => {})
129
+ }
130
+ }
131
+ store.onFinish = (id, next) => {
132
+ const c = store.stmt('SELECT * FROM conversations WHERE id=?').get(id)
133
+ if (c) {
134
+ this.refreshFiles(c, false)
135
+ if (!next) {
136
+ this.environments.delete(id + ':' + (c.turn + 1))
137
+ if (this.workers.has(id)) this.scheduleIdleRelease(id)
138
+ }
139
+ }
140
+ slots?.release?.(id)
141
+ if (next && c && slots.reserve(this, c)) this.serial(c.name, () => {
142
+ const fresh = store.byName(c.name)
143
+ if (fresh && fresh.turn === c.turn && fresh.status === 'queued') return this.dispatch(fresh)
144
+ slots?.release?.(id, c.turn)
145
+ }).catch(() => {
146
+ slots?.release?.(id, c.turn)
147
+ })
148
+ }
149
+ this.workers = new Map()
150
+ this.queues = new Map()
151
+ this.native = new Map()
152
+ this.environments = new Map()
153
+ this.detectWorker = (id, cwd) => detectCli(id, cwd)
154
+ this.syncConcurrency()
155
+ }
156
+
157
+ clearIdleTimer(cid) {
158
+ const timer = this.idleTimers.get(cid)
159
+ if (timer) {
160
+ clearTimeout(timer)
161
+ this.idleTimers.delete(cid)
162
+ }
163
+ }
164
+
165
+ scheduleIdleRelease(cid) {
166
+ this.clearIdleTimer(cid)
167
+ const w = this.workers.get(cid)
168
+ if (!w || w.active || w.stopping || this.idleTimeoutMs <= 0) return
169
+ const timer = setTimeout(() => {
170
+ this.idleTimers.delete(cid)
171
+ const current = this.workers.get(cid)
172
+ if (!current || current !== w || current.active || current.stopping) return
173
+ const c = this.store.stmt('SELECT * FROM conversations WHERE id=?').get(cid)
174
+ if (!c || ['running', 'queued'].includes(c.status)) return
175
+ this.serial(c.name, async () => {
176
+ const fresh = this.store.byName(c.name)
177
+ const target = this.workers.get(cid)
178
+ if (!fresh || ['running', 'queued'].includes(fresh.status) || !target || target.active || target.stopping) return
179
+ await this.release(fresh, target).catch(() => {})
180
+ }).catch(() => {})
181
+ }, this.idleTimeoutMs)
182
+ timer.unref?.()
183
+ this.idleTimers.set(cid, timer)
184
+ }
185
+
186
+ clearEnvFor(cid, turn) {
187
+ if (turn !== undefined) {
188
+ this.environments.delete(cid + ':' + turn)
189
+ return
190
+ }
191
+ const prefix = cid + ':'
192
+ for (const key of [...this.environments.keys()]) {
193
+ if (key.startsWith(prefix)) this.environments.delete(key)
194
+ }
195
+ }
196
+
197
+ syncConcurrency(explicit) {
198
+ if (this.store.readOnly) return
199
+ const configured = this.workerSettings?.()?.concurrency
200
+ const limit = Number.isSafeInteger(explicit) && explicit >= 1
201
+ ? explicit
202
+ : Number.isSafeInteger(configured) && configured >= 1
203
+ ? configured
204
+ : (this.slots?.limitFor?.(this.slots.scopeOf(this), this) ?? this.slots?.limit ?? Number(process.env.BROCO_CONCURRENCY ?? 3))
205
+ if (Number.isSafeInteger(limit) && limit >= 1) this.store.setMetaValue('concurrency', limit)
206
+ }
207
+
208
+ workingDirectory(c, meta = this.store.meta(c.id)) {
209
+ return meta?.cwd ?? (meta?.worktree ? c.cwd : this.workerSettings().repoPath)
210
+ }
211
+
212
+ refreshFiles(c, live = false) {
213
+ if (live && (this.refreshingFiles.has(c.id) || Date.now() - (c.filesChecked ?? 0) < 1200)) return
214
+ c.filesChecked = Date.now()
215
+ const m = this.store.meta(c.id)
216
+ const before = JSON.parse(m?.baseline ?? 'null')
217
+ if (!before) return
218
+ const cwd = this.workingDirectory(c, m)
219
+ if (live) {
220
+ this.refreshingFiles.add(c.id)
221
+ changesAsync(cwd, before)
222
+ .then(files => {
223
+ if (files && this.store.db.isOpen !== false) {
224
+ try { this.store.stmt('UPDATE collaboration SET files=? WHERE cid=?').run(JSON.stringify(files), c.id) } catch {}
225
+ }
226
+ })
227
+ .catch(() => {})
228
+ .finally(() => { this.refreshingFiles.delete(c.id) })
229
+ return
230
+ }
231
+ const files = changes(cwd, before)
232
+ this.store.stmt('UPDATE collaboration SET files=? WHERE cid=?').run(JSON.stringify(files), c.id)
233
+ }
234
+
235
+ serial(name, fn) {
236
+ const previous = this.queues.get(name) || Promise.resolve()
237
+ const result = previous.catch(() => {}).then(fn)
238
+ this.queues.set(name, result)
239
+ const release = () => { if (this.queues.get(name) === result) this.queues.delete(name) }
240
+ result.then(release, release)
241
+ return result
242
+ }
243
+
244
+ async recover(reason) {
245
+ reason ??= 'Runner interrupted; inspect work before resuming'
246
+ const list = this.store.stmt("SELECT * FROM conversations WHERE worker_pid IS NOT NULL OR status='running'").all()
247
+ for (const c of list) {
248
+ for (const m of this.store.stmt("SELECT number,content,turn FROM messages WHERE cid=? AND kind='pending' ORDER BY number").all(c.id)) {
249
+ this.store.follow(c, m.content, 'rejected', 'Runner interrupted; pi delivery unconfirmed', m.turn, m.number)
250
+ }
251
+ if (c.status === 'running') this.store.finish(c.id, c.turn, 'error', reason)
252
+ try {
253
+ await reap(this.store.marker(c.id))
254
+ this.store.owner(c.id, null)
255
+ } catch (err) {
256
+ if (!this.store.finish(c.id, c.turn, 'error', err.message)) this.store.state(c.id, 'error', err.message)
257
+ }
258
+ }
259
+ }
260
+
261
+ async interruptRunning(reason = 'Runner interrupted; inspect work before resuming') {
262
+ for (const timer of this.idleTimers.values()) clearTimeout(timer)
263
+ this.idleTimers.clear()
264
+ await Promise.allSettled([...this.queues.values()])
265
+ const rows = this.store.stmt("SELECT * FROM conversations WHERE worker_pid IS NOT NULL OR status='running'").all()
266
+ for (const c of rows) {
267
+ if (c.status === 'queued') continue
268
+ for (const m of this.store.stmt("SELECT number,content,turn FROM messages WHERE cid=? AND kind='pending' ORDER BY number").all(c.id)) {
269
+ this.store.follow(c, m.content, 'rejected', 'Runner interrupted; pi delivery unconfirmed', m.turn, m.number)
270
+ }
271
+ const native = this.native.get(c.id)
272
+ if (native) {
273
+ const marked = owned(this.store.marker(c.id), [], c.worker_pid)
274
+ this.store.finish(c.id, c.turn, 'error', reason)
275
+ native.controller.abort()
276
+ await reap(this.store.marker(c.id), marked).catch(() => {})
277
+ await native.task.catch(() => {})
278
+ } else {
279
+ const w = this.workers.get(c.id)
280
+ if (c.status === 'running') this.store.finish(c.id, c.turn, 'error', reason)
281
+ await this.release(c, w).catch(() => {})
282
+ }
283
+ this.clearEnvFor(c.id)
284
+ this.slots?.release?.(c.id)
285
+ }
286
+ }
287
+
288
+ async releaseAll() {
289
+ for (const timer of this.idleTimers.values()) clearTimeout(timer)
290
+ this.idleTimers.clear()
291
+ const cids = new Set([
292
+ ...this.workers.keys(),
293
+ ...this.store.stmt('SELECT id FROM conversations WHERE worker_pid IS NOT NULL').all().map(r => r.id)
294
+ ])
295
+ for (const cid of cids) {
296
+ const c = this.store.stmt('SELECT * FROM conversations WHERE id=?').get(cid) ?? { id: cid }
297
+ await this.release(c, this.workers.get(cid)).catch(() => {})
298
+ }
299
+ }
300
+
301
+ record(c, w, e) {
302
+ const s = this.store
303
+ let label = activity(e).replace(/\s+/g, ' ').slice(0, 160)
304
+ if (label === w.activity || !w.active) label = ''
305
+ if (e.type === 'message_update' && !label) return
306
+ s.transaction(() => {
307
+ s.event(c.id, w.turn, e.type, e, label)
308
+ if (e.type === 'tool_execution_end') this.refreshFiles(c, true)
309
+ if (label) {
310
+ w.activity = label
311
+ s.state(c.id, 'running', label)
312
+ }
313
+ if (e.type === 'message_start' && e.message.role === 'user' && w.active) {
314
+ if (w.initialSeen) {
315
+ const item = w.steers.find(item => item.text === messageText(e.message))
316
+ if (item) this.piOutcome(w, item, 'injected', 'pi delivered the message in this turn')
317
+ }
318
+ w.initialSeen = true
319
+ }
320
+ if (e.type === 'message_end' && e.message.role === 'assistant' && w.active) {
321
+ const u = e.message.usage
322
+ if (Number.isSafeInteger(u?.cacheRead)) s.event(c.id, w.turn, 'usage', { cachedInputTokens: u.cacheRead, inputTokens: u.input + u.cacheWrite + u.cacheRead }, 'Cached input: ' + u.cacheRead + ' tokens')
323
+ w.sawAssistant = true
324
+ w.replyId = s.assistant(c.id, w.turn, messageText(e.message))
325
+ w.failure = e.message.stopReason === 'error' ? (e.message.errorMessage || 'Model request failed') : ''
326
+ if (e.message.stopReason === 'length') w.failure = 'Model reached its output limit'
327
+ if (e.message.stopReason === 'aborted') w.failure = 'Aborted by pi'
328
+ }
329
+ if (e.type === 'agent_settled' && w.active && !w.settling) {
330
+ w.settling = true
331
+ w.settled.resolve()
332
+ if (w.stopping) return
333
+ const failure = w.failure || (!w.sawAssistant && 'pi settled without an assistant message')
334
+ const status = e.aborted ? 'stopped' : failure ? 'error' : 'done'
335
+ const detail = e.aborted ? 'Stopped by pi' : failure || 'Waiting for input'
336
+ const finish = () => {
337
+ if (!w.active || w.stopping || w.exited) return
338
+ w.active = false
339
+ s.finish(c.id, w.turn, status, detail, w.replyId)
340
+ }
341
+ if (w.steers.length) this.drainPiSteers(w, status).then(finish)
342
+ else finish()
343
+ }
344
+ })
345
+ }
346
+
347
+ piOutcome(w, item, outcome, reason) {
348
+ const index = w.steers.indexOf(item)
349
+ if (index < 0) return
350
+ w.steers.splice(index, 1)
351
+ const turn = item.c.turn + (outcome === 'queued' ? 1 : 0)
352
+ const receipt = this.store.follow(item.c, item.text, outcome, reason, turn, item.number)
353
+ if (outcome === 'queued') this.environments.set(item.c.id + ':' + turn, item.env)
354
+ item.receipt.resolve(receipt)
355
+ }
356
+
357
+ steerPi(c, w, text, env) {
358
+ const number = this.store.message(c.id, c.turn, 'pending', text)
359
+ const item = { c, text, env, number, receipt: Promise.withResolvers() }
360
+ w.steers.push(item)
361
+ item.ack = w.command('steer', { message: text }).then(ack => {
362
+ if (ack?.disposition === 'queued') return
363
+ if (ack?.disposition !== 'handled') w.resetBeforeReuse = true
364
+ this.piOutcome(w, item, 'rejected', 'pi did not confirm queueing for model delivery')
365
+ }, err => this.piOutcome(w, item, err.declined && !w.stopping ? 'queued' : 'rejected', err.message))
366
+ return { delivery: item.receipt.promise }
367
+ }
368
+
369
+ async drainPiSteers(w, status) {
370
+ await Promise.all(w.steers.map(item => item.ack))
371
+ if (!w.steers.length) return
372
+ let remaining = []
373
+ try {
374
+ const cleared = await w.command('clear_queue')
375
+ if (Array.isArray(cleared?.steering)) remaining = cleared.steering
376
+ else w.resetBeforeReuse = true
377
+ } catch { w.resetBeforeReuse = true }
378
+ for (const item of [...w.steers]) {
379
+ const index = remaining.indexOf(item.text)
380
+ if (index >= 0 && status === 'done' && !w.stopping) {
381
+ remaining.splice(index, 1)
382
+ this.piOutcome(w, item, 'queued', 'Recovered undelivered steer from pi for next turn')
383
+ } else this.piOutcome(w, item, 'rejected', 'pi turn ended without confirmed delivery')
384
+ }
385
+ }
386
+
387
+ rejectMessage(cid, number, error) {
388
+ this.store.stmt('UPDATE messages SET error=? WHERE cid=? AND number=?').run(error, cid, number)
389
+ }
390
+
391
+ async worker(c) {
392
+ this.clearIdleTimer(c.id)
393
+ let w = this.workers.get(c.id)
394
+ if (w && !w.resetBeforeReuse) return w
395
+ if (w) await this.release(c, w)
396
+ else if (c.worker_pid !== null) await reap(this.store.marker(c.id))
397
+ this.store.owner(c.id, 0)
398
+ w = await Pi.launch(c, (worker, record) => this.record(c, worker, record), (worker, err) => {
399
+ if (worker.expectedExit) return
400
+ this.clearIdleTimer(c.id)
401
+ for (const item of [...(worker.steers ?? [])]) this.piOutcome(worker, item, 'rejected', 'pi exited before confirming steer')
402
+ if (!this.store.finish(c.id, worker.turn, 'error', err.message)) this.store.state(c.id, 'error', err.message)
403
+ this.workers.delete(c.id)
404
+ this.serial(c.name, async () => {
405
+ if (this.workers.has(c.id) || this.store.byName(c.name).worker_pid !== worker.child.pid) return
406
+ await reap(this.store.marker(c.id))
407
+ this.store.owner(c.id, null)
408
+ }).catch(error => this.store.state(c.id, 'error', error.message))
409
+ }, this.store.sessions, this.store.marker(c.id))
410
+ this.workers.set(c.id, w)
411
+ this.store.owner(c.id, w.child.pid)
412
+ const state = await w.command('get_state')
413
+ const selected = state?.model
414
+ const actual = selected?.provider + '/' + selected?.id
415
+ if (selected?.provider !== c.provider.slice(3) || !selected.id || (c.model !== c.provider && actual !== c.model) || state.sessionId !== c.id) {
416
+ throw new Error('pi did not select the requested model and session: ' + c.model)
417
+ }
418
+ if (c.thinking && state.thinkingLevel && state.thinkingLevel !== c.thinking) throw new Error('pi did not select the requested effort: ' + c.thinking)
419
+ this.store.stmt("UPDATE conversations SET model=?,native_id=?,transport='pi-rpc' WHERE id=?").run(actual, state.sessionId, c.id)
420
+ return w
421
+ }
422
+
423
+ async release(c, w) {
424
+ this.clearIdleTimer(c.id)
425
+ const marker = this.store.marker(c.id)
426
+ const known = owned(marker, [], w?.child.pid)
427
+ let forced = false
428
+ if (w) {
429
+ w.expectedExit = true
430
+ w.stopping = true
431
+ for (const item of [...(w.steers ?? [])]) this.piOutcome(w, item, 'rejected', 'Stopped before pi confirmed delivery')
432
+ if (w.active && !w.exited) {
433
+ try {
434
+ const terminal = Promise.all([w.command('abort', {}, 4500), w.settled.promise])
435
+ const ack = await Promise.race([terminal.then(() => true), sleep(5000, false, { ref: false })])
436
+ forced = !ack
437
+ } catch { forced = true }
438
+ }
439
+ w.child.stdin.end()
440
+ await Promise.race([w.closed, sleep(600, null, { ref: false })])
441
+ }
442
+ await reap(marker, known)
443
+ if (w && !w.exited) {
444
+ const closed = await Promise.race([w.closed.then(() => true), sleep(1500, false, { ref: false })])
445
+ if (!closed) throw new Error('Could not verify pi RPC process exit')
446
+ }
447
+ this.workers.delete(c.id)
448
+ this.store.owner(c.id, null)
449
+ return forced
450
+ }
451
+
452
+ async pickReviewWorker(p, { model, settings, catalog }) {
453
+ const allow = settings.allow ?? []
454
+ const writerVendor = workerVendor(p.provider, p.model, catalog)
455
+ const crossCandidates = []
456
+ for (const [index, id] of allow.entries()) {
457
+ if (!supportedWorker(id) || id === p.provider) continue
458
+ const entry = settings.entries?.[id] ?? {}
459
+ const preModel = model || entry.model || null
460
+ const preVendor = workerVendor(id, preModel, catalog)
461
+ if (writerVendor && preVendor === writerVendor) continue
462
+ crossCandidates.push({ id, index, entry })
463
+ }
464
+ if (!crossCandidates.length) {
465
+ throw new Error('No cross-vendor reviewer available for ' + p.name + ' (writer: ' + p.provider + (writerVendor ? '/' + writerVendor : '') + '; allowed: ' + (allow.join(', ') || 'none') + '). Allow a worker from another vendor (e.g. broco allow <worker>) or pass --by <worker>.')
466
+ }
467
+ const probed = await Promise.all(crossCandidates.map(async c => {
468
+ if (c.id.startsWith('custom:')) {
469
+ const tpl = c.entry.template
470
+ const inst = Boolean(tpl && executable(tpl.command))
471
+ return {
472
+ ...c,
473
+ detected: {
474
+ installed: inst,
475
+ capability: 'degraded',
476
+ loginStatus: inst ? 'ready' : 'not-installed',
477
+ models: (c.entry.models ?? []).map(mid => ({ id: mid })),
478
+ defaultModel: c.entry.model ?? null,
479
+ quota: null
480
+ }
481
+ }
482
+ }
483
+ const detected = await this.detectWorker(c.id, settings.repoPath)
484
+ return { ...c, detected }
485
+ }))
486
+ const codexQuotaShared = probed.find(x => x.id === 'codex')?.detected?.quota ?? null
487
+ const ready = []
488
+ const unavailable = []
489
+ for (const item of probed) {
490
+ const d = item.detected
491
+ const effectiveModel = model || item.entry.model || d?.defaultModel || null
492
+ const vendor = workerVendor(item.id, effectiveModel, catalog)
493
+ if (writerVendor && vendor === writerVendor) {
494
+ unavailable.push(item.id + ': same vendor (' + vendor + ')')
495
+ continue
496
+ }
497
+ if (!d?.installed || d.loginStatus === 'not-installed') {
498
+ unavailable.push(item.id + ': not-installed')
499
+ continue
500
+ }
501
+ if (!['ready', 'not-required'].includes(d.loginStatus)) {
502
+ unavailable.push(item.id + ': ' + (d.loginStatus || 'unknown'))
503
+ continue
504
+ }
505
+ const visibleModels = (d.models ?? []).filter(m => !hiddenModel(m.id, item.entry.hiddenModels))
506
+ if (!item.id.startsWith('custom:') && (d.models ?? []).length > 0 && visibleModels.length === 0) {
507
+ unavailable.push(item.id + ': all models hidden')
508
+ continue
509
+ }
510
+ const quota = d.quota ?? (item.id === 'pi:openai-codex' ? codexQuotaShared : null)
511
+ const cooldown = observedCooldown(this.store, item.id)
512
+ const avoid = tight(quota) || Boolean(cooldown)
513
+ const plentiful = !avoid && Boolean(quota?.plentiful)
514
+ const wins = Array.isArray(quota?.windows) ? quota.windows.filter(w => Number.isFinite(w.usedPercent)) : []
515
+ const maxUsed = wins.length ? Math.max(...wins.map(w => w.usedPercent)) : 50
516
+ const modelMatch = Boolean(model && visibleModels.some(m => m.id === model || (matchModel(m.id, catalog)?.id && matchModel(m.id, catalog)?.id === matchModel(model, catalog)?.id)))
517
+ ready.push({
518
+ id: item.id,
519
+ index: item.index,
520
+ modelMatch,
521
+ avoid,
522
+ plentiful,
523
+ full: d.capability !== 'degraded',
524
+ maxUsed
525
+ })
526
+ }
527
+ if (!ready.length) {
528
+ throw new Error('No ready cross-vendor reviewer available for ' + p.name + ' (writer: ' + p.provider + (writerVendor ? '/' + writerVendor : '') + '; allowed: ' + allow.join(', ') + '; unavailable: ' + unavailable.join(', ') + '). Sign in to another vendor CLI or specify --by <worker>.')
529
+ }
530
+ ready.sort((a, b) =>
531
+ Number(b.modelMatch) - Number(a.modelMatch) ||
532
+ Number(a.avoid) - Number(b.avoid) ||
533
+ Number(b.plentiful) - Number(a.plentiful) ||
534
+ Number(b.full) - Number(a.full) ||
535
+ a.maxUsed - b.maxUsed ||
536
+ a.index - b.index
537
+ )
538
+ return ready[0].id
539
+ }
540
+
541
+ async review({ name, by, model, effort, env }) {
542
+ const explicitBy = typeof by === 'string' ? by.trim() : by
543
+ if (explicitBy !== undefined && explicitBy !== null && explicitBy !== '') {
544
+ if (!supportedWorker(explicitBy)) throw new Error('Choose --by from broco roster')
545
+ }
546
+ const p = this.store.byName(name)
547
+ if (!p || !['review', 'done'].includes(this.store.ticket(p.id).status) || p.status !== 'idle') throw new Error('Review needs a completed writer turn')
548
+ const settings = this.workerSettings()
549
+ const catalog = cachedCatalog()
550
+ let reviewer = explicitBy
551
+ if (reviewer !== undefined && reviewer !== null && reviewer !== '') {
552
+ if (reviewer === p.provider) throw new Error('Choose a different worker for review')
553
+ const writerVendor = workerVendor(p.provider, p.model, catalog)
554
+ const reviewerEntry = settings.entries?.[reviewer] ?? {}
555
+ const reviewerVendor = workerVendor(reviewer, model || reviewerEntry.model || null, catalog)
556
+ if (writerVendor && reviewerVendor === writerVendor) {
557
+ throw new Error('Choose a different worker for review (same vendor: ' + writerVendor + ')')
558
+ }
559
+ } else {
560
+ reviewer = await this.pickReviewWorker(p, { model, settings, catalog })
561
+ }
562
+ const m = this.store.meta(p.id)
563
+ const files = JSON.parse(m?.files ?? 'null')
564
+ const summary = files === null ? 'Unavailable' : files.map(f => f.status + ' ' + JSON.stringify(f.path)).join('\n') || 'No changes'
565
+ const inputs = this.store.stmt("SELECT content FROM messages WHERE cid=? AND turn=? AND kind IN ('prompt','next','steer') AND error IS NULL ORDER BY number").all(p.id, p.turn)
566
+ const text = ['Review the writer’s work. Inspect the changes in this directory; do not edit files. Report findings and test gaps.',
567
+ 'Writer: ' + name + ', turn ' + p.turn, 'Base commit: ' + (JSON.parse(m?.baseline ?? 'null')?.head ?? 'unavailable'),
568
+ 'Writer instructions for this turn:', ...inputs.map(i => i.content),
569
+ 'File codes describe added, modified or deleted paths since the ticket began; A includes untracked files and does not imply staging.', 'Changed files:', summary, 'Writer final reply:', this.store.reply(p.id, p.turn) ?? '(no reply)'].join('\n')
570
+ const child = name + '-review-' + randomUUID().slice(0, 8)
571
+ return this.say({ name: child, text, worker: reviewer, model, effort, env, title: 'Review: ' + name + ' #' + p.turn,
572
+ defaultCwd: this.workingDirectory(p, m), cwd: m?.cwd ?? undefined }, { parent: p, meta: m })
573
+ }
574
+
575
+ async retry(name, { model, effort, worker, env } = {}) {
576
+ const c = this.store.byName(name)
577
+ if (!c) throw new Error('Unknown conversation: ' + name)
578
+ if (c.turn < 1) throw new Error('Conversation has no turns to retry: ' + name)
579
+ const lastTurn = this.store.stmt('SELECT * FROM turns WHERE cid=? AND turn=?').get(c.id, c.turn)
580
+ if (['running', 'queued'].includes(c.status) || !['error', 'stopped'].includes(lastTurn?.status)) {
581
+ throw new Error('Retry requires a failed or stopped turn: ' + name)
582
+ }
583
+ const promptRows = this.store.stmt("SELECT content FROM messages WHERE cid=? AND turn=? AND kind IN ('prompt','next') ORDER BY number").all(c.id, c.turn)
584
+ const text = promptRows.map(r => r.content).join('\n\n')
585
+ if (!text.trim()) throw new Error('No stored prompt to retry for ' + name)
586
+ const savedExec = lastTurn?.execution ? JSON.parse(lastTurn.execution) : null
587
+ const attachmentPaths = (savedExec?.attachments ?? []).map(f => f.path)
588
+ if (worker !== undefined && worker !== c.provider) {
589
+ if (c.native_id) throw new Error('This name is bound to ' + c.provider + '; use --from ' + name + ' with a new name to switch workers')
590
+ const settings = this.workerSettings()
591
+ if (!supportedWorker(worker) || !settings.allow.includes(worker)) throw new Error('Worker not allowed in this project: ' + worker)
592
+ const previous = this.workers.get(c.id)
593
+ if (previous) await this.release(c, previous)
594
+ const nextEntry = settings.entries?.[worker] ?? {}
595
+ const nextModel = model ?? nextEntry.model ?? worker
596
+ const nextEffort = effort !== undefined ? (effort || null) : (nextEntry.effort ?? null)
597
+ this.store.stmt('UPDATE conversations SET provider=?,model=?,thinking=? WHERE id=?').run(worker, nextModel, nextEffort, c.id)
598
+ }
599
+ const retriedTurn = c.turn
600
+ const res = await this.say({
601
+ name,
602
+ text,
603
+ attachments: attachmentPaths.length ? attachmentPaths : undefined,
604
+ worker,
605
+ model,
606
+ effort,
607
+ defaultCwd: this.workingDirectory(c),
608
+ env,
609
+ _retryingInitialTurn: retriedTurn === 1 && !c.native_id
610
+ })
611
+ if (res.delivery) {
612
+ return { ...res, delivery: res.delivery.then(r => ({ ...r, retriedTurn })) }
613
+ }
614
+ return { ...res, retriedTurn }
615
+ }
616
+
617
+ async say(input, review) {
618
+ if (input.from !== undefined) {
619
+ if (this.store.byName(input.name)) throw new Error('--from requires a new conversation name')
620
+ input = { ...input, text: this.store.handoff(input.from, input.text) }
621
+ }
622
+ this.syncConcurrency()
623
+ const catalog = cachedCatalog()
624
+ const settings = this.workerSettings(), current = this.store.byName(input.name)
625
+ const contextWarning = current ? this.store.contextWarning(current.id, current.turn) : null
626
+ const worker = input.worker ?? current?.provider ?? settings.worker
627
+ const entry = settings.entries?.[worker] ?? {}
628
+ const busy = current && ['running', 'queued'].includes(current.status)
629
+ const unboundPriorSession = Boolean(current && !busy && current.turn >= 1 && !input.newTask && !current.native_id && !input._retryingInitialTurn)
630
+ const agyExplicitSuffix = !busy && worker === 'agy' && typeof input.model === 'string'
631
+ ? /-(off|none|minimal|low|medium|high|xhigh|extra-high|max|ultra)$/.exec(input.model)?.[1] ?? null
632
+ : null
633
+ let model = input.model ?? (busy ? current.model : entry.model || current?.model || worker)
634
+ let effort = input.effort !== undefined ? (input.effort || null) : (agyExplicitSuffix ?? (busy ? current.thinking : entry.effort || current?.thinking || null))
635
+ const requested = describeAttachments(input.attachments)
636
+ let detect = null
637
+ if (supportedWorker(worker) && settings.allow.includes(worker)) {
638
+ detect = !busy && model === worker || requested.length ? await detectCli(worker, settings.repoPath) : null
639
+ if (model === worker && detect?.defaultModel) { model = detect.defaultModel; effort ??= detect.defaultEffort }
640
+ if (!busy && worker === 'agy') model = normalizeAgyModel(model, effort, detect?.models?.map(m => m.id) ?? [])
641
+ let reason
642
+ if (hiddenModel(model, entry.hiddenModels)) reason = 'Selected model is hidden; choose a visible model from roster'
643
+ else if (entry.hiddenModels?.length && model === worker) reason = 'Cannot verify the CLI default against hidden models; choose an explicit visible model'
644
+ if (requested.length) {
645
+ const metadata = detect?.models.find(m => m.id === model) ?? { id: model }
646
+ const caps = modelCapabilities(worker, metadata, matchModel(model, catalog))
647
+ const allDetectSupport = model === worker && detect?.models?.length > 0 && requested.every(file =>
648
+ detect.models.every(m => modelCapabilities(worker, m, matchModel(m.id, catalog)).input[file.kind] === true)
649
+ )
650
+ if (!allDetectSupport && requested.some(file => caps.input[file.kind] !== true)) reason = 'Selected CLI + model cannot accept this attachment (unsupported or unknown capability)'
651
+ }
652
+ if (reason) {
653
+ if (busy) return { ...this.store.follow(current, input.text, 'rejected', reason), contextWarning }
654
+ throw new Error(reason)
655
+ }
656
+ } else if (!busy && worker === 'agy') {
657
+ model = normalizeAgyModel(model, effort)
658
+ }
659
+ const catalogEntry = matchModel(model, catalog)
660
+ const detectedContext = detect?.models?.find(m => m.id === model)?.contextWindow
661
+ const contextTokens = (Number.isSafeInteger(detectedContext) && detectedContext > 0 ? detectedContext : null)
662
+ ?? (Number.isSafeInteger(catalogEntry?.modalities?.context_tokens) && catalogEntry.modalities.context_tokens > 0 ? catalogEntry.modalities.context_tokens : null)
663
+ ?? 250000
664
+ const context = { worker, model, effort, note: entry.note ?? '', rules: [...(settings.rules ?? []), ...(entry.rules ?? [])], capability: worker.startsWith('custom:') ? 'degraded' : 'full' }
665
+ const execution = {
666
+ model,
667
+ thinking: effort,
668
+ template: entry.template ?? null,
669
+ attachments: [],
670
+ contextTokens,
671
+ note: context.note,
672
+ rules: context.rules,
673
+ capability: context.capability
674
+ }
675
+ const annotate = r => {
676
+ const c = this.store.byName(input.name) ?? this.store.byName(r.name)
677
+ const queue = c && (r.kind === 'queued' || c.status === 'queued') ? this.store.queueStatus(c.id) : null
678
+ const reminders = [...context.rules.map(rule => 'Rule reminder: ' + rule), ...(unboundPriorSession ? [SESSION_UNBOUND_WARNING] : [])]
679
+ const receipt = {
680
+ ...r,
681
+ ...context,
682
+ contextWarning,
683
+ queue,
684
+ ...(unboundPriorSession ? { previousSessionBound: false, sessionWarning: SESSION_UNBOUND_WARNING } : {}),
685
+ cwd: c ? this.workingDirectory(c) : null,
686
+ reminders
687
+ }
688
+ if (c && r.outcome !== 'rejected') this.store.transaction(() => {
689
+ this.store.event(c.id, r.turn, 'bro.dispatch', { note: context.note, rules: context.rules, capability: context.capability }, 'Worker: ' + worker + (effort ? ' · ' + effort : ''))
690
+ if (r.outcome !== 'injected') {
691
+ const row = this.store.stmt('SELECT execution FROM turns WHERE cid=? AND turn=?').get(c.id, r.turn)
692
+ const saved = row?.execution ? JSON.parse(row.execution) : execution
693
+ saved.attachments = [...new Map([...(saved.attachments ?? []), ...(execution.attachments ?? [])].map(f => [f.path, f])).values()]
694
+ if (saved.contextTokens === undefined) saved.contextTokens = contextTokens
695
+ saved.note = context.note
696
+ saved.rules = context.rules
697
+ saved.capability = context.capability
698
+ this.store.stmt('UPDATE turns SET execution=? WHERE cid=? AND turn=?').run(JSON.stringify(saved), c.id, r.turn)
699
+ }
700
+ this.store.changed(c.id)
701
+ })
702
+ return receipt
703
+ }
704
+ const result = await this.acceptSay({ ...input, worker, model, effort, execution, requestedAttachments: requested }, review)
705
+ return result.delivery ? { ...result, delivery: result.delivery.then(annotate) } : annotate(result)
706
+ }
707
+
708
+ async acceptSay({ name, text, model, effort, execution, requestedAttachments, worker, defaultCwd, cwd, title, env, worktree, from, newTask }, review) {
709
+ if (typeof name !== 'string' || !name.trim() || /[\x00-\x1f\x7f]/.test(name)) throw new Error('Invalid conversation name')
710
+ let c = this.store.byName(name)
711
+ if (from !== undefined && c) throw new Error('--from requires a new conversation name')
712
+ const settings = this.workerSettings()
713
+ const busy = c && ['running', 'queued'].includes(currentStatus(c))
714
+ worker ??= c?.provider ?? settings.worker
715
+ model ??= c?.model ?? worker
716
+ let invalid
717
+ if (typeof text !== 'string' || !text.trim()) invalid = 'Message is empty'
718
+ else if (title !== undefined && (typeof title !== 'string' || !title.trim())) invalid = 'Title is empty'
719
+ else if (!supportedWorker(worker) || !settings.allow.includes(worker)) invalid = 'Worker not allowed in this project: ' + worker
720
+ else if (c && worker !== c.provider) invalid = 'This name is bound to ' + c.provider
721
+ else if (typeof model !== 'string' || !model || /[\x00-\x1f\x7f]/.test(model)) invalid = 'Invalid model'
722
+ else if (effort && (typeof effort !== 'string' || !/^[a-z0-9_-]{1,40}$/.test(effort))) invalid = 'Invalid effort'
723
+ else if (worker === 'codex' && model.includes('/')) invalid = 'Use --worker pi:<provider> for a provider/model ID'
724
+ else if (newTask && c && (busy || !this.store.currentTask(c.id)?.outcome)) invalid = 'Record the current task with done before --new-task'
725
+ else if (busy && (c.model !== model || c.thinking !== effort)) invalid = 'Cannot change model or effort during an active turn'
726
+ else if (worker === 'cursor-agent' && effort && model === worker) invalid = 'Choose an explicit Cursor model when selecting effort'
727
+ else if (worker.startsWith('custom:') && !execution.template) invalid = 'Configure and test this custom CLI first'
728
+ else if (worker.startsWith('custom:') && effort && !execution.template.effortArgs.length) invalid = 'Custom CLI template has no effort argument'
729
+ else if (worker.startsWith('custom:') && model !== worker && !execution.template.modelArgs.length) invalid = 'Custom CLI template has no model argument'
730
+ else if (cwd !== undefined && (worktree || c && this.store.meta(c.id)?.worktree)) invalid = '--cwd cannot be combined with --worktree or an existing worktree session'
731
+ else if (c && worktree && !this.store.meta(c.id)?.worktree) invalid = 'Choose --worktree when creating a new ticket'
732
+ if (!invalid && cwd !== undefined) {
733
+ try {
734
+ cwd = directory(cwd, '--cwd')
735
+ if (c && cwd !== directory(this.workingDirectory(c))) invalid = 'This name is bound to working directory ' + this.workingDirectory(c) + '; choose a new name to use --cwd with another directory'
736
+ } catch (err) { invalid = err.message }
737
+ }
738
+ if (!invalid && worker.startsWith('pi:') && model !== worker) {
739
+ try { if (providerOf(model) !== worker.slice(3)) invalid = 'Choose --model from the allowed pi provider' }
740
+ catch (err) { invalid = err.message }
741
+ }
742
+ if (invalid) {
743
+ if (busy) return this.store.follow(c, typeof text === 'string' ? text : '', 'rejected', invalid)
744
+ throw new Error(invalid)
745
+ }
746
+ if (requestedAttachments?.length) {
747
+ execution.attachments = snapshotAttachments(requestedAttachments, this.store.directory)
748
+ }
749
+ if (c && !busy && (c.model !== model || c.thinking !== effort)) {
750
+ const previous = this.workers.get(c.id)
751
+ if (previous) await this.release(c, previous)
752
+ this.store.stmt('UPDATE conversations SET model=?,thinking=? WHERE id=?').run(model, effort, c.id)
753
+ c = this.store.byName(name)
754
+ }
755
+ let queuedReason
756
+ if (busy) {
757
+ const pi = this.workers.get(c.id)
758
+ if (!execution.attachments.length && pi?.active && !pi.stopping && !pi.settling) return this.steerPi(c, pi, text, env)
759
+ const target = c.turn + 1
760
+ const active = this.native.get(c.id)
761
+ const steer = !execution.attachments.length && active && await active.ready.promise
762
+ if (steer) {
763
+ try {
764
+ if (await steer(text)) return this.store.follow(c, text, 'injected', 'Codex acknowledged turn/steer')
765
+ } catch (err) { return this.store.follow(c, text, 'rejected', 'Delivery unconfirmed: ' + err.message) }
766
+ }
767
+ queuedReason = steer ? 'Current turn declined steer' : 'Current turn does not accept steer'
768
+ c = this.store.byName(name)
769
+ if (['running', 'queued'].includes(c.status)) {
770
+ const turn = c.turn === target && c.status === 'queued' ? target : c.turn + 1
771
+ const key = c.id + ':' + turn
772
+ if (!this.environments.has(key)) this.environments.set(key, env)
773
+ return this.store.follow(c, text, 'queued', queuedReason, turn)
774
+ }
775
+ if (c.status !== 'idle') return this.store.follow(c, text, 'rejected', 'Previous turn did not complete')
776
+ }
777
+ const receipt = this.store.transaction(() => {
778
+ if (!c) {
779
+ const tree = worktree ? createTree(defaultCwd, this.store.directory, name) : review?.meta
780
+ const workingCwd = directory(worktree ? tree.cwd : cwd ?? defaultCwd)
781
+ c = this.store.create(name, workingCwd, model, title, effort, worker)
782
+ this.store.stmt('INSERT INTO collaboration(cid,parent,parent_turn,worktree,branch,cwd) VALUES (?,?,?,?,?,?)').run(
783
+ c.id, review?.parent.id ?? null, review?.parent.turn ?? null, tree?.worktree ?? null, tree?.branch ?? null, cwd ?? null)
784
+ if (review) this.store.changed(review.parent.id)
785
+ }
786
+ const r = this.store.accept(c, text, title, newTask)
787
+ this.store.stmt('UPDATE turns SET execution=? WHERE cid=? AND turn=?').run(JSON.stringify(execution), c.id, r.turn)
788
+ if (queuedReason) {
789
+ Object.assign(r, { outcome: 'queued', reason: queuedReason })
790
+ this.store.event(c.id, r.turn, 'bro.interjection', r, 'queued: ' + queuedReason)
791
+ }
792
+ return r
793
+ })
794
+ c = this.store.byName(name)
795
+ this.environments.set(c.id + ':' + c.turn, env)
796
+ if (!this.slots.reserve(this, c)) {
797
+ const queue = this.store.queueStatus(c.id)
798
+ if (queue) this.store.state(c.id, 'queued', formatQueuedActivity(queue))
799
+ return { ...receipt, kind: 'queued', queue }
800
+ }
801
+ try {
802
+ await this.dispatch(c)
803
+ } catch (err) {
804
+ this.slots?.release?.(c.id, c.turn)
805
+ throw err
806
+ }
807
+ return receipt
808
+ }
809
+
810
+ dispatch(c) {
811
+ const key = c.id + ':' + c.turn
812
+ const env = this.environments.get(key)
813
+ this.environments.delete(key)
814
+ return withModelEnvironment(env, () => this.startTurn(c)).catch(err => {
815
+ try {
816
+ this.store.finish(c.id, c.turn, 'error', err.message)
817
+ } finally {
818
+ this.slots?.release?.(c.id, c.turn)
819
+ }
820
+ throw err
821
+ })
822
+ }
823
+
824
+ async startTurn(c) {
825
+ this.clearIdleTimer(c.id)
826
+ let messages = []
827
+ try {
828
+ const snapshot = this.store.stmt('SELECT execution FROM turns WHERE cid=? AND turn=?').get(c.id, c.turn)?.execution
829
+ if (snapshot) c = { ...c, ...JSON.parse(snapshot) }
830
+ messages = this.store.stmt("SELECT number,content FROM messages WHERE cid=? AND turn=? AND kind IN ('prompt','next') ORDER BY number").all(c.id, c.turn)
831
+ if (!supportedWorker(c.provider)) throw new Error('Unsupported worker: ' + c.provider)
832
+ if (!this.workerSettings().allow.includes(c.provider)) throw new Error('Worker no longer allowed: ' + c.provider)
833
+ if (hiddenModel(c.model, this.workerSettings().entries?.[c.provider]?.hiddenModels)) throw new Error('Selected model is now hidden')
834
+ const m = this.store.meta(c.id)
835
+ c.cwd = directory(this.workingDirectory(c, m))
836
+ if (m?.worktree) verifyTree(c.cwd, m.branch)
837
+ if (!m?.baseline) {
838
+ const initial = baseline(c.cwd)
839
+ this.store.stmt('INSERT INTO collaboration(cid,baseline,branch) VALUES (?,?,?) ON CONFLICT(cid) DO UPDATE SET baseline=excluded.baseline,branch=coalesce(collaboration.branch,excluded.branch)').run(c.id, JSON.stringify(initial), initial?.branch ?? null)
840
+ }
841
+ this.store.claim(c)
842
+ if (!c.provider.startsWith('pi:')) {
843
+ const controller = new AbortController()
844
+ this.store.working(c)
845
+ const ready = Promise.withResolvers()
846
+ const task = this.runNative(c, messages.map(m => m.content).join('\n\n'), controller, ready, m)
847
+ this.native.set(c.id, { controller, task, ready })
848
+ return
849
+ }
850
+ const w = await this.worker(c)
851
+ Object.assign(w, { turn: c.turn, active: true, stopping: false, activity: '', sawAssistant: false, replyId: null, failure: '',
852
+ initialSeen: false, settling: false, steers: [], settled: Promise.withResolvers() })
853
+ this.store.working(c)
854
+ const ack = await w.command('prompt', { message: messages.map(m => m.content).join('\n\n'), ...(c.attachments?.length ? { images: piImages(c.attachments) } : {}) })
855
+ if (ack?.disposition === 'handled' && w.active) {
856
+ w.active = false
857
+ this.store.finish(c.id, w.turn, 'done', 'Input handled by pi')
858
+ }
859
+ } catch (err) {
860
+ try {
861
+ this.store.rejectDeferred(c.id, c.turn, err.message)
862
+ for (const m of messages) this.rejectMessage(c.id, m.number, err.message)
863
+ this.store.finish(c.id, c.turn, 'error', err.message)
864
+ } finally {
865
+ this.slots?.release?.(c.id, c.turn)
866
+ }
867
+ const failed = this.workers.get(c.id)
868
+ if (failed) failed.active = false
869
+ await this.release(c, failed)
870
+ throw err
871
+ }
872
+ }
873
+
874
+ async runNative(c, text, controller, ready, meta) {
875
+ const s = this.store
876
+ let reply, failure, problem = null, bound = c.native_id
877
+ try {
878
+ reply = await (c.provider === 'codex' ? nativeTurn : streamTurn)({
879
+ ...c, text, session: c.native_id, marker: s.marker(c.id), signal: controller.signal,
880
+ ready: ready.resolve, worktree: meta?.worktree, review: !!meta?.parent,
881
+ owner: pid => s.owner(c.id, pid),
882
+ bind: (id, transport) => {
883
+ if (typeof id !== 'string' || !id || (bound && bound !== id)) throw new Error('Native worker returned a different session')
884
+ bound = id
885
+ s.stmt('UPDATE conversations SET native_id=?,transport=? WHERE id=?').run(id, transport, c.id)
886
+ },
887
+ event: (kind, payload, detail) => s.transaction(() => {
888
+ if (kind === 'tool.completed' || (kind === 'item/completed' && ['fileChange', 'commandExecution'].includes(payload.type))) this.refreshFiles(c, true)
889
+ s.event(c.id, c.turn, kind, payload, detail)
890
+ if (detail) s.state(c.id, 'running', detail)
891
+ })
892
+ })
893
+ if (!bound) throw new Error('Missing native session ID')
894
+ } catch (err) { failure = err.message; problem = err.problem ?? null }
895
+ finally {
896
+ ready.resolve(null)
897
+ await reap(s.marker(c.id)).catch(() => {})
898
+ s.owner(c.id, null)
899
+ this.native.delete(c.id)
900
+ }
901
+ const stopped = controller.signal.aborted
902
+ s.transaction(() => s.finish(c.id, c.turn, stopped ? 'stopped' : failure ? 'error' : 'done',
903
+ stopped ? 'Stopped by manager' : failure || 'Waiting for manager', !stopped && !failure ? s.assistant(c.id, c.turn, reply) : null, stopped ? null : problem))
904
+ }
905
+
906
+ async stop(name) {
907
+ const c = this.store.byName(name)
908
+ if (!c) throw new Error('Unknown conversation: ' + name)
909
+ this.clearIdleTimer(c.id)
910
+ this.clearEnvFor(c.id)
911
+ try {
912
+ if (c.status === 'queued') this.store.rejectDeferred(c.id, c.turn, 'Stopped before delivery')
913
+ const native = this.native.get(c.id)
914
+ if (native) {
915
+ const marked = owned(this.store.marker(c.id), [], c.worker_pid)
916
+ native.controller.abort()
917
+ await reap(this.store.marker(c.id), marked)
918
+ await native.task
919
+ return { name, status: 'stopped', forced: false }
920
+ }
921
+ const w = this.workers.get(c.id)
922
+ const marker = this.store.marker(c.id)
923
+ if (!w && c.worker_pid === null && !existsSync(marker)) {
924
+ const detail = 'Stopped; processes verified'
925
+ if (!this.store.finish(c.id, c.turn, 'stopped', detail)) this.store.state(c.id, 'stopped', detail)
926
+ this.store.event(c.id, c.turn, 'bro.stop', { forced: false }, detail)
927
+ return { name, status: 'stopped', forced: false }
928
+ }
929
+ try {
930
+ const forced = await this.release(c, w)
931
+ const detail = forced ? 'Stopped by forced cleanup; processes verified' : 'Stopped; processes verified'
932
+ if (!this.store.finish(c.id, c.turn, 'stopped', detail)) this.store.state(c.id, 'stopped', detail)
933
+ this.store.event(c.id, c.turn, 'bro.stop', { forced }, detail)
934
+ return { name, status: 'stopped', forced }
935
+ } catch (err) {
936
+ if (!this.store.finish(c.id, c.turn, 'error', err.message)) this.store.state(c.id, 'error', err.message)
937
+ throw err
938
+ }
939
+ } finally {
940
+ this.slots?.release?.(c.id)
941
+ }
942
+ }
943
+ }
944
+
945
+ function currentStatus(c) {
946
+ return c?.status ?? ''
947
+ }