@capybara-hq/testing 0.1.0-rc.4 → 0.1.0-rc.41

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 (99) hide show
  1. package/dist/containers.d.ts +7 -2
  2. package/dist/containers.js +7 -3
  3. package/dist/device-service-conformance.d.ts +38 -0
  4. package/dist/device-service-conformance.js +142 -0
  5. package/dist/dual-replica.d.ts +23 -1
  6. package/dist/dual-replica.js +53 -0
  7. package/dist/fake-channel.d.ts +44 -5
  8. package/dist/fake-channel.js +63 -2
  9. package/dist/fake-dial-in-machine.d.ts +173 -0
  10. package/dist/fake-dial-in-machine.js +429 -0
  11. package/dist/fake-e2b.d.ts +34 -0
  12. package/dist/fake-e2b.js +95 -1
  13. package/dist/fake-git-server.d.ts +32 -4
  14. package/dist/fake-git-server.js +87 -19
  15. package/dist/fake-lark.d.ts +12 -1
  16. package/dist/fake-lark.js +63 -10
  17. package/dist/fake-oauth-server.d.ts +62 -2
  18. package/dist/fake-oauth-server.js +86 -5
  19. package/dist/fake-slack.d.ts +17 -1
  20. package/dist/fake-slack.js +98 -0
  21. package/dist/fake-telegram.d.ts +173 -0
  22. package/dist/fake-telegram.js +632 -0
  23. package/dist/fixtures.d.ts +24 -8
  24. package/dist/fixtures.js +31 -8
  25. package/dist/index.d.ts +15 -9
  26. package/dist/index.js +10 -4
  27. package/dist/kernel-helpers.d.ts +16 -4
  28. package/dist/kernel-helpers.js +39 -4
  29. package/dist/media-samples.d.ts +2 -0
  30. package/dist/media-samples.js +2 -0
  31. package/dist/model-conformance.d.ts +15 -10
  32. package/dist/model-conformance.js +87 -14
  33. package/dist/push-conformance.d.ts +31 -0
  34. package/dist/push-conformance.js +160 -0
  35. package/dist/replica-runner.js +2 -0
  36. package/dist/sandbox-native-conformance.d.ts +31 -0
  37. package/dist/sandbox-native-conformance.js +153 -0
  38. package/dist/sandbox-permission-conformance.d.ts +310 -0
  39. package/dist/sandbox-permission-conformance.js +1491 -0
  40. package/fixtures/extensions/fake-bootstrap-a/src/index.ts +8 -4
  41. package/fixtures/extensions/fake-bootstrap-b/src/index.ts +8 -4
  42. package/fixtures/extensions/fake-client/.capybara-plugin/plugin.json +11 -0
  43. package/fixtures/extensions/fake-client/client/styles/fake.css +11 -0
  44. package/fixtures/extensions/fake-client/package.json +12 -0
  45. package/fixtures/extensions/fake-client/src/client.tsx +51 -0
  46. package/fixtures/extensions/fake-client/src/index.ts +43 -0
  47. package/fixtures/extensions/fake-client/themes/fake.json +11 -0
  48. package/fixtures/extensions/fake-client-broken/.capybara-plugin/plugin.json +7 -0
  49. package/fixtures/extensions/fake-client-broken/package.json +12 -0
  50. package/fixtures/extensions/fake-client-broken/src/client.tsx +22 -0
  51. package/fixtures/extensions/fake-client-broken/src/index.ts +27 -0
  52. package/fixtures/extensions/fake-config-form/src/index.ts +52 -46
  53. package/fixtures/extensions/fake-connector/src/index.ts +64 -34
  54. package/fixtures/extensions/fake-context/.capybara-plugin/plugin.json +7 -0
  55. package/fixtures/extensions/fake-context/package.json +12 -0
  56. package/fixtures/extensions/fake-context/src/index.ts +78 -0
  57. package/fixtures/extensions/fake-dep-provider/src/index.ts +1 -1
  58. package/fixtures/extensions/fake-dep-requirer/src/index.ts +1 -1
  59. package/fixtures/extensions/fake-embed/src/index.ts +26 -26
  60. package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +7 -1
  61. package/fixtures/extensions/fake-im/guides/fake-im-app.md +32 -0
  62. package/fixtures/extensions/fake-im/guides/fake-im-app.zh.md +32 -0
  63. package/fixtures/extensions/fake-im/src/channel.ts +22 -1
  64. package/fixtures/extensions/fake-im/src/checks.ts +94 -0
  65. package/fixtures/extensions/fake-im/src/directory.ts +44 -20
  66. package/fixtures/extensions/fake-im/src/index.ts +59 -11
  67. package/fixtures/extensions/fake-lifecycle/.capybara-plugin/plugin.json +7 -0
  68. package/fixtures/extensions/fake-lifecycle/migrations/0001_init.sql +16 -0
  69. package/fixtures/extensions/fake-lifecycle/package.json +12 -0
  70. package/fixtures/extensions/fake-lifecycle/src/index.ts +72 -0
  71. package/fixtures/extensions/fake-object-store/src/index.ts +12 -8
  72. package/fixtures/extensions/fake-openapi/src/index.ts +46 -34
  73. package/fixtures/extensions/fake-push/.capybara-plugin/plugin.json +13 -0
  74. package/fixtures/extensions/fake-push/guides/fake-push-key.md +6 -0
  75. package/fixtures/extensions/fake-push/guides/fake-push-key.zh.md +6 -0
  76. package/fixtures/extensions/fake-push/migrations/0001_sends.sql +9 -0
  77. package/fixtures/extensions/fake-push/package.json +12 -0
  78. package/fixtures/extensions/fake-push/src/check.ts +40 -0
  79. package/fixtures/extensions/fake-push/src/index.ts +56 -0
  80. package/fixtures/extensions/fake-push/src/push.ts +103 -0
  81. package/fixtures/extensions/fake-tools-ui/src/index.ts +61 -2
  82. package/fixtures/extensions/fake-web/src/index.ts +5 -4
  83. package/fixtures/extensions/fake-web/src/web.ts +11 -7
  84. package/fixtures/extensions/fake-web-2/src/index.ts +2 -2
  85. package/fixtures/extensions/fake-web-2/src/web.ts +11 -7
  86. package/fixtures/plugins/fake-theme/.capybara-plugin/plugin.json +7 -0
  87. package/fixtures/plugins/fake-theme/brand/app-512.png +0 -0
  88. package/fixtures/plugins/fake-theme/brand/app-mask-512.png +0 -0
  89. package/fixtures/plugins/fake-theme/brand/avatars/bot.svg +1 -0
  90. package/fixtures/plugins/fake-theme/brand/avatars/cat.png +0 -0
  91. package/fixtures/plugins/fake-theme/brand/illustration.svg +1 -0
  92. package/fixtures/plugins/fake-theme/brand/unnamed.svg +1 -0
  93. package/fixtures/plugins/fake-theme/fonts/FakeSans.woff2 +1 -0
  94. package/fixtures/plugins/fake-theme/logo.svg +1 -0
  95. package/fixtures/plugins/fake-theme/package.json +8 -0
  96. package/fixtures/plugins/fake-theme/themes/brand-kit.json +24 -0
  97. package/fixtures/plugins/fake-theme/themes/neon-grid.json +13 -0
  98. package/fixtures/plugins/fake-theme/themes/paper.json +12 -0
  99. package/package.json +6 -5
@@ -0,0 +1,78 @@
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. Both deployment fields are
20
+ * org-overridable, so a test can store an org copy (or one 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
+ /** One `provide` call: the request the kernel sent, without its signal. */
29
+ export type FakeContextCall = Omit<ContextRequest, "signal">;
30
+
31
+ /** The probe tests read: every `provide` call of this process. */
32
+ export function fakeContextProbe(): { calls: FakeContextCall[] } {
33
+ const g = globalThis as { __fakeContext?: { calls: FakeContextCall[] } };
34
+ g.__fakeContext ??= { calls: [] };
35
+ return g.__fakeContext;
36
+ }
37
+
38
+ /** Rejects with the signal's reason once it aborts. */
39
+ function hang(signal: AbortSignal): Promise<never> {
40
+ return new Promise((_, reject) => {
41
+ if (signal.aborted) reject(signal.reason);
42
+ else signal.addEventListener("abort", () => reject(signal.reason), { once: true });
43
+ });
44
+ }
45
+
46
+ const NOTE: ToolSpec = {
47
+ name: "note",
48
+ description:
49
+ "Acknowledge a note. Offered only in web and direct-message conversations. Test fixture only.",
50
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
51
+ defaultPolicy: "allow",
52
+ sources: ["web", "channel_dm"],
53
+ };
54
+
55
+ const provider: ContextProvider = {
56
+ async provide(req) {
57
+ const { signal, ...call } = req;
58
+ fakeContextProbe().calls.push(call);
59
+ const cfg = DeploymentConfig.parse(req.config ?? {});
60
+ if (cfg.mode === "throw") throw new Error("fake-context: scripted failure");
61
+ if (cfg.mode === "hang") await hang(signal);
62
+ if (cfg.mode === "null") return null;
63
+ return { text: cfg.text };
64
+ },
65
+ };
66
+
67
+ export default defineExtension({
68
+ name: "fake-context",
69
+ version: "0.1.0",
70
+ sdk: "^0.1.0-rc.0",
71
+ provides: ["context@1"],
72
+ config: { deployment: DeploymentConfig },
73
+ permissions: { tools: ["note"] },
74
+ setup(ctx) {
75
+ ctx.provide("context@1", provider);
76
+ ctx.tools.register(NOTE, async () => ({ content: [{ type: "text", text: "Noted." }] }));
77
+ },
78
+ });
@@ -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
+ });
@@ -1,25 +1,49 @@
1
- import type { Directory, DirectoryMember } from "@capybara-hq/plugin-sdk";
1
+ import {
2
+ configUrlFetch,
3
+ type Directory,
4
+ type DirectoryMember,
5
+ type ExtensionNet,
6
+ } from "@capybara-hq/plugin-sdk";
2
7
  import { z } from "zod";
3
8
 
4
- /** 组织级配置:假平台上一份通讯录的地址(startFakeChannelServer().book(key).url)。 */
5
- export const FakeImOrgConfig = z.object({ url: z.string().url() });
9
+ /**
10
+ * The directory part of the deployment config: the address of a directory book on the fake
11
+ * platform (startFakeChannelServer().book(key).url). Org-overridable: each org sets its own book
12
+ * in its copy. Unset means the directory is not configured (`configured()` false).
13
+ */
14
+ export const FakeImDirectoryConfig = z.object({ directoryUrl: z.string().url().optional() });
6
15
 
7
16
  /**
8
- * 假 IM 平台的 `directory@1`:`listMembers` 按游标 GET `<url>/members?cursor=<c>`(请求头 `x-pid`),
9
- * 非 200 抛错(内核把整轮当作不完整,不移除任何人)。dir-mini 复用它。
17
+ * `directory@1` of the fake IM platform, built in setup from the extension's `ctx.net` and its
18
+ * platform config: `listMembers` GETs `<directoryUrl>/members?cursor=<c>` (header `x-pid`) from the
19
+ * effective config it is given, and throws on anything but 200 (the kernel then treats the round as
20
+ * incomplete and removes nobody). An org's own `directoryUrl` goes through `configUrlFetch`, so it
21
+ * reaches the network through `ctx.net` with the call's `orgId` (the platform's value is fetched
22
+ * directly), so the org's network rules apply. `configured()` is true iff
23
+ * `directoryUrl` is set. dir-mini and dir-opt reuse it.
10
24
  */
11
- export const fakeImDirectory: Directory = {
12
- async listMembers({ orgConfig, cursor, signal }) {
13
- const c = FakeImOrgConfig.parse(orgConfig);
14
- const q = cursor === undefined ? "" : `?cursor=${encodeURIComponent(cursor)}`;
15
- const res = await fetch(`${c.url}/members${q}`, {
16
- signal,
17
- headers: { "x-pid": String(process.pid) },
18
- });
19
- if (res.status !== 200) {
20
- await res.body?.cancel();
21
- throw new Error(`directory returned ${res.status}`);
22
- }
23
- return (await res.json()) as { members: DirectoryMember[]; next?: string };
24
- },
25
- };
25
+ export function makeFakeImDirectory(ctx: {
26
+ net: Pick<ExtensionNet, "fetch">;
27
+ config: unknown;
28
+ }): Directory {
29
+ return {
30
+ configured: (config) =>
31
+ FakeImDirectoryConfig.safeParse(config).data?.directoryUrl !== undefined,
32
+ async listMembers({ config, orgId, cursor, signal }) {
33
+ const directoryUrl = FakeImDirectoryConfig.parse(config).directoryUrl;
34
+ if (directoryUrl === undefined) throw new Error("fake-im directory: directoryUrl is not set");
35
+ const platform = FakeImDirectoryConfig.safeParse(ctx.config).data?.directoryUrl;
36
+ const get = configUrlFetch(ctx.net, { url: directoryUrl, platform, orgId });
37
+ const q = cursor === undefined ? "" : `?cursor=${encodeURIComponent(cursor)}`;
38
+ const res = await get(`${directoryUrl}/members${q}`, {
39
+ signal,
40
+ headers: { "x-pid": String(process.pid) },
41
+ });
42
+ if (res.status !== 200) {
43
+ await res.body?.cancel();
44
+ throw new Error(`directory returned ${res.status}`);
45
+ }
46
+ return (await res.json()) as { members: DirectoryMember[]; next?: string };
47
+ },
48
+ };
49
+ }
@@ -1,5 +1,6 @@
1
1
  import {
2
2
  defineExtension,
3
+ platformOnly,
3
4
  secret,
4
5
  ToolError,
5
6
  type ToolHandler,
@@ -7,19 +8,34 @@ import {
7
8
  } from "@capybara-hq/plugin-sdk";
8
9
  import { z } from "zod";
9
10
  import { makeFakeImChannel } from "./channel.js";
10
- import { FakeImOrgConfig, fakeImDirectory } from "./directory.js";
11
+ import {
12
+ echoSecretCheck,
13
+ failCheck,
14
+ hangCheck,
15
+ ignoreSignalCheck,
16
+ longCheck,
17
+ padToLimitCheck,
18
+ passCheck,
19
+ proxyCheck,
20
+ throwCheck,
21
+ } from "./checks.js";
22
+ import { FakeImDirectoryConfig, makeFakeImDirectory } from "./directory.js";
11
23
  import { fakeImIdentitySource } from "./identity.js";
12
24
 
13
25
  export { FakeImConnection, fakeImWebhook, makeFakeImChannel } from "./channel.js";
14
- export { FakeImOrgConfig, fakeImDirectory } from "./directory.js";
26
+ export { FakeImDirectoryConfig, makeFakeImDirectory } from "./directory.js";
15
27
  export { fakeImIdentitySource } from "./identity.js";
16
28
 
17
- /** 部署级配置:平台地址与登录用的 OAuth 客户端(clientSecret 走密钥存储)。 */
29
+ /**
30
+ * Deployment config: the platform address and the OAuth client for login (clientSecret goes to the
31
+ * secret store), platform-only; and the org-overridable `directoryUrl` of the directory.
32
+ */
18
33
  const Deployment = z.object({
19
- platformUrl: z.string().url(),
20
- tenant: z.string().min(1).default("t1"),
21
- clientId: z.string().min(1),
22
- clientSecret: secret(z.string().min(1)),
34
+ platformUrl: platformOnly(z.string().url()),
35
+ tenant: platformOnly(z.string().min(1).default("t1")),
36
+ clientId: platformOnly(z.string().min(1)),
37
+ clientSecret: platformOnly(secret(z.string().min(1))),
38
+ ...FakeImDirectoryConfig.shape,
23
39
  });
24
40
  export type FakeImDeployment = z.infer<typeof Deployment>;
25
41
 
@@ -70,22 +86,54 @@ const postHandler =
70
86
  * 假 IM 平台的完整测试插件(连 `@capybara-hq/testing` 的 startFakeChannelServer):
71
87
  * `channel@1`(机器人)+ `identity-source@1`(登录)+ `directory@1`(通讯录),另带一个默认需要批准的写工具。
72
88
  * 三处的身份源键都是 `fake-im:<租户>`,同一个人只对应一行身份。T15–T18 的真实渠道插件照这个形状写。
89
+ * It also registers setup checks for the kernel's check runner tests (`checks.ts`).
73
90
  */
74
91
  export default defineExtension({
75
92
  name: "fake-im",
76
93
  version: "0.1.0",
77
94
  sdk: "^0.1.0-rc.0",
78
95
  provides: ["channel@1", "identity-source@1", "directory@1"],
79
- permissions: { tools: ["post_announcement"] },
80
- config: { deployment: Deployment, org: FakeImOrgConfig },
96
+ permissions: {
97
+ tools: ["post_announcement"],
98
+ setupChecks: [
99
+ "pass",
100
+ "fail",
101
+ "proxy",
102
+ "throw",
103
+ "hang",
104
+ "ignore-signal",
105
+ "long",
106
+ "echo-secret",
107
+ "pad-to-limit",
108
+ ],
109
+ },
110
+ config: { deployment: Deployment },
81
111
  setup(ctx) {
82
112
  const config = () => Deployment.parse(ctx.config);
83
113
  ctx.provide(
84
114
  "channel@1",
85
- makeFakeImChannel({ cards: true, edit: true, threads: true }, { webhook: true }),
115
+ makeFakeImChannel(
116
+ {
117
+ cards: true,
118
+ edit: true,
119
+ threads: true,
120
+ files: { maxBytes: 20_971_520, imageMaxBytes: 10_485_760 },
121
+ },
122
+ { webhook: true },
123
+ ),
86
124
  );
87
125
  ctx.provide("identity-source@1", fakeImIdentitySource);
88
- ctx.provide("directory@1", fakeImDirectory);
126
+ ctx.provide("directory@1", makeFakeImDirectory(ctx));
89
127
  ctx.tools.register(POST_SPEC, postHandler(config));
128
+ // setup checks for the kernel's check runner tests (checks.ts says what each does)
129
+ ctx.setup.check("pass", passCheck);
130
+ ctx.setup.check("fail", failCheck);
131
+ ctx.setup.check("proxy", proxyCheck);
132
+ ctx.setup.check("throw", throwCheck);
133
+ ctx.setup.check("hang", hangCheck);
134
+ ctx.setup.check("ignore-signal", ignoreSignalCheck);
135
+ ctx.setup.check("long", longCheck);
136
+ ctx.setup.check("echo-secret", echoSecretCheck);
137
+ ctx.setup.check("pad-to-limit", padToLimitCheck);
90
138
  },
91
139
  });
@@ -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
+ }