@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/uninstall.mjs DELETED
@@ -1,360 +0,0 @@
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
- }