forked from anomalyco/opencode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapply.ts
More file actions
706 lines (602 loc) · 21.4 KB
/
apply.ts
File metadata and controls
706 lines (602 loc) · 21.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
#!/usr/bin/env bun
/**
* Branding Application Script
*
* This script applies branding transformations to the opencode codebase.
* It's designed to work with any future version of opencode by using
* pattern-based replacements rather than hardcoded line numbers.
*
* Usage:
* bun branding/apply.ts <brand-id> [--dry-run] [--verbose]
*
* Example:
* bun branding/apply.ts qbraid
* bun branding/apply.ts qbraid --dry-run
*/
import { parseArgs } from "util"
import path from "path"
import fs from "fs/promises"
import { Glob } from "bun"
import { BrandingSchema, type Branding } from "./schema"
const { values, positionals } = parseArgs({
args: Bun.argv.slice(2),
options: {
"dry-run": { type: "boolean", default: false },
verbose: { type: "boolean", short: "v", default: false },
help: { type: "boolean", short: "h", default: false },
},
allowPositionals: true,
})
if (values.help || positionals.length === 0) {
console.log(`
Usage: bun branding/apply.ts <brand-id> [options]
Arguments:
brand-id The brand configuration to apply (e.g., "qbraid")
Options:
--dry-run Preview changes without modifying files
--verbose Show detailed output
--help Show this help message
Examples:
bun branding/apply.ts qbraid
bun branding/apply.ts qbraid --dry-run --verbose
`)
process.exit(0)
}
const brandId = positionals[0]
const dryRun = values["dry-run"]
const verbose = values.verbose
const ROOT = path.resolve(import.meta.dir, "..")
const BRAND_DIR = path.join(import.meta.dir, brandId)
const BRAND_CONFIG = path.join(BRAND_DIR, "brand.json")
// Statistics
const stats = {
filesScanned: 0,
filesModified: 0,
replacements: 0,
}
function log(msg: string) {
if (verbose) console.log(msg)
}
function info(msg: string) {
console.log(`\x1b[36m${msg}\x1b[0m`)
}
function success(msg: string) {
console.log(`\x1b[32m${msg}\x1b[0m`)
}
function warn(msg: string) {
console.log(`\x1b[33m${msg}\x1b[0m`)
}
function error(msg: string) {
console.error(`\x1b[31m${msg}\x1b[0m`)
}
async function loadConfig(): Promise<Branding> {
const exists = await Bun.file(BRAND_CONFIG).exists()
if (!exists) {
error(`Brand configuration not found: ${BRAND_CONFIG}`)
process.exit(1)
}
const json = await Bun.file(BRAND_CONFIG).json()
const result = BrandingSchema.safeParse(json)
if (!result.success) {
error("Invalid brand configuration:")
console.error(result.error.format())
process.exit(1)
}
return result.data
}
function shouldSkip(filePath: string, skipPatterns: string[]): boolean {
const relative = path.relative(ROOT, filePath)
for (const pattern of skipPatterns) {
const glob = new Glob(pattern)
if (glob.match(relative)) return true
}
return false
}
interface Replacement {
search: string | RegExp
replace: string
description: string
}
function buildReplacements(config: Branding): Replacement[] {
const r = config.replacements
const replacements: Replacement[] = []
// Product name replacements (case-sensitive)
// Use negative lookbehind/lookahead to avoid matching:
// - @opencode-ai package names
// - Directory paths like /opencode/ (but allow /bin/opencode at end of path)
// - File extensions like opencode.json
// - Third-party packages like @gitlab/opencode-gitlab-auth
replacements.push({
search: /(?<!@)(?<!\/opencode)opencode(?!-ai|\/|\.(json|ts|tsx|js)|-gitlab-auth)/g,
replace: r.productName,
description: `opencode -> ${r.productName}`,
})
replacements.push({
search: /\bOpenCode\b/g,
replace: r.displayName,
description: `OpenCode -> ${r.displayName}`,
})
replacements.push({
search: /\bOPENCODE\b/g,
replace: r.envPrefix,
description: `OPENCODE -> ${r.envPrefix}`,
})
// NPM package name - NOTE: We do NOT rename @opencode-ai/ workspace imports
// since those are internal package references that need to stay as-is
// Only rename the published package name in specific contexts
if (r.npmPackage) {
// Only rename opencode-ai when NOT preceded by @ (to preserve workspace refs)
replacements.push({
search: /(?<!@)opencode-ai(?!\/)/g,
replace: r.npmPackage,
description: `opencode-ai -> ${r.npmPackage}`,
})
}
// URL replacements
if (r.urls?.website) {
replacements.push({
search: /https:\/\/opencode\.ai/g,
replace: r.urls.website,
description: `opencode.ai -> ${r.urls.website}`,
})
}
if (r.urls?.api) {
replacements.push({
search: /https:\/\/api\.opencode\.ai/g,
replace: r.urls.api,
description: `api.opencode.ai -> ${r.urls.api}`,
})
replacements.push({
search: /https:\/\/api\.dev\.opencode\.ai/g,
replace: r.urls.api,
description: `api.dev.opencode.ai -> ${r.urls.api}`,
})
}
if (r.urls?.github) {
replacements.push({
search: /https:\/\/github\.com\/anomalyco\/opencode/g,
replace: r.urls.github,
description: `github repo -> ${r.urls.github}`,
})
}
return replacements
}
async function applyReplacements(filePath: string, replacements: Replacement[]): Promise<boolean> {
const content = await Bun.file(filePath).text()
let modified = content
for (const { search, replace, description } of replacements) {
const before = modified
modified = modified.replace(search, replace)
if (before !== modified) {
log(` ${description}`)
stats.replacements++
}
}
if (modified !== content) {
if (!dryRun) {
await Bun.write(filePath, modified)
}
return true
}
return false
}
// File-specific transformations
interface FileTransform {
pattern: string
transform: (content: string, config: Branding) => string | Promise<string>
}
const FILE_TRANSFORMS: FileTransform[] = [
// CLI logo.ts - update the logo export
{
pattern: "packages/opencode/src/cli/logo.ts",
transform: (content, config) => {
// Replace the logo export with qbraid logo
const leftStr = config.logo.tui.left.map((l) => `"${l}"`).join(", ")
const rightStr = config.logo.tui.right.map((l) => `"${l}"`).join(", ")
return `export const logo = {
left: [${leftStr}],
right: [${rightStr}],
}
export const marks = "_^~"
`
},
},
// CLI UI logo() function - update to render Q in purple
// IMPORTANT: LOGO must be defined INSIDE the logo() function, not at module scope.
// The UI namespace compiles to an IIFE in the bundled binary, and module-scope
// const declarations are not accessible inside the IIFE.
{
pattern: "packages/opencode/src/cli/ui.ts",
transform: (content, config) => {
const logoStr = config.logo.cli.map((row) => ` [\`${row[0]}\`, \`${row[1]}\`],`).join("\n")
// Replace the logo() function with LOGO defined as a local constant inside it
const result = content.replace(
/export function logo\(pad\?: string\) \{[\s\S]*?return result\.join\(""\)\.trimEnd\(\)\n \}/,
`export function logo(pad?: string) {
const LOGO = [
${logoStr}
]
const result: string[] = []
const reset = "\\x1b[0m"
const left = {
fg: Bun.color("gray", "ansi") ?? "",
shadow: "\\x1b[38;5;235m",
bg: "\\x1b[48;5;235m",
}
const PURPLE = "\\x1b[38;2;147;112;219m" // Medium purple RGB for Q
for (const row of LOGO) {
if (pad) result.push(pad)
result.push(left.fg)
result.push(row[0])
result.push(reset)
result.push(PURPLE) // Purple for the Q
result.push(row[1])
result.push(reset)
result.push(EOL)
}
return result.join("").trimEnd()
}`
)
return result
},
},
// TUI logo component with purple Q
{
pattern: "packages/opencode/src/cli/cmd/tui/component/logo.tsx",
transform: (content, config) => {
const left = config.logo.tui.left.map((l) => `\`${l}\``).join(", ")
const right = config.logo.tui.right.map((l) => `\`${l}\``).join(", ")
let result = content.replace(/const LOGO_LEFT = \[[\s\S]*?\]/, `const LOGO_LEFT = [${left}]`)
result = result.replace(/const LOGO_RIGHT = \[[\s\S]*?\]/, `const LOGO_RIGHT = [${right}]`)
// Add RGBA import if not already there, and add purple constant
result = result.replace(
/import \{ TextAttributes, RGBA \} from "@opentui\/core"/,
`import { TextAttributes, RGBA } from "@opentui/core"
// Purple color for the Q (qBraid branding)
const PURPLE = RGBA.fromHex("#9370DB")`,
)
// Use purple instead of theme.text for the right side (Q)
result = result.replace(
/\{renderLine\(LOGO_RIGHT\[index\(\)\], theme\.text, true\)\}/,
`{renderLine(LOGO_RIGHT[index()], PURPLE, true)}`,
)
return result
},
},
// Global app directory
{
pattern: "packages/opencode/src/global/index.ts",
transform: (content, config) => {
return content.replace(/const app = "opencode"/, `const app = "${config.replacements.appDir}"`)
},
},
// Package.json binary
{
pattern: "packages/opencode/package.json",
transform: (content, config) => {
const pkg = JSON.parse(content)
const bin = config.replacements.binaryName
// Update binary name
pkg.bin = { [bin]: `./bin/${bin}` }
pkg.name = config.replacements.npmPackage || config.replacements.productName
return JSON.stringify(pkg, null, 2) + "\n"
},
},
// CLI entry point script name
{
pattern: "packages/opencode/src/index.ts",
transform: (content, config) => {
return content.replace(/\.scriptName\("opencode"\)/, `.scriptName("${config.replacements.binaryName}")`)
},
},
// Model provider configuration
// When exclusive=true: replace get() to return only embedded models (original behavior)
// When default=true, exclusive=false: prepend branded models to the models.dev response
{
pattern: "packages/opencode/src/provider/models.ts",
transform: async (content, config) => {
if (!config.models?.source) return content
const modelsPath = path.join(BRAND_DIR, config.models.source.replace("./", ""))
const modelsFile = Bun.file(modelsPath)
if (!(await modelsFile.exists())) {
warn(`Models file not found: ${modelsPath}`)
return content
}
const modelsJson = await modelsFile.json()
delete modelsJson.$schema
delete modelsJson._comment
if (config.models.exclusive) {
// Exclusive mode: only branded models, no models.dev fetch
const result = content.replace(
/export async function get\(\) \{[\s\S]*?\n \}/,
`export async function get() {
// Branding: embedded models (exclusive mode, no external fetch)
return ${JSON.stringify(modelsJson)} as Record<string, Provider>
}`,
)
if (result === content) {
throw new Error("models.ts branding transform failed: get() regex did not match (exclusive mode)")
}
return result
}
// Default mode: prepend branded models, then merge models.dev data
// This ensures qBraid models appear first and are the defaults,
// while all upstream providers (Anthropic, OpenAI, Copilot, Codex, etc.)
// remain available.
//
// The replacement body references variables from the original models.ts scope:
// - filepath (const, path to cache file)
// - data (Bun macro import for bundled snapshot)
// - refresh() (background fetch to update cache)
const brandedModelsStr = JSON.stringify(modelsJson)
const result = content.replace(
/export async function get\(\) \{[\s\S]*?\n \}/,
`export async function get() {
// Branding: qBraid models prepended as defaults
const branded = ${brandedModelsStr} as Record<string, Provider>
// Kick off background cache refresh
refresh()
// Try cached models first, then macro bundle, then live fetch
let upstream: Record<string, Provider> = {}
try {
const file = Bun.file(filepath)
const cached = await file.json().catch(() => undefined)
if (cached) {
upstream = cached as Record<string, Provider>
} else if (typeof data === "function") {
upstream = JSON.parse(await data()) as Record<string, Provider>
} else {
const json = await fetch("https://models.dev/api.json").then((x) => x.text())
upstream = JSON.parse(json) as Record<string, Provider>
}
} catch {
// All upstream sources failed — branded models only
}
// Merge: branded providers win on conflict
return { ...upstream, ...branded }
}`,
)
if (result === content) {
throw new Error("models.ts branding transform failed: get() regex did not match. Has the upstream function signature changed?")
}
return result
},
},
// Provider loaders - remove opencode provider if requested
{
pattern: "packages/opencode/src/provider/provider.ts",
transform: (content, config) => {
if (!config.models?.removeProviders?.includes("opencode")) return content
// Remove the opencode custom loader
const loaderRegex = /async opencode\(input\) \{[\s\S]*?\n \},/
return content.replace(loaderRegex, "// opencode provider removed by branding")
},
},
// Remove builtin plugins only in exclusive mode.
// In default mode (exclusive=false), keep plugins so Anthropic auth,
// Codex OAuth, Copilot device code, etc. continue to work.
{
pattern: "packages/opencode/src/plugin/index.ts",
transform: (content, config) => {
if (!config.models?.exclusive) return content
const result = content.replace(
/const BUILTIN = \["[^"]*"(?:,\s*"[^"]*")*\]/,
"const BUILTIN: string[] = [] // Cleared by branding - no external plugins",
)
if (result === content) {
throw new Error("plugin/index.ts branding transform failed: BUILTIN regex did not match")
}
return result
},
},
// Remove custom loaders only in exclusive mode.
// In default mode, keep all loaders — they're needed for native provider support
// (Anthropic, OpenAI, Bedrock, Copilot, etc.).
{
pattern: "packages/opencode/src/provider/provider.ts",
transform: (content, config) => {
if (!config.models?.exclusive) return content
const result = content.replace(
/const CUSTOM_LOADERS: Record<string, CustomLoader> = \{[\s\S]*?\n \}(?=\n\n export const Model)/,
`const CUSTOM_LOADERS: Record<string, CustomLoader> = {
// All custom loaders removed by branding (exclusive mode)
}`,
)
if (result === content) {
throw new Error("provider.ts branding transform failed: CUSTOM_LOADERS regex did not match")
}
return result
},
},
// System prompts - update branding and add qBraid description
{
pattern: "packages/opencode/src/session/prompt/anthropic.txt",
transform: (content, config) => {
return content.replace(
/You are OpenCode, the best coding agent on the planet\./,
`You are CodeQ, built by qBraid - the leading quantum software company. You are the universe's most powerful coding agent.`,
)
},
},
{
pattern: "packages/opencode/src/session/prompt/anthropic-20250930.txt",
transform: (content, config) => {
return content.replace(
/You are OpenCode, the best coding agent on the planet\./,
`You are CodeQ, built by qBraid - the leading quantum software company. You are the universe's most powerful coding agent.`,
)
},
},
{
pattern: "packages/opencode/src/session/prompt/gemini.txt",
transform: (content, config) => {
return content.replace(
/You are OpenCode, the best coding agent on the planet\./,
`You are CodeQ, built by qBraid - the leading quantum software company. You are the universe's most powerful coding agent.`,
)
},
},
{
pattern: "packages/opencode/src/session/prompt/beast.txt",
transform: (content, config) => {
return content.replace(
/You are OpenCode, the best coding agent on the planet\./,
`You are CodeQ, built by qBraid - the leading quantum software company. You are the universe's most powerful coding agent.`,
)
},
},
{
pattern: "packages/opencode/src/session/prompt/qwen.txt",
transform: (content, config) => {
return content.replace(
/You are OpenCode, the best coding agent on the planet\./,
`You are CodeQ, built by qBraid - the leading quantum software company. You are the universe's most powerful coding agent.`,
)
},
},
{
pattern: "packages/opencode/src/session/prompt/copilot-gpt-5.txt",
transform: (content, config) => {
return content.replace(
/You are OpenCode, the best coding agent on the planet\./,
`You are CodeQ, built by qBraid - the leading quantum software company. You are the universe's most powerful coding agent.`,
)
},
},
]
async function applyFileTransform(filePath: string, config: Branding): Promise<boolean> {
const relative = path.relative(ROOT, filePath)
let content = await Bun.file(filePath).text()
let anyModified = false
// Apply ALL matching transforms for this file (not just the first one)
for (const { pattern, transform } of FILE_TRANSFORMS) {
if (relative === pattern || relative.endsWith(pattern)) {
const modified = await transform(content, config)
if (modified !== content) {
content = modified
anyModified = true
log(` Applied file transform for pattern: ${pattern}`)
}
}
}
if (anyModified && !dryRun) {
await Bun.write(filePath, content)
}
return anyModified
}
async function applyCustomPatches(config: Branding): Promise<void> {
if (!config.patches) return
for (const [filePath, patches] of Object.entries(config.patches)) {
const fullPath = path.join(ROOT, filePath)
const exists = await Bun.file(fullPath).exists()
if (!exists) {
warn(`Patch target not found: ${filePath}`)
continue
}
let content = await Bun.file(fullPath).text()
let modified = false
for (const patch of patches) {
const search = patch.regex ? new RegExp(patch.search, "g") : patch.search
const before = content
content = content.replace(search, patch.replace)
if (before !== content) modified = true
}
if (modified) {
if (!dryRun) {
await Bun.write(fullPath, content)
}
info(`Patched: ${filePath}`)
stats.filesModified++
}
}
}
async function renameBinaryFile(config: Branding): Promise<void> {
const oldBin = path.join(ROOT, "packages/opencode/bin/opencode")
const newBin = path.join(ROOT, `packages/opencode/bin/${config.replacements.binaryName}`)
const exists = await Bun.file(oldBin).exists()
if (!exists) {
warn(`Binary file not found: ${oldBin}`)
return
}
if (oldBin !== newBin) {
if (!dryRun) {
await fs.rename(oldBin, newBin)
}
info(`Renamed binary: opencode -> ${config.replacements.binaryName}`)
}
}
async function createModelsOverride(config: Branding): Promise<void> {
if (!config.models?.providers) return
const overridePath = path.join(BRAND_DIR, "models-override.json")
if (!dryRun) {
await Bun.write(overridePath, JSON.stringify(config.models.providers, null, 2))
}
info(`Created models override: ${path.relative(ROOT, overridePath)}`)
}
async function processDirectory(dir: string, config: Branding, replacements: Replacement[]): Promise<void> {
const skipPatterns = config.skipFiles || []
const entries = await fs.readdir(dir, { withFileTypes: true })
for (const entry of entries) {
const fullPath = path.join(dir, entry.name)
// Skip common non-source directories
if (entry.isDirectory()) {
if (["node_modules", ".git", "dist", "build", ".turbo", ".next"].includes(entry.name)) {
continue
}
await processDirectory(fullPath, config, replacements)
continue
}
// Only process relevant file types
const ext = path.extname(entry.name)
if (![".ts", ".tsx", ".js", ".jsx", ".json", ".md", ".toml", ".sh", ".txt"].includes(ext)) {
continue
}
// Check skip patterns
if (shouldSkip(fullPath, skipPatterns)) {
log(`Skipping: ${path.relative(ROOT, fullPath)}`)
continue
}
stats.filesScanned++
// Apply file-specific transforms first
let modified = await applyFileTransform(fullPath, config)
// Then apply general replacements
const replacementModified = await applyReplacements(fullPath, replacements)
if (modified || replacementModified) {
info(`Modified: ${path.relative(ROOT, fullPath)}`)
stats.filesModified++
}
}
}
async function main() {
info(`\nApplying branding: ${brandId}`)
if (dryRun) warn("(dry run - no files will be modified)\n")
const config = await loadConfig()
const replacements = buildReplacements(config)
info(`\nProcessing source files...`)
await processDirectory(path.join(ROOT, "packages"), config, replacements)
info(`\nApplying custom patches...`)
await applyCustomPatches(config)
info(`\nRenaming binary...`)
await renameBinaryFile(config)
info(`\nCreating models override...`)
await createModelsOverride(config)
success(`
Branding complete!
Files scanned: ${stats.filesScanned}
Files modified: ${stats.filesModified}
Replacements: ${stats.replacements}
${dryRun ? "\n(This was a dry run - run without --dry-run to apply changes)" : ""}
`)
if (!dryRun) {
info(`
Next steps:
1. Review the changes with: git diff
2. Build the branded version: bun run build
3. Test the binary: ./packages/opencode/bin/${config.replacements.binaryName}
`)
}
}
main().catch((e) => {
error(`Error: ${e.message}`)
process.exit(1)
})