@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/roster.mjs
ADDED
|
@@ -0,0 +1,913 @@
|
|
|
1
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
2
|
+
import { accessSync, constants, mkdirSync, mkdtempSync, rmSync, statSync } from 'node:fs'
|
|
3
|
+
import { delimiter, join } from 'node:path'
|
|
4
|
+
import { execFileSync } from 'node:child_process'
|
|
5
|
+
import { cliActions, detectCli, discoverPi } from './detect.mjs'
|
|
6
|
+
import { executable, inspectCommand } from './cli-process.mjs'
|
|
7
|
+
import { hiddenModel, loadCatalog, matchModel, modelKey, modelCapabilities, staleDefaultWarning, visiblePicks } from './model-catalog.mjs'
|
|
8
|
+
import { home } from './paths.mjs'
|
|
9
|
+
import { tight } from './quota.mjs'
|
|
10
|
+
import { SettingsAudit } from './settings-audit.mjs'
|
|
11
|
+
import { supportedWorker } from './worker-policy.mjs'
|
|
12
|
+
import { presets, templateTurn, validateTemplate } from './templates.mjs'
|
|
13
|
+
import { summarize, ticketRecords } from './stats.mjs'
|
|
14
|
+
import { platform } from './platform/index.mjs'
|
|
15
|
+
|
|
16
|
+
const fingerprint = t => createHash('sha256').update(JSON.stringify(validateTemplate(t))).digest('hex')
|
|
17
|
+
const list = (v, labelName) => {
|
|
18
|
+
if (!Array.isArray(v) || v.length > 100 || v.some(s => typeof s !== 'string' || s.length > 4000)) throw new Error('Invalid ' + labelName)
|
|
19
|
+
return v
|
|
20
|
+
}
|
|
21
|
+
const label = v => {
|
|
22
|
+
if (typeof v !== 'string' || v.length > 4000 || v.includes('\0')) throw new Error('Invalid text setting')
|
|
23
|
+
return v
|
|
24
|
+
}
|
|
25
|
+
const envConcurrency = () => {
|
|
26
|
+
const n = Number(process.env.BROCO_CONCURRENCY ?? 3)
|
|
27
|
+
return Number.isSafeInteger(n) && n >= 1 ? n : 3
|
|
28
|
+
}
|
|
29
|
+
const parseConcurrency = v => {
|
|
30
|
+
if (v === null || v === 'inherit' || v === 'default') return null
|
|
31
|
+
const n = typeof v === 'string' && /^\d+$/.test(v.trim()) ? Number(v.trim()) : v
|
|
32
|
+
if (!Number.isSafeInteger(n) || n < 1 || n > 64) throw new Error('Concurrency must be an integer between 1 and 64 (or "inherit")')
|
|
33
|
+
return n
|
|
34
|
+
}
|
|
35
|
+
const splitItems = (v, labelName) => {
|
|
36
|
+
if (v === undefined || v === null) return []
|
|
37
|
+
if (typeof v === 'string') return v.split(',').map(s => s.trim()).filter(Boolean)
|
|
38
|
+
return list(v, labelName).map(s => s.trim()).filter(Boolean)
|
|
39
|
+
}
|
|
40
|
+
const stringItems = (v, labelName) => {
|
|
41
|
+
if (v === undefined || v === null) return []
|
|
42
|
+
if (typeof v === 'string') return v.trim() ? [label(v).trim()] : []
|
|
43
|
+
return list(v, labelName).map(s => label(s).trim()).filter(Boolean)
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function hasCli(name) {
|
|
47
|
+
if (!name) return false
|
|
48
|
+
if (executable(name)) return true
|
|
49
|
+
for (const dir of (process.env.PATH || '').split(delimiter).filter(Boolean)) {
|
|
50
|
+
const p = join(dir, name)
|
|
51
|
+
try { accessSync(p, constants.X_OK); if (statSync(p).isFile()) return true } catch {}
|
|
52
|
+
}
|
|
53
|
+
return false
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function stripRevision(raw) {
|
|
57
|
+
const { revision, ...rest } = raw
|
|
58
|
+
return structuredClone(rest)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function cleanEntry(entries, worker, hadEntry = false) {
|
|
62
|
+
const cur = entries[worker]
|
|
63
|
+
if (!cur) return
|
|
64
|
+
for (const k of Object.keys(cur)) {
|
|
65
|
+
if (cur[k] === undefined) delete cur[k]
|
|
66
|
+
}
|
|
67
|
+
if (!hadEntry && Object.keys(cur).length === 0) delete entries[worker]
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export class Roster {
|
|
71
|
+
constructor(projects) {
|
|
72
|
+
this.projects = projects
|
|
73
|
+
this.db = projects.db
|
|
74
|
+
this.db.exec('CREATE TABLE IF NOT EXISTS roster_settings(scope TEXT PRIMARY KEY,revision INTEGER NOT NULL,data TEXT NOT NULL); CREATE TABLE IF NOT EXISTS note_proposals(id TEXT PRIMARY KEY,scope TEXT NOT NULL,worker TEXT NOT NULL,note TEXT NOT NULL,created INTEGER NOT NULL)')
|
|
75
|
+
if (!this.db.prepare('PRAGMA table_info(note_proposals)').all().some(c => c.name === 'defaults')) {
|
|
76
|
+
this.db.exec('ALTER TABLE note_proposals ADD COLUMN defaults TEXT')
|
|
77
|
+
}
|
|
78
|
+
const projectCols = this.db.prepare('PRAGMA table_info(projects)').all()
|
|
79
|
+
if (projectCols.length && !projectCols.some(c => c.name === 'concurrency')) {
|
|
80
|
+
this.db.exec('ALTER TABLE projects ADD COLUMN concurrency INTEGER')
|
|
81
|
+
}
|
|
82
|
+
this.audit = new SettingsAudit(this.db)
|
|
83
|
+
this.verified = new Map()
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
scopeInfo(scope) {
|
|
87
|
+
if (scope === 'global') return { scope: 'global', p: null, scopeName: 'Global' }
|
|
88
|
+
const p = this.projects.get(scope)
|
|
89
|
+
return { scope: p.id, p, scopeName: p.name || p.id }
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
read(scope) {
|
|
93
|
+
const row = this.db.prepare('SELECT * FROM roster_settings WHERE scope=?').get(scope)
|
|
94
|
+
return row ? { revision: row.revision, ...JSON.parse(row.data) } : { revision: 0, entries: {}, rules: [] }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
effective(project) {
|
|
98
|
+
const global = this.read('global'), local = this.read(project.id)
|
|
99
|
+
const entries = structuredClone(global.entries ?? {})
|
|
100
|
+
for (const [id, entry] of Object.entries(local.entries ?? {})) entries[id] = { ...entries[id], ...entry }
|
|
101
|
+
const policy = local.inheritPolicy ? global : { allow: project.allow, worker: project.worker }
|
|
102
|
+
const concurrency = local.concurrency ?? project.concurrency ?? global.concurrency ?? envConcurrency()
|
|
103
|
+
return {
|
|
104
|
+
allow: policy.allow ?? [],
|
|
105
|
+
worker: policy.worker ?? '',
|
|
106
|
+
concurrency,
|
|
107
|
+
entries,
|
|
108
|
+
rules: local.rulesOverride ? (local.rules ?? []) : [...(global.rules ?? []), ...(local.rules ?? [])]
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
effectiveSummary(scope) {
|
|
113
|
+
if (scope === 'global') {
|
|
114
|
+
const g = this.read('global')
|
|
115
|
+
return {
|
|
116
|
+
scope: 'global',
|
|
117
|
+
allow: g.allow ?? [],
|
|
118
|
+
worker: g.worker ?? '',
|
|
119
|
+
concurrency: g.concurrency ?? envConcurrency(),
|
|
120
|
+
entries: g.entries ?? {},
|
|
121
|
+
rules: g.rules ?? []
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
const p = this.projects.get(scope)
|
|
125
|
+
return { scope: p.id, ...this.effective(p) }
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
syncConcurrency(scope) {
|
|
129
|
+
const slots = this.projects.slots
|
|
130
|
+
if (!slots?.setLimit) return
|
|
131
|
+
if (scope === 'global') {
|
|
132
|
+
const g = this.read('global')
|
|
133
|
+
slots.setLimit('global', g.concurrency ?? envConcurrency())
|
|
134
|
+
for (const p of this.projects.entries?.values() ?? []) {
|
|
135
|
+
slots.setLimit(p.id, this.effective(p).concurrency)
|
|
136
|
+
}
|
|
137
|
+
} else if (this.projects.entries?.has(scope)) {
|
|
138
|
+
const p = this.projects.get(scope)
|
|
139
|
+
slots.setLimit(scope, this.effective(p).concurrency)
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
notifyScope(scope) {
|
|
144
|
+
this.syncConcurrency(scope)
|
|
145
|
+
if (!this.projects.hasListeners || this.projects.hasListeners()) {
|
|
146
|
+
if (this.projects.summary && this.projects.entries) {
|
|
147
|
+
for (const id of this.projects.entries.keys()) {
|
|
148
|
+
this.projects.publish?.({ type: 'project', project: this.projects.summary(id) })
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
this.projects.publish?.({ type: 'settings', scope })
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
config(scope) {
|
|
156
|
+
const p = scope === 'global' ? null : this.projects.get(scope)
|
|
157
|
+
const raw = this.read(scope)
|
|
158
|
+
const global = scope === 'global' ? raw : this.read('global')
|
|
159
|
+
const effective = p ? this.effective(p) : {
|
|
160
|
+
allow: raw.allow ?? [],
|
|
161
|
+
worker: raw.worker ?? '',
|
|
162
|
+
concurrency: raw.concurrency ?? envConcurrency(),
|
|
163
|
+
entries: raw.entries ?? {},
|
|
164
|
+
rules: raw.rules ?? []
|
|
165
|
+
}
|
|
166
|
+
return {
|
|
167
|
+
scope,
|
|
168
|
+
...raw,
|
|
169
|
+
concurrency: raw.concurrency ?? p?.concurrency ?? null,
|
|
170
|
+
effectiveConcurrency: effective.concurrency,
|
|
171
|
+
...(p ? { allow: p.allow, worker: p.worker, effective, inherited: global } : { effective }),
|
|
172
|
+
presets,
|
|
173
|
+
proposals: this.db.prepare('SELECT id,worker,note,defaults FROM note_proposals WHERE scope=? ORDER BY created').all(scope).map(row =>
|
|
174
|
+
row.defaults ? { id: row.id, worker: row.worker, defaults: JSON.parse(row.defaults) } : { id: row.id, worker: row.worker, note: row.note }
|
|
175
|
+
),
|
|
176
|
+
audit: this.auditList(scope, 20)
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
writeScopeSettings(scope, oldRevision, data) {
|
|
181
|
+
this.db.prepare('INSERT INTO roster_settings VALUES (?,?,?) ON CONFLICT(scope) DO UPDATE SET revision=excluded.revision,data=excluded.data').run(scope, oldRevision + 1, JSON.stringify(data))
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
save(scope, data, actor = 'user') {
|
|
185
|
+
const { p, scopeName } = this.scopeInfo(scope)
|
|
186
|
+
const old = this.read(scope)
|
|
187
|
+
if (data.revision !== old.revision) throw new Error('Settings changed; reload before saving')
|
|
188
|
+
const next = {
|
|
189
|
+
entries: {},
|
|
190
|
+
rules: list(data.rules ?? [], 'rules'),
|
|
191
|
+
rulesOverride: !!data.rulesOverride,
|
|
192
|
+
inheritPolicy: !!data.inheritPolicy
|
|
193
|
+
}
|
|
194
|
+
if (data.concurrency !== undefined) {
|
|
195
|
+
const conc = parseConcurrency(data.concurrency)
|
|
196
|
+
if (conc !== null) next.concurrency = conc
|
|
197
|
+
} else if (old.concurrency !== undefined) {
|
|
198
|
+
next.concurrency = old.concurrency
|
|
199
|
+
}
|
|
200
|
+
const inherited = this.read('global').entries ?? {}
|
|
201
|
+
for (const [id, raw] of Object.entries(data.entries ?? {})) {
|
|
202
|
+
if (!supportedWorker(id) || !raw || typeof raw !== 'object') throw new Error('Unknown worker ID: ' + id)
|
|
203
|
+
const entry = {}
|
|
204
|
+
for (const key of ['model', 'effort', 'note']) if (raw[key] !== undefined && raw[key] !== '') entry[key] = label(raw[key])
|
|
205
|
+
if (raw.hiddenModels !== undefined) entry.hiddenModels = list(raw.hiddenModels, 'hidden models')
|
|
206
|
+
if (raw.rules !== undefined) entry.rules = list(raw.rules, 'worker rules')
|
|
207
|
+
if (raw.models !== undefined) entry.models = list(raw.models, 'custom models')
|
|
208
|
+
if (raw.efforts !== undefined) entry.efforts = list(raw.efforts, 'custom efforts')
|
|
209
|
+
if (id.startsWith('custom:') && raw.template) {
|
|
210
|
+
entry.template = validateTemplate(raw.template)
|
|
211
|
+
const hash = fingerprint(entry.template)
|
|
212
|
+
const previous = old.entries?.[id]?.template ?? inherited[id]?.template
|
|
213
|
+
if ((!previous || fingerprint(previous) !== hash) && !(this.verified.get(scope + ':' + hash) > Date.now())) {
|
|
214
|
+
throw new Error('Test this exact template successfully before saving')
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
next.entries[id] = entry
|
|
218
|
+
}
|
|
219
|
+
const allow = [...new Set(list(data.allow ?? p?.allow ?? old.allow ?? [], 'allowlist'))]
|
|
220
|
+
const worker = data.worker ?? p?.worker ?? old.worker ?? ''
|
|
221
|
+
if (allow.some(id => !supportedWorker(id))) throw new Error('Invalid worker allowlist')
|
|
222
|
+
if (allow.some(id => id.startsWith('custom:') && !(next.entries[id]?.template ?? inherited[id]?.template))) {
|
|
223
|
+
throw new Error('Allowed custom workers need a tested template')
|
|
224
|
+
}
|
|
225
|
+
if ((allow.length && !allow.includes(worker)) || (!allow.length && worker)) throw new Error('Default worker must be allowed')
|
|
226
|
+
if (!p) Object.assign(next, { allow, worker })
|
|
227
|
+
if (p && next.inheritPolicy && !this.read('global').allow?.length) throw new Error('Set a global allowlist before inheriting it')
|
|
228
|
+
const nextProjConcurrency = data.concurrency !== undefined ? (next.concurrency ?? null) : (p?.concurrency ?? null)
|
|
229
|
+
const before = {
|
|
230
|
+
kind: 'snapshot',
|
|
231
|
+
settingsData: stripRevision(old),
|
|
232
|
+
project: p ? { allow: [...(p.allow ?? [])], worker: p.worker ?? '', concurrency: p.concurrency ?? null } : null
|
|
233
|
+
}
|
|
234
|
+
const after = {
|
|
235
|
+
kind: 'snapshot',
|
|
236
|
+
settingsData: structuredClone(next),
|
|
237
|
+
project: p ? { allow: [...allow], worker, concurrency: nextProjConcurrency } : null
|
|
238
|
+
}
|
|
239
|
+
this.db.exec('BEGIN IMMEDIATE')
|
|
240
|
+
try {
|
|
241
|
+
this.writeScopeSettings(scope, old.revision, next)
|
|
242
|
+
if (p) this.db.prepare('UPDATE projects SET allow=?,worker=?,concurrency=? WHERE id=?').run(JSON.stringify(allow), worker, nextProjConcurrency, p.id)
|
|
243
|
+
this.audit.record({ scope, scopeName, actor, action: 'save', summary: 'Saved settings for ' + scopeName, before, after })
|
|
244
|
+
this.db.exec('COMMIT')
|
|
245
|
+
} catch (err) { this.db.exec('ROLLBACK'); throw err }
|
|
246
|
+
if (p) Object.assign(p, { allow, worker, concurrency: nextProjConcurrency })
|
|
247
|
+
this.notifyScope(scope)
|
|
248
|
+
return this.config(scope)
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
setDefaults(scope, worker, { model, effort, clear = false } = {}, actor = 'agent') {
|
|
252
|
+
const { scopeName } = this.scopeInfo(scope)
|
|
253
|
+
if (!supportedWorker(worker)) throw new Error('Unknown worker: ' + worker)
|
|
254
|
+
if (!clear && model === undefined && effort === undefined) {
|
|
255
|
+
throw new Error('Supply --model and/or --effort (or --clear)')
|
|
256
|
+
}
|
|
257
|
+
const old = this.read(scope)
|
|
258
|
+
const data = stripRevision(old)
|
|
259
|
+
data.entries ??= {}
|
|
260
|
+
const hadEntry = Object.prototype.hasOwnProperty.call(data.entries, worker)
|
|
261
|
+
const prevEntry = data.entries[worker] ? structuredClone(data.entries[worker]) : undefined
|
|
262
|
+
const nextEntry = { ...(data.entries[worker] ?? {}) }
|
|
263
|
+
if (clear) {
|
|
264
|
+
delete nextEntry.model
|
|
265
|
+
delete nextEntry.effort
|
|
266
|
+
} else {
|
|
267
|
+
if (model !== undefined) {
|
|
268
|
+
if (model === null || model === 'inherit' || model === 'default') delete nextEntry.model
|
|
269
|
+
else {
|
|
270
|
+
const m = label(model).trim()
|
|
271
|
+
if (!m) throw new Error('Default model is empty')
|
|
272
|
+
const effectiveHidden = nextEntry.hiddenModels ?? (scope === 'global' ? [] : (this.read('global').entries?.[worker]?.hiddenModels ?? []))
|
|
273
|
+
if (hiddenModel(m, effectiveHidden)) {
|
|
274
|
+
throw new Error('Model is hidden for ' + worker + ': ' + m + ' (unhide it first with broco unhide ' + worker + ' ' + m + ')')
|
|
275
|
+
}
|
|
276
|
+
nextEntry.model = m
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
if (effort !== undefined) {
|
|
280
|
+
if (effort === null || effort === 'inherit' || effort === 'default') delete nextEntry.effort
|
|
281
|
+
else {
|
|
282
|
+
const e = label(effort).trim()
|
|
283
|
+
if (!e) throw new Error('Default effort is empty')
|
|
284
|
+
if (!/^[a-z0-9_-]{1,40}$/.test(e)) throw new Error('Invalid effort: ' + e)
|
|
285
|
+
nextEntry.effort = e
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
data.entries[worker] = nextEntry
|
|
290
|
+
cleanEntry(data.entries, worker, false)
|
|
291
|
+
const updatedEntry = data.entries[worker]
|
|
292
|
+
const before = { kind: 'entry-fields', worker, fields: { model: prevEntry?.model ?? null, effort: prevEntry?.effort ?? null }, hadEntry }
|
|
293
|
+
const after = { kind: 'entry-fields', worker, fields: { model: updatedEntry?.model ?? null, effort: updatedEntry?.effort ?? null }, hadEntry: !!updatedEntry }
|
|
294
|
+
const parts = [updatedEntry?.model && 'model=' + updatedEntry.model, updatedEntry?.effort && 'effort=' + updatedEntry.effort].filter(Boolean)
|
|
295
|
+
const summary = clear || !parts.length
|
|
296
|
+
? 'Cleared default overrides for ' + worker
|
|
297
|
+
: 'Set ' + worker + ' defaults (' + parts.join(', ') + ')'
|
|
298
|
+
let auditRow
|
|
299
|
+
this.db.exec('BEGIN IMMEDIATE')
|
|
300
|
+
try {
|
|
301
|
+
this.writeScopeSettings(scope, old.revision, data)
|
|
302
|
+
auditRow = this.audit.record({ scope, scopeName, actor, action: 'defaults', summary, before, after })
|
|
303
|
+
this.db.exec('COMMIT')
|
|
304
|
+
} catch (err) { this.db.exec('ROLLBACK'); throw err }
|
|
305
|
+
this.notifyScope(scope)
|
|
306
|
+
const eff = this.effectiveSummary(scope)
|
|
307
|
+
return {
|
|
308
|
+
scope,
|
|
309
|
+
worker,
|
|
310
|
+
defaults: { model: eff.entries[worker]?.model ?? null, effort: eff.entries[worker]?.effort ?? null },
|
|
311
|
+
override: { model: updatedEntry?.model ?? null, effort: updatedEntry?.effort ?? null },
|
|
312
|
+
effective: eff,
|
|
313
|
+
summary,
|
|
314
|
+
auditId: auditRow.id
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
setNote(scope, worker, note, actor = 'agent') {
|
|
319
|
+
const { scopeName } = this.scopeInfo(scope)
|
|
320
|
+
if (!supportedWorker(worker)) throw new Error('Unknown worker: ' + worker)
|
|
321
|
+
if (note === undefined) throw new Error('Note is required')
|
|
322
|
+
const trimmed = note === null ? '' : label(note).trim()
|
|
323
|
+
const old = this.read(scope)
|
|
324
|
+
const data = stripRevision(old)
|
|
325
|
+
data.entries ??= {}
|
|
326
|
+
const hadEntry = Object.prototype.hasOwnProperty.call(data.entries, worker)
|
|
327
|
+
const prevEntry = data.entries[worker] ? structuredClone(data.entries[worker]) : undefined
|
|
328
|
+
const nextEntry = { ...(data.entries[worker] ?? {}) }
|
|
329
|
+
if (!trimmed) delete nextEntry.note
|
|
330
|
+
else nextEntry.note = trimmed
|
|
331
|
+
data.entries[worker] = nextEntry
|
|
332
|
+
cleanEntry(data.entries, worker, false)
|
|
333
|
+
const updatedEntry = data.entries[worker]
|
|
334
|
+
const before = { kind: 'entry-fields', worker, fields: { note: prevEntry?.note ?? null }, hadEntry }
|
|
335
|
+
const after = { kind: 'entry-fields', worker, fields: { note: updatedEntry?.note ?? null }, hadEntry: !!updatedEntry }
|
|
336
|
+
const summary = trimmed
|
|
337
|
+
? 'Set note on ' + worker + ': ' + (trimmed.length > 72 ? trimmed.slice(0, 72) + '…' : trimmed)
|
|
338
|
+
: 'Cleared note on ' + worker
|
|
339
|
+
let auditRow
|
|
340
|
+
this.db.exec('BEGIN IMMEDIATE')
|
|
341
|
+
try {
|
|
342
|
+
this.writeScopeSettings(scope, old.revision, data)
|
|
343
|
+
auditRow = this.audit.record({ scope, scopeName, actor, action: 'note', summary, before, after })
|
|
344
|
+
this.db.exec('COMMIT')
|
|
345
|
+
} catch (err) { this.db.exec('ROLLBACK'); throw err }
|
|
346
|
+
this.notifyScope(scope)
|
|
347
|
+
const eff = this.effectiveSummary(scope)
|
|
348
|
+
return {
|
|
349
|
+
scope,
|
|
350
|
+
worker,
|
|
351
|
+
note: eff.entries[worker]?.note ?? '',
|
|
352
|
+
overrideNote: updatedEntry?.note ?? null,
|
|
353
|
+
effective: eff,
|
|
354
|
+
summary,
|
|
355
|
+
auditId: auditRow.id
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
setAllow(scope, { allow, add = [], remove = [], defaultWorker, inheritPolicy } = {}, actor = 'agent') {
|
|
360
|
+
const { p, scopeName } = this.scopeInfo(scope)
|
|
361
|
+
const old = this.read(scope)
|
|
362
|
+
const global = scope === 'global' ? old : this.read('global')
|
|
363
|
+
const data = stripRevision(old)
|
|
364
|
+
const currentAllow = p ? [...(p.allow ?? [])] : [...(old.allow ?? [])]
|
|
365
|
+
const currentWorker = p ? (p.worker ?? '') : (old.worker ?? '')
|
|
366
|
+
const toAdd = splitItems(add, 'allow add')
|
|
367
|
+
const toRemove = splitItems(remove, 'allow remove')
|
|
368
|
+
let nextAllow = allow !== undefined ? [...new Set(splitItems(allow, 'allowlist'))] : [...currentAllow]
|
|
369
|
+
for (const w of toAdd) if (!nextAllow.includes(w)) nextAllow.push(w)
|
|
370
|
+
if (toRemove.length) nextAllow = nextAllow.filter(w => !toRemove.includes(w))
|
|
371
|
+
if (nextAllow.some(id => !supportedWorker(id))) throw new Error('Invalid worker allowlist')
|
|
372
|
+
const effectiveEntries = p ? this.effective(p).entries : (data.entries ?? {})
|
|
373
|
+
if (nextAllow.some(id => id.startsWith('custom:') && !effectiveEntries[id]?.template)) {
|
|
374
|
+
throw new Error('Allowed custom workers need a tested template')
|
|
375
|
+
}
|
|
376
|
+
const explicitChange = allow !== undefined || toAdd.length > 0 || toRemove.length > 0 || defaultWorker !== undefined
|
|
377
|
+
const nextInherit = p ? (inheritPolicy !== undefined ? !!inheritPolicy : (explicitChange ? false : !!old.inheritPolicy)) : false
|
|
378
|
+
if (p && nextInherit && !(global.allow ?? []).length) throw new Error('Set a global allowlist before inheriting it')
|
|
379
|
+
let nextWorker
|
|
380
|
+
if (defaultWorker !== undefined) {
|
|
381
|
+
nextWorker = defaultWorker || ''
|
|
382
|
+
if ((nextAllow.length && !nextAllow.includes(nextWorker)) || (!nextAllow.length && nextWorker)) {
|
|
383
|
+
throw new Error('Default worker must be allowed')
|
|
384
|
+
}
|
|
385
|
+
} else {
|
|
386
|
+
nextWorker = nextAllow.includes(currentWorker) ? currentWorker : (nextAllow[0] ?? '')
|
|
387
|
+
}
|
|
388
|
+
if (p) data.inheritPolicy = nextInherit
|
|
389
|
+
else Object.assign(data, { allow: nextAllow, worker: nextWorker })
|
|
390
|
+
const before = { kind: 'allow', allow: currentAllow, worker: currentWorker, inheritPolicy: !!old.inheritPolicy }
|
|
391
|
+
const after = { kind: 'allow', allow: nextAllow, worker: nextWorker, inheritPolicy: nextInherit }
|
|
392
|
+
const summary = nextInherit
|
|
393
|
+
? 'Enabled global allowlist inheritance'
|
|
394
|
+
: 'Set allowlist=[' + nextAllow.join(', ') + ']' + (nextWorker ? ', default=' + nextWorker : '')
|
|
395
|
+
let auditRow
|
|
396
|
+
this.db.exec('BEGIN IMMEDIATE')
|
|
397
|
+
try {
|
|
398
|
+
this.writeScopeSettings(scope, old.revision, data)
|
|
399
|
+
if (p) this.db.prepare('UPDATE projects SET allow=?,worker=? WHERE id=?').run(JSON.stringify(nextAllow), nextWorker, p.id)
|
|
400
|
+
auditRow = this.audit.record({ scope, scopeName, actor, action: 'allow', summary, before, after })
|
|
401
|
+
this.db.exec('COMMIT')
|
|
402
|
+
} catch (err) { this.db.exec('ROLLBACK'); throw err }
|
|
403
|
+
if (p) Object.assign(p, { allow: nextAllow, worker: nextWorker })
|
|
404
|
+
this.notifyScope(scope)
|
|
405
|
+
const eff = this.effectiveSummary(scope)
|
|
406
|
+
return {
|
|
407
|
+
scope,
|
|
408
|
+
allow: eff.allow,
|
|
409
|
+
defaultWorker: eff.worker,
|
|
410
|
+
inheritPolicy: nextInherit,
|
|
411
|
+
effective: eff,
|
|
412
|
+
summary,
|
|
413
|
+
auditId: auditRow.id
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
setConcurrency(scope, concurrency, actor = 'agent') {
|
|
418
|
+
const { p, scopeName } = this.scopeInfo(scope)
|
|
419
|
+
const val = parseConcurrency(concurrency)
|
|
420
|
+
const old = this.read(scope)
|
|
421
|
+
const data = stripRevision(old)
|
|
422
|
+
const prevVal = old.concurrency ?? p?.concurrency ?? null
|
|
423
|
+
if (val === null) delete data.concurrency
|
|
424
|
+
else data.concurrency = val
|
|
425
|
+
const before = { kind: 'concurrency', concurrency: prevVal }
|
|
426
|
+
const after = { kind: 'concurrency', concurrency: val }
|
|
427
|
+
let auditRow
|
|
428
|
+
this.db.exec('BEGIN IMMEDIATE')
|
|
429
|
+
try {
|
|
430
|
+
this.writeScopeSettings(scope, old.revision, data)
|
|
431
|
+
if (p) this.db.prepare('UPDATE projects SET concurrency=? WHERE id=?').run(val, p.id)
|
|
432
|
+
if (p) p.concurrency = val
|
|
433
|
+
const effAfter = p ? this.effective(p).concurrency : (val ?? envConcurrency())
|
|
434
|
+
const summary = val === null
|
|
435
|
+
? 'Reset concurrency override (effective=' + effAfter + ')'
|
|
436
|
+
: 'Set concurrency limit to ' + val
|
|
437
|
+
auditRow = this.audit.record({ scope, scopeName, actor, action: 'concurrency', summary, before, after })
|
|
438
|
+
this.db.exec('COMMIT')
|
|
439
|
+
} catch (err) {
|
|
440
|
+
this.db.exec('ROLLBACK')
|
|
441
|
+
if (p) p.concurrency = prevVal
|
|
442
|
+
throw err
|
|
443
|
+
}
|
|
444
|
+
this.notifyScope(scope)
|
|
445
|
+
const eff = this.effectiveSummary(scope)
|
|
446
|
+
return {
|
|
447
|
+
scope,
|
|
448
|
+
concurrency: eff.concurrency,
|
|
449
|
+
override: val,
|
|
450
|
+
effective: eff,
|
|
451
|
+
summary: auditRow.summary,
|
|
452
|
+
auditId: auditRow.id
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
setRules(scope, { add = [], remove = [], clear = false, worker = null, rulesOverride } = {}, actor = 'agent') {
|
|
457
|
+
const { scopeName } = this.scopeInfo(scope)
|
|
458
|
+
const toAdd = stringItems(add, 'rules')
|
|
459
|
+
const toRemove = stringItems(remove, 'rules')
|
|
460
|
+
const old = this.read(scope)
|
|
461
|
+
const data = stripRevision(old)
|
|
462
|
+
let before, after, summary
|
|
463
|
+
if (worker !== null && worker !== undefined) {
|
|
464
|
+
if (!supportedWorker(worker)) throw new Error('Unknown worker: ' + worker)
|
|
465
|
+
data.entries ??= {}
|
|
466
|
+
const hadEntry = Object.prototype.hasOwnProperty.call(data.entries, worker)
|
|
467
|
+
const prevEntry = data.entries[worker] ? structuredClone(data.entries[worker]) : undefined
|
|
468
|
+
let nextRules = clear ? [] : [...(prevEntry?.rules ?? [])]
|
|
469
|
+
for (const r of toAdd) if (!nextRules.includes(r)) nextRules.push(r)
|
|
470
|
+
if (toRemove.length) nextRules = nextRules.filter(r => !toRemove.includes(r))
|
|
471
|
+
list(nextRules, 'worker rules')
|
|
472
|
+
const nextEntry = { ...(data.entries[worker] ?? {}) }
|
|
473
|
+
if (clear && !nextRules.length && scope === 'global') delete nextEntry.rules
|
|
474
|
+
else if (!nextRules.length && !clear && prevEntry?.rules === undefined) delete nextEntry.rules
|
|
475
|
+
else nextEntry.rules = nextRules
|
|
476
|
+
data.entries[worker] = nextEntry
|
|
477
|
+
cleanEntry(data.entries, worker, false)
|
|
478
|
+
const updatedEntry = data.entries[worker]
|
|
479
|
+
before = { kind: 'entry-fields', worker, fields: { rules: prevEntry?.rules ?? null }, hadEntry }
|
|
480
|
+
after = { kind: 'entry-fields', worker, fields: { rules: updatedEntry?.rules ?? null }, hadEntry: !!updatedEntry }
|
|
481
|
+
summary = clear && !toAdd.length
|
|
482
|
+
? 'Cleared rules for ' + worker
|
|
483
|
+
: 'Updated rules for ' + worker + ' (' + nextRules.length + ' active)'
|
|
484
|
+
} else {
|
|
485
|
+
let nextRules = clear ? [] : [...(old.rules ?? [])]
|
|
486
|
+
for (const r of toAdd) if (!nextRules.includes(r)) nextRules.push(r)
|
|
487
|
+
if (toRemove.length) nextRules = nextRules.filter(r => !toRemove.includes(r))
|
|
488
|
+
list(nextRules, 'rules')
|
|
489
|
+
const nextOverride = rulesOverride !== undefined ? !!rulesOverride : !!old.rulesOverride
|
|
490
|
+
data.rules = nextRules
|
|
491
|
+
data.rulesOverride = nextOverride
|
|
492
|
+
before = { kind: 'rules', rules: [...(old.rules ?? [])], rulesOverride: !!old.rulesOverride }
|
|
493
|
+
after = { kind: 'rules', rules: nextRules, rulesOverride: nextOverride }
|
|
494
|
+
summary = clear && !toAdd.length
|
|
495
|
+
? 'Cleared rules for ' + scopeName
|
|
496
|
+
: 'Updated rules for ' + scopeName + ' (' + nextRules.length + ' rule' + (nextRules.length === 1 ? '' : 's') + ')'
|
|
497
|
+
}
|
|
498
|
+
let auditRow
|
|
499
|
+
this.db.exec('BEGIN IMMEDIATE')
|
|
500
|
+
try {
|
|
501
|
+
this.writeScopeSettings(scope, old.revision, data)
|
|
502
|
+
auditRow = this.audit.record({ scope, scopeName, actor, action: 'rules', summary, before, after })
|
|
503
|
+
this.db.exec('COMMIT')
|
|
504
|
+
} catch (err) { this.db.exec('ROLLBACK'); throw err }
|
|
505
|
+
this.notifyScope(scope)
|
|
506
|
+
const eff = this.effectiveSummary(scope)
|
|
507
|
+
return {
|
|
508
|
+
scope,
|
|
509
|
+
...(worker ? { worker, workerRules: eff.entries[worker]?.rules ?? [] } : {}),
|
|
510
|
+
rules: eff.rules,
|
|
511
|
+
effective: eff,
|
|
512
|
+
summary,
|
|
513
|
+
auditId: auditRow.id
|
|
514
|
+
}
|
|
515
|
+
}
|
|
516
|
+
|
|
517
|
+
setHiddenModels(scope, worker, { hide = [], unhide = [], clear = false } = {}, actor = 'agent') {
|
|
518
|
+
const { scopeName } = this.scopeInfo(scope)
|
|
519
|
+
if (!supportedWorker(worker)) throw new Error('Unknown worker: ' + worker)
|
|
520
|
+
const toHide = splitItems(hide, 'hidden models')
|
|
521
|
+
const toUnhide = splitItems(unhide, 'hidden models')
|
|
522
|
+
const old = this.read(scope)
|
|
523
|
+
const data = stripRevision(old)
|
|
524
|
+
data.entries ??= {}
|
|
525
|
+
const hadEntry = Object.prototype.hasOwnProperty.call(data.entries, worker)
|
|
526
|
+
const prevEntry = data.entries[worker] ? structuredClone(data.entries[worker]) : undefined
|
|
527
|
+
const inheritedHidden = scope === 'global' ? [] : (this.read('global').entries?.[worker]?.hiddenModels ?? [])
|
|
528
|
+
let nextHidden = clear ? [] : [...(prevEntry?.hiddenModels ?? inheritedHidden)]
|
|
529
|
+
for (const m of toHide) {
|
|
530
|
+
const k = modelKey(m)
|
|
531
|
+
if (!nextHidden.some(x => x === m || modelKey(x) === k)) nextHidden.push(k)
|
|
532
|
+
}
|
|
533
|
+
if (toUnhide.length) {
|
|
534
|
+
const unhideKeys = new Set(toUnhide.map(modelKey))
|
|
535
|
+
nextHidden = nextHidden.filter(x => !toUnhide.includes(x) && !unhideKeys.has(modelKey(x)))
|
|
536
|
+
}
|
|
537
|
+
list(nextHidden, 'hidden models')
|
|
538
|
+
const nextEntry = { ...(data.entries[worker] ?? {}) }
|
|
539
|
+
if (clear && scope === 'global' && !nextHidden.length) delete nextEntry.hiddenModels
|
|
540
|
+
else nextEntry.hiddenModels = nextHidden
|
|
541
|
+
data.entries[worker] = nextEntry
|
|
542
|
+
cleanEntry(data.entries, worker, false)
|
|
543
|
+
const updatedEntry = data.entries[worker]
|
|
544
|
+
const before = { kind: 'entry-fields', worker, fields: { hiddenModels: prevEntry?.hiddenModels ?? null }, hadEntry }
|
|
545
|
+
const after = { kind: 'entry-fields', worker, fields: { hiddenModels: updatedEntry?.hiddenModels ?? null }, hadEntry: !!updatedEntry }
|
|
546
|
+
const summary = clear && !toHide.length
|
|
547
|
+
? 'Cleared hidden models on ' + worker
|
|
548
|
+
: 'Updated hidden models on ' + worker + ' (' + nextHidden.length + ' hidden)'
|
|
549
|
+
let auditRow
|
|
550
|
+
this.db.exec('BEGIN IMMEDIATE')
|
|
551
|
+
try {
|
|
552
|
+
this.writeScopeSettings(scope, old.revision, data)
|
|
553
|
+
auditRow = this.audit.record({ scope, scopeName, actor, action: 'hidden-models', summary, before, after })
|
|
554
|
+
this.db.exec('COMMIT')
|
|
555
|
+
} catch (err) { this.db.exec('ROLLBACK'); throw err }
|
|
556
|
+
this.notifyScope(scope)
|
|
557
|
+
const eff = this.effectiveSummary(scope)
|
|
558
|
+
return {
|
|
559
|
+
scope,
|
|
560
|
+
worker,
|
|
561
|
+
hiddenModels: eff.entries[worker]?.hiddenModels ?? [],
|
|
562
|
+
effective: eff,
|
|
563
|
+
summary,
|
|
564
|
+
auditId: auditRow.id
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
auditList(scope = null, limit = 30) {
|
|
569
|
+
if (scope && scope !== 'all' && scope !== 'global') this.projects.get(scope)
|
|
570
|
+
return this.audit.list(scope, limit)
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
undoAudit(auditId, opts = {}) {
|
|
574
|
+
if (auditId && typeof auditId === 'object') {
|
|
575
|
+
opts = auditId
|
|
576
|
+
auditId = opts.id ?? opts.auditId ?? null
|
|
577
|
+
}
|
|
578
|
+
const { scope, actor = 'user' } = opts ?? {}
|
|
579
|
+
let row
|
|
580
|
+
if (auditId !== undefined && auditId !== null && auditId !== '') {
|
|
581
|
+
row = this.audit.get(Number(auditId))
|
|
582
|
+
if (!row) throw new Error('Unknown audit entry: ' + auditId)
|
|
583
|
+
if (scope && scope !== 'all' && row.scope !== scope) {
|
|
584
|
+
throw new Error('Audit entry #' + row.id + ' belongs to scope ' + row.scope)
|
|
585
|
+
}
|
|
586
|
+
} else {
|
|
587
|
+
const targetScope = scope && scope !== 'all' ? scope : null
|
|
588
|
+
if (targetScope && targetScope !== 'global') this.projects.get(targetScope)
|
|
589
|
+
row = this.audit.latestUndoable(targetScope)
|
|
590
|
+
if (!row) throw new Error('Nothing to undo' + (targetScope ? ' for ' + targetScope : ''))
|
|
591
|
+
}
|
|
592
|
+
if (row.revertedAt) throw new Error('Audit entry #' + row.id + ' was already reverted')
|
|
593
|
+
if (row.scope !== 'global') {
|
|
594
|
+
let registered = true
|
|
595
|
+
try { this.projects.get(row.scope) } catch { registered = false }
|
|
596
|
+
if (!registered) throw new Error('Cannot undo #' + row.id + ': project ' + (row.scopeName || row.scope) + ' is no longer registered')
|
|
597
|
+
}
|
|
598
|
+
const { p, scopeName } = this.scopeInfo(row.scope)
|
|
599
|
+
const old = this.read(row.scope)
|
|
600
|
+
const data = stripRevision(old)
|
|
601
|
+
const patch = row.before
|
|
602
|
+
let nextAllow = p ? [...(p.allow ?? [])] : [...(data.allow ?? [])]
|
|
603
|
+
let nextWorker = p ? (p.worker ?? '') : (data.worker ?? '')
|
|
604
|
+
let nextConc = p ? (p.concurrency ?? null) : (data.concurrency ?? null)
|
|
605
|
+
let updateProjectCols = false
|
|
606
|
+
|
|
607
|
+
if (patch.kind === 'entry-fields') {
|
|
608
|
+
data.entries ??= {}
|
|
609
|
+
const cur = { ...(data.entries[patch.worker] ?? {}) }
|
|
610
|
+
for (const [k, v] of Object.entries(patch.fields ?? {})) {
|
|
611
|
+
if (v === undefined || v === null) delete cur[k]
|
|
612
|
+
else cur[k] = v
|
|
613
|
+
}
|
|
614
|
+
data.entries[patch.worker] = cur
|
|
615
|
+
cleanEntry(data.entries, patch.worker, !!patch.hadEntry)
|
|
616
|
+
} else if (patch.kind === 'rules') {
|
|
617
|
+
data.rules = [...(patch.rules ?? [])]
|
|
618
|
+
data.rulesOverride = !!patch.rulesOverride
|
|
619
|
+
} else if (patch.kind === 'concurrency') {
|
|
620
|
+
if (patch.concurrency === null || patch.concurrency === undefined) delete data.concurrency
|
|
621
|
+
else data.concurrency = patch.concurrency
|
|
622
|
+
nextConc = patch.concurrency ?? null
|
|
623
|
+
updateProjectCols = true
|
|
624
|
+
} else if (patch.kind === 'allow') {
|
|
625
|
+
nextAllow = [...(patch.allow ?? [])]
|
|
626
|
+
nextWorker = patch.worker ?? ''
|
|
627
|
+
if (nextAllow.length && !nextAllow.includes(nextWorker)) nextWorker = nextAllow[0]
|
|
628
|
+
if (!nextAllow.length) nextWorker = ''
|
|
629
|
+
if (p) data.inheritPolicy = !!patch.inheritPolicy
|
|
630
|
+
else Object.assign(data, { allow: nextAllow, worker: nextWorker })
|
|
631
|
+
updateProjectCols = true
|
|
632
|
+
} else if (patch.kind === 'snapshot') {
|
|
633
|
+
for (const k of Object.keys(data)) delete data[k]
|
|
634
|
+
Object.assign(data, structuredClone(patch.settingsData ?? { entries: {}, rules: [] }))
|
|
635
|
+
if (p && patch.project) {
|
|
636
|
+
nextAllow = [...(patch.project.allow ?? [])]
|
|
637
|
+
nextWorker = patch.project.worker ?? ''
|
|
638
|
+
nextConc = patch.project.concurrency ?? null
|
|
639
|
+
updateProjectCols = true
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
const now = Date.now()
|
|
644
|
+
const summary = 'Reverted #' + row.id + ': ' + row.summary
|
|
645
|
+
let undoRow
|
|
646
|
+
this.db.exec('BEGIN IMMEDIATE')
|
|
647
|
+
try {
|
|
648
|
+
this.writeScopeSettings(row.scope, old.revision, data)
|
|
649
|
+
if (p && updateProjectCols) {
|
|
650
|
+
this.db.prepare('UPDATE projects SET allow=?,worker=?,concurrency=? WHERE id=?').run(JSON.stringify(nextAllow), nextWorker, nextConc, p.id)
|
|
651
|
+
}
|
|
652
|
+
this.audit.markReverted(row.id, now)
|
|
653
|
+
undoRow = this.audit.record({
|
|
654
|
+
scope: row.scope,
|
|
655
|
+
scopeName,
|
|
656
|
+
actor,
|
|
657
|
+
action: 'undo',
|
|
658
|
+
summary,
|
|
659
|
+
before: row.after,
|
|
660
|
+
after: row.before,
|
|
661
|
+
at: now
|
|
662
|
+
})
|
|
663
|
+
this.db.exec('COMMIT')
|
|
664
|
+
} catch (err) { this.db.exec('ROLLBACK'); throw err }
|
|
665
|
+
if (p && updateProjectCols) Object.assign(p, { allow: nextAllow, worker: nextWorker, concurrency: nextConc })
|
|
666
|
+
this.notifyScope(row.scope)
|
|
667
|
+
return {
|
|
668
|
+
undoneId: row.id,
|
|
669
|
+
auditId: undoRow.id,
|
|
670
|
+
scope: row.scope,
|
|
671
|
+
summary,
|
|
672
|
+
effective: this.effectiveSummary(row.scope),
|
|
673
|
+
config: this.config(row.scope)
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
async list(scope, all = false, { refresh = false } = {}) {
|
|
678
|
+
const project = scope === 'global' ? null : this.projects.get(scope)
|
|
679
|
+
const effective = project ? this.effective(project) : this.read('global')
|
|
680
|
+
const allow = effective.allow ?? []
|
|
681
|
+
const cwd = project?.repoPath ?? home
|
|
682
|
+
const discovered = await discoverPi(cwd, { refresh })
|
|
683
|
+
const ids = [...new Set([...allow, 'codex', 'claude', 'agy', 'cursor-agent', ...discovered, ...Object.keys(effective.entries ?? {}), ...(all ? ['pi:openai-codex', 'pi:deepseek', ...Object.keys(presets)] : [])])]
|
|
684
|
+
const catalog = loadCatalog()
|
|
685
|
+
const hiddenAllByWorker = new Map()
|
|
686
|
+
const rows = await Promise.all(ids.map(async id => {
|
|
687
|
+
const entry = effective.entries?.[id] ?? {}
|
|
688
|
+
const custom = id.startsWith('custom:')
|
|
689
|
+
const template = entry.template ?? presets[id]
|
|
690
|
+
const cli = template?.command ?? ''
|
|
691
|
+
const isAllowed = allow.includes(id)
|
|
692
|
+
const inspectGlobalBuiltins = scope === 'global' && all && !allow.length && ['codex', 'claude', 'agy', 'cursor-agent'].includes(id)
|
|
693
|
+
if (!isAllowed && !inspectGlobalBuiltins) {
|
|
694
|
+
const cliName = custom ? cli : id.startsWith('pi:') ? 'pi' : id
|
|
695
|
+
return {
|
|
696
|
+
id,
|
|
697
|
+
cli: cliName,
|
|
698
|
+
allowed: false,
|
|
699
|
+
installed: hasCli(cliName),
|
|
700
|
+
capability: custom ? 'degraded' : 'full',
|
|
701
|
+
loginStatus: 'unknown',
|
|
702
|
+
models: [],
|
|
703
|
+
efforts: [],
|
|
704
|
+
defaultModel: null,
|
|
705
|
+
defaultEffort: null,
|
|
706
|
+
warnings: [],
|
|
707
|
+
note: entry.note ?? '',
|
|
708
|
+
rules: [...(effective.rules ?? []), ...(entry.rules ?? [])]
|
|
709
|
+
}
|
|
710
|
+
}
|
|
711
|
+
const actions = { ...cliActions[cli], ...Object.fromEntries(Object.entries(template?.actions ?? {}).map(([k, v]) => [k, v.join(' ')])) }
|
|
712
|
+
const detected = custom ? {
|
|
713
|
+
...actions,
|
|
714
|
+
cli,
|
|
715
|
+
installed: !!executable(cli),
|
|
716
|
+
capability: 'degraded',
|
|
717
|
+
steering: 'queue',
|
|
718
|
+
cache: false,
|
|
719
|
+
version: null,
|
|
720
|
+
loginStatus: 'unknown',
|
|
721
|
+
models: (entry.models ?? []).map(mId => ({ id: mId })),
|
|
722
|
+
efforts: entry.efforts ?? [],
|
|
723
|
+
defaultModel: null,
|
|
724
|
+
defaultEffort: null,
|
|
725
|
+
tested: !!entry.template,
|
|
726
|
+
warnings: [entry.template ? 'Custom CLI: session and reply extraction verified; detailed steps, live steering and cache are unavailable.' : 'Preset only: test this CLI before saving and allowing it.']
|
|
727
|
+
} : await detectCli(id, cwd, { refresh })
|
|
728
|
+
if (custom && detected.installed && (template?.versionArgs || cliActions[cli])) {
|
|
729
|
+
const version = await inspectCommand(cli, template.versionArgs ?? ['--version'], cwd)
|
|
730
|
+
detected.version = version.ok ? version.text.trim().split('\n')[0].slice(0, 200) : null
|
|
731
|
+
}
|
|
732
|
+
const models = detected.models.map(m => {
|
|
733
|
+
const matched = matchModel(m.id, catalog)
|
|
734
|
+
const description = matched && (all || !hiddenModel(matched.id, entry.hiddenModels)) ? { ...matched, ...(matched.aliases ? { aliases: matched.aliases.filter(aliasId => all || !hiddenModel(aliasId, entry.hiddenModels)) } : {}) } : null
|
|
735
|
+
return { ...m, ...(description ? { catalog: description } : {}), capabilities: modelCapabilities(id, m, description), hidden: hiddenModel(m.id, entry.hiddenModels) }
|
|
736
|
+
}).filter(m => all || !m.hidden)
|
|
737
|
+
if (detected.models.length > 0 && models.length === 0) hiddenAllByWorker.set(id, true)
|
|
738
|
+
const visibleDefault = value => all || !value || !hiddenModel(value, entry.hiddenModels) ? value : null
|
|
739
|
+
const defaultModel = visibleDefault(entry.model || detected.defaultModel)
|
|
740
|
+
const staleWarning = staleDefaultWarning(id, defaultModel, detected.models, catalog)
|
|
741
|
+
if (staleWarning) detected.warnings.push(staleWarning)
|
|
742
|
+
return {
|
|
743
|
+
id,
|
|
744
|
+
...detected,
|
|
745
|
+
models,
|
|
746
|
+
defaultBlocked: hiddenModel(entry.model || detected.defaultModel || '', entry.hiddenModels),
|
|
747
|
+
allowed: isAllowed,
|
|
748
|
+
defaultModel,
|
|
749
|
+
defaultEffort: entry.effort || detected.defaultEffort,
|
|
750
|
+
detectedModel: visibleDefault(detected.defaultModel),
|
|
751
|
+
detectedEffort: detected.defaultEffort,
|
|
752
|
+
note: entry.note ?? '',
|
|
753
|
+
rules: [...(effective.rules ?? []), ...(entry.rules ?? [])]
|
|
754
|
+
}
|
|
755
|
+
}))
|
|
756
|
+
this.observe(rows)
|
|
757
|
+
const workers = all
|
|
758
|
+
? rows
|
|
759
|
+
: rows.filter(w => w.allowed ? w.installed && (['ready', 'not-required'].includes(w.loginStatus) || w.tested) && w.models.length : w.installed)
|
|
760
|
+
const warnings = []
|
|
761
|
+
if (!all) {
|
|
762
|
+
for (const w of rows) {
|
|
763
|
+
if (!w.allowed || workers.includes(w)) continue
|
|
764
|
+
if (!w.installed || w.loginStatus === 'not-installed') {
|
|
765
|
+
warnings.push('Allowed bro ' + w.id + ' is not installed' + (w.install ? '; install: ' + w.install : '') + '.')
|
|
766
|
+
} else if (['signed-out', 'expired', 'missing', 'unavailable'].includes(w.loginStatus)) {
|
|
767
|
+
warnings.push('Allowed bro ' + w.id + ' is ' + w.loginStatus + (w.login ? '; run: ' + w.login : '') + '.')
|
|
768
|
+
} else if (hiddenAllByWorker.get(w.id)) {
|
|
769
|
+
warnings.push('Allowed bro ' + w.id + ' has no visible models (all detected models are hidden).')
|
|
770
|
+
} else if (!w.models.length) {
|
|
771
|
+
warnings.push('Allowed bro ' + w.id + ' reported no models' + (w.login ? '; check login: ' + w.login : '') + '.')
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
}
|
|
775
|
+
return {
|
|
776
|
+
projectId: project?.id ?? null,
|
|
777
|
+
defaultWorker: effective.worker ?? '',
|
|
778
|
+
concurrency: effective.concurrency ?? envConcurrency(),
|
|
779
|
+
rules: effective.rules ?? [],
|
|
780
|
+
workers,
|
|
781
|
+
...(warnings.length ? { warnings } : {}),
|
|
782
|
+
records: this.records().filter(r => r.role === 'write'),
|
|
783
|
+
picks: visiblePicks(catalog, workers),
|
|
784
|
+
effort_advice: catalog.effort_advice,
|
|
785
|
+
catalog: {
|
|
786
|
+
as_of: catalog.as_of,
|
|
787
|
+
source: catalog.source,
|
|
788
|
+
match_rule: catalog.match_rule,
|
|
789
|
+
stale_after_days: catalog.stale_after_days,
|
|
790
|
+
warnings: catalog.warnings
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
records() {
|
|
796
|
+
return summarize((this.projects.crews?.() ?? []).filter(Boolean).flatMap(crew => ticketRecords(crew.store)))
|
|
797
|
+
}
|
|
798
|
+
|
|
799
|
+
observe(rows) {
|
|
800
|
+
const native = rows.find(w => w.id === 'codex')?.quota
|
|
801
|
+
const crews = (this.projects.crews?.() ?? []).filter(Boolean)
|
|
802
|
+
for (const w of rows) {
|
|
803
|
+
if (w.allowed === false) continue
|
|
804
|
+
if (w.id === 'pi:openai-codex' && native) w.quota = { ...native, sharedWith: 'codex' }
|
|
805
|
+
let latest = null, recovered = 0
|
|
806
|
+
for (const crew of crews) {
|
|
807
|
+
const row = crew.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(w.id)
|
|
808
|
+
if (row && (!latest || row.finished > latest.finished)) latest = row
|
|
809
|
+
recovered = Math.max(recovered, crew.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(w.id).at)
|
|
810
|
+
}
|
|
811
|
+
if (!latest || recovered >= latest.finished) continue
|
|
812
|
+
const problem = JSON.parse(latest.problem), at = new Date(latest.finished).toISOString()
|
|
813
|
+
const fresh = problem.resetsAt ? Date.parse(problem.resetsAt) > Date.now() : Date.now() - latest.finished < 6 * 3600e3
|
|
814
|
+
if (!fresh || !['quota', 'region', 'auth'].includes(problem.class)) continue
|
|
815
|
+
if (problem.class === 'quota' && !w.quota) w.quota = { source: 'observed', class: 'quota', at, resetsAt: problem.resetsAt ?? null }
|
|
816
|
+
else if (problem.class !== 'quota' || !tight(w.quota)) w.recentProblem = { class: problem.class, at, message: problem.message.slice(0, 200) }
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
async trial(scope, raw, model, thinking) {
|
|
821
|
+
if (scope !== 'global') this.projects.get(scope)
|
|
822
|
+
const template = validateTemplate(raw)
|
|
823
|
+
if (!executable(template.command)) throw new Error('CLI is not installed: ' + template.command)
|
|
824
|
+
const base = join(home, 'template-tests')
|
|
825
|
+
mkdirSync(base, { recursive: true })
|
|
826
|
+
const cwd = mkdtempSync(join(base, 'trial-'))
|
|
827
|
+
execFileSync('git', ['init', '-q'], { cwd, stdio: 'ignore' })
|
|
828
|
+
const marker = join(cwd, 'owner'), controller = new AbortController()
|
|
829
|
+
const nonce = randomUUID()
|
|
830
|
+
let session, pid, known = []
|
|
831
|
+
const timer = setTimeout(() => { known = platform.owned(marker, [], pid); controller.abort() }, 120000)
|
|
832
|
+
const ctx = {
|
|
833
|
+
cwd,
|
|
834
|
+
marker,
|
|
835
|
+
signal: controller.signal,
|
|
836
|
+
template,
|
|
837
|
+
provider: 'custom:trial',
|
|
838
|
+
model: model || 'custom:trial',
|
|
839
|
+
thinking,
|
|
840
|
+
owner: id => { pid = id },
|
|
841
|
+
ready() {},
|
|
842
|
+
event() {},
|
|
843
|
+
bind: id => { if (session && session !== id) throw new Error('CLI resumed a different session'); session = id }
|
|
844
|
+
}
|
|
845
|
+
try {
|
|
846
|
+
const first = await templateTurn({ ...ctx, text: 'Do not use tools or read or change files. Remember the exact code ' + nonce + '. Reply only ACK.' })
|
|
847
|
+
if (!first || !session) throw new Error('New session extraction failed')
|
|
848
|
+
const reply = await templateTurn({ ...ctx, session, text: 'Without tools, repeat the exact code from my previous message. No other text.' })
|
|
849
|
+
if (!reply.includes(nonce)) throw new Error('Resumed session did not remember the first turn')
|
|
850
|
+
this.verified.set(scope + ':' + fingerprint(template), Date.now() + 15 * 60 * 1000)
|
|
851
|
+
return { status: 'passed', session, capability: 'degraded', expiresInSeconds: 900 }
|
|
852
|
+
} finally {
|
|
853
|
+
clearTimeout(timer)
|
|
854
|
+
const owned = platform.owned(marker, known, pid)
|
|
855
|
+
await platform.reap(marker, owned)
|
|
856
|
+
rmSync(cwd, { recursive: true, force: true })
|
|
857
|
+
}
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
propose(scope, worker, note) {
|
|
861
|
+
this.projects.get(scope)
|
|
862
|
+
if (!supportedWorker(worker)) throw new Error('Unknown worker')
|
|
863
|
+
label(note)
|
|
864
|
+
if (!note.trim()) throw new Error('Note is empty')
|
|
865
|
+
const id = randomUUID()
|
|
866
|
+
this.db.prepare('INSERT INTO note_proposals (id,scope,worker,note,created) VALUES (?,?,?,?,?)').run(id, scope, worker, note, Date.now())
|
|
867
|
+
return { id, status: 'pending-user-confirmation' }
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
proposeDefaults(scope, worker, input) {
|
|
871
|
+
this.projects.get(scope)
|
|
872
|
+
if (!supportedWorker(worker)) throw new Error('Unknown worker')
|
|
873
|
+
const defaults = {}
|
|
874
|
+
for (const key of ['model', 'effort']) if (input[key] !== undefined) {
|
|
875
|
+
defaults[key] = label(input[key]).trim()
|
|
876
|
+
if (!defaults[key]) throw new Error('Default ' + key + ' is empty')
|
|
877
|
+
}
|
|
878
|
+
if (!Object.keys(defaults).length) throw new Error('Supply --model and/or --effort')
|
|
879
|
+
const id = randomUUID()
|
|
880
|
+
this.db.prepare('INSERT INTO note_proposals (id,scope,worker,note,created,defaults) VALUES (?,?,?,?,?,?)').run(id, scope, worker, '', Date.now(), JSON.stringify(defaults))
|
|
881
|
+
return { id, status: 'pending-user-confirmation' }
|
|
882
|
+
}
|
|
883
|
+
|
|
884
|
+
resolveProposal(scope, id, accept) {
|
|
885
|
+
const proposal = this.db.prepare('SELECT * FROM note_proposals WHERE id=? AND scope=?').get(id, scope)
|
|
886
|
+
if (!proposal) throw new Error('Unknown proposal')
|
|
887
|
+
if (accept) {
|
|
888
|
+
const data = this.config(scope)
|
|
889
|
+
data.entries[proposal.worker] = { ...data.entries[proposal.worker], ...(proposal.defaults ? JSON.parse(proposal.defaults) : { note: proposal.note }) }
|
|
890
|
+
this.save(scope, data, 'user')
|
|
891
|
+
}
|
|
892
|
+
this.db.prepare('DELETE FROM note_proposals WHERE id=?').run(id)
|
|
893
|
+
return this.config(scope)
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
terminalCommand(id, action, scope) {
|
|
897
|
+
if (!['login', 'install', 'upgrade'].includes(action)) throw new Error('Unknown CLI action')
|
|
898
|
+
let command
|
|
899
|
+
if (id.startsWith('custom:')) {
|
|
900
|
+
const settings = scope === 'global' ? this.read('global') : this.effective(this.projects.get(scope))
|
|
901
|
+
const template = settings.entries?.[id]?.template ?? presets[id]
|
|
902
|
+
const args = template?.actions?.[action]
|
|
903
|
+
const quote = s => "'" + s.replaceAll("'", "'\\''") + "'"
|
|
904
|
+
command = args ? args.map(quote).join(' ') : cliActions[template?.command]?.[action]
|
|
905
|
+
} else command = cliActions[id]?.[action]
|
|
906
|
+
if (!command) throw new Error('No command configured for this CLI action')
|
|
907
|
+
return command
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
async terminal(id, action, cwd, scope) {
|
|
911
|
+
return platform.openTerminal(this.terminalCommand(id, action, scope), cwd)
|
|
912
|
+
}
|
|
913
|
+
}
|