@elliotsystems/eai 0.1.4 → 0.1.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.
@@ -20,10 +20,10 @@
20
20
  * `.opencode/plugin/` file re-export.
21
21
  */
22
22
  import { isElliotKnowledgeTool, parseOptions, shellVerdict } from "./policy.js"
23
- import { ELLIOT_PROVIDER_ID, configHook, makeAuthHook } from "./proxy-provider.js"
24
- import { readElliotConfig } from "./elliot-auth.js"
23
+ import { configHook } from "./proxy-provider.js"
25
24
  import { formatScope, scopeForWorktree } from "./scope.js"
26
25
  import { applyElliotIdentity } from "./identity.js"
26
+ import { resolveEndUserId, type SessionClient } from "./identity-headers.js"
27
27
 
28
28
  // Structural mirrors of the host types (packages/plugin/src/index.ts @
29
29
  // v1.18.19). Declared locally so this package type-checks and unit-tests
@@ -38,6 +38,7 @@ export interface PluginInput {
38
38
  auth?: {
39
39
  set: (input: { path: { id: string }; body: Record<string, unknown> }) => Promise<unknown>
40
40
  }
41
+ session?: SessionClient["session"]
41
42
  [k: string]: unknown
42
43
  }
43
44
  serverUrl?: URL
@@ -71,6 +72,10 @@ export interface Hooks {
71
72
  input: { sessionID?: string; model: unknown },
72
73
  output: { system: string[] },
73
74
  ) => Promise<void>
75
+ "chat.headers"?: (
76
+ input: { sessionID: string; agent: unknown; model: unknown; provider: unknown; message: unknown },
77
+ output: { headers: Record<string, string> },
78
+ ) => Promise<void>
74
79
  config?: (input: any) => Promise<void>
75
80
  auth?: AuthHook
76
81
  dispose?: () => Promise<void>
@@ -87,25 +92,6 @@ export const ElliotPlugin: Plugin = async (input, rawOptions) => {
87
92
  // the one source the model cannot influence.
88
93
  const worktree = input.worktree || input.directory
89
94
 
90
- // Seed a placeholder auth entry for the `elliot` provider so the host's
91
- // auth loader fires at all (`provider.ts:1584` skips the loader entirely
92
- // when nothing is stored for its provider id — see Task-1 findings). The
93
- // value itself is never the credential that reaches the wire; the auth
94
- // loader's `fetch` attaches the live bearer token per request. Guarded so
95
- // a client-RPC failure never breaks plugin init, and skipped outright when
96
- // the user isn't logged into Elliot.
97
- if (readElliotConfig()) {
98
- try {
99
- await input.client?.auth?.set({
100
- path: { id: ELLIOT_PROVIDER_ID },
101
- body: { type: "api", key: "elliot-managed" },
102
- })
103
- } catch {
104
- // Never break plugin init on a seeding failure — the auth loader
105
- // simply won't fire this session, same as the no-login path.
106
- }
107
- }
108
-
109
95
  return {
110
96
  /**
111
97
  * One handler, two jobs — a JS object literal may carry only one
@@ -177,6 +163,18 @@ export const ElliotPlugin: Plugin = async (input, rawOptions) => {
177
163
  applyElliotIdentity(output.system)
178
164
  },
179
165
 
166
+ /**
167
+ * Per-message LiteLLM `end_user` override for a TEAM-shared runtime. See
168
+ * ./identity-headers.ts for the full rationale. A no-op (static header
169
+ * untouched) when the session carries no stamped identity — a generic
170
+ * instance, a pre-existing session, or a client that doesn't expose
171
+ * `session.get` at all.
172
+ */
173
+ "chat.headers": async (hookInput, output) => {
174
+ const userId = await resolveEndUserId(input.client as SessionClient | undefined, hookInput.sessionID)
175
+ if (userId) output.headers["x-litellm-end-user-id"] = userId
176
+ },
177
+
180
178
  "permission.ask": async (permInput, output) => {
181
179
  if (permInput.type !== "bash") return
182
180
  const command = permInput.metadata?.["command"]
@@ -188,20 +186,13 @@ export const ElliotPlugin: Plugin = async (input, rawOptions) => {
188
186
  },
189
187
 
190
188
  /**
191
- * Registers the `elliot` provider (proxy baseURL) and defaults the
192
- * model to it — no-op when the user isn't logged into Elliot. See
193
- * `proxy-provider.ts`.
189
+ * Registers the `elliot` provider (LiteLLM gateway baseURL + static
190
+ * gateway key) and defaults the model to it — no-op when the user isn't
191
+ * logged into Elliot. See `proxy-provider.ts`.
194
192
  */
195
193
  config: async (c) => {
196
194
  configHook(c)
197
195
  },
198
-
199
- /**
200
- * Self-refreshing auth loader for the `elliot` provider — see
201
- * `proxy-provider.ts`. Only fires once the seeding above has stored an
202
- * auth entry for `ELLIOT_PROVIDER_ID`.
203
- */
204
- auth: makeAuthHook(),
205
196
  }
206
197
  }
207
198
 
@@ -24,7 +24,138 @@ export function sanitizeKey(value: string): string {
24
24
  /** The backend tool behind every Elliot knowledge lookup. */
25
25
  export const KNOWLEDGE_TOOL = "knowledge_search"
26
26
 
27
- /** The agent-visible key for `KNOWLEDGE_TOOL` on a given MCP server. */
27
+ /** The backend tool behind "my own real EAI Gateway spend" (`/usage`, and the
28
+ * sidebar's real-spend section -- see `tui/usage.ts`). */
29
+ export const USAGE_TOOL = "get_eai_usage"
30
+
31
+ /** The agent-visible key for `KNOWLEDGE_TOOL` on a given MCP server.
32
+ *
33
+ * Still the PRE-GATEWAY spelling, and still correct for a runtime wired
34
+ * straight to Elliot. It is no longer the only spelling that arrives — see
35
+ * `toCanonicalTool`.
36
+ */
28
37
  export function knowledgeToolKey(serverName: string): string {
29
38
  return `${sanitizeKey(serverName)}_${KNOWLEDGE_TOOL}`
30
39
  }
40
+
41
+ /**
42
+ * LiteLLM joins its server alias to the tool name with a HYPHEN; OpenCode
43
+ * joins its own server key with an UNDERSCORE. Both appear in one wire name
44
+ * and they are not interchangeable.
45
+ *
46
+ * The SEPARATOR is LiteLLM's composition rule and is fixed. The ALIAS is
47
+ * configuration — it is the `mcp_servers` key in `deploy/litellm/config.yaml`
48
+ * — and this module no longer owns a copy of it. It used to:
49
+ *
50
+ * export const GATEWAY_SERVER_ALIAS = "elliot"
51
+ *
52
+ * restated from the backend and "kept in step by a test". That is four copies
53
+ * of one literal across two languages, and the failure when they diverge is
54
+ * silent: an unrecognised tool name is one whose repo scope is never injected,
55
+ * so the agent answers tenant-wide and says nothing about it.
56
+ *
57
+ * The alias now arrives as a plugin option, served by the backend from
58
+ * `litellm_mcp_server_alias` (`routers/well_known.py`).
59
+ */
60
+ const GATEWAY_SEPARATOR = "-"
61
+
62
+ /**
63
+ * The canonical Elliot tool name behind an agent-visible key.
64
+ *
65
+ * Runtime traffic now reaches Elliot through LiteLLM's MCP gateway, and each
66
+ * hop adds its own namespace. All four spellings below are real, depending on
67
+ * whether the runtime is behind the gateway and how the host composed the key:
68
+ *
69
+ * elliot_elliot-knowledge_search OpenCode prefix + gateway prefix
70
+ * elliot-knowledge_search gateway prefix only
71
+ * elliot_knowledge_search OpenCode prefix only (pre-gateway)
72
+ * knowledge_search bare/canonical
73
+ *
74
+ * Stripping is DETERMINISTIC and bounded: at most one server prefix, then at
75
+ * most one gateway prefix, each only from the front. Never a suffix or
76
+ * substring match — that is what stops a server called `not-elliot` from
77
+ * collecting scope hints meant for ours, and it is why the configured server
78
+ * names are required rather than inferred.
79
+ *
80
+ * Idempotent: feeding a canonical name back in returns it unchanged.
81
+ */
82
+ /**
83
+ * The canonical tool name when the gateway alias is NOT knowable.
84
+ *
85
+ * For the TUI only. The TUI plugin entry (`tui: TuiPlugin = async (api)`)
86
+ * receives no options — the host hands it a UI api and nothing else — so it
87
+ * cannot be told the configured alias, and inventing a config channel for a
88
+ * sidebar would be a worse answer than this one.
89
+ *
90
+ * So it matches on STRUCTURE rather than on a specific alias: strip one
91
+ * configured server prefix, then allow ONE unknown `<something>-` layer.
92
+ *
93
+ * THIS IS NOT A FALLBACK TO A GUESSED ALIAS, and it does not weaken the
94
+ * anti-substring property that `toCanonicalTool` exists to hold. That property
95
+ * comes from the SERVER prefix, which the TUI does know (`api.state.mcp()`
96
+ * supplies it) and which is still required here. By the time an unknown
97
+ * gateway layer is considered, the key has already been proven to belong to a
98
+ * configured Elliot server — `not-elliot_knowledge_search` never reaches that
99
+ * line.
100
+ *
101
+ * Confined to display. Nothing authorizes on this: the sidebar decides which
102
+ * transcript rows to render, and the cost of a wrong answer is a missing or
103
+ * extra row, not a wrong scope. Authorization uses `toCanonicalTool` with the
104
+ * configured alias, on the backend, where the alias is known.
105
+ */
106
+ export function toCanonicalToolUnderAnyGateway(
107
+ toolKey: string,
108
+ serverNames: readonly string[],
109
+ ): string {
110
+ if (!toolKey) return toolKey
111
+ let rest = toolKey
112
+ for (const server of serverNames) {
113
+ const prefix = `${sanitizeKey(server)}_`
114
+ if (rest.startsWith(prefix)) {
115
+ rest = rest.slice(prefix.length)
116
+ break
117
+ }
118
+ }
119
+ // One unknown gateway layer, and only one: `<alias>-<tool>`. The alias may
120
+ // not itself contain the separator, which is what keeps this bounded.
121
+ const layer = rest.indexOf(GATEWAY_SEPARATOR)
122
+ if (layer > 0) {
123
+ const remainder = rest.slice(layer + GATEWAY_SEPARATOR.length)
124
+ if (remainder) return remainder
125
+ }
126
+ return rest
127
+ }
128
+
129
+ export function toCanonicalTool(
130
+ toolKey: string,
131
+ serverNames: readonly string[],
132
+ gatewayAlias: string,
133
+ ): string {
134
+ if (!toolKey) return toolKey
135
+ if (!gatewayAlias) {
136
+ // No silent `|| "elliot"`. A missing alias means the caller is
137
+ // misconfigured, and guessing one would restore the duplicated literal
138
+ // this parameter exists to remove — while hiding the misconfiguration
139
+ // behind behaviour that happens to be right in one deployment.
140
+ throw new Error("toCanonicalTool requires the configured gateway alias")
141
+ }
142
+ const gatewayPrefix = `${gatewayAlias}${GATEWAY_SEPARATOR}`
143
+ let rest = toolKey
144
+
145
+ // One OpenCode `<server>_` prefix, and only for a server we are configured
146
+ // for. An unconfigured server's tools are not ours to recognise.
147
+ for (const server of serverNames) {
148
+ const prefix = `${sanitizeKey(server)}_`
149
+ if (rest.startsWith(prefix)) {
150
+ rest = rest.slice(prefix.length)
151
+ break
152
+ }
153
+ }
154
+
155
+ // Then one LiteLLM `<alias>-` prefix.
156
+ if (rest.startsWith(gatewayPrefix)) {
157
+ rest = rest.slice(gatewayPrefix.length)
158
+ }
159
+
160
+ return rest
161
+ }
@@ -19,7 +19,7 @@ import {
19
19
  killsAgentRuntime,
20
20
  looksLikeCredentialExfiltration,
21
21
  } from "./classifier.js"
22
- import { KNOWLEDGE_TOOL, knowledgeToolKey, sanitizeKey } from "./mcp-keys.js"
22
+ import { KNOWLEDGE_TOOL, sanitizeKey, toCanonicalTool } from "./mcp-keys.js"
23
23
 
24
24
  const OptionsSchema = z
25
25
  .object({
@@ -30,6 +30,27 @@ const OptionsSchema = z
30
30
  * what let the hooks recognise Elliot tools.
31
31
  */
32
32
  serverNames: z.array(z.string().min(1)).min(1).default(["elliot"]),
33
+ /**
34
+ * The LiteLLM MCP gateway's alias for Elliot — the `mcp_servers` key in
35
+ * `deploy/litellm/config.yaml`, which LiteLLM also uses as the prefix on
36
+ * every tool it proxies (`<alias>-<tool>`).
37
+ *
38
+ * REQUIRED, and deliberately without a default. This value used to be a
39
+ * constant in `mcp-keys.ts`, a fourth copy of a literal that also lives in
40
+ * the backend settings, the backend namespace module and the LiteLLM YAML.
41
+ * A default here would be that copy again: a plugin configured without the
42
+ * option would keep working against a guess, and would break silently on
43
+ * the day someone renamed the YAML key — recognising no gateway-prefixed
44
+ * tool, injecting no repo scope, and reporting nothing.
45
+ *
46
+ * The backend serves it with the plugin spec (`routers/well_known.py`),
47
+ * from `litellm_mcp_server_alias`.
48
+ *
49
+ * Distinct from `serverNames`, which is OpenCode's own server key and
50
+ * joins with an UNDERSCORE. Both read "elliot" in the default deployment
51
+ * and they are not the same value.
52
+ */
53
+ gatewayAlias: z.string().min(1),
33
54
  })
34
55
  .strict()
35
56
 
@@ -53,11 +74,22 @@ export { KNOWLEDGE_TOOL, sanitizeKey }
53
74
 
54
75
  /**
55
76
  * Is this agent-visible tool key Elliot's knowledge tool on one of our
56
- * configured servers? Exact composed-key match only — a suffix match would let
57
- * an unrelated MCP server named e.g. "not-elliot" receive our scope hints.
77
+ * configured servers?
78
+ *
79
+ * NORMALISED FIRST, then matched exactly. It used to compare against one
80
+ * composed spelling, which stopped matching the moment runtime traffic moved
81
+ * behind the LiteLLM MCP gateway and the key gained a second namespace
82
+ * (`elliot_elliot-knowledge_search`). A knowledge call that is not recognised
83
+ * here is one that silently loses its repository scope — the agent still
84
+ * answers, just tenant-wide instead of repo-focused, and nothing in the reply
85
+ * says so.
86
+ *
87
+ * The anti-substring property is unchanged: `toCanonicalTool` strips only a
88
+ * prefix belonging to a CONFIGURED server, so `not-elliot_knowledge_search`
89
+ * still does not match.
58
90
  */
59
91
  export function isElliotKnowledgeTool(toolKey: string, options: ElliotPluginOptions): boolean {
60
- return options.serverNames.some((server) => toolKey === knowledgeToolKey(server))
92
+ return toCanonicalTool(toolKey, options.serverNames, options.gatewayAlias) === KNOWLEDGE_TOOL
61
93
  }
62
94
 
63
95
  // -- Shell policy verdicts ---------------------------------------------------
@@ -1,96 +1,177 @@
1
1
  /**
2
- * The Elliot proxy provider: a `config` hook that registers a custom
3
- * `elliot` OpenCode provider pointed at the Elliot LightLLM proxy, and an
4
- * `auth` hook whose `loader` returns a self-refreshing `fetch` that attaches
5
- * a live bearer token per request.
2
+ * The Elliot provider: a `config` hook that registers a custom `elliot`
3
+ * OpenCode provider pointed at LiteLLM directly.
6
4
  *
7
- * Mechanism pinned in `.superpowers/sdd/2026-09-03-eai-proxy-auth/task-1-findings.md`:
8
- * - `config` hook mutates its input in place (no separate output param).
9
- * - `auth.loader`'s return value is spread wholesale into the provider's
10
- * resolved `options`, so `{ apiKey, fetch }` land there directly.
11
- * - `apiKey` is baked into the AI-SDK client at construction time and
12
- * never changes; the actually-rotating credential is injected per
13
- * request by `options.fetch`'s `Authorization` header (never the static
14
- * `apiKey`) — same pattern as OpenCode's bundled snowflake-cortex plugin.
15
- * - The loader only runs once a stored auth entry exists for its
16
- * `provider` id (`provider.ts:1584`); the plugin seeds that entry itself
17
- * at init (see `index.ts`) so no interactive `opencode auth login` step
18
- * is ever required.
5
+ * Since `/llm-proxy` was removed, this no longer needs a self-refreshing
6
+ * per-request `auth` hook (Task-1's pinned mechanism, `.superpowers/sdd/
7
+ * 2026-09-03-eai-proxy-auth/task-1-findings.md` — kept only as history: the
8
+ * per-instance JWT that mechanism refreshed doesn't authenticate this path
9
+ * anymore). LiteLLM's `litellm_master_key` is ONE static secret for the whole
10
+ * gateway — it never expires, so it is baked into `options.apiKey` directly,
11
+ * the same way OpenCode's own `{env:VAR}` config substitution would, just
12
+ * read from `~/.elliot/config.json` instead of the process environment.
19
13
  *
20
14
  * Everything here is a no-op when the user isn't logged in
21
15
  * (`readElliotConfig()` returns null) — OpenCode then runs exactly as it
22
16
  * would without this plugin.
23
17
  */
24
- import { freshToken, readElliotConfig } from "./elliot-auth.js"
18
+ import { readElliotConfig, type ElliotCredential } from "./elliot-auth.js"
25
19
 
26
- export const ELLIOT_LLM_PROXY_URL = "https://backend.elliotsystemsonline.com/llm-proxy"
27
20
  export const ELLIOT_PROVIDER_ID = "elliot"
21
+ export const ELLIOT_GENERAL_MODEL_ID = "elliot-general"
22
+ export const ELLIOT_CODER_MODEL_ID = "elliot-coder"
23
+
24
+ // `limit`/`cost` are what the OpenCode TUI's own sidebar ("Context ... %
25
+ // used ... spent") computes the context-window percentage and per-session
26
+ // dollar cost from (opencode/packages/tui/src/feature-plugins/sidebar/
27
+ // context.tsx) — without them it always shows "0% used"/"$0.00 spent"
28
+ // regardless of real usage, since there is nothing to divide/multiply by.
29
+ //
30
+ // Neither LiteLLM nor its own cost map has this data for either model
31
+ // (confirmed live: `GET /model/info` on the local gateway returns
32
+ // `max_tokens`/`max_input_tokens`/`input_cost_per_token`/
33
+ // `output_cost_per_token` as null/0 for both elliot-general and
34
+ // elliot-coder) — both route to the same OpenRouter deployment,
35
+ // `openrouter/deepseek/deepseek-v4-flash-0731` (deploy/litellm/
36
+ // config.yaml), so the figures below are OpenRouter's own published model
37
+ // data for that exact slug (`GET https://openrouter.ai/api/v1/models`,
38
+ // confirmed live 2026-10-14: context_length 1048576, top_provider.
39
+ // max_completion_tokens 943718, pricing.prompt $0.000000016/token,
40
+ // pricing.completion $0.00000064/token) — not a guess, and not a figure
41
+ // for a different/similar-sounding model. `cost` is $-per-MILLION-tokens,
42
+ // matching this schema's own convention elsewhere (e.g. opencode/packages/
43
+ // opencode/test/provider/transform.test.ts's real-model fixtures), so the
44
+ // per-token prices above are multiplied by 1e6.
45
+ const ALL_MODELS = {
46
+ [ELLIOT_GENERAL_MODEL_ID]: {
47
+ name: "EAI General",
48
+ limit: { context: 1_048_576, output: 943_718 },
49
+ cost: { input: 0.016, output: 0.64 },
50
+ },
51
+ [ELLIOT_CODER_MODEL_ID]: {
52
+ name: "EAI Coder",
53
+ limit: { context: 1_048_576, output: 943_718 },
54
+ cost: { input: 0.016, output: 0.64 },
55
+ },
56
+ }
28
57
 
29
58
  /**
30
- * Registers the `elliot` provider (baseURL = the LightLLM proxy) and
31
- * defaults `cfg.model` to it, mutating `cfg` in place. No-op when the user
32
- * isn't logged in. Never overwrites a model the user already configured, or
33
- * any other existing key under `cfg.provider`/`cfg.plugin`/`cfg.mcp`/etc.
59
+ * The `models` block for one registered provider, filtered to
60
+ * `allowedModels` (Phase 4 governance, docs/LITELLM_GATEWAY.md §14) —
61
+ * LiteLLM gateway audit finding #5, mirrors the identical fix already made
62
+ * to `app/services/opencode/teamconfig.py::build_opencode_config` and
63
+ * `elliot-launcher/lib/setup.js::elliotProvider`. LiteLLM was always the
64
+ * real enforcement point regardless of what this offers; this only stops
65
+ * the menu from offering a model that will be rejected. Falsy
66
+ * (undefined/null/empty) — every team until an admin restricts it — offers
67
+ * both, unchanged from before this parameter existed.
68
+ *
69
+ * A team restricted to ONLY elliot-classifier (never offered here —
70
+ * internal-only, deploy/litellm/config.yaml §5) would otherwise get an
71
+ * empty, unusable menu; degrades to offering both for that listing only,
72
+ * same as the two sibling generators — LiteLLM still rejects any actual
73
+ * request the team isn't allowed to make either way.
34
74
  */
35
- export function configHook(cfg: any): void {
36
- if (!readElliotConfig()) return
75
+ function offeredModels(allowedModels?: string[] | null): typeof ALL_MODELS {
76
+ if (!allowedModels || allowedModels.length === 0) return ALL_MODELS
37
77
 
38
- cfg.provider ??= {}
39
- cfg.provider[ELLIOT_PROVIDER_ID] = {
40
- npm: "@ai-sdk/anthropic",
41
- name: "Elliot (governed)",
42
- options: { baseURL: ELLIOT_LLM_PROXY_URL },
43
- models: { "elliot-governed": { name: "Elliot (governed)" } },
44
- }
78
+ const allowed = new Set(allowedModels)
79
+ const offered = Object.keys(ALL_MODELS).filter((id) => allowed.has(id)) as Array<
80
+ keyof typeof ALL_MODELS
81
+ >
82
+ if (offered.length === 0) return ALL_MODELS
45
83
 
46
- cfg.model ??= "elliot/elliot-governed"
84
+ const filtered = {} as typeof ALL_MODELS
85
+ for (const id of offered) filtered[id] = ALL_MODELS[id]
86
+ return filtered
47
87
  }
48
88
 
49
- /**
50
- * Merge `Authorization: Bearer <token>` into whatever headers `init` already
51
- * carries, without dropping them. Works whether `init.headers` is a plain
52
- * object, a `Headers` instance, or an array of pairs.
53
- */
54
- function withAuthHeader(init: RequestInit | undefined, token: string): RequestInit {
55
- const headers = new Headers(init?.headers)
56
- headers.set("Authorization", `Bearer ${token}`)
57
- return { ...init, headers }
89
+ function registerProvider(
90
+ cfg: any,
91
+ base: string,
92
+ providerId: string,
93
+ label: string,
94
+ apiKey: string,
95
+ allowedModels?: string[] | null,
96
+ ): void {
97
+ cfg.provider ??= {}
98
+ // Never clobber a provider id the user (or an earlier plugin) already
99
+ // configured — same "additive only" contract as the single-provider path
100
+ // this replaces.
101
+ cfg.provider[providerId] ??= {
102
+ npm: "@ai-sdk/openai-compatible",
103
+ name: label,
104
+ options: { baseURL: `${base}/v1`, apiKey },
105
+ models: offeredModels(allowedModels),
106
+ }
58
107
  }
59
108
 
60
109
  /**
61
- * The per-request fetch wrapper: reads `~/.elliot/config.json` fresh on
62
- * every call (so a refresh picked up by another process is honored
63
- * immediately), refreshes via `freshToken` when needed, and attaches the
64
- * bearer token. Never throws — a missing/expired/unrefreshable token just
65
- * means the request goes out unauthenticated and the proxy 401s.
110
+ * Registers one OpenCode provider per LiteLLM credential this person has
111
+ * (Phase 4, docs/LITELLM_GATEWAY.md §14): their own personal key under
112
+ * `elliot`, plus one `elliot-team-<slug>` provider per team they belong to —
113
+ * so `opencode.json`'s own global+project-local merge, not this plugin, is
114
+ * what decides which key a given folder actually uses (a project-local
115
+ * config pins `model` to a team's provider; the global default falls back to
116
+ * the personal one). Mutating `cfg` in place.
117
+ *
118
+ * Falls back to registering a single `elliot` provider from the legacy
119
+ * `litellm_master_key` field when `elliot.credentials` is absent — an
120
+ * `eai setup` written before this phase, or a backend that predates it,
121
+ * keeps working unchanged rather than losing LLM access outright.
122
+ *
123
+ * No-op when the user isn't logged in. Never overwrites a model the user
124
+ * already configured, or any other existing key under
125
+ * `cfg.provider`/`cfg.plugin`/`cfg.mcp`/etc.
66
126
  */
67
- async function elliotFetch(input: string | URL | Request, init?: RequestInit): Promise<Response> {
68
- try {
69
- const cfg = readElliotConfig()
70
- const token = cfg ? await freshToken(cfg) : null
71
- if (token) {
72
- return globalThis.fetch(input, withAuthHeader(init, token))
127
+ export function configHook(cfg: any): void {
128
+ const elliot = readElliotConfig()
129
+ if (!elliot?.litellm_base_url) return
130
+
131
+ const base = elliot.litellm_base_url.replace(/\/+$/, "")
132
+
133
+ // The DEFAULT provider's own offered models decide the default `model`
134
+ // below — never just `elliot-general` unconditionally, since the
135
+ // fallback (single-provider) path can itself be restricted. In the
136
+ // credentials path this is always the personal credential (provider_id
137
+ // "elliot"), which has no team and so is never restricted — `ALL_MODELS`
138
+ // unless a future personal restriction concept changes that.
139
+ let defaultProviderModels: typeof ALL_MODELS = ALL_MODELS
140
+
141
+ if (elliot.credentials?.length) {
142
+ for (const credential of elliot.credentials as ElliotCredential[]) {
143
+ if (!credential.provider_id || !credential.api_key) continue
144
+ registerProvider(
145
+ cfg,
146
+ base,
147
+ credential.provider_id,
148
+ credential.label,
149
+ credential.api_key,
150
+ credential.allowed_models,
151
+ )
152
+ if (credential.provider_id === ELLIOT_PROVIDER_ID) {
153
+ defaultProviderModels = offeredModels(credential.allowed_models)
154
+ }
73
155
  }
74
- return globalThis.fetch(input, init)
75
- } catch {
76
- return globalThis.fetch(input, init)
156
+ } else if (elliot.litellm_master_key) {
157
+ registerProvider(
158
+ cfg,
159
+ base,
160
+ ELLIOT_PROVIDER_ID,
161
+ "Elliot (LiteLLM)",
162
+ elliot.litellm_master_key,
163
+ elliot.allowed_models,
164
+ )
165
+ defaultProviderModels = offeredModels(elliot.allowed_models)
166
+ } else {
167
+ return
77
168
  }
78
- }
79
169
 
80
- /**
81
- * Builds the `auth` hook object per the Task-1 pinned `AuthHook` shape.
82
- * `methods` is empty — this provider is never set up via interactive
83
- * `opencode auth login`; the plugin seeds the stored auth entry itself
84
- * (see `index.ts`) so the loader always fires once the user is logged into
85
- * Elliot.
86
- */
87
- export function makeAuthHook() {
88
- return {
89
- provider: ELLIOT_PROVIDER_ID,
90
- methods: [] as unknown[],
91
- loader: async (_auth: () => Promise<unknown>, _provider: unknown) => ({
92
- apiKey: "elliot-managed",
93
- fetch: elliotFetch,
94
- }),
95
- }
170
+ // Follows the restriction, not always General — a team restricted to
171
+ // Coder-only must not default to a model its own menu just excluded.
172
+ const defaultModelId =
173
+ ELLIOT_GENERAL_MODEL_ID in defaultProviderModels
174
+ ? ELLIOT_GENERAL_MODEL_ID
175
+ : Object.keys(defaultProviderModels)[0]
176
+ cfg.model ??= `${ELLIOT_PROVIDER_ID}/${defaultModelId}`
96
177
  }
@@ -2,7 +2,8 @@
2
2
  * Repository scope from the session worktree — the trusted-context half of the
3
3
  * "the model never names a repository" invariant.
4
4
  *
5
- * Ported (trimmed, not imported) from `elliot-cli/src/project.ts`: the same
5
+ * Ported (trimmed, not imported) from the retired elliot-ai CLI's
6
+ * `src/project.ts`: the same
6
7
  * `execFile` discipline — a fixed, hardcoded argument array, never a string a
7
8
  * shell would parse, and never anything the LLM supplies. The worktree path
8
9
  * comes from OpenCode's own `PluginInput`/`ToolContext`, which is session
@@ -71,3 +71,40 @@ export function formatDiffStat(additions: number, deletions: number): string {
71
71
  export function pluralize(count: number, singular: string, plural = `${singular}s`): string {
72
72
  return `${count} ${count === 1 ? singular : plural}`
73
73
  }
74
+
75
+ /**
76
+ * Mirror of the backend's own `_eai_money` (`backend/app/routers/mcp.py`),
77
+ * so a real spend figure read out of a `get_eai_usage` tool call renders
78
+ * identically whether a model relayed `summary`'s prose or this sidebar
79
+ * rendered the structured `current_spend`/`max_budget` fields directly.
80
+ *
81
+ * ~6 decimal places, widened only as far as needed so a genuinely nonzero
82
+ * spend never prints as "$0.000000" — four decimals rounds a value just
83
+ * under a round number (0.032999144) up to a falsely clean "$0.0330", which
84
+ * reads as exactly that amount when it is not.
85
+ */
86
+ export function formatMoney(n: number): string {
87
+ if (n === 0) return "$0"
88
+ let decimals = 6
89
+ while (decimals < 10 && Number(Math.abs(n).toFixed(decimals)) === 0) decimals += 1
90
+ return `$${n.toFixed(decimals)}`
91
+ }
92
+
93
+ /**
94
+ * Mirror of the backend's own `_eai_date` — "DD Mon YYYY" from an ISO
95
+ * timestamp's date portion. Returns the input unchanged if it does not
96
+ * parse, the same "degrade, never throw" rule `_eai_date` follows, since this
97
+ * renders inside a sidebar slot where a thrown error would blank the chrome.
98
+ */
99
+ export function formatEaiDate(iso: string): string {
100
+ const match = /^(\d{4})-(\d{2})-(\d{2})/.exec(iso)
101
+ if (!match) return iso
102
+ const [, y, m, d] = match
103
+ const months = [
104
+ "Jan", "Feb", "Mar", "Apr", "May", "Jun",
105
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
106
+ ]
107
+ const monthIndex = Number(m) - 1
108
+ if (monthIndex < 0 || monthIndex > 11) return iso
109
+ return `${d} ${months[monthIndex]} ${y}`
110
+ }
@@ -14,7 +14,7 @@
14
14
  * proven from session state or not shown.
15
15
  */
16
16
 
17
- import { knowledgeToolKey } from "../mcp-keys.js"
17
+ import { KNOWLEDGE_TOOL, toCanonicalToolUnderAnyGateway } from "../mcp-keys.js"
18
18
 
19
19
  // ------------------------------------------------------------- host shapes --
20
20
 
@@ -106,9 +106,15 @@ export function elliotServerNames(items: readonly McpItem[]): string[] {
106
106
  * reasoning applies to a panel that would otherwise attribute a third party's
107
107
  * results to Elliot.
108
108
  */
109
- export function isKnowledgeTool(tool: string | undefined, serverNames: readonly string[]): boolean {
109
+ export function isKnowledgeTool(
110
+ tool: string | undefined,
111
+ serverNames: readonly string[],
112
+ ): boolean {
110
113
  if (typeof tool !== "string") return false
111
- return serverNames.some((name) => tool === knowledgeToolKey(name))
114
+ // Alias-agnostic BY NECESSITY, not by preference — see
115
+ // `toCanonicalToolUnderAnyGateway` for why the TUI cannot know the
116
+ // configured alias, and why that is safe for a display surface.
117
+ return toCanonicalToolUnderAnyGateway(tool, serverNames) === KNOWLEDGE_TOOL
112
118
  }
113
119
 
114
120
  /**