@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.
- package/LICENSE +22 -0
- package/README.md +387 -2
- package/agents/team/crafter.md +146 -0
- package/agents/team/falsifier.md +98 -0
- package/agents/team/orchestrator.md +136 -0
- package/agents/team/proof-worker.md +66 -0
- package/agents/team/proposer.md +76 -0
- package/agents/team/scout.md +93 -0
- package/agents/team/security-auditor.md +64 -0
- package/agents/team/sentinel.md +175 -0
- package/agents/team/synthesizer.md +108 -0
- package/agents/team/verifier.md +106 -0
- package/agents/team/worker.md +74 -0
- package/bin/opencode-teamwork.mjs +517 -0
- package/docs/ARTIFACTS.md +806 -0
- package/docs/GUARDRAILS.md +48 -0
- package/lib/doctor.mjs +280 -0
- package/lib/export.mjs +1119 -0
- package/lib/picker.mjs +132 -0
- package/lib/runs.mjs +165 -0
- package/lib/team.mjs +394 -0
- package/lib/timeline.mjs +713 -0
- package/package.json +68 -4
- package/plugins/opencode-teamwork/index.ts +232 -0
- package/plugins/opencode-teamwork/package.json +11 -0
- package/plugins/opencode-teamwork/tools.ts +2912 -0
- package/postinstall.mjs +71 -0
- package/scripts/lint-prompts.mjs +168 -0
- package/scripts/test-cost.mjs +242 -0
- package/scripts/test-doctor.mjs +287 -0
- package/scripts/test-engine.mjs +2041 -0
- package/scripts/test-export.mjs +540 -0
- package/scripts/test-timeline.mjs +1041 -0
package/lib/picker.mjs
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// @heretek-ai/opencode-teamwork-v2 — interactive model picker
|
|
2
|
+
//
|
|
3
|
+
// Dependency-free (node:readline only). Detects the models OpenCode actually
|
|
4
|
+
// has available (via `opencode models`) and lets the user assign one to each
|
|
5
|
+
// team agent, either with a single shared model or per-agent.
|
|
6
|
+
|
|
7
|
+
import { execFile } from "node:child_process"
|
|
8
|
+
import readline from "node:readline/promises"
|
|
9
|
+
import { TEAM_AGENTS, DEFAULT_MODELS } from "./team.mjs"
|
|
10
|
+
|
|
11
|
+
/** Return the list of `provider/model` ids from `opencode models`, or []. */
|
|
12
|
+
export function detectAvailableModels({ timeout = 20000 } = {}) {
|
|
13
|
+
return new Promise((resolve) => {
|
|
14
|
+
execFile("opencode", ["models"], { timeout, maxBuffer: 4 * 1024 * 1024 }, (error, stdout) => {
|
|
15
|
+
if (error || !stdout) return resolve([])
|
|
16
|
+
const models = stdout
|
|
17
|
+
.split(/\r?\n/)
|
|
18
|
+
.map((line) => line.trim())
|
|
19
|
+
.filter((line) => /^[a-zA-Z0-9._-]+\/[a-zA-Z0-9._:-]+$/.test(line))
|
|
20
|
+
resolve([...new Set(models)])
|
|
21
|
+
})
|
|
22
|
+
})
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const PROVIDER_MODEL_RE = /^\S+\/\S+$/
|
|
26
|
+
|
|
27
|
+
function echo(value, max = 64) {
|
|
28
|
+
const shown = String(value).replace(/[\x00-\x1f\x7f-\x9f]/g, "?")
|
|
29
|
+
return shown.length > max ? `${shown.slice(0, max)}...` : shown
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function parseModelToken(input, available, fallback) {
|
|
33
|
+
const value = String(input ?? "").trim()
|
|
34
|
+
if (!value) return fallback
|
|
35
|
+
if (/^\d+$/.test(value)) {
|
|
36
|
+
const index = Number.parseInt(value, 10)
|
|
37
|
+
if (index >= 1 && index <= available.length) return available[index - 1]
|
|
38
|
+
console.warn(` ! "${echo(value)}" is not a detected model number — keeping ${echo(fallback)}`)
|
|
39
|
+
return fallback
|
|
40
|
+
}
|
|
41
|
+
if (available.includes(value) || PROVIDER_MODEL_RE.test(value)) return value
|
|
42
|
+
console.warn(` ! "${echo(value)}" is not a detected model and is not provider/model — keeping ${echo(fallback)}`)
|
|
43
|
+
return fallback
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Print the final agent → model mapping with a short count summary. */
|
|
47
|
+
function printAssignmentSummary(models) {
|
|
48
|
+
const distinct = new Set(TEAM_AGENTS.map((agent) => models[agent.id])).size
|
|
49
|
+
console.log(`\nModel assignment (${TEAM_AGENTS.length} agents, ${distinct} distinct ${distinct === 1 ? "model" : "models"}):`)
|
|
50
|
+
for (const agent of TEAM_AGENTS) console.log(` ${agent.id.padEnd(20)} → ${models[agent.id]}`)
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function printModelList(available, current) {
|
|
54
|
+
if (!available.length) {
|
|
55
|
+
console.log(" (couldn't detect models from `opencode models` — type provider/model manually)")
|
|
56
|
+
return
|
|
57
|
+
}
|
|
58
|
+
console.log("\nAvailable models:")
|
|
59
|
+
available.forEach((model, i) => {
|
|
60
|
+
const used = Object.values(current).includes(model) ? " *" : ""
|
|
61
|
+
console.log(` ${String(i + 1).padStart(3)}. ${model}${used}`)
|
|
62
|
+
})
|
|
63
|
+
console.log(" ( * = already assigned in this session )\n")
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Run the interactive picker. Returns a full model map keyed by agent id.
|
|
68
|
+
* Never throws; falls back to the supplied defaults on any problem.
|
|
69
|
+
*/
|
|
70
|
+
export async function pickModels({ current = {}, available = [], input = process.stdin, output = process.stdout } = {}) {
|
|
71
|
+
const base = { ...DEFAULT_MODELS, ...current }
|
|
72
|
+
const rl = readline.createInterface({ input, output })
|
|
73
|
+
const ask = async (prompt, fallback = "") => {
|
|
74
|
+
try {
|
|
75
|
+
const answer = (await rl.question(prompt)).trim()
|
|
76
|
+
return answer === "" ? fallback : answer
|
|
77
|
+
} catch {
|
|
78
|
+
return fallback
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
try {
|
|
83
|
+
console.log("\n@heretek-ai/opencode-teamwork-v2 — model assignment")
|
|
84
|
+
console.log(`Pick a model for each of the ${TEAM_AGENTS.length} team agents. Press Enter to keep the current value.`)
|
|
85
|
+
console.log("\nHow would you like to assign models?")
|
|
86
|
+
console.log(" 1) Keep current / default models")
|
|
87
|
+
console.log(" 2) Use one model for every agent")
|
|
88
|
+
console.log(" 3) Configure each agent individually")
|
|
89
|
+
const choice = await ask("Choice [1]: ", "1")
|
|
90
|
+
|
|
91
|
+
if (choice === "1") return base
|
|
92
|
+
|
|
93
|
+
if (choice === "2") {
|
|
94
|
+
printModelList(available, base)
|
|
95
|
+
const answer = await ask(`Model for all agents [${base[TEAM_AGENTS[0].id]}]: `, "")
|
|
96
|
+
const model = parseModelToken(answer, available, base[TEAM_AGENTS[0].id])
|
|
97
|
+
const map = {}
|
|
98
|
+
for (const agent of TEAM_AGENTS) map[agent.id] = model
|
|
99
|
+
printAssignmentSummary(map)
|
|
100
|
+
return map
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (choice === "3") {
|
|
104
|
+
printModelList(available, base)
|
|
105
|
+
const map = { ...base }
|
|
106
|
+
for (let i = 0; i < TEAM_AGENTS.length; i++) {
|
|
107
|
+
const agent = TEAM_AGENTS[i]
|
|
108
|
+
console.log(`[${i + 1}/${TEAM_AGENTS.length}] ${agent.id} — ${agent.role}`)
|
|
109
|
+
const answer = await ask(` model [${map[agent.id]}]: `, "")
|
|
110
|
+
map[agent.id] = parseModelToken(answer, available, map[agent.id])
|
|
111
|
+
}
|
|
112
|
+
printAssignmentSummary(map)
|
|
113
|
+
return map
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
console.log("Unrecognised choice — keeping current models.")
|
|
117
|
+
return base
|
|
118
|
+
} finally {
|
|
119
|
+
rl.close()
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Apply CLI overrides (`--all`, repeated `--model id=provider/model`) to a map. */
|
|
124
|
+
export function applyOverrides(models, { all, assignments = {} } = {}) {
|
|
125
|
+
const next = { ...models }
|
|
126
|
+
if (all) for (const agent of TEAM_AGENTS) next[agent.id] = all
|
|
127
|
+
for (const [id, value] of Object.entries(assignments)) {
|
|
128
|
+
const key = id.startsWith("team/") ? id : `team/${id}`
|
|
129
|
+
next[key] = value
|
|
130
|
+
}
|
|
131
|
+
return next
|
|
132
|
+
}
|
package/lib/runs.mjs
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
// lib/runs.mjs — Teamwork run management & inspection helpers
|
|
2
|
+
//
|
|
3
|
+
// Shared by CLI commands (opencode-teamwork runs/inspect/prune) and tests.
|
|
4
|
+
// Zero runtime dependencies.
|
|
5
|
+
|
|
6
|
+
import { existsSync, readdirSync, readFileSync, lstatSync, rmSync } from "node:fs"
|
|
7
|
+
import { join, basename } from "node:path"
|
|
8
|
+
import { execFileSync } from "node:child_process"
|
|
9
|
+
|
|
10
|
+
const SESSION_ID = /^[0-9A-Za-z][0-9A-Za-z._-]{0,63}$/
|
|
11
|
+
|
|
12
|
+
function readJson(file, fallback = undefined) {
|
|
13
|
+
try {
|
|
14
|
+
return JSON.parse(readFileSync(file, "utf8"))
|
|
15
|
+
} catch {
|
|
16
|
+
return fallback
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function listTeamworkRuns(projectRoot = process.cwd()) {
|
|
21
|
+
const dir = join(projectRoot, ".opencode", "teamwork")
|
|
22
|
+
if (!existsSync(dir)) return []
|
|
23
|
+
|
|
24
|
+
try {
|
|
25
|
+
return readdirSync(dir)
|
|
26
|
+
.filter((name) => SESSION_ID.test(name))
|
|
27
|
+
.map((name) => {
|
|
28
|
+
const runDir = join(dir, name)
|
|
29
|
+
let mtime = 0
|
|
30
|
+
try {
|
|
31
|
+
mtime = lstatSync(runDir).mtimeMs
|
|
32
|
+
} catch {}
|
|
33
|
+
|
|
34
|
+
const state = readJson(join(runDir, "state.json"), {})
|
|
35
|
+
const plan = readJson(join(runDir, "plan.dag.json"), {})
|
|
36
|
+
const costs = readJson(join(runDir, "costs.json"), {})
|
|
37
|
+
const audit = readJson(join(runDir, "verify", "security-audit.json"), undefined)
|
|
38
|
+
|
|
39
|
+
const tasks = state.tasks ? Object.values(state.tasks) : []
|
|
40
|
+
const totalTasks = plan.tasks ? plan.tasks.length : tasks.length
|
|
41
|
+
const passedTasks = tasks.filter((t) => t?.status === "pass" || t?.status === "verified_pass").length
|
|
42
|
+
const blockedTasks = tasks.filter((t) => t?.status === "blocked").length
|
|
43
|
+
|
|
44
|
+
let securityStatus = "N/A"
|
|
45
|
+
if (audit) {
|
|
46
|
+
securityStatus = audit.status === "PASS" ? "PASS" : `FAIL (${(audit.severityCounts?.critical || 0) + (audit.severityCounts?.high || 0)} high/crit)`
|
|
47
|
+
} else if (state.phase === "SECURITY_AUDIT") {
|
|
48
|
+
securityStatus = "IN_PROGRESS"
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const spent = Number(costs.spentUsd) || 0
|
|
52
|
+
const budget = typeof costs.budgetUsd === "number" ? costs.budgetUsd : 20
|
|
53
|
+
|
|
54
|
+
return {
|
|
55
|
+
sessionId: name,
|
|
56
|
+
path: runDir,
|
|
57
|
+
phase: state.phase || "UNKNOWN",
|
|
58
|
+
topology: plan.topology || "unknown",
|
|
59
|
+
tasksPassed: passedTasks,
|
|
60
|
+
tasksBlocked: blockedTasks,
|
|
61
|
+
tasksTotal: totalTasks,
|
|
62
|
+
securityStatus,
|
|
63
|
+
spentUsd: spent,
|
|
64
|
+
budgetUsd: budget,
|
|
65
|
+
updatedAt: state.updatedAt || new Date(mtime).toISOString(),
|
|
66
|
+
mtime,
|
|
67
|
+
}
|
|
68
|
+
})
|
|
69
|
+
.sort((a, b) => b.mtime - a.mtime)
|
|
70
|
+
} catch {
|
|
71
|
+
return []
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function inspectTeamworkRun(projectRoot = process.cwd(), sessionId = undefined) {
|
|
76
|
+
const runs = listTeamworkRuns(projectRoot)
|
|
77
|
+
if (!runs.length) return { error: "No Teamwork runs found." }
|
|
78
|
+
|
|
79
|
+
const target = sessionId ? runs.find((r) => r.sessionId === sessionId) : runs[0]
|
|
80
|
+
if (!target) return { error: `Run "${sessionId}" not found.` }
|
|
81
|
+
|
|
82
|
+
const runDir = target.path
|
|
83
|
+
const state = readJson(join(runDir, "state.json"), {})
|
|
84
|
+
const plan = readJson(join(runDir, "plan.dag.json"), {})
|
|
85
|
+
const costs = readJson(join(runDir, "costs.json"), {})
|
|
86
|
+
const audit = readJson(join(runDir, "verify", "security-audit.json"), undefined)
|
|
87
|
+
|
|
88
|
+
let pitfalls = []
|
|
89
|
+
try {
|
|
90
|
+
const pitFile = join(runDir, "pitfalls.md")
|
|
91
|
+
if (existsSync(pitFile)) {
|
|
92
|
+
pitfalls = readFileSync(pitFile, "utf8")
|
|
93
|
+
.split("\n")
|
|
94
|
+
.map((l) => l.trim())
|
|
95
|
+
.filter((l) => l.startsWith("-"))
|
|
96
|
+
}
|
|
97
|
+
} catch {}
|
|
98
|
+
|
|
99
|
+
let conflicts = []
|
|
100
|
+
try {
|
|
101
|
+
const synDir = join(runDir, "synthesis")
|
|
102
|
+
if (existsSync(synDir)) {
|
|
103
|
+
conflicts = readdirSync(synDir)
|
|
104
|
+
.filter((f) => f.startsWith("conflict-") && f.endsWith(".json"))
|
|
105
|
+
.map((f) => readJson(join(synDir, f), { file: f }))
|
|
106
|
+
}
|
|
107
|
+
} catch {}
|
|
108
|
+
|
|
109
|
+
return {
|
|
110
|
+
run: target,
|
|
111
|
+
tasks: state.tasks || {},
|
|
112
|
+
planTasks: plan.tasks || [],
|
|
113
|
+
costs,
|
|
114
|
+
audit,
|
|
115
|
+
pitfalls,
|
|
116
|
+
conflicts,
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function pruneTeamworkWorktrees(projectRoot = process.cwd(), options = {}) {
|
|
121
|
+
const base = process.env.TEAMWORK_WORKTREES_DIR || join(projectRoot, "..", ".teamwork-worktrees")
|
|
122
|
+
if (!existsSync(base)) return { count: 0, removed: [] }
|
|
123
|
+
|
|
124
|
+
const execGit = (args) => {
|
|
125
|
+
try {
|
|
126
|
+
return execFileSync("git", args, { cwd: projectRoot, encoding: "utf8", timeout: 15000, stdio: ["pipe", "pipe", "pipe"] }).trim()
|
|
127
|
+
} catch {
|
|
128
|
+
return ""
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const removed = []
|
|
133
|
+
try {
|
|
134
|
+
const entries = readdirSync(base)
|
|
135
|
+
for (const entry of entries) {
|
|
136
|
+
if (!SESSION_ID.test(entry)) continue
|
|
137
|
+
if (options.sessionId && entry !== options.sessionId) continue
|
|
138
|
+
|
|
139
|
+
const entryPath = join(base, entry)
|
|
140
|
+
if (!options.all && !options.sessionId) {
|
|
141
|
+
// If neither --all nor specific --session is set, check if run is done
|
|
142
|
+
const stateFile = join(projectRoot, ".opencode", "teamwork", entry, "state.json")
|
|
143
|
+
const state = readJson(stateFile, {})
|
|
144
|
+
const isFinished = ["MERGE", "DONE", "PRESENT_PARTIAL"].includes(state.phase)
|
|
145
|
+
if (!isFinished) continue
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
try {
|
|
149
|
+
const subdirs = readdirSync(entryPath)
|
|
150
|
+
for (const sub of subdirs) {
|
|
151
|
+
const subPath = join(entryPath, sub)
|
|
152
|
+
execGit(["worktree", "remove", "--force", subPath])
|
|
153
|
+
}
|
|
154
|
+
} catch {}
|
|
155
|
+
|
|
156
|
+
try {
|
|
157
|
+
rmSync(entryPath, { recursive: true, force: true })
|
|
158
|
+
removed.push(entry)
|
|
159
|
+
} catch {}
|
|
160
|
+
}
|
|
161
|
+
execGit(["worktree", "prune"])
|
|
162
|
+
} catch {}
|
|
163
|
+
|
|
164
|
+
return { count: removed.length, removed }
|
|
165
|
+
}
|
package/lib/team.mjs
ADDED
|
@@ -0,0 +1,394 @@
|
|
|
1
|
+
// @heretek-ai/opencode-teamwork-v2 — installer library
|
|
2
|
+
//
|
|
3
|
+
// Dependency-free helpers shared by the `opencode-teamwork` CLI and the
|
|
4
|
+
// postinstall hook. Responsible for:
|
|
5
|
+
// * locating the OpenCode config directory
|
|
6
|
+
// * reading/writing the team model map (~/.config/opencode/teamwork.json)
|
|
7
|
+
// * installing the 11 `team/*` agent markdown files with the chosen models
|
|
8
|
+
// * registering the plugin in opencode.json(c)
|
|
9
|
+
//
|
|
10
|
+
// Nothing here imports OpenCode APIs, so it is safe to run under plain Node,
|
|
11
|
+
// Bun, npm, or the OpenCode plugin loader.
|
|
12
|
+
|
|
13
|
+
import { existsSync, lstatSync, mkdirSync, readFileSync, writeFileSync, copyFileSync } from "node:fs"
|
|
14
|
+
import { homedir } from "node:os"
|
|
15
|
+
import { join } from "node:path"
|
|
16
|
+
import { fileURLToPath } from "node:url"
|
|
17
|
+
|
|
18
|
+
export const PACKAGE_NAME = "@heretek-ai/opencode-teamwork-v2"
|
|
19
|
+
|
|
20
|
+
// Package root, i.e. the directory containing package.json / agents/ / lib/.
|
|
21
|
+
export const PACKAGE_ROOT = fileURLToPath(new URL("../", import.meta.url))
|
|
22
|
+
|
|
23
|
+
export const PACKAGE_VERSION = (() => {
|
|
24
|
+
try {
|
|
25
|
+
return JSON.parse(readFileSync(join(PACKAGE_ROOT, "package.json"), "utf8")).version
|
|
26
|
+
} catch {
|
|
27
|
+
return "0.0.0"
|
|
28
|
+
}
|
|
29
|
+
})()
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The 11 agents shipped by the package. `id` matches the OpenCode agent name
|
|
33
|
+
* (`team/<file>`), `defaultModel` matches the frontmatter in `agents/team/*.md`.
|
|
34
|
+
*/
|
|
35
|
+
export const TEAM_AGENTS = [
|
|
36
|
+
{ id: "team/crafter", file: "crafter.md", role: "Phase-1 prompt crafter (elicitation wizard)", defaultModel: "deepseek/deepseek-flash" },
|
|
37
|
+
{ id: "team/sentinel", file: "sentinel.md", role: "Main dispatcher for /teamwork", defaultModel: "deepseek/deepseek-v4-pro" },
|
|
38
|
+
{ id: "team/orchestrator", file: "orchestrator.md", role: "Legacy v1 loop coordinator", defaultModel: "deepseek/deepseek-v4-pro" },
|
|
39
|
+
{ id: "team/scout", file: "scout.md", role: "Read-only context gatherer", defaultModel: "deepseek/deepseek-flash" },
|
|
40
|
+
{ id: "team/worker", file: "worker.md", role: "Implementation worker", defaultModel: "deepseek/deepseek-flash" },
|
|
41
|
+
{ id: "team/proof-worker", file: "proof-worker.md", role: "Formal-proof worker", defaultModel: "deepseek/deepseek-v4-pro" },
|
|
42
|
+
{ id: "team/proposer", file: "proposer.md", role: "Candidate generator", defaultModel: "deepseek/deepseek-flash" },
|
|
43
|
+
{ id: "team/falsifier", file: "falsifier.md", role: "Adversarial critic", defaultModel: "deepseek/deepseek-v4-pro" },
|
|
44
|
+
{ id: "team/synthesizer", file: "synthesizer.md", role: "Candidate merger", defaultModel: "deepseek/deepseek-v4-pro" },
|
|
45
|
+
{ id: "team/verifier", file: "verifier.md", role: "Verification forcing function", defaultModel: "deepseek/deepseek-v4-pro" },
|
|
46
|
+
{ id: "team/security-auditor", file: "security-auditor.md", role: "Read-only security auditor", defaultModel: "deepseek/deepseek-v4-pro" },
|
|
47
|
+
]
|
|
48
|
+
|
|
49
|
+
export const DEFAULT_MODELS = Object.fromEntries(TEAM_AGENTS.map((a) => [a.id, a.defaultModel]))
|
|
50
|
+
|
|
51
|
+
/** Resolve the OpenCode config directory. */
|
|
52
|
+
export function resolveConfigDir(override) {
|
|
53
|
+
if (override) return override
|
|
54
|
+
if (process.env.OPENCODE_TEAMWORK_CONFIG) return process.env.OPENCODE_TEAMWORK_CONFIG
|
|
55
|
+
if (process.env.OPENCODE_CONFIG_DIR) return process.env.OPENCODE_CONFIG_DIR
|
|
56
|
+
const base = process.env.XDG_CONFIG_HOME || join(homedir(), ".config")
|
|
57
|
+
return join(base, "opencode")
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Replace (or insert) the `model:` frontmatter line in an agent markdown file. */
|
|
61
|
+
export function applyModel(content, model) {
|
|
62
|
+
if (!model) return content
|
|
63
|
+
if (/^model:.*$/m.test(content)) return content.replace(/^model:.*$/m, `model: ${model}`)
|
|
64
|
+
// No model line yet: insert one right after the opening frontmatter fence.
|
|
65
|
+
if (/^---\r?\n/.test(content)) return content.replace(/^(---\r?\n)/, `$1model: ${model}\n`)
|
|
66
|
+
return `---\nmodel: ${model}\n---\n\n${content}`
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Read the `model:` value out of an existing agent markdown file, if any. */
|
|
70
|
+
export function readModelFromFile(file) {
|
|
71
|
+
try {
|
|
72
|
+
const m = readFileSync(file, "utf8").match(/^model:\s*(.+?)\s*$/m)
|
|
73
|
+
return m ? m[1] : undefined
|
|
74
|
+
} catch {
|
|
75
|
+
return undefined
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export function modelMapPath(configDir) {
|
|
80
|
+
return join(configDir, "teamwork.json")
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Read only raw models from teamwork.json without defaults fallback. */
|
|
84
|
+
export function readRawModelMap(configDir) {
|
|
85
|
+
try {
|
|
86
|
+
const data = JSON.parse(readFileSync(modelMapPath(configDir), "utf8"))
|
|
87
|
+
if (data && typeof data.models === "object" && data.models) {
|
|
88
|
+
return data.models
|
|
89
|
+
}
|
|
90
|
+
} catch {
|
|
91
|
+
/* no map yet */
|
|
92
|
+
}
|
|
93
|
+
return {}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Load the persisted model map, merged over the shipped defaults. */
|
|
97
|
+
export function readModelMap(configDir) {
|
|
98
|
+
const raw = readRawModelMap(configDir)
|
|
99
|
+
return { ...DEFAULT_MODELS, ...raw }
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Persist the model map next to the agents so re-runs and the plugin can read it. */
|
|
103
|
+
export function writeModelMap(configDir, models) {
|
|
104
|
+
mkdirSync(configDir, { recursive: true })
|
|
105
|
+
const payload = {
|
|
106
|
+
$comment: "Generated by @heretek-ai/opencode-teamwork-v2. Maps each team agent to its model. Edit and re-run `opencode-teamwork init` (or `opencode reload`).",
|
|
107
|
+
version: PACKAGE_VERSION,
|
|
108
|
+
models,
|
|
109
|
+
}
|
|
110
|
+
writeFileSync(modelMapPath(configDir), JSON.stringify(payload, null, 2) + "\n")
|
|
111
|
+
return modelMapPath(configDir)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Seed the current model map from whatever is already on disk:
|
|
116
|
+
* defaults -> installed agent frontmatter -> teamwork.json (highest user priority).
|
|
117
|
+
*/
|
|
118
|
+
export function currentModels(configDir) {
|
|
119
|
+
const merged = { ...DEFAULT_MODELS }
|
|
120
|
+
for (const agent of TEAM_AGENTS) {
|
|
121
|
+
const fromFile = readModelFromFile(join(configDir, "agents", "team", agent.file))
|
|
122
|
+
if (fromFile) merged[agent.id] = fromFile
|
|
123
|
+
}
|
|
124
|
+
const rawStored = readRawModelMap(configDir)
|
|
125
|
+
for (const [k, v] of Object.entries(rawStored)) {
|
|
126
|
+
if (v) merged[k] = v
|
|
127
|
+
}
|
|
128
|
+
return merged
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function timestamp() {
|
|
132
|
+
return new Date().toISOString().replace(/[-:T]/g, "").slice(0, 14)
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Install (or update) the agent markdown files into the config dir.
|
|
137
|
+
*
|
|
138
|
+
* Existing files are never overwritten wholesale — only their `model:` line is
|
|
139
|
+
* rewritten — so any local edits the user made are preserved. A one-time backup
|
|
140
|
+
* of every touched file is written under `<configDir>/.opencode-teamwork-backup`.
|
|
141
|
+
*/
|
|
142
|
+
export function installAgents({ configDir, models = {}, packageRoot = PACKAGE_ROOT, dryRun = false, refresh = false }) {
|
|
143
|
+
const targetDir = join(configDir, "agents", "team")
|
|
144
|
+
const sourceDir = join(packageRoot, "agents", "team")
|
|
145
|
+
const result = { created: [], updated: [], unchanged: [], missing: [], backupDir: undefined }
|
|
146
|
+
|
|
147
|
+
if (!existsSync(sourceDir)) {
|
|
148
|
+
result.missing.push(sourceDir)
|
|
149
|
+
return result
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (!dryRun) mkdirSync(targetDir, { recursive: true })
|
|
153
|
+
|
|
154
|
+
const backupRoot = join(configDir, ".opencode-teamwork-backup", timestamp())
|
|
155
|
+
|
|
156
|
+
for (const agent of TEAM_AGENTS) {
|
|
157
|
+
const source = join(sourceDir, agent.file)
|
|
158
|
+
if (!existsSync(source)) {
|
|
159
|
+
result.missing.push(agent.file)
|
|
160
|
+
continue
|
|
161
|
+
}
|
|
162
|
+
const target = join(targetDir, agent.file)
|
|
163
|
+
// Prefer an explicit override, then the model already installed, then the
|
|
164
|
+
// shipped default — so a refresh never resets the user's chosen model.
|
|
165
|
+
const model = models[agent.id] || readModelFromFile(target) || agent.defaultModel
|
|
166
|
+
|
|
167
|
+
if (!existsSync(target)) {
|
|
168
|
+
if (!dryRun) writeFileSync(target, applyModel(readFileSync(source, "utf8"), model))
|
|
169
|
+
result.created.push(agent.file)
|
|
170
|
+
continue
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const existing = readFileSync(target, "utf8")
|
|
174
|
+
// refresh=true (opt-in via --refresh): adopt the shipped prompt
|
|
175
|
+
// body while keeping the user's chosen model line. Default is false so an
|
|
176
|
+
// npm install / plugin load never clobbers local edits. Backup on change.
|
|
177
|
+
const base = refresh ? readFileSync(source, "utf8") : existing
|
|
178
|
+
const next = applyModel(base, model)
|
|
179
|
+
if (next === existing) {
|
|
180
|
+
result.unchanged.push(agent.file)
|
|
181
|
+
continue
|
|
182
|
+
}
|
|
183
|
+
if (!dryRun) {
|
|
184
|
+
mkdirSync(backupRoot, { recursive: true })
|
|
185
|
+
copyFileSync(target, join(backupRoot, agent.file))
|
|
186
|
+
result.backupDir = backupRoot
|
|
187
|
+
writeFileSync(target, next)
|
|
188
|
+
}
|
|
189
|
+
result.updated.push(agent.file)
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
if (!dryRun) writeReferenceFile({ configDir, packageRoot })
|
|
193
|
+
|
|
194
|
+
return result
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Copy the artifacts reference (docs/ARTIFACTS.md) next to the agents so the
|
|
199
|
+
* installed prompts can point at it. Best-effort.
|
|
200
|
+
*/
|
|
201
|
+
export function writeReferenceFile({ configDir, packageRoot = PACKAGE_ROOT, dryRun = false, overwrite = true } = {}) {
|
|
202
|
+
const src = join(packageRoot, "docs", "ARTIFACTS.md")
|
|
203
|
+
if (!existsSync(src)) return false
|
|
204
|
+
const dest = join(configDir, "teamwork", "ARTIFACTS.md")
|
|
205
|
+
if (existsSync(dest) && !overwrite) return true
|
|
206
|
+
if (!dryRun) {
|
|
207
|
+
mkdirSync(join(configDir, "teamwork"), { recursive: true })
|
|
208
|
+
copyFileSync(src, dest)
|
|
209
|
+
}
|
|
210
|
+
return true
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Best-effort, non-interactive install used by the plugin loader: creates only
|
|
215
|
+
* the agent files that are completely missing and leaves every existing file
|
|
216
|
+
* untouched (so a user's `init` choices are never clobbered). Returns the list
|
|
217
|
+
* of created agent files, which is empty when nothing needed doing.
|
|
218
|
+
*/
|
|
219
|
+
export function ensureAgents({ configDir = resolveConfigDir(), packageRoot = PACKAGE_ROOT, models } = {}) {
|
|
220
|
+
const targetDir = join(configDir, "agents", "team")
|
|
221
|
+
const sourceDir = join(packageRoot, "agents", "team")
|
|
222
|
+
const map = models || readModelMap(configDir)
|
|
223
|
+
const created = []
|
|
224
|
+
|
|
225
|
+
for (const agent of TEAM_AGENTS) {
|
|
226
|
+
const target = join(targetDir, agent.file)
|
|
227
|
+
if (existsSync(target)) continue
|
|
228
|
+
const source = join(sourceDir, agent.file)
|
|
229
|
+
if (!existsSync(source)) continue
|
|
230
|
+
mkdirSync(targetDir, { recursive: true })
|
|
231
|
+
writeFileSync(target, applyModel(readFileSync(source, "utf8"), map[agent.id] || agent.defaultModel))
|
|
232
|
+
created.push(agent.file)
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
try { writeReferenceFile({ configDir, packageRoot, overwrite: false }) } catch {}
|
|
236
|
+
return created
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// --- opencode.json(c) registration -----------------------------------------
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Strip // and block comments plus trailing commas, fully string-aware.
|
|
243
|
+
* (The previous trailing-comma pass used a regex that corrupted string values
|
|
244
|
+
* containing `, }` / `, ]`.)
|
|
245
|
+
*/
|
|
246
|
+
export function stripJsonComments(input) {
|
|
247
|
+
let out = ""
|
|
248
|
+
let inString = false
|
|
249
|
+
let inLine = false
|
|
250
|
+
let inBlock = false
|
|
251
|
+
for (let i = 0; i < input.length; i++) {
|
|
252
|
+
const c = input[i]
|
|
253
|
+
const n = input[i + 1]
|
|
254
|
+
if (inLine) {
|
|
255
|
+
if (c === "\n") {
|
|
256
|
+
inLine = false
|
|
257
|
+
out += c
|
|
258
|
+
}
|
|
259
|
+
continue
|
|
260
|
+
}
|
|
261
|
+
if (inBlock) {
|
|
262
|
+
if (c === "*" && n === "/") {
|
|
263
|
+
inBlock = false
|
|
264
|
+
i++
|
|
265
|
+
}
|
|
266
|
+
continue
|
|
267
|
+
}
|
|
268
|
+
if (inString) {
|
|
269
|
+
out += c
|
|
270
|
+
if (c === "\\") {
|
|
271
|
+
out += n ?? ""
|
|
272
|
+
i++
|
|
273
|
+
} else if (c === '"') {
|
|
274
|
+
inString = false
|
|
275
|
+
}
|
|
276
|
+
continue
|
|
277
|
+
}
|
|
278
|
+
if (c === '"') {
|
|
279
|
+
inString = true
|
|
280
|
+
out += c
|
|
281
|
+
} else if (c === "/" && n === "/") {
|
|
282
|
+
inLine = true
|
|
283
|
+
i++
|
|
284
|
+
} else if (c === "/" && n === "*") {
|
|
285
|
+
inBlock = true
|
|
286
|
+
i++
|
|
287
|
+
} else {
|
|
288
|
+
out += c
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
// Remove trailing commas before } or ], string-aware.
|
|
292
|
+
let res = ""
|
|
293
|
+
inString = false
|
|
294
|
+
for (let i = 0; i < out.length; i++) {
|
|
295
|
+
const c = out[i]
|
|
296
|
+
if (inString) {
|
|
297
|
+
res += c
|
|
298
|
+
if (c === "\\") {
|
|
299
|
+
res += out[i + 1] ?? ""
|
|
300
|
+
i++
|
|
301
|
+
} else if (c === '"') {
|
|
302
|
+
inString = false
|
|
303
|
+
}
|
|
304
|
+
continue
|
|
305
|
+
}
|
|
306
|
+
if (c === '"') {
|
|
307
|
+
inString = true
|
|
308
|
+
res += c
|
|
309
|
+
continue
|
|
310
|
+
}
|
|
311
|
+
if (c === ",") {
|
|
312
|
+
let j = i + 1
|
|
313
|
+
while (j < out.length && /\s/.test(out[j])) j++
|
|
314
|
+
if (out[j] === "}" || out[j] === "]") continue
|
|
315
|
+
}
|
|
316
|
+
res += c
|
|
317
|
+
}
|
|
318
|
+
return res
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** True if the raw text contains a comment token outside of a string. */
|
|
322
|
+
export function hasJsonComments(raw) {
|
|
323
|
+
let inString = false
|
|
324
|
+
for (let i = 0; i < raw.length; i++) {
|
|
325
|
+
const c = raw[i]
|
|
326
|
+
const n = raw[i + 1]
|
|
327
|
+
if (inString) {
|
|
328
|
+
if (c === "\\") i++
|
|
329
|
+
else if (c === '"') inString = false
|
|
330
|
+
continue
|
|
331
|
+
}
|
|
332
|
+
if (c === '"') inString = true
|
|
333
|
+
else if (c === "/" && (n === "/" || n === "*")) return true
|
|
334
|
+
}
|
|
335
|
+
return false
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function isTeamworkEntry(entry) {
|
|
339
|
+
const value = typeof entry === "string" ? entry : entry && typeof entry === "object" ? entry.package : undefined
|
|
340
|
+
return typeof value === "string" && value.includes("opencode-teamwork")
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
/** Find the active opencode.json(c) in a config dir. */
|
|
344
|
+
export function findConfigFile(configDir) {
|
|
345
|
+
for (const name of ["opencode.jsonc", "opencode.json", "opencode.json5"]) {
|
|
346
|
+
const file = join(configDir, name)
|
|
347
|
+
if (existsSync(file)) return file
|
|
348
|
+
}
|
|
349
|
+
return undefined
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Add `@heretek-ai/opencode-teamwork-v2` to the `plugins` array in opencode.json(c), unless
|
|
354
|
+
* some existing entry already points at an opencode-teamwork plugin.
|
|
355
|
+
*/
|
|
356
|
+
export function registerPlugin({ configDir, packageName = PACKAGE_NAME, dryRun = false }) {
|
|
357
|
+
const file = findConfigFile(configDir) || join(configDir, "opencode.json")
|
|
358
|
+
const exists = existsSync(file)
|
|
359
|
+
|
|
360
|
+
// Never follow a symlinked config, and never rewrite a commented (JSONC)
|
|
361
|
+
// config — JSON.stringify would drop comments and (previously) corrupt values.
|
|
362
|
+
if (exists) {
|
|
363
|
+
try {
|
|
364
|
+
if (lstatSync(file).isSymbolicLink()) return { status: "symlink", file }
|
|
365
|
+
} catch {}
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const raw = exists
|
|
369
|
+
? readFileSync(file, "utf8")
|
|
370
|
+
: '{\n "$schema": "https://opencode.ai/config.json"\n}\n'
|
|
371
|
+
|
|
372
|
+
if (exists && hasJsonComments(raw)) {
|
|
373
|
+
return { status: /opencode-teamwork/.test(raw) ? "already" : "commented", file }
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
let data
|
|
377
|
+
try {
|
|
378
|
+
data = JSON.parse(stripJsonComments(raw))
|
|
379
|
+
} catch (error) {
|
|
380
|
+
return { status: "unparsed", file, error }
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
data.plugins = Array.isArray(data.plugins) ? data.plugins : []
|
|
384
|
+
const existing = data.plugins.find(isTeamworkEntry)
|
|
385
|
+
if (existing !== undefined) return { status: "already", file, entry: existing }
|
|
386
|
+
|
|
387
|
+
data.plugins.push(packageName)
|
|
388
|
+
if (!dryRun) {
|
|
389
|
+
mkdirSync(configDir, { recursive: true })
|
|
390
|
+
if (exists) copyFileSync(file, `${file}.bak.${timestamp()}`)
|
|
391
|
+
writeFileSync(file, JSON.stringify(data, null, 2) + "\n")
|
|
392
|
+
}
|
|
393
|
+
return { status: "added", file, entry: packageName }
|
|
394
|
+
}
|