@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
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process'
|
|
2
|
+
import { delimiter, join } from 'node:path'
|
|
3
|
+
import { promisify } from 'node:util'
|
|
4
|
+
import { attachmentDirs, claudeAttachments, formatAttachmentPrompt } from './attachments.mjs'
|
|
5
|
+
import { inspectCommand } from './cli-process.mjs'
|
|
6
|
+
import { modelEnvironment } from './model-env.mjs'
|
|
7
|
+
import { home, isolated } from './paths.mjs'
|
|
8
|
+
import { classify } from './problems.mjs'
|
|
9
|
+
import { HOST_SESSION_VARS, commandTurn, templateTurn } from './templates.mjs'
|
|
10
|
+
|
|
11
|
+
const exec = promisify(execFile)
|
|
12
|
+
const runtimePath = () => isolated ? [join(home, 'tools', 'bin'), process.env.PATH].filter(Boolean).join(delimiter) : process.env.PATH
|
|
13
|
+
const effortSuffix = /-(?:off|none|minimal|low|medium|high|extra-high|xhigh|max|ultra)$/
|
|
14
|
+
const commandHeader = /^(?:Created At:|Completed At:|Command exited with code\b|Command output:\s*$)/
|
|
15
|
+
|
|
16
|
+
let agyUsageCache = null
|
|
17
|
+
|
|
18
|
+
export function clearAgyUsageCache() {
|
|
19
|
+
agyUsageCache = null
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function cursorModel(model, effort, catalog = []) {
|
|
23
|
+
if (!effort) return model
|
|
24
|
+
if (model === 'cursor-agent') throw new Error('Choose an explicit Cursor model when selecting effort')
|
|
25
|
+
const match = /^([^\[\]]+)(?:\[([^\[\]]*)\])?$/.exec(model)
|
|
26
|
+
if (!match) throw new Error('Invalid Cursor model override')
|
|
27
|
+
if (!match[2]) {
|
|
28
|
+
const fast = model.endsWith('-fast') ? '-fast' : ''
|
|
29
|
+
const base = model.replace(/-fast$/, '').replace(/-(?:none|minimal|low|medium|high|xhigh|extra-high|max)$/, '')
|
|
30
|
+
const variant = base + '-' + effort + fast
|
|
31
|
+
if (catalog.includes(variant)) return variant
|
|
32
|
+
}
|
|
33
|
+
const options = (match[2]?.split(',') ?? []).filter(s => s && !s.startsWith('effort='))
|
|
34
|
+
return match[1] + '[' + [...options, 'effort=' + effort].join(',') + ']'
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function agyModel(model, effort, catalog = []) {
|
|
38
|
+
if (!model || model === 'agy') return { model: null, effortFlag: effort || null }
|
|
39
|
+
const base = model.replace(effortSuffix, '')
|
|
40
|
+
const isGeminiFamily = /^gemini-/i.test(base) && !/^gemini-pro-orchestrator\b/i.test(base)
|
|
41
|
+
if (effort) {
|
|
42
|
+
const variant = base + '-' + effort
|
|
43
|
+
if ((!catalog.length && (model !== base || isGeminiFamily)) || catalog.includes(variant)) {
|
|
44
|
+
return { model: variant, effortFlag: null }
|
|
45
|
+
}
|
|
46
|
+
if (catalog.includes(model)) return { model, effortFlag: effort }
|
|
47
|
+
if (model !== base || isGeminiFamily || catalog.some(id => id.startsWith(base + '-'))) {
|
|
48
|
+
return { model: variant, effortFlag: null }
|
|
49
|
+
}
|
|
50
|
+
return { model, effortFlag: effort }
|
|
51
|
+
}
|
|
52
|
+
if (catalog.length && !catalog.includes(model)) {
|
|
53
|
+
const picked = catalog.find(id => id === model + '-medium') ?? catalog.find(id => id.startsWith(model + '-')) ?? model
|
|
54
|
+
return { model: picked, effortFlag: null }
|
|
55
|
+
}
|
|
56
|
+
return { model, effortFlag: null }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function windowMinutes(window) {
|
|
60
|
+
if (window === '5h') return 300
|
|
61
|
+
if (window === 'weekly') return 10080
|
|
62
|
+
const hours = /^(\d+)h$/i.exec(window ?? '')
|
|
63
|
+
if (hours) return Number(hours[1]) * 60
|
|
64
|
+
const days = /^(\d+)d$/i.exec(window ?? '')
|
|
65
|
+
if (days) return Number(days[1]) * 1440
|
|
66
|
+
const mins = /^(\d+)m$/i.exec(window ?? '')
|
|
67
|
+
if (mins) return Number(mins[1])
|
|
68
|
+
return null
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function parseAgyUsage(raw, model = null) {
|
|
72
|
+
const rawGroups = raw?.command?.data?.groups ?? raw?.groups
|
|
73
|
+
if (!Array.isArray(rawGroups) || !rawGroups.length) return null
|
|
74
|
+
const groups = rawGroups.map(g => ({
|
|
75
|
+
name: g?.name ?? '',
|
|
76
|
+
windows: (g?.buckets ?? []).filter(b => b && Number.isFinite(b.remaining_fraction)).map(b => {
|
|
77
|
+
const usedPercent = Math.min(100, Math.max(0, Math.round((1 - b.remaining_fraction) * 1000) / 10))
|
|
78
|
+
const parsedReset = typeof b.reset_time === 'string' ? Date.parse(b.reset_time) : NaN
|
|
79
|
+
return {
|
|
80
|
+
id: b.id ?? null,
|
|
81
|
+
minutes: windowMinutes(b.window),
|
|
82
|
+
usedPercent,
|
|
83
|
+
resetsAt: Number.isFinite(parsedReset) ? new Date(parsedReset).toISOString() : null
|
|
84
|
+
}
|
|
85
|
+
})
|
|
86
|
+
})).filter(g => g.windows.length)
|
|
87
|
+
if (!groups.length) return null
|
|
88
|
+
const want3p = typeof model === 'string' && /^(?:claude|gpt)-/i.test(model)
|
|
89
|
+
const picked = (want3p ? groups.find(g => /claude|gpt|3p/i.test(g.name)) : groups.find(g => /gemini/i.test(g.name))) ?? groups[0]
|
|
90
|
+
const windows = picked.windows.map(({ minutes, usedPercent, resetsAt }) => ({ minutes, usedPercent, resetsAt }))
|
|
91
|
+
const reached = windows.some(w => w.usedPercent >= 100)
|
|
92
|
+
const avoid = reached || windows.some(w => w.usedPercent >= 90)
|
|
93
|
+
const plentiful = !avoid && windows.length > 0 && windows.every(w => w.usedPercent <= 25)
|
|
94
|
+
return { source: 'native', windows, groups, reached, avoid, plentiful, at: new Date().toISOString() }
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function parseJsonOutput(text) {
|
|
98
|
+
if (!text) return null
|
|
99
|
+
try { return JSON.parse(text) } catch {}
|
|
100
|
+
for (const line of text.trim().split('\n').reverse()) {
|
|
101
|
+
if (line.trim().startsWith('{')) {
|
|
102
|
+
try { return JSON.parse(line) } catch {}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
return null
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function fetchAgyUsageRaw(cwd, signal) {
|
|
109
|
+
if (signal?.aborted) return null
|
|
110
|
+
try {
|
|
111
|
+
const env = { ...modelEnvironment(), PATH: runtimePath(), NO_COLOR: '1', BROCO_IN_WORKER: '1' }
|
|
112
|
+
for (const key of HOST_SESSION_VARS) delete env[key]
|
|
113
|
+
const { stdout } = await exec('agy', ['-p', '/usage', '--output-format', 'json'], { cwd, env, timeout: 15000, maxBuffer: 1024 * 1024, signal })
|
|
114
|
+
return parseJsonOutput(stdout)
|
|
115
|
+
} catch { return null }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function readAgyUsage(cwd, model, signal, { fresh = false } = {}) {
|
|
119
|
+
if (signal?.aborted) return null
|
|
120
|
+
const key = runtimePath() + '\0' + cwd
|
|
121
|
+
if (fresh) {
|
|
122
|
+
agyUsageCache = null
|
|
123
|
+
const raw = await fetchAgyUsageRaw(cwd, signal)
|
|
124
|
+
return raw ? parseAgyUsage(raw, model) : null
|
|
125
|
+
}
|
|
126
|
+
const now = Date.now()
|
|
127
|
+
if (!agyUsageCache || agyUsageCache.key !== key || now >= agyUsageCache.expiresAt) {
|
|
128
|
+
const promise = fetchAgyUsageRaw(cwd, undefined)
|
|
129
|
+
agyUsageCache = { key, expiresAt: now + 3000, promise }
|
|
130
|
+
}
|
|
131
|
+
const raw = await agyUsageCache.promise
|
|
132
|
+
if (signal?.aborted) return null
|
|
133
|
+
return raw ? parseAgyUsage(raw, model) : null
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function toolTarget(params) {
|
|
137
|
+
if (!params || typeof params !== 'object') return ''
|
|
138
|
+
const raw = params.CommandLine ?? params.command ?? params.Path ?? params.file_path ?? params.path ?? params.notebook_path ?? params.TargetFile ?? params.target_file ?? params.DirectoryPath ?? params.SearchPath ?? params.SearchDirectory ?? params.Url ?? params.url ?? params.Query ?? params.query ?? params.Pattern ?? params.pattern ?? params.glob ?? params.description ?? ''
|
|
139
|
+
return typeof raw === 'string' ? raw.replace(/\s+/g, ' ').trim().slice(0, 120) : ''
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function sanitizeClaudeText(text) {
|
|
143
|
+
return String(text ?? '')
|
|
144
|
+
.replace(/\bBearer\s+\S+/gi, 'Bearer [redacted]')
|
|
145
|
+
.replace(/\bsk-ant-[A-Za-z0-9_-]{8,}\b/g, '[redacted]')
|
|
146
|
+
.trim()
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function claudeToolResultPreview(content) {
|
|
150
|
+
let text = ''
|
|
151
|
+
if (typeof content === 'string') text = content
|
|
152
|
+
else if (Array.isArray(content)) {
|
|
153
|
+
text = content
|
|
154
|
+
.filter(b => b && typeof b === 'object' && typeof b.text === 'string')
|
|
155
|
+
.map(b => b.text)
|
|
156
|
+
.join('\n')
|
|
157
|
+
}
|
|
158
|
+
if (!text) return ''
|
|
159
|
+
const lines = text.split(/\r?\n/).map(l => l.trim()).filter(Boolean)
|
|
160
|
+
return (lines.at(-1) ?? '').replace(/\s+/g, ' ').slice(0, 120)
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function claudeErrorDetail(e) {
|
|
164
|
+
const meta = [
|
|
165
|
+
Number.isSafeInteger(e?.api_error_status) ? 'HTTP ' + e.api_error_status : null,
|
|
166
|
+
typeof e?.api_error_type === 'string' && e.api_error_type ? e.api_error_type : null,
|
|
167
|
+
typeof e?.api_error_code === 'string' && e.api_error_code ? e.api_error_code : null
|
|
168
|
+
].filter(Boolean).join(' ')
|
|
169
|
+
let body = ''
|
|
170
|
+
if (typeof e?.result === 'string' && e.result.trim()) body = e.result.trim()
|
|
171
|
+
else if (Array.isArray(e?.errors) && e.errors.length) {
|
|
172
|
+
body = e.errors.map(x => typeof x === 'string' ? x.trim() : JSON.stringify(x)).filter(Boolean).join('; ')
|
|
173
|
+
} else if (Array.isArray(e?.message?.content)) {
|
|
174
|
+
body = e.message.content.filter(b => b?.type === 'text' && typeof b.text === 'string').map(b => b.text.trim()).filter(Boolean).join('\n')
|
|
175
|
+
} else if (typeof e?.error === 'string' && e.error.trim()) {
|
|
176
|
+
body = e.error.trim()
|
|
177
|
+
}
|
|
178
|
+
const parts = []
|
|
179
|
+
if (meta && (!body || !body.includes(meta))) parts.push(meta)
|
|
180
|
+
if (body) parts.push(body)
|
|
181
|
+
return sanitizeClaudeText(parts.join(': '))
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export function claudeResetEpoch(message = '') {
|
|
185
|
+
const text = String(message ?? '')
|
|
186
|
+
const pipeEpoch = /\|\s*(\d{10})\b/.exec(text)
|
|
187
|
+
if (pipeEpoch) {
|
|
188
|
+
const sec = Number(pipeEpoch[1])
|
|
189
|
+
if (Number.isSafeInteger(sec) && sec > 1700000000) return sec
|
|
190
|
+
}
|
|
191
|
+
const iso = /resets?\s+(?:at\s+)?(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2}))/i.exec(text)
|
|
192
|
+
if (iso) {
|
|
193
|
+
const ms = Date.parse(iso[1])
|
|
194
|
+
if (Number.isFinite(ms)) return Math.floor(ms / 1000)
|
|
195
|
+
}
|
|
196
|
+
return null
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function emitClaudeUsage(ctx, u) {
|
|
200
|
+
if (!u || typeof u !== 'object') return false
|
|
201
|
+
const input = Number.isSafeInteger(u.input_tokens) && u.input_tokens >= 0 ? u.input_tokens : null
|
|
202
|
+
const cacheRead = Number.isSafeInteger(u.cache_read_input_tokens) && u.cache_read_input_tokens >= 0 ? u.cache_read_input_tokens : null
|
|
203
|
+
const cacheCreate = Number.isSafeInteger(u.cache_creation_input_tokens) && u.cache_creation_input_tokens >= 0 ? u.cache_creation_input_tokens : 0
|
|
204
|
+
if (input === null) return false
|
|
205
|
+
const cached = cacheRead ?? 0
|
|
206
|
+
const total = input + cached + cacheCreate
|
|
207
|
+
if (total === 0 && cacheRead === null) return false
|
|
208
|
+
ctx.event('usage', {
|
|
209
|
+
cachedInputTokens: cached,
|
|
210
|
+
inputTokens: total,
|
|
211
|
+
cacheCreationInputTokens: cacheCreate
|
|
212
|
+
}, 'Claude reported cache usage')
|
|
213
|
+
return true
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function toolOutputPreview(info) {
|
|
217
|
+
if (!info || typeof info !== 'object') return ''
|
|
218
|
+
if (typeof info.error?.message === 'string' && info.error.message.trim()) {
|
|
219
|
+
return info.error.message.replace(/\s+/g, ' ').trim().slice(0, 120)
|
|
220
|
+
}
|
|
221
|
+
if (typeof info.output !== 'string' || !info.output) return ''
|
|
222
|
+
const lines = info.output
|
|
223
|
+
.split(/\r?\n/)
|
|
224
|
+
.map(l => l.trim())
|
|
225
|
+
.filter(l => l && !commandHeader.test(l))
|
|
226
|
+
const last = lines.at(-1) ?? ''
|
|
227
|
+
return last.replace(/\s+/g, ' ').slice(0, 120)
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export function resetEpoch(quota, message = '') {
|
|
231
|
+
const valid = [...(quota?.windows ?? [])].filter(w => w.resetsAt)
|
|
232
|
+
const exhausted = valid.filter(w => w.usedPercent >= 99).sort((a, b) => b.usedPercent - a.usedPercent)[0]
|
|
233
|
+
const explicitExhaustion = /(?<!disk )quota (?:exceeded|exhausted|reached)/i.test(String(message ?? ''))
|
|
234
|
+
const fallbackShort = explicitExhaustion
|
|
235
|
+
? valid.filter(w => (w.minutes ?? Infinity) <= 300 && w.usedPercent > 0).sort((a, b) => b.usedPercent - a.usedPercent)[0]
|
|
236
|
+
: null
|
|
237
|
+
const chosen = exhausted ?? fallbackShort
|
|
238
|
+
if (!chosen) return null
|
|
239
|
+
const ms = Date.parse(chosen.resetsAt)
|
|
240
|
+
return Number.isFinite(ms) ? Math.floor(ms / 1000) : null
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export async function streamTurn(ctx) {
|
|
244
|
+
if (ctx.provider.startsWith('custom:')) return templateTurn(ctx)
|
|
245
|
+
const agy = ctx.provider === 'agy'
|
|
246
|
+
const claude = ctx.provider === 'claude'
|
|
247
|
+
if (claude && ctx.attachments?.length) claudeAttachments(ctx.attachments)
|
|
248
|
+
if (!agy && !claude && ctx.attachments?.length) throw new Error('cursor-agent does not support media attachments')
|
|
249
|
+
let reply, completed = false, failure, resultError = '', sawUsage = false, lastQuota = null
|
|
250
|
+
let chosen = ctx.model
|
|
251
|
+
let resolved = { model: ctx.model === 'agy' ? null : ctx.model, effortFlag: ctx.thinking || null }
|
|
252
|
+
if (agy) {
|
|
253
|
+
let ids = []
|
|
254
|
+
const fastGemini = Boolean(ctx.model && /^gemini-(?!pro-orchestrator(?:$|-))/i.test(ctx.model) && (ctx.thinking || effortSuffix.test(ctx.model)))
|
|
255
|
+
if (ctx.model && ctx.model !== 'agy' && !fastGemini && (ctx.thinking || !effortSuffix.test(ctx.model))) {
|
|
256
|
+
const listed = await inspectCommand('agy', ['models'], ctx.cwd, ctx.signal)
|
|
257
|
+
ids = listed.text.split('\n').filter(l => /^\S+\t/.test(l)).map(l => l.split('\t')[0])
|
|
258
|
+
}
|
|
259
|
+
resolved = agyModel(ctx.model, ctx.thinking, ids)
|
|
260
|
+
} else if (!claude && ctx.thinking) {
|
|
261
|
+
const listed = await inspectCommand('cursor-agent', ['--list-models'], ctx.cwd, ctx.signal)
|
|
262
|
+
const ids = listed.text.split('\n').map(l => /^(\S+) - /.exec(l.trim())?.[1]).filter(Boolean)
|
|
263
|
+
chosen = cursorModel(ctx.model, ctx.thinking, ids)
|
|
264
|
+
}
|
|
265
|
+
const args = agy
|
|
266
|
+
? ['--input-format', 'text', '--output-format', 'stream-json']
|
|
267
|
+
: claude
|
|
268
|
+
? ['-p', '--output-format', 'stream-json', '--verbose']
|
|
269
|
+
: ['--print', '--output-format', 'stream-json']
|
|
270
|
+
if (ctx.session) args.push(agy ? '--conversation' : '--resume', ctx.session)
|
|
271
|
+
if (agy) {
|
|
272
|
+
if (resolved.model) args.push('--model', resolved.model)
|
|
273
|
+
if (resolved.effortFlag) args.push('--effort', resolved.effortFlag)
|
|
274
|
+
args.push('--mode', ctx.review ? 'plan' : 'accept-edits', '--disable-slash-commands')
|
|
275
|
+
for (const dir of attachmentDirs(ctx.attachments)) args.push('--add-dir', dir)
|
|
276
|
+
} else if (claude) {
|
|
277
|
+
if (ctx.model && ctx.model !== 'claude') args.push('--model', ctx.model)
|
|
278
|
+
if (ctx.thinking) args.push('--effort', ctx.thinking)
|
|
279
|
+
args.push('--permission-mode', ctx.review ? 'plan' : 'bypassPermissions')
|
|
280
|
+
for (const dir of attachmentDirs(ctx.attachments)) args.push('--add-dir', dir)
|
|
281
|
+
} else {
|
|
282
|
+
if (ctx.model !== ctx.provider) args.push('--model', chosen)
|
|
283
|
+
args.push('--trust', ...(ctx.review ? ['--mode', 'plan'] : ['--force']), '--', ctx.text)
|
|
284
|
+
}
|
|
285
|
+
const promptInput = agy
|
|
286
|
+
? formatAttachmentPrompt(ctx.text, ctx.attachments, 'read_file')
|
|
287
|
+
: claude
|
|
288
|
+
? formatAttachmentPrompt(ctx.text, ctx.attachments, 'Read')
|
|
289
|
+
: ''
|
|
290
|
+
let beforeRecorded = false
|
|
291
|
+
const recordBefore = before => {
|
|
292
|
+
if (before && !beforeRecorded) {
|
|
293
|
+
beforeRecorded = true
|
|
294
|
+
if (!lastQuota) lastQuota = before
|
|
295
|
+
ctx.event('quota', before, '')
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
const beforePromise = agy ? readAgyUsage(ctx.cwd, resolved.model, ctx.signal).then(recordBefore, () => {}) : null
|
|
299
|
+
const seenActiveResponse = new Set()
|
|
300
|
+
const claudeTools = new Map()
|
|
301
|
+
const seenClaudeSteps = new Set()
|
|
302
|
+
let claudeBound = null, lastAssistantText = '', lastApiError = ''
|
|
303
|
+
let turnError = null
|
|
304
|
+
try {
|
|
305
|
+
await commandTurn(ctx, ctx.provider, args, promptInput, e => {
|
|
306
|
+
if (agy) {
|
|
307
|
+
if (e.event === 'init') ctx.bind(e.conversation_id, 'stream-json')
|
|
308
|
+
if (e.step_update) {
|
|
309
|
+
const s = e.step_update
|
|
310
|
+
if (s.step_type === 'agent_response') {
|
|
311
|
+
if (s.state === 'ACTIVE') {
|
|
312
|
+
if (!seenActiveResponse.has(s.step_index)) {
|
|
313
|
+
seenActiveResponse.add(s.step_index)
|
|
314
|
+
ctx.event('tool.started', { step: s.step_index, type: 'agent_response' }, 'Writing reply')
|
|
315
|
+
}
|
|
316
|
+
} else if (s.state === 'DONE') {
|
|
317
|
+
ctx.event('tool.completed', { step: s.step_index, type: 'agent_response', durationSeconds: s.duration_seconds ?? null }, '')
|
|
318
|
+
}
|
|
319
|
+
} else if (s.step_type === 'tool') {
|
|
320
|
+
const name = s.tool_name || s.tool_info?.name || 'tool'
|
|
321
|
+
const target = toolTarget(s.tool_info?.parameters)
|
|
322
|
+
const done = s.state === 'DONE' || s.state === 'ERROR'
|
|
323
|
+
const failed = s.state === 'ERROR' || !!s.tool_info?.error
|
|
324
|
+
const outputPreview = done ? toolOutputPreview(s.tool_info) : ''
|
|
325
|
+
const dur = done && typeof s.duration_seconds === 'number' && Number.isFinite(s.duration_seconds) ? ' (' + s.duration_seconds.toFixed(1) + 's)' : ''
|
|
326
|
+
const tail = outputPreview || target
|
|
327
|
+
const summary = done
|
|
328
|
+
? name + (failed ? ' error' : ' done') + dur + (tail ? ': ' + tail : '')
|
|
329
|
+
: name + (target ? ': ' + target : '')
|
|
330
|
+
ctx.event(done ? 'tool.completed' : 'tool.started', {
|
|
331
|
+
step: s.step_index,
|
|
332
|
+
type: 'tool',
|
|
333
|
+
tool: name,
|
|
334
|
+
target,
|
|
335
|
+
outputPreview,
|
|
336
|
+
durationSeconds: s.duration_seconds ?? null
|
|
337
|
+
}, summary)
|
|
338
|
+
} else if (s.step_type && s.step_type !== 'user_input' && s.step_type !== 'system_message') {
|
|
339
|
+
ctx.event(s.state === 'DONE' ? 'tool.completed' : 'tool.started', { step: s.step_index, type: s.step_type }, [s.step_type, s.state].filter(Boolean).join(' '))
|
|
340
|
+
}
|
|
341
|
+
const u = s.usage
|
|
342
|
+
if (s.state === 'DONE' && Number.isSafeInteger(u?.cache_read_tokens) && Number.isSafeInteger(u.input_tokens)) {
|
|
343
|
+
sawUsage = true
|
|
344
|
+
ctx.event('usage', { cachedInputTokens: u.cache_read_tokens, inputTokens: u.input_tokens + u.cache_read_tokens }, 'agy reported cache usage')
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
if (e.event === 'result') {
|
|
348
|
+
if (e.result?.conversation_id) ctx.bind(e.result.conversation_id, 'stream-json')
|
|
349
|
+
completed = true
|
|
350
|
+
reply = e.result?.response
|
|
351
|
+
const u = e.result?.usage
|
|
352
|
+
if (!sawUsage && Number.isSafeInteger(u?.cache_read_tokens) && Number.isSafeInteger(u.input_tokens)) {
|
|
353
|
+
sawUsage = true
|
|
354
|
+
ctx.event('usage', { cachedInputTokens: u.cache_read_tokens, inputTokens: u.input_tokens + u.cache_read_tokens }, 'agy reported cache usage')
|
|
355
|
+
}
|
|
356
|
+
if (e.result?.status !== 'SUCCESS') {
|
|
357
|
+
resultError = typeof e.result?.error === 'string' ? e.result.error.trim() : ''
|
|
358
|
+
failure = resultError ? 'agy turn failed: ' + resultError : 'agy turn did not succeed'
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
} else if (claude) {
|
|
362
|
+
if (typeof e.session_id === 'string' && e.session_id && e.session_id !== claudeBound) {
|
|
363
|
+
ctx.bind(e.session_id, 'stream-json')
|
|
364
|
+
claudeBound = e.session_id
|
|
365
|
+
}
|
|
366
|
+
if (e.type === 'assistant') {
|
|
367
|
+
if (e.is_api_error_message) {
|
|
368
|
+
const detail = claudeErrorDetail(e)
|
|
369
|
+
if (detail) lastApiError = detail
|
|
370
|
+
} else {
|
|
371
|
+
const blocks = Array.isArray(e.message?.content) ? e.message.content : []
|
|
372
|
+
const msgId = e.message?.id || e.uuid || 'msg'
|
|
373
|
+
const textParts = []
|
|
374
|
+
for (const block of blocks) {
|
|
375
|
+
if (!block || typeof block !== 'object') continue
|
|
376
|
+
if (block.type === 'tool_use') {
|
|
377
|
+
const name = block.name || 'tool'
|
|
378
|
+
const target = toolTarget(block.input)
|
|
379
|
+
if (block.id) claudeTools.set(block.id, { name, target })
|
|
380
|
+
ctx.event('tool.started', { id: block.id ?? null, type: 'tool', tool: name, target }, name + (target ? ': ' + target : ''))
|
|
381
|
+
} else if (block.type === 'thinking') {
|
|
382
|
+
const key = msgId + ':thinking'
|
|
383
|
+
if (!seenClaudeSteps.has(key)) {
|
|
384
|
+
seenClaudeSteps.add(key)
|
|
385
|
+
ctx.event('tool.started', { type: 'thinking' }, 'Thinking')
|
|
386
|
+
}
|
|
387
|
+
} else if (block.type === 'text' && typeof block.text === 'string' && block.text) {
|
|
388
|
+
textParts.push(block.text)
|
|
389
|
+
const key = msgId + ':text'
|
|
390
|
+
if (!seenClaudeSteps.has(key)) {
|
|
391
|
+
seenClaudeSteps.add(key)
|
|
392
|
+
ctx.event('tool.started', { type: 'agent_response' }, 'Writing reply')
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
if (textParts.length) lastAssistantText = textParts.join('')
|
|
397
|
+
if (emitClaudeUsage(ctx, e.message?.usage)) sawUsage = true
|
|
398
|
+
}
|
|
399
|
+
} else if (e.type === 'user') {
|
|
400
|
+
const blocks = Array.isArray(e.message?.content) ? e.message.content : []
|
|
401
|
+
for (const block of blocks) {
|
|
402
|
+
if (!block || block.type !== 'tool_result') continue
|
|
403
|
+
const info = claudeTools.get(block.tool_use_id) ?? { name: 'tool', target: '' }
|
|
404
|
+
const outputPreview = claudeToolResultPreview(block.content)
|
|
405
|
+
const tail = outputPreview || info.target
|
|
406
|
+
const summary = info.name + (block.is_error ? ' error' : ' done') + (tail ? ': ' + tail : '')
|
|
407
|
+
ctx.event('tool.completed', {
|
|
408
|
+
id: block.tool_use_id ?? null,
|
|
409
|
+
type: 'tool',
|
|
410
|
+
tool: info.name,
|
|
411
|
+
target: info.target,
|
|
412
|
+
outputPreview,
|
|
413
|
+
isError: !!block.is_error
|
|
414
|
+
}, summary)
|
|
415
|
+
}
|
|
416
|
+
} else if (e.type === 'result') {
|
|
417
|
+
completed = true
|
|
418
|
+
if (e.is_error || (e.subtype && e.subtype !== 'success')) {
|
|
419
|
+
resultError = claudeErrorDetail(e) || lastApiError
|
|
420
|
+
failure = resultError ? 'claude turn failed: ' + resultError : 'claude turn did not succeed'
|
|
421
|
+
} else {
|
|
422
|
+
reply = typeof e.result === 'string' && e.result ? e.result : lastAssistantText
|
|
423
|
+
if (!sawUsage && emitClaudeUsage(ctx, e.usage)) sawUsage = true
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
} else {
|
|
427
|
+
if (e.session_id) ctx.bind(e.session_id, 'stream-json')
|
|
428
|
+
if (e.type === 'tool_call') {
|
|
429
|
+
const tool = e.tool_call?.name || Object.keys(e.tool_call ?? {}).find(k => k.endsWith('ToolCall')) || 'tool'
|
|
430
|
+
ctx.event(e.subtype === 'completed' ? 'tool.completed' : 'tool.started', { tool }, 'Cursor ' + tool + ' ' + (e.subtype || 'running'))
|
|
431
|
+
}
|
|
432
|
+
if (e.type === 'result') {
|
|
433
|
+
completed = true
|
|
434
|
+
reply = e.result
|
|
435
|
+
if (e.is_error || e.subtype !== 'success') failure = 'Cursor turn did not succeed'
|
|
436
|
+
const u = e.usage
|
|
437
|
+
if (Number.isSafeInteger(u?.cache_read_input_tokens) && Number.isSafeInteger(u.input_tokens)) ctx.event('usage', { cachedInputTokens: u.cache_read_input_tokens, inputTokens: u.input_tokens + u.cache_read_input_tokens + (u.cache_creation_input_tokens ?? 0) }, 'Cursor reported cache usage')
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
})
|
|
441
|
+
} catch (err) {
|
|
442
|
+
const apiErr = resultError || lastApiError
|
|
443
|
+
turnError = apiErr && !err.message.includes(apiErr) ? new Error(err.message + ': ' + apiErr) : err
|
|
444
|
+
} finally {
|
|
445
|
+
if (beforePromise) await beforePromise
|
|
446
|
+
if (agy && !ctx.signal.aborted) {
|
|
447
|
+
const after = await readAgyUsage(ctx.cwd, resolved.model, ctx.signal, { fresh: true })
|
|
448
|
+
if (after) { lastQuota = after; ctx.event('quota', after, '') }
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
const finalFailure = turnError?.message || (!completed || !reply || failure ? (failure || 'CLI returned no final result') : '')
|
|
452
|
+
if (finalFailure) {
|
|
453
|
+
const err = turnError ?? new Error(finalFailure)
|
|
454
|
+
if (agy && lastQuota) {
|
|
455
|
+
const prob = classify(err.message)
|
|
456
|
+
if (prob.class === 'quota') err.problem = classify(err.message, { resetsAt: resetEpoch(lastQuota, err.message) })
|
|
457
|
+
} else if (claude) {
|
|
458
|
+
const prob = classify(err.message)
|
|
459
|
+
err.problem = prob.class === 'quota' ? classify(err.message, { resetsAt: claudeResetEpoch(err.message) }) : prob
|
|
460
|
+
}
|
|
461
|
+
throw err
|
|
462
|
+
}
|
|
463
|
+
return reply
|
|
464
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process'
|
|
2
|
+
import { closeSync, mkdirSync, openSync } from 'node:fs'
|
|
3
|
+
import { delimiter, dirname, join } from 'node:path'
|
|
4
|
+
import { createInterface } from 'node:readline'
|
|
5
|
+
import { modelEnvironment } from './model-env.mjs'
|
|
6
|
+
import { home, isolated } from './paths.mjs'
|
|
7
|
+
import { mask, parseRedactedJson, redactStderr, secretsFrom } from './pi-secrets.mjs'
|
|
8
|
+
|
|
9
|
+
const runtimePath = () => isolated ? [join(home, 'tools', 'bin'), process.env.PATH].filter(Boolean).join(delimiter) : process.env.PATH
|
|
10
|
+
|
|
11
|
+
export const HOST_SESSION_VARS = [
|
|
12
|
+
'CLAUDECODE',
|
|
13
|
+
'CLAUDE_CODE_ENTRYPOINT',
|
|
14
|
+
'CLAUDE_CODE_SSE_PORT',
|
|
15
|
+
'CLAUDE_CODE_SESSION_ID',
|
|
16
|
+
'CLAUDE_CODE_PARENT_SESSION_ID',
|
|
17
|
+
'CLAUDE_CODE_AGENT_ID',
|
|
18
|
+
'CODEX_THREAD_ID',
|
|
19
|
+
'CODEX_INTERNAL_ORIGINATOR_OVERRIDE',
|
|
20
|
+
'AI_AGENT',
|
|
21
|
+
'PI_CODING_AGENT',
|
|
22
|
+
'PI_SESSION_ID',
|
|
23
|
+
'PI_SESSION_FILE',
|
|
24
|
+
'PI_PROVIDER',
|
|
25
|
+
'PI_MODEL',
|
|
26
|
+
'PI_REASONING_LEVEL'
|
|
27
|
+
]
|
|
28
|
+
|
|
29
|
+
const pathValue = (obj, path) => path.split('.').reduce((v, key) => v?.[key], obj)
|
|
30
|
+
const clean = (s, what) => { if (typeof s !== 'string' || !s || s.length > 12000 || s.includes('\0')) throw new Error('Invalid ' + what); return s }
|
|
31
|
+
const array = (a, what) => { if (!Array.isArray(a) || a.length > 100) throw new Error('Expected argument array: ' + what); return a.map(v => clean(v, what)) }
|
|
32
|
+
const placeholders = new Set(['prompt', 'session', 'model', 'effort', 'cwd'])
|
|
33
|
+
|
|
34
|
+
export function validateTemplate(raw) {
|
|
35
|
+
if (!raw || typeof raw !== 'object') throw new Error('Expected a CLI template')
|
|
36
|
+
const t = { command: clean(raw.command, 'command'), newArgs: array(raw.newArgs, 'newArgs'), resumeArgs: array(raw.resumeArgs, 'resumeArgs'),
|
|
37
|
+
modelArgs: array(raw.modelArgs ?? [], 'modelArgs'), effortArgs: array(raw.effortArgs ?? [], 'effortArgs'), stdin: raw.stdin ?? '', format: raw.format ?? 'jsonl', reply: raw.reply, session: raw.session }
|
|
38
|
+
if (raw.versionArgs) t.versionArgs = array(raw.versionArgs, 'versionArgs')
|
|
39
|
+
if (raw.actions) {
|
|
40
|
+
t.actions = {}
|
|
41
|
+
for (const key of ['install', 'upgrade', 'login']) if (raw.actions[key]) {
|
|
42
|
+
t.actions[key] = array(raw.actions[key], 'actions.' + key)
|
|
43
|
+
if (!t.actions[key].length) throw new Error('Action needs an executable')
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
if (/[\r\n{}]/.test(t.command) || (!t.command.includes('/') && /\s/.test(t.command))) throw new Error('Command is one executable path, not a shell expression')
|
|
47
|
+
if (!['json', 'jsonl', 'text'].includes(t.format)) throw new Error('Expected json, jsonl or text output')
|
|
48
|
+
if (typeof t.stdin !== 'string') throw new Error('Expected stdin text')
|
|
49
|
+
for (const s of [...t.newArgs, ...t.resumeArgs, ...t.modelArgs, ...t.effortArgs, t.stdin]) {
|
|
50
|
+
for (const m of s.matchAll(/\{([^{}]+)\}/g)) if (!placeholders.has(m[1])) throw new Error('Unknown placeholder: ' + m[0])
|
|
51
|
+
}
|
|
52
|
+
if (!t.resumeArgs.some(s => s.includes('{session}'))) throw new Error('resumeArgs must contain {session}')
|
|
53
|
+
if (![...t.newArgs, t.stdin].some(s => s.includes('{prompt}')) || ![...t.resumeArgs, t.stdin].some(s => s.includes('{prompt}'))) throw new Error('Both commands must receive {prompt}')
|
|
54
|
+
for (const field of ['reply', 'session']) {
|
|
55
|
+
const s = t[field]
|
|
56
|
+
if (!s || typeof s !== 'object') throw new Error('Missing ' + field + ' extractor')
|
|
57
|
+
if (t.format === 'text') {
|
|
58
|
+
clean(s.regex, field + '.regex')
|
|
59
|
+
if (s.regex.length > 500) throw new Error('Extractor regex is too long')
|
|
60
|
+
new RegExp(s.regex, 'm')
|
|
61
|
+
t[field] = { regex: s.regex }
|
|
62
|
+
} else {
|
|
63
|
+
clean(s.path, field + '.path')
|
|
64
|
+
if (!/^[\w.-]+$/.test(s.path)) throw new Error('Use a dotted JSON path')
|
|
65
|
+
const when = s.when ?? {}
|
|
66
|
+
if (typeof when !== 'object' || Array.isArray(when) || Object.keys(when).length > 10) throw new Error('Invalid extractor condition')
|
|
67
|
+
if (Object.values(when).some(v => !['string', 'boolean', 'number'].includes(typeof v))) throw new Error('Extractor conditions must be scalar')
|
|
68
|
+
t[field] = { path: s.path, when }
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return t
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function templateArgs(t, ctx) {
|
|
75
|
+
const vars = { prompt: ctx.text, session: ctx.session ?? '', model: ctx.model === ctx.provider ? '' : ctx.model, effort: ctx.thinking ?? '', cwd: ctx.cwd }
|
|
76
|
+
const render = s => s.replace(/\{(prompt|session|model|effort|cwd)\}/g, (_, key) => vars[key])
|
|
77
|
+
const args = [...(ctx.session ? t.resumeArgs : t.newArgs), ...(vars.model ? t.modelArgs : []), ...(vars.effort ? t.effortArgs : [])].map(render)
|
|
78
|
+
return { args, input: render(t.stdin) }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function extract(record, selector, compiledRegex = null) {
|
|
82
|
+
if (selector.regex) return (compiledRegex ?? new RegExp(selector.regex, 'm')).exec(record)?.[1]
|
|
83
|
+
if (!Object.entries(selector.when).every(([k, v]) => pathValue(record, k) === v)) return undefined
|
|
84
|
+
return pathValue(record, selector.path)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
export async function commandTurn(ctx, command, args, input, receive, format = 'jsonl') {
|
|
88
|
+
mkdirSync(dirname(ctx.marker), { recursive: true })
|
|
89
|
+
const fd = openSync(ctx.marker, 'a', 0o600)
|
|
90
|
+
let child, failure, killer, size = 0, buffer = '', stderr = ''
|
|
91
|
+
const env = { ...modelEnvironment(), PATH: runtimePath(), BROCO_IN_WORKER: '1' }
|
|
92
|
+
for (const key of HOST_SESSION_VARS) delete env[key]
|
|
93
|
+
const rawSecrets = secretsFrom([], env)
|
|
94
|
+
try { child = spawn(command, args, { cwd: ctx.cwd, env, stdio: ['pipe', 'pipe', 'pipe', fd], signal: ctx.signal }) }
|
|
95
|
+
finally { closeSync(fd) }
|
|
96
|
+
ctx.owner(child.pid ?? null)
|
|
97
|
+
ctx.ready(null)
|
|
98
|
+
const force = () => {
|
|
99
|
+
if (!killer) {
|
|
100
|
+
killer = setTimeout(() => child.kill('SIGKILL'), 1500)
|
|
101
|
+
killer.unref?.()
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
ctx.signal.addEventListener('abort', force, { once: true })
|
|
105
|
+
if (ctx.signal.aborted) force()
|
|
106
|
+
child.on('error', () => { failure = new Error('CLI could not run or was stopped: ' + command) })
|
|
107
|
+
child.stdin.on('error', () => {})
|
|
108
|
+
child.stderr.on('data', part => { stderr = (stderr + part.toString('utf8')).slice(-4096) })
|
|
109
|
+
const consume = line => {
|
|
110
|
+
if (!line.trim() || failure) return
|
|
111
|
+
let record
|
|
112
|
+
try { record = format === 'text' ? mask(line, rawSecrets) : parseRedactedJson(line, rawSecrets) }
|
|
113
|
+
catch { failure = new Error('CLI output did not match its expected protocol'); child.kill(); force(); return }
|
|
114
|
+
try { receive(record) }
|
|
115
|
+
catch (err) { failure = err; child.kill(); force() }
|
|
116
|
+
}
|
|
117
|
+
child.stdout.on('data', data => {
|
|
118
|
+
size += data.length
|
|
119
|
+
if (size > 16 * 1024 * 1024) { failure = new Error('CLI output exceeded 16 MiB'); child.kill(); force() }
|
|
120
|
+
if (format !== 'jsonl') buffer += data.toString()
|
|
121
|
+
})
|
|
122
|
+
const lines = format === 'jsonl' ? createInterface({ input: child.stdout, crlfDelay: Infinity }) : null
|
|
123
|
+
lines?.on('line', consume)
|
|
124
|
+
const drained = lines ? new Promise(ok => lines.once('close', ok)) : Promise.resolve()
|
|
125
|
+
let drainTimer
|
|
126
|
+
const exited = new Promise(ok => child.once('exit', code => {
|
|
127
|
+
drainTimer = setTimeout(() => {
|
|
128
|
+
lines?.close()
|
|
129
|
+
child.stdout?.destroy()
|
|
130
|
+
child.stderr?.destroy()
|
|
131
|
+
ok(code)
|
|
132
|
+
}, 1500)
|
|
133
|
+
drainTimer.unref?.()
|
|
134
|
+
}))
|
|
135
|
+
const closed = new Promise(ok => child.once('close', ok))
|
|
136
|
+
child.stdin.end(input)
|
|
137
|
+
const code = await Promise.race([
|
|
138
|
+
Promise.all([closed, drained]).then(([c]) => c),
|
|
139
|
+
exited
|
|
140
|
+
])
|
|
141
|
+
clearTimeout(drainTimer)
|
|
142
|
+
lines?.close()
|
|
143
|
+
clearTimeout(killer)
|
|
144
|
+
ctx.signal.removeEventListener('abort', force)
|
|
145
|
+
if (format !== 'jsonl' && !failure) consume(buffer)
|
|
146
|
+
if (failure) throw failure
|
|
147
|
+
if (code !== 0) {
|
|
148
|
+
const detail = redactStderr(stderr, env, rawSecrets)
|
|
149
|
+
throw new Error(command + ' exited with status ' + code + (detail ? ': ' + detail : ''))
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function templateTurn(ctx) {
|
|
154
|
+
const t = validateTemplate(ctx.template)
|
|
155
|
+
const { args, input } = templateArgs(t, ctx)
|
|
156
|
+
const sessionRegex = t.session.regex ? new RegExp(t.session.regex, 'm') : null
|
|
157
|
+
const replyRegex = t.reply.regex ? new RegExp(t.reply.regex, 'm') : null
|
|
158
|
+
let reply, session
|
|
159
|
+
ctx.event('cli.start', {}, 'Custom CLI running; detailed steps and cache are unavailable')
|
|
160
|
+
await commandTurn(ctx, t.command, args, input, record => {
|
|
161
|
+
const id = extract(record, t.session, sessionRegex), text = extract(record, t.reply, replyRegex)
|
|
162
|
+
if (typeof id === 'string' && id) { session = id; ctx.bind(id, 'template') }
|
|
163
|
+
if (typeof text === 'string' && text) reply = text
|
|
164
|
+
}, t.format)
|
|
165
|
+
if (!session || !reply) throw new Error('Template did not extract a session ID and final reply')
|
|
166
|
+
return reply
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export const presets = {
|
|
170
|
+
'custom:codex-json': { command: 'codex', newArgs: ['exec', '--json', '-'], resumeArgs: ['exec', 'resume', '--json', '{session}', '-'], modelArgs: ['--model', '{model}'], effortArgs: ['-c', 'model_reasoning_effort="{effort}"'], stdin: '{prompt}', format: 'jsonl', reply: { path: 'item.text', when: { type: 'item.completed', 'item.type': 'agent_message' } }, session: { path: 'thread_id', when: { type: 'thread.started' } } },
|
|
171
|
+
'custom:gemini': { command: 'gemini', newArgs: ['--output-format', 'stream-json', '-p', '{prompt}'], resumeArgs: ['--output-format', 'stream-json', '--resume', '{session}', '-p', '{prompt}'], modelArgs: ['--model', '{model}'], format: 'jsonl', reply: { path: 'content', when: { type: 'message', role: 'assistant' } }, session: { path: 'session_id', when: { type: 'init' } } },
|
|
172
|
+
'custom:opencode': { command: 'opencode', newArgs: ['run', '--format', 'json', '{prompt}'], resumeArgs: ['run', '--format', 'json', '--session', '{session}', '{prompt}'], modelArgs: ['--model', '{model}'], effortArgs: ['--variant', '{effort}'], format: 'jsonl', reply: { path: 'part.text', when: { type: 'text' } }, session: { path: 'sessionID', when: { type: 'text' } } }
|
|
173
|
+
}
|
package/lib/time.mjs
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
function validTimeZone(candidate) {
|
|
2
|
+
if (!candidate || typeof candidate !== 'string') return null
|
|
3
|
+
try {
|
|
4
|
+
new Intl.DateTimeFormat('en-US', { timeZone: candidate })
|
|
5
|
+
return candidate
|
|
6
|
+
} catch {
|
|
7
|
+
return null
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export function resolvedTimeZone(timeZone) {
|
|
12
|
+
return validTimeZone(timeZone)
|
|
13
|
+
|| validTimeZone(process.env.BROCO_TZ)
|
|
14
|
+
|| validTimeZone(process.env.TZ)
|
|
15
|
+
|| validTimeZone(Intl.DateTimeFormat().resolvedOptions().timeZone)
|
|
16
|
+
|| 'UTC'
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function formatDateTime(value = Date.now(), timeZone) {
|
|
20
|
+
return new Date(value).toLocaleString('sv-SE', { timeZone: resolvedTimeZone(timeZone), hour12: false })
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function formatShortTime(value = Date.now(), timeZone) {
|
|
24
|
+
return formatDateTime(value, timeZone).slice(5, 16)
|
|
25
|
+
}
|