@mdsohail99/opencode-agent-teams 2.0.0 → 2.1.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.
@@ -1,154 +1,181 @@
1
- import { Schema } from "effect"
2
- import type { Plugin } from "@opencode/plugin"
3
- import { globalTracker, type TeamMember } from "../state/tracker.js"
4
- import { WorktreeManager, type WorktreeSandbox } from "../worktree/manager.js"
5
- import crypto from "node:crypto"
6
-
7
- export const DelegateInput = Schema.Struct({
8
- team_name: Schema.String.annotate({
9
- description: "Departmental team name (e.g. 'Backend', 'Frontend', 'Security', 'QA', 'DevOps')",
10
- }),
11
- agent_type: Schema.String.annotate({
12
- description: "Specialist agent name or role (e.g. 'backend-architect', 'frontend-developer', 'api-tester')",
13
- }),
14
- prompt: Schema.String.annotate({
15
- description: "Detailed instructions and requirements for the teammate",
16
- }),
17
- worktree: Schema.optional(Schema.Boolean).annotate({
18
- description: "Whether to run this task in an isolated git worktree to prevent concurrent write collisions (default: true)",
19
- }),
20
- })
21
-
22
- function normalizeAgentId(raw: string): string {
23
- if (!raw) return "build"
24
- return raw
25
- .toLowerCase()
26
- .trim()
27
- .replace(/[^a-z0-9]+/g, "-")
28
- .replace(/^-|-$/g, "")
29
- }
30
-
31
- export function createDelegateTool(ctx: Plugin.Context) {
32
- return {
33
- id: "team_delegate",
34
- name: "team_delegate",
35
- description: "Delegate a task to a departmental teammate with optional git worktree sandboxing.",
36
- input: DelegateInput,
37
- execute: async (
38
- input: { team_name: string; agent_type: string; prompt: string; worktree?: boolean },
39
- toolCtx: { sessionID: string },
40
- ) => {
41
- const taskId = crypto.randomUUID().slice(0, 8)
42
- const baseDir = process.cwd()
43
- const useWorktree = input.worktree !== false
44
- const targetAgentId = normalizeAgentId(input.agent_type)
45
-
46
- let sandbox: WorktreeSandbox | undefined
47
- let workDir = baseDir
48
-
49
- if (useWorktree) {
50
- try {
51
- sandbox = await WorktreeManager.createSandbox(baseDir, input.team_name, taskId)
52
- workDir = sandbox.worktreePath
53
- } catch (err: any) {
54
- // If worktree creation fails (e.g. not a git repo), gracefully fallback to baseDir
55
- workDir = baseDir
56
- }
57
- }
58
-
59
- // Create child session via OpenCode v2 session API
60
- let childSession: any
61
- try {
62
- childSession = await ctx.session.create({
63
- agent: targetAgentId,
64
- parentID: toolCtx.sessionID,
65
- location: { directory: workDir },
66
- } as any)
67
- } catch (err: any) {
68
- if (sandbox) {
69
- await WorktreeManager.discardSandbox(baseDir, sandbox)
70
- }
71
- return {
72
- content: `Failed to spawn teammate session for ${input.team_name} (${targetAgentId}): ${err.message || String(err)}`,
73
- }
74
- }
75
-
76
- const sessionId = childSession?.id || `sess_${taskId}`
77
- const memberRecord: TeamMember = {
78
- id: taskId,
79
- teamName: input.team_name,
80
- agentType: targetAgentId,
81
- sessionId,
82
- parentSessionId: toolCtx.sessionID,
83
- status: "running",
84
- prompt: input.prompt,
85
- worktreePath: sandbox?.worktreePath,
86
- worktreeBranch: sandbox?.branchName,
87
- createdAt: Date.now(),
88
- }
89
- globalTracker.register(memberRecord)
90
-
91
- try {
92
- // Dispatch task text to subagent (OpenCode v2 SessionPromptInput takes 'text')
93
- const promptResult = await ctx.session.prompt({
94
- sessionID: sessionId,
95
- text: input.prompt,
96
- } as any)
97
-
98
- if ((ctx.session as any)?.wait) {
99
- try {
100
- await (ctx.session as any).wait({ sessionID: sessionId })
101
- } catch {
102
- // Non-fatal if wait is unsupported or timed out
103
- }
104
- }
105
-
106
- let deliverableText =
107
- (promptResult as any)?.text ||
108
- (promptResult as any)?.content ||
109
- "Task execution dispatched."
110
-
111
- // If a worktree was used, reconcile and merge changes back to base branch
112
- let reconcileNotice = ""
113
- if (sandbox) {
114
- const shortDesc = input.prompt.replace(/\s+/g, " ").slice(0, 60)
115
- const reconcile = await WorktreeManager.reconcileAndCleanup(
116
- baseDir,
117
- sandbox,
118
- `feat(${input.team_name.toLowerCase()}): ${shortDesc}`,
119
- )
120
-
121
- if (reconcile.merged) {
122
- reconcileNotice = `\n[Git]: Successfully merged changes from ${sandbox.branchName} into ${sandbox.baseBranch}. Worktree cleaned up.`
123
- } else if (reconcile.error) {
124
- reconcileNotice = `\n[Git Warning]: ${reconcile.error}`
125
- } else {
126
- reconcileNotice = `\n[Git]: No file modifications detected; worktree discarded.`
127
- }
128
- }
129
-
130
- globalTracker.update(sessionId, {
131
- status: "completed",
132
- finishedAt: Date.now(),
133
- deliverable: deliverableText,
134
- })
135
-
136
- return {
137
- content: `[Teammate Completed] ${input.team_name} (${targetAgentId}):\n${deliverableText}${reconcileNotice}`,
138
- }
139
- } catch (err: any) {
140
- if (sandbox) {
141
- await WorktreeManager.discardSandbox(baseDir, sandbox)
142
- }
143
- globalTracker.update(sessionId, {
144
- status: "error",
145
- finishedAt: Date.now(),
146
- error: err?.message || String(err),
147
- })
148
- return {
149
- content: `[Teammate Error] ${input.team_name} (${targetAgentId}) failed: ${err.message || String(err)}`,
150
- }
151
- }
152
- },
153
- }
154
- }
1
+ import { Schema } from "effect"
2
+ import type { Plugin } from "@opencode/plugin"
3
+ import { globalTracker, type TeamMember } from "../state/tracker.js"
4
+ import { WorktreeManager, type WorktreeSandbox } from "../worktree/manager.js"
5
+ import crypto from "node:crypto"
6
+
7
+ export const DelegateInput = Schema.Struct({
8
+ team_name: Schema.String.annotate({
9
+ description: "Departmental team name (e.g. 'Backend', 'Frontend', 'Security', 'QA', 'DevOps')",
10
+ }),
11
+ agent_type: Schema.String.annotate({
12
+ description: "Specialist agent name or role (e.g. 'backend-architect', 'frontend-developer', 'api-tester')",
13
+ }),
14
+ prompt: Schema.String.annotate({
15
+ description: "Detailed instructions and requirements for the teammate",
16
+ }),
17
+ worktree: Schema.optional(Schema.Boolean).annotate({
18
+ description: "Whether to run this task in an isolated git worktree (default: false; pass true for tasks modifying files concurrently)",
19
+ }),
20
+ })
21
+
22
+ function normalizeAgentId(raw: string): string {
23
+ if (!raw) return "build"
24
+ return raw
25
+ .toLowerCase()
26
+ .trim()
27
+ .replace(/[^a-z0-9]+/g, "-")
28
+ .replace(/^-|-$/g, "")
29
+ }
30
+
31
+ export function createDelegateTool(ctx: Plugin.Context) {
32
+ return {
33
+ id: "team_delegate",
34
+ name: "team_delegate",
35
+ description: "Delegate a task to a departmental teammate with optional git worktree sandboxing.",
36
+ input: DelegateInput,
37
+ execute: async (
38
+ input: { team_name: string; agent_type: string; prompt: string; worktree?: boolean },
39
+ toolCtx: { sessionID: string },
40
+ ) => {
41
+ const taskId = crypto.randomUUID().slice(0, 8)
42
+ const baseDir = process.cwd()
43
+ const useWorktree = input.worktree === true
44
+ const targetAgentId = normalizeAgentId(input.agent_type)
45
+
46
+ let sandbox: WorktreeSandbox | undefined
47
+ let workDir = baseDir
48
+
49
+ if (useWorktree) {
50
+ try {
51
+ sandbox = await WorktreeManager.createSandbox(baseDir, input.team_name, taskId)
52
+ workDir = sandbox.worktreePath
53
+ } catch (err: any) {
54
+ // If worktree creation fails (e.g. not a git repo), gracefully fallback to baseDir
55
+ workDir = baseDir
56
+ }
57
+ }
58
+
59
+ // Create child session via OpenCode v2 session API
60
+ let childSession: any
61
+ try {
62
+ childSession = await ctx.session.create({
63
+ agent: targetAgentId,
64
+ parentID: toolCtx.sessionID,
65
+ location: { directory: workDir },
66
+ } as any)
67
+ } catch (err: any) {
68
+ if (sandbox) {
69
+ await WorktreeManager.discardSandbox(baseDir, sandbox)
70
+ }
71
+ return {
72
+ content: `Failed to spawn teammate session for ${input.team_name} (${targetAgentId}): ${err.message || String(err)}`,
73
+ }
74
+ }
75
+
76
+ const sessionId = childSession?.id || `sess_${taskId}`
77
+ const memberRecord: TeamMember = {
78
+ id: taskId,
79
+ teamName: input.team_name,
80
+ agentType: targetAgentId,
81
+ sessionId,
82
+ parentSessionId: toolCtx.sessionID,
83
+ status: "running",
84
+ prompt: input.prompt,
85
+ worktreePath: sandbox?.worktreePath,
86
+ worktreeBranch: sandbox?.branchName,
87
+ createdAt: Date.now(),
88
+ }
89
+ globalTracker.register(memberRecord)
90
+
91
+ try {
92
+ // Dispatch task text to subagent (OpenCode v2 SessionPromptInput takes 'text')
93
+ const promptResult = await ctx.session.prompt({
94
+ sessionID: sessionId,
95
+ text: input.prompt,
96
+ } as any)
97
+
98
+ if ((ctx.session as any)?.wait) {
99
+ try {
100
+ await (ctx.session as any).wait({ sessionID: sessionId })
101
+ } catch {
102
+ // Non-fatal if wait is unsupported or timed out
103
+ }
104
+ }
105
+
106
+ let deliverableText =
107
+ (promptResult as any)?.text ||
108
+ (promptResult as any)?.content ||
109
+ ""
110
+
111
+ // Inspect session context for the final assistant deliverable text
112
+ if (ctx.session?.context) {
113
+ try {
114
+ const messages = await ctx.session.context({ sessionID: sessionId } as any)
115
+ if (Array.isArray(messages)) {
116
+ for (let i = messages.length - 1; i >= 0; i--) {
117
+ const msg = messages[i]
118
+ if (msg?.type === "assistant" && Array.isArray(msg.content)) {
119
+ const textParts = msg.content
120
+ .filter((p: any) => p?.type === "text" && typeof p?.text === "string")
121
+ .map((p: any) => p.text)
122
+ if (textParts.length > 0) {
123
+ deliverableText = textParts.join("\n")
124
+ break
125
+ }
126
+ }
127
+ }
128
+ }
129
+ } catch {
130
+ // Non-fatal fallback
131
+ }
132
+ }
133
+
134
+ if (!deliverableText) {
135
+ deliverableText = `Task executed by ${targetAgentId} in session ${sessionId}.`
136
+ }
137
+
138
+ // If a worktree was used, reconcile and merge changes back to base branch
139
+ let reconcileNotice = ""
140
+ if (sandbox) {
141
+ const shortDesc = input.prompt.replace(/\s+/g, " ").slice(0, 60)
142
+ const reconcile = await WorktreeManager.reconcileAndCleanup(
143
+ baseDir,
144
+ sandbox,
145
+ `feat(${input.team_name.toLowerCase()}): ${shortDesc}`,
146
+ )
147
+
148
+ if (reconcile.merged) {
149
+ reconcileNotice = `\n[Git]: Successfully merged changes from ${sandbox.branchName} into ${sandbox.baseBranch}. Worktree cleaned up.`
150
+ } else if (reconcile.error) {
151
+ reconcileNotice = `\n[Git Warning]: ${reconcile.error}`
152
+ } else {
153
+ reconcileNotice = `\n[Git]: No file modifications detected; worktree discarded.`
154
+ }
155
+ }
156
+
157
+ globalTracker.update(sessionId, {
158
+ status: "completed",
159
+ finishedAt: Date.now(),
160
+ deliverable: deliverableText,
161
+ })
162
+
163
+ return {
164
+ content: `[Teammate Completed] ${input.team_name} (${targetAgentId}):\n${deliverableText}${reconcileNotice}`,
165
+ }
166
+ } catch (err: any) {
167
+ if (sandbox) {
168
+ await WorktreeManager.discardSandbox(baseDir, sandbox)
169
+ }
170
+ globalTracker.update(sessionId, {
171
+ status: "error",
172
+ finishedAt: Date.now(),
173
+ error: err?.message || String(err),
174
+ })
175
+ return {
176
+ content: `[Teammate Error] ${input.team_name} (${targetAgentId}) failed: ${err.message || String(err)}`,
177
+ }
178
+ }
179
+ },
180
+ }
181
+ }
@@ -1,25 +1,25 @@
1
- import { Schema } from "effect"
2
- import type { Plugin } from "@opencode/plugin"
3
- import { globalTracker } from "../state/tracker.js"
4
-
5
- export const StatusInput = Schema.Struct({
6
- team_name: Schema.optional(Schema.String).annotate({
7
- description: "Filter status query to a specific department (optional)",
8
- }),
9
- })
10
-
11
- export function createStatusTool(ctx: Plugin.Context) {
12
- return {
13
- id: "team_status",
14
- name: "team_status",
15
- description:
16
- "Inspect current progress, deliverables, active git worktrees, and hierarchy of all teammates in the swarm.",
17
- input: StatusInput,
18
- execute: async (input: { team_name?: string }, toolCtx: { sessionID: string }) => {
19
- const tree = globalTracker.formatTree(toolCtx.sessionID)
20
- return {
21
- content: tree,
22
- }
23
- },
24
- }
25
- }
1
+ import { Schema } from "effect"
2
+ import type { Plugin } from "@opencode/plugin"
3
+ import { globalTracker } from "../state/tracker.js"
4
+
5
+ export const StatusInput = Schema.Struct({
6
+ team_name: Schema.optional(Schema.String).annotate({
7
+ description: "Filter status query to a specific department (optional)",
8
+ }),
9
+ })
10
+
11
+ export function createStatusTool(ctx: Plugin.Context) {
12
+ return {
13
+ id: "team_status",
14
+ name: "team_status",
15
+ description:
16
+ "Inspect current progress, deliverables, active git worktrees, and hierarchy of all teammates in the swarm.",
17
+ input: StatusInput,
18
+ execute: async (input: { team_name?: string }, toolCtx: { sessionID: string }) => {
19
+ const tree = globalTracker.formatTree(toolCtx.sessionID)
20
+ return {
21
+ content: tree,
22
+ }
23
+ },
24
+ }
25
+ }
@@ -1,70 +1,70 @@
1
- import { Schema } from "effect"
2
- import type { Plugin } from "@opencode/plugin"
3
- import { globalTracker } from "../state/tracker.js"
4
- import { WorktreeManager } from "../worktree/manager.js"
5
-
6
- export const TerminateInput = Schema.Struct({
7
- target: Schema.String.annotate({
8
- description: "Teammate ID, team name (e.g. 'Frontend'), or 'all' to terminate all running workers",
9
- }),
10
- })
11
-
12
- export function createTerminateTool(ctx: Plugin.Context) {
13
- return {
14
- id: "team_terminate",
15
- name: "team_terminate",
16
- description:
17
- "Gracefully abort/terminate a running teammate and trigger git worktree cleanup.",
18
- input: TerminateInput,
19
- execute: async (input: { target: string }, toolCtx: { sessionID: string }) => {
20
- const allMembers = globalTracker.list(toolCtx.sessionID)
21
- const isAll = input.target.toLowerCase() === "all"
22
-
23
- const targets = allMembers.filter((m) => {
24
- if (m.status !== "running") return false
25
- if (isAll) return true
26
- return (
27
- m.id === input.target ||
28
- m.sessionId === input.target ||
29
- m.teamName.toLowerCase() === input.target.toLowerCase()
30
- )
31
- })
32
-
33
- if (targets.length === 0) {
34
- return {
35
- content: `No active running teammates matched target '${input.target}'.`,
36
- }
37
- }
38
-
39
- const terminated: string[] = []
40
- const baseDir = process.cwd()
41
-
42
- for (const member of targets) {
43
- try {
44
- if (ctx.session.interrupt) {
45
- await ctx.session.interrupt({ sessionID: member.sessionId } as any)
46
- }
47
- } catch {}
48
-
49
- if (member.worktreePath && member.worktreeBranch) {
50
- await WorktreeManager.discardSandbox(baseDir, {
51
- worktreePath: member.worktreePath,
52
- branchName: member.worktreeBranch,
53
- baseBranch: "main",
54
- })
55
- }
56
-
57
- globalTracker.update(member.sessionId, {
58
- status: "terminated",
59
- finishedAt: Date.now(),
60
- })
61
-
62
- terminated.push(`${member.teamName} (${member.id})`)
63
- }
64
-
65
- return {
66
- content: `Terminated and cleaned up ${terminated.length} teammate(s): ${terminated.join(", ")}`,
67
- }
68
- },
69
- }
70
- }
1
+ import { Schema } from "effect"
2
+ import type { Plugin } from "@opencode/plugin"
3
+ import { globalTracker } from "../state/tracker.js"
4
+ import { WorktreeManager } from "../worktree/manager.js"
5
+
6
+ export const TerminateInput = Schema.Struct({
7
+ target: Schema.String.annotate({
8
+ description: "Teammate ID, team name (e.g. 'Frontend'), or 'all' to terminate all running workers",
9
+ }),
10
+ })
11
+
12
+ export function createTerminateTool(ctx: Plugin.Context) {
13
+ return {
14
+ id: "team_terminate",
15
+ name: "team_terminate",
16
+ description:
17
+ "Gracefully abort/terminate a running teammate and trigger git worktree cleanup.",
18
+ input: TerminateInput,
19
+ execute: async (input: { target: string }, toolCtx: { sessionID: string }) => {
20
+ const allMembers = globalTracker.list(toolCtx.sessionID)
21
+ const isAll = input.target.toLowerCase() === "all"
22
+
23
+ const targets = allMembers.filter((m) => {
24
+ if (m.status !== "running") return false
25
+ if (isAll) return true
26
+ return (
27
+ m.id === input.target ||
28
+ m.sessionId === input.target ||
29
+ m.teamName.toLowerCase() === input.target.toLowerCase()
30
+ )
31
+ })
32
+
33
+ if (targets.length === 0) {
34
+ return {
35
+ content: `No active running teammates matched target '${input.target}'.`,
36
+ }
37
+ }
38
+
39
+ const terminated: string[] = []
40
+ const baseDir = process.cwd()
41
+
42
+ for (const member of targets) {
43
+ try {
44
+ if (ctx.session.interrupt) {
45
+ await ctx.session.interrupt({ sessionID: member.sessionId } as any)
46
+ }
47
+ } catch {}
48
+
49
+ if (member.worktreePath && member.worktreeBranch) {
50
+ await WorktreeManager.discardSandbox(baseDir, {
51
+ worktreePath: member.worktreePath,
52
+ branchName: member.worktreeBranch,
53
+ baseBranch: "main",
54
+ })
55
+ }
56
+
57
+ globalTracker.update(member.sessionId, {
58
+ status: "terminated",
59
+ finishedAt: Date.now(),
60
+ })
61
+
62
+ terminated.push(`${member.teamName} (${member.id})`)
63
+ }
64
+
65
+ return {
66
+ content: `Terminated and cleaned up ${terminated.length} teammate(s): ${terminated.join(", ")}`,
67
+ }
68
+ },
69
+ }
70
+ }
package/src/tui.ts CHANGED
@@ -1,9 +1,9 @@
1
- export default {
2
- id: "agent-teams",
3
- setup(ctx: any) {
4
- // Agent-Teams v2 TUI integration
5
- },
6
- tui(api: any) {
7
- // OpenCode TUI compatibility hook
8
- },
9
- }
1
+ export default {
2
+ id: "agent-teams",
3
+ setup(ctx: any) {
4
+ // Agent-Teams v2 TUI integration
5
+ },
6
+ tui(api: any) {
7
+ // OpenCode TUI compatibility hook
8
+ },
9
+ }