@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.
- package/CHANGELOG.md +209 -0
- package/LICENSE +202 -0
- package/README.md +188 -2
- package/README.zh-CN.md +187 -0
- package/assets/broco-board-icon-128.png +0 -0
- package/assets/broco-favicon-192.png +0 -0
- package/assets/broco-favicon-32.png +0 -0
- package/assets/broco-favicon-64.png +0 -0
- package/assets/broco-foreman-256.png +0 -0
- package/assets/broco-hero-1024.png +0 -0
- package/assets/broco-icon-512.png +0 -0
- package/assets/broco-readme-logo-dark.png +0 -0
- package/assets/broco-readme-logo-light.png +0 -0
- package/assets/broco-social-preview-1280x640.png +0 -0
- package/assets/favicon.ico +0 -0
- package/bin/broco +1077 -0
- package/bundle/board/assets/index-Bue0HpFh.css +1 -0
- package/bundle/board/assets/index-DTqMQtD9.js +16 -0
- package/bundle/board/broco-board-icon-128.png +0 -0
- package/bundle/board/broco-favicon-32.png +0 -0
- package/bundle/board/broco-favicon-64.png +0 -0
- package/bundle/board/broco-foreman-256.png +0 -0
- package/bundle/board/favicon.ico +0 -0
- package/bundle/board/fonts/instrument-sans-latin.woff2 +0 -0
- package/bundle/board/fonts/jetbrains-mono-latin.woff2 +0 -0
- package/bundle/board/index.html +18 -0
- package/lib/attachments.mjs +104 -0
- package/lib/claude-md.mjs +132 -0
- package/lib/cli-args.mjs +292 -0
- package/lib/cli-process.mjs +75 -0
- package/lib/client.mjs +198 -0
- package/lib/credential-proxy.mjs +165 -0
- package/lib/credential-source.mjs +23 -0
- package/lib/crew.mjs +947 -0
- package/lib/detect.mjs +279 -0
- package/lib/directories.mjs +32 -0
- package/lib/map.mjs +336 -0
- package/lib/model-catalog.json +864 -0
- package/lib/model-catalog.mjs +138 -0
- package/lib/model-env.mjs +11 -0
- package/lib/native.mjs +228 -0
- package/lib/paths.mjs +63 -0
- package/lib/pi-profile.mjs +29 -0
- package/lib/pi-secrets.mjs +48 -0
- package/lib/pi.mjs +232 -0
- package/lib/platform/index.mjs +13 -0
- package/lib/platform/launchd.mjs +138 -0
- package/lib/platform/linux.mjs +168 -0
- package/lib/platform/macos.mjs +29 -0
- package/lib/platform/processes.mjs +102 -0
- package/lib/problems.mjs +50 -0
- package/lib/projects.mjs +530 -0
- package/lib/quota.mjs +132 -0
- package/lib/roster-output.mjs +136 -0
- package/lib/roster.mjs +913 -0
- package/lib/runner.mjs +403 -0
- package/lib/settings-audit.mjs +104 -0
- package/lib/setup.mjs +416 -0
- package/lib/slots.mjs +177 -0
- package/lib/stats.mjs +92 -0
- package/lib/store.mjs +737 -0
- package/lib/stream-workers.mjs +464 -0
- package/lib/templates.mjs +173 -0
- package/lib/time.mjs +25 -0
- package/lib/web.mjs +260 -0
- package/lib/worker-policy.mjs +17 -0
- package/lib/worktree.mjs +269 -0
- package/package.json +50 -4
- package/scripts/package-board.mjs +53 -0
- package/skills/broco/SKILL.md +59 -0
package/lib/store.mjs
ADDED
|
@@ -0,0 +1,737 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto'
|
|
2
|
+
import { statSync } from 'node:fs'
|
|
3
|
+
import { dirname, join } from 'node:path'
|
|
4
|
+
import { DatabaseSync } from 'node:sqlite'
|
|
5
|
+
import { fileURLToPath } from 'node:url'
|
|
6
|
+
import { classify, infra } from './problems.mjs'
|
|
7
|
+
import { loadCatalog, matchModel } from './model-catalog.mjs'
|
|
8
|
+
import { home } from './paths.mjs'
|
|
9
|
+
import { formatDateTime } from './time.mjs'
|
|
10
|
+
|
|
11
|
+
export const outcomes = ['pass', 'rework', 'fail', 'blocked']
|
|
12
|
+
|
|
13
|
+
export const NO_COMPLETED_REPLY = '(It never completed a reply.)'
|
|
14
|
+
export function handoffPrompt(name, title, cwd, reply, text) {
|
|
15
|
+
return ['You are taking over from an earlier session named ' + name + ', which has stopped. Its tool output and full history are not carried over: you get only its title, its working directory and its last completed reply, followed by the manager\'s request for you. Treat that reply as a summary, and check the files before relying on it.',
|
|
16
|
+
'Earlier session: ' + name + '\nTitle: ' + title + '\nWorking directory: ' + cwd,
|
|
17
|
+
'Its last completed reply:\n' + (reply ?? NO_COMPLETED_REPLY),
|
|
18
|
+
'The manager\'s request for you:\n' + text].join('\n\n')
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export function formatQueuedActivity(queue) {
|
|
22
|
+
if (!queue) return 'Queued'
|
|
23
|
+
const active = queue.activeNames?.length ? '; active: ' + queue.activeNames.join(', ') : ''
|
|
24
|
+
return 'Queued (#' + queue.position + ' of ' + queue.totalQueued + ', limit ' + queue.limit + active + ')'
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const TOOL_EVENT_KINDS = new Set([
|
|
28
|
+
'tool.started',
|
|
29
|
+
'tool.completed',
|
|
30
|
+
'tool_execution_start',
|
|
31
|
+
'tool_execution_end',
|
|
32
|
+
'item/started',
|
|
33
|
+
'item/completed',
|
|
34
|
+
'item.started',
|
|
35
|
+
'item.completed'
|
|
36
|
+
])
|
|
37
|
+
|
|
38
|
+
const builtinCatalogPath = fileURLToPath(new URL('./model-catalog.json', import.meta.url))
|
|
39
|
+
let catalogCache = null
|
|
40
|
+
let catalogCacheKey = ''
|
|
41
|
+
|
|
42
|
+
export function cachedCatalog() {
|
|
43
|
+
const userPath = join(home, 'models.json')
|
|
44
|
+
const bStat = statSync(builtinCatalogPath, { throwIfNoEntry: false })
|
|
45
|
+
const uStat = statSync(userPath, { throwIfNoEntry: false })
|
|
46
|
+
const key = (bStat?.mtimeMs ?? 0) + ':' + (uStat?.mtimeMs ?? -1) + ':' + userPath
|
|
47
|
+
if (!catalogCache || catalogCacheKey !== key) {
|
|
48
|
+
catalogCache = loadCatalog(userPath)
|
|
49
|
+
catalogCacheKey = key
|
|
50
|
+
}
|
|
51
|
+
return catalogCache
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function parseUsageRaw(rawText) {
|
|
55
|
+
const { cachedInputTokens = null, inputTokens = null } = rawText ? JSON.parse(rawText) : {}
|
|
56
|
+
return {
|
|
57
|
+
cachedInputTokens,
|
|
58
|
+
inputTokens,
|
|
59
|
+
cacheRatio: inputTokens > 0 && cachedInputTokens !== null && cachedInputTokens >= 0 && cachedInputTokens <= inputTokens
|
|
60
|
+
? cachedInputTokens / inputTokens
|
|
61
|
+
: null
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function computeQuotaSummary(rows) {
|
|
66
|
+
if (!rows || !rows.length) return null
|
|
67
|
+
const first = rows[0], last = rows.at(-1)
|
|
68
|
+
const spent = (last.windows ?? []).map(w => {
|
|
69
|
+
const before = (first.windows ?? []).find(b => b.minutes === w.minutes)
|
|
70
|
+
return before && before.resetsAt === w.resetsAt ? { minutes: w.minutes, percent: Math.max(0, w.usedPercent - before.usedPercent) } : null
|
|
71
|
+
}).filter(Boolean)
|
|
72
|
+
return { latest: last, spent }
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function buildContextWarning(c, usageTurn, usageRawText, execText, catalog) {
|
|
76
|
+
if (!c || !usageRawText) return null
|
|
77
|
+
const inputTokens = JSON.parse(usageRawText).inputTokens
|
|
78
|
+
if (!Number.isSafeInteger(inputTokens)) return null
|
|
79
|
+
const savedTokens = execText ? JSON.parse(execText)?.contextTokens : null
|
|
80
|
+
const catalogTokens = matchModel(c.model, catalog)?.modalities?.context_tokens
|
|
81
|
+
const contextTokens = (Number.isSafeInteger(savedTokens) && savedTokens > 0 ? savedTokens : null)
|
|
82
|
+
?? (Number.isSafeInteger(catalogTokens) && catalogTokens > 0 ? catalogTokens : null)
|
|
83
|
+
?? 250000
|
|
84
|
+
const threshold = Math.floor(contextTokens * 0.6)
|
|
85
|
+
if (inputTokens <= threshold) return null
|
|
86
|
+
if (['running', 'queued'].includes(c.status)) {
|
|
87
|
+
return {
|
|
88
|
+
inputTokens,
|
|
89
|
+
contextTokens,
|
|
90
|
+
threshold,
|
|
91
|
+
turn: usageTurn,
|
|
92
|
+
actionable: false,
|
|
93
|
+
message: '上下文已达阈值(运行中暂不切换)/ Context high (' + inputTokens + ' > ' + threshold + '): wait for current turn to finish before using --from ' + c.name + '.'
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return {
|
|
97
|
+
inputTokens,
|
|
98
|
+
contextTokens,
|
|
99
|
+
threshold,
|
|
100
|
+
turn: usageTurn,
|
|
101
|
+
actionable: true,
|
|
102
|
+
message: '该换新名字了 / Start a new name: inputTokens=' + inputTokens + ' > ' + threshold + '. Use broco say NEW_NAME "next task and project status files" --from ' + c.name + '.'
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export class Store {
|
|
107
|
+
constructor(readOnly, path) {
|
|
108
|
+
this.readOnly = Boolean(readOnly)
|
|
109
|
+
this.db = new DatabaseSync(path, { readOnly })
|
|
110
|
+
this.directory = dirname(path)
|
|
111
|
+
this.sessions = join(this.directory, 'sessions')
|
|
112
|
+
this.sql = new Map()
|
|
113
|
+
this.dirty = new Set()
|
|
114
|
+
this.db.exec('PRAGMA busy_timeout=5000; PRAGMA foreign_keys=ON')
|
|
115
|
+
if (readOnly) return
|
|
116
|
+
this.db.exec('PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL')
|
|
117
|
+
this.db.exec([
|
|
118
|
+
'CREATE TABLE IF NOT EXISTS conversations (id TEXT PRIMARY KEY, name TEXT NOT NULL UNIQUE, cwd TEXT NOT NULL, model TEXT NOT NULL, status TEXT NOT NULL, activity TEXT NOT NULL, turn INTEGER NOT NULL DEFAULT 0, worker_pid INTEGER, provider TEXT NOT NULL, native_id TEXT, transport TEXT)',
|
|
119
|
+
'CREATE TABLE IF NOT EXISTS turns (cid TEXT REFERENCES conversations, turn INTEGER, status TEXT NOT NULL, started INTEGER NOT NULL, finished INTEGER, error TEXT, PRIMARY KEY(cid,turn))',
|
|
120
|
+
'CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY, cid TEXT NOT NULL, turn INTEGER NOT NULL, number INTEGER, kind TEXT NOT NULL, content TEXT NOT NULL, error TEXT, UNIQUE(cid,number), FOREIGN KEY(cid,turn) REFERENCES turns)',
|
|
121
|
+
'CREATE TABLE IF NOT EXISTS events (id INTEGER PRIMARY KEY, cid TEXT REFERENCES conversations, turn INTEGER NOT NULL, at INTEGER NOT NULL, kind TEXT NOT NULL, raw TEXT NOT NULL, summary TEXT NOT NULL)',
|
|
122
|
+
'CREATE TABLE IF NOT EXISTS collaboration (cid TEXT PRIMARY KEY REFERENCES conversations, parent TEXT REFERENCES conversations, parent_turn INTEGER, worktree TEXT, branch TEXT, baseline TEXT, files TEXT)',
|
|
123
|
+
'CREATE INDEX IF NOT EXISTS reviews_by_parent ON collaboration(parent)',
|
|
124
|
+
'CREATE INDEX IF NOT EXISTS messages_by_turn ON messages(cid,turn,id)',
|
|
125
|
+
"CREATE INDEX IF NOT EXISTS interjections_by_ticket ON events(cid,id) WHERE kind='bro.interjection'",
|
|
126
|
+
"CREATE INDEX IF NOT EXISTS usage_by_turn ON events(cid,turn,id) WHERE kind='usage'",
|
|
127
|
+
'CREATE INDEX IF NOT EXISTS events_by_turn ON events(cid,turn,id)',
|
|
128
|
+
'CREATE INDEX IF NOT EXISTS events_by_cid ON events(cid,id)',
|
|
129
|
+
"CREATE INDEX IF NOT EXISTS events_timeline ON events(cid,id,turn,at,kind,summary) WHERE summary<>''",
|
|
130
|
+
"CREATE INDEX IF NOT EXISTS dispatch_by_turn ON events(cid,turn,id) WHERE kind='bro.dispatch'",
|
|
131
|
+
'CREATE INDEX IF NOT EXISTS conversations_by_status ON conversations(status)',
|
|
132
|
+
'CREATE TABLE IF NOT EXISTS tickets (cid TEXT PRIMARY KEY REFERENCES conversations, title TEXT NOT NULL, stage TEXT NOT NULL, flag TEXT, created INTEGER NOT NULL, updated INTEGER NOT NULL, started INTEGER)',
|
|
133
|
+
'CREATE TABLE IF NOT EXISTS runtime_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)',
|
|
134
|
+
'CREATE TABLE IF NOT EXISTS batches (prefix TEXT PRIMARY KEY, title TEXT NOT NULL, brief TEXT NOT NULL, worker TEXT, model TEXT, effort TEXT, cwd TEXT, created INTEGER NOT NULL, shards TEXT NOT NULL)',
|
|
135
|
+
"INSERT OR IGNORE INTO tickets(cid,title,stage,flag,created,updated,started) SELECT c.id,c.name,CASE WHEN c.turn=0 THEN 'queued' WHEN c.status='idle' THEN 'review' ELSE 'working' END, CASE WHEN c.status IN ('error','stopped') THEN c.status END, coalesce((SELECT min(started) FROM turns WHERE cid=c.id),0),coalesce(r.finished,r.started,0),r.started FROM conversations c LEFT JOIN turns r ON r.cid=c.id AND r.turn=c.turn"
|
|
136
|
+
].join(';'))
|
|
137
|
+
if (!this.db.prepare('PRAGMA table_info(conversations)').all().some(c => c.name === 'thinking')) this.db.exec('ALTER TABLE conversations ADD COLUMN thinking TEXT')
|
|
138
|
+
if (!this.db.prepare('PRAGMA table_info(collaboration)').all().some(c => c.name === 'cwd')) this.db.exec('ALTER TABLE collaboration ADD COLUMN cwd TEXT')
|
|
139
|
+
const turnColumns = this.db.prepare('PRAGMA table_info(turns)').all().map(c => c.name)
|
|
140
|
+
if (!turnColumns.includes('execution')) this.db.exec('ALTER TABLE turns ADD COLUMN execution TEXT')
|
|
141
|
+
if (!turnColumns.includes('problem')) this.db.exec('ALTER TABLE turns ADD COLUMN problem TEXT')
|
|
142
|
+
const fill = this.db.prepare('UPDATE turns SET problem=? WHERE cid=? AND turn=?')
|
|
143
|
+
const unclassified = this.db.prepare("SELECT cid,turn,error FROM turns WHERE status='error' AND problem IS NULL").all()
|
|
144
|
+
if (unclassified.length) this.transaction(() => { for (const t of unclassified) fill.run(JSON.stringify(classify(t.error)), t.cid, t.turn) })
|
|
145
|
+
const ticketColumns = this.db.prepare('PRAGMA table_info(tickets)').all().map(c => c.name)
|
|
146
|
+
for (const column of ['outcome TEXT', 'outcome_reason TEXT', 'outcome_at INTEGER']) if (!ticketColumns.includes(column.split(' ')[0])) this.db.exec('ALTER TABLE tickets ADD COLUMN ' + column)
|
|
147
|
+
this.db.exec("CREATE INDEX IF NOT EXISTS quota_by_turn ON events(cid,turn,id) WHERE kind='quota'")
|
|
148
|
+
this.transaction(() => {
|
|
149
|
+
this.db.exec('CREATE TABLE IF NOT EXISTS tasks (cid TEXT REFERENCES conversations, number INTEGER NOT NULL, title TEXT NOT NULL, start_turn INTEGER NOT NULL, end_turn INTEGER NOT NULL, model TEXT NOT NULL, thinking TEXT, outcome TEXT, outcome_reason TEXT, outcome_at INTEGER, PRIMARY KEY(cid,number))')
|
|
150
|
+
this.db.exec("INSERT INTO tasks SELECT c.id,1,t.title,1,coalesce((SELECT max(turn) FROM turns WHERE cid=c.id),0),c.model,c.thinking,t.outcome,t.outcome_reason,t.outcome_at FROM conversations c JOIN tickets t ON t.cid=c.id WHERE NOT EXISTS (SELECT 1 FROM tasks WHERE cid=c.id)")
|
|
151
|
+
})
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
marker(id) { return join(this.directory, 'workers', id) }
|
|
155
|
+
|
|
156
|
+
stmt(sql) {
|
|
157
|
+
if (!this.sql.has(sql)) this.sql.set(sql, this.db.prepare(sql))
|
|
158
|
+
return this.sql.get(sql)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
hasTable(name) {
|
|
162
|
+
return Boolean(this.stmt("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?").get(name))
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
setMetaValue(key, value) {
|
|
166
|
+
if (this.readOnly || !this.hasTable('runtime_meta')) return
|
|
167
|
+
const text = String(value)
|
|
168
|
+
const existing = this.stmt('SELECT value FROM runtime_meta WHERE key=?').get(key)
|
|
169
|
+
if (existing?.value === text) return
|
|
170
|
+
this.stmt('INSERT INTO runtime_meta(key,value) VALUES (?,?) ON CONFLICT(key) DO UPDATE SET value=excluded.value').run(key, text)
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
getMetaValue(key) {
|
|
174
|
+
if (!this.hasTable('runtime_meta')) return null
|
|
175
|
+
return this.stmt('SELECT value FROM runtime_meta WHERE key=?').get(key)?.value ?? null
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
concurrencyLimit() {
|
|
179
|
+
const stored = Number(this.getMetaValue('concurrency'))
|
|
180
|
+
if (Number.isSafeInteger(stored) && stored >= 1) return stored
|
|
181
|
+
const envLimit = Number(process.env.BROCO_CONCURRENCY ?? 3)
|
|
182
|
+
return Number.isSafeInteger(envLimit) && envLimit >= 1 ? envLimit : 3
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
queueSnapshotMap() {
|
|
186
|
+
const queued = this.stmt("SELECT c.id 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()
|
|
187
|
+
const map = new Map()
|
|
188
|
+
if (!queued.length) return map
|
|
189
|
+
const activeNames = this.stmt("SELECT c.name FROM conversations c LEFT JOIN turns r ON r.cid=c.id AND r.turn=c.turn WHERE c.status='running' ORDER BY r.started ASC, r.rowid ASC, c.name ASC").all().map(r => r.name)
|
|
190
|
+
const limit = this.concurrencyLimit()
|
|
191
|
+
const totalQueued = queued.length
|
|
192
|
+
for (let i = 0; i < totalQueued; i++) {
|
|
193
|
+
const cid = queued[i].id
|
|
194
|
+
const live = this.queueInfo?.(cid)
|
|
195
|
+
if (live) {
|
|
196
|
+
map.set(cid, {
|
|
197
|
+
position: live.position,
|
|
198
|
+
totalQueued: live.totalQueued,
|
|
199
|
+
limit: live.limit,
|
|
200
|
+
activeNames: [...(live.activeNames ?? [])]
|
|
201
|
+
})
|
|
202
|
+
} else {
|
|
203
|
+
map.set(cid, {
|
|
204
|
+
position: i + 1,
|
|
205
|
+
totalQueued,
|
|
206
|
+
limit,
|
|
207
|
+
activeNames: [...activeNames]
|
|
208
|
+
})
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return map
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
queueStatus(cid) {
|
|
215
|
+
const c = this.stmt('SELECT id,status FROM conversations WHERE id=?').get(cid)
|
|
216
|
+
if (!c || c.status !== 'queued') return null
|
|
217
|
+
const live = this.queueInfo?.(cid)
|
|
218
|
+
if (live) {
|
|
219
|
+
return {
|
|
220
|
+
position: live.position,
|
|
221
|
+
totalQueued: live.totalQueued,
|
|
222
|
+
limit: live.limit,
|
|
223
|
+
activeNames: [...(live.activeNames ?? [])]
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return this.queueSnapshotMap().get(cid) ?? null
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
catalog() {
|
|
230
|
+
return cachedCatalog()
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
transaction(fn) {
|
|
234
|
+
if (this.db.isTransaction) return fn()
|
|
235
|
+
this.db.exec(this.readOnly ? 'BEGIN' : 'BEGIN IMMEDIATE')
|
|
236
|
+
let value
|
|
237
|
+
try {
|
|
238
|
+
value = fn()
|
|
239
|
+
this.db.exec('COMMIT')
|
|
240
|
+
} catch (err) {
|
|
241
|
+
this.db.exec('ROLLBACK')
|
|
242
|
+
this.dirty.clear()
|
|
243
|
+
throw err
|
|
244
|
+
}
|
|
245
|
+
const changed = [...this.dirty]
|
|
246
|
+
this.dirty.clear()
|
|
247
|
+
for (const cid of changed) this.onChange?.(cid)
|
|
248
|
+
return value
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
changed(cid) {
|
|
252
|
+
this.stmt('UPDATE tickets SET updated=max(updated+1,?) WHERE cid=?').run(Date.now(), cid)
|
|
253
|
+
this.dirty.add(cid)
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
byName(name) {
|
|
257
|
+
return this.stmt('SELECT * FROM conversations WHERE name=?').get(name)
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
create(name, cwd, model, title, thinking, provider) {
|
|
261
|
+
return this.transaction(() => {
|
|
262
|
+
const id = randomUUID()
|
|
263
|
+
this.stmt("INSERT INTO conversations(id,name,cwd,model,thinking,provider,status,activity) VALUES (?,?,?,?,?,?,'idle','Ready')").run(id, name, cwd, model, thinking, provider)
|
|
264
|
+
this.stmt("INSERT INTO tickets(cid,title,stage,created,updated) VALUES (?,?,'queued',?,?)").run(id, title || name, Date.now(), Date.now())
|
|
265
|
+
return this.byName(name)
|
|
266
|
+
})
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
state(cid, status, activity) {
|
|
270
|
+
this.transaction(() => {
|
|
271
|
+
this.stmt('UPDATE conversations SET status=?,activity=? WHERE id=?').run(status, activity, cid)
|
|
272
|
+
if (status === 'error' || status === 'stopped') this.stmt('UPDATE tickets SET flag=? WHERE cid=?').run(status, cid)
|
|
273
|
+
this.changed(cid)
|
|
274
|
+
})
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
owner(cid, pid) {
|
|
278
|
+
this.stmt('UPDATE conversations SET worker_pid=? WHERE id=?').run(pid, cid)
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
event(cid, turn, kind, raw, summary = '') {
|
|
282
|
+
this.stmt('INSERT INTO events(cid,turn,at,kind,raw,summary) VALUES (?,?,?,?,?,?)').run(cid, turn, Date.now(), kind, JSON.stringify(raw), summary)
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
tasks(cid) {
|
|
286
|
+
return this.stmt('SELECT number AS task,title,start_turn AS startTurn,end_turn AS endTurn,model,thinking AS effort,outcome,outcome_reason AS outcomeReason,outcome_at AS outcomeAt FROM tasks WHERE cid=? ORDER BY number').all(cid)
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
currentTask(cid) {
|
|
290
|
+
return this.stmt('SELECT number AS task,title,start_turn AS startTurn,end_turn AS endTurn,model,thinking AS effort,outcome,outcome_reason AS outcomeReason,outcome_at AS outcomeAt FROM tasks WHERE cid=? ORDER BY number DESC LIMIT 1').get(cid)
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
accept(c, text, title, newTask = false) {
|
|
294
|
+
return this.transaction(() => {
|
|
295
|
+
const turn = this.nextTurn(c.id)
|
|
296
|
+
const previous = this.currentTask(c.id)
|
|
297
|
+
if (newTask && previous && !previous.outcome) throw new Error('Record the current task with done before --new-task')
|
|
298
|
+
const task = previous ? previous.task + (newTask ? 1 : 0) : 1
|
|
299
|
+
if (!previous || newTask) {
|
|
300
|
+
this.stmt('INSERT INTO tasks(cid,number,title,start_turn,end_turn,model,thinking) VALUES (?,?,?,?,?,?,?)').run(c.id, task, title || (previous ? c.name : this.stmt('SELECT title FROM tickets WHERE cid=?').get(c.id).title), turn, turn, c.model, c.thinking)
|
|
301
|
+
}
|
|
302
|
+
this.stmt('UPDATE tasks SET end_turn=?,model=?,thinking=?,outcome=NULL,outcome_reason=NULL,outcome_at=NULL WHERE cid=? AND number=?').run(turn, c.model, c.thinking, c.id, task)
|
|
303
|
+
if (title) this.stmt('UPDATE tasks SET title=? WHERE cid=? AND number=?').run(title, c.id, task)
|
|
304
|
+
if (newTask) this.stmt('UPDATE tickets SET title=? WHERE cid=?').run(title || c.name, c.id)
|
|
305
|
+
this.stmt("INSERT INTO turns(cid,turn,status,started) VALUES (?,?,'queued',?)").run(c.id, turn, Date.now())
|
|
306
|
+
this.stmt("UPDATE conversations SET turn=?,status='queued',activity='Queued' WHERE id=?").run(turn, c.id)
|
|
307
|
+
this.stmt("UPDATE tickets SET stage='queued',flag=NULL,started=NULL,outcome=NULL,outcome_reason=NULL,outcome_at=NULL WHERE cid=?").run(c.id)
|
|
308
|
+
if (title) this.stmt('UPDATE tickets SET title=? WHERE cid=?').run(title, c.id)
|
|
309
|
+
this.changed(c.id)
|
|
310
|
+
const number = this.message(c.id, turn, 'prompt', text)
|
|
311
|
+
this.event(c.id, turn, 'bro.say', { number, kind: 'prompt', task }, 'Queued')
|
|
312
|
+
return { name: c.name, number, turn, task, kind: 'prompt' }
|
|
313
|
+
})
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
nextTurn(cid) {
|
|
317
|
+
return this.stmt('SELECT coalesce(max(turn),0)+1 AS n FROM turns WHERE cid=?').get(cid).n
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
meta(cid) {
|
|
321
|
+
return this.stmt('SELECT * FROM collaboration WHERE cid=?').get(cid)
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
message(cid, turn, kind, text, error = null) {
|
|
325
|
+
const { number } = this.stmt('SELECT coalesce(max(number),0)+1 AS number FROM messages WHERE cid=?').get(cid)
|
|
326
|
+
this.stmt('INSERT INTO messages(cid,turn,number,kind,content,error) VALUES (?,?,?,?,?,?)').run(cid, turn, number, kind, text, error)
|
|
327
|
+
return number
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
follow(c, text, outcome, reason, turn = outcome === 'queued' ? c.turn + 1 : c.turn, pendingNumber) {
|
|
331
|
+
return this.transaction(() => {
|
|
332
|
+
if (outcome === 'queued') {
|
|
333
|
+
this.stmt("INSERT OR IGNORE INTO turns(cid,turn,status,started) VALUES (?,?,'queued',?)").run(c.id, turn, Date.now())
|
|
334
|
+
}
|
|
335
|
+
const task = this.currentTask(c.id)?.task
|
|
336
|
+
if (outcome !== 'rejected') this.stmt('UPDATE tasks SET end_turn=max(end_turn,?) WHERE cid=? AND number=?').run(turn, c.id, task)
|
|
337
|
+
const kind = outcome === 'queued' ? 'next' : outcome === 'injected' ? 'steer' : 'rejected'
|
|
338
|
+
const error = outcome === 'rejected' ? reason : null
|
|
339
|
+
const number = pendingNumber ?? this.message(c.id, turn, kind, text, error)
|
|
340
|
+
if (pendingNumber !== undefined) this.stmt("UPDATE messages SET turn=?,kind=?,error=? WHERE cid=? AND number=? AND kind='pending'").run(turn, kind, error, c.id, number)
|
|
341
|
+
const receipt = { name: c.name, turn, task, number, kind, outcome, reason }
|
|
342
|
+
this.event(c.id, turn, 'bro.interjection', receipt, outcome + ': ' + reason)
|
|
343
|
+
this.changed(c.id)
|
|
344
|
+
return receipt
|
|
345
|
+
})
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
claim(c) {
|
|
349
|
+
this.transaction(() => {
|
|
350
|
+
this.stmt("UPDATE turns SET status='running' WHERE cid=? AND turn=?").run(c.id, c.turn)
|
|
351
|
+
this.state(c.id, 'running', 'Starting worker')
|
|
352
|
+
})
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
working(c) {
|
|
356
|
+
this.transaction(() => {
|
|
357
|
+
this.stmt("UPDATE tickets SET stage='working',flag=NULL,started=? WHERE cid=?").run(Date.now(), c.id)
|
|
358
|
+
this.state(c.id, 'running', 'Working')
|
|
359
|
+
this.event(c.id, c.turn, 'bro.working', {}, 'Working')
|
|
360
|
+
})
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
done(name, { result, why, task } = {}) {
|
|
364
|
+
const c = this.byName(name)
|
|
365
|
+
if (!c) throw new Error('Unknown ticket: ' + name)
|
|
366
|
+
if (task !== undefined && (!Number.isSafeInteger(task) || task < 1)) throw new Error('Expected a positive task number')
|
|
367
|
+
const current = this.currentTask(c.id)
|
|
368
|
+
const selected = task === undefined ? current : this.tasks(c.id).find(t => t.task === task)
|
|
369
|
+
if (!selected) throw new Error('Unknown task: ' + task)
|
|
370
|
+
const archived = selected.task !== current.task
|
|
371
|
+
const ticket = archived ? { id: name, ...selected, status: 'done' } : this.ticket(c.id)
|
|
372
|
+
if (result !== undefined && !outcomes.includes(result)) throw new Error('Expected --result ' + outcomes.join('|'))
|
|
373
|
+
if (why !== undefined && (typeof why !== 'string' || why.length > 2000)) throw new Error('Invalid --why')
|
|
374
|
+
if (ticket.status === 'done' && result === undefined) return ticket
|
|
375
|
+
const closable = ticket.status === 'review' || (result !== undefined && outcomes.includes(result) && ['error', 'stopped'].includes(c.status))
|
|
376
|
+
if (ticket.status !== 'done' && !closable) throw new Error(['fail', 'blocked'].includes(result) ? 'Only finished, failed or stopped tickets can be closed' : 'Only tickets in review can be accepted; use --result fail or blocked to close a failed ticket, or any --result to close an interrupted ticket')
|
|
377
|
+
const turns = this.stmt('SELECT problem FROM turns WHERE cid=? AND turn BETWEEN ? AND ?').all(c.id, selected.startTurn, selected.endTurn).filter(t => !infra.includes(t.problem ? JSON.parse(t.problem).class : '')).length
|
|
378
|
+
const outcome = result ?? (turns > 1 ? 'rework' : 'pass')
|
|
379
|
+
const label = outcome === 'fail' ? 'Closed as failed by manager' : outcome === 'blocked' ? 'Closed as blocked by manager' : 'Accepted by manager'
|
|
380
|
+
this.transaction(() => {
|
|
381
|
+
const at = Date.now()
|
|
382
|
+
this.stmt('UPDATE tasks SET outcome=?,outcome_reason=?,outcome_at=? WHERE cid=? AND number=?').run(outcome, why ?? null, at, c.id, selected.task)
|
|
383
|
+
if (!archived) {
|
|
384
|
+
this.stmt("UPDATE tickets SET stage='done',flag=NULL,outcome=?,outcome_reason=?,outcome_at=? WHERE cid=?").run(outcome, why ?? null, at, c.id)
|
|
385
|
+
this.state(c.id, 'idle', label)
|
|
386
|
+
} else this.changed(c.id)
|
|
387
|
+
this.event(c.id, selected.endTurn, 'bro.accepted', { task: selected.task, outcome, why: why ?? null }, label + ' · task ' + selected.task + ' · ' + outcome)
|
|
388
|
+
})
|
|
389
|
+
if (!archived) this.onDone?.(c.id)
|
|
390
|
+
return archived ? { id: name, ...this.tasks(c.id).find(t => t.task === selected.task), status: 'done' } : this.ticket(c.id)
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
assistant(cid, turn, text) {
|
|
394
|
+
if (!text) return null
|
|
395
|
+
return this.stmt("INSERT INTO messages(cid,turn,kind,content) VALUES (?,?,'assistant',?)").run(cid, turn, text).lastInsertRowid
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
rejectDeferred(cid, turn, reason) {
|
|
399
|
+
for (const { number } of this.stmt("SELECT number FROM messages WHERE cid=? AND turn=? AND kind='next' AND error IS NULL").all(cid, turn)) {
|
|
400
|
+
this.stmt('UPDATE messages SET error=? WHERE cid=? AND number=?').run(reason, cid, number)
|
|
401
|
+
this.event(cid, turn, 'bro.interjection', { number, turn, outcome: 'rejected', reason }, 'rejected: ' + reason)
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
finish(cid, turn, status, detail, replyId = null, problem = null) {
|
|
406
|
+
return this.transaction(() => {
|
|
407
|
+
if (status === 'error') problem ??= classify(detail)
|
|
408
|
+
const updated = this.stmt("UPDATE turns SET status=?,finished=?,error=?,problem=? WHERE cid=? AND turn=? AND status IN ('queued','running')").run(status, Date.now(), status === 'done' ? null : detail, status === 'error' ? JSON.stringify(problem) : null, cid, turn)
|
|
409
|
+
if (!updated.changes) {
|
|
410
|
+
this.onStaleFinish?.(cid, turn)
|
|
411
|
+
return false
|
|
412
|
+
}
|
|
413
|
+
if (replyId !== null) this.stmt("UPDATE messages SET kind='reply' WHERE cid=? AND turn=? AND id=?").run(cid, turn, replyId)
|
|
414
|
+
if (status === 'done') this.stmt("UPDATE tickets SET stage='review',flag=NULL WHERE cid=?").run(cid)
|
|
415
|
+
this.state(cid, status === 'done' ? 'idle' : status, detail)
|
|
416
|
+
this.event(cid, turn, 'bro.' + status, problem ? { problem } : {}, detail)
|
|
417
|
+
const next = this.stmt("SELECT turn FROM turns WHERE cid=? AND turn>? AND status='queued' ORDER BY turn LIMIT 1").get(cid, turn)
|
|
418
|
+
if (next && status === 'done') {
|
|
419
|
+
this.stmt("UPDATE conversations SET turn=?,status='queued',activity='Queued follow-up' WHERE id=?").run(next.turn, cid)
|
|
420
|
+
this.stmt("UPDATE tickets SET stage='queued',flag=NULL,started=NULL WHERE cid=?").run(cid)
|
|
421
|
+
} else if (next) {
|
|
422
|
+
const reason = 'Previous turn did not complete: ' + detail
|
|
423
|
+
const nextProblem = status === 'error' ? JSON.stringify(classify(reason)) : null
|
|
424
|
+
this.stmt("UPDATE turns SET status=?,error=?,problem=?,finished=? WHERE cid=? AND turn=?").run(status, reason, nextProblem, Date.now(), cid, next.turn)
|
|
425
|
+
this.rejectDeferred(cid, next.turn, reason)
|
|
426
|
+
}
|
|
427
|
+
this.onFinish?.(cid, next && status === 'done')
|
|
428
|
+
return true
|
|
429
|
+
})
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
list() {
|
|
433
|
+
const rawRows = this.stmt('SELECT c.id,c.name,c.model,c.cwd,c.status,c.activity,c.turn,r.started,r.finished FROM conversations c LEFT JOIN turns r ON r.cid=c.id AND r.turn=c.turn ORDER BY c.name').all()
|
|
434
|
+
const hasQueued = rawRows.some(r => r.status === 'queued')
|
|
435
|
+
const queueMap = hasQueued && !this.queueInfo ? this.queueSnapshotMap() : null
|
|
436
|
+
return rawRows.map(({ id, ...row }) => {
|
|
437
|
+
const queue = row.status === 'queued'
|
|
438
|
+
? (this.queueInfo ? this.queueStatus(id) : (queueMap?.get(id) ?? null))
|
|
439
|
+
: null
|
|
440
|
+
return { ...row, activity: queue ? formatQueuedActivity(queue) : row.activity, queue }
|
|
441
|
+
})
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
batchMembershipMap() {
|
|
445
|
+
const map = new Map()
|
|
446
|
+
if (!this.hasTable('batches')) return map
|
|
447
|
+
for (const row of this.stmt('SELECT prefix, shards FROM batches').all()) {
|
|
448
|
+
const shards = JSON.parse(row.shards)
|
|
449
|
+
const count = shards.length
|
|
450
|
+
for (const s of shards) {
|
|
451
|
+
map.set(s.name, { prefix: row.prefix, index: s.index, count, input: s.input })
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
return map
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
ticketRows(where = '', ...params) {
|
|
458
|
+
const hasTasks = this.hasTable('tasks')
|
|
459
|
+
const sql = `
|
|
460
|
+
SELECT
|
|
461
|
+
c.id AS cid,
|
|
462
|
+
c.status AS conversationStatus,
|
|
463
|
+
c.name AS id,
|
|
464
|
+
c.cwd,
|
|
465
|
+
t.title,
|
|
466
|
+
t.stage AS status,
|
|
467
|
+
t.flag,
|
|
468
|
+
t.outcome,
|
|
469
|
+
t.outcome_reason AS outcomeReason,
|
|
470
|
+
t.outcome_at AS ticketOutcomeAt,
|
|
471
|
+
c.provider,
|
|
472
|
+
c.model,
|
|
473
|
+
c.thinking AS effort,
|
|
474
|
+
c.activity,
|
|
475
|
+
c.turn,
|
|
476
|
+
t.created,
|
|
477
|
+
t.updated,
|
|
478
|
+
t.started,
|
|
479
|
+
r.finished,
|
|
480
|
+
r.execution,
|
|
481
|
+
r.problem,
|
|
482
|
+
m.parent AS parentCid,
|
|
483
|
+
p.name AS parentName,
|
|
484
|
+
m.parent_turn AS parentTurn,
|
|
485
|
+
m.worktree,
|
|
486
|
+
m.branch,
|
|
487
|
+
m.files,
|
|
488
|
+
${hasTasks ? 'tk.number AS taskNumber, tk.title AS taskTitle, tk.start_turn AS startTurn, tk.end_turn AS endTurn, tk.model AS taskModel, tk.thinking AS taskEffort, tk.outcome AS taskOutcome, tk.outcome_reason AS taskOutcomeReason, tk.outcome_at AS taskOutcomeAt,' : 'NULL AS taskNumber, NULL AS taskTitle, NULL AS startTurn, NULL AS endTurn, NULL AS taskModel, NULL AS taskEffort, NULL AS taskOutcome, NULL AS taskOutcomeReason, NULL AS taskOutcomeAt,'}
|
|
489
|
+
(SELECT at FROM events e WHERE e.cid=c.id AND e.turn=c.turn ORDER BY e.id DESC LIMIT 1) AS lastEventAt,
|
|
490
|
+
(SELECT raw FROM events e WHERE e.cid=c.id AND e.turn=c.turn AND e.kind='usage' ORDER BY e.id DESC LIMIT 1) AS turnUsageRaw,
|
|
491
|
+
(SELECT turn FROM events e WHERE e.cid=c.id AND e.turn<=c.turn AND e.kind='usage' ORDER BY e.turn DESC,e.id DESC LIMIT 1) AS latestUsageTurn,
|
|
492
|
+
(SELECT raw FROM events e WHERE e.cid=c.id AND e.turn<=c.turn AND e.kind='usage' ORDER BY e.turn DESC,e.id DESC LIMIT 1) AS latestUsageRaw,
|
|
493
|
+
(SELECT execution FROM turns tx WHERE tx.cid=c.id AND tx.turn<=c.turn AND tx.execution IS NOT NULL ORDER BY tx.turn DESC LIMIT 1) AS latestExecution
|
|
494
|
+
FROM tickets t
|
|
495
|
+
JOIN conversations c ON c.id=t.cid
|
|
496
|
+
LEFT JOIN turns r ON r.cid=c.id AND r.turn=c.turn
|
|
497
|
+
LEFT JOIN collaboration m ON m.cid=c.id
|
|
498
|
+
LEFT JOIN conversations p ON p.id=m.parent
|
|
499
|
+
${hasTasks ? 'LEFT JOIN tasks tk ON tk.cid=c.id AND tk.number=(SELECT max(number) FROM tasks WHERE cid=c.id)' : ''}
|
|
500
|
+
`
|
|
501
|
+
const rows = this.stmt(sql + where + ' ORDER BY t.created,c.name').all(...params)
|
|
502
|
+
if (!rows.length) return []
|
|
503
|
+
|
|
504
|
+
const cids = rows.map(r => r.cid)
|
|
505
|
+
const cidsJson = JSON.stringify(cids)
|
|
506
|
+
const hasQueued = rows.some(r => r.conversationStatus === 'queued')
|
|
507
|
+
const queueMap = hasQueued && !this.queueInfo ? this.queueSnapshotMap() : null
|
|
508
|
+
const batchMap = this.batchMembershipMap()
|
|
509
|
+
const catalog = this.catalog()
|
|
510
|
+
|
|
511
|
+
const reviewsByCid = new Map()
|
|
512
|
+
for (const rv of this.stmt('SELECT m.parent AS cid,c.name AS id,m.parent_turn AS turn FROM collaboration m JOIN conversations c ON c.id=m.cid WHERE m.parent IN (SELECT value FROM json_each(?)) ORDER BY m.rowid').all(cidsJson)) {
|
|
513
|
+
let arr = reviewsByCid.get(rv.cid)
|
|
514
|
+
if (!arr) { arr = []; reviewsByCid.set(rv.cid, arr) }
|
|
515
|
+
arr.push({ id: rv.id, turn: rv.turn })
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
const interjectionsByCid = new Map()
|
|
519
|
+
for (const ij of this.stmt("SELECT cid,raw FROM events WHERE kind='bro.interjection' AND cid IN (SELECT value FROM json_each(?)) ORDER BY id").all(cidsJson)) {
|
|
520
|
+
let arr = interjectionsByCid.get(ij.cid)
|
|
521
|
+
if (!arr) { arr = []; interjectionsByCid.set(ij.cid, arr) }
|
|
522
|
+
arr.push(JSON.parse(ij.raw))
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
const quotaByCid = new Map()
|
|
526
|
+
for (const q of this.stmt("SELECT e.cid,e.raw FROM events e JOIN conversations c ON c.id=e.cid AND e.turn=c.turn WHERE e.kind='quota' AND e.cid IN (SELECT value FROM json_each(?)) ORDER BY e.id").all(cidsJson)) {
|
|
527
|
+
let arr = quotaByCid.get(q.cid)
|
|
528
|
+
if (!arr) { arr = []; quotaByCid.set(q.cid, arr) }
|
|
529
|
+
arr.push(JSON.parse(q.raw))
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
const stepStateByCid = new Map()
|
|
533
|
+
for (const ev of this.stmt("SELECT e.cid,e.kind,e.summary FROM events e JOIN conversations c ON c.id=e.cid AND e.turn=c.turn WHERE e.summary<>'' AND e.cid IN (SELECT value FROM json_each(?)) ORDER BY e.id").all(cidsJson)) {
|
|
534
|
+
if (!TOOL_EVENT_KINDS.has(ev.kind)) continue
|
|
535
|
+
let state = stepStateByCid.get(ev.cid)
|
|
536
|
+
if (!state) { state = { any: null, preferred: null }; stepStateByCid.set(ev.cid, state) }
|
|
537
|
+
state.any = ev.summary
|
|
538
|
+
if (!/^(?:agent_response\b|Writing reply$)/.test(ev.summary)) state.preferred = ev.summary
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
const needLegacyDispatch = []
|
|
542
|
+
const parsedExecByCid = new Map()
|
|
543
|
+
for (const row of rows) {
|
|
544
|
+
const parsedExec = row.execution ? JSON.parse(row.execution) : null
|
|
545
|
+
parsedExecByCid.set(row.cid, parsedExec)
|
|
546
|
+
if (!parsedExec || !Object.hasOwn(parsedExec, 'note')) needLegacyDispatch.push(row.cid)
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
const legacyDispatchByCid = new Map()
|
|
550
|
+
if (needLegacyDispatch.length) {
|
|
551
|
+
for (const d of this.stmt("SELECT e.cid,e.raw FROM events e JOIN conversations c ON c.id=e.cid AND e.turn=c.turn WHERE e.kind='bro.dispatch' AND e.cid IN (SELECT value FROM json_each(?)) ORDER BY e.id").all(JSON.stringify(needLegacyDispatch))) {
|
|
552
|
+
legacyDispatchByCid.set(d.cid, JSON.parse(d.raw))
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
const nowMs = Date.now()
|
|
557
|
+
return rows.map(row => {
|
|
558
|
+
const {
|
|
559
|
+
cid, conversationStatus, created, updated, started, finished,
|
|
560
|
+
execution, problem, parentCid, parentName, parentTurn, worktree, branch, files,
|
|
561
|
+
ticketOutcomeAt, taskNumber, taskTitle, startTurn, endTurn, taskModel, taskEffort, taskOutcome, taskOutcomeReason, taskOutcomeAt,
|
|
562
|
+
lastEventAt, turnUsageRaw, latestUsageTurn, latestUsageRaw, latestExecution,
|
|
563
|
+
...fields
|
|
564
|
+
} = row
|
|
565
|
+
|
|
566
|
+
const queue = conversationStatus === 'queued'
|
|
567
|
+
? (this.queueInfo ? this.queueStatus(cid) : (queueMap?.get(cid) ?? null))
|
|
568
|
+
: null
|
|
569
|
+
if (queue) fields.activity = formatQueuedActivity(queue)
|
|
570
|
+
|
|
571
|
+
const parsedExec = parsedExecByCid.get(cid)
|
|
572
|
+
if (parsedExec && Object.hasOwn(parsedExec, 'note')) {
|
|
573
|
+
Object.assign(fields, { note: parsedExec.note, rules: parsedExec.rules, capability: parsedExec.capability })
|
|
574
|
+
} else if (legacyDispatchByCid.has(cid)) {
|
|
575
|
+
Object.assign(fields, legacyDispatchByCid.get(cid))
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
if (taskNumber !== null) {
|
|
579
|
+
Object.assign(fields, {
|
|
580
|
+
task: taskNumber,
|
|
581
|
+
title: taskTitle,
|
|
582
|
+
startTurn,
|
|
583
|
+
endTurn,
|
|
584
|
+
model: taskModel,
|
|
585
|
+
effort: taskEffort,
|
|
586
|
+
outcome: taskOutcome,
|
|
587
|
+
outcomeReason: taskOutcomeReason
|
|
588
|
+
})
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
const rawOutcomeAt = taskNumber !== null ? taskOutcomeAt : ticketOutcomeAt
|
|
592
|
+
const usage = {
|
|
593
|
+
...parseUsageRaw(turnUsageRaw),
|
|
594
|
+
quota: computeQuotaSummary(quotaByCid.get(cid)),
|
|
595
|
+
problem: problem ? JSON.parse(problem) : null
|
|
596
|
+
}
|
|
597
|
+
const parent = parentCid ? (parentName ?? null) : null
|
|
598
|
+
const stepState = stepStateByCid.get(cid)
|
|
599
|
+
const currentStep = stepState?.preferred ?? stepState?.any ?? null
|
|
600
|
+
const lastHeartbeatAt = lastEventAt ? new Date(lastEventAt).toISOString() : null
|
|
601
|
+
const contextWarning = buildContextWarning(
|
|
602
|
+
{ name: fields.id, model: row.model, status: conversationStatus },
|
|
603
|
+
latestUsageTurn,
|
|
604
|
+
latestUsageRaw,
|
|
605
|
+
latestExecution,
|
|
606
|
+
catalog
|
|
607
|
+
)
|
|
608
|
+
|
|
609
|
+
Object.assign(fields, usage, {
|
|
610
|
+
outcomeAt: rawOutcomeAt ? new Date(rawOutcomeAt).toISOString() : null,
|
|
611
|
+
contextWarning,
|
|
612
|
+
currentStep,
|
|
613
|
+
lastHeartbeatAt,
|
|
614
|
+
batch: batchMap.get(fields.id) ?? null,
|
|
615
|
+
queue,
|
|
616
|
+
parent,
|
|
617
|
+
parentTurn: parentTurn ?? null,
|
|
618
|
+
reviews: reviewsByCid.get(cid) ?? [],
|
|
619
|
+
interjections: interjectionsByCid.get(cid) ?? [],
|
|
620
|
+
branch: branch ?? null,
|
|
621
|
+
worktree: worktree ?? null,
|
|
622
|
+
changedFiles: JSON.parse(files ?? 'null')
|
|
623
|
+
})
|
|
624
|
+
|
|
625
|
+
if (fields.status === 'done' && fields.worktree && !parent) {
|
|
626
|
+
fields.cleanupHint = 'Worktree and branch retained. After preserving changes, remove the worktree manually: ' + fields.worktree
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
return {
|
|
630
|
+
...fields,
|
|
631
|
+
createdAt: new Date(created).toISOString(),
|
|
632
|
+
updatedAt: new Date(updated).toISOString(),
|
|
633
|
+
startedAt: started === null ? null : new Date(started).toISOString(),
|
|
634
|
+
elapsedMs: started === null ? 0 : Math.max(0, (finished ?? nowMs) - started)
|
|
635
|
+
}
|
|
636
|
+
})
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
ticket(cid) {
|
|
640
|
+
return this.ticketRows('WHERE t.cid=?', cid)[0]
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
detail(name) {
|
|
644
|
+
const c = this.byName(name)
|
|
645
|
+
if (!c) return null
|
|
646
|
+
const ticket = this.ticket(c.id)
|
|
647
|
+
const lastReply = this.reply(c.id, c.turn) ?? null
|
|
648
|
+
const eventStats = this.stmt('SELECT count(*) AS n FROM events WHERE cid=?').get(c.id)
|
|
649
|
+
const latestEvent = this.stmt('SELECT at FROM events WHERE cid=? ORDER BY id DESC LIMIT 1').get(c.id)
|
|
650
|
+
const rows = this.stmt("SELECT turn,at,kind,summary FROM events WHERE cid=? AND summary<>'' ORDER BY id").all(c.id)
|
|
651
|
+
const groups = []
|
|
652
|
+
for (const e of rows) {
|
|
653
|
+
const prev = groups.at(-1)
|
|
654
|
+
if (prev && prev.turn === e.turn && prev.kind === e.kind && prev.rawSummary === e.summary) {
|
|
655
|
+
prev.lastAt = e.at
|
|
656
|
+
prev.count += 1
|
|
657
|
+
} else {
|
|
658
|
+
groups.push({ turn: e.turn, firstAt: e.at, lastAt: e.at, count: 1, kind: e.kind, rawSummary: e.summary })
|
|
659
|
+
}
|
|
660
|
+
}
|
|
661
|
+
const timeline = groups.map(g => {
|
|
662
|
+
const firstIso = new Date(g.firstAt).toISOString()
|
|
663
|
+
const lastIso = new Date(g.lastAt).toISOString()
|
|
664
|
+
const localTime = formatDateTime(g.lastAt)
|
|
665
|
+
return {
|
|
666
|
+
turn: g.turn,
|
|
667
|
+
ts: firstIso,
|
|
668
|
+
lastTs: lastIso,
|
|
669
|
+
count: g.count,
|
|
670
|
+
kind: g.kind,
|
|
671
|
+
rawSummary: g.rawSummary,
|
|
672
|
+
summary: g.count > 1 ? g.rawSummary + ' (×' + g.count + ', last ' + localTime + ')' : g.rawSummary
|
|
673
|
+
}
|
|
674
|
+
})
|
|
675
|
+
const turnTools = rows.filter(r => r.turn === c.turn && TOOL_EVENT_KINDS.has(r.kind))
|
|
676
|
+
const latestTool = turnTools.filter(r => !/^(?:agent_response\b|Writing reply$)/.test(r.summary)).at(-1) ?? turnTools.at(-1)
|
|
677
|
+
const recentMessages = this.stmt('SELECT turn,number,kind,content,error FROM messages WHERE cid=? ORDER BY id DESC LIMIT 10').all(c.id).reverse()
|
|
678
|
+
const progress = {
|
|
679
|
+
status: c.status,
|
|
680
|
+
activity: ticket.activity,
|
|
681
|
+
currentStep: latestTool?.summary ?? null,
|
|
682
|
+
lastHeartbeatAt: latestEvent?.at ? new Date(latestEvent.at).toISOString() : null,
|
|
683
|
+
eventCount: eventStats?.n ?? 0,
|
|
684
|
+
changedFilesCount: ticket.changedFiles?.length ?? 0,
|
|
685
|
+
queue: ticket.queue ?? null
|
|
686
|
+
}
|
|
687
|
+
return { ...ticket, tasks: this.tasks(c.id), lastReply, recentMessages, progress, timeline }
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
history(cid) {
|
|
691
|
+
return this.stmt('SELECT turn,number,kind,content,error FROM messages WHERE cid=? ORDER BY id').all(cid)
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
reply(cid, turn) {
|
|
695
|
+
return this.stmt("SELECT content FROM messages WHERE cid=? AND turn=? AND kind='reply' ORDER BY id DESC LIMIT 1").get(cid, turn)?.content
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
usage(cid, turn) {
|
|
699
|
+
const row = this.stmt("SELECT raw FROM events WHERE cid=? AND turn=? AND kind='usage' ORDER BY id DESC LIMIT 1").get(cid, turn)
|
|
700
|
+
return parseUsageRaw(row?.raw)
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
contextWarning(cid, turn) {
|
|
704
|
+
const row = this.stmt("SELECT turn,raw FROM events WHERE cid=? AND turn<=? AND kind='usage' ORDER BY turn DESC,id DESC LIMIT 1").get(cid, turn)
|
|
705
|
+
if (!row) return null
|
|
706
|
+
const c = this.stmt('SELECT id,name,model,status FROM conversations WHERE id=?').get(cid)
|
|
707
|
+
if (!c) return null
|
|
708
|
+
const execRow = this.stmt('SELECT execution FROM turns WHERE cid=? AND turn<=? AND execution IS NOT NULL ORDER BY turn DESC LIMIT 1').get(cid, turn)
|
|
709
|
+
return buildContextWarning(c, row.turn, row.raw, execRow?.execution ?? null, this.catalog())
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
handoff(name, text) {
|
|
713
|
+
const c = this.byName(name)
|
|
714
|
+
if (!c) throw new Error('Unknown handoff source: ' + name)
|
|
715
|
+
if (['running', 'queued'].includes(c.status)) throw new Error('Handoff needs an inactive source; wait for or stop ' + name)
|
|
716
|
+
if (typeof text !== 'string' || !text.trim()) throw new Error('Message is empty')
|
|
717
|
+
const reply = this.stmt("SELECT m.content FROM messages m JOIN turns t ON t.cid=m.cid AND t.turn=m.turn WHERE m.cid=? AND m.kind='reply' AND t.status='done' ORDER BY m.turn DESC,m.id DESC LIMIT 1").get(c.id)
|
|
718
|
+
return handoffPrompt(name, this.ticket(c.id).title, c.cwd, reply?.content, text)
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
problem(cid, turn) {
|
|
722
|
+
const row = this.stmt('SELECT problem FROM turns WHERE cid=? AND turn=?').get(cid, turn)
|
|
723
|
+
return row?.problem ? JSON.parse(row.problem) : null
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
quota(cid, turn) {
|
|
727
|
+
const rows = this.stmt("SELECT raw FROM events WHERE cid=? AND turn=? AND kind='quota' ORDER BY id").all(cid, turn).map(r => JSON.parse(r.raw))
|
|
728
|
+
return computeQuotaSummary(rows)
|
|
729
|
+
}
|
|
730
|
+
|
|
731
|
+
result(cid, turn) {
|
|
732
|
+
const t = this.stmt('SELECT turn,status,error FROM turns WHERE cid=? AND turn=?').get(cid, turn)
|
|
733
|
+
if (!t) throw new Error('Unknown turn ' + turn)
|
|
734
|
+
const queue = t.status === 'queued' ? this.queueStatus(cid) : null
|
|
735
|
+
return { ...t, ...this.usage(cid, turn), contextWarning: this.contextWarning(cid, turn), quota: this.quota(cid, turn), problem: this.problem(cid, turn), queue, reply: this.reply(cid, turn) ?? null }
|
|
736
|
+
}
|
|
737
|
+
}
|