pantheon-opencode 1.6.2-beta.1 → 1.6.2-beta.10

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 (144) hide show
  1. package/CHANGELOG.md +163 -0
  2. package/README.md +236 -60
  3. package/README.pt-BR.md +19 -1
  4. package/bin/pantheon-init.mjs +195 -13
  5. package/package.json +11 -3
  6. package/plugin.json +1 -1
  7. package/prompts/README.md +58 -0
  8. package/prompts/debug-issue.prompt.md +46 -0
  9. package/prompts/dynamic/agora-generated.txt +38 -0
  10. package/prompts/dynamic/orchestrate-generated.txt +51 -0
  11. package/prompts/focus.prompt.md +42 -0
  12. package/prompts/implement-feature.prompt.md +39 -0
  13. package/prompts/optimize-database.prompt.md +58 -0
  14. package/prompts/orchestrate-with-zeus.prompt.md +441 -0
  15. package/prompts/plan-architecture.prompt.md +59 -0
  16. package/prompts/quick-discovery-large-codebase.prompt.md +294 -0
  17. package/prompts/quick-plan-large-feature.prompt.md +197 -0
  18. package/prompts/semantic-summarize.md +50 -0
  19. package/prompts/sketch.prompt.md +91 -0
  20. package/prompts/subtask.prompt.md +131 -0
  21. package/pyproject.toml +1 -1
  22. package/scripts/decision-router-budget.mjs +780 -0
  23. package/scripts/decision-router-v2-budget.mjs +218 -0
  24. package/scripts/decision-router-v2-egress.mjs +272 -0
  25. package/scripts/decision-router.mjs +758 -0
  26. package/scripts/docs-check-changelog.mjs +5 -3
  27. package/scripts/install/component-selection.mjs +9 -4
  28. package/scripts/install/decision-layer-preview.mjs +376 -0
  29. package/scripts/install/decision-router-config.mjs +560 -0
  30. package/scripts/install/health-check.mjs +20 -11
  31. package/scripts/install/interactive.mjs +103 -14
  32. package/scripts/install/interrupt.mjs +4 -3
  33. package/scripts/install/migrate.mjs +123 -72
  34. package/scripts/install/opencode.mjs +178 -122
  35. package/scripts/install/plan.mjs +8 -1
  36. package/scripts/install/plugin.mjs +4 -3
  37. package/scripts/install/state.mjs +12 -0
  38. package/scripts/install/strings.mjs +22 -0
  39. package/scripts/install/venv.mjs +34 -17
  40. package/scripts/mcp_resources.py +11 -9
  41. package/scripts/release-notes.mjs +30 -7
  42. package/scripts/restore.mjs +22 -10
  43. package/scripts/sync-tui.mjs +3 -3
  44. package/scripts/test-opencode-v2-sandbox.sh +10 -6
  45. package/scripts/versioning.mjs +41 -5
  46. package/src/agents/aphrodite.md +6 -1
  47. package/src/agents/apollo.md +1 -0
  48. package/src/agents/athena.md +1 -0
  49. package/src/agents/demeter.md +1 -1
  50. package/src/agents/gaia.md +1 -0
  51. package/src/agents/hephaestus.md +1 -1
  52. package/src/agents/hermes.md +8 -10
  53. package/src/agents/iris.md +1 -1
  54. package/src/agents/mnemosyne.md +1 -0
  55. package/src/agents/nyx.md +1 -1
  56. package/src/agents/prometheus.md +1 -1
  57. package/src/agents/talos.md +6 -1
  58. package/src/agents/themis.md +1 -1
  59. package/src/agents/zeus.md +52 -62
  60. package/src/mcp/eval_store.py +11 -4
  61. package/src/mcp/mcp_resources.py +11 -9
  62. package/src/mcp/memory_mcp.py +293 -150
  63. package/src/pantheon/cost-command.ts +30 -133
  64. package/src/pantheon/jev-decision-tool.ts +347 -0
  65. package/src/pantheon/jev-decisions.ts +625 -0
  66. package/src/pantheon/local-decision-agents.ts +170 -0
  67. package/src/pantheon/local-decision-budget.ts +1046 -0
  68. package/src/pantheon/local-decision-egress-gate.ts +144 -0
  69. package/src/pantheon/local-decision-prompt.ts +256 -0
  70. package/src/pantheon/local-decision-provider-matrix.ts +44 -0
  71. package/src/pantheon/local-decision-router.ts +225 -0
  72. package/src/pantheon/local-decision-skills.ts +281 -0
  73. package/src/pantheon/local-decision-tool.ts +160 -0
  74. package/src/pantheon/local-decision-turn.ts +101 -0
  75. package/src/pantheon/local-decision-usage-evidence.internal.ts +168 -0
  76. package/src/pantheon/local-orchestration.ts +322 -0
  77. package/src/pantheon/model-pricing.ts +1 -536
  78. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  79. package/src/pantheon/v2-decision-budget.ts +456 -0
  80. package/src/pantheon/v2-decision-contracts.ts +300 -0
  81. package/src/pantheon/v2-decision-egress.ts +203 -0
  82. package/src/pantheon/v2-decision-events.ts +180 -0
  83. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  84. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  85. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  86. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  87. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  88. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  89. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  90. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  91. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  92. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  93. package/src/pantheon/v2-decision-points/p8-guardrail.ts +367 -0
  94. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  95. package/src/pantheon/v2-decision-points.ts +242 -0
  96. package/src/pantheon/v2-decision-policy.ts +166 -0
  97. package/src/pantheon/v2-decision-premises.ts +146 -0
  98. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  99. package/src/pantheon/v2-decision-rank.ts +91 -0
  100. package/src/pantheon/v2-decision-registry.ts +391 -0
  101. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  102. package/src/pantheon/v2-decision-shadow.ts +123 -0
  103. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  104. package/src/pantheon/v2-decision-verify.ts +51 -0
  105. package/src/pantheon/v2-hook-engine.ts +307 -0
  106. package/src/pantheon/v2-native-decisions.ts +365 -0
  107. package/src/pantheon/v2-shell-hooks.ts +66 -2
  108. package/src/pantheon/v2-tools.ts +38 -15
  109. package/src/plugin-v2.ts +419 -26
  110. package/src/plugin.ts +4 -0
  111. package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
  112. package/src/plugins/tui/dist/server-v2.d.ts +19 -11
  113. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -1
  114. package/src/plugins/tui/dist/server-v2.js +19 -666
  115. package/src/plugins/tui/dist/server-v2.js.map +1 -1
  116. package/src/plugins/tui/dist/tui-v2.d.ts +11 -203
  117. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  118. package/src/plugins/tui/dist/tui-v2.js +187 -1917
  119. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  120. package/src/plugins/tui/dist/tui.js +1 -1
  121. package/src/plugins/tui/package-lock.json +17 -2
  122. package/src/plugins/tui/package.json +4 -2
  123. package/src/plugins/tui/src/cost-data.ts +607 -0
  124. package/src/plugins/tui/src/index-v2.tsx +213 -54
  125. package/src/plugins/tui/src/model-pricing.ts +536 -0
  126. package/src/plugins/tui/src/server-v2.ts +18 -838
  127. package/src/plugins/tui/tsdown.config.ts +28 -6
  128. package/src/plugins/tui/dist/quota-adapters.d.ts +0 -89
  129. package/src/plugins/tui/dist/quota-adapters.d.ts.map +0 -1
  130. package/src/plugins/tui/dist/quota-adapters.js +0 -1142
  131. package/src/plugins/tui/dist/quota-adapters.js.map +0 -1
  132. package/src/plugins/tui/dist/quota-cli.d.ts +0 -17
  133. package/src/plugins/tui/dist/quota-cli.d.ts.map +0 -1
  134. package/src/plugins/tui/dist/quota-cli.js +0 -184
  135. package/src/plugins/tui/dist/quota-cli.js.map +0 -1
  136. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js +0 -390
  137. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js.map +0 -1
  138. package/src/plugins/tui/src/go-key-diagnostic-ui.ts +0 -100
  139. package/src/plugins/tui/src/go-key-diagnostic.ts +0 -125
  140. package/src/plugins/tui/src/quota-adapters.ts +0 -1598
  141. package/src/plugins/tui/src/quota-cli.ts +0 -237
  142. package/src/plugins/tui/src/quota-rpc.ts +0 -209
  143. package/src/plugins/tui/src/quota-v2-model.ts +0 -1032
  144. package/src/plugins/tui/src/quota-v2.tsx +0 -986
@@ -0,0 +1,168 @@
1
+ /**
2
+ * Internal, parser-issued usage capabilities for the native Decisions route.
3
+ * This module is deliberately not exported from the package entrypoints;
4
+ * callers cannot provide a cost value — the cost comes from the host's own
5
+ * DecisionResult, and this module only mints the opaque capability the ledger
6
+ * accepts. The legacy direct-fetch receipt verifier was removed with the fetch
7
+ * runner.
8
+ */
9
+
10
+ /** Providers that can appear in usage details: native Decisions routes. */
11
+ export type UsageProvider = 'typesafe-jev' | 'opencode-console' | 'jev-free'
12
+
13
+ export interface ParsedUsageCounts {
14
+ provider: UsageProvider
15
+ model: string
16
+ inputTokens: number
17
+ outputTokens: number
18
+ cachedInputTokens: number
19
+ cacheWriteInputTokens: number
20
+ }
21
+
22
+ export interface UsageReservationBinding {
23
+ reservationId: string
24
+ provider: UsageProvider
25
+ model: string
26
+ period: string
27
+ }
28
+
29
+ declare const verifiedUsageEvidenceBrand: unique symbol
30
+ export type VerifiedUsageEvidence = {
31
+ readonly [verifiedUsageEvidenceBrand]: true
32
+ }
33
+
34
+ export interface VerifiedUsageEvidenceDetails extends ParsedUsageCounts {
35
+ reservationId: string
36
+ period: string
37
+ actualCostMicros: number
38
+ pricingSnapshot: 'host-reported'
39
+ }
40
+
41
+ const RESERVATION_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/
42
+ const UTC_PERIOD = /^\d{4}-(0[1-9]|1[0-2])$/
43
+ const evidenceDetails = new WeakMap<object, VerifiedUsageEvidenceDetails>()
44
+
45
+ /**
46
+ * Budget providers with a native host Decisions route. `openai-decisions` is
47
+ * absent: direct OpenAI has no native route, so it can never settle one.
48
+ */
49
+ function isNativeUsageProvider(value: string): value is UsageProvider {
50
+ return value === 'typesafe-jev' || value === 'opencode-console' || value === 'jev-free'
51
+ }
52
+
53
+ /**
54
+ * Mint a reconciliation capability from a native host Decisions result.
55
+ *
56
+ * On the native route the host is the billing authority (it owns the provider
57
+ * credentials and the Console ledger), so the host-reported `cost` plays the
58
+ * role the fetch path's provider receipt played. Absent cost is a real zero —
59
+ * the free Console variant and hosts that do not price Decisions both land
60
+ * here, and reconciling at zero releases the reservation instead of burning
61
+ * the period's budget. A result that produced no answer settles nothing: an
62
+ * error payload is not evidence that a decision was paid for.
63
+ */
64
+ export function verifyNativeUsageForReservation(
65
+ bindingInput: unknown,
66
+ result: unknown,
67
+ ): VerifiedUsageEvidence | null {
68
+ try {
69
+ if (
70
+ !isPlainRecord(bindingInput) ||
71
+ !hasExactKeys(bindingInput, ['model', 'period', 'provider', 'reservationId'])
72
+ ) {
73
+ return null
74
+ }
75
+ const provider = bindingInput.provider
76
+ const model = bindingInput.model
77
+ const reservationId = bindingInput.reservationId
78
+ const period = bindingInput.period
79
+ if (
80
+ typeof provider !== 'string' ||
81
+ !isNativeUsageProvider(provider) ||
82
+ typeof model !== 'string' ||
83
+ model.length === 0 ||
84
+ typeof reservationId !== 'string' ||
85
+ !RESERVATION_ID.test(reservationId) ||
86
+ typeof period !== 'string' ||
87
+ !UTC_PERIOD.test(period)
88
+ ) {
89
+ return null
90
+ }
91
+ if (
92
+ !isPlainRecord(result) ||
93
+ !Array.isArray(result.answers) ||
94
+ result.answers.length === 0 ||
95
+ !result.answers.every((answer) => isPlainRecord(answer))
96
+ ) {
97
+ return null
98
+ }
99
+
100
+ let actualCostMicros = 0
101
+ if (result.cost !== undefined) {
102
+ if (!isNonNegativeFinite(result.cost)) return null
103
+ actualCostMicros = Math.round(result.cost * 1_000_000)
104
+ if (!Number.isSafeInteger(actualCostMicros)) return null
105
+ }
106
+ let inputTokens = 0
107
+ let outputTokens = 0
108
+ if (result.tokens !== undefined) {
109
+ if (!isPlainRecord(result.tokens)) return null
110
+ const { input, output } = result.tokens
111
+ if (
112
+ (input !== undefined && !isNonNegativeFinite(input)) ||
113
+ (output !== undefined && !isNonNegativeFinite(output))
114
+ ) {
115
+ return null
116
+ }
117
+ inputTokens = typeof input === 'number' ? input : 0
118
+ outputTokens = typeof output === 'number' ? output : 0
119
+ }
120
+
121
+ const evidence = Object.freeze(Object.create(null)) as VerifiedUsageEvidence
122
+ evidenceDetails.set(
123
+ evidence,
124
+ Object.freeze({
125
+ provider,
126
+ model,
127
+ inputTokens,
128
+ outputTokens,
129
+ cachedInputTokens: 0,
130
+ cacheWriteInputTokens: 0,
131
+ reservationId,
132
+ period,
133
+ actualCostMicros,
134
+ pricingSnapshot: 'host-reported',
135
+ }),
136
+ )
137
+ return evidence
138
+ } catch {
139
+ return null
140
+ }
141
+ }
142
+
143
+ /** Ledger-only runtime check: plain objects and serialized capabilities fail. */
144
+ export function getVerifiedUsageEvidenceDetails(
145
+ value: unknown,
146
+ ): Readonly<VerifiedUsageEvidenceDetails> | null {
147
+ if ((typeof value !== 'object' && typeof value !== 'function') || value === null) return null
148
+ return evidenceDetails.get(value as object) ?? null
149
+ }
150
+
151
+ function isNonNegativeFinite(value: unknown): value is number {
152
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0
153
+ }
154
+
155
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
156
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
157
+ const prototype = Object.getPrototypeOf(value)
158
+ return prototype === Object.prototype || prototype === null
159
+ }
160
+
161
+ function hasExactKeys(value: Record<string, unknown>, expectedKeys: readonly string[]): boolean {
162
+ const actualKeys = Object.keys(value).sort()
163
+ const expected = [...expectedKeys].sort()
164
+ return (
165
+ actualKeys.length === expected.length &&
166
+ actualKeys.every((key, index) => key === expected[index])
167
+ )
168
+ }
@@ -0,0 +1,322 @@
1
+ import { readFile } from 'node:fs/promises'
2
+ import { load } from 'js-yaml'
3
+ import {
4
+ classifyLocalDecisionComplexity,
5
+ LOCAL_DECISION_COMPLEXITY_DIMENSIONS,
6
+ LOCAL_DECISION_ROUTER_POLICY_VERSION,
7
+ type LocalDecisionComplexityDimensions,
8
+ type LocalDecisionGateStatus,
9
+ } from './local-decision-router.ts'
10
+ import { isAgentAllowed, type PermissionTaskConfig } from './permission-globs.ts'
11
+ import { PANTHEON_AGENTS } from './v2-delegation-enforce.ts'
12
+
13
+ export interface LocalDecisionAgentPolicy {
14
+ canDelegateTo: readonly string[]
15
+ canReceiveDelegation: boolean
16
+ capabilities: readonly string[]
17
+ skills: readonly string[]
18
+ }
19
+
20
+ export interface LocalDecisionPolicy {
21
+ agents: Readonly<Record<string, LocalDecisionAgentPolicy>>
22
+ permissionTask: PermissionTaskConfig
23
+ }
24
+
25
+ export interface LocalOrchestrationInput {
26
+ schemaVersion: 1
27
+ candidateAgents: readonly string[]
28
+ domain: string | null
29
+ candidateSkillIds: readonly string[]
30
+ candidateResourceIds: readonly string[]
31
+ memorySearchRelevant: boolean
32
+ gateStatus: LocalDecisionGateStatus
33
+ complexity: LocalDecisionComplexityDimensions
34
+ }
35
+
36
+ export type LocalOrchestrationReasonCode =
37
+ | 'CALLER_NOT_ZEUS'
38
+ | 'INVALID_INPUT'
39
+ | 'POLICY_UNAVAILABLE'
40
+ | 'NO_ELIGIBLE_CANDIDATE'
41
+ | 'AMBIGUOUS_CANDIDATE'
42
+ | 'DOMAIN_NOT_ELIGIBLE'
43
+ | 'ADVISORY_ROUTE'
44
+ | 'PROVIDER_RECOMMENDATION'
45
+ | 'PROVIDER_ABSTENTION'
46
+
47
+ export interface LocalOrchestrationPlan {
48
+ schemaVersion: 1
49
+ policyVersion: typeof LOCAL_DECISION_ROUTER_POLICY_VERSION
50
+ decision: 'recommend' | 'abstain'
51
+ reasonCode: LocalOrchestrationReasonCode
52
+ agent: string | null
53
+ skillIds: string[]
54
+ resourceIds: string[]
55
+ recommendMemorySearch: boolean
56
+ gateStatus: LocalDecisionGateStatus
57
+ complexity: ReturnType<typeof classifyLocalDecisionComplexity>
58
+ action: 'advisory_only'
59
+ }
60
+
61
+ const GATE_STATUSES = new Set<LocalDecisionGateStatus>([
62
+ 'none',
63
+ 'review_required',
64
+ 'human_approval_required',
65
+ 'unresolved',
66
+ ])
67
+ const INPUT_KEYS = [
68
+ 'candidateAgents',
69
+ 'candidateResourceIds',
70
+ 'candidateSkillIds',
71
+ 'complexity',
72
+ 'domain',
73
+ 'gateStatus',
74
+ 'memorySearchRelevant',
75
+ 'schemaVersion',
76
+ ]
77
+ const RESOURCE_IDS = new Set(['pantheon://agents', 'pantheon://routing', 'pantheon://skills'])
78
+
79
+ function isRecord(value: unknown): value is Record<string, unknown> {
80
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
81
+ const prototype = Object.getPrototypeOf(value)
82
+ return prototype === Object.prototype || prototype === null
83
+ }
84
+
85
+ function exactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {
86
+ const actual = Object.keys(value).sort()
87
+ const expected = [...keys].sort()
88
+ return actual.length === expected.length && actual.every((key, index) => key === expected[index])
89
+ }
90
+
91
+ function stringArray(value: unknown): value is string[] {
92
+ return Array.isArray(value) && value.every((item) => typeof item === 'string')
93
+ }
94
+
95
+ function hasUsablePolicy(policy: LocalDecisionPolicy | undefined): policy is LocalDecisionPolicy {
96
+ if (
97
+ policy === undefined ||
98
+ !isRecord(policy.agents) ||
99
+ !isRecord(policy.permissionTask) ||
100
+ !isRecord(policy.agents.zeus)
101
+ ) {
102
+ return false
103
+ }
104
+ const grants = Object.entries(policy.permissionTask)
105
+ return (
106
+ grants.length > 0 &&
107
+ grants.every(([, action]) => action === 'allow' || action === 'deny') &&
108
+ stringArray(policy.agents.zeus.canDelegateTo) &&
109
+ stringArray(policy.agents.zeus.capabilities)
110
+ )
111
+ }
112
+
113
+ function parsePolicy(raw: unknown): LocalDecisionPolicy | undefined {
114
+ if (!isRecord(raw) || !isRecord(raw.agents) || !isRecord(raw.permission)) return undefined
115
+ const permission = raw.permission.task
116
+ if (!isRecord(permission)) return undefined
117
+
118
+ const permissionTask: Record<string, 'allow' | 'deny'> = {}
119
+ for (const [pattern, action] of Object.entries(permission)) {
120
+ if (action !== 'allow' && action !== 'deny') return undefined
121
+ permissionTask[pattern] = action
122
+ }
123
+ if (Object.keys(permissionTask).length === 0) return undefined
124
+
125
+ const agents: Record<string, LocalDecisionAgentPolicy> = {}
126
+ for (const [id, value] of Object.entries(raw.agents)) {
127
+ if (!PANTHEON_AGENTS.has(id) || !isRecord(value)) continue
128
+ const canDelegateTo =
129
+ value.subagent_can_delegate_to === undefined && value.can_delegate === false
130
+ ? []
131
+ : value.subagent_can_delegate_to
132
+ if (
133
+ typeof value.can_receive_delegation !== 'boolean' ||
134
+ !stringArray(canDelegateTo) ||
135
+ !stringArray(value.skills) ||
136
+ !stringArray(value.capabilities)
137
+ ) {
138
+ return undefined
139
+ }
140
+ if (
141
+ canDelegateTo.some((target) => !PANTHEON_AGENTS.has(target)) ||
142
+ value.skills.some((skill) => !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(skill))
143
+ ) {
144
+ return undefined
145
+ }
146
+ agents[id] = {
147
+ canDelegateTo,
148
+ canReceiveDelegation: value.can_receive_delegation,
149
+ capabilities: value.capabilities,
150
+ skills: value.skills,
151
+ }
152
+ }
153
+ if (agents.zeus === undefined) return undefined
154
+ return { agents, permissionTask }
155
+ }
156
+
157
+ let policyCache: Promise<LocalDecisionPolicy | undefined> | undefined
158
+
159
+ /**
160
+ * Load only local, non-secret policy metadata; missing or invalid policy abstains.
161
+ * `routing.yml` is a static package asset, so the parsed policy is cached for
162
+ * the process lifetime. Failures are not cached: the next prompt retries, and a
163
+ * test/admin can call `clearLocalDecisionPolicyCache()` to invalidate safely.
164
+ */
165
+ export async function loadLocalDecisionPolicy(): Promise<LocalDecisionPolicy | undefined> {
166
+ if (policyCache === undefined) {
167
+ policyCache = readLocalDecisionPolicy().then(
168
+ (policy) => {
169
+ if (policy === undefined) policyCache = undefined
170
+ return policy
171
+ },
172
+ () => {
173
+ policyCache = undefined
174
+ return undefined
175
+ },
176
+ )
177
+ }
178
+ return policyCache
179
+ }
180
+
181
+ /** Test/admin seam: drop the process policy cache without discharging any state. */
182
+ export function clearLocalDecisionPolicyCache(): void {
183
+ policyCache = undefined
184
+ }
185
+
186
+ async function readLocalDecisionPolicy(): Promise<LocalDecisionPolicy | undefined> {
187
+ try {
188
+ const routingUrl = new URL('../routing.yml', import.meta.url)
189
+ const parsed = load(await readFile(routingUrl, 'utf8'))
190
+ return parsePolicy(parsed)
191
+ } catch {
192
+ return undefined
193
+ }
194
+ }
195
+
196
+ function isValidInput(value: unknown): value is LocalOrchestrationInput {
197
+ if (!isRecord(value) || !exactKeys(value, INPUT_KEYS) || value.schemaVersion !== 1) return false
198
+ if (
199
+ !stringArray(value.candidateAgents) ||
200
+ value.candidateAgents.length > 14 ||
201
+ !stringArray(value.candidateSkillIds) ||
202
+ value.candidateSkillIds.length > 64 ||
203
+ !stringArray(value.candidateResourceIds) ||
204
+ value.candidateResourceIds.length > 32 ||
205
+ (value.domain !== null && typeof value.domain !== 'string') ||
206
+ typeof value.memorySearchRelevant !== 'boolean' ||
207
+ typeof value.gateStatus !== 'string' ||
208
+ !GATE_STATUSES.has(value.gateStatus as LocalDecisionGateStatus) ||
209
+ !isRecord(value.complexity)
210
+ ) {
211
+ return false
212
+ }
213
+ return (
214
+ exactKeys(value.complexity, LOCAL_DECISION_COMPLEXITY_DIMENSIONS) &&
215
+ classifyLocalDecisionComplexity(value.complexity).label !== 'abstain'
216
+ )
217
+ }
218
+
219
+ function abstain(
220
+ reasonCode: LocalOrchestrationReasonCode,
221
+ gateStatus: LocalDecisionGateStatus = 'unresolved',
222
+ complexity?: unknown,
223
+ ): LocalOrchestrationPlan {
224
+ return {
225
+ schemaVersion: 1,
226
+ policyVersion: LOCAL_DECISION_ROUTER_POLICY_VERSION,
227
+ decision: 'abstain',
228
+ reasonCode,
229
+ agent: null,
230
+ skillIds: [],
231
+ resourceIds: [],
232
+ recommendMemorySearch: false,
233
+ gateStatus,
234
+ complexity: classifyLocalDecisionComplexity(complexity),
235
+ action: 'advisory_only',
236
+ }
237
+ }
238
+
239
+ /** Build an advisory plan from structured candidate IDs; this function never dispatches. */
240
+ export function recommendLocalOrchestration(
241
+ input: unknown,
242
+ callerAgent: unknown,
243
+ policy: LocalDecisionPolicy | undefined,
244
+ ): LocalOrchestrationPlan {
245
+ try {
246
+ return evaluateLocalOrchestration(input, callerAgent, policy)
247
+ } catch {
248
+ return abstain('INVALID_INPUT')
249
+ }
250
+ }
251
+
252
+ function evaluateLocalOrchestration(
253
+ input: unknown,
254
+ callerAgent: unknown,
255
+ policy: LocalDecisionPolicy | undefined,
256
+ ): LocalOrchestrationPlan {
257
+ if (callerAgent !== 'zeus') return abstain('CALLER_NOT_ZEUS')
258
+ if (!hasUsablePolicy(policy)) {
259
+ return abstain('POLICY_UNAVAILABLE')
260
+ }
261
+ if (!isValidInput(input)) return abstain('INVALID_INPUT')
262
+
263
+ const gateStatus = input.gateStatus
264
+ const complexity = classifyLocalDecisionComplexity(input.complexity)
265
+ const zeus = policy.agents.zeus
266
+ if (zeus === undefined) return abstain('POLICY_UNAVAILABLE', gateStatus, input.complexity)
267
+ const eligible = [...new Set(input.candidateAgents)].filter((candidate) => {
268
+ const target = policy.agents[candidate]
269
+ return (
270
+ candidate !== 'zeus' &&
271
+ PANTHEON_AGENTS.has(candidate) &&
272
+ target?.canReceiveDelegation === true &&
273
+ zeus.canDelegateTo.includes(candidate) &&
274
+ isAgentAllowed(policy.permissionTask, candidate)
275
+ )
276
+ })
277
+
278
+ if (eligible.length === 0) return abstain('NO_ELIGIBLE_CANDIDATE', gateStatus, input.complexity)
279
+
280
+ let agent: string
281
+ if (input.domain !== null) {
282
+ if (!eligible.includes(input.domain)) {
283
+ return abstain('DOMAIN_NOT_ELIGIBLE', gateStatus, input.complexity)
284
+ }
285
+ agent = input.domain
286
+ } else if (eligible.length === 1) {
287
+ const [onlyEligible] = eligible
288
+ if (onlyEligible === undefined) {
289
+ return abstain('NO_ELIGIBLE_CANDIDATE', gateStatus, input.complexity)
290
+ }
291
+ agent = onlyEligible
292
+ } else {
293
+ return abstain('AMBIGUOUS_CANDIDATE', gateStatus, input.complexity)
294
+ }
295
+
296
+ const agentPolicy = policy.agents[agent]
297
+ if (agentPolicy === undefined) return abstain('POLICY_UNAVAILABLE', gateStatus, input.complexity)
298
+ const skillIds = input.candidateSkillIds.filter(
299
+ (skill, index, all) => all.indexOf(skill) === index && agentPolicy.skills.includes(skill),
300
+ )
301
+ const allowedResources = new Set(RESOURCE_IDS)
302
+ for (const skill of skillIds) allowedResources.add(`pantheon://skills/${skill}`)
303
+ if (PANTHEON_AGENTS.has(agent)) allowedResources.add(`pantheon://agents/${agent}`)
304
+ const resourceIds = input.candidateResourceIds.filter(
305
+ (resource, index, all) => all.indexOf(resource) === index && allowedResources.has(resource),
306
+ )
307
+
308
+ return {
309
+ schemaVersion: 1,
310
+ policyVersion: LOCAL_DECISION_ROUTER_POLICY_VERSION,
311
+ decision: 'recommend',
312
+ reasonCode: 'ADVISORY_ROUTE',
313
+ agent,
314
+ skillIds,
315
+ resourceIds,
316
+ recommendMemorySearch:
317
+ input.memorySearchRelevant && zeus.capabilities.includes('memory_recall'),
318
+ gateStatus,
319
+ complexity,
320
+ action: 'advisory_only',
321
+ }
322
+ }