@capybara-hq/testing 0.1.0-rc.36 → 0.1.0-rc.38

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.
@@ -17,8 +17,8 @@
17
17
  * | `fake-bootstrap-a` | `model-provider@2` with a required secret `apiKey` (pending configuration until set) |
18
18
  * | `fake-bootstrap-b` | `object-store@1` kept in its own PG table; `bucket` + secret `secretKey` |
19
19
  * | `fake-dep-provider` / `fake-dep-requirer` | a dependency pair on `counter@1` (the requirer's plugin.json depends on the provider) |
20
- * | `fake-im` | a whole IM platform for `startFakeChannelServer`: `channel@1` (cards, edits, threads, files via `sendFile`, webhook inbound), `identity-source@1`, `directory@1` (org config `url` of a directory book) and tool `post_announcement` (default policy ask, posts to the platform); deployment config `platformUrl`, `tenant`, `clientId`, secret `clientSecret`. Its `src/index.ts` also exports `makeFakeImChannel`, `fakeImIdentitySource`, `fakeImDirectory` for test extensions that need one part |
21
- * | `fake-web` / `fake-web-2` | `web-search@1` and `web-fetch@1`, scripted by a prefix of the query or of the fetched URL's path (`error:<kind>`, `throw:`, `hang:`, `redirect:<url>`, `junk:`, `empty:`, `big:<n>`; see `makeFakeWeb`); results name the provider; org config secret `token`, `configured()` iff it is set (throws for `throw:configured`); calls recorded on `globalThis.__fakeWeb` (`fakeWebProbe`) |
20
+ * | `fake-im` | a whole IM platform for `startFakeChannelServer`: `channel@1` (cards, edits, threads, files via `sendFile`, webhook inbound), `identity-source@1`, `directory@1` (the org-overridable deployment field `directoryUrl` of a directory book, fetched through `configUrlFetch`; unset = not configured) and tool `post_announcement` (default policy ask, posts to the platform); platform-only deployment config `platformUrl`, `tenant`, `clientId`, secret `clientSecret`. Its `src/index.ts` also exports `makeFakeImChannel`, `fakeImIdentitySource`, `makeFakeImDirectory` for test extensions that need one part |
21
+ * | `fake-web` / `fake-web-2` | `web-search@1` and `web-fetch@1`, scripted by a prefix of the query or of the fetched URL's path (`error:<kind>`, `throw:`, `hang:`, `redirect:<url>`, `junk:`, `empty:`, `big:<n>`; see `makeFakeWeb`); results name the provider; deployment config: a required, org-overridable secret `token` the platform may leave empty, `configured()` iff it is set and not `unconfigured` (throws for `throw:configured`); calls recorded on `globalThis.__fakeWeb` (`fakeWebProbe`) |
22
22
  * | `fake-context` | `context@1` scripted by its deployment config (`text`, default "fake context"; `mode` `ok` / `null` / `throw` / `hang`); calls recorded on `globalThis.__fakeContext` (`fakeContextProbe`); tool `note` (`sources` web and channel_dm) |
23
23
  * | `fake-client` | client extension (`permissions.client`, no extension point): components `hud` (`conversation.properties.section`, server view with `data`), `brand` (`shell.brand`, renders `builtin` in `data-testid="fake-client-brand"`), `empty` (`conversation.empty`), `frame` (`conversation.composer.frame`) and `fx` (`shell.overlay`); `client/styles/fake.css` (outline-color on `button.primary` and the composer's buttons, `--cx-fake-client-run` while `run=running`); an `events` listener storing the last event type; theme `fake`; `suggestedAppearance` = theme `fake` + `shell.brand` -> `brand` |
24
24
  * | `fake-client-broken` | client code that throws: component `boom` (render), a `run.started` events listener, and a `conversation.empty` replacement (render) |
package/dist/fixtures.js CHANGED
@@ -20,8 +20,8 @@ import { fileURLToPath } from "node:url";
20
20
  * | `fake-bootstrap-a` | `model-provider@2` with a required secret `apiKey` (pending configuration until set) |
21
21
  * | `fake-bootstrap-b` | `object-store@1` kept in its own PG table; `bucket` + secret `secretKey` |
22
22
  * | `fake-dep-provider` / `fake-dep-requirer` | a dependency pair on `counter@1` (the requirer's plugin.json depends on the provider) |
23
- * | `fake-im` | a whole IM platform for `startFakeChannelServer`: `channel@1` (cards, edits, threads, files via `sendFile`, webhook inbound), `identity-source@1`, `directory@1` (org config `url` of a directory book) and tool `post_announcement` (default policy ask, posts to the platform); deployment config `platformUrl`, `tenant`, `clientId`, secret `clientSecret`. Its `src/index.ts` also exports `makeFakeImChannel`, `fakeImIdentitySource`, `fakeImDirectory` for test extensions that need one part |
24
- * | `fake-web` / `fake-web-2` | `web-search@1` and `web-fetch@1`, scripted by a prefix of the query or of the fetched URL's path (`error:<kind>`, `throw:`, `hang:`, `redirect:<url>`, `junk:`, `empty:`, `big:<n>`; see `makeFakeWeb`); results name the provider; org config secret `token`, `configured()` iff it is set (throws for `throw:configured`); calls recorded on `globalThis.__fakeWeb` (`fakeWebProbe`) |
23
+ * | `fake-im` | a whole IM platform for `startFakeChannelServer`: `channel@1` (cards, edits, threads, files via `sendFile`, webhook inbound), `identity-source@1`, `directory@1` (the org-overridable deployment field `directoryUrl` of a directory book, fetched through `configUrlFetch`; unset = not configured) and tool `post_announcement` (default policy ask, posts to the platform); platform-only deployment config `platformUrl`, `tenant`, `clientId`, secret `clientSecret`. Its `src/index.ts` also exports `makeFakeImChannel`, `fakeImIdentitySource`, `makeFakeImDirectory` for test extensions that need one part |
24
+ * | `fake-web` / `fake-web-2` | `web-search@1` and `web-fetch@1`, scripted by a prefix of the query or of the fetched URL's path (`error:<kind>`, `throw:`, `hang:`, `redirect:<url>`, `junk:`, `empty:`, `big:<n>`; see `makeFakeWeb`); results name the provider; deployment config: a required, org-overridable secret `token` the platform may leave empty, `configured()` iff it is set and not `unconfigured` (throws for `throw:configured`); calls recorded on `globalThis.__fakeWeb` (`fakeWebProbe`) |
25
25
  * | `fake-context` | `context@1` scripted by its deployment config (`text`, default "fake context"; `mode` `ok` / `null` / `throw` / `hang`); calls recorded on `globalThis.__fakeContext` (`fakeContextProbe`); tool `note` (`sources` web and channel_dm) |
26
26
  * | `fake-client` | client extension (`permissions.client`, no extension point): components `hud` (`conversation.properties.section`, server view with `data`), `brand` (`shell.brand`, renders `builtin` in `data-testid="fake-client-brand"`), `empty` (`conversation.empty`), `frame` (`conversation.composer.frame`) and `fx` (`shell.overlay`); `client/styles/fake.css` (outline-color on `button.primary` and the composer's buttons, `--cx-fake-client-run` while `run=running`); an `events` listener storing the last event type; theme `fake`; `suggestedAppearance` = theme `fake` + `shell.brand` -> `brand` |
27
27
  * | `fake-client-broken` | client code that throws: component `boom` (render), a `run.started` events listener, and a `conversation.empty` replacement (render) |
@@ -221,7 +221,10 @@ export interface SandboxPermissionFixture {
221
221
  readFile(path: string): Promise<Uint8Array | null>;
222
222
  /** Permission bits (`st_mode & 0o7777`), or null when missing. */
223
223
  mode(path: string): Promise<number | null>;
224
- /** The subset of `pids` still running on the device. */
224
+ /**
225
+ * The subset of `pids` still running on the device (a zombie waiting for its reaper may count
226
+ * either way: the harness polls until the killed ones are gone).
227
+ */
225
228
  alive(pids: readonly number[]): Promise<number[]>;
226
229
  /**
227
230
  * Runs a Python 3 program (`python3 - ...args`, program on stdin) as the device user in a
@@ -423,6 +423,21 @@ export async function runSandboxPermissionConformance(fixture, options = {}) {
423
423
  await assert.rejects(promise, (error) => isSandboxScopeDeniedError(error), what);
424
424
  };
425
425
  const waitFor = (path, pending) => waitForFile(fixture.inspect.readFile, path, pending);
426
+ /**
427
+ * Asserts that every process of `pids` ends. A kill is asynchronous: the operation can report
428
+ * its cancel or timeout while a killed descendant is still being delivered its signal or waits
429
+ * for its reaper, so this polls `alive` until none is left, failing with the survivors after
430
+ * 10 s.
431
+ */
432
+ const ended = async (pids, message) => {
433
+ const deadline = Date.now() + 10_000;
434
+ let left = await fixture.inspect.alive(pids);
435
+ while (left.length > 0 && Date.now() < deadline) {
436
+ await new Promise((resolve) => setTimeout(resolve, 20));
437
+ left = await fixture.inspect.alive(left);
438
+ }
439
+ assert.deepEqual(left, [], message);
440
+ };
426
441
  const receipts = async () => Promise.all([granted, ...ungranted].map((endpoint) => endpoint.receipts()));
427
442
  const connect = (endpoint) => `python3 -c ${quote(`import socket; socket.create_connection((${JSON.stringify(endpoint.address)}, ${endpoint.port}), 10).close()`)}`;
428
443
  /** An HTTP request by name; curl and Python use the environment's proxy when there is one. */
@@ -603,7 +618,7 @@ export async function runSandboxPermissionConformance(fixture, options = {}) {
603
618
  abort.abort();
604
619
  const stopped = await cancelled;
605
620
  assert.equal(stopped.exitCode, null, "a cancelled operation has no exit code");
606
- assert.deepEqual(await fixture.inspect.alive(pids), [], "cancellation ends every descendant");
621
+ await ended(pids, "cancellation ends every descendant");
607
622
  await exec(grant, "touch release-keep");
608
623
  assert.equal((await keepAlive).exitCode, 0, "the sibling operation survives the cancel");
609
624
  assert.equal(text(await fixture.inspect.readFile(at(root, "kept"))), "done");
@@ -611,7 +626,7 @@ export async function runSandboxPermissionConformance(fixture, options = {}) {
611
626
  const timed = await exec(grant, `(sleep 1005 & echo $! > p4); sleep 1006`, signal, 1000);
612
627
  assert.equal(timed.timedOut, true, "a restricted timeout is reported");
613
628
  const p4 = Number(text(await fixture.inspect.readFile(at(root, "p4"))));
614
- assert.deepEqual(await fixture.inspect.alive([p4]), [], "timeout ends background children");
629
+ await ended([p4], "timeout ends background children");
615
630
  };
616
631
  /**
617
632
  * An instance-boundary provider (a cloud device): the container or microVM is the sandbox, its
@@ -2,6 +2,7 @@ import {
2
2
  defineExtension,
3
3
  MODEL_PROVIDER_EXTENSION_POINT_V2,
4
4
  type ModelProvider,
5
+ platformOnly,
5
6
  secret,
6
7
  } from "@capybara-hq/plugin-sdk";
7
8
  import { z } from "zod";
@@ -13,10 +14,13 @@ import { z } from "zod";
13
14
  * every request with `fake-bootstrap-a`; it never calls a network service.
14
15
  */
15
16
 
16
- const DeploymentConfig = z.object({
17
- apiKey: secret(z.string().min(1)),
18
- baseUrl: z.string().url().optional(),
19
- });
17
+ /** Platform-only as a whole: the platform must set the key before the extension loads. */
18
+ const DeploymentConfig = platformOnly(
19
+ z.object({
20
+ apiKey: secret(z.string().min(1)),
21
+ baseUrl: z.string().url().optional(),
22
+ }),
23
+ );
20
24
 
21
25
  const REPLY = "fake-bootstrap-a";
22
26
 
@@ -4,6 +4,7 @@ import {
4
4
  OBJECT_STORE_EXTENSION_POINT,
5
5
  type ObjectHead,
6
6
  type ObjectStore,
7
+ platformOnly,
7
8
  secret,
8
9
  } from "@capybara-hq/plugin-sdk";
9
10
  import { z } from "zod";
@@ -17,10 +18,13 @@ import { z } from "zod";
17
18
  * from a browser.
18
19
  */
19
20
 
20
- const DeploymentConfig = z.object({
21
- bucket: z.string().min(1),
22
- secretKey: secret(z.string().min(1)),
23
- });
21
+ /** Platform-only (object-store@1 is infrastructure, unified config spec §5.3). */
22
+ const DeploymentConfig = platformOnly(
23
+ z.object({
24
+ bucket: z.string().min(1),
25
+ secretKey: secret(z.string().min(1)),
26
+ }),
27
+ );
24
28
 
25
29
  type Db = ExtensionContext["db"];
26
30
 
@@ -2,6 +2,7 @@ import {
2
2
  type ConfigUiHints,
3
3
  defineExtension,
4
4
  type LocalizedName,
5
+ platformOnly,
5
6
  secret,
6
7
  ui,
7
8
  } from "@capybara-hq/plugin-sdk";
@@ -141,56 +142,61 @@ const ENDPOINTS: ConfigUiHints = {
141
142
  ],
142
143
  };
143
144
 
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;
145
+ /**
146
+ * The deployment config: endpoints, and their API keys by endpoint name. Platform-only as a whole:
147
+ * the fixture has no org-bound entry, so an org value would never reach it.
148
+ */
149
+ export const FakeConfigFormSchema = platformOnly(
150
+ ui(
151
+ z
152
+ .object({
153
+ endpoints: ui(
154
+ z
155
+ .array(EndpointSchema)
156
+ .min(1)
157
+ .refine((es) => new Set(es.map((e) => e.name)).size === es.length, {
158
+ params: { ui: "duplicateEndpoint" },
159
+ }),
160
+ ENDPOINTS,
161
+ ),
162
+ apiKeys: secret(z.record(z.string(), z.string().min(1))).default({}),
163
+ })
164
+ .superRefine((cfg, ctx) => {
165
+ cfg.endpoints.forEach((e, i) => {
166
+ if (acceptsPdf(e.dialect)) return;
167
+ e.models.forEach((m, j) => {
168
+ if (m.documents !== true) return;
169
+ ctx.addIssue({
170
+ code: "custom",
171
+ path: ["endpoints", i, "models", j, "documents"],
172
+ message: `dialect "${e.dialect}" does not accept PDF documents; documents must be false`,
173
+ params: { ui: "pdfDialect" },
174
+ });
175
+ });
176
+ });
177
+ const names = new Set(cfg.endpoints.map((e) => e.name));
178
+ for (const key of Object.keys(cfg.apiKeys)) {
179
+ if (names.has(key)) continue;
164
180
  ctx.addIssue({
165
181
  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" },
182
+ path: ["apiKeys", key],
183
+ message: `apiKeys["${key}"] does not match any endpoint name`,
184
+ params: { ui: "unknownKey" },
169
185
  });
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"),
186
+ }
187
+ }),
188
+ {
189
+ messages: {
190
+ duplicateEndpoint: T("端点名称重复", "Endpoint names must be unique"),
191
+ duplicateModel: T("模型 ID 重复", "Model ids must be unique within an endpoint"),
192
+ pdfDialect: T(
193
+ "该方言不支持 PDF,请取消勾选",
194
+ "This dialect does not accept PDF; clear the box",
195
+ ),
196
+ unknownKey: T("密钥没有对应的端点", "This key has no endpoint"),
197
+ },
192
198
  },
193
- },
199
+ ),
194
200
  );
195
201
 
196
202
  export default defineExtension({
@@ -10,6 +10,7 @@ import {
10
10
  type ExtensionNet,
11
11
  type Logger,
12
12
  type PromptInfo,
13
+ platformOnly,
13
14
  type ToolContent,
14
15
  ToolError,
15
16
  type ToolResult,
@@ -67,19 +68,22 @@ const CLIENT_INFO = { name: "capybara-fake-connector", version: "0.1.0" };
67
68
  /** The kernel's pipeline timeout (through the signal) decides, not the SDK's default 60 s. */
68
69
  const REQUEST_TIMEOUT_MS = 3_600_000;
69
70
 
70
- const DeploymentConfig = z.object({
71
- /** The auth hint `inspect` reports behind a 401. */
72
- inspectAuth: z.enum(["bearer", "api_key"]).default("bearer"),
73
- /**
74
- * The connector kind it provides (default `fake`). A deployment that loads no other connector
75
- * extension can name it `mcp`, so clients that know only the official kinds (the web install
76
- * wizard) drive it like an MCP connector.
77
- */
78
- kind: z
79
- .string()
80
- .regex(/^[a-z][a-z0-9-]{0,31}$/)
81
- .default("fake"),
82
- });
71
+ /** Platform-only: connector@1 calls carry no org config (spec §5.3). */
72
+ const DeploymentConfig = platformOnly(
73
+ z.object({
74
+ /** The auth hint `inspect` reports behind a 401. */
75
+ inspectAuth: z.enum(["bearer", "api_key"]).default("bearer"),
76
+ /**
77
+ * The connector kind it provides (default `fake`). A deployment that loads no other connector
78
+ * extension can name it `mcp`, so clients that know only the official kinds (the web install
79
+ * wizard) drive it like an MCP connector.
80
+ */
81
+ kind: z
82
+ .string()
83
+ .regex(/^[a-z][a-z0-9-]{0,31}$/)
84
+ .default("fake"),
85
+ }),
86
+ );
83
87
 
84
88
  /** The `_meta` key of a remote tool that names the remote tool serving it (its route). */
85
89
  export const FAKE_ROUTE_META = "fake/route";
@@ -16,8 +16,8 @@ import { z } from "zod";
16
16
  * Every call is recorded (the request without its signal) on `globalThis.__fakeContext`
17
17
  * ({@link fakeContextProbe}; in-process kernels only). It also registers the tool `note` (default
18
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.
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
21
  */
22
22
 
23
23
  const DeploymentConfig = z.object({
@@ -25,9 +25,6 @@ const DeploymentConfig = z.object({
25
25
  mode: z.enum(["ok", "null", "throw", "hang"]).default("ok"),
26
26
  });
27
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
28
  /** One `provide` call: the request the kernel sent, without its signal. */
32
29
  export type FakeContextCall = Omit<ContextRequest, "signal">;
33
30
 
@@ -72,7 +69,7 @@ export default defineExtension({
72
69
  version: "0.1.0",
73
70
  sdk: "^0.1.0-rc.0",
74
71
  provides: ["context@1"],
75
- config: { deployment: DeploymentConfig, org: OrgConfig },
72
+ config: { deployment: DeploymentConfig },
76
73
  permissions: { tools: ["note"] },
77
74
  setup(ctx) {
78
75
  ctx.provide("context@1", provider);
@@ -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,
@@ -18,19 +19,23 @@ import {
18
19
  proxyCheck,
19
20
  throwCheck,
20
21
  } from "./checks.js";
21
- import { FakeImOrgConfig, fakeImDirectory } from "./directory.js";
22
+ import { FakeImDirectoryConfig, makeFakeImDirectory } from "./directory.js";
22
23
  import { fakeImIdentitySource } from "./identity.js";
23
24
 
24
25
  export { FakeImConnection, fakeImWebhook, makeFakeImChannel } from "./channel.js";
25
- export { FakeImOrgConfig, fakeImDirectory } from "./directory.js";
26
+ export { FakeImDirectoryConfig, makeFakeImDirectory } from "./directory.js";
26
27
  export { fakeImIdentitySource } from "./identity.js";
27
28
 
28
- /** 部署级配置:平台地址与登录用的 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
+ */
29
33
  const Deployment = z.object({
30
- platformUrl: z.string().url(),
31
- tenant: z.string().min(1).default("t1"),
32
- clientId: z.string().min(1),
33
- 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,
34
39
  });
35
40
  export type FakeImDeployment = z.infer<typeof Deployment>;
36
41
 
@@ -102,7 +107,7 @@ export default defineExtension({
102
107
  "pad-to-limit",
103
108
  ],
104
109
  },
105
- config: { deployment: Deployment, org: FakeImOrgConfig },
110
+ config: { deployment: Deployment },
106
111
  setup(ctx) {
107
112
  const config = () => Deployment.parse(ctx.config);
108
113
  ctx.provide(
@@ -118,7 +123,7 @@ export default defineExtension({
118
123
  ),
119
124
  );
120
125
  ctx.provide("identity-source@1", fakeImIdentitySource);
121
- ctx.provide("directory@1", fakeImDirectory);
126
+ ctx.provide("directory@1", makeFakeImDirectory(ctx));
122
127
  ctx.tools.register(POST_SPEC, postHandler(config));
123
128
  // setup checks for the kernel's check runner tests (checks.ts says what each does)
124
129
  ctx.setup.check("pass", passCheck);
@@ -2,7 +2,7 @@ import {
2
2
  defineExtension,
3
3
  type ExtensionContext,
4
4
  type HookCall,
5
- orgAccess,
5
+ platformOnly,
6
6
  } from "@capybara-hq/plugin-sdk";
7
7
  import { z } from "zod";
8
8
 
@@ -12,16 +12,16 @@ import { z } from "zod";
12
12
  * (`plugin_fake_lifecycle`): table `calls` gets one row per call, `deliveries` one row per call
13
13
  * that succeeded, each with the mount and the payload. Deployment config `failTimes` (default 0):
14
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,
15
+ * retries; the count lives in PG, so it holds across replicas (platform-only). Deployment config `label` (optional,
16
16
  * at most 10 characters) is overridable per org, so a test can store an org copy that does not
17
17
  * validate (an org whose effective config is invalid).
18
18
  */
19
19
 
20
20
  const DeploymentConfig = z.object({
21
21
  /** How many calls of each (mount, payload) throw before one succeeds. */
22
- failTimes: z.number().int().min(0).default(0),
22
+ failTimes: platformOnly(z.number().int().min(0).default(0)),
23
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"),
24
+ label: z.string().max(10).optional(),
25
25
  });
26
26
 
27
27
  type Db = ExtensionContext["db"];
@@ -14,6 +14,7 @@ import {
14
14
  OBJECT_STORE_EXTENSION_POINT,
15
15
  type ObjectHead,
16
16
  type ObjectStore,
17
+ platformOnly,
17
18
  secret,
18
19
  } from "@capybara-hq/plugin-sdk";
19
20
  import { z } from "zod";
@@ -28,14 +29,17 @@ import { z } from "zod";
28
29
  * refused, `presignGet` sets the disposition and response type.
29
30
  */
30
31
 
31
- const DeploymentConfig = z.object({
32
- endpoint: z.string().url().optional(),
33
- region: z.string().min(1),
34
- bucket: z.string().min(1),
35
- accessKeyId: secret(z.string().min(1)),
36
- secretAccessKey: secret(z.string().min(1)),
37
- forcePathStyle: z.boolean().default(true),
38
- });
32
+ /** Platform-only (object-store@1 is infrastructure, unified config spec §5.3). */
33
+ const DeploymentConfig = platformOnly(
34
+ z.object({
35
+ endpoint: z.string().url().optional(),
36
+ region: z.string().min(1),
37
+ bucket: z.string().min(1),
38
+ accessKeyId: secret(z.string().min(1)),
39
+ secretAccessKey: secret(z.string().min(1)),
40
+ forcePathStyle: z.boolean().default(true),
41
+ }),
42
+ );
39
43
 
40
44
  /** The deployment config of the fake (as `startTestS3()` gives it). */
41
45
  export type FakeObjectStoreConfig = z.input<typeof DeploymentConfig>;
@@ -1,4 +1,9 @@
1
- import { defineExtension, PUSH_PROVIDER_EXTENSION_POINT, secret } from "@capybara-hq/plugin-sdk";
1
+ import {
2
+ defineExtension,
3
+ PUSH_PROVIDER_EXTENSION_POINT,
4
+ platformOnly,
5
+ secret,
6
+ } from "@capybara-hq/plugin-sdk";
2
7
  import { z } from "zod";
3
8
  import { keyCheck } from "./check.js";
4
9
  import { fakePushProbe, makeFakePush } from "./push.js";
@@ -11,12 +16,15 @@ export { type FakePushSend, fakePushProbe, makeFakePush } from "./push.js";
11
16
  * `["com.example.app"]`) and an optional secret `key`. Every send attempt is recorded in
12
17
  * `plugin_fake_push.sends` (counted across replicas) and on `fakePushProbe().sends` (in process).
13
18
  * Its platform setup guide (`guides/fake-push-key.md`, place `extension-deployment`) has one check,
14
- * `fake-push-key` (`check.ts`), which reads `key`.
19
+ * `fake-push-key` (`check.ts`), which reads `key`. Platform-only: push delivery is the kernel's,
20
+ * never an org-bound call (spec §5.3).
15
21
  */
16
- const DeploymentConfig = z.object({
17
- apps: z.array(z.string().min(1)).default(["com.example.app"]),
18
- key: secret(z.string()).optional(),
19
- });
22
+ const DeploymentConfig = platformOnly(
23
+ z.object({
24
+ apps: z.array(z.string().min(1)).default(["com.example.app"]),
25
+ key: secret(z.string()).optional(),
26
+ }),
27
+ );
20
28
 
21
29
  export default defineExtension({
22
30
  name: "fake-push",
@@ -1,11 +1,12 @@
1
1
  import { defineExtension } from "@capybara-hq/plugin-sdk";
2
- import { FakeWebOrgConfig, makeFakeWeb } from "./web.js";
2
+ import { FakeWebConfig, makeFakeWeb } from "./web.js";
3
3
 
4
- export { type FakeWebCall, FakeWebOrgConfig, fakeWebProbe, makeFakeWeb } from "./web.js";
4
+ export { type FakeWebCall, FakeWebConfig, fakeWebProbe, makeFakeWeb } from "./web.js";
5
5
 
6
6
  /**
7
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.
8
+ * scripts). Deployment config `{ token }` (a required, org-overridable secret the platform may
9
+ * leave empty); `configured()` is true iff the token is set and not `unconfigured`.
9
10
  * `fake-web-2` is the same with its own name, for the org default provider.
10
11
  */
11
12
  export default defineExtension({
@@ -13,7 +14,7 @@ export default defineExtension({
13
14
  version: "0.1.0",
14
15
  sdk: "^0.1.0-rc.0",
15
16
  provides: ["web-search@1", "web-fetch@1"],
16
- config: { org: FakeWebOrgConfig },
17
+ config: { deployment: FakeWebConfig },
17
18
  setup(ctx) {
18
19
  const { search, fetch } = makeFakeWeb("fake-web");
19
20
  ctx.provide("web-search@1", search);
@@ -13,10 +13,11 @@ import { z } from "zod";
13
13
  // own directory); test/fixtures.test.ts of @capybara-hq/testing keeps them equal.
14
14
 
15
15
  /**
16
- * Org config of the fake web providers: `configured()` is true iff `token` is set (and throws for
17
- * the token `throw:configured`).
16
+ * Deployment config of the fake web providers: a required, org-overridable secret `token`. The
17
+ * platform may leave it empty (orgs then need their own copy); `configured()` is false for the
18
+ * token `unconfigured` and throws for the token `throw:configured`.
18
19
  */
19
- export const FakeWebOrgConfig = z.object({ token: secret(z.string().min(1)).optional() });
20
+ export const FakeWebConfig = z.object({ token: secret(z.string().min(1)) });
20
21
 
21
22
  /** One provider call, recorded on `globalThis.__fakeWeb` (in-process kernels only). */
22
23
  export interface FakeWebCall {
@@ -43,11 +44,14 @@ const KINDS: readonly WebProviderErrorKind[] = [
43
44
  "invalid",
44
45
  ];
45
46
 
46
- /** True iff the token is set; the token `throw:configured` makes it throw. */
47
- const configured = (orgConfig: unknown): boolean => {
48
- const token = (orgConfig as { token?: unknown } | null)?.token;
47
+ /**
48
+ * True iff the effective config's token is set and is not `unconfigured`; the token
49
+ * `throw:configured` makes it throw.
50
+ */
51
+ const configured = (config: unknown): boolean => {
52
+ const token = (config as { token?: unknown } | null)?.token;
49
53
  if (token === "throw:configured") throw new Error("fake web: configured() failed");
50
- return typeof token === "string" && token.length > 0;
54
+ return typeof token === "string" && token.length > 0 && token !== "unconfigured";
51
55
  };
52
56
 
53
57
  /** The script of a fetch: the decoded URL path (and query) after the first `/`. */
@@ -1,5 +1,5 @@
1
1
  import { defineExtension } from "@capybara-hq/plugin-sdk";
2
- import { FakeWebOrgConfig, makeFakeWeb } from "./web.js";
2
+ import { FakeWebConfig, makeFakeWeb } from "./web.js";
3
3
 
4
4
  /** Test fake: `fake-web` under another name (a second provider of `web-search@1` / `web-fetch@1`). */
5
5
  export default defineExtension({
@@ -7,7 +7,7 @@ export default defineExtension({
7
7
  version: "0.1.0",
8
8
  sdk: "^0.1.0-rc.0",
9
9
  provides: ["web-search@1", "web-fetch@1"],
10
- config: { org: FakeWebOrgConfig },
10
+ config: { deployment: FakeWebConfig },
11
11
  setup(ctx) {
12
12
  const { search, fetch } = makeFakeWeb("fake-web-2");
13
13
  ctx.provide("web-search@1", search);
@@ -13,10 +13,11 @@ import { z } from "zod";
13
13
  // own directory); test/fixtures.test.ts of @capybara-hq/testing keeps them equal.
14
14
 
15
15
  /**
16
- * Org config of the fake web providers: `configured()` is true iff `token` is set (and throws for
17
- * the token `throw:configured`).
16
+ * Deployment config of the fake web providers: a required, org-overridable secret `token`. The
17
+ * platform may leave it empty (orgs then need their own copy); `configured()` is false for the
18
+ * token `unconfigured` and throws for the token `throw:configured`.
18
19
  */
19
- export const FakeWebOrgConfig = z.object({ token: secret(z.string().min(1)).optional() });
20
+ export const FakeWebConfig = z.object({ token: secret(z.string().min(1)) });
20
21
 
21
22
  /** One provider call, recorded on `globalThis.__fakeWeb` (in-process kernels only). */
22
23
  export interface FakeWebCall {
@@ -43,11 +44,14 @@ const KINDS: readonly WebProviderErrorKind[] = [
43
44
  "invalid",
44
45
  ];
45
46
 
46
- /** True iff the token is set; the token `throw:configured` makes it throw. */
47
- const configured = (orgConfig: unknown): boolean => {
48
- const token = (orgConfig as { token?: unknown } | null)?.token;
47
+ /**
48
+ * True iff the effective config's token is set and is not `unconfigured`; the token
49
+ * `throw:configured` makes it throw.
50
+ */
51
+ const configured = (config: unknown): boolean => {
52
+ const token = (config as { token?: unknown } | null)?.token;
49
53
  if (token === "throw:configured") throw new Error("fake web: configured() failed");
50
- return typeof token === "string" && token.length > 0;
54
+ return typeof token === "string" && token.length > 0 && token !== "unconfigured";
51
55
  };
52
56
 
53
57
  /** The script of a fetch: the decoded URL path (and query) after the first `/`. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/testing",
3
- "version": "0.1.0-rc.36",
3
+ "version": "0.1.0-rc.38",
4
4
  "description": "Test helpers for Capybara: test containers, dual-replica harness and fake third-party servers",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -47,18 +47,18 @@
47
47
  "tsx": "^4.23.15",
48
48
  "ws": "^8.22.0",
49
49
  "zod": "^4.6.7",
50
- "@capybara-hq/kernel": "^0.1.0-rc.73"
50
+ "@capybara-hq/kernel": "^0.1.0-rc.78"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@types/pg": "^8.23.1",
54
54
  "@types/ws": "^8.18.2",
55
55
  "@capybara-hq/plugin-client": "^0.1.0-rc.8",
56
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.57"
56
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.64"
57
57
  },
58
58
  "peerDependencies": {
59
59
  "vitest": "^5.0.5",
60
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.57",
61
- "@capybara-hq/plugin-tools": "^0.1.0-rc.20"
60
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.64",
61
+ "@capybara-hq/plugin-tools": "^0.1.0-rc.23"
62
62
  },
63
63
  "peerDependenciesMeta": {
64
64
  "@capybara-hq/plugin-tools": {