@mdsohail99/opencode-agent-teams 2.0.0 → 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.
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "@mdsohail99/opencode-agent-teams",
3
- "version": "2.0.0",
3
+ "version": "2.0.1",
4
4
  "description": "Native Agent-Teams orchestration plugin for OpenCode v2",
5
5
  "type": "module",
6
6
  "bin": {
7
- "opencode-agent-teams": "./bin/cli.js",
8
- "opencode-agent-teams-uninstall": "./bin/cli.js"
7
+ "opencode-agent-teams": "bin/cli.js",
8
+ "opencode-agent-teams-uninstall": "bin/cli.js"
9
9
  },
10
10
  "exports": {
11
11
  ".": "./src/index.ts",
@@ -32,6 +32,7 @@
32
32
  },
33
33
  "devDependencies": {
34
34
  "@types/node": "^24.12.2",
35
+ "tsx": "^4.23.15",
35
36
  "typescript": "^7.0.2"
36
37
  },
37
38
  "repository": {
@@ -48,5 +49,9 @@
48
49
  "subagent",
49
50
  "parallel",
50
51
  "worktree"
51
- ]
52
+ ],
53
+ "scripts": {
54
+ "test": "tsx test/v2-swarm.spec.ts",
55
+ "typecheck": "tsc --noEmit"
56
+ }
52
57
  }
package/src/index.ts CHANGED
@@ -1,115 +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
- })
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
+ })
@@ -1,102 +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()
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()
@@ -1,58 +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
- }
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
+ }