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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (100) hide show
  1. package/AGENTS.md +123 -0
  2. package/CHANGELOG.md +137 -0
  3. package/LICENSE +21 -0
  4. package/README.md +350 -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/orchestrators-fork/orchestrator-agent-teams.md +203 -0
  13. package/agents/specialists/accessibility-auditor.md +322 -0
  14. package/agents/specialists/ai-engineer.md +152 -0
  15. package/agents/specialists/ai-generated-code-security-auditor.md +213 -0
  16. package/agents/specialists/api-platform-engineer.md +169 -0
  17. package/agents/specialists/api-tester.md +311 -0
  18. package/agents/specialists/application-security-engineer.md +497 -0
  19. package/agents/specialists/backend-architect.md +242 -0
  20. package/agents/specialists/brand-guardian.md +327 -0
  21. package/agents/specialists/cloud-security-architect.md +526 -0
  22. package/agents/specialists/code-reviewer.md +83 -0
  23. package/agents/specialists/codebase-archaeologist.md +347 -0
  24. package/agents/specialists/codebase-onboarding-engineer.md +180 -0
  25. package/agents/specialists/compliance-auditor.md +165 -0
  26. package/agents/specialists/data-engineer.md +312 -0
  27. package/agents/specialists/data-visualization-engineer.md +158 -0
  28. package/agents/specialists/database-optimizer.md +183 -0
  29. package/agents/specialists/database-reliability-engineer.md +169 -0
  30. package/agents/specialists/desktop-app-engineer.md +211 -0
  31. package/agents/specialists/developer-tooling-engineer.md +160 -0
  32. package/agents/specialists/devops-automator.md +380 -0
  33. package/agents/specialists/finops-engineer.md +160 -0
  34. package/agents/specialists/frontend-developer.md +230 -0
  35. package/agents/specialists/git-workflow-master.md +91 -0
  36. package/agents/specialists/image-prompt-engineer.md +242 -0
  37. package/agents/specialists/incident-responder.md +443 -0
  38. package/agents/specialists/incident-response-commander.md +448 -0
  39. package/agents/specialists/inclusive-visuals-specialist.md +78 -0
  40. package/agents/specialists/internationalization-engineer.md +191 -0
  41. package/agents/specialists/iot-fleet-engineer.md +155 -0
  42. package/agents/specialists/llm-post-training-engineer.md +172 -0
  43. package/agents/specialists/mcp-builder.md +254 -0
  44. package/agents/specialists/minimal-change-engineer.md +213 -0
  45. package/agents/specialists/mobile-app-builder.md +498 -0
  46. package/agents/specialists/multi-agent-systems-architect.md +593 -0
  47. package/agents/specialists/payments-billing-engineer.md +201 -0
  48. package/agents/specialists/penetration-tester.md +405 -0
  49. package/agents/specialists/performance-benchmarker.md +273 -0
  50. package/agents/specialists/persona-walkthrough-specialist.md +275 -0
  51. package/agents/specialists/privacy-engineer.md +159 -0
  52. package/agents/specialists/prompt-engineer.md +208 -0
  53. package/agents/specialists/rag-pipeline-engineer.md +435 -0
  54. package/agents/specialists/rapid-prototyper.md +467 -0
  55. package/agents/specialists/reality-checker.md +240 -0
  56. package/agents/specialists/realtime-collaboration-engineer.md +194 -0
  57. package/agents/specialists/rust-refactoring-specialist.md +320 -0
  58. package/agents/specialists/search-relevance-engineer.md +244 -0
  59. package/agents/specialists/secrets-credential-hygiene-engineer.md +182 -0
  60. package/agents/specialists/section-508-accessibility-specialist.md +338 -0
  61. package/agents/specialists/security-architect.md +310 -0
  62. package/agents/specialists/software-architect.md +119 -0
  63. package/agents/specialists/sre-site-reliability-engineer.md +97 -0
  64. package/agents/specialists/technical-writer.md +398 -0
  65. package/agents/specialists/test-automation-engineer.md +186 -0
  66. package/agents/specialists/test-results-analyzer.md +310 -0
  67. package/agents/specialists/threat-detection-engineer.md +540 -0
  68. package/agents/specialists/ui-designer.md +388 -0
  69. package/agents/specialists/ui-finish-gate-reviewer.md +220 -0
  70. package/agents/specialists/uswds-developer.md +339 -0
  71. package/agents/specialists/ux-architect.md +474 -0
  72. package/agents/specialists/ux-researcher.md +334 -0
  73. package/agents/specialists/video-streaming-engineer.md +157 -0
  74. package/agents/specialists/visual-storyteller.md +155 -0
  75. package/agents/specialists/web-gis-developer.md +115 -0
  76. package/agents/specialists/webassembly-engineer.md +163 -0
  77. package/agents/specialists/wechat-mini-program-developer.md +356 -0
  78. package/agents/specialists/whimsy-injector.md +444 -0
  79. package/agents/specialists/workflow-architect.md +590 -0
  80. package/bin/cli.js +351 -0
  81. package/bin/install.mjs +418 -0
  82. package/bin/lib/config-root.mjs +51 -0
  83. package/bin/lib/merge-commands.mjs +138 -0
  84. package/bin/lib/merge-env-flags.mjs +92 -0
  85. package/bin/lib/merge-schema.mjs +77 -0
  86. package/bin/lib/merge-subagent-depth.mjs +133 -0
  87. package/bin/lib/plugin-park.mjs +48 -0
  88. package/bin/lib/relay-process.mjs +116 -0
  89. package/bin/lib/runtime-state.mjs +118 -0
  90. package/bin/menu.mjs +582 -0
  91. package/bin/uninstall.mjs +360 -0
  92. package/package.json +50 -4
  93. package/src/index.ts +115 -0
  94. package/src/state/tracker.ts +102 -0
  95. package/src/tools/broadcast.ts +58 -0
  96. package/src/tools/delegate.ts +154 -0
  97. package/src/tools/status.ts +25 -0
  98. package/src/tools/terminate.ts +70 -0
  99. package/src/tui.ts +9 -0
  100. package/src/worktree/manager.ts +142 -0
@@ -0,0 +1,360 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { cp, mkdir, readFile, writeFile, rm, readdir } from "node:fs/promises"
4
+ import { existsSync } from "node:fs"
5
+ import { join, dirname } from "node:path"
6
+ import { fileURLToPath } from "node:url"
7
+ import { spawnSync } from "node:child_process"
8
+ import { killRelayProcesses, killOrphanedServeProcesses, rmRetry } from "./lib/relay-process.mjs"
9
+ import { mergeSubagentDepth } from "./lib/merge-subagent-depth.mjs"
10
+ import { mergeSlashCommands } from "./lib/merge-commands.mjs"
11
+ import { mergeSchema } from "./lib/merge-schema.mjs"
12
+ import { mergeEnvFlags } from "./lib/merge-env-flags.mjs"
13
+ import { resolveConfigRoot } from "./lib/config-root.mjs"
14
+ import { removeRuntimeStateDirs } from "./lib/runtime-state.mjs"
15
+ import { removeParkedPlugin } from "./lib/plugin-park.mjs"
16
+
17
+ const argv = process.argv.slice(2)
18
+ const configDirIndex = argv.indexOf("--config-dir")
19
+ if (configDirIndex !== -1 && argv[configDirIndex + 1]) {
20
+ process.env.OPENCODE_CONFIG_DIR = argv[configDirIndex + 1]
21
+ }
22
+
23
+ // Config root is resolved lazily per action (NOT at module load): menu.mjs may
24
+ // install into the same shared root (~/.config/opencode for both modes; only
25
+ // the plugin placement differs) after this module was imported, and detection
26
+ // must see the markers once written. Legacy `.config/ocd` installs are still
27
+ // detected for cleanup via resolveConfigRoot().
28
+ let cachedRoot = null
29
+ function root() {
30
+ if (!cachedRoot) cachedRoot = resolveConfigRoot()
31
+ return cachedRoot
32
+ }
33
+
34
+ const VERSION_FILE = () => join(root(), ".installed-version")
35
+ const MODE_FILE = () => join(root(), ".installed-mode")
36
+ const BACKUP_ROOT = () => join(root(), ".backups")
37
+
38
+ // Directories/files to EXCLUDE from copy (regenerated or too large)
39
+ const EXCLUDE_DIRS = new Set(["node_modules", ".backups", ".git"])
40
+ const EXCLUDE_FILES = new Set([".relay-token", "bun.lock", "package-lock.json"])
41
+
42
+ // --- Recursively copy excluding unwanted dirs/files ---
43
+ async function copyTreeExcluded(source, target, excludeDirs, excludeFiles) {
44
+ await mkdir(target, { recursive: true })
45
+ const entries = await readdir(source, { withFileTypes: true })
46
+ for (const entry of entries) {
47
+ const srcPath = join(source, entry.name)
48
+ const dstPath = join(target, entry.name)
49
+ if (entry.isDirectory()) {
50
+ if (!excludeDirs.has(entry.name)) {
51
+ await copyTreeExcluded(srcPath, dstPath, excludeDirs, excludeFiles)
52
+ }
53
+ } else {
54
+ if (!excludeFiles.has(entry.name)) {
55
+ await cp(srcPath, dstPath, { force: true })
56
+ }
57
+ }
58
+ }
59
+ }
60
+
61
+ // --- Helpers ---
62
+ async function getCurrentVersion() {
63
+ if (!existsSync(VERSION_FILE())) return null
64
+ return (await readFile(VERSION_FILE(), "utf-8")).trim()
65
+ }
66
+
67
+ // Installed mode: "full" | "agents". Legacy installs that predate the marker
68
+ // default to "full" so their uninstall behaves exactly as before.
69
+ async function getInstalledMode() {
70
+ if (!existsSync(MODE_FILE())) return "full"
71
+ const mode = (await readFile(MODE_FILE(), "utf-8")).trim()
72
+ return mode === "agents" ? "agents" : "full"
73
+ }
74
+
75
+ async function listBackups() {
76
+ if (!existsSync(BACKUP_ROOT())) return []
77
+ const entries = await readdir(BACKUP_ROOT())
78
+ const backups = []
79
+ for (const name of entries) {
80
+ const dir = join(BACKUP_ROOT(), name)
81
+ let version = "unknown"
82
+ try {
83
+ version = (await readFile(join(dir, ".backup-version"), "utf-8")).trim()
84
+ } catch {
85
+ try {
86
+ version = (await readFile(join(dir, ".installed-version"), "utf-8")).trim()
87
+ } catch {}
88
+ }
89
+ backups.push({ name, dir, version })
90
+ }
91
+ return backups.sort((a, b) => b.name.localeCompare(a.name)) // newest first
92
+ }
93
+
94
+ // --- Actions ---
95
+
96
+ export async function uninstall() {
97
+ const version = await getCurrentVersion()
98
+ if (!version) {
99
+ console.log("\n No Agent-Teams installation found.\n")
100
+ return false
101
+ }
102
+
103
+ const mode = await getInstalledMode()
104
+
105
+ console.log(" Stopping any running Agent-Teams relay...")
106
+ await killRelayProcesses()
107
+
108
+ // Reap orphaned auxiliary `opencode serve` processes (parent already dead)
109
+ // so their old in-memory plugin can't respawn relays/state dirs after the
110
+ // uninstall. Only opencode.exe processes with a `serve` argument whose
111
+ // parent PID no longer exists are killed — live instances' servers and any
112
+ // other process are never touched.
113
+ await killOrphanedServeProcesses()
114
+
115
+ // Scrub RUNTIME token/state dirs the relay wrote under
116
+ // %LOCALAPPDATA%\opencode\agent-teams\<port> (plugin stateRoot). This is the
117
+ // live shared-secret the plugin actually reads — removing it is what truly
118
+ // kills a leaked token. removeRuntimeStateDirs only touches plugin-owned
119
+ // per-port dirs (token/token.tmp/relay.log/server.log and the WAL + checkpoint
120
+ // durable store agent-teams-relay.wal/agent-teams-relay-state.json + transient .tmp files),
121
+ // never user files.
122
+ const runtime = await removeRuntimeStateDirs({ removeDatabase: true })
123
+ if (runtime.removed > 0) {
124
+ console.log(` Removed ${runtime.removed} stale runtime token/log dir(s) under ${runtime.root}`)
125
+ }
126
+ if (runtime.skipped > 0) {
127
+ console.warn(` Skipped ${runtime.skipped} dir(s) under ${runtime.root}: contain non-plugin files (kept)`)
128
+ }
129
+
130
+ // Remove managed files only (don't nuke user config). Mode-aware:
131
+ // - full: the whole agents/plugins/relay set (historical behavior)
132
+ // - agents: ONLY our artifacts — never other user plugins, node_modules,
133
+ // opencode.json, or package.json
134
+ //
135
+ // NOTE (legacy scrub): `<configRoot>/.relay-token` is a deprecated vestige of
136
+ // early installs — NO current runtime code reads it (relay + plugin use the
137
+ // per-port token under LOCALAPPDATA/opencode/agent-teams, scrubbed above).
138
+ // We still remove it here for historical compatibility / world-readable secret.
139
+ if (mode === "agents") {
140
+ const MANAGED_PATHS = [
141
+ join(root(), "agents"),
142
+ join(root(), "relay"),
143
+ join(root(), "plugins", "agent-teams.ts"),
144
+ // Parked plugin from agents-only installs sharing the config root
145
+ // (out of autodiscovery under plugins-disabled/).
146
+ join(root(), "plugins-disabled", "agent-teams.ts"),
147
+ join(root(), ".relay-token"),
148
+ ]
149
+ for (const target of MANAGED_PATHS) {
150
+ if (existsSync(target)) await rmRetry(target)
151
+ }
152
+ await removeParkedPlugin(root())
153
+ } else {
154
+ const MANAGED_DIRS = ["agents", "plugins", "relay", "plugins-disabled"]
155
+ const MANAGED_FILES = [".relay-token"]
156
+
157
+ for (const dir of MANAGED_DIRS) {
158
+ const target = join(root(), dir)
159
+ if (existsSync(target)) await rmRetry(target)
160
+ }
161
+ for (const file of MANAGED_FILES) {
162
+ const target = join(root(), file)
163
+ if (existsSync(target)) await rmRetry(target)
164
+ }
165
+ }
166
+ if (existsSync(VERSION_FILE())) await rm(VERSION_FILE(), { force: true })
167
+ if (existsSync(MODE_FILE())) await rm(MODE_FILE(), { force: true })
168
+
169
+ // Strip subagent_depth and slash commands from global opencode.json so stock opencode core can start
170
+ await mergeSubagentDepth(root(), console.log, "uninstall")
171
+ await mergeSlashCommands(root(), console.log, "uninstall")
172
+ await mergeSchema(root(), console.log, "uninstall")
173
+ await mergeEnvFlags(console.log, "uninstall")
174
+
175
+ // Remove only our marked block from AGENTS.md — preserve user content
176
+ const agentsMdPath = join(root(), "AGENTS.md")
177
+ const START_MARKER = "<!-- agent-teams-orchestration:start -->"
178
+ const END_MARKER = "<!-- agent-teams-orchestration:end -->"
179
+ if (existsSync(agentsMdPath)) {
180
+ const content = await readFile(agentsMdPath, "utf-8")
181
+ if (content.includes(START_MARKER) && content.includes(END_MARKER)) {
182
+ const before = content.slice(0, content.indexOf(START_MARKER)).trimEnd()
183
+ const after = content.slice(content.indexOf(END_MARKER) + END_MARKER.length).trimStart()
184
+ const cleaned = [before, after].filter(Boolean).join("\n\n").trimEnd()
185
+ if (cleaned.length === 0) {
186
+ await rm(agentsMdPath, { force: true })
187
+ console.log(" Removed AGENTS.md (was only our content)")
188
+ } else {
189
+ await writeFile(agentsMdPath, cleaned + "\n", "utf-8")
190
+ console.log(" Removed orchestration rules from AGENTS.md (user content preserved)")
191
+ }
192
+ }
193
+ }
194
+
195
+ console.log(`\n Agent-Teams v${version} uninstalled.`)
196
+ console.log(` Mode: ${mode}${mode === "agents" ? " (other user plugins preserved)" : ""}`)
197
+ console.log(` Config directory preserved: ${root()}`)
198
+
199
+ const backups = await listBackups()
200
+ if (backups.length > 0) {
201
+ console.log(`\n Available backups (${backups.length}):`)
202
+ for (const b of backups) {
203
+ console.log(` - v${b.version} (${b.name})`)
204
+ }
205
+ console.log(`\n To restore a backup: npx opencode-agent-teams-relay-uninstall revert`)
206
+ }
207
+ console.log("")
208
+ return true
209
+ }
210
+
211
+ export async function revert(backupName) {
212
+ const backups = await listBackups()
213
+ if (backups.length === 0) {
214
+ console.log("\n No backups available to revert to.\n")
215
+ return false
216
+ }
217
+
218
+ let target
219
+ if (backupName) {
220
+ target = backups.find((b) => b.name === backupName || b.version === backupName)
221
+ if (!target) {
222
+ console.log(`\n Backup '${backupName}' not found.`)
223
+ console.log(" Available backups:")
224
+ for (const b of backups) {
225
+ console.log(` - v${b.version} (${b.name})`)
226
+ }
227
+ console.log("")
228
+ return false
229
+ }
230
+ } else {
231
+ target = backups[0] // default to most recent
232
+ }
233
+
234
+ const currentVersion = await getCurrentVersion()
235
+ console.log(`\n Reverting: v${currentVersion || "?"} -> v${target.version}`)
236
+ console.log(` ${target.dir}\n`)
237
+
238
+ // Step 0: Stop the relay before touching any files it holds open.
239
+ // Without this, the relay keeps relay.log, server.log, and agent-teams.ts
240
+ // locked on Windows (EBUSY), causing the rm below to fail or leave the relay
241
+ // running against a half-wiped config directory.
242
+ console.log(" Stopping any running Agent-Teams relay...")
243
+ await killRelayProcesses()
244
+ await killOrphanedServeProcesses()
245
+
246
+ // Step 1: Clean the config dir completely (except .backups)
247
+ if (existsSync(root())) {
248
+ const entries = await readdir(root())
249
+ for (const entry of entries) {
250
+ if (entry === ".backups") continue
251
+ await rm(join(root(), entry), { recursive: true, force: true })
252
+ }
253
+ }
254
+
255
+ // Step 2: Restore everything from backup
256
+ await copyTreeExcluded(target.dir, root(), EXCLUDE_DIRS, EXCLUDE_FILES)
257
+
258
+ // Step 2.5: Ensure subagent_depth default is (re)applied additively after a restore —
259
+ // never overwrite a value the user set in the backup; just guarantee the key exists.
260
+ // Mode-aware: agents (fork) applies it; full (stock) strips it (invalid on stock).
261
+ const installedMode = await getInstalledMode()
262
+ console.log(` Ensuring subagent_depth and slash commands in global config (mode: ${installedMode})...`)
263
+ await mergeSubagentDepth(root(), console.log, installedMode)
264
+ await mergeSlashCommands(root(), console.log, installedMode)
265
+ await mergeSchema(root(), console.log, installedMode)
266
+
267
+ // Step 3: Run npm install to restore dependencies
268
+ console.log(" Restoring npm dependencies...")
269
+ const npmCmd = process.env.ComSpec || "cmd.exe"
270
+ const npmArgs = process.platform === "win32"
271
+ ? ["/d", "/s", "/c", "npm", "install", "--ignore-scripts", "--no-audit", "--no-fund", "--save-exact"]
272
+ : ["install", "--ignore-scripts", "--no-audit", "--no-fund", "--save-exact"]
273
+ const npmBin = process.platform === "win32" ? npmCmd : "npm"
274
+ spawnSync(npmBin, npmArgs, {
275
+ cwd: root(),
276
+ stdio: "inherit",
277
+ })
278
+
279
+ console.log(`\n ${currentVersion ? `Restored from v${currentVersion}` : "Installed"} to v${target.version}`)
280
+ console.log(` Config: ${root()}`)
281
+ console.log(` Backup kept at: ${target.dir}`)
282
+ console.log(`\n Restart opencode to load the restored version.\n`)
283
+
284
+ return true
285
+ }
286
+
287
+ export async function status() {
288
+ const version = await getCurrentVersion()
289
+ const backups = await listBackups()
290
+ const mode = await getInstalledMode()
291
+
292
+ console.log("\n Agent-Teams Status")
293
+ console.log(" ==================")
294
+
295
+ if (version) {
296
+ console.log(`\n Installed version: v${version}`)
297
+ console.log(` Installed mode: ${mode}${mode === "agents" ? " (agents only)" : ""}`)
298
+ console.log(` Install location: ${root()}`)
299
+ } else {
300
+ console.log("\n Not installed.")
301
+ }
302
+
303
+ if (backups.length > 0) {
304
+ console.log(`\n Backups (${backups.length}):`)
305
+ for (const b of backups) {
306
+ console.log(` - v${b.version} (${b.name})`)
307
+ }
308
+ } else {
309
+ console.log("\n No backups available.")
310
+ }
311
+
312
+ console.log("")
313
+ return { version, backups }
314
+ }
315
+
316
+ export async function deleteBackup(backupName) {
317
+ const backups = await listBackups()
318
+ if (backups.length === 0) {
319
+ console.log("\n No backups available to delete.\n")
320
+ return false
321
+ }
322
+
323
+ if (backupName === "all") {
324
+ for (const b of backups) {
325
+ await rm(b.dir, { recursive: true, force: true })
326
+ }
327
+ console.log(`\n Deleted all ${backups.length} backups.\n`)
328
+ return true
329
+ }
330
+
331
+ const target = backups.find((b) => b.name === backupName || b.version === backupName)
332
+ if (!target) {
333
+ console.log(`\n Backup '${backupName}' not found.\n`)
334
+ return false
335
+ }
336
+
337
+ await rm(target.dir, { recursive: true, force: true })
338
+ console.log(`\n Deleted backup: ${target.name}\n`)
339
+ return true
340
+ }
341
+
342
+ // --- CLI entry point ---
343
+ const args = process.argv.slice(2)
344
+ const command = args[0]
345
+
346
+ if (command === "uninstall") {
347
+ await uninstall()
348
+ } else if (command === "revert") {
349
+ await revert(args[1])
350
+ } else if (command === "clean-backups") {
351
+ await deleteBackup(args[1] || "all")
352
+ } else if (command === "status") {
353
+ await status()
354
+ } else {
355
+ console.log("\n Usage:")
356
+ console.log(" node uninstall.mjs uninstall Remove Agent-Teams (keep config)")
357
+ console.log(" node uninstall.mjs revert [ver] Restore full config from backup")
358
+ console.log(" node uninstall.mjs clean-backups [ver] Delete backup(s)")
359
+ console.log(" node uninstall.mjs status Show installed version and backups\n")
360
+ }
package/package.json CHANGED
@@ -1,6 +1,52 @@
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.0",
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
+ "typescript": "^7.0.2"
36
+ },
37
+ "repository": {
38
+ "type": "git",
39
+ "url": "git+https://github.com/mdsohail99/opencode-agent-teams.git"
40
+ },
41
+ "author": "mdsohail99",
42
+ "license": "MIT",
43
+ "keywords": [
44
+ "opencode",
45
+ "agent-teams",
46
+ "orchestration",
47
+ "multi-agent",
48
+ "subagent",
49
+ "parallel",
50
+ "worktree"
51
+ ]
52
+ }
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
+ }