@webmcp-agents/testing 0.0.0-stage → 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.
- package/README.md +88 -2
- package/dist/chat-peer-CzVYDy7A.js +24 -0
- package/dist/chat.d.ts +193 -0
- package/dist/chat.js +409 -0
- package/dist/guard-9H8JcSkn.js +151 -0
- package/dist/ids-HmfSbtOs.js +29 -0
- package/dist/index-BYejUroK.d.ts +86 -0
- package/dist/index.d.ts +298 -0
- package/dist/index.js +338 -0
- package/dist/matchers-BwXSMeTG.d.ts +225 -0
- package/dist/matchers-CcMe-gCr.js +653 -0
- package/dist/matchers.d.ts +2 -0
- package/dist/matchers.js +1 -0
- package/dist/observe-spans-D8lEWEjY.js +28 -0
- package/dist/peer-mZEQ4Hla.js +30 -0
- package/dist/playwright.d.ts +38 -0
- package/dist/playwright.js +54 -0
- package/dist/record-runs-DjiNzXC_.js +36 -0
- package/dist/record-runs-DofdrRju.js +1 -0
- package/dist/run-record-8RdIf0RD.d.ts +65 -0
- package/dist/run-record-MOCfkhN0.js +196 -0
- package/dist/script-C3gmfClf.js +52 -0
- package/dist/script-CuyU-jLV.d.ts +71 -0
- package/dist/sentinel-D154AjQn.js +15 -0
- package/dist/server.d.ts +113 -0
- package/dist/server.js +266 -0
- package/dist/setup.d.ts +1 -0
- package/dist/setup.js +89 -0
- package/dist/telemetry-Ct63NJwU.js +130 -0
- package/dist/telemetry.d.ts +2 -0
- package/dist/telemetry.js +1 -0
- package/dist/vitest.d.ts +56 -0
- package/dist/vitest.js +164 -0
- package/dist/wait-DJ--Kfhb.js +29 -0
- package/package.json +133 -3
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { r as memoryExporter, t as MEMORY_EXPORTER } from "./telemetry-Ct63NJwU.js";
|
|
2
|
+
import { observeAgents } from "@webmcp-agents/telemetry";
|
|
3
|
+
// src/telemetry/observe-spans.ts
|
|
4
|
+
/**
|
|
5
|
+
* The `spans` fixture's recorder: `observeAgents` sending every browser span to a memory exporter. Its own module,
|
|
6
|
+
* loaded by the fixture on use, so a test that never destructures `spans` needs no `@webmcp-agents/telemetry`.
|
|
7
|
+
*/
|
|
8
|
+
/** Start observing every run into memory: one span per batch, so nothing waits on a timer. */
|
|
9
|
+
function observeSpans() {
|
|
10
|
+
const memory = memoryExporter();
|
|
11
|
+
const stop = observeAgents({
|
|
12
|
+
exporters: [memory],
|
|
13
|
+
batchSize: 1
|
|
14
|
+
});
|
|
15
|
+
return {
|
|
16
|
+
get spans() {
|
|
17
|
+
return memory.spans;
|
|
18
|
+
},
|
|
19
|
+
reset: () => memory.reset(),
|
|
20
|
+
export: (spans, done) => memory.export(spans, done),
|
|
21
|
+
forceFlush: () => memory.forceFlush(),
|
|
22
|
+
shutdown: () => memory.shutdown(),
|
|
23
|
+
[MEMORY_EXPORTER]: true,
|
|
24
|
+
flush: () => stop.flush(),
|
|
25
|
+
stop: () => stop()
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
export { observeSpans };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// src/peer.ts
|
|
2
|
+
/** The sentence a missing peer fails with. Exported for the kit's own tests. */
|
|
3
|
+
const missingPeerMessage = ({ peer, by }) => `${by} needs ${peer}, which is not installed: add it to your devDependencies (pnpm add -D ${peer}).`;
|
|
4
|
+
const NOT_FOUND = /cannot find (module|package)|could not resolve|failed to (load|resolve)|does the file exist|is it installed/i;
|
|
5
|
+
/**
|
|
6
|
+
* True when `err` says `peer` could not be found (Node's ERR_MODULE_NOT_FOUND, Vite's "Could not resolve … Is it
|
|
7
|
+
* installed?", Vitest's "Failed to load url"). An error the package threw while loading is not that, and is rethrown.
|
|
8
|
+
*/
|
|
9
|
+
function isMissingModule(err, peer) {
|
|
10
|
+
const e = err;
|
|
11
|
+
const message = typeof e?.message === "string" ? e.message : String(err);
|
|
12
|
+
if (!message.includes(peer)) return false;
|
|
13
|
+
return e?.code === "ERR_MODULE_NOT_FOUND" || e?.code === "MODULE_NOT_FOUND" || NOT_FOUND.test(message);
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Load an optional peer. Resolves to the module; rejects with {@link missingPeerMessage} when the package is not
|
|
17
|
+
* installed, and with the original error when it failed for another reason.
|
|
18
|
+
*
|
|
19
|
+
* @example
|
|
20
|
+
* const chat = await requirePeer(() => import("@webmcp-agents/chat/agent"), { peer: "@webmcp-agents/chat", by: "@webmcp-agents/testing/chat" });
|
|
21
|
+
*/
|
|
22
|
+
async function requirePeer(load, options) {
|
|
23
|
+
try {
|
|
24
|
+
return await load();
|
|
25
|
+
} catch (err) {
|
|
26
|
+
if (isMissingModule(err, options.peer)) throw new Error(missingPeerMessage(options), { cause: err });
|
|
27
|
+
throw err;
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
export { requirePeer as t };
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @webmcp-agents/testing/playwright: drive a page's WebMCP tools from Playwright, the way an agent would, through
|
|
3
|
+
* `window.agent` (the devtools install it in development builds, so run e2e against `vite dev` or a build with the
|
|
4
|
+
* devtools on). Use `test.use({ reducedMotion: "reduce" })` so the cursor snaps.
|
|
5
|
+
*
|
|
6
|
+
* await openApp(page, "/");
|
|
7
|
+
* const booking = runTool(page, "book_flight", { id: "SK-204" });
|
|
8
|
+
* await parkedOn(page, page.getByRole("button", { name: "Confirm booking" }));
|
|
9
|
+
* await confirm(page, page.getByRole("button", { name: "Confirm booking" }));
|
|
10
|
+
* expect(await booking).toMatch(/booked/i);
|
|
11
|
+
*
|
|
12
|
+
* Needs `@playwright/test`: importing this entry without it fails with a sentence naming it.
|
|
13
|
+
*/
|
|
14
|
+
import { Locator, Page } from "@playwright/test";
|
|
15
|
+
/** Options for {@link openApp}. */
|
|
16
|
+
export interface OpenAppOptions {
|
|
17
|
+
/** How long to wait for `window.agent` and the tools. Default Playwright's expect timeout. */
|
|
18
|
+
timeout?: number;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Go to `path` and wait until the page is ready for tools: `window.agent` exists (the devtools, development builds)
|
|
22
|
+
* and at least one tool is registered (the provider loads the polyfill in a browser without WebMCP first).
|
|
23
|
+
*/
|
|
24
|
+
export declare function openApp(page: Page, path: string, options?: OpenAppOptions): Promise<void>;
|
|
25
|
+
/**
|
|
26
|
+
* Call a tool through `window.agent` and resolve to its text answer (`undefined` when the call navigated away). A
|
|
27
|
+
* failed call resolves to its error text (`Error [code]: …`), as the agent reads it.
|
|
28
|
+
*/
|
|
29
|
+
export declare function runTool(page: Page, name: string, args?: Record<string, unknown>): Promise<string | undefined>;
|
|
30
|
+
/** The names of the tools registered right now, sorted. */
|
|
31
|
+
export declare function listTools(page: Page): Promise<string[]>;
|
|
32
|
+
/**
|
|
33
|
+
* A confirm-gated tool is waiting for the person on `control`: the cursor is parked (`.agent-cursor.is-waiting`) and
|
|
34
|
+
* the control is the one it found (`data-agent-active`). Only a real click goes on: {@link confirm}.
|
|
35
|
+
*/
|
|
36
|
+
export declare function parkedOn(page: Page, control: Locator): Promise<void>;
|
|
37
|
+
/** The person confirms: wait until the tool is parked on `control`, then a real (trusted) click on it. */
|
|
38
|
+
export declare function confirm(page: Page, control: Locator): Promise<void>;
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { t as requirePeer } from "./peer-mZEQ4Hla.js";
|
|
2
|
+
// src/playwright/index.ts
|
|
3
|
+
const { expect } = await requirePeer(() => import("@playwright/test"), {
|
|
4
|
+
peer: "@playwright/test",
|
|
5
|
+
by: "@webmcp-agents/testing/playwright"
|
|
6
|
+
});
|
|
7
|
+
/**
|
|
8
|
+
* Go to `path` and wait until the page is ready for tools: `window.agent` exists (the devtools, development builds)
|
|
9
|
+
* and at least one tool is registered (the provider loads the polyfill in a browser without WebMCP first).
|
|
10
|
+
*/
|
|
11
|
+
async function openApp(page, path, options = {}) {
|
|
12
|
+
await page.goto(path);
|
|
13
|
+
try {
|
|
14
|
+
await page.waitForFunction(() => !!window.agent, void 0, { timeout: options.timeout });
|
|
15
|
+
} catch (err) {
|
|
16
|
+
throw new Error(`openApp("${path}"): window.agent never appeared. It exists in development builds (the devtools install it): run the app with vite dev, or with the devtools on.`, { cause: err });
|
|
17
|
+
}
|
|
18
|
+
await expect.poll(() => listTools(page), {
|
|
19
|
+
timeout: options.timeout,
|
|
20
|
+
message: `tools to register on ${path}`
|
|
21
|
+
}).not.toEqual([]);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Call a tool through `window.agent` and resolve to its text answer (`undefined` when the call navigated away). A
|
|
25
|
+
* failed call resolves to its error text (`Error [code]: …`), as the agent reads it.
|
|
26
|
+
*/
|
|
27
|
+
function runTool(page, name, args = {}) {
|
|
28
|
+
return page.evaluate(async ([n, a]) => {
|
|
29
|
+
const agent = window.agent;
|
|
30
|
+
if (!agent) throw new Error("runTool(): window.agent is missing: call openApp(page, path) first.");
|
|
31
|
+
return (await agent.invoke(n, a))?.content.map((c) => "text" in c ? c.text ?? "" : "").join("\n");
|
|
32
|
+
}, [name, args]);
|
|
33
|
+
}
|
|
34
|
+
/** The names of the tools registered right now, sorted. */
|
|
35
|
+
function listTools(page) {
|
|
36
|
+
return page.evaluate(async () => {
|
|
37
|
+
const agent = window.agent;
|
|
38
|
+
return agent ? (await agent.list()).map((t) => t.name).sort() : [];
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* A confirm-gated tool is waiting for the person on `control`: the cursor is parked (`.agent-cursor.is-waiting`) and
|
|
43
|
+
* the control is the one it found (`data-agent-active`). Only a real click goes on: {@link confirm}.
|
|
44
|
+
*/
|
|
45
|
+
async function parkedOn(page, control) {
|
|
46
|
+
await expect(control).toHaveAttribute("data-agent-active", "");
|
|
47
|
+
await expect(page.locator(".agent-cursor.is-waiting")).toHaveCount(1);
|
|
48
|
+
}
|
|
49
|
+
/** The person confirms: wait until the tool is parked on `control`, then a real (trusted) click on it. */
|
|
50
|
+
async function confirm(page, control) {
|
|
51
|
+
await parkedOn(page, control);
|
|
52
|
+
await control.click();
|
|
53
|
+
}
|
|
54
|
+
export { confirm, listTools, openApp, parkedOn, runTool };
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { t as RUN_LOG } from "./run-record-MOCfkhN0.js";
|
|
2
|
+
import { n as loadedChat } from "./chat-peer-CzVYDy7A.js";
|
|
3
|
+
// src/chat/record-runs.ts
|
|
4
|
+
/**
|
|
5
|
+
* Record every `AgentRunEvent` (the chat's, `useWebAgent`'s, `agent.invoke`'s, sub-agents' included) until `stop()`.
|
|
6
|
+
* The `runs` fixture does this for you around each test. Inputs and outputs are recorded redacted, as an analytics
|
|
7
|
+
* listener sees them; `{ raw: true }` records them as they are.
|
|
8
|
+
*
|
|
9
|
+
* @example
|
|
10
|
+
* const log = recordRuns();
|
|
11
|
+
* await shopper.invoke("Reorder my last purchase.", { adapter });
|
|
12
|
+
* expect(log).toHaveCalledTools(["track_last_order", "add_to_cart"]);
|
|
13
|
+
* expect(log.types()).toContain("step-finish");
|
|
14
|
+
* log.stop();
|
|
15
|
+
*/
|
|
16
|
+
function recordRuns(options = {}) {
|
|
17
|
+
const events = [];
|
|
18
|
+
const off = loadedChat().onAgentRun((e) => events.push(e), { raw: options.raw === true });
|
|
19
|
+
let stopped = false;
|
|
20
|
+
return {
|
|
21
|
+
[RUN_LOG]: true,
|
|
22
|
+
events,
|
|
23
|
+
types: () => events.map((e) => e.type),
|
|
24
|
+
of: (run) => events.filter((e) => e.ref.run === run),
|
|
25
|
+
runIds: () => [...new Set(events.filter((e) => e.type === "run-start").map((e) => e.ref.run))],
|
|
26
|
+
clear: () => {
|
|
27
|
+
events.length = 0;
|
|
28
|
+
},
|
|
29
|
+
stop: () => {
|
|
30
|
+
if (stopped) return;
|
|
31
|
+
stopped = true;
|
|
32
|
+
off();
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
export { recordRuns as t };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export { t as recordRuns } from "./record-runs-DjiNzXC_.js";
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { AgentRunEvent } from "@webmcp-agents/chat";
|
|
2
|
+
/** How a run ended, as the chat's `finish` / `error` parts say it. */
|
|
3
|
+
type FinishReason = "stop" | "max-steps" | "aborted" | "error";
|
|
4
|
+
/** One tool call a run made. */
|
|
5
|
+
interface RecordedCall {
|
|
6
|
+
name: string;
|
|
7
|
+
input: unknown;
|
|
8
|
+
/** The sub-agent that made it, when not the agent itself. */
|
|
9
|
+
agent?: string;
|
|
10
|
+
}
|
|
11
|
+
/** How one run ended. */
|
|
12
|
+
interface RecordedFinish {
|
|
13
|
+
reason: FinishReason;
|
|
14
|
+
/** The adapter's error code (`rate_limited`, `network`…), when it gave one. */
|
|
15
|
+
code?: string;
|
|
16
|
+
/** The error's text, when it failed. */
|
|
17
|
+
error?: string;
|
|
18
|
+
}
|
|
19
|
+
/** What a mock adapter remembers of its runs. */
|
|
20
|
+
interface RunRecord {
|
|
21
|
+
/** Every tool call, every run, in order. */
|
|
22
|
+
readonly calls: RecordedCall[];
|
|
23
|
+
/** The text each run streamed, joined, in run order (undefined for a run that streamed none). */
|
|
24
|
+
readonly answers: (string | undefined)[];
|
|
25
|
+
/** How each run ended, in order (undefined while a run is in flight). */
|
|
26
|
+
readonly finishes: (RecordedFinish | undefined)[];
|
|
27
|
+
/** The tool names offered on each model step, in order. */
|
|
28
|
+
readonly offered: string[][];
|
|
29
|
+
/**
|
|
30
|
+
* The index (in `answers` / `finishes`) of the last top-level run: one without `ref.parent`. A sub-agent's run on
|
|
31
|
+
* the same adapter starts after its parent and ends before it, so the last index is not the run that answered.
|
|
32
|
+
* -1 before any run.
|
|
33
|
+
*/
|
|
34
|
+
top: number;
|
|
35
|
+
}
|
|
36
|
+
/** Where a mock adapter keeps its {@link RunRecord}. */
|
|
37
|
+
declare const RUN_RECORD: unique symbol;
|
|
38
|
+
/** Options for `recordRuns`. */
|
|
39
|
+
interface RunLogOptions {
|
|
40
|
+
/** Record tool inputs and outputs as they are, without the page's redaction. Default false (what a listener sees by default). */
|
|
41
|
+
raw?: boolean;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Every `AgentRunEvent` since recording started, in order (the `runs` fixture, or `recordRuns()` from
|
|
45
|
+
* `@webmcp-agents/testing/chat`). The run matchers read it: the calls (`tool-start`), and how the last top-level run
|
|
46
|
+
* ended (`run-finish`, which tells `"max-steps"` from `"stop"`). It holds no answer text: `toHaveAnswered` needs the
|
|
47
|
+
* `WebAgentResult` or the `mockAdapter`.
|
|
48
|
+
*/
|
|
49
|
+
interface RunLog {
|
|
50
|
+
/** The run events so far (the same array grows while recording). */
|
|
51
|
+
readonly events: readonly AgentRunEvent[];
|
|
52
|
+
/** Their types, in order: `["run-start", "step-start", "step-finish", "run-finish"]`. */
|
|
53
|
+
types(): AgentRunEvent["type"][];
|
|
54
|
+
/** The events of one run, by its id (`ref.run`). */
|
|
55
|
+
of(run: string): AgentRunEvent[];
|
|
56
|
+
/** The ids of the runs that started, in order, sub-agents' included. */
|
|
57
|
+
runIds(): string[];
|
|
58
|
+
/** Forget what was recorded so far; keep recording. */
|
|
59
|
+
clear(): void;
|
|
60
|
+
/** Stop recording. Idempotent. The `runs` fixture stops for you. */
|
|
61
|
+
stop(): void;
|
|
62
|
+
}
|
|
63
|
+
/** True for a log made by `recordRuns` (the `runs` fixture). */
|
|
64
|
+
declare const isRunLog: (value: unknown) => value is RunLog;
|
|
65
|
+
export { RunLog as a, isRunLog as c, RecordedFinish as i, RUN_RECORD as n, RunLogOptions as o, RecordedCall as r, RunRecord as s, FinishReason as t };
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import { onAgentEvent } from "@webmcp-agents/core";
|
|
2
|
+
// src/helpers/events.ts
|
|
3
|
+
/** Marks an object as an {@link EventLog}, so matchers can tell it from any `{ events }`. */
|
|
4
|
+
const EVENT_LOG = Symbol.for("web-agents.testing.event-log");
|
|
5
|
+
/**
|
|
6
|
+
* Record every agent event until `stop()`. The `events` fixture does this for you around each test.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* const log = recordEvents();
|
|
10
|
+
* await callTool("add_to_cart", { qty: 2 });
|
|
11
|
+
* expect(log).toHaveFilled("qty", "2");
|
|
12
|
+
* log.stop();
|
|
13
|
+
*/
|
|
14
|
+
function recordEvents() {
|
|
15
|
+
const events = [];
|
|
16
|
+
const off = onAgentEvent((e) => events.push(e));
|
|
17
|
+
let stopped = false;
|
|
18
|
+
return {
|
|
19
|
+
[EVENT_LOG]: true,
|
|
20
|
+
events,
|
|
21
|
+
types: () => events.map((e) => e.type),
|
|
22
|
+
of: (type) => events.filter((e) => e.type === type),
|
|
23
|
+
clear: () => {
|
|
24
|
+
events.length = 0;
|
|
25
|
+
},
|
|
26
|
+
stop: () => {
|
|
27
|
+
if (stopped) return;
|
|
28
|
+
stopped = true;
|
|
29
|
+
off();
|
|
30
|
+
}
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
/** True for a log made by {@link recordEvents}. */
|
|
34
|
+
const isEventLog = (value) => typeof value === "object" && value !== null && value[EVENT_LOG] === true;
|
|
35
|
+
// src/format.ts
|
|
36
|
+
/** A matcher was given a value it cannot read. */
|
|
37
|
+
var MatcherInputError = class extends Error {
|
|
38
|
+
name = "MatcherInputError";
|
|
39
|
+
};
|
|
40
|
+
/** Short, one-line JSON of `value` (strings quoted), cut at `max` characters. */
|
|
41
|
+
function show(value, max = 160) {
|
|
42
|
+
let text;
|
|
43
|
+
if (value instanceof RegExp) text = String(value);
|
|
44
|
+
else if (typeof value === "string") text = JSON.stringify(value);
|
|
45
|
+
else if (value === void 0) text = "undefined";
|
|
46
|
+
else if (typeof value === "function") text = `[function ${value.name || "anonymous"}]`;
|
|
47
|
+
else if (isAsymmetric(value)) text = value.toString();
|
|
48
|
+
else try {
|
|
49
|
+
text = JSON.stringify(value) ?? String(value);
|
|
50
|
+
} catch {
|
|
51
|
+
text = String(value);
|
|
52
|
+
}
|
|
53
|
+
return text.length > max ? `${text.slice(0, max - 3)}...` : text;
|
|
54
|
+
}
|
|
55
|
+
/** What kind of value `value` is, for "got …" in a message. */
|
|
56
|
+
function kindOf(value) {
|
|
57
|
+
if (value === null) return "null";
|
|
58
|
+
if (Array.isArray(value)) return `an array of ${value.length}`;
|
|
59
|
+
if (typeof value === "string") return `the string ${show(value, 60)}`;
|
|
60
|
+
if (typeof value === "object") return `an object with keys ${show(Object.keys(value).slice(0, 6))}`;
|
|
61
|
+
return `${typeof value} ${show(value, 60)}`;
|
|
62
|
+
}
|
|
63
|
+
/** An asymmetric matcher (`expect.any(…)`, `expect.stringContaining(…)`). */
|
|
64
|
+
const isAsymmetric = (value) => typeof value === "object" && value !== null && typeof value.asymmetricMatch === "function";
|
|
65
|
+
/** The first line of every message: the call as written. */
|
|
66
|
+
function hint(state, matcher, args = []) {
|
|
67
|
+
return `expect(received).${state.isNot ? "not." : ""}${matcher}(${args.map((a) => show(a, 80)).join(", ")})`;
|
|
68
|
+
}
|
|
69
|
+
/** `text` matches `expected`: a string is contained, a RegExp tested, an asymmetric matcher asked. */
|
|
70
|
+
function textMatches(state, text, expected) {
|
|
71
|
+
if (typeof expected === "string") return text.includes(expected);
|
|
72
|
+
if (expected instanceof RegExp) {
|
|
73
|
+
expected.lastIndex = 0;
|
|
74
|
+
return expected.test(text);
|
|
75
|
+
}
|
|
76
|
+
return state.equals(text, expected);
|
|
77
|
+
}
|
|
78
|
+
const isToolResult = (value) => typeof value === "object" && value !== null && Array.isArray(value.content);
|
|
79
|
+
/** Read a tool result, or throw a sentence saying what the matcher needs. */
|
|
80
|
+
function readToolResult(received, matcher) {
|
|
81
|
+
if (isToolResult(received)) return received;
|
|
82
|
+
if (received === null) throw new MatcherInputError(`${matcher} needs a tool result ({ content, isError? }), got null: the call navigated the page away, so there is no result to check.`);
|
|
83
|
+
throw new MatcherInputError(`${matcher} needs a tool result ({ content, isError? }) from callTool() or tools.call(), got ${kindOf(received)}.` + (typeof received === "string" ? " A tool's raw output is not its result: call it through callTool()." : ""));
|
|
84
|
+
}
|
|
85
|
+
/** The result's text parts, joined with a newline. */
|
|
86
|
+
const resultText = (r) => (r.content ?? []).map((c) => "text" in c && typeof c.text === "string" ? c.text : "").join("\n");
|
|
87
|
+
const ERROR_TEXT = /^Error(?: \[([a-z0-9_.-]+)\])?:/i;
|
|
88
|
+
/** Failed: `isError`, or a text that starts with `Error:` / `Error [code]:` (a declarative form cannot set `isError`). */
|
|
89
|
+
const isFailed = (r) => r.isError === true || ERROR_TEXT.test(resultText(r));
|
|
90
|
+
/** The result's error code: `structuredContent.error.code`, else the `[code]` of its text. */
|
|
91
|
+
function errorCode(r) {
|
|
92
|
+
const fromData = (r.structuredContent?.error)?.code;
|
|
93
|
+
if (typeof fromData === "string") return fromData;
|
|
94
|
+
return ERROR_TEXT.exec(resultText(r))?.[1];
|
|
95
|
+
}
|
|
96
|
+
const isAgentEvent = (value) => typeof value === "object" && value !== null && typeof value.type === "string";
|
|
97
|
+
/** Read agent events from an `EventLog` (the `events` fixture, `recordEvents()`) or an array of them. */
|
|
98
|
+
function readEvents(received, matcher) {
|
|
99
|
+
if (isEventLog(received)) return received.events;
|
|
100
|
+
if (Array.isArray(received) && received.every(isAgentEvent)) return received;
|
|
101
|
+
throw new MatcherInputError(`${matcher} needs the events fixture (or recordEvents(), or an array of AgentEvent), got ${kindOf(received)}.`);
|
|
102
|
+
}
|
|
103
|
+
/** One event in a few words: `start add_to_cart`, `fill qty = "2"`, `park place_order ("Click Place order")`. */
|
|
104
|
+
function describeEvent(e) {
|
|
105
|
+
switch (e.type) {
|
|
106
|
+
case "start":
|
|
107
|
+
case "cancel": return `${e.type} ${e.tool}`;
|
|
108
|
+
case "fill": return `fill ${e.field} = ${show(e.value, 40)} (${e.tool})`;
|
|
109
|
+
case "park": return `park ${e.tool} (${show(e.prompt, 60)})`;
|
|
110
|
+
case "result": return `result ${e.tool}`;
|
|
111
|
+
case "error": return `error ${e.tool}: ${show(e.error, 60)}`;
|
|
112
|
+
case "yield": return `yield (${e.reason})`;
|
|
113
|
+
default: return e.type;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/** The events as a numbered list, or "no events". */
|
|
117
|
+
function listEvents(events, max = 12) {
|
|
118
|
+
if (!events.length) return " (no events)";
|
|
119
|
+
const lines = events.slice(0, max).map((e, i) => ` ${i + 1}. ${describeEvent(e)}`);
|
|
120
|
+
if (events.length > max) lines.push(` … ${events.length - max} more`);
|
|
121
|
+
return lines.join("\n");
|
|
122
|
+
}
|
|
123
|
+
// src/run-record.ts
|
|
124
|
+
/** Where a mock adapter keeps its {@link RunRecord}. */
|
|
125
|
+
const RUN_RECORD = Symbol.for("web-agents.testing.run-record");
|
|
126
|
+
/** Marks an object as a {@link RunLog}, so matchers can tell it from any `{ events }`. */
|
|
127
|
+
const RUN_LOG = Symbol.for("web-agents.testing.run-log");
|
|
128
|
+
/** True for a log made by `recordRuns` (the `runs` fixture). */
|
|
129
|
+
const isRunLog = (value) => typeof value === "object" && value !== null && value[RUN_LOG] === true;
|
|
130
|
+
/** A run log as the matchers see it: every call, and how the last top-level run ended. */
|
|
131
|
+
function readRunLog(log) {
|
|
132
|
+
const agents = /* @__PURE__ */ new Map();
|
|
133
|
+
const calls = [];
|
|
134
|
+
let finish;
|
|
135
|
+
for (const e of log.events) if (e.type === "run-start" && e.ref.parent && e.agent) agents.set(e.ref.run, e.agent);
|
|
136
|
+
else if (e.type === "tool-start") {
|
|
137
|
+
const agent = agents.get(e.ref.run);
|
|
138
|
+
calls.push({
|
|
139
|
+
name: e.tool,
|
|
140
|
+
input: e.input,
|
|
141
|
+
...agent ? { agent } : {}
|
|
142
|
+
});
|
|
143
|
+
} else if (e.type === "run-finish" && !e.ref.parent) finish = {
|
|
144
|
+
reason: e.reason,
|
|
145
|
+
...e.code ? { code: e.code } : {},
|
|
146
|
+
...e.error ? { error: e.error } : {}
|
|
147
|
+
};
|
|
148
|
+
return {
|
|
149
|
+
source: "the run log",
|
|
150
|
+
calls,
|
|
151
|
+
finish
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
const isWebAgentResult = (value) => typeof value === "object" && value !== null && typeof value.text === "string" && Array.isArray(value.steps) && Array.isArray(value.messages);
|
|
155
|
+
/** Read a run, or throw a sentence saying what the matcher needs. */
|
|
156
|
+
function readRun(received, matcher) {
|
|
157
|
+
const record = received?.[RUN_RECORD];
|
|
158
|
+
if (record) return {
|
|
159
|
+
source: "the mock adapter",
|
|
160
|
+
calls: record.calls,
|
|
161
|
+
answer: record.answers[record.top],
|
|
162
|
+
finish: record.finishes[record.top],
|
|
163
|
+
offered: record.offered
|
|
164
|
+
};
|
|
165
|
+
if (isWebAgentResult(received)) return {
|
|
166
|
+
source: "the WebAgentResult",
|
|
167
|
+
calls: received.steps.map((s) => ({
|
|
168
|
+
name: s.tool,
|
|
169
|
+
input: s.input,
|
|
170
|
+
...s.agent ? { agent: s.agent } : {}
|
|
171
|
+
})),
|
|
172
|
+
answer: received.text,
|
|
173
|
+
finish: { reason: "stop" },
|
|
174
|
+
finishNote: "agent.invoke resolved, which reads as \"stop\"; a run cut short by maxSteps resolves too. To tell them apart, assert on the mockAdapter."
|
|
175
|
+
};
|
|
176
|
+
if (received instanceof Error) {
|
|
177
|
+
if (matcher === "toHaveCalledTool" || matcher === "toHaveCalledTools") throw new MatcherInputError(`${matcher} cannot read the error agent.invoke rejected with: the error carries no calls. Assert on the mockAdapter or the runs log.`);
|
|
178
|
+
const aborted = received.name === "AbortError";
|
|
179
|
+
const code = received.code;
|
|
180
|
+
return {
|
|
181
|
+
source: "the error agent.invoke rejected with",
|
|
182
|
+
calls: [],
|
|
183
|
+
finish: {
|
|
184
|
+
reason: aborted ? "aborted" : "error",
|
|
185
|
+
...typeof code === "string" ? { code } : {},
|
|
186
|
+
error: received.message
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
if (isRunLog(received)) {
|
|
191
|
+
if (matcher === "toHaveAnswered") throw new MatcherInputError("toHaveAnswered cannot read a RunLog: run events carry no answer text. Pass the WebAgentResult agent.invoke resolved to, or the mockAdapter.");
|
|
192
|
+
return readRunLog(received);
|
|
193
|
+
}
|
|
194
|
+
throw new MatcherInputError(`${matcher} needs a run: the WebAgentResult agent.invoke resolved to, a mockAdapter, the runs fixture's RunLog, or the error agent.invoke rejected with; got ${kindOf(received)}.`);
|
|
195
|
+
}
|
|
196
|
+
export { textMatches as _, MatcherInputError as a, hint as c, kindOf as d, listEvents as f, show as g, resultText as h, readRun as i, isAsymmetric as l, readToolResult as m, RUN_RECORD as n, describeEvent as o, readEvents as p, isRunLog as r, errorCode as s, RUN_LOG as t, isFailed as u, isEventLog as v, recordEvents as y };
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// src/script.ts
|
|
2
|
+
/** A step that answers `content` (and ends the run). */
|
|
3
|
+
const text = (content, options = {}) => ({
|
|
4
|
+
text: content,
|
|
5
|
+
...options
|
|
6
|
+
});
|
|
7
|
+
/** A step that calls `name` with `input` (and continues the run). */
|
|
8
|
+
const toolCall = (name, input = {}, options = {}) => ({ calls: [{
|
|
9
|
+
name,
|
|
10
|
+
input,
|
|
11
|
+
...options.id ? { id: options.id } : {}
|
|
12
|
+
}] });
|
|
13
|
+
/** A step's reasoning. Merge it with the step it belongs to: `[reasoning("Let me check."), toolCall("x")]`. */
|
|
14
|
+
const reasoning = (content, options = {}) => ({ reasoning: {
|
|
15
|
+
text: content,
|
|
16
|
+
signature: options.signature ?? "sig"
|
|
17
|
+
} });
|
|
18
|
+
const MESSAGES = {
|
|
19
|
+
rate_limited: "Too many requests: try again in a minute.",
|
|
20
|
+
network: "Couldn't reach the assistant.",
|
|
21
|
+
chat_disabled: "Chat is not configured on the server.",
|
|
22
|
+
bad_request: "The request was refused."
|
|
23
|
+
};
|
|
24
|
+
/** A step that fails with `code`: the run ends with `error` and that code. */
|
|
25
|
+
const fail = (code, message) => ({ error: {
|
|
26
|
+
code,
|
|
27
|
+
message: message ?? MESSAGES[code] ?? `Failed: ${code}.`
|
|
28
|
+
} });
|
|
29
|
+
/** Merge a {@link StepInput} into one step (texts joined, calls concatenated, the last error / options win). */
|
|
30
|
+
function toStep(input) {
|
|
31
|
+
if (!Array.isArray(input)) return input;
|
|
32
|
+
const step = {};
|
|
33
|
+
for (const s of input) {
|
|
34
|
+
if (s.text !== void 0) step.text = (step.text ?? "") + s.text;
|
|
35
|
+
if (s.reasoning) step.reasoning = s.reasoning;
|
|
36
|
+
if (s.calls) step.calls = [...step.calls ?? [], ...s.calls];
|
|
37
|
+
if (s.error) step.error = s.error;
|
|
38
|
+
if (s.chunks !== void 0) step.chunks = s.chunks;
|
|
39
|
+
if (s.delayMs !== void 0) step.delayMs = s.delayMs;
|
|
40
|
+
if (s.usage) step.usage = s.usage;
|
|
41
|
+
}
|
|
42
|
+
return step;
|
|
43
|
+
}
|
|
44
|
+
/** The pieces `text` streams in: word by word (each keeps its trailing space), or `chunks` even pieces. */
|
|
45
|
+
function chunksOf(content, chunks) {
|
|
46
|
+
if (!chunks || chunks < 1) return content.split(/(?<= )/).filter(Boolean);
|
|
47
|
+
const size = Math.ceil(content.length / chunks);
|
|
48
|
+
const out = [];
|
|
49
|
+
for (let i = 0; i < content.length; i += size) out.push(content.slice(i, i + size));
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
export { toStep as a, text as i, fail as n, toolCall as o, reasoning as r, chunksOf as t };
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A model's turns, scripted. `mockAdapter` (the browser side), `mockModel` (the server side) and `mockChatServer`
|
|
3
|
+
* (both) play the same steps: one step is one model call.
|
|
4
|
+
*
|
|
5
|
+
* mockAdapter([toolCall("track_last_order"), toolCall("add_to_cart", { qty: 2 }), text("Back in your cart.")]);
|
|
6
|
+
*/
|
|
7
|
+
/** Token usage a step reports (the names of the chat's `StepUsage`). */
|
|
8
|
+
interface StepUsage {
|
|
9
|
+
/** Prompt tokens, cached ones included. */
|
|
10
|
+
inputTokens?: number;
|
|
11
|
+
/** Generated tokens, reasoning included. */
|
|
12
|
+
outputTokens?: number;
|
|
13
|
+
/** Of `outputTokens`, the ones spent reasoning. Default 0. */
|
|
14
|
+
reasoningTokens?: number;
|
|
15
|
+
/** Of `inputTokens`, the ones read from the prompt cache. Default 0. */
|
|
16
|
+
cachedInputTokens?: number;
|
|
17
|
+
}
|
|
18
|
+
/** One tool call in a step. */
|
|
19
|
+
interface StepCall {
|
|
20
|
+
/** The call id. Default: the next `call-<n>` (deterministic under `./setup`). */
|
|
21
|
+
id?: string;
|
|
22
|
+
name: string;
|
|
23
|
+
input?: unknown;
|
|
24
|
+
}
|
|
25
|
+
/** A failure the adapter reports instead of a model turn. */
|
|
26
|
+
interface StepError {
|
|
27
|
+
/** The chat's error code: `rate_limited`, `network`, `chat_disabled`, `bad_request`. */
|
|
28
|
+
code?: "chat_disabled" | "rate_limited" | "bad_request" | "network";
|
|
29
|
+
/** The error's text. Default: a sentence naming the code. */
|
|
30
|
+
message?: string;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* One model call: some reasoning, some text, tool calls, or an error. A step with tool calls continues the run (the
|
|
34
|
+
* calls run on the page, the next step follows); a step without ends it.
|
|
35
|
+
*/
|
|
36
|
+
interface Step {
|
|
37
|
+
/** The reply's text. */
|
|
38
|
+
text?: string;
|
|
39
|
+
/** Reasoning kept with the reply (Claude's signed thinking). */
|
|
40
|
+
reasoning?: {
|
|
41
|
+
text: string;
|
|
42
|
+
signature?: string;
|
|
43
|
+
};
|
|
44
|
+
/** Tool calls, in order. */
|
|
45
|
+
calls?: StepCall[];
|
|
46
|
+
/** Fail instead (the run ends with `error` and this code). */
|
|
47
|
+
error?: StepError;
|
|
48
|
+
/** Stream the text in this many pieces. Default: word by word. */
|
|
49
|
+
chunks?: number;
|
|
50
|
+
/** Wait this long between pieces. Default 0. */
|
|
51
|
+
delayMs?: number;
|
|
52
|
+
/** What the step reports it used. Default `{ inputTokens: 10, outputTokens: 5 }`. */
|
|
53
|
+
usage?: StepUsage;
|
|
54
|
+
}
|
|
55
|
+
/** A step, or several merged into one model call (`[reasoning("…"), toolCall("x")]`). */
|
|
56
|
+
type StepInput = Step | Step[];
|
|
57
|
+
/** Options for {@link text}. */
|
|
58
|
+
type TextOptions = Pick<Step, "chunks" | "delayMs" | "usage">;
|
|
59
|
+
/** A step that answers `content` (and ends the run). */
|
|
60
|
+
declare const text: (content: string, options?: TextOptions) => Step;
|
|
61
|
+
/** A step that calls `name` with `input` (and continues the run). */
|
|
62
|
+
declare const toolCall: (name: string, input?: unknown, options?: {
|
|
63
|
+
id?: string;
|
|
64
|
+
}) => Step;
|
|
65
|
+
/** A step's reasoning. Merge it with the step it belongs to: `[reasoning("Let me check."), toolCall("x")]`. */
|
|
66
|
+
declare const reasoning: (content: string, options?: {
|
|
67
|
+
signature?: string;
|
|
68
|
+
}) => Step;
|
|
69
|
+
/** A step that fails with `code`: the run ends with `error` and that code. */
|
|
70
|
+
declare const fail: (code: NonNullable<StepError["code"]>, message?: string) => Step;
|
|
71
|
+
export { StepUsage as a, reasoning as c, StepInput as i, text as l, StepCall as n, TextOptions as o, StepError as r, fail as s, Step as t, toolCall as u };
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// src/sentinel.ts
|
|
2
|
+
/**
|
|
3
|
+
* Sentinel markers: a catalog whose every entry is `⟦its.path⟧`, so a render's text can be checked for anything that
|
|
4
|
+
* did not come from the catalog. Shared by `renderChat` (which builds the catalog) and `toHaveNoHardcodedText` (which
|
|
5
|
+
* reads the page); no import of the chat, so the matchers entry stays free of it.
|
|
6
|
+
*/
|
|
7
|
+
/** One marker: `⟦composer.send⟧`. Global, for `replace`. */
|
|
8
|
+
const SENTINEL = /⟦[\w.]+⟧/g;
|
|
9
|
+
/** `value` with every string or function leaf replaced by `⟦path⟧`. */
|
|
10
|
+
function sentinelOf(value, path = "") {
|
|
11
|
+
if (typeof value === "string" || typeof value === "function") return `⟦${path}⟧`;
|
|
12
|
+
if (typeof value !== "object" || value === null) return value;
|
|
13
|
+
return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, sentinelOf(v, path ? `${path}.${k}` : k)]));
|
|
14
|
+
}
|
|
15
|
+
export { sentinelOf as n, SENTINEL as t };
|