@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/bin/install.mjs DELETED
@@ -1,418 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- import { cp, mkdir, readFile, writeFile, rm, readdir, stat } from "node:fs/promises"
4
- import { existsSync } from "node:fs"
5
- import { join, dirname, relative } 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 { parkPlugin, removeParkedPlugin } from "./lib/plugin-park.mjs"
16
-
17
- // --- ANSI colors ---
18
- const c = {
19
- reset: "\x1b[0m",
20
- bold: "\x1b[1m",
21
- dim: "\x1b[2m",
22
- red: "\x1b[31m",
23
- green: "\x1b[32m",
24
- yellow: "\x1b[33m",
25
- blue: "\x1b[34m",
26
- magenta: "\x1b[35m",
27
- cyan: "\x1b[36m",
28
- white: "\x1b[37m",
29
- bgBlue: "\x1b[44m",
30
- bgGreen: "\x1b[42m",
31
- bgRed: "\x1b[41m",
32
- }
33
-
34
- const packageRoot = join(dirname(fileURLToPath(import.meta.url)), "..")
35
-
36
- // --- Install mode -----------------------------------------------------------
37
- // full (default) : curated agents + AGENTS.md block + plugin + relay + npm dep
38
- // agents (--agents-only): curated agents + AGENTS.md block ONLY (fork users)
39
- const argv = process.argv.slice(2)
40
- const configDirIndex = argv.indexOf("--config-dir")
41
- if (configDirIndex !== -1 && argv[configDirIndex + 1]) {
42
- process.env.OPENCODE_CONFIG_DIR = argv[configDirIndex + 1]
43
- }
44
- const MODE = argv.includes("--agents-only") ? "agents" : "full"
45
- const MODE_LABEL = MODE === "agents" ? "agents-only" : "full"
46
-
47
- const configRoot = resolveConfigRoot(MODE)
48
-
49
- // --- Read version ---
50
- const pkg = JSON.parse(await readFile(join(packageRoot, "package.json"), "utf8"))
51
- const NEW_VERSION = pkg.version
52
-
53
- // --- Paths ---
54
- const VERSION_FILE = join(configRoot, ".installed-version")
55
- const MODE_FILE = join(configRoot, ".installed-mode")
56
- const BACKUP_ROOT = join(configRoot, ".backups")
57
-
58
- // Directories/files to EXCLUDE from backup (they are regenerated or too large)
59
- const EXCLUDE_DIRS = new Set(["node_modules", ".backups", ".git"])
60
- const EXCLUDE_FILES = new Set([".relay-token", "bun.lock", "package-lock.json"])
61
-
62
- const copyTree = async (source, target) => {
63
- await mkdir(target, { recursive: true })
64
- await cp(source, target, { recursive: true, force: true })
65
- }
66
-
67
- // --- Recursively copy, excluding unwanted dirs/files ---
68
- async function copyTreeExcluded(source, target, excludeDirs, excludeFiles) {
69
- await mkdir(target, { recursive: true })
70
- const entries = await readdir(source, { withFileTypes: true })
71
- for (const entry of entries) {
72
- const srcPath = join(source, entry.name)
73
- const dstPath = join(target, entry.name)
74
- if (entry.isDirectory()) {
75
- if (!excludeDirs.has(entry.name)) {
76
- await copyTreeExcluded(srcPath, dstPath, excludeDirs, excludeFiles)
77
- }
78
- } else {
79
- if (!excludeFiles.has(entry.name)) {
80
- await cp(srcPath, dstPath, { force: true })
81
- }
82
- }
83
- }
84
- }
85
-
86
- // --- Backup ENTIRE config directory ---
87
- async function backupExisting() {
88
- const hasInstallation = existsSync(VERSION_FILE) || existsSync(join(configRoot, "agents"))
89
-
90
- if (!hasInstallation) {
91
- // Check if config dir has any content at all
92
- if (!existsSync(configRoot)) {
93
- return null
94
- }
95
- const entries = await readdir(configRoot)
96
- const meaningful = entries.filter((e) => !e.startsWith(".") && e !== "node_modules")
97
- if (meaningful.length === 0) {
98
- return null
99
- }
100
- }
101
-
102
- const prevVersion = existsSync(VERSION_FILE)
103
- ? (await readFile(VERSION_FILE, "utf-8")).trim()
104
- : "pre-install"
105
- const timestamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19)
106
- const backupDir = join(BACKUP_ROOT, `${prevVersion}-${timestamp}`)
107
-
108
- console.log(` ${c.dim}Backing up entire config directory...${c.reset}`)
109
- await copyTreeExcluded(configRoot, backupDir, EXCLUDE_DIRS, EXCLUDE_FILES)
110
-
111
- // Save the version we're backing up
112
- await writeFile(join(backupDir, ".backup-version"), prevVersion, "utf-8")
113
-
114
- console.log(` ${c.green}✓${c.reset} Full backup saved to ${backupDir}`)
115
- return { version: prevVersion, dir: backupDir }
116
- }
117
-
118
- // --- Restore from backup (full restore) ---
119
- export async function restoreFromBackup(backupDir) {
120
- // Read what version this backup is
121
- let backupVersion = "unknown"
122
- try {
123
- backupVersion = (await readFile(join(backupDir, ".backup-version"), "utf-8")).trim()
124
- } catch {}
125
-
126
- console.log(` ${c.dim}Restoring from backup (v${backupVersion})...${c.reset}`)
127
-
128
- // Clean the config dir completely (except .backups)
129
- if (existsSync(configRoot)) {
130
- const entries = await readdir(configRoot)
131
- for (const entry of entries) {
132
- if (entry === ".backups") continue
133
- await rm(join(configRoot, entry), { recursive: true, force: true })
134
- }
135
- }
136
-
137
- // Restore everything from backup (except .backups and node_modules)
138
- await copyTreeExcluded(backupDir, configRoot, EXCLUDE_DIRS, EXCLUDE_FILES)
139
-
140
- // Ensure subagent_depth and max_concurrent_agents defaults are (re)applied additively —
141
- // never overwrite a value the user set in the backup; just guarantee the keys exist.
142
- // Validated by local schema.json in both full and agents modes.
143
- await mergeSubagentDepth(configRoot, console.log, MODE)
144
- await mergeSlashCommands(configRoot, console.log, MODE)
145
- await mergeSchema(configRoot, console.log, MODE)
146
-
147
- // Run npm install to restore dependencies
148
- const npmCmd = process.env.ComSpec || "cmd.exe"
149
- const npmArgs = process.platform === "win32"
150
- ? ["/d", "/s", "/c", "npm", "install", "--ignore-scripts", "--no-audit", "--no-fund", "--save-exact"]
151
- : ["install", "--ignore-scripts", "--no-audit", "--no-fund", "--save-exact"]
152
- const npmBin = process.platform === "win32" ? npmCmd : "npm"
153
- spawnSync(npmBin, npmArgs, {
154
- cwd: configRoot,
155
- stdio: "inherit",
156
- })
157
-
158
- console.log(` ${c.green}✓${c.reset} Restored to v${backupVersion}`)
159
- return backupVersion
160
- }
161
-
162
- // --- Clean managed files only (for fresh install on top) ---
163
- // Mode-aware: full mode manages the whole agents/plugins/relay set; agents-only
164
- // mode manages ONLY our own artifacts and never touches other users' plugins.
165
- async function cleanManaged() {
166
- console.log(" Stopping any running Agent-Teams relay...")
167
- await killRelayProcesses()
168
-
169
- // Also reap auxiliary `opencode serve` processes orphaned by closed
170
- // terminals — their old in-memory plugin respawns relays + state dirs
171
- // after every cleanup, which is what kept "Removed N stale dir(s)" coming
172
- // back. Only processes whose PARENT is already dead are touched; live
173
- // instances' servers (parent alive) are never killed.
174
- await killOrphanedServeProcesses()
175
-
176
- // Scrub RUNTIME token/state dirs from previous runs
177
- // (%LOCALAPPDATA%\opencode\agent-teams\<port> — the live shared-secret the
178
- // plugin reads). Remove them on (re)install so a reinstall never reuses a
179
- // stale token and the runtime dir cannot accumulate. Only plugin-owned
180
- // per-port dirs (token/token.tmp/relay.log/server.log + WAL/checkpoint state files)
181
- // are removed — never user files that happen to sit under the state root.
182
- const runtime = await removeRuntimeStateDirs()
183
- if (runtime.removed > 0) {
184
- console.log(` Removed ${runtime.removed} stale runtime token/log dir(s) under ${runtime.root}`)
185
- }
186
- if (runtime.skipped > 0) {
187
- console.warn(` Skipped ${runtime.skipped} dir(s) under ${runtime.root}: contain non-plugin files (kept)`)
188
- }
189
-
190
- if (MODE === "agents") {
191
- // Remove our dirs and files only. The `plugins` dir is NOT removed as a
192
- // whole — our plugin file is PARKED instead of deleted so other user
193
- // plugins survive a conversion from full -> agents. Parking (moving the
194
- // file into plugins-disabled/) keeps it out of autodiscovery
195
- // (`{plugin,plugins}/*.{ts,js}`), so the native fork's compiled-in
196
- // next_agent/agents_status run collision-free; a later `full` install
197
- // restores it into plugins/.
198
- // `.relay-token` below is a legacy scrub (deprecated; see note in the
199
- // full-mode branch — runtime tokens live under LOCALAPPDATA now).
200
- const MANAGED_PATHS = [
201
- join(configRoot, "agents"),
202
- join(configRoot, "relay"),
203
- join(configRoot, ".relay-token"),
204
- ]
205
- for (const target of MANAGED_PATHS) {
206
- if (!existsSync(target)) continue
207
- try {
208
- await rmRetry(target)
209
- } catch {
210
- // Still locked by an active background process; copyTree will overwrite in place
211
- }
212
- }
213
- if (parkPlugin(configRoot)) {
214
- console.log(` ${c.dim}Parked plugin into plugins-disabled/ (native-fork mode).${c.reset}`)
215
- }
216
- return
217
- }
218
-
219
- const MANAGED_DIRS = ["agents", "plugins", "relay"]
220
- // Legacy scrub: `<configRoot>/.relay-token` is a deprecated vestige of early
221
- // installs; no current runtime code reads it (the relay + plugin use the
222
- // per-port token under LOCALAPPDATA/opencode/agent-teams, scrubbed above).
223
- // Removed here for historical compatibility / world-readable secret.
224
- const MANAGED_FILES = [".relay-token"]
225
-
226
- for (const dir of MANAGED_DIRS) {
227
- const target = join(configRoot, dir)
228
- if (existsSync(target)) {
229
- try {
230
- await rmRetry(target)
231
- } catch {
232
- // Directory locked by active background process; copyTree will overwrite files in place
233
- }
234
- }
235
- }
236
- for (const file of MANAGED_FILES) {
237
- const target = join(configRoot, file)
238
- if (existsSync(target)) {
239
- try {
240
- await rm(target, { force: true })
241
- } catch {
242
- // File locked; copyTree will overwrite
243
- }
244
- }
245
- }
246
- // Full mode re-activates the plugin: drop any parked copy from an earlier
247
- // agents-only install in this same config root.
248
- await removeParkedPlugin(configRoot)
249
- }
250
-
251
- // --- Prune old backups, keep only the last 5 ---
252
- async function pruneBackups() {
253
- if (!existsSync(BACKUP_ROOT)) return
254
- const entries = await readdir(BACKUP_ROOT)
255
- if (entries.length <= 5) return
256
-
257
- const sorted = entries.sort()
258
- const toRemove = sorted.slice(0, sorted.length - 5)
259
- for (const name of toRemove) {
260
- await rm(join(BACKUP_ROOT, name), { recursive: true, force: true })
261
- console.log(` ${c.dim}Pruned old backup: ${name}${c.reset}`)
262
- }
263
- }
264
-
265
- // --- Merge plugin dependency ---
266
- const mergePluginDependency = async () => {
267
- const packagePath = join(configRoot, "package.json")
268
- let config = {}
269
- if (existsSync(packagePath)) {
270
- try {
271
- config = JSON.parse(await readFile(packagePath, "utf8"))
272
- } catch {
273
- throw new Error(`Cannot parse ${packagePath}; fix it before installing Agent-Teams.`)
274
- }
275
- }
276
- config.dependencies = { ...(config.dependencies || {}), "@opencode-ai/plugin": "1.2.27" }
277
- await writeFile(packagePath, `${JSON.stringify(config, null, 2)}\n`, "utf8")
278
-
279
- const npmCmd = process.env.ComSpec || "cmd.exe"
280
- const npmArgs = process.platform === "win32"
281
- ? ["/d", "/s", "/c", "npm", "install", "--ignore-scripts", "--no-audit", "--no-fund", "--save-exact"]
282
- : ["install", "--ignore-scripts", "--no-audit", "--no-fund", "--save-exact"]
283
- const npmBin = process.platform === "win32" ? npmCmd : "npm"
284
- const result = spawnSync(npmBin, npmArgs, {
285
- cwd: configRoot,
286
- stdio: "inherit",
287
- })
288
- if (result.error) throw result.error
289
- if (result.status !== 0) process.exit(result.status || 1)
290
- }
291
-
292
- // --- Merge AGENTS.md (append-or-replace our marked block, never clobber user content) ---
293
- async function mergeAgentsMd() {
294
- const target = join(configRoot, "AGENTS.md")
295
- const AGENTS_MD = join(packageRoot, "AGENTS.md")
296
- const START_MARKER = "<!-- agent-teams-orchestration:start -->"
297
- const END_MARKER = "<!-- agent-teams-orchestration:end -->"
298
-
299
- let packageContent = ""
300
- try {
301
- packageContent = (await readFile(AGENTS_MD, "utf-8")).trimEnd()
302
- } catch {
303
- return // No AGENTS.md in package — nothing to do
304
- }
305
-
306
- // Ensure the package content is wrapped with our markers
307
- if (!packageContent.includes(START_MARKER)) {
308
- packageContent = `${START_MARKER}\n${packageContent}\n${END_MARKER}`
309
- }
310
-
311
- // Fresh install — no AGENTS.md exists yet
312
- if (!existsSync(target)) {
313
- await writeFile(target, packageContent + "\n", "utf-8")
314
- console.log(` ${c.green}✓${c.reset} Created AGENTS.md`)
315
- return
316
- }
317
-
318
- const existing = await readFile(target, "utf-8")
319
-
320
- // Re-install / upgrade — replace only our marked block, preserve everything else
321
- if (existing.includes(START_MARKER) && existing.includes(END_MARKER)) {
322
- const before = existing.slice(0, existing.indexOf(START_MARKER))
323
- const after = existing.slice(existing.indexOf(END_MARKER) + END_MARKER.length)
324
- const merged = before.trimEnd() + "\n\n" + packageContent + "\n" + after.trimStart()
325
- await writeFile(target, merged, "utf-8")
326
- console.log(` ${c.green}✓${c.reset} Updated orchestration rules in AGENTS.md`)
327
- return
328
- }
329
-
330
- // First install on a user who already has their own AGENTS.md — append our block
331
- const merged = existing.trimEnd() + "\n\n" + packageContent + "\n"
332
- await writeFile(target, merged, "utf-8")
333
- console.log(` ${c.green}✓${c.reset} Appended orchestration rules to existing AGENTS.md`)
334
- }
335
-
336
- // ============================================================
337
- // MAIN INSTALL
338
- // ============================================================
339
-
340
- console.log(`\n Agent-Teams v${NEW_VERSION} installer\n`)
341
- console.log(` ${c.dim}Mode: ${MODE_LABEL}${MODE === "agents" ? " (agents only — no plugin/relay/npm)" : " (agents + plugin + relay + npm)"}${c.reset}\n`)
342
-
343
- // Step 1: Full backup of everything
344
- const backup = await backupExisting()
345
-
346
- // Step 2: Clean only managed files (mode-aware)
347
- await cleanManaged()
348
-
349
- // Step 3: Copy new agent-teams files (mode-aware: agents-only copies agents only)
350
- await copyTree(join(packageRoot, "agents", "orchestrators"), join(configRoot, "agents"))
351
- await copyTree(join(packageRoot, "agents", "specialists"), join(configRoot, "agents"))
352
- if (MODE === "agents") {
353
- // Fork-correct Agent-Teams: on the native fork (no relay) the orchestrator
354
- // must use Task(background=true)/next_agent/agents_status, not running_agents.
355
- // Overwrite the relay-based orchestrator with the fork variant.
356
- const forkAgent = join(packageRoot, "agents", "orchestrators-fork", "orchestrator-agent-teams.md")
357
- if (existsSync(forkAgent)) {
358
- await cp(forkAgent, join(configRoot, "agents", "orchestrator-agent-teams.md"), { force: true })
359
- console.log(` ${c.dim}Fork mode: installed native Agent-Teams orchestrator.${c.reset}`)
360
- }
361
- } else {
362
- // Full (stock) mode: restore the relay-based orchestrator OVER any fork
363
- // variant left by an earlier agents-only install in this same config root
364
- // (the copyTree above already overwrites; this makes the restore explicit).
365
- const originalAgent = join(packageRoot, "agents", "orchestrators", "orchestrator-agent-teams.md")
366
- if (existsSync(originalAgent)) {
367
- await cp(originalAgent, join(configRoot, "agents", "orchestrator-agent-teams.md"), { force: true })
368
- console.log(` ${c.dim}Full mode: installed relay-based Agent-Teams orchestrator.${c.reset}`)
369
- }
370
- }
371
- if (MODE === "full") {
372
- await copyTree(join(packageRoot, "plugins"), join(configRoot, "plugins"))
373
- await copyTree(join(packageRoot, "relay"), join(configRoot, "relay"))
374
- }
375
-
376
- // Step 4: Write version + mode markers (mode marker in BOTH modes — also upgrades
377
- // legacy installs that predate the marker to have one on their next run)
378
- await writeFile(VERSION_FILE, NEW_VERSION, "utf-8")
379
- await writeFile(MODE_FILE, MODE, "utf-8")
380
-
381
- // Step 5: Merge AGENTS.md (both modes — it is part of the curated profile)
382
- await mergeAgentsMd()
383
-
384
- // Step 6: Merge subagent_depth & max_concurrent_agents defaults into the user's global opencode.json.
385
- // Both full and agents modes additively merge subagent_depth=2 and max_concurrent_agents=20
386
- // (validated by local schema.json, preserving custom user values).
387
- await mergeSubagentDepth(configRoot, console.log, MODE)
388
-
389
- // Step 6.5: Merge slash commands into global opencode.json (full: inject; agents: strip).
390
- await mergeSlashCommands(configRoot, console.log, MODE)
391
-
392
- // Step 6.6: Install local schema.json and ensure $schema points to it
393
- await mergeSchema(configRoot, console.log, MODE)
394
-
395
- // Step 6.7: Enable OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true by default
396
- await mergeEnvFlags(console.log, MODE)
397
-
398
- // Step 7: Merge dependency and run npm install (FULL mode only; agents-only does
399
- // NOT touch configRoot package.json and performs no npm install)
400
- if (MODE === "full") {
401
- await mergePluginDependency()
402
- } else {
403
- console.log(` ${c.dim}Skipping npm dependency install (agents-only mode).${c.reset}`)
404
- }
405
-
406
- // Step 7: Prune old backups (keep last 5)
407
- await pruneBackups()
408
-
409
- console.log(`\n ${c.green}${c.bold}✓ Installed Agent-Teams v${NEW_VERSION} (${MODE_LABEL} mode)${c.reset}`)
410
- console.log(` ${c.dim}Location: ${configRoot}${c.reset}`)
411
- if (backup) {
412
- console.log(` ${c.yellow}Full backup:${c.reset} ${backup.dir}`)
413
- console.log(` ${c.yellow}To revert:${c.reset} npx opencode-agent-teams-relay-uninstall revert`)
414
- }
415
- if (MODE === "agents") {
416
- console.log(`\n ${c.yellow}Agents-only mode:${c.reset} plugin/relay/npm were NOT installed (intended for the native fork where the plugin is redundant).`)
417
- }
418
- console.log(`\n ${c.bold}Restart opencode${c.reset} to load the new ${MODE === "agents" ? "agents" : "agents and plugin"}.\n`)
@@ -1,51 +0,0 @@
1
- // Shared config-directory resolver for Agent-Teams install/uninstall/menu.
2
- //
3
- // BOTH modes install into <home>/.config/opencode (single config world).
4
- // - full: agents + plugin (plugins/agent-teams.ts) + relay + npm dep
5
- // - agents-only: agents + AGENTS.md only; the plugin is PARKED in
6
- // plugins-disabled/ (out of autodiscovery) so the native fork
7
- // runs collision-free.
8
- //
9
- // resolveConfigRoot() without a mode detects where an existing installation
10
- // lives: a config dir with installation markers (`.installed-mode`,
11
- // `.installed-version`, or an `agents/` folder) is preferred. The legacy
12
- // `.config/ocd` location (pre-1.0.4 agents-only installs) is still honored for
13
- // upgrades/uninstalls, but new installs never target it.
14
- import { join } from "node:path"
15
- import { existsSync } from "node:fs"
16
-
17
- export function homeDir() {
18
- return process.env.USERPROFILE || process.env.HOME || process.cwd()
19
- }
20
-
21
- export function defaultConfigSubdir(mode) {
22
- // Agents-only and full share the stock config root; the mode determines
23
- // plugin placement (parked vs active), not the directory.
24
- return "opencode"
25
- }
26
-
27
- function looksLikeInstalled(dir) {
28
- return (
29
- existsSync(join(dir, ".installed-mode")) ||
30
- existsSync(join(dir, ".installed-version")) ||
31
- existsSync(join(dir, "agents"))
32
- )
33
- }
34
-
35
- /**
36
- * Resolve the config directory.
37
- * @param {"agents"|"full"|undefined} mode explicit install mode, or undefined
38
- * for auto-detection (favour a marked/agents install, else stock opencode).
39
- */
40
- export function resolveConfigRoot(mode) {
41
- const override = process.env.OPENCODE_CONFIG_DIR
42
- if (override) return override
43
- const base = join(homeDir(), ".config")
44
- if (mode === "agents" || mode === "full") return join(base, defaultConfigSubdir(mode))
45
-
46
- const opencode = join(base, "opencode")
47
- if (looksLikeInstalled(opencode)) return opencode
48
- const ocd = join(base, "ocd")
49
- if (looksLikeInstalled(ocd)) return ocd
50
- return opencode
51
- }
@@ -1,138 +0,0 @@
1
- // Shared: merge Agent-Teams slash commands into the USER's global opencode config
2
- // WITHOUT overwriting user-defined custom commands.
3
- //
4
- // MODE-AWARE:
5
- // - In `full` mode (stock opencode): injects the 6 managed slash commands:
6
- // /tree, /report, /ask, /resume, /stop, /errors
7
- // CRITICAL: Every injected command explicitly declares `"agent": "Agent-Teams"`.
8
- // - In `agents` mode (native fork) or `uninstall`: strips only the 6 managed
9
- // commands. If `config.command` becomes empty, deletes `config.command`.
10
- // Preserves all user-defined custom commands.
11
- import { readFile, writeFile } from "node:fs/promises"
12
- import { existsSync } from "node:fs"
13
- import { join } from "node:path"
14
-
15
- export const MANAGED_COMMANDS = {
16
- tree: {
17
- agent: "Agent-Teams",
18
- description: "display the live hierarchical swarm status tree: /tree [filter]",
19
- template: "Call agents_status to inspect and display the live agent hierarchy tree, elapsed times, and progress.",
20
- },
21
- report: {
22
- agent: "Agent-Teams",
23
- description: "synthesize current progress and work done across all leads and specialists: /report [filter]",
24
- template: "Call agents_status to retrieve running and completed children, inspect their deliverables, and synthesize an executive summary.",
25
- },
26
- ask: {
27
- agent: "Agent-Teams",
28
- description: "query any running lead or specialist agent out-of-band: /ask <agent> <question>",
29
- template: "Call ask_agent with target_id and prompt parsed from: $ARGUMENTS",
30
- },
31
- resume: {
32
- agent: "Agent-Teams",
33
- description: "resume or restart a stalled, failed, or paused agent: /resume <agent> [instructions]",
34
- template: "Call resume_agent with target_id and prompt parsed from: $ARGUMENTS",
35
- },
36
- stop: {
37
- agent: "Agent-Teams",
38
- description: "halt a specific agent or all running agents in the swarm: /stop [agent|all]",
39
- template: "Call manage_agents with action='kill' or 'kill_all' based on: $ARGUMENTS",
40
- },
41
- errors: {
42
- agent: "Agent-Teams",
43
- description: "scan swarm for failed, errored, or stalled agents and show diagnostics: /errors",
44
- template: "Call agents_status to find any workers with status 'error' or '[stalled]', then inspect their outputs and recommend fixes.",
45
- },
46
- }
47
-
48
- export const MANAGED_COMMAND_NAMES = Object.keys(MANAGED_COMMANDS)
49
- export const LEGACY_COMMAND_NAMES = ["agents", "status"]
50
-
51
- /**
52
- * Apply (full mode) or strip (agents/uninstall mode) managed Agent-Teams slash
53
- * commands in `configRoot/opencode.json`, preserving every user-defined command.
54
- */
55
- export async function mergeSlashCommands(configRoot, log = console.log, mode = "full") {
56
- const configPath = configRoot.endsWith("opencode.json") ? configRoot : join(configRoot, "opencode.json")
57
- let config = {}
58
- let exists = false
59
-
60
- if (existsSync(configPath)) {
61
- exists = true
62
- try {
63
- config = JSON.parse((await readFile(configPath, "utf8")).replace(/^\uFEFF/, ""))
64
- } catch (err) {
65
- throw new Error(`Cannot parse ${configPath}; fix it before installing Agent-Teams: ${err.message}`)
66
- }
67
- } else {
68
- if (mode !== "full") {
69
- return config
70
- }
71
- config = { $schema: "https://opencode.ai/config.json" }
72
- }
73
-
74
- if (typeof config !== "object" || config === null || Array.isArray(config)) {
75
- throw new Error(`${configPath} does not contain a JSON object; refusing to overwrite it.`)
76
- }
77
-
78
- let changed = false
79
-
80
- if (mode === "full") {
81
- if (!config.command || typeof config.command !== "object" || Array.isArray(config.command)) {
82
- config.command = {}
83
- changed = true
84
- }
85
-
86
- // Clean up legacy conflicting commands from earlier Agent-Teams versions
87
- for (const legacy of LEGACY_COMMAND_NAMES) {
88
- if (config.command[legacy]?.agent === "Agent-Teams") {
89
- delete config.command[legacy]
90
- changed = true
91
- }
92
- }
93
-
94
- for (const [name, def] of Object.entries(MANAGED_COMMANDS)) {
95
- const existing = config.command[name]
96
- if (
97
- !existing ||
98
- existing.agent !== def.agent ||
99
- existing.description !== def.description ||
100
- existing.template !== def.template
101
- ) {
102
- config.command[name] = { ...def }
103
- changed = true
104
- }
105
- }
106
-
107
- if (changed) {
108
- if (config.$schema === undefined) config.$schema = "https://opencode.ai/config.json"
109
- await writeFile(configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8")
110
- log(` ${exists ? "updated" : "created"} ${configPath} with Agent-Teams slash commands (user commands preserved)`)
111
- } else {
112
- log(` Agent-Teams slash commands already up to date in ${configPath}`)
113
- }
114
- } else {
115
- // agents or uninstall mode: strip managed and legacy commands
116
- if (config.command && typeof config.command === "object" && !Array.isArray(config.command)) {
117
- for (const name of [...MANAGED_COMMAND_NAMES, ...LEGACY_COMMAND_NAMES]) {
118
- if (name in config.command && (config.command[name]?.agent === "Agent-Teams" || MANAGED_COMMAND_NAMES.includes(name))) {
119
- delete config.command[name]
120
- changed = true
121
- }
122
- }
123
- if (Object.keys(config.command).length === 0) {
124
- delete config.command
125
- changed = true
126
- }
127
- }
128
-
129
- if (changed) {
130
- await writeFile(configPath, `${JSON.stringify(config, null, 2)}\n`, "utf8")
131
- log(` removed Agent-Teams slash commands from ${configPath}`)
132
- }
133
- }
134
-
135
- return config
136
- }
137
-
138
- export const mergeCommands = mergeSlashCommands