gencow 0.1.287 → 0.1.288

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/gencow.mjs CHANGED
@@ -71,6 +71,7 @@ import { createDevLocalCommands } from "../lib/dev-local-command.mjs";
71
71
  import { handleDeployReadonlySubcommand, renderDeployHelp, verifyAppReady } from "../lib/deploy-command.mjs";
72
72
  import { createDeployCommand } from "../lib/deploy-runtime.mjs";
73
73
  import { createCreditsCommands } from "../lib/credits-command.mjs";
74
+ import { createOpencodeCommands } from "../lib/opencode-command.mjs";
74
75
  import { createDomainCommand } from "../lib/domain-command.mjs";
75
76
  import { createEnvCommand } from "../lib/env-command.mjs";
76
77
  import { createFilesCommand } from "../lib/files-command.mjs";
@@ -410,6 +411,7 @@ ${BOLD}Commands (login required):${RESET}
410
411
  ${GREEN}whoami${RESET} Show current user info
411
412
  ${GREEN}credits${RESET} Show credit balance and plan ${DIM}(--json)${RESET}
412
413
  ${GREEN}usage${RESET} Show usage by app/service ${DIM}(--month YYYY-MM, --app NAME, --json)${RESET}
414
+ ${GREEN}opencode setup${RESET} Connect OpenCode to Gencow LLM ${DIM}(llm/code, uses your login)${RESET}
413
415
  ${GREEN}dev${RESET} Watch + auto-deploy to cloud + live logs
414
416
  ${DIM}--local Run local Bun + Hono + PGlite development${RESET}
415
417
  ${DIM}--verbose Show all HTTP logs (including admin/ws)${RESET}
@@ -515,6 +517,7 @@ ${BOLD}Examples:${RESET}
515
517
  logout: runLogoutCommand,
516
518
  whoami: runWhoamiCommand,
517
519
  ...createCreditsCommands(),
520
+ ...createOpencodeCommands(),
518
521
 
519
522
  // ── static — 정적 파일 배포 (dev 기본, --prod 로 프로덕션) ──
520
523
  static: runStaticCommand,
package/core/index.js CHANGED
@@ -4653,6 +4653,19 @@ async function runWithRlsScope(scope, client, work, holdsQueue = false) {
4653
4653
  });
4654
4654
  }
4655
4655
  var contextBoundBuilders = /* @__PURE__ */ new WeakSet();
4656
+ var runtimeMayDropContext = true;
4657
+ void (async () => {
4658
+ try {
4659
+ const probe = new AsyncLocalStorage();
4660
+ const seen = await probe.run(1, async () => {
4661
+ await null;
4662
+ return { then: (resolve) => resolve(probe.getStore()) };
4663
+ });
4664
+ runtimeMayDropContext = seen !== 1;
4665
+ } catch {
4666
+ runtimeMayDropContext = true;
4667
+ }
4668
+ })();
4656
4669
  function isNativePromiseOrArray(value) {
4657
4670
  return value instanceof Promise || Array.isArray(value);
4658
4671
  }
@@ -4680,8 +4693,14 @@ function bindToStore(value, store) {
4680
4693
  if (prop === "then") {
4681
4694
  return (...args) => {
4682
4695
  const current = activeRlsExecution.getStore();
4683
- if (current?.active || !store.active) return Reflect.apply(member, receiver, args);
4684
- return activeRlsExecution.run(store, () => Reflect.apply(member, receiver, args));
4696
+ if (current?.active) return Reflect.apply(member, receiver, args);
4697
+ if (store.active && runtimeMayDropContext) {
4698
+ return activeRlsExecution.run(store, () => Reflect.apply(member, receiver, args));
4699
+ }
4700
+ if (store.active || runtimeMayDropContext) {
4701
+ return Promise.reject(createRlsScopeConflictError()).then(...args);
4702
+ }
4703
+ return Reflect.apply(member, receiver, args);
4685
4704
  };
4686
4705
  }
4687
4706
  return (...args) => {
@@ -4857,10 +4876,39 @@ async function withRlsLeasedConnection(leased, rls, fn, scope) {
4857
4876
  leased.release();
4858
4877
  }
4859
4878
  }
4860
- var outerConnectionQueues = /* @__PURE__ */ new WeakMap();
4861
- async function withOuterConnectionExclusive(client, work) {
4862
- if (!client || typeof client !== "object" && typeof client !== "function") return work();
4863
- const key = client;
4879
+ var outerConnectionQueues = /* @__PURE__ */ new Map();
4880
+ function isObjectLike(value) {
4881
+ return !!value && (typeof value === "object" || typeof value === "function");
4882
+ }
4883
+ function isBunSqlClient(client) {
4884
+ const c = client;
4885
+ return typeof c.unsafe === "function" && typeof c.savepoint === "function";
4886
+ }
4887
+ async function readConnectionIdentity(client) {
4888
+ if (!isBunSqlClient(client)) return client;
4889
+ const rows4 = await client.unsafe(
4890
+ "select pg_backend_pid()::text as pid, current_database()::text as db"
4891
+ );
4892
+ const row = Array.isArray(rows4) ? rows4[0] : void 0;
4893
+ if (!row || typeof row.pid !== "string" || typeof row.db !== "string") {
4894
+ throw createRlsUnsupportedError("session");
4895
+ }
4896
+ return `bun-pg:${row.db}:${row.pid}`;
4897
+ }
4898
+ function resolveConnectionIdentity(ref) {
4899
+ if (!ref.identity) {
4900
+ const pending = readConnectionIdentity(ref.client);
4901
+ ref.identity = pending;
4902
+ pending.catch(() => {
4903
+ if (ref.identity === pending) ref.identity = void 0;
4904
+ });
4905
+ }
4906
+ return ref.identity;
4907
+ }
4908
+ async function withOuterConnectionExclusive(ref, work) {
4909
+ if (!ref || !isObjectLike(ref.client)) return work();
4910
+ const identity = await resolveConnectionIdentity(ref);
4911
+ const key = identity;
4864
4912
  const previous = outerConnectionQueues.get(key) ?? Promise.resolve();
4865
4913
  let release;
4866
4914
  const mine = new Promise((resolve) => {
@@ -4881,7 +4929,7 @@ async function withRlsConnection(session, rls, reuseOuterConnection, scope, fn,
4881
4929
  if (reuseOuterConnection) {
4882
4930
  const c2 = session.client;
4883
4931
  return withOuterConnectionExclusive(
4884
- queueKey ?? c2,
4932
+ queueKey ?? { client: c2 },
4885
4933
  () => runWithRlsScope(
4886
4934
  scope,
4887
4935
  c2,
@@ -5030,7 +5078,8 @@ function createRlsDbInScope(db, rls, options, scope, inheritedQueueKey) {
5030
5078
  if (hasUnpartitionedRlsCache(db, baseSession)) {
5031
5079
  throw createRlsUnsupportedError("cache");
5032
5080
  }
5033
- const queueKey = reuseOuterConnection ? inheritedQueueKey ?? baseSession.client : void 0;
5081
+ const outerClient = baseSession.client;
5082
+ const queueKey = reuseOuterConnection ? inheritedQueueKey ?? (isObjectLike(outerClient) ? { client: outerClient } : void 0) : void 0;
5034
5083
  const injectScopeOnTx = (tx) => reuseOuterConnection && queueKey ? withOuterConnectionExclusive(
5035
5084
  queueKey,
5036
5085
  () => injectRlsVarsOnTx(tx, rls, options.onTransactionContextFailure)
@@ -1,3 +1,4 @@
1
+ import { literalConfigSyntax } from "./literal-config-syntax.mjs";
1
2
  import { execSync, spawn } from "child_process";
2
3
  import { appendFileSync, existsSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "fs";
3
4
  import { createRequire } from "module";
@@ -52,12 +53,24 @@ function isMissingSpecifierError(error, specifier) {
52
53
  // process.env, and computed expressions are NOT. To use those, migrate to
53
54
  // gencow.config.js. This path will be removed once all projects have moved.
54
55
  function parseTsConfigViaRegex(src) {
56
+ const originalSource = src;
57
+ const syntax = literalConfigSyntax(src);
58
+ src = syntax.content;
59
+ // Find keys before reading values: a decoy string must not consume a real property.
60
+ const matchProperty = (source, key, pattern) => {
61
+ const code = literalConfigSyntax(source).code;
62
+ for (const property of code.matchAll(new RegExp(`\\b${key}:`, "g"))) {
63
+ const match = source.slice(property.index + property[0].length).match(pattern);
64
+ if (match) return match;
65
+ }
66
+ return null;
67
+ };
55
68
  const extract = (key) => {
56
- const match = src.match(new RegExp(`${key}:\\s*["'\`]([^"'\`]+)["'\`]`));
69
+ const match = matchProperty(src, key, /^\s*["'`]([^"'`]+)["'`]/);
57
70
  return match ? match[1] : null;
58
71
  };
59
72
  const extractStringArray = (key) => {
60
- const match = src.match(new RegExp(`${key}:\\s*\\[([\\s\\S]*?)\\]`));
73
+ const match = matchProperty(src, key, /^\s*\[([\s\S]*?)\]/);
61
74
  if (!match) return null;
62
75
  const values = [];
63
76
  const entryRegex = /["'`]([^"'`]*)["'`]/g;
@@ -71,22 +84,22 @@ function parseTsConfigViaRegex(src) {
71
84
  const extractTopLevelStringArray = (key) => {
72
85
  let depth = 0;
73
86
  for (let i = 0; i < src.length; i += 1) {
74
- if (src[i] === "{") {
87
+ if (syntax.code[i] === "{") {
75
88
  depth += 1;
76
89
  continue;
77
90
  }
78
- if (src[i] === "}") {
91
+ if (syntax.code[i] === "}") {
79
92
  depth -= 1;
80
93
  continue;
81
94
  }
82
- if (depth !== 1 || !src.startsWith(key, i)) continue;
83
- const before = src[i - 1] ?? "";
84
- const after = src[i + key.length] ?? "";
95
+ if (depth !== 1 || !syntax.code.startsWith(key, i)) continue;
96
+ const before = syntax.code[i - 1] ?? "";
97
+ const after = syntax.code[i + key.length] ?? "";
85
98
  if (/[\w$]/.test(before) || after !== ":") continue;
86
99
 
87
- const arrayStart = src.indexOf("[", i + key.length);
100
+ const arrayStart = syntax.code.indexOf("[", i + key.length);
88
101
  if (arrayStart < 0) return null;
89
- const arrayEnd = src.indexOf("]", arrayStart);
102
+ const arrayEnd = syntax.code.indexOf("]", arrayStart);
90
103
  if (arrayEnd < 0) return null;
91
104
  const values = [];
92
105
  const entryRegex = /["'`]([^"'`]+)["'`]/g;
@@ -100,63 +113,66 @@ function parseTsConfigViaRegex(src) {
100
113
  }
101
114
  return null;
102
115
  };
103
- const extractNum = (key) => {
104
- const match = src.match(new RegExp(`${key}:\\s*(\\d+)`));
105
- return match ? Number(match[1]) : null;
106
- };
107
116
  const extractObjectFrom = (source, key) => {
108
- const keyIndex = source.search(new RegExp(`${key}:\\s*\\{`));
117
+ const code = literalConfigSyntax(source).code;
118
+ const keyIndex = code.search(new RegExp(`${key}:\\s*\\{`));
109
119
  if (keyIndex < 0) return "";
110
- const open = source.indexOf("{", keyIndex);
120
+ const open = code.indexOf("{", keyIndex);
111
121
  let depth = 0;
112
122
  for (let i = open; i < source.length; i += 1) {
113
- if (source[i] === "{") depth += 1;
114
- if (source[i] === "}") depth -= 1;
123
+ if (code[i] === "{") depth += 1;
124
+ if (code[i] === "}") depth -= 1;
115
125
  if (depth === 0) return source.slice(open, i + 1);
116
126
  }
117
127
  return "";
118
128
  };
119
- const extractTopLevelObject = (key) => {
129
+ const findTopLevelPropertyIndex = (key) => {
120
130
  let depth = 0;
121
131
  for (let i = 0; i < src.length; i += 1) {
122
- if (src[i] === "{") {
132
+ if (syntax.code[i] === "{") {
123
133
  depth += 1;
124
134
  continue;
125
135
  }
126
- if (src[i] === "}") {
136
+ if (syntax.code[i] === "}") {
127
137
  depth -= 1;
128
138
  continue;
129
139
  }
130
- if (depth !== 1 || !src.startsWith(key, i)) continue;
131
- const before = src[i - 1] ?? "";
132
- const after = src[i + key.length] ?? "";
140
+ if (depth !== 1 || !syntax.code.startsWith(key, i)) continue;
141
+ const before = syntax.code[i - 1] ?? "";
142
+ const after = syntax.code[i + key.length] ?? "";
133
143
  if (/[\w$]/.test(before) || after !== ":") continue;
134
- return extractObjectFrom(src.slice(i), key);
144
+ return i;
135
145
  }
136
- return "";
146
+ return -1;
147
+ };
148
+ const extractTopLevelObject = (key) => {
149
+ const index = findTopLevelPropertyIndex(key);
150
+ return index < 0 ? "" : extractObjectFrom(src.slice(index), key);
137
151
  };
138
152
  const extractObject = (key) => extractTopLevelObject(key);
139
153
  const extractArrayBodyFrom = (source, key) => {
140
- const keyIndex = source.search(new RegExp(`${key}:\\s*\\[`));
154
+ const code = literalConfigSyntax(source).code;
155
+ const keyIndex = code.search(new RegExp(`${key}:\\s*\\[`));
141
156
  if (keyIndex < 0) return "";
142
- const open = source.indexOf("[", keyIndex);
157
+ const open = code.indexOf("[", keyIndex);
143
158
  let depth = 0;
144
159
  for (let i = open; i < source.length; i += 1) {
145
- if (source[i] === "[") depth += 1;
146
- if (source[i] === "]") depth -= 1;
160
+ if (code[i] === "[") depth += 1;
161
+ if (code[i] === "]") depth -= 1;
147
162
  if (depth === 0) return source.slice(open + 1, i);
148
163
  }
149
164
  return "";
150
165
  };
151
166
  const splitObjectArray = (source) => {
167
+ const code = literalConfigSyntax(source).code;
152
168
  const objects = [];
153
169
  let start = -1;
154
170
  let depth = 0;
155
171
  for (let i = 0; i < source.length; i += 1) {
156
- if (source[i] === "{") {
172
+ if (code[i] === "{") {
157
173
  if (depth === 0) start = i;
158
174
  depth += 1;
159
- } else if (source[i] === "}") {
175
+ } else if (code[i] === "}") {
160
176
  depth -= 1;
161
177
  if (depth === 0 && start >= 0) {
162
178
  objects.push(source.slice(start, i + 1));
@@ -168,11 +184,11 @@ function parseTsConfigViaRegex(src) {
168
184
  };
169
185
  const codegenBlock = extractObject("codegen");
170
186
  const extractFrom = (block, key) => {
171
- const match = block.match(new RegExp(`${key}:\\s*["'\`]([^"'\`]+)["'\`]`));
187
+ const match = matchProperty(block, key, /^\s*["'`]([^"'`]+)["'`]/);
172
188
  return match ? match[1] : null;
173
189
  };
174
190
  const extractBoolFrom = (block, key) => {
175
- const match = block.match(new RegExp(`${key}:\\s*(true|false)`));
191
+ const match = matchProperty(block, key, /^\s*(true|false)/);
176
192
  return match ? match[1] === "true" : null;
177
193
  };
178
194
 
@@ -183,14 +199,16 @@ function parseTsConfigViaRegex(src) {
183
199
  if (functionsDir !== null) result.functionsDir = functionsDir;
184
200
  const envFile = extract("envFile");
185
201
  if (envFile !== null) result.envFile = envFile;
186
- const schemaStringMatch = src.match(/\bschema:\s*["'`]([^"'`]*)["'`]/u);
202
+ const schemaStringMatch = matchProperty(src, "schema", /^\s*["'`]([^"'`]*)["'`]/u);
187
203
  const schema = extractStringArray("schema") ?? schemaStringMatch?.[1] ?? extract("schema");
188
204
  if (schema !== null) result.schema = schema;
189
205
  const storage = extract("storage");
190
206
  if (storage !== null) result.storage = storage;
191
207
  const dbUrl = extract("url");
192
208
  if (dbUrl !== null) result.db = { url: dbUrl };
193
- const port = extractNum("port");
209
+ const portIndex = findTopLevelPropertyIndex("port");
210
+ const portMatch = portIndex < 0 ? null : src.slice(portIndex).match(/^port:\s*(\d+)/);
211
+ const port = portMatch ? Number(portMatch[1]) : null;
194
212
  if (port !== null) result.port = port;
195
213
 
196
214
  const codegen = {};
@@ -201,7 +219,7 @@ function parseTsConfigViaRegex(src) {
201
219
  if (outDir !== null) codegen.outDir = outDir;
202
220
  const serverOutDir = extractFrom(codegenBlock, "serverOutDir");
203
221
  if (serverOutDir !== null) codegen.serverOutDir = serverOutDir;
204
- const importExtension = readTsCodegenImportExtension(src);
222
+ const importExtension = readTsCodegenImportExtension(originalSource);
205
223
  if (importExtension !== undefined) codegen.importExtension = importExtension;
206
224
  const authSchema = extractBoolFrom(codegenBlock, "authSchema");
207
225
  if (authSchema !== null) codegen.authSchema = authSchema;
@@ -0,0 +1,42 @@
1
+ const lineTerminators = new Set(["\r", "\n", "\u2028", "\u2029"]);
2
+
3
+ export function isLiteralConfigLineTerminator(character) {
4
+ return lineTerminators.has(character);
5
+ }
6
+
7
+ /** Offset-preserving lexical views for the incumbent literal-only TS reader.
8
+ * Comments are trivia; quoted braces/keys are data, not object syntax. No
9
+ * configuration code is evaluated and computed expressions remain unsupported. */
10
+ export function literalConfigSyntax(source) {
11
+ const content = source.split("");
12
+ const code = [...content];
13
+ const hide = (characters, start, end) => {
14
+ for (let index = start; index < end; index++) {
15
+ if (!isLiteralConfigLineTerminator(characters[index])) characters[index] = " ";
16
+ }
17
+ };
18
+ let index = 0;
19
+ while (index < source.length) {
20
+ const start = index;
21
+ const character = source[index];
22
+ if (["'", '"', "`"].includes(character)) {
23
+ index++;
24
+ while (index < source.length) {
25
+ if (source[index] === "\\") index += 2;
26
+ else if (source[index++] === character) break;
27
+ }
28
+ hide(code, start, Math.min(index, source.length));
29
+ } else if (source.startsWith("//", index)) {
30
+ index += 2;
31
+ while (index < source.length && !isLiteralConfigLineTerminator(source[index])) index++;
32
+ hide(content, start, index);
33
+ hide(code, start, index);
34
+ } else if (source.startsWith("/*", index)) {
35
+ const end = source.indexOf("*/", index + 2);
36
+ index = end < 0 ? source.length : end + 2;
37
+ hide(content, start, index);
38
+ hide(code, start, index);
39
+ } else index++;
40
+ }
41
+ return { content: content.join(""), code: code.join("") };
42
+ }
@@ -0,0 +1,202 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { homedir, hostname } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ import { BOLD, CYAN, DIM, RESET, error, info, log, success } from "./output.mjs";
5
+ import { platformFetch, resolveCredsFromSources } from "./platform-client.mjs";
6
+ import {
7
+ GENCOW_MODEL_ID,
8
+ OpencodeSetupError,
9
+ applyOpencodeEdits,
10
+ hasGencowKey,
11
+ hasGencowProvider,
12
+ planOpencodeEdits,
13
+ resolveOpencodePaths,
14
+ } from "./opencode-config.mjs";
15
+
16
+ /**
17
+ * `gencow opencode setup` — connects OpenCode to the Gencow LLM gateway (model `llm/code`) with a user-owned
18
+ * `llm:chat` token minted from the CLI login (docs/specs/spec-gateway-llm-user-token-opencode-20261111.md §7).
19
+ * The token goes to OpenCode's credential store, never to the terminal or the config file.
20
+ */
21
+ const TOKEN_TTL_DAYS = 90;
22
+ const RENEW_WITHIN_MS = 30 * 24 * 60 * 60 * 1000;
23
+ const TOKEN_NAME_PREFIX = "opencode-";
24
+
25
+ function tokenName(hostnameImpl) {
26
+ const host = String(hostnameImpl() || "host").toLowerCase().replace(/[^a-z0-9-]/gu, "-").slice(0, 40);
27
+ return `${TOKEN_NAME_PREFIX}${host}`;
28
+ }
29
+
30
+ async function readJson(response) {
31
+ return response.json().catch(() => null);
32
+ }
33
+
34
+ function platformFailure(body, fallbackCode, fallbackMessage) {
35
+ const e = body?.error ?? {};
36
+ return new OpencodeSetupError(
37
+ typeof e.code === "string" ? e.code : fallbackCode,
38
+ typeof e.message === "string" ? e.message : fallbackMessage,
39
+ typeof e.nextAction === "string" ? e.nextAction : "Run `gencow login`, then run `gencow opencode setup` again.",
40
+ );
41
+ }
42
+
43
+ export function createOpencodeCommands(overrides = {}) {
44
+ const deps = {
45
+ resolveCredsImpl: () => resolveCredsFromSources(),
46
+ platformFetchImpl: platformFetch,
47
+ fetchImpl: fetch,
48
+ homeImpl: homedir,
49
+ hostnameImpl: hostname,
50
+ envImpl: process.env,
51
+ nowImpl: () => Date.now(),
52
+ logImpl: log,
53
+ infoImpl: info,
54
+ successImpl: success,
55
+ errorImpl: error,
56
+ ...overrides,
57
+ };
58
+
59
+ const statePath = () => join(deps.homeImpl(), ".gencow", "opencode.json");
60
+ function readState() {
61
+ try {
62
+ return JSON.parse(readFileSync(statePath(), "utf8"));
63
+ } catch {
64
+ return null;
65
+ }
66
+ }
67
+ function writeState(state) {
68
+ mkdirSync(dirname(statePath()), { recursive: true });
69
+ writeFileSync(statePath(), `${JSON.stringify(state, null, 2)}\n`);
70
+ }
71
+
72
+ async function verifyKey(baseURL, key) {
73
+ try {
74
+ const response = await deps.fetchImpl(`${baseURL}/models`, { headers: { Authorization: `Bearer ${key}` } });
75
+ if (response.status !== 200) return response.status;
76
+ const body = await readJson(response);
77
+ return (body?.data ?? []).some((m) => m?.id === GENCOW_MODEL_ID) ? 200 : "NO_MODEL";
78
+ } catch {
79
+ return "UNREACHABLE";
80
+ }
81
+ }
82
+
83
+ async function revokeBestEffort(creds, id) {
84
+ try {
85
+ await deps.platformFetchImpl(creds, `/platform/tools/tokens/${encodeURIComponent(id)}`, { method: "DELETE" });
86
+ } catch {
87
+ /* the old token expires on its own; it is not used by anything we wrote */
88
+ }
89
+ }
90
+
91
+ async function mintToken(creds, name) {
92
+ const create = () =>
93
+ deps.platformFetchImpl(creds, "/platform/tools/tokens", {
94
+ method: "POST",
95
+ headers: { "Content-Type": "application/json" },
96
+ body: JSON.stringify({ name, scopes: ["llm:chat"], expiresInDays: TOKEN_TTL_DAYS }),
97
+ });
98
+ let response = await create();
99
+ let body = await readJson(response);
100
+ if (response.status === 409 && body?.error?.code === "TOOLS_TOKEN_LIMIT_REACHED") {
101
+ // Free one slot, only from this machine's own earlier token (exact name, llm:chat only): other machines'
102
+ // installs and tokens the user named themselves must keep working.
103
+ const listed = await readJson(await deps.platformFetchImpl(creds, "/platform/tools/tokens"));
104
+ const mine = (listed?.tokens ?? [])
105
+ .filter((t) => t.kind === "manual" && !t.revokedAt && t.name === name && t.scopes?.length === 1 && t.scopes[0] === "llm:chat")
106
+ .sort((a, b) => String(a.createdAt ?? "").localeCompare(String(b.createdAt ?? "")));
107
+ if (mine.length > 0) {
108
+ await revokeBestEffort(creds, mine[0].id);
109
+ response = await create();
110
+ body = await readJson(response);
111
+ }
112
+ }
113
+ if (response.status !== 201 || !body?.token) {
114
+ throw platformFailure(body, "TOOLS_TOKEN_CREATE_FAILED", "Could not create the LLM token. Nothing was changed.");
115
+ }
116
+ return body;
117
+ }
118
+
119
+ async function setup(flags) {
120
+ const creds = deps.resolveCredsImpl();
121
+ if (!creds?.apiKey) {
122
+ throw new OpencodeSetupError("GENCOW_NOT_LOGGED_IN", "You are not logged in to Gencow.", "Run `gencow login`, then run `gencow opencode setup` again.");
123
+ }
124
+ if (creds.credentialSource === "environment") {
125
+ throw new OpencodeSetupError(
126
+ "GENCOW_LOGIN_REQUIRED",
127
+ "A CI/deploy token is set in the environment, and it cannot create LLM tokens.",
128
+ "Unset GENCOW_TOKEN / GENCOW_DEPLOY_TOKEN and run `gencow login`, then run `gencow opencode setup` again.",
129
+ );
130
+ }
131
+ const baseURL = `${creds.platformUrl}/platform/ai/v1`;
132
+ const paths = resolveOpencodePaths({ env: deps.envImpl, home: deps.homeImpl() });
133
+ const state = readState();
134
+ const existingKey = hasGencowKey(paths.authJson);
135
+ const sameAccount = state && state.userId === creds.userId && state.platformUrl === creds.platformUrl;
136
+ const fresh = sameAccount && existingKey && hasGencowProvider(paths) && Date.parse(state.expiresAt) - deps.nowImpl() > RENEW_WITHIN_MS;
137
+ if (fresh && !flags.force && (await verifyKey(baseURL, existingKey)) === 200) {
138
+ return { ok: true, code: "ALREADY_CONFIGURED", changed: false, model: `gencow/${GENCOW_MODEL_ID}`, expiresAt: state.expiresAt };
139
+ }
140
+
141
+ // Refuse before minting when the OpenCode files cannot be edited safely, so no unused token is created.
142
+ planOpencodeEdits({ paths, baseURL, apiKey: "pending" });
143
+ const issued = await mintToken(creds, tokenName(deps.hostnameImpl));
144
+ const plan = planOpencodeEdits({ paths, baseURL, apiKey: issued.token });
145
+ try {
146
+ applyOpencodeEdits({ paths, plan });
147
+ } catch (writeError) {
148
+ await revokeBestEffort(creds, issued.id);
149
+ throw writeError;
150
+ }
151
+ writeState({ userId: creds.userId, platformUrl: creds.platformUrl, tokenId: issued.id, expiresAt: issued.expiresAt });
152
+ if (sameAccount && state.tokenId && state.tokenId !== issued.id) await revokeBestEffort(creds, state.tokenId);
153
+
154
+ const verified = await verifyKey(baseURL, issued.token);
155
+ if (verified !== 200) {
156
+ throw new OpencodeSetupError(
157
+ "GATEWAY_VERIFY_FAILED",
158
+ "The LLM token and OpenCode settings were written, but the gateway check did not pass.",
159
+ verified === "UNREACHABLE"
160
+ ? "Check your network connection, then run `gencow opencode setup --force` again."
161
+ : "Run `gencow opencode setup --force` again. If it keeps failing, report the code GATEWAY_VERIFY_FAILED.",
162
+ );
163
+ }
164
+ const previousAccountToken = Boolean(state?.tokenId && !sameAccount);
165
+ return { ok: true, code: "CONFIGURED", changed: true, previousAccountToken, model: `gencow/${GENCOW_MODEL_ID}`, expiresAt: issued.expiresAt, keptUserModel: plan.keptUserModel };
166
+ }
167
+
168
+ return {
169
+ async opencode(...args) {
170
+ const sub = args.find((a) => !a.startsWith("-"));
171
+ const flags = { json: args.includes("--json"), force: args.includes("--force") };
172
+ if (sub !== "setup") {
173
+ deps.logImpl(`\n${BOLD}Usage:${RESET} gencow opencode setup ${DIM}[--force] [--json]${RESET}`);
174
+ deps.logImpl(` Connect OpenCode to Gencow (${CYAN}gencow/${GENCOW_MODEL_ID}${RESET}) using your Gencow login.\n`);
175
+ process.exitCode = sub ? 1 : 0;
176
+ return;
177
+ }
178
+ try {
179
+ const result = await setup(flags);
180
+ if (flags.json) return deps.logImpl(JSON.stringify(result));
181
+ if (result.code === "ALREADY_CONFIGURED") {
182
+ deps.successImpl(`Already connected: ${CYAN}${result.model}${RESET} ${DIM}(token valid until ${result.expiresAt.slice(0, 10)})${RESET}`);
183
+ } else {
184
+ deps.successImpl(`Gencow LLM connected: ${CYAN}${result.model}${RESET} ${DIM}(token valid until ${result.expiresAt.slice(0, 10)})${RESET}`);
185
+ if (result.keptUserModel) deps.infoImpl(`Your default OpenCode model was kept. Choose ${CYAN}${result.model}${RESET} in OpenCode to use Gencow.`);
186
+ if (result.previousAccountToken) deps.infoImpl("A token from the previously logged-in account is still valid until it expires. Revoke it in that account's dashboard (Account settings > Connected tools) if you no longer use it.");
187
+ deps.infoImpl("Restart OpenCode so it picks up the new provider.");
188
+ }
189
+ } catch (caught) {
190
+ const failure = caught instanceof OpencodeSetupError
191
+ ? caught
192
+ : new OpencodeSetupError("OPENCODE_SETUP_FAILED", "Could not complete the setup.", "Run `gencow opencode setup` again. If it keeps failing, report this code.");
193
+ if (flags.json) deps.logImpl(JSON.stringify({ ok: false, code: failure.code, message: failure.message, nextAction: failure.nextAction }));
194
+ else {
195
+ deps.errorImpl(`${failure.message} ${DIM}(${failure.code})${RESET}`);
196
+ deps.infoImpl(failure.nextAction);
197
+ }
198
+ process.exitCode = 1;
199
+ }
200
+ },
201
+ };
202
+ }