Scénarios d'agents: read-only guide and editable presets of roles -> model, effort, unit and max parallel, with ready-to-paste snippets, and a « Claude vs GPT…

Now also inside Référence (mods/reference, tab Scénarios, /reference scenarios): same drawing (hooks/draw.tsx, synced there), same scenarios. This mod and its /scenarios command keep working while it is loaded; once it is unloaded, /scenarios is answered by Référence.
/scenarios [S1..] [prompt|agent|workflow|frontmatter|env] | close: a read-only guide over editable presets of roles → model, effort, unit (session, sub-conversation, Workflow agent(), Agent subagent) and max parallel, each setting with the doc it rests on (« non vérifié » when the docs do not say), the documented limits, and ready-to-paste snippets with a Copy button.
scenarios.json here, plus your own file (userConfig file, same shape; a same id replaces). Broken rows are left out and listed as errors.agent.spawn: a warn-only toast when an Agent or Workflow agent() call names no model (userConfig warn_no_model); the spawn always goes on unchanged./scenarios vs [benchmark])A second tab of the same pane: Anthropic and OpenAI models side by side, accuracy (benchmark score) against cost (a blended $ per million tokens, weights in blend, 3 input : 1 output by default). Data: versus.json here, or your own copy (userConfig versus_file).
published, or accessed when the page carries no date). A row without one reads « non confirmé » and is never drawn. Nothing is computed or fetched by the mod; checked says when the file was last verified.To update: read the vendors' launch and pricing pages, edit versus.json (a new row needs source_url and source_date), then node mods/scenarios/scripts/regen-shipped.mjs.
The Appliquer Sx button writes the scenario's per-role model and effort (and the env defaults it implies) to ~/.claude/scenarios/applied.json, keeping the previous record as applied.prev.json, then shows the diff role by role: the lead against ~/.claude/settings.json (model, effortLevel), each subagent or Workflow role against ~/.claude/agents/<agent>.md frontmatter, the env defaults against settings env. Models compare by id (opus = claude-opus-5-5, a [1m] suffix ignored).
It never edits settings.json, an agent file or the environment: the record is a note for Julian and his agents, the diff says what to change by hand.
Code: hooks/apply.ts (record, frontmatter, diff; pure) and hooks/apply_io.ts (the two writes and the reads, through an io the register file builds on $.fs, since a hooks module may not pass $ across an import).
node --test mods/scenarios/tests/*.test.mjs # includes versus.test.mjs
CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 claude plugin test mods/scenarios
claude plugin validate mods/scenarios
After an edit of scenarios.json or versus.json: node mods/scenarios/scripts/regen-shipped.mjs (the test kit's copies), then node scripts/sync-libs.mjs (Référence's copy).
hooks/register.tsx 202 lines1// scenarios mod ("Scénarios d'agents"): a read-only guide over editable presets of roles -> model, effort, unit, max parallel.
2// /scenarios [id] [kind] opens the pane; the pane copies a ready-to-paste snippet; « Appliquer ce scénario » notes the
3// chosen per-role model/effort in ~/.claude/scenarios/applied.json and shows the diff (never edits settings or agents). Scenarios come from scenarios.json
4// beside this mod plus the user's own file (userConfig `file`). Nothing here blocks or rewrites a tool call: the only
5// non-UI hook, on agent.spawn, passes the spawn on unchanged and at most shows a toast.
6import { atom, read, update } from 'claude-code'
7import type { EngineInterface, Register } from 'claude-code'
8
9import type { Checked, ScenarioFile } from '../types'
10import { applyScenario, readApplied } from './apply_io'
11import { drawScenarios } from './draw'
12import type { VsFile } from './versus'
13import { versusText } from './versus'
14import { drawVersus } from './versus_draw'
15import { check, expandHome, merge, parseArgs, snippet } from './logic'
16import type { Kind } from './logic'
17
18const PANE = { id: 'scenarios', title: "Scénarios d'agents" }
19const selected = atom({ plugin: 'scenarios', key: 'selected' } as const, '')
20/** File access handed to apply_io.ts ($ never crosses an import). */
21const io = ($: EngineInterface) => ({
22 read: async (path: string): Promise<string | undefined> => {
23 try {
24 return (await $.fs.read(path, { as: 'text' })) as string
25 } catch {
26 return undefined
27 }
28 },
29 write: (path: string, text: string) => $.fs.write(path, text),
30})
31const kind = atom({ plugin: 'scenarios', key: 'kind' } as const, 'prompt')
32const copied = atom({ plugin: 'scenarios', key: 'copied' } as const, '')
33const applyMsg = atom({ plugin: 'scenarios', key: 'applyMsg' } as const, '')
34const tab = atom({ plugin: 'scenarios', key: 'tab' } as const, 'scenarios' as 'scenarios' | 'versus')
35const bench = atom({ plugin: 'scenarios', key: 'bench' } as const, '')
36
37type Options = { file?: string; warn_no_model?: string; versus_file?: string }
38
39/** versus.json beside the mod, or the user's copy (userConfig versus_file) when set. */
40const loadVersus = async ($: EngineInterface, options: Options): Promise<VsFile | undefined> => {
41 const own = options.versus_file?.trim()
42 const path = own ? expandHome(own, await home($)) : `${$.plugin.root.replace(/\\/g, '/')}/versus.json`
43 return (await readJson($, path)).data as unknown as VsFile | undefined
44}
45
46const readJson = async ($: EngineInterface, path: string): Promise<{ data?: ScenarioFile; problem?: string }> => {
47 let text = ''
48 try {
49 text = (await $.fs.read(path, { as: 'text' })) as string
50 } catch {
51 return { problem: `cannot read ${path}` }
52 }
53 try {
54 return { data: JSON.parse(text) as ScenarioFile }
55 } catch (err) {
56 return { problem: `${path}: not valid JSON (${String(err).slice(0, 120)})` }
57 }
58}
59
60const home = async ($: EngineInterface) => {
61 let v: string | undefined
62 try {
63 v = await $.env.get('USERPROFILE')
64 } catch {}
65 if (!v) {
66 try {
67 v = await $.env.get('HOME')
68 } catch {}
69 }
70 return v ?? ''
71}
72
73const load = async ($: EngineInterface, options: Options): Promise<Checked> => {
74 const root = $.plugin.root.replace(/\\/g, '/')
75 const shipped = await readJson($, `${root}/scenarios.json`)
76 const problems: string[] = shipped.problem ? [shipped.problem] : []
77 let extra: ScenarioFile | undefined
78 if (options.file?.trim()) {
79 const user = await readJson($, expandHome(options.file.trim(), await home($)))
80 if (user.problem) problems.push(user.problem)
81 extra = user.data
82 }
83 const checked = check(merge(shipped.data, extra))
84 return { ...checked, errors: [...problems, ...checked.errors] }
85}
86
87export const register: Register = (on, raw) => {
88 const options = (raw ?? {}) as Options
89 // Spam guard for the warn-only toast: one per minute at most.
90 let lastToast = 0
91
92 on('session.start', async ($, e, next) => {
93 await $.command.register({
94 name: 'scenarios',
95 description: "Scénarios d'agents: roles -> model, effort, unit, max parallel, with ready-to-paste snippets (args: [S1..] [prompt|agent|workflow|frontmatter|env])",
96 argumentHint: '[scenario id] [prompt|agent|workflow|frontmatter|env] | vs [benchmark id] | close',
97 })
98 return next(e)
99 })
100
101 on('command.run', { command: 'scenarios' }, async ($, e) => {
102 if ((e.args ?? '').trim().toLowerCase() === 'close') {
103 await $.ui.close({ id: PANE.id })
104 return {}
105 }
106 const words = (e.args ?? '').trim().split(/\s+/).filter(Boolean)
107 const first = (words[0] ?? '').toLowerCase()
108 if (first === 'vs' || first === 'versus' || first === 'gpt') {
109 const f = await loadVersus($, options)
110 const b = words[1] && (f?.benchmarks ?? []).some(x => x.id === words[1]) ? words[1] : ''
111 if (b) await update($, bench, () => b)
112 await update($, tab, () => 'versus' as const)
113 await $.ui.open({ id: PANE.id, title: PANE.title })
114 return { text: versusText(f, b || (await read($, bench)) || undefined) }
115 }
116 await update($, tab, () => 'scenarios' as const)
117 const { catalog, errors } = await load($, options)
118 const ids = catalog.scenarios.map(s => s.id)
119 const args = parseArgs(e.args ?? '', ids)
120 if (args.id && !ids.includes(args.id)) {
121 return { text: `scenarios: no scenario "${args.id}" (known: ${ids.join(', ') || 'none'})${errors[0] ? ` · ${errors[0]}` : ''}` }
122 }
123 const current = await read($, selected)
124 const scenario = catalog.scenarios.find(s => s.id === (args.id ?? current)) ?? catalog.scenarios[0]
125 if (scenario) await update($, selected, () => scenario.id)
126 if (args.kind) await update($, kind, () => args.kind as string)
127 await $.ui.open({ id: PANE.id, title: PANE.title })
128 const head = `scenarios: ${ids.length} scenario(s)${errors.length ? `, ${errors.length} error(s) in the files` : ''}`
129 if (scenario && args.kind) return { text: `${head}\n\n${snippet(catalog, scenario, args.kind)}` }
130 return { text: `${head} · pane opened${scenario ? ` on ${scenario.id} "${scenario.name}"` : ''}` }
131 })
132
133 // Warn-only: a subagent or Workflow agent that names no model inherits one. The spawn goes on untouched.
134 on('agent.spawn', async ($, e, next) => {
135 const result = await next(e)
136 if (options.warn_no_model !== 'off' && !e.model && !e.fork && !e.isTeammate && Date.now() - lastToast > 60000) {
137 lastToast = Date.now()
138 const what = e.workflow ? 'a Workflow agent()' : `an Agent call (${e.subagentType})`
139 $.ui.toast(`scenarios: ${what} named no model; it runs on ${'model' in result && result.model ? result.model : 'the inherited model'}. /scenarios shows what to set.`)
140 }
141 return result
142 }).catch(($, e, next) => next(e)) // fail open: a failing warning never stops a spawn
143
144 on('ui.render', { component: 'Pane', requestId: 'scenarios' }, async ($, e) => {
145 const ui = $.ui.resolve(e)
146 const { Box, Button } = ui
147 const current = await read($, tab)
148 const vf = await loadVersus($, options)
149 const VL = { tab_scenarios: 'Scénarios', tab_versus: 'Claude vs GPT', ...(vf?.labels ?? {}) }
150 const tabs = (
151 <Box flexDirection="row" gap={1}>
152 {(['scenarios', 'versus'] as const).map(t => (
153 <Button key={`tab-${t}`} plain bold={current === t} dimColor={current !== t} onPress={() => update($, tab, () => t)}>
154 {`${current === t ? '▸ ' : ''}${t === 'scenarios' ? VL.tab_scenarios : VL.tab_versus}`}
155 </Button>
156 ))}
157 </Box>
158 )
159 if (current === 'versus') {
160 return (
161 <Box flexDirection="column">
162 {tabs}
163 {drawVersus(ui, { surface: e.surface, file: vf, bench: await read($, bench), onBench: id => update($, bench, () => id) })}
164 </Box>
165 )
166 }
167 const { catalog, errors, warnings } = await load($, options)
168 const claudeDir = `${(await home($)).replace(/\\/g, '/')}/.claude`
169 const body = drawScenarios(ui, {
170 catalog, errors, warnings,
171 selected: await read($, selected),
172 kind: ((await read($, kind)) as Kind) || 'prompt',
173 copied: await read($, copied),
174 applied: await readApplied(io($), catalog, claudeDir),
175 applyMsg: await read($, applyMsg),
176 onSelect: id => update($, selected, () => id),
177 onKind: k => update($, kind, () => k),
178 onCopy: async (text, label, press) => {
179 const r = await $.ui.copy({ text, surface: press.surface })
180 await update($, copied, () => (r.isCopied ? `copied: ${label}` : 'copy failed: select the text above'))
181 },
182 onApply: async id => {
183 const s = catalog.scenarios.find(x => x.id === id)
184 if (!s) return
185 let msg: string
186 try {
187 msg = await applyScenario(io($), catalog, s, claudeDir, new Date(await $.clock.now()).toISOString())
188 } catch (err) {
189 msg = `écriture impossible : ${String(err).slice(0, 160)}`
190 }
191 await update($, applyMsg, () => msg)
192 },
193 })
194 return (
195 <Box flexDirection="column">
196 {tabs}
197 {body}
198 </Box>
199 )
200 })
201}
202hooks/apply_io.ts 48 lines1// « Appliquer ce scénario », file side, used by the scenarios pane and the Référence hub (synced copy). Writes only
2// ~/.claude/scenarios/applied.json and applied.prev.json; reads ~/.claude/settings.json and ~/.claude/agents/*.md.
3// Never writes settings.json, an agent file or the environment. A hooks module may not pass `$` across an import, so
4// the caller hands in `io`: its own read (text or undefined) and write, built on $.fs in its register file.
5import type { Catalog, Scenario } from '../types'
6import { agentsOf, appliedRecord, diffApplied, frontmatter } from './apply.ts'
7import type { Applied, Current, DiffLine } from './apply.ts'
8
9export type Io = { read: (path: string) => Promise<string | undefined>; write: (path: string, text: string) => Promise<void> }
10const json = (t: string | undefined): any => {
11 try {
12 return t ? JSON.parse(t.replace(/^/, '')) : undefined
13 } catch {
14 return undefined
15 }
16}
17
18/** `<claudeDir>/scenarios`, where the record lives. */
19export const appliedDir = (claudeDir: string) => `${claudeDir.replace(/\\/g, '/').replace(/\/+$/, '')}/scenarios`
20
21/** What settings.json and the agent files a record names say now (read-only). */
22export async function readCurrent(io: Io, claudeDir: string, a: Applied): Promise<Current> {
23 const base = claudeDir.replace(/\\/g, '/').replace(/\/+$/, '')
24 const s = json(await io.read(`${base}/settings.json`))
25 const agents: Current['agents'] = {}
26 for (const name of agentsOf(a)) {
27 const md = await io.read(`${base}/agents/${name}.md`)
28 agents[name] = md === undefined ? undefined : frontmatter(md)
29 }
30 return { settings: s ? { model: s.model, effortLevel: s.effortLevel, env: s.env } : undefined, agents }
31}
32
33/** applied.json with its diff, or undefined when none was written. */
34export async function readApplied(io: Io, c: Catalog, claudeDir: string): Promise<{ record: Applied; diff: DiffLine[] } | undefined> {
35 const record = json(await io.read(`${appliedDir(claudeDir)}/applied.json`)) as Applied | undefined
36 if (!record || !Array.isArray(record.roles)) return undefined
37 return { record, diff: diffApplied(c, record, await readCurrent(io, claudeDir, record)) }
38}
39
40/** Keeps the previous record as applied.prev.json, writes the new one; returns the line the pane shows. */
41export async function applyScenario(io: Io, c: Catalog, s: Scenario, claudeDir: string, at: string): Promise<string> {
42 const dir = appliedDir(claudeDir)
43 const prev = await io.read(`${dir}/applied.json`)
44 if (prev !== undefined) await io.write(`${dir}/applied.prev.json`, prev)
45 await io.write(`${dir}/applied.json`, `${JSON.stringify(appliedRecord(c, s, at), null, 1)}\n`)
46 return `${s.id} noté dans ~/.claude/scenarios/applied.json${prev !== undefined ? ' (précédent : applied.prev.json)' : ''}`
47}
48hooks/draw.tsx 148 lines1// scenarios mod: the pane's drawing, pure. No `$`: the elements come in as `ui` ($.ui.resolve(e)) and every action as a
2// callback in `m`, so the scenarios pane and the Référence hub (mods/reference, a synced copy of this file) draw the
3// same tree. Same output as the drawing that lived in register.tsx, plus « Appliquer ce scénario » and its diff.
4import type { Catalog } from '../types'
5import type { Applied, DiffLine } from './apply'
6import { diffSummary } from './apply'
7import { KINDS, KIND_LABEL, limitsFor, roleLine, settingsFor, snippet } from './logic'
8import type { Kind } from './logic'
9
10export type ScenariosModel = {
11 catalog: Catalog
12 errors: string[]
13 warnings: string[]
14 selected: string
15 kind: Kind
16 copied: string
17 /** applied.json and its diff vs the agent files and settings, when one was written */
18 applied?: { record: Applied; diff: DiffLine[] } | undefined
19 /** outcome of the last « Appliquer » press */
20 applyMsg?: string
21 onSelect: (id: string) => void | Promise<void>
22 onKind: (k: Kind) => void | Promise<void>
23 onCopy: (text: string, label: string, press: any) => void | Promise<void>
24 onApply?: (id: string) => void | Promise<void>
25}
26
27export const kindsOf = (c: Catalog): Kind[] => {
28 const listed = c.snippets.filter((k): k is Kind => (KINDS as readonly string[]).includes(k))
29 return listed.length ? listed : [...KINDS]
30}
31
32export function drawScenarios(ui: any, m: ScenariosModel): any {
33 const { Box, Text, Button, Code, Link } = ui
34 const { catalog, errors, warnings } = m
35 const s = catalog.scenarios.find(x => x.id === m.selected) ?? catalog.scenarios[0]
36 const k = m.kind || 'prompt'
37 const kinds = kindsOf(catalog)
38 const url = (key: string) => catalog.sources[key] ?? ''
39 const cite = (key: string, verified = true) => (
40 <Box flexDirection="row" gap={1}>
41 {verified ? null : <Text color="warning">non vérifié</Text>}
42 {url(key) ? <Link href={url(key)} label={url(key)} /> : <Text dimColor>no source</Text>}
43 </Box>
44 )
45 const ap = m.applied
46
47 return (
48 <Box flexDirection="column" gap={1}>
49 <Text dimColor>Read-only guide. Edit scenarios.json or your own file (userConfig "file") to add S5 and more.</Text>
50 {errors.length > 0 && (
51 <Box flexDirection="column">
52 <Text color="error" bold>{`${errors.length} error(s): those scenarios are left out`}</Text>
53 {errors.map(x => <Text color="error">{`· ${x}`}</Text>)}
54 </Box>
55 )}
56 {warnings.length > 0 && (
57 <Box flexDirection="column">
58 {warnings.map(x => <Text color="warning">{`· ${x}`}</Text>)}
59 </Box>
60 )}
61 <Box flexDirection="row" gap={1} flexWrap="wrap">
62 {catalog.scenarios.map(x => (
63 <Button key={`sc-${x.id}`} {...(x.id !== s?.id ? { plain: true as const } : {})} onPress={() => m.onSelect(x.id)}>
64 {`${x.id} ${x.name}`}
65 </Button>
66 ))}
67 </Box>
68 {!s && <Text>No valid scenario. Fix the errors above.</Text>}
69 {s && (
70 <Box flexDirection="column" gap={1}>
71 <Text bold>{`${s.id} · ${s.name}`}</Text>
72 {s.summary ? <Text>{s.summary}</Text> : null}
73 <Text dimColor>
74 {`Escalation: ${s.escalation === false ? 'no' : 'after one failure, one step up'}` +
75 (s.caps && Object.keys(s.caps).length ? ` · caps: ${Object.entries(s.caps).map(([a, b]) => `${a.replace(/_/g, ' ')} ${b}`).join(', ')}` : '')}
76 </Text>
77 <Box flexDirection="column">
78 {s.roles.map(r => (
79 <Box flexDirection="column">
80 <Text bold>{roleLine(catalog, r)}</Text>
81 {settingsFor(catalog, r).map(line => (
82 <Box flexDirection="column">
83 <Text>{` ${line.text}`}</Text>
84 <Box flexDirection="row" gap={1}>
85 <Text dimColor>{' '}</Text>
86 {cite(line.source, line.verified)}
87 </Box>
88 </Box>
89 ))}
90 </Box>
91 ))}
92 </Box>
93 <Text bold>Documented limits</Text>
94 <Box flexDirection="column">
95 {limitsFor(catalog, s).map(l => (
96 <Box flexDirection="column">
97 <Text>{`· ${l.text}`}</Text>
98 <Box flexDirection="row" gap={1}>
99 <Text dimColor>{' '}</Text>
100 {cite(l.source, l.verified)}
101 </Box>
102 </Box>
103 ))}
104 </Box>
105 <Text bold>Snippet</Text>
106 <Box flexDirection="row" gap={1} flexWrap="wrap">
107 {kinds.map(x => (
108 <Button key={`kind-${x}`} {...(x !== k ? { plain: true as const } : {})} onPress={() => m.onKind(x)}>
109 {KIND_LABEL[x]}
110 </Button>
111 ))}
112 </Box>
113 <Code source={snippet(catalog, s, k)} language={k === 'frontmatter' ? 'yaml' : k === 'prompt' ? 'text' : 'javascript'} />
114 <Box flexDirection="row" gap={1}>
115 <Button key="copy" hotkey="c" onPress={(press: any) => m.onCopy(snippet(catalog, s, k), `${s.id} ${KIND_LABEL[k]}`, press)}>
116 Copy snippet
117 </Button>
118 {m.copied ? <Text dimColor>{m.copied}</Text> : null}
119 </Box>
120 {m.onApply ? (
121 <Box flexDirection="column">
122 <Text bold>Appliquer ce scénario</Text>
123 <Text dimColor wrap="wrap">
124 Écrit les modèles et efforts de chaque rôle dans ~/.claude/scenarios/applied.json (le précédent reste dans applied.prev.json) et montre l'écart avec tes agents et settings. Ne modifie jamais settings.json, les agents ni l'environnement.
125 </Text>
126 <Box flexDirection="row" gap={1}>
127 <Button key="apply" onPress={() => m.onApply!(s.id)}>{`Appliquer ${s.id}`}</Button>
128 {m.applyMsg ? <Text dimColor>{m.applyMsg}</Text> : null}
129 </Box>
130 </Box>
131 ) : null}
132 </Box>
133 )}
134 {ap ? (
135 <Box flexDirection="column">
136 <Text bold>{diffSummary(ap.record, ap.diff)}</Text>
137 {ap.diff.map((d, i) => (
138 <Text key={`diff-${i}`} wrap="wrap" {...(d.same ? { dimColor: true } : { color: 'warning' as const })}>
139 {`${d.same ? ' =' : ' ≠'} ${d.role} · ${d.where} · ${d.field} : ${d.current}${d.same ? '' : ` → ${d.applied}`}`}
140 </Text>
141 ))}
142 <Text dimColor wrap="wrap">{ap.record.note}</Text>
143 </Box>
144 ) : null}
145 </Box>
146 )
147}
148hooks/versus.ts 155 lines1// scenarios mod, « Claude vs GPT » tab: pure helpers over versus.json (Anthropic and OpenAI models, accuracy vs cost).
2// No `$`, so node tests import it directly. A number is shown only with its source URL and date; anything else reads
3// « non confirmé » and is never drawn as a point. Nothing here fetches or computes a score: it only reads the file.
4
5export type Vendor = 'anthropic' | 'openai'
6export type VsModel = { id: string; vendor: Vendor; label: string; released?: string; released_url?: string }
7export type VsSource = { source_url?: string; source_date?: string; date_kind?: 'published' | 'accessed'; note?: string }
8export type VsPrice = VsSource & { model: string; in?: number | null; out?: number | null }
9export type VsScore = VsSource & { model: string; bench: string; value?: number | null; effort?: string; reported_by?: string }
10export type VsBench = { id: string; label: string; unit?: string; about?: string; url?: string }
11export type VsLabels = Partial<Record<'tab_scenarios' | 'tab_versus' | 'unconfirmed' | 'cost' | 'score' | 'price' | 'source' | 'per_point', string>>
12export type VsFile = {
13 schema?: number
14 checked?: string
15 blend?: { in?: number; out?: number }
16 benchmarks?: VsBench[]
17 models?: VsModel[]
18 prices?: VsPrice[]
19 scores?: VsScore[]
20 labels?: VsLabels
21}
22
23export const VS_LABELS: Required<VsLabels> = {
24 tab_scenarios: 'Scénarios',
25 tab_versus: 'Claude vs GPT',
26 unconfirmed: 'non confirmé',
27 cost: '$/M tok (mélange)',
28 score: 'score',
29 price: 'prix in/out $/M',
30 source: 'source',
31 per_point: '$/M par point',
32}
33export const vsLabels = (f: VsFile | undefined): Required<VsLabels> => ({ ...VS_LABELS, ...(f?.labels ?? {}) })
34
35const DATE = /^\d{4}-\d{2}-\d{2}$/
36const num = (x: unknown): x is number => typeof x === 'number' && Number.isFinite(x)
37/** A source counts only with an https URL and an ISO date. */
38export const sourced = (s: VsSource | undefined): boolean =>
39 !!s && typeof s.source_url === 'string' && /^https:\/\//.test(s.source_url) && typeof s.source_date === 'string' && DATE.test(s.source_date)
40export const scoreConfirmed = (s: VsScore | undefined): boolean => !!s && num(s.value) && sourced(s)
41export const priceConfirmed = (p: VsPrice | undefined): boolean => !!p && num(p.in) && num(p.out) && sourced(p)
42
43/** Problems that make a row unusable (shown in the pane, the row is then treated as unconfirmed). */
44export const checkVersus = (f: VsFile | undefined): string[] => {
45 if (!f) return ['versus.json: absent ou illisible']
46 const out: string[] = []
47 const ids = new Set((f.models ?? []).map(m => m.id))
48 const benches = new Set((f.benchmarks ?? []).map(b => b.id))
49 for (const m of f.models ?? []) if (m.vendor !== 'anthropic' && m.vendor !== 'openai') out.push(`model ${m.id}: vendor "${m.vendor}" is neither anthropic nor openai`)
50 for (const p of f.prices ?? []) {
51 if (!ids.has(p.model)) out.push(`price: unknown model "${p.model}"`)
52 if ((num(p.in) || num(p.out)) && !sourced(p)) out.push(`price ${p.model}: a number without an https source and a YYYY-MM-DD date`)
53 }
54 for (const s of f.scores ?? []) {
55 if (!ids.has(s.model)) out.push(`score: unknown model "${s.model}"`)
56 if (!benches.has(s.bench)) out.push(`score ${s.model}: unknown benchmark "${s.bench}"`)
57 if (num(s.value) && !sourced(s)) out.push(`score ${s.model} ${s.bench}: a number without an https source and a YYYY-MM-DD date`)
58 if (num(s.value) && (s.value < 0 || s.value > 100)) out.push(`score ${s.model} ${s.bench}: ${s.value} is not a percentage`)
59 }
60 return out
61}
62
63/** Blended $ per million tokens with the file's weights (3 input : 1 output when absent). */
64export const blended = (p: VsPrice | undefined, blend?: VsFile['blend']): number | null => {
65 if (!priceConfirmed(p)) return null
66 const wi = num(blend?.in) && blend!.in! >= 0 ? blend!.in! : 3
67 const wo = num(blend?.out) && blend!.out! >= 0 ? blend!.out! : 1
68 if (wi + wo <= 0) return null
69 return Math.round(((p!.in! * wi + p!.out! * wo) / (wi + wo)) * 100) / 100
70}
71
72export type VsRow = {
73 model: VsModel
74 score: VsScore | undefined
75 confirmed: boolean
76 price: VsPrice | undefined
77 cost: number | null
78}
79
80/** One row per (model, score source) on that benchmark, plus one « non confirmé » row for a model without any score.
81 * Sorted: confirmed first, by score descending; then unconfirmed by label. */
82export const rowsFor = (f: VsFile | undefined, bench: string): VsRow[] => {
83 if (!f) return []
84 const out: VsRow[] = []
85 for (const m of f.models ?? []) {
86 const price = (f.prices ?? []).find(p => p.model === m.id)
87 const cost = blended(price, f.blend)
88 const scores = (f.scores ?? []).filter(s => s.model === m.id && s.bench === bench)
89 if (!scores.length) out.push({ model: m, score: undefined, confirmed: false, price, cost })
90 for (const s of scores) out.push({ model: m, score: s, confirmed: scoreConfirmed(s), price, cost })
91 }
92 return out.sort((a, b) =>
93 a.confirmed !== b.confirmed ? (a.confirmed ? -1 : 1)
94 : a.confirmed ? (b.score!.value! - a.score!.value!) || a.model.label.localeCompare(b.model.label)
95 : a.model.label.localeCompare(b.model.label))
96}
97
98export const fmtCost = (x: number | null): string => (x == null ? '?' : x < 1 ? x.toFixed(2) : x.toFixed(x < 10 ? 1 : 0))
99
100/** One line for a row, e.g. « Claude Opus 5.5 · 66.4 % (xhigh, Anthropic) · 8.0 $/M · 2026-09-22 ». */
101export const rowLine = (L: Required<VsLabels>, r: VsRow): string => {
102 const who = r.model.vendor === 'anthropic' ? 'Claude' : 'GPT'
103 const score = r.confirmed
104 ? `${r.score!.value} %${r.score!.effort || r.score!.reported_by ? ` (${[r.score!.effort, r.score!.reported_by].filter(Boolean).join(', ')})` : ''}`
105 : `${L.unconfirmed}${r.score?.reported_by ? ` (${r.score.reported_by})` : ''}`
106 const cost = r.cost != null ? `${fmtCost(r.cost)} $/M` : `prix ${L.unconfirmed}`
107 const date = r.confirmed ? ` · ${r.score!.source_date}${r.score!.date_kind === 'accessed' ? ' (lu)' : ''}` : ''
108 return `${r.model.label.startsWith(who) ? '' : `${who} · `}${r.model.label} · ${score} · ${cost}${date}`
109}
110
111/** The text answer of /scenarios vs [bench]. */
112export const versusText = (f: VsFile | undefined, bench?: string): string => {
113 if (!f) return 'scenarios vs: versus.json absent ou illisible'
114 const L = vsLabels(f)
115 const b = (f.benchmarks ?? []).find(x => x.id === bench) ?? (f.benchmarks ?? [])[0]
116 if (!b) return 'scenarios vs: aucun benchmark dans versus.json'
117 const rows = rowsFor(f, b.id)
118 const head = `${L.tab_versus} · ${b.label} · vérifié le ${f.checked ?? '?'} · coût = ${L.cost} (${f.blend?.in ?? 3} in : ${f.blend?.out ?? 1} out)`
119 return [head, ...rows.map(r => `· ${rowLine(L, r)}`), 'Scores de chaque éditeur sur son propre harnais : comparer à l’intérieur d’un benchmark, jamais entre deux.'].join('\n')
120}
121
122const esc = (s: string) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>')
123
124/** Static scatter (cost on x, log scale; score on y). Only confirmed score + confirmed price rows are drawn. */
125export const scatterSvg = (f: VsFile | undefined, bench: string, colors: Record<string, string> = {}): string => {
126 const pts = rowsFor(f, bench).filter(r => r.confirmed && r.cost != null && r.cost > 0)
127 const C = { anthropic: '#d97757', openai: '#10a37f', line: '#8c959f', text: '#8c959f', ...colors }
128 const W = 420, H = 240, L = 40, R = 12, T = 12, B = 34
129 if (!pts.length) return `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="40"><text x="4" y="24" fill="${C.text}" font-size="12">aucun point confirmé</text></svg>`
130 const xs = pts.map(p => Math.log10(p.cost!)), ys = pts.map(p => p.score!.value!)
131 const x0 = Math.min(...xs) - 0.1, x1 = Math.max(...xs) + 0.1
132 const y0 = Math.max(0, Math.floor(Math.min(...ys) / 10) * 10 - 5), y1 = Math.min(100, Math.ceil(Math.max(...ys) / 10) * 10 + 5)
133 const px = (v: number) => L + ((v - x0) / (x1 - x0 || 1)) * (W - L - R)
134 const py = (v: number) => T + (1 - (v - y0) / (y1 - y0 || 1)) * (H - T - B)
135 const parts = [
136 `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" font-family="sans-serif" font-size="10">`,
137 `<line x1="${L}" y1="${H - B}" x2="${W - R}" y2="${H - B}" stroke="${C.line}"/>`,
138 `<line x1="${L}" y1="${T}" x2="${L}" y2="${H - B}" stroke="${C.line}"/>`,
139 `<text x="${L}" y="${H - 6}" fill="${C.text}">coût $/M (log) →</text>`,
140 `<text x="2" y="${T + 8}" fill="${C.text}">${y1} %</text>`,
141 `<text x="2" y="${H - B}" fill="${C.text}">${y0} %</text>`,
142 ]
143 pts.forEach((p, i) => {
144 const x = px(Math.log10(p.cost!)), y = py(p.score!.value!)
145 const c = p.model.vendor === 'anthropic' ? C.anthropic : C.openai
146 const indep = /ind[ée]pendant/i.test(p.score!.reported_by ?? '')
147 parts.push(indep
148 ? `<circle cx="${x.toFixed(1)}" cy="${y.toFixed(1)}" r="4" fill="none" stroke="${c}" stroke-width="1.5"/>`
149 : `<circle cx="${x.toFixed(1)}" cy="${y.toFixed(1)}" r="4" fill="${c}"/>`)
150 parts.push(`<text x="${(x + 6).toFixed(1)}" y="${(y + (i % 2 ? 10 : -4)).toFixed(1)}" fill="${c}">${esc(p.model.label.replace(/^Claude |^GPT-/, m => (m === 'GPT-' ? 'GPT-' : '')))} ${p.score!.value}</text>`)
151 })
152 parts.push('</svg>')
153 return parts.join('')
154}
155hooks/versus_draw.tsx 87 lines1// scenarios mod, « Claude vs GPT » tab: the drawing, pure (elements from $.ui.resolve(e), presses through `m`).
2// The scatter is a static picture (svg, not clickable); the benchmark buttons stay buttons.
3import type { VsFile } from './versus'
4import { checkVersus, rowLine, rowsFor, scatterSvg, vsLabels } from './versus'
5
6export type VersusModel = {
7 surface: string
8 file: VsFile | undefined
9 bench: string
10 onBench: (id: string) => void | Promise<void>
11}
12
13export function drawVersus(ui: any, m: VersusModel): any {
14 const { Box, Text, Button, Link } = ui
15 const f = m.file
16 const L = vsLabels(f)
17 const problems = checkVersus(f)
18 const benches = f?.benchmarks ?? []
19 const b = benches.find(x => x.id === m.bench) ?? benches[0]
20 if (!f || !b) {
21 return (
22 <Box flexDirection="column">
23 <Text color="error">{problems[0] ?? 'aucun benchmark dans versus.json'}</Text>
24 </Box>
25 )
26 }
27 const rows = rowsFor(f, b.id)
28 const Svg = m.surface === 'terminal' ? undefined : ui.Svg
29 const confirmed = rows.filter(r => r.confirmed).length
30 return (
31 <Box flexDirection="column" gap={1}>
32 <Text dimColor wrap="wrap">
33 {`Scores et prix lus sur des pages datées (vérifié le ${f.checked ?? '?'}). Coût = ${L.cost} avec ${f.blend?.in ?? 3} in : ${f.blend?.out ?? 1} out. Chaque éditeur mesure sur son propre harnais : comparer à l'intérieur d'un benchmark seulement. « ${L.unconfirmed} » = pas de source lue, jamais un chiffre inventé.`}
34 </Text>
35 {problems.length ? (
36 <Box flexDirection="column">
37 {problems.map((p, i) => <Text key={`vp-${i}`} color="warning" wrap="wrap">{`· ${p}`}</Text>)}
38 </Box>
39 ) : null}
40 <Box flexDirection="row" gap={1} flexWrap="wrap">
41 {benches.map(x => (
42 <Button key={`vs-${x.id}`} {...(x.id !== b.id ? { plain: true as const } : {})} onPress={() => m.onBench(x.id)}>
43 {x.label}
44 </Button>
45 ))}
46 </Box>
47 <Text bold>{`${b.label} · ${confirmed} score(s) confirmé(s) sur ${rows.length} ligne(s)`}</Text>
48 {b.about ? <Text dimColor wrap="wrap">{b.about}</Text> : null}
49 {Svg ? <Svg key={`vs-svg-${b.id}`} source={scatterSvg(f, b.id)} alt={`${b.label} : score selon le coût (Claude en orange, GPT en vert, cercle vide = mesure indépendante)`} /> : null}
50 <Box flexDirection="column">
51 {rows.map((r, i) => (
52 <Box key={`vr-${i}`} flexDirection="column">
53 <Text wrap="wrap" {...(r.confirmed ? {} : { dimColor: true })}>
54 {`· ${rowLine(L, r)}`}
55 </Text>
56 <Box flexDirection="row" gap={1}>
57 <Text dimColor>{' '}</Text>
58 {r.confirmed && r.score?.source_url ? <Link href={r.score.source_url} label={r.score.source_url} /> : <Text color="warning">{L.unconfirmed}</Text>}
59 {r.score?.note ? <Text dimColor wrap="wrap">{r.score.note}</Text> : null}
60 </Box>
61 </Box>
62 ))}
63 </Box>
64 <Text bold>{L.price}</Text>
65 <Box flexDirection="column">
66 {(f.models ?? []).map(md => {
67 const p = (f.prices ?? []).find(x => x.model === md.id)
68 const ok = p && typeof p.in === 'number' && typeof p.out === 'number' && p.source_url
69 return (
70 <Box key={`vpr-${md.id}`} flexDirection="column">
71 <Text wrap="wrap" {...(ok ? {} : { dimColor: true })}>
72 {`· ${md.label} · ${ok ? `${p!.in} / ${p!.out}` : L.unconfirmed}${p?.note ? ` · ${p.note}` : ''}${ok ? ` · ${p!.source_date}${p!.date_kind === 'accessed' ? ' (lu)' : ''}` : ''}`}
73 </Text>
74 {ok ? (
75 <Box flexDirection="row" gap={1}>
76 <Text dimColor>{' '}</Text>
77 <Link href={p!.source_url!} label={p!.source_url!} />
78 </Box>
79 ) : null}
80 </Box>
81 )
82 })}
83 </Box>
84 </Box>
85 )
86}
87hooks/logic.ts 184 lines1// Pure logic of the scenarios mod: merge, validate, describe and turn a scenario into ready-to-paste snippets.
2// No `$`, no imports but types: the engine loads it from register.tsx and `node --test` loads it as plain TS.
3import type { Catalog, Checked, Limit, Role, Scenario, ScenarioFile } from '../types'
4
5export const KINDS = ['prompt', 'agent', 'workflow', 'frontmatter', 'env'] as const
6export type Kind = (typeof KINDS)[number]
7export const KIND_LABEL: Record<Kind, string> = {
8 prompt: 'Prompt line',
9 agent: 'Agent calls',
10 workflow: 'Workflow agent()',
11 frontmatter: 'Agent files',
12 env: 'Env vars',
13}
14
15const EMPTY: Catalog = { sources: {}, models: {}, efforts: [], units: {}, limits: [], snippets: [], scenarios: [] }
16
17/** Shipped file first, then the user's: tables merge by key, limits and scenarios by id (the later one wins). */
18export function merge(...files: (ScenarioFile | undefined)[]): Catalog {
19 const out: Catalog = { ...EMPTY, sources: {}, models: {}, units: {}, limits: [], scenarios: [] }
20 for (const f of files) {
21 if (!f || typeof f !== 'object') continue
22 Object.assign(out.sources, f.sources ?? {})
23 Object.assign(out.models, f.models ?? {})
24 Object.assign(out.units, f.units ?? {})
25 if (Array.isArray(f.efforts) && f.efforts.length) out.efforts = [...f.efforts]
26 if (Array.isArray(f.snippets) && f.snippets.length) out.snippets = [...f.snippets]
27 for (const l of Array.isArray(f.limits) ? f.limits : []) out.limits = [...out.limits.filter(x => x.id !== l?.id), l]
28 for (const s of Array.isArray(f.scenarios) ? f.scenarios : []) out.scenarios = [...out.scenarios.filter(x => x.id !== s?.id), s]
29 }
30 return out
31}
32
33const isFullId = (m: string) => /^claude-[a-z0-9.-]+$/.test(m)
34const rank = (c: Catalog, effort: string) => c.efforts.indexOf(effort)
35const leadOf = (s: Scenario) => s.roles.find(r => r.unit === 'session')
36
37/** Checks every scenario against the catalog's tables and the documented limits; a broken scenario is dropped with its errors. */
38export function check(c: Catalog): Checked {
39 const errors: string[] = []
40 const warnings: string[] = []
41 for (const [key, url] of Object.entries(c.sources)) if (!/^https:\/\//.test(String(url))) errors.push(`source ${key}: not an https URL`)
42 for (const l of c.limits) if (!l || !l.id || !l.text || !(l.source in c.sources)) errors.push(`limit ${l?.id ?? '?'}: needs id, text and a known source`)
43 const seen = new Set<string>()
44 const kept: Scenario[] = []
45 for (const s of c.scenarios) {
46 const where = `scenario ${s?.id ?? '?'}`
47 const own: string[] = []
48 if (!s || typeof s !== 'object') { errors.push(`${where}: not an object`); continue }
49 if (!s.id || typeof s.id !== 'string') own.push(`${where}: missing id`)
50 else if (seen.has(s.id)) own.push(`${where}: duplicate id`)
51 if (!s.name || typeof s.name !== 'string') own.push(`${where}: missing name`)
52 if (!Array.isArray(s.roles) || s.roles.length === 0) own.push(`${where}: needs at least one role`)
53 for (const r of Array.isArray(s.roles) ? s.roles : []) {
54 const at = `${where} role ${r?.role ?? '?'}`
55 if (!r || !r.role) { own.push(`${at}: missing role name`); continue }
56 if (!(r.model in c.models) && !isFullId(String(r.model))) own.push(`${at}: unknown model "${r.model}"`)
57 if (rank(c, r.effort) < 0) own.push(`${at}: effort "${r.effort}" is not one of ${c.efforts.join(', ')}`)
58 if (!(r.unit in c.units)) own.push(`${at}: unit "${r.unit}" is not one of ${Object.keys(c.units).join(', ')}`)
59 if (!Number.isInteger(r.max_parallel) || r.max_parallel < 1) own.push(`${at}: max_parallel must be a whole number >= 1`)
60 for (const l of c.limits) {
61 if (l.max != null && l.unit === r.unit && r.max_parallel > l.max) own.push(`${at}: max_parallel ${r.max_parallel} is above the limit "${l.text}"`)
62 }
63 }
64 if (own.length === 0) {
65 const lead = leadOf(s)
66 for (const r of s.roles) {
67 if (lead && r.unit === 'sub-conversation' && rank(c, r.effort) > rank(c, lead.effort)) {
68 warnings.push(`${where} role ${r.role}: a sub-conversation's effort (${r.effort}) is above its parent's (${lead.effort}); expected at most the parent's (non vérifié)`)
69 }
70 }
71 for (const l of c.limits) {
72 if (l.max == null || !l.unit) continue
73 const total = s.roles.filter(r => r.unit === l.unit).reduce((n, r) => n + r.max_parallel, 0)
74 if (total > l.max) warnings.push(`${where}: ${total} ${l.unit} at once if every role peaks together; limit "${l.text}"`)
75 }
76 }
77 if (s?.id) seen.add(s.id)
78 if (own.length) errors.push(...own)
79 else kept.push(s)
80 }
81 return { catalog: { ...c, scenarios: kept }, errors, warnings }
82}
83
84export const modelLabel = (c: Catalog, m: string) => c.models[m]?.label ?? m
85const roleName = (r: Role) => r.label ?? r.role
86const unitLabel = (c: Catalog, u: string) => c.units[u]?.label ?? u
87
88/** One line per role: what it runs on and as what. */
89export function roleLine(c: Catalog, r: Role): string {
90 return `${roleName(r)}: ${modelLabel(c, r.model)} · ${r.effort} · ${unitLabel(c, r.unit)} · max ${r.max_parallel}${r.note ? ` (${r.note})` : ''}`
91}
92
93/** The exact settings for a role, by the unit it runs as. Each line ends with the doc key it rests on. */
94export function settingsFor(c: Catalog, r: Role): { text: string; source: string; verified: boolean }[] {
95 const agent = r.agent ?? r.role
96 const out: { text: string; source: string; verified: boolean }[] = []
97 switch (r.unit) {
98 case 'session':
99 out.push({ text: `start the session with --model ${r.model} and /effort ${r.effort} (or "model" / "effortLevel" in settings); never switch a running session`, source: 'model-config', verified: true })
100 break
101 case 'sub-conversation':
102 out.push({ text: `start it on ${r.model}, effort ${r.effort}; its effort is expected to be at most the parent's`, source: 'model-config', verified: false })
103 break
104 case 'subagent':
105 out.push({ text: `Agent call: model: "${r.model}", effort: "${r.effort}", subagent_type: "${agent}"`, source: 'sub-agents', verified: true })
106 out.push({ text: `or agents/${agent}.md frontmatter: model: ${r.model}, effort: ${r.effort}`, source: 'sub-agents', verified: true })
107 break
108 case 'workflow-agent':
109 out.push({ text: `the model a script names for an agent() counts as the per-invocation model: ${r.model}`, source: 'workflows', verified: true })
110 out.push({ text: `agent() opts: { model: '${r.model}' } (option spelling not shown in the docs)`, source: 'workflows', verified: false })
111 out.push({ text: `effort ${r.effort}: no documented agent() option; set it in agents/${agent}.md frontmatter`, source: 'workflows', verified: false })
112 break
113 }
114 return out
115}
116
117const envDefault = (s: Scenario, unit: string) => s.roles.find(r => r.unit === unit)?.model
118
119/** A ready-to-paste snippet of one kind for one scenario. */
120export function snippet(c: Catalog, s: Scenario, kind: Kind): string {
121 const subs = s.roles.filter(r => r.unit === 'subagent')
122 const wfs = s.roles.filter(r => r.unit === 'workflow-agent')
123 switch (kind) {
124 case 'prompt': {
125 const caps = Object.entries(s.caps ?? {}).map(([k, v]) => `${k.replace(/_/g, ' ')} <= ${v}`)
126 return (
127 `Scenario ${s.id} "${s.name}": ` +
128 s.roles.map(r => `${roleName(r)} ${modelLabel(c, r.model)} ${r.effort} as ${unitLabel(c, r.unit)} (max ${r.max_parallel})`).join('; ') +
129 `. Every Agent and Workflow agent() call names its model.` +
130 (s.escalation === false ? ' No effort escalation.' : '') +
131 (caps.length ? ` Caps: ${caps.join(', ')}.` : '')
132 )
133 }
134 case 'agent':
135 if (!subs.length) return `// ${s.id}: no role runs as an Agent subagent`
136 return subs
137 .map(r => `// ${roleName(r)}, up to ${r.max_parallel} at once\nAgent({ description: "<3-5 words>", subagent_type: "${r.agent ?? r.role}", model: "${r.model}", effort: "${r.effort}", prompt: "<task>" })`)
138 .join('\n')
139 case 'workflow': {
140 if (!wfs.length) return `// ${s.id}: no role runs as a Workflow agent`
141 const lines = wfs.map(r => ` ${JSON.stringify(r.role)}: { model: '${r.model}' }, // effort ${r.effort}: agents/${r.agent ?? r.role}.md (agent() effort undocumented); max ${r.max_parallel} at once`)
142 return `// Scenario ${s.id} "${s.name}": opts for each agent() call\nconst ROLE_OPTS = {\n${lines.join('\n')}\n}`
143 }
144 case 'frontmatter': {
145 const files = [...subs, ...wfs]
146 if (!files.length) return `# ${s.id}: no agent roles`
147 return files.map(r => `# agents/${r.agent ?? r.role}.md\n---\nname: ${r.agent ?? r.role}\ndescription: ${roleName(r)}\nmodel: ${r.model}\neffort: ${r.effort}\n---`).join('\n\n')
148 }
149 case 'env': {
150 const env: Record<string, string> = {}
151 const sub = s.defaults?.subagent_model ?? envDefault(s, 'subagent')
152 const wf = s.defaults?.workflow_model ?? envDefault(s, 'workflow-agent')
153 if (sub) env.CLAUDE_CODE_SUBAGENT_MODEL = c.models[sub]?.id ?? sub
154 if (wf) env.CLAUDE_CODE_WORKFLOW_SUBAGENT_MODEL = c.models[wf]?.id ?? wf
155 return (
156 `// ~/.claude/settings.json: the model a call that names none falls back to (after its agent file's model)\n` +
157 (wf ? `// CLAUDE_CODE_WORKFLOW_SUBAGENT_MODEL: non vérifié (not in the workflows docs; workflow agents follow the subagent order)\n` : '') +
158 JSON.stringify({ env }, null, 2)
159 )
160 }
161 }
162}
163
164/** Limits that apply to a scenario: every limit with no unit, and those whose unit a role uses. */
165export function limitsFor(c: Catalog, s: Scenario): Limit[] {
166 const units = new Set(s.roles.map(r => r.unit))
167 return c.limits.filter(l => !l.unit || units.has(l.unit))
168}
169
170/** `/scenarios [id] [kind]`, in either order, case-insensitive. */
171export function parseArgs(args: string, ids: string[]): { id?: string; kind?: Kind } {
172 const out: { id?: string; kind?: Kind } = {}
173 for (const word of args.trim().split(/\s+/).filter(Boolean)) {
174 const low = word.toLowerCase()
175 const kind = KINDS.find(k => k === low)
176 if (kind) out.kind = kind
177 else out.id = ids.find(i => i.toLowerCase() === low) ?? word
178 }
179 return out
180}
181
182/** `~` and `%USERPROFILE%`-free path for a user's file. */
183export const expandHome = (p: string, home: string) => p.replace(/^~(?=[\\/]|$)/, home).replace(/\\/g, '/')
184hooks/apply.ts 104 lines1// « Appliquer ce scénario », pure: the record written to ~/.claude/scenarios/applied.json (the previous one is kept as
2// applied.prev.json by the hook) and the diff between that record and what the agent files and settings say now.
3// Nothing here, and nothing in the hook, edits settings.json, an agent file or an env var: the record is a note for
4// Julian and his agents; the diff says what would have to change by hand.
5import type { Catalog, Role, Scenario } from '../types'
6
7export type AppliedRole = { role: string; label: string; unit: string; agent?: string; model: string; model_id: string; effort: string }
8export type Applied = {
9 schema: 1
10 scenario: string
11 name: string
12 applied_at: string
13 roles: AppliedRole[]
14 env: Record<string, string>
15 note: string
16}
17/** What the files say now: ~/.claude/settings.json (model, effortLevel, env) and the frontmatter of each agent file. */
18export type Current = {
19 settings?: { model?: string; effortLevel?: string; env?: Record<string, string> } | undefined
20 agents: Record<string, { model?: string; effort?: string } | undefined>
21}
22export type DiffLine = { role: string; where: string; field: string; current: string; applied: string; same: boolean }
23
24export const NOTE = 'Note locale : rien de ceci n\'a modifié settings.json, les agents ou l\'environnement.'
25
26const modelId = (c: Catalog, m: string | undefined) => (m ? c.models[m]?.id ?? m : '')
27const roleAgent = (r: Role) => (r.unit === 'subagent' || r.unit === 'workflow-agent' ? r.agent ?? r.role : undefined)
28
29/** The env defaults a scenario implies (same rule as the env snippet). */
30export function envOf(c: Catalog, s: Scenario): Record<string, string> {
31 const env: Record<string, string> = {}
32 const sub = s.defaults?.subagent_model ?? s.roles.find(r => r.unit === 'subagent')?.model
33 const wf = s.defaults?.workflow_model ?? s.roles.find(r => r.unit === 'workflow-agent')?.model
34 if (sub) env.CLAUDE_CODE_SUBAGENT_MODEL = modelId(c, sub)
35 if (wf) env.CLAUDE_CODE_WORKFLOW_SUBAGENT_MODEL = modelId(c, wf)
36 return env
37}
38
39/** The record for one scenario, at ISO time `at`. */
40export function appliedRecord(c: Catalog, s: Scenario, at: string): Applied {
41 return {
42 schema: 1,
43 scenario: s.id,
44 name: s.name,
45 applied_at: at,
46 roles: s.roles.map(r => ({
47 role: r.role, label: r.label ?? r.role, unit: r.unit, ...(roleAgent(r) ? { agent: roleAgent(r) } : {}),
48 model: r.model, model_id: modelId(c, r.model), effort: r.effort,
49 })),
50 env: envOf(c, s),
51 note: NOTE,
52 }
53}
54
55/** `model:` and `effort:` (any `key: value`) of a Markdown file's YAML frontmatter; {} without one. */
56export function frontmatter(md: string | undefined): Record<string, string> {
57 const m = /^?---\r?\n([\s\S]*?)\r?\n---/.exec(md ?? '')
58 const out: Record<string, string> = {}
59 if (!m) return out
60 for (const line of m[1]!.split(/\r?\n/)) {
61 const kv = /^([A-Za-z_][\w-]*)\s*:\s*(.*?)\s*$/.exec(line)
62 if (kv) out[kv[1]!] = kv[2]!.replace(/^["']|["']$/g, '')
63 }
64 return out
65}
66
67/** Same model when both name the same id (alias or full id; a `[1m]` suffix ignored). */
68export const sameModel = (c: Catalog, a: string, b: string) => {
69 const id = (x: string) => modelId(c, x.replace(/\[1m\]$/i, '').trim()).toLowerCase()
70 return id(a) === id(b)
71}
72
73/** One line per role and field (and per env default), current value vs the applied one. */
74export function diffApplied(c: Catalog, a: Applied, cur: Current): DiffLine[] {
75 const out: DiffLine[] = []
76 const push = (role: string, where: string, field: string, current: string | undefined, applied: string, model: boolean) => {
77 const now = current ?? ''
78 out.push({ role, where, field, current: now || '(absent)', applied, same: now !== '' && (model ? sameModel(c, now, applied) : now === applied) })
79 }
80 for (const r of a.roles) {
81 if (r.unit === 'session') {
82 push(r.label, 'settings.json', 'model', cur.settings?.model, r.model, true)
83 push(r.label, 'settings.json', 'effortLevel', cur.settings?.effortLevel, r.effort, false)
84 } else if (r.agent) {
85 const f = cur.agents[r.agent]
86 push(r.label, `agents/${r.agent}.md`, 'model', f?.model, r.model, true)
87 push(r.label, `agents/${r.agent}.md`, 'effort', f?.effort, r.effort, false)
88 } else {
89 out.push({ role: r.label, where: 'au lancement', field: 'model · effort', current: '(fixé à chaque lancement)', applied: `${r.model} · ${r.effort}`, same: true })
90 }
91 }
92 for (const [k, v] of Object.entries(a.env)) push('env', 'settings.json env', k, cur.settings?.env?.[k], v, true)
93 return out
94}
95
96/** Agent file names the diff needs. */
97export const agentsOf = (a: Applied) => [...new Set(a.roles.map(r => r.agent).filter((x): x is string => !!x))]
98
99/** « S1 Standard V6 appliqué le … : 3 écarts sur 14 » */
100export function diffSummary(a: Applied, d: DiffLine[]): string {
101 const n = d.filter(x => !x.same).length
102 return `${a.scenario} ${a.name} noté le ${a.applied_at.replace('T', ' ').slice(0, 16)} : ${n ? `${n} écart${n > 1 ? 's' : ''} sur ${d.length}` : `aucun écart (${d.length} valeurs)`}`
103}
104types/index.d.ts 78 lines1// Shapes of scenarios.json (and of a user's extra scenarios file) and the `$.state` values of the scenarios mod.
2
3export type ModelInfo = { label: string; id: string }
4export type UnitInfo = {
5 label: string
6 /** what to set for a role run as this unit (one line) */
7 how: string
8 /** key into `sources` */
9 source: string
10}
11export type Limit = {
12 id: string
13 text: string
14 /** key into `sources` */
15 source: string
16 /** false: not found in the docs ("non vérifié") */
17 verified: boolean
18 /** with `unit`: the most agents of that unit that run at once */
19 max?: number
20 unit?: string
21}
22export type Role = {
23 role: string
24 label?: string
25 /** alias from `models` (opus, sonnet, haiku) or a full model id */
26 model: string
27 effort: string
28 /** key into `units`: session, sub-conversation, workflow-agent, subagent */
29 unit: string
30 max_parallel: number
31 /** agent file name (subagent_type) for subagent and workflow-agent roles */
32 agent?: string
33 note?: string
34}
35export type Scenario = {
36 id: string
37 name: string
38 summary?: string
39 roles: Role[]
40 /** free caps shown as rules: { "ci_pipelines": 4, "workflows": 1 } */
41 caps?: Record<string, number>
42 /** may a role move up the effort ladder after a failure */
43 escalation?: boolean
44 /** default model for the env vars; else the first role of that unit */
45 defaults?: { subagent_model?: string; workflow_model?: string }
46}
47export type ScenarioFile = {
48 schema?: number
49 sources?: Record<string, string>
50 models?: Record<string, ModelInfo>
51 efforts?: string[]
52 units?: Record<string, UnitInfo>
53 limits?: Limit[]
54 snippets?: string[]
55 scenarios?: Scenario[]
56}
57export type Catalog = Required<Omit<ScenarioFile, 'schema'>>
58export type Checked = { catalog: Catalog; errors: string[]; warnings: string[] }
59
60declare module 'claude-code' {
61 interface PluginState {
62 scenarios: {
63 /** id of the scenario the pane shows */
64 selected: string
65 /** snippet kind the pane shows: prompt, agent, workflow, frontmatter, env */
66 kind: string
67 /** last copy's outcome line */
68 copied: string
69 /** outcome of the last « Appliquer ce scénario » press */
70 applyMsg: string
71 /** pane tab: scenarios or versus (« Claude vs GPT ») */
72 tab: 'scenarios' | 'versus'
73 /** benchmark id the « Claude vs GPT » tab shows ('' = the first one) */
74 bench: string
75 }
76 }
77}
78