SLOPSHOPPER

optim-jev

Jev based token-usage optimization tools for Claude Code workflows.

bandrowsguardcommandtoaststatus
★ 49v0.1.0MITupdated 2026-10-26Oqura-ai/optim-jev
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · optim-jev
› fix the failing auth test and add an audit log call ● optim-jev: jev-router: could not render its prompt section (JSON Parse error: Unexpected identifier "dev") ● optim-jev: optim-jev: usage not logged (JSON Parse error: Unexpected identifier "dev") ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /jev-compact ⎿ optim-jev: Usage: /jev-compact stats ╭──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╮ │ · │ │ · · · │ │ · │ │ ✦ optim-jev · Context 49% · soft 60% · hard 85% [ Compact ] │ │ Router off Enable router │ │ Skills off Enable skills │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
╭──────────────────────────────────────────────────────────────────────────────────────────────────╮ │ · │ │ · · · │ │ · │ │ ✦ optim-jev · Context 49% · soft 60% · hard 85% [ Compact ] │ │ Router off Enable router │ │ Skills off Enable skills │ ╰──────────────────────────────────────────────────────────────────────────────────────────────────╯
README

optim-jev

Spend fewer tokens in long agent sessions without changing how you work.

Jev-powered optimization for Claude Code, plus model routing for OpenAI Codex.

Claude Code plugin Codex plugin License: MIT Our Discord

Get started · Codex support · Documentation · Architecture · Contributing

<img src="assets/demo.gif" alt="optim-jev demo in Claude Code" width="100%">

Why optim-jev?

<img src="assets/optim-jev.png" alt="optim-jev architecture: context compaction, model routing, and skill selection" width="100%">

Long agent sessions accumulate stale tool output, send oversized skill catalogs, and use the main model for work a smaller model could handle. Claude Code supports all three optimizers below. Codex supports the model router and an off-by-default advisory skill experiment.

Each tool works independently and fails open if unavailable. Measured cost reports remain Claude-only.

Three tools, one project

ToolWhat it doesAvailable inClaude defaultLearn more
jev-compacterRemoves stale tool calls and outputs instead of summarizing away the whole conversationClaude CodeOnGuide
jev-routerRuns each subagent, Explore searches included, on the cheapest model that fits, within project rules that evolve with your workflowClaude Code and CodexOffGuide
jev-skillsSends a short, relevant skill list for each prompt instead of the entire catalogClaude Code; experimental advisory mode in CodexOffGuide

<img src="assets/jev-compacter.png" alt="jev-compacter session statistics" width="100%">

It works automatically with /compact and auto-compaction. Inspect the current session with:

/jev-compact stats

Want it to prune earlier or keep more? Pick a Compaction: style (balanced, save-tokens, or keep-context) in /config under optim-jev. See Pick a style.

<img src="assets/jev-router.png" alt="jev-router model routing decisions" width="100%">

Your main conversation keeps its model, so its prompt cache stays warm. The routing happens where it pays off: every subagent Claude spawns gets its own model and effort from Jev, Explore searches included. A quick lookup runs on haiku; a deep architecture review gets a stronger model.

Claude works as usual, editing directly and delegating when a task calls for it or when you ask. rules.json sets which models may edit each path; when a path needs a different model than your session's, Claude hands that change to a routed subagent.

/jev-route init "what matters in this project"
/jev-route on | off
/jev-route why | stats

Tell Claude to change a preference later—for example, “let haiku edit the tests”—and the project rules update with your workflow.

<img src="assets/jev-skills.png" alt="jev-skills prompt shortlist" width="100%">

/jev-skills on | off
/jev-skills scope project | global
/jev-skills why | stats | reindex

Claude Code quick start

Requirements

  • Claude Code with plugin support
  • Python 3.10 or newer
  • A TypeSafe API key for Jev

Install

git clone https://github.com/Oqura-ai/optim-jev.git
claude plugin marketplace add ./optim-jev
claude plugin install optim-jev@optim-jev

Set the key in Claude Code under /config → TypeSafe API key, or export it before starting Claude Code:

export TYPESAFE_API_KEY="your-key"

Restart Claude Code. jev-compacter is ready immediately; enable the router and skill picker when you want them. See Getting started for every command, option, and troubleshooting step.

[!NOTE] The plugin uses only Python's standard library. Your API key is passed to child processes through the environment and is never written to project files or logs.

OpenAI Codex support — new

Start with the complete Codex guide for installation, usage, model-tier setup, verification, limitations, troubleshooting, and uninstall steps.

optim-jev can automatically route each Codex subagent to an account-specific fast, balanced, or strong model. It also selects reasoning effort, applies project path rules, escalates after failures, and can provide an optional advisory skill shortlist. Claude and Codex keep separate model catalogues, policies, caches, and logs.

[!IMPORTANT] Compaction is not supported in Codex. Codex hooks cannot replace live conversation history. The AbovePrompt dashboard, slash commands, and measured token and cost reports are also Claude-only.

Install and use

Codex CLI 0.162.1 or newer can install optim-jev directly from GitHub. No PyPI release or manual clone is required.

py -3 -m pip install "https://github.com/Oqura-ai/optim-jev/archive/refs/heads/main.zip"
optim-jev codex install

$env:TYPESAFE_API_KEY = "your-key"
cd C:\path\to\your-project
optim-jev codex setup
optim-jev codex status
codex

On the first Codex launch after install or update, run /hooks, review and trust every optim-jev hook, then restart Codex.

Inside Codex, subagent routing is automatic. Check the most recent decision or control project features with:

!optim-jev codex why
!optim-jev codex status
!optim-jev codex on
!optim-jev codex off
!optim-jev codex skills-on
!optim-jev codex skills-off

Documentation

ResourceWhat you will find
Getting startedInstallation, configuration, commands, and troubleshooting
Codex supportCodex installation, router setup, configuration, and limitations
TinyCart demoA short, repeatable showcase of all three tools on a toy project
Performance metricsHow token usage, cost, and estimated savings are calculated
ArchitectureThe TypeScript-to-Python bridge, data flow, and session logs
ContributingLocal setup, tests, conventions, and pull requests

Community and support

License

optim-jev is released under the MIT License.

Built by Oqura.ai for more efficient coding-agent workflows.

Source 4 files
hooks/optim-jev.ts 1515 lines
1import type {
2  AgentSpawnInput,
3  CommandRunInput,
4  CommandRunResult,
5  EngineInterface as Engine,
6  ModelUsage,
7  On,
8  PluginOptions,
9  PromptComposeSection,
10  PromptSubmitInput,
11  Register,
12  SessionCompactInput,
13  SessionCompactResult,
14  SessionMessage,
15  TurnCompleteInput,
16} from 'claude-code';
17import {
18  DASHBOARD_STAR_FRAME_MS,
19  DASHBOARD_STAR_ROWS,
20  dashboardStarFrame,
21  dashboardTree,
22  type CompactionOutcome,
23  type DashboardView,
24  type RouterDecision,
25  type SkillsOutcome,
26} from './dashboard';
27import { commandOutputTree } from './command-output';
28import type { Effort, Escalated, Mode, Permission, RenderAnswer, SessionRecord, SpawnAnswer, SpawnAskClaude } from './router-lib';
29import {
30  DEFAULT_ESCALATE_AFTER,
31  DEFAULT_INIT_MODEL,
32  MODEL_GONE,
33  MODES,
34  ROUTER_COMMAND,
35  ROUTER_MODULE,
36  SECTION_ID,
37  STORE_KEY,
38  USAGE,
39  lookup,
40  newTurn,
41  numberOption,
42  oneOf,
43  isRulesFile,
44  MAX_RECENT_INPUTS,
45  parseDecision,
46  relPath,
47  rememberInput,
48  writeTargets,
49} from './router-lib';
50
51type Level = 'soft' | 'hard' | 'idle' | 'manual';
52
53type KeptMessage = {
54  from: number;
55  toolUses?: { tool_use_id: string; text?: string }[];
56  toolResults?: { tool_use_id: string; text: string }[];
57};
58
59type CompactAnswer = {
60  action: 'skip' | 'apply' | 'defer' | 'summarize';
61  message: string;
62  log: string[];
63  messages?: KeptMessage[];
64  tokensAfter?: number;
65  freedTokensEst?: number;
66};
67
68type CheckAnswer = { level: Level | null };
69
70const API_KEY_OPTION = 'typesafe_api_key';
71const PYTHON_TIMEOUT_MS = 180_000;
72const DEFAULT_HARD_PERCENT = 85;
73
74function errorText(error: unknown): string {
75  return error instanceof Error ? error.message : String(error);
76}
77
78function notify($: Engine, text: string, timeoutMs = 15_000): void {
79  $.ui.log(text);
80  $.ui.toast(text, { timeoutMs });
81}
82
83async function apiKey($: Engine, options: PluginOptions): Promise<string | undefined> {
84  const configured = options[API_KEY_OPTION];
85  if (typeof configured === 'string' && configured) return configured;
86  const fromEnv = await $.env.get('TYPESAFE_API_KEY');
87  if (fromEnv) return fromEnv;
88  const env = (await $.settings.read())['env'];
89  const fromSettings =
90    env && typeof env === 'object' ? (env as Record<string, unknown>)['TYPESAFE_API_KEY'] : undefined;
91  return typeof fromSettings === 'string' && fromSettings ? fromSettings : undefined;
92}
93
94/** Options for the Python tools, the secret left out (it travels in the child's environment). */
95function toolOptions(options: PluginOptions): Record<string, unknown> {
96  const { [API_KEY_OPTION]: _secret, ...rest } = options as Record<string, unknown>;
97  return rest;
98}
99
100async function runTool<T>(
101  $: Engine,
102  options: PluginOptions,
103  module: string,
104  mode: string,
105  request: object,
106  timeoutMs = PYTHON_TIMEOUT_MS,
107): Promise<T> {
108  const python = typeof options['python'] === 'string' && options['python'] ? options['python'] : 'python';
109  const env: Record<string, string> = { PYTHONPATH: `${$.plugin.root}/src`, PYTHONIOENCODING: 'utf-8' };
110  const key = await apiKey($, options);
111  if (key) env['TYPESAFE_API_KEY'] = key;
112  const { exitCode, stdout, stderr } = await $.process.run([python, '-m', module, mode], {
113    env,
114    stdin: JSON.stringify(request),
115    timeoutMs,
116  });
117  if (exitCode !== 0) {
118    throw new Error(`${python} exited ${exitCode}: ${stderr.trim().split('\n').slice(-3).join(' | ')}`);
119  }
120  return JSON.parse(stdout) as T;
121}
122
123// ------------------------------------------------------------- usage log
124
125const LOGS_MODULE = 'optim_jev.core.logs';
126// Claude's own token counts, as the API reported them; written to logs/claude/<session_id>.jsonl
127// in one Python call when a main-loop turn ends (the hook API can't append to a file).
128let usageBuffer: Record<string, unknown>[] = [];
129
130function recordUsage(kind: string, usage: ModelUsage, fields: Record<string, unknown>): void {
131  usageBuffer.push({
132    ts: Math.round(Date.now() / 1000),
133    kind,
134    ...fields,
135    input_tokens: usage.input_tokens,
136    output_tokens: usage.output_tokens,
137    cache_read_input_tokens: usage.cache_read_input_tokens,
138    cache_creation_input_tokens: usage.cache_creation_input_tokens,
139  });
140}
141
142async function flushUsage($: Engine, options: PluginOptions): Promise<void> {
143  if (usageBuffer.length === 0) return;
144  const records = usageBuffer;
145  usageBuffer = [];
146  try {
147    await runTool($, options, LOGS_MODULE, 'claude', {
148      session_id: await $.session.id(),
149      project_dir: await $.session.root(),
150      records,
151    });
152  } catch (error) {
153    $.ui.log(`optim-jev: usage not logged (${errorText(error)})`, { to: 'debug' });
154  }
155}
156
157const TOOL_MODULE = 'optim_jev.tools.jev_compacter.tool';
158const DEFAULT_SOFT_PERCENT = 60;
159
160async function sessionFields($: Engine, options: PluginOptions) {
161  const { context } = await $.session.usage();
162  const used = context.tokens ?? Math.round(((context.percent ?? 0) / 100) * context.window);
163  return {
164    session_id: await $.session.id(),
165    project_dir: await $.session.root(),
166    usage: {
167      used_tokens: used,
168      window_tokens: context.window,
169      idle_seconds: lastActivityAt === null ? 0 : Math.max(0, ((await $.clock.now()) - lastActivityAt) / 1000),
170      cache_cold: (await coldReason($, options)) !== null,
171    },
172    options: toolOptions(options),
173    percent: context.percent ?? (100 * used) / context.window,
174  };
175}
176
177function wire(message: SessionMessage) {
178  return {
179    role: message.role,
180    text: message.text,
181    toolUses: message.toolUses.map((t) => ({
182      tool_use_id: t.tool_use_id,
183      tool: t.tool,
184      input: t.input,
185      text: t.text,
186      isError: t.isError === true,
187    })),
188    toolResults: (message.toolResults ?? []).map((r) => ({
189      tool_use_id: r.tool_use_id,
190      text: r.text,
191      isError: r.isError,
192    })),
193  };
194}
195
196/**
197 * An unchanged message is the engine's own (handle included); a changed one is rebuilt from
198 * the original without its handle, keeping only the listed tool blocks with the given texts.
199 */
200function rebuild(input: readonly SessionMessage[], kept: KeptMessage): SessionMessage {
201  const original = input[kept.from];
202  if (!original) throw new Error(`answer names message ${kept.from} of ${input.length}`);
203  if (!kept.toolUses && !kept.toolResults) return original;
204  const uses = new Map(original.toolUses.map((t) => [t.tool_use_id, t]));
205  const results = new Map((original.toolResults ?? []).map((r) => [r.tool_use_id, r]));
206  const message: SessionMessage = {
207    role: original.role,
208    text: original.text,
209    toolUses: (kept.toolUses ?? []).map(({ tool_use_id, text }) => {
210      const use = uses.get(tool_use_id);
211      if (!use) throw new Error(`unknown tool_use ${tool_use_id}`);
212      return text === undefined || text === use.text ? use : { ...use, text, result: undefined };
213    }),
214  };
215  const toolResults = (kept.toolResults ?? []).map(({ tool_use_id, text }) => {
216    const result = results.get(tool_use_id);
217    if (!result) throw new Error(`unknown tool_result ${tool_use_id}`);
218    return text === result.text ? result : { ...result, text, result: undefined };
219  });
220  if (toolResults.length > 0) message.toolResults = toolResults;
221  return message;
222}
223
224// ---------------------------------------------------------------- jev-router
225
226let routerOptions: PluginOptions = {};
227let escalateAfter = DEFAULT_ESCALATE_AFTER;
228let initModel = DEFAULT_INIT_MODEL;
229let record: SessionRecord = { sessionId: '', mode: 'off' };
230let section = '';
231let rules: Record<string, Permission> = {};
232let tiers: string[] = ['haiku', 'sonnet', 'opus'];
233let sessionAlias: string | null = null;
234let offline = false;
235let turn = newTurn();
236// Per routed subagent: the model it runs on, its effort, and the files its prompt named.
237const agentModels = new Map<string, string>();
238const agentEfforts = new Map<string, Effort>();
239const agentFiles = new Map<string, string[]>();
240// Session-wide: per file, how many levels up the next subagent starts (same effort), after errors there.
241const escalated = new Map<string, Escalated>();
242// The person's last prompts, newest last; shared by the router and the skill picker.
243let recentInputs: string[] = [];
244const DEFAULT_DECIDER_MODEL = 'haiku';
245let deciderModel = DEFAULT_DECIDER_MODEL;
246
247const isActive = () => record.mode === 'on';
248const aliasOf = (model: string | undefined | null) =>
249  model ? tiers.find((t) => model.toLowerCase().includes(t)) : undefined;
250const bump = (alias: string) => tiers[Math.min(tiers.length - 1, tiers.indexOf(alias) + 1)] ?? alias;
251
252// Dashboard snapshot. Feature state in each tool remains the source of truth.
253const DASHBOARD_STORE_KEY = 'optim_jev_dashboard_session';
254type DashboardRecord = {
255  sessionId: string;
256  contextPercent: number | null;
257  compactionOutcome: CompactionOutcome;
258  compacterDegraded: boolean;
259  routerDecision: RouterDecision | null;
260  routerOffline: boolean;
261  skillsOutcome: SkillsOutcome;
262};
263
264let pluginOptions: PluginOptions = {};
265let compacterOn = true;
266let dashboardOn = true;
267let dashboardSessionId = '';
268let dashboardActivity: string | null = null;
269let dashboardContextPercent: number | null = null;
270let compactionOutcome: CompactionOutcome = { kind: 'not_run' };
271let compacterDegraded = false;
272let routerHasRules = false;
273let routerRefreshingFailed = false;
274let routerRouting = false;
275let lastRouterDecision: RouterDecision | null = null;
276let dashboardStarFrameNumber = 0;
277let dashboardStarRequestId: string | null = null;
278let dashboardStarTimer: { cancel(): void } | null = null;
279let dashboardStarColumns = 1;
280let dashboardSaveQueue: Promise<void> = Promise.resolve();
281
282function dashboardRecord(): DashboardRecord {
283  return {
284    sessionId: dashboardSessionId,
285    contextPercent: dashboardContextPercent,
286    compactionOutcome,
287    compacterDegraded,
288    routerDecision: lastRouterDecision,
289    routerOffline: offline,
290    skillsOutcome,
291  };
292}
293
294function restoreDashboard(stored: Partial<DashboardRecord> | undefined): void {
295  if (!stored || stored.sessionId !== dashboardSessionId) return;
296  if (stored.contextPercent === null || (typeof stored.contextPercent === 'number' && Number.isFinite(stored.contextPercent))) {
297    dashboardContextPercent = stored.contextPercent;
298  }
299  if (stored.compactionOutcome?.kind) compactionOutcome = stored.compactionOutcome;
300  if (typeof stored.compacterDegraded === 'boolean') compacterDegraded = stored.compacterDegraded;
301  if (stored.routerDecision === null || stored.routerDecision?.model) lastRouterDecision = stored.routerDecision;
302  if (typeof stored.routerOffline === 'boolean') offline = stored.routerOffline;
303  if (stored.skillsOutcome?.kind) skillsOutcome = stored.skillsOutcome;
304}
305
306function persistDashboard($: Engine): void {
307  if (!dashboardSessionId) return;
308  const snapshot = dashboardRecord();
309  dashboardSaveQueue = dashboardSaveQueue
310    .catch(() => undefined)
311    .then(async () => {
312      await $.store.set(DASHBOARD_STORE_KEY, snapshot);
313    })
314    .catch((error) => {
315      $.ui.log(`optim-jev: dashboard state not saved (${errorText(error)})`, { to: 'debug' });
316    });
317}
318
319function stopDashboardStars(): void {
320  dashboardStarRequestId = null;
321  dashboardStarTimer?.cancel();
322  dashboardStarTimer = null;
323}
324
325function animateDashboardStars($: Engine, requestId: string, columns: number): void {
326  dashboardStarRequestId = requestId;
327  dashboardStarColumns = columns;
328  if (dashboardStarTimer) return;
329  try {
330    dashboardStarTimer = $.clock.every(DASHBOARD_STAR_FRAME_MS, () => {
331      const active = dashboardStarRequestId;
332      if (!active) return stopDashboardStars();
333      dashboardStarFrameNumber += 1;
334      void $.ui
335        .blit({
336          requestId: active,
337          key: 'dashboard-stars',
338          cells: dashboardStarFrame(dashboardStarFrameNumber, dashboardStarColumns, DASHBOARD_STAR_ROWS),
339        })
340        .then((result) => {
341          if ('deny' in result && result.deny) stopDashboardStars();
342        })
343        .catch(stopDashboardStars);
344    });
345  } catch {
346    // Animation is optional: keep the static particle frame and the dashboard itself.
347    dashboardStarTimer = null;
348  }
349}
350
351function refreshUi($: Engine): void {
352  persistDashboard($);
353  try {
354    if (dashboardOn) {
355      $.ui.status(undefined);
356      $.ui.invalidate('ui.render');
357    } else {
358      $.ui.status(dashboardActivity ? `◆ jev · ${dashboardActivity}` : idleStatus());
359    }
360  } catch (error) {
361    $.ui.log(`optim-jev: dashboard not refreshed (${errorText(error)})`, { to: 'debug' });
362  }
363}
364
365function showActivity($: Engine, activity: string | null): void {
366  dashboardActivity = activity;
367  refreshUi($);
368}
369
370function rememberContext(percent: number): void {
371  dashboardContextPercent = Number.isFinite(percent) ? percent : null;
372}
373
374async function rememberCompactedContext(
375  $: Engine,
376  options: PluginOptions,
377  result: SessionCompactResult,
378  knownWindow = 0,
379): Promise<void> {
380  try {
381    const fields = knownWindow > 0 ? null : await sessionFields($, options);
382    const windowTokens = knownWindow > 0 ? knownWindow : (fields?.usage.window_tokens ?? 0);
383    // Claude Code reports tokensAfter, but its published types don't declare it yet.
384    const { tokensAfter } = result as { tokensAfter?: unknown };
385    if (typeof tokensAfter === 'number' && windowTokens > 0) {
386      rememberContext((100 * tokensAfter) / windowTokens);
387    } else if (fields && (fields.percent > 0 || dashboardContextPercent === null)) {
388      rememberContext(fields.percent);
389    }
390  } catch {
391    // The exact outcome remains useful even when usage is temporarily unavailable.
392  }
393}
394
395function dashboardView(): DashboardView {
396  return {
397    contextPercent: dashboardContextPercent,
398    activity: dashboardActivity,
399    compacter: {
400      enabled: compacterOn,
401      softPercent: numberOption(pluginOptions, 'jev_compacter_soft_percent', DEFAULT_SOFT_PERCENT),
402      hardPercent: numberOption(pluginOptions, 'jev_compacter_hard_percent', DEFAULT_HARD_PERCENT),
403      outcome: compactionOutcome,
404      degraded: compacterDegraded,
405    },
406    router: {
407      mode: record.mode,
408      routing: routerRouting,
409      offline: offline || routerRefreshingFailed,
410      hasRules: routerHasRules,
411      decision: lastRouterDecision,
412    },
413    skills: {
414      mode: skills.mode,
415      scope: skills.scope,
416      count: skillCount,
417      indexing: skillsIndexing,
418      picking: skillsPicking,
419      outcome: skillsOutcome,
420    },
421  };
422}
423
424function idleStatus(): string {
425  const router = !isActive()
426    ? 'router off'
427    : offline
428      ? `router offline → ${sessionAlias ?? 'session model'}`
429      : 'routing subagents';
430  return `◆ jev · compact ${compacterOn ? 'on' : 'off'} · ${router} · ${skillsStatus()}`;
431}
432
433async function routerFields($: Engine) {
434  return {
435    session_id: await $.session.id(),
436    project_dir: await $.session.root(),
437    session_model: await $.session.model(),
438    options: toolOptions(routerOptions),
439  };
440}
441
442async function saveRecord($: Engine) {
443  await $.store.set(STORE_KEY, record);
444}
445
446async function refresh($: Engine) {
447  try {
448    const answer = await runTool<RenderAnswer>($, routerOptions, ROUTER_MODULE, 'render', await routerFields($));
449    section = answer.section;
450    rules = answer.rules;
451    tiers = answer.tiers.length > 0 ? answer.tiers : tiers;
452    sessionAlias = answer.current;
453    routerHasRules = answer.has_rules;
454    routerRefreshingFailed = false;
455  } catch (error) {
456    section = '';
457    routerRefreshingFailed = true;
458    $.ui.log(`jev-router: could not render its prompt section (${errorText(error)})`);
459  }
460  refreshUi($);
461}
462
463async function setMode($: Engine, mode: Mode) {
464  record = { ...record, mode };
465  await saveRecord($);
466  await refresh($);
467}
468
469async function routerSessionStart($: Engine) {
470  await $.command.register({
471    name: ROUTER_COMMAND,
472    description: 'Jev model router: on or off; init, why, stats',
473    argumentHint: '[on|off|init|why|stats]',
474  });
475  const sessionId = await $.session.id();
476  const stored = (await $.store.get(STORE_KEY)) as Partial<SessionRecord> | undefined;
477  if (stored && stored.sessionId === sessionId) {
478    record = { sessionId, mode: oneOf(MODES, stored.mode, record.mode) };
479  } else {
480    record = { ...record, sessionId };
481    await saveRecord($);
482  }
483  escalated.clear();
484  agentEfforts.clear();
485  recentInputs = await typedPrompts($);
486  await refresh($);
487}
488
489/** A resumed or reloaded session's last prompts, from the transcript: the person's own text only. */
490async function typedPrompts($: Engine): Promise<string[]> {
491  try {
492    let recent: string[] = [];
493    for (const m of await $.session.messages()) {
494      if (m.role === 'user' && !(m.toolResults?.length)) recent = rememberInput(recent, m.text);
495    }
496    return recent;
497  } catch {
498    return [];
499  }
500}
501
502async function runCommand($: Engine, e: CommandRunInput): Promise<CommandRunResult> {
503  const [verb = '', ...rest] = e.args.trim().split(/\s+/).filter(Boolean);
504  const arg = rest.join(' ');
505  try {
506    if (verb === '') return { text: `jev-router: ${record.mode}\n\n${USAGE}` };
507    if ((MODES as readonly string[]).includes(verb)) {
508      await setMode($, verb as Mode);
509      return {
510        text:
511          verb === 'on'
512            ? 'jev-router: on for this session. Claude delegates when it helps; Jev picks each subagent\'s model.'
513            : 'jev-router: off for this session.',
514      };
515    }
516    if (verb === 'why' || verb === 'stats') {
517      const { text } = await runTool<{ text: string }>($, routerOptions, ROUTER_MODULE, verb, await routerFields($));
518      return { text };
519    }
520    if (verb === 'init') return await runInit($, arg);
521    return { text: USAGE };
522  } catch (error) {
523    dashboardActivity = null;
524    refreshUi($);
525    return { text: `jev-router: ${errorText(error)}` };
526  }
527}
528
529/** A one-token call: the full id if it answers, the alias alone (id learned later), or unavailable. */
530async function checkModel(
531  $: Engine,
532  alias: string,
533  id: string,
534  sessionModel: string,
535): Promise<{ id: string; available: boolean }> {
536  if (aliasOf(sessionModel) === alias) return { id: sessionModel, available: true };
537  for (const model of id ? [id, alias] : [alias]) {
538    try {
539      const r = await $.model.complete({ model, prompt: 'Reply OK.', maxTokens: 1, timeoutMs: 30_000 });
540      if (r.isAnswered || r.reason !== 'api-error' || !MODEL_GONE.has(r.error)) {
541        return { id: model === alias ? '' : model, available: true };
542      }
543    } catch {
544      // the engine refused to send it: a blocked or unknown model
545    }
546  }
547  return { id: '', available: false };
548}
549
550async function runInit($: Engine, arg: string): Promise<CommandRunResult> {
551  const depthMatch = /--depth[ =](\d+)/.exec(arg);
552  const depth = depthMatch ? Number(depthMatch[1]) : undefined;
553  const force = /(^|\s)--force(?=\s|$)/.test(arg);
554  const directive = arg
555    .replace(/--depth[ =]\d+/, '')
556    .replace(/(^|\s)--force(?=\s|$)/, ' ')
557    .trim()
558    .replace(/^["']|["']$/g, '');
559  showActivity($, 'Scanning project for router rules…');
560  const base = await routerFields($);
561  const scan = await runTool<
562    | { refused: string }
563    | { refused?: undefined; system: string; prompt: string; paths: number; models: { alias: string; id: string }[] }
564  >($, routerOptions, ROUTER_MODULE, 'scan', { ...base, directive, depth, force });
565  if (scan.refused !== undefined) {
566    showActivity($, null);
567    return { text: scan.refused };
568  }
569  showActivity($, 'Checking model access…');
570  const checks = Object.fromEntries(
571    await Promise.all(scan.models.map(async (m) => [m.alias, await checkModel($, m.alias, m.id, base.session_model)] as const)),
572  );
573  showActivity($, `Writing router rules for ${scan.paths} paths…`);
574  const reply = await $.model.complete({
575    model: initModel,
576    system: scan.system,
577    prompt: scan.prompt,
578    maxTokens: 8_000,
579    timeoutMs: 180_000,
580  });
581  if (reply.usage) recordUsage('init', reply.usage, { model: initModel });
582  if (!reply.isAnswered) {
583    showActivity($, null);
584    return { text: `jev-router: the rules writer (${initModel}) gave no answer (${reply.reason})` };
585  }
586  const saved = await runTool<{ text: string; count: number }>($, routerOptions, ROUTER_MODULE, 'init_save', {
587    ...base,
588    directive,
589    depth,
590    reply: reply.text,
591    checks,
592  });
593  dashboardActivity = null;
594  const turnedOn = !isActive();
595  if (turnedOn) await setMode($, 'on');
596  else await refresh($);
597  return { text: saved.text + (turnedOn ? '\n\nRouting is now on for this session.' : '') };
598}
599
600function composeSections(sections: readonly PromptComposeSection[]): readonly PromptComposeSection[] {
601  if (!isActive() || !section) return sections;
602  return [...sections.filter((s) => s.id !== SECTION_ID), { id: SECTION_ID, text: section, scope: 'session' }];
603}
604
605/** The main loop and each routed subagent change only the files their model is allowed. */
606async function guardWrite(
607  $: Engine,
608  e: Record<string, unknown> & { agentId?: string },
609): Promise<{ deny?: string; watched: boolean }> {
610  if (!isActive()) return { watched: false };
611  const { paths, kind } = writeTargets(e);
612  if (paths.length === 0) return { watched: false };
613  const root = await $.session.root();
614  const main = e.agentId === undefined;
615  // The main loop may always change the two routing files: that is how preferences evolve.
616  if (main && kind === 'write' && paths.every((p) => isRulesFile(relPath(p, root)))) return { watched: false };
617  // A main loop on a model outside the ladder is held only to paths no model may change.
618  const running = main ? sessionAlias : agentModels.get(e.agentId ?? '');
619  if (!main && !running) return { watched: false };
620  for (const target of paths) {
621    const rel = relPath(target, root);
622    const permission = lookup(rules, rel, tiers);
623    const allowed = kind === 'write' ? permission.write : permission.delete;
624    if (allowed.length > 0 && (!running || allowed.includes(running))) continue;
625    turn.deniedCount += 1;
626    const why =
627      allowed.length === 0
628        ? `no model may ${kind} ${rel}`
629        : `${running} may not ${kind} ${rel}; it needs ${allowed.join(' or ')}`;
630    const advice = !main
631      ? 'Leave it and say so in your final report.'
632      : allowed.length > 0
633        ? 'Hand this change to a subagent with the Agent tool; Jev runs it on a model the rule allows.'
634        : 'Leave it and tell the person.';
635    notify($, `🔒 jev: ${why}`, 8_000);
636    return { watched: false, deny: `jev-router: ${why} (.optim-jev/jev_router/rules.json). ${advice}` };
637  }
638  return { watched: !main };
639}
640
641async function editedRulesFile($: Engine, e: Record<string, unknown>): Promise<boolean> {
642  const { paths, kind } = writeTargets(e);
643  if (kind !== 'write' || paths.length === 0) return false;
644  const root = await $.session.root();
645  return paths.some((p) => isRulesFile(relPath(p, root)));
646}
647
648/** A routing file changed: reload the copy guardWrite checks, and report what a hand edit broke. */
649async function afterRulesEdit($: Engine): Promise<string | undefined> {
650  await refresh($);
651  try {
652    const { problems } = await runTool<{ problems: string[] }>(
653      $,
654      routerOptions,
655      ROUTER_MODULE,
656      'validate',
657      await routerFields($),
658    );
659    if (problems.length === 0) return undefined;
660    notify($, `⚠ jev: rules.json has ${problems.length} problem(s); Claude was told`, 10_000);
661    return `jev-router: rules.json has problems. Fix them now.\n${problems.map((p) => `- ${p}`).join('\n')}`;
662  } catch (error) {
663    $.ui.log(`jev-router: rules.json not validated (${errorText(error)})`, { to: 'debug' });
664    return undefined;
665  }
666}
667
668function countWriteResult($: Engine, agentId: string | undefined, isError: boolean) {
669  if (!isError || agentId === undefined) return;
670  const errors = (turn.errors.get(agentId) ?? 0) + 1;
671  turn.errors.set(agentId, errors);
672  if (errors !== escalateAfter) return;
673  const from = agentModels.get(agentId);
674  const files = agentFiles.get(agentId) ?? [];
675  // Stops at the strongest model; errors !== escalateAfter above makes it once per subagent.
676  if (!from || files.length === 0 || bump(from) === from) return;
677  const effort = agentEfforts.get(agentId) ?? null;
678  for (const f of files) escalated.set(f, { levels: (escalated.get(f)?.levels ?? 0) + 1, effort });
679  turn.escalations.push({ from, to: bump(from), effort, files });
680  const at = effort ? ` at ${effort} effort` : '';
681  notify($, `⬆ jev: ${from} hit ${escalateAfter} errors; the next subagent for ${files.join(', ')} starts on ${bump(from)}${at}`, 8_000);
682}
683
684/** Jev's input stayed over budget: a small, low-effort Claude model decides instead. */
685async function askClaudeToRoute($: Engine, prompt: string): Promise<{ model?: string; effort?: string } | { failed: string }> {
686  try {
687    const r = await $.model.complete({ model: deciderModel, prompt, maxTokens: 100, effort: 'low', timeoutMs: 30_000 });
688    if (r.usage) recordUsage('route_decider', r.usage, { model: deciderModel });
689    if (!r.isAnswered) return { failed: `${deciderModel} gave no answer (${r.reason})` };
690    return parseDecision(r.text) ?? { failed: `${deciderModel} answered no JSON` };
691  } catch (error) {
692    return { failed: `${deciderModel}: ${errorText(error)}` };
693  }
694}
695
696async function routeSpawn(
697  $: Engine,
698  e: AgentSpawnInput,
699): Promise<{ model?: string; effort?: Effort; prompt?: string; files: string[] }> {
700  if (!isActive() || e.fork || e.isTeammate) return { files: [] };
701  routerRouting = true;
702  showActivity($, `Routing “${e.description || 'subagent'}”…`);
703  try {
704    const request = {
705      ...(await routerFields($)),
706      description: e.description,
707      prompt: e.prompt,
708      subagent_type: e.subagentType,
709      escalated: Object.fromEntries(escalated),
710      recent_inputs: recentInputs,
711    };
712    let answer = await runTool<SpawnAnswer | SpawnAskClaude>($, routerOptions, ROUTER_MODULE, 'spawn', request);
713    if ('ask_claude' in answer) {
714      showActivity($, `Routing “${e.description || 'subagent'}” with ${deciderModel}…`);
715      const decided = await askClaudeToRoute($, answer.ask_claude);
716      answer = await runTool<SpawnAnswer | SpawnAskClaude>($, routerOptions, ROUTER_MODULE, 'spawn', { ...request, decided });
717      if ('ask_claude' in answer) throw new Error('router asked for a decision twice');
718    }
719    offline = answer.jev_failed !== null;
720    turn.spawned += 1;
721    lastRouterDecision = {
722      task: e.description || 'subagent',
723      model: answer.model,
724      effort: answer.effort,
725      source: answer.source ?? (answer.jev_failed ? 'fallback' : 'jev'),
726      escalated: answer.escalated ?? 0,
727    };
728    notify($, answer.toast, 6_000);
729    return {
730      model: answer.model,
731      ...(answer.effort ? { effort: answer.effort } : {}),
732      prompt: answer.appendix ? e.prompt + answer.appendix : undefined,
733      files: answer.files,
734    };
735  } catch (error) {
736    offline = true;
737    lastRouterDecision = {
738      task: e.description || 'subagent',
739      model: sessionAlias ?? 'session',
740      source: 'session',
741      escalated: 0,
742    };
743    $.ui.log(`jev-router: subagent not routed (${errorText(error)})`, { to: 'debug' });
744    return { files: [] };
745  } finally {
746    routerRouting = false;
747    showActivity($, null);
748  }
749}
750
751async function routerTurnComplete($: Engine, e: TurnCompleteInput) {
752  if (e.agentId !== undefined) return;
753  if (isActive() && (turn.spawned > 0 || turn.escalations.length > 0 || turn.deniedCount > 0)) {
754    try {
755      await runTool($, routerOptions, ROUTER_MODULE, 'outcome', {
756        ...(await routerFields($)),
757        record: {
758          turn_id: e.turnId,
759          reason: e.reason,
760          spawned: turn.spawned,
761          errors: [...turn.errors.values()].reduce((a, b) => a + b, 0),
762          escalations: turn.escalations,
763          denials: turn.deniedCount,
764        },
765      });
766    } catch (error) {
767      $.ui.log(`jev-router: outcome not logged (${errorText(error)})`, { to: 'debug' });
768    }
769  }
770  refreshUi($);
771}
772
773/**
774 * The router's own hooks. `session.start` and `turn.complete` are shared with the compacter, whose
775 * hooks call routerSessionStart and routerTurnComplete (one unmatched hook per event per plugin).
776 */
777function registerRouter(on: On, pluginOptions: PluginOptions): void {
778  routerOptions = pluginOptions;
779  escalateAfter = numberOption(routerOptions, 'jev_router_escalate_after', DEFAULT_ESCALATE_AFTER);
780  deciderModel =
781    typeof routerOptions['jev_router_decider_model'] === 'string' && routerOptions['jev_router_decider_model']
782      ? routerOptions['jev_router_decider_model']
783      : DEFAULT_DECIDER_MODEL;
784  initModel =
785    typeof routerOptions['jev_router_init_model'] === 'string' && routerOptions['jev_router_init_model']
786      ? routerOptions['jev_router_init_model']
787      : DEFAULT_INIT_MODEL;
788  record = { sessionId: '', mode: oneOf(MODES, routerOptions['jev_router_mode'], 'off') };
789
790  on('command.run', { command: 'jev-route' }, async ($, e) => runCommand($, e));
791
792  on('prompt.compose', async ($, e, next) => {
793    const result = await next(e);
794    return { sections: composeSections(result.sections) };
795  });
796
797  on('turn.start', async ($, e, next) => {
798    turn = newTurn();
799    if (e.agentId === undefined) compacterTurnStart();
800    return next(e);
801  });
802
803  on('tool.call', { tool: ['Edit', 'Write', 'NotebookEdit', 'Bash', 'PowerShell'] }, async ($, e, next) => {
804    const input = e as unknown as Record<string, unknown> & { agentId?: string };
805    const verdict = await guardWrite($, input);
806    if (verdict.deny !== undefined) return { deny: verdict.deny };
807    const result = await next(e);
808    if (verdict.watched) countWriteResult($, e.agentId, result.isError === true);
809    if (result.deny !== undefined || result.isError === true || !(await editedRulesFile($, input))) return result;
810    const warning = await afterRulesEdit($);
811    return warning ? { ...result, context: [...(result.context ?? []), warning] } : result;
812  });
813
814  // A spawn can't set effort, so each of a routed subagent's requests gets it here. A model
815  // without effort sends none (e.effort absent), so nothing is forced on it.
816  on('turn.step', async function* ($, e, next) {
817    const effort = e.agentId !== undefined ? agentEfforts.get(e.agentId) : undefined;
818    return yield* next(effort && e.effort !== undefined && e.effort !== effort ? { ...e, effort } : e);
819  });
820
821  on('agent.spawn', async ($, e, next) => {
822    // Claude Code keeps a resumed subagent's model and ignores a new one, so a resume isn't routed again.
823    if (e.resume) return next(e);
824    const routed = await routeSpawn($, e);
825    const result = await next({
826      ...e,
827      ...(routed.model ? { model: routed.model } : {}),
828      ...(routed.prompt ? { prompt: routed.prompt } : {}),
829    });
830    if (routed.model && result.agentId) {
831      const ranOn = aliasOf(result.model) ?? routed.model;
832      agentModels.set(result.agentId, ranOn);
833      agentFiles.set(result.agentId, routed.files);
834      // Jev chose the effort for the routed model, so it only applies if the subagent runs on it.
835      if (ranOn === routed.model) {
836        if (routed.effort) agentEfforts.set(result.agentId, routed.effort);
837      } else {
838        $.ui.log(`jev-router: “${e.description}” was routed to ${routed.model} but kept ${ranOn}`, { to: 'debug' });
839      }
840      // Ties this agent's `turn` records to the router's spawn record.
841      usageBuffer.push({
842        ts: Math.round(Date.now() / 1000),
843        kind: 'spawned',
844        agent_id: result.agentId,
845        description: e.description,
846        routed_model: routed.model,
847        effort: routed.effort ?? null,
848        model: result.model,
849        files: routed.files,
850      });
851    }
852    return result;
853  });
854}
855
856// ---------------------------------------------------------------- jev-skills
857
858const SKILLS_MODULE = 'optim_jev.tools.jev_skills.tool';
859const SKILLS_COMMAND = 'jev-skills';
860const SKILLS_STORE_KEY = 'jev_skills_session';
861const SKILLS_MODES = ['off', 'on'] as const;
862const SKILLS_SCOPES = ['project', 'global'] as const;
863const SKILLS_TIMEOUT_MS = 30_000;
864const SKILLS_USAGE = [
865  'Usage: /jev-skills [on | off]',
866  '       /jev-skills scope project|global',
867  '       /jev-skills why | stats | reindex',
868].join('\n');
869const FOLLOW_UP =
870  /^(y(es)?|no?|ok(ay)?|sure|continue|go( ahead)?|do it|proceed|thanks?|thank you|lgtm|looks good|next|done)[.! ]*$/i;
871type SkillsRecord = { sessionId: string; mode: (typeof SKILLS_MODES)[number]; scope: (typeof SKILLS_SCOPES)[number] };
872
873let skillsOptions: PluginOptions = {};
874let skills: SkillsRecord = { sessionId: '', mode: 'off', scope: 'project' };
875// Folders outside the project holding skills in scope: Claude may read them without asking.
876let skillDirs: string[] = [];
877let skillCount = 0;
878let lastPicks: string[] = [];
879let listingNote = '';
880let skillsIndexing = false;
881let skillsPicking = false;
882let skillsOutcome: SkillsOutcome = { kind: 'not_run', picks: [] };
883
884const skillsOn = () => skills.mode === 'on';
885const normPath = (p: string) => p.replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase();
886
887function skillsStatus(): string {
888  return skillsOn() ? `skills ${skills.scope} (${skillCount})` : 'skills off';
889}
890
891async function skillsFields($: Engine) {
892  return {
893    session_id: await $.session.id(),
894    project_dir: await $.session.root(),
895    scope: skills.scope,
896    options: toolOptions(skillsOptions),
897  };
898}
899
900async function reindex($: Engine) {
901  if (!skillsOn()) {
902    skillDirs = [];
903    skillsIndexing = false;
904    return;
905  }
906  skillsIndexing = true;
907  showActivity($, `Indexing ${skills.scope} skills…`);
908  try {
909    const answer = await runTool<{ count: number; dirs: string[] }>($, skillsOptions, SKILLS_MODULE, 'index', await skillsFields($));
910    skillCount = answer.count;
911    skillDirs = answer.dirs.map(normPath);
912    if (skillsOutcome.kind === 'unavailable') skillsOutcome = { kind: 'not_run', picks: [] };
913  } catch (error) {
914    skillsOutcome = { kind: 'unavailable', picks: [] };
915    $.ui.log(`jev-skills: could not index skills (${errorText(error)})`);
916  } finally {
917    skillsIndexing = false;
918    showActivity($, null);
919  }
920}
921
922async function skillsSessionStart($: Engine) {
923  await $.command.register({
924    name: SKILLS_COMMAND,
925    description: 'Jev skill picker: on or off, project or global scope; why, stats',
926    argumentHint: '[on|off|scope project|global|why|stats|reindex]',
927  });
928  const sessionId = await $.session.id();
929  const stored = (await $.store.get(SKILLS_STORE_KEY)) as Partial<SkillsRecord> | undefined;
930  skills =
931    stored && stored.sessionId === sessionId
932      ? { sessionId, mode: oneOf(SKILLS_MODES, stored.mode, skills.mode), scope: oneOf(SKILLS_SCOPES, stored.scope, skills.scope) }
933      : { ...skills, sessionId };
934  await $.store.set(SKILLS_STORE_KEY, skills);
935  const hasListSkills = (await $.tool.list()).some((t) => t.name === 'ListSkills');
936  listingNote =
937    'Skills are not listed here: optim-jev\'s skill picker shortlists the relevant ones with each request. ' +
938    (hasListSkills
939      ? 'If you need a skill that was not shortlisted, search with the ListSkills tool.'
940      : 'The person can also run any skill with /<name>.');
941  await reindex($);
942}
943
944async function updateSkills($: Engine, change: Partial<Pick<SkillsRecord, 'mode' | 'scope'>> = {}): Promise<void> {
945  skills = { ...skills, ...change };
946  await $.store.set(SKILLS_STORE_KEY, skills);
947  await reindex($);
948  refreshUi($);
949}
950
951async function runSkillsCommand($: Engine, e: CommandRunInput): Promise<CommandRunResult> {
952  const [verb = '', arg = ''] = e.args.trim().split(/\s+/).filter(Boolean);
953  try {
954    if (verb === '') return { text: `jev-skills: ${skillsStatus()}\n\n${SKILLS_USAGE}` };
955    if ((SKILLS_MODES as readonly string[]).includes(verb) || verb === 'scope' || verb === 'reindex') {
956      if (verb === 'scope') {
957        if (!(SKILLS_SCOPES as readonly string[]).includes(arg)) return { text: SKILLS_USAGE };
958        await updateSkills($, { scope: arg as SkillsRecord['scope'] });
959      } else if (verb !== 'reindex') {
960        await updateSkills($, { mode: verb as SkillsRecord['mode'] });
961      } else {
962        await updateSkills($);
963      }
964      const extra =
965        skillsOn() && skills.scope === 'global'
966          ? `\nClaude may read files in ${skillDirs.length} skill folder(s) outside the project without asking.`
967          : '';
968      return { text: `jev-skills: ${skillsStatus()}${extra}` };
969    }
970    if (verb === 'why' || verb === 'stats') {
971      const { text } = await runTool<{ text: string }>($, skillsOptions, SKILLS_MODULE, verb, await skillsFields($));
972      return { text };
973    }
974    return { text: SKILLS_USAGE };
975  } catch (error) {
976    return { text: `jev-skills: ${errorText(error)}` };
977  }
978}
979
980/** The shortlist for one prompt, as context beside it; nothing for slash commands and short follow-ups. */
981async function shortlistFor($: Engine, e: PromptSubmitInput): Promise<string | undefined> {
982  const text = e.text.trim();
983  const kind = e.origin.kind;
984  if (!skillsOn() || skillCount === 0 || (kind !== 'composer' && kind !== 'bridge')) return undefined;
985  if (text.startsWith('/') || text.length < 12 || FOLLOW_UP.test(text)) return undefined;
986  skillsPicking = true;
987  showActivity($, `Picking skills from ${skillCount}…`);
988  try {
989    const answer = await runTool<{ picks: string[]; context: string; failed: string | null }>(
990      $,
991      skillsOptions,
992      SKILLS_MODULE,
993      'shortlist',
994      { ...(await skillsFields($)), prompt: e.text, recent_inputs: recentInputs.slice(-(MAX_RECENT_INPUTS - 1)) },
995      SKILLS_TIMEOUT_MS,
996    );
997    lastPicks = answer.picks;
998    skillsOutcome = {
999      kind: answer.failed ? 'jev_offline' : answer.picks.length > 0 ? 'picked' : 'none',
1000      picks: answer.picks,
1001    };
1002    if (answer.picks.length > 0) notify($, `jev skills · ${answer.picks.join(', ')}`, 6_000);
1003    return answer.context || undefined;
1004  } catch (error) {
1005    skillsOutcome = { kind: 'unavailable', picks: [] };
1006    $.ui.log(`jev-skills: no shortlist (${errorText(error)})`, { to: 'debug' });
1007    return undefined;
1008  } finally {
1009    skillsPicking = false;
1010    showActivity($, null);
1011  }
1012}
1013
1014function isSkillPath(input: unknown): boolean {
1015  if (!input || typeof input !== 'object') return false;
1016  const record = input as Record<string, unknown>;
1017  const raw = record['file_path'] ?? record['path'];
1018  if (typeof raw !== 'string' || !raw) return false;
1019  const path = normPath(raw);
1020  return skillDirs.some((dir) => path === dir || path.startsWith(dir + '/'));
1021}
1022
1023function registerSkills(on: On, pluginOptions: PluginOptions): void {
1024  skillsOptions = pluginOptions;
1025  skills = {
1026    sessionId: '',
1027    mode: oneOf(SKILLS_MODES, pluginOptions['jev_skills_mode'], 'off'),
1028    scope: oneOf(SKILLS_SCOPES, pluginOptions['jev_skills_scope'], 'project'),
1029  };
1030
1031  on('command.run', { command: SKILLS_COMMAND }, async ($, e) => runSkillsCommand($, e));
1032
1033  // The built-in listing of every skill goes; a fixed note takes its place so the cache keeps it.
1034  on('prompt.attachment', async ($, e, next) => {
1035    if (!skillsOn() || e.type !== 'skill_listing') return next(e);
1036    return { text: listingNote };
1037  });
1038
1039  on('prompt.submit', async ($, e, next) => {
1040    // Earlier prompts only: the current one goes to Jev as the request itself.
1041    const context = await shortlistFor($, e);
1042    if (e.origin.kind === 'composer' || e.origin.kind === 'bridge') recentInputs = rememberInput(recentInputs, e.text);
1043    return next(context ? { ...e, context: [...(e.context ?? []), context] } : e);
1044  });
1045
1046  // Global scope: reading a shortlisted skill's own files outside the project needs no prompt.
1047  on('tool.check', { tool: ['Read', 'Glob', 'Grep'] }, async ($, e, next) => {
1048    const verdict = await next(e);
1049    if (verdict.decision !== 'ask' || !skillsOn() || skills.scope !== 'global' || !isSkillPath(e.input)) return verdict;
1050    return { decision: 'allow', reason: 'optim-jev: a skill folder in the skill picker\'s global scope' };
1051  });
1052
1053  on('skill.prompt', async ($, e, next) => {
1054    const result = await next(e);
1055    if (skillsOn()) {
1056      try {
1057        await runTool($, skillsOptions, SKILLS_MODULE, 'loaded', {
1058          ...(await skillsFields($)),
1059          skill: e.skill,
1060          shortlisted: lastPicks.includes(e.skill),
1061        });
1062      } catch (error) {
1063        $.ui.log(`jev-skills: load not logged (${errorText(error)})`, { to: 'debug' });
1064      }
1065    }
1066    return result;
1067  });
1068}
1069
1070// ------------------------------------------------------------- jev-compacter
1071
1072// The level a compaction this plugin starts runs at, read by its session.compact.
1073let pendingLevel: Level | null = null;
1074let checking = false;
1075
1076/** Claude Code's own summary: its real token counts are the baseline jev-compacter is measured against. */
1077async function recordSummary(
1078  $: Engine,
1079  e: SessionCompactInput,
1080  result: SessionCompactResult,
1081  level: Level | null,
1082): Promise<void> {
1083  if (!result.messages || !result.usage) return;
1084  recordUsage('summary', result.usage, {
1085    trigger: e.trigger,
1086    level,
1087    agent_id: e.agentId ?? null,
1088    model: await $.session.model(),
1089    tokens_before: result.tokensBefore ?? null,
1090    tokens_after: result.tokensAfter ?? null,
1091  });
1092}
1093
1094async function autoCompact($: Engine, options: PluginOptions): Promise<void> {
1095  checking = true;
1096  showActivity($, 'Checking context…');
1097  try {
1098    const fields = await sessionFields($, options);
1099    rememberContext(fields.percent);
1100    const soft = options['jev_compacter_soft_percent'];
1101    if (fields.percent >= (typeof soft === 'number' ? soft : DEFAULT_SOFT_PERCENT)) {
1102      const { percent: _percent, ...request } = fields;
1103      const { level } = await runTool<CheckAnswer>($, options, TOOL_MODULE, 'check', request);
1104      compacterDegraded = false;
1105      if (level) {
1106        pendingLevel = level;
1107        await $.session.compact();
1108      }
1109    }
1110  } catch (error) {
1111    compacterDegraded = true;
1112    compactionOutcome = { kind: 'skipped' };
1113    $.ui.log(`jev-compacter: auto-compaction check skipped (${errorText(error)})`);
1114  } finally {
1115    pendingLevel = null;
1116    checking = false;
1117    showActivity($, null);
1118  }
1119}
1120
1121// ------------------------------------------------------------- cold prompt cache
1122//
1123// Once the main conversation's prompt cache is gone, the next request re-reads everything uncached
1124// anyway, so a Jev prune costs no extra cache misses and makes that read smaller. Claude Code's own
1125// summary is the opposite: its request re-reads the whole history uncached, so it is never used here.
1126
1127const COLD_CACHE_MODES = ['ask', 'auto', 'off'] as const;
1128const CACHE_TTLS = ['auto', '5m', '1h'] as const;
1129type CacheTtl = '5m' | '1h';
1130// How far past the TTL before the cache counts as gone.
1131const COLD_GRACE_MS = 15_000;
1132// A resume or model switch: offer once the session has settled.
1133const COLD_SOON_MS = 2_000;
1134const PRUNE_NOW = 'Prune now';
1135
1136let interactive = false;
1137let mainTurnRunning = false;
1138// When Claude last responded on the main loop; the cache stays warm one TTL past it.
1139let lastActivityAt: number | null = null;
1140// Why the main conversation's cache is gone, once a timer, a resume or a model switch said so.
1141let cacheColdReason: string | null = null;
1142// One offer per cold period: the next main-loop turn starts a new one.
1143let coldOffered = false;
1144let coldTimer: { cancel(): void } | null = null;
1145// The TTL Claude Code reported at the last model switch.
1146let reportedTtl: CacheTtl | null = null;
1147
1148function ttlMs(ttl: CacheTtl): number {
1149  return ttl === '1h' ? 3_600_000 : 300_000;
1150}
1151
1152function durationText(ms: number): string {
1153  const minutes = Math.round(ms / 60_000);
1154  return minutes >= 60 ? `${Math.floor(minutes / 60)}h ${minutes % 60}m` : `${minutes}m`;
1155}
1156
1157/** The main conversation's TTL, resolved in the order Claude Code's prompt-caching docs give. */
1158async function cacheTtl($: Engine, options: PluginOptions): Promise<CacheTtl> {
1159  const configured = oneOf(CACHE_TTLS, options['jev_compacter_cache_ttl'], 'auto');
1160  if (configured !== 'auto') return configured;
1161  if (reportedTtl) return reportedTtl;
1162  const settings = await $.settings.read();
1163  const raw = settings['env'];
1164  const settingsEnv = raw && typeof raw === 'object' ? (raw as Record<string, unknown>) : {};
1165  const fromEnv = (value: string | undefined, name: string) => value ?? settingsEnv[name];
1166  if (fromEnv(await $.env.get('FORCE_PROMPT_CACHING_5M'), 'FORCE_PROMPT_CACHING_5M') === '1') return '5m';
1167  const chosen = [
1168    fromEnv(await $.env.get('CLAUDE_CODE_PROMPT_CACHE_TTL'), 'CLAUDE_CODE_PROMPT_CACHE_TTL'),
1169    settings['promptCacheTtl'],
1170  ].find((value): value is CacheTtl => value === '5m' || value === '1h');
1171  if (chosen) return chosen;
1172  if (fromEnv(await $.env.get('ENABLE_PROMPT_CACHING_1H'), 'ENABLE_PROMPT_CACHING_1H') === '1') return '1h';
1173  // The hour is the default only on a subscription within its plan's usage.
1174  const plan = ((await $.session.usage()).rateLimits ?? []).filter(
1175    (limit) => limit.kind === 'five_hour' || limit.kind === 'seven_day',
1176  );
1177  return plan.length > 0 && plan.every((limit) => limit.percentUsed < 100) ? '1h' : '5m';
1178}
1179
1180/** Why the main conversation's cache is gone, or null while it may still be warm. */
1181async function coldReason($: Engine, options: PluginOptions): Promise<string | null> {
1182  if (cacheColdReason !== null) return cacheColdReason;
1183  if (lastActivityAt === null || mainTurnRunning) return null;
1184  try {
1185    const idleMs = (await $.clock.now()) - lastActivityAt;
1186    if (idleMs < ttlMs('5m')) return null;
1187    return idleMs >= ttlMs(await cacheTtl($, options)) ? `idle ${durationText(idleMs)}` : null;
1188  } catch {
1189    return null;
1190  }
1191}
1192
1193function coldCacheMode(options: PluginOptions) {
1194  return oneOf(COLD_CACHE_MODES, options['jev_compacter_cold_cache'], 'ask');
1195}
1196
1197function cancelColdTimer(): void {
1198  coldTimer?.cancel();
1199  coldTimer = null;
1200}
hooks/dashboard.tsx 400 lines
1/* Hallmark · component: terminal dashboard · genre: modern-minimal · theme: warm orange
2 * pre-emit critique: P5 H5 E5 S5 R5 V4 · states and focus: Claude Code Button
3 */
4export type CompactionOutcome =
5  | { kind: 'not_run' }
6  | { kind: 'applied'; freedTokensEst: number }
7  | { kind: 'deferred'; freedTokensEst: number }
8  | { kind: 'builtin' }
9  | { kind: 'nothing' }
10  | { kind: 'skipped' };
11
12export type RouterDecision = {
13  task: string;
14  model: string;
15  effort?: string | null;
16  source: 'jev' | 'rules' | 'escalation' | 'claude' | 'fallback' | 'session';
17  escalated: number;
18};
19
20export type SkillsOutcome =
21  | { kind: 'not_run'; picks: string[] }
22  | { kind: 'picked'; picks: string[] }
23  | { kind: 'none'; picks: string[] }
24  | { kind: 'jev_offline'; picks: string[] }
25  | { kind: 'unavailable'; picks: string[] };
26
27export type DashboardView = {
28  contextPercent: number | null;
29  activity: string | null;
30  compacter: {
31    enabled: boolean;
32    softPercent: number;
33    hardPercent: number;
34    outcome: CompactionOutcome;
35    degraded: boolean;
36  };
37  router: {
38    mode: 'on' | 'off';
39    routing: boolean;
40    offline: boolean;
41    hasRules: boolean;
42    decision: RouterDecision | null;
43  };
44  skills: {
45    mode: 'on' | 'off';
46    scope: 'project' | 'global';
47    count: number;
48    indexing: boolean;
49    picking: boolean;
50    outcome: SkillsOutcome;
51  };
52};
53
54export type DashboardActions = {
55  compact: () => unknown;
56  toggleRouter: () => unknown;
57  toggleSkills: () => unknown;
58};
59
60const ACCENT = '#d97757';
61const WARNING = '#f0b35f';
62const BACKGROUND = '#191411';
63export const DASHBOARD_STAR_COLUMNS = 40;
64export const DASHBOARD_STAR_ROWS = 3;
65export const DASHBOARD_STAR_FRAME_MS = 220;
66export const DASHBOARD_STAR_SPACING = 11;
67
68const particleNoise = (seed: number) => {
69  const value = Math.sin(seed * 12.9898) * 43758.5453;
70  return value - Math.floor(value);
71};
72
73const smoothstep = (value: number) => value * value * (3 - 2 * value);
74
75/** One independently timed particle per horizontal zone; each respawn gets a fresh position. */
76export function dashboardStarPoints(columns: number, rows: number, frame: number) {
77  const count = Math.ceil(columns / DASHBOARD_STAR_SPACING);
78  return Array.from({ length: count }, (_, slot) => {
79    const start = slot * DASHBOARD_STAR_SPACING;
80    const width = Math.min(DASHBOARD_STAR_SPACING, columns - start);
81    const seed = slot * 47 + 11;
82    const lifetime = 18 + Math.floor(particleNoise(seed + 5) * 22);
83    const shifted = frame + Math.floor(particleNoise(seed + 17) * lifetime);
84    const run = Math.floor(shifted / lifetime);
85    const age = (shifted % lifetime) / lifetime;
86    const cycleSeed = seed + run * 197;
87    const glow =
88      age < 0.2
89        ? smoothstep(age / 0.2)
90        : age < 0.58
91          ? 1
92          : age < 0.82
93            ? smoothstep((0.82 - age) / 0.24)
94            : 0;
95    return {
96      x: start + Math.floor(particleNoise(cycleSeed) * Math.max(1, width)),
97      y: (slot + run + Math.floor(particleNoise(cycleSeed + 29) * rows)) % rows,
98      glow: glow * (0.45 + particleNoise(cycleSeed + 73) * 0.55),
99    };
100  });
101}
102
103/** A sparse terminal-native field whose independent particles fade, rest, and respawn. */
104export function dashboardStarFrame(
105  frame: number,
106  columns = DASHBOARD_STAR_COLUMNS,
107  rows = DASHBOARD_STAR_ROWS,
108): string {
109  const words = new Uint32Array(columns * rows * 3);
110  const particles = new Map(
111    dashboardStarPoints(columns, rows, frame).map((particle) => [particle.y * columns + particle.x, particle]),
112  );
113  for (let row = 0; row < rows; row++)
114    for (let x = 0; x < columns; x++) {
115      const i = (row * columns + x) * 3;
116      const particle = particles.get(row * columns + x);
117      const glow = particle?.glow ?? 0;
118      words[i] = glow > 0.16 ? 0x00b7 : 0x20;
119      words[i + 1] = glow > 0.68 ? 0xd97757 : 0x513327;
120      words[i + 2] = 0x191411;
121    }
122  return new Uint8Array(words.buffer).toBase64();
123}
124
125const DASHBOARD_STARS_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="1600" height="60" viewBox="0 0 1600 60" preserveAspectRatio="none"><style>.s{fill:${ACCENT};opacity:0;animation:tw 7s ease-in-out infinite}@keyframes tw{0%,100%{opacity:0}18%{opacity:.42}58%{opacity:.18}78%{opacity:0}}@media(prefers-reduced-motion:reduce){.s{animation:none;opacity:.14}}</style><circle class="s" cx="34" cy="12" r=".8" style="animation-duration:5.4s;animation-delay:-1.1s"/><circle class="s" cx="146" cy="43" r=".8" style="animation-duration:8.1s;animation-delay:-5.3s"/><circle class="s" cx="278" cy="20" r=".8" style="animation-duration:6.7s;animation-delay:-2.7s"/><circle class="s" cx="404" cy="49" r=".8" style="animation-duration:9.3s;animation-delay:-7.4s"/><circle class="s" cx="538" cy="9" r=".8" style="animation-duration:7.6s;animation-delay:-3.1s"/><circle class="s" cx="674" cy="35" r=".8" style="animation-duration:5.9s;animation-delay:-4.8s"/><circle class="s" cx="818" cy="16" r=".8" style="animation-duration:10.2s;animation-delay:-2.2s"/><circle class="s" cx="956" cy="47" r=".8" style="animation-duration:6.3s;animation-delay:-.9s"/><circle class="s" cx="1094" cy="25" r=".8" style="animation-duration:8.8s;animation-delay:-6.5s"/><circle class="s" cx="1232" cy="8" r=".8" style="animation-duration:7.1s;animation-delay:-1.5s"/><circle class="s" cx="1374" cy="41" r=".8" style="animation-duration:9.7s;animation-delay:-8.9s"/><circle class="s" cx="1542" cy="18" r=".8" style="animation-duration:5.7s;animation-delay:-.3s"/></svg>`;
126
127function title(value: string): string {
128  return value ? value[0]!.toUpperCase() + value.slice(1) : value;
129}
130
131function short(value: string, limit: number): string {
132  const one = value.replace(/\s+/g, ' ').trim();
133  return one.length <= limit ? one : `${one.slice(0, limit - 1)}…`;
134}
135
136function tokens(value: number): string {
137  return value >= 1000 ? `~${(value / 1000).toFixed(value >= 10_000 ? 0 : 1)}k` : `~${value}`;
138}
139
140export function compacterText(view: DashboardView, _narrow = false): string {
141  const c = view.compacter;
142  if (!c.enabled) return 'Compacter off';
143  const percent = view.contextPercent === null ? '—' : `${Math.round(view.contextPercent)}%`;
144  const threshold = `soft ${c.softPercent}% · hard ${c.hardPercent}%`;
145  const outcome =
146    c.outcome.kind === 'applied'
147      ? `freed ${tokens(c.outcome.freedTokensEst)}`
148      : c.outcome.kind === 'deferred'
149        ? `deferred ${tokens(c.outcome.freedTokensEst)}`
150        : c.outcome.kind === 'builtin'
151          ? 'built-in summary'
152          : c.outcome.kind === 'nothing'
153            ? 'nothing to prune'
154            : c.outcome.kind === 'skipped'
155              ? 'skipped'
156              : '';
157  return [`Context ${percent}`, threshold, outcome].filter(Boolean).join(' · ');
158}
159
160export function routerText(view: DashboardView, narrow = false): string {
161  const r = view.router;
162  if (r.mode === 'off') return 'Router off';
163  if (r.routing) return 'Router routing…';
164  if (r.offline && !r.decision) return 'Router offline · session model';
165  if (!r.decision) {
166    if (!r.hasRules) return 'Router on · no rules · run /jev-route init';
167    return 'Router on';
168  }
169  const up = r.decision.escalated ? ` ↑${r.decision.escalated}` : '';
170  const effort = r.decision.effort ? ` · ${r.decision.effort}` : '';
171  if (narrow) return `Router on → ${title(r.decision.model)}${effort}${up}`;
172  if (r.decision.source === 'fallback' || r.decision.source === 'session') {
173    return `Router on · ${short(r.decision.task, 22)} → ${title(r.decision.model)}${effort} · session model · Jev offline${up}`;
174  }
175  const source = r.decision.source === 'jev' ? 'Jev' : r.decision.source === 'claude' ? 'Claude' : r.decision.source;
176  return `Router on · ${short(r.decision.task, 22)} → ${title(r.decision.model)}${effort} via ${source}${up}`;
177}
178
179export function skillsText(view: DashboardView, narrow = false): string {
180  const s = view.skills;
181  if (s.mode === 'off') return 'Skills off';
182  if (s.indexing) return 'Skills indexing…';
183  if (s.picking) return narrow ? 'Skills picking…' : `Skills picking from ${s.count}…`;
184  const base = `Skills ${title(s.scope)} ${s.count}`;
185  if (s.outcome.kind === 'unavailable') return `${base} · picker unavailable`;
186  if (s.outcome.kind === 'jev_offline') return `${base} · Jev offline · skill names attached`;
187  if (s.outcome.kind === 'none') return `${base} · none matched`;
188  if (s.outcome.kind !== 'picked') return base;
189  const [first, second] = s.outcome.picks;
190  const picked = second ? `${first} +${s.outcome.picks.length - 1}` : first;
191  return `${base} · ${short(picked ?? '', narrow ? 16 : 24)}`;
192}
193
194type Elements = {
195  // Claude Code supplies these components for the surface being rendered.
196  // eslint-disable-next-line @typescript-eslint/no-explicit-any
197  Box: any;
198  // eslint-disable-next-line @typescript-eslint/no-explicit-any
199  Text: any;
200  // eslint-disable-next-line @typescript-eslint/no-explicit-any
201  Button: any;
202  // eslint-disable-next-line @typescript-eslint/no-explicit-any
203  Raster?: any;
204  // eslint-disable-next-line @typescript-eslint/no-explicit-any
205  Svg?: any;
206};
207
208/** The host can reduce AbovePrompt's height independently of terminal width. */
209export function dashboardLayout(columns: number, maxRows = 5) {
210  const width = Number.isFinite(columns) ? Math.max(0, Math.floor(columns)) : 0;
211  const rows = Number.isFinite(maxRows) ? Math.max(0, Math.floor(maxRows)) : 0;
212  return {
213    width,
214    rows,
215    full: width >= 60 && rows >= 5,
216    controls: width >= 50 && rows >= 2,
217  };
218}
219
220export function dashboardTree(
221  elements: Elements,
222  view: DashboardView,
223  actions: DashboardActions,
224  columns: number,
225  terminal = false,
226  starFrame = 0,
227  maxRows = 5,
228) {
229  const { Box, Text, Button } = elements;
230  const layout = dashboardLayout(columns, maxRows);
231  // No border or fixed-size decoration when the host cannot fit the five-row card.
232  // Commands remain available when there is no room for buttons.
233  if (terminal && !layout.full) {
234    if (!layout.width || !layout.rows) return null;
235    const percent = view.contextPercent === null ? '?' : `${Math.round(view.contextPercent)}%`;
236    const compact = view.compacter.enabled ? `Ctx ${percent}` : 'Compact off';
237    const router = view.router.mode === 'off'
238      ? 'off' : view.router.routing ? 'routing' : view.router.offline ? 'offline' : 'on';
239    const skills = view.skills.mode === 'off'
240      ? 'off' : view.skills.indexing ? 'indexing' : view.skills.picking ? 'picking' : 'on';
241    const status = `${compact} | Router ${router} | Skills ${skills}`;
242    return (
243      <Box
244        key="optim-jev-dashboard"
245        flexDirection="column"
246        width={layout.width}
247        height={layout.controls ? 2 : 1}
248        overflow="hidden"
249      >
250        <Box height={1} minWidth={0} overflow="hidden">
251          <Text wrap="truncate">{view.activity ? `${status} | ${view.activity}` : status}</Text>
252        </Box>
253        {layout.controls ? (
254          <Box
255            key="dashboard-actions"
256            flexDirection="row"
257            flexWrap="nowrap"
258            gap={1}
259            height={1}
260            minWidth={0}
261            overflow="hidden"
262          >
263            <Button key="dashboard-compact" plain label="Compact" onPress={actions.compact} />
264            <Button
265              key="dashboard-router"
266              plain
267              label={`Router ${view.router.mode}`}
268              onPress={actions.toggleRouter}
269            />
270            <Button
271              key="dashboard-skills"
272              plain
273              label={`Skills ${view.skills.mode}`}
274              onPress={actions.toggleSkills}
275            />
276          </Box>
277        ) : null}
278      </Box>
279    );
280  }
281  const narrow = columns > 0 && columns < 90;
282  const compactWarning = view.compacter.degraded;
283  const routerWarning = view.router.mode === 'on' && view.router.offline;
284  const skillsWarning = view.skills.outcome.kind === 'jev_offline' || view.skills.outcome.kind === 'unavailable';
285  const brand = (
286    <Box flexShrink={0}>
287      <Text color={ACCENT} bold>
288        ✦ optim-jev
289      </Text>
290    </Box>
291  );
292  const compactControl = (
293    <Button key="dashboard-compact" variant="secondary" label="Compact" onPress={actions.compact} />
294  );
295  const routerControl = (
296    <Button
297      key="dashboard-router"
298      plain
299      dimColor={view.router.mode === 'off'}
300      label={`${view.router.mode === 'on' ? 'Disable' : 'Enable'} router`}
301      onPress={actions.toggleRouter}
302    />
303  );
304  const skillsControl = (
305    <Button
306      key="dashboard-skills"
307      plain
308      dimColor={view.skills.mode === 'off'}
309      label={`${view.skills.mode === 'on' ? 'Disable' : 'Enable'} skills`}
310      onPress={actions.toggleSkills}
311    />
312  );
313  const controls = (
314    <Box key="dashboard-actions" flexShrink={0} flexDirection="row" flexWrap="wrap" gap={1} alignItems="center">
315      {compactControl}
316      {routerControl}
317      {skillsControl}
318    </Box>
319  );
320  const starColumns = Math.max(1, columns - 4);
321  const terminalStars =
322    terminal && columns >= 60 && elements.Raster ? (
323      <Box key="dashboard-star-field" position="absolute" top={0} left={0} right={0} bottom={0} overflow="hidden">
324        <elements.Raster
325          key="dashboard-stars"
326          columns={starColumns}
327          rows={DASHBOARD_STAR_ROWS}
328          cells={dashboardStarFrame(starFrame, starColumns, DASHBOARD_STAR_ROWS)}
329        />
330      </Box>
331    ) : null;
332  const desktopStars =
333    !terminal && elements.Svg ? (
334      <Box key="dashboard-star-field" position="absolute" top={0} right={0} bottom={0}>
335        <elements.Svg source={DASHBOARD_STARS_SVG} alt="" width={420} height={60} />
336      </Box>
337    ) : null;
338  return (
339    <Box
340      key="optim-jev-dashboard"
341      position="relative"
342      flexDirection="column"
343      paddingX={1}
344      overflow="hidden"
345      backgroundColor={BACKGROUND}
346      borderStyle="round"
347    >
348      {desktopStars}
349      {terminalStars}
350      {terminal ? (
351        <Box flexDirection="column" overflow="hidden">
352          <Box flexDirection="row" gap={1} alignItems="center">
353            {brand}
354            <Text dimColor>·</Text>
355            <Box flexGrow={1} flexShrink={1} minWidth={0} overflow="hidden">
356              <Text color={compactWarning ? WARNING : undefined} wrap="truncate">
357                {view.activity ?? compacterText(view)}
358              </Text>
359            </Box>
360            {compactControl}
361          </Box>
362          <Box flexDirection="row" gap={1} alignItems="center">
363            <Box flexGrow={1} flexShrink={1} minWidth={0} overflow="hidden">
364              <Text color={routerWarning ? WARNING : undefined} wrap="truncate">{routerText(view)}</Text>
365            </Box>
366            {routerControl}
367          </Box>
368          <Box flexDirection="row" gap={1} alignItems="center">
369            <Box flexGrow={1} flexShrink={1} minWidth={0} overflow="hidden">
370              <Text color={skillsWarning ? WARNING : undefined} wrap="truncate">{skillsText(view)}</Text>
371            </Box>
372            {skillsControl}
373          </Box>
374        </Box>
375      ) : (
376        <Box flexDirection="column">
377          <Box flexDirection="row" gap={1} alignItems="center">
378            {brand}
379            <Box flexGrow={1} flexShrink={1} minWidth={0} overflow="hidden">
380              {view.activity ? (
381                <Text color={ACCENT} wrap="truncate">
382                  {view.activity}
383                </Text>
384              ) : null}
385            </Box>
386            {controls}
387          </Box>
388          <Text wrap="truncate">
389            <Text color={compactWarning ? WARNING : undefined}>{compacterText(view, narrow)}</Text>
390            <Text dimColor>{'  │  '}</Text>
391            <Text color={routerWarning ? WARNING : undefined}>{routerText(view, narrow)}</Text>
392            <Text dimColor>{'  │  '}</Text>
393            <Text color={skillsWarning ? WARNING : undefined}>{skillsText(view, narrow)}</Text>
394          </Text>
395        </Box>
396      )}
397    </Box>
398  );
399}
400
hooks/command-output.tsx 113 lines
1/** Styled transcript cards for optim-jev's diagnostic slash commands. */
2
3type Elements = {
4  // Claude Code supplies these constructors for the active render surface.
5  // eslint-disable-next-line @typescript-eslint/no-explicit-any
6  Box: any;
7  // eslint-disable-next-line @typescript-eslint/no-explicit-any
8  Text: any;
9};
10
11const TITLES: Record<string, Partial<Record<string, string>>> = {
12  'jev-route': { stats: 'Router stats', why: 'Why this route' },
13  'jev-skills': { stats: 'Skills stats', why: 'Why these skills' },
14  'jev-compact': { stats: 'Compacter stats' },
15};
16
17const TOKEN = /(saved|applied|shortlist(?:ed)?|measured)/gi;
18const GOOD = /^(saved|applied|shortlist(?:ed)?|measured)$/i;
19
20function valueParts(Text: Elements['Text'], line: string) {
21  return line.split(TOKEN).filter(Boolean).map((part, index) => {
22    return GOOD.test(part) ? <Text key={`part-${index}`} bold>{part}</Text> : part;
23  });
24}
25
26function outputText(Text: Elements['Text'], line: string, _isErrored: boolean) {
27  const note = /^(Estimate prices|Prices |Listing and note sizes|No routed subagent turns)/.test(line);
28
29  return (
30    <Text wrap="wrap" dimColor={note}>
31      {valueParts(Text, line)}
32    </Text>
33  );
34}
35
36type OutputRow =
37  | { kind: 'blank' }
38  | { kind: 'heading'; text: string }
39  | { kind: 'raw'; text: string }
40  | { kind: 'note'; text: string }
41  | { kind: 'table'; label: string; value: string }
42  | { kind: 'text'; text: string };
43
44function outputRow(line: string): OutputRow {
45  if (!line) return { kind: 'blank' };
46  // Stats reports (src/optim_jev/core/report.py): titles, box-drawn tables, notes.
47  if (line.startsWith('▸ ')) return { kind: 'heading', text: line.slice(2) };
48  if (/^[┌│├└]/.test(line)) return { kind: 'raw', text: line };
49  if (line.startsWith('- ')) return { kind: 'note', text: line.slice(2) };
50  const cost = /^\s{2,}(.+?)\s{2,}(\$[\d,.]+.*)$/.exec(line);
51  if (cost) return { kind: 'table', label: cost[1]!.trim(), value: cost[2]!.trim() };
52  const colon = line.indexOf(':');
53  if (!line.startsWith('-') && colon > 0 && colon < 40 && colon < line.length - 1) {
54    return { kind: 'table', label: line.slice(0, colon).trim(), value: line.slice(colon + 1).trim() };
55  }
56  return { kind: 'text', text: line };
57}
58
59export function commandOutputTitle(command: string, args: string): string | null {
60  const verb = args.trim().split(/\s+/, 1)[0] ?? '';
61  return TITLES[command]?.[verb] ?? null;
62}
63
64export function commandOutputTree(
65  elements: Elements,
66  command: string,
67  args: string,
68  output: string,
69  isErrored = false,
70  columns = 100,
71) {
72  const title = commandOutputTitle(command, args);
73  if (!title) return null;
74  const { Box, Text } = elements;
75  const rows = output.split('\n').map(outputRow);
76  const widestLabel = Math.max(0, ...rows.map((row) => row.kind === 'table' ? row.label.length : 0));
77  const labelWidth = Math.max(12, Math.min(28, widestLabel + 2, Math.floor(columns * 0.36)));
78
79  return (
80    <Box key="optim-jev-command-output" flexDirection="column">
81      <Text>
82        ╭─ ◆ <Text bold>{title}</Text>
83      </Text>
84      {rows.map((row, index) => (
85        <Box key={`output-${index}`} flexDirection="row">
86          <Text>│{row.kind === 'blank' ? '' : ' '}</Text>
87          {row.kind === 'table' ? (
88            <Box flexDirection="row" flexGrow={1} minWidth={0}>
89              <Box width={labelWidth} flexShrink={0}>
90                <Text bold>
91                  {row.label}
92                </Text>
93              </Box>
94              <Box flexGrow={1} flexShrink={1} minWidth={0}>
95                {outputText(Text, row.value, isErrored)}
96              </Box>
97            </Box>
98          ) : row.kind === 'heading' ? (
99            <Text bold>{row.text}</Text>
100          ) : row.kind === 'raw' ? (
101            <Text wrap="truncate-end">{valueParts(Text, row.text)}</Text>
102          ) : row.kind === 'note' ? (
103            <Text wrap="wrap" dimColor>
104              {row.text}
105            </Text>
106          ) : row.kind === 'text' ? outputText(Text, row.text, isErrored) : null}
107        </Box>
108      ))}
109      <Text>╰─</Text>
110    </Box>
111  );
112}
113
hooks/router-lib.ts 149 lines
1import type { PluginOptions } from 'claude-code';
2
3export const ROUTER_MODULE = 'optim_jev.tools.jev_router.tool';
4export const ROUTER_COMMAND = 'jev-route';
5export const SECTION_ID = 'optim-jev:jev-router';
6export const STORE_KEY = 'jev_router_session';
7export const MODES = ['off', 'on'] as const;
8export const DEFAULT_ESCALATE_AFTER = 3;
9export const DEFAULT_INIT_MODEL = 'sonnet';
10/** Model call errors that mean the account can't use that model (not a transient failure). */
11export const MODEL_GONE = new Set<string>(['model_not_found', 'invalid_request', 'oauth_org_not_allowed']);
12export const DELETE_COMMANDS = new Set(['rm', 'rmdir', 'del', 'erase', 'unlink', 'remove-item', 'ri', 'mv', 'move', 'move-item']);
13
14/** The routing files Claude may edit itself while routing is on (project-relative). */
15export const RULES_FILES = ['.optim-jev/jev_router/rules.json', '.optim-jev/jev_router/RULES.md'];
16export const isRulesFile = (rel: string) => RULES_FILES.some((f) => f.toLowerCase() === rel.toLowerCase());
17
18export type Mode = (typeof MODES)[number];
19export type Permission = { write: string[]; delete: string[] };
20export type RenderAnswer = {
21  section: string;
22  rules: Record<string, Permission>;
23  tiers: string[];
24  current: string | null;
25  has_rules: boolean;
26};
27export type SpawnAnswer = {
28  model: string;
29  effort: Effort | null;
30  files: string[];
31  appendix: string;
32  toast: string;
33  source: 'jev' | 'rules' | 'escalation' | 'claude' | 'fallback';
34  escalated: number;
35  jev_failed: string | null;
36};
37/** Jev's input was over budget even after trimming: Claude is asked instead, with this prompt. */
38export type SpawnAskClaude = { ask_claude: string; reason: string | null };
39export type Effort = 'low' | 'medium' | 'high' | 'xhigh';
40export const EFFORTS: readonly Effort[] = ['low', 'medium', 'high', 'xhigh'];
41/** Per file: model levels to move up, and the effort to keep, after errors there. */
42export type Escalated = { levels: number; effort: Effort | null };
43export const MAX_RECENT_INPUTS = 4;
44const RECENT_INPUT_STORE_CHARS = 2000;
45
46/**
47 * The person's own prompts, newest last, at most MAX_RECENT_INPUTS: no slash commands, nothing the
48 * plugin or Claude Code injected (system reminders, our shortlist notes).
49 */
50export function rememberInput(recent: string[], text: string): string[] {
51  const t = text.trim();
52  if (!t || t.startsWith('/') || t.startsWith('<') || t.startsWith('optim-jev')) return recent;
53  return [...recent, t.slice(0, RECENT_INPUT_STORE_CHARS)].slice(-MAX_RECENT_INPUTS);
54}
55
56/** Claude's routing answer: `{"model": "...", "effort": "..."}`, possibly wrapped in prose or a fence. */
57export function parseDecision(text: string): { model?: string; effort?: string } | null {
58  const match = /\{[^{}]*\}/.exec(text);
59  if (!match) return null;
60  try {
61    const value = JSON.parse(match[0]) as Record<string, unknown>;
62    return {
63      ...(typeof value['model'] === 'string' ? { model: value['model'].toLowerCase() } : {}),
64      ...(typeof value['effort'] === 'string' ? { effort: value['effort'].toLowerCase() } : {}),
65    };
66  } catch {
67    return null;
68  }
69}
70export type SessionRecord = { sessionId: string; mode: Mode };
71export type Escalation = { from: string; to: string; effort: Effort | null; files: string[] };
72export type TurnState = {
73  spawned: number;
74  errors: Map<string, number>;
75  escalations: Escalation[];
76  deniedCount: number;
77};
78
79export const USAGE = [
80  'Usage: /jev-route [on | off]',
81  '       /jev-route init [--depth N] [--force] ["what matters in this project"]',
82  '       /jev-route why | stats',
83].join('\n');
84
85export function newTurn(): TurnState {
86  return { spawned: 0, errors: new Map(), escalations: [], deniedCount: 0 };
87}
88
89export function oneOf<T extends string>(values: readonly T[], value: unknown, fallback: T): T {
90  return typeof value === 'string' && (values as readonly string[]).includes(value) ? (value as T) : fallback;
91}
92
93export function numberOption(options: PluginOptions, key: string, fallback: number): number {
94  const raw = options[key];
95  const value = typeof raw === 'string' ? Number(raw) : raw;
96  return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback;
97}
98
99export function relPath(file: string, root: string): string {
100  const norm = (p: string) => p.replace(/\\/g, '/').replace(/\/+$/, '');
101  let path = norm(file);
102  const base = norm(root);
103  if (path.toLowerCase().startsWith(base.toLowerCase() + '/')) path = path.slice(base.length + 1);
104  while (path.startsWith('./')) path = path.slice(2);
105  return path;
106}
107
108export function lookup(rules: Record<string, Permission>, rel: string, tiers: string[]): Permission {
109  const index = new Map(Object.entries(rules).map(([k, v]) => [k.toLowerCase(), v]));
110  let probe = rel.toLowerCase().replace(/\/+$/, '');
111  const exact = index.get(probe);
112  if (exact) return exact;
113  while (probe) {
114    const hit = index.get(probe + '/') ?? index.get(probe);
115    if (hit) return hit;
116    probe = probe.includes('/') ? probe.slice(0, probe.lastIndexOf('/')) : '';
117  }
118  return { write: tiers, delete: tiers };
119}
120
121export function words(segment: string): string[] {
122  return [...segment.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)].map((m) => m[1] ?? m[2] ?? m[3] ?? '');
123}
124
125/** Paths a shell command deletes or moves away; best effort, not a security boundary. */
126export function deletedPaths(command: string): string[] {
127  const paths: string[] = [];
128  for (const segment of command.split(/&&|\|\||[;|\n]/)) {
129    let argv = words(segment.trim());
130    if (argv[0] === 'git' && (argv[1] === 'rm' || argv[1] === 'mv')) argv = argv.slice(1);
131    if (argv[0] === 'sudo') argv = argv.slice(1);
132    const name = (argv[0] ?? '').toLowerCase();
133    if (!DELETE_COMMANDS.has(name)) continue;
134    const args = argv.slice(1).filter((a) => !a.startsWith('-') && !(a.startsWith('/') && a.length <= 3));
135    const isMove = ['mv', 'move', 'move-item'].includes(name);
136    paths.push(...(isMove ? args.slice(0, -1) : args));
137  }
138  return paths.filter(Boolean);
139}
140
141export function writeTargets(e: Record<string, unknown>): { paths: string[]; kind: 'write' | 'delete' } {
142  const tool = String(e['tool']);
143  if (tool === 'Edit' || tool === 'Write') return { paths: [String(e['file_path'] ?? '')], kind: 'write' };
144  if (tool === 'NotebookEdit') return { paths: [String(e['notebook_path'] ?? '')], kind: 'write' };
145  if (tool === 'Bash' || tool === 'PowerShell') return { paths: deletedPaths(String(e['command'] ?? '')), kind: 'delete' };
146  return { paths: [], kind: 'write' };
147}
148
149