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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/containers.d.ts +7 -2
  2. package/dist/containers.js +7 -3
  3. package/dist/dual-replica.d.ts +11 -2
  4. package/dist/dual-replica.js +48 -0
  5. package/dist/fake-channel.d.ts +31 -2
  6. package/dist/fake-channel.js +29 -2
  7. package/dist/fake-e2b.d.ts +34 -0
  8. package/dist/fake-e2b.js +95 -1
  9. package/dist/fake-git-server.d.ts +32 -4
  10. package/dist/fake-git-server.js +87 -19
  11. package/dist/fake-oauth-server.d.ts +16 -2
  12. package/dist/fake-oauth-server.js +21 -1
  13. package/dist/fake-telegram.d.ts +165 -0
  14. package/dist/fake-telegram.js +569 -0
  15. package/dist/fixtures.d.ts +21 -4
  16. package/dist/fixtures.js +30 -4
  17. package/dist/index.d.ts +8 -5
  18. package/dist/index.js +6 -3
  19. package/dist/kernel-helpers.d.ts +48 -16
  20. package/dist/kernel-helpers.js +73 -13
  21. package/dist/model-conformance.d.ts +11 -10
  22. package/dist/model-conformance.js +38 -14
  23. package/dist/replica-runner.js +16 -8
  24. package/dist/sandbox-native-conformance.d.ts +31 -0
  25. package/dist/sandbox-native-conformance.js +153 -0
  26. package/dist/sandbox-permission-conformance.d.ts +60 -0
  27. package/dist/sandbox-permission-conformance.js +486 -0
  28. package/fixtures/extensions/fake-client/.capybara-plugin/plugin.json +11 -0
  29. package/fixtures/extensions/fake-client/client/styles/fake.css +11 -0
  30. package/fixtures/extensions/fake-client/package.json +12 -0
  31. package/fixtures/extensions/fake-client/src/client.tsx +51 -0
  32. package/fixtures/extensions/fake-client/src/index.ts +43 -0
  33. package/fixtures/extensions/fake-client/themes/fake.json +11 -0
  34. package/fixtures/extensions/fake-client-broken/.capybara-plugin/plugin.json +7 -0
  35. package/fixtures/extensions/fake-client-broken/package.json +12 -0
  36. package/fixtures/extensions/fake-client-broken/src/client.tsx +22 -0
  37. package/fixtures/extensions/fake-client-broken/src/index.ts +27 -0
  38. package/fixtures/extensions/fake-config-form/.capybara-plugin/plugin.json +11 -0
  39. package/fixtures/extensions/fake-config-form/package.json +12 -0
  40. package/fixtures/extensions/fake-config-form/src/index.ts +205 -0
  41. package/fixtures/extensions/fake-context/.capybara-plugin/plugin.json +7 -0
  42. package/fixtures/extensions/fake-context/package.json +12 -0
  43. package/fixtures/extensions/fake-context/src/index.ts +81 -0
  44. package/fixtures/extensions/fake-dep-provider/src/index.ts +1 -1
  45. package/fixtures/extensions/fake-dep-requirer/src/index.ts +1 -1
  46. package/fixtures/extensions/fake-embed/src/index.ts +26 -26
  47. package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +7 -1
  48. package/fixtures/extensions/fake-im/guides/fake-im-app.md +32 -0
  49. package/fixtures/extensions/fake-im/guides/fake-im-app.zh.md +32 -0
  50. package/fixtures/extensions/fake-im/src/channel.ts +3 -1
  51. package/fixtures/extensions/fake-im/src/checks.ts +94 -0
  52. package/fixtures/extensions/fake-im/src/index.ts +36 -1
  53. package/fixtures/extensions/fake-lifecycle/.capybara-plugin/plugin.json +7 -0
  54. package/fixtures/extensions/fake-lifecycle/migrations/0001_init.sql +16 -0
  55. package/fixtures/extensions/fake-lifecycle/package.json +12 -0
  56. package/fixtures/extensions/fake-lifecycle/src/index.ts +72 -0
  57. package/fixtures/extensions/fake-storage-user/src/index.ts +1 -1
  58. package/fixtures/extensions/fake-tools-ui/skills/fake-notes/SKILL.md +1 -1
  59. package/fixtures/extensions/fake-tools-ui/src/index.ts +62 -3
  60. package/fixtures/extensions/fake-web/.capybara-plugin/plugin.json +7 -0
  61. package/fixtures/extensions/fake-web/package.json +12 -0
  62. package/fixtures/extensions/fake-web/src/index.ts +22 -0
  63. package/fixtures/extensions/fake-web/src/web.ts +183 -0
  64. package/fixtures/extensions/fake-web-2/.capybara-plugin/plugin.json +7 -0
  65. package/fixtures/extensions/fake-web-2/package.json +12 -0
  66. package/fixtures/extensions/fake-web-2/src/index.ts +16 -0
  67. package/fixtures/extensions/fake-web-2/src/web.ts +183 -0
  68. package/fixtures/plugins/fake-theme/.capybara-plugin/plugin.json +7 -0
  69. package/fixtures/plugins/fake-theme/fonts/FakeSans.woff2 +1 -0
  70. package/fixtures/plugins/fake-theme/logo.svg +1 -0
  71. package/fixtures/plugins/fake-theme/package.json +8 -0
  72. package/fixtures/plugins/fake-theme/themes/neon-grid.json +13 -0
  73. package/fixtures/plugins/fake-theme/themes/paper.json +12 -0
  74. package/package.json +6 -5
@@ -0,0 +1,22 @@
1
+ import { defineClientExtension, defineComponent } from "@capybara-hq/plugin-client";
2
+
3
+ const Boom = (): never => {
4
+ throw new Error("fake-client-broken: boom");
5
+ };
6
+
7
+ const Empty = (): never => {
8
+ throw new Error("fake-client-broken: empty");
9
+ };
10
+
11
+ export default defineClientExtension({
12
+ name: "fake-client-broken",
13
+ components: {
14
+ boom: defineComponent("conversation.properties.section", Boom),
15
+ empty: defineComponent("conversation.empty", Empty),
16
+ },
17
+ events: {
18
+ "run.started": () => {
19
+ throw new Error("fake-client-broken: run.started");
20
+ },
21
+ },
22
+ });
@@ -0,0 +1,27 @@
1
+ import { defineExtension } from "@capybara-hq/plugin-sdk";
2
+
3
+ const t = (zh: string, en: string) => ({ zh, en });
4
+
5
+ /**
6
+ * Test fake of a client extension whose browser code is broken, for the host's isolation (error
7
+ * boundaries, the crash budget, safe mode): component `boom` (`conversation.properties.section`)
8
+ * throws on render, the module-level `events` listener throws on `run.started`, and `empty`
9
+ * (`conversation.empty`) throws on render. No server side beyond the declarations.
10
+ */
11
+ export default defineExtension({
12
+ name: "fake-client-broken",
13
+ version: "0.1.0",
14
+ sdk: "^0.1.0-rc.0",
15
+ provides: [],
16
+ ui: [
17
+ {
18
+ id: "boom",
19
+ title: t("崩溃", "Boom"),
20
+ slot: "conversation.properties.section",
21
+ kind: "component",
22
+ },
23
+ { id: "empty", title: t("问候", "Greeting"), slot: "conversation.empty", kind: "component" },
24
+ ],
25
+ permissions: { client: true, ui: { components: ["boom", "empty"] } },
26
+ setup() {},
27
+ });
@@ -0,0 +1,11 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "name": "fake-config-form",
4
+ "displayName": {
5
+ "zh": "表单样例",
6
+ "en": "Form sample"
7
+ },
8
+ "version": "0.1.0",
9
+ "publisher": "Capybara",
10
+ "description": "Test fake: an openai-compatible-shaped deployment config schema with config form hints"
11
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "@capybara-hq/test-plugin-fake-config-form",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "description": "Test fake: an openai-compatible-shaped deployment config schema with config form hints",
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,205 @@
1
+ import {
2
+ type ConfigUiHints,
3
+ defineExtension,
4
+ type LocalizedName,
5
+ secret,
6
+ ui,
7
+ } from "@capybara-hq/plugin-sdk";
8
+ import { z } from "zod";
9
+
10
+ /**
11
+ * Test fake of a hinted deployment config (extension config forms spec §6): the shape of
12
+ * openai-compatible's config (endpoints with models, API keys in a top-level secret record keyed by
13
+ * endpoint name) with the hints that plugin carries, so the web form (presets, item secrets, model
14
+ * rows, advanced fields, localized custom issues) is tested without an official plugin. It provides
15
+ * nothing and calls no service: setup only validates the config. Display name 表单样例 / Form sample.
16
+ */
17
+
18
+ const T = (zh: string, en: string): LocalizedName => ({ zh, en });
19
+ const flag = (zh: string, en: string, help?: LocalizedName) =>
20
+ ui(z.boolean().optional(), { label: T(zh, en), widget: "checkbox", ...(help && { help }) });
21
+
22
+ /** Whether a dialect accepts PDF documents (as in openai-compatible: generic and qwen). */
23
+ const acceptsPdf = (dialect: string): boolean => dialect === "generic" || dialect === "qwen";
24
+
25
+ const EndpointModelSchema = ui(
26
+ z.object({
27
+ id: ui(z.string().min(1), { label: T("模型 ID", "Model ID"), placeholder: "deepseek-chat" }),
28
+ contextWindow: ui(z.number().int().positive(), {
29
+ label: T("上下文窗口", "Context window"),
30
+ unit: T("tokens", "tokens"),
31
+ }),
32
+ maxOutputTokens: ui(z.number().int().positive(), {
33
+ label: T("最大输出", "Max output"),
34
+ unit: T("tokens", "tokens"),
35
+ }),
36
+ vision: flag("图片", "Images"),
37
+ documents: flag(
38
+ "PDF 文档",
39
+ "PDF documents",
40
+ T("仅通用与通义千问方言支持", "Only the generic and Qwen dialects accept PDF"),
41
+ ),
42
+ reasoning: flag("推理", "Reasoning"),
43
+ caching: ui(z.boolean().optional(), {
44
+ label: T("缓存", "Caching"),
45
+ widget: "tristate",
46
+ help: T("默认按方言", "Default follows the dialect"),
47
+ advanced: true,
48
+ }),
49
+ streamIdleTimeoutMs: ui(z.number().int().positive().optional(), {
50
+ label: T("流空闲超时", "Stream idle timeout"),
51
+ unit: T("毫秒", "ms"),
52
+ advanced: true,
53
+ }),
54
+ }),
55
+ { layout: "row" },
56
+ );
57
+
58
+ const EndpointSchema = z.strictObject({
59
+ name: ui(z.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]*$/), {
60
+ label: T("名称", "Name"),
61
+ help: T("对外模型 ID 为 <名称>/<模型 ID>", "Models are exposed as <name>/<model id>"),
62
+ }),
63
+ baseUrl: ui(z.string().url(), {
64
+ label: T("接口地址", "Base URL"),
65
+ widget: "url",
66
+ placeholder: "https://api.example.com/v1",
67
+ }),
68
+ dialect: ui(z.enum(["generic", "deepseek", "qwen", "ark"]), {
69
+ label: T("方言", "Dialect"),
70
+ options: [
71
+ { value: "generic", label: T("通用(vLLM 等)", "Generic (vLLM, …)") },
72
+ { value: "deepseek", label: T("DeepSeek", "DeepSeek") },
73
+ { value: "qwen", label: T("通义千问(百炼)", "Qwen (Model Studio)") },
74
+ { value: "ark", label: T("火山方舟", "Volcano Ark") },
75
+ ],
76
+ }),
77
+ midConversationSystem: ui(z.boolean().optional(), {
78
+ label: T("对话中途的 system 消息", "Mid-conversation system messages"),
79
+ widget: "tristate",
80
+ advanced: true,
81
+ }),
82
+ models: ui(
83
+ z
84
+ .array(EndpointModelSchema)
85
+ .min(1)
86
+ .refine((ms) => new Set(ms.map((m) => m.id)).size === ms.length, {
87
+ params: { ui: "duplicateModel" },
88
+ }),
89
+ {
90
+ label: T("模型", "Models"),
91
+ item: { title: "{id}", addLabel: T("添加模型", "Add model"), reorder: true },
92
+ },
93
+ ),
94
+ });
95
+
96
+ const ENDPOINTS: ConfigUiHints = {
97
+ label: T("端点", "Endpoints"),
98
+ item: {
99
+ title: "{name}",
100
+ subtitle: "{baseUrl}",
101
+ addLabel: T("添加端点", "Add endpoint"),
102
+ reorder: true,
103
+ },
104
+ secrets: [
105
+ {
106
+ path: "apiKeys",
107
+ keyBy: "name",
108
+ after: "baseUrl",
109
+ label: T("API 密钥", "API key"),
110
+ help: T(
111
+ "留空则请求不带凭据(如内网 vLLM)",
112
+ "Leave empty for services without a key (e.g. an internal vLLM)",
113
+ ),
114
+ },
115
+ ],
116
+ presets: [
117
+ {
118
+ id: "deepseek",
119
+ label: T("DeepSeek", "DeepSeek"),
120
+ values: { name: "deepseek", baseUrl: "https://api.deepseek.com", dialect: "deepseek" },
121
+ },
122
+ {
123
+ id: "qwen",
124
+ label: T("通义千问(百炼)", "Qwen (Model Studio)"),
125
+ values: {
126
+ name: "qwen",
127
+ baseUrl: "https://dashscope.aliyuncs.com/compatible-mode/v1",
128
+ dialect: "qwen",
129
+ },
130
+ },
131
+ {
132
+ id: "ark",
133
+ label: T("火山方舟", "Volcano Ark"),
134
+ values: { name: "ark", baseUrl: "https://ark.cn-beijing.volces.com/api/v3", dialect: "ark" },
135
+ },
136
+ {
137
+ id: "generic",
138
+ label: T("其他兼容服务", "Other compatible service"),
139
+ values: { dialect: "generic" },
140
+ },
141
+ ],
142
+ };
143
+
144
+ /** The deployment config: endpoints, and their API keys by endpoint name. */
145
+ export const FakeConfigFormSchema = ui(
146
+ z
147
+ .object({
148
+ endpoints: ui(
149
+ z
150
+ .array(EndpointSchema)
151
+ .min(1)
152
+ .refine((es) => new Set(es.map((e) => e.name)).size === es.length, {
153
+ params: { ui: "duplicateEndpoint" },
154
+ }),
155
+ ENDPOINTS,
156
+ ),
157
+ apiKeys: secret(z.record(z.string(), z.string().min(1))).default({}),
158
+ })
159
+ .superRefine((cfg, ctx) => {
160
+ cfg.endpoints.forEach((e, i) => {
161
+ if (acceptsPdf(e.dialect)) return;
162
+ e.models.forEach((m, j) => {
163
+ if (m.documents !== true) return;
164
+ ctx.addIssue({
165
+ code: "custom",
166
+ path: ["endpoints", i, "models", j, "documents"],
167
+ message: `dialect "${e.dialect}" does not accept PDF documents; documents must be false`,
168
+ params: { ui: "pdfDialect" },
169
+ });
170
+ });
171
+ });
172
+ const names = new Set(cfg.endpoints.map((e) => e.name));
173
+ for (const key of Object.keys(cfg.apiKeys)) {
174
+ if (names.has(key)) continue;
175
+ ctx.addIssue({
176
+ code: "custom",
177
+ path: ["apiKeys", key],
178
+ message: `apiKeys["${key}"] does not match any endpoint name`,
179
+ params: { ui: "unknownKey" },
180
+ });
181
+ }
182
+ }),
183
+ {
184
+ messages: {
185
+ duplicateEndpoint: T("端点名称重复", "Endpoint names must be unique"),
186
+ duplicateModel: T("模型 ID 重复", "Model ids must be unique within an endpoint"),
187
+ pdfDialect: T(
188
+ "该方言不支持 PDF,请取消勾选",
189
+ "This dialect does not accept PDF; clear the box",
190
+ ),
191
+ unknownKey: T("密钥没有对应的端点", "This key has no endpoint"),
192
+ },
193
+ },
194
+ );
195
+
196
+ export default defineExtension({
197
+ name: "fake-config-form",
198
+ version: "0.1.0",
199
+ sdk: "^0.1.0-rc.0",
200
+ provides: [],
201
+ config: { deployment: FakeConfigFormSchema },
202
+ setup(ctx) {
203
+ FakeConfigFormSchema.parse(ctx.config ?? {});
204
+ },
205
+ });
@@ -0,0 +1,7 @@
1
+ {
2
+ "schemaVersion": 1,
3
+ "name": "fake-context",
4
+ "version": "0.1.0",
5
+ "publisher": "Capybara",
6
+ "description": "Test fake: a scripted context provider (context@1) and one tool limited to one-to-one conversations"
7
+ }
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "@capybara-hq/test-plugin-fake-context",
3
+ "version": "0.1.0",
4
+ "private": true,
5
+ "description": "Test fake: a scripted context provider (context@1) and one tool limited to one-to-one conversations",
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,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
  });