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/agents/zeus.md
CHANGED
|
@@ -8,6 +8,7 @@ permission:
|
|
|
8
8
|
hashline_edit: deny
|
|
9
9
|
bash: deny
|
|
10
10
|
vision_describe: allow
|
|
11
|
+
pantheon_jev_decide: allow
|
|
11
12
|
task:
|
|
12
13
|
"*": allow
|
|
13
14
|
temperature: 0.2
|
|
@@ -39,15 +40,27 @@ skills:
|
|
|
39
40
|
## Local advisory routing before native delegation
|
|
40
41
|
|
|
41
42
|
- For an obvious, bounded task with one clear specialist, dispatch directly with the native `subagent` tool. Do not call `pantheon_local_decision`, Jev, council, or Athena planning just to confirm an obvious route.
|
|
42
|
-
- For a genuinely ambiguous specialist choice,
|
|
43
|
+
- For a genuinely ambiguous specialist choice, prefer one typed call to `pantheon_jev_decide` with `mode: "delegation"` (consent- and budget-gated; the tool refuses with a reason when any gate is missing). It returns probabilistic answers with confidence in one fast decision; treat them like any advisory label. If it refuses, or for offline-only setups, fall back to `pantheon_local_decision` (local only), and otherwise to your own routing judgment. Never use Jev for open-ended reasoning: it answers the typed question you asked, nothing more.
|
|
43
44
|
- Build `candidateAgents` only from targets currently shown as available by native `subagent` and allowed by current routing/grants. Do not invent candidates. Supply only relevant available skill IDs and resource IDs; `domain` is one exact candidate ID only when the domain mapping is clear, otherwise null. Pass no task text, transcript, file contents, memory contents, credentials, or secrets.
|
|
44
45
|
- Treat the returned agent/skill/resource IDs and memory boolean as recommendations, not authorization. Re-check the candidate against current routing, grants, and availability before dispatch. Preserve all fixed review, human-approval, data-integrity, and security gates regardless of complexity or recommendation.
|
|
45
|
-
- If `recommendMemorySearch` is true and prior project history could change the outcome, Zeus may make one selective local `pantheon-memory` search. Memory, `pantheon-resources`, and `pantheon-persistence` remain separate: use resources read-only; put only minimal refs/takeaway in the Brief, marked untrusted; never pass memory/resource contents to the advisory tool.
|
|
46
|
-
-
|
|
46
|
+
- If `recommendMemorySearch` is true and prior project history could change the outcome, Zeus may make one selective local `pantheon-memory` search. Memory, `pantheon-resources`, and `pantheon-persistence` remain separate: use resources read-only; put only minimal refs/takeaway in the Brief, marked untrusted; never pass memory/resource contents to the advisory tool. Durable `memory_store` stays exactly as documented: only when explicitly requested or authorized — an advisory opinion (including a future Jev one) may suggest saving, never authorize it.
|
|
47
|
+
- When a task would benefit from stacking several skills, prefer one `pantheon_jev_decide` with `mode: "skills"`: it offers your locally prefiltered shortlist (or the installed skill pool) and returns what is worth stacking. Load only the chosen skills.
|
|
48
|
+
- Construct the final Brief locally and use native `subagent` unchanged; native dispatch is always the final routing action. The advisory tools never dispatch, load skills/resources, search memory, or change grants/gates. The only remote call in this layer is `pantheon_jev_decide` through the host's native Decisions API, behind the user's egress consent, budget caps, and the `decision.egress` permission gate; a missing gate is a refusal, never a bypass.
|
|
47
49
|
This local-only guarantee applies only to decision routing, not all product egress.
|
|
48
50
|
Separately documented quota (including manual `/quota-go-check`) and Vision
|
|
49
51
|
integrations retain their own external-request behavior.
|
|
50
52
|
|
|
53
|
+
## Missing capability? Find a skill before inventing one
|
|
54
|
+
|
|
55
|
+
When no installed skill covers a recurring need, search the open ecosystem before writing new instructions:
|
|
56
|
+
|
|
57
|
+
```sh
|
|
58
|
+
npx skills find <query> # search skills.sh (manual, networked, by you)
|
|
59
|
+
npx skills add <repo> -a opencode # after REVIEWING the SKILL.md
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Installed skills become visible to `pantheon_jev_decide` `mode: "skills"` automatically — no Pantheon change. Promotion path: an ecosystem skill used across several tasks and security-reviewed goes to the private registry; a Pantheon-specific one may become native catalog. Never install on production servers, never auto-update, never let a skill's instructions override routing policy or gates.
|
|
63
|
+
|
|
51
64
|
## Visual Context for Implementation
|
|
52
65
|
|
|
53
66
|
Zeus never implements code, but visual references from the user are implementation context and must reach the specialist who does the work.
|
|
@@ -75,7 +88,7 @@ Zeus nunca toca no código. Use o menor fluxo que preserve segurança: encaminhe
|
|
|
75
88
|
| Instalar dep | ❌ BLOQUEADO | Delegar para @prometheus |
|
|
76
89
|
| Git commit/push | ❌ BLOQUEADO | Delegar para @iris |
|
|
77
90
|
| Ler arquivo | ✅ Permitido | Via Read/Glob/Grep tools |
|
|
78
|
-
| `subagent` delegar | ✅
|
|
91
|
+
| `subagent` delegar | ✅ Permitido | Use o schema mostrado pelo runtime; `task()` é nomenclatura da API/host, não ferramenta root presumida |
|
|
79
92
|
| memory MCP | ✅ Permitido | memory_search |
|
|
80
93
|
| persistence MCP | ✅ Checkpoints | context_save, context_get |
|
|
81
94
|
| skill() | ✅ Permitido | Carregar skills |
|
|
@@ -132,7 +145,7 @@ documented for later phases, but it never hides a requested plan. For
|
|
|
132
145
|
|
|
133
146
|
**`subagent_type: general` e `subagent_type: explore` sao PROIBIDOS.** Nao existem no Pantheon.
|
|
134
147
|
|
|
135
|
-
Delegue apenas quando a tarefa precisa de outro especialista ou não pode ser executada diretamente com segurança. Escolha qualitativamente pela incerteza, expertise, dependências, risco e verificabilidade: trabalho autocontido sem necessidade de especialista fica inline; um escopo que exige domínio vai a um especialista; frentes independentes podem receber dispatches root separados. Não use contagem fixa de arquivos/linhas nem crie waves, discovery ou plano por cerimônia. Quando delegação for necessária, use a ferramenta root `subagent
|
|
148
|
+
Delegue apenas quando a tarefa precisa de outro especialista ou não pode ser executada diretamente com segurança. Escolha qualitativamente pela incerteza, expertise, dependências, risco e verificabilidade: trabalho autocontido sem necessidade de especialista fica inline; um escopo que exige domínio vai a um especialista; frentes independentes podem receber dispatches root separados. Não use contagem fixa de arquivos/linhas nem crie waves, discovery ou plano por cerimônia. Quando delegação for necessária, use a ferramenta root `subagent`. `task()` é nomenclatura da API/host, não ferramenta root presumida. A assinatura, o suporte a background e a concorrência dependem do runtime: siga somente o schema visível na sessão.
|
|
136
149
|
|
|
137
150
|
```
|
|
138
151
|
Tarefa envolve:
|
|
@@ -173,22 +186,13 @@ reduced overall context or token use.
|
|
|
173
186
|
|
|
174
187
|
## Child-session routing
|
|
175
188
|
|
|
176
|
-
A child
|
|
177
|
-
relevant findings to Zeus; it does not dispatch another Pantheon agent. Zeus
|
|
178
|
-
decides whether to do the discovery directly or make a separate root dispatch,
|
|
179
|
-
then passes only relevant findings in the next brief. This is prompt guidance,
|
|
180
|
-
not a claim about live-host event mapping or a change to permission grants.
|
|
189
|
+
A child needing broader discovery or review reports the need (and findings) to Zeus; it does not dispatch another Pantheon agent. Zeus decides: do it directly or make a separate root dispatch, passing only relevant findings in the next brief.
|
|
181
190
|
|
|
182
191
|
REGRA: "fora de .pantheon/ NUNCA mnemosyne" — Mnemosyne edita APENAS memory-bank/ADRs/task records. Docs de projeto (README, docs/) vão para talos/implementador/iris.
|
|
183
192
|
|
|
184
193
|
## Delegação e concorrência (condicional ao runtime)
|
|
185
194
|
|
|
186
|
-
Prefira delegação síncrona para trabalho unitário ou dependente
|
|
187
|
-
|
|
188
|
-
`OPENCODE_EXPERIMENTAL_BACKGROUND_SUBAGENTS=true` é uma configuração de host documentada para ambientes que suportam background, não uma garantia de que o modo ou suas opções estejam expostos nesta sessão.
|
|
189
|
-
|
|
190
|
-
Faça revisão Themis conforme o risco e os gates aplicáveis, não como uma etapa universal.
|
|
191
|
-
|
|
195
|
+
Prefira delegação síncrona para trabalho unitário ou dependente; background apenas para frentes independentes e somente se o schema visível de `subagent` expuser o modo. `task_status`/tracking de jobs não são ferramentas root disponíveis; não invoque nem presuma fan-in ou recuperação garantidos. Revisão Themis conforme o risco e os gates aplicáveis, não como etapa universal.
|
|
192
196
|
|
|
193
197
|
## Limite de delegação
|
|
194
198
|
|
|
@@ -219,52 +223,18 @@ vão a idle com todos incompletos. Guards (todos no `src/pantheon/todo-enforcer.
|
|
|
219
223
|
(lido na construção do plugin). routing.yml é espelho de documentação — o env
|
|
220
224
|
var é o switch real (precedente COMPACTION_MAX_ITEMS).
|
|
221
225
|
|
|
222
|
-
##
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
"OpenCode generation and plugin contract").
|
|
238
|
-
**Caveat**: a tool so reaparece para quem re-rodar `init` depois do fix. O
|
|
239
|
-
`postinstall` nao re-executa `init`, entao ate la o config existente continua
|
|
240
|
-
resolvendo para V1 e a tool segue ausente — nesse estado, tratar `/cost` como
|
|
241
|
-
indisponivel.
|
|
242
|
-
|
|
243
|
-
Causa raiz como era na tag `1.6.0-beta.4` (registro para quem ainda tem um
|
|
244
|
-
install quebrado): o host `opencode v2.0.22` rejeita caminhos de arquivo `.ts` nos
|
|
245
|
-
arrays de plugin do config (recusa `configured plugin path must be a directory`,
|
|
246
|
-
medida em runtime nesse host; o repo so registra a parafrase `must be a
|
|
247
|
-
directory`), e a selecao de geracao caia sempre em V1 — a geracao V1 escreve
|
|
248
|
-
entradas `.ts` sob a chave singular `plugin` (`config.plugin`, o bloco de merge
|
|
249
|
-
em `scripts/install/opencode.mjs`) e o host descarta todas, logo nenhum
|
|
250
|
-
modulo Pantheon entra no processo Node. **O que mudou**: `resolveOpenCodeVersion`
|
|
251
|
-
agora tem default `'auto'` nos dois call sites e no proprio signature, e `auto`
|
|
252
|
-
consulta o host. Precedencia `auto`: flag explicito > `OPENCODE_VERSION` >
|
|
253
|
-
basename `opencode2` > probe `--version` do host (major >= 2 => v2) > soft-fail
|
|
254
|
-
para V1 com warning visivel. Precedencia e criterios do probe estao em
|
|
255
|
-
`docs/INSTALLATION.md` -> "OpenCode generation and plugin contract".
|
|
256
|
-
|
|
257
|
-
Comportamento da tool — **NAO VERIFICADO em runtime**: em 1.6.0-beta.4 o modulo
|
|
258
|
-
(`src/pantheon/cost-command.ts`) nunca era carregado no processo, e o fix nao foi
|
|
259
|
-
exercitado end-to-end, entao este descritivo permanece nao verificado.
|
|
260
|
-
`pantheon_cost({ days?: number })` le o `opencode.db` READ-ONLY usando o backend
|
|
261
|
-
unico `node:sqlite`; se indisponivel, retorna `UNSUPPORTED`, sem fallback. Devolve tabela markdown de custo + tokens por
|
|
262
|
-
agente nos ultimos N dias (default 7). Uso: quando Nyx pedir visibilidade de
|
|
263
|
-
custo, ou antes de escalar tier — decida se o batch valeu o preco.
|
|
264
|
-
|
|
265
|
-
### Themis Tier Policy (routing.yml go-deepseek)
|
|
266
|
-
Revisoes de FASE do themis rodam em `opencode/deepseek-v4-flash`
|
|
267
|
-
(review rapido, barato — evita a assinatura empty-mode2 de retorno vazio).
|
|
268
|
-
O tier PRO (`deepseek-v4-pro`) fica RESERVADO para o FINAL GATE (auditoria
|
|
269
|
-
final apos tudo aprovado) — override manual na hora. Athena NAO muda:
|
|
270
|
-
planner continua em pro.
|
|
226
|
+
## Runtime guards (automatic)
|
|
227
|
+
|
|
228
|
+
- **Empty-result retry**: an empty child-session result becomes an explicit error at the plugin layer (`tool.execute.after`), so a silent child failure is never mistaken for success.
|
|
229
|
+
- **Continue-on-idle**: the plugin re-injects "Continue: pending todos remain" when a root session idles with incomplete todos. Suppressed 30 s after user activity, while a background job runs, or while a native child updated itself in the last 2 min. Kill-switch: `PANTHEON_TODO_ENFORCER=off`.
|
|
230
|
+
|
|
231
|
+
### Themis Tier Policy (routing.yml)
|
|
232
|
+
Phase reviews run on `opencode/deepseek-v4-flash` (fast, cheap review tier). The
|
|
233
|
+
`deepseek-v4-pro` tier is RESERVED for the final gate (final audit after
|
|
234
|
+
everything else is approved) — manual override at that moment. Athena stays on
|
|
235
|
+
pro; the planner tier does not change.
|
|
236
|
+
|
|
237
|
+
**Decision-model economics**: routing and skill-stacking ambiguity is the
|
|
238
|
+
orchestrator's most frequent paid reasoning. One typed `pantheon_jev_decide`
|
|
239
|
+
call answers it in a single fast decision instead of open-ended deliberation;
|
|
240
|
+
obvious routes still skip the tool entirely (see Local advisory routing above).
|
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The explicit V2 tool surface for native Jev Decisions.
|
|
3
|
+
*
|
|
4
|
+
* This is the one production call site for the native Decisions scaffold. The
|
|
5
|
+
* surface is an explicit tool invocation, which resolves the hook path's
|
|
6
|
+
* correlation problem by construction: the model calls the tool during its own
|
|
7
|
+
* turn, so there is no queued/steer ambiguity to prove. Egress still passes the
|
|
8
|
+
* full gate chain before the host's `experimental.generate.decisions` is ever
|
|
9
|
+
* invoked — user-level config (`enabled`, `egress_consent`), exactly one
|
|
10
|
+
* cap-valid native candidate from the budget ledger, the host permission
|
|
11
|
+
* kill-switch on the `decision.egress` action, and the bounded request
|
|
12
|
+
* preparer. Transport is the host's own provider layer: this module never
|
|
13
|
+
* touches fetch, endpoints, or credentials.
|
|
14
|
+
*
|
|
15
|
+
* Settlement follows the fetch runner's fail-closed contract: reserve before
|
|
16
|
+
* the call, reconcile from the host-reported cost after it, and leave the
|
|
17
|
+
* reservation pending (budget held for the period) when no evidence can be
|
|
18
|
+
* minted. A failed or unreconciled call is a refusal, never a retry.
|
|
19
|
+
*/
|
|
20
|
+
import { readUserDecisionRouterConfig } from '../../scripts/install/decision-router-config.mjs'
|
|
21
|
+
import {
|
|
22
|
+
consumeJevDecisionResult,
|
|
23
|
+
isJevDecisionPreset,
|
|
24
|
+
type JevDecisionCatalogEntry,
|
|
25
|
+
type JevHostSkill,
|
|
26
|
+
type NativeJevRouteFailure,
|
|
27
|
+
prepareJevDecisionRequest,
|
|
28
|
+
prepareJevPresetRequest,
|
|
29
|
+
resolveNativeJevRoute,
|
|
30
|
+
} from './jev-decisions.ts'
|
|
31
|
+
import {
|
|
32
|
+
openLocalDecisionBudgetLedger,
|
|
33
|
+
resolveLocalDecisionBudgetDbPath,
|
|
34
|
+
} from './local-decision-budget.ts'
|
|
35
|
+
import {
|
|
36
|
+
assertDecisionEgressPermission,
|
|
37
|
+
buildDecisionEgressRequest,
|
|
38
|
+
} from './local-decision-egress-gate.ts'
|
|
39
|
+
import { verifyNativeUsageForReservation } from './local-decision-usage-evidence.internal.ts'
|
|
40
|
+
import type { NativeDecisionRequest } from './v2-native-decisions.ts'
|
|
41
|
+
import type { V2ToolDef } from './v2-tools.ts'
|
|
42
|
+
|
|
43
|
+
export interface V2JevDecisionRuntime {
|
|
44
|
+
/** Raw host model catalog (`ctx.model.list`); may resolve to anything. */
|
|
45
|
+
readonly listModels: () => Promise<unknown>
|
|
46
|
+
/** The host's native Decisions API (`ctx.experimental.generate.decisions`). */
|
|
47
|
+
readonly decide: (request: NativeDecisionRequest) => Promise<unknown>
|
|
48
|
+
/**
|
|
49
|
+
* Raw host skill registry (`ctx.skill.list()`); optional. Its entries extend
|
|
50
|
+
* the skills preset so installed Agent Skills become decidable.
|
|
51
|
+
*/
|
|
52
|
+
readonly listSkills?: () => Promise<unknown>
|
|
53
|
+
/** Host permission kill-switch (`ctx.permission.assert`), when present. */
|
|
54
|
+
readonly permissionAssert?: (input: Record<string, unknown>) => Promise<unknown>
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Logical permission resource: no endpoint URL exists on the native route. */
|
|
58
|
+
export function nativeJevPermissionResource(providerID: string, id: string): string {
|
|
59
|
+
return `pantheon-native-decisions://${providerID}/${id}`
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export type JevDecisionRunFailure =
|
|
63
|
+
| 'CALLER_NOT_ZEUS'
|
|
64
|
+
| 'CONTEXT_UNAVAILABLE'
|
|
65
|
+
| 'CONFIG_UNAVAILABLE'
|
|
66
|
+
| 'DISABLED'
|
|
67
|
+
| 'CONSENT_MISSING'
|
|
68
|
+
| 'CATALOG_UNAVAILABLE'
|
|
69
|
+
| 'CAP_OR_PERIOD_DENIED'
|
|
70
|
+
| NativeJevRouteFailure
|
|
71
|
+
| 'PERMISSION_UNAVAILABLE'
|
|
72
|
+
| 'PERMISSION_DENIED'
|
|
73
|
+
| 'STATE_INVALID'
|
|
74
|
+
| 'QUESTIONS_INVALID'
|
|
75
|
+
| 'PRESET_INVALID'
|
|
76
|
+
| 'RESERVATION_DENIED'
|
|
77
|
+
| 'DECISION_CALL_FAILED'
|
|
78
|
+
| 'USAGE_UNRECONCILED'
|
|
79
|
+
|
|
80
|
+
interface JevToolContext {
|
|
81
|
+
sessionID?: unknown
|
|
82
|
+
messageID?: unknown
|
|
83
|
+
agent?: unknown
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function refusal(reasonCode: JevDecisionRunFailure): string {
|
|
87
|
+
return JSON.stringify({ advisory: false, effect: 'none', reasonCode })
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function isNonBlankString(value: unknown): value is string {
|
|
91
|
+
return typeof value === 'string' && value.trim().length > 0
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Read the host's installed skills for the stacking preset. Anything that is
|
|
96
|
+
* not a plain {id, description?} record is skipped; a missing or hostile
|
|
97
|
+
* registry degrades to the catalog-only preset. Reading the registry applies
|
|
98
|
+
* no trust: installation already was the user's manual, reviewed act.
|
|
99
|
+
*/
|
|
100
|
+
async function readHostSkills(runtime: V2JevDecisionRuntime): Promise<JevHostSkill[] | undefined> {
|
|
101
|
+
if (typeof runtime.listSkills !== 'function') return undefined
|
|
102
|
+
let raw: unknown
|
|
103
|
+
try {
|
|
104
|
+
raw = await runtime.listSkills()
|
|
105
|
+
} catch {
|
|
106
|
+
return undefined
|
|
107
|
+
}
|
|
108
|
+
if (!Array.isArray(raw)) return undefined
|
|
109
|
+
const skills: JevHostSkill[] = []
|
|
110
|
+
for (const entry of raw) {
|
|
111
|
+
if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) continue
|
|
112
|
+
const record = entry as { id?: unknown; description?: unknown }
|
|
113
|
+
if (typeof record.id !== 'string' || record.id.length === 0) continue
|
|
114
|
+
skills.push({
|
|
115
|
+
id: record.id,
|
|
116
|
+
...(typeof record.description === 'string' && record.description.length > 0
|
|
117
|
+
? { description: record.description }
|
|
118
|
+
: {}),
|
|
119
|
+
})
|
|
120
|
+
}
|
|
121
|
+
return skills
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async function readCatalog(runtime: V2JevDecisionRuntime): Promise<JevDecisionCatalogEntry[]> {
|
|
125
|
+
const raw = await runtime.listModels()
|
|
126
|
+
if (!Array.isArray(raw)) throw new TypeError('Model catalog is not a list')
|
|
127
|
+
const entries: JevDecisionCatalogEntry[] = []
|
|
128
|
+
for (const model of raw) {
|
|
129
|
+
if (model === null || typeof model !== 'object' || Array.isArray(model)) continue
|
|
130
|
+
const record = model as Record<string, unknown>
|
|
131
|
+
if (!isNonBlankString(record.providerID) || !isNonBlankString(record.id)) continue
|
|
132
|
+
if (typeof record.type !== 'string') continue
|
|
133
|
+
entries.push({
|
|
134
|
+
providerID: record.providerID,
|
|
135
|
+
id: record.id,
|
|
136
|
+
type: record.type,
|
|
137
|
+
} as JevDecisionCatalogEntry)
|
|
138
|
+
}
|
|
139
|
+
return entries
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Run one explicit, gate-checked native Jev decision. Every failure path
|
|
144
|
+
* returns a bounded refusal JSON; the only caller-visible success output is
|
|
145
|
+
* the validated advice with `effect: 'none'`.
|
|
146
|
+
*/
|
|
147
|
+
export async function runJevDecision(
|
|
148
|
+
input: unknown,
|
|
149
|
+
toolContext: unknown,
|
|
150
|
+
runtime: V2JevDecisionRuntime,
|
|
151
|
+
): Promise<string> {
|
|
152
|
+
const context =
|
|
153
|
+
toolContext !== null && typeof toolContext === 'object' && !Array.isArray(toolContext)
|
|
154
|
+
? (toolContext as JevToolContext)
|
|
155
|
+
: undefined
|
|
156
|
+
if (context?.agent !== 'zeus') return refusal('CALLER_NOT_ZEUS')
|
|
157
|
+
const sessionID = context?.sessionID
|
|
158
|
+
const messageID = context?.messageID
|
|
159
|
+
if (!isNonBlankString(sessionID) || !isNonBlankString(messageID)) {
|
|
160
|
+
return refusal('CONTEXT_UNAVAILABLE')
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
let config: ReturnType<typeof readUserDecisionRouterConfig>
|
|
164
|
+
try {
|
|
165
|
+
config = readUserDecisionRouterConfig()
|
|
166
|
+
} catch {
|
|
167
|
+
return refusal('CONFIG_UNAVAILABLE')
|
|
168
|
+
}
|
|
169
|
+
if (!config.enabled) return refusal('DISABLED')
|
|
170
|
+
if (!config.egress_consent) return refusal('CONSENT_MISSING')
|
|
171
|
+
|
|
172
|
+
let catalog: JevDecisionCatalogEntry[]
|
|
173
|
+
try {
|
|
174
|
+
catalog = await readCatalog(runtime)
|
|
175
|
+
} catch {
|
|
176
|
+
return refusal('CATALOG_UNAVAILABLE')
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const ledger = openLocalDecisionBudgetLedger({ dbPath: resolveLocalDecisionBudgetDbPath() })
|
|
180
|
+
try {
|
|
181
|
+
const selection = resolveNativeJevRoute(
|
|
182
|
+
config,
|
|
183
|
+
catalog,
|
|
184
|
+
(provider, model) => ledger.canReserve(provider, model).status === 'eligible',
|
|
185
|
+
)
|
|
186
|
+
if (!selection.ok) return refusal(selection.reasonCode)
|
|
187
|
+
|
|
188
|
+
if (typeof runtime.permissionAssert !== 'function') return refusal('PERMISSION_UNAVAILABLE')
|
|
189
|
+
const assertion = await assertDecisionEgressPermission(
|
|
190
|
+
runtime.permissionAssert,
|
|
191
|
+
buildDecisionEgressRequest({
|
|
192
|
+
sessionID,
|
|
193
|
+
messageID,
|
|
194
|
+
endpoint: nativeJevPermissionResource(
|
|
195
|
+
selection.selection.route.model.providerID,
|
|
196
|
+
selection.selection.route.model.id,
|
|
197
|
+
),
|
|
198
|
+
agent: 'zeus',
|
|
199
|
+
}),
|
|
200
|
+
)
|
|
201
|
+
if (assertion === 'deny') return refusal('PERMISSION_DENIED')
|
|
202
|
+
|
|
203
|
+
const requested = (input ?? {}) as { mode?: unknown; questions?: unknown }
|
|
204
|
+
const prepared =
|
|
205
|
+
requested.mode === undefined
|
|
206
|
+
? prepareJevDecisionRequest(selection.selection.route, input ?? {})
|
|
207
|
+
: isJevDecisionPreset(requested.mode)
|
|
208
|
+
? prepareJevPresetRequest(
|
|
209
|
+
selection.selection.route,
|
|
210
|
+
requested.mode,
|
|
211
|
+
input ?? {},
|
|
212
|
+
requested.mode === 'skills' ? await readHostSkills(runtime) : undefined,
|
|
213
|
+
)
|
|
214
|
+
: { ok: false as const, reasonCode: 'PRESET_INVALID' as const }
|
|
215
|
+
if (!prepared.ok) return refusal(prepared.reasonCode)
|
|
216
|
+
|
|
217
|
+
const reservation = ledger.reserve(
|
|
218
|
+
selection.selection.accountingProvider,
|
|
219
|
+
selection.selection.model,
|
|
220
|
+
)
|
|
221
|
+
if (reservation.status !== 'reserved') return refusal('RESERVATION_DENIED')
|
|
222
|
+
|
|
223
|
+
let response: unknown
|
|
224
|
+
try {
|
|
225
|
+
response = await runtime.decide(prepared.request)
|
|
226
|
+
} catch {
|
|
227
|
+
return refusal('DECISION_CALL_FAILED')
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
const evidence = verifyNativeUsageForReservation(
|
|
231
|
+
{
|
|
232
|
+
reservationId: reservation.reservationId,
|
|
233
|
+
provider: selection.selection.accountingProvider,
|
|
234
|
+
model: selection.selection.model,
|
|
235
|
+
period: reservation.period,
|
|
236
|
+
},
|
|
237
|
+
response,
|
|
238
|
+
)
|
|
239
|
+
if (evidence === null) return refusal('USAGE_UNRECONCILED')
|
|
240
|
+
const reconciliation = ledger.reconcileVerified(reservation.reservationId, evidence)
|
|
241
|
+
if (reconciliation.status !== 'reconciled') return refusal('USAGE_UNRECONCILED')
|
|
242
|
+
|
|
243
|
+
const advice = consumeJevDecisionResult(response, prepared.request)
|
|
244
|
+
return JSON.stringify({
|
|
245
|
+
advisory: true,
|
|
246
|
+
effect: 'none',
|
|
247
|
+
reason: 'JEV_DECISION',
|
|
248
|
+
route: {
|
|
249
|
+
providerID: selection.selection.route.model.providerID,
|
|
250
|
+
id: selection.selection.route.model.id,
|
|
251
|
+
billing: selection.selection.route.billing,
|
|
252
|
+
},
|
|
253
|
+
...(requested.mode === undefined ? {} : { preset: requested.mode }),
|
|
254
|
+
answers: advice.answers,
|
|
255
|
+
missing: advice.missing,
|
|
256
|
+
usage: { costUsd: advice.costUsd, tokens: advice.tokens },
|
|
257
|
+
frozen: reconciliation.frozen,
|
|
258
|
+
})
|
|
259
|
+
} finally {
|
|
260
|
+
ledger.close()
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
const TOOL_DESCRIPTION =
|
|
265
|
+
'Zeus-only advisory typed decisions via the host native Jev route (OpenCode Console or a ' +
|
|
266
|
+
'configured decision model). Two ways to ask: pass `mode: "skills"` to stack skills for the ' +
|
|
267
|
+
'state text (local prefilter shortlist, catalog fallback, plus every skill installed in the ' +
|
|
268
|
+
'host), `mode: "delegation"` to pick ' +
|
|
269
|
+
'a specialist, or pass explicit typed `questions` (choice, score, predicate). Returns ' +
|
|
270
|
+
'probabilistic answers with confidence. Requires decision-router egress consent and budget ' +
|
|
271
|
+
'caps; asks host permission first. It never dispatches agents, runs skills, executes tools, ' +
|
|
272
|
+
'or alters permissions — results are advisory only.'
|
|
273
|
+
|
|
274
|
+
const questionSchema = {
|
|
275
|
+
type: 'object',
|
|
276
|
+
additionalProperties: false,
|
|
277
|
+
required: ['type', 'name', 'instructions'],
|
|
278
|
+
properties: {
|
|
279
|
+
type: { type: 'string', enum: ['choice', 'score', 'predicate'] },
|
|
280
|
+
name: { type: 'string', minLength: 1, maxLength: 64 },
|
|
281
|
+
instructions: { type: 'string', minLength: 1, maxLength: 2000 },
|
|
282
|
+
choices: {
|
|
283
|
+
type: 'array',
|
|
284
|
+
minItems: 2,
|
|
285
|
+
maxItems: 16,
|
|
286
|
+
items: {
|
|
287
|
+
type: 'object',
|
|
288
|
+
additionalProperties: false,
|
|
289
|
+
required: ['value'],
|
|
290
|
+
properties: {
|
|
291
|
+
value: { type: 'string', minLength: 1, maxLength: 64 },
|
|
292
|
+
description: { type: 'string', minLength: 1, maxLength: 500 },
|
|
293
|
+
},
|
|
294
|
+
},
|
|
295
|
+
},
|
|
296
|
+
levels: {
|
|
297
|
+
type: 'array',
|
|
298
|
+
minItems: 2,
|
|
299
|
+
maxItems: 10,
|
|
300
|
+
items: {
|
|
301
|
+
type: 'object',
|
|
302
|
+
additionalProperties: false,
|
|
303
|
+
required: ['label'],
|
|
304
|
+
properties: {
|
|
305
|
+
label: { type: 'string', minLength: 1, maxLength: 64 },
|
|
306
|
+
description: { type: 'string', minLength: 1, maxLength: 500 },
|
|
307
|
+
},
|
|
308
|
+
},
|
|
309
|
+
},
|
|
310
|
+
},
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
const JEV_INPUT_SCHEMA: Record<string, unknown> = {
|
|
314
|
+
type: 'object',
|
|
315
|
+
additionalProperties: false,
|
|
316
|
+
required: ['schemaVersion', 'state'],
|
|
317
|
+
properties: {
|
|
318
|
+
schemaVersion: { type: 'integer', const: 1 },
|
|
319
|
+
state: { type: 'string', minLength: 1, maxLength: 12_000 },
|
|
320
|
+
mode: { type: 'string', enum: ['skills', 'delegation'] },
|
|
321
|
+
questions: { type: 'array', minItems: 1, maxItems: 4, items: questionSchema },
|
|
322
|
+
},
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** Create the V2 tool definition; registration is the caller's decision. */
|
|
326
|
+
export function createV2JevDecisionDefinition(runtime: V2JevDecisionRuntime): V2ToolDef {
|
|
327
|
+
return {
|
|
328
|
+
name: 'pantheon_jev_decide',
|
|
329
|
+
description: TOOL_DESCRIPTION,
|
|
330
|
+
input: JEV_INPUT_SCHEMA,
|
|
331
|
+
output: {},
|
|
332
|
+
execute: async (input: Record<string, unknown>, context: unknown) => ({
|
|
333
|
+
output: await runJevDecision(input, context, runtime),
|
|
334
|
+
}),
|
|
335
|
+
}
|
|
336
|
+
}
|