pantheon-opencode 1.6.0 → 1.6.2-beta.1

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.
Files changed (115) hide show
  1. package/AGENTS.global.md +11 -11
  2. package/AGENTS.md +2 -2
  3. package/CHANGELOG.md +45 -0
  4. package/README.md +122 -6
  5. package/README.pt-BR.md +14 -9
  6. package/bin/pantheon-init.mjs +255 -39
  7. package/package.json +8 -6
  8. package/plugin.json +1 -1
  9. package/pyproject.toml +1 -1
  10. package/scripts/build-agents-md.mjs +1 -1
  11. package/scripts/doctor.mjs +231 -46
  12. package/scripts/install/agents-md.mjs +2 -1
  13. package/scripts/install/config-migration.mjs +344 -393
  14. package/scripts/install/config-paths.mjs +15 -0
  15. package/scripts/install/interactive.mjs +30 -9
  16. package/scripts/install/interrupt.mjs +78 -0
  17. package/scripts/install/mcp-permissions.mjs +164 -0
  18. package/scripts/install/opencode-state.mjs +91 -0
  19. package/scripts/install/opencode-version.mjs +31 -13
  20. package/scripts/install/opencode-wildcard.mjs +106 -0
  21. package/scripts/install/opencode.mjs +508 -108
  22. package/scripts/install/plan-artifact.mjs +12 -1
  23. package/scripts/install/plugin.mjs +17 -1
  24. package/scripts/install/run-record.mjs +115 -0
  25. package/scripts/install/strings.mjs +35 -6
  26. package/scripts/install/v2-capabilities.mjs +204 -0
  27. package/scripts/package-evidence.mjs +1 -0
  28. package/scripts/release-gates.mjs +7 -2
  29. package/scripts/sandbox-env.sh +174 -0
  30. package/scripts/setup-v2-config.mjs +1703 -0
  31. package/scripts/setup.mjs +415 -0
  32. package/scripts/sync-tui.mjs +9 -1
  33. package/scripts/test-opencode-v2-sandbox.sh +438 -151
  34. package/scripts/update-skills-lock.mjs +30 -0
  35. package/skills-lock.json +10 -10
  36. package/src/agents/aphrodite.md +5 -2
  37. package/src/agents/apollo.md +5 -0
  38. package/src/agents/athena.md +6 -1
  39. package/src/agents/demeter.md +5 -1
  40. package/src/agents/gaia.md +4 -0
  41. package/src/agents/hephaestus.md +6 -1
  42. package/src/agents/hermes.md +6 -3
  43. package/src/agents/iris.md +5 -1
  44. package/src/agents/mnemosyne.md +20 -50
  45. package/src/agents/nyx.md +5 -1
  46. package/src/agents/prometheus.md +4 -0
  47. package/src/agents/talos.md +4 -0
  48. package/src/agents/themis.md +4 -0
  49. package/src/agents/zeus.md +9 -3
  50. package/src/instructions/agent-return-format.instructions.md +1 -1
  51. package/src/instructions/memory-protocol.instructions.md +3 -3
  52. package/src/instructions/test-economy.instructions.md +6 -6
  53. package/src/mcp/pantheon_vision.py +37 -36
  54. package/src/mcp/requirements-mcp.txt +1 -1
  55. package/src/mcp/requirements-vision.txt +1 -1
  56. package/src/pantheon/cost-command.ts +127 -40
  57. package/src/pantheon/delegation-enforce.ts +160 -23
  58. package/src/pantheon/guard-path.ts +162 -0
  59. package/src/pantheon/v2-bounded-read.ts +15 -1
  60. package/src/pantheon/v2-bridge.ts +27 -0
  61. package/src/pantheon/v2-shell-hooks.ts +260 -0
  62. package/src/pantheon/v2-unsupported.mjs +32 -4
  63. package/src/pantheon/v2-vision.ts +34 -29
  64. package/src/pantheon/vision.ts +49 -11
  65. package/src/plugin-v2.ts +413 -60
  66. package/src/plugin.ts +22 -2
  67. package/src/plugins/tui/dist/quota-adapters.d.ts +89 -0
  68. package/src/plugins/tui/dist/quota-adapters.d.ts.map +1 -0
  69. package/src/plugins/tui/dist/quota-adapters.js +1142 -0
  70. package/src/plugins/tui/dist/quota-adapters.js.map +1 -0
  71. package/src/plugins/tui/dist/quota-cli.d.ts +17 -0
  72. package/src/plugins/tui/dist/quota-cli.d.ts.map +1 -0
  73. package/src/plugins/tui/dist/quota-cli.js +184 -0
  74. package/src/plugins/tui/dist/quota-cli.js.map +1 -0
  75. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js +390 -0
  76. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js.map +1 -0
  77. package/src/plugins/tui/dist/server-v2.d.ts +14 -0
  78. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -0
  79. package/src/plugins/tui/dist/server-v2.js +673 -0
  80. package/src/plugins/tui/dist/server-v2.js.map +1 -0
  81. package/src/plugins/tui/dist/tui-v2.d.ts +247 -52
  82. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  83. package/src/plugins/tui/dist/tui-v2.js +2492 -529
  84. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  85. package/src/plugins/tui/dist/tui.js +1 -1
  86. package/src/plugins/tui/index-v2.ts +3 -6
  87. package/src/plugins/tui/package-lock.json +11 -11
  88. package/src/plugins/tui/package.json +6 -4
  89. package/src/plugins/tui/src/context-gauge.ts +59 -0
  90. package/src/plugins/tui/src/go-key-diagnostic-ui.ts +100 -0
  91. package/src/plugins/tui/src/go-key-diagnostic.ts +125 -0
  92. package/src/plugins/tui/src/index-v2.tsx +199 -240
  93. package/src/plugins/tui/src/model-usage-limits.ts +4 -0
  94. package/src/plugins/tui/src/quota-adapters.ts +1598 -0
  95. package/src/plugins/tui/src/quota-cli.ts +237 -0
  96. package/src/plugins/tui/src/quota-rpc.ts +209 -0
  97. package/src/plugins/tui/src/quota-v2-model.ts +1032 -0
  98. package/src/plugins/tui/src/quota-v2.tsx +986 -0
  99. package/src/plugins/tui/src/server-v2.ts +841 -0
  100. package/src/plugins/tui/src/sidebar-width.ts +129 -0
  101. package/src/plugins/tui/tsconfig.typecheck.json +1 -1
  102. package/src/plugins/tui/tsdown.config.ts +8 -1
  103. package/src/routing.yml +72 -13
  104. package/src/skills/README.md +4 -0
  105. package/src/skills/agent-coordination/SKILL.md +0 -3
  106. package/src/skills/artifact-management/SKILL.md +0 -3
  107. package/src/skills/auto-continue/SKILL.md +0 -3
  108. package/src/skills/code-review-checklist/SKILL.md +0 -3
  109. package/src/skills/context-compression/SKILL.md +0 -3
  110. package/src/skills/memory-bank/SKILL.md +6 -28
  111. package/src/skills/session-goal/SKILL.md +0 -3
  112. package/src/skills/simplify/SKILL.md +5 -4
  113. package/src/skills/tdd-with-agents/SKILL.md +0 -3
  114. package/src/skills/visual-review-pipeline/SKILL.md +0 -1
  115. package/src/pantheon/memory-context.ts +0 -1017
@@ -0,0 +1,15 @@
1
+ import os from 'node:os'
2
+ import path from 'node:path'
3
+
4
+ /** Resolve the global OpenCode config directory used by init and setup. */
5
+ export function resolveGlobalConfigDirectory(env = process.env, home = os.homedir()) {
6
+ const xdgConfigHome = env.XDG_CONFIG_HOME
7
+ if (
8
+ xdgConfigHome !== undefined &&
9
+ xdgConfigHome !== '' &&
10
+ (typeof xdgConfigHome !== 'string' || !path.isAbsolute(xdgConfigHome))
11
+ ) {
12
+ throw new Error('XDG_CONFIG_HOME must be an absolute path.')
13
+ }
14
+ return path.join(xdgConfigHome || path.join(home, '.config'), 'opencode')
15
+ }
@@ -2,6 +2,7 @@
2
2
 
3
3
  import * as clack from '@clack/prompts'
4
4
  import { PROMPT_CANCELED } from './prompt-result.mjs'
5
+ import { strings } from './strings.mjs'
5
6
 
6
7
  export { PROMPT_CANCELED }
7
8
 
@@ -9,9 +10,21 @@ function isTerminal() {
9
10
  return Boolean(process.stdin.isTTY && process.stdout.isTTY)
10
11
  }
11
12
 
12
- function cancelPrompt(prompts, value) {
13
+ /**
14
+ * Print the ONE cancel line, naming where the user stopped.
15
+ *
16
+ * The point is a stable key from the string table (`cancelPoints`), so the same
17
+ * identifier can be persisted in the run record without parsing prose.
18
+ *
19
+ * @param {typeof clack} prompts
20
+ * @param {unknown} value a prompt result
21
+ * @param {string} point stable cancel-point key
22
+ * @returns {boolean} whether the prompt was canceled
23
+ */
24
+ function cancelPrompt(prompts, value, point) {
13
25
  if (!prompts.isCancel(value)) return false
14
- prompts.cancel('Installation canceled.')
26
+ const S = strings()
27
+ prompts.cancel(S.canceledAt(S.cancelPoints[point] ?? point))
15
28
  return true
16
29
  }
17
30
 
@@ -28,7 +41,7 @@ export async function promptReview(
28
41
  ) {
29
42
  if (!isTTY) return false
30
43
  const result = await prompts.confirm({ message: planSummary, initialValue: defaultValue })
31
- if (cancelPrompt(prompts, result)) return PROMPT_CANCELED
44
+ if (cancelPrompt(prompts, result, 'review')) return PROMPT_CANCELED
32
45
  return result === true
33
46
  }
34
47
 
@@ -36,7 +49,11 @@ export async function promptReview(
36
49
  * Collect interactive setup choices before the installer begins any writes.
37
50
  *
38
51
  * @param {{ components?: string[], defaultComponents?: string[], noMcp?: boolean, prompts?: typeof clack, isTTY?: boolean }} [options]
39
- * @returns {Promise<{ components?: Set<string>, target?: string, confirmed?: boolean, canceled?: boolean }>}
52
+ * @returns {Promise<{ components?: Set<string>, target?: string, confirmed?: boolean, canceled?: boolean, cancelPoint?: string }>}
53
+ *
54
+ * `cancelPoint` names the step the user stopped at (`components`, `target`,
55
+ * `confirmation`), so the caller can print one explainable line and persist the
56
+ * same stable key in the run record.
40
57
  */
41
58
  export async function runInteractiveInstall({
42
59
  components = [],
@@ -70,12 +87,14 @@ export async function runInteractiveInstall({
70
87
  initialValues: [...defaultSet],
71
88
  required: false,
72
89
  })
73
- if (cancelPrompt(prompts, chosen)) return { canceled: true }
90
+ if (cancelPrompt(prompts, chosen, 'components'))
91
+ return { canceled: true, cancelPoint: 'components' }
74
92
 
75
93
  const selectedComponents = new Set(chosen.filter(isAllowed))
76
94
  if (selectedComponents.size === 0) {
77
- prompts.cancel?.('No components selected. Installation canceled.')
78
- return { canceled: true }
95
+ const S = strings()
96
+ prompts.cancel?.(S.canceledAt(S.cancelPoints.components))
97
+ return { canceled: true, cancelPoint: 'components' }
79
98
  }
80
99
 
81
100
  const target = await prompts.select({
@@ -89,13 +108,15 @@ export async function runInteractiveInstall({
89
108
  { label: 'Current project', value: 'project', hint: './.opencode (scoped to this project)' },
90
109
  ],
91
110
  })
92
- if (cancelPrompt(prompts, target)) return { canceled: true }
111
+ if (cancelPrompt(prompts, target, 'target')) return { canceled: true, cancelPoint: 'target' }
93
112
 
94
113
  const confirmed = await prompts.confirm({
95
114
  message: `Install ${selectedComponents.size} component(s) in ${target === 'global' ? 'global config' : 'current project'}?`,
96
115
  initialValue: true,
97
116
  })
98
- if (cancelPrompt(prompts, confirmed)) return { canceled: true }
117
+ if (cancelPrompt(prompts, confirmed, 'confirmation')) {
118
+ return { canceled: true, cancelPoint: 'confirmation' }
119
+ }
99
120
 
100
121
  return { components: selectedComponents, target, confirmed }
101
122
  }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * interrupt.mjs — Ctrl-C behaves like every other cancel, for the window in
3
+ * which the installer is actually working.
4
+ *
5
+ * Before this existed, NOTHING under `bin/` or `scripts/install/` handled
6
+ * SIGINT: an interrupted install died by default action, printed no reason, and
7
+ * left no trace — the user could not tell an interrupt from a crash, and a
8
+ * re-run could not tell what the previous attempt did. The prompt library
9
+ * consumes Ctrl-C in raw mode while a question is on screen, so this covers the
10
+ * rest of the run (backup, copies, config write, state write).
11
+ *
12
+ * LIFETIME MATTERS AS MUCH AS THE MESSAGE: the handler is registered when the
13
+ * install starts and must be DEACTIVATED once the run has been recorded. Left
14
+ * registered, a Ctrl-C during the post-install `--doctor` step would rewrite a
15
+ * COMPLETED install as `canceled / applied:false` and claim nothing was
16
+ * applied. {@link createInterruptHandler} therefore owns its registration and
17
+ * exposes `deactivate()` for the caller to call at that point.
18
+ *
19
+ * Contract, all of it pinned by tests:
20
+ * - exactly ONE message is printed, and it names the interrupt as the point;
21
+ * - with `--json`, the message goes to stderr so stdout stays parsable;
22
+ * - the outcome is recorded once (a second Ctrl-C must not record twice);
23
+ * - the exit code is 130, the documented "canceled" code;
24
+ * - after `deactivate()`, the signal is no longer handled at all.
25
+ *
26
+ * Kept injectable rather than reading globals so the exit code, the streams,
27
+ * the emitter and the record call are all observable in a unit test.
28
+ *
29
+ * @module interrupt
30
+ */
31
+
32
+ /**
33
+ * Build and REGISTER a SIGINT handler.
34
+ *
35
+ * @param {{
36
+ * message: string,
37
+ * json?: boolean,
38
+ * onInterrupt?: () => void,
39
+ * endGaugeLine?: () => void,
40
+ * writeStderr?: (line: string) => void,
41
+ * logStderr?: (line: string) => void,
42
+ * exit?: (code: number) => void,
43
+ * emitter?: { once: (event: string, listener: () => void) => unknown, removeListener: (event: string, listener: () => void) => unknown },
44
+ * }} options
45
+ * @returns {(() => void) & { deactivate: () => void }} the registered handler
46
+ */
47
+ export function createInterruptHandler({
48
+ message,
49
+ json = false,
50
+ onInterrupt = () => {},
51
+ endGaugeLine = () => {},
52
+ writeStderr = (line) => process.stderr.write(`${line}\n`),
53
+ logStderr = (line) => console.error(line),
54
+ exit = (code) => process.exit(code),
55
+ emitter = process,
56
+ }) {
57
+ let handled = false
58
+ const handle = function handleInterrupt() {
59
+ if (handled) return
60
+ handled = true
61
+ try {
62
+ // The progress gauge owns the current terminal line; close it so the
63
+ // message is not appended to a half-drawn bar and then erased.
64
+ endGaugeLine()
65
+ if (json) writeStderr(message)
66
+ else logStderr(message)
67
+ onInterrupt()
68
+ } finally {
69
+ exit(130)
70
+ }
71
+ }
72
+ /** Stop handling SIGINT: the run this handler described is over. */
73
+ handle.deactivate = () => {
74
+ emitter.removeListener('SIGINT', handle)
75
+ }
76
+ emitter.once('SIGINT', handle)
77
+ return handle
78
+ }
@@ -0,0 +1,164 @@
1
+ import { opencodeWildcardPatternsOverlap } from './opencode-wildcard.mjs'
2
+
3
+ /** Canonical OpenCode V2 MCP action-name normalization shared by all writers. */
4
+
5
+ export function normalizeMcpPermissionSegment(value) {
6
+ return value.replace(/[^a-zA-Z0-9_]/g, '_')
7
+ }
8
+
9
+ /** V1 spellings support V1 hosts; normalized spellings are required by V2. */
10
+ export function mcpPermissionAliases(value) {
11
+ return [...new Set([value, normalizeMcpPermissionSegment(value)])]
12
+ }
13
+
14
+ export function mcpServerPermissionActions(server) {
15
+ return mcpPermissionAliases(server).map((alias) => `${alias}_*`)
16
+ }
17
+
18
+ /**
19
+ * These generated action patterns are all fixed prefixes followed by `*`.
20
+ * Their languages intersect exactly when one fixed prefix contains the other.
21
+ */
22
+ export function mcpPermissionActionPatternsOverlap(left, right) {
23
+ return opencodeWildcardPatternsOverlap(left, right)
24
+ }
25
+
26
+ export function mcpServerPermissionScopesOverlap(left, right) {
27
+ return mcpServerPermissionActions(left).some((leftAction) =>
28
+ mcpServerPermissionActions(right).some((rightAction) =>
29
+ mcpPermissionActionPatternsOverlap(leftAction, rightAction),
30
+ ),
31
+ )
32
+ }
33
+
34
+ /** Refuse distinct V1 server names whose generated action globs overlap in V2. */
35
+ export function assertMcpServerPermissionScopesUnambiguous(rules) {
36
+ for (let leftIndex = 0; leftIndex < rules.length; leftIndex += 1) {
37
+ const left = rules[leftIndex]
38
+ for (let rightIndex = leftIndex + 1; rightIndex < rules.length; rightIndex += 1) {
39
+ const right = rules[rightIndex]
40
+ if (
41
+ left.server !== right.server &&
42
+ mcpServerPermissionScopesOverlap(left.server, right.server)
43
+ ) {
44
+ throw new TypeError(
45
+ 'Distinct MCP permission server scopes overlap after OpenCode V2 action normalization.',
46
+ )
47
+ }
48
+ }
49
+ }
50
+ }
51
+
52
+ /** Refuse policy scopes that also match a distinct configured MCP server. */
53
+ export function assertMcpPermissionScopesDoNotAliasConfiguredServers(
54
+ policyServers,
55
+ configuredServers,
56
+ ) {
57
+ for (const policyServer of policyServers) {
58
+ for (const configuredServer of configuredServers) {
59
+ if (
60
+ policyServer !== configuredServer &&
61
+ mcpServerPermissionScopesOverlap(policyServer, configuredServer)
62
+ ) {
63
+ throw new TypeError(
64
+ 'An MCP permission scope overlaps a distinct configured server after OpenCode V2 action normalization.',
65
+ )
66
+ }
67
+ }
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Agent MCP metadata emits default server denies and then explicit grants.
73
+ * Refuse grants that can also match a different server's denied action scope.
74
+ */
75
+ export function assertMcpPermissionServerGrantsUnambiguous(servers) {
76
+ const scopes = servers.map(({ server, tools }) => ({
77
+ server,
78
+ tools,
79
+ effect: tools === 'all' ? 'allow' : 'deny',
80
+ }))
81
+
82
+ for (let leftIndex = 0; leftIndex < scopes.length; leftIndex += 1) {
83
+ const left = scopes[leftIndex]
84
+ for (let rightIndex = leftIndex + 1; rightIndex < scopes.length; rightIndex += 1) {
85
+ const right = scopes[rightIndex]
86
+ if (
87
+ left.effect !== right.effect &&
88
+ mcpServerPermissionScopesOverlap(left.server, right.server)
89
+ ) {
90
+ throw new TypeError('Overlapping MCP permission scopes have conflicting agent effects.')
91
+ }
92
+ }
93
+ }
94
+
95
+ for (const grant of scopes) {
96
+ if (!Array.isArray(grant.tools)) continue
97
+ const grantActions = grant.tools.flatMap((tool) =>
98
+ mcpPermissionAliases(grant.server).flatMap((serverAlias) =>
99
+ mcpPermissionAliases(tool).map((toolAlias) => `${serverAlias}_${toolAlias}`),
100
+ ),
101
+ )
102
+ for (const deny of scopes) {
103
+ if (grant.server === deny.server || deny.effect !== 'deny') continue
104
+ if (
105
+ grantActions.some((action) =>
106
+ mcpServerPermissionActions(deny.server).some((scope) =>
107
+ mcpPermissionActionPatternsOverlap(action, scope),
108
+ ),
109
+ )
110
+ ) {
111
+ throw new TypeError('An MCP tool grant overlaps a different server deny scope.')
112
+ }
113
+ }
114
+ }
115
+ }
116
+
117
+ /** Refuse generated MCP allows that would replace an explicit agent deny/ask. */
118
+ export function assertMcpGeneratedPermissionsDoNotWeakenExplicitRules(explicit, generated) {
119
+ if (explicit === undefined) return
120
+ if (explicit === null || typeof explicit !== 'object' || Array.isArray(explicit)) {
121
+ throw new TypeError(
122
+ 'Explicit agent permissions must be an object when combined with mcp_tools.',
123
+ )
124
+ }
125
+
126
+ const grants = Object.entries(generated).filter(([, effect]) => effect === 'allow')
127
+ if (grants.length === 0) return
128
+
129
+ for (const [action, rule] of Object.entries(explicit)) {
130
+ if (!grants.some(([grantAction]) => opencodeWildcardPatternsOverlap(action, grantAction))) {
131
+ continue
132
+ }
133
+ const isResourceMap = rule !== null && typeof rule === 'object' && !Array.isArray(rule)
134
+ if (typeof rule !== 'string' && !isResourceMap) {
135
+ throw new TypeError(
136
+ 'An overlapping explicit agent permission cannot be safely combined with mcp_tools.',
137
+ )
138
+ }
139
+ const effects = typeof rule === 'string' ? [rule] : isResourceMap ? Object.values(rule) : []
140
+ if (effects.some((effect) => !['allow', 'ask', 'deny'].includes(effect))) {
141
+ throw new TypeError(
142
+ 'An overlapping explicit agent permission cannot be safely combined with mcp_tools.',
143
+ )
144
+ }
145
+ if (effects.some((effect) => effect === 'deny' || effect === 'ask')) {
146
+ throw new TypeError(
147
+ 'A generated MCP grant overlaps an explicit agent deny or ask permission.',
148
+ )
149
+ }
150
+ }
151
+ }
152
+
153
+ /** Refuse names whose V2-normalized action cannot distinguish their source. */
154
+ export function assertMcpPermissionNamesUnambiguous(names) {
155
+ const normalizedOwners = new Map()
156
+ for (const name of names) {
157
+ const normalized = normalizeMcpPermissionSegment(name)
158
+ const owner = normalizedOwners.get(normalized)
159
+ if (owner !== undefined && owner !== name) {
160
+ throw new TypeError('MCP names collide after OpenCode V2 permission normalization.')
161
+ }
162
+ normalizedOwners.set(normalized, name)
163
+ }
164
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * opencode-state.mjs — where an OpenCode host keeps its state, resolved once.
3
+ *
4
+ * WHY THIS MODULE EXISTS: the installer used to PRINT a hardcoded claim about
5
+ * state isolation (`~/.local/share/opencode/opencode-v2.db`, "open service port
6
+ * 49375"). Nothing in this package ever set `OPENCODE_DB`, no installer created
7
+ * that file, and no code bound that port — it was a sentence about a
8
+ * configuration that never existed outside a sandbox. A notice is a statement
9
+ * about the user's machine, so it has to be produced by the same rule the host
10
+ * and Pantheon's own database consumers use, not by a literal.
11
+ *
12
+ * THE RULE (mirrored from `resolveCostDbPath` in src/pantheon/cost-command.ts
13
+ * and from the credential-store lookup in scripts/vision-status.mjs):
14
+ *
15
+ * 1. `OPENCODE_DB` — an explicit file override (what a SANDBOX uses; it is
16
+ * also the only reason an `opencode-v2.db` name ever appears anywhere);
17
+ * 2. otherwise the XDG default `<data dir>/opencode.db`, where `<data dir>` is
18
+ * `$XDG_DATA_HOME/opencode` when `XDG_DATA_HOME` is set, else
19
+ * `~/.local/share/opencode`.
20
+ *
21
+ * There is deliberately NO per-generation filename and no per-generation port:
22
+ * both host generations read the same store, and the schema — not the filename
23
+ * — is what distinguishes their ledgers. `PANTHEON_COST_DB` is NOT part of this
24
+ * rule: it redirects the cost REPORT only, never the host's store.
25
+ *
26
+ * Plain Node ESM on purpose: this is consumed by the installer (no TypeScript)
27
+ * and by tests, and the equivalent TypeScript resolver is not importable there.
28
+ *
29
+ * @module opencode-state
30
+ */
31
+
32
+ import { homedir } from 'node:os'
33
+ import { join } from 'node:path'
34
+
35
+ /** The one filename every real installation writes. */
36
+ export const OPENCODE_DB_FILENAME = 'opencode.db'
37
+
38
+ /** Directory name under the XDG data root. */
39
+ export const OPENCODE_DATA_DIR_NAME = 'opencode'
40
+
41
+ /**
42
+ * OpenCode data directory: `$XDG_DATA_HOME/opencode` when set, else
43
+ * `~/.local/share/opencode`.
44
+ *
45
+ * @param {NodeJS.ProcessEnv} [env]
46
+ * @param {string} [home]
47
+ * @returns {string}
48
+ */
49
+ export function openCodeDataDir(env = process.env, home = homedir()) {
50
+ const configured = typeof env.XDG_DATA_HOME === 'string' ? env.XDG_DATA_HOME.trim() : ''
51
+ const dataHome = configured !== '' ? configured : join(home, '.local', 'share')
52
+ return join(dataHome, OPENCODE_DATA_DIR_NAME)
53
+ }
54
+
55
+ /**
56
+ * Resolve the host's state database the way the host does.
57
+ *
58
+ * Returns the path AND its source, because the two produce different honest
59
+ * wording: an `OPENCODE_DB` override is the user's own choice, while the XDG
60
+ * path is only this platform's documented default.
61
+ *
62
+ * @param {NodeJS.ProcessEnv} [env]
63
+ * @param {string} [home]
64
+ * @returns {{ path: string, source: 'OPENCODE_DB' | 'default' }}
65
+ */
66
+ export function resolveOpenCodeStatePath(env = process.env, home = homedir()) {
67
+ const override = typeof env.OPENCODE_DB === 'string' ? env.OPENCODE_DB.trim() : ''
68
+ if (override !== '') return { path: override, source: 'OPENCODE_DB' }
69
+ return { path: join(openCodeDataDir(env, home), OPENCODE_DB_FILENAME), source: 'default' }
70
+ }
71
+
72
+ /**
73
+ * One honest sentence about state sharing for the generation being installed.
74
+ *
75
+ * Both generations read one store, so "isolated" is never the right word. The
76
+ * sentence names the resolved path, says where that path came from, and states
77
+ * that Pantheon binds no service port (there is nothing to name).
78
+ *
79
+ * @param {NodeJS.ProcessEnv} [env]
80
+ * @param {string} [home]
81
+ * @returns {string}
82
+ */
83
+ export function describeSharedState(env = process.env, home = homedir()) {
84
+ const { path: dbPath, source } = resolveOpenCodeStatePath(env, home)
85
+ const origin = source === 'OPENCODE_DB' ? 'set by OPENCODE_DB' : 'the host default'
86
+ return (
87
+ `State is shared, not isolated per generation: OpenCode V1 and V2 read the same ` +
88
+ `store (${dbPath}; ${origin}). Pantheon configures no separate database and binds ` +
89
+ 'no service port.'
90
+ )
91
+ }
@@ -11,20 +11,38 @@ const VALID_VERSIONS = new Set(['v1', 'v2', 'auto'])
11
11
 
12
12
  /** @param {string[]} args @returns {'v1'|'v2'|'auto'|null} */
13
13
  export function parseOpenCodeVersion(args) {
14
- for (let index = 0; index < args.length; index += 1) {
15
- const arg = args[index]
16
- if (arg.startsWith('--opencode-version=')) return normalize(arg.split('=', 2)[1])
17
- if (arg === '--opencode-version') return normalize(args[index + 1])
18
- // --version v1|v2 was supported by 1.4.x. Bare --version remains the
19
- // package version command and is deliberately not interpreted here.
20
- if (arg.startsWith('--version=')) return normalize(arg.split('=', 2)[1])
21
- if (arg === '--version' && args[index + 1]?.startsWith('v')) {
22
- // Preserve bare --version/package-version compatibility, while making
23
- // unsupported OpenCode selectors (for example v3) fail loudly.
24
- return normalize(args[index + 1])
25
- }
14
+ // Match init's selector precedence: modern --version wins over the legacy
15
+ // alias regardless of argument order. The package-level --version command is
16
+ // handled before this init selector parser is called.
17
+ const inlineModern = args.find((arg) => arg.startsWith('--version='))
18
+ if (inlineModern !== undefined) {
19
+ const value = inlineModern.slice('--version='.length)
20
+ if (!value) throw missingVersionValue('--version')
21
+ return normalize(value)
22
+ }
23
+ const modernIndex = args.indexOf('--version')
24
+ if (modernIndex >= 0) {
25
+ const modern = args[modernIndex + 1]
26
+ if (modern === undefined || modern.startsWith('-')) throw missingVersionValue('--version')
27
+ return normalize(modern)
28
+ }
29
+ const inlineLegacy = args.find((arg) => arg.startsWith('--opencode-version='))
30
+ if (inlineLegacy !== undefined) {
31
+ const value = inlineLegacy.slice('--opencode-version='.length)
32
+ if (!value) throw missingVersionValue('--opencode-version')
33
+ return normalize(value)
26
34
  }
27
- return null
35
+ const legacyIndex = args.indexOf('--opencode-version')
36
+ if (legacyIndex < 0) return null
37
+ const legacy = args[legacyIndex + 1]
38
+ if (legacy === undefined || legacy.startsWith('-')) {
39
+ throw missingVersionValue('--opencode-version')
40
+ }
41
+ return normalize(legacy)
42
+ }
43
+
44
+ function missingVersionValue(flag) {
45
+ return new Error(`${flag} requires a value: v1, v2, or auto.`)
28
46
  }
29
47
 
30
48
  function normalize(value) {
@@ -0,0 +1,106 @@
1
+ /** OpenCode's permission wildcard matcher and exact language intersection. */
2
+
3
+ const CASE_INSENSITIVE = process.platform === 'win32'
4
+
5
+ function normalizePattern(pattern) {
6
+ return pattern.replaceAll('\\', '/')
7
+ }
8
+
9
+ function escapeRegexCharacter(char) {
10
+ return /[\\^$.*+?()[\]{}|]/.test(char) ? `\\${char}` : char
11
+ }
12
+
13
+ /** Match the OpenCode Wildcard.match behavior used by permission evaluation. */
14
+ export function opencodeWildcardMatch(input, pattern) {
15
+ const normalizedPattern = normalizePattern(pattern)
16
+ const trailingSpaceStar = normalizedPattern.endsWith(' *')
17
+ const body = trailingSpaceStar ? normalizedPattern.slice(0, -2) : normalizedPattern
18
+ let expression = '^'
19
+ for (let index = 0; index < body.length; index += 1) {
20
+ const char = body[index]
21
+ if (char === '*') expression += '.*'
22
+ else if (char === '?') expression += '.'
23
+ else expression += escapeRegexCharacter(char)
24
+ }
25
+ if (trailingSpaceStar) expression += '(?: .*)?'
26
+ return new RegExp(`${expression}$`, CASE_INSENSITIVE ? 'is' : 's').test(normalizePattern(input))
27
+ }
28
+
29
+ function compileWildcard(pattern) {
30
+ const normalized = normalizePattern(pattern)
31
+ const trailingSpaceStar = normalized.endsWith(' *')
32
+ const body = trailingSpaceStar ? normalized.slice(0, -2) : normalized
33
+ const states = [{ epsilon: [], edges: [] }]
34
+ let current = 0
35
+ const addState = () => {
36
+ states.push({ epsilon: [], edges: [] })
37
+ return states.length - 1
38
+ }
39
+ const edge = (from, to, kind, value) => states[from].edges.push({ to, kind, value })
40
+
41
+ for (let index = 0; index < body.length; index += 1) {
42
+ const char = body[index]
43
+ if (char === '*') {
44
+ const next = addState()
45
+ states[current].epsilon.push(next)
46
+ edge(current, current, 'any')
47
+ current = next
48
+ } else {
49
+ const next = addState()
50
+ edge(current, next, char === '?' ? 'any' : 'literal', char)
51
+ current = next
52
+ }
53
+ }
54
+
55
+ if (trailingSpaceStar) {
56
+ const next = addState()
57
+ const spaceLoop = addState()
58
+ states[current].epsilon.push(next)
59
+ edge(current, spaceLoop, 'literal', ' ')
60
+ states[spaceLoop].epsilon.push(next)
61
+ edge(spaceLoop, spaceLoop, 'any')
62
+ current = next
63
+ }
64
+
65
+ return { states, start: 0, accept: current }
66
+ }
67
+
68
+ function literalCharactersOverlap(left, right) {
69
+ if (!CASE_INSENSITIVE) return left === right
70
+ return new RegExp(`^${escapeRegexCharacter(left)}$`, 'i').test(right)
71
+ }
72
+
73
+ function edgesOverlap(left, right) {
74
+ if (left.kind === 'any' || right.kind === 'any') return true
75
+ return literalCharactersOverlap(left.value, right.value)
76
+ }
77
+
78
+ /**
79
+ * Exact non-empty language intersection for OpenCode's `*`/`?` wildcard
80
+ * grammar. Brackets and other regex punctuation are literal; backslashes are
81
+ * normalized to slashes; `*` crosses slashes; and a final ` *` is optional.
82
+ */
83
+ export function opencodeWildcardPatternsOverlap(leftPattern, rightPattern) {
84
+ const left = compileWildcard(leftPattern)
85
+ const right = compileWildcard(rightPattern)
86
+ const queue = [[left.start, right.start]]
87
+ const visited = new Set()
88
+
89
+ for (let cursor = 0; cursor < queue.length; cursor += 1) {
90
+ const [leftState, rightState] = queue[cursor]
91
+ const key = `${leftState}:${rightState}`
92
+ if (visited.has(key)) continue
93
+ visited.add(key)
94
+ if (leftState === left.accept && rightState === right.accept) return true
95
+
96
+ for (const next of left.states[leftState].epsilon) queue.push([next, rightState])
97
+ for (const next of right.states[rightState].epsilon) queue.push([leftState, next])
98
+ for (const leftEdge of left.states[leftState].edges) {
99
+ for (const rightEdge of right.states[rightState].edges) {
100
+ if (edgesOverlap(leftEdge, rightEdge)) queue.push([leftEdge.to, rightEdge.to])
101
+ }
102
+ }
103
+ }
104
+
105
+ return false
106
+ }