pantheon-opencode 1.6.0 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -34,6 +34,7 @@
34
34
 
35
35
  // ─── Types ─────────────────────────────────────────────────────────────
36
36
 
37
+ import type { GuardPathResolution } from './guard-path.ts'
37
38
  import { isAgentAllowed, type PermissionTaskConfig } from './permission-globs.ts'
38
39
 
39
40
  /** Why a session is read-only. */
@@ -203,43 +204,179 @@ export const DEFAULT_BLOCKED_TOOLS: ReadonlySet<string> = new Set([
203
204
  export const ZEUS_READ_DENY_PATTERNS: ReadonlyArray<RegExp> = [/^src\//, /^tests?\//, /^scripts?\//]
204
205
 
205
206
  /**
206
- * Path exceptions that Zeus MAY read even if they match a deny pattern.
207
- * Markdown files, .pantheon/ configs, and memories/ are operational context
208
- * that Zeus legitimately needs.
207
+ * Normalize a tool-supplied path before it meets the deny patterns.
208
+ *
209
+ * The patterns are anchored on `/`, so two spellings of the same source path
210
+ * used to pass: Windows separators (`src\\file.ts`) and a redundant dot prefix
211
+ * (`./src/file.ts`). Normalizing both is a TIGHTENING — it can only turn a
212
+ * previously allowed spelling into a denied one, never the reverse.
213
+ */
214
+ function normalizeGuardPath(value: string): string {
215
+ let normalized = value.replace(/\\/g, '/')
216
+ while (normalized.startsWith('./')) normalized = normalized.slice(2)
217
+ return normalized
218
+ }
219
+
220
+ /** One path-bearing argument, and whether it names a target or a query. */
221
+ interface GuardCandidate {
222
+ value: string
223
+ /** `filePath`/`path` name the read target; `pattern` may be a grep query. */
224
+ target: boolean
225
+ }
226
+
227
+ /**
228
+ * Path-bearing arguments of a read/glob/grep call.
229
+ *
230
+ * EVERY target is returned, not just the first: a `grep` call carries its
231
+ * directory in `path` and query in `pattern`. `pattern` is a TARGET for `glob`
232
+ * (it is the path pattern) but a QUERY for `grep` (it is the text to search
233
+ * for). Zeus' `grep.include` is rejected separately because the host's glob
234
+ * base and basename-matching semantics are not established.
235
+ */
236
+ function guardPathCandidates(tool: string, args: unknown): GuardCandidate[] {
237
+ if (args === null || typeof args !== 'object') return []
238
+ const record = args as Record<string, unknown>
239
+ const candidates: GuardCandidate[] = []
240
+ for (const key of ['filePath', 'path', 'pattern']) {
241
+ const value = record[key]
242
+ if (typeof value !== 'string' || value.trim() === '') continue
243
+ candidates.push({ value, target: key !== 'pattern' || tool === 'glob' })
244
+ }
245
+ return candidates
246
+ }
247
+
248
+ /**
249
+ * Whether a normalized path points AT or INTO a denied code root.
250
+ *
251
+ * A TARGET spelled without a trailing slash (`path: 'src'`) is a directory
252
+ * reference, so the slash form is tested too — `^src\\/` alone would miss it.
253
+ * A query (`pattern`) is only denied when it is path-shaped, so grepping for
254
+ * the literal word `src` stays allowed while `src/**` does not. Absolute paths
255
+ * are matched on every segment-boundary suffix, so `/abs/src/x` is the same
256
+ * source tree as `src/x`.
257
+ */
258
+ function isDeniedReadPath(candidate: string, target: boolean): boolean {
259
+ const matches = (value: string): boolean =>
260
+ ZEUS_READ_DENY_PATTERNS.some((pattern) => pattern.test(value))
261
+ const test = (value: string): boolean => {
262
+ if (matches(value)) return true
263
+ return target && !value.endsWith('/') && matches(`${value}/`)
264
+ }
265
+ if (test(candidate)) return true
266
+ if (!candidate.startsWith('/')) return false
267
+ const segments = candidate.split('/').filter((segment) => segment !== '')
268
+ for (let index = 0; index < segments.length; index++) {
269
+ if (test(segments.slice(index).join('/'))) return true
270
+ }
271
+ return false
272
+ }
273
+
274
+ /**
275
+ * Resolve a raw tool path for the guard. Supplied by the call site, never
276
+ * invoked by the pure predicate unless one is passed.
277
+ */
278
+ export type GuardPathResolver = (rawPath: string) => GuardPathResolution
279
+
280
+ /**
281
+ * Glob expansion is controlled by the host and its symlink-follow behavior is
282
+ * not part of this guard's contract. Only exact, non-glob paths are safe to
283
+ * preflight; fail closed on glob metacharacters rather than infer the host's
284
+ * expansion semantics.
209
285
  */
210
- export const ALLOWED_PATHS: ReadonlyArray<RegExp> = [/\.md$/, /\.pantheon\//, /memories\//]
286
+ function hasGlobMeta(value: string): boolean {
287
+ return ['*', '?', '[', ']', '{', '}', '(', ')'].some((meta) => value.includes(meta))
288
+ }
211
289
 
212
290
  /**
213
291
  * Zeus read guard. When the active agent is Zeus, deny read/glob/grep calls
214
292
  * that target source code, tests, or scripts — Zeus must delegate those to
215
- * @apollo. Allowed paths (markdown, .pantheon/, memories/) are exempt.
293
+ * @apollo. Project-root `.pantheon/` and `memories/` paths and ordinary docs
294
+ * remain readable because they are outside the denied code roots; they never
295
+ * exempt a resolved `src/`, `tests/`, or `scripts/` target. Glob patterns with
296
+ * wildcard metacharacters are rejected conservatively because host expansion
297
+ * and symlink-follow behavior cannot be safely preflighted here.
298
+ *
299
+ * Every path-bearing argument is checked, and path spellings are normalized
300
+ * first. Both are tightenings: a call Zeus could make before with a
301
+ * `path: 'src'` directory plus a harmless `pattern`, or with `./src/x` /
302
+ * `src\\x`, is now denied. When a resolver is supplied every target is resolved
303
+ * before any code-root decision, so the original spelling or an allowed suffix
304
+ * cannot hide a resolved code target. Zeus grep additionally requires resolver
305
+ * evidence that its target is a regular file inside the canonical project root.
306
+ *
307
+ * Symlink resolution is NOT part of this predicate: it is pure and synchronous
308
+ * and shared with V1, so a call site that wants it passes `resolvePath` (see
309
+ * `createGuardPathResolver`). When a resolver is supplied it runs for every
310
+ * TARGET path — a `grep` query is text, not a path — and a resolution FAILURE
311
+ * denies: a read guard fails closed. Non-Zeus behavior remains unchanged; Zeus
312
+ * grep without resolver evidence fails closed.
313
+ *
314
+ * Zeus grep requires an explicit, non-empty `path` that resolves to an existing
315
+ * regular file inside the project root. Directories (including `.` and `..`),
316
+ * paths outside the project, missing paths, and resolution failures are denied
317
+ * to prevent recursive or unbounded reads. Every `include` filter is rejected
318
+ * because host glob semantics are not established. Exact allowed docs files
319
+ * with ordinary text queries remain searchable.
216
320
  *
217
321
  * Non-Zeus sessions are never affected.
218
322
  *
219
323
  * @throws {Error} when Zeus attempts a denied read
220
324
  */
221
- export function zeusReadGuard(tool: string, args: unknown, agent: string | undefined): void {
325
+ export function zeusReadGuard(
326
+ tool: string,
327
+ args: unknown,
328
+ agent: string | undefined,
329
+ resolvePath?: GuardPathResolver,
330
+ ): void {
222
331
  if (agent !== 'zeus') return
223
332
  if (tool !== 'read' && tool !== 'glob' && tool !== 'grep') return
224
333
 
225
- const record = args as Record<string, unknown> | undefined
226
- const filePath =
227
- typeof record?.filePath === 'string'
228
- ? record.filePath
229
- : typeof record?.pattern === 'string'
230
- ? record.pattern
231
- : undefined
232
-
233
- if (!filePath) return
234
-
235
- for (const pattern of ZEUS_READ_DENY_PATTERNS) {
236
- if (pattern.test(filePath)) {
237
- // Check allowed-path exceptions before denying
238
- for (const allowed of ALLOWED_PATHS) {
239
- if (allowed.test(filePath)) return
240
- }
241
- throw new Error(`Zeus cannot read ${filePath} — delegate to @apollo`)
334
+ if (tool === 'grep') {
335
+ const record =
336
+ args !== null && typeof args === 'object' ? (args as Record<string, unknown>) : {}
337
+ const grepPath = record.path
338
+ if (typeof grepPath !== 'string' || grepPath.trim() === '') {
339
+ throw new Error('Zeus cannot grep without an explicit non-empty path — delegate to @apollo')
340
+ }
341
+ if (Object.hasOwn(record, 'include')) {
342
+ throw new Error('Zeus cannot use grep include filters — delegate to @apollo')
343
+ }
344
+ }
345
+
346
+ for (const candidate of guardPathCandidates(tool, args)) {
347
+ const normalized = normalizeGuardPath(candidate.value)
348
+ const deny = () => {
349
+ throw new Error(`Zeus cannot read ${candidate.value} — delegate to @apollo`)
350
+ }
351
+ if (normalized === '') {
352
+ if (tool === 'grep' && candidate.target) deny()
353
+ continue
354
+ }
355
+ // A project-root spelling is an unbounded grep target, even though it does
356
+ // not match any individual denied source-root pattern.
357
+ if (tool === 'grep' && candidate.target && normalized === '.') deny()
358
+ const resolution =
359
+ candidate.target && resolvePath !== undefined ? resolvePath(candidate.value) : undefined
360
+ if (resolution?.failed) deny()
361
+ if (
362
+ tool === 'grep' &&
363
+ candidate.target &&
364
+ (resolution === undefined ||
365
+ resolution.isRegularFile !== true ||
366
+ resolution.withinProject !== true)
367
+ ) {
368
+ deny()
369
+ }
370
+ const effectivePath = normalizeGuardPath(resolution?.resolved ?? normalized)
371
+ if (effectivePath === '' || (tool === 'grep' && candidate.target && effectivePath === '.')) {
372
+ if (tool === 'grep' && candidate.target) deny()
373
+ continue
242
374
  }
375
+ // Resolve every direct grep/glob path before any policy decision. Wildcard
376
+ // expansion itself cannot be safely preflighted using the host's unknown
377
+ // symlink semantics, so Zeus may glob exact paths only.
378
+ if (tool === 'glob' && candidate.target && hasGlobMeta(effectivePath)) deny()
379
+ if (isDeniedReadPath(effectivePath, candidate.target)) deny()
243
380
  }
244
381
  }
245
382
 
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Symlink resolution for the Zeus read guard.
3
+ *
4
+ * `zeusReadGuard` is a pure, synchronous predicate shared by V1 and V2, so it
5
+ * cannot touch the filesystem itself. It therefore used to match only the
6
+ * STRING path: `docs/link → ../src` reached `src/` after resolution but passed
7
+ * the guard, while `pantheon_bounded_read` refused the same path via `lstat` +
8
+ * `realpath`. This module closes that gap at the CALL SITES: they resolve the
9
+ * raw path once, then hand the result to the guard.
10
+ *
11
+ * Resolution rules:
12
+ * - relative paths resolve against the project root, absolute paths stand;
13
+ * - a path that does not exist resolves its deepest EXISTING ancestor and
14
+ * re-appends the remaining segments — a deleted path can still be a bypass;
15
+ * - a resolved path inside the project root is expressed RELATIVE to it (so a
16
+ * project living under a directory named `src` is not a false positive),
17
+ * and a resolved path outside the root stays absolute (the guard already
18
+ * suffix-matches absolute paths, which is what catches `../src`);
19
+ * - any resolution failure (symlink loop, permissions, …) is reported as
20
+ * `failed`: a read guard fails CLOSED, and the guard denies.
21
+ */
22
+
23
+ import { lstatSync, realpathSync, statSync } from 'node:fs'
24
+ import path from 'node:path'
25
+
26
+ /** One path form prepared for the guard. */
27
+ export interface GuardPathResolution {
28
+ /** Path as supplied, with separators normalized. */
29
+ raw: string
30
+ /**
31
+ * Symlink-resolved path: relative to the project root when it lands inside
32
+ * it, absolute otherwise. Absent when resolution failed.
33
+ */
34
+ resolved?: string
35
+ /** `true` when the path could not be resolved — the guard must DENY. */
36
+ failed: boolean
37
+ /** Filesystem annotation from the call-site resolver; never computed by the pure guard. */
38
+ isRegularFile?: boolean
39
+ /** Whether the canonical target is the project root or one of its descendants. */
40
+ withinProject?: boolean
41
+ }
42
+
43
+ /** Errors that mean "this component does not exist", not "resolution failed". */
44
+ const MISSING_CODES: ReadonlySet<string> = new Set(['ENOENT', 'ENOTDIR'])
45
+ /** Bound filesystem component walks; paths beyond this limit fail closed. */
46
+ const MAX_PATH_COMPONENTS = 64
47
+
48
+ function errorCode(error: unknown): string {
49
+ if (typeof error !== 'object' || error === null || !('code' in error)) return ''
50
+ return String((error as { code: unknown }).code)
51
+ }
52
+
53
+ function isMissing(error: unknown): boolean {
54
+ return MISSING_CODES.has(errorCode(error))
55
+ }
56
+
57
+ /** `true` when `target` is `root` or lives under it (both absolute). */
58
+ function isWithin(root: string, target: string): boolean {
59
+ const relative = path.relative(root, target)
60
+ return (
61
+ relative === '' ||
62
+ (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative))
63
+ )
64
+ }
65
+
66
+ /**
67
+ * `realpath` of `absolute`, or of its deepest existing ancestor with the
68
+ * non-existent remainder appended. At most 64 components are examined; an
69
+ * existing dangling symlink or an overlong path fails closed.
70
+ *
71
+ * @returns the resolved absolute path, or `undefined` when resolution failed
72
+ * for a reason other than a missing component.
73
+ */
74
+ function resolveExistingPrefix(absolute: string): string | undefined {
75
+ let cursor = path.resolve(absolute)
76
+ if (cursor.split(path.sep).filter(Boolean).length > MAX_PATH_COMPONENTS) return undefined
77
+ const remainder: string[] = []
78
+ for (let walked = 0; walked < MAX_PATH_COMPONENTS; walked++) {
79
+ try {
80
+ const resolved = realpathSync(cursor)
81
+ return remainder.length === 0 ? resolved : path.join(resolved, ...remainder)
82
+ } catch (error) {
83
+ if (!isMissing(error)) return undefined
84
+ try {
85
+ if (lstatSync(cursor).isSymbolicLink()) return undefined
86
+ } catch (lstatError) {
87
+ if (!isMissing(lstatError)) return undefined
88
+ }
89
+ const parent = path.dirname(cursor)
90
+ // Reached the filesystem root without resolving: unreachable on a sane
91
+ // system, but a failure must stay a failure (fail closed).
92
+ if (parent === cursor) return undefined
93
+ remainder.unshift(path.basename(cursor))
94
+ cursor = parent
95
+ }
96
+ }
97
+ return undefined
98
+ }
99
+
100
+ /** Normalize a resolved absolute path into the form the guard matches. */
101
+ function toGuardForm(resolvedAbsolute: string, rootReal: string): string {
102
+ const relative = isWithin(rootReal, resolvedAbsolute)
103
+ ? path.relative(rootReal, resolvedAbsolute)
104
+ : resolvedAbsolute
105
+ return relative.split(path.sep).join('/')
106
+ }
107
+
108
+ /** Canonicalize an existing project directory; failure must never broaden access. */
109
+ function canonicalProjectRoot(projectRoot: string): string | undefined {
110
+ try {
111
+ const rootReal = realpathSync(path.resolve(projectRoot))
112
+ return statSync(rootReal).isDirectory() ? rootReal : undefined
113
+ } catch {
114
+ return undefined
115
+ }
116
+ }
117
+
118
+ function resolveAgainst(rawPath: string, rootReal: string): GuardPathResolution {
119
+ const raw = rawPath.replace(/\\/g, '/')
120
+ const absolute = path.resolve(rootReal, raw)
121
+ const resolvedAbsolute = resolveExistingPrefix(absolute)
122
+ if (resolvedAbsolute === undefined) return { raw, failed: true }
123
+ let isRegularFile = false
124
+ try {
125
+ isRegularFile = statSync(resolvedAbsolute).isFile()
126
+ } catch (error) {
127
+ if (!isMissing(error)) return { raw, failed: true }
128
+ }
129
+ return {
130
+ raw,
131
+ resolved: toGuardForm(resolvedAbsolute, rootReal),
132
+ failed: false,
133
+ isRegularFile,
134
+ withinProject: isWithin(rootReal, resolvedAbsolute),
135
+ }
136
+ }
137
+
138
+ /**
139
+ * Resolve one raw tool path for the Zeus read guard.
140
+ *
141
+ * Use {@link createGuardPathResolver} at a call site that checks many paths:
142
+ * it resolves the project root once instead of once per path.
143
+ */
144
+ export function resolveGuardPathForCheck(
145
+ rawPath: string,
146
+ projectRoot: string,
147
+ ): GuardPathResolution {
148
+ const rootReal = canonicalProjectRoot(projectRoot)
149
+ return rootReal === undefined ? { raw: rawPath, failed: true } : resolveAgainst(rawPath, rootReal)
150
+ }
151
+
152
+ /**
153
+ * Build the per-call-site resolver. The project root is resolved once, so a
154
+ * symlinked root (`/tmp` → `/private/tmp`) compares against real paths.
155
+ */
156
+ export function createGuardPathResolver(
157
+ projectRoot: string,
158
+ ): (rawPath: string) => GuardPathResolution {
159
+ const rootReal = canonicalProjectRoot(projectRoot)
160
+ return (rawPath) =>
161
+ rootReal === undefined ? { raw: rawPath, failed: true } : resolveAgainst(rawPath, rootReal)
162
+ }
@@ -61,6 +61,12 @@ const DENIED_EXTENSIONS = new Set([
61
61
  '.db',
62
62
  '.sql',
63
63
  ])
64
+ /**
65
+ * Top-level code roots denied for the same reason the Zeus read guard denies
66
+ * them (`ZEUS_READ_DENY_PATTERNS` in delegation-enforce.ts): `src/`, `tests/`,
67
+ * `scripts/`. Mirrors `/^(src\/|tests?\/|scripts?\/)/`.
68
+ */
69
+ const DENIED_CODE_ROOTS = new Set(['src', 'test', 'tests', 'script', 'scripts'])
64
70
  const DENIED_MEDIA_EXTENSIONS = new Set([
65
71
  '.avif',
66
72
  '.bmp',
@@ -314,6 +320,14 @@ function sensitivePath(relativePath: string): boolean {
314
320
  const leaf = components.at(-1) ?? ''
315
321
  const extension = path.extname(leaf)
316
322
  return (
323
+ // Code roots are denied for the SAME reason the Zeus read guard denies
324
+ // `read`/`glob`/`grep` on them (issue #264): this tool is root-Zeus-only, so
325
+ // allowing `src/`, `tests/` or `scripts/` here would let the orchestrator
326
+ // read 2×400 lines of source through a first-class tool while the guarded
327
+ // `read` is refused — the documented "Zeus delegates code reads to @apollo"
328
+ // policy would hold only on paper. Docs, config, the memory bank and
329
+ // `.pantheon/` stay readable: that is what this tool exists for.
330
+ DENIED_CODE_ROOTS.has(components[0] ?? '') ||
317
331
  components.some(
318
332
  (component) =>
319
333
  DENIED_COMPONENTS.has(component) ||
@@ -499,7 +513,7 @@ export function createV2BoundedReadTool(dependencies: BoundedReadDependencies):
499
513
  const definition: V2ToolDef = {
500
514
  name: BOUNDED_READ_TOOL,
501
515
  description:
502
- 'Read a small line range from one exact text file inside the current project. Root Zeus only; two files and 400 lines total per assistant message. Denies recognized sensitive scopes and known binary/media formats; returns only bounded valid UTF-8 text after secret scanning. No directories or fallback reading.',
516
+ 'Read a small line range from one exact text file inside the current project. Root Zeus only; two files and 400 lines total per assistant message. Denies the code roots Zeus must delegate (src/, tests/, scripts/), recognized sensitive scopes, and known binary/media formats; returns only bounded valid UTF-8 text after secret scanning. No directories or fallback reading.',
503
517
  input: {
504
518
  type: 'object',
505
519
  additionalProperties: false,
@@ -124,3 +124,30 @@ export function getV2BridgeFromContext(ctx: V2ContextLike): PantheonV2Bridge | n
124
124
  export function injectBridge(ctx: V2ContextLike, bridge: PantheonV2Bridge): void {
125
125
  ctx.options[BRIDGE_OPTIONS_KEY] = bridge
126
126
  }
127
+
128
+ // ─── Process-wide registration (cross-generation) ──────────────────────
129
+
130
+ /**
131
+ * The bridge registered by whichever plugin loaded first in this process.
132
+ *
133
+ * The module-level handle lives HERE rather than in `plugin-v2.ts` because V1
134
+ * must be able to publish its singletons WITHOUT importing the V2 plugin: a
135
+ * V1-only install never loads `plugin-v2.ts`, and importing it just to hand
136
+ * over a bridge would pull the V2 `define()` into that process.
137
+ *
138
+ * Why registration matters: in a process that loads both generations (npm +
139
+ * repo double load, or a mixed config), V1's idle dispatcher and the V2 entry
140
+ * would otherwise each build a TodoEnforcer and answer the same `session.idle`
141
+ * twice — two continuation prompts for one idle. V1 registers; V2 reuses.
142
+ */
143
+ let registeredBridge: PantheonV2Bridge | null = null
144
+
145
+ /** Publish (or, with `null`, clear) the process-wide bridge. */
146
+ export function registerV2Bridge(bridge: PantheonV2Bridge | null): void {
147
+ registeredBridge = bridge
148
+ }
149
+
150
+ /** The bridge published by this process, or null. */
151
+ export function getRegisteredV2Bridge(): PantheonV2Bridge | null {
152
+ return registeredBridge
153
+ }