@mdsohail99/opencode-agent-teams 0.0.0-stage → 2.0.1

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 (88) hide show
  1. package/AGENTS.md +67 -0
  2. package/CHANGELOG.md +158 -0
  3. package/LICENSE +21 -0
  4. package/README.md +167 -2
  5. package/agents/orchestrators/agent-teams.md +198 -0
  6. package/agents/orchestrators/ai-data.md +91 -0
  7. package/agents/orchestrators/backend.md +109 -0
  8. package/agents/orchestrators/devops.md +89 -0
  9. package/agents/orchestrators/frontend.md +117 -0
  10. package/agents/orchestrators/qa.md +89 -0
  11. package/agents/orchestrators/security.md +98 -0
  12. package/agents/specialists/accessibility-auditor.md +322 -0
  13. package/agents/specialists/ai-engineer.md +152 -0
  14. package/agents/specialists/ai-generated-code-security-auditor.md +213 -0
  15. package/agents/specialists/api-platform-engineer.md +169 -0
  16. package/agents/specialists/api-tester.md +311 -0
  17. package/agents/specialists/application-security-engineer.md +497 -0
  18. package/agents/specialists/backend-architect.md +242 -0
  19. package/agents/specialists/brand-guardian.md +327 -0
  20. package/agents/specialists/cloud-security-architect.md +526 -0
  21. package/agents/specialists/code-reviewer.md +83 -0
  22. package/agents/specialists/codebase-archaeologist.md +347 -0
  23. package/agents/specialists/codebase-onboarding-engineer.md +180 -0
  24. package/agents/specialists/compliance-auditor.md +165 -0
  25. package/agents/specialists/data-engineer.md +312 -0
  26. package/agents/specialists/data-visualization-engineer.md +158 -0
  27. package/agents/specialists/database-optimizer.md +183 -0
  28. package/agents/specialists/database-reliability-engineer.md +169 -0
  29. package/agents/specialists/desktop-app-engineer.md +211 -0
  30. package/agents/specialists/developer-tooling-engineer.md +160 -0
  31. package/agents/specialists/devops-automator.md +380 -0
  32. package/agents/specialists/finops-engineer.md +160 -0
  33. package/agents/specialists/frontend-developer.md +230 -0
  34. package/agents/specialists/git-workflow-master.md +91 -0
  35. package/agents/specialists/image-prompt-engineer.md +242 -0
  36. package/agents/specialists/incident-responder.md +443 -0
  37. package/agents/specialists/incident-response-commander.md +448 -0
  38. package/agents/specialists/inclusive-visuals-specialist.md +78 -0
  39. package/agents/specialists/internationalization-engineer.md +191 -0
  40. package/agents/specialists/iot-fleet-engineer.md +155 -0
  41. package/agents/specialists/llm-post-training-engineer.md +172 -0
  42. package/agents/specialists/mcp-builder.md +254 -0
  43. package/agents/specialists/minimal-change-engineer.md +213 -0
  44. package/agents/specialists/mobile-app-builder.md +498 -0
  45. package/agents/specialists/multi-agent-systems-architect.md +593 -0
  46. package/agents/specialists/payments-billing-engineer.md +201 -0
  47. package/agents/specialists/penetration-tester.md +405 -0
  48. package/agents/specialists/performance-benchmarker.md +273 -0
  49. package/agents/specialists/persona-walkthrough-specialist.md +275 -0
  50. package/agents/specialists/privacy-engineer.md +159 -0
  51. package/agents/specialists/prompt-engineer.md +208 -0
  52. package/agents/specialists/rag-pipeline-engineer.md +435 -0
  53. package/agents/specialists/rapid-prototyper.md +467 -0
  54. package/agents/specialists/reality-checker.md +240 -0
  55. package/agents/specialists/realtime-collaboration-engineer.md +194 -0
  56. package/agents/specialists/rust-refactoring-specialist.md +320 -0
  57. package/agents/specialists/search-relevance-engineer.md +244 -0
  58. package/agents/specialists/secrets-credential-hygiene-engineer.md +182 -0
  59. package/agents/specialists/section-508-accessibility-specialist.md +338 -0
  60. package/agents/specialists/security-architect.md +310 -0
  61. package/agents/specialists/software-architect.md +119 -0
  62. package/agents/specialists/sre-site-reliability-engineer.md +97 -0
  63. package/agents/specialists/technical-writer.md +398 -0
  64. package/agents/specialists/test-automation-engineer.md +186 -0
  65. package/agents/specialists/test-results-analyzer.md +310 -0
  66. package/agents/specialists/threat-detection-engineer.md +540 -0
  67. package/agents/specialists/ui-designer.md +388 -0
  68. package/agents/specialists/ui-finish-gate-reviewer.md +220 -0
  69. package/agents/specialists/uswds-developer.md +339 -0
  70. package/agents/specialists/ux-architect.md +474 -0
  71. package/agents/specialists/ux-researcher.md +334 -0
  72. package/agents/specialists/video-streaming-engineer.md +157 -0
  73. package/agents/specialists/visual-storyteller.md +155 -0
  74. package/agents/specialists/web-gis-developer.md +115 -0
  75. package/agents/specialists/webassembly-engineer.md +163 -0
  76. package/agents/specialists/wechat-mini-program-developer.md +356 -0
  77. package/agents/specialists/whimsy-injector.md +444 -0
  78. package/agents/specialists/workflow-architect.md +590 -0
  79. package/bin/cli.js +351 -0
  80. package/package.json +55 -4
  81. package/src/index.ts +115 -0
  82. package/src/state/tracker.ts +102 -0
  83. package/src/tools/broadcast.ts +58 -0
  84. package/src/tools/delegate.ts +154 -0
  85. package/src/tools/status.ts +25 -0
  86. package/src/tools/terminate.ts +70 -0
  87. package/src/tui.ts +9 -0
  88. package/src/worktree/manager.ts +142 -0
package/bin/cli.js ADDED
@@ -0,0 +1,351 @@
1
+ #!/usr/bin/env node
2
+ import fs from "node:fs"
3
+ import path from "node:path"
4
+ import os from "node:os"
5
+ import { fileURLToPath } from "node:url"
6
+ import readline from "node:readline/promises"
7
+
8
+ const __dirname = path.dirname(fileURLToPath(import.meta.url))
9
+ const rootDir = path.resolve(__dirname, "..")
10
+
11
+ const args = process.argv.slice(2)
12
+ const binName = path.basename(process.argv[1] || "")
13
+
14
+ // ANSI styling
15
+ const c = {
16
+ reset: "\x1b[0m",
17
+ bold: "\x1b[1m",
18
+ dim: "\x1b[2m",
19
+ red: "\x1b[31m",
20
+ green: "\x1b[32m",
21
+ yellow: "\x1b[33m",
22
+ cyan: "\x1b[36m",
23
+ white: "\x1b[37m",
24
+ }
25
+
26
+ function resolveConfigRoot(globalMode = true) {
27
+ if (globalMode) {
28
+ if (process.env.OPENCODE_CONFIG_DIR) {
29
+ return path.resolve(process.env.OPENCODE_CONFIG_DIR)
30
+ }
31
+ return path.join(os.homedir(), ".config", "opencode")
32
+ }
33
+ return process.cwd()
34
+ }
35
+
36
+ function getShippedAgents() {
37
+ const shipped = []
38
+ const sourceAgentsDir = path.resolve(rootDir, "agents")
39
+ if (!fs.existsSync(sourceAgentsDir)) return shipped
40
+
41
+ function scan(dir) {
42
+ for (const item of fs.readdirSync(dir, { withFileTypes: true })) {
43
+ const p = path.join(dir, item.name)
44
+ if (item.isDirectory()) {
45
+ scan(p)
46
+ } else if (item.isFile() && item.name.endsWith(".md")) {
47
+ shipped.push({
48
+ name: item.name,
49
+ sourcePath: p,
50
+ })
51
+ }
52
+ }
53
+ }
54
+ scan(sourceAgentsDir)
55
+ return shipped
56
+ }
57
+
58
+ function getStatus(globalMode = true) {
59
+ const targetDir = resolveConfigRoot(globalMode)
60
+ const configPath = path.resolve(targetDir, "opencode.json")
61
+ const agentsDir = globalMode
62
+ ? path.resolve(targetDir, "agents")
63
+ : path.resolve(targetDir, ".opencode", "agents")
64
+
65
+ let configExists = false
66
+ let subagentDepth = null
67
+ let isPluginRegistered = false
68
+ let agentCount = 0
69
+
70
+ if (fs.existsSync(configPath)) {
71
+ configExists = true
72
+ try {
73
+ const parsed = JSON.parse(fs.readFileSync(configPath, "utf-8"))
74
+ subagentDepth = parsed.subagent_depth ?? null
75
+ if (Array.isArray(parsed.plugins)) {
76
+ isPluginRegistered = parsed.plugins.some(
77
+ (p) => typeof p === "string" && (p.includes("agent-teams") || p.includes("orchestration"))
78
+ )
79
+ }
80
+ } catch {}
81
+ }
82
+
83
+ if (fs.existsSync(agentsDir)) {
84
+ try {
85
+ agentCount = fs.readdirSync(agentsDir).filter((f) => f.endsWith(".md")).length
86
+ } catch {}
87
+ }
88
+
89
+ const isInstalled = isPluginRegistered && agentCount > 0
90
+ return {
91
+ targetDir,
92
+ configPath,
93
+ agentsDir,
94
+ configExists,
95
+ subagentDepth,
96
+ isPluginRegistered,
97
+ agentCount,
98
+ isInstalled,
99
+ }
100
+ }
101
+
102
+ async function doInstall(globalMode = true) {
103
+ const targetDir = resolveConfigRoot(globalMode)
104
+ const configPath = path.resolve(targetDir, "opencode.json")
105
+ const agentsTargetDir = globalMode
106
+ ? path.resolve(targetDir, "agents")
107
+ : path.resolve(targetDir, ".opencode", "agents")
108
+ const manifestPath = path.resolve(agentsTargetDir, ".agent-teams-manifest.json")
109
+
110
+ console.log(`\n${c.cyan}Installing Agent-Teams (${globalMode ? "Global" : "Local"})...${c.reset}`)
111
+ console.log(`${c.dim}Target directory: ${targetDir}${c.reset}`)
112
+
113
+ let config = {
114
+ $schema: "https://opencode.ai/config.json",
115
+ subagent_depth: 2,
116
+ plugins: [],
117
+ }
118
+
119
+ if (fs.existsSync(configPath)) {
120
+ try {
121
+ config = JSON.parse(fs.readFileSync(configPath, "utf-8"))
122
+ } catch (err) {
123
+ console.warn("Notice: Creating fresh config structure due to parse error.")
124
+ }
125
+ }
126
+
127
+ config.subagent_depth = 2
128
+
129
+ const pluginRef = fs.existsSync(path.join(rootDir, "src", "index.ts"))
130
+ ? rootDir.replace(/\\/g, "/")
131
+ : "@mdsohail99/opencode-agent-teams"
132
+
133
+ if (!Array.isArray(config.plugins)) {
134
+ config.plugins = []
135
+ }
136
+ if (!config.plugins.includes(pluginRef)) {
137
+ config.plugins.push(pluginRef)
138
+ }
139
+
140
+ fs.mkdirSync(path.dirname(configPath), { recursive: true })
141
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2), "utf-8")
142
+ console.log(` ${c.green}✓${c.reset} Configured opencode.json (subagent_depth: 2, plugin: ${pluginRef})`)
143
+
144
+ const shippedAgents = getShippedAgents()
145
+ if (shippedAgents.length > 0) {
146
+ fs.mkdirSync(agentsTargetDir, { recursive: true })
147
+ const installedList = []
148
+
149
+ for (const agent of shippedAgents) {
150
+ const dest = path.resolve(agentsTargetDir, agent.name)
151
+ fs.copyFileSync(agent.sourcePath, dest)
152
+ installedList.push(agent.name)
153
+ }
154
+
155
+ fs.writeFileSync(
156
+ manifestPath,
157
+ JSON.stringify({ plugin: "@mdsohail99/opencode-agent-teams", version: "2.0.0", files: installedList }, null, 2),
158
+ "utf-8"
159
+ )
160
+ console.log(` ${c.green}✓${c.reset} Installed ${installedList.length} curated agents into ${agentsTargetDir}`)
161
+ }
162
+
163
+ console.log(`\n${c.green}${c.bold}✓ Setup complete!${c.reset} Launch OpenCode with ${c.bold}opencode${c.reset} and select agent-teams.\n`)
164
+ }
165
+
166
+ async function doUninstall(globalMode = true) {
167
+ const targetDir = resolveConfigRoot(globalMode)
168
+ const configPath = path.resolve(targetDir, "opencode.json")
169
+ const agentsTargetDir = globalMode
170
+ ? path.resolve(targetDir, "agents")
171
+ : path.resolve(targetDir, ".opencode", "agents")
172
+ const manifestPath = path.resolve(agentsTargetDir, ".agent-teams-manifest.json")
173
+
174
+ console.log(`\n${c.yellow}Uninstalling Agent-Teams (${globalMode ? "Global" : "Local"})...${c.reset}`)
175
+ console.log(`${c.dim}Target directory: ${targetDir}${c.reset}`)
176
+
177
+ if (fs.existsSync(configPath)) {
178
+ try {
179
+ const raw = fs.readFileSync(configPath, "utf-8")
180
+ const config = JSON.parse(raw)
181
+ if (Array.isArray(config.plugins)) {
182
+ const beforeCount = config.plugins.length
183
+ config.plugins = config.plugins.filter((p) => {
184
+ if (typeof p === "string" && (p.includes("agent-teams") || p.includes("orchestration"))) return false
185
+ return true
186
+ })
187
+ if (config.plugins.length !== beforeCount) {
188
+ fs.writeFileSync(configPath, JSON.stringify(config, null, 2), "utf-8")
189
+ console.log(` ${c.green}✓${c.reset} Removed plugin from opencode.json`)
190
+ }
191
+ }
192
+ } catch {}
193
+ }
194
+
195
+ let filesRemoved = 0
196
+ if (fs.existsSync(agentsTargetDir)) {
197
+ let filesToDelete = []
198
+ if (fs.existsSync(manifestPath)) {
199
+ try {
200
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8"))
201
+ if (Array.isArray(manifest.files)) filesToDelete = manifest.files
202
+ } catch {}
203
+ }
204
+ if (filesToDelete.length === 0) {
205
+ filesToDelete = getShippedAgents().map((a) => a.name)
206
+ }
207
+
208
+ for (const file of filesToDelete) {
209
+ const targetFile = path.resolve(agentsTargetDir, file)
210
+ if (fs.existsSync(targetFile)) {
211
+ try {
212
+ fs.unlinkSync(targetFile)
213
+ filesRemoved++
214
+ } catch {}
215
+ }
216
+ }
217
+
218
+ if (fs.existsSync(manifestPath)) {
219
+ try {
220
+ fs.unlinkSync(manifestPath)
221
+ } catch {}
222
+ }
223
+
224
+ try {
225
+ const remaining = fs.readdirSync(agentsTargetDir)
226
+ if (remaining.length === 0) fs.rmdirSync(agentsTargetDir)
227
+ } catch {}
228
+
229
+ console.log(` ${c.green}✓${c.reset} Removed ${filesRemoved} agent markdown files from ${agentsTargetDir}`)
230
+ }
231
+
232
+ console.log(`\n${c.green}${c.bold}✓ Uninstall complete!${c.reset} Agent-Teams cleanly removed.\n`)
233
+ }
234
+
235
+ function printStatus() {
236
+ const globalStat = getStatus(true)
237
+ const localStat = getStatus(false)
238
+
239
+ console.log(`\n${c.bold}${c.cyan}Agent-Teams v2 Status Report${c.reset}\n`)
240
+ console.log(`${c.bold}Global Configuration (~/.config/opencode):${c.reset}`)
241
+ console.log(` Status: ${globalStat.isInstalled ? c.green + "Installed (Active)" + c.reset : c.dim + "Not Installed" + c.reset}`)
242
+ console.log(` Config Path: ${globalStat.configPath}`)
243
+ console.log(` Subagent Depth: ${globalStat.subagentDepth ?? "not set"}`)
244
+ console.log(` Plugin Linked: ${globalStat.isPluginRegistered ? c.green + "Yes" + c.reset : "No"}`)
245
+ console.log(` Agents Count: ${globalStat.agentCount} agents in ${globalStat.agentsDir}`)
246
+
247
+ console.log(`\n${c.bold}Local Directory Configuration (.opencode):${c.reset}`)
248
+ console.log(` Status: ${localStat.isInstalled ? c.green + "Installed (Local Active)" + c.reset : c.dim + "Not Installed" + c.reset}`)
249
+ console.log(` Config Path: ${localStat.configPath}`)
250
+ console.log(` Plugin Linked: ${localStat.isPluginRegistered ? c.green + "Yes" + c.reset : "No"}`)
251
+ console.log(` Agents Count: ${localStat.agentCount} agents\n`)
252
+ }
253
+
254
+ async function runInteractiveMenu() {
255
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
256
+
257
+ while (true) {
258
+ const stat = getStatus(true)
259
+ console.log(`
260
+ ${c.bold}${c.cyan}┌────────────────────────────────────────────────────────┐${c.reset}
261
+ ${c.bold}${c.cyan}│ Agent-Teams v2 Setup & Management │${c.reset}
262
+ ${c.bold}${c.cyan}└────────────────────────────────────────────────────────┘${c.reset}
263
+ ${c.dim}Global Config:${c.reset} ${stat.targetDir}
264
+ ${c.dim}Status:${c.reset} ${stat.isInstalled ? c.green + "● Installed & Active" + c.reset : c.yellow + "○ Not Installed" + c.reset} ${stat.isInstalled ? `(Agents: ${stat.agentCount}, Depth: ${stat.subagentDepth})` : ""}
265
+
266
+ ${c.cyan}1${c.reset} Install / Update Agent-Teams ${c.green}(Global - Recommended)${c.reset}
267
+ ${c.cyan}2${c.reset} Install to Current Project Only ${c.dim}(Local)${c.reset}
268
+ ${c.cyan}3${c.reset} Inspect Status & Registered Agents
269
+ ${c.cyan}4${c.reset} Uninstall Agent-Teams
270
+ ${c.cyan}5${c.reset} Exit
271
+ `)
272
+
273
+ const choice = (await rl.question(` ${c.bold}Choose option [1-5]:${c.reset} `)).trim()
274
+
275
+ if (choice === "1") {
276
+ await doInstall(true)
277
+ } else if (choice === "2") {
278
+ await doInstall(false)
279
+ } else if (choice === "3") {
280
+ printStatus()
281
+ } else if (choice === "4") {
282
+ await doUninstall(true)
283
+ } else if (choice === "5" || choice.toLowerCase() === "q" || choice.toLowerCase() === "exit") {
284
+ console.log(`\n${c.dim}Goodbye!${c.reset}\n`)
285
+ break
286
+ } else {
287
+ console.log(`\n${c.red}Invalid choice. Please select 1-5.${c.reset}`)
288
+ }
289
+
290
+ await rl.question(`\n${c.dim}Press Enter to return to menu...${c.reset}`)
291
+ }
292
+
293
+ rl.close()
294
+ }
295
+
296
+ // -------------------------------------------------------------
297
+ // CLI EXECUTION DISPATCHER
298
+ // -------------------------------------------------------------
299
+ const isUninstallCommand =
300
+ binName.includes("uninstall") ||
301
+ args.includes("uninstall") ||
302
+ args.includes("--uninstall") ||
303
+ args.includes("-u")
304
+
305
+ const isLocal = args.includes("--local") || args.includes("-l")
306
+ const isGlobal = !isLocal
307
+ const isHelp = args.includes("--help") || args.includes("-h")
308
+ const isStatus = args.includes("status") || args.includes("--status")
309
+ const isInstallExplicit = args.includes("install") || args.includes("--install")
310
+
311
+ if (isHelp) {
312
+ console.log(`
313
+ Agent-Teams v2 CLI for OpenCode
314
+
315
+ Usage:
316
+ npx @mdsohail99/opencode-agent-teams Launch interactive menu (default)
317
+ npx @mdsohail99/opencode-agent-teams install [options] Install Agent-Teams plugin and agents
318
+ npx @mdsohail99/opencode-agent-teams uninstall [options] Uninstall Agent-Teams cleanly
319
+ npx @mdsohail99/opencode-agent-teams status Inspect current status
320
+
321
+ Options:
322
+ -l, --local Target current project directory only instead of global OpenCode (~/.config/opencode)
323
+ -u, --uninstall Uninstall Agent-Teams and remove associated agents
324
+ -h, --help Show this help message
325
+ `)
326
+ process.exit(0)
327
+ }
328
+
329
+ if (isStatus) {
330
+ printStatus()
331
+ process.exit(0)
332
+ }
333
+
334
+ if (isUninstallCommand) {
335
+ await doUninstall(isGlobal)
336
+ process.exit(0)
337
+ }
338
+
339
+ if (isInstallExplicit) {
340
+ await doInstall(isGlobal)
341
+ process.exit(0)
342
+ }
343
+
344
+ // If invoked without arguments:
345
+ // In an interactive TTY -> launch interactive menu!
346
+ // In a non-interactive/scripted environment -> default to install
347
+ if (process.stdin.isTTY && args.length === 0) {
348
+ await runInteractiveMenu()
349
+ } else {
350
+ await doInstall(isGlobal)
351
+ }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@mdsohail99/opencode-agent-teams",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "2.0.1",
4
+ "description": "Native Agent-Teams orchestration plugin for OpenCode v2",
5
+ "type": "module",
6
+ "bin": {
7
+ "opencode-agent-teams": "bin/cli.js",
8
+ "opencode-agent-teams-uninstall": "bin/cli.js"
9
+ },
10
+ "exports": {
11
+ ".": "./src/index.ts",
12
+ "./server": "./src/index.ts",
13
+ "./tui": "./src/tui.ts"
14
+ },
15
+ "files": [
16
+ "src",
17
+ "agents",
18
+ "bin",
19
+ "AGENTS.md",
20
+ "README.md",
21
+ "CHANGELOG.md",
22
+ "LICENSE"
23
+ ],
24
+ "engines": {
25
+ "node": ">=20.19"
26
+ },
27
+ "dependencies": {
28
+ "@opencode/client": "2.1.1",
29
+ "@opencode/plugin": "2.1.1",
30
+ "@opencode/schema": "2.1.1",
31
+ "effect": "4.0.1"
32
+ },
33
+ "devDependencies": {
34
+ "@types/node": "^24.12.2",
35
+ "tsx": "^4.23.15",
36
+ "typescript": "^7.0.2"
37
+ },
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/mdsohail99/opencode-agent-teams.git"
41
+ },
42
+ "author": "mdsohail99",
43
+ "license": "MIT",
44
+ "keywords": [
45
+ "opencode",
46
+ "agent-teams",
47
+ "orchestration",
48
+ "multi-agent",
49
+ "subagent",
50
+ "parallel",
51
+ "worktree"
52
+ ],
53
+ "scripts": {
54
+ "test": "tsx test/v2-swarm.spec.ts",
55
+ "typecheck": "tsc --noEmit"
56
+ }
57
+ }
package/src/index.ts ADDED
@@ -0,0 +1,115 @@
1
+ import { Plugin } from "@opencode/plugin"
2
+ import { createDelegateTool } from "./tools/delegate.js"
3
+ import { createStatusTool } from "./tools/status.js"
4
+ import { createBroadcastTool } from "./tools/broadcast.js"
5
+ import { createTerminateTool } from "./tools/terminate.js"
6
+ import { globalTracker } from "./state/tracker.js"
7
+ import fs from "node:fs"
8
+ import path from "node:path"
9
+
10
+ export const AGENT_TEAMS_ORCHESTRATION_RULES = `
11
+ <!-- agent-teams-orchestration:start -->
12
+ # Department Team-Lead Orchestration (Agent-Teams v2)
13
+
14
+ The swarm is organized into departments led by Orchestrators (Backend, Frontend, Security, DevOps, AI & Data, QA).
15
+
16
+ ## Swarm Protocol:
17
+ 1. Use \`team_delegate\` to dispatch tasks to specialists in dedicated, isolated git worktrees.
18
+ 2. Monitor progress non-blockingly using \`team_status\`.
19
+ 3. Broadcast steering guidance or updates using \`team_broadcast\`.
20
+ 4. Gracefully terminate tasks using \`team_terminate\`.
21
+ 5. Upon task completion, changes in the worktree are automatically committed and merged into the base branch.
22
+ 6. OpenCode hierarchical depth = 2 (subagent_depth: 2) enables Department Leads (Depth 1) to dispatch Domain Specialists (Depth 2).
23
+ <!-- agent-teams-orchestration:end -->
24
+ `
25
+
26
+ /**
27
+ * Ensures subagent_depth: 2 is present in an opencode.json configuration file.
28
+ */
29
+ function ensureSubagentDepth(filePath: string) {
30
+ try {
31
+ if (fs.existsSync(filePath)) {
32
+ const raw = fs.readFileSync(filePath, "utf-8")
33
+ const parsed = JSON.parse(raw)
34
+ if (typeof parsed === "object" && parsed !== null) {
35
+ if (!parsed.subagent_depth || parsed.subagent_depth < 2) {
36
+ parsed.subagent_depth = 2
37
+ fs.writeFileSync(filePath, JSON.stringify(parsed, null, 2), "utf-8")
38
+ }
39
+ }
40
+ }
41
+ } catch {
42
+ // Non-fatal safety guard
43
+ }
44
+ }
45
+
46
+ export default Plugin.define({
47
+ id: "agent-teams",
48
+ async setup(ctx: Plugin.Context) {
49
+ // 0. Auto-ensure subagent_depth: 2 in local and config-dir opencode.json
50
+ ensureSubagentDepth(path.resolve(process.cwd(), "opencode.json"))
51
+ if (process.env.OPENCODE_CONFIG_DIR) {
52
+ ensureSubagentDepth(path.join(process.env.OPENCODE_CONFIG_DIR, "opencode.json"))
53
+ }
54
+
55
+ // 1. Register Swarm Tools (team_delegate, team_status, team_broadcast, team_terminate)
56
+ ctx.tool.transform((editor: any) => {
57
+ editor.add(createDelegateTool(ctx))
58
+ editor.add(createStatusTool(ctx))
59
+ editor.add(createBroadcastTool(ctx))
60
+ editor.add(createTerminateTool(ctx))
61
+ })
62
+
63
+ // 2. Register Clean, Non-Conflicting Slash Commands
64
+ if (ctx.command?.transform) {
65
+ ctx.command.transform((editor: any) => {
66
+ editor.add({
67
+ name: "team",
68
+ description: "Display live hierarchical swarm status tree and active worktrees",
69
+ execute: async (inv: any) => {
70
+ const tree = globalTracker.formatTree(inv.sessionID)
71
+ await ctx.session.prompt({
72
+ sessionID: inv.sessionID,
73
+ text: `Please display the following active swarm status to the user:\n\`\`\`\n${tree}\n\`\`\``,
74
+ } as any)
75
+ },
76
+ })
77
+
78
+ editor.add({
79
+ name: "team-status",
80
+ description: "Inspect swarm progress and active teammate worktrees",
81
+ execute: async (inv: any) => {
82
+ const tree = globalTracker.formatTree(inv.sessionID)
83
+ await ctx.session.prompt({
84
+ sessionID: inv.sessionID,
85
+ text: `Teammate status report:\n\`\`\`\n${tree}\n\`\`\``,
86
+ } as any)
87
+ },
88
+ })
89
+
90
+ editor.add({
91
+ name: "team-stop",
92
+ description: "Halt all running teammates in the swarm and clean up worktrees",
93
+ execute: async (inv: any) => {
94
+ const tool = createTerminateTool(ctx)
95
+ const res = await tool.execute({ target: "all" }, { sessionID: inv.sessionID })
96
+ await ctx.session.prompt({
97
+ sessionID: inv.sessionID,
98
+ text: `Swarm termination executed:\n${res.content}`,
99
+ } as any)
100
+ },
101
+ })
102
+ })
103
+ }
104
+
105
+ // 3. Inject Orchestration System Rules to Agent-Teams
106
+ if (ctx.agent?.transform) {
107
+ ctx.agent.transform((editor: any) => {
108
+ const agentTeams = editor.get("Agent-Teams") || editor.get("agent-teams")
109
+ if (agentTeams && agentTeams.instructions) {
110
+ agentTeams.instructions += `\n\n${AGENT_TEAMS_ORCHESTRATION_RULES}`
111
+ }
112
+ })
113
+ }
114
+ },
115
+ })
@@ -0,0 +1,102 @@
1
+ export interface TeamMember {
2
+ id: string
3
+ teamName: string
4
+ agentType: string
5
+ sessionId: string
6
+ parentSessionId: string
7
+ status: "running" | "completed" | "error" | "terminated"
8
+ prompt: string
9
+ worktreePath?: string
10
+ worktreeBranch?: string
11
+ createdAt: number
12
+ finishedAt?: number
13
+ lastEvent?: string
14
+ deliverable?: string
15
+ error?: string
16
+ }
17
+
18
+ export class SwarmTracker {
19
+ private members = new Map<string, TeamMember>()
20
+
21
+ register(member: TeamMember): void {
22
+ this.members.set(member.sessionId, member)
23
+ }
24
+
25
+ update(sessionId: string, patch: Partial<TeamMember>): TeamMember | undefined {
26
+ const existing = this.members.get(sessionId)
27
+ if (!existing) return undefined
28
+ const updated = { ...existing, ...patch }
29
+ this.members.set(sessionId, updated)
30
+ return updated
31
+ }
32
+
33
+ get(idOrSessionId: string): TeamMember | undefined {
34
+ if (this.members.has(idOrSessionId)) {
35
+ return this.members.get(idOrSessionId)
36
+ }
37
+ for (const member of this.members.values()) {
38
+ if (member.id === idOrSessionId || member.teamName.toLowerCase() === idOrSessionId.toLowerCase()) {
39
+ return member
40
+ }
41
+ }
42
+ return undefined
43
+ }
44
+
45
+ list(parentSessionId?: string): TeamMember[] {
46
+ const all = Array.from(this.members.values())
47
+ if (!parentSessionId) return all
48
+ return all.filter((m) => m.parentSessionId === parentSessionId)
49
+ }
50
+
51
+ formatTree(parentSessionId?: string): string {
52
+ const list = this.list(parentSessionId)
53
+ if (list.length === 0) {
54
+ return "No active or recorded teammates in this session."
55
+ }
56
+
57
+ const lines: string[] = ["Swarm Hierarchy & Teammate Status:"]
58
+ const byTeam = new Map<string, TeamMember[]>()
59
+ for (const m of list) {
60
+ const items = byTeam.get(m.teamName) || []
61
+ items.push(m)
62
+ byTeam.set(m.teamName, items)
63
+ }
64
+
65
+ const teams = Array.from(byTeam.keys())
66
+ teams.forEach((team, tIdx) => {
67
+ const isLastTeam = tIdx === teams.length - 1
68
+ const teamPrefix = isLastTeam ? "└── " : "├── "
69
+ const subPrefix = isLastTeam ? " " : "│ "
70
+ lines.push(`${teamPrefix}[Team: ${team}]`)
71
+
72
+ const members = byTeam.get(team)!
73
+ members.forEach((m, mIdx) => {
74
+ const isLastMember = mIdx === members.length - 1
75
+ const memberBranch = isLastMember ? "└── " : "├── "
76
+ const elapsed = m.finishedAt
77
+ ? `${Math.round((m.finishedAt - m.createdAt) / 1000)}s`
78
+ : `${Math.round((Date.now() - m.createdAt) / 1000)}s`
79
+ const statusEmoji =
80
+ m.status === "completed"
81
+ ? "✅"
82
+ : m.status === "running"
83
+ ? "⚡"
84
+ : m.status === "error"
85
+ ? "❌"
86
+ : "🛑"
87
+ const wtInfo = m.worktreeBranch ? ` (worktree: ${m.worktreeBranch})` : ""
88
+ lines.push(
89
+ `${subPrefix}${memberBranch}${statusEmoji} ${m.agentType} [${m.status}] (${elapsed})${wtInfo}`,
90
+ )
91
+ if (m.deliverable) {
92
+ const preview = m.deliverable.replace(/\s+/g, " ").trim().slice(0, 120)
93
+ lines.push(`${subPrefix}${isLastMember ? " " : "│ "}↳ deliverable: ${preview}...`)
94
+ }
95
+ })
96
+ })
97
+
98
+ return lines.join("\n")
99
+ }
100
+ }
101
+
102
+ export const globalTracker = new SwarmTracker()
@@ -0,0 +1,58 @@
1
+ import { Schema } from "effect"
2
+ import type { Plugin } from "@opencode/plugin"
3
+ import { globalTracker } from "../state/tracker.js"
4
+
5
+ export const BroadcastInput = Schema.Struct({
6
+ message: Schema.String.annotate({
7
+ description: "Guidance or steering message to broadcast to active teammates",
8
+ }),
9
+ team_name: Schema.optional(Schema.String).annotate({
10
+ description: "Limit broadcast to a specific department, or omit to broadcast to all running teammates",
11
+ }),
12
+ })
13
+
14
+ export function createBroadcastTool(ctx: Plugin.Context) {
15
+ return {
16
+ id: "team_broadcast",
17
+ name: "team_broadcast",
18
+ description: "Broadcast steering instructions to active teammates simultaneously.",
19
+ input: BroadcastInput,
20
+ execute: async (
21
+ input: { message: string; team_name?: string },
22
+ toolCtx: { sessionID: string },
23
+ ) => {
24
+ const allMembers = globalTracker.list(toolCtx.sessionID)
25
+ const running = allMembers.filter((m) => {
26
+ if (m.status !== "running") return false
27
+ if (input.team_name && m.teamName.toLowerCase() !== input.team_name.toLowerCase()) {
28
+ return false
29
+ }
30
+ return true
31
+ })
32
+
33
+ if (running.length === 0) {
34
+ return {
35
+ content: "No matching running teammates found to receive the broadcast.",
36
+ }
37
+ }
38
+
39
+ const results = await Promise.allSettled(
40
+ running.map(async (m) => {
41
+ await ctx.session.prompt({
42
+ sessionID: m.sessionId,
43
+ prompt: `[Broadcast from Orchestrator]: ${input.message}`,
44
+ } as any)
45
+ return m.teamName
46
+ }),
47
+ )
48
+
49
+ const notified = results
50
+ .filter((r) => r.status === "fulfilled")
51
+ .map((_, i) => running[i].teamName)
52
+
53
+ return {
54
+ content: `Broadcast delivered to ${notified.length} teammate(s): ${notified.join(", ")}`,
55
+ }
56
+ },
57
+ }
58
+ }