pantheon-opencode 1.6.2-beta.3 → 1.6.2-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -0
- package/README.md +209 -1
- package/bin/pantheon-init.mjs +22 -0
- package/package.json +9 -3
- package/plugin.json +1 -1
- package/pyproject.toml +1 -1
- package/scripts/decision-router-budget.mjs +781 -0
- package/scripts/decision-router-v2-budget.mjs +218 -0
- package/scripts/decision-router-v2-egress.mjs +272 -0
- package/scripts/decision-router.mjs +519 -0
- package/scripts/docs-check-changelog.mjs +5 -3
- package/scripts/install/decision-layer-preview.mjs +376 -0
- package/scripts/install/decision-router-config.mjs +579 -0
- package/scripts/install/interactive.mjs +76 -5
- package/scripts/install/opencode.mjs +12 -0
- package/scripts/install/state.mjs +5 -0
- package/scripts/install/strings.mjs +4 -0
- package/scripts/mcp_resources.py +11 -9
- package/scripts/release-notes.mjs +30 -7
- package/scripts/versioning.mjs +41 -5
- package/src/agents/zeus.md +12 -0
- package/src/mcp/eval_store.py +11 -4
- package/src/mcp/mcp_resources.py +11 -9
- package/src/mcp/memory_mcp.py +293 -150
- package/src/pantheon/local-decision-agents.ts +170 -0
- package/src/pantheon/local-decision-budget.ts +1043 -0
- package/src/pantheon/local-decision-egress-gate.ts +264 -0
- package/src/pantheon/local-decision-prompt.ts +268 -0
- package/src/pantheon/local-decision-provider-matrix.ts +92 -0
- package/src/pantheon/local-decision-provider-protocol.ts +335 -0
- package/src/pantheon/local-decision-provider.internal.ts +260 -0
- package/src/pantheon/local-decision-router.ts +225 -0
- package/src/pantheon/local-decision-skills.ts +281 -0
- package/src/pantheon/local-decision-tool.ts +160 -0
- package/src/pantheon/local-decision-turn.ts +338 -0
- package/src/pantheon/local-decision-usage-evidence.internal.ts +207 -0
- package/src/pantheon/local-orchestration.ts +322 -0
- package/src/pantheon/pantheon-decision-catalog.ts +101 -0
- package/src/pantheon/v2-decision-budget.ts +456 -0
- package/src/pantheon/v2-decision-contracts.ts +300 -0
- package/src/pantheon/v2-decision-egress.ts +203 -0
- package/src/pantheon/v2-decision-events.ts +180 -0
- package/src/pantheon/v2-decision-heuristic.ts +121 -0
- package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
- package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
- package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
- package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
- package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
- package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
- package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
- package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
- package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
- package/src/pantheon/v2-decision-points/p8-guardrail.ts +366 -0
- package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
- package/src/pantheon/v2-decision-points.ts +242 -0
- package/src/pantheon/v2-decision-policy.ts +166 -0
- package/src/pantheon/v2-decision-premises.ts +146 -0
- package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
- package/src/pantheon/v2-decision-rank.ts +91 -0
- package/src/pantheon/v2-decision-registry.ts +391 -0
- package/src/pantheon/v2-decision-resource-ids.ts +127 -0
- package/src/pantheon/v2-decision-shadow.ts +123 -0
- package/src/pantheon/v2-decision-telemetry.ts +214 -0
- package/src/pantheon/v2-decision-verify.ts +51 -0
- package/src/pantheon/v2-tools.ts +35 -15
- package/src/plugin-v2.ts +357 -22
- package/src/plugin.ts +4 -0
- package/src/plugins/tui/dist/tui-v2.js +3 -3
- package/src/plugins/tui/dist/tui.js +1 -1
- package/src/plugins/tui/package-lock.json +2 -2
- package/src/plugins/tui/package.json +1 -1
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Consent/config gate and host assertion contract for the single
|
|
3
|
+
* decision-provider egress action.
|
|
4
|
+
*
|
|
5
|
+
* Source of truth: the user-level decision-router configuration. Egress
|
|
6
|
+
* requires `enabled`, `egress_consent: true`, exactly one enabled and cap-valid
|
|
7
|
+
* provider/model candidate, a confirmed UTC budget period, and positive
|
|
8
|
+
* user/provider/model caps. Local mode, missing consent, or an unconfirmed
|
|
9
|
+
* period means no request, and the host is not even asked.
|
|
10
|
+
*
|
|
11
|
+
* `permission.assert` is a host kill-switch layered on top, never consent:
|
|
12
|
+
*
|
|
13
|
+
* - Deny is observable: the host throws (`Permission.BlockedError`, whose
|
|
14
|
+
* message is `Permission denied: <action>` unless an evaluate hook supplied a
|
|
15
|
+
* reason) or, defensively, resolves an explicit denial marker.
|
|
16
|
+
* - Allow is NOT observable as a positive value. The measured host contract
|
|
17
|
+
* (`Permission.assert` in the bundled opencode host) resolves `undefined` when
|
|
18
|
+
* every rule admits the request. A resolved non-denial therefore only means
|
|
19
|
+
* "the host did not block it"; the configuration above remains the authority.
|
|
20
|
+
*
|
|
21
|
+
* The custom action has no default rule, and the measured v2.2.0 canary showed
|
|
22
|
+
* the host is NOT deny-by-default for it: an assertion with no matching rule
|
|
23
|
+
* resolved allow. The config/consent gate above is therefore the source of
|
|
24
|
+
* truth for authorization, and an explicit `deny` rule is the kill-switch; the
|
|
25
|
+
* fix for a blocked host is an explicit user permission rule for
|
|
26
|
+
* `decision.egress`, not a bypass in this plugin. This module never retries,
|
|
27
|
+
* downgrades, or reinterprets a denial.
|
|
28
|
+
*
|
|
29
|
+
* `assert` is called by the plugin in the same process it protects. It is not a
|
|
30
|
+
* boundary against hostile same-process code; the fixed endpoints, redirect
|
|
31
|
+
* refusal, timeout, response cap, and accounting ledger are the real protection
|
|
32
|
+
* against an accidental or over-broad egress.
|
|
33
|
+
*
|
|
34
|
+
* Canary note: a real host canary of v2.2.0 observed that `permission.assert`
|
|
35
|
+
* reaches the `evaluate` hook on the allow path and is not invoked for an
|
|
36
|
+
* explicit deny, that an assertion with no rule for this custom action resolved
|
|
37
|
+
* allow rather than deny, and that the host accepts a rule under root
|
|
38
|
+
* `permission`/`permissions` or `agents.<id>.permissions` while ignoring an
|
|
39
|
+
* `agents.<id>.permission` map. Egress therefore must not depend on an
|
|
40
|
+
* evaluate-hook decision, and the plugin does not mint or consume an
|
|
41
|
+
* allowance.
|
|
42
|
+
*/
|
|
43
|
+
import {
|
|
44
|
+
readUserDecisionRouterConfig,
|
|
45
|
+
resolveUserDecisionRouterCandidate,
|
|
46
|
+
type UserDecisionRouterCandidate,
|
|
47
|
+
} from '../../scripts/install/decision-router-config.mjs'
|
|
48
|
+
import {
|
|
49
|
+
openLocalDecisionBudgetLedger,
|
|
50
|
+
resolveLocalDecisionBudgetDbPath,
|
|
51
|
+
} from './local-decision-budget.ts'
|
|
52
|
+
import {
|
|
53
|
+
DECISION_PROVIDER_ADAPTERS,
|
|
54
|
+
type DecisionProviderId,
|
|
55
|
+
} from './local-decision-provider-matrix.ts'
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Custom host action, distinct from `webfetch`. It has no default host rule; the
|
|
59
|
+
* measured host resolves an unruled assertion as allow, so only an explicit
|
|
60
|
+
* `deny` rule blocks it.
|
|
61
|
+
*/
|
|
62
|
+
export const DECISION_EGRESS_ACTION = 'decision.egress'
|
|
63
|
+
|
|
64
|
+
/** Namespaced prefix that marks a Pantheon-internal assertion, not a real call. */
|
|
65
|
+
export const DECISION_EGRESS_SOURCE_PREFIX = 'pantheon-decision:'
|
|
66
|
+
|
|
67
|
+
export interface DecisionEgressSource {
|
|
68
|
+
type: 'tool'
|
|
69
|
+
id: string
|
|
70
|
+
messageID: string
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Reason codes shared with the provider runner's fallback contract. */
|
|
74
|
+
export type DecisionEgressGateReason =
|
|
75
|
+
| 'CONFIG_UNAVAILABLE'
|
|
76
|
+
| 'DISABLED'
|
|
77
|
+
| 'CONSENT_MISSING'
|
|
78
|
+
| 'NO_ELIGIBLE_CANDIDATE'
|
|
79
|
+
| 'CAP_OR_PERIOD_DENIED'
|
|
80
|
+
| 'PERMISSION_UNAVAILABLE'
|
|
81
|
+
| 'PERMISSION_DENIED'
|
|
82
|
+
|
|
83
|
+
export type PermissionAssert = (input: Record<string, unknown>) => Promise<unknown>
|
|
84
|
+
|
|
85
|
+
export type DecisionEgressAssertion = 'allow' | 'deny'
|
|
86
|
+
|
|
87
|
+
function nonEmptyString(value: unknown): string | undefined {
|
|
88
|
+
if (typeof value !== 'string') return undefined
|
|
89
|
+
const trimmed = value.trim()
|
|
90
|
+
return trimmed.length === 0 ? undefined : trimmed
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Synthetic, stable source accepted by the host for this action. */
|
|
94
|
+
export function decisionPermissionSource(
|
|
95
|
+
sessionID: string,
|
|
96
|
+
messageID: string,
|
|
97
|
+
): DecisionEgressSource {
|
|
98
|
+
return {
|
|
99
|
+
type: 'tool',
|
|
100
|
+
id: `${DECISION_EGRESS_SOURCE_PREFIX}${sessionID}:${messageID}`,
|
|
101
|
+
messageID,
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* The only shape the provider runner and the cached-turn recheck send to
|
|
107
|
+
* `permission.assert`. Keeping it in one place prevents the prompt-source
|
|
108
|
+
* schema mismatch the canary caught.
|
|
109
|
+
*/
|
|
110
|
+
export function buildDecisionEgressRequest(input: {
|
|
111
|
+
sessionID: string
|
|
112
|
+
messageID: string
|
|
113
|
+
endpoint: string
|
|
114
|
+
/** Current agent, only when the caller actually knows it. */
|
|
115
|
+
agent?: string | undefined
|
|
116
|
+
}): Record<string, unknown> {
|
|
117
|
+
const request: Record<string, unknown> = {
|
|
118
|
+
sessionID: input.sessionID,
|
|
119
|
+
action: DECISION_EGRESS_ACTION,
|
|
120
|
+
resources: [input.endpoint],
|
|
121
|
+
save: [],
|
|
122
|
+
source: decisionPermissionSource(input.sessionID, input.messageID),
|
|
123
|
+
}
|
|
124
|
+
// The host only uses `agent` to resolve that agent's rules. Emit it only when
|
|
125
|
+
// the caller knows the current agent; never invent a default such as `zeus`.
|
|
126
|
+
const agent = nonEmptyString(input.agent)
|
|
127
|
+
if (agent !== undefined) request.agent = agent
|
|
128
|
+
return request
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const DENIAL_VALUES = new Set(['deny', 'denied', 'reject', 'rejected', 'blocked'])
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The host words a denial as prose (`Permission denied: decision.egress`), not
|
|
135
|
+
* only as an enum value. Matching it is what makes a returned host denial — as
|
|
136
|
+
* a bare string or inside `message`/`error` — recognizable as deny.
|
|
137
|
+
*/
|
|
138
|
+
const DENIAL_PATTERN = /permission\s+denied|not\s+allowed|forbidden|(?<!not\s)blocked/i
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Defensive read of an assertion result.
|
|
142
|
+
*
|
|
143
|
+
* The measured contract signals deny by throwing and allow by resolving
|
|
144
|
+
* `undefined`, so this only recognizes the explicit denial shapes a future or
|
|
145
|
+
* alternative host could return. A resolved non-denial is treated as allow
|
|
146
|
+
* because allow has no positive representation to check for.
|
|
147
|
+
*/
|
|
148
|
+
export function isDecisionAssertionDenial(result: unknown): boolean {
|
|
149
|
+
if (result === false) return true
|
|
150
|
+
if (typeof result === 'string') {
|
|
151
|
+
return DENIAL_VALUES.has(result.trim().toLowerCase()) || DENIAL_PATTERN.test(result)
|
|
152
|
+
}
|
|
153
|
+
if (result === null || typeof result !== 'object' || Array.isArray(result)) return false
|
|
154
|
+
const record = result as Record<string, unknown>
|
|
155
|
+
if (record.denied === true || record.allowed === false || record.ok === false) return true
|
|
156
|
+
for (const key of ['effect', 'decision', 'status', 'result']) {
|
|
157
|
+
const value = record[key]
|
|
158
|
+
if (typeof value === 'string' && DENIAL_VALUES.has(value.trim().toLowerCase())) return true
|
|
159
|
+
}
|
|
160
|
+
for (const key of ['message', 'error']) {
|
|
161
|
+
const value = record[key]
|
|
162
|
+
if (typeof value === 'string' && DENIAL_PATTERN.test(value)) return true
|
|
163
|
+
}
|
|
164
|
+
return false
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Ask the host's kill-switch and normalize the outcome.
|
|
169
|
+
*
|
|
170
|
+
* A throw is a deny. A resolved explicit denial marker is a deny. Everything
|
|
171
|
+
* else is `allow` — not because the host promised consent, but because the
|
|
172
|
+
* host's allow path is indistinguishable from `undefined`; the config gate
|
|
173
|
+
* above is what actually authorizes egress.
|
|
174
|
+
*/
|
|
175
|
+
export async function assertDecisionEgressPermission(
|
|
176
|
+
permissionAssert: PermissionAssert,
|
|
177
|
+
request: Record<string, unknown>,
|
|
178
|
+
): Promise<DecisionEgressAssertion> {
|
|
179
|
+
let result: unknown
|
|
180
|
+
try {
|
|
181
|
+
result = await permissionAssert(request)
|
|
182
|
+
} catch {
|
|
183
|
+
return 'deny'
|
|
184
|
+
}
|
|
185
|
+
return isDecisionAssertionDenial(result) ? 'deny' : 'allow'
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export interface CapValidDecisionCandidate {
|
|
189
|
+
provider: DecisionProviderId
|
|
190
|
+
adapter: (typeof DECISION_PROVIDER_ADAPTERS)[DecisionProviderId]
|
|
191
|
+
candidate: UserDecisionRouterCandidate
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* Single cap-valid selection shared by the provider runner and the cached-turn
|
|
196
|
+
* recheck. Opens the ledger, keeps only enabled, egress-eligible candidates
|
|
197
|
+
* whose period and caps admit a reservation, resolves the preference, and
|
|
198
|
+
* requires the resolved model to match the fixed matrix row.
|
|
199
|
+
*
|
|
200
|
+
* Throws when the ledger cannot be opened or queried; callers map that to
|
|
201
|
+
* `CAP_OR_PERIOD_DENIED`. Returns `null` when no candidate qualifies.
|
|
202
|
+
*/
|
|
203
|
+
export function selectCapValidDecisionCandidate(
|
|
204
|
+
config: ReturnType<typeof readUserDecisionRouterConfig>,
|
|
205
|
+
): CapValidDecisionCandidate | null {
|
|
206
|
+
const ledger = openLocalDecisionBudgetLedger({ dbPath: resolveLocalDecisionBudgetDbPath() })
|
|
207
|
+
try {
|
|
208
|
+
const valid: UserDecisionRouterCandidate[] = []
|
|
209
|
+
for (const candidate of config.enabled_candidates) {
|
|
210
|
+
const provider = candidate.provider as DecisionProviderId
|
|
211
|
+
const adapter = DECISION_PROVIDER_ADAPTERS[provider]
|
|
212
|
+
if (adapter === undefined || !adapter.egressEligible) continue
|
|
213
|
+
if (ledger.canReserve(adapter.accountingProvider, candidate.model).status !== 'eligible') {
|
|
214
|
+
continue
|
|
215
|
+
}
|
|
216
|
+
valid.push(candidate)
|
|
217
|
+
}
|
|
218
|
+
const selected = resolveUserDecisionRouterCandidate(config, valid)
|
|
219
|
+
if (selected === null) return null
|
|
220
|
+
const provider = selected.provider as DecisionProviderId
|
|
221
|
+
const adapter = DECISION_PROVIDER_ADAPTERS[provider]
|
|
222
|
+
if (adapter === undefined || !adapter.egressEligible) return null
|
|
223
|
+
if (selected.model !== adapter.model) return null
|
|
224
|
+
return { provider, adapter, candidate: selected }
|
|
225
|
+
} finally {
|
|
226
|
+
ledger.close()
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export type DecisionEgressConsent =
|
|
231
|
+
| { ok: true; selected: CapValidDecisionCandidate }
|
|
232
|
+
| {
|
|
233
|
+
ok: false
|
|
234
|
+
reasonCode: Exclude<DecisionEgressGateReason, 'PERMISSION_UNAVAILABLE' | 'PERMISSION_DENIED'>
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Evaluate the consent/config gate without touching the network or the host.
|
|
239
|
+
*
|
|
240
|
+
* Callers run this BEFORE `permission.assert`: an invalid configuration is not
|
|
241
|
+
* worth an interactive prompt, and the host must not be asked to approve a
|
|
242
|
+
* request that the user's own configuration already forbids.
|
|
243
|
+
*/
|
|
244
|
+
export function resolveDecisionEgressConsent(): DecisionEgressConsent {
|
|
245
|
+
let config: ReturnType<typeof readUserDecisionRouterConfig>
|
|
246
|
+
try {
|
|
247
|
+
config = readUserDecisionRouterConfig()
|
|
248
|
+
} catch {
|
|
249
|
+
return { ok: false, reasonCode: 'CONFIG_UNAVAILABLE' }
|
|
250
|
+
}
|
|
251
|
+
if (!config.enabled) return { ok: false, reasonCode: 'DISABLED' }
|
|
252
|
+
if (!config.egress_consent || config.selection.mode === 'local') {
|
|
253
|
+
return { ok: false, reasonCode: 'CONSENT_MISSING' }
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
let selected: CapValidDecisionCandidate | null
|
|
257
|
+
try {
|
|
258
|
+
selected = selectCapValidDecisionCandidate(config)
|
|
259
|
+
} catch {
|
|
260
|
+
return { ok: false, reasonCode: 'CAP_OR_PERIOD_DENIED' }
|
|
261
|
+
}
|
|
262
|
+
if (selected === null) return { ok: false, reasonCode: 'NO_ELIGIBLE_CANDIDATE' }
|
|
263
|
+
return { ok: true, selected }
|
|
264
|
+
}
|
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
import { decideForTurn, type TurnDecision, type TurnDecisionInput } from './local-decision-turn.ts'
|
|
2
|
+
import { isPantheonAgentId, isPantheonSkillId } from './pantheon-decision-catalog.ts'
|
|
3
|
+
|
|
4
|
+
const MARKER_PREFIX = '<!-- pantheon-decision-router:v1'
|
|
5
|
+
const MARKER_PATTERN = /<!-- pantheon-decision-router:v1\b[^>]*-->/
|
|
6
|
+
|
|
7
|
+
/** The host sends the *string* `"undefined"` for absent prompt fields (F-08). */
|
|
8
|
+
const MEASURED_SENTINELS: ReadonlySet<string> = new Set(['undefined', 'null'])
|
|
9
|
+
|
|
10
|
+
/** Where the observed skill list came from: the prompt array, the draft, or nowhere. */
|
|
11
|
+
export type SkillsSource = 'none' | 'prompt' | 'draft'
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Why the skill outcome is what it is. Tokens only — no content, no count of
|
|
15
|
+
* user text. Every result carries one, so an empty selection is never silent.
|
|
16
|
+
*/
|
|
17
|
+
export type PromptApplicationReason =
|
|
18
|
+
| 'invalid.payload'
|
|
19
|
+
| 'request.empty'
|
|
20
|
+
| 'marker.present'
|
|
21
|
+
| 'decision.inactive'
|
|
22
|
+
| 'selection.empty'
|
|
23
|
+
| 'skills.source.prompt'
|
|
24
|
+
| 'skills.source.draft'
|
|
25
|
+
| 'skills.source.absent'
|
|
26
|
+
| 'skills.source.empty'
|
|
27
|
+
| 'skills.source.unstable'
|
|
28
|
+
| 'skills.selection.disjoint'
|
|
29
|
+
| 'skills.synthetic.narrowed'
|
|
30
|
+
|
|
31
|
+
export interface PromptApplicationResult {
|
|
32
|
+
markerApplied: boolean
|
|
33
|
+
skillsFiltered: boolean
|
|
34
|
+
/** Observable source of the skill list; `none` in the measured host shape (F-08). */
|
|
35
|
+
skillsSource: SkillsSource
|
|
36
|
+
/** Always present: explains the skill outcome, including every empty selection. */
|
|
37
|
+
reason: PromptApplicationReason
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface SkillSourceResolution {
|
|
41
|
+
readonly skillsSource: SkillsSource
|
|
42
|
+
/** Stable identifiers found in the chosen source, deduplicated, in order. */
|
|
43
|
+
readonly skillIds: readonly string[]
|
|
44
|
+
readonly reason: PromptApplicationReason
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
interface SkillNarrowing {
|
|
48
|
+
readonly skillsFiltered: boolean
|
|
49
|
+
readonly skillsSource: SkillsSource
|
|
50
|
+
readonly reason: PromptApplicationReason
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** True when the value is the measured placeholder string, not real data. */
|
|
54
|
+
function isMeasuredSentinel(value: unknown): boolean {
|
|
55
|
+
return typeof value === 'string' && MEASURED_SENTINELS.has(value)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Normalize a measured prompt field: a sentinel string or null means "absent". */
|
|
59
|
+
export function normalizeMeasuredValue(value: unknown): unknown {
|
|
60
|
+
if (value === null || value === undefined) return undefined
|
|
61
|
+
return isMeasuredSentinel(value) ? undefined : value
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function skillIdentifier(value: unknown): string | undefined {
|
|
65
|
+
if (typeof value === 'string') return value
|
|
66
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) return undefined
|
|
67
|
+
const record = value as { name?: unknown; id?: unknown; slug?: unknown }
|
|
68
|
+
for (const candidate of [record.name, record.id, record.slug]) {
|
|
69
|
+
if (typeof candidate === 'string' && candidate.length > 0) return candidate
|
|
70
|
+
}
|
|
71
|
+
return undefined
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function identifiers(list: readonly unknown[]): { ids: string[]; unstable: boolean } {
|
|
75
|
+
const ids: string[] = []
|
|
76
|
+
let unstable = false
|
|
77
|
+
for (const item of list) {
|
|
78
|
+
const identifier = skillIdentifier(item)
|
|
79
|
+
if (identifier === undefined) unstable = true
|
|
80
|
+
else if (!ids.includes(identifier)) ids.push(identifier)
|
|
81
|
+
}
|
|
82
|
+
return { ids, unstable }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Resolve the observed skill list and say where it came from.
|
|
87
|
+
*
|
|
88
|
+
* The prompt list wins when it is a real array. Otherwise the per-turn draft
|
|
89
|
+
* (`ctx.skill.list()`, F-06) is reported as `draft`. The measured host shape
|
|
90
|
+
* carries the sentinel string `"undefined"` (F-08), which is treated as absent.
|
|
91
|
+
*
|
|
92
|
+
* The `draft` branch has **no production caller**: the shipped prompt hook calls
|
|
93
|
+
* `applyTurnDecisionToPrompt(prompt, decision)` without `skillsDraft`, and
|
|
94
|
+
* `ctx.skill.list()` is never read by it. At runtime `skillsSource` is therefore
|
|
95
|
+
* `none` or `prompt` only, and the `draft` source is exercised by tests alone.
|
|
96
|
+
*/
|
|
97
|
+
export function resolveSkillSource(
|
|
98
|
+
promptSkills: unknown,
|
|
99
|
+
draftSkills?: unknown,
|
|
100
|
+
): SkillSourceResolution {
|
|
101
|
+
const promptList = normalizeMeasuredValue(promptSkills)
|
|
102
|
+
const draftList = normalizeMeasuredValue(draftSkills)
|
|
103
|
+
|
|
104
|
+
if (Array.isArray(promptList) && promptList.length > 0) {
|
|
105
|
+
const resolved = identifiers(promptList)
|
|
106
|
+
return {
|
|
107
|
+
skillsSource: 'prompt',
|
|
108
|
+
skillIds: resolved.ids,
|
|
109
|
+
reason: resolved.unstable ? 'skills.source.unstable' : 'skills.source.prompt',
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
if (Array.isArray(draftList) && draftList.length > 0) {
|
|
113
|
+
const resolved = identifiers(draftList)
|
|
114
|
+
return {
|
|
115
|
+
skillsSource: 'draft',
|
|
116
|
+
skillIds: resolved.ids,
|
|
117
|
+
reason: resolved.unstable ? 'skills.source.unstable' : 'skills.source.draft',
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return {
|
|
121
|
+
skillsSource: 'none',
|
|
122
|
+
skillIds: [],
|
|
123
|
+
reason: Array.isArray(promptList) ? 'skills.source.empty' : 'skills.source.absent',
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Best-effort narrowing of the host's pre-resolution skill list.
|
|
129
|
+
*
|
|
130
|
+
* Only a real prompt array can be narrowed, and an empty advisory selection
|
|
131
|
+
* must never erase skills the host or user chose. The measured host shape is
|
|
132
|
+
* the sentinel string (F-08), so this is unreachable on the default path: P2 is
|
|
133
|
+
* an empirical no-op there (F-09). The array shape is synthetic — never
|
|
134
|
+
* observed — and its outcome is not a measured effect: PROBE-E measured no
|
|
135
|
+
* effect for any `prompt.skills`/`prompt.agents` mutation (F-24), while C6 as a
|
|
136
|
+
* question is closed for `skill.transform` and `prompt.text`.
|
|
137
|
+
*/
|
|
138
|
+
function narrowSkills(
|
|
139
|
+
prompt: Record<string, unknown>,
|
|
140
|
+
selection: readonly string[],
|
|
141
|
+
draftSkills?: unknown,
|
|
142
|
+
): SkillNarrowing {
|
|
143
|
+
const resolution = resolveSkillSource(prompt.skills, draftSkills)
|
|
144
|
+
if (selection.length === 0) {
|
|
145
|
+
return {
|
|
146
|
+
skillsFiltered: false,
|
|
147
|
+
skillsSource: resolution.skillsSource,
|
|
148
|
+
reason: 'selection.empty',
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
if (resolution.skillsSource !== 'prompt') {
|
|
152
|
+
return {
|
|
153
|
+
skillsFiltered: false,
|
|
154
|
+
skillsSource: resolution.skillsSource,
|
|
155
|
+
reason: resolution.reason,
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
if (resolution.skillIds.length === 0) {
|
|
159
|
+
return { skillsFiltered: false, skillsSource: 'prompt', reason: 'skills.source.unstable' }
|
|
160
|
+
}
|
|
161
|
+
const selected = new Set(selection)
|
|
162
|
+
const kept = (prompt.skills as readonly unknown[]).filter((item) => {
|
|
163
|
+
const identifier = skillIdentifier(item)
|
|
164
|
+
return identifier !== undefined && selected.has(identifier)
|
|
165
|
+
})
|
|
166
|
+
if (kept.length === 0) {
|
|
167
|
+
return { skillsFiltered: false, skillsSource: 'prompt', reason: 'skills.selection.disjoint' }
|
|
168
|
+
}
|
|
169
|
+
prompt.skills = kept
|
|
170
|
+
return { skillsFiltered: true, skillsSource: 'prompt', reason: 'skills.synthetic.narrowed' }
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function buildMarker(decision: TurnDecision): string | null {
|
|
174
|
+
const skillIds = decision.skillIds.filter((id) => isPantheonSkillId(id))
|
|
175
|
+
const agent = decision.agent !== null && isPantheonAgentId(decision.agent) ? decision.agent : null
|
|
176
|
+
if (skillIds.length === 0 && agent === null) return null
|
|
177
|
+
const parts = [`source=${decision.source}`]
|
|
178
|
+
if (skillIds.length > 0) parts.push(`skills=${skillIds.join(',')}`)
|
|
179
|
+
if (agent !== null) parts.push(`agent=${agent}`)
|
|
180
|
+
return `${MARKER_PREFIX} ${parts.join(' ')} -->`
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* Apply an advisory decision to the host prompt payload in place. It never
|
|
185
|
+
* dispatches, changes permissions, or removes a pre-existing host marker.
|
|
186
|
+
* `skillsDraft` is the per-turn draft list; it is observed for `skillsSource`
|
|
187
|
+
* and never applied to admission.
|
|
188
|
+
*/
|
|
189
|
+
export function applyTurnDecisionToPrompt(
|
|
190
|
+
prompt: unknown,
|
|
191
|
+
decision: TurnDecision | null,
|
|
192
|
+
skillsDraft?: unknown,
|
|
193
|
+
): PromptApplicationResult {
|
|
194
|
+
const invalid: PromptApplicationResult = {
|
|
195
|
+
markerApplied: false,
|
|
196
|
+
skillsFiltered: false,
|
|
197
|
+
skillsSource: 'none',
|
|
198
|
+
reason: 'invalid.payload',
|
|
199
|
+
}
|
|
200
|
+
if (prompt === null || typeof prompt !== 'object' || Array.isArray(prompt)) return invalid
|
|
201
|
+
if (decision === null || !decision.active) return { ...invalid, reason: 'decision.inactive' }
|
|
202
|
+
const target = prompt as Record<string, unknown>
|
|
203
|
+
const narrowing = narrowSkills(
|
|
204
|
+
target,
|
|
205
|
+
decision.skillIds.filter((id) => isPantheonSkillId(id)),
|
|
206
|
+
skillsDraft,
|
|
207
|
+
)
|
|
208
|
+
const result: PromptApplicationResult = {
|
|
209
|
+
markerApplied: false,
|
|
210
|
+
skillsFiltered: narrowing.skillsFiltered,
|
|
211
|
+
skillsSource: narrowing.skillsSource,
|
|
212
|
+
reason: narrowing.reason,
|
|
213
|
+
}
|
|
214
|
+
if (typeof target.text !== 'string' || target.text.includes(MARKER_PREFIX)) return result
|
|
215
|
+
const marker = buildMarker(decision)
|
|
216
|
+
if (marker === null) return result
|
|
217
|
+
target.text = `${target.text}\n\n${marker}`
|
|
218
|
+
return { ...result, markerApplied: true }
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** True when the prompt already carries a decision-router marker. */
|
|
222
|
+
export function hasDecisionRouterMarker(text: unknown): boolean {
|
|
223
|
+
return typeof text === 'string' && MARKER_PATTERN.test(text)
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* Compute and apply the advisory decision to a host admission payload. The
|
|
228
|
+
* optional `requestText` lets the caller keep Pantheon's own visual context out
|
|
229
|
+
* of the decision input; malformed payloads are a no-op.
|
|
230
|
+
*/
|
|
231
|
+
export async function applyDecisionRouterToPrompt(
|
|
232
|
+
admission: unknown,
|
|
233
|
+
permissionAssert?: TurnDecisionInput['permissionAssert'],
|
|
234
|
+
requestText?: string,
|
|
235
|
+
): Promise<PromptApplicationResult> {
|
|
236
|
+
const none = (reason: PromptApplicationReason): PromptApplicationResult => ({
|
|
237
|
+
markerApplied: false,
|
|
238
|
+
skillsFiltered: false,
|
|
239
|
+
skillsSource: 'none',
|
|
240
|
+
reason,
|
|
241
|
+
})
|
|
242
|
+
if (admission === null || typeof admission !== 'object' || Array.isArray(admission)) {
|
|
243
|
+
return none('invalid.payload')
|
|
244
|
+
}
|
|
245
|
+
const event = admission as { sessionID?: unknown; messageID?: unknown; prompt?: unknown }
|
|
246
|
+
const prompt = event.prompt
|
|
247
|
+
if (prompt === null || typeof prompt !== 'object' || Array.isArray(prompt)) {
|
|
248
|
+
return none('invalid.payload')
|
|
249
|
+
}
|
|
250
|
+
const promptText = (prompt as { text?: unknown }).text
|
|
251
|
+
if (typeof promptText !== 'string' || promptText.trim().length === 0) {
|
|
252
|
+
return none('request.empty')
|
|
253
|
+
}
|
|
254
|
+
const text =
|
|
255
|
+
typeof requestText === 'string' && requestText.trim().length > 0 ? requestText : promptText
|
|
256
|
+
if (hasDecisionRouterMarker(text)) return none('marker.present')
|
|
257
|
+
try {
|
|
258
|
+
const decision = await decideForTurn({
|
|
259
|
+
request: text,
|
|
260
|
+
sessionID: event.sessionID,
|
|
261
|
+
messageID: event.messageID,
|
|
262
|
+
permissionAssert,
|
|
263
|
+
})
|
|
264
|
+
return applyTurnDecisionToPrompt(prompt, decision)
|
|
265
|
+
} catch {
|
|
266
|
+
return none('invalid.payload')
|
|
267
|
+
}
|
|
268
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Private provider matrix: fixed provider/model/endpoint/credential rows and
|
|
3
|
+
* their ledger accounting mapping. No network I/O and no caller-supplied
|
|
4
|
+
* transport, config, env, or ledger.
|
|
5
|
+
*/
|
|
6
|
+
import {
|
|
7
|
+
DECISION_PROVIDER_BUDGET_MAPPING,
|
|
8
|
+
DECISION_ROUTER_MODELS,
|
|
9
|
+
} from '../../scripts/install/decision-router-config.mjs'
|
|
10
|
+
import type { BudgetProvider } from './local-decision-budget.ts'
|
|
11
|
+
|
|
12
|
+
export type DecisionProviderId =
|
|
13
|
+
| 'openai-decisions'
|
|
14
|
+
| 'typesafe-jev'
|
|
15
|
+
| 'opencode-console-jev'
|
|
16
|
+
| 'opencode-console-jev-free'
|
|
17
|
+
|
|
18
|
+
export type DecisionProtocol = 'openai' | 'systemone'
|
|
19
|
+
|
|
20
|
+
export const PROVIDER_MAX_RESPONSE_BYTES = 64 * 1024
|
|
21
|
+
export const PROVIDER_REQUEST_TIMEOUT_MS = 5_000
|
|
22
|
+
|
|
23
|
+
export interface DecisionProviderAdapter {
|
|
24
|
+
model: string
|
|
25
|
+
endpoint: string
|
|
26
|
+
credentialEnv: string
|
|
27
|
+
accountingProvider: BudgetProvider
|
|
28
|
+
egressEligible: boolean
|
|
29
|
+
protocol: DecisionProtocol
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const ADAPTER_DEFINITIONS: Readonly<
|
|
33
|
+
Record<
|
|
34
|
+
DecisionProviderId,
|
|
35
|
+
{
|
|
36
|
+
endpoint: string
|
|
37
|
+
credentialEnv: string
|
|
38
|
+
egressEligible: boolean
|
|
39
|
+
protocol: DecisionProtocol
|
|
40
|
+
}
|
|
41
|
+
>
|
|
42
|
+
> = Object.freeze({
|
|
43
|
+
'openai-decisions': {
|
|
44
|
+
endpoint: 'https://api.openai.com/v1/decisions',
|
|
45
|
+
credentialEnv: 'OPENAI_API_KEY',
|
|
46
|
+
egressEligible: true,
|
|
47
|
+
protocol: 'openai',
|
|
48
|
+
},
|
|
49
|
+
'typesafe-jev': {
|
|
50
|
+
endpoint: 'https://api.typesafe.ai/v1/systemone',
|
|
51
|
+
credentialEnv: 'TYPESAFE_API_KEY',
|
|
52
|
+
egressEligible: true,
|
|
53
|
+
protocol: 'systemone',
|
|
54
|
+
},
|
|
55
|
+
'opencode-console-jev': {
|
|
56
|
+
endpoint: 'https://opencode.ai/inference/systemone/v1/systemone',
|
|
57
|
+
credentialEnv: 'OPENCODE_API_KEY',
|
|
58
|
+
egressEligible: false,
|
|
59
|
+
protocol: 'systemone',
|
|
60
|
+
},
|
|
61
|
+
'opencode-console-jev-free': {
|
|
62
|
+
endpoint: 'https://opencode.ai/inference/systemone/v1/systemone',
|
|
63
|
+
credentialEnv: 'OPENCODE_API_KEY',
|
|
64
|
+
egressEligible: false,
|
|
65
|
+
protocol: 'systemone',
|
|
66
|
+
},
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* Single provider matrix. Model and accounting IDs come from the canonical
|
|
71
|
+
* config so the adapter and the ledger can never drift silently.
|
|
72
|
+
*/
|
|
73
|
+
export const DECISION_PROVIDER_ADAPTERS: Readonly<
|
|
74
|
+
Record<DecisionProviderId, DecisionProviderAdapter>
|
|
75
|
+
> = Object.freeze(
|
|
76
|
+
Object.fromEntries(
|
|
77
|
+
(Object.keys(ADAPTER_DEFINITIONS) as DecisionProviderId[]).map((provider) => {
|
|
78
|
+
const definition = ADAPTER_DEFINITIONS[provider]
|
|
79
|
+
const models = DECISION_ROUTER_MODELS[provider]
|
|
80
|
+
const model = models?.[0]
|
|
81
|
+
if (model === undefined) throw new Error(`Missing decision provider model: ${provider}`)
|
|
82
|
+
return [
|
|
83
|
+
provider,
|
|
84
|
+
Object.freeze({
|
|
85
|
+
...definition,
|
|
86
|
+
model,
|
|
87
|
+
accountingProvider: DECISION_PROVIDER_BUDGET_MAPPING[provider] as BudgetProvider,
|
|
88
|
+
}),
|
|
89
|
+
]
|
|
90
|
+
}),
|
|
91
|
+
) as Record<DecisionProviderId, DecisionProviderAdapter>,
|
|
92
|
+
)
|