@capybara-hq/testing 0.1.0-rc.2 → 0.1.0-rc.21

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 (74) hide show
  1. package/dist/containers.d.ts +7 -2
  2. package/dist/containers.js +7 -3
  3. package/dist/dual-replica.d.ts +11 -2
  4. package/dist/dual-replica.js +48 -0
  5. package/dist/fake-channel.d.ts +31 -2
  6. package/dist/fake-channel.js +29 -2
  7. package/dist/fake-e2b.d.ts +34 -0
  8. package/dist/fake-e2b.js +95 -1
  9. package/dist/fake-git-server.d.ts +32 -4
  10. package/dist/fake-git-server.js +87 -19
  11. package/dist/fake-oauth-server.d.ts +16 -2
  12. package/dist/fake-oauth-server.js +21 -1
  13. package/dist/fake-telegram.d.ts +165 -0
  14. package/dist/fake-telegram.js +569 -0
  15. package/dist/fixtures.d.ts +21 -4
  16. package/dist/fixtures.js +30 -4
  17. package/dist/index.d.ts +8 -5
  18. package/dist/index.js +6 -3
  19. package/dist/kernel-helpers.d.ts +48 -16
  20. package/dist/kernel-helpers.js +73 -13
  21. package/dist/model-conformance.d.ts +11 -10
  22. package/dist/model-conformance.js +38 -14
  23. package/dist/replica-runner.js +16 -8
  24. package/dist/sandbox-native-conformance.d.ts +31 -0
  25. package/dist/sandbox-native-conformance.js +153 -0
  26. package/dist/sandbox-permission-conformance.d.ts +60 -0
  27. package/dist/sandbox-permission-conformance.js +486 -0
  28. package/fixtures/extensions/fake-client/.capybara-plugin/plugin.json +11 -0
  29. package/fixtures/extensions/fake-client/client/styles/fake.css +11 -0
  30. package/fixtures/extensions/fake-client/package.json +12 -0
  31. package/fixtures/extensions/fake-client/src/client.tsx +51 -0
  32. package/fixtures/extensions/fake-client/src/index.ts +43 -0
  33. package/fixtures/extensions/fake-client/themes/fake.json +11 -0
  34. package/fixtures/extensions/fake-client-broken/.capybara-plugin/plugin.json +7 -0
  35. package/fixtures/extensions/fake-client-broken/package.json +12 -0
  36. package/fixtures/extensions/fake-client-broken/src/client.tsx +22 -0
  37. package/fixtures/extensions/fake-client-broken/src/index.ts +27 -0
  38. package/fixtures/extensions/fake-config-form/.capybara-plugin/plugin.json +11 -0
  39. package/fixtures/extensions/fake-config-form/package.json +12 -0
  40. package/fixtures/extensions/fake-config-form/src/index.ts +205 -0
  41. package/fixtures/extensions/fake-context/.capybara-plugin/plugin.json +7 -0
  42. package/fixtures/extensions/fake-context/package.json +12 -0
  43. package/fixtures/extensions/fake-context/src/index.ts +81 -0
  44. package/fixtures/extensions/fake-dep-provider/src/index.ts +1 -1
  45. package/fixtures/extensions/fake-dep-requirer/src/index.ts +1 -1
  46. package/fixtures/extensions/fake-embed/src/index.ts +26 -26
  47. package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +7 -1
  48. package/fixtures/extensions/fake-im/guides/fake-im-app.md +32 -0
  49. package/fixtures/extensions/fake-im/guides/fake-im-app.zh.md +32 -0
  50. package/fixtures/extensions/fake-im/src/channel.ts +3 -1
  51. package/fixtures/extensions/fake-im/src/checks.ts +94 -0
  52. package/fixtures/extensions/fake-im/src/index.ts +36 -1
  53. package/fixtures/extensions/fake-lifecycle/.capybara-plugin/plugin.json +7 -0
  54. package/fixtures/extensions/fake-lifecycle/migrations/0001_init.sql +16 -0
  55. package/fixtures/extensions/fake-lifecycle/package.json +12 -0
  56. package/fixtures/extensions/fake-lifecycle/src/index.ts +72 -0
  57. package/fixtures/extensions/fake-storage-user/src/index.ts +1 -1
  58. package/fixtures/extensions/fake-tools-ui/skills/fake-notes/SKILL.md +1 -1
  59. package/fixtures/extensions/fake-tools-ui/src/index.ts +62 -3
  60. package/fixtures/extensions/fake-web/.capybara-plugin/plugin.json +7 -0
  61. package/fixtures/extensions/fake-web/package.json +12 -0
  62. package/fixtures/extensions/fake-web/src/index.ts +22 -0
  63. package/fixtures/extensions/fake-web/src/web.ts +183 -0
  64. package/fixtures/extensions/fake-web-2/.capybara-plugin/plugin.json +7 -0
  65. package/fixtures/extensions/fake-web-2/package.json +12 -0
  66. package/fixtures/extensions/fake-web-2/src/index.ts +16 -0
  67. package/fixtures/extensions/fake-web-2/src/web.ts +183 -0
  68. package/fixtures/plugins/fake-theme/.capybara-plugin/plugin.json +7 -0
  69. package/fixtures/plugins/fake-theme/fonts/FakeSans.woff2 +1 -0
  70. package/fixtures/plugins/fake-theme/logo.svg +1 -0
  71. package/fixtures/plugins/fake-theme/package.json +8 -0
  72. package/fixtures/plugins/fake-theme/themes/neon-grid.json +13 -0
  73. package/fixtures/plugins/fake-theme/themes/paper.json +12 -0
  74. package/package.json +6 -5
@@ -0,0 +1,94 @@
1
+ import type { SetupCheckArgs, SetupCheckDefinition } from "@capybara-hq/plugin-sdk";
2
+ import { FakeImConnection } from "./channel.js";
3
+
4
+ /**
5
+ * The setup checks of `fake-im` (setup guides v2 §10), one per behavior the kernel's runner must
6
+ * handle. Each is registered in `index.ts` with a literal id (the `perm-setup-check` rule):
7
+ *
8
+ * - `pass` / `fail`: ok, and failing with a reason and a fix (no third-party call);
9
+ * - `proxy`: one `POST <platformUrl>/checks` per run (counted by `FakeChannelServer.checks`, held
10
+ * by `holdChecks`), then ok: what a real check's third-party call looks like;
11
+ * - `throw`: throws an error whose message carries the connection's `appSecret`;
12
+ * - `hang`: waits for `signal` and rejects when it aborts (a well-behaved slow check);
13
+ * - `ignore-signal`: never settles, whatever `signal` does;
14
+ * - `long`: a reason over the 300-character limit (an invalid result);
15
+ * - `echo-secret`: puts the connection's `appSecret` into the reason and the fix, and the
16
+ * deployment config's `clientSecret` (from `args.config`) into the fix;
17
+ * - `pad-to-limit`: a reason of exactly 300 characters that contains the connection's
18
+ * `webhookToken` (set it to 8 or 9 characters): valid as returned, too long once redacted.
19
+ */
20
+
21
+ const conn = (args: SetupCheckArgs) => {
22
+ if (args.target.kind !== "channel-connection") throw new Error("not a channel connection");
23
+ return FakeImConnection.parse(args.target.config);
24
+ };
25
+
26
+ const channelCheck = (run: SetupCheckDefinition["run"]): SetupCheckDefinition => ({
27
+ place: "channel-connection",
28
+ run,
29
+ });
30
+
31
+ export const passCheck = channelCheck(async () => ({
32
+ status: "ok",
33
+ reason: { en: "The fake platform accepted the app.", zh: "fake 平台接受了这个应用。" },
34
+ }));
35
+
36
+ export const failCheck = channelCheck(async () => ({
37
+ status: "failing",
38
+ reason: { en: "The fake platform refused the app." },
39
+ fix: { en: "Create the app again and copy the new secret." },
40
+ }));
41
+
42
+ export const proxyCheck = channelCheck(async (args) => {
43
+ const c = conn(args);
44
+ const res = await fetch(`${c.platformUrl}/checks`, {
45
+ method: "POST",
46
+ headers: { "content-type": "application/json", "x-pid": String(process.pid) },
47
+ body: JSON.stringify({
48
+ check: "proxy",
49
+ connectionId: args.target.kind === "channel-connection" ? args.target.connectionId : "",
50
+ }),
51
+ signal: args.signal,
52
+ });
53
+ await res.body?.cancel();
54
+ return res.status === 200
55
+ ? { status: "ok", reason: { en: "The fake platform answered." } }
56
+ : { status: "unknown", reason: { en: "The fake platform did not answer; retry later." } };
57
+ });
58
+
59
+ export const throwCheck = channelCheck(async (args) => {
60
+ throw new Error(`the platform refused ${conn(args).appSecret}`);
61
+ });
62
+
63
+ export const hangCheck = channelCheck(
64
+ (args) =>
65
+ new Promise((_, reject) => {
66
+ const stop = () => reject(new Error("aborted"));
67
+ if (args.signal.aborted) stop();
68
+ else args.signal.addEventListener("abort", stop, { once: true });
69
+ }),
70
+ );
71
+
72
+ export const ignoreSignalCheck = channelCheck(() => new Promise(() => {}));
73
+
74
+ export const longCheck = channelCheck(async () => ({
75
+ status: "ok",
76
+ reason: { en: "x".repeat(301) },
77
+ }));
78
+
79
+ export const echoSecretCheck = channelCheck(async (args) => {
80
+ const secret = conn(args).appSecret;
81
+ const client = (args.config as { clientSecret?: string } | null)?.clientSecret ?? "";
82
+ return {
83
+ status: "failing",
84
+ reason: { en: `The platform refused ${secret}.`, zh: `平台拒绝了 ${secret}。` },
85
+ fix: { en: `Replace ${secret} with a new secret (login client ${client}).` },
86
+ };
87
+ });
88
+
89
+ export const padToLimitCheck = channelCheck(async (args) => {
90
+ const c = conn(args);
91
+ const secret = c.webhookToken ?? c.appSecret;
92
+ const head = `Token ${secret} `;
93
+ return { status: "ok", reason: { en: head + "x".repeat(300 - head.length) } };
94
+ });
@@ -7,6 +7,17 @@ import {
7
7
  } from "@capybara-hq/plugin-sdk";
8
8
  import { z } from "zod";
9
9
  import { makeFakeImChannel } from "./channel.js";
10
+ import {
11
+ echoSecretCheck,
12
+ failCheck,
13
+ hangCheck,
14
+ ignoreSignalCheck,
15
+ longCheck,
16
+ padToLimitCheck,
17
+ passCheck,
18
+ proxyCheck,
19
+ throwCheck,
20
+ } from "./checks.js";
10
21
  import { FakeImOrgConfig, fakeImDirectory } from "./directory.js";
11
22
  import { fakeImIdentitySource } from "./identity.js";
12
23
 
@@ -70,13 +81,27 @@ const postHandler =
70
81
  * 假 IM 平台的完整测试插件(连 `@capybara-hq/testing` 的 startFakeChannelServer):
71
82
  * `channel@1`(机器人)+ `identity-source@1`(登录)+ `directory@1`(通讯录),另带一个默认需要批准的写工具。
72
83
  * 三处的身份源键都是 `fake-im:<租户>`,同一个人只对应一行身份。T15–T18 的真实渠道插件照这个形状写。
84
+ * It also registers setup checks for the kernel's check runner tests (`checks.ts`).
73
85
  */
74
86
  export default defineExtension({
75
87
  name: "fake-im",
76
88
  version: "0.1.0",
77
89
  sdk: "^0.1.0-rc.0",
78
90
  provides: ["channel@1", "identity-source@1", "directory@1"],
79
- permissions: { tools: ["post_announcement"] },
91
+ permissions: {
92
+ tools: ["post_announcement"],
93
+ setupChecks: [
94
+ "pass",
95
+ "fail",
96
+ "proxy",
97
+ "throw",
98
+ "hang",
99
+ "ignore-signal",
100
+ "long",
101
+ "echo-secret",
102
+ "pad-to-limit",
103
+ ],
104
+ },
80
105
  config: { deployment: Deployment, org: FakeImOrgConfig },
81
106
  setup(ctx) {
82
107
  const config = () => Deployment.parse(ctx.config);
@@ -87,5 +112,15 @@ export default defineExtension({
87
112
  ctx.provide("identity-source@1", fakeImIdentitySource);
88
113
  ctx.provide("directory@1", fakeImDirectory);
89
114
  ctx.tools.register(POST_SPEC, postHandler(config));
115
+ // setup checks for the kernel's check runner tests (checks.ts says what each does)
116
+ ctx.setup.check("pass", passCheck);
117
+ ctx.setup.check("fail", failCheck);
118
+ ctx.setup.check("proxy", proxyCheck);
119
+ ctx.setup.check("throw", throwCheck);
120
+ ctx.setup.check("hang", hangCheck);
121
+ ctx.setup.check("ignore-signal", ignoreSignalCheck);
122
+ ctx.setup.check("long", longCheck);
123
+ ctx.setup.check("echo-secret", echoSecretCheck);
124
+ ctx.setup.check("pad-to-limit", padToLimitCheck);
90
125
  },
91
126
  });
@@ -0,0 +1,7 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "name": "fake-lifecycle",
4
+ "version": "0.1.0",
5
+ "publisher": "Capybara",
6
+ "description": "Test fake: observes the lifecycle hooks and records each delivery in its own table"
7
+ }
@@ -0,0 +1,16 @@
1
+ -- Runs with search_path "plugin_fake_lifecycle, public": table names carry no schema prefix.
2
+ -- Every call of a lifecycle hook (one row per call, failed ones too).
3
+ CREATE TABLE IF NOT EXISTS calls (
4
+ id bigserial PRIMARY KEY,
5
+ mount text NOT NULL,
6
+ payload jsonb NOT NULL,
7
+ at timestamptz NOT NULL DEFAULT now()
8
+ );
9
+
10
+ -- Every successful delivery (one row per call that did not throw).
11
+ CREATE TABLE IF NOT EXISTS deliveries (
12
+ id bigserial PRIMARY KEY,
13
+ mount text NOT NULL,
14
+ payload jsonb NOT NULL,
15
+ at timestamptz NOT NULL DEFAULT now()
16
+ );
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "@capybara-hq/test-plugin-fake-lifecycle",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "description": "Test fake: observes the lifecycle hooks and records each delivery in its own table",
6
+ "license": "Apache-2.0",
7
+ "type": "module",
8
+ "dependencies": {
9
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.0",
10
+ "zod": "^4.6.7"
11
+ }
12
+ }
@@ -0,0 +1,72 @@
1
+ import {
2
+ defineExtension,
3
+ type ExtensionContext,
4
+ type HookCall,
5
+ orgAccess,
6
+ } from "@capybara-hq/plugin-sdk";
7
+ import { z } from "zod";
8
+
9
+ /**
10
+ * Test fake of an extension that cleans up after removals: it observes the three lifecycle hooks
11
+ * (`org.member_removed`, `agent.deleted`, `org.deleted`) and records every call in its own schema
12
+ * (`plugin_fake_lifecycle`): table `calls` gets one row per call, `deliveries` one row per call
13
+ * that succeeded, each with the mount and the payload. Deployment config `failTimes` (default 0):
14
+ * the first `failTimes` calls of each (mount, payload) throw, so tests can drive the kernel's
15
+ * retries; the count lives in PG, so it holds across replicas. Deployment config `label` (optional,
16
+ * at most 10 characters) is overridable per org, so a test can store an org copy that does not
17
+ * validate (an org whose effective config is invalid).
18
+ */
19
+
20
+ const DeploymentConfig = z.object({
21
+ /** How many calls of each (mount, payload) throw before one succeeds. */
22
+ failTimes: z.number().int().min(0).default(0),
23
+ /** Overridable per org; an org copy with a longer label makes that org's config invalid. */
24
+ label: orgAccess(z.string().max(10).optional(), "override"),
25
+ });
26
+
27
+ type Db = ExtensionContext["db"];
28
+
29
+ /** Records the call, throws while it is one of the first `failTimes`, else records the delivery. */
30
+ async function handle(
31
+ db: Db,
32
+ mount: string,
33
+ payload: object,
34
+ call: HookCall | undefined,
35
+ ): Promise<void> {
36
+ const json = JSON.stringify(payload);
37
+ await db.insertInto("calls").values({ mount, payload: json }).execute();
38
+ const { failTimes } = DeploymentConfig.parse(call?.config ?? {});
39
+ if (failTimes > 0) {
40
+ const row = await db
41
+ .selectFrom("calls")
42
+ .select((eb) => eb.fn.countAll<string>().as("n"))
43
+ .where("mount", "=", mount)
44
+ .where("payload", "=", json)
45
+ .executeTakeFirstOrThrow();
46
+ if (Number(row.n) <= failTimes) throw new Error(`fake-lifecycle: call ${row.n} fails`);
47
+ }
48
+ await db.insertInto("deliveries").values({ mount, payload: json }).execute();
49
+ }
50
+
51
+ export default defineExtension({
52
+ name: "fake-lifecycle",
53
+ version: "0.1.0",
54
+ sdk: "^0.1.0-rc.0",
55
+ provides: [],
56
+ migrations: "../migrations",
57
+ config: { deployment: DeploymentConfig },
58
+ permissions: { hooks: ["org.member_removed", "agent.deleted", "org.deleted"] },
59
+ setup(ctx) {
60
+ ctx.hooks.on(
61
+ "org.member_removed",
62
+ (p, _signal, call) => handle(ctx.db, "org.member_removed", p, call),
63
+ { mode: "observe" },
64
+ );
65
+ ctx.hooks.on("agent.deleted", (p, _signal, call) => handle(ctx.db, "agent.deleted", p, call), {
66
+ mode: "observe",
67
+ });
68
+ ctx.hooks.on("org.deleted", (p, _signal, call) => handle(ctx.db, "org.deleted", p, call), {
69
+ mode: "observe",
70
+ });
71
+ },
72
+ });
@@ -3,7 +3,7 @@ import { z } from "zod";
3
3
 
4
4
  /**
5
5
  * Test fake of an extension that uses `ctx.storage` (`permissions.storage`): tool `note`
6
- * (model-visible `fake-storage-user__note`) writes the text to `notes/<conversationId>.txt`, which
6
+ * (model-visible `plugin__fake-storage-user__note`) writes the text to `notes/<conversationId>.txt`, which
7
7
  * the kernel prefixes with `plugins/fake-storage-user/<orgId>/`, and returns the stored size; tool
8
8
  * `read_note` returns it (or says there is none). Needs an `object-store@1` provider.
9
9
  */
@@ -4,4 +4,4 @@ description: Keep a short item list for the conversation with the fake-tools-ui
4
4
  ---
5
5
  # fake-notes
6
6
 
7
- Call `fake-tools-ui__write` with every item of the list.
7
+ Call `plugin__fake-tools-ui__write` with every item of the list.
@@ -11,8 +11,10 @@ import { z } from "zod";
11
11
  * Test fake of a tool + UI extension: the kernel contracts an extension tool, a schema-rendered
12
12
  * view, a migration and a full plugin bundle exercise, without the official todo plugin. Like todo
13
13
  * it needs no object store (storage is `fake-storage-user`'s).
14
- * - tool `write` (model-visible `fake-tools-ui__write`, default policy allow): replaces the
14
+ * - tool `write` (model-visible `plugin__fake-tools-ui__write`, default policy allow): replaces the
15
15
  * conversation's item list in the extension's own table, then invalidates the view `tasks`;
16
+ * - tool `web-only` (default policy allow, `sources: ["web", "channel_dm"]`): returns, as JSON
17
+ * text, the call's `source`, `ownerAccountId`, `accountId` and `role`;
16
18
  * - view `tasks` (conversation tab): badge `<done>/<total>` and a checklist;
17
19
  * - the plugin also ships the skill `fake-notes` and the connector template `fake-notes`
18
20
  * (for the `fake-connector` extension).
@@ -62,6 +64,16 @@ const WRITE: ToolSpec = {
62
64
  defaultPolicy: "allow",
63
65
  };
64
66
 
67
+ const WEB_ONLY: ToolSpec = {
68
+ name: "web-only",
69
+ description:
70
+ "Report who and where this call runs: the conversation source, its owner, the caller and the " +
71
+ "caller's role. Offered only in web and direct-message conversations. Test fixture only.",
72
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
73
+ defaultPolicy: "allow",
74
+ sources: ["web", "channel_dm"],
75
+ };
76
+
65
77
  const render = (items: FakeItem[]): string =>
66
78
  items.length === 0
67
79
  ? "The list is now empty."
@@ -104,8 +116,31 @@ export default defineExtension({
104
116
  sdk: "^0.1.0-rc.0",
105
117
  provides: [],
106
118
  migrations: "../migrations",
107
- ui: [{ id: "tasks", title: { zh: "条目", en: "Items" }, place: "conversation", kind: "view" }],
108
- permissions: { tools: ["write"], ui: { views: ["tasks"] } },
119
+ ui: [
120
+ { id: "tasks", title: { zh: "条目", en: "Items" }, slot: "conversation.panel", kind: "view" },
121
+ {
122
+ id: "agent-notes",
123
+ title: { zh: "智能体备注", en: "Agent notes" },
124
+ slot: "agent.detail.section",
125
+ kind: "view",
126
+ },
127
+ {
128
+ id: "org-admin",
129
+ title: { zh: "组织设置扩展", en: "Org admin" },
130
+ slot: "org.settings.section",
131
+ kind: "view",
132
+ },
133
+ {
134
+ id: "platform-home",
135
+ title: { zh: "平台首页", en: "Platform home" },
136
+ slot: "platform.page",
137
+ kind: "view",
138
+ },
139
+ ],
140
+ permissions: {
141
+ tools: ["write", "web-only"],
142
+ ui: { views: ["tasks", "agent-notes", "org-admin", "platform-home"] },
143
+ },
109
144
  setup(ctx) {
110
145
  ctx.tools.register(WRITE, async (input, tctx) => {
111
146
  const parsed = WriteInput.safeParse(input);
@@ -133,8 +168,32 @@ export default defineExtension({
133
168
  },
134
169
  };
135
170
  });
171
+ ctx.tools.register(WEB_ONLY, async (_input, tctx) => {
172
+ const { source, ownerAccountId, accountId, role } = tctx;
173
+ return {
174
+ content: [
175
+ { type: "text", text: JSON.stringify({ source, ownerAccountId, accountId, role }) },
176
+ ],
177
+ };
178
+ });
136
179
  ctx.ui.view("tasks", async ({ conversationId }) =>
137
180
  tasksView(conversationId === undefined ? [] : await readItems(ctx.db, conversationId)),
138
181
  );
182
+ const ping: UiView["blocks"] = [
183
+ { type: "actions", buttons: [{ actionId: "ping", label: "Ping" }] },
184
+ ];
185
+ const done = async () => ({ toast: { zh: "已完成", en: "Done" } });
186
+ ctx.ui.view("agent-notes", async (args) => ({
187
+ blocks: [{ type: "heading", text: `Agent ${args.agentId ?? ""}`.trim() }, ...ping],
188
+ }));
189
+ ctx.ui.action("agent-notes", done);
190
+ ctx.ui.view("org-admin", async () => ({
191
+ blocks: [{ type: "heading", text: "Org settings" }, ...ping],
192
+ }));
193
+ ctx.ui.action("org-admin", done);
194
+ ctx.ui.view("platform-home", async () => ({
195
+ blocks: [{ type: "heading", text: "Platform home" }, ...ping],
196
+ }));
197
+ ctx.ui.action("platform-home", done);
139
198
  },
140
199
  });
@@ -0,0 +1,7 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "name": "fake-web",
4
+ "version": "0.1.0",
5
+ "publisher": "Capybara",
6
+ "description": "Test fake: a scripted web search and web fetch provider (web-search@1, web-fetch@1)"
7
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "@capybara-hq/test-plugin-fake-web",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "description": "Test fake: a scripted web search and web fetch provider (web-search@1, web-fetch@1)",
6
+ "license": "Apache-2.0",
7
+ "type": "module",
8
+ "dependencies": {
9
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.0",
10
+ "zod": "^4.6.7"
11
+ }
12
+ }
@@ -0,0 +1,22 @@
1
+ import { defineExtension } from "@capybara-hq/plugin-sdk";
2
+ import { FakeWebOrgConfig, makeFakeWeb } from "./web.js";
3
+
4
+ export { type FakeWebCall, FakeWebOrgConfig, fakeWebProbe, makeFakeWeb } from "./web.js";
5
+
6
+ /**
7
+ * Test fake: a scripted web provider (`web-search@1` and `web-fetch@1`; see `makeFakeWeb` for the
8
+ * scripts). Org config `{ token? }` (secret); `configured()` is true iff the token is set.
9
+ * `fake-web-2` is the same with its own name, for the org default provider.
10
+ */
11
+ export default defineExtension({
12
+ name: "fake-web",
13
+ version: "0.1.0",
14
+ sdk: "^0.1.0-rc.0",
15
+ provides: ["web-search@1", "web-fetch@1"],
16
+ config: { org: FakeWebOrgConfig },
17
+ setup(ctx) {
18
+ const { search, fetch } = makeFakeWeb("fake-web");
19
+ ctx.provide("web-search@1", search);
20
+ ctx.provide("web-fetch@1", fetch);
21
+ },
22
+ });
@@ -0,0 +1,183 @@
1
+ import {
2
+ secret,
3
+ type WebFetchPage,
4
+ type WebFetchProvider,
5
+ WebProviderError,
6
+ type WebProviderErrorKind,
7
+ type WebSearchProvider,
8
+ type WebSearchResult,
9
+ } from "@capybara-hq/plugin-sdk";
10
+ import { z } from "zod";
11
+
12
+ // fake-web/src/web.ts and fake-web-2/src/web.ts are byte-identical (a plugin imports only from its
13
+ // own directory); test/fixtures.test.ts of @capybara-hq/testing keeps them equal.
14
+
15
+ /**
16
+ * Org config of the fake web providers: `configured()` is true iff `token` is set (and throws for
17
+ * the token `throw:configured`).
18
+ */
19
+ export const FakeWebOrgConfig = z.object({ token: secret(z.string().min(1)).optional() });
20
+
21
+ /** One provider call, recorded on `globalThis.__fakeWeb` (in-process kernels only). */
22
+ export interface FakeWebCall {
23
+ provider: string;
24
+ op: "search" | "fetch";
25
+ /** The query (search) or the URL (fetch). */
26
+ input: string;
27
+ }
28
+
29
+ /** The probe tests read: every call of every fake web provider in this process. */
30
+ export function fakeWebProbe(): { calls: FakeWebCall[] } {
31
+ const g = globalThis as { __fakeWeb?: { calls: FakeWebCall[] } };
32
+ g.__fakeWeb ??= { calls: [] };
33
+ return g.__fakeWeb;
34
+ }
35
+
36
+ // capybara:allow-module-state a read-only constant list
37
+ const KINDS: readonly WebProviderErrorKind[] = [
38
+ "not_found",
39
+ "blocked",
40
+ "auth",
41
+ "rate_limited",
42
+ "unavailable",
43
+ "invalid",
44
+ ];
45
+
46
+ /** True iff the token is set; the token `throw:configured` makes it throw. */
47
+ const configured = (orgConfig: unknown): boolean => {
48
+ const token = (orgConfig as { token?: unknown } | null)?.token;
49
+ if (token === "throw:configured") throw new Error("fake web: configured() failed");
50
+ return typeof token === "string" && token.length > 0;
51
+ };
52
+
53
+ /** The script of a fetch: the decoded URL path (and query) after the first `/`. */
54
+ function fetchScript(url: string): string {
55
+ try {
56
+ const u = new URL(url);
57
+ return decodeURIComponent(u.pathname.slice(1)) + u.search;
58
+ } catch {
59
+ return "";
60
+ }
61
+ }
62
+
63
+ /** Rejects with the signal's reason once it aborts (`hang:`). */
64
+ function hang(signal: AbortSignal): Promise<never> {
65
+ return new Promise((_, reject) => {
66
+ if (signal.aborted) reject(signal.reason);
67
+ else signal.addEventListener("abort", () => reject(signal.reason), { once: true });
68
+ });
69
+ }
70
+
71
+ /** The scripted failures shared by search and fetch; returns normally for other scripts. */
72
+ async function scriptedFailure(name: string, script: string, signal: AbortSignal): Promise<void> {
73
+ if (script.startsWith("error:")) {
74
+ const kind = script.slice("error:".length).split(/[\s/?]/)[0] as WebProviderErrorKind;
75
+ if (!KINDS.includes(kind)) throw new Error(`${name}: unknown scripted error kind ${kind}`);
76
+ throw new WebProviderError(`${name}: scripted ${kind} failure`, { kind });
77
+ }
78
+ if (script.startsWith("throw:")) {
79
+ throw new Error(`${name} internal failure: ${script.slice("throw:".length)}`);
80
+ }
81
+ if (script.startsWith("hang:")) await hang(signal);
82
+ }
83
+
84
+ /**
85
+ * The two providers of a fake web extension named `name`. Behavior is scripted by a prefix of the
86
+ * search `query`, or of the fetched URL's path after the first `/` (e.g.
87
+ * `https://example.com/redirect:https://other.com/x`):
88
+ * - `error:<kind>`: throws `WebProviderError` of that kind;
89
+ * - `throw:<text>`: throws a plain `Error` whose message names the provider and carries `<text>`;
90
+ * - `hang:`: waits until the signal aborts, then rejects with its reason;
91
+ * - `redirect:<url>` (fetch): the page's `finalUrl` is `<url>`;
92
+ * - `redirect-long:<n>` (fetch): the page's `finalUrl` is `https://example.com/` followed by `n`
93
+ * characters;
94
+ * - `junk:` (search): unusable results (relative URL, `javascript:`, `ftp:`, empty title) plus one
95
+ * usable result and a second result with its URL; `junk:all`: only the four unusable ones;
96
+ * - `idn:` (search): one result on the IDN host `bücher.example` (its URL parses to the punycode
97
+ * host `xn--bcher-kva.example`) and one on example.org;
98
+ * - `empty:`: no results (search) / an empty `markdown` (fetch);
99
+ * - `big:<n>`: `n` results, ignoring `maxResults` (search) / `n` characters of markdown (fetch).
100
+ * Anything else: three results on docs.example.com, example.org and www.example.net (search) or
101
+ * a short page (fetch). Every title, snippet and page names the provider.
102
+ */
103
+ export function makeFakeWeb(name: string): { search: WebSearchProvider; fetch: WebFetchProvider } {
104
+ const search: WebSearchProvider = {
105
+ configured,
106
+ async search({ query, signal }) {
107
+ fakeWebProbe().calls.push({ provider: name, op: "search", input: query });
108
+ await scriptedFailure(name, query, signal);
109
+ if (query.startsWith("empty:")) return { results: [] };
110
+ if (query.startsWith("idn:")) {
111
+ return {
112
+ results: [
113
+ { title: `${name} idn`, url: `https://bücher.example/${name}/1` },
114
+ { title: `${name} other`, url: `https://example.org/${name}/2` },
115
+ ],
116
+ };
117
+ }
118
+ if (query.startsWith("junk:")) {
119
+ const bad: WebSearchResult[] = [
120
+ { title: `${name} relative`, url: "/relative/path" },
121
+ { title: `${name} script`, url: "javascript:alert(1)" },
122
+ { title: `${name} ftp`, url: "ftp://example.com/file" },
123
+ { title: "", url: "https://example.com/untitled" },
124
+ ];
125
+ if (query.startsWith("junk:all")) return { results: bad };
126
+ return {
127
+ results: [
128
+ ...bad,
129
+ { title: `${name} first`, url: "https://example.com/dup" },
130
+ { title: `${name} again`, url: "https://example.com/dup" },
131
+ ],
132
+ };
133
+ }
134
+ if (query.startsWith("big:")) {
135
+ const n = Number.parseInt(query.slice("big:".length), 10) || 0;
136
+ return {
137
+ results: Array.from({ length: n }, (_, i) => ({
138
+ title: `${name} result ${i + 1}`,
139
+ url: `https://example.com/${name}/${i + 1}`,
140
+ snippet: `${name} snippet ${i + 1} for ${query}`,
141
+ })),
142
+ };
143
+ }
144
+ const hosts = ["docs.example.com", "example.org", "www.example.net"];
145
+ const results: WebSearchResult[] = hosts.map((h, i) => ({
146
+ title: `${name} result ${i + 1}`,
147
+ url: `https://${h}/${name}/${i + 1}`,
148
+ snippet: `${name} snippet ${i + 1} for ${query}`,
149
+ publishedAt: "2026-11-01",
150
+ }));
151
+ return { results };
152
+ },
153
+ };
154
+ const fetch: WebFetchProvider = {
155
+ configured,
156
+ async fetch({ url, signal }): Promise<WebFetchPage> {
157
+ fakeWebProbe().calls.push({ provider: name, op: "fetch", input: url });
158
+ const script = fetchScript(url);
159
+ await scriptedFailure(name, script, signal);
160
+ if (script.startsWith("redirect-long:")) {
161
+ const n = Number.parseInt(script.slice("redirect-long:".length), 10) || 0;
162
+ const finalUrl = `https://example.com/${"a".repeat(n)}`;
163
+ return { finalUrl, title: `${name} redirect`, markdown: "Moved." };
164
+ }
165
+ if (script.startsWith("redirect:")) {
166
+ const finalUrl = script.slice("redirect:".length);
167
+ return { finalUrl, title: `${name} redirect`, markdown: `Moved to ${finalUrl}.` };
168
+ }
169
+ if (script.startsWith("empty:")) return { finalUrl: url, markdown: "" };
170
+ if (script.startsWith("big:")) {
171
+ const n = Number.parseInt(script.slice("big:".length), 10) || 0;
172
+ return { finalUrl: url, title: `${name} big page`, markdown: "x".repeat(n) };
173
+ }
174
+ return {
175
+ finalUrl: url,
176
+ title: `${name} page`,
177
+ markdown: `# Page from ${name}\n\nFetched ${url} with ${name}.`,
178
+ contentType: "text/html",
179
+ };
180
+ },
181
+ };
182
+ return { search, fetch };
183
+ }
@@ -0,0 +1,7 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "name": "fake-web-2",
4
+ "version": "0.1.0",
5
+ "publisher": "Capybara",
6
+ "description": "Test fake: a scripted web search and web fetch provider (web-search@1, web-fetch@1)"
7
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "@capybara-hq/test-plugin-fake-web-2",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "description": "Test fake: a scripted web search and web fetch provider (web-search@1, web-fetch@1)",
6
+ "license": "Apache-2.0",
7
+ "type": "module",
8
+ "dependencies": {
9
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.0",
10
+ "zod": "^4.6.7"
11
+ }
12
+ }
@@ -0,0 +1,16 @@
1
+ import { defineExtension } from "@capybara-hq/plugin-sdk";
2
+ import { FakeWebOrgConfig, makeFakeWeb } from "./web.js";
3
+
4
+ /** Test fake: `fake-web` under another name (a second provider of `web-search@1` / `web-fetch@1`). */
5
+ export default defineExtension({
6
+ name: "fake-web-2",
7
+ version: "0.1.0",
8
+ sdk: "^0.1.0-rc.0",
9
+ provides: ["web-search@1", "web-fetch@1"],
10
+ config: { org: FakeWebOrgConfig },
11
+ setup(ctx) {
12
+ const { search, fetch } = makeFakeWeb("fake-web-2");
13
+ ctx.provide("web-search@1", search);
14
+ ctx.provide("web-fetch@1", fetch);
15
+ },
16
+ });