pantheon-opencode 2.0.3 → 2.0.4

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.
@@ -51,32 +51,11 @@ mcp_tools:
51
51
  - **Code-mode / infrastructure reads** — cheap and on demand; never for
52
52
  decisions the ladder already answers.
53
53
 
54
- ## Verification Tiers
54
+ ## Fast-Path Execution Contract
55
55
 
56
- Small bounded fix → change + one targeted proof, no ceremony. Material change → full test discipline. Match the tier to the change.
57
-
58
-
59
- ## Core Capabilities
60
-
61
- ### 1. Rapid Repairs
62
- - Single-file fixes (< 10 lines)
63
- - Multi-file fixes (max 2 files)
64
- - CSS, typo, import, and minor logic fixes
65
-
66
- ### 2. No TDD Ceremony
67
- - Hotfixes skip the RED->GREEN->REFACTOR cycle
68
- - Fix and run the narrowest relevant existing test/check; do not run a full suite for a micro-edit
69
- - Document the root cause inline
70
-
71
- ### 3. Escalation Rules
72
- Escalate to @zeus if:
73
- - Fix requires > 2 files or > 10 lines changed
74
- - Has security implications
75
- - Requires database migration
76
- - Touches authentication, security-sensitive behavior, production data, global configuration, or broad permissions
77
- - Breaks existing tests unexpectedly
78
-
79
- Full-auto does not permit Talos to perform push/merge/deploy, destructive/global changes, or sensitive work; escalate for required specialist review and explicit human approval.
56
+ - **Micro-scope only**: single-file (< 10 lines) or max 2 files (CSS, typos, imports, isolated logic fixes).
57
+ - **Zero ceremony**: skip RED->GREEN->REFACTOR; run only the narrowest relevant test slice via `test-slicing`.
58
+ - **Standalone execution**: no subagents, no orchestration overhead. Return `## subtask_summary` directly.
80
59
 
81
60
  ## Requested Artifact Completion
82
61
 
@@ -84,19 +63,10 @@ Full-auto does not permit Talos to perform push/merge/deploy, destructive/global
84
63
  - Searching the MCP Code Mode catalog only discovers MCP tools. A missing MCP match does not mean native file tools are unavailable.
85
64
  - Verify the write succeeded and, when practical, read the artifact back. If a native file tool is actually unavailable or denies the write, state that specific limitation and do not claim completion.
86
65
 
87
- ## Constraints
88
- - No orchestration: you work standalone
89
- - No Themis review needed (low-risk)
90
- - Return subtask_summary format
91
- - If complexity exceeds threshold, escalate immediately
92
-
93
- ## Auto-Continue (Embedded: Hotfix)
94
-
95
- - Auto-continue through quick fix cycles (identify → fix → verify)
96
- - No checkpoint needed (single-file fixes, low complexity)
97
- - Escalate to Zeus if fix takes > 3 turns or requires > 2 files / > 10 lines
98
- - If fix breaks existing tests, stop immediately and escalate
99
- - No partial results — either fix is applied or escalate
66
+ ## Escalation Boundaries
100
67
 
101
- ## Skills
102
- `code-review-checklist`, `git-workflow-and-versioning`
68
+ Escalate to @zeus immediately if:
69
+ - Change requires > 2 files or > 10 lines
70
+ - Touches security, authentication, credentials, migrations, or broad permissions
71
+ - Fix takes > 3 turns or causes unexpected test regression
72
+ - Full-auto never permits push/merge/deploy or destructive operations without specialist review and human approval.
@@ -183,6 +183,14 @@ Estimated time: ~60% of review effort
183
183
  - [ ] IntentGate passed (code solves the right problem)
184
184
  - [ ] Auth/security, data/schema, and sensitive actions preserve applicable tests, specialist review, and human approval
185
185
 
186
+ ## Local Reflex Loop (Self-Healing)
187
+
188
+ When Layer 1 (lint/formatting/style) or Layer 2 (narrow test slice) fails:
189
+ - Themis executes a direct local reflex loop with the implementer (up to 2 retry attempts).
190
+ - Emits `themis:reflex:discrepancy` with the exact failing slice/rules.
191
+ - Does NOT escalate to Zeus unless the 2-retry reflex budget is exhausted or an architectural/IntentGate mismatch occurs.
192
+ - On successful remediation, emits `themis:reflex:resolved` and issues PASS / PASS_WITH_NOTES.
193
+
186
194
  ## Verdict
187
195
 
188
196
  After review, return one of these:
@@ -13,6 +13,7 @@
13
13
  import { mkdir, rename, unlink, writeFile } from 'node:fs/promises'
14
14
  import { dirname, join } from 'node:path'
15
15
 
16
+ import { getSharedBus } from './bus.ts'
16
17
  import { createPantheonLogger } from './logger.ts'
17
18
 
18
19
  // Silence-by-default TUI policy (pantheon-hooks L42-58): console output in a
@@ -292,6 +293,14 @@ export class BackgroundJobBoard {
292
293
 
293
294
  this.jobs.set(input.taskID, record)
294
295
  await this.persistRecord(record)
296
+ getSharedBus().emit('job:created', {
297
+ taskID: record.taskID,
298
+ alias: record.alias,
299
+ agent: record.agent,
300
+ parentSessionID: record.parentSessionID,
301
+ state: record.state,
302
+ timestamp: now,
303
+ })
295
304
  return record
296
305
  }
297
306
 
@@ -364,6 +373,14 @@ export class BackgroundJobBoard {
364
373
 
365
374
  // --- write-ahead log: persist before notify ---
366
375
  await this.persistRecord(job)
376
+ getSharedBus().emit('job:updated', {
377
+ taskID: job.taskID,
378
+ alias: job.alias,
379
+ agent: job.agent,
380
+ state: job.state,
381
+ resultSummary: job.resultSummary,
382
+ timestamp: job.updatedAt,
383
+ })
367
384
 
368
385
  // --- signal on terminal states ---
369
386
  if (willBeTerminal) {
@@ -463,6 +480,11 @@ export class BackgroundJobBoard {
463
480
  // cycle deleted them. Instead, remove any still-pending wake signal so
464
481
  // reconcile leaves no `<alias>.signal.json` behind.
465
482
  await this.deleteSignal(job.alias)
483
+ getSharedBus().emit('job:reconciled', {
484
+ taskID: job.taskID,
485
+ alias: job.alias,
486
+ timestamp: job.updatedAt,
487
+ })
466
488
 
467
489
  return job
468
490
  }
@@ -728,6 +750,17 @@ export class BackgroundJobBoard {
728
750
  }
729
751
 
730
752
  private notifyTerminal(taskID: string): void {
753
+ const job = this.jobs.get(taskID)
754
+ if (job) {
755
+ getSharedBus().emit('job:terminal', {
756
+ taskID: job.taskID,
757
+ alias: job.alias,
758
+ agent: job.agent,
759
+ state: job.state,
760
+ resultSummary: job.resultSummary,
761
+ timestamp: job.completedAt ?? Date.now(),
762
+ })
763
+ }
731
764
  for (const listener of this.terminalListeners) {
732
765
  try {
733
766
  listener(taskID)
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Pantheon Event Bus (pantheon-bus) — In-memory reactive event system.
3
+ *
4
+ * Eliminates disk I/O and polling loops for inter-agent communication,
5
+ * background job tracking, and reactive verification.
6
+ *
7
+ * Process-global singleton anchored in globalThis.__pantheonSharedBus,
8
+ * matching the dual-plugin deduplication architecture in shared-board.ts.
9
+ *
10
+ * Pure TypeScript — zero external dependencies.
11
+ *
12
+ * @module bus
13
+ */
14
+
15
+ export interface JobEventPayload {
16
+ readonly taskID: string
17
+ readonly alias: string
18
+ readonly agent: string
19
+ readonly timestamp: number
20
+ readonly parentSessionID?: string | undefined
21
+ readonly state?: string | undefined
22
+ readonly resultSummary?: string | null | undefined
23
+ }
24
+
25
+ export interface ThemisReflexEventPayload {
26
+ readonly taskID: string
27
+ readonly agent: string
28
+ readonly file: string
29
+ readonly error: string
30
+ readonly attempt: number
31
+ readonly maxAttempts: number
32
+ readonly timestamp: number
33
+ readonly resolved?: boolean | undefined
34
+ }
35
+
36
+ export interface ExecutionReceiptPayload {
37
+ readonly receiptId: string
38
+ readonly taskID: string
39
+ readonly agent: string
40
+ readonly status: 'VERIFIED' | 'UNVERIFIED' | 'FAILED'
41
+ readonly files: ReadonlyArray<{
42
+ readonly path: string
43
+ readonly hash: string
44
+ readonly sizeBytes: number
45
+ }>
46
+ readonly testSlice?:
47
+ | { readonly command: string; readonly exitCode: number; readonly durationMs: number }
48
+ | undefined
49
+ readonly timestamp: number
50
+ readonly signature: string
51
+ }
52
+
53
+ export interface PantheonEventMap {
54
+ 'job:created': JobEventPayload
55
+ 'job:updated': JobEventPayload
56
+ 'job:terminal': JobEventPayload
57
+ 'job:reconciled': { readonly taskID: string; readonly alias: string; readonly timestamp: number }
58
+ 'themis:reflex:discrepancy': ThemisReflexEventPayload
59
+ 'themis:reflex:resolved': ThemisReflexEventPayload
60
+ 'agent:execution:receipt': ExecutionReceiptPayload
61
+ }
62
+
63
+ export type PantheonEventName = keyof PantheonEventMap
64
+
65
+ // biome-ignore lint/suspicious/noExplicitAny: internal heterogeneous event listener storage
66
+ type AnyListener = (payload: any) => void | Promise<void>
67
+
68
+ export class PantheonBus {
69
+ private readonly listeners: Map<string, Set<AnyListener>> = new Map()
70
+
71
+ /**
72
+ * Register a persistent listener for an event.
73
+ * Returns an unsubscribe callback for easy cleanup.
74
+ */
75
+ on<E extends PantheonEventName>(
76
+ event: E,
77
+ listener: (payload: PantheonEventMap[E]) => void | Promise<void>,
78
+ ): () => void {
79
+ let set = this.listeners.get(event)
80
+ if (!set) {
81
+ set = new Set()
82
+ this.listeners.set(event, set)
83
+ }
84
+ set.add(listener)
85
+ return () => {
86
+ set?.delete(listener)
87
+ if (set?.size === 0) {
88
+ this.listeners.delete(event)
89
+ }
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Register a one-shot listener that unregisters itself after firing once.
95
+ */
96
+ once<E extends PantheonEventName>(
97
+ event: E,
98
+ listener: (payload: PantheonEventMap[E]) => void | Promise<void>,
99
+ ): () => void {
100
+ const unsubscribe = this.on(event, (payload) => {
101
+ unsubscribe()
102
+ return listener(payload)
103
+ })
104
+ return unsubscribe
105
+ }
106
+
107
+ /**
108
+ * Synchronously emit an event to all registered listeners.
109
+ * Listener rejections are logged safely without throwing.
110
+ */
111
+ emit<E extends PantheonEventName>(event: E, payload: PantheonEventMap[E]): void {
112
+ const set = this.listeners.get(event)
113
+ if (!set || set.size === 0) return
114
+ for (const listener of Array.from(set)) {
115
+ try {
116
+ const result = listener(payload)
117
+ if (result instanceof Promise) {
118
+ result.catch(() => {})
119
+ }
120
+ } catch {
121
+ // Safe swallow: an in-memory listener crash must not fail the emitter
122
+ }
123
+ }
124
+ }
125
+
126
+ /**
127
+ * Wait asynchronously for a specific event matching a predicate, with an optional timeout.
128
+ */
129
+ waitFor<E extends PantheonEventName>(
130
+ event: E,
131
+ predicate: (payload: PantheonEventMap[E]) => boolean,
132
+ timeoutMs = 30_000,
133
+ ): Promise<PantheonEventMap[E]> {
134
+ return new Promise((resolve, reject) => {
135
+ let timer: NodeJS.Timeout | null = null
136
+ let unsubscribe: (() => void) | null = null
137
+
138
+ if (timeoutMs > 0 && Number.isFinite(timeoutMs)) {
139
+ timer = setTimeout(() => {
140
+ unsubscribe?.()
141
+ reject(new Error(`Timed out waiting for bus event "${event}" after ${timeoutMs}ms`))
142
+ }, timeoutMs)
143
+ }
144
+
145
+ unsubscribe = this.on(event, (payload) => {
146
+ try {
147
+ if (predicate(payload)) {
148
+ if (timer) clearTimeout(timer)
149
+ unsubscribe?.()
150
+ resolve(payload)
151
+ }
152
+ } catch (err) {
153
+ if (timer) clearTimeout(timer)
154
+ unsubscribe?.()
155
+ reject(err)
156
+ }
157
+ })
158
+ })
159
+ }
160
+
161
+ /** Number of active listeners for a specific event or in total. */
162
+ listenerCount(event?: PantheonEventName): number {
163
+ if (event) {
164
+ return this.listeners.get(event)?.size ?? 0
165
+ }
166
+ let total = 0
167
+ for (const set of this.listeners.values()) {
168
+ total += set.size
169
+ }
170
+ return total
171
+ }
172
+
173
+ /** Clear all listeners (primarily for unit tests). */
174
+ clear(): void {
175
+ this.listeners.clear()
176
+ }
177
+ }
178
+
179
+ const BUS_KEY = '__pantheonSharedBus'
180
+
181
+ /**
182
+ * Access the process-global PantheonBus singleton.
183
+ */
184
+ export function getSharedBus(): PantheonBus {
185
+ const host = globalThis as { [BUS_KEY]?: PantheonBus }
186
+ if (host[BUS_KEY] instanceof PantheonBus) return host[BUS_KEY]
187
+ const bus = new PantheonBus()
188
+ host[BUS_KEY] = bus
189
+ return bus
190
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Execution Proof Receipts — Verifiable task completion contracts for agent execution.
3
+ *
4
+ * Implements SOTA late-2026 verification principles: subagents return cryptographic
5
+ * receipts containing deterministic content hashes of modified files and verifiable
6
+ * test-slicing proofs, eliminating false-positive completion reports.
7
+ *
8
+ * Emits reactive verification events on `PantheonBus`.
9
+ *
10
+ * Pure TypeScript — stdlib crypto only.
11
+ *
12
+ * @module execution-receipt
13
+ */
14
+
15
+ import { createHash } from 'node:crypto'
16
+ import { type ExecutionReceiptPayload, getSharedBus } from './bus.ts'
17
+
18
+ export interface FileInput {
19
+ readonly path: string
20
+ readonly content: string | Buffer
21
+ }
22
+
23
+ export interface TestSliceInput {
24
+ readonly command: string
25
+ readonly exitCode: number
26
+ readonly durationMs: number
27
+ }
28
+
29
+ export interface CreateReceiptInput {
30
+ readonly taskID: string
31
+ readonly agent: string
32
+ readonly files: readonly FileInput[]
33
+ readonly testSlice?: TestSliceInput | undefined
34
+ }
35
+
36
+ /**
37
+ * Compute SHA-256 fingerprint for a string or buffer.
38
+ */
39
+ export function hashContent(content: string | Buffer): string {
40
+ return createHash('sha256').update(content).digest('hex')
41
+ }
42
+
43
+ /**
44
+ * Compute cryptographic signature binding task, agent, timestamp and file hashes.
45
+ */
46
+ export function computeReceiptSignature(
47
+ taskID: string,
48
+ agent: string,
49
+ timestamp: number,
50
+ files: ReadonlyArray<{ readonly path: string; readonly hash: string }>,
51
+ ): string {
52
+ const sortedFiles = [...files].sort((a, b) => a.path.localeCompare(b.path))
53
+ const payload = [
54
+ taskID,
55
+ agent,
56
+ String(timestamp),
57
+ sortedFiles.map((f) => `${f.path}:${f.hash}`).join(';'),
58
+ ].join('|')
59
+ return createHash('sha256').update(payload).digest('hex')
60
+ }
61
+
62
+ /**
63
+ * Generate a verifiable Execution Proof Receipt and emit it on the shared bus.
64
+ */
65
+ export function createExecutionReceipt(input: CreateReceiptInput): ExecutionReceiptPayload {
66
+ const timestamp = Date.now()
67
+ const files = input.files.map((f) => {
68
+ const buf = typeof f.content === 'string' ? Buffer.from(f.content, 'utf8') : f.content
69
+ return {
70
+ path: f.path,
71
+ hash: hashContent(buf),
72
+ sizeBytes: buf.length,
73
+ }
74
+ })
75
+
76
+ const signature = computeReceiptSignature(input.taskID, input.agent, timestamp, files)
77
+ const receiptId = `rcpt_${signature.slice(0, 16)}`
78
+
79
+ let status: 'VERIFIED' | 'UNVERIFIED' | 'FAILED' = 'UNVERIFIED'
80
+ if (input.testSlice) {
81
+ status = input.testSlice.exitCode === 0 ? 'VERIFIED' : 'FAILED'
82
+ }
83
+
84
+ const receipt: ExecutionReceiptPayload = {
85
+ receiptId,
86
+ taskID: input.taskID,
87
+ agent: input.agent,
88
+ status,
89
+ files,
90
+ testSlice: input.testSlice,
91
+ timestamp,
92
+ signature,
93
+ }
94
+
95
+ getSharedBus().emit('agent:execution:receipt', receipt)
96
+ return receipt
97
+ }
98
+
99
+ /**
100
+ * Verify whether an execution receipt signature matches its declared files and metadata.
101
+ */
102
+ export function verifyExecutionReceipt(receipt: ExecutionReceiptPayload): boolean {
103
+ if (!receipt?.signature || !receipt.taskID || !receipt.agent) {
104
+ return false
105
+ }
106
+ const expected = computeReceiptSignature(
107
+ receipt.taskID,
108
+ receipt.agent,
109
+ receipt.timestamp,
110
+ receipt.files,
111
+ )
112
+ return receipt.signature === expected
113
+ }
@@ -288,8 +288,14 @@ export async function runGatedNativeJevCall(params: {
288
288
  let config: ReturnType<typeof readUserDecisionRouterConfig>
289
289
  try {
290
290
  config = readUserDecisionRouterConfig()
291
- } catch {
292
- return { ok: false, reasonCode: 'CONFIG_UNAVAILABLE' }
291
+ } catch (error) {
292
+ const detail =
293
+ error instanceof Error && error.message.includes('group-writable')
294
+ ? 'CONFIG_PATH_GROUP_WRITABLE'
295
+ : error instanceof Error
296
+ ? error.name
297
+ : 'ConfigError'
298
+ return { ok: false, reasonCode: 'CONFIG_UNAVAILABLE', detail }
293
299
  }
294
300
  if (!config.enabled) return { ok: false, reasonCode: 'DISABLED' }
295
301
  if (!config.egress_consent) return { ok: false, reasonCode: 'CONSENT_MISSING' }
@@ -1,5 +1,13 @@
1
1
  import { randomUUID } from 'node:crypto'
2
- import { chmodSync, closeSync, lstatSync, mkdirSync, openSync, type Stats } from 'node:fs'
2
+ import {
3
+ chmodSync,
4
+ closeSync,
5
+ existsSync,
6
+ lstatSync,
7
+ mkdirSync,
8
+ openSync,
9
+ type Stats,
10
+ } from 'node:fs'
3
11
  import { homedir } from 'node:os'
4
12
  import { basename, dirname, isAbsolute, join, parse, resolve, sep } from 'node:path'
5
13
  import { performance } from 'node:perf_hooks'
@@ -1202,20 +1210,42 @@ function ensureTrustedDirectoryChain(directoryPath: string): void {
1202
1210
  }
1203
1211
  }
1204
1212
 
1213
+ function isPermittedGroupWritable(env: NodeJS.ProcessEnv = process.env): boolean {
1214
+ if (env.PANTHEON_ALLOW_GROUP_WRITABLE === '1' || env.PANTHEON_ALLOW_GROUP_WRITABLE === 'true') {
1215
+ return true
1216
+ }
1217
+ if (
1218
+ env.JUPYTERHUB_USER ||
1219
+ env.JUPYTER_IMAGE ||
1220
+ env.JUPYTER_SERVER_ROOT ||
1221
+ env.KUBERNETES_SERVICE_HOST ||
1222
+ env.container ||
1223
+ existsSync('/.dockerenv')
1224
+ ) {
1225
+ return true
1226
+ }
1227
+ return false
1228
+ }
1229
+
1205
1230
  function validateDirectoryTrust(stat: Stats, uid: number, isFinalDirectory: boolean): void {
1206
1231
  if (!stat.isDirectory() || stat.isSymbolicLink()) {
1207
1232
  throw new Error('Budget ledger path contains a non-directory or symlink ancestor')
1208
1233
  }
1209
- if (stat.uid !== uid && stat.uid !== 0) {
1234
+ const mode = stat.mode & 0o7777
1235
+ const isSticky = (mode & 0o1000) !== 0
1236
+ const isSystemOrUser = stat.uid === uid || stat.uid === 0 || (isSticky && stat.uid === 65534)
1237
+ if (!isSystemOrUser) {
1210
1238
  throw new Error('Budget ledger path contains an untrusted owner')
1211
1239
  }
1212
1240
  if (isFinalDirectory && stat.uid !== uid) {
1213
1241
  throw new Error('Budget ledger directory must be owned by the current user')
1214
1242
  }
1215
- const mode = stat.mode & 0o7777
1216
- const writableByOthers = (mode & 0o022) !== 0
1217
- const rootStickyDirectory = stat.uid === 0 && (mode & 0o1000) !== 0
1218
- if (writableByOthers && !rootStickyDirectory) {
1243
+ const worldWritable = (mode & 0o002) !== 0
1244
+ const groupWritable = (mode & 0o020) !== 0
1245
+ if (worldWritable && !isSticky) {
1246
+ throw new Error('Budget ledger path contains a group/other-writable directory')
1247
+ }
1248
+ if (groupWritable && !isSticky && !isFinalDirectory && !isPermittedGroupWritable()) {
1219
1249
  throw new Error('Budget ledger path contains a group/other-writable directory')
1220
1250
  }
1221
1251
  }
@@ -606,7 +606,7 @@ async function updateActivePreset(
606
606
  if (!options.v2Mode) {
607
607
  const env = envValue(options)
608
608
  fallbackPreset = defaultFallbackPreset()
609
- // Prefer env preset if set and known (V1 legacy behavior only).
609
+ // Prefer env preset if set and known.
610
610
  const envPreset = env.PANTHEON_MODEL_PRESET?.trim()
611
611
  if (envPreset && envPreset !== '' && envPreset !== 'none') {
612
612
  try {
@@ -1031,9 +1031,7 @@ export function createModelCommand(options: ModelCommandOptions = {}): ModelTool
1031
1031
  const args = options.v2Mode
1032
1032
  ? {
1033
1033
  ...modelArgs,
1034
- action: modelArgs.action.describe(
1035
- 'Operation: status/show, set, or reset. V1 no-args invocation runs the legacy wizard.',
1036
- ),
1034
+ action: modelArgs.action.describe('Operation: status/show, set, or reset.'),
1037
1035
  }
1038
1036
  : modelArgs
1039
1037
 
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Prompt Prefix Cache Hierarchy Optimizer — Late-2026 KV-Cache Alignment.
3
+ *
4
+ * Enforces deterministic hierarchical ordering for agent prompts to maximize
5
+ * prefix cache hit rates across LLM providers (Anthropic Claude 3.5/3.7,
6
+ * Gemini 2.0/Flash, OpenAI GPT-5/o3/Luna):
7
+ *
8
+ * [Tier 1: Static Identity & Invariants] ->
9
+ * [Tier 2: Tool Schemas & Governance] ->
10
+ * [Tier 3: Repository Standards & Gates] ->
11
+ * [Tier 4: Ephemeral Session History] ->
12
+ * [Tier 5: Current Turn & Scratchpad]
13
+ *
14
+ * Pure TypeScript — zero external dependencies.
15
+ *
16
+ * @module prompt-cache-order
17
+ */
18
+
19
+ export interface PromptLayers {
20
+ readonly identity: string
21
+ readonly tools?: readonly string[] | undefined
22
+ readonly conventions?: readonly string[] | undefined
23
+ readonly history?: readonly string[] | undefined
24
+ readonly currentTurn: string
25
+ }
26
+
27
+ export interface CachedPromptResult {
28
+ readonly prompt: string
29
+ /** The byte/character offset separating invariant prefix from volatile turns */
30
+ readonly prefixBoundaryIndex: number
31
+ /** Estimated token length (heuristic ~4 chars/token) */
32
+ readonly estimatedTokens: number
33
+ /** Whether the prefix meets typical provider minimum threshold (e.g. 1024 tokens) */
34
+ readonly cacheEligible: boolean
35
+ }
36
+
37
+ /** Standard token threshold for provider-level prompt caching (Anthropic=1024, OpenAI=1024) */
38
+ export const DEFAULT_CACHE_MIN_TOKENS = 1024
39
+
40
+ /**
41
+ * Assemble agent prompt with strict invariant-prefix ordering to maximize KV cache hit rate.
42
+ */
43
+ export function buildPrefixCachedPrompt(
44
+ layers: PromptLayers,
45
+ minCacheTokens = DEFAULT_CACHE_MIN_TOKENS,
46
+ ): CachedPromptResult {
47
+ const invariantParts: string[] = []
48
+
49
+ // 1. Identity & Core System Instructions
50
+ invariantParts.push(layers.identity.trim())
51
+
52
+ // 2. Tools & Permissions Schemas
53
+ if (layers.tools && layers.tools.length > 0) {
54
+ invariantParts.push(`## Tool Specifications\n${layers.tools.map((t) => t.trim()).join('\n\n')}`)
55
+ }
56
+
57
+ // 3. Project Conventions & Architecture Gates
58
+ if (layers.conventions && layers.conventions.length > 0) {
59
+ invariantParts.push(
60
+ `## Project Standards & Gates\n${layers.conventions.map((c) => c.trim()).join('\n\n')}`,
61
+ )
62
+ }
63
+
64
+ const prefix = invariantParts.join('\n\n')
65
+ const prefixBoundaryIndex = prefix.length
66
+
67
+ const volatileParts: string[] = []
68
+
69
+ // 4. Conversation History (if any)
70
+ if (layers.history && layers.history.length > 0) {
71
+ volatileParts.push(
72
+ `## Conversation History\n${layers.history.map((h) => h.trim()).join('\n\n')}`,
73
+ )
74
+ }
75
+
76
+ // 5. Current Turn Payload
77
+ volatileParts.push(layers.currentTurn.trim())
78
+
79
+ const fullPrompt = [prefix, volatileParts.join('\n\n')].join('\n\n')
80
+ const estimatedTokens = Math.ceil(fullPrompt.length / 4)
81
+ const estimatedPrefixTokens = Math.ceil(prefix.length / 4)
82
+
83
+ return {
84
+ prompt: fullPrompt,
85
+ prefixBoundaryIndex,
86
+ estimatedTokens,
87
+ cacheEligible: estimatedPrefixTokens >= minCacheTokens,
88
+ }
89
+ }