SLOPSHOPPER

zebra-mod

Turns Claude Code into a rare-disease research workstation: phenotype-driven diagnosis, variant interpretation (ACMG), sequence-to-function models…

panebandspinnerrowsguardcommand
v0.3.9MITupdated 2026-10-26zwbao/zebra-mod
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · zebra-mod
│ ┃ zebra-board ✕ › fix the failing auth╭────────────────────────────────────────────╮ │ ┃ No active case. /zebra new <dir> [title] │ zebra-mod │ │ ⏺ Read(src/auth.ts) │ 🦓 zebra-mod is ready: just describe │ │ ⎿ Read 6 lines │ symptoms or test results. Type /zebra demo │ │ ⏺ Update(src/auth.ts) │ to try a demo case, /zebra for everything │ │ ⎿ Added 2 lines, re╰────────────────────────────────────────────╯ │ ⏺ 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 │ │ › /zebra │ ⎿ zebra-mod: 🦓 **zebra-mod** · rare-disease research workstation · │ ⎿ zebra-mod: │ ⎿ zebra-mod: **How to use it: just ask.** Describe symptoms, paste │ ⎿ zebra-mod: - My daughter has had seizures with fever since 6 mon │ ⎿ zebra-mod: - What could this be: small head, hearing loss, walke │ ⎿ zebra-mod: - Which treatments are approved for Dravet syndrome, │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · zebra-board
No active case. /zebra new <dir> [title]
README

🦓 zebra-mod

A rare-disease research workstation inside Claude Code

From symptoms to a differential, from a variant to an ACMG class, from a sequence to its function, from a genotype to a therapy — every claim tied to a source you can open.

License: MIT Version Claude Code Python

English · 中文

"When you hear hoofbeats, think horses, not zebras." Medicine is taught to expect the common. People with rare diseases call themselves zebras because their answers lie off the beaten path. zebra-mod is built to look there, and to show its evidence at every step.

zebra-mod is a Claude Code mod for families on a diagnostic odyssey, clinicians, and researchers. It gives Claude 22 tools over live public databases (HPO, Monarch, Orphanet, ClinVar, gnomAD, Ensembl VEP, ClinGen, PanelApp, Open Targets, ClinicalTrials.gov, Europe PMC and more), a case workspace with an evidence ledger, and a set of procedures for diagnosis, variant interpretation, therapy search and reporting. You talk to Claude as usual, in English or Chinese; it reaches for the tools itself.

<a href="docs/media/zebra-mod-promo.mp4"> <img src="docs/media/zebra-mod-promo.gif" alt="zebra-mod in 30 seconds" width="100%"> </a>

Highlights

  • Differential diagnosis from records. Clinic notes, lab sheets and photos become a verified HPO profile; three independent rankers (offline, Monarch, PubCaseFinder) are reported side by side, next to Claude's own clinical reasoning, never instead of it.
  • Variant interpretation with code-computed ACMG points. VEP, gnomAD, ClinVar, ClinGen, SpliceAI, AlphaMissense, REVEL and MaveDB feed the evidence; you justify the codes, zebra does the arithmetic (Tavtigian 2020 points beside the 2015 rules).
  • Beyond SNVs. CNVs and microarray results against ClinGen dosage maps, exon deletions with reading-frame arithmetic, SMN1/SMN2 copy number, repeat expansions (D4Z4, DMPK, FMR1, HTT…) sized by rule.
  • Sequence-to-function, run in the mod. SpliceAI, Pangolin, GPN-MSA, Evo 2 and AlphaGenome, each reported on its own axis with the highest claim it supports, combined by agreement and never averaged.
  • Genotype to therapy, with access. Approved and investigational drugs by mechanism, FDA/EMA status from the agencies' records, approval and reimbursement in China, recruiting trials with sites in China, N-of-1 routes (antisense, base editing).
  • Reports a family can hold. Clinician summaries and plain-language family sheets, audited by an independent subagent, exported to HTML, Word and PDF with Chinese typography.
  • Private by construction. Case files stay on your machine; a privacy gate keeps registered names, birth dates and record numbers out of every outgoing call.

Quick start

1. Install. In Claude Code, say:

Install https://github.com/zwbao/zebra-mod

Claude reads INSTALL.md and does the rest: checks Claude Code (≥ 2.1.289) and Python (≥ 3.9), installs the plugin, fetches the HPO release (~80 MB) and runs a health check. Or from a shell:

curl -fsSL https://raw.githubusercontent.com/zwbao/zebra-mod/main/install.sh | sh

2. Try the demo. Start a new session and type /zebra demo. It opens a synthetic case (a clinic note and a genetic report) with the first question ready; press Enter and watch it read the records, build the differential and interpret the variant.

3. Ask about your own case. No commands to learn:

My daughter started having fever-triggered seizures at 6 months. The genetic report says
SCN1A NM_001165963.4:c.2134C>T. What does it mean, and what should we ask the neurologist?

/zebra shows what the mod can do; /zebra new <folder> starts a case for a patient whose records you want to keep together.

What you can ask

You areFor example
A patient or family"跑了好几家医院都没查出来,这是孩子的检查单,可能是什么病?" · "What does a VUS mean for my son?" · "Are there trials for FSHD in China?" · "Write a one-page list of questions for our next visit."
A clinician"Ranked differential for these HPO terms, and which test finds each candidate." · "ACMG reading of this variant with the segregation in this pedigree." · "Management and surveillance plan for a patient with DM1 and conduction disease." · "Is a catheter angiogram safe in vascular EDS?"
A researcher"Re-analyse this trio VCF with the phenotype." · "SpliceAI, Pangolin and AlphaGenome for this deep-intronic variant." · "Cosegregation likelihood ratio for these meioses." · "Which exon skip restores the frame for a DMD exon 45–50 deletion?"

A full list of what each capability does, tool by tool, is in docs/FEATURES.md.

How it works

you
└─► Claude Code
      ├─ research doctrine (system prompt) · 13 skills · 6 subagents
      └─► zebra-mod hooks
            ├─ privacy gate
            └─► 22 tools (mcp__zebra-mod__*)
                  └─► zebra engine (Python, stdlib only)
                        ├─► public databases and models: HPO · Monarch · ClinVar · gnomAD · VEP · ClinGen …
                        └─► case folder on your machine: case.json · evidence/ledger.jsonl (E1, E2, …) · reports/
  • The engine computes, the model interprets. Rankings, ACMG points, repeat sizes and statistics come from the zebra engine; the model never writes or adjusts a number, and openly overrides a ranking when evidence the ranker cannot see decides the question.
  • Every source is kept. Each tool result is appended to the case's evidence ledger with its database, record and retrieval time; reports cite those sources.
  • Claude's own knowledge is welcome, labelled. What was retrieved this session and what comes from recall are marked apart, so a reader can tell which is which.
  • The mod adds, it never subtracts. Nothing in it is a gate the person must pass before getting an answer: the answer comes first, the case work around it.

The same engine is a command-line tool you can use from any shell, notebook or agent:

zebra phenotype rank --present HP:0002373 HP:0001263 --sources local,monarch,pubcasefinder
zebra acmg suggest NM_001165963.4:c.2134C>T --inheritance AD
zebra acmg classify PVS1 PS2 PM2_Supporting
zebra s2f predict 12-25245350-C-T --models spliceai,pangolin,gpn_msa
zebra vcf triage trio.vcf.gz --proband P --mother M --father F --sex female --hpo-genes
zebra stats maxaf --prevalence 0.0000625 --allelic 0.05 --penetrance 0.9

How well it works

Measured, with the method and confidence intervals in docs/BENCHMARK.md:

  • Phenotype ranking (GA4GH phenopacket-store, 10,374 published cases, split by disease). On held-out cases whose own paper was not used to build the HPO annotations — the fair test for a new patient — the correct disease is in the offline top 10 for 28% and the causal gene for 40%. A ranking is a list of hypotheses, which is why Claude's own differential stands beside it.
  • With vs without the mod (six held-out end-to-end cases written without access to the mod's instructions, 8 runs per arm, graded item by item against guideline ground truth). Pooled, the two arms are level (difference −0.02, 95% CI −0.16 to +0.12): the mod was better on an emergency buried in long records and on a VUS with segregation, worse on two cases. "Never worse" is not yet established, and the benchmark says so.
  • 19 end-to-end evals in evals/ run with claude plugin eval, from a Chinese parent's records to a somatic tumour report that must be read on oncology's terms, not as a rare disease.

Privacy and safety

  • Stays local: case files, records and the evidence ledger are written only on your machine.
  • Never sent by zebra: names, birth dates and record numbers. Database queries carry biology (HPO ids, genes, variants); a privacy gate refuses an outgoing call that contains a registered identifier or an ID-number, phone or email pattern, and asks before a case file or raw genome file leaves the machine.
  • What the gate cannot do: any record you ask Claude to read is sent to the model provider as part of the conversation, as with any file in Claude Code. Redact first if that matters to you.
  • Urgent first: a symptom that needs care today is said first, before any analysis.
  • Research-grade: zebra-mod drafts analyses for a clinician's review. It is not a medical device, does not diagnose or prescribe on its own authority, and does not replace a clinician or genetic counsellor.

Configuration

Options live under /config → zebra-mod (or pluginConfigs in settings):

OptionDefaultWhat it does
doctrineautoFull research rules while a case is open, a short rare-disease-only section otherwise; or always, case, off
privacyGateonThe outgoing-call check described above
interfacefullTool rows, spinner text and the galloping zebra; quiet without animation; off for Claude Code's own drawing
pythonpython3Interpreter for the engine

Optional sequence models (/zebra doctor checks them all):

ModelNeeds
SpliceAI, Pangolin, GPN-MSAnothing
Evo 2NVCF_RUN_KEY (NVIDIA hosted)
AlphaGenomeALPHAGENOME_API_KEY and pip install alphagenome (or ZEBRA_ALPHAGENOME_PYTHON); non-commercial, not for clinical decisions

Documentation

docs/FEATURES.mdEvery capability, tool, skill and subagent
docs/BENCHMARK.mdRanking benchmark and with/without-mod evaluations
docs/DATA-SOURCES.mdEach database and model, its terms and licence
docs/PRD.md · docs/ROADMAP.mdDesign and what comes next
INSTALL.md · CHANGELOG.mdInstallation steps and release notes

Development

hooks/        the mod: tools, doctrine, privacy gate, case board, /zebra   (TypeScript)
skills/       13 procedures, routed by zebra-start
agents/       6 subagents (curators, scouts, evidence auditor)
zebra/        the engine: sources, ACMG, statistics, VCF, S2F, reports    (Python, stdlib only)
evals/        end-to-end cases for `claude plugin eval`
tests/        pytest (offline; live network with ZEBRA_NETWORK_TESTS=1)
python3 -m pytest -q            # engine
claude plugin test .            # mod hooks
claude plugin validate .        # manifest, skills, agents
claude --plugin-dir .           # run this checkout for one session

Issues and pull requests are welcome. A change to the doctrine or a skill should come with a with/without-mod eval run (claude plugin eval --ablation with-without); held-out rubrics in evals/heldout-* are never edited to fit a result.

Data sources and licences

zebra-mod queries public resources live and records where each answer came from; every resource keeps its own terms (docs/DATA-SOURCES.md). Notably: AlphaGenome outputs are non-commercial and not for clinical decision-making, SpliceAI weights are CC BY-NC, and OMIM content is not redistributed.

Citation

@software{zebra_mod,
  author  = {zwbao},
  title   = {zebra-mod: a rare-disease research workstation for Claude Code},
  year    = {2026},
  version = {0.3.9},
  url     = {https://github.com/zwbao/zebra-mod}
}

Acknowledgements

Built on the work of the HPO, Monarch, Orphanet, ClinGen, ClinVar, gnomAD, Ensembl, PanelApp, Open Targets, Europe PMC, PubTator, LitVar and PubCaseFinder teams, and of the authors of SpliceAI, Pangolin, GPN-MSA, Evo 2 and AlphaGenome. The galloping zebra above the prompt is traced from Eadweard Muybridge's The Horse in Motion (1878, public domain).

MIT licence © 2026 zwbao.

Source 7 files
hooks/register.tsx 959 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Board, Ready } from '../types'
5import { DOCTRINE, DOCTRINE_BRIEF, renderDoctrine } from './doctrine'
6import { schemaArgs, TOOLS, toolArgv, type ToolDef } from './tools'
7import { registerUi } from './ui'
8import { guardCheck, invokesZebra, isOutboundShell, outboundText, sendsVariantList, shellWords, uploadedPaths, uploadsGenome } from './privacy'
9
10const PLUGIN = 'zebra-mod'
11const PANE = 'zebra-board'
12const TOOL_PREFIX = `mcp__${PLUGIN}__`
13const MAX_RESULT_CHARS = 60_000
14const MAX_ARTIFACT_SCAN = 200_000
15// The case summary is pinned as a status line only when the mod's own drawing is off: Claude Code
16// draws pinned lines as notices (with a warning sign), and ui.tsx carries the summary in the footer.
17// A case that cannot be read is still pinned: that one is a warning.
18let pinCaseStatus = false
19
20// Tools that never reach the network: they read and write the local case only.
21const LOCAL_TOOLS = new Set(['case_status', 'case_update', 'report_export'])
22// Tools whose answer is a lookup with no side effect, safe to run without asking.
23// tools that can carry text off the machine: what a crashed gate refuses instead of passing
24const OUTBOUND_HINT = /^(?:Bash|WebFetch|WebSearch|Artifact|SendMessage|Agent|mcp__)/
25const READ_ONLY_TOOLS = new Set([
26  'case_status', 'hpo_search', 'phenotype_rank', 'gene_card', 'variant_card', 'disease_card', 'acmg',
27  's2f_predict', 'therapy_landscape', 'trials_search', 'literature_search', 'rare_stats', 'edit_check', 'china_rare',
28  'cnv_interpret', 'access', 'expression', 'aso_screen',
29])
30
31const board = atom({ plugin: 'zebra-mod', key: 'board' } as const, null as Board | null)
32const casePath = atom({ plugin: 'zebra-mod', key: 'casePath' } as const, null as string | null)
33const guard = atom({ plugin: 'zebra-mod', key: 'guard' } as const, [] as string[])
34const ready = atom({ plugin: 'zebra-mod', key: 'ready' } as const, null as Ready | null)
35// zebra tools the person allowed for the rest of this session in zebra's own approval dialog
36const trusted = atom({ plugin: 'zebra-mod', key: 'trusted' } as const, [] as string[])
37// identifiers registered while no case was open: protected for this session, kept only in memory,
38// and added to the next case that is opened or created
39const sessionIds = atom({ plugin: 'zebra-mod', key: 'sessionIds' } as const, [] as string[])
40// 'zh' once the person has written a Chinese prompt (set by ui.tsx at each turn's start)
41const lang = atom({ plugin: 'zebra-mod', key: 'lang' } as const, null as string | null)
42
43type Envelope = {
44  ok: boolean
45  result?: unknown
46  sources?: unknown[]
47  warnings?: string[]
48  ledger?: string[]
49  error?: { type: string; message: string }
50}
51
52export const register: Register = (on, options) => {
53  // first, so its hooks wrap the ones below: what the person sees of zebra-mod at work
54  registerUi(on, options)
55  pinCaseStatus = options.interface === 'off'
56  const python = String(options.python ?? 'python3')
57  const doctrineMode = String(options.doctrine ?? 'auto')
58  const privacyOn = options.privacyGate !== false
59
60  // ------------------------------------------------------------ session
61
62  on('session.start', async ($, e, next) => {
63    const started = await next(e)
64
65    // The tools first: a slow interpreter must not delay the first prompt.
66    for (const def of TOOLS) {
67      await $.tool.register({ name: def.name, description: def.description, inputSchema: def.inputSchema })
68    }
69    await $.command.register({
70      name: 'zebra',
71      description: 'zebra-mod: what it does and how to start — /zebra [demo|new <dir> [title]|case <dir>|board|ledger|doctor|close]',
72      argumentHint: '[demo|new <dir> [title]|case <dir>|board|ledger|doctor|close]',
73    })
74
75    // bin/ on PATH, and the interpreter the tools use, so `zebra` in Bash is the same CLI
76    const path = (await $.env.get('PATH')) ?? ''
77    const bin = `${$.plugin.root}/bin`
78    if (!path.split(':').includes(bin)) await $.env.set('PATH', `${bin}:${path}`)
79    await $.env.set('ZEBRA_PYTHON', python)
80
81    void (async () => {
82      const r = await checkCli($, python)
83      if (!r.version) {
84        $.ui.toast(r.python
85          ? `zebra-mod: ${python} could not run the zebra CLI — run /zebra doctor`
86          : `zebra-mod: ${python} not found; set the plugin's python option (needs Python 3.9+)`)
87      }
88
89      // A case is adopted only when this directory is one or lies inside one, or when it was
90      // the case last used in this directory. A case is never inherited from another project.
91      const held = await read($, casePath)
92      let active: string | null = held
93      if (active === null) {
94        const own = (await caseAt($, e.cwd)) ?? (await enclosingCase($, e.cwd))
95        if (own) active = own
96        else {
97          const remembered = await rememberedFor($, e.cwd)
98          if (remembered && (await caseAt($, remembered))) active = remembered
99          else if (remembered) {
100            $.ui.toast(`zebra-mod: the case remembered here (${remembered}) is gone; /zebra case <dir> to pick one`)
101          }
102        }
103      }
104      if (active) await setCase($, python, active, e.isInteractive)
105      else $.ui.status(undefined)
106
107      // keep the board in step with edits made outside the mod's tools (the CLI in Bash, an editor)
108      let lastSeen = ''
109      $.clock.every(4000, async () => {
110        const now = await read($, casePath)
111        if (!now) return
112        try {
113          const st = await $.fs.stat(`${now}/case.json`)
114          const led = await $.fs.stat(`${now}/evidence/ledger.jsonl`).catch(() => undefined)
115          const stamp = `${st.mtimeMs}:${led?.mtimeMs ?? 0}:${led?.size ?? 0}`
116          if (stamp !== lastSeen) {
117            lastSeen = stamp
118            await refreshBoard($, python)
119          }
120        } catch {
121          // the case folder moved or was deleted: leave the board as it was
122        }
123      })
124    })().catch(() => undefined) // background work: a failure here must not surface as an unhandled rejection
125
126    return started
127  })
128
129  // ------------------------------------------------------------ the doctrine
130
131  on('prompt.compose', async ($, e, next) => {
132    const composed = await next(e)
133    if (doctrineMode === 'off' || e.traits.includes('bare')) return composed
134    const active = await read($, casePath)
135    if (doctrineMode === 'case' && !active) return composed
136    // auto (the default): the full doctrine with a case open; otherwise a short section that
137    // applies only to rare-disease questions, so other work in the same Claude Code is untouched
138    const text = doctrineMode === 'auto' && !active ? DOCTRINE_BRIEF : renderDoctrine(DOCTRINE, active, await read($, board))
139    return {
140      sections: [...composed.sections, { id: 'zebra-mod:doctrine', text, scope: 'session' as const }],
141    }
142  })
143
144  // ------------------------------------------------------------ tools
145
146  on('tool.call', async ($, e, next) => {
147    if (!e.tool.startsWith(TOOL_PREFIX)) return next(e)
148    const def = TOOLS.find(t => `${TOOL_PREFIX}${t.name}` === e.tool)
149    if (!def) return next(e)
150    const input = e as unknown as Record<string, unknown>
151    // A tool this plugin registers is answered here, and nothing beneath this hook runs
152    // the engine's permission chain for it. So the decision is asked for explicitly:
153    // the person's rules, the session's mode and the privacy gate apply to zebra's own
154    // tools exactly as they do to any other tool.
155    const verdict = await $.tool.check({ tool: e.tool, input: schemaArgs(def, input) })
156    if (verdict.decision === 'deny') return { deny: verdict.reason ?? `${def.name} was refused` }
157    if (verdict.decision === 'ask' && !(await approved($, def, verdict))) {
158      return { deny: `${def.name} was not approved` }
159    }
160    if (def.name === 'case_update' && !(await read($, casePath))) {
161      const held = await holdForSession($, input)
162      if (held) return { result: held }
163    }
164    let argv: string[]
165    try {
166      argv = await toolArgv(def, input, await read($, casePath))
167    } catch (err) {
168      return { result: `zebra ${def.name}: ${String(err instanceof Error ? err.message : err)}` }
169    }
170    const got = await runZebra($, python, argv, def.timeoutMs ?? 120_000)
171    if (def.touchesCase) await refreshBoard($, python)
172    return { result: formatEnvelope(def, got) }
173  })
174
175  on('tool.describe', async ($, e, next) => {
176    if (!e.tool.startsWith(TOOL_PREFIX)) return next(e)
177    const def = TOOLS.find(t => `${TOOL_PREFIX}${t.name}` === e.tool)
178    if (!def) return next(e)
179    const described = await next(e)
180    return { ...described, isDeferred: def.deferred === true }
181  })
182
183  // ------------------------------------------------------------ permissions and privacy
184
185  on('tool.check', async ($, e, next) => {
186    const own = e.tool.startsWith(TOOL_PREFIX) ? TOOLS.find(t => `${TOOL_PREFIX}${t.name}` === e.tool) : undefined
187    const isLocalOwn = own !== undefined && LOCAL_TOOLS.has(own.name)
188    const command = e.tool === 'Bash' ? String((e.input as { command?: unknown })?.command ?? '') : ''
189    const isRemoteAgent = e.tool === 'Agent' && (e.input as { isolation?: unknown })?.isolation === 'remote'
190    const outbound =
191      (own !== undefined && !isLocalOwn) ||
192      e.tool === 'WebFetch' ||
193      e.tool === 'WebSearch' ||
194      e.tool === 'Artifact' ||
195      e.tool === 'SendMessage' ||
196      isRemoteAgent ||
197      (e.tool.startsWith('mcp__') && own === undefined) ||
198      (e.tool === 'Bash' && isOutboundShell(command))
199
200    let closedAsk: string | null = null
201    let nameAsk: string | null = null
202    if (privacyOn && outbound) {
203      const active = await read($, casePath)
204      const now = await identifiersNow($, active)
205      // a copy: the session list comes from engine state, which must not be mutated in place
206      const held = { isClosed: now.isClosed, ids: [...now.ids, ...(e.tool === 'Bash' ? await namedCaseIdentifiers($, command, active) : [])] }
207      // An unreadable case.json: the identifiers are unknown. zebra's own tools, the zebra CLI and
208      // anything that touches the case folder are refused; other outbound calls (a WebSearch about
209      // something else) are asked about, after the identifiers last read are still checked below.
210      if (held.isClosed) {
211        if (own !== undefined || (e.tool === 'Bash' && invokesZebra(command)) || (await touchesCase($, active, e.tool, command, e.input))) {
212          return {
213            decision: 'deny' as const,
214            reason: `zebra-mod privacy gate: ${active}/case.json cannot be read, so the protected identifiers are unknown and the gate is closed. Fix or re-create the case file, or /zebra close to work without one.`,
215          }
216        }
217        closedAsk = String(active)
218      }
219      // Scan what actually leaves: a shell command's outbound segments without local paths
220      // or sample names; a published page's text below; anything else as given.
221      const scanned = e.tool === 'Bash' ? { command: outboundText(command) }
222        : e.tool === 'Artifact' ? artifactFields(e.input)
223        : own !== undefined ? schemaArgs(own, (e.input ?? {}) as Record<string, unknown>)
224        : e.input
225      const found = guardCheck(scanned, held.ids)
226      if (found?.level === 'ask') {
227        // a registered two-character Chinese name inside a longer word: often a medical term (张力 in 肌张力);
228        // asked about once the checks below that can refuse have run
229        nameAsk = `zebra-mod privacy gate: this call contains ${found.what}. If it is an ordinary word, confirm; if it names the patient, do not send it.`
230      }
231      const hit = found?.level === 'deny' ? found.what : undefined
232      if (hit && !hit.startsWith('protected identifier') && !active && own === undefined) {
233        // No case is open, so this is not known to be patient work: an email or a phone number
234        // in an ordinary call (a PR body, an API request) is asked about, never refused outright.
235        return {
236          decision: 'ask' as const,
237          reason: `zebra-mod privacy gate: this call would send ${hit} off this machine. If it belongs to a patient, do not send it; if it is yours or public, confirm.`,
238        }
239      }
240      if (hit) {
241        return {
242          decision: 'deny' as const,
243          reason: `zebra-mod privacy gate: this call would send ${hit} off this machine. Query public databases with HPO ids, gene symbols, variants and disease names only.`,
244        }
245      }
246      // a file from the case folder about to be sent somewhere
247      const paths = e.tool === 'Bash' ? uploadedPaths(command) : artifactPaths(e.input)
248      if (paths.length > 0 && active) {
249        const inside = await firstInsideCase($, active, paths, (e.input as { root?: unknown })?.root)
250        if (inside) {
251          return {
252            decision: 'ask' as const,
253            reason: `zebra-mod: this would send ${inside}, a file inside the case folder, off this machine. Its contents are not checked for names or record numbers — confirm only if you have read it and trust the destination.`,
254          }
255        }
256      }
257      if (e.tool === 'Artifact') {
258        const scan = await artifactLeak($, e.input, held.ids)
259        if (scan.ask && !scan.leak) {
260          return {
261            decision: 'ask' as const,
262            reason: `zebra-mod privacy gate: the page about to be published contains ${scan.ask}. If it is an ordinary word, confirm; if it names the patient, do not publish it.`,
263          }
264        }
265        if (scan.leak) {
266          return {
267            decision: 'deny' as const,
268            reason: `zebra-mod privacy gate: the page about to be published contains ${scan.leak}. Publishing puts it on the web.`,
269          }
270        }
271        if (scan.unread.length > 0) {
272          return {
273            decision: 'ask' as const,
274            reason: `zebra-mod: ${scan.unread.join(', ')} could not be read to check for names or record numbers before publishing — confirm only if you have checked it yourself.`,
275          }
276        }
277      }
278      if (e.tool === 'Bash' && uploadsGenome(command)) {
279        return {
280          decision: 'ask' as const,
281          reason: 'zebra-mod: this command may move raw genome data (VCF/BAM/CRAM/FASTQ) to another machine. A genome identifies a person and their relatives — confirm the destination is one you trust.',
282        }
283      }
284      if (e.tool === 'Bash' && sendsVariantList(command)) {
285        return {
286          decision: 'ask' as const,
287          reason: 'zebra-mod: --prefilter myvariant sends every quality-passing variant position in this VCF (often tens of thousands) to myvariant.info. Taken together they are the person\'s genome — confirm, or run triage without the prefilter (only the candidates that survive local filtering go out).',
288        }
289      }
290    }
291
292    if (nameAsk !== null) return { decision: 'ask' as const, reason: nameAsk }
293    if (closedAsk !== null) {
294      return {
295        decision: 'ask' as const,
296        reason: `zebra-mod privacy gate: ${closedAsk}/case.json cannot be read, so this call could not be checked against the case's current protected identifiers (it does not touch the case). If it carries nothing about the patient, confirm. Fix the case file, or /zebra close, to stop this question.`,
297      }
298    }
299
300    // The engine's own decision stands; this only spares the person a prompt for a
301    // read-only lookup, and never overrides a deny, a rule or the mode's own answer.
302    const below = await next(e)
303    const writes = own?.name === 'cnv_interpret' && (e.input as { record?: unknown })?.record === true
304    if (own && !writes && below.decision === 'ask' && below.rule === undefined && READ_ONLY_TOOLS.has(own.name)) {
305      return { decision: 'allow' as const, reason: 'zebra-mod: read-only lookup in public databases and local case files' }
306    }
307    return below
308  }).catch(async ($, e, next) => {
309    if (OUTBOUND_HINT.test(e.tool)) {
310      return { decision: 'deny' as const, reason: `zebra-mod privacy gate could not check this call (${next.error.kind}); it was refused rather than let through unchecked` }
311    }
312    return next(e)
313  })
314
315  // ------------------------------------------------------------ /zebra
316
317  on('command.run', { command: 'zebra' }, async ($, e) => {
318    const words = shellWords(e.args.trim())
319    const verb = words[0] ?? ''
320    const rest = words.slice(1)
321    if (verb === '' || verb === 'help' || verb === 'zh' || verb === 'en') {
322      if ((await read($, ready)) === null) await checkCli($, python)
323      const r = await read($, ready)
324      const active = await read($, casePath)
325      if (active) await $.ui.open({ id: PANE, title: 'zebra · case board' })
326      return { text: helpText(r, active, await guideIsZh($, verb === 'zh' || verb === 'en' ? verb : rest[0])) }
327    }
328    if (verb === 'demo') {
329      // the bundled synthetic case: created (or reopened), made active, the first question put in the prompt box
330      const zh = await guideIsZh($, rest[0])
331      const dirArg = rest.find(w => w !== 'zh' && w !== 'en')
332      const made = await runZebra($, python, [
333        'case', 'demo', ...(dirArg ? [await absolute($, dirArg)] : []), '--lang', zh ? 'zh' : 'en',
334      ])
335      if (!made.ok) return { text: `${zh ? '示例病例没能准备好:' : 'Could not prepare the demo case: '}${made.error?.message ?? 'unknown error'}` }
336      const demo = made.result as DemoResult
337      await setCase($, python, demo.path, e.origin.kind === 'composer')
338      await $.ui.open({ id: PANE, title: 'zebra · case board' })
339      const filled = await $.prompt.fill({ text: demo.first_prompt, mode: 'replace' })
340      return { text: demoText(demo, zh, filled.isFilled) }
341    }
342    if (verb === 'board') {
343      const active = await read($, casePath)
344      if (!active) return { text: 'No active case. /zebra new <dir> [title] creates one; /zebra case <dir> opens one.' }
345      await refreshBoard($, python)
346      const opened = await $.ui.open({ id: PANE, title: 'zebra · case board' })
347      return { text: opened.isPlaced ? 'Case board opened.' : 'Case board waits for a wider terminal.' }
348    }
349    if (verb === 'case') {
350      const arg = rest.join(' ')
351      if (!arg) return { text: `Active case: ${(await read($, casePath)) ?? 'none'}` }
352      const dir = await absolute($, rest.length === 1 ? (rest[0] as string) : arg)
353      if (!(await $.fs.exists(`${dir}/case.json`))) return { text: `No case.json in ${dir}. /zebra new ${arg} creates one.` }
354      await setCase($, python, dir, e.origin.kind === 'composer')
355      await $.ui.open({ id: PANE, title: 'zebra · case board' })
356      return { text: `Active case: ${dir}` }
357    }
358    if (verb === 'new') {
359      const dirArg = rest[0]
360      const title = rest.slice(1).join(' ')
361      if (!dirArg) return { text: 'Usage: /zebra new <dir> [title]   (quote a path or title that contains spaces)' }
362      const dir = await absolute($, dirArg)
363      const lang = (await guideIsZh($, undefined)) ? 'zh' : 'en'
364      const made = await runZebra($, python, ['case', 'init', dir, ...(title ? ['--title', title] : []), '--lang', lang])
365      if (!made.ok) return { text: `Could not create the case: ${made.error?.message ?? 'unknown error'}` }
366      await setCase($, python, dir, e.origin.kind === 'composer')
367      await $.ui.open({ id: PANE, title: 'zebra · case board' })
368      return {
369        text: `Case created at ${dir} (case.json, records/, evidence/, reports/). Put reports and lab results in records/.`,
370        context: [`A new zebra case is active at ${dir}. Next useful step: /zebra-mod:zebra-intake to turn records into an HPO profile.`],
371      }
372    }
373    if (verb === 'close') {
374      await setCase($, python, null, e.origin.kind === 'composer')
375      await $.ui.close({ id: PANE })
376      return { text: 'No active case.' }
377    }
378    if (verb === 'doctor') {
379      const got = await runZebra($, python, ['doctor'], 90_000)
380      return { text: got.ok ? doctorText(got.result) : `zebra doctor failed: ${got.error?.message}` }
381    }
382    if (verb === 'ledger') {
383      const active = await read($, casePath)
384      if (!active) return { text: 'No active case.' }
385      // --tail: the CLI keeps the newest rows and reports the true total (an output trim would keep the oldest)
386      const got = await runZebra($, python, ['case', 'ledger', '--case', active, '--tail', '25'])
387      if (!got.ok) return { text: `Could not read the ledger: ${got.error?.message ?? 'unknown error'}` }
388      const r = (got.result ?? {}) as { total?: number; rows?: Array<Record<string, unknown>> }
389      const rows = r.rows ?? []
390      const tail = rows.map(row => `${row.eid}  ${row.db}  ${row.record ?? ''}  ${row.url ?? ''}`)
391      return { text: rows.length ? `${r.total ?? rows.length} evidence rows (newest ${rows.length}):\n${tail.join('\n')}` : 'The evidence ledger is empty.' }
392    }
393    return { text: `Unknown: /zebra ${verb}. Try /zebra help.` }
394  })
395
396  // ------------------------------------------------------------ the case board
397
398  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
399    const { Box, Text, Button, Markdown } = $.ui.resolve(e)
400    const b = await read($, board)
401    if (!b) {
402      return (
403        <Box flexDirection="column">
404          <Text dimColor>No active case. /zebra new &lt;dir&gt; [title]</Text>
405        </Box>
406      )
407    }
408    return (
409      <Box flexDirection="column">
410        <Text bold>🦓 {b.title}</Text>
411        <Text dimColor>
412          {b.role || 'unspecified'}{b.role_confirmed === false ? ' (not confirmed)' : ''} · {b.evidence_count} evidence rows · {b.identifiers} protected identifiers
413        </Text>
414        <Markdown key="body" text={boardMarkdown(b)} />
415        <Box flexDirection="row" gap={1}>
416          <Button key="refresh" label="Refresh" hotkey="r" onPress={() => refreshBoard($, python)} />
417          <Button key="close" label="Close" role="dismiss" onPress={() => $.ui.close({ id: PANE })} />
418        </Box>
419      </Box>
420    )
421  })
422}
423
424// ------------------------------------------------------------ $-using helpers (top level, as the engine requires)
425
426async function runZebra($: EngineInterface, python: string, args: readonly string[], timeoutMs = 120_000): Promise<Envelope> {
427  const active = await read($, casePath)
428  const env: Record<string, string> = { ZEBRA_DEADLINE_MS: String(Math.max(5_000, timeoutMs - 10_000)) }
429  if (active) env.ZEBRA_CASE = active
430  try {
431    const ran = await $.process.run([python, `${$.plugin.root}/bin/zebra`, '--json', ...args], { env, timeoutMs })
432    if (ran.isStdoutTruncated) {
433      return { ok: false, error: { type: 'OutputTooLarge', message: 'the CLI wrote more than 4 MiB; narrow the query (fewer items, a shorter range)' } }
434    }
435    const out = ran.stdout.trim()
436    if (!out) {
437      // a traceback ends with the exception, so keep the tail, not the head
438      const err = (ran.stderr || `exit ${ran.exitCode}`).trim()
439      return { ok: false, error: { type: 'NoOutput', message: err.slice(-2000) } }
440    }
441    return JSON.parse(out) as Envelope
442  } catch (err) {
443    return { ok: false, error: { type: 'ProcessError', message: String(err).slice(0, 2000) } }
444  }
445}
446
447/** Run the CLI's version check now and record the answer. */
448async function checkCli($: EngineInterface, python: string): Promise<Ready> {
449  let r: Ready
450  try {
451    const v = await $.process.run([python, `${$.plugin.root}/bin/zebra`, '--version'], { timeoutMs: 20_000 })
452    const version = v.exitCode === 0 ? v.stdout.trim() : null
453    r = { python, version, error: version ? null : (v.stderr || 'zebra CLI failed').slice(0, 300) }
454  } catch (err) {
455    r = { python: null, version: null, error: String(err).slice(0, 300) }
456  }
457  await update($, ready, () => r)
458  return r
459}
460
461/**
462 * Ask the person whether a zebra tool may run; no one to ask means no. The engine's permission
463 * dialog only opens for tools it runs itself, so this is an AskUserQuestion. An ask that comes
464 * from the session's mode may be answered once for the session; one a settings rule asks for
465 * (`rule` set) is asked every time, as the person configured.
466 */
467async function approved($: EngineInterface, def: ToolDef, verdict: { reason?: string; rule?: unknown }): Promise<boolean> {
468  const sessionable = verdict.rule === undefined
469  if (sessionable && (await read($, trusted)).includes(def.name)) return true
470  const always = `Allow ${def.name} for this session`
471  const options = sessionable ? ['Allow', always, 'Deny'] : ['Allow', 'Deny']
472  try {
473    const why = verdict.reason ? `${verdict.reason.replace(/[??.。]\s*$/, '')}. ` : ''
474    const answer = await $.ui.ask(`${why}Allow zebra-mod to run ${def.name}?`, options)
475    if (sessionable && answer === always) {
476      await update($, trusted, t => (t.includes(def.name) ? t : [...t, def.name]))
477      return true
478    }
479    return answer === 'Allow'
480  } catch {
481    return false // dismissed, or a headless run with nobody to ask
482  }
483}
484
485/** The case directory at `dir`, or null when it holds no zebra case. */
486async function caseAt($: EngineInterface, dir: string): Promise<string | null> {
487  try {
488    if (!(await $.fs.exists(`${dir}/case.json`))) return null
489    const raw = JSON.parse(await $.fs.read(`${dir}/case.json`)) as { schema?: string }
490    return raw.schema === 'zebra.case/1' ? dir : null
491  } catch {
492    return null
493  }
494}
495
496/** The case folder this directory lies inside (a session started in <case>/records), up to four levels up. */
497async function enclosingCase($: EngineInterface, cwd: string): Promise<string | null> {
498  let dir = cwd.replace(/\/+$/, '')
499  for (let i = 0; i < 4; i++) {
500    const parent = dir.slice(0, dir.lastIndexOf('/'))
501    if (!parent || parent === dir) return null
502    const found = await caseAt($, parent)
503    if (found) return found
504    dir = parent
505  }
506  return null
507}
508
509/** The case last used in this working directory, if any. Cases are never shared between projects. */
510async function rememberedFor($: EngineInterface, cwd: string): Promise<string | null> {
511  const saved = await $.store.get('casesByDir')
512  if (saved && typeof saved === 'object') {
513    const held = (saved as Record<string, unknown>)[cwd]
514    if (typeof held === 'string') return held
515  }
516  return null
517}
518
519async function refreshBoard($: EngineInterface, python: string): Promise<void> {
520  const active = await read($, casePath)
521  if (!active) {
522    await update($, board, () => null)
523    await update($, guard, () => [])
524    $.ui.status(undefined)
525    return
526  }
527  const got = await runZebra($, python, ['case', 'summary', active], 30_000)
528  if (got.ok && got.result) {
529    const b = got.result as Board
530    await update($, board, () => b)
531    $.ui.status(pinCaseStatus ? statusLine(b) : undefined)
532  } else {
533    $.ui.status(`zebra: case ${active} unreadable`)
534  }
535  const held = await identifiersNow($, active)
536  if (!held.isClosed) await update($, guard, () => held.ids)
537}
538
539/**
540 * The case's protected identifiers, read now rather than from the last poll, so a
541 * `zebra case identifiers --add` in the same turn is already in force.
542 * `isClosed` means the file could not be read: the caller must refuse outbound calls.
543 */
544async function identifiersNow($: EngineInterface, active: string | null): Promise<{ ids: string[]; isClosed: boolean }> {
545  const session = await read($, sessionIds)
546  if (!active) return { ids: session, isClosed: false }
547  try {
548    const raw = JSON.parse(await $.fs.read(`${active}/case.json`)) as { privacy?: { identifiers?: unknown } }
549    const listed = raw.privacy?.identifiers
550    if (listed === undefined || listed === null) return { ids: session, isClosed: false }
551    if (!Array.isArray(listed)) return { ids: session, isClosed: true }
552    return { ids: [...session, ...listed.filter((s): s is string => typeof s === 'string' && s.trim().length >= 2)], isClosed: false }
553  } catch {
554    const kept = await read($, guard)
555    return { ids: [...session, ...kept], isClosed: true }
556  }
557}
558
559/**
560 * case_update with no case open. Identifiers are the one thing worth keeping without a case: a
561 * parent pastes a clinic note before any folder exists, and the gate must know the child's name
562 * from that moment. They are held in memory for this session (written nowhere) and added to the
563 * next case opened or created. Anything else in the call needs a case and is reported as not
564 * recorded. Returns the tool's answer, or undefined when the call carries no identifiers.
565 */
566async function holdForSession($: EngineInterface, input: Record<string, unknown>): Promise<string | undefined> {
567  const raw = Array.isArray(input.identifiers) ? input.identifiers : []
568  const values = raw.filter((v): v is string => typeof v === 'string' && v.trim().length >= 2).map(v => v.trim())
569  if (values.length === 0) return undefined
570  const held = await update($, sessionIds, list => [...new Set([...list, ...values])])
571  const other = Object.keys(input).filter(k => k !== 'identifiers' && k !== 'tool' && k !== 'tool_use_id' && input[k] !== undefined)
572  const fields = TOOLS.find(t => t.name === 'case_update')
573  const declared = new Set(Object.keys(((fields?.inputSchema as { properties?: object })?.properties ?? {}) as object))
574  const lost = other.filter(k => declared.has(k))
575  return JSON.stringify({
576    warnings: lost.length ? [`no case is open, so ${lost.join(', ')} ${lost.length === 1 ? 'was' : 'were'} not recorded: /zebra new <dir> starts a case`] : [],
577    result: {
578      identifiers: { protected_for_this_session: held.length },
579      note: 'No case is open: these identifiers are protected for the rest of this session (kept in memory only, never written) and will be added to the next case opened or created.',
580    },
581  })
582}
583
584async function setCase($: EngineInterface, python: string, path: string | null, isInteractive: boolean): Promise<void> {
585  await update($, casePath, () => path)
586  if (isInteractive) {
587    const cwd = await $.session.cwd()
588    const saved = await $.store.get('casesByDir')
589    const map: Record<string, unknown> = saved && typeof saved === 'object' ? { ...(saved as Record<string, unknown>) } : {}
590    if (path) map[cwd] = path
591    else delete map[cwd]
592    await $.store.set('casesByDir', map)
593  }
594  if (path) await $.env.set('ZEBRA_CASE', path)
595  else await $.env.set('ZEBRA_CASE', undefined)
596  if (path) {
597    const pending = await read($, sessionIds)
598    if (pending.length) {
599      const got = await runZebra($, python, ['case', 'apply', path, '--ops', JSON.stringify({ identifiers: pending })], 30_000)
600      if (!got.ok) $.ui.toast(`zebra-mod: the identifiers held for this session could not be added to ${path}: ${got.error?.message ?? 'unknown error'}`)
601    }
602  }
603  await refreshBoard($, python)
604}
605
606/**
607 * Whether an outbound call touches the case folder: names its path, or sends a file from it.
608 * Used when case.json cannot be read, to keep the refusal to what concerns the case.
609 */
610async function touchesCase($: EngineInterface, active: string | null, tool: string, command: string, input: unknown): Promise<boolean> {
611  if (!active) return false
612  const root = active.replace(/\/+$/, '')
613  let text = ''
614  try {
615    text = tool === 'Bash' ? command : JSON.stringify(input ?? {})
616  } catch {
617    return true
618  }
619  if (text.includes(root) || text.includes(root.replace(/^\/Users\/[^/]+|^\/home\/[^/]+/, '~'))) return true
620  const paths = tool === 'Bash' ? uploadedPaths(command) : artifactPaths(input)
621  return paths.length > 0 && (await firstInsideCase($, active, paths, (input as { root?: unknown })?.root)) !== undefined
622}
623
624/** The first of `paths` that lies inside the case folder, resolved through links. */
625async function firstInsideCase($: EngineInterface, active: string, paths: readonly string[], root?: unknown): Promise<string | undefined> {
626  const caseRoot = await $.fs.stat(active, { resolve: true }).catch(() => undefined)
627  const realRoot = caseRoot?.realPath
628  if (realRoot === undefined) return undefined
629  const home = (await $.env.get('HOME')) ?? ''
630  const base = typeof root === 'string' && root ? root.replace(/\/$/, '') : ''
631  for (const p of paths) {
632    let q = p.replace(/^\$HOME(?=\/|$)/, home).replace(/^~(?=\/|$)/, home)
633    if (base && !q.startsWith('/')) q = `${base}/${q}`
634    const stat = await $.fs.stat(q, { resolve: true }).catch(() => undefined)
635    const real = stat?.realPath
636    if (real !== undefined && (real === realRoot || real.startsWith(`${realRoot}/`))) return p
637  }
638  return undefined
639}
640
641function artifactPaths(input: unknown): string[] {
642  const i = (input ?? {}) as { file_path?: unknown; file_paths?: unknown; files?: unknown; root?: unknown }
643  const root = typeof i.root === 'string' && i.root ? i.root.replace(/\/$/, '') : ''
644  const under = (p: string) => (root && !p.startsWith('/') ? `${root}/${p}` : p)
645  const out: string[] = []
646  if (typeof i.file_path === 'string') out.push(i.file_path)
647  if (Array.isArray(i.file_paths)) for (const p of i.file_paths) if (typeof p === 'string') out.push(p)
648  if (Array.isArray(i.files)) {
649    for (const f of i.files) {
650      if (typeof f === 'string') out.push(under(f))
651      else if (f && typeof f === 'object' && typeof (f as { path?: unknown }).path === 'string') out.push(under((f as { path: string }).path))
652    }
653  } else if (i.files && typeof i.files === 'object') {
654    for (const v of Object.values(i.files as Record<string, unknown>)) {
655      if (typeof v === 'string') out.push(under(v))
656      else if (v && typeof v === 'object' && typeof (v as { from?: unknown }).from === 'string') out.push(under((v as { from: string }).from))
657    }
658  }
659  return out
660}
661
662/** The parts of an Artifact call that are published themselves (title, description), not paths. */
663const ARTIFACT_PATH_KEYS = new Set(['file_path', 'file_paths', 'files', 'root', 'out_dir', 'url', 'from_url', 'type_url',
664  'path', 'paths'])
665
666function artifactFields(input: unknown): Record<string, unknown> {
667  const i = (input ?? {}) as Record<string, unknown>
668  const out: Record<string, unknown> = {}
669  for (const [k, v] of Object.entries(i)) if (!ARTIFACT_PATH_KEYS.has(k)) out[k] = v
670  return out
671}
672
673/**
674 * The identifiers of every other case a shell command names with --case: a clinician with several
675 * cases open in turn may query for one while another is active. Unreadable case files add nothing
676 * here (the active case's own unreadable file still closes the gate).
677 */
678async function namedCaseIdentifiers($: EngineInterface, command: string, active: string | null): Promise<string[]> {
679  const words = shellWords(command)
680  const named = new Set<string>()
681  words.forEach((w, i) => {
682    if (w === '--case' && words[i + 1]) named.add(words[i + 1] as string)
683    else if (w.startsWith('--case=')) named.add(w.slice('--case='.length))
684  })
685  if (named.size === 0) return []
686  const home = (await $.env.get('HOME')) ?? ''
687  const out: string[] = []
688  for (const raw of named) {
689    const dir = raw.replace(/^\$HOME(?=\/|$)/, home).replace(/^~(?=\/|$)/, home).replace(/\/+$/, '')
690    if (!dir || dir === active?.replace(/\/+$/, '')) continue
691    try {
692      const data = JSON.parse(await $.fs.read(`${dir}/case.json`)) as { privacy?: { identifiers?: unknown } }
693      const listed = data.privacy?.identifiers
694      if (Array.isArray(listed)) out.push(...listed.filter((x): x is string => typeof x === 'string' && x.trim().length >= 2))
695    } catch {
696      // not a case, or not readable: nothing to add
697    }
698  }
699  return out
700}
701
702/**
703 * What a page about to be published carries: the case's identifiers and the ID/phone/email
704 * patterns, checked in every file it publishes. A file that cannot be read (missing, over the
705 * 4 MiB read limit) is reported as unread, so the caller asks instead of passing it unseen.
706 */
707async function artifactLeak($: EngineInterface, input: unknown, ids: readonly string[]): Promise<{ leak?: string; ask?: string; unread: string[] }> {
708  const unread: string[] = []
709  let ask: string | undefined
710  const root = (input as { root?: unknown })?.root
711  const base = typeof root === 'string' && root ? root.replace(/\/$/, '') : ''
712  for (const p of artifactPaths(input)) {
713    const path = base && !p.startsWith('/') ? `${base}/${p}` : p
714    const text = await $.fs.read(path).catch(() => undefined)
715    if (text === undefined) {
716      unread.push(p)
717      continue
718    }
719    // paragraph by paragraph (tags, entities and soft line breaks folded first): numbers from all
720    // over a page must never join into a record number, but a name split by a line break still counts
721    const chunks = text.split(/\n\s*\n|<\/(?:p|div|li|tr|td|th|h[1-6]|section|table)>|<br\s*\/?>/i)
722      .map(c => c.replace(/\s*\n\s*/g, ' '))
723    const hit = guardCheck(chunks, ids)
724    if (hit?.level === 'deny') return { leak: `${hit.what} (in ${p})`, unread }
725    if (hit && ask === undefined) ask = `${hit.what} (in ${p})`
726  }
727  return { ask, unread }
728}
729
730// ------------------------------------------------------------ text
731
732async function absolute($: EngineInterface, p: string): Promise<string> {
733  const home = (await $.env.get('HOME')) ?? ''
734  const expanded = p === '~' ? home : p.startsWith('~/') ? `${home}/${p.slice(2)}` : p
735  const raw = expanded.startsWith('/') ? expanded : `${await $.session.cwd()}/${expanded}`
736  const parts: string[] = []
737  for (const part of raw.split('/')) {
738    if (part === '' || part === '.') continue
739    if (part === '..') parts.pop()
740    else parts.push(part)
741  }
742  return `/${parts.join('/')}`
743}
744
745function statusLine(b: Board): string {
746  const present = b.phenotypes.filter(p => p.status === 'present').length
747  const lead = b.hypotheses.find(h => h.status === 'confirmed' || h.status === 'leading')
748  return `🦓 ${b.title} · HPO ${present} · variants ${b.variants.length}${lead ? ` · ${lead.status}: ${lead.disease}` : ''} · E${b.evidence_count}`
749}
750
751/** Case text is the person's own; it must not be read as Markdown when the board draws it. */
752function plain(text: string | null | undefined, fallback = ''): string {
753  const t = (text ?? fallback).replace(/[\r\n]+/g, ' ')
754  return t.replace(/[\\`*_[\]<>|#~]/g, m => `\\${m}`)
755}
756
757function boardMarkdown(b: Board): string {
758  const lines: string[] = []
759  const present = b.phenotypes.filter(p => p.status === 'present')
760  const excluded = b.phenotypes.filter(p => p.status === 'excluded')
761  lines.push(`**Phenotypes** (${present.length} present, ${excluded.length} excluded)`)
762  for (const p of present.slice(0, 20)) lines.push(`- ${plain(p.label, p.id)} (${plain(p.id)})`)
763  if (present.length > 20) lines.push(`- … ${present.length - 20} more`)
764  for (const p of excluded.slice(0, 8)) lines.push(`- ${plain(p.label, p.id)} (${plain(p.id)}, absent)`)
765  lines.push('', `**Variants** (${b.variants.length})`)
766  for (const v of b.variants) {
767    lines.push(`- ${plain(v.gene)} ${plain(v.label)} ${plain(v.zygosity)} — ${plain(v.classification, 'unclassified')}`)
768  }
769  lines.push('', `**Hypotheses** (${b.hypotheses.length})`)
770  for (const h of b.hypotheses) lines.push(`- [${plain(h.status)}] ${plain(h.disease)} (+${h.support} / −${h.against})`)
771  if (b.therapy_leads.length) {
772    lines.push('', `**Therapy leads** (${b.therapy_leads.length})`)
773    for (const t of b.therapy_leads) lines.push(`- [${plain(t.kind)}] ${plain(t.name)}${t.status ? ` — ${plain(t.status)}` : ''}`)
774  }
775  if (b.questions.length) {
776    lines.push('', `**Questions for the care team** (${b.questions.length})`)
777    for (const q of b.questions.slice(0, 10)) lines.push(`- ${plain(q)}`)
778  }
779  return lines.join('\n')
780}
781
782type DemoResult = {
783  path: string
784  reused: boolean
785  title: string
786  records: string[]
787  identifiers: number
788  first_prompt: string
789  next_prompts: string[]
790}
791
792/** The session's language: an explicit `zh`/`en`, else the open case's, else the prompts', else LANG. */
793async function guideIsZh($: EngineInterface, asked: string | undefined): Promise<boolean> {
794  if (asked === 'zh') return true
795  if (asked === 'en') return false
796  const b = await read($, board)
797  if (b?.language) return b.language.toLowerCase().startsWith('zh')
798  const l = await read($, lang)
799  if (l) return l === 'zh'
800  const env = (await $.env.get('LC_ALL')) || (await $.env.get('LANG')) || ''
801  return env.toLowerCase().startsWith('zh')
802}
803
804function demoText(d: DemoResult, zh: boolean, isFilled: boolean): string {
805  const next = d.next_prompts.map(q => `- ${q}`).join('\n')
806  if (zh) {
807    return [
808      `🦓 **已打开示例病例**「${d.title}」`,
809      `\`${d.path}\``,
810      '',
811      `- records/ 里有两份合成资料:${d.records.join('、')}。`,
812      `- 其中的姓名、出生日期、电话和病历号已登记为受保护身份信息(${d.identifiers} 项),隐私闸门会拦住带有它们的外发查询。`,
813      isFilled
814        ? '- **第一个问题已经放进输入框,按回车就开始。** 它会整理病历、做鉴别诊断、解读变异;过程中能看到工具行、奔跑的斑马和右侧病例看板的变化。'
815        : `- 把这个问题发给 Claude 就开始:\n\n  ${d.first_prompt}`,
816      '',
817      '之后可以接着问:',
818      next,
819      '',
820      '用你自己的资料:`/zebra new ~/cases/<名字>`,把病历、化验单、基因报告放进它的 records/,再直接提问。',
821    ].join('\n')
822  }
823  return [
824    `🦓 **Demo case open:** ${d.title}`,
825    `\`${d.path}\``,
826    '',
827    `- records/ holds two synthetic files: ${d.records.join(', ')}.`,
828    `- The name, date of birth, phone and record numbers in them are registered as protected identifiers (${d.identifiers}); the privacy gate keeps them out of every outgoing query.`,
829    isFilled
830      ? '- **The first question is in the prompt box: press Enter.** It reads the records, ranks a differential and interprets the variant; you will see its tool rows, the galloping zebra and the case board on the right fill in.'
831      : `- Send Claude this to begin:\n\n  ${d.first_prompt}`,
832    '',
833    'Then try:',
834    next,
835    '',
836    'Your own records: `/zebra new ~/cases/<name>`, put reports, lab sheets and the genetic report in its records/, and ask.',
837  ].join('\n')
838}
839
840/** `/zebra`: what the mod does and how to start, in the person's language. */
841function helpText(r: Ready | null, active: string | null, zh: boolean): string {
842  const version = r?.version ?? (zh ? `未就绪(${r?.error ?? '尚未检查 Python'})` : `not ready (${r?.error ?? 'python not checked'})`)
843  if (zh) {
844    return [
845      `🦓 **zebra-mod** · 罕见病研究工作台 · ${version} · 当前病例:${active ?? '无'}`,
846      '',
847      '**怎么用:直接提问。** 用中文或英文描述症状,贴检查结果或基因报告,Claude 会自己调用 zebra-mod 去查公开数据库、做计算,每个结论都标出处。不需要记命令。例如:',
848      '- 孩子 6 个月开始发热抽搐,基因报告说 SCN1A c.2134C>T,这是什么意思?',
849      '- 这些表现可能是什么病:头围小、听力下降、走路晚,肌张力正常',
850      '- Dravet 综合征现在有哪些获批的药和在招募的临床试验?我们在中国',
851      '',
852      '**先试一下:`/zebra demo`** 打开一个合成示例病例,第一个问题会放进输入框,按回车即可。',
853      '',
854      '**能做什么**',
855      '- 鉴别诊断:病历 → 标准表型(HPO)→ 三个来源分别排序 → 该做哪种基因检测',
856      '- 变异解读:ClinVar、gnomAD、预测分数 → ACMG 证据,分数由程序计算',
857      '- 拷贝数变异、外显子缺失、SMN1 拷贝数、重复扩增;剪接与非编码变异的序列功能预测',
858      '- 治疗与试验:获批药物(含中国获批与医保)、在招募的试验(含中国中心)、反义寡核苷酸与碱基编辑可行性',
859      '- 统计:共分离、再发风险、携带频率;文献检索;在本机重分析 VCF',
860      '- 给家属的说明信、就诊准备单,导出 Word / PDF;隔几个月复查有无新进展',
861      '',
862      '**病例命令**(病例文件只保存在本机)',
863      '`/zebra demo` 示例病例 · `/zebra new <目录> [标题]` 新建 · `/zebra case <目录>` 切换 · `/zebra board` 病例看板 · `/zebra ledger` 证据台账 · `/zebra doctor` 环境自检 · `/zebra close` 关闭病例',
864      '',
865      '隐私:Claude 读到的病历会照常发给模型服务商;zebra-mod 只保证已登记的姓名、证件号、病历号不会出现在它对外的数据库查询里。研究用途,不能代替医生。',
866    ].join('\n')
867  }
868  return [
869    `🦓 **zebra-mod** · rare-disease research workstation · ${version} · active case: ${active ?? 'none'}`,
870    '',
871    '**How to use it: just ask.** Describe symptoms, paste test results or a genetic report, in English or Chinese; Claude calls zebra-mod to query public databases and compute, and cites a source for every claim. No commands to learn. For example:',
872    '- My daughter has had seizures with fever since 6 months; her report says SCN1A c.2134C>T. What does it mean?',
873    '- What could this be: small head, hearing loss, walked late, normal muscle tone',
874    '- Which treatments are approved for Dravet syndrome, and are any trials recruiting?',
875    '',
876    '**Try it first: `/zebra demo`** opens a synthetic demo case and puts the first question in the prompt box; press Enter.',
877    '',
878    '**What it does**',
879    '- Differential diagnosis: records → HPO phenotypes → three rankings kept apart → which test finds each candidate',
880    '- Variant interpretation: ClinVar, gnomAD, predictors → ACMG evidence, points computed by code',
881    '- CNVs, exon deletions, SMN1 copy number, repeat expansions; sequence-to-function for splicing and non-coding variants',
882    '- Therapy and trials: approved drugs (incl. China approval and reimbursement), recruiting trials, antisense and base-editing feasibility',
883    '- Statistics: segregation, recurrence risk, carrier frequency; literature; VCF reanalysis on this machine',
884    '- A family letter and a visit-preparation sheet, exported to Word / PDF; rechecks months later',
885    '',
886    '**Case commands** (case files stay on this machine)',
887    '`/zebra demo` · `/zebra new <dir> [title]` · `/zebra case <dir>` · `/zebra board` · `/zebra ledger` · `/zebra doctor` · `/zebra close`',
888    '',
889    'Privacy: records Claude reads reach the model provider as in any session; zebra-mod keeps registered names and record numbers out of its outgoing database queries. Research-grade, not a substitute for a clinician.',
890  ].join('\n')
891}
892
893function doctorText(result: unknown): string {
894  const r = (result ?? {}) as {
895    checks?: Array<{ name: string; ok: boolean; optional?: boolean; detail?: string }>
896    summary?: { ok?: number; failed?: number; optional_missing?: number }
897  }
898  // ○ marks what zebra works without (research keys, offline data): not a failure
899  const rows = (r.checks ?? []).map(c => `${c.ok ? '✓' : c.optional ? '○' : '✗'} ${c.name}${c.detail ? ` — ${c.detail}` : ''}`)
900  const s = r.summary
901  if (s) rows.push(`${s.ok ?? 0} ok, ${s.failed ?? 0} failed, ${s.optional_missing ?? 0} optional not set up (○)`)
902  return rows.length ? rows.join('\n') : JSON.stringify(result, null, 1)
903}
904
905/** The longest list inside `result`, so a too-large answer loses items rather than its provenance. */
906function trimLongestList(result: unknown): { result: unknown; dropped: number; key: string } | undefined {
907  if (!result || typeof result !== 'object') return undefined
908  let best: { holder: Record<string, unknown>; key: string; list: unknown[] } | undefined
909  const walk = (value: unknown, depth: number): void => {
910    if (depth > 4 || !value || typeof value !== 'object') return
911    for (const [key, v] of Object.entries(value as Record<string, unknown>)) {
912      if (Array.isArray(v) && v.length > 1 && (best === undefined || v.length > best.list.length)) {
913        best = { holder: value as Record<string, unknown>, key, list: v }
914      }
915      walk(v, depth + 1)
916    }
917  }
918  walk(result, 0)
919  if (!best) return undefined
920  const keep = Math.max(1, Math.floor(best.list.length / 2))
921  const dropped = best.list.length - keep
922  best.holder[best.key] = best.list.slice(0, keep)
923  return { result, dropped, key: best.key }
924}
925
926function formatEnvelope(def: ToolDef, got: Envelope): string {
927  if (!got.ok) {
928    return `zebra ${def.name} failed: ${got.error?.type ?? 'error'}: ${got.error?.message ?? 'no message'}`
929  }
930  const warnings = [...(got.warnings ?? [])]
931  // Pair each source with the evidence id the ledger gave it: one claim, one row to cite.
932  const ledger = got.ledger ?? []
933  const sources = (got.sources ?? []).map((src, i) =>
934    ledger.length === (got.sources ?? []).length && src && typeof src === 'object'
935      ? { eid: ledger[i], ...(src as Record<string, unknown>) }
936      : src)
937  // warnings, ledger and sources first: they are what the answer must cite, so a
938  // trim never costs them. The result is trimmed until the whole envelope fits.
939  let body = { warnings, ledger, sources, result: got.result }
940  let text = JSON.stringify(body)
941  for (let i = 0; i < 12 && text.length > MAX_RESULT_CHARS; i++) {
942    const trimmed = trimLongestList(body.result)
943    if (!trimmed) break
944    warnings.push(`zebra-mod trimmed ${trimmed.dropped} of "${trimmed.key}" to fit the tool result; run the same query with the zebra CLI and --json for all of it`)
945    body = { ...body, warnings, result: trimmed.result }
946    text = JSON.stringify(body)
947  }
948  if (text.length > MAX_RESULT_CHARS) {
949    body = {
950      warnings: [...warnings, 'zebra-mod could not fit this result; only its provenance is shown. Run the same query with the zebra CLI and --json.'],
951      ledger: body.ledger,
952      sources: body.sources,
953      result: null,
954    }
955    text = JSON.stringify(body)
956  }
957  return text
958}
959
hooks/doctrine.ts 53 lines
1import type { Board } from '../types'
2
3// The research doctrine zebra-mod adds to the system prompt. Short on purpose:
4// the skills carry the procedures; this carries the rules every answer keeps.
5export const DOCTRINE = `# zebra-mod: rare-disease research mode
6
7This Claude Code has zebra-mod: a rare-disease research workstation for patients and families on a diagnostic odyssey, clinicians and researchers. Its tools (mcp__zebra-mod__*) query live public databases (HPO, Monarch, Orphanet, ClinVar, gnomAD, Ensembl VEP, ClinGen, PanelApp, Open Targets, ClinicalTrials.gov, Europe PMC, PubTator/LitVar, SpliceAI) and run local analyses; every result carries its sources and, with an active case, is written to the case's evidence ledger (ids E1, E2, ...). The skills (/zebra-mod:zebra-start to start) hold the procedures.
8
9Principle: the mod adds, it never subtracts. Its tools, data and case workspace are there to make your answer better than it would be without them, never narrower, slower or more timid. If following a rule below would leave the person with a worse answer than you could give without the mod, the rule is being misapplied: answer the question they asked, with your full clinical and scientific reasoning, and use the tools to check and cite it.
10
11Rules for every answer in this mode:
120. Urgent first. A symptom happening now that needs care today (a seizure past 5 minutes, suspected metabolic decompensation, respiratory or cardiac decline, a stroke-like episode, adrenal crisis) is said first, plainly, with "contact your doctor or go to the emergency department" — before any analysis. Read /zebra-mod:zebra-safety for those, and for the drug, anaesthesia and procedure hazards of specific rare diseases.
131. Evidence, not recall passed off as retrieved. Prefer a tool result or a source fetched in this session for a gene–disease link, a variant's classification or frequency, a prevalence, a drug's approval status, a trial or a paper, and cite it (ledger id, PMID, database record). Your own medical and scientific knowledge is welcome — reasoning, mechanisms, guideline content, what a result means — but say which statements are retrieved and which are from your knowledge (e.g. 已检索 / 凭记忆, "to verify"). Never present recall as a retrieved source, and never synthesize evidence. A number that follows from a rule zebra implements (repeat units from a fragment size, a repeat class, ACMG points, a recurrence or carrier risk in rare_stats) comes from that tool, never from mental arithmetic; any other derived number (a dose per kg, BMI, QTc, a protein target) shows its formula and inputs. A guideline target or threshold names the guideline and the population it applies to.
142. Code scores, you interpret. Phenotype rankings, ACMG points and statistics come from zebra tools; never invent or adjust a number. A ranking is one weak input, not the verdict and not the boundary of the differential (for new patients the correct disease is in the local top 10 about 28% of the time): add the diagnoses your clinical knowledge suggests — gestalt, a treatable disorder that fits, a hallmark finding — labelled as yours, and check them with disease_card; when other evidence decides the question (a diagnostic genetic result, a mechanism the ranker cannot see), say so and override the ranking openly, with the reason.
153. Identifiers are verified, not written from memory: HPO, OMIM, ORPHA, MONDO ids, rsIDs, NCT numbers and PMIDs appear as tools returned them. A variant or result copied verbatim from the person's own report, and a well-known variant name (F508del, m.3243A>G, DMD exon 51), may be used directly. When you know a paper or trial but have not fetched it, name it in words (authors, year, trial name) — never let the missing number keep its content out of the answer.
164. When a tool or source fails or times out, say what failed in one line, then answer from your own knowledge labelled as unverified (未核实 / "not checked this session") and list what to check — never leave the person with only "the search failed".
175. Clarify, never invent. Genome assembly (GRCh38/GRCh37), transcript, zygosity, inheritance, sex and ancestry change conclusions; when one is missing and matters, ask, or state the conclusion as conditional on it. A finding that the records do not mention is unknown — never evidence against a diagnosis.
186. Match the person. A clinician or researcher (the default for someone operating Claude Code on a case, unless they say they are the patient or family) is the care team: give your diagnostic judgment, prognosis, a management plan (surveillance, respiratory, cardiac, rehabilitation, nutrition, trials), drug hazards and acute management directly, and dose ranges as proposals for their review, marked as such; they decide. With a patient or family: a possible diagnosis is something to raise with the care team, not news delivered as fact; no prescription-drug doses, never stopping or starting a prescribed treatment; general ranges for nutrition, exercise and supplements are fine with "confirm with your doctor"; for an established diagnosis, the typical course and its range, labelled as population averages, not a forecast for this person. Classifications are research-grade until an accredited laboratory or clinical geneticist confirms them; a laboratory's own interpretation of its test, and a clinical geneticist's own reading, are such confirmations — a finding the laboratory classifies as pathogenic or diagnostic is a diagnosis, not a hypothesis to re-prove.
197. Sequence-to-function predictions (SpliceAI, AlphaGenome, Evo 2, AlphaMissense) are hypotheses: give model, score and what level they speak to (molecular, cellular); combine independent axes by agreement, never average them into one number.
208. Look beyond the obvious ("think zebras"), and say how strong each lead is: established, emerging, speculative.
219. Privacy: zebra writes case files only on this machine, but what you read (records, reports, this conversation) reaches the model provider as in any Claude Code session — say so if asked. When records name the patient, register the identifiers that point to a person (name in every spelling, date of birth, national ID, phone, address, hospital record/admission numbers) with case_update \`identifiers\` before any outgoing lookup — not every exam or barcode number; the privacy gate then keeps them out of every outgoing call. Never send names, birth dates, record numbers or raw genome files to a web service; query with HPO ids, genes and variants. Do not write them back in replies to a family (address the person as 您 / you); a clinician may refer to their own patient.
2210. Register: with families plain, warm and exact (Chinese by default for Chinese speakers); with clinicians and researchers precise and technical.
2311. Work through the skills, in proportion: zebra-start routes to the procedure for the question (intake, diagnose, variant, reanalysis, s2f, therapy, care, stats, literature, family, report); a wide search goes to the zebra-mod subagents, several in one message. Answer the question that was asked first, from what you have read; creating a case, intake, HPO coding, ledger writes and subagent fan-out support the answer and come after it or alongside it — offered, never a gate the person must pass first. Stay in scope: somatic tumour sequencing, common-disease polygenic risk, pharmacogenomics and prenatal screening are not rare-disease germline questions — answer them on their own terms, not through ACMG germline classification or phenotype ranking. What you hand to people (a plan, a letter, a report) names the underlying sources (PMID, NCT, GeneReviews, a database record), never zebra's machinery (skill or tool names, /zebra commands, ledger ids).`
24
25// What a session without an active case carries under the default `auto` mode: the mod is
26// installed in Claude Code used for everything else too, so it speaks only when asked about
27// a rare disease and never changes how unrelated work is done.
28export const DOCTRINE_BRIEF = `# zebra-mod (installed)
29
30This Claude Code has zebra-mod, a rare-disease research workstation. When — and only when — the person asks about a rare or undiagnosed disease, a patient's records, a genetic test report or variant, or treatment of a rare disease, load /zebra-mod:zebra-start and follow it. Not for somatic tumour reports, common-disease polygenic risk, pharmacogenomics or prenatal screening. The mod adds tools; it never narrows your answer. In short: answer first; a symptom that needs care today comes first; prefer tool results and sources fetched in this session, cite them, and label what comes from your own knowledge — your own diagnoses are welcome next to any ranking, and when a tool fails, answer from knowledge marked unverified; never write HPO/OMIM/ORPHA ids, rsIDs, NCT numbers or PMIDs from memory (name the paper or trial in words instead); with clinicians, full judgment, management and dose-range proposals; with families no prescription doses or diagnosis as fact; never send a patient's name, birth date or record numbers to a web service. For anything else, ignore this section.`
31
32export function renderDoctrine(base: string, active: string | null, board: Board | null): string {
33  if (!active) {
34    return `${base}\n\nNo active case. /zebra new <dir> [title] starts one; without one, tool results are not written to a ledger.`
35  }
36  const lines = [`${base}`, '', `Active case: ${active}${board ? ` — "${board.title}" (role: ${board.role}, language: ${board.language ?? 'not set'})` : ''}.`]
37  if (board) {
38    if (board.role === 'unspecified') {
39      lines.push('Who is asking has not been recorded yet: treat the person operating Claude Code as a clinician or researcher unless they say they are the patient or a relative; ask once if it changes the answer, then record it with case_update profile.role.')
40    } else if (board.role_confirmed === false) {
41      lines.push(`The role "${board.role}" was a default (cases from zebra-mod 0.3.3 and earlier started as family), never set by the person: go by how the person presents themself; ask once if it changes the answer, then record it with case_update profile.role.`)
42    }
43    const present = board.phenotypes.filter(p => p.status === 'present').length
44    lines.push(
45      `It holds ${present} present phenotypes, ${board.variants.length} variants, ${board.hypotheses.length} hypotheses, ${board.tests?.length ?? 0} tests done, ${board.evidence_count} evidence rows. Read it with mcp__zebra-mod__case_status before relying on it; record findings with mcp__zebra-mod__case_update.`,
46    )
47    if (board.identifiers === 0) {
48      lines.push('No protected identifiers are registered for this case: if its records name the patient, register them (case_update identifiers) before any outgoing lookup.')
49    }
50  }
51  return lines.join('\n')
52}
53
hooks/tools.ts 700 lines
1// The tools zebra-mod gives the model. Each one is a thin, typed door onto a
2// `zebra` CLI command (bin/zebra, Python standard library only), so the CLI
3// stays the single implementation: the same answers come back whether the
4// model calls the tool, a skill runs the command in Bash, or a researcher
5// scripts it.
6
7export type ToolDef = {
8  name: string
9  description: string
10  inputSchema: Record<string, unknown>
11  argv: (input: Record<string, unknown>, casePath: string | null) => string[]
12  deferred?: boolean
13  touchesCase?: boolean
14  timeoutMs?: number
15}
16
17const str = (v: unknown): string | undefined => (typeof v === 'string' && v.trim() ? v.trim() : undefined)
18const num = (v: unknown): string | undefined => (typeof v === 'number' && Number.isFinite(v) ? String(v) : undefined)
19const list = (v: unknown): string[] =>
20  Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string' && x.trim() !== '').map(x => x.trim()) : []
21const flag = (name: string, v: string | undefined): string[] => (v === undefined ? [] : [name, v])
22
23// What each statistics method accepts, so a params key cannot smuggle --help or --case.
24const STATS_FLAGS: Record<string, string[]> = {
25  segregation: ['ad-meioses', 'xlr-male-meioses', 'ar-affected-sibs', 'ar-unaffected-sibs', 'nonsegregations',
26    'unaffected-carriers', 'full-penetrance'],
27  maxaf: ['prevalence', 'allelic', 'genetic', 'penetrance', 'inheritance', 'an', 'faf95'],
28  carrier: ['prevalence', 'allele-freqs'],
29  recurrence: ['mode', 'penetrance', 'mosaic', 'prior', 'unaffected-sons', 'affected-sons'],
30  fisher: ['a', 'b', 'c', 'd'],
31  burden: ['case-carriers', 'case-n', 'control-carriers', 'control-n'],
32  denovo: ['observed', 'trios', 'mu'],
33  km: ['csv', 'time-col', 'event-col', 'group-col', 'event-coding'],
34  nof1: ['effect', 'sd-diff', 'alpha', 'power', 'treatment', 'control'],
35}
36
37const HPO = { type: 'string', pattern: '^HP:\\d{7}$' }
38const ASSEMBLY = { type: 'string', enum: ['GRCh38', 'GRCh37'], description: 'Genome build of genomic coordinates; ask when unknown.' }
39
40export const TOOLS: ToolDef[] = [
41  {
42    name: 'case_status',
43    description:
44      'Read the active zebra case: phenotypes (HPO), variants, hypotheses, therapy leads, open questions and how many evidence rows back them. Call before relying on what the case holds.',
45    inputSchema: { type: 'object', properties: {} },
46    argv: (_i, casePath) => {
47      if (!casePath) throw new Error('no active case (the person can run /zebra new <dir> or /zebra case <dir>)')
48      return ['case', 'summary', casePath]
49    },
50  },
51  {
52    name: 'case_update',
53    description:
54      'Record findings in the active case, several kinds in one call. identifiers FIRST when records name the patient (every spelling of the name, date of birth, record/ID numbers): the privacy gate then keeps them out of every outgoing call. Phenotype ids come from hpo_search; variants of every kind with the laboratory\'s interpretation verbatim; a hypothesis is confirmed when a lab result establishes it; ACMG classes are computed by zebra from your codes. Field notes below.',
55    inputSchema: {
56      type: 'object',
57      properties: {
58        profile: {
59          type: 'object',
60          description: 'who is asking and proband basics (no names or birth dates)',
61          properties: {
62            title: { type: 'string' },
63            role: { type: 'string', enum: ['family', 'patient', 'clinician', 'researcher'], description: 'from what the person says about themselves, never from their language; someone operating Claude Code on a case is clinician/researcher unless they say otherwise' },
64            language: { type: 'string', description: 'zh or en' },
65            sex: { type: 'string', enum: ['female', 'male', 'unknown'] },
66            age: { type: 'string', description: 'age or age band, e.g. "2y11m"' },
67            ancestry: { type: 'string' },
68            consanguinity: { type: 'boolean' },
69          },
70        },
71        phenotypes: {
72          type: 'array',
73          items: {
74            type: 'object',
75            properties: {
76              id: HPO,
77              status: { type: 'string', enum: ['present', 'excluded'] },
78              onset: { type: 'string' },
79              source: { type: 'string', description: 'where it is documented, e.g. records/neuro-2023.pdf p2' },
80              note: { type: 'string' },
81            },
82            required: ['id'],
83          },
84        },
85        variants: {
86          type: 'array',
87          items: {
88            type: 'object',
89            properties: {
90              gene: { type: 'string' },
91              hgvs_c: { type: 'string', description: 'with transcript, e.g. NM_001165963.4:c.2134C>T' },
92              hgvs_g: { type: 'string' },
93              hgvs_p: { type: 'string' },
94              vcf: { type: 'string', description: 'chrom-pos-ref-alt, e.g. 2-166001-C-T' },
95              assembly: ASSEMBLY,
96              zygosity: { type: 'string', enum: ['het', 'hom', 'hemi', 'mosaic', 'unknown'] },
97              inheritance: { type: 'string', enum: ['de_novo', 'maternal', 'paternal', 'biparental', 'unknown'] },
98              classification_lab: { type: 'string', description: 'as written on the lab report' },
99              source: { type: 'string' },
100              description: { type: 'string' },
101              kind: {
102                type: 'string',
103                enum: ['small', 'cnv', 'exon_cnv', 'copy_number', 'repeat_expansion', 'repeat_contraction', 'methylation'],
104                description: 'small (default): SNV/indel; cnv: CMA/CNV-seq; exon_cnv: exon-level del/dup; copy_number: SMN1-type dosage; repeat_contraction: e.g. FSHD1 D4Z4 (fragment_kb, haplotype); methylation (methylation_pct, locus). A sized fragment or a methylation result is a finding to record, never "no variant".',
105              },
106              region: { type: 'string', description: 'cnv: chr15:23123715-28193120' },
107              iscn: { type: 'string', description: 'cnv: the ISCN string as reported, e.g. arr[GRCh38] 22q11.21(18648855_21800471)x1' },
108              cnv_type: { type: 'string', enum: ['loss', 'gain'] },
109              copy_number: { type: 'number', description: 'copies reported (SMN1 exon 7 = 0, 1, 2 …)' },
110              exons: { type: 'string', description: 'exon_cnv: 45-50, or a single exon number' },
111              genes: { type: 'array', items: { type: 'string' }, description: 'genes the finding covers, as a tool returned them' },
112              motif: { type: 'string', description: 'repeat: the repeat unit, e.g. CGG' },
113              repeat_count: { type: 'number', description: 'repeat: the number of units reported' },
114              method: { type: 'string', description: 'CMA, MLPA, repeat-primed PCR, PFGE/Southern, bisulfite sequencing …' },
115              locus: { type: 'string', description: 'a named locus when there are no coordinates: 4q35 D4Z4, D4Z4/PAS, an imprinting centre' },
116              fragment_kb: { type: 'number', description: 'repeat_contraction: fragment size in kb as reported (e.g. EcoRI/p13E-11 17.0)' },
117              haplotype: { type: 'string', description: 'repeat_contraction: haplotype as reported, e.g. 4qA' },
118              methylation_pct: { type: 'number', description: 'methylation: the percentage reported (reference range in note)' },
119              lab_interpretation: { type: 'string', description: "the laboratory's own conclusion, verbatim (e.g. 符合 FSHD1 的诊断). When it establishes a diagnosis, also record a hypothesis citing this finding's id." },
120            },
121          },
122        },
123        hypotheses: {
124          type: 'array',
125          items: {
126            type: 'object',
127            properties: {
128              disease: { type: 'string' },
129              status: { type: 'string', enum: ['leading', 'considered', 'excluded', 'confirmed'] },
130              ids: { type: 'array', items: { type: 'string' }, description: 'ORPHA:33069, OMIM:607208, MONDO:0100135 as tools returned them' },
131              support: { type: 'array', items: { type: 'string' }, description: 'ledger ids (E4), case item ids (v1 a genetic finding, x2 a test, f1 a relative), or short reasons in words' },
132              against: { type: 'array', items: { type: 'string' }, description: 'the same kinds; only what argues against (a documented absent hallmark, incompatible inheritance, a negative decisive test) — never "not documented"' },
133              note: { type: 'string' },
134            },
135            required: ['disease'],
136          },
137        },
138        leads: {
139          type: 'array',
140          items: {
141            type: 'object',
142            properties: {
143              name: { type: 'string' },
144              kind: { type: 'string', enum: ['approved', 'trial', 'repurposing', 'n-of-1', 'supportive', 'other'] },
145              status: { type: 'string' },
146              evidence: { type: 'array', items: { type: 'string' } },
147              note: { type: 'string' },
148            },
149            required: ['name', 'kind'],
150          },
151        },
152        acmg: {
153          type: 'array',
154          description: 'research-grade ACMG reading of a recorded variant: your justified codes; zebra classifies',
155          items: {
156            type: 'object',
157            properties: {
158              variant_id: { type: 'string', description: 'v1, v2 ... as case_status lists them' },
159              codes: { type: 'array', items: { type: 'string' } },
160              note: { type: 'string' },
161            },
162            required: ['variant_id', 'codes'],
163          },
164        },
165        questions: { type: 'array', items: { type: 'string' } },
166        identifiers: {
167          type: 'array',
168          items: { type: 'string' },
169          description: 'protected identifiers to add; never shown back',
170        },
171        tests: {
172          type: 'array',
173          description: 'tests already done and their reported result',
174          items: {
175            type: 'object',
176            properties: {
177              type: { type: 'string', description: 'CMA, panel, trio exome, genome, MLPA, repeat sizing, metabolic screen, MRI, EEG…' },
178              date: { type: 'string' },
179              result: { type: 'string', description: 'as reported, e.g. "normal", "VUS SCN1A c.…", "arr[GRCh38] 22q11.21(…)x1"' },
180              lab: { type: 'string' },
181              method: { type: 'string' },
182              source: { type: 'string', description: 'which record file it came from' },
183              note: { type: 'string' },
184            },
185            required: ['type'],
186          },
187        },
188        family: {
189          type: 'array',
190          description: 'relatives as the records describe them; never names',
191          items: {
192            type: 'object',
193            properties: {
194              relation: { type: 'string', enum: ['mother', 'father', 'sibling', 'brother', 'sister', 'half-sibling', 'child', 'son', 'daughter', 'maternal grandmother', 'maternal grandfather', 'paternal grandmother', 'paternal grandfather', 'maternal aunt', 'maternal uncle', 'paternal aunt', 'paternal uncle', 'cousin', 'twin', 'other'] },
195              sex: { type: 'string' },
196              affected: { type: ['boolean', 'string'], description: 'true, false or "unknown"' },
197              status: { type: 'string', description: 'alive, deceased, …' },
198              genotype: { type: 'string', description: 'e.g. "het for v1", "not carrier of v1", "not tested"' },
199              age: { type: 'string' },
200              note: { type: 'string' },
201              source: { type: 'string' },
202            },
203          },
204        },
205        timeline: {
206          type: 'array',
207          items: {
208            type: 'object',
209            properties: { date: { type: 'string' }, event: { type: 'string' }, source: { type: 'string' } },
210            required: ['event'],
211          },
212        },
213        remove: {
214          type: 'array',
215          items: {
216            type: 'object',
217            properties: {
218              kind: { type: 'string', enum: ['phenotype', 'variant', 'hypothesis', 'lead', 'test', 'relative'] },
219              id: { type: 'string' },
220            },
221            required: ['kind', 'id'],
222          },
223        },
224      },
225    },
226    argv: (input, casePath) => {
227      if (!casePath) throw new Error('no active case (the person can run /zebra new <dir> or /zebra case <dir>)')
228      return ['case', 'apply', casePath, '--ops', JSON.stringify(input)]
229    },
230    touchesCase: true,
231  },
232  {
233    name: 'hpo_search',
234    description:
235      'Find Human Phenotype Ontology terms for a clinical phrase. Chinese: official Chinese labels once the HPO release is fetched, and the lay phrases families use (走路晚, 抽风, 不会说话, 发热惊厥, 头围小, 听力下降) with or without it — also inside a short sentence ("孩子走路晚"); a negation (无明显抽搐) is not read as the feature and is warned about. English works either way. Returns verified ids with the label, the Chinese label where there is one, and what matched (label, synonym or lay phrase). Use it for every phenotype before recording one.',
236    inputSchema: {
237      type: 'object',
238      properties: { text: { type: 'string' }, limit: { type: 'number', default: 8 } },
239      required: ['text'],
240    },
241    argv: i => ['hpo', 'search', str(i.text) ?? '', ...flag('--limit', num(i.limit))],
242  },
243  {
244    name: 'phenotype_rank',
245    description:
246      'Phenotype-driven differential diagnosis: rank diseases and genes for a set of HPO terms (present, and excluded). Sources: local (offline Resnik best-match over HPO annotations), monarch (Monarch semantic similarity), pubcasefinder (PubCaseFinder). Each source ranks on its own; agreement across them is the signal. Excluded terms are checked against each disease and listed in `excluded_hits` (a disease that usually has a feature the patient lacks) but do not lower the local score — on the phenopacket-store benchmark that ranked better (docs/BENCHMARK.md); read the hits and weigh them yourself, or set excluded_weight 1 for the 0.1.0 penalty. Ties at the top are reported. from_case uses the active case\'s phenotypes. The ranking is one weak input, not the differential: for a new patient (held-out cases whose own paper is not an HPO annotation source) the correct disease is in the local top 10 for only 28% (70% across all held-out cases, an upper bound), and in docs/BENCHMARK.md local alone did better than a consensus of sources. Add the candidates your clinical knowledge suggests (a mechanism, a hallmark, a test result the ranker cannot see) and check each with disease_card.',
247    inputSchema: {
248      type: 'object',
249      properties: {
250        present: { type: 'array', items: HPO },
251        excluded: { type: 'array', items: HPO },
252        from_case: { type: 'boolean' },
253        sources: { type: 'array', items: { type: 'string', enum: ['local', 'monarch', 'pubcasefinder'] } },
254        top: { type: 'number', default: 15 },
255        local_method: { type: 'string', enum: ['resnik', 'lr'], description: 'local scoring (default resnik)' },
256        excluded_weight: { type: 'number', description: 'local penalty for excluded terms present in a disease: 0 (default, flagged only) to 10; 1 = zebra 0.1.0' },
257      },
258    },
259    argv: i => {
260      const out = ['phenotype', 'rank']
261      const present = list(i.present)
262      const excluded = list(i.excluded)
263      if (present.length) out.push('--present', ...present)
264      if (excluded.length) out.push('--exclude', ...excluded)
265      if (i.from_case === true) out.push('--from-case')
266      const sources = list(i.sources)
267      if (sources.length) out.push('--sources', sources.join(','))
268      return [...out, ...flag('--top', num(i.top)), ...flag('--local-method', str(i.local_method)),
269        ...flag('--excluded-weight', num(i.excluded_weight))]
270    },
271    timeoutMs: 180_000,
272  },
273  {
274    name: 'gene_card',
275    description:
276      'Everything that matters about one gene for rare disease: HGNC identity (aliases resolved), causal disease associations with inheritance (Monarch: OMIM and ClinGen), ClinGen gene–disease validity classes and dosage sensitivity (haploinsufficiency / triplosensitivity), gnomAD constraint (pLI, LOEUF, missense Z), PanelApp (England and Australia) panels with confidence, protein function (UniProt) and AlphaFold model. Use symbols as HGNC spells them.',
277    inputSchema: { type: 'object', properties: { symbol: { type: 'string' } }, required: ['symbol'] },
278    argv: i => ['gene', str(i.symbol) ?? ''],
279  },
280  {
281    name: 'variant_card',
282    description:
283      'Annotate one variant: normalized forms (HGVS, GRCh38/37 coordinates), consequence on the MANE transcript (Ensembl VEP), population frequency (gnomAD, by genetic ancestry group, with filtering AF), ClinVar classification with review status, in-silico predictors (REVEL, AlphaMissense, CADD, SpliceAI where available) and literature mentions (LitVar). Input: HGVS with transcript (NM_...:c.), rsID, or chrom-pos-ref-alt with assembly.',
284    inputSchema: {
285      type: 'object',
286      properties: {
287        variant: { type: 'string', description: 'HGVS, chrom-pos-ref-alt, rsID, or an mtDNA change such as "m.3243A>G 35%"' },
288        assembly: ASSEMBLY,
289        gene: { type: 'string' },
290        heteroplasmy: { type: 'number', description: 'mtDNA only: the reported heteroplasmy, in percent' },
291      },
292      required: ['variant'],
293    },
294    argv: i => [
295      'variant', str(i.variant) ?? '', ...flag('--assembly', str(i.assembly)), ...flag('--gene', str(i.gene)),
296      ...flag('--heteroplasmy', num(i.heteroplasmy)),
297    ],
298    timeoutMs: 180_000,
299  },
300  {
301    name: 'disease_card',
302    description:
303      'One rare disease: identifiers across ORPHA, OMIM, MONDO, ICD; definition, prevalence, inheritance, age of onset, associated genes (Orphanet / Monarch), GeneReviews chapter, whether it is on China\'s national rare disease lists. Input: a name or an id (ORPHA:33069, OMIM:607208, MONDO:0100135).',
304    inputSchema: { type: 'object', properties: { query: { type: 'string' } }, required: ['query'] },
305    argv: i => ['disease', str(i.query) ?? ''],
306    timeoutMs: 180_000,
307  },
308  {
309    name: 'acmg',
310    description:
311      'ACMG/AMP classification arithmetic. classify: give the evidence codes you have justified (e.g. PVS1, PS2, PM2_Supporting, PP3_Strong, BS1) and get the points (Tavtigian 2020) and the 2015 combining-rule class, with rule warnings. suggest: for a variant, the codes that follow from numbers alone (frequency, REVEL, SpliceAI) with their ClinGen thresholds — judgement codes (PVS1, PS3, PM3, PP1, PS4...) stay yours to justify.',
312    inputSchema: {
313      type: 'object',
314      properties: {
315        mode: { type: 'string', enum: ['classify', 'suggest'] },
316        codes: { type: 'array', items: { type: 'string' } },
317        variant: { type: 'string' },
318        assembly: ASSEMBLY,
319        inheritance: { type: 'string', enum: ['AD', 'AR', 'XLD', 'XLR', 'unknown'] },
320        prevalence: { type: 'number', description: 'suggest: disease prevalence (e.g. 0.0001) for the Whiffin maximum credible AF behind BS1' },
321        allelic: { type: 'number', description: 'suggest: maximum allelic contribution of one variant (0-1]' },
322        genetic: { type: 'number', description: 'suggest: maximum genetic contribution of this gene (0-1]' },
323        penetrance: { type: 'number', description: 'suggest: penetrance (0-1]' },
324        inheritance_mode: { type: 'string', enum: ['monoallelic', 'biallelic'], description: 'suggest: only for XLR, XLD or unknown inheritance; AD/AR choose it themselves' },
325        pm2_max_af: { type: 'number', description: 'suggest: a gene-specific PM2 ceiling from a ClinGen VCEP' },
326        heteroplasmy: { type: 'number', description: 'suggest, mtDNA: heteroplasmy in percent' },
327        no_splice_lookup: { type: 'boolean', description: 'suggest: skip the SpliceAI/Pangolin lookup (±4,999 nt) and use VEP\'s precomputed SpliceAI' },
328      },
329      required: ['mode'],
330    },
331    argv: i => {
332      if (i.mode === 'suggest') {
333        return [
334          'acmg', 'suggest', str(i.variant) ?? '', ...flag('--assembly', str(i.assembly)), ...flag('--inheritance', str(i.inheritance)),
335          ...flag('--prevalence', num(i.prevalence)), ...flag('--allelic', num(i.allelic)), ...flag('--genetic', num(i.genetic)),
336          ...flag('--penetrance', num(i.penetrance)), ...flag('--inheritance-mode', str(i.inheritance_mode)),
337          ...flag('--pm2-max-af', num(i.pm2_max_af)), ...flag('--heteroplasmy', num(i.heteroplasmy)),
338          ...(i.no_splice_lookup === true ? ['--no-splice-lookup'] : []),
339        ]
340      }
341      return ['acmg', 'classify', ...list(i.codes)]
342    },
343    timeoutMs: 240_000,
344    deferred: true,
345  },
346  {
347    name: 's2f_predict',
348    description:
349      'Sequence-to-function predictions for one variant, each model reported separately with its claim ceiling (never averaged): spliceai and pangolin (Broad lookup service; GRCh38 and GRCh37) — the default; gpn_msa (conservation from the published hg38 table, SNVs, no key, ~30 s; in the default set for hg38 SNVs); and, with their keys, alphagenome (expression/splicing/chromatin in one tissue: needs ontology, e.g. UBERON:0000955 brain; 1–3 min) and evo2 (zero-shot likelihood; ~1 min, up to 10 when queued). A model that cannot run is not_run with the reason. Use for splice-region, deep intronic, UTR, promoter and other non-coding variants, and to test a mechanism.',
350    inputSchema: {
351      type: 'object',
352      properties: {
353        variant: { type: 'string', description: 'chrom-pos-ref-alt, transcript HGVS or rsID' },
354        assembly: ASSEMBLY,
355        models: { type: 'array', items: { type: 'string', enum: ['spliceai', 'pangolin', 'gpn_msa', 'alphagenome', 'evo2'] }, description: 'default spliceai + pangolin' },
356        ontology: { type: 'string', description: 'tissue/cell CURIE for alphagenome (UBERON:/CL:), chosen for the disease' },
357        distance: { type: 'number', description: 'SpliceAI window around the variant (default 500)' },
358        timeout: { type: 'number', description: 'seconds per s2f model run (default 540)' },
359      },
360      required: ['variant'],
361    },
362    argv: i => {
363      const models = list(i.models)
364      return [
365        's2f', 'predict', str(i.variant) ?? '',
366        ...flag('--assembly', str(i.assembly)),
367        '--models', (models.length ? models : ['spliceai', 'pangolin']).join(','),
368        ...flag('--ontology', str(i.ontology)),
369        ...flag('--distance', num(i.distance)),
370        ...flag('--timeout', num(i.timeout) ?? '540'),
371      ]
372    },
373    timeoutMs: 600_000,
374    deferred: true,
375  },
376  {
377    name: 'therapy_landscape',
378    description:
379      'Therapy landscape for a disease or gene (data only, no judgement): approved and investigational drugs and clinical candidates with stage and mechanism (Open Targets / ChEMBL), target tractability for a gene, and EU orphan designations (EMA; US designations are not checked). Input: a disease name or MONDO/EFO id, or a gene symbol (OMIM:/ORPHA: ids are not accepted — use the name). Mechanism fit and N-of-1 routes are for the zebra-therapy skill to judge.',
380    inputSchema: { type: 'object', properties: { query: { type: 'string', description: 'disease name or MONDO/EFO id, or gene symbol' } }, required: ['query'] },
381    argv: i => ['therapy', str(i.query) ?? ''],
382    timeoutMs: 180_000,
383    deferred: true,
384  },
385  {
386    name: 'trials_search',
387    description:
388      'Clinical trials from ClinicalTrials.gov (v2 API): by condition and optionally a keyword (gene, drug, modality), country and status (default RECRUITING; ANY for all). With a country, only trials with a site there are returned, and those sites are listed. Returns NCT ids, phase, status, interventions, ages, eligibility criteria, contacts, sites and URL, and flags a trial whose status looks stale or inconsistent. ChiCTR (the Chinese registry) is not covered: for China, say so and point to it. Before saying there are no trials, look in result.filtered (trials whose conditions do not name this disease — basket, gene-level and modality trials land there) and search again with status ANY or NOT_YET_RECRUITING / ACTIVE_NOT_RECRUITING, and with the gene as term.',
389    inputSchema: {
390      type: 'object',
391      properties: {
392        condition: { type: 'string' },
393        term: { type: 'string', description: 'extra keyword: gene, drug, modality' },
394        country: { type: 'string', description: 'e.g. China, United States; only trials with a site there, and those sites are listed' },
395        full_eligibility: { type: 'boolean', description: 'the whole eligibility text instead of its first 600 characters' },
396        keep_unrelated: { type: 'boolean', description: 'keep trials whose conditions do not name this disease (normally moved to result.filtered)' },
397        status: { type: 'string', enum: ['RECRUITING', 'NOT_YET_RECRUITING', 'ACTIVE_NOT_RECRUITING', 'COMPLETED', 'ANY'] },
398        limit: { type: 'number', default: 20 },
399      },
400      required: ['condition'],
401    },
402    argv: i => [
403      'trials', str(i.condition) ?? '',
404      ...flag('--term', str(i.term)), ...flag('--country', str(i.country)), ...flag('--status', str(i.status)),
405      ...(i.full_eligibility === true ? ['--full-eligibility'] : []), ...flag('--limit', num(i.limit)),
406      ...(i.keep_unrelated === true ? ['--keep-unrelated'] : []),
407    ],
408    deferred: true,
409  },
410  {
411    name: 'literature_search',
412    description:
413      'Search the literature (Europe PMC; with gene/variant, PubTator3 and LitVar for papers that mention them). Returns PMIDs, titles, years, journals and open-access links; read a paper before citing what it says.',
414    inputSchema: {
415      type: 'object',
416      properties: {
417        query: { type: 'string' },
418        gene: { type: 'string' },
419        variant: { type: 'string', description: 'rsID or HGVS protein/cDNA change' },
420        sort: { type: 'string', enum: ['relevance', 'date', 'cited'] },
421        abstract: { type: 'array', items: { type: 'string' }, description: 'PMIDs whose abstracts to return' },
422        limit: { type: 'number', default: 15 },
423      },
424    },
425    argv: i => [
426      'lit', ...(str(i.query) ? [str(i.query) as string] : []),
427      ...flag('--gene', str(i.gene)), ...flag('--variant', str(i.variant)), ...flag('--sort', str(i.sort)),
428      ...(list(i.abstract).length ? ['--abstract', ...list(i.abstract)] : []), ...flag('--limit', num(i.limit)),
429    ],
430  },
431  {
432    name: 'rare_stats',
433    description:
434      'Classical statistics for rare-disease genetics (no network): segregation (cosegregation LR and PP1 strength), maxaf (Whiffin maximum credible allele frequency), carrier (Hardy–Weinberg carrier frequency from prevalence or allele frequencies), recurrence, fisher, burden (case/control collapsing test), denovo (de novo enrichment, Poisson), km (Kaplan–Meier from a CSV), nof1 (N-of-1 trial design or analysis). params are the CLI flags of `zebra stats <method>` without dashes.',
435    inputSchema: {
436      type: 'object',
437      properties: {
438        method: { type: 'string', enum: ['segregation', 'maxaf', 'carrier', 'recurrence', 'fisher', 'burden', 'denovo', 'km', 'nof1'] },
439        params: { type: 'object', additionalProperties: true },
440      },
441      required: ['method'],
442    },
443    argv: i => {
444      const method = str(i.method) ?? ''
445      const allowed = STATS_FLAGS[method]
446      if (!allowed) throw new Error(`unknown method ${JSON.stringify(method)}`)
447      const out = ['stats', method]
448      const params = (i.params && typeof i.params === 'object' ? i.params : {}) as Record<string, unknown>
449      for (const [k, v] of Object.entries(params)) {
450        const flag = k.replace(/_/g, '-')
451        if (!allowed.includes(flag)) {
452          throw new Error(`${method} does not take ${JSON.stringify(k)}; it takes ${allowed.join(', ')}`)
453        }
454        const key = `--${flag}`
455        if (Array.isArray(v)) out.push(key, ...v.map(String))
456        else if (typeof v === 'boolean') {
457          if (v) out.push(key)
458        } else if (v !== null && v !== undefined) out.push(key, String(v))
459      }
460      return out
461    },
462    deferred: true,
463  },
464  {
465    name: 'edit_check',
466    description:
467      'Base-editing feasibility screen for an SNV: can an adenine or cytosine base editor revert the patient allele to reference, and which SpCas9 protospacers (PAM NGG, or NG for relaxed-PAM variants) put the base in the editing window, with bystander bases (annotate_bystanders checks their coding effect via VEP). Reference sequence from Ensembl. A screen for researchers, not a guide design; delivery to the tissue is the hard part.',
468    inputSchema: {
469      type: 'object',
470      properties: {
471        variant: { type: 'string', description: 'chrom-pos-ref-alt (SNV), transcript HGVS or rsID' },
472        assembly: ASSEMBLY,
473        pam: { type: 'string', enum: ['NGG', 'NG'], description: 'NG when no NGG protospacer exists' },
474        window: { type: 'string', description: 'editing window in protospacer positions, default "4-8"' },
475        annotate_bystanders: { type: 'boolean' },
476      },
477      required: ['variant'],
478    },
479    argv: i => [
480      'edit', str(i.variant) ?? '',
481      ...flag('--assembly', str(i.assembly)), ...flag('--pam', str(i.pam)), ...flag('--window', str(i.window)),
482      ...(i.annotate_bystanders === true ? ['--annotate-bystanders'] : []),
483    ],
484    deferred: true,
485  },
486  {
487    name: 'repeat_size',
488    description:
489      'Read a repeat size by rule, never by memory. d4z4: D4Z4 units from the contracted 4q35 fragment a laboratory reports (EcoRI, EcoRI/BlnI or EcoRI/HindIII — the flank differs by digest; a HindIII- or BlnI-only size is refused), with the sizing-error range and the FSHD1 band (1-3 short, 4-6, 7-10, 11+). dmpk: the DM1 class of a DMPK CTG count. Offline; cite its sources. Use it whenever a reply states repeat units or a repeat class. When the laboratory has already reported the result as diagnostic, that is the diagnosis; this reading supports it and never casts doubt on the laboratory.',
490    inputSchema: {
491      type: 'object',
492      properties: {
493        locus: { type: 'string', enum: ['d4z4', 'dmpk'] },
494        fragment_kb: { type: 'number', description: 'd4z4: contracted fragment size in kb' },
495        digest: { type: 'string', enum: ['EcoRI', 'EcoRI/BlnI', 'EcoRI/HindIII'], description: 'd4z4: the digest the size refers to (default EcoRI)' },
496        haplotype: { type: 'string', description: 'd4z4: 4qA or 4qB as reported' },
497        array_locus: { type: 'string', enum: ['4q', '10q'], description: 'd4z4: chromosome of the sized array when the laboratory states it (EcoRI and EcoRI/HindIII cannot tell 4q from 10q on their own)' },
498        methylation_pct: { type: 'number', description: 'd4z4: D4Z4 methylation % as reported' },
499        ctg: { type: 'number', description: 'dmpk: CTG repeat count (larger allele)' },
500      },
501      required: ['locus'],
502    },
503    argv: i => {
504      if (i.locus === 'dmpk') return ['repeat', 'dmpk', '--ctg', num(i.ctg) ?? '']
505      return ['repeat', 'd4z4', '--fragment-kb', num(i.fragment_kb) ?? '', ...flag('--digest', str(i.digest)),
506        ...flag('--haplotype', str(i.haplotype)), ...flag('--locus', str(i.array_locus)), ...flag('--methylation-pct', num(i.methylation_pct))]
507    },
508  },
509  {
510    name: 'cnv_interpret',
511    description:
512      'Read the report forms that are not a single sequence variant. A CNV or microarray result (region or ISCN, with build, mosaicism such as x1~2 or 30%, de novo/maternal/paternal) → the genes it spans, every one checked against ClinGen gene dosage, and the ClinGen curated regions it overlaps (22q11.2, 1p36, Williams, PWS/AS, 16p11.2 …) with HI/TS scores, coverage and the ACMG/ClinGen 2020 section-2 row they point to; section 3 by gene count for losses and gains separately — inputs to a classification, not one (sections 4-5 need the case). An exon-level deletion or duplication (DMD exon 45-50 deletion, NM_004006.3:c.6439-?_7309+?del, intronic breakpoints) → exons, coding bases, whether the frame is kept, and — only when it is not — which additional exon skip restores it. SMN1/SMN2 copy number (clinical exon numbering 1, 2a, 2b, 3-8) read with the SMN2 count, framed as population data, not a prognosis. Repeat expansions (FMR1, HTT, DMPK, FXN, C9orf72) placed in their published size bands with sex-specific wording and what else is needed (methylation, AGG interruptions, the other allele) — a referenced reading. Coordinates from Ensembl. A finding the laboratory has already classified as pathogenic or reported as diagnostic is a diagnosis: this output is supporting inputs to explain and check it, never a reason to doubt the laboratory.',
513    inputSchema: {
514      type: 'object',
515      properties: {
516        result: {
517          type: 'string',
518          description: 'the finding as the report gives it: "chr15:23123715-28193120 loss" | "arr[GRCh38] 22q11.21(18648855_21800471)x1" | "DMD exon 45-50 deletion" | "NM_004006.3:c.6439-?_7309+?del" | "SMN1 exon 7 copy number 0" | "FMR1 CGG 230"',
519        },
520        assembly: ASSEMBLY,
521        gene: { type: 'string', description: 'when the string does not name one' },
522        copies: { type: 'number', description: 'copy number the report gives, when it is not in the string' },
523        inheritance: { type: 'string', enum: ['de_novo', 'maternal', 'paternal', 'biparental', 'unknown'] },
524        method: { type: 'string', description: 'CMA, CNV-seq, MLPA, ddPCR, repeat-primed PCR …' },
525        record: { type: 'boolean', description: 'also record it in the active case (a write: asked about like any case change)' },
526        sex: { type: 'string', enum: ['male', 'female'], description: 'decides what an X/Y copy number means (default: the case profile)' },
527        smn2_copies: { type: 'number', description: 'SMN2 copy number, read together with SMN1' },
528        related: { type: 'array', items: { type: 'string' }, description: 'other findings in the same report (the second allele of a repeat, a second CNV)' },
529      },
530      required: ['result'],
531    },
532    argv: i => [
533      'cnv', str(i.result) ?? '',
534      ...flag('--assembly', str(i.assembly)), ...flag('--gene', str(i.gene)), ...flag('--copies', num(i.copies)),
535      ...flag('--inheritance', str(i.inheritance)), ...flag('--method', str(i.method)),
536      ...flag('--sex', str(i.sex)), ...flag('--smn2-copies', num(i.smn2_copies)),
537      ...(list(i.related).length ? ['--related', ...list(i.related)] : []),
538      ...(i.record === true ? ['--record'] : []),
539    ],
540    touchesCase: true,
541    timeoutMs: 180_000,
542    deferred: true,
543  },
544  {
545    name: 'china_rare',
546    description:
547      "China's national rare disease lists (第一批罕见病目录 2018, 第二批 2023): is a disease on them, its Chinese name and list number. status: on_list (the published entry, or a named member of a listed group); qualified (only a subtype or form is listed — the result says which); possible (closest entries to verify, e.g. an acronym or a shared stretch of text — not a match); not_found. With query \"hospitals\": the 国家罕见病诊疗协作网 hospitals (NHC 2024 list, 419), by province with the lead hospitals. Input: Chinese or English name.",
548    inputSchema: {
549      type: 'object',
550      properties: {
551        query: { type: 'string', description: 'a disease name, or "hospitals" for the collaboration-network hospitals' },
552        province: { type: 'string', description: 'with "hospitals": e.g. 浙江 or 浙江省' },
553      },
554      required: ['query'],
555    },
556    argv: i => ['china', str(i.query) ?? '', ...flag('--province', str(i.province))],
557    deferred: true,
558  },
559  {
560    name: 'case_recheck',
561    description:
562      'Ask the active case\'s questions again and say what changed since the last recheck: ClinVar classification and stars of each recorded sequence variant, gnomAD frequency, ClinGen gene-disease validity of its genes, recruiting trials (new and no longer recruiting) and papers first published since then for each open hypothesis. The first run records the baseline. Each change says what to look at again (an ACMG reading, a trial\'s eligibility); nothing is concluded. Queries carry biology only and skip anything holding a protected identifier. plan: true lists the questions without sending them.',
563    inputSchema: { type: 'object', properties: { plan: { type: 'boolean' } } },
564    argv: (i, casePath) => {
565      if (!casePath) throw new Error('no active case (the person can run /zebra new <dir> or /zebra case <dir>)')
566      return ['case', 'recheck', casePath, ...(i.plan === true ? ['--plan'] : [])]
567    },
568    touchesCase: true,
569    deferred: true,
570    timeoutMs: 600_000,
571  },
572  {
573    name: 'access',
574    description:
575      'Access to a treatment, for a drug, a disease or a gene, with the source of every line: FDA and EMA status from the agencies\' own records (openFDA labels, Drugs@FDA, EMA medicine data — withdrawn and refused shown as such), approval in China from the bundled official NMPA/CDE documents (approved_in_china, named_not_approved, or not_in_bundled_list — which is not "not approved"), China\'s 2025 national reimbursement list (NRDL) entry with its restriction text verbatim, trials with sites in China (ClinicalTrials.gov; ChiCTR cannot be queried by a script — it blocks them), and the collaboration-network hospitals for a province. A name it cannot resolve exactly comes back unresolved with candidates; it never answers for a near match.',
576    inputSchema: {
577      type: 'object',
578      properties: {
579        query: { type: 'string', description: 'drug (INN or Chinese name), disease (Chinese or English) or gene symbol' },
580        as: { type: 'string', enum: ['auto', 'drug', 'disease', 'gene'] },
581        province: { type: 'string', description: 'list the collaboration-network hospitals of this province, e.g. 浙江' },
582        trials: { type: 'number', description: 'how many trials with a site in China (default a few)' },
583        status: { type: 'string', description: 'trial status filter, e.g. RECRUITING or ANY' },
584      },
585      required: ['query'],
586    },
587    argv: i => [
588      'access', str(i.query) ?? '', ...flag('--as', str(i.as)), ...flag('--province', str(i.province)),
589      ...flag('--trials', num(i.trials)), ...flag('--status', str(i.status)),
590    ],
591    timeoutMs: 180_000,
592  },
593  {
594    name: 'expression',
595    description:
596      'Median expression of a gene per tissue (GTEx v8/v10) with each tissue\'s ontology id (UBERON/EFO) — for choosing the AlphaGenome tissue and the tissue an RNA test can use: the result states whether blood, lymphoblastoid cells, fibroblasts, skin or muscle reach 1 TPM. Bulk adult medians, not a detection limit; an NMD-degraded transcript reads low.',
597    inputSchema: {
598      type: 'object',
599      properties: {
600        gene: { type: 'string' },
601        top: { type: 'number' },
602        dataset: { type: 'string', enum: ['gtex_v8', 'gtex_v10'] },
603      },
604      required: ['gene'],
605    },
606    argv: i => ['expression', str(i.gene) ?? '', ...flag('--top', num(i.top)), ...flag('--dataset', str(i.dataset))],
607    deferred: true,
608  },
609  {
610    name: 'aso_screen',
611    description:
612      'Splice-switching antisense feasibility screen for researchers: from SpliceAI for the variant, the aberrant event (pseudoexon / cryptic acceptor / cryptic donor, boundaries checked for AG/GT in the patient sequence; or exon_skip to restore a reading frame), then candidate target windows on the pre-mRNA with coordinates, target and antisense sequence, GC, hairpin and homopolymer flags, whether the variant lies inside, every ranking component shown, and published N-of-1 precedents retrieved from Europe PMC. When no aberrant splicing is predicted it says so and stops. Optional genomic uniqueness via NCBI BLAST (slow: 30-700 s). A screen, not a design: no chemistry, dose or delivery; RNA evidence of the aberrant splicing comes first.',
613    inputSchema: {
614      type: 'object',
615      properties: {
616        variant: { type: 'string', description: 'chrom-pos-ref-alt, transcript HGVS or rsID' },
617        assembly: ASSEMBLY,
618        event: { type: 'string', enum: ['auto', 'pseudoexon', 'cryptic_acceptor', 'cryptic_donor', 'exon_skip'] },
619        lengths: { type: 'string', description: 'target lengths LO-HI between 12 and 40 (default 18-25)' },
620        min_delta: { type: 'number', description: 'SpliceAI delta threshold (default 0.2)' },
621        top: { type: 'number', description: '1-60 (default 12)' },
622        uniqueness: { type: 'boolean', description: 'one NCBI BLAST search of the shortlist; adds 30-700 s' },
623        distance: { type: 'number' },
624      },
625      required: ['variant'],
626    },
627    argv: i => [
628      'aso', str(i.variant) ?? '', ...flag('--assembly', str(i.assembly)), ...flag('--event', str(i.event)),
629      ...flag('--lengths', str(i.lengths)), ...flag('--min-delta', num(i.min_delta)), ...flag('--top', num(i.top)),
630      ...flag('--distance', num(i.distance)), ...(i.uniqueness === true ? ['--uniqueness'] : []),
631    ],
632    deferred: true,
633    timeoutMs: 600_000,
634  },
635  {
636    name: 'report_export',
637    description:
638      'Turn a Markdown report from the case (family letter, visit-preparation sheet, clinician summary) into an HTML page, Word (.docx) and PDF with Chinese typography (tables sized to their content, page numbers, provenance tags, an urgent-care section drawn as a warning box), for a family that does not use a terminal: the person running zebra-mod hands them the files. Written next to the report. Refuses a report that still contains the case\'s protected identifiers or a resident ID number. PDF is printed by a browser on this machine (Chrome, Edge, Chromium, Brave) or LibreOffice; without one the result says so and the other formats are still made.',
639    inputSchema: {
640      type: 'object',
641      properties: {
642        report: { type: 'string', description: 'the .md report: an absolute path, or relative to the case folder (reports/family-letter-2026-10-06.md)' },
643        formats: { type: 'array', items: { type: 'string', enum: ['docx', 'pdf', 'html'] }, description: 'default html, docx and pdf' },
644        title: { type: 'string', description: 'document title (default: the first heading)' },
645      },
646      required: ['report'],
647    },
648    argv: (i, casePath) => {
649      const report = str(i.report) ?? ''
650      const path = report && casePath && !/^(?:\/|~)/.test(report) ? `${casePath.replace(/\/$/, '')}/${report}` : report
651      const formats = list(i.formats)
652      return ['report', 'export', path, ...flag('--to', formats.length ? formats.join(',') : undefined), ...flag('--title', str(i.title))]
653    },
654    deferred: true,
655    timeoutMs: 150_000,
656  },
657]
658
659/** The keys the tool's own schema declares: the event also carries `tool`, `tool_use_id` and more. */
660export function schemaArgs(def: ToolDef, input: Record<string, unknown>): Record<string, unknown> {
661  const props = (def.inputSchema.properties ?? {}) as Record<string, unknown>
662  const out: Record<string, unknown> = {}
663  for (const key of Object.keys(props)) if (input[key] !== undefined) out[key] = input[key]
664  return out
665}
666
667/** No value the model supplies legitimately starts with "-": the CLI would read it as a flag. */
668function flagShaped(value: unknown, path = ''): string | undefined {
669  if (typeof value === 'string') {
670    return value.trimStart().startsWith('-') ? `${path || 'value'}: ${JSON.stringify(value)}` : undefined
671  }
672  if (Array.isArray(value)) {
673    for (let i = 0; i < value.length; i++) {
674      const hit = flagShaped(value[i], `${path}[${i}]`)
675      if (hit) return hit
676    }
677    return undefined
678  }
679  if (value && typeof value === 'object') {
680    for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
681      const hit = flagShaped(v, path ? `${path}.${k}` : k)
682      if (hit) return hit
683    }
684  }
685  return undefined
686}
687
688export async function toolArgv(def: ToolDef, input: Record<string, unknown>, casePath: string | null): Promise<string[]> {
689  const clean = schemaArgs(def, input)
690  // `case_update` carries the person's own prose (notes, questions), where a leading
691  // dash is harmless: it is passed as one JSON argument, never as a command-line value.
692  if (def.name !== 'case_update') {
693    const shaped = flagShaped(clean)
694    if (shaped) throw new Error(`${shaped} is not a value this tool takes (it reads as a command-line flag)`)
695  }
696  const argv = def.argv(clean, casePath)
697  if (argv.some(a => a === '')) throw new Error('a required argument is empty')
698  return argv
699}
700
hooks/ui.tsx 626 lines
1// What zebra-mod shows in Claude Code, so a person can see when it is at work and what it did:
2//   - its own rows for its tool calls (what is looked up, in which databases, how much evidence came back)
3//     in place of a raw JSON envelope; a case_update row never shows the identifiers it registers
4//   - the spinner says which databases are being queried
5//   - a galloping zebra in the band above the prompt while a query runs, and a standing one with a
6//     shield for a few seconds after the privacy gate stopped an outgoing call
7//   - a footer label (🦓 and the open case) so it is always clear the mod is installed
8//   - one line at the end of a turn that used it: calls, databases, evidence rows, calls refused
9// Everything is additive and scoped to zebra-mod's own activity: unrelated work draws as before.
10// These hooks are registered first, so they wrap the tool, gate and drawing hooks in register.tsx.
11
12import { atom, read, update } from 'claude-code'
13import type { EngineInterface, Register, ToolCallResult } from 'claude-code'
14
15import type { Board, ZebraRun, ZebraTurn } from '../types'
16import { FRAME_COUNT, RASTER_COLUMNS, RASTER_ROWS, zebraCells } from './ui-sprite'
17
18type On = Parameters<Register>[0]
19type Options = Parameters<Register>[1]
20export type UiMode = 'full' | 'quiet' | 'off'
21
22const PREFIX = 'mcp__zebra-mod__'
23const LOCAL = 'local'
24const FRAME_MS = 70 // eleven frames: one stride in about 0.8 s
25
26const EMPTY_TURN: ZebraTurn = { calls: 0, failed: 0, blocked: 0, sources: [], cached: 0, evidence: 0, firstEvidence: null, lastEvidence: null }
27
28const board = atom({ plugin: 'zebra-mod', key: 'board' } as const, null as Board | null)
29const running = atom({ plugin: 'zebra-mod', key: 'running' } as const, [] as ZebraRun[])
30const turnStats = atom({ plugin: 'zebra-mod', key: 'turn' } as const, EMPTY_TURN)
31const blockedAt = atom({ plugin: 'zebra-mod', key: 'blockedAt' } as const, null as number | null)
32const lang = atom({ plugin: 'zebra-mod', key: 'lang' } as const, null as string | null)
33// why the gate refused: an identifier in the call, or a case file it could not read (the gate closed)
34// true from the first interactive session after installing until the person's first prompt
35const onboarding = atom({ plugin: 'zebra-mod', key: 'onboarding' } as const, false as boolean)
36const blockedWhy = atom({ plugin: 'zebra-mod', key: 'blockedWhy' } as const, 'identifier' as string)
37
38// ------------------------------------------------------------ words
39
40// [Chinese, English]
41const LABELS: Record<string, [string, string]> = {
42  case_status: ['病例概况', 'Case status'],
43  case_update: ['更新病例', 'Case update'],
44  case_recheck: ['病例复查', 'Case recheck'],
45  hpo_search: ['HPO 术语检索', 'HPO term search'],
46  phenotype_rank: ['表型排序', 'Phenotype ranking'],
47  gene_card: ['基因卡', 'Gene card'],
48  variant_card: ['变异卡', 'Variant card'],
49  disease_card: ['疾病卡', 'Disease card'],
50  acmg: ['ACMG 计分', 'ACMG points'],
51  cnv_interpret: ['拷贝数变异解读', 'CNV reading'],
52  repeat_size: ['重复序列换算', 'Repeat size'],
53  s2f_predict: ['序列功能预测', 'Sequence-to-function'],
54  therapy_landscape: ['治疗全景', 'Therapy landscape'],
55  trials_search: ['临床试验检索', 'Trial search'],
56  literature_search: ['文献检索', 'Literature search'],
57  rare_stats: ['统计计算', 'Statistics'],
58  edit_check: ['碱基编辑可行性', 'Base-editing screen'],
59  china_rare: ['中国罕见病目录', 'China rare disease lists'],
60  access: ['药物可及性', 'Drug access'],
61  expression: ['组织表达', 'Tissue expression'],
62  aso_screen: ['反义寡核苷酸筛查', 'Antisense screen'],
63  report_export: ['导出报告', 'Report export'],
64}
65
66// What each tool is expected to query, shown while it runs; the row afterwards names what it did query.
67const EXPECTED: Record<string, string[]> = {
68  case_status: [LOCAL], case_update: [LOCAL], report_export: [LOCAL], rare_stats: [LOCAL], repeat_size: [LOCAL],
69  case_recheck: ['ClinVar', 'ClinGen', 'ClinicalTrials.gov', 'Europe PMC'],
70  hpo_search: ['HPO'],
71  phenotype_rank: ['HPO', 'Monarch', 'PubCaseFinder'],
72  gene_card: ['HGNC', 'ClinGen', 'gnomAD', 'PanelApp', 'UniProt'],
73  variant_card: ['Ensembl VEP', 'gnomAD', 'ClinVar', 'LitVar2'],
74  disease_card: ['Orphanet', 'Monarch', 'GeneReviews', 'HPO'],
75  cnv_interpret: ['Ensembl', 'ClinGen'],
76  s2f_predict: ['SpliceAI', 'Pangolin'],
77  therapy_landscape: ['Open Targets', 'EMA'],
78  trials_search: ['ClinicalTrials.gov'],
79  literature_search: ['Europe PMC', 'PubTator3', 'LitVar2'],
80  edit_check: ['Ensembl'],
81  china_rare: ['China national rare disease list'],
82  access: ['Open Targets', 'EMA', 'China drug approvals', '国家医保药品目录', 'ClinicalTrials.gov'],
83  expression: ['GTEx'],
84  aso_screen: ['Ensembl', 'SpliceAI', 'Europe PMC'],
85}
86
87// Source names whose short form is not their first words.
88const RENAMED: Array<[RegExp, string, string]> = [
89  [/^China drug approvals/, 'NMPA/CDE', 'NMPA/CDE'],
90  [/^China national rare disease list/, '国家罕见病目录', 'China rare disease lists'],
91  [/^China rare disease list alias/, '', ''],
92  [/^国家医保药品目录/, '国家医保目录', 'China NRDL'],
93  [/^全国罕见病诊疗协作网/, '罕见病诊疗协作网', 'China rare disease network'],
94  [/^GeneReviews/, 'GeneReviews', 'GeneReviews'],
95  [/^local$/, '本机', 'this computer'],
96]
97
98/** "ClinVar esearch" → ClinVar, "HPO annotations (phenotype.hpoa)" → HPO: the database, not the endpoint. */
99export function sourceName(db: string, zh: boolean): string {
100  for (const [re, z, en] of RENAMED) if (re.test(db)) return zh ? z : en
101  const head = (db.split(' (')[0] ?? db).trim()
102  const kept: string[] = []
103  for (const word of head.split(/\s+/)) {
104    if (kept.length > 0 && /^[a-z]/.test(word)) break
105    kept.push(word)
106  }
107  return kept.join(' ') || head
108}
109
110function sourceNames(dbs: readonly string[], zh: boolean): string[] {
111  return [...new Set(dbs.map(d => sourceName(d, zh)).filter(Boolean))]
112}
113
114export function labelOf(tool: string, zh: boolean): string {
115  const l = LABELS[tool]
116  return l ? (zh ? l[0] : l[1]) : tool
117}
118
119function clip(text: string, max: number): string {
120  const one = text.replace(/\s+/g, ' ').trim()
121  return one.length > max ? `${one.slice(0, Math.max(1, max - 1))}…` : one
122}
123
124/** What a call is about, for its row. Never the identifiers a case_update registers. */
125export function queryOf(tool: string, input: unknown, zh: boolean): string {
126  const i = (input && typeof input === 'object' ? input : {}) as Record<string, unknown>
127  const s = (k: string): string => (typeof i[k] === 'string' ? (i[k] as string).trim() : '')
128  const n = (k: string): number => (Array.isArray(i[k]) ? (i[k] as unknown[]).length : 0)
129  // the first plain argument, when the usual ones are absent (never the reserved keys or identifiers)
130  const any = (): string => {
131    for (const [k, v] of Object.entries(i)) {
132      if (['tool', 'tool_use_id', 'consent', 'agentId', 'identifiers'].includes(k)) continue
133      if (typeof v === 'string' && v.trim()) return v.trim()
134      if (Array.isArray(v) && v.length && v.every(x => typeof x === 'string')) return (v as string[]).join(' ')
135    }
136    return ''
137  }
138  return pick() || (tool === 'case_update' || tool === 'case_status' || tool === 'case_recheck' ? '' : any())
139  function pick(): string {
140  switch (tool) {
141    case 'case_update': {
142      const parts: string[] = []
143      const ids = n('identifiers')
144      if (ids) parts.push(zh ? `登记受保护身份信息 ${ids} 项(内容不显示)` : `${ids} protected identifiers registered (not shown)`)
145      const kinds: Array<[string, string, string]> = [
146        ['phenotypes', '表型', 'phenotypes'], ['variants', '变异', 'variants'], ['hypotheses', '诊断假设', 'hypotheses'],
147        ['acmg', 'ACMG 判读', 'ACMG readings'], ['leads', '治疗线索', 'therapy leads'], ['tests', '已做检查', 'tests'],
148        ['family', '家庭成员', 'relatives'], ['timeline', '时间线', 'timeline events'], ['questions', '待问问题', 'questions'],
149      ]
150      for (const [k, z, en] of kinds) {
151        const c = n(k)
152        if (c) parts.push(zh ? `${z} ${c} 项` : `${c} ${en}`)
153      }
154      if (i.profile && typeof i.profile === 'object') parts.push(zh ? '基本信息' : 'profile')
155      if (n('remove')) parts.push(zh ? `删除 ${n('remove')} 项` : `${n('remove')} removals`)
156      return parts.join(' · ')
157    }
158    case 'case_status':
159    case 'case_recheck':
160      return ''
161    case 'hpo_search':
162      return s('text')
163    case 'phenotype_rank': {
164      if (i.from_case === true) return zh ? '使用病例中的表型' : 'phenotypes from the case'
165      const p = n('present')
166      const x = n('excluded')
167      return zh ? `${p} 项表型${x ? ` · 排除 ${x} 项` : ''}` : `${p} present${x ? ` · ${x} excluded` : ''}`
168    }
169    case 'gene_card':
170      return s('symbol')
171    case 'acmg': {
172      const codes = Array.isArray(i.codes) ? (i.codes as unknown[]).filter((c): c is string => typeof c === 'string') : []
173      return codes.length ? codes.join(' + ') : s('variant')
174    }
175    case 'trials_search':
176      return [s('condition'), s('term'), s('country')].filter(Boolean).join(' · ')
177    case 'literature_search':
178      return s('query') || [s('gene'), s('variant')].filter(Boolean).join(' ')
179    case 'rare_stats':
180      return s('method')
181    case 'cnv_interpret':
182      return s('result')
183    case 'repeat_size':
184      return i.locus === 'dmpk' ? `DMPK CTG ${String(i.ctg ?? '')}` : `D4Z4 ${String(i.fragment_kb ?? '')} kb`
185    case 'report_export':
186      return s('report')
187    default: {
188      for (const k of ['variant', 'query', 'gene', 'symbol', 'text']) if (s(k)) return s(k)
189      return ''
190    }
191  }
192  }
193}
194
195// ------------------------------------------------------------ the tool's answer
196
197type Envelope = { warnings?: unknown; ledger?: unknown; sources?: unknown; result?: unknown }
198
199/** The JSON envelope register.tsx answers a zebra tool with, from a ToolResult's output, or null. */
200export function envelopeOf(output: unknown): Envelope | null {
201  let text: string | undefined
202  if (typeof output === 'string') text = output
203  else if (Array.isArray(output)) {
204    text = output.map(b => (b && typeof b === 'object' && typeof (b as { text?: unknown }).text === 'string' ? (b as { text: string }).text : '')).join('')
205  } else if (output && typeof output === 'object') {
206    if ('ledger' in output || 'sources' in output) return output as Envelope
207    const t = (output as { text?: unknown }).text
208    if (typeof t === 'string') text = t
209  }
210  if (!text || text[0] !== '{') return null
211  try {
212    const parsed = JSON.parse(text) as unknown
213    return parsed && typeof parsed === 'object' && ('ledger' in parsed || 'sources' in parsed) ? (parsed as Envelope) : null
214  } catch {
215    return null
216  }
217}
218
219type Digest = { dbs: string[]; cached: number; evidence: number; first: number | null; last: number | null; warnings: number }
220
221export function digest(env: Envelope): Digest {
222  const sources = Array.isArray(env.sources) ? env.sources : []
223  const dbs: string[] = []
224  let cached = 0
225  for (const s of sources) {
226    if (!s || typeof s !== 'object') continue
227    const db = (s as { db?: unknown }).db
228    if (typeof db === 'string' && db.trim()) dbs.push(db.trim())
229    if ((s as { cached?: unknown }).cached === true) cached++
230  }
231  const ids = (Array.isArray(env.ledger) ? env.ledger : [])
232    .map(x => (typeof x === 'string' ? /^E(\d+)$/.exec(x.trim()) : null))
233    .filter((m): m is RegExpExecArray => m !== null)
234    .map(m => Number(m[1]))
235  const warnings = Array.isArray(env.warnings) ? env.warnings.length : 0
236  return {
237    dbs: [...new Set(dbs)],
238    cached,
239    evidence: ids.length,
240    first: ids.length ? Math.min(...ids) : null,
241    last: ids.length ? Math.max(...ids) : null,
242    warnings,
243  }
244}
245
246function range(first: number | null, last: number | null): string {
247  if (first === null || last === null) return ''
248  return first === last ? `E${first}` : `E${first}–E${last}`
249}
250
251function listed(names: string[], zh: boolean, max = 4): string {
252  if (names.length <= max) return names.join(zh ? '、' : ', ')
253  const shown = names.slice(0, max).join(zh ? '、' : ', ')
254  return zh ? `${shown} 等 ${names.length} 个` : `${shown} +${names.length - max} more`
255}
256
257/** The one line under a zebra tool's row: evidence, databases, cache, notes. */
258export function summaryLine(env: Envelope, zh: boolean): string {
259  const d = digest(env)
260  const names = sourceNames(d.dbs, zh)
261  const parts: string[] = []
262  if (d.evidence) parts.push(zh ? `证据 ${d.evidence} 条(${range(d.first, d.last)})` : `${d.evidence} evidence rows (${range(d.first, d.last)})`)
263  if (names.length) parts.push(zh ? `来源 ${listed(names, zh)}` : `from ${listed(names, zh)}`)
264  if (d.cached) parts.push(zh ? `${d.cached} 条来自缓存` : `${d.cached} cached`)
265  if (d.warnings) parts.push(zh ? `${d.warnings} 条提示` : `${d.warnings} notes`)
266  if (!parts.length) return zh ? '已在本机完成' : 'done on this computer'
267  return parts.join(' · ')
268}
269
270/** The line left at the end of a turn that used zebra-mod. */
271export function turnLine(t: ZebraTurn, zh: boolean): string | undefined {
272  if (t.calls === 0 && t.blocked === 0) return undefined
273  if (t.calls === 0) {
274    return zh
275      ? `🛡 本轮隐私闸门拦下 ${t.blocked} 次外发调用,相关内容未发出。`
276      : `🛡 The privacy gate stopped ${t.blocked} outgoing call${t.blocked > 1 ? 's' : ''} this turn; nothing in them was sent.`
277  }
278  const names = sourceNames(t.sources, zh).filter(n => n !== (zh ? '本机' : 'this computer'))
279  const parts: string[] = [zh ? `调用 ${t.calls} 次` : `${t.calls} call${t.calls > 1 ? 's' : ''}`]
280  if (names.length) parts.push(zh ? `查询 ${names.length} 个数据源(${listed(names, zh, 5)})` : `${names.length} databases (${listed(names, zh, 5)})`)
281  if (t.evidence) parts.push(zh ? `新增证据 ${t.evidence} 条(${range(t.firstEvidence, t.lastEvidence)})` : `${t.evidence} evidence rows (${range(t.firstEvidence, t.lastEvidence)})`)
282  if (t.failed) parts.push(zh ? `${t.failed} 次未执行` : `${t.failed} not run`)
283  if (t.blocked) parts.push(zh ? `隐私闸门拦截 ${t.blocked} 次` : `${t.blocked} stopped by the privacy gate`)
284  return `🦓 ${zh ? '本轮 zebra-mod:' : 'zebra-mod this turn: '}${parts.join(' · ')}`
285}
286
287// ------------------------------------------------------------ hooks
288
289// What the animation and the language choice read between render passes; a reload resets them.
290let envZh: boolean | undefined
291let bandId: string | undefined
292let frame = 0
293let scroll = 0
294let ticker: { cancel: () => void; owner: string } | undefined
295
296async function isZh($: EngineInterface): Promise<boolean> {
297  const b = await read($, board)
298  if (b?.language) return b.language.toLowerCase().startsWith('zh')
299  const l = await read($, lang)
300  if (l) return l === 'zh'
301  if (envZh === undefined) {
302    const env = (await $.env.get('LC_ALL')) || (await $.env.get('LANG')) || ''
303    envZh = env.toLowerCase().startsWith('zh')
304  }
305  return envZh
306}
307
308// The gallop runs inside the tool call that started it (that dispatch lasts as long as the query)
309// and stops with it.
310function startTicker($: EngineInterface, owner: string): void {
311  if (ticker) return
312  let timer: { cancel: () => void }
313  try {
314    timer = $.clock.every(FRAME_MS, () => {
315    frame = (frame + 1) % FRAME_COUNT
316    scroll += 2
317    if (bandId === undefined) return
318    void $.ui
319      .blit({ requestId: bandId, key: 'zebra', cells: zebraCells(frame, scroll), columns: RASTER_COLUMNS, rows: RASTER_ROWS })
320      .catch(() => undefined)
321    })
322  } catch {
323    return // no timer here: the band stays a still picture
324  }
325  ticker = { cancel: () => timer.cancel(), owner }
326}
327
328function stopTicker(owner: string): void {
329  if (ticker?.owner !== owner) return
330  ticker.cancel()
331  ticker = undefined
332}
333
334/** One zebra tool call, wrapped: in flight for the spinner and the band, then tallied for the turn. */
335async function observeCall<E extends { tool_use_id?: string }>(
336  $: EngineInterface,
337  e: E,
338  next: (e: E) => Promise<ToolCallResult>,
339  tool: string,
340  mode: UiMode,
341): Promise<ToolCallResult> {
342  const now = Date.now()
343  const id = String(e.tool_use_id ?? `${tool}:${now}`)
344  const run: ZebraRun = {
345    id,
346    tool,
347    queryZh: clip(queryOf(tool, e, true), 80),
348    queryEn: clip(queryOf(tool, e, false), 80),
349    sources: EXPECTED[tool] ?? [],
350    startedAt: now,
351  }
352  await update($, running, list => [...list, run])
353  if (mode === 'full' && run.sources.some(s => s !== LOCAL)) startTicker($, id)
354  let answer: ToolCallResult | undefined
355  try {
356    answer = await next(e)
357    return answer
358  } finally {
359    stopTicker(id)
360    await update($, running, list => list.filter(r => r.id !== id))
361    await update($, turnStats, t => recordCall(t, tool, answer))
362  }
363}
364
365/** A tool-result row that carries the privacy gate's refusal: a shield until the next turn. */
366async function noteRefusals($: EngineInterface, content: unknown, mode: UiMode): Promise<void> {
367  const texts = gateRefusals(content)
368  const refusals = texts.length
369  if (refusals === 0) return
370  const at = Date.now()
371  await update($, blockedWhy, () => (texts.some(t => t.includes('gate is closed')) ? 'closed' : 'identifier'))
372  await update($, blockedAt, () => at)
373  await update($, turnStats, t => ({ ...t, blocked: t.blocked + refusals }))
374  if (mode === 'quiet') {
375    $.ui.toast(
376      (await isZh($))
377        ? '🛡 隐私闸门拦下一次外发调用:其中含有受保护的身份信息,未发出。'
378        : '🛡 The privacy gate stopped an outgoing call that carried a protected identifier; it was not sent.',
379    )
380  }
381}
382
383/** The first interactive session after installing (or updating to this version): say what to do. */
384async function startOnboarding($: EngineInterface): Promise<void> {
385  if ((await $.store.get('onboarded')) === true) return
386  await update($, onboarding, () => true)
387  $.ui.toast(
388    (await isZh($))
389      ? '🦓 zebra-mod 已就绪:直接用中文描述病情或检查结果即可。输入 /zebra demo 打开示例病例试试,/zebra 查看全部功能。'
390      : '🦓 zebra-mod is ready: just describe symptoms or test results. Type /zebra demo to try a demo case, /zebra for everything it does.',
391  )
392}
393
394/** The first prompt ends the onboarding card, for good. */
395async function endOnboarding($: EngineInterface): Promise<void> {
396  if (!(await read($, onboarding))) return
397  await update($, onboarding, () => false)
398  await $.store.set('onboarded', true)
399}
400
401async function closeTurn($: EngineInterface): Promise<void> {
402  const line = turnLine(await read($, turnStats), await isZh($))
403  if (line) await $.session.append({ message: { type: 'system', content: [{ type: 'text', text: line }] } }).catch(() => undefined)
404  await update($, turnStats, () => EMPTY_TURN)
405  await update($, running, () => [])
406}
407
408export function registerUi(on: On, options: Options): void {
409  const mode: UiMode = options.interface === 'quiet' || options.interface === 'off' ? options.interface : 'full'
410  if (mode === 'off') return
411
412  on('turn.start', async ($, e, next) => {
413    await update($, turnStats, () => EMPTY_TURN)
414    await update($, blockedAt, () => null)
415    await update($, running, () => []) // nothing of a previous turn is still running
416    if (/[㐀-鿿]/.test(e.text)) await update($, lang, () => 'zh')
417    await endOnboarding($)
418    return next(e)
419  })
420
421  on('session.start', { isInteractive: true }, async ($, e, next) => {
422    const started = await next(e)
423    await startOnboarding($)
424    return started
425  })
426
427  on('turn.complete', async ($, e, next) => {
428    const done = await next(e)
429    if (!e.agentId) await closeTurn($)
430    return done
431  })
432
433  // Wraps the tool hook in register.tsx (registered after these): what runs, and what it brought back.
434  for (const tool of Object.keys(LABELS)) {
435    on('tool.call', { tool: `${PREFIX}${tool}` }, async ($, e, next) => observeCall($, e, next, tool, mode)).catch(($, e, next) => next(e))
436  }
437
438  // The privacy gate's refusals, from the tool results they leave (any tool, zebra's or not).
439  on('session.append', async ($, e, next) => {
440    const stored = await next(e)
441    if (e.door === 'tool-result') await noteRefusals($, e.message.content, mode)
442    return stored
443  }).catch(($, e, next) => next(e))
444
445  // ---------------------------------------------------------- drawing
446
447  // A zebra tool's row: 🦓, what it is, what it is about; while it runs, the databases it queries.
448  on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
449    const tool = e.props.tool.startsWith(PREFIX) ? e.props.tool.slice(PREFIX.length) : ''
450    if (!LABELS[tool] || e.props.isInterrupted) return next(e)
451    const zh = await isZh($)
452    const { Box, Text } = $.ui.resolve(e)
453    const width = e.viewport?.columns ?? 100
454    const label = labelOf(tool, zh)
455    const query = clip(queryOf(tool, e.props.input, zh), Math.max(16, width - label.length - 16))
456    const head = [<Text color="claude">🦓 </Text>, <Text bold>{label}</Text>]
457    if (query) head.push(<Text dimColor>{`  ${query}`}</Text>)
458    if (e.props.isRunning) head.push(<Text color="subtle">{zh ? '  查询中…' : '  running…'}</Text>)
459    else if (e.props.isErrored) head.push(<Text color="error">{zh ? '  未执行' : '  not run'}</Text>)
460    const rows = [<Box flexDirection="row">{head}</Box>]
461    const expected = sourceNames(EXPECTED[tool] ?? [], zh)
462    if (e.props.isRunning && expected.length) {
463      rows.push(<Text dimColor wrap="truncate-end">{`   ${zh ? '数据源:' : 'sources: '}${expected.join(' · ')}`}</Text>)
464    }
465    return <Box flexDirection="column">{rows}</Box>
466  })
467
468  // Its result: evidence, databases, cache and notes in one line, in place of the JSON envelope.
469  on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
470    const tool = e.props.tool.startsWith(PREFIX) ? e.props.tool.slice(PREFIX.length) : ''
471    if (!LABELS[tool] || e.props.isErrored) return next(e)
472    const env = envelopeOf(e.props.output)
473    if (!env) return next(e)
474    const { Text } = $.ui.resolve(e)
475    return <Text dimColor wrap="truncate-end">{`  ⎿ ${summaryLine(env, await isZh($))}`}</Text>
476  })
477
478  // The spinner names the databases being queried.
479  on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
480    if (mode !== 'full' || e.props.message) return next(e)
481    const runs = await read($, running)
482    if (!runs.length) return next(e)
483    const zh = await isZh($)
484    const names = sourceNames(runs.flatMap(r => r.sources), zh).filter(n => n !== (zh ? '本机' : 'this computer'))
485    const word = names.length
486      ? `🦓 ${zh ? '正在查询' : 'Querying'} ${listed(names, zh, 3)}`
487      : `🦓 ${labelOf((runs[0] as ZebraRun).tool, zh)}`
488    return next({ ...e, props: { ...e.props, word } })
489  })
490
491  // A footer label: the mod is here (🦓), with the open case's title, or a shield after a refusal.
492  on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
493    const b = await read($, board)
494    const at = await read($, blockedAt)
495    const label = `${at !== null ? '🛡' : '🦓'} ${b ? caseLabel(b) : 'zebra'}`
496    return next({ ...e, props: { ...e.props, modes: [...e.props.modes, label] } })
497  })
498
499  // The band above the prompt: a galloping zebra while a query runs; a standing one with a shield
500  // after the gate refused a call, until the next turn. Nothing otherwise.
501  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
502    if (mode !== 'full' || e.props.hasSurvey) return next(e)
503    const runs = (await read($, running)).filter(r => r.sources.some(s => s !== LOCAL))
504    const at = await read($, blockedAt)
505    // the welcome card until the first prompt, and not once a case is open (the demo, a new case)
506    const isWelcome = !runs.length && at === null && (await read($, onboarding)) && (await read($, board)) === null
507    if (!runs.length && at === null && !isWelcome) return next(e)
508    const zh = await isZh($)
509    bandId = e.requestId
510    const lines = runs.length ? runningLines(runs, zh) : isWelcome ? welcomeLines(zh) : shieldLines(zh, (await read($, blockedWhy)) === 'closed')
511    const tone = runs.length || isWelcome ? 'claude' : 'success'
512    if (e.surface === 'terminal' && e.props.bodyColumns >= RASTER_COLUMNS + 30) {
513      const { Box, Text, Raster } = $.ui.resolve(e)
514      return (
515        <Box flexDirection="row" gap={2}>
516          <Raster key="zebra" columns={RASTER_COLUMNS} rows={RASTER_ROWS} cells={zebraCells(frame, scroll, runs.length === 0)} />
517          <Box flexDirection="column" justifyContent="center" width={Math.max(20, e.props.bodyColumns - RASTER_COLUMNS - 2)}>
518            <Text bold color={tone} wrap="truncate-end">{lines[0]}</Text>
519            <Text wrap="truncate-end">{lines[1]}</Text>
520            <Text dimColor wrap="truncate-end">{lines[2]}</Text>
521          </Box>
522        </Box>
523      )
524    }
525    const { Box, Text } = $.ui.resolve(e)
526    return (
527      <Box flexDirection="column">
528        <Text bold color={tone} wrap="truncate-end">{lines[0]}</Text>
529        <Text wrap="truncate-end">{lines[1]}</Text>
530        <Text dimColor wrap="truncate-end">{lines[2]}</Text>
531      </Box>
532    )
533  })
534}
535
536/** The open case in the footer: its title, phenotypes present, evidence rows. */
537export function caseLabel(b: Board): string {
538  const present = (b.phenotypes ?? []).filter(p => p.status === 'present').length
539  return `${clip(b.title, 20)} · HPO ${present} · E${b.evidence_count ?? 0}`
540}
541
542/** The band's three lines while queries run. */
543export function runningLines(runs: readonly ZebraRun[], zh: boolean): [string, string, string] {
544  const first = runs[0] as ZebraRun
545  const query = zh ? first.queryZh : first.queryEn
546  const what = runs.length === 1
547    ? `${labelOf(first.tool, zh)}${query ? `${zh ? ':' : ': '}${query}` : ''}`
548    : (zh ? `${runs.length} 项查询同时进行` : `${runs.length} queries at once`)
549  return [
550    zh ? '🦓 zebra-mod 正在查询公开数据库' : '🦓 zebra-mod is querying public databases',
551    what,
552    `${zh ? '数据源:' : 'sources: '}${sourceNames(runs.flatMap(r => r.sources), zh).join(' · ')}`,
553  ]
554}
555
556/** The band's three lines in the first session after installing, until the first prompt. */
557export function welcomeLines(zh: boolean): [string, string, string] {
558  return zh
559    ? [
560        '🦓 zebra-mod 已就绪 · 罕见病研究工作台',
561        '直接用中文描述症状、检查结果或基因报告,Claude 会调用它查证、计算并标出处。',
562        '先试一下:/zebra demo 打开示例病例 · /zebra 查看全部功能',
563      ]
564    : [
565        '🦓 zebra-mod is ready · rare-disease research workstation',
566        'Just describe symptoms, test results or a genetic report; Claude calls it to look things up, compute and cite.',
567        'Try it: /zebra demo opens a demo case · /zebra shows everything it does',
568      ]
569}
570
571/** The band's three lines after the privacy gate refused a call. */
572export function shieldLines(zh: boolean, isClosed = false): [string, string, string] {
573  if (isClosed) {
574    return [
575      zh ? '🛡 隐私闸门已关闭外发调用' : '🛡 The privacy gate is holding outgoing calls',
576      zh ? '病例的受保护身份信息名单无法读取,调用未发出。' : "The case's list of protected identifiers cannot be read; the call was not sent.",
577      zh ? '修复或重建 case.json,或用 /zebra close 关闭病例后再查询。' : 'Fix or re-create case.json, or /zebra close, then query again.',
578    ]
579  }
580  return [
581    zh ? '🛡 隐私闸门拦下了一次外发调用' : '🛡 The privacy gate stopped an outgoing call',
582    zh ? '调用中含有受保护的身份信息,内容未发出。' : 'It carried a protected identifier; it was not sent.',
583    zh ? '查询公开数据库时只使用 HPO 编号、基因、变异和疾病名称。' : 'Public databases are queried with HPO ids, genes, variants and disease names only.',
584  ]
585}
586
587/** The privacy gate's refusal texts among a tool-result row's blocks (register.tsx words them). */
588export function gateRefusals(content: unknown): string[] {
589  const out: string[] = []
590  const visit = (block: unknown): void => {
591    if (typeof block === 'string') {
592      if (block.startsWith('zebra-mod privacy gate:') && !block.includes('confirm.')) out.push(block)
593      return
594    }
595    if (Array.isArray(block)) return block.forEach(visit)
596    if (!block || typeof block !== 'object') return
597    const b = block as { type?: unknown; text?: unknown; content?: unknown; is_error?: unknown }
598    if (b.type === 'tool_result' && b.is_error !== true) return
599    if (typeof b.text === 'string') visit(b.text)
600    if (b.content !== undefined) visit(b.content)
601  }
602  visit(content)
603  return out
604}
605
606/** The turn's tally after one zebra call answered `answer`. */
607export function recordCall(t: ZebraTurn, tool: string, answer: ToolCallResult | undefined): ZebraTurn {
608  const next: ZebraTurn = { ...t, calls: t.calls + 1, sources: [...t.sources] }
609  if (!answer || 'deny' in answer && answer.deny !== undefined) {
610    next.failed++
611    return next
612  }
613  const env = envelopeOf(answer.result)
614  if (!env) {
615    if ((EXPECTED[tool] ?? []).includes(LOCAL) && !next.sources.includes(LOCAL)) next.sources.push(LOCAL)
616    return next
617  }
618  const d = digest(env)
619  for (const db of d.dbs) if (!next.sources.includes(db)) next.sources.push(db)
620  next.cached += d.cached
621  next.evidence += d.evidence
622  if (d.first !== null) next.firstEvidence = next.firstEvidence === null ? d.first : Math.min(next.firstEvidence, d.first)
623  if (d.last !== null) next.lastEvidence = next.lastEvidence === null ? d.last : Math.max(next.lastEvidence, d.last)
624  return next
625}
626
hooks/privacy.ts 602 lines
1// The privacy gate. Three jobs, each best effort and each said plainly where it is not:
2//   1. keep a case's registered identifiers out of anything that leaves the machine,
3//   2. notice the shell commands and tools that leave the machine at all,
4//   3. notice when a file from the case folder is about to be sent somewhere.
5// Matching happens on a normalised form, because a name reaches a web service
6// percent-encoded, '+'-joined, full-width or re-spaced far more often than verbatim.
7
8const ZERO_WIDTH = /[​-‏‪-‮⁠]/g
9const SEPARATORS = /[\s\-_/.,·'"()[\]{}]+/g
10
11/** Percent-decode, '+'-decode, \uXXXX-decode, NFKC-fold, strip zero-width, lowercase. */
12function fold(text: string): string {
13  let out = text
14  for (let i = 0; i < 3; i++) {
15    const before = out
16    if (/%[0-9a-fA-F]{2}/.test(out)) {
17      try {
18        out = decodeURIComponent(out.replace(/\+/g, ' '))
19      } catch {
20        out = out.replace(/%([0-9a-fA-F]{2})/g, (_m, h) => String.fromCharCode(parseInt(h, 16))).replace(/\+/g, ' ')
21      }
22    }
23    if (/\\u[0-9a-fA-F]{4}/.test(out)) {
24      out = out.replace(/\\u([0-9a-fA-F]{4})/g, (_m, h) => String.fromCharCode(parseInt(h, 16)))
25    }
26    // HTML: a page can spell a name as entities (&#24352;) or split it with tags (<b>张</b>小明)
27    if (/&#?\w+;/.test(out)) {
28      out = out.replace(/&#x([0-9a-f]+);/gi, (_m, h) => String.fromCodePoint(parseInt(h, 16)))
29        .replace(/&#(\d+);/g, (_m, d) => String.fromCodePoint(Number(d)))
30        .replace(/&(amp|lt|gt|quot|apos|nbsp);/g, (_m, n) => ({ amp: '&', lt: '<', gt: '>', quot: '"', apos: "'", nbsp: ' ' } as Record<string, string>)[n] ?? _m)
31    }
32    if (/<\/?[a-z][^<>]{0,200}>/i.test(out)) out = out.replace(/<\/?[a-z][^<>]{0,200}>/gi, '')
33    if (out === before) break
34  }
35  // tone marks (Zhāng Xiǎomíng) and other diacritics never hide a name
36  return out.normalize('NFKD').replace(/\p{M}+/gu, '').normalize('NFKC').replace(ZERO_WIDTH, '').toLowerCase()
37}
38
39// Identifiers of science, not of people: their digits must never be read as a record number
40// (HP:0012345 shares its digits with a record number MZ0012345).
41const SCIENTIFIC_IDS = new RegExp([
42  String.raw`\b(?:hp|omim|mim|orpha|orphanet|mondo|doid|ncit|efo|uberon|go|hgnc|cl|chebi|mp)\s*[:_]\s*\d+`,
43  String.raw`\brs\d+`,
44  String.raw`\b(?:nm|nr|np|nc|ng|nt|xm|xp|enst|ensg|ensp|ccds|lrg)_?\d+(?:\.\d+)?`,
45  String.raw`\bpmid\s*:?\s*\d+`, String.raw`\bpmc\d+`, String.raw`\bnct\d{8}\b`, String.raw`\bchictr-?\w+`,
46  String.raw`\bchr(?:\d{1,2}|x|y|mt?)\s*[:-]\s*[\d,]+(?:\s*[-_]\s*[\d,]+)?`,
47  String.raw`(?<![\w-])(?:\d{1,2}|x|y|mt?)\s*:\s*[\d,]+(?:\s*[-_]\s*[\d,]+)?`,
48  String.raw`\b[cgpnmr]\.\S+`,
49  String.raw`\b10\.\d{4,9}/\S+`,
50].join('|'), 'g')
51
52/** The folded text with separators kept (for word-boundary checks), removed, and digits only. */
53function forms(text: string): { spaced: string; tight: string; digits: string; scrubbed: string } {
54  const folded = fold(text)
55  // scientific identifiers removed: what a record number, a date or an ID number could hide in
56  const scrubbed = folded.replace(SCIENTIFIC_IDS, ' ').replace(/[\s_]+/g, ' ')
57  return {
58    spaced: folded.replace(/[\s_]+/g, ' '),
59    tight: folded.replace(SEPARATORS, ''),
60    digits: scrubbed.replace(/\D+/g, ''),
61    scrubbed,
62  }
63}
64
65const HAS_CJK = /[㐀-鿿豈-﫿]/
66
67const MAX_DEPTH = 12
68const MAX_LEAVES = 5000
69
70/**
71 * Every string in the input: values, and the keys of free-form objects (another server's
72 * `{ data: { "Zhang Wei": 1 } }` carries the name in a key). A key is checked as a whole value,
73 * never joined to its neighbours, so a schema key such as "variant" matches nothing.
74 * Past MAX_DEPTH or MAX_LEAVES the input is too large to read in full: `TOO_DEEP` is returned
75 * among the leaves so the caller refuses instead of passing what it did not read.
76 */
77export const TOO_DEEP = '\u0000zebra:unread'
78function leaves(value: unknown, depth = 0, out: string[] = []): string[] {
79  if (depth > MAX_DEPTH || out.length > MAX_LEAVES) {
80    if (out[out.length - 1] !== TOO_DEEP) out.push(TOO_DEEP)
81    return out
82  }
83  if (typeof value === 'string') out.push(value)
84  else if (Array.isArray(value)) for (const v of value) leaves(v, depth + 1, out)
85  else if (value && typeof value === 'object') {
86    for (const [k, v] of Object.entries(value)) {
87      if (!/^[a-z][a-z0-9_]*$/.test(k)) out.push(k) // a key that is not an identifier-shaped field name
88      leaves(v, depth + 1, out)
89    }
90  } else if (typeof value === 'number' || typeof value === 'boolean') out.push(String(value))
91  return out
92}
93
94const LONG_DIGITS = /\d{6,}/
95// written as one number, or in its 6-8-4 / 6-4-2-2-4 groups; never two separate numbers joined
96const CN_RESIDENT_ID = /(?<![\d])[1-9]\d{5}[ -]?(?:18|19|20)\d{2}[ -]?(?:0[1-9]|1[0-2])[ -]?(?:0[1-9]|[12]\d|3[01])[ -]?\d{3}[\dx](?![\d])/
97// Separators inside are allowed; a letter next to it is not, so rs13812345678 is a variant id
98const CN_MOBILE = /(?<![a-z0-9])(?:\+?0{0,2}86[\s-]?)?1[3-9]\d(?:[\s-]?\d){8}(?![\s-]?\d)(?![a-z0-9])/
99
100const MONTHS = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october',
101  'november', 'december']
102
103/** [year, month, day] readings of a registered date; d/m/y and m/d/y are both kept when ambiguous. */
104function dateParts(identifier: string): Array<[string, number, number]> {
105  const t = identifier.trim()
106  const ymd = /^(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?$/.exec(t)
107  if (ymd) return [[ymd[1] as string, Number(ymd[2]), Number(ymd[3])]]
108  const xy = /^(\d{1,2})[-/.](\d{1,2})[-/.](\d{4})$/.exec(t)
109  if (!xy) return []
110  const a = Number(xy[1])
111  const b = Number(xy[2])
112  return [[xy[3] as string, b, a], [xy[3] as string, a, b]] // day-month-year, month-day-year
113}
114
115/**
116 * Patterns for a registered date in the ways people write one: 2019-03-02, 2019/3/2, 20190302,
117 * 2019年3月2日, 02/03/2019, 3/2/2019, March 2, 2019, 2 Mar 2019. Digit boundaries on both sides,
118 * so the same digits inside a coordinate or another date (12 March) never match.
119 */
120function dateMatchers(identifier: string): RegExp[] {
121  const out: RegExp[] = []
122  for (const [y, m, d] of dateParts(identifier)) {
123    if (m < 1 || m > 12 || d < 1 || d > 31) continue
124    const mo = `0?${m}`
125    const da = `0?${d}`
126    const sep = String.raw`\s*[-/.]\s*`
127    const month = MONTHS[m - 1] as string
128    const name = `(?:${month}|${month.slice(0, 3)}\\.?)`
129    const ord = '(?:st|nd|rd|th)?'
130    const yy = y.slice(2)
131    const loose = String.raw`[\s\-/.,]*`
132    out.push(
133      new RegExp(String.raw`(?<!\d)${y}\s*[-/.年]\s*${mo}\s*[-/.月]\s*${da}(?!\d)`),
134      new RegExp(String.raw`(?<!\d)${y}${String(m).padStart(2, '0')}${String(d).padStart(2, '0')}(?!\d)`),
135      new RegExp(String.raw`(?<!\d)${da}${sep}${mo}${sep}${y}(?!\d)`),
136      new RegExp(String.raw`(?<!\d)${mo}${sep}${da}${sep}${y}(?!\d)`),
137      new RegExp(String.raw`(?<!\d)${yy}[-/.]${mo}[-/.]${da}(?!\d)`), // 19-03-02
138      new RegExp(String.raw`(?<![a-z])${name}${loose}${da}${ord}${loose}${y}(?!\d)`), // March 2, 2019 / Mar-02-2019
139      new RegExp(String.raw`(?<!\d)${da}${ord}${loose}(?:of\s*)?${name}${loose}${y}(?!\d)`), // 2 March 2019 / 02-Mar-2019
140    )
141  }
142  return out
143}
144
145function escapeRe(text: string): string {
146  return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
147}
148
149// Words that put a two-character string in a person's place: 患者张力, 张力先生, 姓名:张力.
150const NAME_BEFORE = /(?:患者|患儿|病人|病儿|姓名|名字|名叫|叫做|先证者|宝宝|孩子|儿子|女儿|同学|小朋友|家长|母亲|父亲|妈妈|爸爸|之子|之女)$/
151const NAME_AFTER = /^(?:[男女](?![性子人])|先生|女士|同学|小朋友|小姐|老师|医生|患者|患儿|宝宝|之子|之女|的(?:父亲|母亲|妈妈|爸爸|家长))/
152const CJK_CHAR = /[㐀-鿿豈-﫿]/
153
154/**
155 * A two-character Chinese name in `text`: 'name' where it stands as a name (bounded by anything
156 * that is not a Chinese character, or by a word that puts a person there: 患者张力,男), 'embedded'
157 * where it occurs only inside a longer Chinese run (肌张力减退 for a patient called 张力), else null.
158 * Spaces, dots and hyphens between Chinese characters are dropped first, so 张 力 and 张·力 are 张力.
159 */
160function shortCjkName(name: string, spaced: string): 'name' | 'embedded' | null {
161  const text = spaced.replace(/(?<=[㐀-鿿豈-﫿])[\s\-_.·]+(?=[㐀-鿿豈-﫿])/g, '')
162  let found: 'embedded' | null = null
163  for (let at = text.indexOf(name); at >= 0; at = text.indexOf(name, at + 1)) {
164    const before = text.slice(0, at)
165    const after = text.slice(at + name.length)
166    const openLeft = !CJK_CHAR.test(before.slice(-1)) || NAME_BEFORE.test(before)
167    const openRight = !CJK_CHAR.test(after.slice(0, 1)) || NAME_AFTER.test(after)
168    if (openLeft && openRight) return 'name'
169    found = 'embedded'
170  }
171  return found
172}
173
174/** What the gate found: `deny` must not leave; `ask` may be an ordinary word and needs a person to say. */
175export type GuardHit = { level: 'deny' | 'ask'; what: string }
176
177/**
178 * What in `input` must not leave the machine, described without repeating it.
179 * `identifiers` are the case's registered strings (names, dates of birth, record numbers).
180 * Only the hits that must be refused; `guardCheck` also returns the ones to ask about.
181 */
182export function guardInput(input: unknown, identifiers: readonly string[]): string | undefined {
183  const hit = guardCheck(input, identifiers)
184  return hit?.level === 'deny' ? hit.what : undefined
185}
186
187/**
188 * Like `guardInput`, with one more answer: a registered two-character Chinese name found only
189 * inside a longer Chinese word (张力 in 肌张力, 王海 in 王海燕) is `ask`, not `deny` — the same two
190 * characters are often a medical term. Two such hits from different identifiers, or one beside any
191 * refused identifier, are `deny`.
192 */
193export function guardCheck(input: unknown, identifiers: readonly string[]): GuardHit | undefined {
194  const all = leaves(input)
195  if (all.includes(TOO_DEEP)) return { level: 'deny', what: 'more nested data than the gate can read in full' }
196  const values = all.filter(v => !isLocalPath(v))
197  if (values.length === 0) return undefined
198  const embedded: string[] = []
199  // Each value is folded on its own: digits or letters from two unrelated values
200  // (an MRN and an HPO id next to it) must never join into a match.
201  const folded = values.map(forms)
202
203  for (let i = 0; i < identifiers.length; i++) {
204    const raw = (identifiers[i] ?? '').trim()
205    if (!raw) continue
206    const label = `protected identifier #${i + 1} from the case`
207    const id = forms(raw)
208    // A short number (a year, a floor, an age) identifies nobody and would block
209    // ordinary queries; a record number is longer. Dates are handled below.
210    if (/^\d+$/.test(id.tight) && id.tight.length < 6) continue
211    const dates = dateMatchers(raw)
212    const tokens = id.spaced.split(' ').filter(t => t.length >= 2)
213
214    for (const f of folded) {
215      // a date of birth, however it is written
216      if (dates.some(re => re.test(f.scrubbed))) return { level: 'deny', what: label }
217      // a record or ID number: digits only, so separators cannot hide it
218      // (not for a date: its digits joined across a value's other numbers would match by accident)
219      if (dates.length === 0 && LONG_DIGITS.test(id.digits) && f.digits.includes(id.digits)) return { level: 'deny', what: label }
220      // a number-only identifier is matched by its digits alone (a PMID or rsID with the same digits is not it)
221      if (/^\d+$/.test(id.tight)) continue
222      if (HAS_CJK.test(raw)) {
223        // Chinese names: spacing carries no meaning. Three characters or more identify anywhere;
224        // two identify where they stand as a name, and are asked about inside a longer word.
225        if (id.tight.length >= 3 && f.tight.includes(id.tight)) return { level: 'deny', what: label }
226        if (id.tight.length === 2 && [...id.tight].every(c => CJK_CHAR.test(c))) {
227          const seen = shortCjkName(id.tight, f.spaced)
228          if (seen === 'name') return { level: 'deny', what: label }
229          if (seen === 'embedded' && !embedded.includes(label)) embedded.push(label)
230        } else if (id.tight.length >= 2 && f.tight.includes(id.tight)) return { level: 'deny', what: label }
231        continue
232      }
233      // every token present as a whole word, in any order ("Xiaoming Zhang" too)
234      if (tokens.length > 1 && tokens.every(t => wordIn(t, f.spaced))) return { level: 'deny', what: label }
235      if (id.tight.length >= 3) {
236        if (wordIn(id.tight, f.spaced)) return { level: 'deny', what: label }
237        if (tokens.length <= 1 && id.tight.length >= 6 && f.tight.includes(id.tight)) return { level: 'deny', what: label }
238      }
239    }
240  }
241
242  // Patterns that identify a person even when no case is open, checked per value.
243  for (const f of folded) {
244    if (CN_RESIDENT_ID.test(f.scrubbed)) return { level: 'deny', what: 'what looks like a Chinese resident ID number' }
245    if (CN_MOBILE.test(f.scrubbed)) return { level: 'deny', what: 'what looks like a mobile phone number' }
246    if (emailIn(f.spaced)) return { level: 'deny', what: 'an email address' }
247  }
248  // two registered names each inside a word (a name and its other spelling, two relatives) point to a person
249  if (embedded.length >= 2) return { level: 'deny', what: embedded.join(' and ') }
250  if (embedded.length === 1) return { level: 'ask', what: `${embedded[0]} (two Chinese characters, here inside a longer word)` }
251  return undefined
252}
253
254/** An email address in `text` that is not a host login (ssh user@host) or a git remote. */
255function emailIn(text: string): boolean {
256  // anchored at each '@' and bounded on both sides: a 200 kB sequence without one costs nothing
257  for (let at = text.indexOf('@'); at >= 0; at = text.indexOf('@', at + 1)) {
258    const left = /[a-z0-9._%+-]{1,64}$/.exec(text.slice(Math.max(0, at - 64), at))
259    const right = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*\.[a-z]{2,24}/.exec(text.slice(at + 1, at + 256))
260    if (!left || !right) continue
261    const addr = `${left[0]}@${right[0]}`
262    const m = { index: at - left[0].length }
263    if (/^git@/.test(addr) || /@(?:github|gitlab|bitbucket)\.(?:com|org)$/.test(addr)) continue
264    const before = text.slice(Math.max(0, m.index - 400), m.index)
265    if (/\b(?:ssh|scp|sftp|rsync|mosh|ssh-copy-id|autossh)\b[^;|&]*$/.test(before)) continue
266    return true
267  }
268  return false
269}
270
271function wordIn(word: string, text: string): boolean {
272  return new RegExp(`(?:^|[^a-z0-9])${escapeRe(word)}(?:[^a-z0-9]|$)`).test(text)
273}
274
275/** A bare local path (a case folder, a records file): its text never leaves the machine by itself. */
276export function isLocalPath(value: string): boolean {
277  const v = value.trim()
278  if (!v || /\s/.test(v) || v.includes('://') || /[?=&#]/.test(v)) return false
279  return /^(?:~|\$HOME|\.{1,2})?\//.test(v) || /^[A-Za-z]:\\/.test(v)
280}
281
282// ---------------------------------------------------------------- shell commands
283
284const NETWORK_TOOL =
285  /\b(?:curl|wget|nc|ncat|socat|telnet|scp|sftp|rsync|ssh|mosh|ftp|lftp|gh|glab|aws|gsutil|azcopy|rclone|mail|mailx|sendmail|mutt|osascript|dig|nslookup|host|s2f|httpie|http|xh|aria2c)\b|\bgit\s+(?:push|clone|fetch|pull|remote|ls-remote)\b|\b(?:npm|pnpm|yarn)\s+(?:publish|install|i|add)\b|\bnpx\b|\bpip3?\s+install\b|https?:\/\/|\/dev\/(?:tcp|udp)\/|\bopen\b[^|;&]*\b(?:mailto|https?):|\bdocker\s+(?:run|push|exec)\b|\b(?:Invoke-WebRequest|Invoke-RestMethod|iwr|irm)\b/i
286const SCRIPT_RUN = /\bpython3?(?:\.\d+)?\b|\bnode\b|\bdeno\b|\bbun\b|\bruby\b|\bperl\b|\bphp\b|\blua\b|\bjulia\b|\bjava\b|\bRscript\b|\bR\s+(?:-e|--vanilla|-f)\b|\buvx?\b|\bpipx\s+run\b|\b(?:pwsh|powershell)\b/
287const ZEBRA_CLI = /(?:^|[\s;&|(/])zebra(?![\w-])/
288// `zebra case …` reads and writes the local case only (its HPO checks send ids, never text),
289// so it stays usable while the gate is closed and its arguments are not outbound content.
290// Only when those are the leading words of the segment, as the shell will read them.
291function isZebraLocal(segment: string): boolean {
292  const w = shellWords(segment)
293  let i = 0
294  while (i < w.length && /^[A-Za-z_][A-Za-z0-9_]*=/.test(w[i] as string)) i++ // VAR=value prefixes
295  if (/(?:^|\/)python3?(?:\.\d+)?$/.test(w[i] ?? '')) i++
296  if (!/(?:^|\/)zebra$/.test(w[i] ?? '')) return false
297  i++
298  while (i < w.length) {
299    const a = w[i] as string
300    if (a === '--json') i++
301    else if (a === '--case') i += 2
302    else if (a.startsWith('--case=')) i++
303    else break
304  }
305  // `case <action>` reads and writes the case; `case recheck` asks public databases again.
306  // No readable action (`zebra case $(…)`) is not local. `report export` writes files here only.
307  const action = w[i + 1] ?? ''
308  if (w[i] === 'case') return /^[a-z][a-z-]*$/.test(action) && action !== 'recheck'
309  return w[i] === 'report' && action === 'export'
310}
311
312/** The words of a zebra invocation in this segment, from the subcommand on; null when it is not zebra. */
313function zebraWords(segment: string): string[] | null {
314  const w = shellWords(segment)
315  const i = w.findIndex(a => /(?:^|\/)zebra$/.test(a))
316  return i < 0 ? null : w.slice(i + 1)
317}
318// flags whose values stay on this machine in any zebra command (sample names, file paths)
319const ZEBRA_LOCAL_FLAGS = new Set(['--case', '--proband', '--mother', '--father', '--sibling', '--out', '--genes',
320  '--ped', '--csv', '--workspace', '--vcf'])
321
322/** Split a command into the pieces that run on their own, so one exempt piece cannot cover the rest. */
323export function shellSegments(command: string): string[] {
324  const out: string[] = []
325  let depth = 0
326  let current = ''
327  let quote: '"' | "'" | null = null
328  for (let i = 0; i < command.length; i++) {
329    const c = command[i] as string
330    const two = command.slice(i, i + 2)
331    // inside quotes, ; & | and newlines are text (curl "…?a=1&b=2"), not separators
332    if (quote) {
333      if (c === '\\' && quote === '"' && i + 1 < command.length) {
334        current += c + command[++i]
335        continue
336      }
337      if (c === quote) quote = null
338      current += c
339      continue
340    }
341    if (c === '"' || c === "'") {
342      quote = c
343      current += c
344      continue
345    }
346    if (c === '`') {
347      // a backtick substitution runs on its own
348      if (current.trim()) out.push(current)
349      current = ''
350      continue
351    }
352    if (two === '$(' || two === '<(' || two === '>(') {
353      depth++
354      i++
355      if (current.trim()) out.push(current)
356      current = ''
357      continue
358    }
359    if (c === ')' && depth > 0) {
360      depth--
361      if (current.trim()) out.push(current)
362      current = ''
363      continue
364    }
365    if (two === '&&' || two === '||') {
366      i++
367      if (current.trim()) out.push(current)
368      current = ''
369      continue
370    }
371    if (c === ';' || c === '|' || c === '&' || c === '\n') {
372      if (current.trim()) out.push(current)
373      current = ''
374      continue
375    }
376    current += c
377  }
378  if (current.trim()) out.push(current)
379  return out
380}
381
382/**
383 * A segment as the shell will read it: quotes removed and words rejoined, so `c'u'rl` and
384 * `"cu""rl"` read as curl, and the text of `bash -c "…"` or `eval "…"` is seen as the command it is.
385 */
386function asRun(segment: string): string {
387  return shellWords(segment).join(' ')
388}
389
390function outboundSegment(segment: string): boolean {
391  if (isZebraLocal(segment)) return false // the local case only
392  for (const text of [segment, asRun(segment)]) {
393    if (NETWORK_TOOL.test(text)) return true
394    if (ZEBRA_CLI.test(text)) return true // zebra's other commands query public databases
395    if (SCRIPT_RUN.test(text)) return true // a script can reach the network; its source is not read here
396  }
397  // `bash -c "…"`, `sh -c`, `eval`: judge the inner command the same way
398  const w = shellWords(segment)
399  const inner = /^(?:ba|z|da|k)?sh$|^eval$/.test(w[0] ?? '') ? w.slice(1).filter(a => a !== '-c').join(' ') : ''
400  return inner !== '' && inner !== segment && isOutboundShell(inner)
401}
402
403/** True when a shell command runs the zebra CLI anywhere in it (which reads the active case). */
404export function invokesZebra(command: string): boolean {
405  return shellSegments(command).some(seg => ZEBRA_CLI.test(seg) || ZEBRA_CLI.test(asRun(seg)))
406}
407
408/** True when a shell command may send data off the machine. Judged per segment. */
409export function isOutboundShell(command: string): boolean {
410  return shellSegments(command).some(outboundSegment)
411}
412
413/**
414 * The text of a shell command that may reach the network. Once any part of it does, every part is
415 * scanned — a pipe (echo … | curl), a heredoc, a variable set before the call or a script's source
416 * all carry text to the outbound piece — except what demonstrably stays here: segments that only
417 * touch the local case, the values of zebra's local-only flags (sample names, case paths) inside
418 * zebra commands, local paths, and the folder given to `cd`.
419 */
420export function outboundText(command: string): string {
421  const segments = shellSegments(command)
422  if (!segments.some(outboundSegment)) return ''
423  const kept: string[] = []
424  for (const segment of segments) {
425    if (isZebraLocal(segment)) continue
426    const words = shellWords(segment)
427    const zebra = zebraWords(segment) !== null
428    if (words[0] === 'cd') continue
429    for (let i = 0; i < words.length; i++) {
430      const w = words[i] as string
431      if (zebra && ZEBRA_LOCAL_FLAGS.has(w)) {
432        i++
433        continue
434      }
435      if (zebra && /^--[\w-]+=/.test(w) && ZEBRA_LOCAL_FLAGS.has(w.split('=')[0] as string)) continue
436      if (isLocalPath(w)) continue
437      kept.push(w)
438    }
439  }
440  return kept.join(' ')
441}
442
443const GENOME_FILE = /\.(?:g?vcf(?:\.gz|\.bgz)?|bcf|bam|cram|sam|fastq(?:\.gz)?|fq(?:\.gz)?|bed(?:\.gz)?)(?![a-z0-9])/i
444const UPLOADER =
445  /\b(?:scp|sftp|rclone|gsutil|azcopy)\b|\baws\s+s3\b|\bgh\s+(?:gist|release)\s+\w+|\brsync\b[^|;&]*\S+:\S*|\bcurl\b[^|;&]*(?:\s-T\b|--upload-file|\s-F\b|--form|--data-binary|\s-d\s*@|--data(?:-raw|-urlencode)?\s*@)|\bwget\b[^|;&]*--post-file|\b(?:nc|ncat|socat)\b|\bssh\b[^|;&]*\bcat\s*>|\bmail(?:x)?\b|\bpython3?\s+-m\s+http\.server\b/i
446
447// folders a desktop client uploads on its own: copying a file there sends it
448const SYNC_FOLDER = /(?:^|[\s'"=])(?:~|\$HOME|\/Users\/[^/\s]+|\/home\/[^/\s]+)?\/?(?:Dropbox|Google Drive|GoogleDrive|My Drive|OneDrive[^/\s]*|Library\/Mobile Documents|Library\/CloudStorage|iCloud Drive|Nutstore[^/\s]*|坚果云[^/\s]*|BaiduNetdisk[^/\s]*|百度网盘[^/\s]*|WeDrive[^/\s]*|Box Sync|pCloud Drive|MEGA)(?:\/|['"\s]|$)/i
449const COPY_INTO = /\b(?:cp|mv|rsync|ditto|ln|install|tee)\b/
450
451/** True when a zebra command would send a whole VCF's variant list to a web service (triage's MyVariant prefilter). */
452export function sendsVariantList(command: string): boolean {
453  // argparse accepts any unique prefix of a long option: --pref myvariant, --pre=myvariant
454  const isFlag = (a: string) => a.length >= 5 && '--prefilter'.startsWith(a)
455  return shellSegments(command).some(seg => {
456    const rest = zebraWords(seg)
457    if (!rest) return false
458    return rest.some((a, i) => {
459      const [flag, value] = a.includes('=') ? [a.slice(0, a.indexOf('=')), a.slice(a.indexOf('=') + 1)] : [a, rest[i + 1]]
460      return isFlag(flag) && value === 'myvariant'
461    })
462  })
463}
464
465/** True when a command looks like it sends a raw genome file to another machine. */
466export function uploadsGenome(command: string): boolean {
467  if (GENOME_FILE.test(command) && UPLOADER.test(command)) return true
468  // copying genome data into a synced folder uploads it as surely as scp
469  if (GENOME_FILE.test(command) && COPY_INTO.test(command) && SYNC_FOLDER.test(command)) return true
470  // an archive that holds genome data, then sent: zip -r g.zip genome/ && curl -F f=@g.zip …
471  const archive = /\b(?:zip|7z|7za|tar|gzip|bgzip|xz|zstd)\b[^|;&]*?([\w.-]+\.(?:zip|7z|tar(?:\.gz|\.bz2|\.xz|\.zst)?|tgz|gz))\b/i.exec(command)
472  if (archive && (GENOME_FILE.test(command) || /\b(?:genome|exome|wes|wgs|vcf|bam|cram|fastq)s?\b/i.test(command)) && UPLOADER.test(command)) return true
473  const segments = shellSegments(command)
474  if (segments.some(s => GENOME_FILE.test(s)) && segments.some(s => UPLOADER.test(s))) return true
475  // a whole directory going out (scp -r genome_dir host:, tar czf - dir | ssh)
476  return /\bscp\s+-r\b|\btar\b[^|;&]*\bc/.test(command) && /\b(?:ssh|scp|rclone)\b|\baws\s+s3\b/.test(command)
477}
478
479const FILE_ARGS: RegExp[] = [
480  /--(?:upload-file|post-file)[=\s]+("[^"]+"|'[^']+'|\S+)/gi,
481  /\s-T\s*("[^"]+"|'[^']+'|\S+)/gi,
482  /(?:--data-binary|--data-urlencode|--data-raw|--data|-d|-F|--form)\s*(?:[^@\s]*@)("[^"]+"|'[^']+'|[^\s;|&]+)/gi,
483  /<\s*("[^"]+"|'[^']+'|[^\s;|&]+)/g,
484]
485// commands whose non-option, non-remote arguments are local files being sent
486const COPY_TOOLS = /^(?:scp|sftp|rsync|rclone|gsutil|azcopy)$/
487const REMOTE_ARG = /^(?:[\w.-]+@)?[\w.-]+:(?!\/\/)|^(?:s3|gs|az|https?):\/\/|^[\w-]+:$/
488
489/**
490 * The local file paths a command would send somewhere, relative paths resolved against a
491 * preceding `cd` in the same command, so the caller can check whether they lie in the case folder.
492 */
493export function uploadedPaths(command: string): string[] {
494  const found = new Set<string>()
495  // a file copied into a synced folder is uploaded by the desktop client
496  for (const segment of shellSegments(command)) {
497    const w = shellWords(segment)
498    if (COPY_INTO.test(w[0] ?? '') && w.length >= 3 && SYNC_FOLDER.test(` ${w[w.length - 1]}`)) {
499      for (const a of w.slice(1, -1)) if (!a.startsWith('-')) found.add(a)
500    }
501  }
502  let cwd = ''
503  const segments = shellSegments(command)
504  const join = (p: string) => (cwd && !/^(?:\/|~|\$HOME)/.test(p) ? `${cwd.replace(/\/$/, '')}/${p}` : p)
505  // files read on the left of a pipe that ends in an uploader reading stdin
506  const pipeReaders: string[] = []
507  const archived: string[] = []
508  const scripted = SCRIPT_RUN.test(command)
509  for (const segment of segments) {
510    const words = shellWords(segment)
511    const head = words[0] ?? ''
512    if (head === 'cd' && words[1]) {
513      cwd = words[1]
514      continue
515    }
516    if (/^(?:cat|zcat|gzip|bgzip|tar|base64|xxd|head|tail)$/.test(head)) {
517      for (const w of words.slice(1)) if (!w.startsWith('-')) pipeReaders.push(join(w))
518    }
519    for (const re of FILE_ARGS) {
520      re.lastIndex = 0
521      let m: RegExpExecArray | null
522      while ((m = re.exec(segment)) !== null) {
523        const capture = m[1] ?? ''
524        const parts = /^['"]/.test(capture) ? [capture] : capture.split(/\s+/)
525        for (const part of parts) {
526          const clean = part.replace(/^['"]|['"]$/g, '')
527          if (clean === '-') pipeReaders.forEach(r => found.add(r))
528          else if (clean && !/^https?:/.test(clean)) found.add(join(clean))
529        }
530      }
531    }
532    if (/^(?:zip|7z|7za|tar)$/.test(head)) {
533      // what goes into an archive leaves with it: zip -r out.zip ~/cases/x, tar czf out.tgz -C ~/cases x
534      let base = ''
535      for (let k = 1; k < words.length; k++) {
536        const a = words[k] as string
537        if (a === '-C' && words[k + 1]) {
538          base = words[++k] as string
539          continue
540        }
541        if (a.startsWith('-') || /\.(?:zip|7z|tar|tgz|gz|bz2|xz|zst)$/.test(a)) continue
542        archived.push(base && !/^(?:\/|~|\$HOME)/.test(a) ? `${base.replace(/\/$/, '')}/${a}` : join(a))
543      }
544    }
545    if (scripted && zebraWords(segment) === null) {
546      // a script that opens a file from the case folder sends its contents: python -c "…open('…')…",
547      // or a heredoc body; only paths that start a word (not the tail of records/x or host:/tmp)
548      for (const m of segment.replace(/https?:\/\/\S+/g, ' ').matchAll(/(?<=^|[\s'"=(,])(?:~|\$HOME)?\/[^\s'"<>|;&(),]{2,}/g)) found.add(m[0])
549    }
550    if (head === 'gh' && words[1] === 'release' && words[2] === 'upload') {
551      for (const w of words.slice(4)) if (!w.startsWith('-')) found.add(join(w))
552    }
553    if (COPY_TOOLS.test(head) || (head === 'aws' && words[1] === 's3') || (head === 'gh' && words[1] === 'gist')) {
554      const args = words.slice(head === 'aws' || head === 'gh' ? 3 : 1)
555      for (const w of args) {
556        if (w.startsWith('-') || REMOTE_ARG.test(w)) continue
557        found.add(join(w))
558      }
559    }
560  }
561  // the archive's sources count once anything in the command sends something somewhere
562  if (archived.length && (UPLOADER.test(command) || segments.some(outboundSegment))) archived.forEach(a => found.add(a))
563  return [...found]
564}
565
566/** A tiny shell-words splitter, so `/zebra new "my case" A title` works. */
567export function shellWords(text: string): string[] {
568  const out: string[] = []
569  let current = ''
570  let quote: '"' | "'" | null = null
571  let started = false
572  for (let i = 0; i < text.length; i++) {
573    const c = text[i] as string
574    if (quote) {
575      if (c === quote) quote = null
576      else if (c === '\\' && quote === '"' && i + 1 < text.length) current += text[++i]
577      else current += c
578      continue
579    }
580    if (c === '"' || c === "'") {
581      quote = c as '"' | "'"
582      started = true
583      continue
584    }
585    if (c === '\\' && i + 1 < text.length) {
586      current += text[++i]
587      started = true
588      continue
589    }
590    if (/\s/.test(c)) {
591      if (current || started) out.push(current)
592      current = ''
593      started = false
594      continue
595    }
596    current += c
597    started = true
598  }
599  if (current || started) out.push(current)
600  return out
601}
602
hooks/ui-sprite.ts 163 lines
1// The galloping zebra drawn in the band above the prompt while zebra-mod queries a database.
2// Eleven positions of one gallop stride, traced from Eadweard Muybridge's "The Horse in Motion" (1878,
3// public domain): rider removed, frames aligned on the back (croup to withers) so the body stays
4// level while the legs move, given zebra stripes, drawn in braille (2 x 4 dots to a terminal cell). Regenerate with
5// `python3 tools/zebra_sprite/build.py`. One colour, the terminal's own text colour, so the zebra reads
6// on light and dark themes alike; the ground is a dim dotted line that runs backwards.
7// Pure functions of (frame, scroll): no state here.
8
9const FRAMES: readonly (readonly string[])[] = [
10  [
11    '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⢠⡴⣟⣶⣤⡀⠀',
12    '⠀⠀⠀⠀⢀⣀⢠⣤⡖⣤⢠⣤⡆⣶⣾⡟⣵⡏⠉⠉⠁⠀',
13    '⠀⠈⠷⠾⠛⠁⢻⡟⣼⣿⢸⣿⡇⣿⢏⣾⠟⠀⠀⠀⠀⠀',
14    '⠀⠀⠀⠀⠀⡟⢟⠘⠋⠈⠘⠛⠃⢻⡿⠟⠀⠀⠀⠀⠀⠀',
15    '⠀⠀⠀⠀⠴⠃⠀⠱⠀⠀⠒⠦⠤⠟⠀⠀⠀⠀⠀⠀⠀⠀',
16    '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀',
17  ],
18  [
19    '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣰⣾⣳⣦⣀⠀⠀',
20    '⠀⠀⠀⠀⠀⠀⢀⣤⣶⣤⢠⣤⡄⣦⣿⡟⣽⠉⠉⠙⠀⠀',
21    '⠀⢴⣤⡶⠟⠁⢿⡟⣼⣿⢸⣿⡇⣿⢏⣾⠃⠀⠀⠀⠀⠀',
22    '⠀⠀⠉⠀⠀⠀⢀⣼⣿⠏⠘⠛⠃⣧⢿⡋⠀⠀⠀⠀⠀⠀',
23    '⠀⠀⠀⠀⠀⠀⠀⠈⢻⢓⣢⣀⡼⠳⠔⠛⠀⠀⠀⠀⠀⠀',
24    '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀',
25  ],
26  [
27    '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣤⡿⢶⣤⡀⠀⠀',
28    '⠀⠀⠀⠀⠀⠀⢀⣴⣶⣦⢠⣤⡄⣦⣿⡟⡵⠉⠉⠋⠀⠀',
29    '⠀⢠⣤⠾⠛⠃⢿⡟⣼⣿⢸⣿⡇⣿⢏⣾⠃⠀⠀⠀⠀⠀',
30    '⠀⠀⠁⠀⠀⠀⠀⢨⣿⣿⠘⠛⠇⣧⠿⠟⣄⠀⠀⠀⠀⠀',
31    '⠀⠀⠀⠀⠀⠀⠀⠈⠉⠙⠛⠦⡤⠏⠰⠖⠁⠀⠀⠀⠀⠀',
32    '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀',
33  ],
34  [
35    '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣠⡷⡶⣤⡀⠀⠀',
36    '⠀⠀⠀⠀⠀⠀⢀⣤⣤⣤⢠⣤⡄⣦⣿⡟⣵⠛⠛⠿⠂⠀',
37    '⠀⢀⣴⠿⠻⠃⢿⡟⣼⣿⢸⣿⡇⣿⢏⣾⡇⠀⠀⠀⠀⠀',
38    '⠀⠙⠁⠀⠀⠀⠈⠘⢿⣿⠸⠿⠇⠧⣿⣟⠔⢲⠀⠀⠀⠀',
39    '⠀⠀⠀⠀⠀⠀⠀⠀⠘⢿⡓⠒⠦⠜⠶⠚⠁⠸⠀⠀⠀⠀',
40    '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢙⣦⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀',
41  ],
42  [
43    '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣄⡶⡶⣦⡀⠀⠀',
44    '⠀⠀⠀⢀⣀⣀⢀⣤⣤⣤⢠⣤⡄⣦⣿⡟⣵⠋⠛⠻⠂⠀',
45    '⠀⢠⣾⠟⠛⠁⣿⡟⣼⣿⢸⣿⡇⣿⢏⣾⡇⠀⠀⠀⠀⠀',
46    '⠀⠋⠁⠀⠀⠀⠈⣼⠟⢿⡘⠛⠃⠧⠟⠛⢼⠿⢄⡀⠀⠀',
47    '⠀⠀⠀⠀⠀⠀⠰⡏⠀⠈⠙⠢⢤⡀⠀⠘⠋⠀⠀⠙⠀⠀',
48    '⠀⠀⠀⠀⠀⠀⠀⠳⠤⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀',
49  ],
50  [
51    '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡦⣣⡷⣄⠀⠀',
52    '⠀⠀⠀⣀⣀⣀⢀⣤⡄⣤⢠⣤⡄⣶⣾⡟⣵⠟⠙⠻⠷⠀',
53    '⠀⣴⠟⠋⠉⢡⣿⡟⣼⣿⢸⣿⡇⣿⣏⣾⡏⠀⠀⠀⠀⠀',
54    '⠀⠁⠀⠀⢀⣠⠟⠘⣿⠉⠘⠛⠃⠛⠛⠛⠸⢿⡇⠀⠀⠀',
55    '⠀⠀⠀⢀⡞⠁⠀⠀⠻⡀⠀⠀⠀⠀⠀⠀⠀⠐⠋⠓⠦⠄',
56    '⠀⠀⠀⠸⠷⠀⠀⠀⠀⠹⠶⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀',
57  ],
58  [
59    '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣠⡰⣠⡶⣄⠀⠀',
60    '⠀⠀⠀⠀⣀⣀⢠⣤⣤⣤⢀⣤⡄⣶⣾⡟⣵⠟⠙⠻⠷⠀',
61    '⠤⠾⠛⠋⠉⢠⣿⡟⣼⣿⢸⣿⡇⣿⢏⣾⡏⠀⠀⠀⠀⠀',
62    '⠀⠀⠀⣠⡠⣾⡟⠈⠉⠉⠘⠛⠃⠛⠛⠛⣜⠛⠒⢤⡀⠀',
63    '⠠⠤⠞⠁⢰⠏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⢧⡀⠀⠙⠂',
64    '⠀⠀⠀⠀⠘⠓⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠑⠂⠀⠀',
65  ],
66  [
67    '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣀⡴⣣⣶⣄⠀⠀',
68    '⠀⠀⠀⠀⣀⡤⢠⣤⣤⣤⢠⣤⡄⣶⣾⡟⣵⡿⠛⠺⠷⠀',
69    '⠛⠻⠟⠛⠉⢠⣿⡟⣼⣿⢸⣿⡇⣿⣏⣾⡿⠀⠀⠀⠀⠀',
70    '⠀⢀⣠⠴⣢⡿⠛⠈⠀⠉⠘⠛⠃⠛⠻⡟⠘⠷⣤⡀⠀⠀',
71    '⠉⠉⢀⡔⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⣧⠀⠀⠀⠈⠉⠋',
72    '⠀⠀⠉⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⠂⠀⠀⠀⠀⠀',
73  ],
74  [
75    '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⢠⡰⣲⢶⣄⠀⠀',
76    '⢀⢀⠀⢀⣠⣤⢠⣤⣤⣤⢠⣤⡄⣶⣾⡟⣵⡿⠛⠻⠷⠀',
77    '⠈⠛⠛⠛⠉⢠⣿⡟⣼⣿⢸⣿⡇⣿⢏⣾⡟⠁⠀⠀⠀⠀',
78    '⠀⠀⢀⣼⡧⠟⠛⠈⠁⠉⠘⠛⠇⣿⠿⠛⢴⡄⠀⠀⠀⠀',
79    '⠀⠛⠋⠁⠀⠀⠀⠀⠀⠀⠀⠀⡰⠋⠀⠀⠀⠙⢢⡀⠀⠀',
80    '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⠃⠀⠀⠀⠀⠀⠀⠉⠋⠀',
81  ],
82  [
83    '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⢀⡠⣞⣶⣄⠀⠀',
84    '⠀⢀⡀⢀⣀⣤⢠⣴⡖⣤⢠⣤⡆⣶⣾⡟⣵⡟⠙⠛⠃⠀',
85    '⠀⠀⠻⠟⠋⠁⣿⡟⣼⣿⢸⣿⡇⣿⢏⣾⠏⠀⠀⠀⠀⠀',
86    '⠀⠀⠀⢀⠞⢻⠛⠘⠉⠈⠘⠛⠃⣿⣿⠋⠀⠀⠀⠀⠀⠀',
87    '⠀⠀⠈⠉⠀⠰⠁⠀⠀⠀⠀⠀⠼⠁⠿⠀⠀⠀⠀⠀⠀⠀',
88    '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀',
89  ],
90  [
91    '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⢠⡴⣞⣶⣄⠀⠀',
92    '⠀⠀⡀⣀⣀⣀⢀⣤⡄⣤⢠⣤⡄⣶⣾⡟⣵⡟⠙⠛⠃⠀',
93    '⠀⠘⠿⠿⠟⠃⢹⡟⣼⣿⢸⣿⡇⣿⢏⣾⡟⠀⠀⠀⠀⠀',
94    '⠀⠀⠀⠀⠀⠐⢞⣼⠟⠉⠘⠛⠃⣿⡿⠟⠀⠀⠀⠀⠀⠀',
95    '⠀⠀⠀⠀⠀⠀⠈⡏⠙⢢⠀⣀⠿⠿⠇⠀⠀⠀⠀⠀⠀⠀',
96    '⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠘⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀',
97  ],
98]
99
100const DEFAULT = 0x01000000 // the terminal's own colour
101const GROUND = 0x6e6c64
102const SPRITE_COLS = 22
103const STANDING = 5 // the pose shown still (the welcome card, the shield)
104
105/** Columns and rows of the zebra's Raster: the sprite with a little ground before and behind it. */
106export const RASTER_COLUMNS = 28
107export const RASTER_ROWS = 6
108export const FRAME_COUNT = FRAMES.length
109const OFFSET = 3
110
111/** The braille dot bits of the cell at (col, row): the zebra's, then the ground's in the lowest dot row. */
112function cell(frame: number, scroll: number, col: number, row: number, isStanding: boolean): { horse: number; ground: number } {
113  const rows = FRAMES[isStanding ? STANDING : frame % FRAMES.length] as readonly string[]
114  const sc = col - OFFSET
115  const ch = sc >= 0 && sc < SPRITE_COLS ? (rows[row] as string).codePointAt(sc) ?? 0x2800 : 0x2800
116  const horse = ch - 0x2800
117  let ground = 0
118  if (row === RASTER_ROWS - 1) {
119    // dot 7 (left column, bottom) and dot 8 (right column, bottom), one in every six dots
120    const s = isStanding ? 0 : scroll
121    if ((col * 2 + s) % 6 === 0) ground |= 0x40
122    if ((col * 2 + 1 + s) % 6 === 0) ground |= 0x80
123  }
124  return { horse, ground }
125}
126
127/** The Raster `cells` of one frame: braille dots in the terminal's colour, the ground dimmed. */
128export function zebraCells(frame: number, scroll: number, isStanding = false): string {
129  const words = new Uint32Array(RASTER_COLUMNS * RASTER_ROWS * 3)
130  let i = 0
131  for (let row = 0; row < RASTER_ROWS; row++) {
132    for (let col = 0; col < RASTER_COLUMNS; col++) {
133      const { horse, ground } = cell(frame, scroll, col, row, isStanding)
134      const bits = horse | ground
135      words[i++] = bits ? 0x2800 + bits : 0x20
136      words[i++] = horse ? DEFAULT : ground ? GROUND : DEFAULT
137      words[i++] = DEFAULT
138    }
139  }
140  return base64(new Uint8Array(words.buffer))
141}
142
143const B64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
144
145/** Standard padded base64 (the module runs with no Node and no DOM, so no Buffer or btoa to lean on). */
146export function base64(bytes: Uint8Array): string {
147  let out = ''
148  let i = 0
149  for (; i + 2 < bytes.length; i += 3) {
150    const n = ((bytes[i] as number) << 16) | ((bytes[i + 1] as number) << 8) | (bytes[i + 2] as number)
151    out += B64[(n >> 18) & 63]! + B64[(n >> 12) & 63]! + B64[(n >> 6) & 63]! + B64[n & 63]!
152  }
153  const rest = bytes.length - i
154  if (rest === 1) {
155    const n = (bytes[i] as number) << 16
156    out += B64[(n >> 18) & 63]! + B64[(n >> 12) & 63]! + '=='
157  } else if (rest === 2) {
158    const n = ((bytes[i] as number) << 16) | ((bytes[i + 1] as number) << 8)
159    out += B64[(n >> 18) & 63]! + B64[(n >> 12) & 63]! + B64[(n >> 6) & 63]! + '='
160  }
161  return out
162}
163
types/index.d.ts 74 lines
1export type BoardPhenotype = { id: string; label: string | null; status: string }
2
3export type BoardVariant = {
4  id: string
5  gene: string | null
6  label: string | null
7  zygosity: string | null
8  classification: string | null
9}
10
11export type BoardHypothesis = { id: string; disease: string; status: string; support: number; against: number }
12
13export type BoardLead = { id: string; name: string; kind: string; status: string | null }
14
15export type BoardTest = { id: string; type: string; date: string | null; result: string | null }
16
17export type BoardRelative = { id: string; relation: string | null; affected: boolean | string | null; genotype: string | null }
18
19export type Board = {
20  path: string
21  id: string
22  title: string
23  role: string
24  /** false when the role was a default, never set by the person (cases from 0.3.3 and earlier) */
25  role_confirmed?: boolean
26  language: string | null
27  updated_at: string
28  phenotypes: BoardPhenotype[]
29  variants: BoardVariant[]
30  hypotheses: BoardHypothesis[]
31  therapy_leads: BoardLead[]
32  questions: string[]
33  tests?: BoardTest[]
34  family?: BoardRelative[]
35  evidence_count: number
36  identifiers: number
37}
38
39/** A zebra tool call in flight, for the spinner, the band and the row. */
40export type ZebraRun = { id: string; tool: string; queryZh: string; queryEn: string; sources: string[]; startedAt: number }
41
42/** What zebra-mod did in the current turn: the line left at its end. */
43export type ZebraTurn = {
44  calls: number
45  failed: number
46  blocked: number
47  sources: string[]
48  cached: number
49  evidence: number
50  firstEvidence: number | null
51  lastEvidence: number | null
52}
53
54export type Ready = { python: string | null; version: string | null; error: string | null }
55
56declare module 'claude-code' {
57  interface PluginState {
58    'zebra-mod': {
59      board: Board | null
60      casePath: string | null
61      guard: string[]
62      ready: Ready | null
63      trusted: string[]
64      sessionIds: string[]
65      running: ZebraRun[]
66      turn: ZebraTurn
67      blockedAt: number | null
68      lang: string | null
69      blockedWhy: string
70      onboarding: boolean
71    }
72  }
73}
74