@heretek-ai/opencode-teamwork-v2 0.0.0-stage → 0.5.10

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.
@@ -0,0 +1,517 @@
1
+ #!/usr/bin/env node
2
+ // @heretek-ai/opencode-teamwork-v2 — installer CLI
3
+ //
4
+ // opencode-teamwork init pick models + install agents + register plugin
5
+ // opencode-teamwork models pick models + reinstall agents (no config edit)
6
+ // opencode-teamwork install non-interactive install using defaults/flags
7
+ // opencode-teamwork status show what is currently configured
8
+ // opencode-teamwork help
9
+
10
+ import { existsSync, lstatSync, readFileSync, realpathSync, writeFileSync } from "node:fs"
11
+ import { tmpdir } from "node:os"
12
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"
13
+ import {
14
+ PACKAGE_NAME,
15
+ TEAM_AGENTS,
16
+ resolveConfigDir,
17
+ readModelMap,
18
+ readRawModelMap,
19
+ writeModelMap,
20
+ installAgents,
21
+ registerPlugin,
22
+ currentModels,
23
+ findConfigFile,
24
+ stripJsonComments,
25
+ modelMapPath,
26
+ } from "../lib/team.mjs"
27
+ import { detectAvailableModels, pickModels, applyOverrides } from "../lib/picker.mjs"
28
+ import { listTeamworkRuns, inspectTeamworkRun, pruneTeamworkWorktrees } from "../lib/runs.mjs"
29
+ import { runDoctor, nextSteps } from "../lib/doctor.mjs"
30
+ import { buildTimeline, renderTimeline, timelineWarnings } from "../lib/timeline.mjs"
31
+ import { buildExportData, renderExport } from "../lib/export.mjs"
32
+
33
+ // Echo a user-supplied value in an error message: control characters become "?"
34
+ // and the value is capped, so a hostile argv cannot inject escapes or bloat stderr.
35
+ function safeEcho(value, max = 64) {
36
+ const shown = String(value ?? "").replace(/[\x00-\x1f\x7f-\x9f]/g, "?")
37
+ return shown.length > max ? `${shown.slice(0, max)}...` : shown
38
+ }
39
+
40
+ const HELP = `@heretek-ai/opencode-teamwork-v2
41
+
42
+ Usage: opencode-teamwork <command> [options]
43
+
44
+ Commands:
45
+ init Pick a model for each team agent, install agents, register the plugin
46
+ models Same as init but never edits opencode.json
47
+ install Non-interactive install using defaults / flags
48
+ status Show config dir, model map, installed agents and plugin state
49
+ runs List active and past Teamwork runs in .opencode/teamwork/
50
+ inspect Inspect DAG, task progress, security report and costs for a run
51
+ timeline Show per-task lifecycle timing, rounds, and cost for a run (--json for raw data)
52
+ export Render a run as an offline HTML report (default) or Markdown (-m)
53
+ prune Prune git worktrees for completed Teamwork runs
54
+ doctor Diagnose config, agents, model sync and git/worktree health
55
+ help Show this help
56
+
57
+ Options:
58
+ -y, --yes Accept current/default models without prompting
59
+ --all <model> Use one model for every agent (e.g. anthropic/claude-sonnet-4-5)
60
+ --model <id>=<m> Override one agent (repeatable), id may omit the "team/" prefix
61
+ --session <id> Target a specific session ID (for inspect, prune or export)
62
+ --json Print doctor or timeline output as raw JSON
63
+ --html Export as HTML (default for export)
64
+ -m, --markdown Export as Markdown (for export)
65
+ -o, --output <file> Export destination (for export); "-" streams to stdout
66
+ Default: .opencode/teamwork/<id>/report.html (or report.md)
67
+ --no-color Disable ANSI colours (for timeline)
68
+ --no-register Don't touch opencode.json(c)
69
+ --refresh Overwrite agent prompt bodies with the shipped versions
70
+ (keeps your model choices; backs up the old files)
71
+ --config-dir <dir> Override the OpenCode config directory
72
+ --dry-run Print what would change without writing files
73
+ -h, --help Show this help
74
+ `
75
+
76
+ function parseArgs(argv) {
77
+ const options = { command: undefined, yes: false, all: undefined, assignments: {}, register: true, dryRun: false, refresh: false, configDir: undefined, session: undefined, json: false, noColor: false, help: false, markdown: false, output: undefined }
78
+ const rest = [...argv]
79
+ options.command = rest.shift()
80
+ while (rest.length) {
81
+ const arg = rest.shift()
82
+ switch (arg) {
83
+ case "-y":
84
+ case "--yes":
85
+ options.yes = true
86
+ break
87
+ case "--all":
88
+ options.all = rest.shift() || true
89
+ break
90
+ case "--session":
91
+ options.session = rest.shift()
92
+ break
93
+ case "--model": {
94
+ const pair = rest.shift() || ""
95
+ const eq = pair.indexOf("=")
96
+ if (eq > 0) options.assignments[pair.slice(0, eq).trim()] = pair.slice(eq + 1).trim()
97
+ else console.warn(`Ignoring malformed --model "${pair}" (expected id=provider/model)`)
98
+ break
99
+ }
100
+ case "--no-register":
101
+ options.register = false
102
+ break
103
+ case "--config-dir":
104
+ options.configDir = rest.shift()
105
+ break
106
+ case "--dry-run":
107
+ options.dryRun = true
108
+ break
109
+ case "--refresh":
110
+ options.refresh = true
111
+ break
112
+ case "--json":
113
+ options.json = true
114
+ break
115
+ case "--no-color":
116
+ options.noColor = true
117
+ break
118
+ case "--html":
119
+ options.markdown = false
120
+ break
121
+ case "-m":
122
+ case "--markdown":
123
+ options.markdown = true
124
+ break
125
+ case "-o":
126
+ case "--output":
127
+ // "" (missing value) is rejected by exportCommand; "-" means stdout.
128
+ options.output = rest.shift() ?? ""
129
+ break
130
+ case "-h":
131
+ case "--help":
132
+ options.help = true
133
+ break
134
+ default:
135
+ if (arg && !options.session && (options.command === "inspect" || options.command === "prune" || options.command === "timeline" || options.command === "export") && !arg.startsWith("-")) {
136
+ options.session = arg
137
+ } else if (arg) {
138
+ console.warn(`Ignoring unknown argument: ${arg}`)
139
+ }
140
+ }
141
+ }
142
+ return options
143
+ }
144
+
145
+ function isInteractive(options) {
146
+ return !options.yes && Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY)
147
+ }
148
+
149
+ function printSummary(configDir, models, install, registration, { init = false } = {}) {
150
+ const changed = install.created.length + install.updated.length
151
+ console.log("")
152
+ console.log(`Config dir : ${configDir}`)
153
+ console.log(`Agents : ${TEAM_AGENTS.length} (${install.created.length} created, ${install.updated.length} updated, ${install.unchanged.length} unchanged)`)
154
+ if (install.backupDir) console.log(`Backups : ${install.backupDir}`)
155
+ if (install.missing.length) console.log(`Missing : ${install.missing.join(", ")}`)
156
+ if (registration) {
157
+ if (registration.status === "added") console.log(`Plugin : added "${registration.entry}" to ${registration.file}`)
158
+ else if (registration.status === "already") console.log(`Plugin : already configured (${registration.entry}) in ${registration.file}`)
159
+ else if (registration.status === "commented")
160
+ console.log(`Plugin : ${registration.file} has comments — not rewriting it. Add "${PACKAGE_NAME}" to "plugins" manually.`)
161
+ else if (registration.status === "symlink")
162
+ console.log(`Plugin : ${registration.file} is a symlink — refusing to rewrite it. Add "${PACKAGE_NAME}" to "plugins" manually.`)
163
+ else if (registration.status === "unparsed") console.log(`Plugin : could not parse ${registration.file} — add "${PACKAGE_NAME}" to "plugins" manually`)
164
+ }
165
+ console.log("\nModel assignment:")
166
+ for (const agent of TEAM_AGENTS) console.log(` ${agent.id.padEnd(20)} ${models[agent.id]}`)
167
+ if (changed === 0 && !registration) console.log("\nNothing changed.")
168
+ console.log("\nRestart OpenCode (or run `opencode reload`) to pick up the changes.")
169
+ if (init) {
170
+ console.log("\nNext steps:")
171
+ console.log(" opencode-teamwork models")
172
+ console.log(" /teamwork-craft (in OpenCode)")
173
+ }
174
+ }
175
+
176
+ async function run(options, { register, init = false }) {
177
+ const configDir = resolveConfigDir(options.configDir)
178
+ const current = currentModels(configDir)
179
+
180
+ let models = current
181
+ if (isInteractive(options)) {
182
+ const available = await detectAvailableModels()
183
+ models = await pickModels({ current, available })
184
+ }
185
+ models = applyOverrides(models, { all: options.all, assignments: options.assignments })
186
+
187
+ if (!options.dryRun) writeModelMap(configDir, models)
188
+ const install = installAgents({ configDir, models, dryRun: options.dryRun, refresh: options.refresh === true })
189
+ const registration = register ? registerPlugin({ configDir, dryRun: options.dryRun }) : undefined
190
+
191
+ printSummary(configDir, models, install, registration, { init })
192
+ }
193
+
194
+ function status(options) {
195
+ const configDir = resolveConfigDir(options.configDir)
196
+ const hasMap = existsSync(modelMapPath(configDir))
197
+ const models = hasMap ? readRawModelMap(configDir) : {}
198
+ const configFile = findConfigFile(configDir)
199
+ console.log(`Config dir : ${configDir}`)
200
+ console.log(`Config file: ${configFile || "(none — would create opencode.json)"}`)
201
+ if (configFile) {
202
+ try {
203
+ const data = JSON.parse(stripJsonComments(readFileSync(configFile, "utf8")))
204
+ const entries = Array.isArray(data.plugins) ? data.plugins.filter((p) => typeof p === "string" && p.includes("opencode-teamwork")) : []
205
+ console.log(`Plugin : ${entries.length ? entries.join(", ") : "not registered"}`)
206
+ } catch {
207
+ console.log("Plugin : (config not parsed)")
208
+ }
209
+ }
210
+ console.log("\nAgents:")
211
+ for (const agent of TEAM_AGENTS) {
212
+ const file = join(configDir, "agents", "team", agent.file)
213
+ const present = existsSync(file)
214
+ const model = present ? (readFileSync(file, "utf8").match(/^model:\s*(.+?)\s*$/m)?.[1] ?? "?") : "not installed"
215
+ console.log(` ${agent.id.padEnd(20)} ${present ? "ok " : "-- "} ${model}${models[agent.id] && models[agent.id] !== model && present ? ` (teamwork.json: ${models[agent.id]})` : ""}`)
216
+ }
217
+ console.log(`\nModel map : ${modelMapPath(configDir)} (${existsSync(modelMapPath(configDir)) ? "present" : "not written"})`)
218
+ }
219
+
220
+ function runsCommand() {
221
+ const runs = listTeamworkRuns(process.cwd())
222
+ if (!runs.length) {
223
+ console.log("No Teamwork runs found in .opencode/teamwork/")
224
+ return
225
+ }
226
+
227
+ console.log(`Teamwork Runs (${runs.length}):\n`)
228
+ console.log(
229
+ "SESSION ID".padEnd(26) +
230
+ "PHASE".padEnd(16) +
231
+ "TOPOLOGY".padEnd(20) +
232
+ "TASKS".padEnd(12) +
233
+ "SECURITY".padEnd(14) +
234
+ "COST ($)"
235
+ )
236
+ console.log("-".repeat(96))
237
+
238
+ for (const r of runs) {
239
+ const tasks = `${r.tasksPassed}/${r.tasksTotal}${r.tasksBlocked ? ` (${r.tasksBlocked} blk)` : ""}`
240
+ const cost = `$${r.spentUsd} / $${r.budgetUsd}`
241
+ console.log(
242
+ r.sessionId.padEnd(26) +
243
+ r.phase.padEnd(16) +
244
+ r.topology.padEnd(20) +
245
+ tasks.padEnd(12) +
246
+ r.securityStatus.padEnd(14) +
247
+ cost
248
+ )
249
+ }
250
+ }
251
+
252
+ function inspectCommand(options) {
253
+ const result = inspectTeamworkRun(process.cwd(), options.session)
254
+ if (result.error) {
255
+ console.error(result.error)
256
+ process.exitCode = 1
257
+ return
258
+ }
259
+
260
+ const { run, tasks, costs, audit, pitfalls, conflicts } = result
261
+ console.log(`Teamwork Run: ${run.sessionId}`)
262
+ console.log(`Topology : ${run.topology}`)
263
+ console.log(`Phase : ${run.phase}`)
264
+ console.log(`Cost : $${run.spentUsd} / $${run.budgetUsd} (source: ${costs?.budgetSource || "default"})`)
265
+ console.log(`Updated At : ${run.updatedAt}`)
266
+
267
+ console.log(`\nTasks (${Object.keys(tasks).length}):`)
268
+ for (const [id, t] of Object.entries(tasks)) {
269
+ const round = t?.round ? `round ${t.round}` : "round 0"
270
+ const branch = t?.branch ? `[${t.branch}]` : ""
271
+ console.log(` ${id.padEnd(20)} : ${String(t?.status || "pending").padEnd(16)} (${round}) ${branch}`)
272
+ if (t?.summary) console.log(` Summary : ${t.summary}`)
273
+ if (t?.feedback) console.log(` Feedback: ${t.feedback}`)
274
+ }
275
+
276
+ console.log(`\nSecurity Audit:`)
277
+ if (!audit) {
278
+ console.log(` Not yet run (phase: ${run.phase})`)
279
+ } else {
280
+ console.log(` Status : ${audit.status}`)
281
+ console.log(` Summary : ${audit.summary || "No summary"}`)
282
+ if (audit.severityCounts) {
283
+ console.log(` Findings: ${audit.severityCounts.critical || 0} Critical, ${audit.severityCounts.high || 0} High, ${audit.severityCounts.medium || 0} Medium, ${audit.severityCounts.low || 0} Low`)
284
+ }
285
+ }
286
+
287
+ if (conflicts.length) {
288
+ console.log(`\nMerge Conflicts (${conflicts.length}):`)
289
+ for (const c of conflicts) {
290
+ console.log(` - Task ${c.taskId}: ${c.conflictingFiles?.join(", ") || "conflicts recorded"}`)
291
+ }
292
+ }
293
+
294
+ if (pitfalls.length) {
295
+ console.log(`\nPitfalls (${pitfalls.length}):`)
296
+ for (const p of pitfalls.slice(-5)) {
297
+ console.log(` ${p}`)
298
+ }
299
+ }
300
+ }
301
+
302
+ function timelineCommand(options) {
303
+ const runs = listTeamworkRuns(process.cwd())
304
+ if (!runs.length) {
305
+ console.error("No Teamwork runs found.")
306
+ process.exitCode = 1
307
+ return
308
+ }
309
+ const target = options.session ? runs.find((r) => r.sessionId === options.session) : runs[0]
310
+ if (!target) {
311
+ console.error(`Run "${safeEcho(options.session)}" not found.`)
312
+ process.exitCode = 1
313
+ return
314
+ }
315
+
316
+ const timeline = buildTimeline(process.cwd(), target.sessionId)
317
+ if (options.json) {
318
+ // JSON.stringify escapes C0 only; escape DEL and C1 (incl. 0x9b CSI) too so
319
+ // no raw control byte from a run file can reach the terminal.
320
+ const json = JSON.stringify(timeline, null, 2).replace(
321
+ /[\x7f-\x9f]/g,
322
+ (c) => "\\u" + c.charCodeAt(0).toString(16).padStart(4, "0"),
323
+ )
324
+ console.log(json)
325
+ for (const warning of timelineWarnings(timeline)) console.error(`warning: ${warning}`)
326
+ return
327
+ }
328
+
329
+ const color = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR && !options.noColor
330
+ for (const line of renderTimeline(timeline, { color })) console.log(line)
331
+ }
332
+
333
+ const SESSION_ID_RE = /^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/
334
+
335
+ // Resolve a path through symlinks where it exists; otherwise fall back to resolve().
336
+ function realOrResolved(p) {
337
+ try {
338
+ return realpathSync(p)
339
+ } catch {
340
+ return resolve(p)
341
+ }
342
+ }
343
+
344
+ function isWithin(child, parent) {
345
+ const rel = relative(parent, child)
346
+ return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`))
347
+ }
348
+
349
+ // Validate an explicit -o target. Returns { path } or { error }.
350
+ // Allowed: inside the project root or the OS temp dir. Traversal segments are refused outright.
351
+ function resolveExportOutput(rawOutput, root) {
352
+ if (rawOutput === "") return { error: "-o / --output requires a file path (use -o - for stdout)" }
353
+ if (rawOutput.startsWith("-")) return { error: `Refusing output path "${safeEcho(rawOutput, 200)}": paths starting with "-" are not accepted (use -o - for stdout)` }
354
+ if (rawOutput.split(/[\\/]/).includes("..")) return { error: `Refusing output path "${safeEcho(rawOutput, 200)}": traversal segments ("..") are not allowed` }
355
+ const target = resolve(root, rawOutput)
356
+ const parent = realOrResolved(dirname(target))
357
+ const candidate = join(parent, basename(target))
358
+ try {
359
+ if (lstatSync(candidate).isSymbolicLink()) return { error: `Refusing output path "${safeEcho(rawOutput, 200)}": target is a symlink` }
360
+ } catch {}
361
+ const allowedRoots = [realOrResolved(root), realOrResolved(tmpdir())]
362
+ if (!allowedRoots.some((base) => isWithin(candidate, base))) {
363
+ return { error: `Refusing output path "${safeEcho(rawOutput, 200)}": must be inside the project root or the temp directory (${safeEcho(allowedRoots[0], 200)}, ${safeEcho(allowedRoots[1], 200)})` }
364
+ }
365
+ return { path: candidate }
366
+ }
367
+
368
+ function exportCommand(options) {
369
+ const root = process.cwd()
370
+ let sessionId = options.session
371
+ if (sessionId === undefined) {
372
+ const runs = listTeamworkRuns(root)
373
+ if (!runs.length) {
374
+ console.error("No Teamwork runs found in .opencode/teamwork/ (nothing to export)")
375
+ process.exitCode = 1
376
+ return
377
+ }
378
+ sessionId = runs[0].sessionId
379
+ }
380
+ if (typeof sessionId !== "string" || !SESSION_ID_RE.test(sessionId)) {
381
+ console.error(`Invalid session id "${safeEcho(sessionId)}": must match ^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$`)
382
+ process.exitCode = 1
383
+ return
384
+ }
385
+
386
+ const format = options.markdown ? "markdown" : "html"
387
+ const data = buildExportData(root, sessionId)
388
+ if (data.error) {
389
+ console.error(data.error)
390
+ process.exitCode = 1
391
+ return
392
+ }
393
+ const doc = renderExport(data, { format })
394
+
395
+ if (options.output === "-") {
396
+ // Ignore EPIPE when the reader (e.g. `| head`) closes early; report anything else.
397
+ process.stdout.on("error", (err) => {
398
+ if (err?.code === "EPIPE") return
399
+ console.error(`Could not write to stdout: ${safeEcho(err?.code || err?.message, 120)}`)
400
+ process.exitCode = 1
401
+ })
402
+ process.stdout.write(doc)
403
+ return
404
+ }
405
+
406
+ let target
407
+ if (options.output === undefined) {
408
+ target = join(root, ".opencode", "teamwork", sessionId, format === "markdown" ? "report.md" : "report.html")
409
+ } else {
410
+ const resolved = resolveExportOutput(options.output, root)
411
+ if (resolved.error) {
412
+ console.error(resolved.error)
413
+ process.exitCode = 1
414
+ return
415
+ }
416
+ target = resolved.path
417
+ }
418
+
419
+ try {
420
+ if (lstatSync(target, { throwIfNoEntry: false })?.isSymbolicLink()) {
421
+ console.error(`Refusing to write ${safeEcho(target, 200)}: target is a symlink`)
422
+ process.exitCode = 1
423
+ return
424
+ }
425
+ writeFileSync(target, doc, { encoding: "utf8", flag: "w" })
426
+ } catch (err) {
427
+ console.error(`Could not write ${safeEcho(target, 200)}: ${safeEcho(err?.code || err?.message, 120)}`)
428
+ process.exitCode = 1
429
+ return
430
+ }
431
+ console.log(target)
432
+ }
433
+
434
+ function pruneCommand(options) {
435
+ const res = pruneTeamworkWorktrees(process.cwd(), {
436
+ all: Boolean(options.all),
437
+ sessionId: options.session,
438
+ })
439
+ if (!res.count) {
440
+ console.log("No worktrees were pruned.")
441
+ } else {
442
+ console.log(`Pruned ${res.count} worktree directory(s): ${res.removed.join(", ")}`)
443
+ }
444
+ }
445
+
446
+ const DOCTOR_INDICATORS = { pass: "[✓]", warn: "[!]", fail: "[✗]" }
447
+
448
+ function doctorCommand(options) {
449
+ const configDir = resolveConfigDir(options.configDir)
450
+ const report = runDoctor({ configDir, cwd: process.cwd() })
451
+ const steps = nextSteps(report.checks)
452
+
453
+ if (options.json) {
454
+ // Additive: existing consumers still see { ok, checks }; nextSteps is new.
455
+ console.log(JSON.stringify({ ...report, nextSteps: steps }, null, 2))
456
+ process.exitCode = report.ok ? 0 : 1
457
+ return
458
+ }
459
+
460
+ console.log("opencode-teamwork doctor")
461
+ console.log(`Config dir: ${configDir}\n`)
462
+ for (const check of report.checks) {
463
+ const indicator = DOCTOR_INDICATORS[check.status] || DOCTOR_INDICATORS.fail
464
+ console.log(`${indicator} ${check.name.padEnd(20)} ${check.message}`)
465
+ }
466
+
467
+ const failed = report.checks.filter((check) => check.status === "fail").length
468
+ const warned = report.checks.filter((check) => check.status === "warn").length
469
+ console.log("")
470
+ if (report.ok) {
471
+ console.log(warned ? `Environment looks healthy (${warned} warning(s)).` : "Environment looks healthy.")
472
+ } else {
473
+ console.log(`Environment has ${failed} failing check(s)${warned ? ` and ${warned} warning(s)` : ""}.`)
474
+ }
475
+ if (steps.length) {
476
+ console.log("\nNext steps:")
477
+ for (const step of steps) console.log(` → ${step}`)
478
+ }
479
+ process.exitCode = report.ok ? 0 : 1
480
+ }
481
+
482
+ async function main() {
483
+ const options = parseArgs(process.argv.slice(2))
484
+ const command = options.command || (options.help ? "help" : "init")
485
+
486
+ if (options.help || command === "help") {
487
+ console.log(HELP)
488
+ return
489
+ }
490
+ if (!["init", "models", "install", "status", "runs", "inspect", "timeline", "export", "prune", "doctor"].includes(command)) {
491
+ console.error(`Unknown command: ${command}\n`)
492
+ console.log(HELP)
493
+ process.exitCode = 1
494
+ return
495
+ }
496
+
497
+ if (command === "status") return status(options)
498
+ if (command === "runs") return runsCommand()
499
+ if (command === "inspect") return inspectCommand(options)
500
+ if (command === "timeline") return timelineCommand(options)
501
+ if (command === "export") return exportCommand(options)
502
+ if (command === "prune") return pruneCommand(options)
503
+ if (command === "doctor") return doctorCommand(options)
504
+ if (command === "install") {
505
+ options.yes = true
506
+ return run(options, { register: options.register })
507
+ }
508
+ if (command === "models") {
509
+ return run(options, { register: false })
510
+ }
511
+ return run(options, { register: options.register, init: true })
512
+ }
513
+
514
+ main().catch((error) => {
515
+ console.error(`@heretek-ai/opencode-teamwork-v2: ${error?.message || error}`)
516
+ process.exitCode = 1
517
+ })