@alexkroman1/aai-cli 0.13.0 → 0.14.1

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
@@ -1,36 +1,46 @@
1
1
  import { tool, toolFailure } from "@alexkroman1/aai";
2
2
  import { z } from "zod";
3
- import { fetchFdaLabel, first } from "../fda.ts";
3
+ import { fetchFdaLabel, first, type LabelLookup } from "../fda.ts";
4
4
 
5
- export default tool({
6
- description:
7
- "Look up detailed information about a single medication, including purpose, warnings, dosage, side effects, and manufacturer. Works with both generic and brand names.",
8
- inputSchema: z.object({
9
- name: z.string().describe("Medication name (generic or brand, e.g. 'ibuprofen' or 'Advil')"),
10
- }),
11
- async execute(args, ctx) {
12
- // `ctx.signal` reaches openFDA through `CallOptions`: a caller who barges in
13
- // or hangs up mid-lookup cancels the request rather than leaving it to run
14
- // out the builtin's own deadline with nobody left to tell.
15
- const drug = await fetchFdaLabel(args.name, { signal: ctx.signal });
16
- if (!drug) {
17
- return toolFailure(`No FDA data found for: ${args.name}`);
18
- }
5
+ /**
6
+ * The tool, over whichever label lookup it is handed — openFDA unless told
7
+ * otherwise. A function rather than a bare `tool()` so `agent.test.ts` can pass
8
+ * a lookup that never touches the network; the default export below is the one
9
+ * the agent registers.
10
+ */
11
+ export function medicationLookup(lookup: LabelLookup = fetchFdaLabel) {
12
+ return tool({
13
+ description:
14
+ "Look up detailed information about a single medication, including purpose, warnings, dosage, side effects, and manufacturer. Works with both generic and brand names.",
15
+ inputSchema: z.object({
16
+ name: z.string().describe("Medication name (generic or brand, e.g. 'ibuprofen' or 'Advil')"),
17
+ }),
18
+ async execute(args, ctx) {
19
+ // `ctx.signal` reaches openFDA through `CallOptions`: a caller who barges in
20
+ // or hangs up mid-lookup cancels the request rather than leaving it to run
21
+ // out the builtin's own deadline with nobody left to tell.
22
+ const drug = await lookup(args.name, { signal: ctx.signal });
23
+ if (!drug) {
24
+ return toolFailure(`No FDA data found for: ${args.name}`);
25
+ }
19
26
 
20
- // Every read goes through `first`, which is where the runtime check and the
21
- // entity decode live — see `fda.ts`. A section openFDA served as something
22
- // other than an array of strings reads as absent instead of crashing the
23
- // tool, and `SMITH & NEPHEW` is spoken as a manufacturer rather than as
24
- // an ampersand entity.
25
- const openfda = drug.openfda ?? {};
26
- return {
27
- name: first(openfda.generic_name) ?? args.name,
28
- brand_names: openfda.brand_name ?? [],
29
- purpose: first(drug.purpose) ?? first(drug.indications_and_usage) ?? "N/A",
30
- warnings: first(drug.warnings)?.slice(0, 500) ?? "N/A",
31
- dosage: first(drug.dosage_and_administration)?.slice(0, 500) ?? "N/A",
32
- side_effects: first(drug.adverse_reactions)?.slice(0, 500) ?? "N/A",
33
- manufacturer: first(openfda.manufacturer_name) ?? "N/A",
34
- };
35
- },
36
- });
27
+ // Every read goes through `first`, which is where the runtime check and the
28
+ // entity decode live — see `fda.ts`. A section openFDA served as something
29
+ // other than an array of strings reads as absent instead of crashing the
30
+ // tool, and `SMITH & NEPHEW` is spoken as a manufacturer rather than as
31
+ // an ampersand entity.
32
+ const openfda = drug.openfda ?? {};
33
+ return {
34
+ name: first(openfda.generic_name) ?? args.name,
35
+ brand_names: openfda.brand_name ?? [],
36
+ purpose: first(drug.purpose) ?? first(drug.indications_and_usage) ?? "N/A",
37
+ warnings: first(drug.warnings)?.slice(0, 500) ?? "N/A",
38
+ dosage: first(drug.dosage_and_administration)?.slice(0, 500) ?? "N/A",
39
+ side_effects: first(drug.adverse_reactions)?.slice(0, 500) ?? "N/A",
40
+ manufacturer: first(openfda.manufacturer_name) ?? "N/A",
41
+ };
42
+ },
43
+ });
44
+ }
45
+
46
+ export default medicationLookup();
@@ -62,19 +62,21 @@
62
62
  * this file SHIPS — see `agent.test.ts`.
63
63
  */
64
64
  import agentDef from "virtual:aai/agent";
65
+ import {
66
+ type FetchRouteHandler,
67
+ type FetchRouteRequest,
68
+ stubFetchRoutes,
69
+ } from "@alexkroman1/aai-runtime/testing";
65
70
  import {
66
71
  describeEval,
67
72
  describeToolCalls,
68
73
  type EvalToolCall,
69
74
  type EvalWorkflows,
70
- installStubStepFetch,
71
- routeStepFetch,
72
- type StepRoute,
73
75
  stubGatewayRoute,
74
76
  toolResultIn,
75
77
  toolResultsIn,
76
78
  } from "@alexkroman1/aai-runtime/testing/vitest";
77
- import { expect } from "vitest";
79
+ import { expect, onTestFinished } from "vitest";
78
80
  import { z } from "zod";
79
81
  import { recap, SAMPLE_RECORDING } from "./shared.ts";
80
82
 
@@ -128,12 +130,16 @@ function stubProvider(options: { hold?: boolean; ending?: Ending } = {}): Script
128
130
  const gate = Promise.withResolvers<void>();
129
131
  const model = stubGatewayRoute(RECAP_JSON);
130
132
  let polls = 0;
133
+ // Logged as each request ARRIVES, not when it is answered: a held poll is in
134
+ // flight, and "the run is waiting on the provider" is a claim about it.
135
+ const calls: FetchRouteRequest[] = [];
131
136
  // Two legs: the model, then the provider's job API. Anything neither answers is a
132
- // finding, which is `routeStepFetch`'s default rather than this file's throw.
137
+ // finding, which is `stubFetchRoutes`' default rather than this file's throw.
133
138
  // Annotated, so the leg's contract is visible where it is written: answer the
134
139
  // requests you recognise, `undefined` for everything else, and let
135
- // `routeStepFetch` decide what an unrecognised one means.
136
- const provider: StepRoute = (request) => {
140
+ // `stubFetchRoutes` decide what an unrecognised one means.
141
+ const provider: FetchRouteHandler = (request) => {
142
+ calls.push(request);
137
143
  if (request.method === "POST") return { body: { id: TRANSCRIPT_ID, status: "queued" } };
138
144
  // The compensation. A real DELETE removes the transcript from the account,
139
145
  // which is what makes "a failed run leaves nothing behind" a claim rather
@@ -145,15 +151,22 @@ function stubProvider(options: { hold?: boolean; ending?: Ending } = {}): Script
145
151
  ? { body: { status: "error", error: "that recording could not be decoded" } }
146
152
  : { body: { status: "completed", text: TRANSCRIPT_TEXT, audio_duration: 254 } };
147
153
  };
148
- const route = routeStepFetch([model.route, provider]);
149
- const stub = installStubStepFetch(async (request) => {
150
- const answered = route(request);
151
- // Held AFTER routing, so the poll this returns is the one the script owed
152
- // it — and `polls` has already counted this request.
153
- if (options.hold === true && request.method === "GET" && polls === 1) await gate.promise;
154
- return answered;
155
- });
156
- return { calls: stub.calls, release: () => gate.resolve() };
154
+ // The STEP fetch only: a live run's own model traffic goes over the global.
155
+ const net = stubFetchRoutes(
156
+ [
157
+ model.route,
158
+ async (request) => {
159
+ const answered = await provider(request);
160
+ // Held AFTER routing, so the poll this returns is the one the script owed
161
+ // it — and `polls` has already counted this request.
162
+ if (options.hold === true && request.method === "GET" && polls === 1) await gate.promise;
163
+ return answered;
164
+ },
165
+ ],
166
+ { globalFetch: false },
167
+ );
168
+ onTestFinished(net.restore);
169
+ return { calls, release: () => gate.resolve() };
157
170
  }
158
171
 
159
172
  /** `request_recap`'s two answers — it started one, or it found the live one. */
@@ -43,7 +43,7 @@ import {
43
43
  describeWorkflowEval,
44
44
  installStubStepFetch,
45
45
  } from "@alexkroman1/aai-runtime/testing/vitest";
46
- import { expect } from "vitest";
46
+ import { assert, expect } from "vitest";
47
47
  import agentDef, { dailyDigest } from "./agent.ts";
48
48
  import { MAX_POLL_ATTEMPTS, POLL_DELAY_MS, scheduleIntervalMs } from "./workflows/digest.ts";
49
49
 
@@ -245,7 +245,7 @@ describeWorkflowEval(agentDef, (test) => {
245
245
  expect(run.error).toBeUndefined();
246
246
  expect(run.status).toBe("completed");
247
247
  const output = run.output;
248
- if (output === undefined) expect.fail("a completed run must carry an output");
248
+ assert(output !== undefined, "a completed run must carry an output");
249
249
 
250
250
  // THE INVARIANT: one sleep BETWEEN digests and none after the last, because
251
251
  // a run that has delivered everything it owes should end rather than sleep
@@ -321,7 +321,7 @@ describeWorkflowEval(agentDef, (test) => {
321
321
 
322
322
  expect(run.error).toBeUndefined();
323
323
  const output = run.output;
324
- if (output === undefined) expect.fail("a completed run must carry an output");
324
+ assert(output !== undefined, "a completed run must carry an output");
325
325
 
326
326
  // The fast episode was polled ONCE and then dropped out of `pending`; the
327
327
  // slow one took four rounds. Five polls, not eight.
@@ -28,9 +28,9 @@ import { type FeedItem, parseFeed } from "@alexkroman1/aai/html";
28
28
  import {
29
29
  createWorkflowContext,
30
30
  parseSchemaInput,
31
- routeStepFetch,
32
31
  runWorkflow,
33
32
  schemaInputIssues,
33
+ stubFetchRoutes,
34
34
  stubGatewayRoute,
35
35
  type WorkflowContextRecorder,
36
36
  } from "@alexkroman1/aai-runtime/testing";
@@ -39,7 +39,7 @@ import {
39
39
  installStubStepFetch,
40
40
  installStubTranscribe,
41
41
  } from "@alexkroman1/aai-runtime/testing/vitest";
42
- import { beforeEach, describe, expect, test, vi } from "vitest";
42
+ import { beforeEach, describe, expect, onTestFinished, test, vi } from "vitest";
43
43
  import agentDef, { dailyDigest } from "./agent.ts";
44
44
  import {
45
45
  dailyDigestFlow,
@@ -465,25 +465,25 @@ const THREE_EPISODES = feedXml(
465
465
  /**
466
466
  * Route by URL, so one stub can answer a whole resolution chain.
467
467
  *
468
- * `installStubStepFetch` unpublishes on `onTestFinished`, which is why no
468
+ * Its `restore` is registered with `onTestFinished` here, which is why no
469
469
  * describe block below keeps a `restore` of its own — a hand-kept registry is
470
470
  * the thing that forgets, and a step fetch left published reaches the next file.
471
471
  */
472
472
  function stubRoutes(routes: Record<string, { status?: number; body?: unknown }>) {
473
- return installStubStepFetch(
474
- routeStepFetch(
475
- Object.entries(routes).map(
476
- ([fragment, answer]) =>
477
- (request) =>
478
- request.url.includes(fragment) ? answer : undefined,
479
- ),
480
- // A 404 rather than the default throw, and this one is deliberate: several
481
- // cases below are ABOUT a feed the run cannot reach, and they express that
482
- // by leaving it out of `routes`. Where an unrecognised request would be a
483
- // finding instead, the default is what says so at the call.
484
- { unmatched: "notFound" },
473
+ const net = stubFetchRoutes(
474
+ Object.entries(routes).map(
475
+ ([fragment, answer]) =>
476
+ (request) =>
477
+ request.url.includes(fragment) ? answer : undefined,
485
478
  ),
479
+ // A 404 rather than the default throw, and this one is deliberate: several
480
+ // cases below are ABOUT a feed the run cannot reach, and they express that
481
+ // by leaving it out of `routes`. Where an unrecognised request would be a
482
+ // finding instead, the default is what says so at the call.
483
+ { unmatched: "notFound" },
486
484
  );
485
+ onTestFinished(net.restore);
486
+ return net;
487
487
  }
488
488
 
489
489
  describe("discoverEpisodes", () => {
@@ -495,7 +495,7 @@ describe("discoverEpisodes", () => {
495
495
  const episodes = await discoverEpisodes("https://show.test/feed.xml", 10);
496
496
 
497
497
  // Once. Deciding it is a feed and reading it are the same download.
498
- expect(stubbed.calls).toHaveLength(1);
498
+ expect(stubbed.hits).toHaveLength(1);
499
499
 
500
500
  expect(episodes.map((episode) => episode.title)).toEqual(["newest", "middle", "oldest"]);
501
501
  expect(episodes[0]?.podcastTitle).toBe("Example Show");
@@ -535,7 +535,7 @@ describe("discoverEpisodes", () => {
535
535
  // Verified, not trusted — the advertised URL is fetched before it is used.
536
536
  // And fetched ONCE: the verified body is carried into the reader rather
537
537
  // than the identical document being downloaded again.
538
- expect(stubbed.calls.map((call) => call.url)).toEqual([
538
+ expect(stubbed.hits.map((call) => call.url)).toEqual([
539
539
  "https://show.test/home",
540
540
  "https://show.test/feed.xml",
541
541
  ]);
@@ -29,17 +29,16 @@
29
29
  // endpointing, barge-in, whether two sentences merged into one turn.
30
30
 
31
31
  import agentDef from "virtual:aai/agent";
32
+ import { stubFetchRoutes } from "@alexkroman1/aai-runtime/testing";
32
33
  import {
33
34
  describeEval,
34
35
  type EvalToolCall,
35
36
  type EvalWorkflows,
36
37
  installStubStepDelegate,
37
- installStubStepFetch,
38
- routeStepFetch,
39
38
  stubGatewayRoute,
40
39
  toolResultIn,
41
40
  } from "@alexkroman1/aai-runtime/testing/vitest";
42
- import { expect } from "vitest";
41
+ import { expect, onTestFinished } from "vitest";
43
42
  import { z } from "zod";
44
43
  import { research } from "./shared.ts";
45
44
  /**
@@ -133,23 +132,31 @@ type ScriptedSteps = {
133
132
  function scriptSteps(options: { hold?: boolean } = {}): ScriptedSteps {
134
133
  const gate = Promise.withResolvers<void>();
135
134
  const model = stubGatewayRoute(MODEL_SCRIPT);
136
- // Throwing on an unrecognised request is `routeStepFetch`'s default and is
137
- // what this file wants: every step here is a model call.
138
- const route = routeStepFetch([model.route]);
139
- const stub = installStubStepFetch(async (request) => {
140
- const answered = route(request);
141
- // `model.calls` has already recorded this one, so a length of 1 IS the first
142
- // answer — and holding after the route rather than before it keeps the reply
143
- // this returns the one the script owed that call.
144
- if (options.hold === true && model.calls.length === 1) await gate.promise;
145
- return answered;
146
- });
135
+ // Throwing on an unrecognised request is `stubFetchRoutes`' default and is
136
+ // what this file wants: every step here is a model call. The STEP fetch only:
137
+ // a live run's own model traffic goes over the global and must stay real.
138
+ const net = stubFetchRoutes(
139
+ [
140
+ async (request) => {
141
+ const answered = model.route(request);
142
+ // `model.calls` has already recorded this one, so a length of 1 IS the
143
+ // first answer — and holding after the route rather than before it keeps
144
+ // the reply this returns the one the script owed that call.
145
+ if (answered !== undefined && options.hold === true && model.calls.length === 1) {
146
+ await gate.promise;
147
+ }
148
+ return answered;
149
+ },
150
+ ],
151
+ { globalFetch: false },
152
+ );
153
+ onTestFinished(net.restore);
147
154
  // The researcher's own loop, which does NOT go through `stepFetch`: a subagent
148
155
  // resolves a provider client, so the seam a step reaches it through is the
149
156
  // delegate slot. Unstubbed it THROWS, which is why a converted template's eval
150
157
  // cannot silently keep passing over research that never ran.
151
158
  installStubStepDelegate({ routes: { researcher: RESEARCH_FINDINGS } });
152
- return { calls: stub.calls, release: () => gate.resolve() };
159
+ return { calls: net.hits, release: () => gate.resolve() };
153
160
  }
154
161
 
155
162
  /** `request_research`'s answer when it really started something. */
@@ -524,13 +524,6 @@ describe("the desk's research configuration", () => {
524
524
  * them again would pin the SDK's rendering from the outside.
525
525
  */
526
526
  describe("filing the findings", () => {
527
- // See the note in "the run is DURABLE": the scaffold's vitest config does not
528
- // set `unstubEnvs`, so a webhook stubbed by one case is still set in the next
529
- // unless each case starts from a known environment.
530
- beforeEach(() => {
531
- vi.unstubAllEnvs();
532
- });
533
-
534
527
  const WEBHOOK = "https://hooks.slack.com/services/T000/B000/abc";
535
528
  const TRIGGER = "https://hooks.slack.com/triggers/T000/B000/abc";
536
529
 
@@ -685,14 +678,8 @@ describe("the run is DURABLE", () => {
685
678
  const RUN = { name: "research" } satisfies RunWorkflowOptions;
686
679
 
687
680
  beforeEach(() => {
688
- // `unstubAllEnvs` FIRST, and it is load-bearing rather than tidy: the
689
- // workspace's vitest config sets `unstubEnvs: true` and the SCAFFOLD's does
690
- // not, so in a project `aai init` produced, a `vi.stubEnv` from an earlier
691
- // test is still in the environment here. These cases assert that no webhook
692
- // is configured, so inheriting one made four of them fail in a scaffolded
693
- // project while passing in this repo — the failure shape this guide warns
694
- // about, where the in-tree run is not evidence.
695
- vi.unstubAllEnvs();
681
+ // `unstubEnvs` (set by `defineAgentTestConfig`) undoes the webhook an
682
+ // earlier case stubbed, so these cases start with none configured.
696
683
  vi.stubEnv("ASSEMBLYAI_API_KEY", "sk-test");
697
684
  // No `RESEARCH_SLACK_WEBHOOK_URL`, so the filing step posts nothing — which
698
685
  // is why the gateway counts below are the run's model calls and only those.
@@ -1,7 +1,6 @@
1
1
  /** The def a DEPLOYED agent runs: authored, plus what `tools/` declares. */
2
2
  import agentDef from "virtual:aai/agent";
3
3
  import type { ToolContext } from "@alexkroman1/aai";
4
- import { visitWebpage, webSearch } from "@alexkroman1/aai/tools";
5
4
  import {
6
5
  createToolContext,
7
6
  expectDialogOk,
@@ -17,14 +16,14 @@ import { describe, expect, test, vi } from "vitest";
17
16
  import { executeStep, executor, MAX_STEP_TURNS, normalizeAct, planNode } from "./procedure.ts";
18
17
  import { PLANNER_SYSTEM, REPLANNER_SYSTEM, REVISE_SYSTEM, type StepAnswer } from "./prompts.ts";
19
18
  import {
19
+ createWebTools,
20
20
  MAX_PAGE_CHARS,
21
21
  MAX_PAST_STEPS,
22
22
  MAX_REVISIONS,
23
23
  planFlow,
24
24
  planSlot,
25
25
  planView,
26
- readTool,
27
- searchTool,
26
+ type WebAccess,
28
27
  } from "./shared.ts";
29
28
  import startPlan from "./tools/start_plan.ts";
30
29
 
@@ -32,12 +31,18 @@ import startPlan from "./tools/start_plan.ts";
32
31
  * The web, faked at the SDK's own seam.
33
32
  *
34
33
  * `webSearch` screens a URL and then really fetches it, through an undici
35
- * dispatcher a `globalThis.fetch` stub cannot reach — so mocking the module is
36
- * the only honest way to keep this suite offline. The EXECUTOR's own tests need
37
- * none of it: they stub the delegation, which is the seam a subagent is reached
38
- * through.
34
+ * dispatcher a `globalThis.fetch` stub cannot reach — so the two calls are
35
+ * handed to `createWebTools` as fakes, which keeps this suite offline while
36
+ * everything the tools do with an answer stays real. The EXECUTOR's own tests
37
+ * need none of it: they stub the delegation, which is the seam a subagent is
38
+ * reached through.
39
39
  */
40
- vi.mock("@alexkroman1/aai/tools", () => ({ webSearch: vi.fn(), visitWebpage: vi.fn() }));
40
+ const fakeSearch = vi.fn<WebAccess["webSearch"]>();
41
+ const fakeVisit = vi.fn<WebAccess["visitWebpage"]>();
42
+ const { searchTool, readTool } = createWebTools({
43
+ webSearch: fakeSearch,
44
+ visitWebpage: fakeVisit,
45
+ });
41
46
 
42
47
  // ─── A scripted desk ─────────────────────────────────────────────────────────
43
48
  //
@@ -254,7 +259,7 @@ describe("the executor's guardrail", () => {
254
259
 
255
260
  describe("the executor's search tool", () => {
256
261
  test("renders the hits the model reasons over", async () => {
257
- vi.mocked(webSearch).mockResolvedValueOnce({
262
+ fakeSearch.mockResolvedValueOnce({
258
263
  results: [{ title: "Fares to Lisbon", url: "https://example.test/fares" }],
259
264
  });
260
265
 
@@ -270,7 +275,7 @@ describe("the executor's search tool", () => {
270
275
  // carries the refusal out as the tool's own `ToolFailure` — an empty list
271
276
  // would tell the executor there is nothing out there, and a thrown `Error`
272
277
  // would have the runtime log an ordinary 403 as an uncaught tool bug.
273
- vi.mocked(webSearch).mockResolvedValueOnce({ error: "403 Forbidden" });
278
+ fakeSearch.mockResolvedValueOnce({ error: "403 Forbidden" });
274
279
 
275
280
  expect(await searchTool.execute({ query: "anything" }, createToolContext())).toEqual({
276
281
  error: "403 Forbidden",
@@ -281,16 +286,16 @@ describe("the executor's search tool", () => {
281
286
  // A tool body gets a signal and `CallOptions` takes one; until they were
282
287
  // joined, a caller who hung up mid-step left a search running against a
283
288
  // third party.
284
- vi.mocked(webSearch).mockResolvedValueOnce({ results: [] });
289
+ fakeSearch.mockResolvedValueOnce({ results: [] });
285
290
  const ctx = createToolContext();
286
291
 
287
292
  await searchTool.execute({ query: "anything" }, ctx);
288
293
 
289
- expect(vi.mocked(webSearch).mock.calls[0]?.[0]).toMatchObject({ signal: ctx.signal });
294
+ expect(fakeSearch.mock.calls[0]?.[0]).toMatchObject({ signal: ctx.signal });
290
295
  });
291
296
 
292
297
  test("says so when the web really had nothing", async () => {
293
- vi.mocked(webSearch).mockResolvedValueOnce({ results: [] });
298
+ fakeSearch.mockResolvedValueOnce({ results: [] });
294
299
  expect(await searchTool.execute({ query: "anything" }, createToolContext())).toBe(
295
300
  "No results.",
296
301
  );
@@ -299,7 +304,7 @@ describe("the executor's search tool", () => {
299
304
 
300
305
  describe("the executor's read tool", () => {
301
306
  test("hands back the page body, capped", async () => {
302
- vi.mocked(visitWebpage).mockResolvedValueOnce({ content: "x".repeat(MAX_PAGE_CHARS + 500) });
307
+ fakeVisit.mockResolvedValueOnce({ content: "x".repeat(MAX_PAGE_CHARS + 500) });
303
308
 
304
309
  const body = await readTool.execute({ url: "https://example.test/fares" }, createToolContext());
305
310
 
@@ -309,7 +314,7 @@ describe("the executor's read tool", () => {
309
314
  });
310
315
 
311
316
  test("a page that would not load is not a page that said nothing", async () => {
312
- vi.mocked(visitWebpage).mockResolvedValueOnce({ error: "404 Not Found" });
317
+ fakeVisit.mockResolvedValueOnce({ error: "404 Not Found" });
313
318
 
314
319
  expect(
315
320
  await readTool.execute({ url: "https://example.test/gone" }, createToolContext()),
@@ -317,12 +322,12 @@ describe("the executor's read tool", () => {
317
322
  });
318
323
 
319
324
  test("the caller's signal reaches the fetch here too", async () => {
320
- vi.mocked(visitWebpage).mockResolvedValueOnce({ content: "anything" });
325
+ fakeVisit.mockResolvedValueOnce({ content: "anything" });
321
326
  const ctx = createToolContext();
322
327
 
323
328
  await readTool.execute({ url: "https://example.test/fares" }, ctx);
324
329
 
325
- expect(vi.mocked(visitWebpage).mock.calls[0]?.[1]).toMatchObject({ signal: ctx.signal });
330
+ expect(fakeVisit.mock.calls[0]?.[1]).toMatchObject({ signal: ctx.signal });
326
331
  });
327
332
  });
328
333