@uselemma/opencode 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.
@@ -0,0 +1,376 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/setup.ts
4
+ import { spawn } from "node:child_process";
5
+ import { randomUUID as randomUUID2 } from "node:crypto";
6
+ import {
7
+ chmod as chmod2,
8
+ lstat,
9
+ mkdir as mkdir2,
10
+ readFile as readFile2,
11
+ rename as rename2,
12
+ unlink as unlink2,
13
+ writeFile as writeFile2
14
+ } from "node:fs/promises";
15
+ import { dirname as dirname2, join as join2, resolve as resolve2, win32 } from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+
18
+ // src/storage.ts
19
+ import { randomUUID } from "node:crypto";
20
+ import { existsSync, readFileSync } from "node:fs";
21
+ import {
22
+ chmod,
23
+ mkdir,
24
+ readFile,
25
+ rename,
26
+ unlink,
27
+ writeFile
28
+ } from "node:fs/promises";
29
+ import { homedir } from "node:os";
30
+ import { dirname, join, resolve } from "node:path";
31
+ var LEMMA_OPENCODE_CREDENTIALS_HELP = "Lemma OpenCode credentials are missing or invalid. Run `pnpm dlx @uselemma/opencode setup` to connect or rotate the scoped credential.";
32
+ function isRecord(value) {
33
+ return typeof value === "object" && value !== null && !Array.isArray(value);
34
+ }
35
+ function isCredentials(value) {
36
+ return isRecord(value) && value.version === 1 && typeof value.apiUrl === "string" && value.apiUrl.length > 0 && typeof value.projectId === "string" && value.projectId.length > 0 && typeof value.credentialId === "string" && value.credentialId.length > 0 && typeof value.accessToken === "string" && value.accessToken.length > 0;
37
+ }
38
+ function resolveConfigDir(options = {}) {
39
+ if (options.configDir) return resolve(options.configDir);
40
+ const env = options.env ?? process.env;
41
+ const configured = env.OPENCODE_CONFIG_DIR?.trim();
42
+ if (configured) return resolve(configured);
43
+ const home = options.homeDir ?? homedir();
44
+ const xdgConfigHome = env.XDG_CONFIG_HOME?.trim();
45
+ return xdgConfigHome ? join(resolve(xdgConfigHome), "opencode") : join(resolve(home), ".config", "opencode");
46
+ }
47
+ function defaultDataDir(options) {
48
+ return join(resolveConfigDir(options), "lemma");
49
+ }
50
+ function dataDirLocationPath(options) {
51
+ return join(defaultDataDir(options), "data-dir-location.json");
52
+ }
53
+ function resolveDataDir(options = {}) {
54
+ if (options.dataDir) return resolve(options.dataDir);
55
+ const env = options.env ?? process.env;
56
+ const configured = env.LEMMA_OPENCODE_DATA_DIR?.trim();
57
+ if (configured) return resolve(configured);
58
+ const fallback = defaultDataDir(options);
59
+ try {
60
+ const value = JSON.parse(
61
+ readFileSync(dataDirLocationPath(options), "utf8")
62
+ );
63
+ if (isRecord(value) && value.version === 1 && typeof value.dataDir === "string" && value.dataDir.trim().length > 0) {
64
+ return resolve(value.dataDir);
65
+ }
66
+ } catch (error) {
67
+ if (error.code !== "ENOENT") throw error;
68
+ }
69
+ return fallback;
70
+ }
71
+ function credentialsPath(options = {}) {
72
+ return join(resolveDataDir(options), "credentials.json");
73
+ }
74
+ function pluginPath(options = {}) {
75
+ return join(resolveConfigDir(options), "plugins", "uselemma-opencode.js");
76
+ }
77
+ async function writeSecureJson(path, value) {
78
+ await mkdir(dirname(path), { recursive: true, mode: 448 });
79
+ if (process.platform !== "win32") await chmod(dirname(path), 448);
80
+ const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
81
+ await writeFile(temporaryPath, `${JSON.stringify(value)}
82
+ `, {
83
+ encoding: "utf8",
84
+ mode: 384,
85
+ flag: "wx"
86
+ });
87
+ if (process.platform !== "win32") await chmod(temporaryPath, 384);
88
+ await rename(temporaryPath, path);
89
+ if (process.platform !== "win32") await chmod(path, 384);
90
+ }
91
+ async function writeCredentials(credentials, options = {}) {
92
+ if (!isCredentials(credentials)) {
93
+ throw new Error(LEMMA_OPENCODE_CREDENTIALS_HELP);
94
+ }
95
+ await writeSecureJson(credentialsPath(options), credentials);
96
+ }
97
+ async function writeDataDirLocation(dataDir, options = {}) {
98
+ const absolute = resolve(dataDir);
99
+ const fallback = defaultDataDir(options);
100
+ const locationPath = dataDirLocationPath(options);
101
+ if (absolute === fallback) {
102
+ await unlink(locationPath).catch((error) => {
103
+ if (error.code !== "ENOENT") throw error;
104
+ });
105
+ return;
106
+ }
107
+ await writeSecureJson(locationPath, { version: 1, dataDir: absolute });
108
+ }
109
+
110
+ // src/setup.ts
111
+ var DEFAULT_API_URL = "https://api.uselemma.ai";
112
+ var MANAGED_PLUGIN_MARKER = "// @uselemma/opencode managed plugin";
113
+ function isRecord2(value) {
114
+ return typeof value === "object" && value !== null && !Array.isArray(value);
115
+ }
116
+ function normalizedWebUrl(value, label) {
117
+ const url = new URL(value);
118
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && (url.hostname === "localhost" || url.hostname === "127.0.0.1"))) {
119
+ throw new Error(`${label} must use HTTPS (or localhost HTTP)`);
120
+ }
121
+ return url.toString().replace(/\/$/, "");
122
+ }
123
+ function normalizedApiUrl(value) {
124
+ return normalizedWebUrl(value, "Lemma API URL");
125
+ }
126
+ async function jsonResponse(response) {
127
+ const body = await response.json().catch(() => null);
128
+ if (!response.ok) {
129
+ const detail = isRecord2(body) && typeof body.detail === "string" ? body.detail : `HTTP ${response.status}`;
130
+ throw new Error(detail);
131
+ }
132
+ return body;
133
+ }
134
+ async function startDeviceAuthorization(apiUrl, fetchImplementation) {
135
+ const body = await jsonResponse(
136
+ await fetchImplementation(
137
+ `${apiUrl}/coding-harness/device-authorizations`,
138
+ {
139
+ method: "POST",
140
+ headers: { "content-type": "application/json" },
141
+ body: JSON.stringify({ harness: "opencode" })
142
+ }
143
+ )
144
+ );
145
+ if (!isRecord2(body) || typeof body.device_code !== "string" || typeof body.user_code !== "string" || typeof body.verification_uri_complete !== "string" || typeof body.expires_in !== "number" || typeof body.interval !== "number") {
146
+ throw new Error("Lemma returned an invalid OpenCode device authorization");
147
+ }
148
+ return {
149
+ deviceCode: body.device_code,
150
+ userCode: body.user_code,
151
+ verificationUriComplete: normalizedWebUrl(
152
+ body.verification_uri_complete,
153
+ "Lemma verification URL"
154
+ ),
155
+ expiresIn: body.expires_in,
156
+ interval: body.interval
157
+ };
158
+ }
159
+ async function pollDeviceAuthorization(apiUrl, deviceCode, fetchImplementation) {
160
+ const response = await fetchImplementation(
161
+ `${apiUrl}/coding-harness/device-authorizations/token`,
162
+ {
163
+ method: "POST",
164
+ headers: { "content-type": "application/json" },
165
+ body: JSON.stringify({ device_code: deviceCode })
166
+ }
167
+ );
168
+ const body = await response.json().catch(() => null);
169
+ if (!isRecord2(body) || typeof body.status !== "string") {
170
+ throw new Error(`Lemma OpenCode login failed with HTTP ${response.status}`);
171
+ }
172
+ switch (body.status) {
173
+ case "authorization_pending":
174
+ case "slow_down":
175
+ return {
176
+ status: body.status,
177
+ interval: typeof body.interval === "number" ? body.interval : 5
178
+ };
179
+ case "expired_token":
180
+ case "access_denied":
181
+ return { status: body.status };
182
+ case "approved":
183
+ if (typeof body.access_token !== "string" || typeof body.credential_id !== "string" || typeof body.project_id !== "string") {
184
+ throw new Error("Lemma returned an invalid OpenCode scoped credential");
185
+ }
186
+ return {
187
+ status: "approved",
188
+ accessToken: body.access_token,
189
+ credentialId: body.credential_id,
190
+ projectId: body.project_id
191
+ };
192
+ default:
193
+ throw new Error(
194
+ "Lemma returned an unknown OpenCode authorization status"
195
+ );
196
+ }
197
+ }
198
+ async function launchBrowser(url) {
199
+ const command = browserLaunchCommand(url);
200
+ await new Promise((resolvePromise, reject) => {
201
+ const child = spawn(command.file, command.args, {
202
+ detached: true,
203
+ stdio: "ignore"
204
+ });
205
+ child.once("error", reject);
206
+ child.once("spawn", () => {
207
+ child.unref();
208
+ resolvePromise();
209
+ });
210
+ });
211
+ }
212
+ function browserLaunchCommand(url, platform = process.platform, env = process.env) {
213
+ if (platform === "darwin") return { file: "/usr/bin/open", args: [url] };
214
+ if (platform === "win32") {
215
+ const systemRoot = env.SystemRoot ?? env.SYSTEMROOT ?? env.windir ?? env.WINDIR;
216
+ const normalizedSystemRoot = systemRoot && win32.normalize(systemRoot);
217
+ if (!normalizedSystemRoot || !/^[A-Za-z]:\\Windows$/i.test(normalizedSystemRoot)) {
218
+ throw new Error(
219
+ "Lemma could not resolve the trusted Windows browser launcher"
220
+ );
221
+ }
222
+ return {
223
+ file: win32.join(normalizedSystemRoot, "System32", "rundll32.exe"),
224
+ args: ["url.dll,FileProtocolHandler", url]
225
+ };
226
+ }
227
+ return { file: "/usr/bin/xdg-open", args: [url] };
228
+ }
229
+ function packagedRuntimeDir() {
230
+ return resolve2(dirname2(fileURLToPath(import.meta.url)), "../runtime");
231
+ }
232
+ async function installGlobalPlugin(runtimeDir, configDir) {
233
+ const destination = pluginPath({ configDir });
234
+ await mkdir2(dirname2(destination), { recursive: true, mode: 448 });
235
+ const source = await readFile2(join2(runtimeDir, "lemma.mjs"), "utf8");
236
+ if (!source.startsWith(MANAGED_PLUGIN_MARKER)) {
237
+ throw new Error(
238
+ "The bundled Lemma OpenCode plugin is missing its ownership marker"
239
+ );
240
+ }
241
+ const existing = await lstat(destination).catch((error) => {
242
+ if (error.code === "ENOENT") return null;
243
+ throw error;
244
+ });
245
+ if (existing?.isSymbolicLink()) {
246
+ throw new Error(
247
+ `Refusing to replace symlinked plugin path: ${destination}`
248
+ );
249
+ }
250
+ if (existing) {
251
+ const current = await readFile2(destination, "utf8");
252
+ if (!current.startsWith(MANAGED_PLUGIN_MARKER)) {
253
+ throw new Error(`Refusing to replace an unowned plugin: ${destination}`);
254
+ }
255
+ }
256
+ const temporaryPath = `${destination}.${process.pid}.${randomUUID2()}.tmp`;
257
+ await writeFile2(temporaryPath, source, { encoding: "utf8", mode: 384 });
258
+ if (existing && process.platform === "win32") await unlink2(destination);
259
+ await rename2(temporaryPath, destination);
260
+ if (process.platform !== "win32") {
261
+ await chmod2(destination, 384);
262
+ }
263
+ }
264
+ async function runSetup(options = {}, dependencies = {}) {
265
+ const apiUrl = normalizedApiUrl(options.apiUrl ?? DEFAULT_API_URL);
266
+ const fetchImplementation = dependencies.fetch ?? fetch;
267
+ const output = dependencies.output ?? console.log;
268
+ const authorization = await startDeviceAuthorization(
269
+ apiUrl,
270
+ fetchImplementation
271
+ );
272
+ output(
273
+ `Authorize OpenCode for one Lemma project: ${authorization.verificationUriComplete}`
274
+ );
275
+ output(`Device code: ${authorization.userCode}`);
276
+ if (options.openBrowser !== false) {
277
+ await (dependencies.launchBrowser ?? launchBrowser)(
278
+ authorization.verificationUriComplete
279
+ );
280
+ }
281
+ const sleep = dependencies.sleep ?? ((milliseconds) => new Promise(
282
+ (resolvePromise) => setTimeout(resolvePromise, milliseconds)
283
+ ));
284
+ const deadline = Date.now() + authorization.expiresIn * 1e3;
285
+ let interval = authorization.interval;
286
+ while (Date.now() < deadline) {
287
+ await sleep(interval * 1e3);
288
+ const result = await pollDeviceAuthorization(
289
+ apiUrl,
290
+ authorization.deviceCode,
291
+ fetchImplementation
292
+ );
293
+ if (result.status === "authorization_pending") {
294
+ interval = result.interval;
295
+ continue;
296
+ }
297
+ if (result.status === "slow_down") {
298
+ interval = result.interval;
299
+ continue;
300
+ }
301
+ if (result.status === "expired_token")
302
+ throw new Error("Lemma login expired");
303
+ if (result.status === "access_denied")
304
+ throw new Error("Lemma login was denied");
305
+ const credentials = {
306
+ version: 1,
307
+ apiUrl,
308
+ projectId: result.projectId,
309
+ credentialId: result.credentialId,
310
+ accessToken: result.accessToken
311
+ };
312
+ const dataDir = resolveDataDir(options);
313
+ await writeCredentials(credentials, { ...options, dataDir });
314
+ await (dependencies.persistDataDirLocation ?? writeDataDirLocation)(
315
+ dataDir,
316
+ options
317
+ );
318
+ if (options.installPlugin !== false) {
319
+ const configDir = resolveConfigDir(options);
320
+ await (dependencies.installPlugin ?? installGlobalPlugin)(
321
+ options.runtimeDir ?? packagedRuntimeDir(),
322
+ configDir
323
+ );
324
+ output(`Installed the Lemma plugin in ${join2(configDir, "plugins")}`);
325
+ }
326
+ output("OpenCode is connected to the selected Lemma project.");
327
+ return credentials;
328
+ }
329
+ throw new Error("Lemma login expired");
330
+ }
331
+
332
+ // src/setup-entry.ts
333
+ function usage() {
334
+ console.error(
335
+ "Usage: lemma-opencode setup [--api-url URL] [--config-dir PATH] [--data-dir PATH] [--no-browser] [--skip-install]"
336
+ );
337
+ process.exit(2);
338
+ }
339
+ function parseOptions(args) {
340
+ const options = {};
341
+ const values = args[0] === "setup" ? args.slice(1) : args;
342
+ for (let index = 0; index < values.length; index += 1) {
343
+ const argument = values[index];
344
+ switch (argument) {
345
+ case "--api-url":
346
+ options.apiUrl = values[index + 1] ?? usage();
347
+ index += 1;
348
+ break;
349
+ case "--config-dir":
350
+ options.configDir = values[index + 1] ?? usage();
351
+ index += 1;
352
+ break;
353
+ case "--data-dir":
354
+ options.dataDir = values[index + 1] ?? usage();
355
+ index += 1;
356
+ break;
357
+ case "--no-browser":
358
+ options.openBrowser = false;
359
+ break;
360
+ case "--skip-install":
361
+ options.installPlugin = false;
362
+ break;
363
+ default:
364
+ usage();
365
+ }
366
+ }
367
+ return options;
368
+ }
369
+ try {
370
+ await runSetup(parseOptions(process.argv.slice(2)));
371
+ } catch (error) {
372
+ console.error(
373
+ `Lemma OpenCode setup failed: ${error instanceof Error ? error.message : String(error)}`
374
+ );
375
+ process.exitCode = 1;
376
+ }