@opencode-manager/ocm-cli 0.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.
- package/LICENSE +21 -0
- package/dist/ocm.js +716 -0
- package/dist/plugin.js +51 -0
- package/package.json +38 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025 Chris Scott
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/ocm.js
ADDED
|
@@ -0,0 +1,716 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// bin/ocm.ts
|
|
3
|
+
import { spawn as spawn2, spawnSync as spawnSync4 } from "child_process";
|
|
4
|
+
import { basename } from "path";
|
|
5
|
+
|
|
6
|
+
// src/state.ts
|
|
7
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
8
|
+
import { homedir } from "os";
|
|
9
|
+
import { dirname, join } from "path";
|
|
10
|
+
var STATE_DIR = join(homedir(), ".config", "opencode-manager");
|
|
11
|
+
var STATE_FILE = join(STATE_DIR, "state.json");
|
|
12
|
+
function getStatePath() {
|
|
13
|
+
return STATE_FILE;
|
|
14
|
+
}
|
|
15
|
+
function readState() {
|
|
16
|
+
if (!existsSync(STATE_FILE))
|
|
17
|
+
return null;
|
|
18
|
+
try {
|
|
19
|
+
const raw = readFileSync(STATE_FILE, "utf-8");
|
|
20
|
+
const parsed = JSON.parse(raw);
|
|
21
|
+
if (!parsed.managerUrl)
|
|
22
|
+
return null;
|
|
23
|
+
return parsed;
|
|
24
|
+
} catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function writeState(state) {
|
|
29
|
+
mkdirSync(dirname(STATE_FILE), { recursive: true });
|
|
30
|
+
const next = { ...state, updatedAt: Date.now() };
|
|
31
|
+
writeFileSync(STATE_FILE, JSON.stringify(next, null, 2), { mode: 384 });
|
|
32
|
+
}
|
|
33
|
+
function clearState() {
|
|
34
|
+
if (existsSync(STATE_FILE)) {
|
|
35
|
+
writeFileSync(STATE_FILE, "{}", { mode: 384 });
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// src/keychain.ts
|
|
40
|
+
import { spawnSync } from "child_process";
|
|
41
|
+
var SERVICE = "opencode-manager";
|
|
42
|
+
|
|
43
|
+
class KeychainError extends Error {
|
|
44
|
+
exitCode;
|
|
45
|
+
constructor(message, exitCode) {
|
|
46
|
+
super(message);
|
|
47
|
+
this.exitCode = exitCode;
|
|
48
|
+
this.name = "KeychainError";
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
function runSecurity(args, input) {
|
|
52
|
+
const res = spawnSync("security", args, {
|
|
53
|
+
input,
|
|
54
|
+
encoding: "utf-8"
|
|
55
|
+
});
|
|
56
|
+
return { stdout: res.stdout ?? "", stderr: res.stderr ?? "", code: res.status };
|
|
57
|
+
}
|
|
58
|
+
function setToken(account, token) {
|
|
59
|
+
const res = runSecurity([
|
|
60
|
+
"add-generic-password",
|
|
61
|
+
"-s",
|
|
62
|
+
SERVICE,
|
|
63
|
+
"-a",
|
|
64
|
+
account,
|
|
65
|
+
"-w",
|
|
66
|
+
token,
|
|
67
|
+
"-U"
|
|
68
|
+
]);
|
|
69
|
+
if (res.code !== 0) {
|
|
70
|
+
throw new KeychainError(`Failed to store token in Keychain: ${res.stderr.trim()}`, res.code);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function getToken(account) {
|
|
74
|
+
const res = runSecurity([
|
|
75
|
+
"find-generic-password",
|
|
76
|
+
"-s",
|
|
77
|
+
SERVICE,
|
|
78
|
+
"-a",
|
|
79
|
+
account,
|
|
80
|
+
"-w"
|
|
81
|
+
]);
|
|
82
|
+
if (res.code !== 0)
|
|
83
|
+
return null;
|
|
84
|
+
return res.stdout.trim() || null;
|
|
85
|
+
}
|
|
86
|
+
function deleteToken(account) {
|
|
87
|
+
const res = runSecurity([
|
|
88
|
+
"delete-generic-password",
|
|
89
|
+
"-s",
|
|
90
|
+
SERVICE,
|
|
91
|
+
"-a",
|
|
92
|
+
account
|
|
93
|
+
]);
|
|
94
|
+
return res.code === 0;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
// src/manager-api.ts
|
|
98
|
+
class ManagerApi {
|
|
99
|
+
baseUrl;
|
|
100
|
+
token;
|
|
101
|
+
constructor(baseUrl, token) {
|
|
102
|
+
this.baseUrl = baseUrl;
|
|
103
|
+
this.token = token;
|
|
104
|
+
}
|
|
105
|
+
headers(extra = {}) {
|
|
106
|
+
return { Authorization: `Bearer ${this.token}`, ...extra };
|
|
107
|
+
}
|
|
108
|
+
async mirrorUp(repoId, body, opts) {
|
|
109
|
+
const params = new URLSearchParams;
|
|
110
|
+
if (opts.force)
|
|
111
|
+
params.set("force", "1");
|
|
112
|
+
if (opts.create) {
|
|
113
|
+
params.set("create", "1");
|
|
114
|
+
params.set("name", opts.create.name);
|
|
115
|
+
if (opts.create.originUrl)
|
|
116
|
+
params.set("originUrl", opts.create.originUrl);
|
|
117
|
+
if (opts.create.branch)
|
|
118
|
+
params.set("branch", opts.create.branch);
|
|
119
|
+
}
|
|
120
|
+
const qs = params.toString() ? `?${params.toString()}` : "";
|
|
121
|
+
const url = `${this.baseUrl}/api/internal/repos/${repoId}/mirror${qs}`;
|
|
122
|
+
const res = await fetch(url, {
|
|
123
|
+
method: "POST",
|
|
124
|
+
headers: {
|
|
125
|
+
...this.headers(),
|
|
126
|
+
"Content-Type": "application/x-tar"
|
|
127
|
+
},
|
|
128
|
+
body,
|
|
129
|
+
duplex: "half"
|
|
130
|
+
});
|
|
131
|
+
if (!res.ok)
|
|
132
|
+
throw new Error(`mirror ${res.status}: ${await res.text()}`);
|
|
133
|
+
return await res.json();
|
|
134
|
+
}
|
|
135
|
+
async mirrorDown(repoId) {
|
|
136
|
+
const res = await fetch(`${this.baseUrl}/api/internal/repos/${repoId}/mirror`, {
|
|
137
|
+
headers: this.headers()
|
|
138
|
+
});
|
|
139
|
+
if (!res.ok)
|
|
140
|
+
throw new Error(`mirror ${res.status}: ${await res.text()}`);
|
|
141
|
+
return res.body;
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// src/mirror.ts
|
|
146
|
+
import { spawnSync as spawnSync3, spawn } from "child_process";
|
|
147
|
+
import { existsSync as existsSync2 } from "fs";
|
|
148
|
+
import * as fsp from "fs/promises";
|
|
149
|
+
import { Readable } from "stream";
|
|
150
|
+
import { join as join2 } from "path";
|
|
151
|
+
import { tmpdir } from "os";
|
|
152
|
+
|
|
153
|
+
// src/local-repo.ts
|
|
154
|
+
import { spawnSync as spawnSync2 } from "child_process";
|
|
155
|
+
function git(cwd, args) {
|
|
156
|
+
const res = spawnSync2("git", args, { cwd, encoding: "utf-8" });
|
|
157
|
+
if (res.status !== 0)
|
|
158
|
+
return null;
|
|
159
|
+
return (res.stdout ?? "").trim();
|
|
160
|
+
}
|
|
161
|
+
function getRepoRoot(cwd) {
|
|
162
|
+
return git(cwd, ["rev-parse", "--show-toplevel"]);
|
|
163
|
+
}
|
|
164
|
+
function getOriginUrl(dir) {
|
|
165
|
+
return git(dir, ["remote", "get-url", "origin"]);
|
|
166
|
+
}
|
|
167
|
+
function getDirtyPaths(dir) {
|
|
168
|
+
const out = git(dir, ["status", "--porcelain", "-z", "--untracked-files=all"]);
|
|
169
|
+
if (!out)
|
|
170
|
+
return new Set;
|
|
171
|
+
const paths = new Set;
|
|
172
|
+
for (const record of out.split("\x00")) {
|
|
173
|
+
if (!record)
|
|
174
|
+
continue;
|
|
175
|
+
const path = record.slice(3);
|
|
176
|
+
if (path)
|
|
177
|
+
paths.add(path);
|
|
178
|
+
}
|
|
179
|
+
return paths;
|
|
180
|
+
}
|
|
181
|
+
function normalizeUrl(url) {
|
|
182
|
+
return url.trim().replace(/\.git$/, "").replace(/^git@([^:]+):/, "ssh://git@$1/").replace(/\/+$/, "").toLowerCase();
|
|
183
|
+
}
|
|
184
|
+
function getBranchName(dir) {
|
|
185
|
+
return git(dir, ["rev-parse", "--abbrev-ref", "HEAD"]);
|
|
186
|
+
}
|
|
187
|
+
function urlsEqual(a, b) {
|
|
188
|
+
if (!a || !b)
|
|
189
|
+
return false;
|
|
190
|
+
return normalizeUrl(a) === normalizeUrl(b);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// src/mirror.ts
|
|
194
|
+
var HARDCODED_EXCLUDES = ["node_modules", "dist", ".next", ".venv", "__pycache__", ".turbo"];
|
|
195
|
+
function getGitignoreExclusions(repoRoot) {
|
|
196
|
+
const res = spawnSync3("git", ["ls-files", "--others", "--ignored", "--exclude-standard", "--directory"], {
|
|
197
|
+
cwd: repoRoot,
|
|
198
|
+
encoding: "utf-8"
|
|
199
|
+
});
|
|
200
|
+
if (res.status !== 0)
|
|
201
|
+
return [];
|
|
202
|
+
return (res.stdout ?? "").split(`
|
|
203
|
+
`).filter((line) => line.length > 0);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
class MirrorAbort extends Error {
|
|
207
|
+
constructor(message) {
|
|
208
|
+
super(message);
|
|
209
|
+
this.name = "MirrorAbort";
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
function prepareMirror(cwd, remotes) {
|
|
213
|
+
const repoRoot = getRepoRoot(cwd);
|
|
214
|
+
if (!repoRoot)
|
|
215
|
+
throw new MirrorAbort("not in a git repository");
|
|
216
|
+
const localOrigin = getOriginUrl(repoRoot);
|
|
217
|
+
if (!localOrigin)
|
|
218
|
+
throw new MirrorAbort("no origin URL found");
|
|
219
|
+
const matched = remotes.filter((r) => urlsEqual(localOrigin, r.originUrl));
|
|
220
|
+
return { repoRoot, localOrigin, matched };
|
|
221
|
+
}
|
|
222
|
+
async function mirrorUp(plan, opts) {
|
|
223
|
+
const tarArgs = ["-c", "-C", plan.repoRoot];
|
|
224
|
+
for (const dir of HARDCODED_EXCLUDES)
|
|
225
|
+
tarArgs.push("--exclude", dir);
|
|
226
|
+
const ignoredPaths = getGitignoreExclusions(plan.repoRoot);
|
|
227
|
+
let excludeFile = null;
|
|
228
|
+
if (ignoredPaths.length > 0) {
|
|
229
|
+
excludeFile = join2(tmpdir(), `ocm-exclude-${Date.now()}-${Math.random().toString(36).slice(2)}.txt`);
|
|
230
|
+
await fsp.writeFile(excludeFile, ignoredPaths.join(`
|
|
231
|
+
`));
|
|
232
|
+
tarArgs.push("--exclude-from", excludeFile);
|
|
233
|
+
}
|
|
234
|
+
tarArgs.push(".");
|
|
235
|
+
const child = spawn("tar", tarArgs, { stdio: ["pipe", "pipe", "pipe"] });
|
|
236
|
+
const stderrChunks = [];
|
|
237
|
+
child.stderr.on("data", (chunk) => stderrChunks.push(chunk));
|
|
238
|
+
const tarExit = new Promise((resolve, reject) => {
|
|
239
|
+
child.on("close", (code) => {
|
|
240
|
+
if (code === 0)
|
|
241
|
+
resolve();
|
|
242
|
+
else {
|
|
243
|
+
const stderr = Buffer.concat(stderrChunks).toString("utf-8").trim();
|
|
244
|
+
reject(new Error(`tar exited with code ${code}${stderr ? `: ${stderr}` : ""}`));
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
child.on("error", reject);
|
|
248
|
+
});
|
|
249
|
+
const body = Readable.toWeb(child.stdout);
|
|
250
|
+
const repoId = opts.create ? 0 : plan.matched[0].repoId;
|
|
251
|
+
try {
|
|
252
|
+
const [result] = await Promise.all([
|
|
253
|
+
opts.api.mirrorUp(repoId, body, {
|
|
254
|
+
force: opts.force,
|
|
255
|
+
create: opts.create
|
|
256
|
+
}),
|
|
257
|
+
tarExit
|
|
258
|
+
]);
|
|
259
|
+
return result;
|
|
260
|
+
} finally {
|
|
261
|
+
if (excludeFile) {
|
|
262
|
+
await fsp.rm(excludeFile, { force: true }).catch(() => {});
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
async function mirrorDown(repoId, repoRoot, api, opts = { force: false }) {
|
|
267
|
+
if (!opts.force && getDirtyPaths(repoRoot).size > 0) {
|
|
268
|
+
throw new MirrorAbort("working tree has uncommitted changes; rerun with --force");
|
|
269
|
+
}
|
|
270
|
+
const staging = `${repoRoot}.ocm-recv-${Date.now()}`;
|
|
271
|
+
await fsp.mkdir(staging, { recursive: true });
|
|
272
|
+
try {
|
|
273
|
+
const tarball = await api.mirrorDown(repoId);
|
|
274
|
+
const child = spawn("tar", ["-x", "-f", "-", "-C", staging], { stdio: ["pipe", "pipe", "pipe"] });
|
|
275
|
+
const stderrChunks = [];
|
|
276
|
+
child.stderr.on("data", (chunk) => stderrChunks.push(chunk));
|
|
277
|
+
const tarDone = new Promise((resolve, reject) => {
|
|
278
|
+
child.on("close", (code) => {
|
|
279
|
+
if (code === 0)
|
|
280
|
+
resolve();
|
|
281
|
+
else {
|
|
282
|
+
const stderr = Buffer.concat(stderrChunks).toString("utf-8").trim();
|
|
283
|
+
reject(new Error(`tar exited with code ${code}${stderr ? `: ${stderr}` : ""}`));
|
|
284
|
+
}
|
|
285
|
+
});
|
|
286
|
+
child.on("error", reject);
|
|
287
|
+
});
|
|
288
|
+
const stdinWritable = Readable.fromWeb(tarball);
|
|
289
|
+
stdinWritable.pipe(child.stdin);
|
|
290
|
+
await tarDone;
|
|
291
|
+
const backupDir = `${repoRoot}.ocm-backup-${Date.now()}`;
|
|
292
|
+
await fsp.mkdir(backupDir, { recursive: true });
|
|
293
|
+
if (existsSync2(repoRoot)) {
|
|
294
|
+
const entries = await fsp.readdir(repoRoot);
|
|
295
|
+
for (const entry of entries) {
|
|
296
|
+
await fsp.rename(join2(repoRoot, entry), join2(backupDir, entry));
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
try {
|
|
300
|
+
const stagingEntries = await fsp.readdir(staging);
|
|
301
|
+
for (const entry of stagingEntries) {
|
|
302
|
+
await fsp.rename(join2(staging, entry), join2(repoRoot, entry));
|
|
303
|
+
}
|
|
304
|
+
await fsp.rm(backupDir, { recursive: true, force: true }).catch(() => {});
|
|
305
|
+
await fsp.rm(staging, { recursive: true, force: true }).catch(() => {});
|
|
306
|
+
} catch (swapError) {
|
|
307
|
+
const backupEntries = await fsp.readdir(backupDir).catch(() => []);
|
|
308
|
+
for (const entry of backupEntries) {
|
|
309
|
+
await fsp.rename(join2(backupDir, entry), join2(repoRoot, entry)).catch(() => {});
|
|
310
|
+
}
|
|
311
|
+
await fsp.rm(backupDir, { recursive: true, force: true }).catch(() => {});
|
|
312
|
+
throw swapError;
|
|
313
|
+
}
|
|
314
|
+
} catch (error) {
|
|
315
|
+
await fsp.rm(staging, { recursive: true, force: true }).catch(() => {});
|
|
316
|
+
throw error;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
// src/resolve-target.ts
|
|
321
|
+
function resolveTarget(input) {
|
|
322
|
+
const repoRoot = getRepoRoot(input.cwd);
|
|
323
|
+
const localOrigin = repoRoot ? getOriginUrl(repoRoot) : null;
|
|
324
|
+
if (repoRoot && localOrigin) {
|
|
325
|
+
const matches = input.repos.filter((r) => urlsEqual(localOrigin, r.originUrl));
|
|
326
|
+
if (matches.length === 1) {
|
|
327
|
+
return { kind: "cwd-match", repo: matches[0], repoRoot };
|
|
328
|
+
}
|
|
329
|
+
if (matches.length > 1) {
|
|
330
|
+
return { kind: "cwd-ambiguous", matches, localOrigin, repoRoot };
|
|
331
|
+
}
|
|
332
|
+
return { kind: "local", reason: "no-match", repoRoot };
|
|
333
|
+
}
|
|
334
|
+
if (input.last) {
|
|
335
|
+
return { kind: "last", repo: toTarget(input.last) };
|
|
336
|
+
}
|
|
337
|
+
return { kind: "local", reason: "no-target", repoRoot };
|
|
338
|
+
}
|
|
339
|
+
function toTarget(last) {
|
|
340
|
+
return {
|
|
341
|
+
repoId: last.repoId,
|
|
342
|
+
name: last.name,
|
|
343
|
+
branch: last.branch,
|
|
344
|
+
directory: last.directory
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// bin/ocm.ts
|
|
349
|
+
var USAGE = `ocm - OpenCode Manager workspace launcher
|
|
350
|
+
|
|
351
|
+
Usage:
|
|
352
|
+
ocm Attach to the Manager repo matching $PWD's git origin,
|
|
353
|
+
fall back to the last selected repo, or launch local
|
|
354
|
+
opencode when no Manager target applies
|
|
355
|
+
ocm login <url> [token] Save manager URL + token (token via stdin if omitted)
|
|
356
|
+
ocm logout Forget saved token (Keychain) and state
|
|
357
|
+
ocm status Show current manager URL, repo, and whether token is set
|
|
358
|
+
ocm list List ready repos from the manager
|
|
359
|
+
ocm use <repoId|name> Attach to a specific repo and remember it as last
|
|
360
|
+
ocm push [--force] [--create] [--yes] Mirror $PWD to the matching Manager repo (or create one)
|
|
361
|
+
ocm pull [--force] Mirror the matching Manager repo over $PWD
|
|
362
|
+
ocm --help Show this help
|
|
363
|
+
`;
|
|
364
|
+
function die(msg, code = 1) {
|
|
365
|
+
process.stderr.write(`ocm: ${msg}
|
|
366
|
+
`);
|
|
367
|
+
process.exit(code);
|
|
368
|
+
}
|
|
369
|
+
function info(msg) {
|
|
370
|
+
process.stdout.write(`${msg}
|
|
371
|
+
`);
|
|
372
|
+
}
|
|
373
|
+
function requireState() {
|
|
374
|
+
const state = readState();
|
|
375
|
+
if (!state || !state.managerUrl) {
|
|
376
|
+
die(`no manager configured. Run \`ocm login <url>\` first.`);
|
|
377
|
+
}
|
|
378
|
+
return state;
|
|
379
|
+
}
|
|
380
|
+
function requireToken(state) {
|
|
381
|
+
const token = getToken(state.managerUrl);
|
|
382
|
+
if (!token) {
|
|
383
|
+
die(`no token in Keychain for ${state.managerUrl}. Run \`ocm login ${state.managerUrl}\`.`);
|
|
384
|
+
}
|
|
385
|
+
return token;
|
|
386
|
+
}
|
|
387
|
+
async function fetchRepos(managerUrl, token) {
|
|
388
|
+
const res = await fetch(`${managerUrl}/api/internal/opencode-workspaces`, {
|
|
389
|
+
headers: { Authorization: `Bearer ${token}` }
|
|
390
|
+
});
|
|
391
|
+
if (!res.ok) {
|
|
392
|
+
throw new Error(`manager responded ${res.status} ${res.statusText}`);
|
|
393
|
+
}
|
|
394
|
+
const data = await res.json();
|
|
395
|
+
return data.workspaces;
|
|
396
|
+
}
|
|
397
|
+
function attach(managerUrl, token, repo) {
|
|
398
|
+
const proxyUrl = `${managerUrl}/api/opencode-proxy`;
|
|
399
|
+
const args = [
|
|
400
|
+
"attach",
|
|
401
|
+
proxyUrl,
|
|
402
|
+
"--dir",
|
|
403
|
+
repo.directory,
|
|
404
|
+
"--password",
|
|
405
|
+
token,
|
|
406
|
+
"--username",
|
|
407
|
+
"opencode"
|
|
408
|
+
];
|
|
409
|
+
const child = spawn2("opencode", args, { stdio: "inherit" });
|
|
410
|
+
child.on("close", (code) => process.exit(code ?? 0));
|
|
411
|
+
child.on("error", (err) => die(`failed to spawn opencode: ${err.message}`));
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
function findRepo(repos, needle) {
|
|
415
|
+
if (typeof needle === "number") {
|
|
416
|
+
return repos.find((r) => r.repoId === needle);
|
|
417
|
+
}
|
|
418
|
+
const asNum = Number(needle);
|
|
419
|
+
if (!Number.isNaN(asNum)) {
|
|
420
|
+
const byId = repos.find((r) => r.repoId === asNum);
|
|
421
|
+
if (byId)
|
|
422
|
+
return byId;
|
|
423
|
+
}
|
|
424
|
+
return repos.find((r) => r.name === needle) ?? repos.find((r) => r.name.toLowerCase() === needle.toLowerCase());
|
|
425
|
+
}
|
|
426
|
+
async function cmdLogin(args) {
|
|
427
|
+
const url = args[0];
|
|
428
|
+
if (!url)
|
|
429
|
+
die("usage: ocm login <url> [token]");
|
|
430
|
+
const normalisedUrl = url.replace(/\/+$/, "");
|
|
431
|
+
let token = args[1];
|
|
432
|
+
if (!token) {
|
|
433
|
+
if (process.stdin.isTTY) {
|
|
434
|
+
process.stderr.write("Paste token (input hidden): ");
|
|
435
|
+
const res = spawnSync4("bash", ["-c", 'read -s LINE && printf "%s" "$LINE"'], {
|
|
436
|
+
stdio: ["inherit", "pipe", "inherit"],
|
|
437
|
+
encoding: "utf-8"
|
|
438
|
+
});
|
|
439
|
+
process.stderr.write(`
|
|
440
|
+
`);
|
|
441
|
+
token = (res.stdout ?? "").trim();
|
|
442
|
+
} else {
|
|
443
|
+
token = await new Promise((resolve) => {
|
|
444
|
+
const chunks = [];
|
|
445
|
+
process.stdin.on("data", (c) => chunks.push(c));
|
|
446
|
+
process.stdin.on("end", () => resolve(Buffer.concat(chunks).toString("utf-8").trim()));
|
|
447
|
+
});
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
if (!token)
|
|
451
|
+
die("no token provided");
|
|
452
|
+
try {
|
|
453
|
+
setToken(normalisedUrl, token);
|
|
454
|
+
} catch (err) {
|
|
455
|
+
if (err instanceof KeychainError)
|
|
456
|
+
die(`Keychain error: ${err.message}`);
|
|
457
|
+
throw err;
|
|
458
|
+
}
|
|
459
|
+
const existing = readState();
|
|
460
|
+
writeState({
|
|
461
|
+
...existing,
|
|
462
|
+
managerUrl: normalisedUrl
|
|
463
|
+
});
|
|
464
|
+
info(`Saved token for ${normalisedUrl} in Keychain.`);
|
|
465
|
+
info(`State file: ${getStatePath()}`);
|
|
466
|
+
}
|
|
467
|
+
async function cmdLogout() {
|
|
468
|
+
const state = readState();
|
|
469
|
+
if (!state || !state.managerUrl) {
|
|
470
|
+
info("Nothing to log out from.");
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
const deleted = deleteToken(state.managerUrl);
|
|
474
|
+
clearState();
|
|
475
|
+
info(deleted ? `Removed Keychain entry for ${state.managerUrl}.` : `No Keychain entry found.`);
|
|
476
|
+
info("State cleared.");
|
|
477
|
+
}
|
|
478
|
+
async function cmdStatus() {
|
|
479
|
+
const state = readState();
|
|
480
|
+
if (!state) {
|
|
481
|
+
info("no state. run: ocm login <url>");
|
|
482
|
+
return;
|
|
483
|
+
}
|
|
484
|
+
info(`manager url: ${state.managerUrl}`);
|
|
485
|
+
info(`token in kc: ${getToken(state.managerUrl) ? "yes" : "no"}`);
|
|
486
|
+
if (state.lastRepoId !== undefined) {
|
|
487
|
+
info(`last repo: ${state.lastRepoName} (id=${state.lastRepoId}, branch=${state.lastRepoBranch ?? "n/a"})`);
|
|
488
|
+
info(`last repo dir: ${state.lastRepoDir}`);
|
|
489
|
+
} else {
|
|
490
|
+
info("last repo: (none)");
|
|
491
|
+
}
|
|
492
|
+
info(`state file: ${getStatePath()}`);
|
|
493
|
+
}
|
|
494
|
+
async function cmdList() {
|
|
495
|
+
const state = requireState();
|
|
496
|
+
const token = requireToken(state);
|
|
497
|
+
const repos = await fetchRepos(state.managerUrl, token);
|
|
498
|
+
if (repos.length === 0) {
|
|
499
|
+
info("No ready repos.");
|
|
500
|
+
return;
|
|
501
|
+
}
|
|
502
|
+
const idWidth = Math.max(...repos.map((r) => String(r.repoId).length));
|
|
503
|
+
const nameWidth = Math.max(...repos.map((r) => r.name.length));
|
|
504
|
+
for (const r of repos) {
|
|
505
|
+
const id = String(r.repoId).padStart(idWidth);
|
|
506
|
+
const name = r.name.padEnd(nameWidth);
|
|
507
|
+
const branch = r.branch ? ` (${r.branch})` : "";
|
|
508
|
+
info(`${id} ${name} ${r.cloneStatus}${branch}`);
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
async function cmdUse(args) {
|
|
512
|
+
const needle = args[0];
|
|
513
|
+
if (!needle)
|
|
514
|
+
die("usage: ocm use <repoId|name>");
|
|
515
|
+
const state = requireState();
|
|
516
|
+
const token = requireToken(state);
|
|
517
|
+
const repos = await fetchRepos(state.managerUrl, token);
|
|
518
|
+
const repo = findRepo(repos, needle);
|
|
519
|
+
if (!repo)
|
|
520
|
+
die(`repo not found: ${needle}`);
|
|
521
|
+
writeState({
|
|
522
|
+
...state,
|
|
523
|
+
lastRepoId: repo.repoId,
|
|
524
|
+
lastRepoName: repo.name,
|
|
525
|
+
lastRepoDir: repo.directory,
|
|
526
|
+
lastRepoBranch: repo.branch
|
|
527
|
+
});
|
|
528
|
+
attach(state.managerUrl, token, repo);
|
|
529
|
+
}
|
|
530
|
+
async function cmdDefault() {
|
|
531
|
+
const state = requireState();
|
|
532
|
+
const token = requireToken(state);
|
|
533
|
+
const last = state.lastRepoId !== undefined && state.lastRepoDir ? {
|
|
534
|
+
repoId: state.lastRepoId,
|
|
535
|
+
name: state.lastRepoName ?? `repo-${state.lastRepoId}`,
|
|
536
|
+
directory: state.lastRepoDir,
|
|
537
|
+
branch: state.lastRepoBranch ?? null
|
|
538
|
+
} : undefined;
|
|
539
|
+
const repos = await fetchRepos(state.managerUrl, token);
|
|
540
|
+
const result = resolveTarget({ cwd: process.cwd(), repos, last });
|
|
541
|
+
switch (result.kind) {
|
|
542
|
+
case "cwd-match": {
|
|
543
|
+
const repo = result.repo;
|
|
544
|
+
info(`attaching to ${repo.name} (matched $PWD origin)`);
|
|
545
|
+
writeState({
|
|
546
|
+
...state,
|
|
547
|
+
lastRepoId: repo.repoId,
|
|
548
|
+
lastRepoName: repo.name,
|
|
549
|
+
lastRepoDir: repo.directory,
|
|
550
|
+
lastRepoBranch: repo.branch
|
|
551
|
+
});
|
|
552
|
+
attach(state.managerUrl, token, toManagerRepo(repo));
|
|
553
|
+
return;
|
|
554
|
+
}
|
|
555
|
+
case "last":
|
|
556
|
+
attach(state.managerUrl, token, toManagerRepo(result.repo));
|
|
557
|
+
return;
|
|
558
|
+
case "cwd-ambiguous": {
|
|
559
|
+
const names = result.matches.map((r) => `${r.name} (id=${r.repoId})`).join(", ");
|
|
560
|
+
die(`multiple Manager repos match origin ${result.localOrigin}: ${names}; disambiguate with \`ocm use <repoId>\``);
|
|
561
|
+
}
|
|
562
|
+
case "local":
|
|
563
|
+
runLocalOpencode(result.reason);
|
|
564
|
+
return;
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
function runLocalOpencode(reason) {
|
|
568
|
+
const message = reason === "no-match" ? "no Manager repo matches $PWD; launching local opencode" : "no last repo; launching local opencode";
|
|
569
|
+
process.stderr.write(`ocm: ${message}
|
|
570
|
+
`);
|
|
571
|
+
const child = spawn2("opencode", [], { stdio: "inherit" });
|
|
572
|
+
child.on("close", (code) => process.exit(code ?? 0));
|
|
573
|
+
child.on("error", (err) => die(`failed to spawn opencode: ${err.message}`));
|
|
574
|
+
return;
|
|
575
|
+
}
|
|
576
|
+
function toManagerRepo(repo) {
|
|
577
|
+
return {
|
|
578
|
+
repoId: repo.repoId,
|
|
579
|
+
name: repo.name,
|
|
580
|
+
branch: repo.branch,
|
|
581
|
+
cloneStatus: "ready",
|
|
582
|
+
directory: repo.directory,
|
|
583
|
+
extra: { repoId: repo.repoId, localPath: "", fullPath: repo.directory }
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
async function cmdPush(args) {
|
|
587
|
+
let force = false;
|
|
588
|
+
let create = false;
|
|
589
|
+
let yes = false;
|
|
590
|
+
for (const arg of args) {
|
|
591
|
+
if (arg === "--force")
|
|
592
|
+
force = true;
|
|
593
|
+
else if (arg === "--create")
|
|
594
|
+
create = true;
|
|
595
|
+
else if (arg === "--yes")
|
|
596
|
+
yes = true;
|
|
597
|
+
}
|
|
598
|
+
const state = requireState();
|
|
599
|
+
const token = requireToken(state);
|
|
600
|
+
const api = new ManagerApi(state.managerUrl, token);
|
|
601
|
+
const repos = await fetchRepos(state.managerUrl, token);
|
|
602
|
+
const remotes = repos.map((r) => ({
|
|
603
|
+
repoId: r.repoId,
|
|
604
|
+
name: r.name,
|
|
605
|
+
originUrl: r.originUrl ?? null,
|
|
606
|
+
branch: r.branch
|
|
607
|
+
}));
|
|
608
|
+
const plan = prepareMirror(process.cwd(), remotes);
|
|
609
|
+
if (plan.matched.length === 0) {
|
|
610
|
+
if (!create) {
|
|
611
|
+
die(`no matching Manager repo for origin ${plan.localOrigin}. Re-run with --create to create one.`);
|
|
612
|
+
}
|
|
613
|
+
const name = basename(plan.repoRoot);
|
|
614
|
+
const branch = getBranchName(plan.repoRoot);
|
|
615
|
+
if (process.stdin.isTTY && !yes) {
|
|
616
|
+
process.stderr.write(`Create Manager repo "${name}" by uploading ${plan.repoRoot} (origin: ${plan.localOrigin})? [y/N] `);
|
|
617
|
+
const res = spawnSync4("bash", ["-c", 'read LINE && printf "%s" "$LINE"'], {
|
|
618
|
+
stdio: ["inherit", "pipe", "inherit"],
|
|
619
|
+
encoding: "utf-8"
|
|
620
|
+
});
|
|
621
|
+
const answer = (res.stdout ?? "").trim().toLowerCase();
|
|
622
|
+
if (answer !== "y" && answer !== "yes") {
|
|
623
|
+
die("aborted");
|
|
624
|
+
}
|
|
625
|
+
} else if (!process.stdin.isTTY && !yes) {
|
|
626
|
+
die("stdin is not a TTY; pass --yes to confirm creation");
|
|
627
|
+
}
|
|
628
|
+
const result = await mirrorUp(plan, {
|
|
629
|
+
api,
|
|
630
|
+
force,
|
|
631
|
+
create: { name, originUrl: plan.localOrigin, branch }
|
|
632
|
+
});
|
|
633
|
+
info(`pushed ${plan.repoRoot} -> ${result.created ? "created" : "updated"} (repoId=${result.repoId}, branch=${result.branch})`);
|
|
634
|
+
} else if (plan.matched.length === 1) {
|
|
635
|
+
const result = await mirrorUp(plan, { api, force });
|
|
636
|
+
info(`pushed ${plan.repoRoot} -> ${plan.matched[0].name} (repoId=${result.repoId}, branch=${result.branch})`);
|
|
637
|
+
} else {
|
|
638
|
+
const names = plan.matched.map((r) => `${r.name} (id=${r.repoId})`).join(", ");
|
|
639
|
+
die(`multiple Manager repos match origin ${plan.localOrigin}: ${names}; disambiguate with \`ocm push <repoId>\``);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
async function cmdPull(args) {
|
|
643
|
+
let force = false;
|
|
644
|
+
for (const arg of args) {
|
|
645
|
+
if (arg === "--force")
|
|
646
|
+
force = true;
|
|
647
|
+
}
|
|
648
|
+
const state = requireState();
|
|
649
|
+
const token = requireToken(state);
|
|
650
|
+
const api = new ManagerApi(state.managerUrl, token);
|
|
651
|
+
const repos = await fetchRepos(state.managerUrl, token);
|
|
652
|
+
const remotes = repos.map((r) => ({
|
|
653
|
+
repoId: r.repoId,
|
|
654
|
+
name: r.name,
|
|
655
|
+
originUrl: r.originUrl ?? null,
|
|
656
|
+
branch: r.branch
|
|
657
|
+
}));
|
|
658
|
+
const plan = prepareMirror(process.cwd(), remotes);
|
|
659
|
+
if (plan.matched.length === 0) {
|
|
660
|
+
die(`no matching Manager repo for origin ${plan.localOrigin}.`);
|
|
661
|
+
}
|
|
662
|
+
if (plan.matched.length > 1) {
|
|
663
|
+
const names = plan.matched.map((r) => `${r.name} (id=${r.repoId})`).join(", ");
|
|
664
|
+
die(`multiple Manager repos match origin ${plan.localOrigin}: ${names}; disambiguate with \`ocm pull <repoId>\``);
|
|
665
|
+
}
|
|
666
|
+
await mirrorDown(plan.matched[0].repoId, plan.repoRoot, api, { force });
|
|
667
|
+
info(`pulled ${plan.matched[0].name} -> ${plan.repoRoot}`);
|
|
668
|
+
}
|
|
669
|
+
async function main() {
|
|
670
|
+
const [, , cmd, ...rest] = process.argv;
|
|
671
|
+
if (cmd === "--help" || cmd === "-h" || cmd === "help") {
|
|
672
|
+
process.stdout.write(USAGE);
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
try {
|
|
676
|
+
switch (cmd) {
|
|
677
|
+
case undefined:
|
|
678
|
+
await cmdDefault();
|
|
679
|
+
break;
|
|
680
|
+
case "login":
|
|
681
|
+
await cmdLogin(rest);
|
|
682
|
+
break;
|
|
683
|
+
case "logout":
|
|
684
|
+
await cmdLogout();
|
|
685
|
+
break;
|
|
686
|
+
case "status":
|
|
687
|
+
await cmdStatus();
|
|
688
|
+
break;
|
|
689
|
+
case "list":
|
|
690
|
+
case "ls":
|
|
691
|
+
await cmdList();
|
|
692
|
+
break;
|
|
693
|
+
case "use":
|
|
694
|
+
case "attach":
|
|
695
|
+
await cmdUse(rest);
|
|
696
|
+
break;
|
|
697
|
+
case "push":
|
|
698
|
+
await cmdPush(rest);
|
|
699
|
+
break;
|
|
700
|
+
case "pull":
|
|
701
|
+
await cmdPull(rest);
|
|
702
|
+
break;
|
|
703
|
+
default:
|
|
704
|
+
die(`unknown command: ${cmd}. run \`ocm --help\``);
|
|
705
|
+
}
|
|
706
|
+
} catch (err) {
|
|
707
|
+
die(err instanceof Error ? err.message : String(err));
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
var entryUrl = process.argv[1] ? `file://${process.argv[1]}` : "";
|
|
711
|
+
if (entryUrl === import.meta.url || process.argv[1]?.endsWith("/ocm.js") || process.argv[1]?.endsWith("/ocm")) {
|
|
712
|
+
main();
|
|
713
|
+
}
|
|
714
|
+
export {
|
|
715
|
+
cmdPush
|
|
716
|
+
};
|
package/dist/plugin.js
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
// src/plugin.ts
|
|
2
|
+
import { mkdirSync, symlinkSync, lstatSync, readlinkSync, unlinkSync, existsSync, chmodSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join, resolve } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
var PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
|
7
|
+
var OCM_TARGET = join(PACKAGE_ROOT, "dist", "ocm.js");
|
|
8
|
+
var BIN_DIR = join(homedir(), ".local", "bin");
|
|
9
|
+
var BIN_LINK = join(BIN_DIR, "ocm");
|
|
10
|
+
function ensureSymlink() {
|
|
11
|
+
if (!existsSync(OCM_TARGET)) {
|
|
12
|
+
return { installed: false, message: `ocm-cli: missing ${OCM_TARGET}, skipping bin install` };
|
|
13
|
+
}
|
|
14
|
+
try {
|
|
15
|
+
chmodSync(OCM_TARGET, 493);
|
|
16
|
+
} catch {}
|
|
17
|
+
try {
|
|
18
|
+
mkdirSync(BIN_DIR, { recursive: true });
|
|
19
|
+
} catch (err) {
|
|
20
|
+
return { installed: false, message: `ocm-cli: cannot create ${BIN_DIR}: ${err.message}` };
|
|
21
|
+
}
|
|
22
|
+
try {
|
|
23
|
+
const stat = lstatSync(BIN_LINK);
|
|
24
|
+
if (stat.isSymbolicLink()) {
|
|
25
|
+
if (readlinkSync(BIN_LINK) === OCM_TARGET) {
|
|
26
|
+
return { installed: false };
|
|
27
|
+
}
|
|
28
|
+
unlinkSync(BIN_LINK);
|
|
29
|
+
} else {
|
|
30
|
+
return { installed: false, message: `ocm-cli: ${BIN_LINK} exists and is not a symlink; leaving alone` };
|
|
31
|
+
}
|
|
32
|
+
} catch {}
|
|
33
|
+
try {
|
|
34
|
+
symlinkSync(OCM_TARGET, BIN_LINK);
|
|
35
|
+
} catch (err) {
|
|
36
|
+
return { installed: false, message: `ocm-cli: failed to symlink ${BIN_LINK}: ${err.message}` };
|
|
37
|
+
}
|
|
38
|
+
const onPath = (process.env.PATH ?? "").split(":").includes(BIN_DIR);
|
|
39
|
+
const pathHint = onPath ? "" : ` (add "${BIN_DIR}" to your PATH to run \`ocm\`)`;
|
|
40
|
+
return { installed: true, message: `ocm-cli: installed \`ocm\` at ${BIN_LINK}${pathHint}` };
|
|
41
|
+
}
|
|
42
|
+
var result = ensureSymlink();
|
|
43
|
+
if (result.message) {
|
|
44
|
+
process.stderr.write(`${result.message}
|
|
45
|
+
`);
|
|
46
|
+
}
|
|
47
|
+
var plugin = async () => ({});
|
|
48
|
+
var plugin_default = plugin;
|
|
49
|
+
export {
|
|
50
|
+
plugin_default as default
|
|
51
|
+
};
|
package/package.json
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@opencode-manager/ocm-cli",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "OpenCode Manager CLI: attach a local OpenCode TUI to a Manager-hosted repo.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/chriswritescode-dev/opencode-manager.git",
|
|
9
|
+
"directory": "ocm-cli"
|
|
10
|
+
},
|
|
11
|
+
"type": "module",
|
|
12
|
+
"main": "./dist/plugin.js",
|
|
13
|
+
"exports": {
|
|
14
|
+
".": {
|
|
15
|
+
"import": "./dist/plugin.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"bin": {
|
|
19
|
+
"ocm": "dist/ocm.js"
|
|
20
|
+
},
|
|
21
|
+
"files": [
|
|
22
|
+
"dist",
|
|
23
|
+
"README.md"
|
|
24
|
+
],
|
|
25
|
+
"dependencies": {},
|
|
26
|
+
"devDependencies": {
|
|
27
|
+
"@types/node": "^22.0.0",
|
|
28
|
+
"typescript": "^5.5.0",
|
|
29
|
+
"vitest": "^3.1.0"
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "bun scripts/build.ts",
|
|
33
|
+
"postinstall": "node scripts/postinstall.mjs || true",
|
|
34
|
+
"typecheck": "tsc --noEmit",
|
|
35
|
+
"test": "bun scripts/build.ts && vitest run",
|
|
36
|
+
"test:watch": "vitest"
|
|
37
|
+
}
|
|
38
|
+
}
|