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

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 (72) 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 +7 -5
  18. package/dist/index.js +4 -2
  19. package/dist/kernel-helpers.d.ts +40 -16
  20. package/dist/kernel-helpers.js +44 -13
  21. package/dist/model-conformance.d.ts +5 -0
  22. package/dist/model-conformance.js +33 -1
  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/fixtures/extensions/fake-client/.capybara-plugin/plugin.json +11 -0
  27. package/fixtures/extensions/fake-client/client/styles/fake.css +11 -0
  28. package/fixtures/extensions/fake-client/package.json +12 -0
  29. package/fixtures/extensions/fake-client/src/client.tsx +51 -0
  30. package/fixtures/extensions/fake-client/src/index.ts +43 -0
  31. package/fixtures/extensions/fake-client/themes/fake.json +11 -0
  32. package/fixtures/extensions/fake-client-broken/.capybara-plugin/plugin.json +7 -0
  33. package/fixtures/extensions/fake-client-broken/package.json +12 -0
  34. package/fixtures/extensions/fake-client-broken/src/client.tsx +22 -0
  35. package/fixtures/extensions/fake-client-broken/src/index.ts +27 -0
  36. package/fixtures/extensions/fake-config-form/.capybara-plugin/plugin.json +11 -0
  37. package/fixtures/extensions/fake-config-form/package.json +12 -0
  38. package/fixtures/extensions/fake-config-form/src/index.ts +205 -0
  39. package/fixtures/extensions/fake-context/.capybara-plugin/plugin.json +7 -0
  40. package/fixtures/extensions/fake-context/package.json +12 -0
  41. package/fixtures/extensions/fake-context/src/index.ts +81 -0
  42. package/fixtures/extensions/fake-dep-provider/src/index.ts +1 -1
  43. package/fixtures/extensions/fake-dep-requirer/src/index.ts +1 -1
  44. package/fixtures/extensions/fake-embed/src/index.ts +26 -26
  45. package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +7 -1
  46. package/fixtures/extensions/fake-im/guides/fake-im-app.md +32 -0
  47. package/fixtures/extensions/fake-im/guides/fake-im-app.zh.md +32 -0
  48. package/fixtures/extensions/fake-im/src/channel.ts +3 -1
  49. package/fixtures/extensions/fake-im/src/checks.ts +94 -0
  50. package/fixtures/extensions/fake-im/src/index.ts +36 -1
  51. package/fixtures/extensions/fake-lifecycle/.capybara-plugin/plugin.json +7 -0
  52. package/fixtures/extensions/fake-lifecycle/migrations/0001_init.sql +16 -0
  53. package/fixtures/extensions/fake-lifecycle/package.json +12 -0
  54. package/fixtures/extensions/fake-lifecycle/src/index.ts +72 -0
  55. package/fixtures/extensions/fake-storage-user/src/index.ts +1 -1
  56. package/fixtures/extensions/fake-tools-ui/skills/fake-notes/SKILL.md +1 -1
  57. package/fixtures/extensions/fake-tools-ui/src/index.ts +62 -3
  58. package/fixtures/extensions/fake-web/.capybara-plugin/plugin.json +7 -0
  59. package/fixtures/extensions/fake-web/package.json +12 -0
  60. package/fixtures/extensions/fake-web/src/index.ts +22 -0
  61. package/fixtures/extensions/fake-web/src/web.ts +183 -0
  62. package/fixtures/extensions/fake-web-2/.capybara-plugin/plugin.json +7 -0
  63. package/fixtures/extensions/fake-web-2/package.json +12 -0
  64. package/fixtures/extensions/fake-web-2/src/index.ts +16 -0
  65. package/fixtures/extensions/fake-web-2/src/web.ts +183 -0
  66. package/fixtures/plugins/fake-theme/.capybara-plugin/plugin.json +7 -0
  67. package/fixtures/plugins/fake-theme/fonts/FakeSans.woff2 +1 -0
  68. package/fixtures/plugins/fake-theme/logo.svg +1 -0
  69. package/fixtures/plugins/fake-theme/package.json +8 -0
  70. package/fixtures/plugins/fake-theme/themes/neon-grid.json +13 -0
  71. package/fixtures/plugins/fake-theme/themes/paper.json +12 -0
  72. package/package.json +6 -5
@@ -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
  });
@@ -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
+ });