@plainconceptsplatform/agent-harness 3.4.1 → 3.6.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.
Files changed (96) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +455 -454
  3. package/cli/commands/join.js +259 -259
  4. package/cli/commands/migrate.js +310 -310
  5. package/cli/commands/shared.js +27 -27
  6. package/cli/commands/single.js +79 -79
  7. package/cli/commands/wizard.js +134 -134
  8. package/cli/fragments/ops-backlog/az.md +28 -28
  9. package/cli/fragments/ops-backlog/gh.md +28 -28
  10. package/cli/fragments/ops-backlog/jira.md +28 -28
  11. package/cli/fragments/ops-review/az.md +62 -62
  12. package/cli/fragments/ops-review/gh.md +51 -51
  13. package/cli/fragments/ops-review/gl.md +55 -55
  14. package/cli/fragments/ops-ship/gh.md +67 -67
  15. package/cli/fragments/ops-ship/gl.md +84 -84
  16. package/cli/index.js +116 -116
  17. package/cli/presets/clean.json +21 -21
  18. package/cli/presets/models.json +68 -68
  19. package/cli/presets/optimization.json +32 -32
  20. package/cli/presets/platforms.json +76 -76
  21. package/cli/presets/source.json +23 -23
  22. package/cli/steps/clean/index.js +120 -120
  23. package/cli/steps/copy/agents.js +120 -120
  24. package/cli/steps/copy/fullstack-engineer.js +89 -89
  25. package/cli/steps/copy/opencode-json.js +324 -324
  26. package/cli/steps/copy/skills.js +316 -316
  27. package/cli/steps/models/format.js +88 -88
  28. package/cli/steps/models/index.js +64 -64
  29. package/cli/steps/openspec/index.js +136 -136
  30. package/cli/steps/optimization/codegraph.js +141 -141
  31. package/cli/steps/optimization/detect.js +66 -66
  32. package/cli/steps/optimization/humanizer.js +17 -17
  33. package/cli/steps/optimization/index.js +158 -158
  34. package/cli/steps/optimization/memory.js +91 -91
  35. package/cli/steps/optimization/patch-guardrails.js +111 -111
  36. package/cli/steps/optimization/simple-english.js +17 -17
  37. package/cli/steps/optimization/skills-lock.js +30 -30
  38. package/cli/steps/platform/index.js +109 -109
  39. package/cli/steps/source/index.js +123 -123
  40. package/cli/utils/agent-color.js +111 -111
  41. package/cli/utils/copy.js +134 -134
  42. package/cli/utils/exec-spinner.js +47 -47
  43. package/cli/utils/exec.js +134 -134
  44. package/cli/utils/legacy-check.js +30 -30
  45. package/cli/utils/models-cache.js +58 -58
  46. package/cli/utils/models-pricing.js +42 -42
  47. package/cli/utils/paths.js +81 -81
  48. package/cli/utils/process.js +3 -3
  49. package/cli/utils/terminal.js +6 -6
  50. package/cli/utils/update-manifest.js +75 -75
  51. package/harness/.opencode/_gitignore +10 -10
  52. package/harness/.opencode/commands/ops-backlog.md +10 -10
  53. package/harness/.opencode/commands/ops-review.md +10 -10
  54. package/harness/.opencode/commands/ops-ship.md +9 -9
  55. package/harness/.opencode/commands/plan-archive.md +7 -7
  56. package/harness/.opencode/commands/plan-explore.md +11 -11
  57. package/harness/.opencode/commands/plan-propose.md +11 -11
  58. package/harness/.opencode/commands/plan-quick.md +7 -7
  59. package/harness/.opencode/commands/plan-story.md +11 -11
  60. package/harness/.opencode/commands/repo-audit.md +7 -7
  61. package/harness/.opencode/commands/repo-help.md +5 -5
  62. package/harness/.opencode/package.json +5 -5
  63. package/harness/.opencode/plugins/pc-commit-coauthor.js +41 -0
  64. package/harness/.opencode/plugins/pc-subagent-monitor.js +184 -184
  65. package/harness/.opencode/plugins/pc-subagent-tiers.js +367 -367
  66. package/harness/.opencode/plugins/pc-system-reminders.js +386 -386
  67. package/harness/.opencode/scripts/check-diff.mjs +252 -244
  68. package/harness/.opencode/scripts/code-rules.mjs +288 -288
  69. package/harness/ARCHITECTURE.md +13 -13
  70. package/harness/DESIGN.md +13 -13
  71. package/harness/opencode.jsonc +36 -36
  72. package/harness/openspec/config.yaml +20 -20
  73. package/harness/skills-lock.json +17 -17
  74. package/package.json +14 -12
  75. package/skills/agent-harness-cli/SKILL.md +86 -86
  76. package/skills/pc-guardrails-generic/SKILL.md +53 -53
  77. package/skills/pc-guardrails-project/SKILL.md +8 -8
  78. package/skills/pc-make-architecture/structure-template.md +64 -64
  79. package/skills/pc-make-engineer/SKILL.md +59 -59
  80. package/skills/pc-make-engineer/template.md +36 -36
  81. package/skills/pc-make-guardrails/category-reference.md +112 -112
  82. package/skills/pc-make-merge-risk-assess/SKILL.md +70 -70
  83. package/skills/pc-make-merge-risk-assess/category-reference.md +114 -114
  84. package/skills/pc-ops-ship/SKILL.md +22 -22
  85. package/skills/pc-plan-apply/SKILL.md +88 -86
  86. package/skills/pc-plan-apply/simple-mode.md +21 -21
  87. package/skills/pc-plan-explore/SKILL.md +21 -21
  88. package/skills/pc-plan-goal/SKILL.md +91 -91
  89. package/skills/pc-plan-goal/failure-policy.md +30 -30
  90. package/skills/pc-plan-goal/output-mode.md +10 -10
  91. package/skills/pc-plan-propose/SKILL.md +125 -125
  92. package/skills/pc-plan-propose/task-annotation.md +39 -39
  93. package/skills/pc-plan-quick/SKILL.md +46 -46
  94. package/skills/pc-repo-audit/SKILL.md +44 -44
  95. package/skills/pc-repo-help/SKILL.md +87 -87
  96. package/skills/pc-repo-verify/SKILL.md +150 -150
@@ -1,367 +1,367 @@
1
- // pc-subagent-tiers: on startup, reads *-engineer.md templates and creates
2
- // tier variant agent files with the resolved model, plus the two primary agents
3
- // the user actually talks to. Everything generated here is gitignored and
4
- // rebuilt every startup. Model resolution: user override > team config.
5
- //
6
- // Agent topology:
7
- // build.md / plan.md mode: primary the only agents a human selects.
8
- // Both are fullstack-engineer with a
9
- // tier model; plan can neither edit
10
- // nor spawn.
11
- // planner.md mode: all fullstack-engineer on the plan tier
12
- // that may write but not spawn. The
13
- // thinking commands run on it, and a
14
- // CI lead spawns it for propose and
15
- // archive, so those steps take the
16
- // plan model whatever the session's is.
17
- // fullstack-engineer.md mode: subagent the shared body of build and plan,
18
- // and the fallback worker.
19
- // *-engineer.md mode: subagent specialists, spawned by subagent().
20
- // *-engineer.<tier>.md mode: subagent the same specialist pinned to a tier.
21
- //
22
- // OpenCode 2 discovers agents from .opencode/agents/*.md and overrides a built-in
23
- // by ID, so the generated files replace the built-in build/plan. The plugin API's
24
- // agent editor can update or remove an existing agent but cannot add one, so file
25
- // generation is the mechanism: writing the files in setup, before agents resolve,
26
- // is what makes them visible.
27
-
28
- import { Plugin, Model } from "@opencode/plugin"
29
- import fs from "node:fs/promises"
30
- import path from "node:path"
31
-
32
- const TIERS = ["build", "fast", "plan"]
33
-
34
- // The two primaries, and the tier each takes its model from. plan denies edit
35
- // and subagent: a planning session cannot mutate the tree itself, and it cannot
36
- // spawn a worker that would do it on its behalf. shell stays allowed because the
37
- // planning skills shell out to git and openspec to read state, and
38
- // pc-system-reminders holds it to inspection commands.
39
- const PRIMARIES = {
40
- build: {
41
- tier: "build",
42
- color: "primary",
43
- description: "Implement changes in this repository. Full write access, spawns specialist engineers for parallel work.",
44
- permissions: null,
45
- },
46
- plan: {
47
- tier: "plan",
48
- color: "warning",
49
- description: "Explore and plan without touching the tree. Read-only: proposes work for build to carry out.",
50
- permissions: [
51
- { action: "edit", resource: "*", effect: "deny" },
52
- { action: "subagent", resource: "*", effect: "deny" },
53
- ],
54
- },
55
- planner: {
56
- tier: "plan",
57
- mode: "all",
58
- color: "info",
59
- description: "Write plans, proposals, stories, reviews and archives on the plan model. Edits the tree, never spawns workers.",
60
- permissions: [{ action: "subagent", resource: "*", effect: "deny" }],
61
- },
62
- }
63
-
64
- // opencode's theme keywords. Treated as unset so a name-derived hex wins: the
65
- // old /make-engineer template asked whoever ran it to pick one of these and
66
- // avoid collisions by hand, which does not survive more than a few agents.
67
- const THEME_COLORS = new Set(["primary", "secondary", "accent", "success", "warning", "error", "info"])
68
-
69
- // Fields V1 agent frontmatter used that V2 forbids. Stripped on sight so a repo
70
- // upgraded in place does not carry a definition V2 refuses to load.
71
- const LEGACY_FIELDS = [
72
- "model",
73
- "permission",
74
- "prompt",
75
- "disable",
76
- "disabled",
77
- "temperature",
78
- "top_p",
79
- "maxSteps",
80
- "tools",
81
- ]
82
-
83
- // Mirrors cli/utils/agent-color.js in the CLI, duplicated because a plugin has
84
- // to stand alone in the consumer repo. agent-color.test.js asserts the two stay
85
- // in step; change one and change the other.
86
- //
87
- // Only the hue is hashed. Fixed saturation and lightness are what keep every
88
- // result usable: hashing those too would eventually produce a near-grey,
89
- // near-black or near-white agent, invisible against one theme or the other.
90
- function agentColor(name) {
91
- let h = 0x811c9dc5
92
- for (let i = 0; i < name.length; i++) {
93
- h ^= name.charCodeAt(i)
94
- h = Math.imul(h, 0x01000193) >>> 0
95
- }
96
- const hue = (h >>> 0) % 360
97
- const sat = 0.68
98
- const light = 0.52
99
- const c = (1 - Math.abs(2 * light - 1)) * sat
100
- const x = c * (1 - Math.abs(((hue / 60) % 2) - 1))
101
- const m = light - c / 2
102
- const [r, g, b] =
103
- hue < 60 ? [c, x, 0] :
104
- hue < 120 ? [x, c, 0] :
105
- hue < 180 ? [0, c, x] :
106
- hue < 240 ? [0, x, c] :
107
- hue < 300 ? [x, 0, c] :
108
- [c, 0, x]
109
- const toHex = v => Math.round((v + m) * 255).toString(16).padStart(2, "0")
110
- return `#${toHex(r)}${toHex(g)}${toHex(b)}`.toUpperCase()
111
- }
112
-
113
- /** A theme keyword or a missing value yields to the derived hex; a hex stays. */
114
- function shouldDeriveColor(current) {
115
- if (!current) return true
116
- return THEME_COLORS.has(current.trim().toLowerCase())
117
- }
118
-
119
- /**
120
- * Render a colour for YAML frontmatter.
121
- *
122
- * A hex has to be quoted. `#` opens a comment in YAML, so `color: #D83155`
123
- * parses as null and opencode refuses the agent with "Invalid input color".
124
- * Theme keywords need no quoting and stay bare.
125
- */
126
- function yamlColor(value) {
127
- return value.startsWith("#") ? `"${value}"` : value
128
- }
129
-
130
- function unquoteColor(raw) {
131
- return (raw ?? "").trim().replace(/^["']/, "").replace(/["']$/, "")
132
- }
133
-
134
- function splitFrontmatter(content) {
135
- const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/)
136
- if (!match) return { frontmatter: null, body: content }
137
- return { frontmatter: match[1], body: content.slice(match[0].length) }
138
- }
139
-
140
- function stripLegacyFields(frontmatter) {
141
- const lines = frontmatter.split(/\r?\n/)
142
- const kept = []
143
- for (let i = 0; i < lines.length; i++) {
144
- const key = lines[i].match(/^([A-Za-z0-9_-]+):/)?.[1]
145
- if (key && LEGACY_FIELDS.includes(key)) {
146
- // Drop the key and any indented continuation lines that belong to it.
147
- i++
148
- while (i < lines.length && /^\s+\S/.test(lines[i])) i++
149
- i--
150
- continue
151
- }
152
- kept.push(lines[i])
153
- }
154
- return kept.join("\n").replace(/\n{3,}/g, "\n\n").trim()
155
- }
156
-
157
- function setScalar(frontmatter, key, value) {
158
- const line = `${key}: ${value}`
159
- // String operations rather than a built RegExp: `key` is one of this module's
160
- // own constants, so the pattern would be safe, but a dynamic regexp here is a
161
- // ReDoS-shaped pattern that static analysis rightly refuses to clear.
162
- const lines = frontmatter.split(/\r?\n/)
163
- const index = lines.findIndex(current => current.startsWith(`${key}:`))
164
- if (index === -1) {
165
- return frontmatter ? `${line}\n${frontmatter}` : line
166
- }
167
- lines[index] = line
168
- return lines.join("\n")
169
- }
170
-
171
- function permissionsYaml(permissions) {
172
- return [
173
- "permissions:",
174
- ...permissions.flatMap(p => [
175
- ` - action: ${p.action}`,
176
- ` resource: ${p.resource}`,
177
- ` effect: ${p.effect}`,
178
- ]),
179
- ].join("\n")
180
- }
181
-
182
- /** The colour line an agent should have, or null when the current one is right. */
183
- function colorLineFor(name, rawCurrent) {
184
- const current = unquoteColor(rawCurrent)
185
- const target = shouldDeriveColor(current) ? agentColor(name) : current
186
- const rendered = yamlColor(target)
187
- return (rawCurrent ?? "").trim() === rendered ? null : `color: ${rendered}`
188
- }
189
-
190
- const FULLSTACK_NAME = "fullstack-engineer"
191
- const FULLSTACK_TEMPLATE = `${FULLSTACK_NAME}.md`
192
-
193
- /** Rewrite a template's frontmatter to a clean V2 subagent definition. */
194
- function normalizeTemplate(content, name) {
195
- const { frontmatter, body } = splitFrontmatter(content)
196
- if (frontmatter === null) return `---\nmode: subagent\ncolor: ${yamlColor(agentColor(name))}\n---\n\n${content}`
197
-
198
- let fm = stripLegacyFields(frontmatter)
199
- fm = setScalar(fm, "mode", "subagent")
200
- const colorLine = colorLineFor(name, fm.match(/^color:\s*(.+)$/m)?.[1])
201
- if (colorLine) fm = setScalar(fm, "color", colorLine.slice("color: ".length))
202
- return `---\n${fm}\n---\n${body}`
203
- }
204
-
205
- /** A tier-pinned copy of a specialist: same body, resolved model. */
206
- function buildVariant(templateContent, model) {
207
- const { frontmatter, body } = splitFrontmatter(templateContent)
208
- let fm = stripLegacyFields(frontmatter ?? "")
209
- fm = setScalar(fm, "mode", "subagent")
210
- fm = setScalar(fm, "model", model)
211
- // Hidden by default: a tier is chosen by whoever writes the task, not picked
212
- // from the @ menu. Without this the menu lists every specialist once per tier.
213
- fm = setScalar(fm, "hidden", "true")
214
- if (!/^color:/m.test(fm)) {
215
- const name = ""
216
- fm = setScalar(fm, "color", name ? yamlColor(agentColor(name)) : yamlColor(agentColor("engineer")))
217
- }
218
- return `---\n${fm}\n---\n${body}`
219
- }
220
-
221
- /**
222
- * Build a primary from the fullstack body: same identity and the same
223
- * ## Abilities block, with our own frontmatter on top. The body is taken
224
- * verbatim so /make-engineer only has to maintain fullstack-engineer.md and
225
- * both primaries inherit whatever it lists.
226
- */
227
- function buildPrimary(spec, fullstackContent, model) {
228
- const { body } = splitFrontmatter(fullstackContent)
229
- const lines = [
230
- "---",
231
- `description: ${spec.description}`,
232
- `mode: ${spec.mode ?? "primary"}`,
233
- ]
234
- if (model) lines.push(`model: ${model}`)
235
- lines.push(`color: ${yamlColor(spec.color)}`)
236
- if (spec.permissions) lines.push(permissionsYaml(spec.permissions))
237
- lines.push("---")
238
- return `${lines.join("\n")}\n\n${body.trim()}\n`
239
- }
240
-
241
- async function readJson(filePath) {
242
- try {
243
- return JSON.parse(await fs.readFile(filePath, "utf-8"))
244
- } catch {
245
- return null
246
- }
247
- }
248
-
249
- async function scanEngineers(agentsDir) {
250
- try {
251
- const entries = await fs.readdir(agentsDir)
252
- return {
253
- templates: entries
254
- .filter(f => /^[\w-]+-engineer\.md$/.test(f) && f !== FULLSTACK_TEMPLATE)
255
- .map(f => f.replace(/\.md$/, "")),
256
- variantFiles: entries.filter(f => /^[\w-]+-engineer\.(build|fast|plan)\.md$/.test(f)),
257
- hasFullstack: entries.includes(FULLSTACK_TEMPLATE),
258
- }
259
- } catch {
260
- return { templates: [], variantFiles: [], hasFullstack: false }
261
- }
262
- }
263
-
264
- async function writeIfChanged(filePath, content) {
265
- try {
266
- if ((await fs.readFile(filePath, "utf-8")) === content) return
267
- } catch {
268
- // file missing, write it
269
- }
270
- const tmpPath = `${filePath}.tmp`
271
- await fs.writeFile(tmpPath, content, "utf-8")
272
- await fs.rename(tmpPath, filePath)
273
- }
274
-
275
- export default Plugin.define({
276
- id: "pc.subagent-tiers",
277
- async setup(ctx) {
278
- const root = ctx.location.directory
279
- const agentsDir = path.join(root, ".opencode", "agents")
280
-
281
- try {
282
- const [user, team] = await Promise.all([
283
- readJson(path.join(root, ".opencode", "harness.user.json")),
284
- readJson(path.join(root, ".opencode", "harness.json")),
285
- ])
286
- const models = {}
287
- for (const tier of TIERS) {
288
- models[tier] = user?.models?.[tier] ?? team?.models?.[tier] ?? null
289
- }
290
- const available = TIERS.filter(t => models[t])
291
-
292
- const { templates, variantFiles, hasFullstack } = await scanEngineers(agentsDir)
293
-
294
- if (hasFullstack) {
295
- const fullstackPath = path.join(agentsDir, FULLSTACK_TEMPLATE)
296
- const rawFullstack = await fs.readFile(fullstackPath, "utf-8")
297
- const fullstack = normalizeTemplate(rawFullstack, FULLSTACK_NAME)
298
- if (fullstack !== rawFullstack) {
299
- await writeIfChanged(fullstackPath, fullstack)
300
- console.error("[pc-subagent-tiers] Normalized fullstack-engineer.md (V2 subagent)")
301
- }
302
-
303
- for (const [name, spec] of Object.entries(PRIMARIES)) {
304
- await writeIfChanged(
305
- path.join(agentsDir, `${name}.md`),
306
- buildPrimary(spec, fullstack, models[spec.tier]),
307
- )
308
- }
309
- console.error(`[pc-subagent-tiers] Wrote primaries: build (${models.build ?? "session model"}), plan and planner (${models.plan ?? "session model"})`)
310
- } else {
311
- console.error(`[pc-subagent-tiers] ${FULLSTACK_TEMPLATE} missing: build and plan not generated`)
312
- }
313
-
314
- const keepSet = new Set()
315
- const variantsToWrite = []
316
- for (const name of templates) {
317
- const rawContent = await fs.readFile(path.join(agentsDir, `${name}.md`), "utf-8")
318
- const content = normalizeTemplate(rawContent, name)
319
- if (content !== rawContent) {
320
- await writeIfChanged(path.join(agentsDir, `${name}.md`), content)
321
- console.error(`[pc-subagent-tiers] Normalized ${name}.md (V2 subagent)`)
322
- }
323
- for (const tier of available) {
324
- const file = `${name}.${tier}.md`
325
- variantsToWrite.push({ file, path: path.join(agentsDir, file), content: buildVariant(content, models[tier]) })
326
- keepSet.add(file)
327
- }
328
- }
329
-
330
- await Promise.all(variantsToWrite.map(v => writeIfChanged(v.path, v.content)))
331
- await Promise.all(
332
- variantFiles.filter(f => !keepSet.has(f)).map(f => fs.unlink(path.join(agentsDir, f)).catch(() => {})),
333
- )
334
-
335
- if (variantsToWrite.length > 0) {
336
- console.error(`[pc-subagent-tiers] Created ${variantsToWrite.length} variant files (${templates.length} engineers x ${available.length} tiers)`)
337
- } else if (templates.length > 0) {
338
- console.error(`[pc-subagent-tiers] No variants created. Models: ${JSON.stringify(models)}`)
339
- }
340
-
341
- // Best effort: if V2 already discovered these agents (same startup), pin
342
- // the primaries' model and plan's read-only permissions in memory too.
343
- if (typeof ctx.agent?.transform === "function") {
344
- await ctx.agent.transform(editor => {
345
- for (const [id, spec] of Object.entries(PRIMARIES)) {
346
- const existing = editor.get(id)
347
- if (!existing) continue
348
- const model = models[spec.tier]
349
- if (model) {
350
- try {
351
- existing.model = Model.Ref.parse(model)
352
- } catch {
353
- // invalid model ref; leave undefined so session model applies
354
- }
355
- }
356
- existing.mode = spec.mode ?? "primary"
357
- existing.description = spec.description
358
- if (spec.permissions) existing.permissions = spec.permissions
359
- }
360
- })
361
- await ctx.agent.reload?.()
362
- }
363
- } catch (error) {
364
- console.error(`[pc-subagent-tiers] Error: ${error?.message}`)
365
- }
366
- },
367
- })
1
+ // pc-subagent-tiers: on startup, reads *-engineer.md templates and creates
2
+ // tier variant agent files with the resolved model, plus the two primary agents
3
+ // the user actually talks to. Everything generated here is gitignored and
4
+ // rebuilt every startup. Model resolution: user override > team config.
5
+ //
6
+ // Agent topology:
7
+ // build.md / plan.md mode: primary the only agents a human selects.
8
+ // Both are fullstack-engineer with a
9
+ // tier model; plan can neither edit
10
+ // nor spawn.
11
+ // planner.md mode: all fullstack-engineer on the plan tier
12
+ // that may write but not spawn. The
13
+ // thinking commands run on it, and a
14
+ // CI lead spawns it for propose and
15
+ // archive, so those steps take the
16
+ // plan model whatever the session's is.
17
+ // fullstack-engineer.md mode: subagent the shared body of build and plan,
18
+ // and the fallback worker.
19
+ // *-engineer.md mode: subagent specialists, spawned by subagent().
20
+ // *-engineer.<tier>.md mode: subagent the same specialist pinned to a tier.
21
+ //
22
+ // OpenCode 2 discovers agents from .opencode/agents/*.md and overrides a built-in
23
+ // by ID, so the generated files replace the built-in build/plan. The plugin API's
24
+ // agent editor can update or remove an existing agent but cannot add one, so file
25
+ // generation is the mechanism: writing the files in setup, before agents resolve,
26
+ // is what makes them visible.
27
+
28
+ import { Plugin, Model } from "@opencode/plugin"
29
+ import fs from "node:fs/promises"
30
+ import path from "node:path"
31
+
32
+ const TIERS = ["build", "fast", "plan"]
33
+
34
+ // The two primaries, and the tier each takes its model from. plan denies edit
35
+ // and subagent: a planning session cannot mutate the tree itself, and it cannot
36
+ // spawn a worker that would do it on its behalf. shell stays allowed because the
37
+ // planning skills shell out to git and openspec to read state, and
38
+ // pc-system-reminders holds it to inspection commands.
39
+ const PRIMARIES = {
40
+ build: {
41
+ tier: "build",
42
+ color: "primary",
43
+ description: "Implement changes in this repository. Full write access, spawns specialist engineers for parallel work.",
44
+ permissions: null,
45
+ },
46
+ plan: {
47
+ tier: "plan",
48
+ color: "warning",
49
+ description: "Explore and plan without touching the tree. Read-only: proposes work for build to carry out.",
50
+ permissions: [
51
+ { action: "edit", resource: "*", effect: "deny" },
52
+ { action: "subagent", resource: "*", effect: "deny" },
53
+ ],
54
+ },
55
+ planner: {
56
+ tier: "plan",
57
+ mode: "all",
58
+ color: "info",
59
+ description: "Write plans, proposals, stories, reviews and archives on the plan model. Edits the tree, never spawns workers.",
60
+ permissions: [{ action: "subagent", resource: "*", effect: "deny" }],
61
+ },
62
+ }
63
+
64
+ // opencode's theme keywords. Treated as unset so a name-derived hex wins: the
65
+ // old /make-engineer template asked whoever ran it to pick one of these and
66
+ // avoid collisions by hand, which does not survive more than a few agents.
67
+ const THEME_COLORS = new Set(["primary", "secondary", "accent", "success", "warning", "error", "info"])
68
+
69
+ // Fields V1 agent frontmatter used that V2 forbids. Stripped on sight so a repo
70
+ // upgraded in place does not carry a definition V2 refuses to load.
71
+ const LEGACY_FIELDS = [
72
+ "model",
73
+ "permission",
74
+ "prompt",
75
+ "disable",
76
+ "disabled",
77
+ "temperature",
78
+ "top_p",
79
+ "maxSteps",
80
+ "tools",
81
+ ]
82
+
83
+ // Mirrors cli/utils/agent-color.js in the CLI, duplicated because a plugin has
84
+ // to stand alone in the consumer repo. agent-color.test.js asserts the two stay
85
+ // in step; change one and change the other.
86
+ //
87
+ // Only the hue is hashed. Fixed saturation and lightness are what keep every
88
+ // result usable: hashing those too would eventually produce a near-grey,
89
+ // near-black or near-white agent, invisible against one theme or the other.
90
+ function agentColor(name) {
91
+ let h = 0x811c9dc5
92
+ for (let i = 0; i < name.length; i++) {
93
+ h ^= name.charCodeAt(i)
94
+ h = Math.imul(h, 0x01000193) >>> 0
95
+ }
96
+ const hue = (h >>> 0) % 360
97
+ const sat = 0.68
98
+ const light = 0.52
99
+ const c = (1 - Math.abs(2 * light - 1)) * sat
100
+ const x = c * (1 - Math.abs(((hue / 60) % 2) - 1))
101
+ const m = light - c / 2
102
+ const [r, g, b] =
103
+ hue < 60 ? [c, x, 0] :
104
+ hue < 120 ? [x, c, 0] :
105
+ hue < 180 ? [0, c, x] :
106
+ hue < 240 ? [0, x, c] :
107
+ hue < 300 ? [x, 0, c] :
108
+ [c, 0, x]
109
+ const toHex = v => Math.round((v + m) * 255).toString(16).padStart(2, "0")
110
+ return `#${toHex(r)}${toHex(g)}${toHex(b)}`.toUpperCase()
111
+ }
112
+
113
+ /** A theme keyword or a missing value yields to the derived hex; a hex stays. */
114
+ function shouldDeriveColor(current) {
115
+ if (!current) return true
116
+ return THEME_COLORS.has(current.trim().toLowerCase())
117
+ }
118
+
119
+ /**
120
+ * Render a colour for YAML frontmatter.
121
+ *
122
+ * A hex has to be quoted. `#` opens a comment in YAML, so `color: #D83155`
123
+ * parses as null and opencode refuses the agent with "Invalid input color".
124
+ * Theme keywords need no quoting and stay bare.
125
+ */
126
+ function yamlColor(value) {
127
+ return value.startsWith("#") ? `"${value}"` : value
128
+ }
129
+
130
+ function unquoteColor(raw) {
131
+ return (raw ?? "").trim().replace(/^["']/, "").replace(/["']$/, "")
132
+ }
133
+
134
+ function splitFrontmatter(content) {
135
+ const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n?/)
136
+ if (!match) return { frontmatter: null, body: content }
137
+ return { frontmatter: match[1], body: content.slice(match[0].length) }
138
+ }
139
+
140
+ function stripLegacyFields(frontmatter) {
141
+ const lines = frontmatter.split(/\r?\n/)
142
+ const kept = []
143
+ for (let i = 0; i < lines.length; i++) {
144
+ const key = lines[i].match(/^([A-Za-z0-9_-]+):/)?.[1]
145
+ if (key && LEGACY_FIELDS.includes(key)) {
146
+ // Drop the key and any indented continuation lines that belong to it.
147
+ i++
148
+ while (i < lines.length && /^\s+\S/.test(lines[i])) i++
149
+ i--
150
+ continue
151
+ }
152
+ kept.push(lines[i])
153
+ }
154
+ return kept.join("\n").replace(/\n{3,}/g, "\n\n").trim()
155
+ }
156
+
157
+ function setScalar(frontmatter, key, value) {
158
+ const line = `${key}: ${value}`
159
+ // String operations rather than a built RegExp: `key` is one of this module's
160
+ // own constants, so the pattern would be safe, but a dynamic regexp here is a
161
+ // ReDoS-shaped pattern that static analysis rightly refuses to clear.
162
+ const lines = frontmatter.split(/\r?\n/)
163
+ const index = lines.findIndex(current => current.startsWith(`${key}:`))
164
+ if (index === -1) {
165
+ return frontmatter ? `${line}\n${frontmatter}` : line
166
+ }
167
+ lines[index] = line
168
+ return lines.join("\n")
169
+ }
170
+
171
+ function permissionsYaml(permissions) {
172
+ return [
173
+ "permissions:",
174
+ ...permissions.flatMap(p => [
175
+ ` - action: ${p.action}`,
176
+ ` resource: ${p.resource}`,
177
+ ` effect: ${p.effect}`,
178
+ ]),
179
+ ].join("\n")
180
+ }
181
+
182
+ /** The colour line an agent should have, or null when the current one is right. */
183
+ function colorLineFor(name, rawCurrent) {
184
+ const current = unquoteColor(rawCurrent)
185
+ const target = shouldDeriveColor(current) ? agentColor(name) : current
186
+ const rendered = yamlColor(target)
187
+ return (rawCurrent ?? "").trim() === rendered ? null : `color: ${rendered}`
188
+ }
189
+
190
+ const FULLSTACK_NAME = "fullstack-engineer"
191
+ const FULLSTACK_TEMPLATE = `${FULLSTACK_NAME}.md`
192
+
193
+ /** Rewrite a template's frontmatter to a clean V2 subagent definition. */
194
+ function normalizeTemplate(content, name) {
195
+ const { frontmatter, body } = splitFrontmatter(content)
196
+ if (frontmatter === null) return `---\nmode: subagent\ncolor: ${yamlColor(agentColor(name))}\n---\n\n${content}`
197
+
198
+ let fm = stripLegacyFields(frontmatter)
199
+ fm = setScalar(fm, "mode", "subagent")
200
+ const colorLine = colorLineFor(name, fm.match(/^color:\s*(.+)$/m)?.[1])
201
+ if (colorLine) fm = setScalar(fm, "color", colorLine.slice("color: ".length))
202
+ return `---\n${fm}\n---\n${body}`
203
+ }
204
+
205
+ /** A tier-pinned copy of a specialist: same body, resolved model. */
206
+ function buildVariant(templateContent, model) {
207
+ const { frontmatter, body } = splitFrontmatter(templateContent)
208
+ let fm = stripLegacyFields(frontmatter ?? "")
209
+ fm = setScalar(fm, "mode", "subagent")
210
+ fm = setScalar(fm, "model", model)
211
+ // Hidden by default: a tier is chosen by whoever writes the task, not picked
212
+ // from the @ menu. Without this the menu lists every specialist once per tier.
213
+ fm = setScalar(fm, "hidden", "true")
214
+ if (!/^color:/m.test(fm)) {
215
+ const name = ""
216
+ fm = setScalar(fm, "color", name ? yamlColor(agentColor(name)) : yamlColor(agentColor("engineer")))
217
+ }
218
+ return `---\n${fm}\n---\n${body}`
219
+ }
220
+
221
+ /**
222
+ * Build a primary from the fullstack body: same identity and the same
223
+ * ## Abilities block, with our own frontmatter on top. The body is taken
224
+ * verbatim so /make-engineer only has to maintain fullstack-engineer.md and
225
+ * both primaries inherit whatever it lists.
226
+ */
227
+ function buildPrimary(spec, fullstackContent, model) {
228
+ const { body } = splitFrontmatter(fullstackContent)
229
+ const lines = [
230
+ "---",
231
+ `description: ${spec.description}`,
232
+ `mode: ${spec.mode ?? "primary"}`,
233
+ ]
234
+ if (model) lines.push(`model: ${model}`)
235
+ lines.push(`color: ${yamlColor(spec.color)}`)
236
+ if (spec.permissions) lines.push(permissionsYaml(spec.permissions))
237
+ lines.push("---")
238
+ return `${lines.join("\n")}\n\n${body.trim()}\n`
239
+ }
240
+
241
+ async function readJson(filePath) {
242
+ try {
243
+ return JSON.parse(await fs.readFile(filePath, "utf-8"))
244
+ } catch {
245
+ return null
246
+ }
247
+ }
248
+
249
+ async function scanEngineers(agentsDir) {
250
+ try {
251
+ const entries = await fs.readdir(agentsDir)
252
+ return {
253
+ templates: entries
254
+ .filter(f => /^[\w-]+-engineer\.md$/.test(f) && f !== FULLSTACK_TEMPLATE)
255
+ .map(f => f.replace(/\.md$/, "")),
256
+ variantFiles: entries.filter(f => /^[\w-]+-engineer\.(build|fast|plan)\.md$/.test(f)),
257
+ hasFullstack: entries.includes(FULLSTACK_TEMPLATE),
258
+ }
259
+ } catch {
260
+ return { templates: [], variantFiles: [], hasFullstack: false }
261
+ }
262
+ }
263
+
264
+ async function writeIfChanged(filePath, content) {
265
+ try {
266
+ if ((await fs.readFile(filePath, "utf-8")) === content) return
267
+ } catch {
268
+ // file missing, write it
269
+ }
270
+ const tmpPath = `${filePath}.tmp`
271
+ await fs.writeFile(tmpPath, content, "utf-8")
272
+ await fs.rename(tmpPath, filePath)
273
+ }
274
+
275
+ export default Plugin.define({
276
+ id: "pc.subagent-tiers",
277
+ async setup(ctx) {
278
+ const root = ctx.location.directory
279
+ const agentsDir = path.join(root, ".opencode", "agents")
280
+
281
+ try {
282
+ const [user, team] = await Promise.all([
283
+ readJson(path.join(root, ".opencode", "harness.user.json")),
284
+ readJson(path.join(root, ".opencode", "harness.json")),
285
+ ])
286
+ const models = {}
287
+ for (const tier of TIERS) {
288
+ models[tier] = user?.models?.[tier] ?? team?.models?.[tier] ?? null
289
+ }
290
+ const available = TIERS.filter(t => models[t])
291
+
292
+ const { templates, variantFiles, hasFullstack } = await scanEngineers(agentsDir)
293
+
294
+ if (hasFullstack) {
295
+ const fullstackPath = path.join(agentsDir, FULLSTACK_TEMPLATE)
296
+ const rawFullstack = await fs.readFile(fullstackPath, "utf-8")
297
+ const fullstack = normalizeTemplate(rawFullstack, FULLSTACK_NAME)
298
+ if (fullstack !== rawFullstack) {
299
+ await writeIfChanged(fullstackPath, fullstack)
300
+ console.error("[pc-subagent-tiers] Normalized fullstack-engineer.md (V2 subagent)")
301
+ }
302
+
303
+ for (const [name, spec] of Object.entries(PRIMARIES)) {
304
+ await writeIfChanged(
305
+ path.join(agentsDir, `${name}.md`),
306
+ buildPrimary(spec, fullstack, models[spec.tier]),
307
+ )
308
+ }
309
+ console.error(`[pc-subagent-tiers] Wrote primaries: build (${models.build ?? "session model"}), plan and planner (${models.plan ?? "session model"})`)
310
+ } else {
311
+ console.error(`[pc-subagent-tiers] ${FULLSTACK_TEMPLATE} missing: build and plan not generated`)
312
+ }
313
+
314
+ const keepSet = new Set()
315
+ const variantsToWrite = []
316
+ for (const name of templates) {
317
+ const rawContent = await fs.readFile(path.join(agentsDir, `${name}.md`), "utf-8")
318
+ const content = normalizeTemplate(rawContent, name)
319
+ if (content !== rawContent) {
320
+ await writeIfChanged(path.join(agentsDir, `${name}.md`), content)
321
+ console.error(`[pc-subagent-tiers] Normalized ${name}.md (V2 subagent)`)
322
+ }
323
+ for (const tier of available) {
324
+ const file = `${name}.${tier}.md`
325
+ variantsToWrite.push({ file, path: path.join(agentsDir, file), content: buildVariant(content, models[tier]) })
326
+ keepSet.add(file)
327
+ }
328
+ }
329
+
330
+ await Promise.all(variantsToWrite.map(v => writeIfChanged(v.path, v.content)))
331
+ await Promise.all(
332
+ variantFiles.filter(f => !keepSet.has(f)).map(f => fs.unlink(path.join(agentsDir, f)).catch(() => {})),
333
+ )
334
+
335
+ if (variantsToWrite.length > 0) {
336
+ console.error(`[pc-subagent-tiers] Created ${variantsToWrite.length} variant files (${templates.length} engineers x ${available.length} tiers)`)
337
+ } else if (templates.length > 0) {
338
+ console.error(`[pc-subagent-tiers] No variants created. Models: ${JSON.stringify(models)}`)
339
+ }
340
+
341
+ // Best effort: if V2 already discovered these agents (same startup), pin
342
+ // the primaries' model and plan's read-only permissions in memory too.
343
+ if (typeof ctx.agent?.transform === "function") {
344
+ await ctx.agent.transform(editor => {
345
+ for (const [id, spec] of Object.entries(PRIMARIES)) {
346
+ const existing = editor.get(id)
347
+ if (!existing) continue
348
+ const model = models[spec.tier]
349
+ if (model) {
350
+ try {
351
+ existing.model = Model.Ref.parse(model)
352
+ } catch {
353
+ // invalid model ref; leave undefined so session model applies
354
+ }
355
+ }
356
+ existing.mode = spec.mode ?? "primary"
357
+ existing.description = spec.description
358
+ if (spec.permissions) existing.permissions = spec.permissions
359
+ }
360
+ })
361
+ await ctx.agent.reload?.()
362
+ }
363
+ } catch (error) {
364
+ console.error(`[pc-subagent-tiers] Error: ${error?.message}`)
365
+ }
366
+ },
367
+ })