pantheon-opencode 1.6.2-beta.2 → 1.6.2-beta.4

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 (57) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +56 -16
  3. package/bin/pantheon-init.mjs +68 -13
  4. package/package.json +10 -3
  5. package/plugin.json +1 -1
  6. package/prompts/README.md +58 -0
  7. package/prompts/debug-issue.prompt.md +46 -0
  8. package/prompts/dynamic/agora-generated.txt +38 -0
  9. package/prompts/dynamic/orchestrate-generated.txt +51 -0
  10. package/prompts/focus.prompt.md +42 -0
  11. package/prompts/implement-feature.prompt.md +39 -0
  12. package/prompts/optimize-database.prompt.md +58 -0
  13. package/prompts/orchestrate-with-zeus.prompt.md +441 -0
  14. package/prompts/plan-architecture.prompt.md +59 -0
  15. package/prompts/quick-discovery-large-codebase.prompt.md +294 -0
  16. package/prompts/quick-plan-large-feature.prompt.md +197 -0
  17. package/prompts/semantic-summarize.md +50 -0
  18. package/prompts/sketch.prompt.md +91 -0
  19. package/prompts/subtask.prompt.md +131 -0
  20. package/pyproject.toml +1 -1
  21. package/scripts/decision-router-budget.mjs +781 -0
  22. package/scripts/decision-router.mjs +297 -0
  23. package/scripts/install/component-selection.mjs +9 -4
  24. package/scripts/install/decision-router-config.mjs +432 -0
  25. package/scripts/install/health-check.mjs +20 -11
  26. package/scripts/install/interactive.mjs +78 -14
  27. package/scripts/install/interrupt.mjs +4 -3
  28. package/scripts/install/migrate.mjs +123 -72
  29. package/scripts/install/opencode.mjs +162 -114
  30. package/scripts/install/plan.mjs +8 -1
  31. package/scripts/install/state.mjs +12 -0
  32. package/scripts/install/strings.mjs +10 -0
  33. package/scripts/install/venv.mjs +34 -17
  34. package/scripts/restore.mjs +22 -10
  35. package/scripts/test-opencode-v2-sandbox.sh +10 -6
  36. package/src/agents/zeus.md +12 -0
  37. package/src/pantheon/local-decision-agents.ts +170 -0
  38. package/src/pantheon/local-decision-budget.ts +1043 -0
  39. package/src/pantheon/local-decision-egress-gate.ts +264 -0
  40. package/src/pantheon/local-decision-prompt.ts +123 -0
  41. package/src/pantheon/local-decision-provider-matrix.ts +92 -0
  42. package/src/pantheon/local-decision-provider-protocol.ts +335 -0
  43. package/src/pantheon/local-decision-provider.internal.ts +260 -0
  44. package/src/pantheon/local-decision-router.ts +225 -0
  45. package/src/pantheon/local-decision-skills.ts +171 -0
  46. package/src/pantheon/local-decision-tool.ts +126 -0
  47. package/src/pantheon/local-decision-turn.ts +338 -0
  48. package/src/pantheon/local-decision-usage-evidence.internal.ts +207 -0
  49. package/src/pantheon/local-orchestration.ts +322 -0
  50. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  51. package/src/pantheon/v2-tools.ts +15 -14
  52. package/src/plugin-v2.ts +52 -19
  53. package/src/plugin.ts +4 -0
  54. package/src/plugins/tui/dist/tui-v2.js +3 -3
  55. package/src/plugins/tui/dist/tui.js +1 -1
  56. package/src/plugins/tui/package-lock.json +2 -2
  57. package/src/plugins/tui/package.json +1 -1
@@ -21,6 +21,8 @@ const TABLE = {
21
21
  cancelPoints: {
22
22
  components: 'component selection',
23
23
  target: 'install location',
24
+ decisionRouter: 'decision router selection',
25
+ egressConsent: 'external data-sharing consent',
24
26
  confirmation: 'pre-install confirmation',
25
27
  review: 'review prompt',
26
28
  interrupt: 'interrupt (Ctrl-C)',
@@ -30,6 +32,9 @@ const TABLE = {
30
32
  // stronger claim would be false.
31
33
  canceledAt: (point) =>
32
34
  `Installation canceled at ${point} — nothing was applied; no configuration was changed.`,
35
+ interruptedAfterWrite: (backupDir) =>
36
+ `Installation interrupted at Ctrl-C — changes may be partially applied; no automatic rollback was attempted. ` +
37
+ `The backup is preserved${backupDir ? ` at ${backupDir}` : ''}; inspect it and restore manually if needed.`,
33
38
  declinedAt: (point) =>
34
39
  `Installation declined at ${point} — nothing was applied; no configuration was changed; ` +
35
40
  're-run init to review the plan again.',
@@ -111,12 +116,17 @@ const TABLE = {
111
116
  cancelPoints: {
112
117
  components: 'seleção de componentes',
113
118
  target: 'local da instalação',
119
+ decisionRouter: 'seleção do roteador decisório',
120
+ egressConsent: 'consentimento de compartilhamento externo',
114
121
  confirmation: 'confirmação antes de instalar',
115
122
  review: 'prompt de revisão',
116
123
  interrupt: 'interrupção (Ctrl-C)',
117
124
  },
118
125
  canceledAt: (point) =>
119
126
  `Instalação cancelada em ${point} — nada foi aplicado; nenhuma configuração foi alterada.`,
127
+ interruptedAfterWrite: (backupDir) =>
128
+ `Instalação interrompida por Ctrl-C — alterações podem ter sido aplicadas parcialmente; nenhum rollback automático foi feito. ` +
129
+ `O backup foi preservado${backupDir ? ` em ${backupDir}` : ''}; revise e restaure manualmente se necessário.`,
120
130
  declinedAt: (point) =>
121
131
  `Instalação recusada em ${point} — nada foi aplicado; nenhuma configuração foi alterada; ` +
122
132
  'rode init de novo para revisar o plano.',
@@ -43,8 +43,8 @@ export function venvPythonPath(target) {
43
43
  * Set up a Python virtual environment and install MCP dependencies.
44
44
  *
45
45
  * @param {string} target - Target installation directory (e.g. ~/.config/opencode)
46
- * @param {{ dryRun?: boolean, skipInstall?: boolean, force?: boolean, recorder?: (change: object) => void, reviewedRemovals?: Set<string>|null, reviewedSnapshots?: Map<string, object>|null }} [options]
47
- * @returns {{ venvPath: string, python: string }}
46
+ * @param {{ dryRun?: boolean, skipInstall?: boolean, force?: boolean, verbose?: boolean, recorder?: (change: object) => void, reviewedRemovals?: Set<string>|null, reviewedSnapshots?: Map<string, object>|null }} [options]
47
+ * @returns {{ venvPath: string, python: string, runtimeEffects: { venv: 'create'|'reuse'|'recreate', dependencies: 'install'|'skip' } }}
48
48
  */
49
49
  export function setupVenv(
50
50
  target,
@@ -52,6 +52,7 @@ export function setupVenv(
52
52
  dryRun = false,
53
53
  skipInstall = false,
54
54
  force = false,
55
+ verbose = false,
55
56
  recorder = null,
56
57
  reviewedRemovals = null,
57
58
  reviewedSnapshots = null,
@@ -59,9 +60,13 @@ export function setupVenv(
59
60
  ) {
60
61
  const venvPath = join(target, '.venv')
61
62
  const pythonBin = venvPythonPath(target)
63
+ const hadVenv = existsSync(venvPath)
64
+ const recreateVenv = force && hadVenv
65
+ const hadPython = existsSync(pythonBin)
66
+ const venvAction = recreateVenv ? 'recreate' : hadPython ? 'reuse' : 'create'
62
67
 
63
68
  // Step 1: Force recreate venv if --force
64
- if (force && existsSync(venvPath)) {
69
+ if (recreateVenv) {
65
70
  if (dryRun) {
66
71
  recordRemovalTree(venvPath, recorder)
67
72
  info('.venv would be removed (--force)')
@@ -74,7 +79,7 @@ export function setupVenv(
74
79
  }
75
80
 
76
81
  // Step 1b: Create venv if not exists
77
- const venvExists = existsSync(pythonBin)
82
+ const venvExists = !recreateVenv && hadPython
78
83
  if (!venvExists) {
79
84
  if (dryRun) {
80
85
  // Never claim a directory was created by a run that writes nothing.
@@ -116,12 +121,12 @@ export function setupVenv(
116
121
  // Ensure PIP_USER=0 to install into venv, not user site-packages
117
122
  const pipEnv = { ...process.env, PIP_USER: '0' }
118
123
 
119
- // stdio is 'ignore' (pip is noisy here), so the step marker is the ONLY
120
- // evidence this ran — report both start and outcome instead of a silent
121
- // 30s pause.
124
+ // Inherit pip output while the step marker makes the upgrade's start
125
+ // and outcome explicit.
122
126
  const pipUpgradeStep = step('Upgrading pip')
123
- const pipUpgrade = spawnSync(pip, ['install', '--upgrade', 'pip'], {
124
- stdio: 'ignore',
127
+ const pipVerbosity = verbose ? ['--verbose'] : ['--quiet']
128
+ const pipUpgrade = spawnSync(pip, ['install', ...pipVerbosity, '--upgrade', 'pip'], {
129
+ stdio: 'inherit',
125
130
  timeout: 30_000,
126
131
  env: pipEnv,
127
132
  })
@@ -129,8 +134,9 @@ export function setupVenv(
129
134
  pipUpgradeStep(upgraded)
130
135
  if (!upgraded) warning('pip upgrade failed — continuing with the bundled version')
131
136
 
132
- // Install requirements — attempt 1: normal
133
- const r = spawnSync(pip, ['install', '-r', reqFile], {
137
+ // Pip's quiet mode keeps normal init output concise while preserving
138
+ // stderr and its non-zero status; --verbose retains resolver detail.
139
+ const r = spawnSync(pip, ['install', ...pipVerbosity, '-r', reqFile], {
134
140
  stdio: 'inherit',
135
141
  timeout: 120_000,
136
142
  env: pipEnv,
@@ -139,11 +145,15 @@ export function setupVenv(
139
145
  if (r.status !== 0) {
140
146
  // Attempt 2: --break-system-packages (PEP 668 / externally-managed)
141
147
  warning('First attempt failed, retrying with --break-system-packages...')
142
- const r2 = spawnSync(pip, ['install', '-r', reqFile, '--break-system-packages'], {
143
- stdio: 'inherit',
144
- timeout: 120_000,
145
- env: pipEnv,
146
- })
148
+ const r2 = spawnSync(
149
+ pip,
150
+ ['install', ...pipVerbosity, '-r', reqFile, '--break-system-packages'],
151
+ {
152
+ stdio: 'inherit',
153
+ timeout: 120_000,
154
+ env: pipEnv,
155
+ },
156
+ )
147
157
  if (r2.status !== 0) {
148
158
  throw new Error(
149
159
  'Failed to install MCP dependencies. ' +
@@ -169,7 +179,14 @@ export function setupVenv(
169
179
  info('Dependency install skipped (--skip-install)')
170
180
  }
171
181
 
172
- return { venvPath, python: pythonBin }
182
+ return {
183
+ venvPath,
184
+ python: pythonBin,
185
+ runtimeEffects: {
186
+ venv: venvAction,
187
+ dependencies: skipInstall ? 'skip' : 'install',
188
+ },
189
+ }
173
190
  }
174
191
 
175
192
  // ---------------------------------------------------------------------------
@@ -35,6 +35,7 @@ import {
35
35
  restoreBackupSet,
36
36
  verifyBackupSet,
37
37
  } from './install/backup.mjs'
38
+ import { PROMPT_CANCELED } from './install/prompt-result.mjs'
38
39
 
39
40
  /**
40
41
  * Resolve the config dir whose `opencode.json` the installer manages.
@@ -122,9 +123,16 @@ export function pickBackupSet(configDir, from) {
122
123
  * @param {string} opts.backupDir
123
124
  * @param {boolean} [opts.dryRun]
124
125
  * @param {boolean} [opts.yes]
125
- * @returns {Promise<{ ok: boolean, code: number, entries?: object[] }>}
126
+ * @param {(message: string, options: object) => Promise<unknown>} [opts.promptReview]
127
+ * @returns {Promise<{ ok: boolean, code: number, reason?: string, entries?: object[] }>}
126
128
  */
127
- export async function runRestore({ configDir, backupDir, dryRun = false, yes = false }) {
129
+ export async function runRestore({
130
+ configDir,
131
+ backupDir,
132
+ dryRun = false,
133
+ yes = false,
134
+ promptReview: injectedPromptReview = null,
135
+ }) {
128
136
  const verify = verifyBackupSet(backupDir)
129
137
  if (!verify.ok) {
130
138
  console.error(
@@ -155,22 +163,26 @@ export async function runRestore({ configDir, backupDir, dryRun = false, yes = f
155
163
 
156
164
  if (dryRun) {
157
165
  console.log(' (dry-run) No files were written.')
158
- return { ok: true, code: 0, entries: plan.entries }
166
+ return { ok: true, code: 0, reason: 'preview', entries: plan.entries }
159
167
  }
160
168
 
161
- if (!yes) {
169
+ if (yes !== true) {
162
170
  // Reuse the shared confirm semantics (default NO). An interactive TTY may
163
171
  // authorize without --yes; a non-TTY run must never proceed silently.
164
172
  const tty = Boolean(process.stdin.isTTY && process.stdout.isTTY)
165
- if (!tty) {
173
+ if (!tty && typeof injectedPromptReview !== 'function') {
166
174
  console.error('❌ Refusing to restore without authorization. Re-run with --yes.')
167
- return { ok: false, code: 1 }
175
+ return { ok: false, code: 1, reason: 'not-authorized', entries: plan.entries }
168
176
  }
169
- const { promptReview } = await import('./install/interactive.mjs')
177
+ const promptReview =
178
+ injectedPromptReview ?? (await import('./install/interactive.mjs')).promptReview
170
179
  const accepted = await promptReview('Restore these changes?', { default: false })
171
- if (!accepted) {
180
+ if (accepted === PROMPT_CANCELED) {
181
+ return { ok: false, code: 130, reason: 'canceled', entries: plan.entries }
182
+ }
183
+ if (accepted !== true) {
172
184
  console.log(' Nothing restored.')
173
- return { ok: true, code: 0, entries: plan.entries }
185
+ return { ok: true, code: 0, reason: 'declined', entries: plan.entries }
174
186
  }
175
187
  }
176
188
 
@@ -189,7 +201,7 @@ export async function runRestore({ configDir, backupDir, dryRun = false, yes = f
189
201
 
190
202
  restoreBackupSet(backupDir, configDir, { dryRun: false })
191
203
  console.log(` ✅ Restored ${plan.entries.length} path(s).`)
192
- return { ok: true, code: 0, entries: plan.entries }
204
+ return { ok: true, code: 0, reason: 'restored', entries: plan.entries }
193
205
  }
194
206
 
195
207
  async function main() {
@@ -17,8 +17,9 @@
17
17
  #
18
18
  # Modes (run sequentially; a failure stops later checks):
19
19
  # --prepare Build tarball, install pantheon-opencode + the OpenCode V2
20
- # binary in the sandbox prefix, headless init, and generate
21
- # the project config and sandbox run-test.sh.
20
+ # binary in the sandbox prefix, headless init with the
21
+ # default components plus opt-in runtime, and generate the
22
+ # project config and sandbox run-test.sh.
22
23
  # --run v2 Base validation: opencode mcp list + doctor (config is
23
24
  # regenerated first).
24
25
  # --prompts Prompt battery via `opencode run --format json`.
@@ -1043,7 +1044,8 @@ npm install -g "$TGZ"
1043
1044
  if ! git -C "$REPO_DIR" ls-files --error-unmatch -- "$TGZ" >/dev/null 2>&1; then rm -f -- "$TGZ"; fi
1044
1045
 
1045
1046
  echo "--- Init (headless) ---"
1046
- pantheon-opencode init --headless -y
1047
+ pantheon-opencode init --headless -y \
1048
+ --components agents,skills,instructions,commands,plugins,runtime
1047
1049
  rewrite_v2_mcp_config
1048
1050
  if ! node "$REPO_DIR/scripts/validate-sandbox-install.mjs" \
1049
1051
  --repo "$REPO_DIR" \
@@ -1436,7 +1438,7 @@ prepare_project() {
1436
1438
  pan="$(sandbox_bin_for "pantheon-opencode")" \
1437
1439
  || die "pantheon-opencode not installed in sandbox prefix — run $0 --prepare first"
1438
1440
  log "--- Regenerating config in $dir ---"
1439
- (cd "$dir" && "$pan" init --project --version "$TARGET_VERSION" --model "$PANTHEON_SANDBOX_MODEL" -y) \
1441
+ (cd "$dir" && "$pan" init --project --version "$TARGET_VERSION" --model "$PANTHEON_SANDBOX_MODEL" --components agents,skills,instructions,commands,plugins,runtime -y) \
1440
1442
  || die "sandbox project initialization failed"
1441
1443
  rewrite_v2_mcp_config
1442
1444
  validate_sandbox_install
@@ -1550,8 +1552,10 @@ cmd_prepare() {
1550
1552
  local pan
1551
1553
  pan="$(sandbox_bin_for "pantheon-opencode")" \
1552
1554
  || die "pantheon-opencode not found in sandbox prefix after install"
1553
- log "--- Headless init (global venv + runtime) ---"
1554
- "$pan" init --headless -y --model "$PANTHEON_SANDBOX_MODEL" \
1555
+ log "--- Headless init (default components + runtime) ---"
1556
+ "$pan" init --headless -y \
1557
+ --components agents,skills,instructions,commands,plugins,runtime \
1558
+ --model "$PANTHEON_SANDBOX_MODEL" \
1555
1559
  || die "pantheon-opencode init --headless failed"
1556
1560
  prepare_project
1557
1561
  write_extract_py
@@ -36,6 +36,18 @@ skills:
36
36
 
37
37
  **Coordenador APENAS. Zeus NUNCA lê arquivos de código-fonte.** Toda leitura de `src/`, `tests/`, `scripts/` vai para @apollo. Leia apenas: config, docs, memory bank, delegação.
38
38
 
39
+ ## Local advisory routing before native delegation
40
+
41
+ - 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, use `pantheon_local_decision` only if it is present. It evaluates locally only; provider transport/API has been removed, and provider configuration, consent, caps, or period confirmation do not enable runtime calls. If absent, unconfigured, or it abstains, continue with your own routing judgment and the host's actual native tool schema.
43
+ - 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
+ - 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
+ - Construct the final Brief locally and use native `subagent` unchanged; native dispatch is always the final routing action. The local recommendation tool never dispatches, loads skills/resources, searches memory, or changes grants/gates. No remote Jev or OpenAI Decisions runtime calls are available, regardless of user control settings.
47
+ This local-only guarantee applies only to decision routing, not all product egress.
48
+ Separately documented quota (including manual `/quota-go-check`) and Vision
49
+ integrations retain their own external-request behavior.
50
+
39
51
  ## Visual Context for Implementation
40
52
 
41
53
  Zeus never implements code, but visual references from the user are implementation context and must reach the specialist who does the work.
@@ -0,0 +1,170 @@
1
+ import type { LocalDecisionPolicy } from './local-orchestration.ts'
2
+ import { PANTHEON_AGENT_CATALOG, PANTHEON_AGENT_IDS } from './pantheon-decision-catalog.ts'
3
+ import { isAgentAllowed } from './permission-globs.ts'
4
+ import { PANTHEON_AGENTS } from './v2-delegation-enforce.ts'
5
+
6
+ export type AgentRecommendationReason =
7
+ | 'RECOMMENDED'
8
+ | 'NO_DELEGATION_SIGNAL'
9
+ | 'NO_ELIGIBLE_CANDIDATE'
10
+ | 'AMBIGUOUS_CANDIDATE'
11
+ | 'POLICY_UNAVAILABLE'
12
+ | 'INVALID_INPUT'
13
+
14
+ export interface LocalAgentRecommendation {
15
+ agent: string | null
16
+ reasonCode: AgentRecommendationReason
17
+ }
18
+
19
+ const MAX_REQUEST_LENGTH = 20_000
20
+ const CATALOG_ORDER = new Map(PANTHEON_AGENT_CATALOG.map((entry, index) => [entry.id, index]))
21
+
22
+ const EXPLICIT_DELEGATION_TOKENS = new Set([
23
+ 'delegate',
24
+ 'delegation',
25
+ 'delegar',
26
+ 'delegacao',
27
+ 'handoff',
28
+ 'subagent',
29
+ 'specialist',
30
+ 'especialista',
31
+ 'route',
32
+ 'routing',
33
+ 'parallel',
34
+ 'paralelo',
35
+ ])
36
+
37
+ const ACTION_TOKENS = new Set([
38
+ 'add',
39
+ 'audit',
40
+ 'build',
41
+ 'change',
42
+ 'create',
43
+ 'debug',
44
+ 'design',
45
+ 'fix',
46
+ 'implement',
47
+ 'implementar',
48
+ 'investigate',
49
+ 'migrate',
50
+ 'optimize',
51
+ 'plan',
52
+ 'planejar',
53
+ 'refactor',
54
+ 'research',
55
+ 'review',
56
+ 'revisar',
57
+ 'update',
58
+ ])
59
+
60
+ /** Specialist keywords. Scores are local only and never grant permission. */
61
+ const AGENT_KEYWORDS: Readonly<Record<string, readonly string[]>> = Object.freeze({
62
+ athena: ['plan', 'planning', 'architecture', 'architect', 'strategy', 'spec', 'requirements'],
63
+ apollo: ['investigate', 'investigation', 'research', 'discovery', 'explore', 'find', 'search'],
64
+ hermes: ['api', 'backend', 'fastapi', 'python', 'endpoint', 'async', 'server', 'pytest'],
65
+ aphrodite: [
66
+ 'frontend',
67
+ 'react',
68
+ 'typescript',
69
+ 'css',
70
+ 'component',
71
+ 'ui',
72
+ 'accessibility',
73
+ 'wcag',
74
+ 'responsive',
75
+ ],
76
+ demeter: ['database', 'sql', 'schema', 'migration', 'alembic', 'sqlalchemy', 'query', 'index'],
77
+ themis: ['security', 'owasp', 'audit', 'lint', 'coverage', 'quality', 'vulnerability', 'cve'],
78
+ prometheus: ['docker', 'ci', 'pipeline', 'deploy', 'infrastructure', 'provider', 'container'],
79
+ hephaestus: ['langchain', 'langgraph', 'rag', 'vector', 'embedding', 'llm', 'pipeline', 'ai'],
80
+ nyx: ['observability', 'telemetry', 'opentelemetry', 'tracing', 'metrics', 'langsmith', 'cost'],
81
+ gaia: ['satellite', 'spectral', 'sar', 'geospatial', 'imagery', 'remote', 'sensing'],
82
+ iris: ['github', 'pull', 'request', 'issue', 'branch', 'release', 'tag', 'pr'],
83
+ mnemosyne: ['memory', 'adr', 'documentation', 'knowledge', 'persistent'],
84
+ talos: ['typo', 'hotfix', 'small', 'quick', 'minor', 'css'],
85
+ })
86
+
87
+ function normalize(value: string): string {
88
+ return value
89
+ .normalize('NFD')
90
+ .replace(/[\u0300-\u036f]/g, '')
91
+ .toLowerCase()
92
+ }
93
+
94
+ function tokenize(value: string): Set<string> {
95
+ const tokens = value.match(/[a-z0-9]+(?:[+#.-][a-z0-9]+)*/g) ?? []
96
+ return new Set(tokens)
97
+ }
98
+
99
+ /** True when the request plausibly considers delegating to a specialist. */
100
+ export function hasDelegationSignal(request: unknown): boolean {
101
+ if (typeof request !== 'string' || request.trim().length === 0) return false
102
+ if (request.length > MAX_REQUEST_LENGTH) return false
103
+ const tokens = tokenize(normalize(request))
104
+ for (const token of EXPLICIT_DELEGATION_TOKENS) {
105
+ if (tokens.has(token)) return true
106
+ }
107
+ if (![...tokens].some((token) => ACTION_TOKENS.has(token))) return false
108
+ return [...tokens].some((token) =>
109
+ Object.values(AGENT_KEYWORDS).some((keywords) => keywords.includes(token)),
110
+ )
111
+ }
112
+
113
+ /** Intersect canonical agents with Zeus grants, routing defaults, and task rules. */
114
+ export function listEligibleDecisionAgents(policy: LocalDecisionPolicy | undefined): string[] {
115
+ if (policy === undefined || !PANTHEON_AGENTS.has('zeus')) return []
116
+ const zeus = policy.agents.zeus
117
+ if (zeus === undefined) return []
118
+ return PANTHEON_AGENT_CATALOG.filter(({ id }) => id !== 'zeus')
119
+ .filter(({ id }) => {
120
+ const target = policy.agents[id]
121
+ return (
122
+ PANTHEON_AGENT_IDS.has(id) &&
123
+ target?.canReceiveDelegation === true &&
124
+ zeus.canDelegateTo.includes(id) &&
125
+ isAgentAllowed(policy.permissionTask, id)
126
+ )
127
+ })
128
+ .map(({ id }) => id)
129
+ }
130
+
131
+ /**
132
+ * Recommend at most one canonical specialist, or abstain. The result is
133
+ * advisory only: it neither dispatches nor grants anything.
134
+ */
135
+ export function recommendLocalDecisionAgent(
136
+ request: unknown,
137
+ policy: LocalDecisionPolicy | undefined,
138
+ ): LocalAgentRecommendation {
139
+ if (typeof request !== 'string' || request.trim().length === 0) {
140
+ return { agent: null, reasonCode: 'INVALID_INPUT' }
141
+ }
142
+ if (request.length > MAX_REQUEST_LENGTH) {
143
+ return { agent: null, reasonCode: 'INVALID_INPUT' }
144
+ }
145
+ if (policy === undefined) return { agent: null, reasonCode: 'POLICY_UNAVAILABLE' }
146
+ if (!hasDelegationSignal(request)) {
147
+ return { agent: null, reasonCode: 'NO_DELEGATION_SIGNAL' }
148
+ }
149
+
150
+ const eligible = new Set(listEligibleDecisionAgents(policy))
151
+ if (eligible.size === 0) return { agent: null, reasonCode: 'NO_ELIGIBLE_CANDIDATE' }
152
+
153
+ const tokens = tokenize(normalize(request))
154
+ const scored: Array<{ id: string; score: number; order: number }> = []
155
+ for (const id of eligible) {
156
+ const keywords = AGENT_KEYWORDS[id] ?? []
157
+ const score = keywords.reduce((total, keyword) => total + (tokens.has(keyword) ? 1 : 0), 0)
158
+ if (score <= 0) continue
159
+ scored.push({ id, score, order: CATALOG_ORDER.get(id) ?? 0 })
160
+ }
161
+ if (scored.length === 0) return { agent: null, reasonCode: 'NO_ELIGIBLE_CANDIDATE' }
162
+
163
+ scored.sort((left, right) => right.score - left.score || left.order - right.order)
164
+ const [first, second] = scored
165
+ if (first === undefined) return { agent: null, reasonCode: 'NO_ELIGIBLE_CANDIDATE' }
166
+ if (second !== undefined && second.score === first.score) {
167
+ return { agent: null, reasonCode: 'AMBIGUOUS_CANDIDATE' }
168
+ }
169
+ return { agent: first.id, reasonCode: 'RECOMMENDED' }
170
+ }