pantheon-opencode 2.1.6 → 2.2.0-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.
Files changed (63) hide show
  1. package/AGENTS.global.md +2 -2
  2. package/AGENTS.md +1 -1
  3. package/CHANGELOG.md +64 -0
  4. package/README.md +13 -9
  5. package/README.pt-BR.md +13 -9
  6. package/bin/pantheon-init.mjs +1 -1
  7. package/commands/pantheon-audit.md +4 -5
  8. package/commands/pantheon-model.md +1 -2
  9. package/package.json +8 -2
  10. package/plugin.json +1 -1
  11. package/prompts/dynamic/agora-generated.txt +2 -2
  12. package/prompts/dynamic/orchestrate-generated.txt +4 -4
  13. package/prompts/sketch.prompt.md +1 -1
  14. package/pyproject.toml +1 -1
  15. package/scripts/build-agents-md.mjs +73 -12
  16. package/scripts/build-plugin.mjs +3 -1
  17. package/scripts/hooks/format-multi-language.sh +30 -29
  18. package/scripts/install-mcp.mjs +55 -27
  19. package/scripts/prune.mjs +124 -2
  20. package/scripts/setup.mjs +1 -1
  21. package/scripts/themis_heuristic_scan.py +3 -5
  22. package/skills-lock.json +1 -1
  23. package/src/agents/aphrodite.md +1 -1
  24. package/src/agents/athena.md +6 -14
  25. package/src/agents/demeter.md +1 -1
  26. package/src/agents/hermes.md +3 -2
  27. package/src/agents/iris.md +4 -6
  28. package/src/agents/prometheus.md +3 -7
  29. package/src/agents/roster.json +567 -0
  30. package/src/agents/zeus.md +3 -0
  31. package/src/instructions/agent-return-format.instructions.md +1 -1
  32. package/src/instructions/zeus-anti-stall.instructions.md +11 -35
  33. package/src/instructions/zeus-council-synthesis.instructions.md +17 -49
  34. package/src/instructions/zeus-timeout-retry.instructions.md +12 -80
  35. package/src/mcp/mcp_codemap_module.py +6 -5
  36. package/src/mcp/pantheon-mcp-server.mjs +875 -0
  37. package/src/pantheon/agent-forge-tool.ts +316 -0
  38. package/src/pantheon/auto-permissions.ts +31 -1
  39. package/src/pantheon/codemap-tools.ts +525 -0
  40. package/src/pantheon/deepwork/plan-tracker.ts +63 -2
  41. package/src/pantheon/execute-after.ts +21 -0
  42. package/src/pantheon/hook-engine.ts +2 -1
  43. package/src/pantheon/native-memory-tools.ts +686 -0
  44. package/src/pantheon/presets.mjs +15 -0
  45. package/src/pantheon/step-ledger.ts +259 -0
  46. package/src/pantheon/swe-eval-harness.ts +211 -0
  47. package/src/pantheon/tools.ts +62 -7
  48. package/src/plugin/index.js +2091 -136
  49. package/src/plugin/index.ts +1 -14
  50. package/src/plugin.ts +167 -10
  51. package/src/plugins/tui/dist/tui.d.ts +66 -0
  52. package/src/plugins/tui/dist/tui.d.ts.map +1 -1
  53. package/src/plugins/tui/dist/tui.js +1259 -367
  54. package/src/plugins/tui/dist/tui.js.map +1 -1
  55. package/src/plugins/tui/package-lock.json +2 -2
  56. package/src/plugins/tui/package.json +1 -1
  57. package/src/plugins/tui/src/index.tsx +632 -71
  58. package/src/plugins/tui/src/pantheon-settings.tsx +78 -14
  59. package/src/plugins/tui/src/quota-state.ts +190 -0
  60. package/src/plugins/tui/src/tui-prefs.ts +169 -12
  61. package/src/routing.yml +3 -0
  62. package/src/skills/auto-continue/references/auto-continue-details.md +2 -31
  63. /package/scripts/{setup-v2-config.mjs → setup-config.mjs} +0 -0
@@ -0,0 +1,875 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * pantheon-mcp-server.mjs — 100% Native Node.js MCP server for Pantheon.
4
+ *
5
+ * Replaces Python-based FastMCP servers with native ESM running on Node.js >= 26.
6
+ * Zero Python dependencies, zero .venv required, 100% compatible with Windows Desktop,
7
+ * macOS, and Linux. Speaks MCP JSON-RPC 2.0 over standard I/O.
8
+ *
9
+ * Usage:
10
+ * node src/mcp/pantheon-mcp-server.mjs --server pantheon-resources
11
+ * node src/mcp/pantheon-mcp-server.mjs --server pantheon-memory
12
+ * node src/mcp/pantheon-mcp-server.mjs --server pantheon-persistence
13
+ * node src/mcp/pantheon-mcp-server.mjs --server pantheon-code-mode
14
+ * node src/mcp/pantheon-mcp-server.mjs --server pantheon-vision
15
+ * node src/mcp/pantheon-mcp-server.mjs --server all
16
+ */
17
+
18
+ import { execFile } from 'node:child_process'
19
+ import { createHash } from 'node:crypto'
20
+ import {
21
+ existsSync,
22
+ mkdirSync,
23
+ readdirSync,
24
+ readFileSync,
25
+ realpathSync,
26
+ writeFileSync,
27
+ } from 'node:fs'
28
+ import { basename, dirname, extname, join, resolve, sep } from 'node:path'
29
+ import { createInterface } from 'node:readline'
30
+ import { DatabaseSync } from 'node:sqlite'
31
+ import { fileURLToPath } from 'node:url'
32
+
33
+ const __dirname = dirname(fileURLToPath(import.meta.url))
34
+ const ROOT = resolve(__dirname, '..', '..')
35
+
36
+ // ── Security & Path Confinement Helpers ────────────────────────────────
37
+
38
+ const SAFE_SEGMENT_RE = /^[a-zA-Z0-9._:-]{1,128}$/
39
+
40
+ function assertSafeSegment(value, label) {
41
+ if (
42
+ typeof value !== 'string' ||
43
+ !SAFE_SEGMENT_RE.test(value) ||
44
+ value === '.' ||
45
+ value === '..' ||
46
+ value.includes('..') ||
47
+ value.includes('/') ||
48
+ value.includes('\\')
49
+ ) {
50
+ throw new Error(`Invalid ${label}: must be a safe identifier without path traversal`)
51
+ }
52
+ return value
53
+ }
54
+
55
+ function resolveConfinedPath(baseDir, ...segments) {
56
+ mkdirSync(baseDir, { recursive: true })
57
+ const canonicalBase = realpathSync(baseDir)
58
+ const candidate = resolve(canonicalBase, ...segments)
59
+ const prefix = canonicalBase.endsWith(sep) ? canonicalBase : `${canonicalBase}${sep}`
60
+ if (candidate !== canonicalBase && !candidate.startsWith(prefix)) {
61
+ throw new Error('Path traversal denied: target escapes confined directory')
62
+ }
63
+ return candidate
64
+ }
65
+
66
+ const CODE_MODE_ENV_ALLOWLIST = [
67
+ 'PATH',
68
+ 'HOME',
69
+ 'USER',
70
+ 'LANG',
71
+ 'LC_ALL',
72
+ 'TMPDIR',
73
+ 'TEMP',
74
+ 'TMP',
75
+ 'PANTHEON_PROJECT',
76
+ 'NODE_ENV',
77
+ ]
78
+
79
+ function buildSandboxedEnv() {
80
+ const env = {}
81
+ for (const key of CODE_MODE_ENV_ALLOWLIST) {
82
+ if (process.env[key] !== undefined) {
83
+ env[key] = process.env[key]
84
+ }
85
+ }
86
+ return env
87
+ }
88
+
89
+ // ── Argument Parsing ───────────────────────────────────────────────────
90
+
91
+ const args = process.argv.slice(2)
92
+ let serverType = 'all'
93
+ for (let i = 0; i < args.length; i++) {
94
+ if (args[i] === '--server' && args[i + 1]) {
95
+ serverType = args[i + 1]
96
+ i++
97
+ }
98
+ }
99
+
100
+ // ── Path Helpers ───────────────────────────────────────────────────────
101
+
102
+ function getProjectRoot() {
103
+ return process.env.PANTHEON_PROJECT || process.cwd()
104
+ }
105
+
106
+ // ── SQLite Memory Setup (with FTS5 + TTL support) ──────────────────────
107
+
108
+ let dbInstance = null
109
+ function getMemoryDb() {
110
+ if (dbInstance) return dbInstance
111
+ const memoryDir = join(getProjectRoot(), '.pantheon', 'memory')
112
+ mkdirSync(memoryDir, { recursive: true })
113
+ const dbPath = join(memoryDir, 'memory.db')
114
+ const db = new DatabaseSync(dbPath)
115
+ db.exec(`
116
+ CREATE TABLE IF NOT EXISTS memories (
117
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
118
+ namespace TEXT NOT NULL,
119
+ key TEXT NOT NULL,
120
+ value TEXT NOT NULL,
121
+ metadata TEXT,
122
+ created_at TEXT NOT NULL,
123
+ expires_at TEXT,
124
+ UNIQUE(namespace, key)
125
+ );
126
+ CREATE INDEX IF NOT EXISTS idx_memories_ns_key ON memories(namespace, key);
127
+ `)
128
+ try {
129
+ db.exec(`
130
+ CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
131
+ namespace,
132
+ key,
133
+ value,
134
+ content='memories',
135
+ content_rowid='id',
136
+ tokenize='porter unicode61'
137
+ );
138
+ CREATE TRIGGER IF NOT EXISTS memories_ai AFTER INSERT ON memories BEGIN
139
+ INSERT INTO memories_fts(rowid, namespace, key, value)
140
+ VALUES (new.id, new.namespace, new.key, new.value);
141
+ END;
142
+ CREATE TRIGGER IF NOT EXISTS memories_ad AFTER DELETE ON memories BEGIN
143
+ INSERT INTO memories_fts(memories_fts, rowid, namespace, key, value)
144
+ VALUES ('delete', old.id, old.namespace, old.key, old.value);
145
+ END;
146
+ CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE ON memories BEGIN
147
+ INSERT INTO memories_fts(memories_fts, rowid, namespace, key, value)
148
+ VALUES ('delete', old.id, old.namespace, old.key, old.value);
149
+ INSERT INTO memories_fts(rowid, namespace, key, value)
150
+ VALUES (new.id, new.namespace, new.key, new.value);
151
+ END;
152
+ `)
153
+ } catch {
154
+ /* FTS5 optional fallback if SQLite build omits fts5 */
155
+ }
156
+ dbInstance = db
157
+ return db
158
+ }
159
+
160
+ // ── Tool Definitions ───────────────────────────────────────────────────
161
+
162
+ function getToolsForServer(type) {
163
+ const tools = []
164
+
165
+ if (type === 'all' || type === 'pantheon-memory') {
166
+ tools.push(
167
+ {
168
+ name: 'memory_store',
169
+ description:
170
+ 'Store a memory entry with namespace, key, value, and optional metadata string.',
171
+ inputSchema: {
172
+ type: 'object',
173
+ properties: {
174
+ namespace: { type: 'string' },
175
+ key: { type: 'string' },
176
+ value: { type: 'string' },
177
+ metadata: { type: 'string' },
178
+ expires_at: { type: 'string' },
179
+ },
180
+ required: ['namespace', 'key', 'value'],
181
+ },
182
+ },
183
+ {
184
+ name: 'memory_search',
185
+ description: 'Search memories using FTS5 BM25 lexical matching (with keyword fallback).',
186
+ inputSchema: {
187
+ type: 'object',
188
+ properties: {
189
+ query: { type: 'string' },
190
+ namespace: { type: 'string' },
191
+ top_k: { type: 'number' },
192
+ limit: { type: 'number' },
193
+ },
194
+ required: ['query'],
195
+ },
196
+ },
197
+ {
198
+ name: 'memory_recall',
199
+ description: 'Recall a specific memory entry by exact namespace and key.',
200
+ inputSchema: {
201
+ type: 'object',
202
+ properties: {
203
+ namespace: { type: 'string' },
204
+ key: { type: 'string' },
205
+ },
206
+ required: ['namespace', 'key'],
207
+ },
208
+ },
209
+ {
210
+ name: 'memory_forget',
211
+ description: 'Delete a memory entry by namespace and key.',
212
+ inputSchema: {
213
+ type: 'object',
214
+ properties: {
215
+ namespace: { type: 'string' },
216
+ key: { type: 'string' },
217
+ },
218
+ required: ['namespace', 'key'],
219
+ },
220
+ },
221
+ {
222
+ name: 'memory_list',
223
+ description: 'List active memory entries for a namespace.',
224
+ inputSchema: {
225
+ type: 'object',
226
+ properties: {
227
+ namespace: { type: 'string' },
228
+ limit: { type: 'number' },
229
+ },
230
+ },
231
+ },
232
+ {
233
+ name: 'memory_stats',
234
+ description: 'Get memory storage statistics.',
235
+ inputSchema: { type: 'object', properties: {} },
236
+ },
237
+ )
238
+ }
239
+
240
+ if (type === 'all' || type === 'pantheon-persistence') {
241
+ tools.push(
242
+ {
243
+ name: 'context_save',
244
+ description: 'Save a session checkpoint under a session_id key.',
245
+ inputSchema: {
246
+ type: 'object',
247
+ properties: {
248
+ session_id: { type: 'string' },
249
+ content: { type: 'string' },
250
+ namespace: { type: 'string' },
251
+ },
252
+ required: ['session_id', 'content'],
253
+ },
254
+ },
255
+ {
256
+ name: 'context_get',
257
+ description: 'Retrieve a saved session checkpoint by session_id.',
258
+ inputSchema: {
259
+ type: 'object',
260
+ properties: {
261
+ session_id: { type: 'string' },
262
+ namespace: { type: 'string' },
263
+ },
264
+ required: ['session_id'],
265
+ },
266
+ },
267
+ {
268
+ name: 'goal_create',
269
+ description: 'Create a persistent session goal.',
270
+ inputSchema: {
271
+ type: 'object',
272
+ properties: {
273
+ id: { type: 'string' },
274
+ title: { type: 'string' },
275
+ criteria: { type: 'array', items: { type: 'string' } },
276
+ },
277
+ required: ['title'],
278
+ },
279
+ },
280
+ {
281
+ name: 'goal_get',
282
+ description: 'Get active session goal by id or latest.',
283
+ inputSchema: {
284
+ type: 'object',
285
+ properties: {
286
+ id: { type: 'string' },
287
+ },
288
+ },
289
+ },
290
+ {
291
+ name: 'goal_update',
292
+ description: 'Update progress on an active session goal.',
293
+ inputSchema: {
294
+ type: 'object',
295
+ properties: {
296
+ id: { type: 'string' },
297
+ status: { type: 'string' },
298
+ notes: { type: 'string' },
299
+ },
300
+ required: ['id'],
301
+ },
302
+ },
303
+ {
304
+ name: 'goal_done',
305
+ description: 'Mark a session goal as completed.',
306
+ inputSchema: {
307
+ type: 'object',
308
+ properties: {
309
+ id: { type: 'string' },
310
+ summary: { type: 'string' },
311
+ },
312
+ required: ['id'],
313
+ },
314
+ },
315
+ {
316
+ name: 'persistence_save',
317
+ description: 'Save durable state JSON to .pantheon/persistence/<namespace>/<key>.json',
318
+ inputSchema: {
319
+ type: 'object',
320
+ properties: {
321
+ namespace: { type: 'string' },
322
+ key: { type: 'string' },
323
+ payload: { type: 'object' },
324
+ },
325
+ required: ['namespace', 'key', 'payload'],
326
+ },
327
+ },
328
+ {
329
+ name: 'persistence_load',
330
+ description: 'Load durable state JSON from .pantheon/persistence/<namespace>/<key>.json',
331
+ inputSchema: {
332
+ type: 'object',
333
+ properties: {
334
+ namespace: { type: 'string' },
335
+ key: { type: 'string' },
336
+ },
337
+ required: ['namespace', 'key'],
338
+ },
339
+ },
340
+ {
341
+ name: 'persistence_list',
342
+ description: 'List durable state keys for a given namespace.',
343
+ inputSchema: {
344
+ type: 'object',
345
+ properties: {
346
+ namespace: { type: 'string' },
347
+ },
348
+ required: ['namespace'],
349
+ },
350
+ },
351
+ )
352
+ }
353
+
354
+ if (type === 'all' || type === 'pantheon-code-mode') {
355
+ tools.push(
356
+ {
357
+ name: 'execute_code_script',
358
+ description:
359
+ 'Execute a manifest-verified orchestration script from .pantheon/code-mode/ directory.',
360
+ inputSchema: {
361
+ type: 'object',
362
+ properties: {
363
+ script: { type: 'string' },
364
+ args: { type: 'array', items: { type: 'string' } },
365
+ },
366
+ required: ['script'],
367
+ },
368
+ },
369
+ {
370
+ name: 'approve_code_script',
371
+ description: 'Record SHA-256 approval for a script in .pantheon/code-mode/manifest.json.',
372
+ inputSchema: {
373
+ type: 'object',
374
+ properties: {
375
+ script: { type: 'string' },
376
+ },
377
+ required: ['script'],
378
+ },
379
+ },
380
+ )
381
+ }
382
+
383
+ if (type === 'all' || type === 'pantheon-vision') {
384
+ tools.push({
385
+ name: 'vision_describe',
386
+ description:
387
+ 'Fallback MCP bridge: delegates image analysis to OpenCode native vision_describe tool.',
388
+ inputSchema: {
389
+ type: 'object',
390
+ properties: {
391
+ image_path: { type: 'string' },
392
+ prompt: { type: 'string' },
393
+ },
394
+ required: ['image_path'],
395
+ },
396
+ })
397
+ }
398
+
399
+ return tools
400
+ }
401
+
402
+ // ── Resource Definitions ───────────────────────────────────────────────
403
+
404
+ function getResourcesForServer(type) {
405
+ if (type !== 'all' && type !== 'pantheon-resources') return []
406
+ return [
407
+ {
408
+ uri: 'pantheon://agents',
409
+ name: 'Pantheon Agents',
410
+ description: 'List of all Pantheon specialized agents and roles',
411
+ mimeType: 'text/markdown',
412
+ },
413
+ {
414
+ uri: 'pantheon://skills',
415
+ name: 'Pantheon Skills',
416
+ description: 'List of all Pantheon skills with descriptions',
417
+ mimeType: 'text/markdown',
418
+ },
419
+ {
420
+ uri: 'pantheon://routing',
421
+ name: 'Pantheon Routing Rules',
422
+ description: 'Canonical orchestration routing configuration',
423
+ mimeType: 'text/yaml',
424
+ },
425
+ ]
426
+ }
427
+
428
+ // ── Tool Execution Handler ─────────────────────────────────────────────
429
+
430
+ function isNotExpiredSql() {
431
+ return '(expires_at IS NULL OR expires_at > ?)'
432
+ }
433
+
434
+ async function handleToolCall(name, params = {}) {
435
+ const nowIso = new Date().toISOString()
436
+
437
+ switch (name) {
438
+ case 'memory_store': {
439
+ const db = getMemoryDb()
440
+ const valueStr = String(params.value ?? '')
441
+ if (Buffer.byteLength(valueStr, 'utf8') > 65536) {
442
+ throw new Error('memory_store value exceeds maximum size of 64 KiB')
443
+ }
444
+ const stmt = db.prepare(`
445
+ INSERT INTO memories (namespace, key, value, metadata, created_at, expires_at)
446
+ VALUES (?, ?, ?, ?, ?, ?)
447
+ ON CONFLICT(namespace, key) DO UPDATE SET
448
+ value = excluded.value,
449
+ metadata = excluded.metadata,
450
+ created_at = excluded.created_at,
451
+ expires_at = excluded.expires_at
452
+ `)
453
+ stmt.run(
454
+ String(params.namespace),
455
+ String(params.key),
456
+ valueStr,
457
+ params.metadata ? String(params.metadata) : null,
458
+ nowIso,
459
+ params.expires_at ? String(params.expires_at) : null,
460
+ )
461
+ return { status: 'stored', namespace: params.namespace, key: params.key }
462
+ }
463
+ case 'memory_recall': {
464
+ const db = getMemoryDb()
465
+ const row = db
466
+ .prepare(
467
+ `SELECT namespace, key, value, metadata, created_at, expires_at
468
+ FROM memories
469
+ WHERE namespace = ? AND key = ? AND ${isNotExpiredSql()}`,
470
+ )
471
+ .get(String(params.namespace), String(params.key), nowIso)
472
+ return row || { error: 'not_found' }
473
+ }
474
+ case 'memory_search': {
475
+ const db = getMemoryDb()
476
+ const limit = Number(params.top_k ?? params.limit ?? 10)
477
+ const rawQuery = String(params.query ?? '').trim()
478
+ if (!rawQuery) return { count: 0, results: [] }
479
+
480
+ // Try FTS5 BM25 first, fallback to tokenized LIKE
481
+ const tokens = rawQuery
482
+ .replace(/[^\p{L}\p{N}_-]+/gu, ' ')
483
+ .trim()
484
+ .split(/\s+/)
485
+ .filter((t) => t.length >= 2)
486
+ if (tokens.length > 0) {
487
+ try {
488
+ const ftsExpr = tokens.map((t) => `"${t.replace(/"/g, '""')}"*`).join(' OR ')
489
+ let ftsSql = `
490
+ SELECT m.namespace, m.key, m.value, m.metadata, m.created_at, bm25(memories_fts) AS score
491
+ FROM memories_fts
492
+ JOIN memories m ON m.id = memories_fts.rowid
493
+ WHERE memories_fts MATCH ? AND (m.expires_at IS NULL OR m.expires_at > ?)
494
+ `
495
+ const ftsParams = [ftsExpr, nowIso]
496
+ if (params.namespace) {
497
+ ftsSql += ' AND m.namespace = ?'
498
+ ftsParams.push(String(params.namespace))
499
+ }
500
+ ftsSql += ' ORDER BY score LIMIT ?'
501
+ ftsParams.push(limit)
502
+ const rows = db.prepare(ftsSql).all(...ftsParams)
503
+ if (rows.length > 0) {
504
+ return { count: rows.length, results: rows }
505
+ }
506
+ } catch {
507
+ /* fallback to LIKE below */
508
+ }
509
+ }
510
+
511
+ const escaped = rawQuery.replace(/[\\%_]/g, '\\$&')
512
+ let query = `
513
+ SELECT namespace, key, value, metadata, created_at
514
+ FROM memories
515
+ WHERE (value LIKE ? ESCAPE '\\' OR key LIKE ? ESCAPE '\\')
516
+ AND ${isNotExpiredSql()}
517
+ `
518
+ const queryParams = [`%${escaped}%`, `%${escaped}%`, nowIso]
519
+ if (params.namespace) {
520
+ query += ' AND namespace = ?'
521
+ queryParams.push(String(params.namespace))
522
+ }
523
+ query += ' ORDER BY id DESC LIMIT ?'
524
+ queryParams.push(limit)
525
+ const rows = db.prepare(query).all(...queryParams)
526
+ return { count: rows.length, results: rows }
527
+ }
528
+ case 'memory_forget': {
529
+ const db = getMemoryDb()
530
+ const info = db
531
+ .prepare('DELETE FROM memories WHERE namespace = ? AND key = ?')
532
+ .run(String(params.namespace), String(params.key))
533
+ return { deleted: info.changes > 0, namespace: params.namespace, key: params.key }
534
+ }
535
+ case 'memory_list': {
536
+ const db = getMemoryDb()
537
+ const limit = Number(params.limit || 50)
538
+ let query = `SELECT namespace, key, created_at FROM memories WHERE ${isNotExpiredSql()}`
539
+ const queryParams = [nowIso]
540
+ if (params.namespace) {
541
+ query += ' AND namespace = ?'
542
+ queryParams.push(String(params.namespace))
543
+ }
544
+ query += ' ORDER BY id DESC LIMIT ?'
545
+ queryParams.push(limit)
546
+ return db.prepare(query).all(...queryParams)
547
+ }
548
+ case 'memory_stats': {
549
+ const db = getMemoryDb()
550
+ const total = db
551
+ .prepare(`SELECT count(*) as count FROM memories WHERE ${isNotExpiredSql()}`)
552
+ .get(nowIso)
553
+ const byNamespace = db
554
+ .prepare(
555
+ `SELECT namespace, count(*) as count FROM memories WHERE ${isNotExpiredSql()} GROUP BY namespace`,
556
+ )
557
+ .all(nowIso)
558
+ return { total: total?.count || 0, byNamespace }
559
+ }
560
+ case 'context_save': {
561
+ const ns = assertSafeSegment(params.namespace || 'checkpoints', 'namespace')
562
+ const key = assertSafeSegment(params.session_id, 'session_id')
563
+ const baseDir = join(getProjectRoot(), '.pantheon', 'persistence')
564
+ const dir = resolveConfinedPath(baseDir, ns)
565
+ mkdirSync(dir, { recursive: true })
566
+ const filePath = resolveConfinedPath(dir, `${key}.json`)
567
+ const record = {
568
+ session_id: key,
569
+ namespace: ns,
570
+ content:
571
+ typeof params.content === 'string' ? params.content : JSON.stringify(params.content),
572
+ updated_at: nowIso,
573
+ }
574
+ writeFileSync(filePath, JSON.stringify(record, null, 2), 'utf8')
575
+ return { status: 'saved', session_id: key, updated_at: nowIso }
576
+ }
577
+ case 'context_get': {
578
+ const ns = assertSafeSegment(params.namespace || 'checkpoints', 'namespace')
579
+ const key = assertSafeSegment(params.session_id, 'session_id')
580
+ const baseDir = join(getProjectRoot(), '.pantheon', 'persistence')
581
+ const dir = resolveConfinedPath(baseDir, ns)
582
+ const filePath = resolveConfinedPath(dir, `${key}.json`)
583
+ if (!existsSync(filePath)) return { error: 'not_found', session_id: key }
584
+ return JSON.parse(readFileSync(filePath, 'utf8'))
585
+ }
586
+ case 'goal_create': {
587
+ const id = assertSafeSegment(params.id || `goal-${Date.now()}`, 'id')
588
+ const goalsDir = join(getProjectRoot(), '.pantheon', 'goals')
589
+ const filePath = resolveConfinedPath(goalsDir, `${id}.json`)
590
+ const goal = {
591
+ id,
592
+ title: String(params.title ?? ''),
593
+ criteria: Array.isArray(params.criteria) ? params.criteria.map(String) : [],
594
+ status: 'active',
595
+ created_at: nowIso,
596
+ updated_at: nowIso,
597
+ }
598
+ writeFileSync(filePath, JSON.stringify(goal, null, 2), 'utf8')
599
+ return goal
600
+ }
601
+ case 'goal_get': {
602
+ const goalsDir = join(getProjectRoot(), '.pantheon', 'goals')
603
+ mkdirSync(goalsDir, { recursive: true })
604
+ if (params.id) {
605
+ const id = assertSafeSegment(params.id, 'id')
606
+ const filePath = resolveConfinedPath(goalsDir, `${id}.json`)
607
+ if (!existsSync(filePath)) return { error: 'not_found', id }
608
+ return JSON.parse(readFileSync(filePath, 'utf8'))
609
+ }
610
+ const files = readdirSync(goalsDir).filter((f) => f.endsWith('.json'))
611
+ if (files.length === 0) return { error: 'no_active_goals' }
612
+ const latest = files.sort().at(-1)
613
+ return JSON.parse(readFileSync(resolveConfinedPath(goalsDir, latest), 'utf8'))
614
+ }
615
+ case 'goal_update':
616
+ case 'goal_done': {
617
+ const id = assertSafeSegment(params.id, 'id')
618
+ const goalsDir = join(getProjectRoot(), '.pantheon', 'goals')
619
+ const filePath = resolveConfinedPath(goalsDir, `${id}.json`)
620
+ if (!existsSync(filePath)) return { error: 'not_found', id }
621
+ const existing = JSON.parse(readFileSync(filePath, 'utf8'))
622
+ const updated = {
623
+ ...existing,
624
+ status: name === 'goal_done' ? 'completed' : String(params.status ?? existing.status),
625
+ notes: params.notes ?? params.summary ?? existing.notes,
626
+ updated_at: nowIso,
627
+ }
628
+ writeFileSync(filePath, JSON.stringify(updated, null, 2), 'utf8')
629
+ return updated
630
+ }
631
+ case 'persistence_save': {
632
+ const ns = assertSafeSegment(params.namespace, 'namespace')
633
+ const key = assertSafeSegment(params.key, 'key')
634
+ const baseDir = join(getProjectRoot(), '.pantheon', 'persistence')
635
+ const dir = resolveConfinedPath(baseDir, ns)
636
+ mkdirSync(dir, { recursive: true })
637
+ const filePath = resolveConfinedPath(dir, `${key}.json`)
638
+ writeFileSync(filePath, JSON.stringify(params.payload, null, 2), 'utf8')
639
+ return { status: 'saved', path: filePath }
640
+ }
641
+ case 'persistence_load': {
642
+ const ns = assertSafeSegment(params.namespace, 'namespace')
643
+ const key = assertSafeSegment(params.key, 'key')
644
+ const baseDir = join(getProjectRoot(), '.pantheon', 'persistence')
645
+ const dir = resolveConfinedPath(baseDir, ns)
646
+ const filePath = resolveConfinedPath(dir, `${key}.json`)
647
+ if (!existsSync(filePath)) return { error: 'not_found' }
648
+ return JSON.parse(readFileSync(filePath, 'utf8'))
649
+ }
650
+ case 'persistence_list': {
651
+ const ns = assertSafeSegment(params.namespace, 'namespace')
652
+ const baseDir = join(getProjectRoot(), '.pantheon', 'persistence')
653
+ const dir = resolveConfinedPath(baseDir, ns)
654
+ if (!existsSync(dir)) return []
655
+ return readdirSync(dir)
656
+ .filter((f) => f.endsWith('.json'))
657
+ .map((f) => f.replace(/\.json$/, ''))
658
+ }
659
+ case 'approve_code_script': {
660
+ const scriptName = assertSafeSegment(basename(String(params.script ?? '')), 'script')
661
+ if (scriptName !== params.script) {
662
+ throw new Error('Script must be a bare filename inside .pantheon/code-mode/')
663
+ }
664
+ const codeDir = join(getProjectRoot(), '.pantheon', 'code-mode')
665
+ const scriptPath = resolveConfinedPath(codeDir, scriptName)
666
+ if (!existsSync(scriptPath)) {
667
+ throw new Error(`Script ${scriptName} not found in ${codeDir}`)
668
+ }
669
+ const sha256 = createHash('sha256').update(readFileSync(scriptPath)).digest('hex')
670
+ const manifestPath = resolveConfinedPath(codeDir, 'manifest.json')
671
+ let manifest = { scripts: {} }
672
+ if (existsSync(manifestPath)) {
673
+ try {
674
+ manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
675
+ if (!manifest.scripts || typeof manifest.scripts !== 'object') manifest.scripts = {}
676
+ } catch {
677
+ manifest = { scripts: {} }
678
+ }
679
+ }
680
+ manifest.scripts[scriptName] = { sha256, approved_at: nowIso }
681
+ writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8')
682
+ return { status: 'approved', script: scriptName, sha256 }
683
+ }
684
+ case 'execute_code_script': {
685
+ const scriptName = assertSafeSegment(basename(String(params.script ?? '')), 'script')
686
+ if (scriptName !== params.script) {
687
+ throw new Error('Script must be a bare filename inside .pantheon/code-mode/')
688
+ }
689
+ const codeDir = join(getProjectRoot(), '.pantheon', 'code-mode')
690
+ const scriptPath = resolveConfinedPath(codeDir, scriptName)
691
+ if (!existsSync(scriptPath)) {
692
+ throw new Error(`Script ${scriptName} not found in ${codeDir}`)
693
+ }
694
+
695
+ // Verify SHA-256 against manifest.json if present
696
+ const manifestPath = resolveConfinedPath(codeDir, 'manifest.json')
697
+ if (existsSync(manifestPath)) {
698
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
699
+ const expected =
700
+ manifest?.scripts?.[scriptName]?.sha256 ??
701
+ manifest?.[scriptName]?.sha256 ??
702
+ manifest?.[scriptName]
703
+ const actual = createHash('sha256').update(readFileSync(scriptPath)).digest('hex')
704
+ if (typeof expected === 'string' && expected !== actual) {
705
+ throw new Error(
706
+ `Script ${scriptName} SHA-256 mismatch against manifest.json (run approve_code_script first)`,
707
+ )
708
+ }
709
+ }
710
+
711
+ const ext = extname(scriptName).toLowerCase()
712
+ const interpreter = ext === '.py' ? 'python3' : ext === '.sh' ? '/bin/bash' : process.execPath
713
+ const scriptArgs = Array.isArray(params.args) ? params.args.map(String) : []
714
+
715
+ return new Promise((resolvePromise) => {
716
+ execFile(
717
+ interpreter,
718
+ [scriptPath, ...scriptArgs],
719
+ { timeout: 30000, cwd: getProjectRoot(), env: buildSandboxedEnv() },
720
+ (err, stdout, stderr) => {
721
+ if (err) resolvePromise({ exitCode: err.code || 1, stderr: stderr || err.message })
722
+ else resolvePromise({ exitCode: 0, stdout })
723
+ },
724
+ )
725
+ })
726
+ }
727
+ case 'vision_describe': {
728
+ return {
729
+ status: 'delegated_to_native',
730
+ message:
731
+ 'Use the native OpenCode Pantheon plugin tool `vision_describe` directly in your session.',
732
+ }
733
+ }
734
+ default:
735
+ throw new Error(`Unknown tool: ${name}`)
736
+ }
737
+ }
738
+
739
+ // ── Resource Read Handler ──────────────────────────────────────────────
740
+
741
+ async function handleResourceRead(uri) {
742
+ if (uri === 'pantheon://agents') {
743
+ const agentsDir = join(ROOT, 'src', 'agents')
744
+ if (existsSync(agentsDir)) {
745
+ const files = readdirSync(agentsDir).filter((f) => f.endsWith('.md') && f !== 'README.md')
746
+ const content = files
747
+ .map((f) => `### ${f.replace('.md', '')}\n\n${readFileSync(join(agentsDir, f), 'utf8')}`)
748
+ .join('\n\n---\n\n')
749
+ return [{ uri, mimeType: 'text/markdown', text: content }]
750
+ }
751
+ return [{ uri, mimeType: 'text/markdown', text: '# Agents not found' }]
752
+ }
753
+ if (uri === 'pantheon://skills') {
754
+ const skillsLock = join(ROOT, 'skills-lock.json')
755
+ if (existsSync(skillsLock)) {
756
+ return [{ uri, mimeType: 'application/json', text: readFileSync(skillsLock, 'utf8') }]
757
+ }
758
+ return [{ uri, mimeType: 'text/markdown', text: '# Skills lock not found' }]
759
+ }
760
+ if (uri === 'pantheon://routing') {
761
+ const routingFile = join(ROOT, 'src', 'routing.yml')
762
+ if (existsSync(routingFile)) {
763
+ return [{ uri, mimeType: 'text/yaml', text: readFileSync(routingFile, 'utf8') }]
764
+ }
765
+ return [{ uri, mimeType: 'text/yaml', text: '# Routing file not found' }]
766
+ }
767
+ throw new Error(`Resource not found: ${uri}`)
768
+ }
769
+
770
+ // ── JSON-RPC 2.0 STDIO Loop ────────────────────────────────────────────
771
+
772
+ function sendResponse(id, result) {
773
+ const payload = JSON.stringify({ jsonrpc: '2.0', id, result })
774
+ process.stdout.write(`${payload}\n`)
775
+ }
776
+
777
+ function sendError(id, code, message, data) {
778
+ const payload = JSON.stringify({
779
+ jsonrpc: '2.0',
780
+ id,
781
+ error: { code, message, ...(data ? { data } : {}) },
782
+ })
783
+ process.stdout.write(`${payload}\n`)
784
+ }
785
+
786
+ const rl = createInterface({
787
+ input: process.stdin,
788
+ terminal: false,
789
+ })
790
+
791
+ rl.on('line', async (line) => {
792
+ const trimmed = line.trim()
793
+ if (!trimmed) return
794
+
795
+ let msg
796
+ try {
797
+ msg = JSON.parse(trimmed)
798
+ } catch {
799
+ return
800
+ }
801
+
802
+ const { id, method, params } = msg
803
+
804
+ // Notifications have no id
805
+ if (id === undefined || id === null) {
806
+ return
807
+ }
808
+
809
+ try {
810
+ switch (method) {
811
+ case 'initialize': {
812
+ sendResponse(id, {
813
+ protocolVersion: params?.protocolVersion || '2024-11-05',
814
+ capabilities: {
815
+ tools: {},
816
+ resources: {},
817
+ },
818
+ serverInfo: {
819
+ name: serverType === 'all' ? 'pantheon-mcp-native' : serverType,
820
+ version: '2.2.0',
821
+ },
822
+ })
823
+ break
824
+ }
825
+ case 'ping': {
826
+ sendResponse(id, {})
827
+ break
828
+ }
829
+ case 'tools/list': {
830
+ sendResponse(id, {
831
+ tools: getToolsForServer(serverType),
832
+ })
833
+ break
834
+ }
835
+ case 'tools/call': {
836
+ const toolName = params?.name
837
+ const toolArgs = params?.arguments || {}
838
+ const output = await handleToolCall(toolName, toolArgs)
839
+ sendResponse(id, {
840
+ content: [
841
+ {
842
+ type: 'text',
843
+ text: typeof output === 'string' ? output : JSON.stringify(output, null, 2),
844
+ },
845
+ ],
846
+ })
847
+ break
848
+ }
849
+ case 'resources/list': {
850
+ sendResponse(id, {
851
+ resources: getResourcesForServer(serverType),
852
+ })
853
+ break
854
+ }
855
+ case 'resources/read': {
856
+ const contents = await handleResourceRead(params?.uri)
857
+ sendResponse(id, { contents })
858
+ break
859
+ }
860
+ case 'resources/templates/list': {
861
+ sendResponse(id, { resourceTemplates: [] })
862
+ break
863
+ }
864
+ case 'prompts/list': {
865
+ sendResponse(id, { prompts: [] })
866
+ break
867
+ }
868
+ default: {
869
+ sendError(id, -32601, `Method not found: ${method}`)
870
+ }
871
+ }
872
+ } catch (err) {
873
+ sendError(id, -32603, err?.message || 'Internal error')
874
+ }
875
+ })