pantheon-opencode 1.6.0-beta.9 → 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.
Files changed (140) hide show
  1. package/AGENTS.global.md +118 -0
  2. package/AGENTS.md +18 -168
  3. package/CHANGELOG.md +144 -365
  4. package/README.md +124 -607
  5. package/README.pt-BR.md +120 -345
  6. package/bin/pantheon-init.mjs +504 -141
  7. package/commands/pantheon-deepwork.md +14 -3
  8. package/commands/pantheon-vision.md +61 -12
  9. package/package.json +22 -13
  10. package/plugin.json +1 -1
  11. package/pyproject.toml +6 -2
  12. package/scripts/_pantheon_paths.py +24 -0
  13. package/scripts/build-agents-md.mjs +368 -69
  14. package/scripts/changelog-merge.mjs +161 -0
  15. package/scripts/check-plugin-v2-coverage.mjs +11 -8
  16. package/scripts/docs-check-changelog.mjs +204 -0
  17. package/scripts/docs-link-check.mjs +314 -0
  18. package/scripts/docs-media.mjs +157 -0
  19. package/scripts/doctor.mjs +850 -45
  20. package/scripts/install/agents-md.mjs +2 -2
  21. package/scripts/install/backup.mjs +648 -0
  22. package/scripts/install/cli-ui.mjs +303 -72
  23. package/scripts/install/component-selection.mjs +61 -0
  24. package/scripts/install/config-migration.mjs +583 -27
  25. package/scripts/install/exit-codes.mjs +26 -0
  26. package/scripts/install/file-inventory.mjs +555 -0
  27. package/scripts/install/health-check.mjs +31 -25
  28. package/scripts/install/interactive.mjs +99 -383
  29. package/scripts/install/interrupt.mjs +78 -0
  30. package/scripts/install/migrate.mjs +49 -25
  31. package/scripts/install/model-picker.mjs +218 -250
  32. package/scripts/install/opencode-state.mjs +91 -0
  33. package/scripts/install/opencode-version.mjs +83 -21
  34. package/scripts/install/opencode.mjs +1675 -187
  35. package/scripts/install/plan-artifact.mjs +517 -0
  36. package/scripts/install/plan.mjs +475 -0
  37. package/scripts/install/plugin.mjs +214 -27
  38. package/scripts/install/prompt-result.mjs +2 -0
  39. package/scripts/install/run-record.mjs +115 -0
  40. package/scripts/install/shared.mjs +256 -99
  41. package/scripts/install/state.mjs +63 -8
  42. package/scripts/install/strings.mjs +93 -8
  43. package/scripts/install/v2-capabilities.mjs +205 -0
  44. package/scripts/install/venv.mjs +90 -47
  45. package/scripts/install/verify.mjs +128 -0
  46. package/scripts/install/vision-prompt.mjs +173 -0
  47. package/scripts/install-mcp.mjs +2 -2
  48. package/scripts/manifest-inventory.mjs +49 -3
  49. package/scripts/mcp_persistence.py +1535 -1050
  50. package/scripts/memory_mcp.py +12 -843
  51. package/scripts/node-engine-policy.mjs +85 -0
  52. package/scripts/package-evidence.mjs +10 -2
  53. package/scripts/postinstall.mjs +26 -26
  54. package/scripts/probe-pantheon-cost.mjs +118 -19
  55. package/scripts/prune.mjs +9 -3
  56. package/scripts/reconcile.mjs +325 -0
  57. package/scripts/release-gates.mjs +687 -0
  58. package/scripts/restore.mjs +222 -0
  59. package/scripts/run-node-tests.mjs +24 -8
  60. package/scripts/sync-artifacts.mjs +19 -7
  61. package/scripts/sync-tui.mjs +5 -1
  62. package/scripts/test-opencode-v2-sandbox.sh +36 -123
  63. package/scripts/uninstall.mjs +369 -34
  64. package/scripts/update.mjs +164 -0
  65. package/scripts/validate-node-engine-policy.mjs +13 -0
  66. package/scripts/version-check.mjs +34 -1
  67. package/scripts/versioning.mjs +23 -3
  68. package/scripts/vision-status.mjs +682 -0
  69. package/skills-lock.json +8 -8
  70. package/src/agents/aphrodite.md +13 -10
  71. package/src/agents/apollo.md +4 -5
  72. package/src/agents/athena.md +74 -46
  73. package/src/agents/demeter.md +10 -7
  74. package/src/agents/gaia.md +0 -1
  75. package/src/agents/hephaestus.md +4 -3
  76. package/src/agents/hermes.md +10 -9
  77. package/src/agents/iris.md +6 -1
  78. package/src/agents/mnemosyne.md +10 -4
  79. package/src/agents/nyx.md +4 -4
  80. package/src/agents/prometheus.md +12 -11
  81. package/src/agents/talos.md +6 -0
  82. package/src/agents/zeus.md +84 -56
  83. package/src/instructions/agent-return-format.instructions.md +12 -41
  84. package/src/instructions/memory-protocol.instructions.md +5 -11
  85. package/src/instructions/test-economy.instructions.md +12 -0
  86. package/src/instructions/yagni.instructions.md +6 -15
  87. package/src/instructions/zeus-anti-stall.instructions.md +6 -6
  88. package/src/instructions/zeus-communication-rules.instructions.md +6 -6
  89. package/src/instructions/zeus-council-synthesis.instructions.md +11 -12
  90. package/src/instructions/zeus-memory-operations.instructions.md +13 -7
  91. package/src/instructions/zeus-timeout-retry.instructions.md +36 -10
  92. package/src/mcp/_pantheon_paths.py +24 -0
  93. package/src/mcp/mcp_codemap_module.py +86 -18
  94. package/src/mcp/mcp_persistence.py +1535 -1050
  95. package/src/mcp/memory_mcp.py +444 -94
  96. package/src/mcp/pantheon_vision.py +285 -41
  97. package/src/mcp/requirements-mcp.txt +6 -1
  98. package/src/mcp/requirements-vision.txt +1 -1
  99. package/src/pantheon/context-pruner.ts +541 -0
  100. package/src/pantheon/cost-command.ts +901 -60
  101. package/src/pantheon/delegation-enforce.ts +160 -23
  102. package/src/pantheon/goal-loop.ts +11 -8
  103. package/src/pantheon/guard-path.ts +162 -0
  104. package/src/pantheon/memory-context.ts +1017 -0
  105. package/src/pantheon/model-agents.ts +19 -0
  106. package/src/pantheon/model-command.ts +218 -56
  107. package/src/pantheon/model-pricing.ts +536 -0
  108. package/src/pantheon/presets.mjs +2 -0
  109. package/src/pantheon/task-result-guard.ts +50 -14
  110. package/src/pantheon/v2-bounded-read.ts +654 -0
  111. package/src/pantheon/v2-bridge.ts +27 -0
  112. package/src/pantheon/v2-delegation-enforce.ts +133 -6
  113. package/src/pantheon/v2-execute-after.ts +135 -24
  114. package/src/pantheon/v2-model-overrides.ts +275 -0
  115. package/src/pantheon/v2-shell-hooks.ts +260 -0
  116. package/src/pantheon/v2-tools.ts +89 -35
  117. package/src/pantheon/v2-unsupported.mjs +34 -7
  118. package/src/pantheon/v2-vision.ts +622 -0
  119. package/src/pantheon/vision-local.ts +531 -0
  120. package/src/pantheon/vision.ts +1166 -116
  121. package/src/plugin-v2.ts +1039 -171
  122. package/src/plugin.ts +37 -13
  123. package/src/plugins/tui/dist/tui-v2.d.ts +1029 -2
  124. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  125. package/src/plugins/tui/dist/tui-v2.js +3742 -85
  126. package/src/plugins/tui/dist/tui.js +1 -1
  127. package/src/plugins/tui/package-lock.json +15 -15
  128. package/src/plugins/tui/package.json +7 -5
  129. package/src/plugins/tui/src/index-v2.tsx +4314 -50
  130. package/src/plugins/tui/tsconfig.typecheck.json +5 -0
  131. package/src/routing.yml +50 -5
  132. package/src/skills/agent-coordination/SKILL.md +7 -2
  133. package/src/skills/artifact-management/SKILL.md +5 -1
  134. package/src/skills/auto-continue/SKILL.md +14 -6
  135. package/src/skills/codemap/SKILL.md +1 -1
  136. package/src/skills/memory-bank/SKILL.md +21 -13
  137. package/src/skills/session-goal/SKILL.md +12 -22
  138. package/src/skills/spec-driven-development/SKILL.md +3 -1
  139. package/src/skills/worktrees/SKILL.md +30 -11
  140. package/scripts/probe-context-rehydrate.mjs +0 -263
@@ -0,0 +1,654 @@
1
+ /** Minimal, session-scoped bounded file reader for the OpenCode V2 surface. */
2
+
3
+ import { constants } from 'node:fs'
4
+ import { lstat, open, realpath } from 'node:fs/promises'
5
+ import path from 'node:path'
6
+ import type { V2ToolDef } from './v2-tools.ts'
7
+
8
+ export const BOUNDED_READ_TOOL = 'pantheon_bounded_read'
9
+ export const BOUNDED_READ_MAX_CALLS = 2
10
+ export const BOUNDED_READ_MAX_FILES = 2
11
+ export const BOUNDED_READ_MAX_LINES = 400
12
+ export const BOUNDED_READ_MAX_BYTES = 32 * 1024
13
+ const BYTES_PER_CALL = BOUNDED_READ_MAX_BYTES / BOUNDED_READ_MAX_CALLS
14
+ const ORIGIN_TTL_MS = 60_000
15
+ const MAX_SESSIONS = 256
16
+ const READ_CHUNK_BYTES = 1
17
+ const DENIED_COMPONENTS = new Set([
18
+ '.aws',
19
+ '.config',
20
+ '.docker',
21
+ '.gnupg',
22
+ '.kube',
23
+ '.netrc',
24
+ '.npmrc',
25
+ '.pypirc',
26
+ '.ssh',
27
+ '.git',
28
+ 'auth',
29
+ 'authentication',
30
+ 'database',
31
+ 'db',
32
+ 'global',
33
+ 'migration',
34
+ 'migrations',
35
+ 'schema',
36
+ 'schemas',
37
+ 'data',
38
+ 'dataset',
39
+ 'datasets',
40
+ 'authorized_keys',
41
+ 'credentials',
42
+ 'id_ed25519',
43
+ 'id_rsa',
44
+ 'known_hosts',
45
+ 'secrets',
46
+ ])
47
+ const DENIED_EXTENSIONS = new Set([
48
+ '.cer',
49
+ '.crt',
50
+ '.der',
51
+ '.jks',
52
+ '.key',
53
+ '.p12',
54
+ '.p7b',
55
+ '.p7c',
56
+ '.pem',
57
+ '.pfx',
58
+ '.pub',
59
+ '.sqlite',
60
+ '.sqlite3',
61
+ '.db',
62
+ '.sql',
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'])
70
+ const DENIED_MEDIA_EXTENSIONS = new Set([
71
+ '.avif',
72
+ '.bmp',
73
+ '.gif',
74
+ '.heic',
75
+ '.heif',
76
+ '.ico',
77
+ '.jpeg',
78
+ '.jpg',
79
+ '.png',
80
+ '.svg',
81
+ '.webp',
82
+ '.pdf',
83
+ '.mp3',
84
+ '.mp4',
85
+ '.wav',
86
+ '.zip',
87
+ '.gz',
88
+ '.tar',
89
+ '.7z',
90
+ '.a',
91
+ '.class',
92
+ '.dll',
93
+ '.docx',
94
+ '.dylib',
95
+ '.exe',
96
+ '.jar',
97
+ '.odt',
98
+ '.ods',
99
+ '.otf',
100
+ '.o',
101
+ '.pptx',
102
+ '.pyc',
103
+ '.rar',
104
+ '.so',
105
+ '.ttf',
106
+ '.wasm',
107
+ '.woff',
108
+ '.woff2',
109
+ '.xlsx',
110
+ '.xz',
111
+ ])
112
+
113
+ export interface BoundedReadIdentity {
114
+ sessionID: string
115
+ messageID: string
116
+ callID: string
117
+ agent: string
118
+ relativePath: string
119
+ }
120
+
121
+ interface StoredOrigin extends BoundedReadIdentity {
122
+ capturedAt: number
123
+ }
124
+
125
+ function isRecord(value: unknown): value is Record<string, unknown> {
126
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
127
+ }
128
+
129
+ function nonEmpty(value: unknown): string | undefined {
130
+ return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined
131
+ }
132
+
133
+ function originKey(sessionID: string, messageID: string, callID: string): string {
134
+ return JSON.stringify([sessionID, messageID, callID])
135
+ }
136
+
137
+ function budgetKey(sessionID: string, messageID: string): string {
138
+ return JSON.stringify([sessionID, messageID])
139
+ }
140
+
141
+ /** One-shot proof that this exact V2 root tool invocation reached execute(). */
142
+ export class V2BoundedReadOriginRegistry {
143
+ private readonly entries = new Map<string, StoredOrigin>()
144
+
145
+ capture(rawEvent: unknown, now = Date.now()): BoundedReadIdentity | undefined {
146
+ this.prune(now)
147
+ if (!isRecord(rawEvent) || rawEvent.tool !== BOUNDED_READ_TOOL || !isRecord(rawEvent.input)) {
148
+ return undefined
149
+ }
150
+ const identity = {
151
+ sessionID: nonEmpty(rawEvent.sessionID),
152
+ messageID: nonEmpty(rawEvent.messageID),
153
+ callID: nonEmpty(rawEvent.id),
154
+ agent: nonEmpty(rawEvent.agent),
155
+ relativePath: validateRelativePath(rawEvent.input.path) ? rawEvent.input.path : undefined,
156
+ }
157
+ if (
158
+ identity.sessionID === undefined ||
159
+ identity.messageID === undefined ||
160
+ identity.callID === undefined ||
161
+ identity.agent !== 'zeus' ||
162
+ identity.relativePath === undefined ||
163
+ this.entries.size >= MAX_SESSIONS
164
+ ) {
165
+ return undefined
166
+ }
167
+ const origin: BoundedReadIdentity = {
168
+ sessionID: identity.sessionID,
169
+ messageID: identity.messageID,
170
+ callID: identity.callID,
171
+ agent: identity.agent,
172
+ relativePath: identity.relativePath,
173
+ }
174
+ this.entries.set(originKey(origin.sessionID, origin.messageID, origin.callID), {
175
+ ...origin,
176
+ capturedAt: now,
177
+ })
178
+ return origin
179
+ }
180
+
181
+ consume(
182
+ identity: Omit<BoundedReadIdentity, 'relativePath'> & { relativePath: unknown },
183
+ now = Date.now(),
184
+ ): BoundedReadIdentity | undefined {
185
+ this.prune(now)
186
+ const key = originKey(identity.sessionID, identity.messageID, identity.callID)
187
+ const origin = this.entries.get(key)
188
+ this.entries.delete(key)
189
+ if (
190
+ origin === undefined ||
191
+ identity.agent !== origin.agent ||
192
+ identity.relativePath !== origin.relativePath
193
+ ) {
194
+ return undefined
195
+ }
196
+ const { capturedAt: _capturedAt, ...result } = origin
197
+ return result
198
+ }
199
+
200
+ forget(rawEvent: unknown): void {
201
+ if (!isRecord(rawEvent)) return
202
+ const sessionID = nonEmpty(rawEvent.sessionID)
203
+ const messageID = nonEmpty(rawEvent.messageID)
204
+ const callID = nonEmpty(rawEvent.id)
205
+ if (sessionID && messageID && callID) {
206
+ this.entries.delete(originKey(sessionID, messageID, callID))
207
+ }
208
+ }
209
+
210
+ clearSession(sessionID: string): void {
211
+ for (const [key, entry] of this.entries) {
212
+ if (entry.sessionID === sessionID) this.entries.delete(key)
213
+ }
214
+ }
215
+
216
+ private prune(now: number): void {
217
+ for (const [key, entry] of this.entries) {
218
+ if (now - entry.capturedAt > ORIGIN_TTL_MS) this.entries.delete(key)
219
+ }
220
+ }
221
+ }
222
+
223
+ interface Budget {
224
+ sessionID: string
225
+ messageID: string
226
+ root: string
227
+ files: Set<string>
228
+ calls: number
229
+ lines: number
230
+ bytes: number
231
+ sealed: boolean
232
+ }
233
+
234
+ export interface BoundedReadHostSession {
235
+ id?: unknown
236
+ parentID?: unknown
237
+ projectID?: unknown
238
+ }
239
+
240
+ export interface BoundedReadDependencies {
241
+ /** Project identity is taken from ctx.location once during plugin setup. */
242
+ rootDirectory: string
243
+ projectID: string
244
+ getSession: (sessionID: string) => Promise<unknown>
245
+ assertPermission: (request: Record<string, unknown>) => Promise<unknown>
246
+ scanContent: (input: {
247
+ content: string
248
+ agent: string
249
+ sessionID: string
250
+ messageID: string
251
+ callID: string
252
+ }) => Promise<'allow' | 'deny' | 'unavailable'>
253
+ }
254
+
255
+ interface ReadArgs {
256
+ path: string
257
+ offset: number
258
+ limit: number
259
+ }
260
+
261
+ function validateRelativePath(value: unknown): value is string {
262
+ if (typeof value !== 'string' || value.length === 0 || value.length > 240) return false
263
+ if (
264
+ value.startsWith('/') ||
265
+ value.startsWith('\\') ||
266
+ value.includes('\\') ||
267
+ value.includes('\0') ||
268
+ value.includes(':') ||
269
+ value.includes('*') ||
270
+ value.includes('?') ||
271
+ value.includes('[') ||
272
+ value.includes(']') ||
273
+ value.includes('{') ||
274
+ value.includes('}') ||
275
+ value.includes('%') ||
276
+ value.startsWith('~')
277
+ ) {
278
+ return false
279
+ }
280
+ const components = value.split('/')
281
+ if (components.some((component) => component === '' || component === '.' || component === '..')) {
282
+ return false
283
+ }
284
+ return components.every((component) =>
285
+ [...component].every((character) => {
286
+ const code = character.charCodeAt(0)
287
+ return code > 0x1f && code !== 0x7f
288
+ }),
289
+ )
290
+ }
291
+
292
+ function parseArgs(input: Record<string, unknown>): ReadArgs | undefined {
293
+ if (Object.keys(input).some((key) => !['path', 'offset', 'limit'].includes(key))) return undefined
294
+ const filePath = input.path
295
+ const offset = input.offset
296
+ const limit = input.limit
297
+ if (
298
+ !validateRelativePath(filePath) ||
299
+ !Number.isSafeInteger(offset) ||
300
+ (offset as number) < 1 ||
301
+ !Number.isSafeInteger(limit) ||
302
+ (limit as number) < 1 ||
303
+ (limit as number) > BOUNDED_READ_MAX_LINES
304
+ ) {
305
+ return undefined
306
+ }
307
+ return { path: filePath, offset: offset as number, limit: limit as number }
308
+ }
309
+
310
+ function isWithin(root: string, target: string): boolean {
311
+ const relative = path.relative(root, target)
312
+ return (
313
+ relative === '' ||
314
+ (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative))
315
+ )
316
+ }
317
+
318
+ function sensitivePath(relativePath: string): boolean {
319
+ const components = relativePath.split('/').map((component) => component.toLowerCase())
320
+ const leaf = components.at(-1) ?? ''
321
+ const extension = path.extname(leaf)
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] ?? '') ||
331
+ components.some(
332
+ (component) =>
333
+ DENIED_COMPONENTS.has(component) ||
334
+ component.startsWith('.env') ||
335
+ /(^|[._-])(auth|authentication|data|dataset|datasets|database|db|schema|schemas|global|migration|migrations)([._-]|$)/.test(
336
+ component,
337
+ ),
338
+ ) ||
339
+ /(^|[._-])(secret|token|credential|credentials|password|private)([._-]|$)/.test(leaf) ||
340
+ DENIED_EXTENSIONS.has(extension) ||
341
+ DENIED_MEDIA_EXTENSIONS.has(extension)
342
+ )
343
+ }
344
+
345
+ function errorResult(code: string): { output: string } {
346
+ return { output: code }
347
+ }
348
+
349
+ function hasParent(session: BoundedReadHostSession): boolean {
350
+ return Object.hasOwn(session, 'parentID')
351
+ }
352
+
353
+ async function readLineWindow(
354
+ filePath: string,
355
+ offset: number,
356
+ limit: number,
357
+ byteCap: number,
358
+ ): Promise<{ content: string; linesRead: number; bytes: number }> {
359
+ const before = await lstat(filePath)
360
+ if (before.isSymbolicLink()) throw new Error('PATH_DENIED')
361
+ if (!before.isFile() || before.nlink > 1) throw new Error('PATH_DENIED')
362
+
363
+ let file: Awaited<ReturnType<typeof open>> | undefined
364
+ try {
365
+ file = await open(filePath, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0))
366
+ const opened = await file.stat()
367
+ if (
368
+ !opened.isFile() ||
369
+ opened.dev !== before.dev ||
370
+ opened.ino !== before.ino ||
371
+ opened.nlink > 1
372
+ ) {
373
+ throw new Error('CHANGED')
374
+ }
375
+
376
+ const chunks: Buffer[] = []
377
+ const inspectedChunks: Buffer[] = []
378
+ const buffer = Buffer.allocUnsafe(READ_CHUNK_BYTES)
379
+ let position = 0
380
+ let currentLine = 1
381
+ let linesRead = 0
382
+ let selectedBytes = 0
383
+ let inspectedBytes = 0
384
+ let currentLineHasBytes = false
385
+ let intervalComplete = false
386
+ while (inspectedBytes < byteCap) {
387
+ const size = Math.min(buffer.length, byteCap - inspectedBytes)
388
+ const read = await file.read(buffer, 0, size, position)
389
+ if (read.bytesRead === 0) break
390
+ position += read.bytesRead
391
+ inspectedBytes += read.bytesRead
392
+ inspectedChunks.push(Buffer.from(buffer.subarray(0, read.bytesRead)))
393
+ let consumed = 0
394
+ let selectedStart = -1
395
+ for (; consumed < read.bytesRead; consumed++) {
396
+ const byte = buffer.readUInt8(consumed)
397
+ if (
398
+ byte === 0 ||
399
+ (byte < 0x20 && byte !== 0x09 && byte !== 0x0a && byte !== 0x0d) ||
400
+ byte === 0x7f
401
+ ) {
402
+ throw new Error('PATH_DENIED')
403
+ }
404
+ const selected = currentLine >= offset && currentLine < offset + limit
405
+ if (selected) {
406
+ if (selectedStart === -1) selectedStart = consumed
407
+ currentLineHasBytes = true
408
+ }
409
+ if (byte === 0x0a) {
410
+ if (selected) linesRead += 1
411
+ currentLine += 1
412
+ currentLineHasBytes = false
413
+ if (currentLine >= offset + limit) {
414
+ intervalComplete = true
415
+ consumed += 1
416
+ break
417
+ }
418
+ } else if (!selected && currentLine >= offset && currentLine < offset + limit) {
419
+ currentLineHasBytes = true
420
+ }
421
+ }
422
+ if (selectedStart !== -1) {
423
+ const selectedEnd = consumed
424
+ const selectedChunk = Buffer.from(buffer.subarray(selectedStart, selectedEnd))
425
+ selectedBytes += selectedChunk.length
426
+ if (selectedBytes > byteCap) throw new Error('BUDGET_EXCEEDED')
427
+ chunks.push(selectedChunk)
428
+ }
429
+ if (intervalComplete) break
430
+ if (read.bytesRead < size) break
431
+ }
432
+
433
+ if (
434
+ !intervalComplete &&
435
+ currentLineHasBytes &&
436
+ currentLine >= offset &&
437
+ currentLine < offset + limit
438
+ ) {
439
+ linesRead += 1
440
+ }
441
+ if (!intervalComplete && inspectedBytes === byteCap && currentLine < offset + limit) {
442
+ throw new Error('BUDGET_EXCEEDED')
443
+ }
444
+ try {
445
+ new TextDecoder('utf-8', { fatal: true }).decode(
446
+ Buffer.concat(inspectedChunks, inspectedBytes),
447
+ )
448
+ } catch {
449
+ throw new Error('PATH_DENIED')
450
+ }
451
+ const bytes = Buffer.concat(chunks, selectedBytes)
452
+ let content: string
453
+ try {
454
+ content = new TextDecoder('utf-8', { fatal: true }).decode(bytes)
455
+ } catch {
456
+ throw new Error('PATH_DENIED')
457
+ }
458
+ return { content, linesRead, bytes: selectedBytes }
459
+ } finally {
460
+ await file?.close().catch(() => undefined)
461
+ }
462
+ }
463
+
464
+ /** Build one registered tool and its in-memory, session-lifecycle state. */
465
+ export function createV2BoundedReadTool(dependencies: BoundedReadDependencies): {
466
+ definition: V2ToolDef
467
+ origins: V2BoundedReadOriginRegistry
468
+ clearSession: (sessionID: string) => void
469
+ } {
470
+ const origins = new V2BoundedReadOriginRegistry()
471
+ const budgets = new Map<string, Budget>()
472
+
473
+ const reserve = (
474
+ sessionID: string,
475
+ messageID: string,
476
+ root: string,
477
+ args: ReadArgs,
478
+ ): string | undefined => {
479
+ const key = budgetKey(sessionID, messageID)
480
+ let budget = budgets.get(key)
481
+ if (budget === undefined) {
482
+ if (budgets.size >= MAX_SESSIONS) return 'UNAVAILABLE'
483
+ budget = {
484
+ sessionID,
485
+ messageID,
486
+ root,
487
+ files: new Set(),
488
+ calls: 0,
489
+ lines: 0,
490
+ bytes: 0,
491
+ sealed: false,
492
+ }
493
+ budgets.set(key, budget)
494
+ }
495
+ if (budget.root !== root || budget.sealed) return 'SCOPE_DENIED'
496
+ if (budget.files.has(args.path)) return 'SCOPE_DENIED'
497
+ if (
498
+ budget.calls + 1 > BOUNDED_READ_MAX_CALLS ||
499
+ budget.files.size + 1 > BOUNDED_READ_MAX_FILES ||
500
+ budget.lines + args.limit > BOUNDED_READ_MAX_LINES ||
501
+ budget.bytes + BYTES_PER_CALL > BOUNDED_READ_MAX_BYTES
502
+ ) {
503
+ budget.sealed = true
504
+ return 'BUDGET_EXCEEDED'
505
+ }
506
+ budget.calls += 1
507
+ budget.files.add(args.path)
508
+ budget.lines += args.limit
509
+ budget.bytes += BYTES_PER_CALL
510
+ return undefined
511
+ }
512
+
513
+ const definition: V2ToolDef = {
514
+ name: BOUNDED_READ_TOOL,
515
+ description:
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.',
517
+ input: {
518
+ type: 'object',
519
+ additionalProperties: false,
520
+ required: ['path', 'offset', 'limit'],
521
+ properties: {
522
+ path: {
523
+ type: 'string',
524
+ minLength: 1,
525
+ description:
526
+ 'Exact relative file path inside the current project; no globs or traversal.',
527
+ },
528
+ offset: {
529
+ type: 'integer',
530
+ minimum: 1,
531
+ description: 'First line to return, starting at 1.',
532
+ },
533
+ limit: {
534
+ type: 'integer',
535
+ minimum: 1,
536
+ maximum: BOUNDED_READ_MAX_LINES,
537
+ description: 'Number of lines requested; at most 400 lines total across this turn.',
538
+ },
539
+ },
540
+ },
541
+ output: {},
542
+ async execute(rawInput: Record<string, unknown>, rawContext: unknown) {
543
+ const args = parseArgs(rawInput)
544
+ if (args === undefined) return errorResult('ARGUMENT_INVALID')
545
+ if (!isRecord(rawContext)) return errorResult('BOUND_READ_UNAUTHORIZED')
546
+ const sessionID = nonEmpty(rawContext.sessionID)
547
+ const messageID = nonEmpty(rawContext.messageID)
548
+ const callID = nonEmpty(rawContext.id)
549
+ const agent = nonEmpty(rawContext.agent)
550
+ if (!sessionID || !messageID || !callID || agent !== 'zeus') {
551
+ return errorResult('BOUND_READ_UNAUTHORIZED')
552
+ }
553
+ const origin = origins.consume({
554
+ sessionID,
555
+ messageID,
556
+ callID,
557
+ agent,
558
+ relativePath: args.path,
559
+ })
560
+ if (origin === undefined) return errorResult('BOUND_READ_UNAUTHORIZED')
561
+
562
+ let sessionValue: unknown
563
+ try {
564
+ sessionValue = await dependencies.getSession(sessionID)
565
+ } catch {
566
+ return errorResult('BOUND_READ_UNAUTHORIZED')
567
+ }
568
+ if (!isRecord(sessionValue)) return errorResult('BOUND_READ_UNAUTHORIZED')
569
+ const session = sessionValue as BoundedReadHostSession
570
+ if (
571
+ session.id !== sessionID ||
572
+ hasParent(session) ||
573
+ session.projectID !== dependencies.projectID
574
+ ) {
575
+ return errorResult('BOUND_READ_UNAUTHORIZED')
576
+ }
577
+
578
+ // The caller supplies the realpath captured before registration. This is
579
+ // pure lexical work, so quota reservation still precedes filesystem I/O.
580
+ const root = path.resolve(dependencies.rootDirectory)
581
+ const target = path.resolve(root, ...args.path.split('/'))
582
+ if (!isWithin(root, target) || sensitivePath(args.path)) return errorResult('PATH_DENIED')
583
+ const reservationError = reserve(sessionID, messageID, root, args)
584
+ if (reservationError !== undefined) return errorResult(reservationError)
585
+
586
+ try {
587
+ await dependencies.assertPermission({
588
+ sessionID,
589
+ agent,
590
+ action: 'read',
591
+ resources: [target],
592
+ save: [],
593
+ source: { type: 'tool', messageID, id: callID },
594
+ })
595
+ } catch {
596
+ return errorResult('TOOL_DENIED')
597
+ }
598
+
599
+ const rootInfo = await lstat(root).catch(() => undefined)
600
+ if (!rootInfo?.isDirectory() || rootInfo.isSymbolicLink()) return errorResult('PATH_DENIED')
601
+ const components = args.path.split('/')
602
+ let cursor = root
603
+ for (const [index, component] of components.entries()) {
604
+ cursor = path.join(cursor, component)
605
+ const info = await lstat(cursor).catch(() => undefined)
606
+ if (info === undefined || info.isSymbolicLink()) return errorResult('PATH_DENIED')
607
+ if (index < components.length - 1 && !info.isDirectory()) return errorResult('PATH_DENIED')
608
+ if (index === components.length - 1 && !info.isFile()) return errorResult('PATH_DENIED')
609
+ }
610
+ const targetReal = await realpath(target).catch(() => undefined)
611
+ if (targetReal === undefined || !isWithin(root, targetReal)) return errorResult('PATH_DENIED')
612
+
613
+ try {
614
+ const result = await readLineWindow(targetReal, args.offset, args.limit, BYTES_PER_CALL)
615
+ const scanDecision = await dependencies.scanContent({
616
+ content: result.content,
617
+ agent,
618
+ sessionID,
619
+ messageID,
620
+ callID,
621
+ })
622
+ if (scanDecision !== 'allow') {
623
+ return errorResult(scanDecision === 'deny' ? 'SCOPE_DENIED' : 'UNAVAILABLE')
624
+ }
625
+ return {
626
+ output: JSON.stringify({
627
+ path: args.path,
628
+ offset: args.offset,
629
+ linesRead: result.linesRead,
630
+ bytes: result.bytes,
631
+ status: result.linesRead === 0 ? 'empty' : 'ok',
632
+ content: result.content,
633
+ }),
634
+ }
635
+ } catch (error) {
636
+ const code = error instanceof Error ? error.message : ''
637
+ return errorResult(
638
+ ['CHANGED', 'BUDGET_EXCEEDED', 'PATH_DENIED'].includes(code) ? code : 'UNAVAILABLE',
639
+ )
640
+ }
641
+ },
642
+ }
643
+
644
+ return {
645
+ definition,
646
+ origins,
647
+ clearSession(sessionID) {
648
+ for (const [key, budget] of budgets) {
649
+ if (budget.sessionID === sessionID) budgets.delete(key)
650
+ }
651
+ origins.clearSession(sessionID)
652
+ },
653
+ }
654
+ }
@@ -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
+ }