@alexkroman1/aai-cli 0.13.0 → 0.14.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 (66) hide show
  1. package/README.md +15 -15
  2. package/dist/{_bundler-CgBw5Bcu.mjs → _bundler-B6v31ROV.mjs} +1 -1
  3. package/dist/_console-audio.d.ts +18 -0
  4. package/dist/{_dev-server-BNq5OnUJ.mjs → _dev-server-GoEXEVpA.mjs} +2 -2
  5. package/dist/_resource-commands.d.ts +34 -2
  6. package/dist/{_slug-api-DJuwYZ6T.mjs → _slug-api-BnmTHtjd.mjs} +1 -1
  7. package/dist/{_studio-BH05zugt.mjs → _studio-B5m4jBTD.mjs} +14 -9
  8. package/dist/_studio.d.ts +16 -4
  9. package/dist/_target-bundle.d.ts +2 -0
  10. package/dist/{_templates-Bv-rd0SO.mjs → _templates-BVMVsQh0.mjs} +10 -6
  11. package/dist/_templates.d.ts +9 -2
  12. package/dist/{build-B37oBfEv.mjs → build-CKhanHVv.mjs} +28 -32
  13. package/dist/cli-workflow.d.ts +7 -0
  14. package/dist/cli.mjs +213 -181
  15. package/dist/{client-bundler-D4SeZJ8E.mjs → client-bundler-DZ_Zoznn.mjs} +2 -1
  16. package/dist/client-bundler.d.ts +7 -1
  17. package/dist/client-bundler.mjs +1 -1
  18. package/dist/{console-D6OOjjeJ.mjs → console-Dxq26Adz.mjs} +14 -10
  19. package/dist/{delete-Br0EOH0g.mjs → delete-DwXCHzTl.mjs} +8 -8
  20. package/dist/delete.d.ts +4 -3
  21. package/dist/{deploy-CLUH5cv2.mjs → deploy-CbA8Ibiu.mjs} +2 -2
  22. package/dist/{dev-ZVuyPLUk.mjs → dev-BWBDbUEb.mjs} +1 -1
  23. package/dist/{init-x3FsKl2q.mjs → init-CidslZZz.mjs} +1 -1
  24. package/dist/{logs-BfRq1HX9.mjs → logs-CnPK-Prw.mjs} +25 -3
  25. package/dist/scaffold/CLAUDE.md +52 -52
  26. package/dist/scaffold/agent-guide/AGENT-API.md +20 -20
  27. package/dist/scaffold/agent-guide/HOSTING.md +32 -33
  28. package/dist/scaffold/agent-guide/PIPELINE-TUNING.md +44 -47
  29. package/dist/scaffold/agent-guide/PROVIDERS.md +54 -57
  30. package/dist/scaffold/agent-guide/TESTING-EVALS.md +31 -31
  31. package/dist/scaffold/agent-guide/TOOLS.md +86 -87
  32. package/dist/scaffold/agent-guide/UI.md +59 -58
  33. package/dist/scaffold/agent-guide/WORKFLOWS.md +129 -127
  34. package/dist/scaffold/package.json +4 -4
  35. package/dist/scaffold/vitest.config.ts +3 -3
  36. package/dist/{secret-Db1UWLSZ.mjs → secret-DPdPEet2.mjs} +2 -2
  37. package/dist/{studio-DAoJApzD.mjs → studio-COjK25Rl.mjs} +23 -24
  38. package/dist/studio.d.ts +5 -4
  39. package/dist/templates/call-audit-workflow/agent.eval.test.ts +6 -6
  40. package/dist/templates/call-audit-workflow/agent.test.ts +2 -2
  41. package/dist/templates/document-redline-workflow/agent.eval.test.ts +14 -17
  42. package/dist/templates/home-assistant-agent/agent.test.ts +0 -1
  43. package/dist/templates/link-digest-workflow/agent.eval.test.ts +2 -2
  44. package/dist/templates/link-digest-workflow/agent.test.ts +24 -25
  45. package/dist/templates/medication-safety-agent/agent.test.ts +15 -18
  46. package/dist/templates/medication-safety-agent/fda.test.ts +16 -17
  47. package/dist/templates/medication-safety-agent/fda.ts +7 -0
  48. package/dist/templates/medication-safety-agent/tools/check_drug_interaction.ts +61 -53
  49. package/dist/templates/medication-safety-agent/tools/medication_lookup.ts +42 -32
  50. package/dist/templates/meeting-recap-agent/agent.eval.test.ts +29 -16
  51. package/dist/templates/podcast-digest-workflow/agent.eval.test.ts +3 -3
  52. package/dist/templates/podcast-digest-workflow/agent.test.ts +17 -17
  53. package/dist/templates/research-handoff-agent/agent.eval.test.ts +22 -15
  54. package/dist/templates/research-handoff-agent/agent.test.ts +2 -15
  55. package/dist/templates/research-planner-agent/agent.test.ts +22 -17
  56. package/dist/templates/research-planner-agent/shared.ts +122 -93
  57. package/dist/templates/retail-orders-agent/shared.ts +2 -2
  58. package/dist/templates/retail-orders-agent/tools/get_order_details.ts +1 -1
  59. package/dist/templates/spoken-summary-workflow/agent.eval.test.ts +6 -6
  60. package/dist/templates/spoken-summary-workflow/agent.test.ts +2 -2
  61. package/dist/templates/transcription-workflow/agent.eval.test.ts +3 -3
  62. package/dist/templates/transcription-workflow/agent.test.ts +2 -1
  63. package/dist/templates/transcription-workflow/recover.test.ts +4 -7
  64. package/dist/templates/web-research-agent/agent.test.ts +4 -3
  65. package/dist/templates/word-game-agent/agent.test.ts +11 -5
  66. package/package.json +6 -6
package/dist/studio.d.ts CHANGED
@@ -12,11 +12,12 @@
12
12
  * production.
13
13
  */
14
14
  import { type CommandResult } from "./_output.ts";
15
+ import { type StudioDeps } from "./_studio.ts";
15
16
  import { type Ui } from "./_ui.ts";
16
17
  export declare function executeList(opts: {
17
18
  cwd: string;
18
19
  server?: string | undefined;
19
- }, ui?: Ui): Promise<CommandResult<{
20
+ }, ui?: Ui, deps?: StudioDeps): Promise<CommandResult<{
20
21
  projects: string[];
21
22
  }>>;
22
23
  export declare function executePull(opts: {
@@ -25,7 +26,7 @@ export declare function executePull(opts: {
25
26
  dir?: string | undefined;
26
27
  force?: boolean | undefined;
27
28
  server?: string | undefined;
28
- }, ui?: Ui): Promise<CommandResult<{
29
+ }, ui?: Ui, deps?: StudioDeps): Promise<CommandResult<{
29
30
  project: string;
30
31
  dir: string;
31
32
  files: number;
@@ -34,7 +35,7 @@ export declare function executePush(opts: {
34
35
  cwd: string;
35
36
  server?: string | undefined;
36
37
  force?: boolean | undefined;
37
- }, ui?: Ui): Promise<CommandResult<{
38
+ }, ui?: Ui, deps?: StudioDeps): Promise<CommandResult<{
38
39
  project: string;
39
40
  created: boolean;
40
41
  url: string;
@@ -45,7 +46,7 @@ export declare function executePublish(opts: {
45
46
  server?: string | undefined;
46
47
  force?: boolean | undefined;
47
48
  skipTypecheck?: boolean | undefined;
48
- }, ui?: Ui): Promise<CommandResult<{
49
+ }, ui?: Ui, deps?: StudioDeps): Promise<CommandResult<{
49
50
  project: string;
50
51
  slug: string;
51
52
  url: string;
@@ -58,7 +58,7 @@ import {
58
58
  installStubUploads,
59
59
  stubGatewayRoute,
60
60
  } from "@alexkroman1/aai-runtime/testing/vitest";
61
- import { describe, expect, test } from "vitest";
61
+ import { assert, describe, expect, test } from "vitest";
62
62
  import agentDef, { audit } from "./agent.ts";
63
63
  import { ANALYSIS_FORMAT, BYTES_PER_SECOND, MAX_SEGMENT_SECONDS } from "./workflows/media.ts";
64
64
 
@@ -261,7 +261,7 @@ describeWorkflowEvalWithFfmpeg(
261
261
  expect(run.error).toBeUndefined();
262
262
  expect(run.status).toBe("completed");
263
263
  const output = run.output;
264
- if (output === undefined) expect.fail("a completed run must carry an output");
264
+ assert(output !== undefined, "a completed run must carry an output");
265
265
 
266
266
  // ffmpeg really ran: this is ffprobe's reading of the file, and the
267
267
  // duration is the normalized PCM's own byte count rather than anything a
@@ -334,7 +334,7 @@ describeWorkflowEvalWithFfmpeg(
334
334
 
335
335
  expect(run.error).toBeUndefined();
336
336
  const output = run.output;
337
- if (output === undefined) expect.fail("a completed run must carry an output");
337
+ assert(output !== undefined, "a completed run must carry an output");
338
338
 
339
339
  expect(output.segments).toBe(2);
340
340
  // ONE blind cut — the first segment's end. The recording's own end is
@@ -372,7 +372,7 @@ describeWorkflowEvalWithFfmpeg(
372
372
 
373
373
  expect(run.error).toBeUndefined();
374
374
  const output = run.output;
375
- if (output === undefined) expect.fail("a completed run must carry an output");
375
+ assert(output !== undefined, "a completed run must carry an output");
376
376
  // Under the cap, so no cut at all.
377
377
  expect(output.segments).toBe(1);
378
378
  expect(output.blindCuts).toBe(0);
@@ -382,7 +382,7 @@ describeWorkflowEvalWithFfmpeg(
382
382
  // file nothing can play.
383
383
  expect(uploads.writes).toHaveLength(2);
384
384
  const [pcm, mp3] = uploads.writes;
385
- if (pcm === undefined || mp3 === undefined) expect.fail("both files must be written");
385
+ assert(pcm !== undefined && mp3 !== undefined, "both files must be written");
386
386
  // Named after the recording, and typed HONESTLY: raw samples with no
387
387
  // container, so not `audio/wav` and not `audio/L16` either.
388
388
  expect(pcm.name).toBe("quick.pcm");
@@ -445,7 +445,7 @@ describeWorkflowEvalWithFfmpeg(
445
445
  expect(run.error).toBeUndefined();
446
446
  expect(run.status).toBe("completed");
447
447
  const output = run.output;
448
- if (output === undefined) expect.fail("a completed run must carry an output");
448
+ assert(output !== undefined, "a completed run must carry an output");
449
449
 
450
450
  // ffprobe read the container it really was, and the FILENAME a reader
451
451
  // sees is the one they uploaded rather than the converted artifact's.
@@ -177,8 +177,8 @@ function pauses(...starts: number[]): Silence[] {
177
177
 
178
178
  beforeEach(() => {
179
179
  // The step env, which is where `requireStepEnv`, `stepSpeak` and the gateway
180
- // read the key. `vi.stubEnv` rather than an assignment: `unstubEnvs` undoes it
181
- // before every test, so nothing here has to remember to put it back.
180
+ // read the key. `vi.stubEnv` rather than an assignment: `unstubEnvs` (set by
181
+ // `defineAgentTestConfig`) undoes it after every test, so nothing here has to remember to put it back.
182
182
  vi.stubEnv("ASSEMBLYAI_API_KEY", "test-key");
183
183
  });
184
184
 
@@ -29,13 +29,9 @@
29
29
  // journal, no replay, and no per-step retry, so a rate-limited live run FAILS
30
30
  // where a deployed one would have ridden it out. The tier that really resumes a
31
31
  // run is `aai-cli`'s `dev-workflow.scenario.test.ts`.
32
- import {
33
- describeWorkflowEval,
34
- installStubStepFetch,
35
- routeStepFetch,
36
- stubGatewayRoute,
37
- } from "@alexkroman1/aai-runtime/testing/vitest";
38
- import { expect } from "vitest";
32
+ import { stubFetchRoutes } from "@alexkroman1/aai-runtime/testing";
33
+ import { describeWorkflowEval, stubGatewayRoute } from "@alexkroman1/aai-runtime/testing/vitest";
34
+ import { assert, expect, onTestFinished } from "vitest";
39
35
  import agentDef, { MAX_ROUNDS, redline } from "./agent.ts";
40
36
 
41
37
  /** A brief with a word in it nothing else would produce, so the draft is checkable. */
@@ -74,20 +70,21 @@ const critique = (verdict: "ship" | "revise", score = 8): string =>
74
70
  * fail on the script rather than on the code. Both of those are now the SDK's
75
71
  * one copy rather than this file's second.
76
72
  *
77
- * `installStubStepFetch` rather than `installStubGateway`: `stepGenerate` goes
78
- * through the published `stepFetch` slot, and a published slot BEATS a stubbed
79
- * global, so stubbing the global here would test a path production does not
80
- * take. Anything that is not a completion request THROWS — every step in this
73
+ * The step fetch rather than `installStubGateway`: `stepGenerate` goes through
74
+ * the published `stepFetch` slot, and a published slot BEATS a stubbed global,
75
+ * so stubbing the global here would test a path production does not take —
76
+ * hence `globalFetch: false`. Anything that is not a completion request THROWS — every step in this
81
77
  * body is a model call, so a request the route does not recognise is a finding,
82
78
  * and answering it with a reply anyway is how a stage that started dialling
83
79
  * something else would pass.
84
80
  */
85
81
  function scriptGateway(contents: readonly string[]) {
86
82
  const model = stubGatewayRoute(contents);
87
- // `routeStepFetch` defaults to throwing on an unrecognised request, which is
83
+ // `stubFetchRoutes` defaults to throwing on an unrecognised request, which is
88
84
  // what this file wants and what it used to spell out: every step in this body
89
85
  // is a model call, so anything the route does not recognise is a finding.
90
- installStubStepFetch(routeStepFetch([model.route]));
86
+ const net = stubFetchRoutes([model.route], { globalFetch: false });
87
+ onTestFinished(net.restore);
91
88
  return model;
92
89
  }
93
90
 
@@ -112,12 +109,12 @@ describeWorkflowEval(agentDef, (test) => {
112
109
  expect(run.status).toBe("completed");
113
110
 
114
111
  const output = run.output;
115
- if (output === undefined) expect.fail("a completed run must carry an output");
112
+ assert(output !== undefined, "a completed run must carry an output");
116
113
  expect(output.roundsRun).toBe(1);
117
114
  expect(output.rounds).toHaveLength(1);
118
115
 
119
116
  const last = output.rounds.at(-1);
120
- if (last === undefined) expect.fail("a run of one round must record it");
117
+ assert(last !== undefined, "a run of one round must record it");
121
118
  // THE INVARIANT the template exists for: `shipped` is true exactly when the
122
119
  // critic said so, and a shipped round revised nothing after it. Get either
123
120
  // half wrong and the loop spends a model call it did not need, or stops one
@@ -169,7 +166,7 @@ describeWorkflowEval(agentDef, (test) => {
169
166
 
170
167
  expect(run.error).toBeUndefined();
171
168
  const output = run.output;
172
- if (output === undefined) expect.fail("a completed run must carry an output");
169
+ assert(output !== undefined, "a completed run must carry an output");
173
170
 
174
171
  // The BUDGET stopped it, not the critic — which is the field a page reads to
175
172
  // say "this is as good as it got" rather than "this is finished".
@@ -218,7 +215,7 @@ describeWorkflowEval(agentDef, (test) => {
218
215
 
219
216
  expect(run.error).toBeUndefined();
220
217
  const output = run.output;
221
- if (output === undefined) expect.fail("a completed run must carry an output");
218
+ assert(output !== undefined, "a completed run must carry an output");
222
219
 
223
220
  // ONE call — the critique. A desk that wrote a first draft anyway would make
224
221
  // two, and the page would show a piece nobody attached.
@@ -47,7 +47,6 @@ const NOW = new Date(pdt(9, 28, 14));
47
47
 
48
48
  afterEach(() => {
49
49
  vi.useRealTimers();
50
- vi.unstubAllEnvs();
51
50
  });
52
51
 
53
52
  describe("the agent", () => {
@@ -31,7 +31,7 @@ import {
31
31
  installStubStepFetch,
32
32
  stubGatewayRoute,
33
33
  } from "@alexkroman1/aai-runtime/testing/vitest";
34
- import { expect, onTestFinished } from "vitest";
34
+ import { assert, expect, onTestFinished } from "vitest";
35
35
  import agentDef, { digest } from "./agent.ts";
36
36
  import { SETTLE_MS } from "./workflows/digest.ts";
37
37
 
@@ -212,7 +212,7 @@ describeWorkflowEval(agentDef, (test) => {
212
212
  expect(run.status).toBe("completed");
213
213
 
214
214
  const asked = model.calls[0];
215
- if (asked === undefined) expect.fail("the run must have shown the article to the model");
215
+ assert(asked !== undefined, "the run must have shown the article to the model");
216
216
  expect(asked.prompt).toContain("Sea otters are one of the few mammals that use tools");
217
217
  // The page's OWN abstract, labelled — it comes off the `<meta>` the head
218
218
  // declares, which `pageMetadata` reads and `htmlToText` (rightly) does not.
@@ -245,7 +245,8 @@ describe("summarize", () => {
245
245
 
246
246
  beforeEach(() => {
247
247
  // `stepEnv` falls back to the process env when no host has published one,
248
- // which is exactly the case a spec is. `unstubEnvs` clears it per test.
248
+ // which is exactly the case a spec is. `unstubEnvs` (set by
249
+ // `defineAgentTestConfig`) clears it after each test.
249
250
  vi.stubEnv("ASSEMBLYAI_API_KEY", "sk-test");
250
251
  });
251
252
 
@@ -530,15 +531,9 @@ function frame(event: string, data: unknown): string {
530
531
  * answering `client-config` differently.
531
532
  */
532
533
  function stubAgent(options: { page?: string; runs?: unknown[]; events?: string } = {}) {
533
- const calls: { method: string; url: string; body?: unknown }[] = [];
534
- const fetchStub = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
534
+ const fetchStub = vi.fn<typeof fetch>(async (input, init) => {
535
535
  const url = String(input);
536
536
  const method = init?.method ?? "GET";
537
- calls.push({
538
- method,
539
- url,
540
- ...(typeof init?.body === "string" ? { body: JSON.parse(init.body) } : {}),
541
- });
542
537
  if (url === `${BASE}/client-config`) {
543
538
  return Response.json({ name: "Link Digest", page: options.page ?? "static" });
544
539
  }
@@ -555,18 +550,24 @@ function stubAgent(options: { page?: string; runs?: unknown[]; events?: string }
555
550
  }
556
551
  return Response.json({ error: `no route for ${method} ${url}` }, { status: 404 });
557
552
  });
553
+ // `unstubGlobals` (set by `defineAgentTestConfig`) puts `fetch` back.
558
554
  vi.stubGlobal("fetch", fetchStub);
559
- onTestFinished(() => {
560
- vi.unstubAllGlobals();
561
- });
562
- return calls;
555
+ return fetchStub;
556
+ }
557
+
558
+ /** The JSON body of the first POST the stub received. */
559
+ function postedBody(fetchStub: ReturnType<typeof stubAgent>): unknown {
560
+ const post = fetchStub.mock.calls.find(([, init]) => init?.method === "POST");
561
+ return JSON.parse(String(post?.[1]?.body));
563
562
  }
564
563
 
565
564
  test("connect reads the agent's own description before anything else", async () => {
566
- const calls = stubAgent();
565
+ const fetchStub = stubAgent();
567
566
  const agent = await connect({ baseUrl: BASE });
568
567
 
569
- expect(calls[0]).toMatchObject({ method: "GET", url: `${BASE}/client-config` });
568
+ const [url, init] = fetchStub.mock.calls[0] ?? [];
569
+ expect(String(url)).toBe(`${BASE}/client-config`);
570
+ expect(init?.method ?? "GET").toBe("GET");
570
571
  // The normalized base is on the client, which is what the error messages quote
571
572
  // — a caller should never have to keep the string it was built from.
572
573
  expect(agent.baseUrl).toBe(BASE);
@@ -584,13 +585,13 @@ test("connect refuses a base URL pointing at a VOICE agent, naming it", async ()
584
585
  test("connect drops a trailing slash rather than asking for //client-config", async () => {
585
586
  // A platform routing `/:slug/client-config` answers the doubled path with a
586
587
  // 404, so the normalization is load-bearing rather than cosmetic.
587
- const calls = stubAgent();
588
+ const fetchStub = stubAgent();
588
589
  await connect({ baseUrl: `${BASE}/` });
589
- expect(calls[0]?.url).toBe(`${BASE}/client-config`);
590
+ expect(String(fetchStub.mock.calls[0]?.[0])).toBe(`${BASE}/client-config`);
590
591
  });
591
592
 
592
593
  test("digestLink starts the run under the caller's key and follows it to the end", async () => {
593
- const calls = stubAgent();
594
+ const fetchStub = stubAgent();
594
595
  const agent = await connect({ baseUrl: BASE });
595
596
 
596
597
  const run = await digestLink(agent, "https://example.com/otters", "nightly-job");
@@ -603,8 +604,7 @@ test("digestLink starts the run under the caller's key and follows it to the end
603
604
  expect(run.output.headline).toBe("Otters use stones");
604
605
  expect(run.output.filedAt).toBeTruthy();
605
606
 
606
- const started = calls.find((call) => call.method === "POST");
607
- expect(started?.body).toEqual({
607
+ expect(postedBody(fetchStub)).toEqual({
608
608
  workflow: "digest",
609
609
  input: { url: "https://example.com/otters" },
610
610
  key: "nightly-job",
@@ -614,12 +614,11 @@ test("digestLink starts the run under the caller's key and follows it to the end
614
614
  test("digestLink sends NO key when the caller named none", async () => {
615
615
  // `omitUndefined` rather than `{ key: undefined }`: the request body is what
616
616
  // the agent indexes the run under, and a null key is not the same as no key.
617
- const calls = stubAgent();
617
+ const fetchStub = stubAgent();
618
618
  const agent = await connect({ baseUrl: BASE });
619
619
  await digestLink(agent, "https://example.com/otters");
620
620
 
621
- const started = calls.find((call) => call.method === "POST");
622
- expect(started?.body).not.toHaveProperty("key");
621
+ expect(postedBody(fetchStub)).not.toHaveProperty("key");
623
622
  });
624
623
 
625
624
  test("digestLink refuses to answer for a run the agent never knew", async () => {
@@ -632,15 +631,15 @@ test("digestLink refuses to answer for a run the agent never knew", async () =>
632
631
  });
633
632
 
634
633
  test("pastDigests asks for this caller's runs by KEY, with the limit it was given", async () => {
635
- const calls = stubAgent({ runs: [COMPLETED] });
634
+ const fetchStub = stubAgent({ runs: [COMPLETED] });
636
635
  const agent = await connect({ baseUrl: BASE });
637
636
 
638
637
  const runs = await pastDigests(agent, "nightly-job", { limit: 5 });
639
638
 
640
639
  expect(runs).toHaveLength(1);
641
640
  expect(runs[0]?.status).toBe("completed");
642
- const listed = calls.find((call) => call.url.includes("/runs?"));
643
- const query = new URL(listed?.url ?? "").searchParams;
641
+ const listed = fetchStub.mock.calls.find(([url]) => String(url).includes("/runs?"));
642
+ const query = new URL(String(listed?.[0])).searchParams;
644
643
  expect(query.get("workflow")).toBe("digest");
645
644
  expect(query.get("key")).toBe("nightly-job");
646
645
  expect(query.get("limit")).toBe("5");
@@ -8,9 +8,11 @@ import {
8
8
  toolInputIssues,
9
9
  } from "@alexkroman1/aai-runtime/testing";
10
10
  import { beforeEach, describe, expect, test, vi } from "vitest";
11
- import { excerptAround, type FdaLabel, toDrugInfo } from "./fda.ts";
12
- import CheckDrugInteraction from "./tools/check_drug_interaction.ts";
13
- import MedicationLookup from "./tools/medication_lookup.ts";
11
+ import { excerptAround, type FdaLabel, type LabelLookup, toDrugInfo } from "./fda.ts";
12
+ import type CheckDrugInteraction from "./tools/check_drug_interaction.ts";
13
+ import { checkDrugInteraction } from "./tools/check_drug_interaction.ts";
14
+ import type MedicationLookup from "./tools/medication_lookup.ts";
15
+ import { medicationLookup } from "./tools/medication_lookup.ts";
14
16
 
15
17
  /**
16
18
  * Only the NETWORK half of `fda.ts` is faked.
@@ -18,17 +20,10 @@ import MedicationLookup from "./tools/medication_lookup.ts";
18
20
  * `fetchFdaLabel` is the one function in this template that leaves the process,
19
21
  * so it is the one thing a unit test may not run — everything the tools are
20
22
  * actually about (the cross-mention scan, the refuse-on-a-missing-drug rule,
21
- * the field folding) is pure and stays real. `importActual` rather than a whole
22
- * module stub for exactly that reason: a fully mocked `fda.ts` would leave
23
- * `toDrugInfo` returning `undefined` and the tools passing over nothing.
23
+ * the field folding) is pure and stays real. Each tool takes its lookup as an
24
+ * argument, so the fake is handed in rather than swapped into `fda.ts`.
24
25
  */
25
- vi.mock("./fda.ts", async (importOriginal) => ({
26
- ...(await importOriginal<typeof import("./fda.ts")>()),
27
- fetchFdaLabel: vi.fn(),
28
- }));
29
-
30
- const { fetchFdaLabel } = await import("./fda.ts");
31
- const label = vi.mocked(fetchFdaLabel);
26
+ const label = vi.fn<LabelLookup>();
32
27
 
33
28
  /** The def a DEPLOYED agent runs: authored, plus what `tools/` declares. */
34
29
  import agentDef from "virtual:aai/agent";
@@ -48,13 +43,15 @@ import agentDef from "virtual:aai/agent";
48
43
  * the zod schema the tool really declares, so a renamed or retyped field breaks
49
44
  * the BUILD here and the two files cannot drift apart quietly.
50
45
  *
51
- * Handed the tool FILE's default export — the very object `agentDef` registers
52
- * under that name — `runTool` types the result as the tool's own return, so a
53
- * spec reading a field needs no cast.
46
+ * Handed the tool FILE's own factory — the one its default export, the very
47
+ * object `agentDef` registers under that name, is built by — over the fake
48
+ * lookup, `runTool` types the result as the tool's own return, so a spec
49
+ * reading a field needs no cast.
54
50
  */
55
- const lookUp = (args: InferToolInput<typeof MedicationLookup>) => runTool(MedicationLookup, args);
51
+ const lookUp = (args: InferToolInput<typeof MedicationLookup>) =>
52
+ runTool(medicationLookup(label), args);
56
53
  const check = (args: InferToolInput<typeof CheckDrugInteraction>) =>
57
- runTool(CheckDrugInteraction, args);
54
+ runTool(checkDrugInteraction(label), args);
58
55
 
59
56
  const IBUPROFEN: FdaLabel = {
60
57
  openfda: { generic_name: ["IBUPROFEN"], brand_name: ["Advil"], manufacturer_name: ["Acme"] },
@@ -1,9 +1,9 @@
1
1
  /**
2
2
  * The half of `fda.ts` that `agent.test.ts` cannot reach.
3
3
  *
4
- * That spec replaces `fetchFdaLabel` with a `vi.fn()`, which is right for what
5
- * it is about — the cross-mention scan, the refuse-on-a-missing-drug rule — and
6
- * leaves the lookup itself, the cache and the section readers untested. This
4
+ * That spec hands the tools a `vi.fn()` in place of `fetchFdaLabel`, which is
5
+ * right for what it is about — the cross-mention scan, the refuse-on-a-missing-
6
+ * drug rule — and leaves the lookup itself, the cache and the section readers untested. This
7
7
  * file drives the REAL function, with no module mocking at all: `CallOptions`
8
8
  * carries a `fetch`, documented as being for exactly this, so the query openFDA
9
9
  * receives and the signal it is cancelled by are both observable from here
@@ -18,14 +18,12 @@ import type { CallOptions } from "@alexkroman1/aai/tools";
18
18
  import { describe, expect, test, vi } from "vitest";
19
19
  import { fetchFdaLabel, first, sectionText, toDrugInfo } from "./fda.ts";
20
20
 
21
- /** A fetch that answers one JSON body and records the requests it was given. */
21
+ /** `CallOptions` whose `fetch` answers one JSON body; its `mock.calls` are the requests. */
22
22
  function stubFetch(body: unknown, status = 200) {
23
- const calls: { url: string; signal: AbortSignal | null | undefined }[] = [];
24
- const fetch = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {
25
- calls.push({ url: String(input), signal: init?.signal });
26
- return new Response(JSON.stringify(body), { status });
27
- });
28
- return { calls, options: { fetch } satisfies CallOptions };
23
+ const fetch = vi.fn<typeof globalThis.fetch>(
24
+ async () => new Response(JSON.stringify(body), { status }),
25
+ );
26
+ return { fetch } satisfies CallOptions;
29
27
  }
30
28
 
31
29
  const ASPIRIN = {
@@ -39,22 +37,23 @@ const ASPIRIN = {
39
37
 
40
38
  describe("fetchFdaLabel", () => {
41
39
  test("asks openFDA for the generic OR brand match and answers the first result", async () => {
42
- const { calls, options } = stubFetch(ASPIRIN);
40
+ const options = stubFetch(ASPIRIN);
43
41
 
44
42
  const label = await fetchFdaLabel("Aspirin", options);
43
+ const url = String(options.fetch.mock.calls[0]?.[0]);
45
44
 
46
45
  expect(label).toMatchObject({ purpose: ["Pain reliever"] });
47
46
  // Lowercased and URL-encoded, and BOTH fields searched — a caller who says
48
47
  // "Advil" has to reach the same label as one who says "ibuprofen".
49
- expect(calls[0]?.url).toContain('openfda.generic_name:"aspirin"');
50
- expect(calls[0]?.url).toContain('openfda.brand_name:"aspirin"');
48
+ expect(url).toContain('openfda.generic_name:"aspirin"');
49
+ expect(url).toContain('openfda.brand_name:"aspirin"');
51
50
  });
52
51
 
53
52
  test("a second question about the same drug does not go back to the network", async () => {
54
53
  // The whole reason the cache is in this module rather than in either tool:
55
54
  // a session that looks a drug up and then checks it for interactions would
56
55
  // otherwise pay the round-trip twice.
57
- const { options } = stubFetch({ results: [{ purpose: ["Anticoagulant"] }] });
56
+ const options = stubFetch({ results: [{ purpose: ["Anticoagulant"] }] });
58
57
 
59
58
  await fetchFdaLabel("dabigatran", options);
60
59
  await fetchFdaLabel("DABIGATRAN", options);
@@ -66,7 +65,7 @@ describe("fetchFdaLabel", () => {
66
65
  // openFDA answers 404 for a search that matches nothing, which `fetchJson`
67
66
  // reports as a `ToolFailure` rather than throwing. Caching it would pin a
68
67
  // transient outage for the rest of the call.
69
- const { options } = stubFetch({ error: { code: "NOT_FOUND" } }, 404);
68
+ const options = stubFetch({ error: { code: "NOT_FOUND" } }, 404);
70
69
 
71
70
  expect(await fetchFdaLabel("sparkleforin", options)).toBeNull();
72
71
  expect(await fetchFdaLabel("sparkleforin", options)).toBeNull();
@@ -79,11 +78,11 @@ describe("fetchFdaLabel", () => {
79
78
  // fires one of these per drug, and a hang-up mid-check has to take them all
80
79
  // down. The signal the request sees is a COMBINED one — `fetchJson` folds
81
80
  // its own deadline in — so the claim is that aborting the caller's aborts it.
82
- const { calls, options } = stubFetch({ results: [{ purpose: ["Statin"] }] });
81
+ const options = stubFetch({ results: [{ purpose: ["Statin"] }] });
83
82
  const controller = new AbortController();
84
83
 
85
84
  await fetchFdaLabel("rosuvastatin", { ...options, signal: controller.signal });
86
- const seen = calls[0]?.signal;
85
+ const seen = options.fetch.mock.calls[0]?.[1]?.signal;
87
86
  expect(seen?.aborted).toBe(false);
88
87
 
89
88
  controller.abort();
@@ -99,6 +99,13 @@ export function fetchFdaLabel(name: string, options?: CallOptions): Promise<FdaL
99
99
  return p;
100
100
  }
101
101
 
102
+ /**
103
+ * How a tool reaches a label — {@link fetchFdaLabel}'s shape, named so the two
104
+ * tools can take one as an argument and a spec can hand them a lookup that
105
+ * never leaves the process.
106
+ */
107
+ export type LabelLookup = typeof fetchFdaLabel;
108
+
102
109
  /**
103
110
  * One openFDA lookup, through the SDK's own REST call rather than a bare
104
111
  * `fetch`.
@@ -1,62 +1,70 @@
1
1
  import { tool, toolFailure } from "@alexkroman1/aai";
2
2
  import { z } from "zod";
3
- import { excerptAround, fetchFdaLabel, toDrugInfo } from "../fda.ts";
3
+ import { excerptAround, fetchFdaLabel, type LabelLookup, toDrugInfo } from "../fda.ts";
4
4
 
5
- export default tool({
6
- description:
7
- "Check for interactions between two or more medications using FDA drug label data. Looks up each drug's official label and reports where one drug's Drug Interactions section mentions another. Absence of a mention does not guarantee safety.",
8
- inputSchema: z.object({
9
- drugs: z
10
- .array(z.string().min(1))
11
- .min(2)
12
- .describe("Medication names to check, e.g. ['ibuprofen', 'warfarin']"),
13
- }),
14
- async execute(args, ctx) {
15
- const names = args.drugs.map((d) => d.trim().toLowerCase()).filter((d) => d.length > 0);
16
- if (names.length < 2) {
17
- return toolFailure("Provide at least two medication names to check.");
18
- }
5
+ /**
6
+ * The tool, over whichever label lookup it is handed — openFDA unless told
7
+ * otherwise, for the same reason as `medication_lookup.ts`'s.
8
+ */
9
+ export function checkDrugInteraction(lookup: LabelLookup = fetchFdaLabel) {
10
+ return tool({
11
+ description:
12
+ "Check for interactions between two or more medications using FDA drug label data. Looks up each drug's official label and reports where one drug's Drug Interactions section mentions another. Absence of a mention does not guarantee safety.",
13
+ inputSchema: z.object({
14
+ drugs: z
15
+ .array(z.string().min(1))
16
+ .min(2)
17
+ .describe("Medication names to check, e.g. ['ibuprofen', 'warfarin']"),
18
+ }),
19
+ async execute(args, ctx) {
20
+ const names = args.drugs.map((d) => d.trim().toLowerCase()).filter((d) => d.length > 0);
21
+ if (names.length < 2) {
22
+ return toolFailure("Provide at least two medication names to check.");
23
+ }
19
24
 
20
- // One request per drug, all under the caller's own signal (`CallOptions`).
21
- // This fan-out is the reason `fetchFdaLabel` takes one at all: a hang-up
22
- // used to leave N openFDA requests running with nobody left to answer.
23
- const labels = await Promise.all(names.map((n) => fetchFdaLabel(n, { signal: ctx.signal })));
24
- const unresolved = names.filter((_, i) => labels[i] === null);
25
- if (unresolved.length > 0) {
26
- // Never silently drop a drug from an interaction check — a partial
27
- // answer would read as "no interaction" for the missing one.
28
- return toolFailure(
29
- `Could not find FDA label data for: ${unresolved.join(", ")}. Check the spelling, or try the generic name.`,
30
- );
31
- }
25
+ // One request per drug, all under the caller's own signal (`CallOptions`).
26
+ // This fan-out is the reason the lookup takes one at all: a hang-up
27
+ // used to leave N openFDA requests running with nobody left to answer.
28
+ const labels = await Promise.all(names.map((n) => lookup(n, { signal: ctx.signal })));
29
+ const unresolved = names.filter((_, i) => labels[i] === null);
30
+ if (unresolved.length > 0) {
31
+ // Never silently drop a drug from an interaction check — a partial
32
+ // answer would read as "no interaction" for the missing one.
33
+ return toolFailure(
34
+ `Could not find FDA label data for: ${unresolved.join(", ")}. Check the spelling, or try the generic name.`,
35
+ );
36
+ }
32
37
 
33
- // The unresolved check above guarantees every label resolved.
34
- const drugs = names.map((name, i) => toDrugInfo(name, labels[i]!));
38
+ // The unresolved check above guarantees every label resolved.
39
+ const drugs = names.map((name, i) => toDrugInfo(name, labels[i]!));
35
40
 
36
- const interactions: Array<{ drug: string; mentions: string; excerpt: string }> = [];
37
- for (const a of drugs) {
38
- if (!a.interactionsText) continue;
39
- for (const b of drugs) {
40
- if (a === b) continue;
41
- const hit = b.aliases.find((alias) => a.interactionsText.includes(alias));
42
- if (hit) {
43
- interactions.push({
44
- drug: a.name,
45
- mentions: b.name,
46
- excerpt: excerptAround(a.interactionsText, hit).slice(0, 400),
47
- });
41
+ const interactions: Array<{ drug: string; mentions: string; excerpt: string }> = [];
42
+ for (const a of drugs) {
43
+ if (!a.interactionsText) continue;
44
+ for (const b of drugs) {
45
+ if (a === b) continue;
46
+ const hit = b.aliases.find((alias) => a.interactionsText.includes(alias));
47
+ if (hit) {
48
+ interactions.push({
49
+ drug: a.name,
50
+ mentions: b.name,
51
+ excerpt: excerptAround(a.interactionsText, hit).slice(0, 400),
52
+ });
53
+ }
48
54
  }
49
55
  }
50
- }
51
56
 
52
- return {
53
- drugs: names,
54
- interactions_found: interactions.length,
55
- interactions: interactions.slice(0, 5),
56
- note:
57
- interactions.length === 0
58
- ? "No cross-mentions found in the FDA label Drug Interactions sections. This does not guarantee the combination is safe — confirm with a pharmacist or doctor."
59
- : "Based on FDA label Drug Interactions sections. Confirm with a pharmacist or doctor.",
60
- };
61
- },
62
- });
57
+ return {
58
+ drugs: names,
59
+ interactions_found: interactions.length,
60
+ interactions: interactions.slice(0, 5),
61
+ note:
62
+ interactions.length === 0
63
+ ? "No cross-mentions found in the FDA label Drug Interactions sections. This does not guarantee the combination is safe — confirm with a pharmacist or doctor."
64
+ : "Based on FDA label Drug Interactions sections. Confirm with a pharmacist or doctor.",
65
+ };
66
+ },
67
+ });
68
+ }
69
+
70
+ export default checkDrugInteraction();