@capybara-hq/testing 0.1.0-rc.3 → 0.1.0-rc.30

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 (92) hide show
  1. package/dist/containers.d.ts +7 -2
  2. package/dist/containers.js +7 -3
  3. package/dist/dual-replica.d.ts +15 -1
  4. package/dist/dual-replica.js +49 -0
  5. package/dist/fake-channel.d.ts +51 -3
  6. package/dist/fake-channel.js +71 -3
  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-lark.d.ts +12 -1
  12. package/dist/fake-lark.js +63 -10
  13. package/dist/fake-oauth-server.d.ts +16 -2
  14. package/dist/fake-oauth-server.js +21 -1
  15. package/dist/fake-slack.d.ts +17 -1
  16. package/dist/fake-slack.js +98 -0
  17. package/dist/fake-telegram.d.ts +173 -0
  18. package/dist/fake-telegram.js +632 -0
  19. package/dist/fixtures.d.ts +25 -7
  20. package/dist/fixtures.js +35 -7
  21. package/dist/index.d.ts +12 -8
  22. package/dist/index.js +8 -4
  23. package/dist/kernel-helpers.d.ts +16 -4
  24. package/dist/kernel-helpers.js +39 -4
  25. package/dist/media-samples.d.ts +2 -0
  26. package/dist/media-samples.js +2 -0
  27. package/dist/model-conformance.d.ts +15 -10
  28. package/dist/model-conformance.js +87 -14
  29. package/dist/push-conformance.d.ts +31 -0
  30. package/dist/push-conformance.js +160 -0
  31. package/dist/replica-runner.js +2 -0
  32. package/dist/sandbox-native-conformance.d.ts +31 -0
  33. package/dist/sandbox-native-conformance.js +153 -0
  34. package/dist/sandbox-permission-conformance.d.ts +307 -0
  35. package/dist/sandbox-permission-conformance.js +1475 -0
  36. package/fixtures/extensions/fake-client/.capybara-plugin/plugin.json +11 -0
  37. package/fixtures/extensions/fake-client/client/styles/fake.css +11 -0
  38. package/fixtures/extensions/fake-client/package.json +12 -0
  39. package/fixtures/extensions/fake-client/src/client.tsx +51 -0
  40. package/fixtures/extensions/fake-client/src/index.ts +43 -0
  41. package/fixtures/extensions/fake-client/themes/fake.json +11 -0
  42. package/fixtures/extensions/fake-client-broken/.capybara-plugin/plugin.json +7 -0
  43. package/fixtures/extensions/fake-client-broken/package.json +12 -0
  44. package/fixtures/extensions/fake-client-broken/src/client.tsx +22 -0
  45. package/fixtures/extensions/fake-client-broken/src/index.ts +27 -0
  46. package/fixtures/extensions/fake-config-form/.capybara-plugin/plugin.json +11 -0
  47. package/fixtures/extensions/fake-config-form/package.json +12 -0
  48. package/fixtures/extensions/fake-config-form/src/index.ts +205 -0
  49. package/fixtures/extensions/fake-connector/src/index.ts +41 -21
  50. package/fixtures/extensions/fake-context/.capybara-plugin/plugin.json +7 -0
  51. package/fixtures/extensions/fake-context/package.json +12 -0
  52. package/fixtures/extensions/fake-context/src/index.ts +81 -0
  53. package/fixtures/extensions/fake-dep-provider/src/index.ts +1 -1
  54. package/fixtures/extensions/fake-dep-requirer/src/index.ts +1 -1
  55. package/fixtures/extensions/fake-embed/src/index.ts +26 -26
  56. package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +7 -1
  57. package/fixtures/extensions/fake-im/guides/fake-im-app.md +32 -0
  58. package/fixtures/extensions/fake-im/guides/fake-im-app.zh.md +32 -0
  59. package/fixtures/extensions/fake-im/src/channel.ts +22 -1
  60. package/fixtures/extensions/fake-im/src/checks.ts +94 -0
  61. package/fixtures/extensions/fake-im/src/index.ts +45 -2
  62. package/fixtures/extensions/fake-lifecycle/.capybara-plugin/plugin.json +7 -0
  63. package/fixtures/extensions/fake-lifecycle/migrations/0001_init.sql +16 -0
  64. package/fixtures/extensions/fake-lifecycle/package.json +12 -0
  65. package/fixtures/extensions/fake-lifecycle/src/index.ts +72 -0
  66. package/fixtures/extensions/fake-openapi/src/index.ts +46 -34
  67. package/fixtures/extensions/fake-push/.capybara-plugin/plugin.json +13 -0
  68. package/fixtures/extensions/fake-push/guides/fake-push-key.md +6 -0
  69. package/fixtures/extensions/fake-push/guides/fake-push-key.zh.md +6 -0
  70. package/fixtures/extensions/fake-push/migrations/0001_sends.sql +9 -0
  71. package/fixtures/extensions/fake-push/package.json +12 -0
  72. package/fixtures/extensions/fake-push/src/check.ts +40 -0
  73. package/fixtures/extensions/fake-push/src/index.ts +48 -0
  74. package/fixtures/extensions/fake-push/src/push.ts +103 -0
  75. package/fixtures/extensions/fake-storage-user/src/index.ts +1 -1
  76. package/fixtures/extensions/fake-tools-ui/skills/fake-notes/SKILL.md +1 -1
  77. package/fixtures/extensions/fake-tools-ui/src/index.ts +62 -3
  78. package/fixtures/extensions/fake-web/.capybara-plugin/plugin.json +7 -0
  79. package/fixtures/extensions/fake-web/package.json +12 -0
  80. package/fixtures/extensions/fake-web/src/index.ts +22 -0
  81. package/fixtures/extensions/fake-web/src/web.ts +183 -0
  82. package/fixtures/extensions/fake-web-2/.capybara-plugin/plugin.json +7 -0
  83. package/fixtures/extensions/fake-web-2/package.json +12 -0
  84. package/fixtures/extensions/fake-web-2/src/index.ts +16 -0
  85. package/fixtures/extensions/fake-web-2/src/web.ts +183 -0
  86. package/fixtures/plugins/fake-theme/.capybara-plugin/plugin.json +7 -0
  87. package/fixtures/plugins/fake-theme/fonts/FakeSans.woff2 +1 -0
  88. package/fixtures/plugins/fake-theme/logo.svg +1 -0
  89. package/fixtures/plugins/fake-theme/package.json +8 -0
  90. package/fixtures/plugins/fake-theme/themes/neon-grid.json +13 -0
  91. package/fixtures/plugins/fake-theme/themes/paper.json +12 -0
  92. package/package.json +6 -5
@@ -0,0 +1,81 @@
1
+ import {
2
+ type ContextProvider,
3
+ type ContextRequest,
4
+ defineExtension,
5
+ type ToolSpec,
6
+ } from "@capybara-hq/plugin-sdk";
7
+ import { z } from "zod";
8
+
9
+ /**
10
+ * Test fake of a `context@1` provider (memory plugin spec §6.1). Its behavior follows its
11
+ * deployment config, which the kernel passes back as the request's effective `config`:
12
+ * - `mode: "ok"` (default): returns `{ text }` (`text` default "fake context");
13
+ * - `mode: "null"`: returns null (nothing to add);
14
+ * - `mode: "throw"`: throws;
15
+ * - `mode: "hang"`: waits until the request's signal aborts, then rejects with its reason.
16
+ * Every call is recorded (the request without its signal) on `globalThis.__fakeContext`
17
+ * ({@link fakeContextProbe}; in-process kernels only). It also registers the tool `note` (default
18
+ * policy allow, `sources: ["web", "channel_dm"]`), so `tools` in a request lists
19
+ * `plugin__fake-context__note` only in one-to-one conversations. Its org config (`label`, default
20
+ * "") exists only so a test can store an org copy that no longer validates.
21
+ */
22
+
23
+ const DeploymentConfig = z.object({
24
+ text: z.string().default("fake context"),
25
+ mode: z.enum(["ok", "null", "throw", "hang"]).default("ok"),
26
+ });
27
+
28
+ /** An org-only config (all defaults), so a test can make the org's stored copy invalid. */
29
+ const OrgConfig = z.object({ label: z.string().default("") });
30
+
31
+ /** One `provide` call: the request the kernel sent, without its signal. */
32
+ export type FakeContextCall = Omit<ContextRequest, "signal">;
33
+
34
+ /** The probe tests read: every `provide` call of this process. */
35
+ export function fakeContextProbe(): { calls: FakeContextCall[] } {
36
+ const g = globalThis as { __fakeContext?: { calls: FakeContextCall[] } };
37
+ g.__fakeContext ??= { calls: [] };
38
+ return g.__fakeContext;
39
+ }
40
+
41
+ /** Rejects with the signal's reason once it aborts. */
42
+ function hang(signal: AbortSignal): Promise<never> {
43
+ return new Promise((_, reject) => {
44
+ if (signal.aborted) reject(signal.reason);
45
+ else signal.addEventListener("abort", () => reject(signal.reason), { once: true });
46
+ });
47
+ }
48
+
49
+ const NOTE: ToolSpec = {
50
+ name: "note",
51
+ description:
52
+ "Acknowledge a note. Offered only in web and direct-message conversations. Test fixture only.",
53
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
54
+ defaultPolicy: "allow",
55
+ sources: ["web", "channel_dm"],
56
+ };
57
+
58
+ const provider: ContextProvider = {
59
+ async provide(req) {
60
+ const { signal, ...call } = req;
61
+ fakeContextProbe().calls.push(call);
62
+ const cfg = DeploymentConfig.parse(req.config ?? {});
63
+ if (cfg.mode === "throw") throw new Error("fake-context: scripted failure");
64
+ if (cfg.mode === "hang") await hang(signal);
65
+ if (cfg.mode === "null") return null;
66
+ return { text: cfg.text };
67
+ },
68
+ };
69
+
70
+ export default defineExtension({
71
+ name: "fake-context",
72
+ version: "0.1.0",
73
+ sdk: "^0.1.0-rc.0",
74
+ provides: ["context@1"],
75
+ config: { deployment: DeploymentConfig, org: OrgConfig },
76
+ permissions: { tools: ["note"] },
77
+ setup(ctx) {
78
+ ctx.provide("context@1", provider);
79
+ ctx.tools.register(NOTE, async () => ({ content: [{ type: "text", text: "Noted." }] }));
80
+ },
81
+ });
@@ -10,7 +10,7 @@ export default defineExtension({
10
10
  version: "0.1.0",
11
11
  sdk: "^0.1.0-rc.0",
12
12
  provides: ["counter@1"],
13
- permissions: { http: [{ method: "GET", path: "/ping" }] },
13
+ permissions: { http: [{ method: "GET", path: "/ping", access: "public" }] },
14
14
  setup(ctx) {
15
15
  const pong = "pong from fake-dep-provider";
16
16
  ctx.provide("counter@1", { ping: () => pong });
@@ -11,7 +11,7 @@ export default defineExtension({
11
11
  sdk: "^0.1.0-rc.0",
12
12
  provides: [],
13
13
  requires: ["counter@1"],
14
- permissions: { http: [{ method: "GET", path: "/ping" }] },
14
+ permissions: { http: [{ method: "GET", path: "/ping", access: "public" }] },
15
15
  setup(ctx) {
16
16
  ctx.http.route("GET", "/ping", async () => {
17
17
  const impl = ctx.extensionPoints.list<{ ping(): string }>("counter@1")[0]?.impl;
@@ -1,27 +1,27 @@
1
- import { defineExtension, EMBED_PROTOCOL, type EmbedClaims } from "@capybara-hq/plugin-sdk";
1
+ import { defineExtension, EMBED_PROTOCOL, type RouteCaller } from "@capybara-hq/plugin-sdk";
2
2
  import { z } from "zod";
3
3
 
4
4
  /**
5
5
  * Test fake of an embed extension (`ui.embeds`): the kernel side of embedded apps (token issue and
6
6
  * verification, the `/plugin-ui` proxy, `ctx.bus` across replicas) without the official board.
7
7
  * - embeds `panel` (org page, `/ui/panel`) and `panel-conv` (conversation tab, `/ui/panel-conv`);
8
- * both pages are static HTML loading the static script `/ui/panel.js`; none of them needs a
9
- * token. The script speaks the host's message bridge (`capybara-embed/1`): on `init` it fetches
8
+ * both pages are static HTML loading the static script `/ui/panel.js`; all three are `public`
9
+ * GET routes (an iframe navigation carries no token). The script speaks the host's message bridge (`capybara-embed/1`): on `init` it fetches
10
10
  * `claims` with the token it was given, shows `<contribution> <orgId>` in `#status` and posts a
11
11
  * `toast` "fake-embed ready" to the host (a failed fetch shows `error <status>`), then reads the
12
12
  * `/ui/events` stream with the token: `ready` sets `data-live="1"` on the body, each `event`
13
13
  * shows its text in `#event`;
14
- * - every data route checks `Authorization: Bearer <embed token>` with `ctx.ui.verifyEmbedToken`
15
- * (401 otherwise); identity comes only from the claims;
16
- * - `GET /ui/claims` returns the verified claims;
14
+ * - every data route is an `embed` route: the kernel checks the embed token (`Authorization: Bearer`
15
+ * or `?token=`) and hands the handler the caller; identity comes only from `caller` (an org-scope
16
+ * caller, 401 otherwise);
17
+ * - `GET /ui/claims` returns the caller;
17
18
  * - `POST /ui/events` `{ text }` publishes `{ conversationId, text }` on the bus topic
18
19
  * `events.<orgId>` (202);
19
20
  * - `GET /ui/events` is an SSE stream: `ready` first, then an `event` for each message in the
20
21
  * token's scope (its conversation, or org-wide messages for a page token); it ends when the
21
- * client disconnects or the token expires.
22
+ * client disconnects or the token expires (`caller.exp`).
22
23
  */
23
24
 
24
- const BEARER_RE = /^Bearer ([A-Za-z0-9._-]{1,4096})$/;
25
25
  const EventBody = z.object({ text: z.string().min(1).max(200) });
26
26
 
27
27
  const PAGE = `<!doctype html><html><head><meta charset="utf-8"><title>Fake embed</title><script src="./panel.js"></script></head><body><p>fake-embed</p><p id="status">waiting</p><p id="event"></p></body></html>`;
@@ -96,34 +96,33 @@ export default defineExtension({
96
96
  {
97
97
  id: "panel",
98
98
  title: { zh: "面板", en: "Panel" },
99
- place: "page",
99
+ slot: "org.page",
100
100
  kind: "embed",
101
101
  path: "/ui/panel",
102
102
  },
103
103
  {
104
104
  id: "panel-conv",
105
105
  title: { zh: "面板", en: "Panel" },
106
- place: "conversation",
106
+ slot: "conversation.panel",
107
107
  kind: "embed",
108
108
  path: "/ui/panel-conv",
109
109
  },
110
110
  ],
111
111
  permissions: {
112
112
  http: [
113
- { method: "GET", path: "/ui/panel" },
114
- { method: "GET", path: "/ui/panel-conv" },
115
- { method: "GET", path: "/ui/panel.js" },
116
- { method: "GET", path: "/ui/claims" },
117
- { method: "POST", path: "/ui/events" },
118
- { method: "GET", path: "/ui/events" },
113
+ { method: "GET", path: "/ui/panel", access: "public" },
114
+ { method: "GET", path: "/ui/panel-conv", access: "public" },
115
+ { method: "GET", path: "/ui/panel.js", access: "public" },
116
+ { method: "GET", path: "/ui/claims", access: "embed" },
117
+ { method: "POST", path: "/ui/events", access: "embed" },
118
+ { method: "GET", path: "/ui/events", access: "embed" },
119
119
  ],
120
120
  ui: { embeds: ["panel", "panel-conv"] },
121
121
  },
122
122
  setup(ctx) {
123
- const auth = async (req: Request): Promise<EmbedClaims | null> => {
124
- const m = BEARER_RE.exec(req.headers.get("authorization") ?? "");
125
- return m?.[1] === undefined ? null : ctx.ui.verifyEmbedToken(m[1]);
126
- };
123
+ /** The org-scope embed caller (every contribution here is in an org slot), or null. */
124
+ const auth = (caller: RouteCaller) =>
125
+ caller.access === "embed" && caller.scope === "org" ? caller : null;
127
126
  const page = async () =>
128
127
  new Response(PAGE, { headers: { "content-type": "text/html; charset=utf-8" } });
129
128
  ctx.http.route("GET", "/ui/panel", page);
@@ -135,13 +134,13 @@ export default defineExtension({
135
134
  new Response(SCRIPT, { headers: { "content-type": "text/javascript; charset=utf-8" } }),
136
135
  );
137
136
 
138
- ctx.http.route("GET", "/ui/claims", async (req) => {
139
- const claims = await auth(req);
137
+ ctx.http.route("GET", "/ui/claims", async (_req, caller) => {
138
+ const claims = auth(caller);
140
139
  return claims ? json(200, claims) : unauthorized();
141
140
  });
142
141
 
143
- ctx.http.route("POST", "/ui/events", async (req) => {
144
- const claims = await auth(req);
142
+ ctx.http.route("POST", "/ui/events", async (req, caller) => {
143
+ const claims = auth(caller);
145
144
  if (!claims) return unauthorized();
146
145
  const body = EventBody.safeParse(await req.json().catch(() => undefined));
147
146
  if (!body.success) {
@@ -154,9 +153,10 @@ export default defineExtension({
154
153
  return json(202, { published: true });
155
154
  });
156
155
 
157
- ctx.http.route("GET", "/ui/events", async (req) => {
158
- const claims = await auth(req);
156
+ ctx.http.route("GET", "/ui/events", async (req, caller) => {
157
+ const claims = auth(caller);
159
158
  if (!claims) return unauthorized();
159
+ // ends when the client disconnects or the token expires (`caller.exp`)
160
160
  const done = AbortSignal.any([
161
161
  req.signal,
162
162
  AbortSignal.timeout(Math.max(1, claims.exp * 1000 - Date.now())),
@@ -3,5 +3,11 @@
3
3
  "name": "fake-im",
4
4
  "version": "0.1.0",
5
5
  "publisher": "Capybara",
6
- "description": "Test fake: a whole IM platform for startFakeChannelServer (channel@1, identity-source@1, directory@1) and a write tool that asks"
6
+ "description": "Test fake: a whole IM platform for startFakeChannelServer (channel@1, identity-source@1, directory@1) and a write tool that asks",
7
+ "setupGuides": [
8
+ {
9
+ "id": "fake-im-app",
10
+ "place": "channel-connection"
11
+ }
12
+ ]
7
13
  }
@@ -0,0 +1,32 @@
1
+ # Create the fake IM app
2
+
3
+ Open the fake platform console and create an app from the manifest below.
4
+
5
+ ::: mode long_connection
6
+
7
+ ```yaml title="App manifest"
8
+ # The fake IM app, fake-im {{pluginVersion}}.
9
+ app:
10
+ name: "{{connectionName}}"
11
+ long_connection: true
12
+ sign_in_redirect: "{{signInCallbackUrl}}"
13
+ ```
14
+
15
+ :::
16
+
17
+ ::: mode webhook
18
+
19
+ The platform posts events to `{{webhookUrl}}`.
20
+
21
+ ```json title="App manifest"
22
+ {
23
+ "app": {
24
+ "name": "{{connectionName}}",
25
+ "long_connection": false,
26
+ "request_url": "{{webhookUrl}}",
27
+ "sign_in_redirect": "{{signInCallbackUrl}}"
28
+ }
29
+ }
30
+ ```
31
+
32
+ :::
@@ -0,0 +1,32 @@
1
+ # 创建 fake IM 应用
2
+
3
+ 打开 fake 平台控制台,用下面的 manifest 创建应用。
4
+
5
+ ::: mode long_connection
6
+
7
+ ```yaml title="应用 manifest"
8
+ # The fake IM app, fake-im {{pluginVersion}}.
9
+ app:
10
+ name: "{{connectionName}}"
11
+ long_connection: true
12
+ sign_in_redirect: "{{signInCallbackUrl}}"
13
+ ```
14
+
15
+ :::
16
+
17
+ ::: mode webhook
18
+
19
+ 平台把事件发到 `{{webhookUrl}}`。
20
+
21
+ ```json title="应用 manifest"
22
+ {
23
+ "app": {
24
+ "name": "{{connectionName}}",
25
+ "long_connection": false,
26
+ "request_url": "{{webhookUrl}}",
27
+ "sign_in_redirect": "{{signInCallbackUrl}}"
28
+ }
29
+ }
30
+ ```
31
+
32
+ :::
@@ -6,6 +6,7 @@ import {
6
6
  type ChannelWebhook,
7
7
  type InboundEvent,
8
8
  secret,
9
+ ui,
9
10
  } from "@capybara-hq/plugin-sdk";
10
11
  import { z } from "zod";
11
12
 
@@ -26,8 +27,9 @@ export const FakeImConnection = z.object({
26
27
  /**
27
28
  * Optional secret (also tests PATCH secret semantics); the webhook signing secret: webhook
28
29
  * requests are signed `x-fake-signature: sha256=<hex HMAC-SHA256(webhookToken, raw body)>`.
30
+ * Drawn and required in webhook mode only (`inboundModes`, channel inbound mode fields spec §2).
29
31
  */
30
- webhookToken: secret(z.string().min(1).optional()),
32
+ webhookToken: ui(secret(z.string().min(1).optional()), { inboundModes: ["webhook"] }),
31
33
  /** 被中止后拖这么久才返回(模拟不及时退出的插件)。 */
32
34
  lingerMs: z.number().int().nonnegative().default(0),
33
35
  });
@@ -221,4 +223,23 @@ export const makeFakeImChannel = (
221
223
  const res = await post(c, "/update", body, signal);
222
224
  await res.body?.cancel();
223
225
  },
226
+ ...(features.files !== undefined && {
227
+ async sendFile({ config, target, file, signal, idempotencyKey, locale }) {
228
+ const c = config as ConnConfig;
229
+ const body = {
230
+ appId: c.appId,
231
+ target,
232
+ file: {
233
+ name: file.name,
234
+ contentType: file.contentType,
235
+ kind: file.kind,
236
+ data: Buffer.from(file.data).toString("base64"),
237
+ },
238
+ idempotencyKey,
239
+ locale,
240
+ };
241
+ const res = await post(c, "/send-file", body, signal);
242
+ return (await res.json()) as { messageId: string };
243
+ },
244
+ }),
224
245
  });
@@ -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,22 +81,54 @@ 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);
83
108
  ctx.provide(
84
109
  "channel@1",
85
- makeFakeImChannel({ cards: true, edit: true, threads: true }, { webhook: true }),
110
+ makeFakeImChannel(
111
+ {
112
+ cards: true,
113
+ edit: true,
114
+ threads: true,
115
+ files: { maxBytes: 20_971_520, imageMaxBytes: 10_485_760 },
116
+ },
117
+ { webhook: true },
118
+ ),
86
119
  );
87
120
  ctx.provide("identity-source@1", fakeImIdentitySource);
88
121
  ctx.provide("directory@1", fakeImDirectory);
89
122
  ctx.tools.register(POST_SPEC, postHandler(config));
123
+ // setup checks for the kernel's check runner tests (checks.ts says what each does)
124
+ ctx.setup.check("pass", passCheck);
125
+ ctx.setup.check("fail", failCheck);
126
+ ctx.setup.check("proxy", proxyCheck);
127
+ ctx.setup.check("throw", throwCheck);
128
+ ctx.setup.check("hang", hangCheck);
129
+ ctx.setup.check("ignore-signal", ignoreSignalCheck);
130
+ ctx.setup.check("long", longCheck);
131
+ ctx.setup.check("echo-secret", echoSecretCheck);
132
+ ctx.setup.check("pad-to-limit", padToLimitCheck);
90
133
  },
91
134
  });
@@ -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
+ });