@eduardo191labs/opencode-actions 0.0.0-stage → 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,299 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Installs the bot into every repository an account can write to.
4
+ *
5
+ * opencode-actions-install --owner eduardo191-star --config-repo owner/bot-config
6
+ *
7
+ * For each repository it:
8
+ * 1. detects the stack (so the config can pick test/build commands),
9
+ * 2. skips archived, disabled and forked repositories,
10
+ * 3. writes the three narrow workflows, replacing only files it owns,
11
+ * 4. copies FREEPI_JWT from the user's environment into the repository secret,
12
+ * 5. enables the permissions the workflows declare.
13
+ *
14
+ * Re-running is idempotent: the workflows carry a marker, and a file that lacks
15
+ * the marker is never overwritten.
16
+ */
17
+ import { createRequire } from "node:module";
18
+ import { GitHub, parseRepo } from "./github.js";
19
+ import { detect, workflowTemplates } from "./detect.js";
20
+ const MARKER = "uses: eduardo191-star/opencode-actions@";
21
+ async function main() {
22
+ const options = parseArgs(process.argv.slice(2));
23
+ const github = new GitHub({ token: options.token });
24
+ const repos = options.repo ? [parseRepo(`${options.owner}/${options.repo}`)] : await listRepos(github, options);
25
+ console.error(`→ ${repos.length} repositories selected`);
26
+ const results = [];
27
+ for (const ref of repos) {
28
+ const name = `${ref.owner}/${ref.repo}`;
29
+ try {
30
+ const found = await detect(github, ref);
31
+ const reason = skipReason(found, options);
32
+ if (reason) {
33
+ results.push({ repo: name, action: "skipped", detail: reason });
34
+ console.error(`· ${name}: skipped (${reason})`);
35
+ continue;
36
+ }
37
+ console.error(`→ ${name}: ${found.stack.language}${found.stack.packageManager ? ` via ${found.stack.packageManager}` : ""}`);
38
+ const workflows = workflowTemplates({
39
+ configRepo: options.configRepo,
40
+ configRef: options.configRef,
41
+ model: options.model,
42
+ plugins: options.plugins,
43
+ actionRef: options.actionRef,
44
+ stack: found.stack,
45
+ });
46
+ if (options.dryRun) {
47
+ results.push({ repo: name, action: "dry-run", detail: workflows.map((w) => w.path).join(", ") });
48
+ console.error(` would write ${workflows.length} workflows`);
49
+ continue;
50
+ }
51
+ let written = 0;
52
+ let skipped = 0;
53
+ for (const workflow of workflows) {
54
+ const existing = await github.getFile(ref, workflow.path).catch(() => null);
55
+ if (existing && !existing.content.includes(MARKER)) {
56
+ skipped++;
57
+ console.error(` ! ${workflow.path} exists and is not ours; leaving it alone`);
58
+ continue;
59
+ }
60
+ if (existing && existing.content.trim() === workflow.content.trim())
61
+ continue;
62
+ await putFile(github, ref, workflow.path, workflow.content, `chore: install ${workflow.path.split("/").pop()}`, found.repo.defaultBranch, existing?.sha);
63
+ written++;
64
+ }
65
+ // The whole feature set depends on this secret; copy it from the caller.
66
+ if (options.secretValue) {
67
+ await putSecret(github, ref, options.secretName, options.secretValue);
68
+ }
69
+ // Allow the workflows to create PRs and push fix branches.
70
+ await enableWorkflowPermissions(github, ref).catch(() => { });
71
+ results.push({ repo: name, action: "installed", detail: `${written} written, ${skipped} untouched` });
72
+ console.error(` ✓ ${written} workflows written, ${skipped} untouched`);
73
+ }
74
+ catch (error) {
75
+ results.push({ repo: name, action: "failed", detail: error.message });
76
+ console.error(` ✗ ${name}: ${error.message}`);
77
+ }
78
+ }
79
+ const summary = {
80
+ total: results.length,
81
+ installed: results.filter((r) => r.action === "installed").length,
82
+ skipped: results.filter((r) => r.action === "skipped").length,
83
+ failed: results.filter((r) => r.action === "failed").length,
84
+ results,
85
+ };
86
+ process.stdout.write(JSON.stringify(summary, null, 2) + "\n");
87
+ if (summary.failed)
88
+ process.exitCode = 1;
89
+ }
90
+ async function listRepos(github, options) {
91
+ const repos = [];
92
+ let page = 1;
93
+ while (page <= 20) {
94
+ const batch = await github.get(options.owner.startsWith("org:")
95
+ ? `/orgs/${options.owner.slice(4)}/repos?per_page=100&page=${page}&type=all`
96
+ : `/users/${options.owner}/repos?per_page=100&page=${page}&type=owner`);
97
+ if (!batch.length)
98
+ break;
99
+ repos.push(...batch.map((item) => ({
100
+ owner: item.owner.login,
101
+ repo: item.name,
102
+ private: item.private,
103
+ archived: item.archived,
104
+ fork: item.fork,
105
+ disabled: item.disabled,
106
+ })));
107
+ if (batch.length < 100)
108
+ break;
109
+ page++;
110
+ }
111
+ return repos
112
+ .filter((repo) => {
113
+ if (options.onlyPublic && repo.private)
114
+ return false;
115
+ if (!options.includeArchived && repo.archived)
116
+ return false;
117
+ if (!options.includeForks && repo.fork)
118
+ return false;
119
+ if (repo.disabled)
120
+ return false;
121
+ if (options.exclude.some((pattern) => repo.repo === pattern || `${repo.owner}/${repo.repo}` === pattern))
122
+ return false;
123
+ return true;
124
+ })
125
+ .map((repo) => ({ owner: repo.owner, repo: repo.repo }));
126
+ }
127
+ function skipReason(found, options) {
128
+ if (found.repo.archived && !options.includeArchived)
129
+ return "archived";
130
+ if (found.repo.disabled)
131
+ return "disabled";
132
+ if (found.repo.fork && !options.includeForks)
133
+ return "fork";
134
+ if (found.repo.private && options.onlyPublic)
135
+ return "private";
136
+ return null;
137
+ }
138
+ async function putFile(github, ref, path, content, message, branch, sha) {
139
+ await github.put(`/repos/${ref.owner}/${ref.repo}/contents/${path}`, {
140
+ message,
141
+ content: Buffer.from(content, "utf8").toString("base64"),
142
+ branch,
143
+ ...(sha ? { sha } : {}),
144
+ });
145
+ }
146
+ async function putSecret(github, ref, name, value) {
147
+ // The REST secret API requires the repository public key, which is fine here
148
+ // because the token already has admin access to these repositories.
149
+ const { key, key_id } = await github.get(`/repos/${ref.owner}/${ref.repo}/actions/secrets/public-key`);
150
+ const sealed = sealSecret(value, key);
151
+ await github.put(`/repos/${ref.owner}/${ref.repo}/actions/secrets/${name}`, {
152
+ encrypted_value: sealed,
153
+ key_id,
154
+ });
155
+ }
156
+ /**
157
+ * libsodium sealed box, implemented with Node's crypto. GitHub expects
158
+ * crypto_box_seal; Node cannot do that natively, so the caller must provide
159
+ * `sodium-native` or we fall back to reporting the limitation.
160
+ */
161
+ function sealSecret(value, publicKeyBase64) {
162
+ // Lazy require so the installer works without the optional dependency.
163
+ const require_ = createRequire(import.meta.url);
164
+ let sodium;
165
+ try {
166
+ sodium = require_("sodium-native");
167
+ }
168
+ catch {
169
+ throw new Error("Sealing a repository secret needs `sodium-native`. Install it with `npm i -g sodium-native`, or set the secret manually with `gh secret set`.");
170
+ }
171
+ const key = Buffer.from(publicKeyBase64, "base64");
172
+ const message = Buffer.from(value, "utf8");
173
+ const sealed = Buffer.alloc(message.length + sodium.crypto_box_SEALBYTES);
174
+ sodium.crypto_box_seal(sealed, message, key);
175
+ return sealed.toString("base64");
176
+ }
177
+ async function enableWorkflowPermissions(github, ref) {
178
+ await github.put(`/repos/${ref.owner}/${ref.repo}/actions/permissions/workflow`, {
179
+ default_workflow_permissions: "write",
180
+ can_approve_pull_request_reviews: true,
181
+ });
182
+ }
183
+ function parseArgs(argv) {
184
+ const options = {
185
+ owner: process.env.GITHUB_REPOSITORY_OWNER ?? "",
186
+ configRepo: process.env.OPENCODE_ACTIONS_CONFIG_REPO ?? "",
187
+ configRef: "main",
188
+ model: "free-pi/glm-5.3-flash",
189
+ plugins: "@eduardo191labs/opencode-free-pi@latest",
190
+ actionRef: "v1",
191
+ token: process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN ?? "",
192
+ secretName: "FREEPI_JWT",
193
+ secretValue: process.env.FREEPI_JWT,
194
+ dryRun: false,
195
+ includeForks: false,
196
+ includeArchived: false,
197
+ onlyPublic: false,
198
+ exclude: [],
199
+ };
200
+ for (let index = 0; index < argv.length; index++) {
201
+ const arg = argv[index];
202
+ const next = () => argv[++index];
203
+ switch (arg) {
204
+ case "--owner":
205
+ options.owner = next();
206
+ break;
207
+ case "--repo":
208
+ options.repo = next();
209
+ break;
210
+ case "--config-repo":
211
+ options.configRepo = next();
212
+ break;
213
+ case "--config-ref":
214
+ options.configRef = next();
215
+ break;
216
+ case "--model":
217
+ options.model = next();
218
+ break;
219
+ case "--plugins":
220
+ options.plugins = next();
221
+ break;
222
+ case "--action-ref":
223
+ options.actionRef = next();
224
+ break;
225
+ case "--secret-name":
226
+ options.secretName = next();
227
+ break;
228
+ case "--secret-value":
229
+ options.secretValue = next();
230
+ break;
231
+ case "--exclude":
232
+ options.exclude.push(next());
233
+ break;
234
+ case "--include-forks":
235
+ options.includeForks = true;
236
+ break;
237
+ case "--include-archived":
238
+ options.includeArchived = true;
239
+ break;
240
+ case "--only-public":
241
+ options.onlyPublic = true;
242
+ break;
243
+ case "--dry-run":
244
+ options.dryRun = true;
245
+ break;
246
+ case "-h":
247
+ case "--help":
248
+ process.stdout.write(usage());
249
+ process.exit(0);
250
+ default:
251
+ if (arg.startsWith("--")) {
252
+ console.error(`Unknown flag ${arg}`);
253
+ process.exit(2);
254
+ }
255
+ }
256
+ }
257
+ if (!options.owner) {
258
+ console.error("--owner is required (or set GITHUB_REPOSITORY_OWNER)");
259
+ process.exit(2);
260
+ }
261
+ if (!options.configRepo) {
262
+ console.error("--config-repo is required (or set OPENCODE_ACTIONS_CONFIG_REPO)");
263
+ process.exit(2);
264
+ }
265
+ if (!options.token) {
266
+ console.error("GITHUB_TOKEN is required");
267
+ process.exit(2);
268
+ }
269
+ return options;
270
+ }
271
+ function usage() {
272
+ return `opencode-actions-install — install the bot into repositories
273
+
274
+ Usage:
275
+ opencode-actions-install --owner <login> --config-repo <owner/repo> [flags]
276
+
277
+ Flags:
278
+ --owner <login> User or "org:<name>". Defaults to GITHUB_REPOSITORY_OWNER
279
+ --repo <name> Only this repository
280
+ --config-repo <repo> Configuration repository (required)
281
+ --config-ref <ref> Configuration ref (default: main)
282
+ --model <id> Model for the workflows (default: free-pi/glm-5.3-flash)
283
+ --plugins <list> Plugins installed in the workflows
284
+ --action-ref <ref> Tag of opencode-actions to use (default: v1)
285
+ --secret-name <name> Secret to copy (default: FREEPI_JWT)
286
+ --secret-value <text> Secret value; defaults to $FREEPI_JWT
287
+ --exclude <name> Repository to skip (repeatable)
288
+ --include-forks Also install in forks
289
+ --include-archived Also install in archived repositories
290
+ --only-public Only public repositories
291
+ --dry-run Detect and report; change nothing
292
+
293
+ The installer never overwrites a workflow file the bot did not create.
294
+ `;
295
+ }
296
+ main().catch((error) => {
297
+ console.error(error);
298
+ process.exit(1);
299
+ });
@@ -0,0 +1,54 @@
1
+ import { type BotConfig } from "./config.js";
2
+ import { GitHub, type RepoRef } from "./github.js";
3
+ /** Deep merge that recurses into plain objects (config layers stack). */
4
+ export declare function mergeConfig(base: BotConfig, override: Partial<BotConfig>): BotConfig;
5
+ export declare function deepMerge(base: any, override: any): any;
6
+ export interface LoadConfigOptions {
7
+ /** Local directory that may contain opencode-actions.yml (the checked-out repo). */
8
+ workspace: string;
9
+ /** Filename inside the config repo. Defaults to opencode-actions.yml. */
10
+ configPath?: string;
11
+ /** GitHub client, used when configRepo is set. */
12
+ github?: GitHub;
13
+ /** "owner/repo" of a separate configuration repository. */
14
+ configRepo?: string;
15
+ /** Ref of the config repository. */
16
+ configRef?: string;
17
+ /** Config repo token, if it differs from the workflow token. */
18
+ configToken?: string;
19
+ /** Inline JSON/YAML config from the action input. */
20
+ inline?: string;
21
+ }
22
+ /**
23
+ * Resolution order (later wins):
24
+ * 1. DEFAULT_CONFIG
25
+ * 2. <workspace>/opencode-actions.yml
26
+ * 3. config repo file (remote)
27
+ * 4. inline JSON from the `config` input
28
+ * 5. environment overrides (OPENCODE_BOT_MODEL, ...)
29
+ */
30
+ export declare function loadConfig(options: LoadConfigOptions): Promise<{
31
+ config: BotConfig;
32
+ sources: string[];
33
+ }>;
34
+ /**
35
+ * A tiny YAML subset parser. It covers what configuration files actually use:
36
+ * nested maps, lists of scalars, block scalars and quoted strings. Full YAML
37
+ * would drag in a dependency for no benefit; the JSON schema covers validation.
38
+ */
39
+ export declare function parseYaml(text: string): unknown;
40
+ export declare function parseConfigText(text: string, source: string): Partial<BotConfig>;
41
+ /**
42
+ * Map configured provider credentials onto environment variables that
43
+ * OpenCode understands. When `sources` provides a `provider:<name>` entry,
44
+ * the caller has already exported the secret; this only builds the answers
45
+ * for `opencode auth login`.
46
+ */
47
+ export declare function providerAuthPlan(config: BotConfig): {
48
+ provider: string;
49
+ method?: string;
50
+ answers: Record<string, string>;
51
+ }[];
52
+ /** Export `secrets.env` mappings: config value names the GitHub secret. */
53
+ export declare function resolveSecretEnv(config: BotConfig): Record<string, string>;
54
+ export type { RepoRef };
package/dist/loader.js ADDED
@@ -0,0 +1,306 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { existsSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { DEFAULT_CONFIG } from "./config.js";
5
+ import { parseRepo } from "./github.js";
6
+ /** Deep merge that recurses into plain objects (config layers stack). */
7
+ export function mergeConfig(base, override) {
8
+ return deepMerge(base, override);
9
+ }
10
+ export function deepMerge(base, override) {
11
+ if (override === undefined)
12
+ return base;
13
+ if (Array.isArray(override))
14
+ return override;
15
+ if (isPlainObject(override) && isPlainObject(base)) {
16
+ const out = { ...base };
17
+ for (const [key, value] of Object.entries(override)) {
18
+ out[key] = deepMerge(base[key], value);
19
+ }
20
+ return out;
21
+ }
22
+ return override;
23
+ }
24
+ function isPlainObject(value) {
25
+ return typeof value === "object" && value !== null && !Array.isArray(value);
26
+ }
27
+ /**
28
+ * Resolution order (later wins):
29
+ * 1. DEFAULT_CONFIG
30
+ * 2. <workspace>/opencode-actions.yml
31
+ * 3. config repo file (remote)
32
+ * 4. inline JSON from the `config` input
33
+ * 5. environment overrides (OPENCODE_BOT_MODEL, ...)
34
+ */
35
+ export async function loadConfig(options) {
36
+ let config = { ...DEFAULT_CONFIG };
37
+ const sources = ["defaults"];
38
+ const localPath = join(options.workspace, "opencode-actions.yml");
39
+ if (existsSync(localPath)) {
40
+ const text = await readFile(localPath, "utf8");
41
+ config = mergeConfig(config, parseConfigText(text, localPath));
42
+ sources.push("opencode-actions.yml");
43
+ }
44
+ if (options.configRepo) {
45
+ const remote = await loadRemoteConfig(options);
46
+ if (remote) {
47
+ config = mergeConfig(config, remote.config);
48
+ sources.push(`${options.configRepo}@${options.configRef ?? "default"}`);
49
+ }
50
+ }
51
+ if (options.inline) {
52
+ config = mergeConfig(config, parseConfigText(options.inline, "action input"));
53
+ sources.push("input.config");
54
+ }
55
+ if (process.env.OPENCODE_BOT_MODEL) {
56
+ config.bot = { ...config.bot, model: { ...config.bot?.model, id: process.env.OPENCODE_BOT_MODEL } };
57
+ }
58
+ if (process.env.OPENCODE_BOT_BASE_BRANCH) {
59
+ config.bot = { ...config.bot, base_branch: process.env.OPENCODE_BOT_BASE_BRANCH };
60
+ }
61
+ return { config, sources };
62
+ }
63
+ async function loadRemoteConfig(options) {
64
+ const github = options.github;
65
+ if (!github)
66
+ throw new Error("A GitHub client is required to read the configuration repository");
67
+ const ref = parseRepo(options.configRepo);
68
+ const path = options.configPath ?? "opencode-actions.yml";
69
+ const direct = await github.getFile(ref, path, options.configRef);
70
+ if (direct)
71
+ return { config: parseConfigText(direct.content, `${options.configRepo}/${path}`) };
72
+ // Fall back to the first yml/json file at the root so a minimal config repo just works.
73
+ const entries = await github.listDir(ref, "", options.configRef);
74
+ const candidate = entries.find((entry) => entry.type === "file" && /\.(ya?ml|json|jsonc)$/.test(entry.name));
75
+ if (!candidate)
76
+ throw new Error(`No ${path} found in ${options.configRepo}`);
77
+ const file = await github.getFile(ref, candidate.path, options.configRef);
78
+ if (!file)
79
+ throw new Error(`Could not read ${candidate.path} from ${options.configRepo}`);
80
+ return { config: parseConfigText(file.content, `${options.configRepo}/${candidate.path}`) };
81
+ }
82
+ /**
83
+ * A tiny YAML subset parser. It covers what configuration files actually use:
84
+ * nested maps, lists of scalars, block scalars and quoted strings. Full YAML
85
+ * would drag in a dependency for no benefit; the JSON schema covers validation.
86
+ */
87
+ export function parseYaml(text) {
88
+ const lines = text
89
+ .replace(/\r\n/g, "\n")
90
+ .split("\n")
91
+ .filter((line) => !/^\s*#/.test(line) && line.trim() !== "");
92
+ let index = 0;
93
+ const indentOf = (line) => line.match(/^ */)[0].length;
94
+ function parseBlock(minIndent) {
95
+ if (index >= lines.length)
96
+ return null;
97
+ const first = lines[index];
98
+ const indent = indentOf(first);
99
+ if (indent < minIndent)
100
+ return null;
101
+ const isList = first.trim().startsWith("- ") || first.trim() === "-";
102
+ return isList ? parseList(indent) : parseMap(indent);
103
+ }
104
+ function parseList(indent) {
105
+ const out = [];
106
+ while (index < lines.length) {
107
+ const line = lines[index];
108
+ const currentIndent = indentOf(line);
109
+ if (currentIndent !== indent || !line.trim().startsWith("-"))
110
+ break;
111
+ const rest = line.trim().slice(1).trim();
112
+ index++;
113
+ if (!rest) {
114
+ out.push(parseBlock(indent + 1));
115
+ continue;
116
+ }
117
+ if (rest.includes(":") && !/^["'].*["']$/.test(rest)) {
118
+ // Inline map entry: "- key: value" starts a map at this indent.
119
+ const map = {};
120
+ const [key = "", ...valueParts] = rest.split(":");
121
+ const value = valueParts.join(":").trim();
122
+ map[key.trim()] = value ? parseScalar(value) : parseBlock(indent + 1);
123
+ // Consume sibling keys at deeper indent.
124
+ while (index < lines.length && indentOf(lines[index]) > indent && !lines[index].trim().startsWith("-")) {
125
+ const sibling = lines[index];
126
+ const [k = "", ...v] = sibling.trim().split(":");
127
+ const siblingValue = v.join(":").trim();
128
+ map[k.trim()] = siblingValue ? parseScalar(siblingValue) : parseBlock(indentOf(sibling) + 1);
129
+ index++;
130
+ }
131
+ out.push(map);
132
+ continue;
133
+ }
134
+ out.push(parseScalar(rest));
135
+ }
136
+ return out;
137
+ }
138
+ function parseMap(indent) {
139
+ const out = {};
140
+ while (index < lines.length) {
141
+ const line = lines[index];
142
+ const currentIndent = indentOf(line);
143
+ if (currentIndent !== indent)
144
+ break;
145
+ const trimmed = line.trim();
146
+ const colon = trimmed.indexOf(":");
147
+ if (colon === -1) {
148
+ index++;
149
+ continue;
150
+ }
151
+ const key = trimmed.slice(0, colon).trim().replace(/^["']|["']$/g, "");
152
+ const rest = trimmed.slice(colon + 1).trim();
153
+ index++;
154
+ if (rest === "|" || rest === ">" || rest === "|-" || rest === ">-") {
155
+ const blockLines = [];
156
+ while (index < lines.length && (indentOf(lines[index]) > indent || lines[index].trim() === "")) {
157
+ blockLines.push(lines[index].slice(Math.min(indentOf(lines[index]), indent + 2)));
158
+ index++;
159
+ }
160
+ out[key] = blockLines.join(rest.startsWith(">") ? " " : "\n").trim();
161
+ continue;
162
+ }
163
+ if (!rest) {
164
+ const next = index < lines.length ? indentOf(lines[index]) : 0;
165
+ out[key] = next > indent ? parseBlock(next) : null;
166
+ continue;
167
+ }
168
+ out[key] = parseScalar(rest);
169
+ }
170
+ return out;
171
+ }
172
+ function parseScalar(value) {
173
+ const trimmed = value.trim();
174
+ if (trimmed === "null" || trimmed === "~")
175
+ return null;
176
+ if (trimmed === "true")
177
+ return true;
178
+ if (trimmed === "false")
179
+ return false;
180
+ if (/^-?\d+(\.\d+)?$/.test(trimmed))
181
+ return Number(trimmed);
182
+ if ((trimmed.startsWith('"') && trimmed.endsWith('"')) || (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
183
+ return trimmed.slice(1, -1);
184
+ }
185
+ if (trimmed.startsWith("[") && trimmed.endsWith("]")) {
186
+ const inner = trimmed.slice(1, -1).trim();
187
+ if (!inner)
188
+ return [];
189
+ return splitFlow(inner).map((item) => parseScalar(item));
190
+ }
191
+ if (trimmed.startsWith("{") && trimmed.endsWith("}")) {
192
+ // Accept both JSON and the unquoted `{ a: 1 }` form.
193
+ try {
194
+ return JSON.parse(trimmed);
195
+ }
196
+ catch {
197
+ const inner = trimmed.slice(1, -1).trim();
198
+ if (!inner)
199
+ return {};
200
+ const out = {};
201
+ for (const part of splitFlow(inner)) {
202
+ const colon = part.indexOf(":");
203
+ if (colon === -1)
204
+ continue;
205
+ out[part.slice(0, colon).trim()] = parseScalar(part.slice(colon + 1));
206
+ }
207
+ return out;
208
+ }
209
+ }
210
+ return trimmed;
211
+ }
212
+ /** Split a flow collection on commas that are not inside quotes or nested brackets. */
213
+ function splitFlow(input) {
214
+ const out = [];
215
+ let depth = 0;
216
+ let quote = null;
217
+ let current = "";
218
+ for (const char of input) {
219
+ if (quote) {
220
+ current += char;
221
+ if (char === quote)
222
+ quote = null;
223
+ continue;
224
+ }
225
+ if (char === '"' || char === "'") {
226
+ quote = char;
227
+ current += char;
228
+ continue;
229
+ }
230
+ if (char === "[" || char === "{")
231
+ depth++;
232
+ if (char === "]" || char === "}")
233
+ depth--;
234
+ if (char === "," && depth === 0) {
235
+ out.push(current.trim());
236
+ current = "";
237
+ continue;
238
+ }
239
+ current += char;
240
+ }
241
+ if (current.trim())
242
+ out.push(current.trim());
243
+ return out;
244
+ }
245
+ const result = parseBlock(0);
246
+ return result ?? {};
247
+ }
248
+ export function parseConfigText(text, source) {
249
+ const trimmed = text.trim();
250
+ if (!trimmed)
251
+ return {};
252
+ try {
253
+ if (trimmed.startsWith("{")) {
254
+ const json = JSON.parse(trimmed);
255
+ validateShape(json, source);
256
+ return json;
257
+ }
258
+ const parsed = parseYaml(trimmed);
259
+ validateShape(parsed, source);
260
+ return parsed;
261
+ }
262
+ catch (error) {
263
+ throw new Error(`Invalid configuration in ${source}: ${error.message}`);
264
+ }
265
+ }
266
+ function validateShape(value, source) {
267
+ if (!isPlainObject(value))
268
+ throw new Error(`${source} must contain a mapping, not ${typeof value}`);
269
+ if (value.version !== undefined && value.version !== 1) {
270
+ throw new Error(`${source}: unsupported version ${String(value.version)} (expected 1)`);
271
+ }
272
+ }
273
+ // ------------------------------------------------------------------- secrets
274
+ /**
275
+ * Map configured provider credentials onto environment variables that
276
+ * OpenCode understands. When `sources` provides a `provider:<name>` entry,
277
+ * the caller has already exported the secret; this only builds the answers
278
+ * for `opencode auth login`.
279
+ */
280
+ export function providerAuthPlan(config) {
281
+ const plan = [];
282
+ for (const [provider, spec] of Object.entries(config.bot?.secrets?.providers ?? {})) {
283
+ const answers = { ...(spec.answers ?? {}) };
284
+ if (spec.token_env) {
285
+ const value = process.env[spec.token_env];
286
+ if (value) {
287
+ answers.key = value;
288
+ answers.token = value;
289
+ answers.apiKey = value;
290
+ answers.api_key = value;
291
+ }
292
+ }
293
+ plan.push({ provider, method: spec.method, answers });
294
+ }
295
+ return plan;
296
+ }
297
+ /** Export `secrets.env` mappings: config value names the GitHub secret. */
298
+ export function resolveSecretEnv(config) {
299
+ const out = {};
300
+ for (const [variable, secretName] of Object.entries(config.bot?.secrets?.env ?? {})) {
301
+ const value = process.env[secretName] ?? process.env[variable];
302
+ if (value)
303
+ out[variable] = value;
304
+ }
305
+ return out;
306
+ }
@@ -0,0 +1,16 @@
1
+ #!/usr/bin/env node
2
+ import { GitHub, type RepoRef } from "./github.js";
3
+ import { type BotConfig } from "./config.js";
4
+ interface Tool {
5
+ name: string;
6
+ description: string;
7
+ inputSchema: Record<string, unknown>;
8
+ handler(args: Record<string, any>, ctx: McpContext): Promise<unknown>;
9
+ }
10
+ interface McpContext {
11
+ github: GitHub;
12
+ repo: RepoRef;
13
+ config: BotConfig;
14
+ }
15
+ declare const TOOLS: Tool[];
16
+ export { TOOLS };