ctxmedic 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +2 -0
  2. package/dist/index.js +96 -27
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -136,6 +136,8 @@ telemetry, no update checks.
136
136
  - Only `consult --ai`, which you run yourself. It replaces secrets with
137
137
  `[REDACTED]`, then sends your instruction files either to a local Ollama or,
138
138
  after you confirm, to Anthropic or OpenAI with your own key.
139
+ `CTXMEDIC_AI_MODEL` picks the model; `CTXMEDIC_AI_TIMEOUT_MS` (default 120000)
140
+ is how long it waits without an answer.
139
141
  - The UI server (`ctxmedic ui`) listens on `127.0.0.1` only and requires a
140
142
  per-run token for writes.
141
143
 
package/dist/index.js CHANGED
@@ -1503,6 +1503,10 @@ var en = {
1503
1503
  nothingSent: "Nothing was sent.",
1504
1504
  consulting: (provider) => `Consulting ${provider}`,
1505
1505
  secondOpinion: "Second opinion",
1506
+ receiving: (chars) => `Receiving the review (${n(chars)} characters)`,
1507
+ answeredBy: (model) => `Second opinion from ${model}`,
1508
+ aiRefused: "The model declined to review this configuration.",
1509
+ aiTimeout: (seconds) => `No answer for ${seconds} s. Set CTXMEDIC_AI_TIMEOUT_MS to wait longer.`,
1506
1510
  goodbye: "Get well soon! Follow-up: ctxmedic checkup",
1507
1511
  cancelled: "Cancelled"
1508
1512
  }
@@ -1655,7 +1659,7 @@ var harnesses = [
1655
1659
  ];
1656
1660
 
1657
1661
  // ../clinical/src/engine.ts
1658
- var VERSION = true ? "0.4.0" : "0.0.0-dev";
1662
+ var VERSION = true ? "0.5.0" : "0.0.0-dev";
1659
1663
  var TRIAGE = { critical: "resuscitation", warning: "therapy", info: "preventive" };
1660
1664
  var ORDER = ["resuscitation", "therapy", "preventive"];
1661
1665
  var human = (k) => k.replace(/([A-Z])/g, " $1").replace(/^./, (c) => c.toUpperCase());
@@ -1789,10 +1793,21 @@ ${known}
1789
1793
  Configuration files:
1790
1794
  ${docs}`.slice(0, MAX_CHARS);
1791
1795
  }
1792
- async function askAi(provider, prompt) {
1796
+ var aiTimeoutMs = () => Number(process.env.CTXMEDIC_AI_TIMEOUT_MS ?? 12e4);
1797
+ var timedOut = (e) => e?.name === "TimeoutError" || e?.name === "AbortError";
1798
+ async function askAi(provider, prompt, onProgress) {
1799
+ try {
1800
+ return await ask(provider, prompt, onProgress);
1801
+ } catch (e) {
1802
+ if (timedOut(e)) throw new Error("timeout");
1803
+ throw e;
1804
+ }
1805
+ }
1806
+ async function ask(provider, prompt, onProgress) {
1793
1807
  if (provider === "ollama") {
1794
1808
  const r2 = await fetch(`${OLLAMA}/api/chat`, {
1795
1809
  method: "POST",
1810
+ signal: AbortSignal.timeout(aiTimeoutMs()),
1796
1811
  body: JSON.stringify({
1797
1812
  model: process.env.CTXMEDIC_OLLAMA_MODEL ?? "llama3.1",
1798
1813
  stream: false,
@@ -1803,30 +1818,12 @@ async function askAi(provider, prompt) {
1803
1818
  })
1804
1819
  });
1805
1820
  if (!r2.ok) throw new Error(`Ollama: HTTP ${r2.status}`);
1806
- return (await r2.json()).message?.content ?? "";
1807
- }
1808
- if (provider === "anthropic") {
1809
- const r2 = await fetch(`${process.env.ANTHROPIC_BASE_URL ?? "https://api.anthropic.com"}/v1/messages`, {
1810
- method: "POST",
1811
- headers: {
1812
- "content-type": "application/json",
1813
- "x-api-key": process.env.ANTHROPIC_API_KEY ?? "",
1814
- "anthropic-version": "2023-06-01"
1815
- },
1816
- body: JSON.stringify({
1817
- model: process.env.CTXMEDIC_AI_MODEL ?? "claude-opus-5-5",
1818
- max_tokens: 16e3,
1819
- system: SYSTEM,
1820
- messages: [{ role: "user", content: prompt }]
1821
- })
1822
- });
1823
- if (!r2.ok) throw new Error(`Anthropic: HTTP ${r2.status}`);
1824
- const res = await r2.json();
1825
- if (res.stop_reason === "refusal") return "The model declined to review this configuration.";
1826
- return (res.content ?? []).flatMap((b) => b.type === "text" && b.text ? [b.text] : []).join("\n");
1821
+ return { text: (await r2.json()).message?.content ?? "", refused: false };
1827
1822
  }
1823
+ if (provider === "anthropic") return askAnthropic(prompt, onProgress);
1828
1824
  const r = await fetch("https://api.openai.com/v1/chat/completions", {
1829
1825
  method: "POST",
1826
+ signal: AbortSignal.timeout(aiTimeoutMs()),
1830
1827
  headers: { "content-type": "application/json", authorization: `Bearer ${process.env.OPENAI_API_KEY}` },
1831
1828
  body: JSON.stringify({
1832
1829
  model: process.env.CTXMEDIC_AI_MODEL ?? "gpt-5-mini",
@@ -1837,7 +1834,72 @@ async function askAi(provider, prompt) {
1837
1834
  })
1838
1835
  });
1839
1836
  if (!r.ok) throw new Error(`OpenAI: HTTP ${r.status}`);
1840
- return (await r.json()).choices?.[0]?.message?.content ?? "";
1837
+ const text2 = (await r.json()).choices?.[0]?.message?.content ?? "";
1838
+ return { text: text2, refused: false };
1839
+ }
1840
+ async function askAnthropic(prompt, onProgress) {
1841
+ const fallback = !process.env.CTXMEDIC_AI_MODEL;
1842
+ const abort = new AbortController();
1843
+ let timer;
1844
+ const idle = () => {
1845
+ clearTimeout(timer);
1846
+ timer = setTimeout(() => abort.abort(new DOMException("idle", "TimeoutError")), aiTimeoutMs());
1847
+ };
1848
+ idle();
1849
+ try {
1850
+ const r = await fetch(`${process.env.ANTHROPIC_BASE_URL ?? "https://api.anthropic.com"}/v1/messages`, {
1851
+ method: "POST",
1852
+ signal: abort.signal,
1853
+ headers: {
1854
+ "content-type": "application/json",
1855
+ "x-api-key": process.env.ANTHROPIC_API_KEY ?? "",
1856
+ "anthropic-version": "2023-06-01",
1857
+ ...fallback ? { "anthropic-beta": "server-side-fallback-2026-07-01" } : {}
1858
+ },
1859
+ body: JSON.stringify({
1860
+ model: process.env.CTXMEDIC_AI_MODEL ?? "claude-opus-5-5",
1861
+ max_tokens: 64e3,
1862
+ stream: true,
1863
+ ...fallback ? { fallbacks: "default" } : {},
1864
+ system: SYSTEM,
1865
+ messages: [{ role: "user", content: prompt }]
1866
+ })
1867
+ });
1868
+ if (!r.ok || !r.body) {
1869
+ const detail = (await r.json().catch(() => ({}))).error?.message;
1870
+ throw new Error(`Anthropic: HTTP ${r.status}${detail ? ` (${detail})` : ""}`);
1871
+ }
1872
+ let blocks = [];
1873
+ let model;
1874
+ let stop;
1875
+ let buf = "";
1876
+ const decoder = new TextDecoder();
1877
+ for await (const chunk of r.body) {
1878
+ idle();
1879
+ buf += decoder.decode(chunk, { stream: true });
1880
+ let end;
1881
+ while ((end = buf.indexOf("\n\n")) >= 0) {
1882
+ const data = buf.slice(0, end).split("\n").find((l) => l.startsWith("data:"));
1883
+ buf = buf.slice(end + 2);
1884
+ if (!data) continue;
1885
+ const ev = JSON.parse(data.slice(5));
1886
+ if (ev.type === "message_start") model = ev.message?.model;
1887
+ else if (ev.type === "content_block_start" && ev.content_block?.type === "fallback") {
1888
+ blocks = [];
1889
+ model = ev.content_block.to?.model ?? model;
1890
+ } else if (ev.type === "content_block_start" && ev.content_block?.type === "text") blocks.push(ev.content_block.text ?? "");
1891
+ else if (ev.type === "content_block_delta" && ev.delta?.type === "text_delta") {
1892
+ blocks[blocks.length - 1] = (blocks.at(-1) ?? "") + ev.delta.text;
1893
+ onProgress?.(blocks.reduce((n2, b) => n2 + b.length, 0));
1894
+ } else if (ev.type === "message_delta" && ev.delta?.stop_reason) stop = ev.delta.stop_reason;
1895
+ else if (ev.type === "error") throw new Error(`Anthropic: ${ev.error?.type ?? "error"}`);
1896
+ }
1897
+ }
1898
+ if (stop === "refusal") return { text: "", model, refused: true };
1899
+ return { text: blocks.filter(Boolean).join("\n"), model, refused: false };
1900
+ } finally {
1901
+ clearTimeout(timer);
1902
+ }
1841
1903
  }
1842
1904
 
1843
1905
  // ../server/src/index.ts
@@ -2093,9 +2155,16 @@ common(program.command("consult [path]").description("interactive appointment: a
2093
2155
  if (p2.isCancel(ok) || !ok) return p2.outro(m.nothingSent);
2094
2156
  }
2095
2157
  s.start(m.consulting(provider));
2096
- const answer = await askAi(provider, prompt).catch((e) => `Error: ${e.message}`);
2097
- s.stop(m.secondOpinion);
2098
- console.log(answer);
2158
+ const res = await askAi(provider, prompt, (chars) => s.message(m.receiving(chars))).catch(
2159
+ (e) => e.message === "timeout" ? m.aiTimeout(aiTimeoutMs() / 1e3) : `Error: ${e.message}`
2160
+ );
2161
+ if (typeof res === "string") {
2162
+ s.stop(m.secondOpinion);
2163
+ console.log(res);
2164
+ } else {
2165
+ s.stop(res.model ? m.answeredBy(res.model) : m.secondOpinion);
2166
+ console.log(res.refused ? m.aiRefused : res.text);
2167
+ }
2099
2168
  }
2100
2169
  p2.outro(m.goodbye);
2101
2170
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ctxmedic",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "The context medic for your AI coding setup: checkup, treat, savings for Claude Code, Cursor, Windsurf, Codex CLI, OpenCode, Cline and Copilot.",
5
5
  "type": "module",
6
6
  "license": "FSL-1.1-MIT",