pantheon-opencode 1.6.2-beta.5 → 1.6.2-beta.7
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 +35 -0
- package/README.md +40 -38
- package/README.pt-BR.md +9 -0
- package/package.json +2 -1
- package/plugin.json +1 -1
- package/pyproject.toml +1 -1
- package/scripts/decision-router-budget.mjs +4 -5
- package/scripts/decision-router.mjs +240 -1
- package/scripts/install/decision-router-config.mjs +4 -23
- package/src/agents/zeus.md +35 -65
- package/src/pantheon/jev-decision-tool.ts +336 -0
- package/src/pantheon/jev-decisions.ts +625 -0
- package/src/pantheon/local-decision-budget.ts +4 -1
- package/src/pantheon/local-decision-egress-gate.ts +16 -136
- package/src/pantheon/local-decision-prompt.ts +3 -9
- package/src/pantheon/local-decision-provider-matrix.ts +14 -62
- package/src/pantheon/local-decision-turn.ts +15 -252
- package/src/pantheon/local-decision-usage-evidence.internal.ts +80 -119
- package/src/pantheon/v2-decision-points/p8-guardrail.ts +3 -2
- package/src/pantheon/v2-decision-points.ts +1 -1
- package/src/pantheon/v2-native-decisions.ts +365 -0
- package/src/pantheon/v2-tools.ts +3 -0
- package/src/plugin-v2.ts +59 -15
- 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
- package/src/pantheon/local-decision-provider-protocol.ts +0 -335
- package/src/pantheon/local-decision-provider.internal.ts +0 -260
package/src/plugin-v2.ts
CHANGED
|
@@ -73,6 +73,11 @@
|
|
|
73
73
|
* If the SDK ever exposes these host domains, replacing `hostDomains` with the real
|
|
74
74
|
* type is a one-line change. Do NOT make that change while 1.18.x lacks them.
|
|
75
75
|
*
|
|
76
|
+
* The separate offline native Decisions scaffold is typed against
|
|
77
|
+
* `@opencode/plugin@2.2.5`. It intentionally has no production call site and
|
|
78
|
+
* does not claim native Decisions support for V1 or OpenCode V2.0/2.1. The
|
|
79
|
+
* legacy plugin registrations are not migrated as part of that scaffold.
|
|
80
|
+
*
|
|
76
81
|
* V2_UNSUPPORTED_FEATURES distinguishes adapter limitations from observed
|
|
77
82
|
* host-absent APIs; setup handles optional registrations on a best-effort basis.
|
|
78
83
|
*
|
|
@@ -110,6 +115,7 @@ import {
|
|
|
110
115
|
} from './pantheon/delegation-enforce.ts'
|
|
111
116
|
import { GOAL_LOOP_DEFAULTS, GoalStore } from './pantheon/goal-loop.ts'
|
|
112
117
|
import { createGuardPathResolver } from './pantheon/guard-path.ts'
|
|
118
|
+
import type { V2JevDecisionRuntime } from './pantheon/jev-decision-tool.ts'
|
|
113
119
|
import { DECISION_EGRESS_ACTION } from './pantheon/local-decision-egress-gate.ts'
|
|
114
120
|
import { applyDecisionRouterToPrompt } from './pantheon/local-decision-prompt.ts'
|
|
115
121
|
import { getSharedBoard } from './pantheon/shared-board.ts'
|
|
@@ -156,6 +162,7 @@ import {
|
|
|
156
162
|
} from './pantheon/v2-delegation-enforce.ts'
|
|
157
163
|
import { createV2ExecuteAfter, resolveV2SandboxConfig } from './pantheon/v2-execute-after.ts'
|
|
158
164
|
import { applyV2ModelOverrides, readV2ModelConfiguration } from './pantheon/v2-model-overrides.ts'
|
|
165
|
+
import type { NativeDecisionRequest } from './pantheon/v2-native-decisions.ts'
|
|
159
166
|
import { createV2ShellHooks, type V2ShellRunner } from './pantheon/v2-shell-hooks.ts'
|
|
160
167
|
import { createV2ToolDefinitions, type V2ToolResult } from './pantheon/v2-tools.ts'
|
|
161
168
|
import { V2_UNSUPPORTED_FEATURE_SEED } from './pantheon/v2-unsupported.mjs'
|
|
@@ -351,6 +358,16 @@ interface V2GenerateDomain {
|
|
|
351
358
|
text?: (input: { model: { providerID: string; id: string }; prompt: string }) => Promise<unknown>
|
|
352
359
|
}
|
|
353
360
|
|
|
361
|
+
/**
|
|
362
|
+
* The host's experimental generation domain. Only `decisions` is declared: the
|
|
363
|
+
* native Jev route feature-detects it, and every other member stays unknown.
|
|
364
|
+
*/
|
|
365
|
+
interface V2ExperimentalDomain {
|
|
366
|
+
generate?: {
|
|
367
|
+
decisions?: (request: NativeDecisionRequest) => Promise<unknown>
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
354
371
|
/** `PluginContext` plus the host domains 1.18.x omits. See the module header. */
|
|
355
372
|
interface HostPluginContext extends PluginContext {
|
|
356
373
|
tool?: V2ToolDomain
|
|
@@ -359,6 +376,7 @@ interface HostPluginContext extends PluginContext {
|
|
|
359
376
|
session?: V2SessionDomain
|
|
360
377
|
model?: V2ModelDomain
|
|
361
378
|
generate?: V2GenerateDomain
|
|
379
|
+
experimental?: V2ExperimentalDomain
|
|
362
380
|
location?: V2LocationDomain
|
|
363
381
|
}
|
|
364
382
|
|
|
@@ -669,20 +687,53 @@ async function registerV2Tools(
|
|
|
669
687
|
// it, and the host rejects a definition whose result shape cannot satisfy
|
|
670
688
|
// the declaration it makes.
|
|
671
689
|
const model = host.model
|
|
672
|
-
const
|
|
690
|
+
const modelListFn = model?.list
|
|
691
|
+
const visionReady = typeof modelListFn === 'function'
|
|
673
692
|
if (!visionReady) markUnsupported('vision-tool')
|
|
674
693
|
const visionRuntime = visionReady ? ({ model } as V2VisionRuntime) : undefined
|
|
694
|
+
// The native Jev tool needs BOTH the V2 model catalog (route resolution)
|
|
695
|
+
// and the host's native Decisions API. A host without either simply does
|
|
696
|
+
// not get the tool — same feature-detect discipline as vision_describe.
|
|
697
|
+
const decisionsFn = host.experimental?.generate?.decisions
|
|
698
|
+
const jevReady = visionReady && typeof decisionsFn === 'function'
|
|
699
|
+
if (!jevReady) markUnsupported('jev-decision-tool')
|
|
700
|
+
const permissionAssertFn = host.permission?.assert
|
|
701
|
+
let jevRuntime: V2JevDecisionRuntime | undefined
|
|
702
|
+
if (jevReady && typeof decisionsFn === 'function' && typeof modelListFn === 'function') {
|
|
703
|
+
const decide = decisionsFn
|
|
704
|
+
const listModels = modelListFn
|
|
705
|
+
// The 2.2.5 host exposes ctx.skill as the SkillEditor (list()); the SDK
|
|
706
|
+
// types this file sees declare skill as the registration hook, so the
|
|
707
|
+
// runtime shape is read through one narrow, feature-detected cast.
|
|
708
|
+
const skillList = (host as { skill?: { list?: () => unknown } }).skill?.list
|
|
709
|
+
const permissionAssert =
|
|
710
|
+
typeof permissionAssertFn === 'function'
|
|
711
|
+
? (input: Record<string, unknown>) => permissionAssertFn.call(host.permission, input)
|
|
712
|
+
: undefined
|
|
713
|
+
jevRuntime = {
|
|
714
|
+
listModels: () => listModels(),
|
|
715
|
+
decide: (request: NativeDecisionRequest) => decide(request),
|
|
716
|
+
// Sync-or-async host skill list; absent/throwing falls back to the
|
|
717
|
+
// catalog-only preset inside the tool.
|
|
718
|
+
listSkills: async () => skillList?.(),
|
|
719
|
+
...(permissionAssert === undefined ? {} : { permissionAssert }),
|
|
720
|
+
}
|
|
721
|
+
}
|
|
675
722
|
// P3 (complexity) declares `tool.invoke`; its construction site is the
|
|
676
723
|
// local selector's execute, fed by that tool's own input schema. The sink
|
|
677
724
|
// is the 0b record path (in-memory, bounded, I/O-free) and every record
|
|
678
725
|
// carries `mode: 'shadow'` — the mode the registry declares.
|
|
679
726
|
const p3Sink = createTelemetrySink()
|
|
680
727
|
p3TelemetrySink = p3Sink
|
|
681
|
-
const toolDefs = createV2ToolDefinitions(
|
|
682
|
-
|
|
683
|
-
|
|
728
|
+
const toolDefs = createV2ToolDefinitions(
|
|
729
|
+
visionRuntime,
|
|
730
|
+
{
|
|
731
|
+
complexitySink: (record) => {
|
|
732
|
+
p3Sink.emit({ ...record, mode: 'shadow' })
|
|
733
|
+
},
|
|
684
734
|
},
|
|
685
|
-
|
|
735
|
+
jevRuntime,
|
|
736
|
+
)
|
|
686
737
|
if (boundedRead !== undefined) toolDefs.push(boundedRead)
|
|
687
738
|
|
|
688
739
|
// P11's record sink, created per registration (in-memory, bounded, I/O-free).
|
|
@@ -1204,12 +1255,6 @@ async function registerV2SessionHooks(context: PluginContext): Promise<boolean>
|
|
|
1204
1255
|
warnContextPrunerConfigOnce(context.options)
|
|
1205
1256
|
const host = hostDomains(context)
|
|
1206
1257
|
const sessionCtx = host.session
|
|
1207
|
-
const permission = host.permission
|
|
1208
|
-
const assertPermission = permission?.assert
|
|
1209
|
-
const permissionAssert =
|
|
1210
|
-
typeof assertPermission === 'function'
|
|
1211
|
-
? (input: Record<string, unknown>) => assertPermission.call(permission, input)
|
|
1212
|
-
: undefined
|
|
1213
1258
|
|
|
1214
1259
|
if (!sessionCtx?.hook) {
|
|
1215
1260
|
return false
|
|
@@ -1331,10 +1376,9 @@ async function registerV2SessionHooks(context: PluginContext): Promise<boolean>
|
|
|
1331
1376
|
if (visualContext) prompt.text = `${prompt.text}\n\n${visualContext}`
|
|
1332
1377
|
}
|
|
1333
1378
|
|
|
1334
|
-
//
|
|
1335
|
-
//
|
|
1336
|
-
|
|
1337
|
-
await applyDecisionRouterToPrompt(admission, permissionAssert, userRequest)
|
|
1379
|
+
// Local deterministic recommendations are advisory only. This path
|
|
1380
|
+
// never consults provider consent/credentials or invokes remote egress.
|
|
1381
|
+
await applyDecisionRouterToPrompt(admission, userRequest)
|
|
1338
1382
|
|
|
1339
1383
|
// Shadow observation only. The projection carries `prompt.agents` and
|
|
1340
1384
|
// `prompt.skills` and nothing else, so no prompt text or file bytes
|
|
@@ -5022,7 +5022,7 @@ function QuotaPluginDetails(props) {
|
|
|
5022
5022
|
setProp(_el$58, "paddingTop", 1);
|
|
5023
5023
|
insertNode(_el$59, createTextNode(`Plugin`));
|
|
5024
5024
|
setProp(_el$59, "attributes", 1);
|
|
5025
|
-
insert(_el$61, `Pantheon TUI v1.6.2-beta.
|
|
5025
|
+
insert(_el$61, `Pantheon TUI v1.6.2-beta.7`);
|
|
5026
5026
|
insertNode(_el$62, createTextNode(`Status de conexão consultado pelo OpenCode; segredos não são exibidos.`));
|
|
5027
5027
|
insert(_el$64, () => `Status da quota: ${quotaSnapshotStatusLabel(props.snapshot.status, props.snapshot.error)}`);
|
|
5028
5028
|
insert(_el$58, createComponent(Show, {
|
|
@@ -8300,7 +8300,7 @@ function Sidebar(props) {
|
|
|
8300
8300
|
setProp(_el$12, "width", "100%");
|
|
8301
8301
|
setProp(_el$12, "padding", 1);
|
|
8302
8302
|
setProp(_el$13, "attributes", 1);
|
|
8303
|
-
insert(_el$13, `Pantheon v1.6.2-beta.
|
|
8303
|
+
insert(_el$13, `Pantheon v1.6.2-beta.7`);
|
|
8304
8304
|
insert(_el$14, () => presetHeaderLine(model.preset().name ?? "", model.provider()));
|
|
8305
8305
|
insert(_el$12, createComponent(Show, {
|
|
8306
8306
|
get when() {
|
|
@@ -9027,7 +9027,7 @@ function HomeStatus(props) {
|
|
|
9027
9027
|
const muted = () => props.context.theme?.text?.muted ?? props.context.theme?.text?.base;
|
|
9028
9028
|
return (() => {
|
|
9029
9029
|
var _el$72 = createElement("text");
|
|
9030
|
-
insert(_el$72, () => `Pantheon v1.6.2-beta.
|
|
9030
|
+
insert(_el$72, () => `Pantheon v1.6.2-beta.7${preset().name ? ` ▸ ${preset().name}` : ""}`);
|
|
9031
9031
|
effect((_$p) => setProp(_el$72, "fg", muted(), _$p));
|
|
9032
9032
|
return _el$72;
|
|
9033
9033
|
})();
|
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pantheon-tui",
|
|
3
|
-
"version": "1.6.2-beta.
|
|
3
|
+
"version": "1.6.2-beta.7",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "pantheon-tui",
|
|
9
|
-
"version": "1.6.2-beta.
|
|
9
|
+
"version": "1.6.2-beta.7",
|
|
10
10
|
"license": "MIT",
|
|
11
11
|
"dependencies": {
|
|
12
12
|
"@opencode-ai/plugin": "1.18.33",
|
|
@@ -1,335 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Private provider protocol: payload construction, fixed request bodies, and
|
|
3
|
-
* strict response decoding. This module performs no network I/O and accepts no
|
|
4
|
-
* fetch, env, config, or ledger.
|
|
5
|
-
*/
|
|
6
|
-
import {
|
|
7
|
-
DECISION_PROVIDER_ADAPTERS,
|
|
8
|
-
type DecisionProtocol,
|
|
9
|
-
type DecisionProviderId,
|
|
10
|
-
} from './local-decision-provider-matrix.ts'
|
|
11
|
-
import {
|
|
12
|
-
agentCatalogSubset,
|
|
13
|
-
isPantheonAgentId,
|
|
14
|
-
isPantheonSkillId,
|
|
15
|
-
skillCatalogSubset,
|
|
16
|
-
} from './pantheon-decision-catalog.ts'
|
|
17
|
-
|
|
18
|
-
const MAX_REQUEST_LENGTH = 12_000
|
|
19
|
-
const MIN_CONFIDENCE = 0.8
|
|
20
|
-
/**
|
|
21
|
-
* Best-effort rejection of high-confidence credential shapes. This is a
|
|
22
|
-
* denylist, not a secret scanner: an unrecognized credential can still be sent
|
|
23
|
-
* with the request text, so prompts must not contain secrets in the first
|
|
24
|
-
* place. The `sk-` family requires a token boundary and a structured prefix
|
|
25
|
-
* (`sk-proj-`, `sk-svcacct-`, `sk-admin-`, `sk-ant-…-`) or a long bare token, so
|
|
26
|
-
* prose such as `task-force-…`, `risk-based-…`, `disk-usage-…`,
|
|
27
|
-
* `desk-organization-…`, or `mask-generation-…` is not mistaken for a key.
|
|
28
|
-
* Also covers Stripe, cloud/SaaS tokens, JWTs, bearer values, and
|
|
29
|
-
* `password=`/`api_key=` assignments.
|
|
30
|
-
*/
|
|
31
|
-
const SECRET_PATTERN = new RegExp(
|
|
32
|
-
[
|
|
33
|
-
'(?<![A-Za-z0-9])sk-(?:proj-|svcacct-|admin-|ant-[a-z0-9]+-)?[A-Za-z0-9]{20,}',
|
|
34
|
-
'sk_live_[A-Za-z0-9]{20,}',
|
|
35
|
-
'sk_test_[A-Za-z0-9]{20,}',
|
|
36
|
-
'rk_live_[A-Za-z0-9]{20,}',
|
|
37
|
-
'AKIA[0-9A-Z]{16}',
|
|
38
|
-
'gh[pousr]_[A-Za-z0-9_]{36,}',
|
|
39
|
-
'glpat-[A-Za-z0-9_-]{20}',
|
|
40
|
-
'xox[baprs]-[0-9]{10,13}-[0-9]{10,13}-[a-zA-Z0-9]{24}',
|
|
41
|
-
'bearer[ \t]+[A-Za-z0-9_.-]{20,}',
|
|
42
|
-
'eyJ[A-Za-z0-9_-]*\\.eyJ[A-Za-z0-9_-]*\\.[A-Za-z0-9_-]*',
|
|
43
|
-
'(?:password|passwd|pwd|api[_-]?key|apikey|client[_-]?secret|secret[_-]?key|access[_-]?token|auth[_-]?token)[ \\t]*[:=][ \\t]*[\'"]?[^\\s\'"&]{8,}',
|
|
44
|
-
].join('|'),
|
|
45
|
-
'i',
|
|
46
|
-
)
|
|
47
|
-
export interface DecisionPayload {
|
|
48
|
-
request: string
|
|
49
|
-
skills: Array<{ id: string; description: string }>
|
|
50
|
-
agents?: Array<{ id: string; description: string }>
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
export interface DecisionPayloadInput {
|
|
54
|
-
request: unknown
|
|
55
|
-
skillIds: readonly string[]
|
|
56
|
-
agentIds?: readonly string[]
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
/**
|
|
60
|
-
* Build the only authorized provider payload: the current user request plus a
|
|
61
|
-
* short allowlisted skill catalog, and eligible agent IDs only when delegation
|
|
62
|
-
* is under consideration. Transcripts, files, paths, memory, and instructions
|
|
63
|
-
* are rejected by construction.
|
|
64
|
-
*/
|
|
65
|
-
export function buildDecisionPayload(input: DecisionPayloadInput): DecisionPayload | null {
|
|
66
|
-
try {
|
|
67
|
-
const request =
|
|
68
|
-
typeof input.request === 'string' && input.request.trim().length > 0
|
|
69
|
-
? input.request.trim()
|
|
70
|
-
: ''
|
|
71
|
-
if (request.length === 0 || request.length > MAX_REQUEST_LENGTH) return null
|
|
72
|
-
if (SECRET_PATTERN.test(request)) return null
|
|
73
|
-
if (!Array.isArray(input.skillIds) || input.skillIds.length === 0) return null
|
|
74
|
-
if (new Set(input.skillIds).size !== input.skillIds.length) return null
|
|
75
|
-
if (!input.skillIds.every((id) => isPantheonSkillId(id))) return null
|
|
76
|
-
const skills = skillCatalogSubset(input.skillIds)
|
|
77
|
-
if (skills.length !== input.skillIds.length) return null
|
|
78
|
-
|
|
79
|
-
if (input.agentIds === undefined) return { request, skills }
|
|
80
|
-
if (!Array.isArray(input.agentIds) || input.agentIds.length === 0) return null
|
|
81
|
-
if (new Set(input.agentIds).size !== input.agentIds.length) return null
|
|
82
|
-
if (!input.agentIds.every((id) => id !== 'zeus' && isPantheonAgentId(id))) return null
|
|
83
|
-
const agents = agentCatalogSubset(input.agentIds)
|
|
84
|
-
if (agents.length !== input.agentIds.length) return null
|
|
85
|
-
return { request, skills, agents }
|
|
86
|
-
} catch {
|
|
87
|
-
return null
|
|
88
|
-
}
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
interface ChoiceQuestion {
|
|
92
|
-
name: 'skill' | 'agent'
|
|
93
|
-
choices: string[]
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
function createQuestions(payload: DecisionPayload): ChoiceQuestion[] {
|
|
97
|
-
const questions: ChoiceQuestion[] = [
|
|
98
|
-
{ name: 'skill', choices: [...payload.skills.map((skill) => skill.id), 'abstain'] },
|
|
99
|
-
]
|
|
100
|
-
if (payload.agents !== undefined) {
|
|
101
|
-
questions.push({
|
|
102
|
-
name: 'agent',
|
|
103
|
-
choices: [...payload.agents.map((agent) => agent.id), 'abstain'],
|
|
104
|
-
})
|
|
105
|
-
}
|
|
106
|
-
return questions
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
/** Build the fixed provider request body for one adapter. */
|
|
110
|
-
export function buildProviderRequest(
|
|
111
|
-
provider: DecisionProviderId,
|
|
112
|
-
payload: DecisionPayload,
|
|
113
|
-
): Record<string, unknown> | null {
|
|
114
|
-
const adapter = DECISION_PROVIDER_ADAPTERS[provider]
|
|
115
|
-
if (adapter === undefined || !adapter.egressEligible) return null
|
|
116
|
-
const questions = createQuestions(payload)
|
|
117
|
-
if (questions.length === 0) return null
|
|
118
|
-
|
|
119
|
-
if (adapter.protocol === 'openai') {
|
|
120
|
-
return {
|
|
121
|
-
model: adapter.model,
|
|
122
|
-
input: [
|
|
123
|
-
{
|
|
124
|
-
role: 'user',
|
|
125
|
-
content: [{ type: 'input_json', data: payload }],
|
|
126
|
-
},
|
|
127
|
-
],
|
|
128
|
-
questions: questions.map((question) => ({
|
|
129
|
-
type: 'choice',
|
|
130
|
-
name: question.name,
|
|
131
|
-
instructions:
|
|
132
|
-
question.name === 'skill'
|
|
133
|
-
? 'Choose one supplied skill ID, or choose abstain.'
|
|
134
|
-
: 'Choose one supplied specialist ID, or choose abstain.',
|
|
135
|
-
choices: question.choices.map((value) => ({ value, description: value })),
|
|
136
|
-
})),
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
return {
|
|
141
|
-
model: adapter.model,
|
|
142
|
-
state: payload,
|
|
143
|
-
questions: Object.fromEntries(
|
|
144
|
-
questions.map((question) => [
|
|
145
|
-
question.name,
|
|
146
|
-
{
|
|
147
|
-
type: 'choice',
|
|
148
|
-
instructions:
|
|
149
|
-
question.name === 'skill'
|
|
150
|
-
? 'Choose one supplied skill ID, or choose abstain.'
|
|
151
|
-
: 'Choose one supplied specialist ID, or choose abstain.',
|
|
152
|
-
criteria: Object.fromEntries(question.choices.map((choice) => [choice, choice])),
|
|
153
|
-
},
|
|
154
|
-
]),
|
|
155
|
-
),
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
export type ProviderDecision =
|
|
160
|
-
| { status: 'decided'; skillIds: string[]; agent: string | null }
|
|
161
|
-
| { status: 'abstain'; reasonCode: 'PROVIDER_ABSTAIN' }
|
|
162
|
-
| { status: 'invalid'; reasonCode: 'INVALID_PROVIDER_RESPONSE' }
|
|
163
|
-
|
|
164
|
-
interface DecodedAnswer {
|
|
165
|
-
choice: string | null
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
function parseProbabilities(
|
|
169
|
-
value: unknown,
|
|
170
|
-
choices: readonly string[],
|
|
171
|
-
protocol: DecisionProtocol,
|
|
172
|
-
): { selected: string; max: number } | null {
|
|
173
|
-
let entries: Array<[string, unknown]>
|
|
174
|
-
if (protocol === 'openai' && Array.isArray(value)) {
|
|
175
|
-
if (value.length !== choices.length) return null
|
|
176
|
-
const seen = new Set<string>()
|
|
177
|
-
entries = []
|
|
178
|
-
for (const item of value) {
|
|
179
|
-
if (!isPlainRecord(item) || !hasExactKeys(item, ['probability', 'value'])) return null
|
|
180
|
-
if (typeof item.value !== 'string' || !choices.includes(item.value) || seen.has(item.value)) {
|
|
181
|
-
return null
|
|
182
|
-
}
|
|
183
|
-
seen.add(item.value)
|
|
184
|
-
entries.push([item.value, item.probability])
|
|
185
|
-
}
|
|
186
|
-
if (seen.size !== choices.length) return null
|
|
187
|
-
} else if (protocol === 'systemone' && isPlainRecord(value)) {
|
|
188
|
-
const keys = Object.keys(value).sort()
|
|
189
|
-
const expected = [...choices].sort()
|
|
190
|
-
if (keys.length !== expected.length || keys.some((key, index) => key !== expected[index])) {
|
|
191
|
-
return null
|
|
192
|
-
}
|
|
193
|
-
entries = keys.map((key) => [key, value[key]])
|
|
194
|
-
} else {
|
|
195
|
-
return null
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
let total = 0
|
|
199
|
-
let selected = ''
|
|
200
|
-
let maximum = -1
|
|
201
|
-
let maximumCount = 0
|
|
202
|
-
for (const [choice, probability] of entries) {
|
|
203
|
-
if (
|
|
204
|
-
typeof probability !== 'number' ||
|
|
205
|
-
!Number.isFinite(probability) ||
|
|
206
|
-
probability < 0 ||
|
|
207
|
-
probability > 1
|
|
208
|
-
) {
|
|
209
|
-
return null
|
|
210
|
-
}
|
|
211
|
-
total += probability
|
|
212
|
-
if (probability > maximum) {
|
|
213
|
-
maximum = probability
|
|
214
|
-
selected = choice
|
|
215
|
-
maximumCount = 1
|
|
216
|
-
} else if (probability === maximum) {
|
|
217
|
-
maximumCount += 1
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
if (Math.abs(total - 1) > 1e-6 || maximumCount !== 1) return null
|
|
221
|
-
return { selected, max: maximum }
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
function decodeAnswer(
|
|
225
|
-
value: unknown,
|
|
226
|
-
question: ChoiceQuestion,
|
|
227
|
-
protocol: DecisionProtocol,
|
|
228
|
-
): DecodedAnswer | null {
|
|
229
|
-
if (!isPlainRecord(value)) return null
|
|
230
|
-
if (value.type === 'refusal') {
|
|
231
|
-
if (protocol !== 'openai' || !hasExactKeys(value, ['name', 'type'])) return null
|
|
232
|
-
return value.name === question.name ? { choice: null } : null
|
|
233
|
-
}
|
|
234
|
-
const keys =
|
|
235
|
-
protocol === 'openai'
|
|
236
|
-
? ['choice', 'confidence', 'name', 'probabilities', 'type']
|
|
237
|
-
: ['choice', 'confidence', 'probabilities', 'type']
|
|
238
|
-
if (
|
|
239
|
-
!hasExactKeys(value, keys) ||
|
|
240
|
-
value.type !== 'choice' ||
|
|
241
|
-
(protocol === 'openai' && value.name !== question.name) ||
|
|
242
|
-
typeof value.choice !== 'string' ||
|
|
243
|
-
!question.choices.includes(value.choice) ||
|
|
244
|
-
typeof value.confidence !== 'number' ||
|
|
245
|
-
!Number.isFinite(value.confidence) ||
|
|
246
|
-
value.confidence < 0 ||
|
|
247
|
-
value.confidence > 1
|
|
248
|
-
) {
|
|
249
|
-
return null
|
|
250
|
-
}
|
|
251
|
-
const distribution = parseProbabilities(value.probabilities, question.choices, protocol)
|
|
252
|
-
if (distribution === null || distribution.selected !== value.choice) return null
|
|
253
|
-
if (value.choice === 'abstain') return { choice: null }
|
|
254
|
-
if (value.confidence < MIN_CONFIDENCE || distribution.max < MIN_CONFIDENCE) {
|
|
255
|
-
return { choice: null }
|
|
256
|
-
}
|
|
257
|
-
return { choice: value.choice }
|
|
258
|
-
}
|
|
259
|
-
|
|
260
|
-
/**
|
|
261
|
-
* Decode only documented answer fields. IDs must be exactly the supplied
|
|
262
|
-
* candidates; the model cannot introduce, grant, or dispatch anything.
|
|
263
|
-
*/
|
|
264
|
-
export function parseProviderDecision(
|
|
265
|
-
provider: DecisionProviderId,
|
|
266
|
-
response: unknown,
|
|
267
|
-
payload: DecisionPayload,
|
|
268
|
-
): ProviderDecision {
|
|
269
|
-
try {
|
|
270
|
-
const adapter = DECISION_PROVIDER_ADAPTERS[provider]
|
|
271
|
-
if (adapter === undefined || !isPlainRecord(response) || response.model !== adapter.model) {
|
|
272
|
-
return { status: 'invalid', reasonCode: 'INVALID_PROVIDER_RESPONSE' }
|
|
273
|
-
}
|
|
274
|
-
const questions = createQuestions(payload)
|
|
275
|
-
const answers = new Map<ChoiceQuestion['name'], DecodedAnswer>()
|
|
276
|
-
|
|
277
|
-
if (adapter.protocol === 'openai') {
|
|
278
|
-
const rawAnswers = response.answers
|
|
279
|
-
if (!Array.isArray(rawAnswers) || rawAnswers.length !== questions.length) {
|
|
280
|
-
return { status: 'invalid', reasonCode: 'INVALID_PROVIDER_RESPONSE' }
|
|
281
|
-
}
|
|
282
|
-
for (const [index, question] of questions.entries()) {
|
|
283
|
-
const decoded = decodeAnswer(rawAnswers[index], question, 'openai')
|
|
284
|
-
if (decoded === null) return { status: 'invalid', reasonCode: 'INVALID_PROVIDER_RESPONSE' }
|
|
285
|
-
answers.set(question.name, decoded)
|
|
286
|
-
}
|
|
287
|
-
} else {
|
|
288
|
-
const rawAnswers = response.answers
|
|
289
|
-
if (
|
|
290
|
-
!isPlainRecord(rawAnswers) ||
|
|
291
|
-
!hasExactKeys(
|
|
292
|
-
rawAnswers,
|
|
293
|
-
questions.map((question) => question.name),
|
|
294
|
-
)
|
|
295
|
-
) {
|
|
296
|
-
return { status: 'invalid', reasonCode: 'INVALID_PROVIDER_RESPONSE' }
|
|
297
|
-
}
|
|
298
|
-
for (const question of questions) {
|
|
299
|
-
const decoded = decodeAnswer(rawAnswers[question.name], question, 'systemone')
|
|
300
|
-
if (decoded === null) return { status: 'invalid', reasonCode: 'INVALID_PROVIDER_RESPONSE' }
|
|
301
|
-
answers.set(question.name, decoded)
|
|
302
|
-
}
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
const skill = answers.get('skill')?.choice ?? null
|
|
306
|
-
const agent = answers.get('agent')?.choice ?? null
|
|
307
|
-
if (skill !== null && !payload.skills.some((entry) => entry.id === skill)) {
|
|
308
|
-
return { status: 'invalid', reasonCode: 'INVALID_PROVIDER_RESPONSE' }
|
|
309
|
-
}
|
|
310
|
-
if (agent !== null && !(payload.agents ?? []).some((entry) => entry.id === agent)) {
|
|
311
|
-
return { status: 'invalid', reasonCode: 'INVALID_PROVIDER_RESPONSE' }
|
|
312
|
-
}
|
|
313
|
-
if (skill === null && agent === null) {
|
|
314
|
-
return { status: 'abstain', reasonCode: 'PROVIDER_ABSTAIN' }
|
|
315
|
-
}
|
|
316
|
-
return { status: 'decided', skillIds: skill === null ? [] : [skill], agent }
|
|
317
|
-
} catch {
|
|
318
|
-
return { status: 'invalid', reasonCode: 'INVALID_PROVIDER_RESPONSE' }
|
|
319
|
-
}
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
function isPlainRecord(value: unknown): value is Record<string, unknown> {
|
|
323
|
-
if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
|
|
324
|
-
const prototype = Object.getPrototypeOf(value)
|
|
325
|
-
return prototype === Object.prototype || prototype === null
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
function hasExactKeys(value: Record<string, unknown>, expectedKeys: readonly string[]): boolean {
|
|
329
|
-
const actualKeys = Object.keys(value).sort()
|
|
330
|
-
const expected = [...expectedKeys].sort()
|
|
331
|
-
return (
|
|
332
|
-
actualKeys.length === expected.length &&
|
|
333
|
-
actualKeys.every((key, index) => key === expected[index])
|
|
334
|
-
)
|
|
335
|
-
}
|