pantheon-opencode 1.6.1 → 1.6.2-beta.2
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/AGENTS.global.md +11 -11
- package/AGENTS.md +2 -2
- package/CHANGELOG.md +29 -0
- package/README.md +100 -19
- package/README.pt-BR.md +27 -11
- package/bin/pantheon-init.mjs +106 -19
- package/package.json +3 -2
- package/plugin.json +1 -1
- package/pyproject.toml +1 -1
- package/scripts/build-agents-md.mjs +1 -1
- package/scripts/doctor.mjs +213 -45
- package/scripts/install/agents-md.mjs +2 -1
- package/scripts/install/config-migration.mjs +344 -393
- package/scripts/install/config-paths.mjs +15 -0
- package/scripts/install/mcp-permissions.mjs +164 -0
- package/scripts/install/opencode-version.mjs +31 -13
- package/scripts/install/opencode-wildcard.mjs +106 -0
- package/scripts/install/opencode.mjs +240 -69
- package/scripts/install/plan-artifact.mjs +12 -1
- package/scripts/install/plugin.mjs +17 -1
- package/scripts/install/v2-capabilities.mjs +5 -6
- package/scripts/package-evidence.mjs +1 -0
- package/scripts/sandbox-env.sh +174 -0
- package/scripts/setup-v2-config.mjs +1703 -0
- package/scripts/setup.mjs +415 -0
- package/scripts/sync-tui.mjs +9 -1
- package/scripts/test-opencode-v2-sandbox.sh +438 -151
- package/scripts/update-skills-lock.mjs +30 -0
- package/skills-lock.json +10 -10
- package/src/agents/aphrodite.md +5 -2
- package/src/agents/apollo.md +5 -0
- package/src/agents/athena.md +6 -1
- package/src/agents/demeter.md +5 -1
- package/src/agents/gaia.md +4 -0
- package/src/agents/hephaestus.md +6 -1
- package/src/agents/hermes.md +6 -3
- package/src/agents/iris.md +5 -1
- package/src/agents/mnemosyne.md +20 -50
- package/src/agents/nyx.md +5 -1
- package/src/agents/prometheus.md +4 -0
- package/src/agents/talos.md +4 -0
- package/src/agents/themis.md +4 -0
- package/src/agents/zeus.md +9 -3
- package/src/instructions/agent-return-format.instructions.md +1 -1
- package/src/instructions/memory-protocol.instructions.md +3 -3
- package/src/instructions/test-economy.instructions.md +6 -6
- package/src/mcp/pantheon_vision.py +37 -36
- package/src/pantheon/cost-command.ts +30 -133
- package/src/pantheon/model-pricing.ts +1 -536
- package/src/pantheon/v2-vision.ts +34 -29
- package/src/pantheon/vision.ts +43 -10
- package/src/plugin-v2.ts +30 -53
- package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
- package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js +749 -0
- package/src/plugins/tui/dist/cost-data-CCZUs1aJ.js.map +1 -0
- package/src/plugins/tui/dist/quota-adapters.d.ts +89 -0
- package/src/plugins/tui/dist/quota-adapters.d.ts.map +1 -0
- package/src/plugins/tui/dist/quota-adapters.js +1142 -0
- package/src/plugins/tui/dist/quota-adapters.js.map +1 -0
- package/src/plugins/tui/dist/quota-cli.d.ts +17 -0
- package/src/plugins/tui/dist/quota-cli.d.ts.map +1 -0
- package/src/plugins/tui/dist/quota-cli.js +184 -0
- package/src/plugins/tui/dist/quota-cli.js.map +1 -0
- package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js +684 -0
- package/src/plugins/tui/dist/quota-rpc-DMmXBhBe.js.map +1 -0
- package/src/plugins/tui/dist/server-v2.d.ts +14 -0
- package/src/plugins/tui/dist/server-v2.d.ts.map +1 -0
- package/src/plugins/tui/dist/server-v2.js +796 -0
- package/src/plugins/tui/dist/server-v2.js.map +1 -0
- package/src/plugins/tui/dist/tui-v2.d.ts +375 -53
- package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
- package/src/plugins/tui/dist/tui-v2.js +5876 -530
- package/src/plugins/tui/dist/tui-v2.js.map +1 -1
- package/src/plugins/tui/dist/tui.js +1 -1
- package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js +118 -0
- package/src/plugins/tui/dist/usage-history-contract-nt1rnBPE.js.map +1 -0
- package/src/plugins/tui/dist/usage-history-worker.js +25 -0
- package/src/plugins/tui/dist/usage-history-worker.js.map +1 -0
- package/src/plugins/tui/index-v2.ts +3 -6
- package/src/plugins/tui/package-lock.json +17 -2
- package/src/plugins/tui/package.json +6 -3
- package/src/plugins/tui/src/context-gauge.ts +59 -0
- package/src/plugins/tui/src/cost-data.ts +607 -0
- package/src/plugins/tui/src/go-key-diagnostic-ui.ts +100 -0
- package/src/plugins/tui/src/go-key-diagnostic.ts +125 -0
- package/src/plugins/tui/src/index-v2.tsx +231 -240
- package/src/plugins/tui/src/model-pricing.ts +536 -0
- package/src/plugins/tui/src/model-usage-limits.ts +4 -0
- package/src/plugins/tui/src/quota-adapters.ts +1598 -0
- package/src/plugins/tui/src/quota-cli.ts +237 -0
- package/src/plugins/tui/src/quota-rpc.ts +373 -0
- package/src/plugins/tui/src/quota-v2-model.ts +1032 -0
- package/src/plugins/tui/src/quota-v2.tsx +1238 -0
- package/src/plugins/tui/src/server-v2.ts +985 -0
- package/src/plugins/tui/src/sidebar-width.ts +129 -0
- package/src/plugins/tui/src/usage-history-contract.ts +217 -0
- package/src/plugins/tui/src/usage-history-validation.ts +104 -0
- package/src/plugins/tui/src/usage-history-view.tsx +236 -0
- package/src/plugins/tui/src/usage-history-worker.ts +25 -0
- package/src/plugins/tui/src/usage-view-model.ts +272 -0
- package/src/plugins/tui/tsconfig.typecheck.json +6 -1
- package/src/plugins/tui/tsdown.config.ts +44 -5
- package/src/routing.yml +72 -13
- package/src/skills/README.md +4 -0
- package/src/skills/agent-coordination/SKILL.md +0 -3
- package/src/skills/artifact-management/SKILL.md +0 -3
- package/src/skills/auto-continue/SKILL.md +0 -3
- package/src/skills/code-review-checklist/SKILL.md +0 -3
- package/src/skills/context-compression/SKILL.md +0 -3
- package/src/skills/memory-bank/SKILL.md +6 -28
- package/src/skills/session-goal/SKILL.md +0 -3
- package/src/skills/simplify/SKILL.md +5 -4
- package/src/skills/tdd-with-agents/SKILL.md +0 -3
- package/src/skills/visual-review-pipeline/SKILL.md +0 -1
- package/src/pantheon/memory-context.ts +0 -1017
|
@@ -0,0 +1,1703 @@
|
|
|
1
|
+
import fs from 'node:fs'
|
|
2
|
+
import path from 'node:path'
|
|
3
|
+
import { isDeepStrictEqual } from 'node:util'
|
|
4
|
+
import * as clack from '@clack/prompts'
|
|
5
|
+
import { createBackupSet } from './install/backup.mjs'
|
|
6
|
+
import {
|
|
7
|
+
MCP_ENTRYPOINT_RENAMES,
|
|
8
|
+
migrateV1toV2,
|
|
9
|
+
PANTHEON_MCP_ENTRYPOINTS,
|
|
10
|
+
validateMcpV1toV2Source,
|
|
11
|
+
} from './install/config-migration.mjs'
|
|
12
|
+
import { resolveGlobalConfigDirectory } from './install/config-paths.mjs'
|
|
13
|
+
import { mcpServerPermissionActions } from './install/mcp-permissions.mjs'
|
|
14
|
+
import { PANTHEON_MCP_SERVERS, pluginReferenceIdentity } from './install/opencode.mjs'
|
|
15
|
+
import {
|
|
16
|
+
opencodeWildcardMatch,
|
|
17
|
+
opencodeWildcardPatternsOverlap,
|
|
18
|
+
} from './install/opencode-wildcard.mjs'
|
|
19
|
+
import { writeConfigWithBackup } from './install/shared.mjs'
|
|
20
|
+
import {
|
|
21
|
+
assertNoSymlinkAncestors as assertManagedPathNoSymlinks,
|
|
22
|
+
assertPathWithin,
|
|
23
|
+
} from './install/verify.mjs'
|
|
24
|
+
|
|
25
|
+
const CONFIG_NAMES = ['opencode.json', 'opencode.jsonc']
|
|
26
|
+
const MCP_SERVER_NAME = /^[a-zA-Z0-9._-]+$/
|
|
27
|
+
const EFFECTS = new Set(['allow', 'ask', 'deny'])
|
|
28
|
+
|
|
29
|
+
export { resolveGlobalConfigDirectory }
|
|
30
|
+
|
|
31
|
+
function assertNoSymlinkAncestors(directory, filesystem) {
|
|
32
|
+
const absolute = path.resolve(directory)
|
|
33
|
+
const { root } = path.parse(absolute)
|
|
34
|
+
let current = root
|
|
35
|
+
for (const segment of absolute.slice(root.length).split(path.sep).filter(Boolean)) {
|
|
36
|
+
current = path.join(current, segment)
|
|
37
|
+
let stat
|
|
38
|
+
try {
|
|
39
|
+
stat = filesystem.lstatSync(current)
|
|
40
|
+
} catch (error) {
|
|
41
|
+
if (error.code === 'ENOENT') return
|
|
42
|
+
throw new Error(`Cannot safely inspect config directory ancestor ${current}.`)
|
|
43
|
+
}
|
|
44
|
+
if (stat.isSymbolicLink()) {
|
|
45
|
+
throw new Error(`Refusing config directory with symlinked ancestor ${current}.`)
|
|
46
|
+
}
|
|
47
|
+
if (!stat.isDirectory()) {
|
|
48
|
+
throw new Error(`Refusing config directory with non-directory ancestor ${current}.`)
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function readString(source, cursor) {
|
|
54
|
+
const start = cursor
|
|
55
|
+
cursor += 1
|
|
56
|
+
let escaped = false
|
|
57
|
+
while (cursor < source.length) {
|
|
58
|
+
const char = source[cursor]
|
|
59
|
+
if (escaped) {
|
|
60
|
+
escaped = false
|
|
61
|
+
} else if (char === '\\') {
|
|
62
|
+
escaped = true
|
|
63
|
+
} else if (char === '"') {
|
|
64
|
+
const end = cursor + 1
|
|
65
|
+
return { value: JSON.parse(source.slice(start, end)), start, end, cursor: end }
|
|
66
|
+
}
|
|
67
|
+
cursor += 1
|
|
68
|
+
}
|
|
69
|
+
throw new SyntaxError(`Unterminated string at offset ${start}`)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Parse JSON/JSONC while retaining source spans so edits can preserve unrelated text. */
|
|
73
|
+
function parseConfig(source, jsonc) {
|
|
74
|
+
let cursor = 0
|
|
75
|
+
const comments = []
|
|
76
|
+
|
|
77
|
+
function skipTrivia() {
|
|
78
|
+
while (cursor < source.length) {
|
|
79
|
+
if (/\s/.test(source[cursor])) {
|
|
80
|
+
cursor += 1
|
|
81
|
+
continue
|
|
82
|
+
}
|
|
83
|
+
if (source.startsWith('//', cursor)) {
|
|
84
|
+
if (!jsonc) throw new SyntaxError(`Comments are not allowed at offset ${cursor}`)
|
|
85
|
+
const start = cursor
|
|
86
|
+
const newline = source.indexOf('\n', cursor + 2)
|
|
87
|
+
cursor = newline < 0 ? source.length : newline
|
|
88
|
+
comments.push({ start, end: cursor })
|
|
89
|
+
continue
|
|
90
|
+
}
|
|
91
|
+
if (source.startsWith('/*', cursor)) {
|
|
92
|
+
if (!jsonc) throw new SyntaxError(`Comments are not allowed at offset ${cursor}`)
|
|
93
|
+
const start = cursor
|
|
94
|
+
const close = source.indexOf('*/', cursor + 2)
|
|
95
|
+
if (close < 0) throw new SyntaxError(`Unterminated comment at offset ${start}`)
|
|
96
|
+
cursor = close + 2
|
|
97
|
+
comments.push({ start, end: cursor })
|
|
98
|
+
continue
|
|
99
|
+
}
|
|
100
|
+
break
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function parseValue() {
|
|
105
|
+
skipTrivia()
|
|
106
|
+
const start = cursor
|
|
107
|
+
const char = source[cursor]
|
|
108
|
+
|
|
109
|
+
if (char === '"') {
|
|
110
|
+
const token = readString(source, cursor)
|
|
111
|
+
cursor = token.cursor
|
|
112
|
+
return { value: token.value, start, end: cursor, type: 'scalar' }
|
|
113
|
+
}
|
|
114
|
+
if (char === '{') {
|
|
115
|
+
cursor += 1
|
|
116
|
+
const value = {}
|
|
117
|
+
const properties = []
|
|
118
|
+
const keys = new Set()
|
|
119
|
+
skipTrivia()
|
|
120
|
+
if (source[cursor] === '}') {
|
|
121
|
+
cursor += 1
|
|
122
|
+
return { value, properties, start, end: cursor, closeStart: cursor - 1, type: 'object' }
|
|
123
|
+
}
|
|
124
|
+
let previousProperty = null
|
|
125
|
+
while (cursor < source.length) {
|
|
126
|
+
skipTrivia()
|
|
127
|
+
if (source[cursor] !== '"') throw new SyntaxError(`Expected object key at offset ${cursor}`)
|
|
128
|
+
const key = readString(source, cursor)
|
|
129
|
+
cursor = key.cursor
|
|
130
|
+
if (keys.has(key.value))
|
|
131
|
+
throw new SyntaxError(`Duplicate object key ${JSON.stringify(key.value)}`)
|
|
132
|
+
keys.add(key.value)
|
|
133
|
+
skipTrivia()
|
|
134
|
+
if (source[cursor] !== ':') throw new SyntaxError(`Expected ':' at offset ${cursor}`)
|
|
135
|
+
cursor += 1
|
|
136
|
+
const parsedValue = parseValue()
|
|
137
|
+
Object.defineProperty(value, key.value, {
|
|
138
|
+
value: parsedValue.value,
|
|
139
|
+
enumerable: true,
|
|
140
|
+
configurable: true,
|
|
141
|
+
writable: true,
|
|
142
|
+
})
|
|
143
|
+
const property = {
|
|
144
|
+
key: key.value,
|
|
145
|
+
keyStart: key.start,
|
|
146
|
+
keyEnd: key.end,
|
|
147
|
+
valueStart: parsedValue.start,
|
|
148
|
+
valueEnd: parsedValue.end,
|
|
149
|
+
value: parsedValue.value,
|
|
150
|
+
valueNode: parsedValue,
|
|
151
|
+
commaBefore: previousProperty?.commaAfter ?? null,
|
|
152
|
+
commaAfter: null,
|
|
153
|
+
}
|
|
154
|
+
properties.push(property)
|
|
155
|
+
skipTrivia()
|
|
156
|
+
if (source[cursor] === ',') {
|
|
157
|
+
property.commaAfter = cursor
|
|
158
|
+
cursor += 1
|
|
159
|
+
skipTrivia()
|
|
160
|
+
if (source[cursor] === '}') {
|
|
161
|
+
if (!jsonc)
|
|
162
|
+
throw new SyntaxError(
|
|
163
|
+
`Trailing commas are not allowed at offset ${property.commaAfter}`,
|
|
164
|
+
)
|
|
165
|
+
cursor += 1
|
|
166
|
+
return { value, properties, start, end: cursor, closeStart: cursor - 1, type: 'object' }
|
|
167
|
+
}
|
|
168
|
+
previousProperty = property
|
|
169
|
+
continue
|
|
170
|
+
}
|
|
171
|
+
if (source[cursor] === '}') {
|
|
172
|
+
cursor += 1
|
|
173
|
+
return { value, properties, start, end: cursor, closeStart: cursor - 1, type: 'object' }
|
|
174
|
+
}
|
|
175
|
+
throw new SyntaxError(`Expected ',' or '}' at offset ${cursor}`)
|
|
176
|
+
}
|
|
177
|
+
throw new SyntaxError(`Unterminated object at offset ${start}`)
|
|
178
|
+
}
|
|
179
|
+
if (char === '[') {
|
|
180
|
+
cursor += 1
|
|
181
|
+
const value = []
|
|
182
|
+
const items = []
|
|
183
|
+
skipTrivia()
|
|
184
|
+
if (source[cursor] === ']') {
|
|
185
|
+
cursor += 1
|
|
186
|
+
return { value, items, start, end: cursor, closeStart: cursor - 1, type: 'array' }
|
|
187
|
+
}
|
|
188
|
+
let previousItem = null
|
|
189
|
+
while (cursor < source.length) {
|
|
190
|
+
const itemNode = parseValue()
|
|
191
|
+
value.push(itemNode.value)
|
|
192
|
+
const item = {
|
|
193
|
+
...itemNode,
|
|
194
|
+
commaBefore: previousItem?.commaAfter ?? null,
|
|
195
|
+
commaAfter: null,
|
|
196
|
+
}
|
|
197
|
+
items.push(item)
|
|
198
|
+
skipTrivia()
|
|
199
|
+
if (source[cursor] === ',') {
|
|
200
|
+
const comma = cursor
|
|
201
|
+
item.commaAfter = comma
|
|
202
|
+
cursor += 1
|
|
203
|
+
skipTrivia()
|
|
204
|
+
if (source[cursor] === ']') {
|
|
205
|
+
if (!jsonc) throw new SyntaxError(`Trailing commas are not allowed at offset ${comma}`)
|
|
206
|
+
cursor += 1
|
|
207
|
+
return { value, items, start, end: cursor, closeStart: cursor - 1, type: 'array' }
|
|
208
|
+
}
|
|
209
|
+
previousItem = item
|
|
210
|
+
continue
|
|
211
|
+
}
|
|
212
|
+
if (source[cursor] === ']') {
|
|
213
|
+
cursor += 1
|
|
214
|
+
return { value, items, start, end: cursor, closeStart: cursor - 1, type: 'array' }
|
|
215
|
+
}
|
|
216
|
+
throw new SyntaxError(`Expected ',' or ']' at offset ${cursor}`)
|
|
217
|
+
}
|
|
218
|
+
throw new SyntaxError(`Unterminated array at offset ${start}`)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const literal = /^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(
|
|
222
|
+
source.slice(cursor),
|
|
223
|
+
)
|
|
224
|
+
if (!literal) throw new SyntaxError(`Expected JSON value at offset ${cursor}`)
|
|
225
|
+
cursor += literal[0].length
|
|
226
|
+
return { value: JSON.parse(literal[0]), start, end: cursor, type: 'scalar' }
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const ast = parseValue()
|
|
230
|
+
skipTrivia()
|
|
231
|
+
if (cursor !== source.length) throw new SyntaxError(`Unexpected content at offset ${cursor}`)
|
|
232
|
+
if (ast.type !== 'object') throw new SyntaxError('The config root must be a JSON object')
|
|
233
|
+
return { ...ast, comments }
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Inspect both global config filenames independently; neither file is canonicalized. */
|
|
237
|
+
export function inspectConfigFiles(configDir, filesystem = fs) {
|
|
238
|
+
const directoryError = () =>
|
|
239
|
+
CONFIG_NAMES.map((name) => ({
|
|
240
|
+
name,
|
|
241
|
+
path: path.join(configDir, name),
|
|
242
|
+
exists: true,
|
|
243
|
+
format: name.endsWith('.jsonc') ? 'jsonc' : 'json',
|
|
244
|
+
directoryError: true,
|
|
245
|
+
parseError: 'Config directory cannot be safely inspected.',
|
|
246
|
+
}))
|
|
247
|
+
try {
|
|
248
|
+
assertNoSymlinkAncestors(configDir, filesystem)
|
|
249
|
+
} catch (error) {
|
|
250
|
+
return directoryError(error)
|
|
251
|
+
}
|
|
252
|
+
return CONFIG_NAMES.map((name) => {
|
|
253
|
+
const filePath = path.join(configDir, name)
|
|
254
|
+
try {
|
|
255
|
+
assertNoSymlinkAncestors(configDir, filesystem)
|
|
256
|
+
} catch {
|
|
257
|
+
return {
|
|
258
|
+
name,
|
|
259
|
+
path: filePath,
|
|
260
|
+
exists: true,
|
|
261
|
+
format: name.endsWith('.jsonc') ? 'jsonc' : 'json',
|
|
262
|
+
directoryError: true,
|
|
263
|
+
parseError: 'Config directory cannot be safely inspected.',
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
if (!filesystem.existsSync(filePath)) {
|
|
267
|
+
return {
|
|
268
|
+
name,
|
|
269
|
+
path: filePath,
|
|
270
|
+
exists: false,
|
|
271
|
+
format: name.endsWith('.jsonc') ? 'jsonc' : 'json',
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
const stat = filesystem.lstatSync(filePath)
|
|
275
|
+
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
276
|
+
return {
|
|
277
|
+
name,
|
|
278
|
+
path: filePath,
|
|
279
|
+
exists: true,
|
|
280
|
+
format: name.endsWith('.jsonc') ? 'jsonc' : 'json',
|
|
281
|
+
parseError: 'Only regular config files are supported.',
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
try {
|
|
285
|
+
assertNoSymlinkAncestors(configDir, filesystem)
|
|
286
|
+
const readStat = filesystem.lstatSync(filePath)
|
|
287
|
+
if (readStat.isSymbolicLink() || !readStat.isFile() || !sameIdentity(readStat, stat)) {
|
|
288
|
+
return {
|
|
289
|
+
name,
|
|
290
|
+
path: filePath,
|
|
291
|
+
exists: true,
|
|
292
|
+
format: name.endsWith('.jsonc') ? 'jsonc' : 'json',
|
|
293
|
+
parseError: 'Config file changed during inspection.',
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
} catch {
|
|
297
|
+
return {
|
|
298
|
+
name,
|
|
299
|
+
path: filePath,
|
|
300
|
+
exists: true,
|
|
301
|
+
format: name.endsWith('.jsonc') ? 'jsonc' : 'json',
|
|
302
|
+
directoryError: true,
|
|
303
|
+
parseError: 'Config directory cannot be safely inspected.',
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
const content = filesystem.readFileSync(filePath, 'utf8')
|
|
307
|
+
try {
|
|
308
|
+
assertNoSymlinkAncestors(configDir, filesystem)
|
|
309
|
+
} catch {
|
|
310
|
+
return {
|
|
311
|
+
name,
|
|
312
|
+
path: filePath,
|
|
313
|
+
exists: true,
|
|
314
|
+
format: name.endsWith('.jsonc') ? 'jsonc' : 'json',
|
|
315
|
+
directoryError: true,
|
|
316
|
+
parseError: 'Config directory cannot be safely inspected.',
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
const format = name.endsWith('.jsonc') ? 'jsonc' : 'json'
|
|
320
|
+
try {
|
|
321
|
+
const ast = parseConfig(content, format === 'jsonc')
|
|
322
|
+
return {
|
|
323
|
+
name,
|
|
324
|
+
path: filePath,
|
|
325
|
+
exists: true,
|
|
326
|
+
format,
|
|
327
|
+
mode: stat.mode,
|
|
328
|
+
identity: { dev: stat.dev, ino: stat.ino },
|
|
329
|
+
content,
|
|
330
|
+
config: ast.value,
|
|
331
|
+
ast,
|
|
332
|
+
}
|
|
333
|
+
} catch {
|
|
334
|
+
return {
|
|
335
|
+
name,
|
|
336
|
+
path: filePath,
|
|
337
|
+
exists: true,
|
|
338
|
+
format,
|
|
339
|
+
mode: stat.mode,
|
|
340
|
+
content,
|
|
341
|
+
parseError: 'Invalid config syntax.',
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
})
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function makeConfigPreconditions(files, plannedContents = new Map()) {
|
|
348
|
+
return files.map((file) => {
|
|
349
|
+
const planned = plannedContents.get(file.path)
|
|
350
|
+
const changed = planned !== undefined
|
|
351
|
+
return {
|
|
352
|
+
path: file.path,
|
|
353
|
+
originalExists: file.exists,
|
|
354
|
+
originalContent: file.exists ? file.content : null,
|
|
355
|
+
originalIdentity: file.identity ?? null,
|
|
356
|
+
originalMode: file.mode ?? null,
|
|
357
|
+
expectedExists: changed || file.exists,
|
|
358
|
+
expectedContent: changed ? planned.contents : file.exists ? file.content : null,
|
|
359
|
+
expectedIdentity: changed ? null : (file.identity ?? null),
|
|
360
|
+
expectedMode: changed ? (file.mode ?? 0o100600) : (file.mode ?? null),
|
|
361
|
+
}
|
|
362
|
+
})
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
/** Check reviewed JSON/JSONC input bytes and file identities without logging them. */
|
|
366
|
+
export function verifyConfigPreconditions(
|
|
367
|
+
preconditions,
|
|
368
|
+
{ configDir, stage = 'original', filesystem = fs } = {},
|
|
369
|
+
) {
|
|
370
|
+
if (!Array.isArray(preconditions) || !['original', 'expected'].includes(stage)) return false
|
|
371
|
+
const root = path.resolve(configDir ?? '')
|
|
372
|
+
if (!configDir || !path.isAbsolute(root)) return false
|
|
373
|
+
try {
|
|
374
|
+
for (const item of preconditions) {
|
|
375
|
+
const filePath = path.resolve(item.path)
|
|
376
|
+
if (path.dirname(filePath) !== root || !CONFIG_NAMES.includes(path.basename(filePath))) {
|
|
377
|
+
return false
|
|
378
|
+
}
|
|
379
|
+
assertPathWithin(root, filePath)
|
|
380
|
+
assertManagedPathNoSymlinks(filePath)
|
|
381
|
+
let stat = null
|
|
382
|
+
try {
|
|
383
|
+
stat = filesystem.lstatSync(filePath)
|
|
384
|
+
} catch (error) {
|
|
385
|
+
if (error?.code !== 'ENOENT') return false
|
|
386
|
+
}
|
|
387
|
+
const exists = stage === 'original' ? item.originalExists : item.expectedExists
|
|
388
|
+
const content = stage === 'original' ? item.originalContent : item.expectedContent
|
|
389
|
+
const mode = stage === 'original' ? item.originalMode : item.expectedMode
|
|
390
|
+
const identity = stage === 'original' ? item.originalIdentity : item.expectedIdentity
|
|
391
|
+
if (!exists) {
|
|
392
|
+
if (stat !== null) return false
|
|
393
|
+
continue
|
|
394
|
+
}
|
|
395
|
+
if (!stat || stat.isSymbolicLink() || !stat.isFile() || stat.mode !== mode) return false
|
|
396
|
+
if (identity && !sameIdentity(stat, identity)) return false
|
|
397
|
+
if (filesystem.readFileSync(filePath, 'utf8') !== content) return false
|
|
398
|
+
}
|
|
399
|
+
return true
|
|
400
|
+
} catch {
|
|
401
|
+
return false
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function policySources(files) {
|
|
406
|
+
const mcpServers = [
|
|
407
|
+
...new Set([
|
|
408
|
+
...PANTHEON_MCP_SERVERS,
|
|
409
|
+
...files
|
|
410
|
+
.filter((file) => file.exists && !file.parseError)
|
|
411
|
+
.flatMap((file) => configuredMcpServers(file.config).map(([name]) => name)),
|
|
412
|
+
]),
|
|
413
|
+
]
|
|
414
|
+
return files.flatMap((file) => {
|
|
415
|
+
if (!file.exists || file.parseError) return []
|
|
416
|
+
const properties = new Map(file.ast.properties.map((property) => [property.key, property]))
|
|
417
|
+
return ['permission', 'permissions']
|
|
418
|
+
.filter((key) => properties.has(key))
|
|
419
|
+
.map((key) => ({
|
|
420
|
+
id: `${file.name}#${key}`,
|
|
421
|
+
file,
|
|
422
|
+
mcpServers,
|
|
423
|
+
key,
|
|
424
|
+
value: properties.get(key).value,
|
|
425
|
+
property: properties.get(key),
|
|
426
|
+
}))
|
|
427
|
+
})
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
function configuredMcpServers(config) {
|
|
431
|
+
if (!isRecord(config?.mcp)) return []
|
|
432
|
+
const mcp = config.mcp
|
|
433
|
+
const legacyToggle =
|
|
434
|
+
isRecord(mcp.servers) &&
|
|
435
|
+
Object.keys(mcp.servers).length === 1 &&
|
|
436
|
+
typeof mcp.servers.enabled === 'boolean'
|
|
437
|
+
const nested =
|
|
438
|
+
!legacyToggle && isRecord(mcp.servers) && Object.values(mcp.servers).every(isRecord)
|
|
439
|
+
const entries = nested
|
|
440
|
+
? [
|
|
441
|
+
...Object.entries(mcp.servers),
|
|
442
|
+
...Object.entries(mcp).filter(([name]) => name !== 'servers'),
|
|
443
|
+
]
|
|
444
|
+
: Object.entries(mcp).filter(([name]) => !(legacyToggle && name === 'servers'))
|
|
445
|
+
const seen = new Set()
|
|
446
|
+
return entries.filter(([name, value]) => {
|
|
447
|
+
if (!isRecord(value)) return false
|
|
448
|
+
if (seen.has(name)) {
|
|
449
|
+
throw new Error('Conflicting flat and nested MCP server entries cannot be inspected safely.')
|
|
450
|
+
}
|
|
451
|
+
seen.add(name)
|
|
452
|
+
return true
|
|
453
|
+
})
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function isGeneratedMcpEntry(name, entry) {
|
|
457
|
+
const current = PANTHEON_MCP_ENTRYPOINTS[name]
|
|
458
|
+
if (!current || !isRecord(entry)) return false
|
|
459
|
+
const stale = Object.entries(MCP_ENTRYPOINT_RENAMES).find(([, next]) => next === current)?.[0]
|
|
460
|
+
const command = entry.command
|
|
461
|
+
const keys = Object.keys(entry).sort()
|
|
462
|
+
const installerShape =
|
|
463
|
+
keys.join(',') === 'command,cwd,type' ||
|
|
464
|
+
(keys.join(',') === 'command,cwd,enabled,type' && entry.enabled === true)
|
|
465
|
+
return (
|
|
466
|
+
installerShape &&
|
|
467
|
+
entry.type === 'local' &&
|
|
468
|
+
typeof entry.cwd === 'string' &&
|
|
469
|
+
path.isAbsolute(entry.cwd) &&
|
|
470
|
+
Array.isArray(command) &&
|
|
471
|
+
command.length === 2 &&
|
|
472
|
+
typeof command[0] === 'string' &&
|
|
473
|
+
path.isAbsolute(command[0]) &&
|
|
474
|
+
(command[0] === path.join(entry.cwd, '.venv', 'bin', 'python3') ||
|
|
475
|
+
command[0] === path.win32.join(entry.cwd, '.venv', 'Scripts', 'python.exe')) &&
|
|
476
|
+
(command[1] === `scripts/${current}` || command[1] === `scripts/${stale}`)
|
|
477
|
+
)
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
function inspectInstallerEntries(config) {
|
|
481
|
+
const plugins = new Set()
|
|
482
|
+
if (Array.isArray(config.plugins)) {
|
|
483
|
+
for (const entry of config.plugins) {
|
|
484
|
+
if (pluginReferenceIdentity(entry) === 'src/plugin-v2') plugins.add('V2 plugin')
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
const mcp = []
|
|
489
|
+
if (isRecord(config.mcp)) {
|
|
490
|
+
for (const [name, entry] of configuredMcpServers(config)) {
|
|
491
|
+
if (isGeneratedMcpEntry(name, entry)) mcp.push(name)
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
return { plugins: [...plugins].sort(), mcp }
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
function flatThirdPartyMcpEntryCount(file) {
|
|
499
|
+
if (file.name !== 'opencode.jsonc' || !isRecord(file.config?.mcp)) return 0
|
|
500
|
+
const mcp = file.config.mcp
|
|
501
|
+
const { hasV2ServersMap, legacyServersToggle } = validateMcpV1toV2Source(mcp)
|
|
502
|
+
const flatEntries = Object.entries(mcp).flatMap(([name, entry]) => {
|
|
503
|
+
if (hasV2ServersMap && name === 'servers') return []
|
|
504
|
+
if (legacyServersToggle && name === 'servers') return []
|
|
505
|
+
return [[name, entry]]
|
|
506
|
+
})
|
|
507
|
+
return flatEntries.filter(([name, entry]) => isRecord(entry) && !isGeneratedMcpEntry(name, entry))
|
|
508
|
+
.length
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
function removeObjectPropertyEdit(file, objectNode, key) {
|
|
512
|
+
const property = findProperty(objectNode, key)
|
|
513
|
+
if (!property) throw new Error('A verified entry could not be located for removal.')
|
|
514
|
+
let start = property.keyStart
|
|
515
|
+
let end = property.valueEnd
|
|
516
|
+
if (property.commaAfter !== null) end = property.commaAfter + 1
|
|
517
|
+
else if (property.commaBefore !== null) start = property.commaBefore
|
|
518
|
+
if (commentsWithin(file.ast, start, end)) {
|
|
519
|
+
throw new Error('A comment is attached to the verified entry.')
|
|
520
|
+
}
|
|
521
|
+
return { start, end, text: '' }
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
function removeArrayPrefixEdit(file, arrayNode, count) {
|
|
525
|
+
if (count === 0) return null
|
|
526
|
+
if (commentsWithin(file.ast, arrayNode.start, arrayNode.end)) {
|
|
527
|
+
throw new Error('Comments prevent safe removal of a verified plugin entry.')
|
|
528
|
+
}
|
|
529
|
+
const last = arrayNode.items[count - 1]
|
|
530
|
+
return {
|
|
531
|
+
start: arrayNode.items[0].start,
|
|
532
|
+
end: last.commaAfter === null ? last.end : last.commaAfter + 1,
|
|
533
|
+
text: '',
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
function removeArrayItemsEdits(file, arrayNode, indexes) {
|
|
538
|
+
if (indexes.length === 0) return []
|
|
539
|
+
if (commentsWithin(file.ast, arrayNode.start, arrayNode.end)) {
|
|
540
|
+
throw new Error('Comments prevent safe removal of a verified plugin entry.')
|
|
541
|
+
}
|
|
542
|
+
const sorted = [...new Set(indexes)].sort((a, b) => a - b)
|
|
543
|
+
const groups = []
|
|
544
|
+
for (const index of sorted) {
|
|
545
|
+
const last = groups.at(-1)
|
|
546
|
+
if (last && last[1] === index - 1) last[1] = index
|
|
547
|
+
else groups.push([index, index])
|
|
548
|
+
}
|
|
549
|
+
return groups.map(([firstIndex, lastIndex]) => {
|
|
550
|
+
const first = arrayNode.items[firstIndex]
|
|
551
|
+
const last = arrayNode.items[lastIndex]
|
|
552
|
+
let start
|
|
553
|
+
let end
|
|
554
|
+
if (firstIndex === 0 && lastIndex === arrayNode.items.length - 1) {
|
|
555
|
+
start = first.start
|
|
556
|
+
end = last.commaAfter === null ? last.end : last.commaAfter + 1
|
|
557
|
+
} else if (lastIndex < arrayNode.items.length - 1) {
|
|
558
|
+
start = first.start
|
|
559
|
+
end = last.commaAfter + 1
|
|
560
|
+
} else {
|
|
561
|
+
start = first.commaBefore
|
|
562
|
+
end = last.end
|
|
563
|
+
}
|
|
564
|
+
return { start, end, text: '' }
|
|
565
|
+
})
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
function managedEntryMovePlan(files) {
|
|
569
|
+
const source = files.find((file) => file.name === 'opencode.jsonc' && file.exists)
|
|
570
|
+
const target = files.find((file) => file.name === 'opencode.json')
|
|
571
|
+
if (!source || source.parseError || !target || target.parseError) {
|
|
572
|
+
return {
|
|
573
|
+
source,
|
|
574
|
+
target,
|
|
575
|
+
moves: [],
|
|
576
|
+
edits: [],
|
|
577
|
+
removedMcpEntries: [],
|
|
578
|
+
unsafeCount: 0,
|
|
579
|
+
unsafePluginCount: 0,
|
|
580
|
+
unsafeMcpNames: [],
|
|
581
|
+
removedDuplicatePluginCount: 0,
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
|
|
585
|
+
const moves = []
|
|
586
|
+
const edits = []
|
|
587
|
+
const removedMcpEntries = []
|
|
588
|
+
let unsafeCount = 0
|
|
589
|
+
let unsafePluginCount = 0
|
|
590
|
+
const unsafeMcpNames = []
|
|
591
|
+
let removedDuplicatePluginCount = 0
|
|
592
|
+
const sourcePluginsProperty = findProperty(source.ast, 'plugins')
|
|
593
|
+
const sourcePlugins = sourcePluginsProperty?.valueNode
|
|
594
|
+
if (sourcePlugins?.type === 'array') {
|
|
595
|
+
const pluginItems = sourcePlugins.items.filter(
|
|
596
|
+
(item) => pluginReferenceIdentity(item.value) === 'src/plugin-v2',
|
|
597
|
+
)
|
|
598
|
+
if (pluginItems.length > 0) {
|
|
599
|
+
const targetPlugins = target.config?.plugins
|
|
600
|
+
const targetHasSelector =
|
|
601
|
+
Array.isArray(targetPlugins) &&
|
|
602
|
+
targetPlugins.some((plugin) => typeof plugin === 'string' && plugin.startsWith('-'))
|
|
603
|
+
const sourceHasSelector = sourcePlugins.value.some(
|
|
604
|
+
(plugin) => typeof plugin === 'string' && plugin.startsWith('-'),
|
|
605
|
+
)
|
|
606
|
+
const prefixCount = pluginItems.length
|
|
607
|
+
const prefixSafe = pluginItems.every((item, index) => sourcePlugins.items[index] === item)
|
|
608
|
+
const targetManagedPlugins = Array.isArray(targetPlugins)
|
|
609
|
+
? targetPlugins.filter((plugin) => pluginReferenceIdentity(plugin) === 'src/plugin-v2')
|
|
610
|
+
: []
|
|
611
|
+
if (targetManagedPlugins.length > 0) {
|
|
612
|
+
const exactDuplicate =
|
|
613
|
+
targetManagedPlugins.length === 1 &&
|
|
614
|
+
pluginItems.every((item) => isDeepStrictEqual(item.value, targetManagedPlugins[0]))
|
|
615
|
+
if (exactDuplicate && !targetHasSelector && !sourceHasSelector) {
|
|
616
|
+
try {
|
|
617
|
+
const indexes = pluginItems.map((item) => sourcePlugins.items.indexOf(item))
|
|
618
|
+
edits.push(...removeArrayItemsEdits(source, sourcePlugins, indexes))
|
|
619
|
+
removedDuplicatePluginCount += pluginItems.length
|
|
620
|
+
} catch {
|
|
621
|
+
unsafeCount += pluginItems.length
|
|
622
|
+
unsafePluginCount += pluginItems.length
|
|
623
|
+
}
|
|
624
|
+
} else {
|
|
625
|
+
unsafeCount += pluginItems.length
|
|
626
|
+
unsafePluginCount += pluginItems.length
|
|
627
|
+
}
|
|
628
|
+
} else {
|
|
629
|
+
const exactSourceDuplicates = pluginItems.every((item) =>
|
|
630
|
+
isDeepStrictEqual(item.value, pluginItems[0].value),
|
|
631
|
+
)
|
|
632
|
+
const targetSafe =
|
|
633
|
+
targetPlugins === undefined ||
|
|
634
|
+
(Array.isArray(targetPlugins) &&
|
|
635
|
+
!targetPlugins.some((plugin) => pluginReferenceIdentity(plugin) === 'src/plugin-v2'))
|
|
636
|
+
const canMove =
|
|
637
|
+
prefixSafe &&
|
|
638
|
+
exactSourceDuplicates &&
|
|
639
|
+
targetSafe &&
|
|
640
|
+
!targetHasSelector &&
|
|
641
|
+
!sourceHasSelector &&
|
|
642
|
+
!commentsWithin(source.ast, sourcePlugins.start, sourcePlugins.end)
|
|
643
|
+
if (canMove) {
|
|
644
|
+
moves.push({ kind: 'plugin', value: pluginItems[0].value })
|
|
645
|
+
removedDuplicatePluginCount += pluginItems.length - 1
|
|
646
|
+
const edit = removeArrayPrefixEdit(source, sourcePlugins, prefixCount)
|
|
647
|
+
if (edit) edits.push(edit)
|
|
648
|
+
} else {
|
|
649
|
+
unsafeCount += pluginItems.length
|
|
650
|
+
unsafePluginCount += pluginItems.length
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
const sourceMcpProperty = findProperty(source.ast, 'mcp')
|
|
657
|
+
const sourceMcpNode = sourceMcpProperty?.valueNode
|
|
658
|
+
if (sourceMcpNode?.type === 'object') {
|
|
659
|
+
const nestedProperty = findProperty(sourceMcpNode, 'servers')
|
|
660
|
+
const nested = validateMcpV1toV2Source(source.config.mcp).hasV2ServersMap
|
|
661
|
+
const sourceMap = nested ? nestedProperty.valueNode : sourceMcpNode
|
|
662
|
+
for (const [name, entry] of configuredMcpServers(source.config)) {
|
|
663
|
+
if (!isGeneratedMcpEntry(name, entry)) continue
|
|
664
|
+
const targetMcp = target.config?.mcp
|
|
665
|
+
const targetNested = isRecord(targetMcp) && validateMcpV1toV2Source(targetMcp).hasV2ServersMap
|
|
666
|
+
const targetMap = targetNested ? targetMcp.servers : isRecord(targetMcp) ? targetMcp : {}
|
|
667
|
+
if (
|
|
668
|
+
(targetMcp !== undefined && !isRecord(targetMcp)) ||
|
|
669
|
+
(isRecord(targetMcp) && targetMcp.servers !== undefined && !isRecord(targetMcp.servers))
|
|
670
|
+
) {
|
|
671
|
+
unsafeCount += 1
|
|
672
|
+
unsafeMcpNames.push(name)
|
|
673
|
+
continue
|
|
674
|
+
}
|
|
675
|
+
const prior = targetMap[name]
|
|
676
|
+
if (prior !== undefined && !isDeepStrictEqual(prior, entry)) {
|
|
677
|
+
unsafeCount += 1
|
|
678
|
+
unsafeMcpNames.push(name)
|
|
679
|
+
continue
|
|
680
|
+
}
|
|
681
|
+
try {
|
|
682
|
+
if (commentsWithin(source.ast, sourceMap.start, sourceMap.end)) {
|
|
683
|
+
throw new Error('Comments make the managed server map unsafe to edit.')
|
|
684
|
+
}
|
|
685
|
+
edits.push(removeObjectPropertyEdit(source, sourceMap, name))
|
|
686
|
+
removedMcpEntries.push({ name, value: entry, nested })
|
|
687
|
+
if (prior === undefined) moves.push({ kind: 'mcp', name, value: entry, nested })
|
|
688
|
+
} catch {
|
|
689
|
+
unsafeCount += 1
|
|
690
|
+
unsafeMcpNames.push(name)
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
return {
|
|
695
|
+
source,
|
|
696
|
+
target,
|
|
697
|
+
moves,
|
|
698
|
+
edits,
|
|
699
|
+
removedMcpEntries,
|
|
700
|
+
unsafeCount,
|
|
701
|
+
unsafePluginCount,
|
|
702
|
+
unsafeMcpNames: [...new Set(unsafeMcpNames)],
|
|
703
|
+
removedDuplicatePluginCount,
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
function addManagedEntriesToJson(config, moves, disabledMcpServers = []) {
|
|
708
|
+
for (const move of moves) {
|
|
709
|
+
if (move.kind === 'plugin') {
|
|
710
|
+
if (config.plugins === undefined) config.plugins = []
|
|
711
|
+
if (!Array.isArray(config.plugins)) throw new Error('Target plugin list is unsupported.')
|
|
712
|
+
config.plugins.push(move.value)
|
|
713
|
+
continue
|
|
714
|
+
}
|
|
715
|
+
if (config.mcp === undefined) config.mcp = {}
|
|
716
|
+
if (!isRecord(config.mcp)) throw new Error('Target MCP map is unsupported.')
|
|
717
|
+
let targetShape = validateMcpV1toV2Source(config.mcp)
|
|
718
|
+
if (move.nested && !targetShape.hasV2ServersMap && Object.hasOwn(config.mcp, 'servers')) {
|
|
719
|
+
config.mcp = migrateV1toV2({ mcp: config.mcp }).mcp
|
|
720
|
+
targetShape = validateMcpV1toV2Source(config.mcp)
|
|
721
|
+
}
|
|
722
|
+
const nested = move.nested || targetShape.hasV2ServersMap
|
|
723
|
+
if (nested) {
|
|
724
|
+
if (config.mcp.servers === undefined) config.mcp.servers = {}
|
|
725
|
+
if (!isRecord(config.mcp.servers)) throw new Error('Target MCP server map is unsupported.')
|
|
726
|
+
config.mcp.servers[move.name] = move.value
|
|
727
|
+
} else {
|
|
728
|
+
config.mcp[move.name] = move.value
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
for (const name of disabledMcpServers) {
|
|
732
|
+
if (!isRecord(config.mcp)) throw new Error('Target MCP map is unsupported.')
|
|
733
|
+
const nestedMap = isRecord(config.mcp.servers) && Object.hasOwn(config.mcp.servers, name)
|
|
734
|
+
const flatMap = Object.hasOwn(config.mcp, name)
|
|
735
|
+
const serverMap = nestedMap ? config.mcp.servers : flatMap ? config.mcp : null
|
|
736
|
+
if (!serverMap) throw new Error('Target MCP server is unavailable to disable.')
|
|
737
|
+
if (!isRecord(serverMap[name])) throw new Error('Target MCP server is unavailable to disable.')
|
|
738
|
+
serverMap[name] = { ...serverMap[name], disabled: true }
|
|
739
|
+
}
|
|
740
|
+
return config
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
function getMcpAskEntries(source) {
|
|
744
|
+
const policy = source.value
|
|
745
|
+
if (source.key === 'permission' && isRecord(policy) && isRecord(policy.mcp)) {
|
|
746
|
+
return Object.entries(policy.mcp)
|
|
747
|
+
.filter(([, effect]) => effect === 'ask')
|
|
748
|
+
.map(([server], index) => ({
|
|
749
|
+
id: `${source.id}#mcp:${server}`,
|
|
750
|
+
label: `legacy MCP rule ${index + 1} in ${source.file.name}`,
|
|
751
|
+
server,
|
|
752
|
+
kind: 'legacy',
|
|
753
|
+
}))
|
|
754
|
+
}
|
|
755
|
+
if (source.key === 'permissions' && Array.isArray(policy)) {
|
|
756
|
+
return policy
|
|
757
|
+
.map((rule, index) => ({ rule, index }))
|
|
758
|
+
.filter(
|
|
759
|
+
({ rule }) =>
|
|
760
|
+
isRecord(rule) &&
|
|
761
|
+
rule.effect === 'ask' &&
|
|
762
|
+
typeof rule.resource === 'string' &&
|
|
763
|
+
typeof rule.action === 'string' &&
|
|
764
|
+
opencodeWildcardMatch('*', rule.resource) &&
|
|
765
|
+
(source.mcpServers ?? []).some((server) => {
|
|
766
|
+
return mcpServerPermissionActions(server).some((action) =>
|
|
767
|
+
opencodeWildcardPatternsOverlap(rule.action, action),
|
|
768
|
+
)
|
|
769
|
+
}),
|
|
770
|
+
)
|
|
771
|
+
.map(({ rule, index }) => {
|
|
772
|
+
const matchingServers = (source.mcpServers ?? []).filter((server) => {
|
|
773
|
+
return mcpServerPermissionActions(server).some((action) =>
|
|
774
|
+
opencodeWildcardPatternsOverlap(rule.action, action),
|
|
775
|
+
)
|
|
776
|
+
})
|
|
777
|
+
return {
|
|
778
|
+
id: `${source.id}#mcp:${rule.action}:${rule.resource}:${index}`,
|
|
779
|
+
label: `V2 MCP rule ${index + 1} in ${source.file.name}`,
|
|
780
|
+
action: rule.action,
|
|
781
|
+
resource: rule.resource,
|
|
782
|
+
server: matchingServers.length === 1 ? matchingServers[0] : null,
|
|
783
|
+
scope: rule.action.endsWith('_*') ? 'server' : 'tool',
|
|
784
|
+
index,
|
|
785
|
+
kind: 'v2',
|
|
786
|
+
}
|
|
787
|
+
})
|
|
788
|
+
}
|
|
789
|
+
return []
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
function isRecord(value) {
|
|
793
|
+
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
function validateLegacyPolicy(value) {
|
|
797
|
+
if (!isRecord(value)) throw new Error('Legacy permission policy is malformed.')
|
|
798
|
+
for (const [action, rule] of Object.entries(value)) {
|
|
799
|
+
if (action === 'mcp') {
|
|
800
|
+
if (!isRecord(rule)) throw new Error('Legacy MCP permission policy is malformed.')
|
|
801
|
+
for (const [server, effect] of Object.entries(rule)) {
|
|
802
|
+
if (!MCP_SERVER_NAME.test(server) || !EFFECTS.has(effect)) {
|
|
803
|
+
throw new Error('Legacy MCP permission policy contains an unsupported value.')
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
continue
|
|
807
|
+
}
|
|
808
|
+
if (typeof rule === 'string') {
|
|
809
|
+
if (!EFFECTS.has(rule))
|
|
810
|
+
throw new Error('Legacy permission policy contains an unsupported effect.')
|
|
811
|
+
continue
|
|
812
|
+
}
|
|
813
|
+
if (!isRecord(rule)) throw new Error('Legacy permission policy contains an unsupported value.')
|
|
814
|
+
for (const effect of Object.values(rule)) {
|
|
815
|
+
if (!EFFECTS.has(effect))
|
|
816
|
+
throw new Error('Legacy permission policy contains an unsupported effect.')
|
|
817
|
+
}
|
|
818
|
+
}
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
function validateV2Policy(value) {
|
|
822
|
+
if (!Array.isArray(value)) throw new Error('V2 permissions policy is malformed.')
|
|
823
|
+
for (const rule of value) {
|
|
824
|
+
if (
|
|
825
|
+
!isRecord(rule) ||
|
|
826
|
+
typeof rule.action !== 'string' ||
|
|
827
|
+
typeof rule.resource !== 'string' ||
|
|
828
|
+
!EFFECTS.has(rule.effect)
|
|
829
|
+
) {
|
|
830
|
+
throw new Error('V2 permissions policy contains a malformed rule.')
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
|
|
835
|
+
function applyAskChoices(source, choices) {
|
|
836
|
+
const resolved = structuredClone(source.value)
|
|
837
|
+
for (const ask of getMcpAskEntries(source)) {
|
|
838
|
+
const choice = choices[ask.id]
|
|
839
|
+
if (!['allow', 'deny', 'accessible', 'disable'].includes(choice)) {
|
|
840
|
+
throw new Error('Every ineffective MCP ask rule needs an explicit policy choice.')
|
|
841
|
+
}
|
|
842
|
+
if (ask.kind === 'legacy') {
|
|
843
|
+
if (choice === 'allow' || choice === 'deny') resolved.mcp[ask.server] = choice
|
|
844
|
+
else delete resolved.mcp[ask.server]
|
|
845
|
+
} else if (choice === 'allow' || choice === 'deny') {
|
|
846
|
+
resolved[ask.index].effect = choice
|
|
847
|
+
} else {
|
|
848
|
+
resolved[ask.index] = null
|
|
849
|
+
}
|
|
850
|
+
}
|
|
851
|
+
return Array.isArray(resolved) ? resolved.filter((rule) => rule !== null) : resolved
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
function makeV2Policy(source, askChoices) {
|
|
855
|
+
if (source.key === 'permission') {
|
|
856
|
+
validateLegacyPolicy(source.value)
|
|
857
|
+
const permission = applyAskChoices(source, askChoices)
|
|
858
|
+
const converted = migrateV1toV2({ permission }, { mcpServerNames: source.mcpServers ?? [] })
|
|
859
|
+
const policy = converted.permissions ?? []
|
|
860
|
+
validateV2Policy(policy)
|
|
861
|
+
return policy
|
|
862
|
+
}
|
|
863
|
+
validateV2Policy(source.value)
|
|
864
|
+
return applyAskChoices(source, askChoices)
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
function hasCrossLayerPermissionConflict(files, sources, selectedSources, askChoices) {
|
|
868
|
+
const policies = []
|
|
869
|
+
for (const source of sources) {
|
|
870
|
+
const selected = selectedSources.get(source.file.path)
|
|
871
|
+
if (selected && selected.id !== source.id) continue
|
|
872
|
+
const policy =
|
|
873
|
+
selected || source.key === 'permission' ? makeV2Policy(source, askChoices) : source.value
|
|
874
|
+
policies.push({ source, policy })
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
const ordered = []
|
|
878
|
+
for (const file of files) {
|
|
879
|
+
for (const { source, policy } of policies) {
|
|
880
|
+
if (source.file.path !== file.path) continue
|
|
881
|
+
for (const rule of policy) {
|
|
882
|
+
if (isRecord(rule)) ordered.push({ source, rule })
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
|
|
887
|
+
for (let earlierIndex = 0; earlierIndex < ordered.length; earlierIndex += 1) {
|
|
888
|
+
const earlier = ordered[earlierIndex]
|
|
889
|
+
for (let laterIndex = earlierIndex + 1; laterIndex < ordered.length; laterIndex += 1) {
|
|
890
|
+
const later = ordered[laterIndex]
|
|
891
|
+
if (
|
|
892
|
+
later.rule.effect === earlier.rule.effect ||
|
|
893
|
+
!opencodeWildcardPatternsOverlap(earlier.rule.action, later.rule.action) ||
|
|
894
|
+
!opencodeWildcardPatternsOverlap(earlier.rule.resource, later.rule.resource)
|
|
895
|
+
) {
|
|
896
|
+
continue
|
|
897
|
+
}
|
|
898
|
+
const crossSource =
|
|
899
|
+
earlier.source.file.path !== later.source.file.path ||
|
|
900
|
+
earlier.source.key !== later.source.key
|
|
901
|
+
if (crossSource) return true
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
return false
|
|
905
|
+
}
|
|
906
|
+
|
|
907
|
+
function hasNativeCrossLayerPermissionConflict(files, sources) {
|
|
908
|
+
const nativeSources = sources.filter((source) => source.key === 'permissions')
|
|
909
|
+
const policies = nativeSources.map((source) => ({ source, policy: source.value }))
|
|
910
|
+
return nativePoliciesConflict(files, policies)
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
function nativePoliciesConflict(files, policies) {
|
|
914
|
+
const ordered = []
|
|
915
|
+
for (const file of files) {
|
|
916
|
+
for (const { source, policy } of policies) {
|
|
917
|
+
if (source.file.path !== file.path) continue
|
|
918
|
+
if (!Array.isArray(policy)) return true
|
|
919
|
+
for (const rule of policy) {
|
|
920
|
+
if (
|
|
921
|
+
isRecord(rule) &&
|
|
922
|
+
typeof rule.action === 'string' &&
|
|
923
|
+
typeof rule.resource === 'string' &&
|
|
924
|
+
EFFECTS.has(rule.effect)
|
|
925
|
+
) {
|
|
926
|
+
ordered.push({ source, rule })
|
|
927
|
+
}
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
}
|
|
931
|
+
for (let i = 0; i < ordered.length; i += 1) {
|
|
932
|
+
const earlier = ordered[i]
|
|
933
|
+
for (let j = i + 1; j < ordered.length; j += 1) {
|
|
934
|
+
const later = ordered[j]
|
|
935
|
+
if (
|
|
936
|
+
later.source.file.path !== earlier.source.file.path &&
|
|
937
|
+
later.rule.effect !== earlier.rule.effect &&
|
|
938
|
+
opencodeWildcardPatternsOverlap(earlier.rule.action, later.rule.action) &&
|
|
939
|
+
opencodeWildcardPatternsOverlap(earlier.rule.resource, later.rule.resource)
|
|
940
|
+
) {
|
|
941
|
+
return true
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
return false
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
function commentsWithin(ast, start, end) {
|
|
949
|
+
return ast.comments.some((comment) => comment.start >= start && comment.end <= end)
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
function findProperty(node, key) {
|
|
953
|
+
return node?.type === 'object' ? node.properties.find((property) => property.key === key) : null
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
function setObjectFieldEdit(file, objectNode, key, value) {
|
|
957
|
+
if (objectNode?.type !== 'object') {
|
|
958
|
+
throw new Error('A selected MCP server entry cannot be safely edited.')
|
|
959
|
+
}
|
|
960
|
+
const property = findProperty(objectNode, key)
|
|
961
|
+
if (property) {
|
|
962
|
+
if (commentsWithin(file.ast, property.valueStart, property.valueEnd)) {
|
|
963
|
+
throw new Error(
|
|
964
|
+
'The selected MCP server field contains a comment; it cannot be safely edited.',
|
|
965
|
+
)
|
|
966
|
+
}
|
|
967
|
+
return { start: property.valueStart, end: property.valueEnd, text: JSON.stringify(value) }
|
|
968
|
+
}
|
|
969
|
+
if (commentsWithin(file.ast, objectNode.start, objectNode.closeStart)) {
|
|
970
|
+
throw new Error('The selected MCP server entry has comments; it cannot be safely edited.')
|
|
971
|
+
}
|
|
972
|
+
const last = objectNode.properties.at(-1)
|
|
973
|
+
const hasTrailingComma = last?.commaAfter !== null && last?.commaAfter !== undefined
|
|
974
|
+
const multiline = file.content.slice(objectNode.start, objectNode.closeStart).includes('\n')
|
|
975
|
+
const parentIndent = indentAt(file.content, objectNode.start)
|
|
976
|
+
const childIndent = last ? indentAt(file.content, last.keyStart) : `${parentIndent} `
|
|
977
|
+
const prefix = last && !hasTrailingComma ? ',' : ''
|
|
978
|
+
const text = multiline
|
|
979
|
+
? `${prefix}\n${childIndent}${JSON.stringify(key)}: ${JSON.stringify(value)}\n${parentIndent}`
|
|
980
|
+
: `${prefix}${last ? ' ' : ''}${JSON.stringify(key)}: ${JSON.stringify(value)} `
|
|
981
|
+
return { start: objectNode.closeStart, end: objectNode.closeStart, text }
|
|
982
|
+
}
|
|
983
|
+
|
|
984
|
+
function effectiveMcpServer(files, name) {
|
|
985
|
+
let effective = null
|
|
986
|
+
for (const file of files) {
|
|
987
|
+
if (!file.exists || file.parseError) continue
|
|
988
|
+
const mcpNode = findProperty(file.ast, 'mcp')?.valueNode
|
|
989
|
+
if (mcpNode?.type !== 'object') continue
|
|
990
|
+
const serversProperty = findProperty(mcpNode, 'servers')
|
|
991
|
+
const nested = validateMcpV1toV2Source(file.config.mcp).hasV2ServersMap
|
|
992
|
+
const serverMapNode = nested ? serversProperty.valueNode : mcpNode
|
|
993
|
+
const serverProperty = findProperty(serverMapNode, name)
|
|
994
|
+
if (serverProperty?.valueNode?.type === 'object') {
|
|
995
|
+
effective = { file, server: serverProperty.valueNode, nested }
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
return effective
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
function indentAt(source, offset) {
|
|
1002
|
+
const lineStart = source.lastIndexOf('\n', offset - 1) + 1
|
|
1003
|
+
return /^[\t ]*/.exec(source.slice(lineStart, offset))[0]
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
function formatValue(value, indent) {
|
|
1007
|
+
return JSON.stringify(value, null, 2)
|
|
1008
|
+
.split('\n')
|
|
1009
|
+
.map((line, index) => (index === 0 ? line : `${indent}${line}`))
|
|
1010
|
+
.join('\n')
|
|
1011
|
+
}
|
|
1012
|
+
|
|
1013
|
+
function applyTextEdits(source, edits) {
|
|
1014
|
+
let result = source
|
|
1015
|
+
for (const edit of [...edits].sort((a, b) => b.start - a.start)) {
|
|
1016
|
+
result = `${result.slice(0, edit.start)}${edit.text}${result.slice(edit.end)}`
|
|
1017
|
+
}
|
|
1018
|
+
return result
|
|
1019
|
+
}
|
|
1020
|
+
|
|
1021
|
+
function editConfig(file, policy, extraEdits = []) {
|
|
1022
|
+
const { ast, content } = file
|
|
1023
|
+
const properties = new Map(ast.properties.map((property) => [property.key, property]))
|
|
1024
|
+
const legacy = properties.get('permission')
|
|
1025
|
+
const native = properties.get('permissions')
|
|
1026
|
+
const edits = [...extraEdits]
|
|
1027
|
+
|
|
1028
|
+
if (legacy && commentsWithin(ast, legacy.valueStart, legacy.valueEnd)) {
|
|
1029
|
+
throw new Error(
|
|
1030
|
+
`${file.name} has comments inside the legacy permission value; it is preview-only to preserve comments.`,
|
|
1031
|
+
)
|
|
1032
|
+
}
|
|
1033
|
+
if (native && commentsWithin(ast, native.valueStart, native.valueEnd)) {
|
|
1034
|
+
throw new Error(
|
|
1035
|
+
`${file.name} has comments inside the permissions value; it is preview-only to preserve comments.`,
|
|
1036
|
+
)
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
if (native) {
|
|
1040
|
+
const indent = indentAt(content, native.keyStart)
|
|
1041
|
+
edits.push({
|
|
1042
|
+
start: native.valueStart,
|
|
1043
|
+
end: native.valueEnd,
|
|
1044
|
+
text: formatValue(policy, indent),
|
|
1045
|
+
})
|
|
1046
|
+
if (legacy) {
|
|
1047
|
+
if (commentsWithin(ast, legacy.keyStart, legacy.valueEnd)) {
|
|
1048
|
+
throw new Error(
|
|
1049
|
+
`${file.name} has comments attached to both permission keys; it is preview-only.`,
|
|
1050
|
+
)
|
|
1051
|
+
}
|
|
1052
|
+
if (legacy.commaAfter !== null) {
|
|
1053
|
+
if (commentsWithin(ast, legacy.keyStart, legacy.commaAfter + 1)) {
|
|
1054
|
+
throw new Error(
|
|
1055
|
+
`${file.name} has comments next to the legacy permission key; it is preview-only.`,
|
|
1056
|
+
)
|
|
1057
|
+
}
|
|
1058
|
+
edits.push({ start: legacy.keyStart, end: legacy.commaAfter + 1, text: '' })
|
|
1059
|
+
} else if (legacy.commaBefore !== null) {
|
|
1060
|
+
if (commentsWithin(ast, legacy.commaBefore, legacy.valueEnd)) {
|
|
1061
|
+
throw new Error(
|
|
1062
|
+
`${file.name} has comments next to the legacy permission key; it is preview-only.`,
|
|
1063
|
+
)
|
|
1064
|
+
}
|
|
1065
|
+
edits.push({ start: legacy.commaBefore, end: legacy.valueEnd, text: '' })
|
|
1066
|
+
} else {
|
|
1067
|
+
edits.push({ start: legacy.keyStart, end: legacy.valueEnd, text: '' })
|
|
1068
|
+
}
|
|
1069
|
+
}
|
|
1070
|
+
} else if (legacy) {
|
|
1071
|
+
const indent = indentAt(content, legacy.keyStart)
|
|
1072
|
+
edits.push({ start: legacy.keyStart, end: legacy.keyEnd, text: '"permissions"' })
|
|
1073
|
+
edits.push({
|
|
1074
|
+
start: legacy.valueStart,
|
|
1075
|
+
end: legacy.valueEnd,
|
|
1076
|
+
text: formatValue(policy, indent),
|
|
1077
|
+
})
|
|
1078
|
+
} else {
|
|
1079
|
+
const last = ast.properties.at(-1)
|
|
1080
|
+
const indent = last ? indentAt(content, last.keyStart) : ' '
|
|
1081
|
+
const beforeClose = content.slice(last?.valueEnd ?? ast.start + 1, ast.closeStart)
|
|
1082
|
+
if (commentsWithin(ast, last?.valueEnd ?? ast.start + 1, ast.closeStart)) {
|
|
1083
|
+
throw new Error(`${file.name} has trailing comments at the root; it is preview-only.`)
|
|
1084
|
+
}
|
|
1085
|
+
const hasTrailingComma = last?.commaAfter !== null && last?.commaAfter !== undefined
|
|
1086
|
+
const prefix = last ? (hasTrailingComma ? '' : ',') : ''
|
|
1087
|
+
const linePrefix = beforeClose.includes('\n') || content.includes('\n') ? '\n' : ' '
|
|
1088
|
+
const suffix = linePrefix
|
|
1089
|
+
const insertion = `${prefix}${linePrefix}${indent}"permissions": ${formatValue(policy, indent)}${suffix}`
|
|
1090
|
+
edits.push({ start: ast.closeStart, end: ast.closeStart, text: insertion })
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
const updated = applyTextEdits(content, edits)
|
|
1094
|
+
parseConfig(updated, file.format === 'jsonc')
|
|
1095
|
+
return updated
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
function emit(output, text = '') {
|
|
1099
|
+
if (typeof output === 'function') output(text)
|
|
1100
|
+
else if (typeof output.write === 'function') output.write(`${text}\n`)
|
|
1101
|
+
else output.log?.(text)
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
function printPolicyPreview(file, policy, output) {
|
|
1105
|
+
emit(output, `Proposed policy: ${file.name}: ${policy.length} ordered V2 rule(s).`)
|
|
1106
|
+
for (const [index, rule] of policy.entries()) {
|
|
1107
|
+
if (!isRecord(rule)) continue
|
|
1108
|
+
emit(
|
|
1109
|
+
output,
|
|
1110
|
+
`Policy rule ${index + 1}: action=${reviewPolicyValue(rule.action, 'action')}; ` +
|
|
1111
|
+
`resource=${reviewPolicyValue(rule.resource, 'resource')}; effect=${EFFECTS.has(rule.effect) ? rule.effect : '[redacted]'}.`,
|
|
1112
|
+
)
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
|
|
1116
|
+
const SENSITIVE_POLICY_VALUE =
|
|
1117
|
+
/(?:^|[^a-z0-9])(?:sk-|gh[pousr]_|github_pat_|xox[baprs]-|akia|secret|token|password|credential)/i
|
|
1118
|
+
|
|
1119
|
+
function reviewPolicyValue(value, kind) {
|
|
1120
|
+
if (
|
|
1121
|
+
typeof value !== 'string' ||
|
|
1122
|
+
value.length === 0 ||
|
|
1123
|
+
value.length > 96 ||
|
|
1124
|
+
/[\r\n\0]/.test(value) ||
|
|
1125
|
+
path.isAbsolute(value) ||
|
|
1126
|
+
path.win32.isAbsolute(value) ||
|
|
1127
|
+
SENSITIVE_POLICY_VALUE.test(value)
|
|
1128
|
+
) {
|
|
1129
|
+
return '[redacted]'
|
|
1130
|
+
}
|
|
1131
|
+
const allowed =
|
|
1132
|
+
kind === 'action' ? /^[A-Za-z][A-Za-z0-9._-]*(?:_[A-Za-z0-9.*-]+)?$/ : /^[A-Za-z0-9_*?. /-]+$/
|
|
1133
|
+
if (!allowed.test(value) || value.split('/').includes('..')) return '[redacted]'
|
|
1134
|
+
return value
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
function printInspection(files, sources, output) {
|
|
1138
|
+
emit(output, 'V2 config preflight (read-only; no files have been changed):')
|
|
1139
|
+
emit(
|
|
1140
|
+
output,
|
|
1141
|
+
'OpenCode V2 loads opencode.json then opencode.jsonc. MCP servers merge by name, later server objects replace earlier ones, and permission arrays append in file order.',
|
|
1142
|
+
)
|
|
1143
|
+
for (const file of files) {
|
|
1144
|
+
if (!file.exists) {
|
|
1145
|
+
emit(output, `- ${file.name}: not present`)
|
|
1146
|
+
continue
|
|
1147
|
+
}
|
|
1148
|
+
if (file.directoryError) {
|
|
1149
|
+
emit(output, `- ${file.name}: blocked (unsafe path or file type).`)
|
|
1150
|
+
continue
|
|
1151
|
+
}
|
|
1152
|
+
if (file.parseError) {
|
|
1153
|
+
emit(output, `- ${file.name}: cannot safely parse; no changes proposed.`)
|
|
1154
|
+
continue
|
|
1155
|
+
}
|
|
1156
|
+
const relevant = ['permission', 'permissions']
|
|
1157
|
+
.filter((key) => Object.hasOwn(file.config, key))
|
|
1158
|
+
.map((key) => `${key} policy present`)
|
|
1159
|
+
const managed = inspectInstallerEntries(file.config)
|
|
1160
|
+
if (managed.plugins.length > 0)
|
|
1161
|
+
relevant.push(`Pantheon V2 plugin entry: ${managed.plugins.length}`)
|
|
1162
|
+
if (managed.mcp.length > 0)
|
|
1163
|
+
relevant.push(`verified Pantheon MCP entries: ${managed.mcp.length}`)
|
|
1164
|
+
emit(
|
|
1165
|
+
output,
|
|
1166
|
+
`- ${file.name}: ${relevant.length ? relevant.join('; ') : 'no permission policy keys'}`,
|
|
1167
|
+
)
|
|
1168
|
+
}
|
|
1169
|
+
for (const file of files) {
|
|
1170
|
+
const localSources = sources.filter((source) => source.file.path === file.path)
|
|
1171
|
+
if (localSources.length > 1) {
|
|
1172
|
+
emit(
|
|
1173
|
+
output,
|
|
1174
|
+
`Conflict in ${file.name}: both legacy and V2 permission policies are present; choose the policy source for this file.`,
|
|
1175
|
+
)
|
|
1176
|
+
}
|
|
1177
|
+
}
|
|
1178
|
+
for (const source of sources) {
|
|
1179
|
+
for (const [index] of getMcpAskEntries(source).entries()) {
|
|
1180
|
+
emit(
|
|
1181
|
+
output,
|
|
1182
|
+
`Ineffective MCP ask detected: rule ${index + 1} in ${source.file.name}; an explicit outcome is required.`,
|
|
1183
|
+
)
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
}
|
|
1187
|
+
|
|
1188
|
+
function terminalPrompts() {
|
|
1189
|
+
return clack
|
|
1190
|
+
}
|
|
1191
|
+
|
|
1192
|
+
/** Collect source-aware V2 config choices and return a write-free operation plan. */
|
|
1193
|
+
export async function prepareV2Config({
|
|
1194
|
+
configDir,
|
|
1195
|
+
interactive = false,
|
|
1196
|
+
prompts = terminalPrompts(),
|
|
1197
|
+
output = console,
|
|
1198
|
+
filesystem = fs,
|
|
1199
|
+
dryRun = false,
|
|
1200
|
+
} = {}) {
|
|
1201
|
+
const files = inspectConfigFiles(configDir, filesystem)
|
|
1202
|
+
const directoryFailure = files.find((file) => file.directoryError)
|
|
1203
|
+
const parseFailure = files.find((file) => file.exists && file.parseError)
|
|
1204
|
+
if (directoryFailure || parseFailure) {
|
|
1205
|
+
printInspection(files, policySources(files), output)
|
|
1206
|
+
if (directoryFailure)
|
|
1207
|
+
return { status: 'blocked', reason: directoryFailure.parseError, changes: [] }
|
|
1208
|
+
return {
|
|
1209
|
+
status: 'blocked',
|
|
1210
|
+
reason: `${parseFailure.name} is not valid ${parseFailure.format.toUpperCase()}.`,
|
|
1211
|
+
changes: [],
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1214
|
+
|
|
1215
|
+
const malformedMcpFile = files.find((file) => {
|
|
1216
|
+
if (!file.exists || file.config?.mcp === undefined) return false
|
|
1217
|
+
try {
|
|
1218
|
+
validateMcpV1toV2Source(file.config.mcp)
|
|
1219
|
+
return false
|
|
1220
|
+
} catch {
|
|
1221
|
+
return true
|
|
1222
|
+
}
|
|
1223
|
+
})
|
|
1224
|
+
if (malformedMcpFile) {
|
|
1225
|
+
const reason =
|
|
1226
|
+
`${malformedMcpFile.name} contains a malformed or ambiguous MCP configuration; ` +
|
|
1227
|
+
'setup stopped before writes.'
|
|
1228
|
+
printInspection(files, [], output)
|
|
1229
|
+
emit(output, reason)
|
|
1230
|
+
return { status: 'blocked', reason, changes: [], configDir }
|
|
1231
|
+
}
|
|
1232
|
+
|
|
1233
|
+
const flatJsoncMcpEntries = files.reduce(
|
|
1234
|
+
(total, file) => total + flatThirdPartyMcpEntryCount(file),
|
|
1235
|
+
0,
|
|
1236
|
+
)
|
|
1237
|
+
if (flatJsoncMcpEntries > 0) {
|
|
1238
|
+
const reason =
|
|
1239
|
+
`opencode.jsonc contains ${flatJsoncMcpEntries} flat third-party MCP server ` +
|
|
1240
|
+
`${flatJsoncMcpEntries === 1 ? 'entry' : 'entries'} at redacted path mcp.<redacted>. ` +
|
|
1241
|
+
'Convert them manually to mcp.servers or remove them before retrying V2 setup.'
|
|
1242
|
+
printInspection(files, policySources(files), output)
|
|
1243
|
+
emit(output, reason)
|
|
1244
|
+
return { status: 'blocked', reason, changes: [], configDir }
|
|
1245
|
+
}
|
|
1246
|
+
|
|
1247
|
+
const sources = policySources(files)
|
|
1248
|
+
const entryPlan = managedEntryMovePlan(files)
|
|
1249
|
+
printInspection(files, sources, output)
|
|
1250
|
+
|
|
1251
|
+
if (hasNativeCrossLayerPermissionConflict(files, sources)) {
|
|
1252
|
+
const reason =
|
|
1253
|
+
'Overlapping permission layers have conflicting effects; resolve the layers before setup.'
|
|
1254
|
+
emit(output, reason)
|
|
1255
|
+
return { status: 'blocked', reason, changes: [], configDir }
|
|
1256
|
+
}
|
|
1257
|
+
|
|
1258
|
+
if (entryPlan.unsafePluginCount > 0) {
|
|
1259
|
+
const reason =
|
|
1260
|
+
'A verified Pantheon plugin entry cannot be migrated or deduplicated safely in the V2 init preview; setup stopped before writes.'
|
|
1261
|
+
emit(output, reason)
|
|
1262
|
+
return { status: 'blocked', reason, changes: [], configDir }
|
|
1263
|
+
}
|
|
1264
|
+
const sourcesFor = (file) => sources.filter((source) => source.file.path === file.path)
|
|
1265
|
+
const askEntries = sources.flatMap((source) => getMcpAskEntries(source))
|
|
1266
|
+
const needsLegacyConversion = sources.some((source) => source.key === 'permission')
|
|
1267
|
+
|
|
1268
|
+
if (
|
|
1269
|
+
entryPlan.unsafeCount === 0 &&
|
|
1270
|
+
entryPlan.moves.length === 0 &&
|
|
1271
|
+
entryPlan.edits.length === 0 &&
|
|
1272
|
+
(sources.length === 0 || (!needsLegacyConversion && askEntries.length === 0))
|
|
1273
|
+
) {
|
|
1274
|
+
emit(output, 'No permission-policy migration is required.')
|
|
1275
|
+
return {
|
|
1276
|
+
status: 'unchanged',
|
|
1277
|
+
changes: [],
|
|
1278
|
+
configDir,
|
|
1279
|
+
unsafeMcpNames: entryPlan.unsafeMcpNames,
|
|
1280
|
+
configPreconditions: makeConfigPreconditions(files),
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
if (!interactive || dryRun) {
|
|
1285
|
+
emit(
|
|
1286
|
+
output,
|
|
1287
|
+
'Preview only. Rerun `npm run setup` in an interactive terminal to review and authorize setup.',
|
|
1288
|
+
)
|
|
1289
|
+
if (entryPlan.moves.length > 0) {
|
|
1290
|
+
emit(
|
|
1291
|
+
output,
|
|
1292
|
+
`Managed-entry migration: ${entryPlan.moves.length} verified JSONC entry/entries can be moved without reordering.`,
|
|
1293
|
+
)
|
|
1294
|
+
}
|
|
1295
|
+
if (entryPlan.removedDuplicatePluginCount > 0) {
|
|
1296
|
+
emit(
|
|
1297
|
+
output,
|
|
1298
|
+
`Managed-entry migration: ${entryPlan.removedDuplicatePluginCount} exact duplicate Pantheon plugin entry/entries can be removed from JSONC.`,
|
|
1299
|
+
)
|
|
1300
|
+
}
|
|
1301
|
+
if (entryPlan.unsafeCount > 0) {
|
|
1302
|
+
emit(
|
|
1303
|
+
output,
|
|
1304
|
+
`${entryPlan.unsafeCount} verified JSONC entry/entries need an explicit keep-in-place or abort choice.`,
|
|
1305
|
+
)
|
|
1306
|
+
}
|
|
1307
|
+
return { status: 'preview', changes: [], configDir }
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
if (entryPlan.unsafeCount > 0) {
|
|
1311
|
+
const selected = await prompts.select({
|
|
1312
|
+
message:
|
|
1313
|
+
'Some verified Pantheon entries cannot be moved without risking order, selector, or same-name override changes. Continue leaving them in JSONC, or abort setup?',
|
|
1314
|
+
options: [
|
|
1315
|
+
{ value: 'abort', label: 'Abort setup' },
|
|
1316
|
+
{ value: 'keep', label: 'Continue, leaving those entries unchanged' },
|
|
1317
|
+
],
|
|
1318
|
+
})
|
|
1319
|
+
if (prompts.isCancel?.(selected) || selected === 'abort') {
|
|
1320
|
+
prompts.cancel?.('Setup stopped because a JSONC entry could not be migrated safely.')
|
|
1321
|
+
return { status: 'skipped', changes: [], configDir }
|
|
1322
|
+
}
|
|
1323
|
+
if (selected !== 'keep') {
|
|
1324
|
+
return { status: 'blocked', reason: 'Unsafe managed-entry choice.', changes: [], configDir }
|
|
1325
|
+
}
|
|
1326
|
+
emit(output, `User choice: leave ${entryPlan.unsafeCount} verified entry/entries in JSONC.`)
|
|
1327
|
+
}
|
|
1328
|
+
|
|
1329
|
+
const askChoices = Object.create(null)
|
|
1330
|
+
const disableCandidates = new Map()
|
|
1331
|
+
const disableCandidateNames = new Map()
|
|
1332
|
+
for (const ask of sources.flatMap((source) => getMcpAskEntries(source))) {
|
|
1333
|
+
const server = ask.server ? effectiveMcpServer(files, ask.server) : null
|
|
1334
|
+
const supportsDisable = server?.nested === true
|
|
1335
|
+
const scope = ask.scope === 'tool' ? 'this MCP rule' : 'every tool for this MCP server'
|
|
1336
|
+
const options = [
|
|
1337
|
+
{ value: 'deny', label: `Deny ${scope}` },
|
|
1338
|
+
...(supportsDisable ? [{ value: 'disable', label: 'Disable this MCP server' }] : []),
|
|
1339
|
+
{ value: 'accessible', label: 'Leave accessible without a prompt (no rule)' },
|
|
1340
|
+
{ value: 'allow', label: `Allow ${scope}` },
|
|
1341
|
+
]
|
|
1342
|
+
const selected = await prompts.select({
|
|
1343
|
+
message: `MCP policy ${ask.label} is ineffective in V2. Choose an explicit outcome:`,
|
|
1344
|
+
options,
|
|
1345
|
+
})
|
|
1346
|
+
if (prompts.isCancel?.(selected) || !options.some(({ value }) => value === selected)) {
|
|
1347
|
+
prompts.cancel?.('MCP policy choice missing; no files were changed.')
|
|
1348
|
+
return { status: 'canceled', changes: [], configDir }
|
|
1349
|
+
}
|
|
1350
|
+
if (selected === 'disable' && ask.server && server) {
|
|
1351
|
+
disableCandidates.set(ask.id, server)
|
|
1352
|
+
disableCandidateNames.set(ask.id, ask.server)
|
|
1353
|
+
}
|
|
1354
|
+
askChoices[ask.id] = selected
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
const requiredPaths = new Set(
|
|
1358
|
+
sources
|
|
1359
|
+
.filter((source) => source.key === 'permission' || getMcpAskEntries(source).length > 0)
|
|
1360
|
+
.map((source) => source.file.path),
|
|
1361
|
+
)
|
|
1362
|
+
if (entryPlan.moves.length > 0) {
|
|
1363
|
+
if (entryPlan.source) requiredPaths.add(entryPlan.source.path)
|
|
1364
|
+
if (entryPlan.target) requiredPaths.add(entryPlan.target.path)
|
|
1365
|
+
}
|
|
1366
|
+
if (entryPlan.edits.length > 0 && entryPlan.source) requiredPaths.add(entryPlan.source.path)
|
|
1367
|
+
for (const server of disableCandidates.values()) requiredPaths.add(server.file.path)
|
|
1368
|
+
if (
|
|
1369
|
+
[...disableCandidates].some(([askId, server]) => {
|
|
1370
|
+
const name = disableCandidateNames.get(askId)
|
|
1371
|
+
return (
|
|
1372
|
+
server.file.path === entryPlan.source?.path &&
|
|
1373
|
+
entryPlan.removedMcpEntries.some((entry) => entry.name === name)
|
|
1374
|
+
)
|
|
1375
|
+
}) &&
|
|
1376
|
+
entryPlan.target
|
|
1377
|
+
) {
|
|
1378
|
+
requiredPaths.add(entryPlan.target.path)
|
|
1379
|
+
}
|
|
1380
|
+
const targetOptions = files
|
|
1381
|
+
.filter((file) => requiredPaths.has(file.path))
|
|
1382
|
+
.map((file) => ({
|
|
1383
|
+
value: file.path,
|
|
1384
|
+
label: file.name,
|
|
1385
|
+
hint: 'Select explicitly to allow this file to be changed.',
|
|
1386
|
+
}))
|
|
1387
|
+
if (targetOptions.length === 0) {
|
|
1388
|
+
return {
|
|
1389
|
+
status: 'unchanged',
|
|
1390
|
+
changes: [],
|
|
1391
|
+
configDir,
|
|
1392
|
+
unsafeMcpNames: entryPlan.unsafeMcpNames,
|
|
1393
|
+
configPreconditions: makeConfigPreconditions(files),
|
|
1394
|
+
}
|
|
1395
|
+
}
|
|
1396
|
+
const targetAnswer = await prompts.multiselect({
|
|
1397
|
+
message: 'Which existing config file(s) may be changed?',
|
|
1398
|
+
options: targetOptions,
|
|
1399
|
+
initialValues: [],
|
|
1400
|
+
required: false,
|
|
1401
|
+
})
|
|
1402
|
+
if (
|
|
1403
|
+
prompts.isCancel?.(targetAnswer) ||
|
|
1404
|
+
!Array.isArray(targetAnswer) ||
|
|
1405
|
+
targetAnswer.length === 0
|
|
1406
|
+
) {
|
|
1407
|
+
prompts.cancel?.('Config preparation canceled; files were not changed.')
|
|
1408
|
+
return { status: 'canceled', changes: [], configDir }
|
|
1409
|
+
}
|
|
1410
|
+
const targets = files.filter((file) => targetAnswer.includes(file.path))
|
|
1411
|
+
if ([...requiredPaths].some((filePath) => !targetAnswer.includes(filePath))) {
|
|
1412
|
+
const reason = 'Every file with legacy or ineffective MCP ask rules must be reviewed.'
|
|
1413
|
+
emit(output, reason)
|
|
1414
|
+
return { status: 'blocked', reason, changes: [], configDir }
|
|
1415
|
+
}
|
|
1416
|
+
|
|
1417
|
+
const selectedSources = new Map()
|
|
1418
|
+
try {
|
|
1419
|
+
for (const target of targets) {
|
|
1420
|
+
const localSources = sourcesFor(target)
|
|
1421
|
+
if (localSources.length === 0) continue
|
|
1422
|
+
let selectedSource = localSources[0]
|
|
1423
|
+
if (localSources.length > 1) {
|
|
1424
|
+
const selected = await prompts.select({
|
|
1425
|
+
message: `Which policy in ${target.name} should remain? Choosing one removes the other policy key.`,
|
|
1426
|
+
options: localSources.map((source) => ({
|
|
1427
|
+
value: source.id,
|
|
1428
|
+
label: source.key,
|
|
1429
|
+
hint: 'Policy values are not displayed.',
|
|
1430
|
+
})),
|
|
1431
|
+
})
|
|
1432
|
+
if (prompts.isCancel?.(selected) || !selected) {
|
|
1433
|
+
prompts.cancel?.('Policy source not selected; files were not changed.')
|
|
1434
|
+
return { status: 'canceled', changes: [], configDir }
|
|
1435
|
+
}
|
|
1436
|
+
selectedSource = localSources.find((source) => source.id === selected)
|
|
1437
|
+
if (!selectedSource) {
|
|
1438
|
+
return {
|
|
1439
|
+
status: 'blocked',
|
|
1440
|
+
reason: 'The selected policy source is invalid.',
|
|
1441
|
+
changes: [],
|
|
1442
|
+
configDir,
|
|
1443
|
+
}
|
|
1444
|
+
}
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
selectedSources.set(target.path, selectedSource)
|
|
1448
|
+
}
|
|
1449
|
+
} catch {
|
|
1450
|
+
emit(output, 'Preview blocked: selected policy data could not be safely converted.')
|
|
1451
|
+
return {
|
|
1452
|
+
status: 'blocked',
|
|
1453
|
+
reason: 'Selected policy data is unsupported.',
|
|
1454
|
+
changes: [],
|
|
1455
|
+
configDir,
|
|
1456
|
+
}
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
for (const source of selectedSources.values()) {
|
|
1460
|
+
for (const ask of getMcpAskEntries(source)) {
|
|
1461
|
+
const outcome = askChoices[ask.id]
|
|
1462
|
+
if (!outcome) continue
|
|
1463
|
+
const actions = ask.action
|
|
1464
|
+
? [ask.action]
|
|
1465
|
+
: ask.server
|
|
1466
|
+
? mcpServerPermissionActions(ask.server)
|
|
1467
|
+
: ['[redacted]']
|
|
1468
|
+
emit(
|
|
1469
|
+
output,
|
|
1470
|
+
`MCP policy outcome: ${source.file.name} ${source.key} rule → ${outcome}; ` +
|
|
1471
|
+
`action=${actions.map((action) => reviewPolicyValue(action, 'action')).join(' + ')}; ` +
|
|
1472
|
+
`resource=${reviewPolicyValue(ask.resource ?? '*', 'resource')}.`,
|
|
1473
|
+
)
|
|
1474
|
+
}
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
// Ask outcomes only affect the source the user selected to retain. In
|
|
1478
|
+
// particular, a `disable` answer attached to a discarded same-file policy
|
|
1479
|
+
// must not mutate the MCP server independently of that source.
|
|
1480
|
+
const disabledServers = new Map()
|
|
1481
|
+
for (const source of selectedSources.values()) {
|
|
1482
|
+
for (const ask of getMcpAskEntries(source)) {
|
|
1483
|
+
if (askChoices[ask.id] !== 'disable' || !ask.server) continue
|
|
1484
|
+
const server = effectiveMcpServer(files, ask.server)
|
|
1485
|
+
if (server) disabledServers.set(ask.server, server)
|
|
1486
|
+
}
|
|
1487
|
+
}
|
|
1488
|
+
const relocatedDisabledServers = new Set()
|
|
1489
|
+
for (const [name, server] of disabledServers) {
|
|
1490
|
+
if (
|
|
1491
|
+
server.file.path === entryPlan.source?.path &&
|
|
1492
|
+
entryPlan.removedMcpEntries.some((entry) => entry.name === name)
|
|
1493
|
+
) {
|
|
1494
|
+
relocatedDisabledServers.add(name)
|
|
1495
|
+
}
|
|
1496
|
+
}
|
|
1497
|
+
for (const [name, server] of disabledServers) {
|
|
1498
|
+
const destination = relocatedDisabledServers.has(name) ? entryPlan.target : server.file
|
|
1499
|
+
emit(
|
|
1500
|
+
output,
|
|
1501
|
+
`Config operation: ${destination.name} mcp.servers[${reviewPolicyValue(name, 'action')}].disabled = true.`,
|
|
1502
|
+
)
|
|
1503
|
+
}
|
|
1504
|
+
try {
|
|
1505
|
+
if (hasCrossLayerPermissionConflict(files, sources, selectedSources, askChoices)) {
|
|
1506
|
+
const reason =
|
|
1507
|
+
'Overlapping permission sources change effective policy across config layers; resolve the layers explicitly before setup.'
|
|
1508
|
+
emit(output, reason)
|
|
1509
|
+
return { status: 'blocked', reason, changes: [], configDir }
|
|
1510
|
+
}
|
|
1511
|
+
} catch {
|
|
1512
|
+
return {
|
|
1513
|
+
status: 'blocked',
|
|
1514
|
+
reason: 'Permission policy conflict could not be safely evaluated.',
|
|
1515
|
+
changes: [],
|
|
1516
|
+
configDir,
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
|
|
1520
|
+
const extraEdits = new Map()
|
|
1521
|
+
if (entryPlan.source && entryPlan.edits.length > 0) {
|
|
1522
|
+
extraEdits.set(entryPlan.source.path, [...entryPlan.edits])
|
|
1523
|
+
}
|
|
1524
|
+
try {
|
|
1525
|
+
for (const [name, server] of disabledServers) {
|
|
1526
|
+
if (relocatedDisabledServers.has(name)) continue
|
|
1527
|
+
if (!server?.nested) throw new Error('MCP disable schema unavailable')
|
|
1528
|
+
const edits = extraEdits.get(server.file.path) ?? []
|
|
1529
|
+
edits.push(setObjectFieldEdit(server.file, server.server, 'disabled', true))
|
|
1530
|
+
extraEdits.set(server.file.path, edits)
|
|
1531
|
+
}
|
|
1532
|
+
} catch {
|
|
1533
|
+
return {
|
|
1534
|
+
status: 'blocked',
|
|
1535
|
+
reason: 'An MCP server could not be safely disabled.',
|
|
1536
|
+
changes: [],
|
|
1537
|
+
configDir,
|
|
1538
|
+
}
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
const plannedContents = new Map()
|
|
1542
|
+
try {
|
|
1543
|
+
for (const file of files) {
|
|
1544
|
+
if (!file.exists || file.parseError) continue
|
|
1545
|
+
const edits = extraEdits.get(file.path) ?? []
|
|
1546
|
+
const selectedSource = selectedSources.get(file.path)
|
|
1547
|
+
let contents = file.content
|
|
1548
|
+
let policy = null
|
|
1549
|
+
if (selectedSource) {
|
|
1550
|
+
policy = makeV2Policy(selectedSource, askChoices)
|
|
1551
|
+
contents = editConfig(file, policy, edits)
|
|
1552
|
+
} else if (edits.length > 0) {
|
|
1553
|
+
contents = applyTextEdits(file.content, edits)
|
|
1554
|
+
parseConfig(contents, file.format === 'jsonc')
|
|
1555
|
+
}
|
|
1556
|
+
if (contents !== file.content) plannedContents.set(file.path, { file, contents, policy })
|
|
1557
|
+
if (policy) printPolicyPreview(file, policy, output)
|
|
1558
|
+
}
|
|
1559
|
+
if (entryPlan.moves.length > 0 || relocatedDisabledServers.size > 0) {
|
|
1560
|
+
const target = entryPlan.target
|
|
1561
|
+
const previous =
|
|
1562
|
+
plannedContents.get(target.path)?.contents ?? (target.exists ? target.content : '{}\n')
|
|
1563
|
+
const config = target.exists ? parseConfig(previous, false).value : {}
|
|
1564
|
+
addManagedEntriesToJson(config, entryPlan.moves, relocatedDisabledServers)
|
|
1565
|
+
plannedContents.set(target.path, {
|
|
1566
|
+
file: target,
|
|
1567
|
+
contents: `${JSON.stringify(config, null, 2)}\n`,
|
|
1568
|
+
policy: selectedSources.has(target.path)
|
|
1569
|
+
? makeV2Policy(selectedSources.get(target.path), askChoices)
|
|
1570
|
+
: null,
|
|
1571
|
+
})
|
|
1572
|
+
}
|
|
1573
|
+
} catch {
|
|
1574
|
+
emit(output, 'Preview blocked: the requested edits cannot preserve the existing config safely.')
|
|
1575
|
+
return {
|
|
1576
|
+
status: 'blocked',
|
|
1577
|
+
reason: 'The requested edits are not safe to apply.',
|
|
1578
|
+
changes: [],
|
|
1579
|
+
configDir,
|
|
1580
|
+
}
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
const changes = [...plannedContents.values()].map(({ file, contents, policy }) => ({
|
|
1584
|
+
path: file.path,
|
|
1585
|
+
original: file.exists ? file.content : null,
|
|
1586
|
+
contents,
|
|
1587
|
+
policy,
|
|
1588
|
+
identity: file.identity ?? null,
|
|
1589
|
+
fileName: file.name,
|
|
1590
|
+
}))
|
|
1591
|
+
|
|
1592
|
+
if (changes.length === 0) {
|
|
1593
|
+
emit(
|
|
1594
|
+
output,
|
|
1595
|
+
'The selected files already match the selected V2 policy; no config changes are needed.',
|
|
1596
|
+
)
|
|
1597
|
+
return {
|
|
1598
|
+
status: 'unchanged',
|
|
1599
|
+
changes: [],
|
|
1600
|
+
configDir,
|
|
1601
|
+
unsafeMcpNames: entryPlan.unsafeMcpNames,
|
|
1602
|
+
configPreconditions: makeConfigPreconditions(files, plannedContents),
|
|
1603
|
+
}
|
|
1604
|
+
}
|
|
1605
|
+
emit(output, `Config plan: ${changes.length} file(s) will be updated after setup authorization.`)
|
|
1606
|
+
for (const change of changes) {
|
|
1607
|
+
if (!CONFIG_NAMES.includes(change.fileName)) continue
|
|
1608
|
+
const file = files.find((candidate) => candidate.path === change.path)
|
|
1609
|
+
const policyKeys = ['permission', 'permissions'].filter((key) =>
|
|
1610
|
+
file?.ast?.properties.some((property) => property.key === key),
|
|
1611
|
+
)
|
|
1612
|
+
if (policyKeys.length > 0) {
|
|
1613
|
+
emit(
|
|
1614
|
+
output,
|
|
1615
|
+
`Config operation: ${change.fileName} ${policyKeys.join(' + ')} → permissions (${change.policy?.length ?? 0} rule(s)).`,
|
|
1616
|
+
)
|
|
1617
|
+
}
|
|
1618
|
+
}
|
|
1619
|
+
if (entryPlan.moves.length > 0) {
|
|
1620
|
+
emit(
|
|
1621
|
+
output,
|
|
1622
|
+
`Managed-entry migration: ${entryPlan.moves.length} verified entry/entries will move into opencode.json.`,
|
|
1623
|
+
)
|
|
1624
|
+
}
|
|
1625
|
+
if (entryPlan.removedDuplicatePluginCount > 0) {
|
|
1626
|
+
emit(
|
|
1627
|
+
output,
|
|
1628
|
+
`Managed-entry migration: ${entryPlan.removedDuplicatePluginCount} exact duplicate Pantheon plugin entry/entries will be removed from JSONC.`,
|
|
1629
|
+
)
|
|
1630
|
+
}
|
|
1631
|
+
emit(
|
|
1632
|
+
output,
|
|
1633
|
+
'If interrupted between files, use `pantheon-opencode restore` to review and restore the setup backup set.',
|
|
1634
|
+
)
|
|
1635
|
+
const jsonFile = files.find((file) => file.name === 'opencode.json')
|
|
1636
|
+
const jsonChange = jsonFile ? plannedContents.get(jsonFile.path) : null
|
|
1637
|
+
const configPreview = jsonChange?.contents ?? (jsonFile?.exists ? jsonFile.content : '{}\n')
|
|
1638
|
+
return {
|
|
1639
|
+
status: 'planned',
|
|
1640
|
+
changes,
|
|
1641
|
+
configDir,
|
|
1642
|
+
configPreview,
|
|
1643
|
+
unsafeMcpNames: entryPlan.unsafeMcpNames,
|
|
1644
|
+
configPreconditions: makeConfigPreconditions(files, plannedContents),
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
|
|
1648
|
+
/** Apply a reviewed plan with the installer's existing backup and atomic writer. */
|
|
1649
|
+
export function applyConfigChanges(
|
|
1650
|
+
changes,
|
|
1651
|
+
{
|
|
1652
|
+
configDir = changes[0] ? path.dirname(changes[0].path) : process.cwd(),
|
|
1653
|
+
filesystem = fs,
|
|
1654
|
+
backupSet = createBackupSet,
|
|
1655
|
+
writeConfig = writeConfigWithBackup,
|
|
1656
|
+
} = {},
|
|
1657
|
+
) {
|
|
1658
|
+
if (changes.length === 0) return { dir: null, name: null }
|
|
1659
|
+
const root = path.resolve(configDir)
|
|
1660
|
+
const relativePaths = []
|
|
1661
|
+
for (const change of changes) {
|
|
1662
|
+
assertPathWithin(root, change.path)
|
|
1663
|
+
if (
|
|
1664
|
+
path.dirname(path.resolve(change.path)) !== root ||
|
|
1665
|
+
!CONFIG_NAMES.includes(path.basename(change.path))
|
|
1666
|
+
) {
|
|
1667
|
+
throw new Error('The reviewed plan contains an unsupported config target.')
|
|
1668
|
+
}
|
|
1669
|
+
assertManagedPathNoSymlinks(change.path)
|
|
1670
|
+
let stat = null
|
|
1671
|
+
try {
|
|
1672
|
+
stat = filesystem.lstatSync(change.path)
|
|
1673
|
+
} catch (error) {
|
|
1674
|
+
if (error?.code !== 'ENOENT') throw new Error('A reviewed config target cannot be inspected.')
|
|
1675
|
+
}
|
|
1676
|
+
if (stat?.isSymbolicLink() || (stat && !stat.isFile())) {
|
|
1677
|
+
throw new Error('A reviewed config target is not a regular file.')
|
|
1678
|
+
}
|
|
1679
|
+
const current = stat ? filesystem.readFileSync(change.path, 'utf8') : null
|
|
1680
|
+
if (
|
|
1681
|
+
current !== change.original ||
|
|
1682
|
+
(stat && change.identity && !sameIdentity(stat, change.identity))
|
|
1683
|
+
) {
|
|
1684
|
+
throw new Error('A config changed after review; no stale content was written.')
|
|
1685
|
+
}
|
|
1686
|
+
relativePaths.push(path.basename(change.path))
|
|
1687
|
+
}
|
|
1688
|
+
|
|
1689
|
+
const backup = backupSet({ configDir: root, entries: relativePaths, keep: 0 })
|
|
1690
|
+
for (const change of changes) {
|
|
1691
|
+
const status = writeConfig(change.path, change.contents, false, {
|
|
1692
|
+
expectedContent: change.original,
|
|
1693
|
+
})
|
|
1694
|
+
if (status === 'conflict') {
|
|
1695
|
+
throw new Error('A config changed during apply; restore from the setup backup if needed.')
|
|
1696
|
+
}
|
|
1697
|
+
}
|
|
1698
|
+
return backup
|
|
1699
|
+
}
|
|
1700
|
+
|
|
1701
|
+
function sameIdentity(stat, identity) {
|
|
1702
|
+
return stat.dev === identity.dev && stat.ino === identity.ino
|
|
1703
|
+
}
|