pantheon-opencode 2.1.3 → 2.1.5

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.
@@ -1,13 +1,13 @@
1
1
  ---
2
- description: "Test economy — sub-10s test slicing; heavy suites are opt-in."
2
+ description: "Test economy — risk-based validation protocol and sub-10s test slicing."
3
3
  name: "Test Economy"
4
4
  ---
5
5
 
6
6
  Write one focused test per behavior; do not duplicate coverage.
7
7
 
8
- - **Test Slicing**: In dev loops, run ONLY the narrowest slice (<10s) for changed code (`node --test <slice>`, `pytest -k`); avoid unconstrained suites.
9
- - **Repo Selector & Receipt**: Prefer repo selectors (`test:quick`, `test:slice`); record command, targets, duration, and selection reason in `subtask_summary`.
10
- - **Failure/Fix Loops**: Rerun ONLY failed checks; never rerun passing tests without code changes.
11
- - **Mapping Gaps**: If a file lacks tests, run static check fallback plus nearest slice.
12
- - Slow install/E2E suites are opt-in, never per edit; reserve for release gates.
8
+ - **Risk-Based Slicing**: Run narrowest slice (<10s) first; broaden only on cross-module, contract, auth, or DB risk.
9
+ - **Suite Escalation**: Full suites are for CI/release; state if execution is agent recommendation or mandatory gate.
10
+ - **Failure/Fix Loops**: Rerun ONLY failed checks; never repeat passing tests. Never delete tests to speed up checks.
11
+ - **Mapping Gaps & Receipts**: Missing tests use static check plus nearest slice; record command, duration, and pending gates.
12
+ - **CLI vs Code**: Run CLI binaries (`opencode-quota`, `git`, `npm`) via `shell`/`bash`, not eval; on failure, never glob `~/.config`.
13
13
  - Test economy does NOT weaken stronger gates: auth, security, data-integrity, and required coverage.
@@ -295,9 +295,33 @@ def _validated_session_id(value: object) -> str | None:
295
295
  return value if isinstance(value, str) and value.startswith("ses") else None
296
296
 
297
297
 
298
+ def _discover_active_session_id() -> str | None:
299
+ """Discover active session id from environment or opencode.db."""
300
+ for env_var in ("OPENCODE_SESSION_ID", "SESSION_ID"):
301
+ val = os.getenv(env_var, "").strip()
302
+ if _validated_session_id(val):
303
+ return val
304
+ opencode_db_env = os.getenv("OPENCODE_DB", "").strip()
305
+ if opencode_db_env:
306
+ try:
307
+ db_path = Path(opencode_db_env)
308
+ if db_path.exists():
309
+ with sqlite3.connect(f"file:{db_path}?mode=ro", uri=True) as conn:
310
+ cur = conn.cursor()
311
+ cur.execute("SELECT id FROM session_v2 ORDER BY time_created DESC LIMIT 1")
312
+ row = cur.fetchone()
313
+ if row and _validated_session_id(row[0]):
314
+ return str(row[0])
315
+ except Exception:
316
+ pass
317
+ return None
318
+
319
+
298
320
  def _require_session_id(value: object) -> str:
299
321
  """Return a valid session id or fail before any Zen-bound work."""
300
322
  session_id = _validated_session_id(value)
323
+ if session_id is None and value is None:
324
+ session_id = _discover_active_session_id()
301
325
  if session_id is None:
302
326
  raise VisionError(
303
327
  "A valid OpenCode session id is required for Zen Vision; "
@@ -88,8 +88,29 @@ const SAFE_DEV_BINARIES: ReadonlySet<string> = new Set([
88
88
  'go',
89
89
  'sh',
90
90
  'bash',
91
+ 'opencode-quota',
91
92
  ])
92
93
 
94
+ /** Check if a resource target points to an excluded or sensitive path (.git, node_modules, traversal). */
95
+ export function isExcludedReadPath(rawPath: string): boolean {
96
+ const trimmed = rawPath.trim()
97
+ if (!trimmed) return false
98
+ const normalized = trimmed.replace(/\\/g, '/')
99
+ // Traversal outside workspace
100
+ if (normalized.startsWith('../') || normalized === '..' || normalized.includes('/../')) {
101
+ return true
102
+ }
103
+ // Sensitive system paths
104
+ if (/^\/(etc|boot|sys|proc|root)(\/|$)/.test(normalized)) {
105
+ return true
106
+ }
107
+ // Excluded repository internal directories (.git and node_modules)
108
+ if (/(^|\/)(\.git|node_modules)(\/|$)/.test(normalized)) {
109
+ return true
110
+ }
111
+ return false
112
+ }
113
+
93
114
  /** Check if auto-permissions engine is enabled in environment. */
94
115
  export function autoPermissionsEnabled(
95
116
  env: Record<string, string | undefined> = process.env,
@@ -238,14 +259,14 @@ export function evaluateAutoPermission(
238
259
 
239
260
  // 2. Read-only agents are strictly prohibited from mutating tools or shell
240
261
  if (READ_ONLY_AGENTS.has(agent)) {
241
- if (['edit', 'write', 'hashline_edit', 'bash', 'shell'].includes(action)) {
262
+ if (['edit', 'write', 'hashline_edit', 'bash', 'shell', 'execute'].includes(action)) {
242
263
  event.effect = 'deny'
243
264
  event.message = `Pantheon auto-permissions denied: read-only agent '${agent}' cannot execute mutating action '${action}'`
244
265
  return { decision: 'deny', reason: 'read-only-role-violation' }
245
266
  }
246
267
  }
247
268
 
248
- // 3. Read-only inspection tools are safe within workspace (excluding network/external URLs)
269
+ // 3. Read-only inspection tools are safe within workspace (excluding network/external URLs and excluded directories)
249
270
  if (['read', 'glob', 'grep', 'webfetch', 'question'].includes(action)) {
250
271
  const firstResource =
251
272
  Array.isArray(event.resources) && typeof event.resources[0] === 'string'
@@ -254,12 +275,17 @@ export function evaluateAutoPermission(
254
275
  if (firstResource.startsWith('http://') || firstResource.startsWith('https://')) {
255
276
  return { decision: 'passthrough' }
256
277
  }
278
+ if (firstResource && isExcludedReadPath(firstResource)) {
279
+ event.effect = 'deny'
280
+ event.message = `Pantheon auto-permissions denied: reading '${firstResource}' is prohibited (.git and node_modules are excluded)`
281
+ return { decision: 'deny', reason: 'excluded-path' }
282
+ }
257
283
  event.effect = 'allow'
258
284
  return { decision: 'allow', reason: 'safe-read-action' }
259
285
  }
260
286
 
261
- // 4. Shell commands
262
- if (action === 'bash' || action === 'shell') {
287
+ // 4. Shell and execution commands
288
+ if (action === 'bash' || action === 'shell' || action === 'execute') {
263
289
  const rawCmd =
264
290
  Array.isArray(event.resources) && typeof event.resources[0] === 'string'
265
291
  ? event.resources[0]
@@ -200,9 +200,15 @@ export const DEFAULT_BLOCKED_TOOLS: ReadonlySet<string> = new Set([
200
200
  /**
201
201
  * Path patterns that Zeus must NOT read directly. Zeus must delegate
202
202
  * codebase reads to @apollo to avoid context bloat and enforce separation
203
- * of concerns.
203
+ * of concerns. .git and node_modules are excluded repository noise.
204
204
  */
205
- export const ZEUS_READ_DENY_PATTERNS: ReadonlyArray<RegExp> = [/^src\//, /^tests?\//, /^scripts?\//]
205
+ export const ZEUS_READ_DENY_PATTERNS: ReadonlyArray<RegExp> = [
206
+ /^src\//,
207
+ /^tests?\//,
208
+ /^scripts?\//,
209
+ /(^|\/)\.git(\/|$)/,
210
+ /(^|\/)node_modules(\/|$)/,
211
+ ]
206
212
 
207
213
  /**
208
214
  * Normalize a tool-supplied path before it meets the deny patterns.
@@ -300,6 +306,9 @@ export function isDeniedGlobPattern(pattern: string): boolean {
300
306
  if (normalized.startsWith('../') || normalized === '..' || normalized.includes('/../')) {
301
307
  return true
302
308
  }
309
+ if (/(^|\/)(\.git|node_modules)(\/|$)/.test(normalized)) {
310
+ return true
311
+ }
303
312
  if (isDeniedReadPath(normalized, true)) {
304
313
  return true
305
314
  }
@@ -2,6 +2,7 @@
2
2
 
3
3
  import type { LookupAddress } from 'node:dns'
4
4
  import { lookup as dnsLookup } from 'node:dns/promises'
5
+ import { existsSync } from 'node:fs'
5
6
  import { readFile } from 'node:fs/promises'
6
7
  import { request as httpRequest } from 'node:http'
7
8
  import { request as httpsRequest } from 'node:https'
@@ -524,6 +525,53 @@ async function imageAttachment(
524
525
  return toImageAttachment(bytes, localPath.split(/[\\/]/).at(-1) || 'image')
525
526
  }
526
527
 
528
+ /**
529
+ * Discover the active OpenCode session ID from environment or opencode.db.
530
+ */
531
+ export function discoverActiveSessionId(directory?: string): string | undefined {
532
+ for (const envVar of ['OPENCODE_SESSION_ID', 'SESSION_ID']) {
533
+ const val = (process.env[envVar] ?? '').trim()
534
+ if (isValidSessionId(val)) return val
535
+ }
536
+ try {
537
+ const dataHome = process.env.XDG_DATA_HOME || join(homedir(), '.local', 'share')
538
+ const dbPath = process.env.OPENCODE_DB || join(dataHome, 'opencode', 'opencode.db')
539
+ if (!existsSync(dbPath)) return undefined
540
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
541
+ const sqlite = require('node:sqlite') as {
542
+ DatabaseSync: new (
543
+ path: string,
544
+ options: { readOnly: boolean },
545
+ ) => {
546
+ prepare: (query: string) => {
547
+ get: (...params: unknown[]) => Record<string, unknown> | undefined
548
+ }
549
+ close: () => void
550
+ }
551
+ }
552
+ const db = new sqlite.DatabaseSync(dbPath, { readOnly: true })
553
+ try {
554
+ if (directory) {
555
+ const row = db
556
+ .prepare(
557
+ 'SELECT id FROM session_v2 WHERE directory = ? ORDER BY time_created DESC LIMIT 1',
558
+ )
559
+ .get(directory)
560
+ if (row && isValidSessionId(row.id)) return String(row.id)
561
+ }
562
+ const fallbackRow = db
563
+ .prepare('SELECT id FROM session_v2 ORDER BY time_created DESC LIMIT 1')
564
+ .get()
565
+ if (fallbackRow && isValidSessionId(fallbackRow.id)) return String(fallbackRow.id)
566
+ } finally {
567
+ db.close()
568
+ }
569
+ } catch {
570
+ // Graceful fallback when node:sqlite is unavailable or db schema differs
571
+ }
572
+ return undefined
573
+ }
574
+
527
575
  export function createV2VisionTool(runtime: V2VisionRuntime): V2VisionToolDefinition {
528
576
  return {
529
577
  name: 'vision_describe',
@@ -551,7 +599,11 @@ export function createV2VisionTool(runtime: V2VisionRuntime): V2VisionToolDefini
551
599
  let stage = 'validate OpenCode session'
552
600
  try {
553
601
  const call = (asRecord(rawContext) ?? {}) as V2VisionToolContext
554
- if (!isValidSessionId(call.sessionID)) {
602
+ let sessionID = isValidSessionId(call.sessionID) ? call.sessionID : undefined
603
+ if (!sessionID) {
604
+ sessionID = discoverActiveSessionId(call.directory || process.cwd())
605
+ }
606
+ if (!sessionID) {
555
607
  throw new Error(
556
608
  'a valid OpenCode session id is required; retry this tool from an active OpenCode session',
557
609
  )
@@ -594,7 +646,7 @@ export function createV2VisionTool(runtime: V2VisionRuntime): V2VisionToolDefini
594
646
  // header ONLY for Zen targets, never to a non-Zen provider.
595
647
  const requestTarget: NativeVisionTarget = {
596
648
  ...target,
597
- sessionID: call.sessionID,
649
+ sessionID,
598
650
  }
599
651
  let failure: NativeVisionFailure | undefined
600
652
  const output = await describeImagesNative(
@@ -14,6 +14,9 @@
14
14
  * @module pantheon/skill-search-tool
15
15
  */
16
16
 
17
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
18
+ import { homedir } from 'node:os'
19
+ import { join } from 'node:path'
17
20
  // @ts-expect-error scripts/skill-search.mjs is a plain Node ESM script without bundled .d.ts
18
21
  import { searchSkillSources } from '../../scripts/skill-search.mjs'
19
22
  import { PANTHEON_SKILL_CATALOG } from './pantheon-decision-catalog.ts'
@@ -27,6 +30,101 @@ export interface SkillSearchResult {
27
30
  readonly installs?: number | null
28
31
  readonly url?: string
29
32
  readonly installCommand?: string | null
33
+ readonly path?: string | null
34
+ readonly scope?: 'internal' | 'project' | 'global'
35
+ }
36
+
37
+ export interface InstalledSkillRecord {
38
+ readonly id: string
39
+ readonly description: string
40
+ readonly path: string
41
+ readonly scope: 'internal' | 'project' | 'global'
42
+ }
43
+
44
+ export function extractSkillMetadata(
45
+ content: string,
46
+ fallbackName: string,
47
+ ): { name: string; description: string } {
48
+ let name = fallbackName
49
+ let description = ''
50
+ const fmMatch = content.match(/^---\r?\n([\s\S]*?)\r?\n---/)
51
+ const yaml = fmMatch?.[1]
52
+ if (yaml) {
53
+ const nameMatch = yaml.match(/^name:\s*["']?([^"'\r\n]+)["']?/m)
54
+ if (nameMatch?.[1]) name = nameMatch[1].trim()
55
+ const descMatch = yaml.match(/^description:\s*["']?([^"'\r\n]+)["']?/m)
56
+ if (descMatch?.[1]) description = descMatch[1].trim()
57
+ }
58
+ if (!description) {
59
+ const withoutFm = content.replace(/^---\r?\n[\s\S]*?\r?\n---/, '').trim()
60
+ const lines = withoutFm.split('\n')
61
+ for (const l of lines) {
62
+ const trimmed = l.trim()
63
+ if (trimmed && !trimmed.startsWith('#')) {
64
+ description = trimmed.slice(0, 160)
65
+ break
66
+ }
67
+ }
68
+ }
69
+ return { name, description }
70
+ }
71
+
72
+ export function scanInstalledSkills(
73
+ cwd: string = process.cwd(),
74
+ ): Map<string, InstalledSkillRecord> {
75
+ const map = new Map<string, InstalledSkillRecord>()
76
+
77
+ // 1. Built-in Pantheon catalog (internal base)
78
+ for (const entry of PANTHEON_SKILL_CATALOG) {
79
+ map.set(entry.id.toLowerCase(), {
80
+ id: entry.id,
81
+ description: entry.description,
82
+ path: `src/skills/${entry.id}/SKILL.md`,
83
+ scope: 'internal',
84
+ })
85
+ }
86
+
87
+ const scanDir = (baseDir: string, scope: 'project' | 'global') => {
88
+ try {
89
+ if (!existsSync(baseDir)) return
90
+ const entries = readdirSync(baseDir, { withFileTypes: true })
91
+ for (const entry of entries) {
92
+ if (!entry.isDirectory() && !entry.isSymbolicLink()) continue
93
+ const skillName = entry.name
94
+ if (skillName.startsWith('.')) continue
95
+ const skillMd = join(baseDir, skillName, 'SKILL.md')
96
+ if (existsSync(skillMd)) {
97
+ try {
98
+ const raw = readFileSync(skillMd, 'utf8')
99
+ const { name, description } = extractSkillMetadata(raw, skillName)
100
+ const id = (name || skillName).trim()
101
+ map.set(id.toLowerCase(), {
102
+ id,
103
+ description: description || skillName,
104
+ path: skillMd,
105
+ scope,
106
+ })
107
+ } catch {
108
+ // ignore unreadable files
109
+ }
110
+ }
111
+ }
112
+ } catch {
113
+ // ignore directory errors
114
+ }
115
+ }
116
+
117
+ // 2. Global directories
118
+ const xdgConfig = process.env.XDG_CONFIG_HOME || join(homedir(), '.config')
119
+ scanDir(join(xdgConfig, 'opencode', 'skills'), 'global')
120
+ scanDir(join(homedir(), '.agents', 'skills'), 'global')
121
+
122
+ // 3. Project directories (override global/internal)
123
+ scanDir(join(cwd, '.opencode', 'skills'), 'project')
124
+ scanDir(join(cwd, '.agents', 'skills'), 'project')
125
+ scanDir(join(cwd, 'skills'), 'project')
126
+
127
+ return map
30
128
  }
31
129
 
32
130
  export interface SkillSearchOutput {
@@ -74,7 +172,10 @@ const SKILL_SEARCH_INPUT_SCHEMA: Record<string, unknown> = {
74
172
  },
75
173
  }
76
174
 
77
- export function executeSkillSearch(input: Record<string, unknown>): SkillSearchOutput {
175
+ export function executeSkillSearch(
176
+ input: Record<string, unknown>,
177
+ options: { cwd?: string } = {},
178
+ ): SkillSearchOutput {
78
179
  const query = typeof input.query === 'string' ? input.query.trim() : ''
79
180
  if (query.length === 0) {
80
181
  return { ok: false, query: '', count: 0, results: [], failures: ['query must be non-empty'] }
@@ -97,7 +198,10 @@ export function executeSkillSearch(input: Record<string, unknown>): SkillSearchO
97
198
  const results: SkillSearchResult[] = []
98
199
  const failures: string[] = []
99
200
 
100
- // 1. Tier 1: Installed Pantheon catalog (in-memory, instant, zero-network)
201
+ const cwd = options.cwd ?? process.cwd()
202
+ const installedMap = scanInstalledSkills(cwd)
203
+
204
+ // 1. Tier 1: Installed skills (Pantheon catalog + local filesystem .opencode/skills and .agents/skills)
101
205
  if (sources.has('installed')) {
102
206
  const tokens = query
103
207
  .toLowerCase()
@@ -105,7 +209,7 @@ export function executeSkillSearch(input: Record<string, unknown>): SkillSearchO
105
209
  .filter((t) => t.length > 2)
106
210
 
107
211
  if (tokens.length > 0) {
108
- for (const entry of PANTHEON_SKILL_CATALOG) {
212
+ for (const entry of installedMap.values()) {
109
213
  const idLower = entry.id.toLowerCase()
110
214
  const descLower = entry.description.toLowerCase()
111
215
  const matchScore = tokens.reduce((score, t) => {
@@ -129,6 +233,8 @@ export function executeSkillSearch(input: Record<string, unknown>): SkillSearchO
129
233
  installed: true,
130
234
  installs: null,
131
235
  installCommand: null,
236
+ path: entry.path,
237
+ scope: entry.scope,
132
238
  })
133
239
  }
134
240
  }
@@ -152,15 +258,26 @@ export function executeSkillSearch(input: Record<string, unknown>): SkillSearchO
152
258
 
153
259
  if (Array.isArray(extRes.entries)) {
154
260
  for (const entry of extRes.entries) {
155
- results.push({
261
+ const bareName = (
262
+ entry.skill.includes('@') ? entry.skill.split('@')[1] : entry.skill
263
+ ).toLowerCase()
264
+ const isInstalled =
265
+ installedMap.has(entry.skill.toLowerCase()) || installedMap.has(bareName)
266
+ const installedRecord =
267
+ installedMap.get(entry.skill.toLowerCase()) || installedMap.get(bareName)
268
+
269
+ const pushItem: SkillSearchResult = {
156
270
  skill: entry.skill,
157
271
  description: entry.skill,
158
272
  source: entry.source as 'anthropic' | 'skills-sh' | 'github',
159
- installed: false,
273
+ installed: isInstalled,
160
274
  installs: entry.installs ?? null,
161
- url: entry.url,
162
- installCommand: `npx skills add ${entry.skill} -a opencode -y`,
163
- })
275
+ ...(entry.url ? { url: entry.url } : {}),
276
+ installCommand: isInstalled ? null : `npx skills add ${entry.skill} -a opencode -y`,
277
+ path: isInstalled && installedRecord ? installedRecord.path : null,
278
+ ...(isInstalled && installedRecord ? { scope: installedRecord.scope } : {}),
279
+ }
280
+ results.push(pushItem)
164
281
  }
165
282
  }
166
283
  } catch (err) {
@@ -186,8 +303,11 @@ export function createV2SkillSearchDefinition(): V2ToolDef {
186
303
  description: TOOL_DESCRIPTION,
187
304
  input: SKILL_SEARCH_INPUT_SCHEMA,
188
305
  output: {},
189
- execute: async (input: Record<string, unknown>) => ({
190
- output: JSON.stringify(executeSkillSearch(input), null, 2),
191
- }),
306
+ execute: async (input: Record<string, unknown>, context?: unknown) => {
307
+ const cwd = (context as { directory?: string } | undefined)?.directory || process.cwd()
308
+ return {
309
+ output: JSON.stringify(executeSkillSearch(input, { cwd }), null, 2),
310
+ }
311
+ },
192
312
  }
193
313
  }
@@ -567,7 +567,8 @@ const shellTool: V2ToolDef = {
567
567
  input: SHELL_INPUT,
568
568
  output: {},
569
569
  execute: async (input, context) => {
570
- const command = String((input as Record<string, unknown>).command ?? '')
570
+ const raw = (input as Record<string, unknown>) ?? {}
571
+ const command = String(raw.command ?? raw.cmd ?? '')
571
572
  if (!command.trim()) {
572
573
  return { output: '', ok: false, error: 'Command cannot be empty' }
573
574
  }