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.
Files changed (71) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +209 -1
  3. package/bin/pantheon-init.mjs +22 -0
  4. package/package.json +9 -3
  5. package/plugin.json +1 -1
  6. package/pyproject.toml +1 -1
  7. package/scripts/decision-router-budget.mjs +781 -0
  8. package/scripts/decision-router-v2-budget.mjs +218 -0
  9. package/scripts/decision-router-v2-egress.mjs +272 -0
  10. package/scripts/decision-router.mjs +519 -0
  11. package/scripts/docs-check-changelog.mjs +5 -3
  12. package/scripts/install/decision-layer-preview.mjs +376 -0
  13. package/scripts/install/decision-router-config.mjs +579 -0
  14. package/scripts/install/interactive.mjs +76 -5
  15. package/scripts/install/opencode.mjs +12 -0
  16. package/scripts/install/state.mjs +5 -0
  17. package/scripts/install/strings.mjs +4 -0
  18. package/scripts/mcp_resources.py +11 -9
  19. package/scripts/release-notes.mjs +30 -7
  20. package/scripts/versioning.mjs +41 -5
  21. package/src/agents/zeus.md +12 -0
  22. package/src/mcp/eval_store.py +11 -4
  23. package/src/mcp/mcp_resources.py +11 -9
  24. package/src/mcp/memory_mcp.py +293 -150
  25. package/src/pantheon/local-decision-agents.ts +170 -0
  26. package/src/pantheon/local-decision-budget.ts +1043 -0
  27. package/src/pantheon/local-decision-egress-gate.ts +264 -0
  28. package/src/pantheon/local-decision-prompt.ts +268 -0
  29. package/src/pantheon/local-decision-provider-matrix.ts +92 -0
  30. package/src/pantheon/local-decision-provider-protocol.ts +335 -0
  31. package/src/pantheon/local-decision-provider.internal.ts +260 -0
  32. package/src/pantheon/local-decision-router.ts +225 -0
  33. package/src/pantheon/local-decision-skills.ts +281 -0
  34. package/src/pantheon/local-decision-tool.ts +160 -0
  35. package/src/pantheon/local-decision-turn.ts +338 -0
  36. package/src/pantheon/local-decision-usage-evidence.internal.ts +207 -0
  37. package/src/pantheon/local-orchestration.ts +322 -0
  38. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  39. package/src/pantheon/v2-decision-budget.ts +456 -0
  40. package/src/pantheon/v2-decision-contracts.ts +300 -0
  41. package/src/pantheon/v2-decision-egress.ts +203 -0
  42. package/src/pantheon/v2-decision-events.ts +180 -0
  43. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  44. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  45. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  46. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  47. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  48. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  49. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  50. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  51. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  52. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  53. package/src/pantheon/v2-decision-points/p8-guardrail.ts +366 -0
  54. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  55. package/src/pantheon/v2-decision-points.ts +242 -0
  56. package/src/pantheon/v2-decision-policy.ts +166 -0
  57. package/src/pantheon/v2-decision-premises.ts +146 -0
  58. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  59. package/src/pantheon/v2-decision-rank.ts +91 -0
  60. package/src/pantheon/v2-decision-registry.ts +391 -0
  61. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  62. package/src/pantheon/v2-decision-shadow.ts +123 -0
  63. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  64. package/src/pantheon/v2-decision-verify.ts +51 -0
  65. package/src/pantheon/v2-tools.ts +35 -15
  66. package/src/plugin-v2.ts +357 -22
  67. package/src/plugin.ts +4 -0
  68. package/src/plugins/tui/dist/tui-v2.js +3 -3
  69. package/src/plugins/tui/dist/tui.js +1 -1
  70. package/src/plugins/tui/package-lock.json +2 -2
  71. package/src/plugins/tui/package.json +1 -1
@@ -0,0 +1,225 @@
1
+ import { PANTHEON_AGENTS } from './v2-delegation-enforce.ts'
2
+
3
+ /** Explicit opt-in for the local advisory API. Unset and any value except `1` disable it. */
4
+ export const LOCAL_DECISION_ROUTER_ENV = 'PANTHEON_LOCAL_DECISION_ROUTER'
5
+ export const LOCAL_DECISION_ROUTER_POLICY_VERSION = 'local-decision-router/v1'
6
+
7
+ export const LOCAL_DECISION_COMPLEXITY_DIMENSIONS = [
8
+ 'boundedness',
9
+ 'reversibility',
10
+ 'dependencies',
11
+ 'uncertainty',
12
+ 'verification',
13
+ ] as const
14
+
15
+ export type LocalDecisionComplexityDimensions = Readonly<
16
+ Record<(typeof LOCAL_DECISION_COMPLEXITY_DIMENSIONS)[number], 0 | 1 | 2>
17
+ >
18
+
19
+ export type LocalDecisionGateStatus =
20
+ | 'none'
21
+ | 'review_required'
22
+ | 'human_approval_required'
23
+ | 'unresolved'
24
+
25
+ /** Versioned structured input; domain entries are exact canonical specialist IDs. */
26
+ export interface LocalDecisionInput {
27
+ schemaVersion: 1
28
+ domains: readonly string[]
29
+ complexity: LocalDecisionComplexityDimensions
30
+ gateStatus: LocalDecisionGateStatus
31
+ }
32
+
33
+ export type LocalDecisionRouteReasonCode =
34
+ | 'DISABLED'
35
+ | 'INVALID_INPUT'
36
+ | 'NO_DOMAIN'
37
+ | 'AMBIGUOUS_DOMAIN'
38
+ | 'UNKNOWN_DOMAIN'
39
+ | 'UNROUTABLE_ROLE'
40
+ | 'CANONICAL_ROLE'
41
+
42
+ export type LocalDecisionComplexityReasonCode =
43
+ | 'DISABLED'
44
+ | 'INVALID_INPUT'
45
+ | 'INVALID_COMPLEXITY'
46
+ | 'CLASSIFIED_FROM_STRUCTURED_DIMENSIONS'
47
+
48
+ export interface LocalDecisionRecommendation {
49
+ schemaVersion: 1
50
+ policyVersion: typeof LOCAL_DECISION_ROUTER_POLICY_VERSION
51
+ decision: 'route' | 'abstain'
52
+ /** Non-null only when `decision` is `route`, and always a canonical specialist ID. */
53
+ agent: string | null
54
+ reasonCode: LocalDecisionRouteReasonCode
55
+ complexity: {
56
+ label: 'low' | 'medium' | 'high' | 'abstain'
57
+ reasonCode: LocalDecisionComplexityReasonCode
58
+ }
59
+ /** Security/authorization status is carried separately and never changes complexity. */
60
+ gateStatus: LocalDecisionGateStatus
61
+ }
62
+
63
+ const ROUTABLE_AGENTS: ReadonlySet<string> = new Set(
64
+ [...PANTHEON_AGENTS].filter((agent) => agent !== 'zeus'),
65
+ )
66
+
67
+ const GATE_STATUSES: ReadonlySet<string> = new Set([
68
+ 'none',
69
+ 'review_required',
70
+ 'human_approval_required',
71
+ 'unresolved',
72
+ ])
73
+
74
+ const INPUT_KEYS = ['complexity', 'domains', 'gateStatus', 'schemaVersion']
75
+ const COMPLEXITY_KEYS = [...LOCAL_DECISION_COMPLEXITY_DIMENSIONS].sort()
76
+
77
+ function isPlainRecord(value: unknown): value is Record<string, unknown> {
78
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) return false
79
+ const prototype = Object.getPrototypeOf(value)
80
+ return prototype === Object.prototype || prototype === null
81
+ }
82
+
83
+ function hasExactKeys(value: Record<string, unknown>, keys: readonly string[]): boolean {
84
+ const actualKeys = Object.keys(value).sort()
85
+ const expectedKeys = [...keys].sort()
86
+ return (
87
+ actualKeys.length === expectedKeys.length &&
88
+ actualKeys.every((key, index) => key === expectedKeys[index])
89
+ )
90
+ }
91
+
92
+ function isValidInputShape(input: unknown): input is LocalDecisionInput {
93
+ if (!isPlainRecord(input) || !hasExactKeys(input, INPUT_KEYS)) return false
94
+ if (
95
+ input.schemaVersion !== 1 ||
96
+ typeof input.gateStatus !== 'string' ||
97
+ !GATE_STATUSES.has(input.gateStatus)
98
+ ) {
99
+ return false
100
+ }
101
+ if (
102
+ !Array.isArray(input.domains) ||
103
+ !input.domains.every((domain) => typeof domain === 'string')
104
+ ) {
105
+ return false
106
+ }
107
+ if (!isPlainRecord(input.complexity) || !hasExactKeys(input.complexity, COMPLEXITY_KEYS)) {
108
+ return false
109
+ }
110
+ return classifyLocalDecisionComplexity(input.complexity).label !== 'abstain'
111
+ }
112
+
113
+ export function classifyLocalDecisionComplexity(
114
+ value: unknown,
115
+ ): LocalDecisionRecommendation['complexity'] {
116
+ if (!isPlainRecord(value) || !hasExactKeys(value, COMPLEXITY_KEYS)) {
117
+ return { label: 'abstain', reasonCode: 'INVALID_COMPLEXITY' }
118
+ }
119
+
120
+ const scores = LOCAL_DECISION_COMPLEXITY_DIMENSIONS.map((dimension) => value[dimension])
121
+ if (
122
+ !scores.every(
123
+ (score) => typeof score === 'number' && Number.isInteger(score) && score >= 0 && score <= 2,
124
+ )
125
+ ) {
126
+ return { label: 'abstain', reasonCode: 'INVALID_COMPLEXITY' }
127
+ }
128
+
129
+ const label = scores.includes(2) ? 'high' : scores.includes(1) ? 'medium' : 'low'
130
+ return { label, reasonCode: 'CLASSIFIED_FROM_STRUCTURED_DIMENSIONS' }
131
+ }
132
+
133
+ function createAbstention(
134
+ reasonCode: LocalDecisionRouteReasonCode,
135
+ complexityReasonCode: LocalDecisionComplexityReasonCode,
136
+ gateStatus: LocalDecisionGateStatus = 'unresolved',
137
+ ): LocalDecisionRecommendation {
138
+ return {
139
+ schemaVersion: 1,
140
+ policyVersion: LOCAL_DECISION_ROUTER_POLICY_VERSION,
141
+ decision: 'abstain',
142
+ agent: null,
143
+ reasonCode,
144
+ complexity: { label: 'abstain', reasonCode: complexityReasonCode },
145
+ gateStatus,
146
+ }
147
+ }
148
+
149
+ function evaluateEnabledInput(input: unknown): LocalDecisionRecommendation {
150
+ if (!isValidInputShape(input)) {
151
+ const gateStatus =
152
+ isPlainRecord(input) &&
153
+ typeof input.gateStatus === 'string' &&
154
+ GATE_STATUSES.has(input.gateStatus)
155
+ ? (input.gateStatus as LocalDecisionGateStatus)
156
+ : 'unresolved'
157
+ const complexity = isPlainRecord(input)
158
+ ? classifyLocalDecisionComplexity(input.complexity)
159
+ : { label: 'abstain' as const, reasonCode: 'INVALID_COMPLEXITY' as const }
160
+ const complexityReasonCode =
161
+ complexity.reasonCode === 'INVALID_COMPLEXITY' ? 'INVALID_COMPLEXITY' : 'INVALID_INPUT'
162
+ return createAbstention('INVALID_INPUT', complexityReasonCode, gateStatus)
163
+ }
164
+
165
+ const gateStatus = input.gateStatus
166
+ const complexity = classifyLocalDecisionComplexity(input.complexity)
167
+
168
+ if (input.domains.length === 0) {
169
+ return { ...createAbstention('NO_DOMAIN', complexity.reasonCode, gateStatus), complexity }
170
+ }
171
+ if (input.domains.length !== 1) {
172
+ return {
173
+ ...createAbstention('AMBIGUOUS_DOMAIN', complexity.reasonCode, gateStatus),
174
+ complexity,
175
+ }
176
+ }
177
+
178
+ const [domain] = input.domains
179
+ if (typeof domain !== 'string') {
180
+ return createAbstention('INVALID_INPUT', complexity.reasonCode, gateStatus)
181
+ }
182
+ if (domain === 'zeus') {
183
+ return {
184
+ ...createAbstention('UNROUTABLE_ROLE', complexity.reasonCode, gateStatus),
185
+ complexity,
186
+ }
187
+ }
188
+ if (!ROUTABLE_AGENTS.has(domain)) {
189
+ return {
190
+ ...createAbstention('UNKNOWN_DOMAIN', complexity.reasonCode, gateStatus),
191
+ complexity,
192
+ }
193
+ }
194
+
195
+ return {
196
+ schemaVersion: 1,
197
+ policyVersion: LOCAL_DECISION_ROUTER_POLICY_VERSION,
198
+ decision: 'route',
199
+ agent: domain,
200
+ reasonCode: 'CANONICAL_ROLE',
201
+ complexity,
202
+ gateStatus,
203
+ }
204
+ }
205
+
206
+ /**
207
+ * Return a local advisory recommendation only when explicitly enabled.
208
+ *
209
+ * This function never calls a provider, dispatches an agent, or changes permissions.
210
+ * The default-off environment gate intentionally leaves native host dispatch untouched.
211
+ */
212
+ export function recommendLocalDecision(
213
+ input: LocalDecisionInput,
214
+ env: Readonly<Record<string, string | undefined>> = process.env,
215
+ ): LocalDecisionRecommendation {
216
+ try {
217
+ if (env[LOCAL_DECISION_ROUTER_ENV] !== '1') {
218
+ return createAbstention('DISABLED', 'DISABLED')
219
+ }
220
+ return evaluateEnabledInput(input)
221
+ } catch {
222
+ // Malformed accessors and injected env are invalid data; never route on failure.
223
+ return createAbstention('INVALID_INPUT', 'INVALID_INPUT')
224
+ }
225
+ }
@@ -0,0 +1,281 @@
1
+ import { PANTHEON_SKILL_CATALOG, PANTHEON_SKILL_IDS } from './pantheon-decision-catalog.ts'
2
+
3
+ export type SkillSelectionReason =
4
+ | 'SELECTED_BY_KEYWORDS'
5
+ | 'SELECTED_BY_MATERIAL_REQUIREMENT'
6
+ | 'NO_LOCAL_MATCH'
7
+ | 'INVALID_INPUT'
8
+
9
+ /** Material requirement that must seat `artifact-management` (D2). */
10
+ export type MaterialRequirement = 'gate' | 'planning'
11
+
12
+ export interface LocalSkillSelection {
13
+ skillIds: string[]
14
+ reasonCode: SkillSelectionReason
15
+ /** `null` unless the request materially requires a gate or a plan (D2). */
16
+ materialRequirement: MaterialRequirement | null
17
+ }
18
+
19
+ /** Bounded so a malformed or huge prompt can never fan out local work. */
20
+ export const MAX_SELECTED_SKILLS = 4
21
+ const MAX_REQUEST_LENGTH = 20_000
22
+
23
+ /**
24
+ * Small, allowlisted keyword table. It is intentionally local and
25
+ * deterministic: no model, no embedding index, no network.
26
+ */
27
+ const KEYWORDS: Readonly<Record<string, readonly string[]>> = Object.freeze({
28
+ 'agent-coordination': [
29
+ 'agent',
30
+ 'agents',
31
+ 'delegate',
32
+ 'delegation',
33
+ 'orchestrate',
34
+ 'orchestration',
35
+ 'route',
36
+ 'routing',
37
+ 'subagent',
38
+ ],
39
+ 'artifact-management': ['artifact', 'artifacts', 'planned', 'multi-phase', 'impl'],
40
+ 'auto-continue': ['continue', 'continuation', 'todo', 'todos', 'multi-step', 'idle'],
41
+ clonedeps: ['clone', 'dependency', 'dependencies', 'internals', 'library', 'package'],
42
+ 'code-review-checklist': ['review', 'reviews', 'pull request', 'feedback', 'checklist'],
43
+ codemap: ['codemap', 'structure', 'codebase', 'unfamiliar', 'repository', 'overview'],
44
+ 'context-compression': ['compact', 'compaction', 'compress', 'context', 'checkpoint', 'resume'],
45
+ 'git-workflow-and-versioning': [
46
+ 'commit',
47
+ 'commits',
48
+ 'git',
49
+ 'branch',
50
+ 'version',
51
+ 'release',
52
+ 'tag',
53
+ 'changelog',
54
+ ],
55
+ 'incremental-implementation': [
56
+ 'increment',
57
+ 'incremental',
58
+ 'slice',
59
+ 'slices',
60
+ 'implement',
61
+ 'implementation',
62
+ ],
63
+ 'loop-engineering': ['loop', 'iterate', 'iteration', 'refine', 'refinement', 'cycle'],
64
+ 'memory-bank': ['memory', 'adr', 'adrs', 'documentation', 'docs', 'knowledge'],
65
+ reflect: ['reflect', 'reflection', 'retro', 'retrospective', 'friction', 'workflow'],
66
+ 'security-hardening': [
67
+ 'security',
68
+ 'secure',
69
+ 'owasp',
70
+ 'vulnerability',
71
+ 'vulnerabilities',
72
+ 'secret',
73
+ 'secrets',
74
+ 'cve',
75
+ 'audit',
76
+ ],
77
+ 'session-goal': ['goal', 'objective', 'scope', 'alignment', 'session'],
78
+ simplify: [
79
+ 'simplify',
80
+ 'simplification',
81
+ 'refactor',
82
+ 'complexity',
83
+ 'readable',
84
+ 'readability',
85
+ 'cleanup',
86
+ ],
87
+ 'spec-driven-development': [
88
+ 'spec',
89
+ 'specification',
90
+ 'requirements',
91
+ 'prd',
92
+ 'acceptance',
93
+ 'criteria',
94
+ ],
95
+ 'tdd-with-agents': ['tdd', 'test', 'tests', 'testing', 'pytest', 'vitest', 'jest', 'coverage'],
96
+ 'verification-planning': [
97
+ 'verification',
98
+ 'verify',
99
+ 'evidence',
100
+ 'validation',
101
+ 'validate',
102
+ 'reproduce',
103
+ ],
104
+ 'visual-review-pipeline': [
105
+ 'visual',
106
+ 'screenshot',
107
+ 'screenshots',
108
+ 'ui',
109
+ 'ux',
110
+ 'accessibility',
111
+ 'wcag',
112
+ 'playwright',
113
+ 'responsive',
114
+ ],
115
+ worktrees: ['worktree', 'worktrees', 'parallel', 'isolation', 'isolated'],
116
+ })
117
+
118
+ /**
119
+ * Material gate/planning signals (D2).
120
+ *
121
+ * `artifact-management` exists for planned or materially risky work. Keyword
122
+ * scoring alone left it unreachable when the request demanded a gate or a plan
123
+ * without naming the artifact: "breaking change with human approval and a
124
+ * rollback plan" matched no keyword at all. These are static phrase/token
125
+ * lists, so detection stays local, deterministic, and bounded: no file, memory,
126
+ * catalog, or network read.
127
+ */
128
+ const MATERIAL_GATE_TOKENS: ReadonlySet<string> = new Set([
129
+ 'approval',
130
+ 'cutover',
131
+ 'gate',
132
+ 'irreversible',
133
+ 'signoff',
134
+ ])
135
+
136
+ const MATERIAL_GATE_PHRASES: readonly string[] = Object.freeze([
137
+ 'breaking change',
138
+ 'risk assessment',
139
+ 'risk review',
140
+ 'schema change',
141
+ 'sign off',
142
+ ])
143
+
144
+ const MATERIAL_PLANNING_TOKENS: ReadonlySet<string> = new Set([
145
+ 'deliverable',
146
+ 'deliverables',
147
+ 'milestone',
148
+ 'milestones',
149
+ 'plan',
150
+ 'planning',
151
+ 'roadmap',
152
+ 'rollback',
153
+ ])
154
+
155
+ const MATERIAL_PLANNING_PHRASES: readonly string[] = Object.freeze([
156
+ 'across phases',
157
+ 'break down',
158
+ 'design doc',
159
+ 'implementation plan',
160
+ 'migration plan',
161
+ 'rollout plan',
162
+ 'work breakdown',
163
+ ])
164
+
165
+ const ARTIFACT_SKILL_ID = 'artifact-management'
166
+
167
+ const CATALOG_ORDER = new Map(PANTHEON_SKILL_CATALOG.map((entry, index) => [entry.id, index]))
168
+
169
+ function normalize(value: string): string {
170
+ return value
171
+ .normalize('NFD')
172
+ .replace(/[\u0300-\u036f]/g, '')
173
+ .toLowerCase()
174
+ }
175
+
176
+ function tokenize(value: string): Set<string> {
177
+ const tokens = value.match(/[a-z0-9]+(?:[+#.-][a-z0-9]+)*/g) ?? []
178
+ return new Set(tokens)
179
+ }
180
+
181
+ function scoreSkill(normalizedRequest: string, tokens: ReadonlySet<string>, skillId: string) {
182
+ const keywords = KEYWORDS[skillId] ?? []
183
+ let score = 0
184
+ for (const keyword of keywords) {
185
+ if (keyword.includes(' ')) {
186
+ if (normalizedRequest.includes(keyword)) score += 3
187
+ continue
188
+ }
189
+ if (tokens.has(keyword)) score += 2
190
+ }
191
+ return score
192
+ }
193
+
194
+ function hasMaterialSignal(
195
+ normalizedRequest: string,
196
+ tokens: ReadonlySet<string>,
197
+ signalTokens: ReadonlySet<string>,
198
+ signalPhrases: readonly string[],
199
+ ): boolean {
200
+ for (const token of signalTokens) {
201
+ if (tokens.has(token)) return true
202
+ }
203
+ return signalPhrases.some((phrase) => normalizedRequest.includes(phrase))
204
+ }
205
+
206
+ /**
207
+ * Detect a material gate or planning requirement (D2). A gate requirement wins
208
+ * over a planning one, so the reported token is stable when both are present.
209
+ */
210
+ function detectMaterialRequirement(
211
+ normalizedRequest: string,
212
+ tokens: ReadonlySet<string>,
213
+ ): MaterialRequirement | null {
214
+ if (hasMaterialSignal(normalizedRequest, tokens, MATERIAL_GATE_TOKENS, MATERIAL_GATE_PHRASES)) {
215
+ return 'gate'
216
+ }
217
+ if (
218
+ hasMaterialSignal(
219
+ normalizedRequest,
220
+ tokens,
221
+ MATERIAL_PLANNING_TOKENS,
222
+ MATERIAL_PLANNING_PHRASES,
223
+ )
224
+ ) {
225
+ return 'planning'
226
+ }
227
+ return null
228
+ }
229
+
230
+ /**
231
+ * Select a small, deterministic set of allowlisted Pantheon skills for the
232
+ * current request. This function never reads files, memory, transcripts, or
233
+ * the network, and it never returns the whole catalog as a fallback.
234
+ *
235
+ * D2 — when the request materially requires a gate or a plan, the artifact
236
+ * skill is guaranteed a seat instead of depending on the literal keywords
237
+ * `artifact`/`planned`/`multi-phase`/`impl`. That seat is first, so a hard
238
+ * budget drops the lowest-scoring keyword skill rather than the required one.
239
+ * This only ranks identifiers: it does not filter or mutate any prompt, and P2
240
+ * remains an empirical no-op on the default path (F-09).
241
+ */
242
+ export function selectPantheonSkills(
243
+ request: unknown,
244
+ maxSkills = MAX_SELECTED_SKILLS,
245
+ ): LocalSkillSelection {
246
+ if (
247
+ typeof request !== 'string' ||
248
+ request.trim().length === 0 ||
249
+ request.length > MAX_REQUEST_LENGTH ||
250
+ !Number.isInteger(maxSkills) ||
251
+ maxSkills < 1 ||
252
+ maxSkills > MAX_SELECTED_SKILLS
253
+ ) {
254
+ return { skillIds: [], reasonCode: 'INVALID_INPUT', materialRequirement: null }
255
+ }
256
+
257
+ const normalizedRequest = normalize(request)
258
+ const tokens = tokenize(normalizedRequest)
259
+ const material = detectMaterialRequirement(normalizedRequest, tokens)
260
+ const scored: Array<{ id: string; score: number; order: number }> = []
261
+ for (const skillId of PANTHEON_SKILL_IDS) {
262
+ const score = scoreSkill(normalizedRequest, tokens, skillId)
263
+ if (score <= 0) continue
264
+ scored.push({ id: skillId, score, order: CATALOG_ORDER.get(skillId) ?? 0 })
265
+ }
266
+ if (material === null && scored.length === 0) {
267
+ return { skillIds: [], reasonCode: 'NO_LOCAL_MATCH', materialRequirement: null }
268
+ }
269
+
270
+ scored.sort((left, right) => right.score - left.score || left.order - right.order)
271
+ const ranked = scored.map((entry) => entry.id)
272
+ const ordered =
273
+ material === null
274
+ ? ranked
275
+ : [ARTIFACT_SKILL_ID, ...ranked.filter((id) => id !== ARTIFACT_SKILL_ID)]
276
+ return {
277
+ skillIds: ordered.slice(0, maxSkills),
278
+ reasonCode: material === null ? 'SELECTED_BY_KEYWORDS' : 'SELECTED_BY_MATERIAL_REQUIREMENT',
279
+ materialRequirement: material,
280
+ }
281
+ }
@@ -0,0 +1,160 @@
1
+ import { type ToolContext, tool } from '@opencode-ai/plugin'
2
+ import {
3
+ LOCAL_DECISION_COMPLEXITY_DIMENSIONS,
4
+ type LocalDecisionGateStatus,
5
+ } from './local-decision-router.ts'
6
+ import {
7
+ type LocalDecisionPolicy,
8
+ loadLocalDecisionPolicy,
9
+ recommendLocalOrchestration,
10
+ } from './local-orchestration.ts'
11
+ import { evaluateComplexityPoint } from './v2-decision-points/p3-complexity.ts'
12
+ import type { ShadowSink } from './v2-decision-shadow.ts'
13
+
14
+ const TOOL_DESCRIPTION =
15
+ 'Zeus-only local advisory selector. Use selectively only when specialist routing is genuinely ' +
16
+ 'ambiguous; obvious work should go directly to native subagent without this tool. Accepts only ' +
17
+ 'structured candidate IDs, never task text. It does not dispatch, run a skill/resource, search ' +
18
+ 'memory, or authorize/alter grants or review gates. Provider egress is disabled; all decisions ' +
19
+ 'remain local.'
20
+
21
+ const gateStatuses: LocalDecisionGateStatus[] = [
22
+ 'none',
23
+ 'review_required',
24
+ 'human_approval_required',
25
+ 'unresolved',
26
+ ]
27
+
28
+ const inputShape = {
29
+ schemaVersion: tool.schema.literal(1),
30
+ candidateAgents: tool.schema.array(tool.schema.string().min(1)).max(14),
31
+ domain: tool.schema.string().nullable(),
32
+ candidateSkillIds: tool.schema.array(tool.schema.string().min(1)).max(64),
33
+ candidateResourceIds: tool.schema.array(tool.schema.string().min(1)).max(32),
34
+ memorySearchRelevant: tool.schema.boolean(),
35
+ gateStatus: tool.schema.enum(
36
+ gateStatuses as [LocalDecisionGateStatus, ...LocalDecisionGateStatus[]],
37
+ ),
38
+ complexity: tool.schema
39
+ .object({
40
+ boundedness: tool.schema.number().int().min(0).max(2),
41
+ reversibility: tool.schema.number().int().min(0).max(2),
42
+ dependencies: tool.schema.number().int().min(0).max(2),
43
+ uncertainty: tool.schema.number().int().min(0).max(2),
44
+ verification: tool.schema.number().int().min(0).max(2),
45
+ })
46
+ .strict(),
47
+ }
48
+
49
+ type LocalDecisionToolOptions = {
50
+ loadPolicy?: () => Promise<LocalDecisionPolicy | undefined>
51
+ }
52
+
53
+ /**
54
+ * Optional shadow observer for the V2 tool point.
55
+ *
56
+ * P3 declares `tool.invoke`, and the local selector's input is the surface that
57
+ * carries `complexity` and `gateStatus`. The sink is supplied by the plugin when
58
+ * it registers the tool; nothing here applies its record.
59
+ */
60
+ type LocalDecisionShadowOptions = {
61
+ sink?: ShadowSink
62
+ }
63
+
64
+ /**
65
+ * Observe P3 in shadow at `tool.invoke`.
66
+ *
67
+ * Contained on purpose: the adapter already contains its own failures, and
68
+ * this wrapper guarantees that even an unexpected throw cannot change the
69
+ * tool result. No input is mutated and no decision is applied.
70
+ */
71
+ function observeToolComplexity(input: unknown, sink?: ShadowSink): void {
72
+ try {
73
+ evaluateComplexityPoint(input, sink)
74
+ } catch {
75
+ // Shadow is best-effort; the tool result is unaffected.
76
+ }
77
+ }
78
+
79
+ async function runDecision(
80
+ input: unknown,
81
+ callerAgent: unknown,
82
+ loadPolicy: () => Promise<LocalDecisionPolicy | undefined>,
83
+ ): Promise<string> {
84
+ if (callerAgent !== 'zeus') {
85
+ return JSON.stringify(recommendLocalOrchestration(input, callerAgent, undefined))
86
+ }
87
+ const policy = await loadPolicy().catch(() => undefined)
88
+ // Caller context is a host-provided identity string, not non-forgeable runtime provenance.
89
+ // Keep this route hard local-only until provider authorization can be established safely.
90
+ return JSON.stringify(recommendLocalOrchestration(input, callerAgent, policy))
91
+ }
92
+
93
+ /** Create the V1 plugin tool; execution is fail-closed unless host context identifies Zeus. */
94
+ export function createLocalDecisionTool(options: LocalDecisionToolOptions = {}) {
95
+ const policyLoader = options.loadPolicy ?? loadLocalDecisionPolicy
96
+ return tool({
97
+ description: TOOL_DESCRIPTION,
98
+ args: inputShape,
99
+ execute: async (input, context: ToolContext) => runDecision(input, context.agent, policyLoader),
100
+ })
101
+ }
102
+
103
+ const v2InputSchema: Record<string, unknown> = {
104
+ type: 'object',
105
+ additionalProperties: false,
106
+ required: [
107
+ 'schemaVersion',
108
+ 'candidateAgents',
109
+ 'domain',
110
+ 'candidateSkillIds',
111
+ 'candidateResourceIds',
112
+ 'memorySearchRelevant',
113
+ 'gateStatus',
114
+ 'complexity',
115
+ ],
116
+ properties: {
117
+ schemaVersion: { type: 'integer', const: 1 },
118
+ candidateAgents: { type: 'array', maxItems: 14, items: { type: 'string', minLength: 1 } },
119
+ domain: { type: ['string', 'null'] },
120
+ candidateSkillIds: { type: 'array', maxItems: 64, items: { type: 'string', minLength: 1 } },
121
+ candidateResourceIds: { type: 'array', maxItems: 32, items: { type: 'string', minLength: 1 } },
122
+ memorySearchRelevant: { type: 'boolean' },
123
+ gateStatus: { type: 'string', enum: gateStatuses },
124
+ complexity: {
125
+ type: 'object',
126
+ additionalProperties: false,
127
+ required: [...LOCAL_DECISION_COMPLEXITY_DIMENSIONS],
128
+ properties: Object.fromEntries(
129
+ LOCAL_DECISION_COMPLEXITY_DIMENSIONS.map((dimension) => [
130
+ dimension,
131
+ { type: 'integer', minimum: 0, maximum: 2 },
132
+ ]),
133
+ ),
134
+ },
135
+ },
136
+ }
137
+
138
+ /** Create a V2 transform definition with the same Zeus-only execution guard and local plan. */
139
+ export function createV2LocalDecisionDefinition(
140
+ options: LocalDecisionToolOptions & LocalDecisionShadowOptions = {},
141
+ ) {
142
+ const policyLoader = options.loadPolicy ?? loadLocalDecisionPolicy
143
+ return {
144
+ name: 'pantheon_local_decision',
145
+ description: TOOL_DESCRIPTION,
146
+ input: v2InputSchema,
147
+ output: {},
148
+ execute: async (input: Record<string, unknown>, context: unknown) => {
149
+ // P3 shadow observation at `tool.invoke`. The input schema declares
150
+ // `complexity` and `gateStatus`, so this is the one wired surface that
151
+ // can feed a complexity decision; the record never alters the result.
152
+ observeToolComplexity(input, options.sink)
153
+ const callerAgent =
154
+ context !== null && typeof context === 'object'
155
+ ? (context as { agent?: unknown }).agent
156
+ : undefined
157
+ return { output: await runDecision(input, callerAgent, policyLoader) }
158
+ },
159
+ }
160
+ }