@capybara-hq/testing 0.1.0-rc.15 → 0.1.0-rc.17

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.
@@ -38,12 +38,17 @@ export declare const DEFAULT_CONTAINER_STARTS = 4;
38
38
  * `key` is the slot set (tests use their own).
39
39
  */
40
40
  export declare function withStartSlot<T>(start: () => Promise<T>, key?: string): Promise<T>;
41
+ /** The PostgreSQL image tests run on: PostgreSQL 17 with pgvector, as in the compose files. */
42
+ export declare const TEST_PG_IMAGE = "pgvector/pgvector:pg17";
41
43
  /**
42
- * Start a throwaway PostgreSQL 17 container. `tuned` is for the run-wide shared instance: many files
43
- * connect at once (raise `max_connections`), and durability is irrelevant for tests (no fsync).
44
+ * Start a throwaway PostgreSQL 17 container (`TEST_PG_IMAGE` unless `image` names another, e.g.
45
+ * plain `postgres:17` to test a server without pgvector). `tuned` is for the run-wide shared
46
+ * instance: many files connect at once (raise `max_connections`), and durability is irrelevant for
47
+ * tests (no fsync).
44
48
  */
45
49
  export declare function startPostgresContainer(opts?: {
46
50
  tuned?: boolean;
51
+ image?: string;
47
52
  }): Promise<TestContainer>;
48
53
  /** Start a throwaway Valkey 8 container, returning `redis://host:port`. */
49
54
  export declare function startRedisContainer(opts?: {
@@ -90,12 +90,16 @@ export async function withStartSlot(start, key = START_SLOTS_KEY) {
90
90
  r.disconnect();
91
91
  }
92
92
  }
93
+ /** The PostgreSQL image tests run on: PostgreSQL 17 with pgvector, as in the compose files. */
94
+ export const TEST_PG_IMAGE = "pgvector/pgvector:pg17";
93
95
  /**
94
- * Start a throwaway PostgreSQL 17 container. `tuned` is for the run-wide shared instance: many files
95
- * connect at once (raise `max_connections`), and durability is irrelevant for tests (no fsync).
96
+ * Start a throwaway PostgreSQL 17 container (`TEST_PG_IMAGE` unless `image` names another, e.g.
97
+ * plain `postgres:17` to test a server without pgvector). `tuned` is for the run-wide shared
98
+ * instance: many files connect at once (raise `max_connections`), and durability is irrelevant for
99
+ * tests (no fsync).
96
100
  */
97
101
  export async function startPostgresContainer(opts = {}) {
98
- const image = new PostgreSqlContainer("postgres:17");
102
+ const image = new PostgreSqlContainer(opts.image ?? TEST_PG_IMAGE);
99
103
  if (opts.tuned) {
100
104
  image.withCommand([
101
105
  "postgres",
@@ -108,7 +108,13 @@ export interface Harness {
108
108
  * 另一个副本照常工作。已退出时是空操作。
109
109
  */
110
110
  kill(index: number): Promise<void>;
111
- /** 停两个副本(15s 后 SIGKILL)、删临时库、关自有容器;幂等。 */
111
+ /**
112
+ * 停两个副本(15s 后 SIGKILL)、删临时库、关自有容器;幂等。Before the replicas stop it asserts
113
+ * that they left no queued run without its job (neither in the outbox nor in BullMQ: the "queue
114
+ * lost jobs" canary of the kernel's run-orphan-check, transactional outbox spec §11); after the
115
+ * cleanup it rejects naming such runs, or with the check's own error. A database or Redis it
116
+ * cannot reach skips the check.
117
+ */
112
118
  stop(): Promise<void>;
113
119
  }
114
120
  /**
@@ -3,6 +3,7 @@ import { randomBytes } from "node:crypto";
3
3
  import { createRequire } from "node:module";
4
4
  import { extname, resolve } from "node:path";
5
5
  import { fileURLToPath, pathToFileURL } from "node:url";
6
+ import { Redis } from "ioredis";
6
7
  import { createFreshDatabase, sharedPgAdminUrl, startPostgresContainer, startTestRedis, } from "./containers.js";
7
8
  /** 副本在响应头里标明自己的序号(runner 把 `http.replicaId` 设为 `"0"` / `"1"`)。 */
8
9
  export const REPLICA_HEADER = "x-capybara-replica";
@@ -20,6 +21,41 @@ const ALL_ROLES = ["api", "worker", "gateway"];
20
21
  const STOP_TIMEOUT_MS = 15_000;
21
22
  const START_TIMEOUT_MS = 60_000;
22
23
  const STDERR_TAIL = 4000;
24
+ /**
25
+ * The queued runs of the harness's database whose job is neither in the outbox nor in BullMQ (the
26
+ * kernel's `queuedRunsWithoutJob`; a BullMQ job is the hash `bull:<queue>:<jobId>`). Null only when
27
+ * the database or Redis cannot be reached (a test that stopped them: the check is skipped); any
28
+ * other error is thrown.
29
+ */
30
+ async function queuedOrphansOf(dbUrl, redisUrl) {
31
+ // loaded here, not at the top: a process that only spawns replicas (or is killed) never needs
32
+ // the kernel in its own module graph
33
+ const { createDb, kernelDb, queuedRunsWithoutJob } = await import("@capybara-hq/kernel");
34
+ const { sql } = await import("kysely");
35
+ const raw = createDb(dbUrl, 1, () => { }, { connectTimeoutMs: 5000 });
36
+ const redis = new Redis(redisUrl, {
37
+ lazyConnect: true,
38
+ connectTimeout: 5000,
39
+ maxRetriesPerRequest: 1,
40
+ retryStrategy: () => null,
41
+ });
42
+ redis.on("error", () => { });
43
+ try {
44
+ try {
45
+ await redis.connect();
46
+ await sql `SELECT 1`.execute(raw);
47
+ }
48
+ catch {
49
+ return null;
50
+ }
51
+ const found = await queuedRunsWithoutJob(kernelDb(raw), async (queue, jobId) => (await redis.exists(`bull:${queue}:${jobId}`)) === 1, { minAgeMs: 0 });
52
+ return found.map((c) => `${c.runId} (conversation ${c.conversationId}, job ${c.jobId})`);
53
+ }
54
+ finally {
55
+ redis.disconnect();
56
+ await raw.destroy().catch(() => { });
57
+ }
58
+ }
23
59
  /** runner 与本文件同目录;源码下是 .ts,编译后是 .js。 */
24
60
  const runnerPath = fileURLToPath(new URL(`./replica-runner${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
25
61
  /**
@@ -120,6 +156,8 @@ export async function createDualReplicaHarness(opts) {
120
156
  const runners = [];
121
157
  let dropDb;
122
158
  let stopPromise;
159
+ /** Set once both replicas started: `stop()` then checks for queued runs without a job. */
160
+ let checkOrphans;
123
161
  const stopRunner = async (r) => {
124
162
  if (r.child.exitCode !== null || r.child.signalCode !== null)
125
163
  return;
@@ -138,9 +176,18 @@ export async function createDualReplicaHarness(opts) {
138
176
  };
139
177
  const stop = () => {
140
178
  stopPromise ??= (async () => {
179
+ const checked = await checkOrphans?.().then((orphans) => ({ orphans }), (error) => ({ error }));
141
180
  await Promise.allSettled(runners.map(stopRunner));
142
181
  await Promise.allSettled([dropDb?.()]);
143
182
  await Promise.allSettled(owned.map((c) => c.stop()));
183
+ if (checked && "error" in checked)
184
+ throw checked.error;
185
+ const orphans = checked?.orphans ?? null;
186
+ if (orphans !== null && orphans.length > 0) {
187
+ throw new Error(`the replicas left ${orphans.length} queued run(s) without a job (neither owed by the ` +
188
+ `outbox nor in BullMQ; the run-orphan-check would report "the queue lost jobs"): ` +
189
+ orphans.join(", "));
190
+ }
144
191
  })();
145
192
  return stopPromise;
146
193
  };
@@ -216,6 +263,7 @@ export async function createDualReplicaHarness(opts) {
216
263
  };
217
264
  let calls = 0;
218
265
  let extraChain = Promise.resolve();
266
+ checkOrphans = () => queuedOrphansOf(db.url, redisUrl);
219
267
  const kill = async (index) => {
220
268
  const { runner: r } = runnerAt(index);
221
269
  if (r.child.exitCode === null && r.child.signalCode === null)
@@ -10,19 +10,21 @@
10
10
  * | `fake-connector` | `connector@1` kind `fake`: an MCP client for `startFakeMcpServer` (auth, one 401 retry, connectorData routes from `_meta["fake/route"]`, onToolsChanged, onElicit incl. `-32042`, resources, prompts, inspect); endpoint `{ url, headers?, notesText? }`; template `fake-demo`; deployment config `allowInsecureLoopback` (default true), `inspectAuth` (`bearer` / `api_key`), `kind` (default `fake`; `mcp` lets clients that know only the official kinds drive it) |
11
11
  * | `fake-openapi` | `connector@1` kind `openapi` (the web wizard's OpenAPI flow): reads a small JSON document (`securitySchemes` as auth hints, `operations` as tools) from the endpoint's `specUrl`, calls operations over HTTP with the injected auth; endpoint `{ specUrl, baseUrl?, operations? }`; deployment config `allowInsecureLoopback` (default true) |
12
12
  * | `fake-object-store` | `object-store@1` on the `startTestS3()` container (deployment config as `TestS3` gives it; POST-policy presign) |
13
- * | `fake-tools-ui` | tool `write`, view `tasks`, a migration, skill `fake-notes`, template `fake-notes` (for fake-connector); no storage |
13
+ * | `fake-tools-ui` | tools `write` and `web-only` (`sources` web and channel_dm; returns its call context), view `tasks`, a migration, skill `fake-notes`, template `fake-notes` (for fake-connector); no storage |
14
14
  * | `fake-storage-user` | tools `note` / `read_note` through `ctx.storage` (`permissions.storage`) |
15
+ * | `fake-lifecycle` | observes `org.member_removed`, `agent.deleted` and `org.deleted`; a migration with tables `calls` (every call) and `deliveries` (every call that succeeded), each row the mount and the payload; deployment config `failTimes` (default 0): the first `failTimes` calls of each (mount, payload) throw, and `label` (optional, at most 10 characters, overridable per org: an invalid org copy) |
15
16
  * | `fake-embed` | embeds `panel` (page) and `panel-conv` (conversation), static `/ui/panel.js`, token-checked routes, SSE over `ctx.bus` |
16
17
  * | `fake-bootstrap-a` | `model-provider@2` with a required secret `apiKey` (pending configuration until set) |
17
18
  * | `fake-bootstrap-b` | `object-store@1` kept in its own PG table; `bucket` + secret `secretKey` |
18
19
  * | `fake-dep-provider` / `fake-dep-requirer` | a dependency pair on `counter@1` (the requirer's plugin.json depends on the provider) |
19
20
  * | `fake-im` | a whole IM platform for `startFakeChannelServer`: `channel@1` (cards, edits, threads, 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 |
20
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`) |
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) |
21
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` |
22
24
  * | `fake-client-broken` | client code that throws: component `boom` (render), a `run.started` events listener, and a `conversation.empty` replacement (render) |
23
25
  * | `fake-config-form` | display name 表单样例 / Form sample; no extension point: an openai-compatible-shaped deployment config (endpoints with a preset menu, an API key per endpoint in the secret record `apiKeys`, model rows, advanced fields, localized custom issues) carrying the config form hints of the extension config forms spec §6, for the web form e2e |
24
26
  */
25
- export declare const FAKE_EXTENSIONS: readonly ["fake-connector", "fake-openapi", "fake-object-store", "fake-tools-ui", "fake-storage-user", "fake-embed", "fake-bootstrap-a", "fake-bootstrap-b", "fake-dep-provider", "fake-dep-requirer", "fake-im", "fake-web", "fake-web-2", "fake-config-form", "fake-client", "fake-client-broken"];
27
+ export declare const FAKE_EXTENSIONS: readonly ["fake-connector", "fake-openapi", "fake-object-store", "fake-tools-ui", "fake-storage-user", "fake-lifecycle", "fake-embed", "fake-bootstrap-a", "fake-bootstrap-b", "fake-dep-provider", "fake-dep-requirer", "fake-im", "fake-web", "fake-web-2", "fake-context", "fake-config-form", "fake-client", "fake-client-broken"];
26
28
  /**
27
29
  * Fake plugins without an extension (declarative: they live in `fixtures/plugins/<name>`, same
28
30
  * pack layout).
package/dist/fixtures.js CHANGED
@@ -13,14 +13,16 @@ import { fileURLToPath } from "node:url";
13
13
  * | `fake-connector` | `connector@1` kind `fake`: an MCP client for `startFakeMcpServer` (auth, one 401 retry, connectorData routes from `_meta["fake/route"]`, onToolsChanged, onElicit incl. `-32042`, resources, prompts, inspect); endpoint `{ url, headers?, notesText? }`; template `fake-demo`; deployment config `allowInsecureLoopback` (default true), `inspectAuth` (`bearer` / `api_key`), `kind` (default `fake`; `mcp` lets clients that know only the official kinds drive it) |
14
14
  * | `fake-openapi` | `connector@1` kind `openapi` (the web wizard's OpenAPI flow): reads a small JSON document (`securitySchemes` as auth hints, `operations` as tools) from the endpoint's `specUrl`, calls operations over HTTP with the injected auth; endpoint `{ specUrl, baseUrl?, operations? }`; deployment config `allowInsecureLoopback` (default true) |
15
15
  * | `fake-object-store` | `object-store@1` on the `startTestS3()` container (deployment config as `TestS3` gives it; POST-policy presign) |
16
- * | `fake-tools-ui` | tool `write`, view `tasks`, a migration, skill `fake-notes`, template `fake-notes` (for fake-connector); no storage |
16
+ * | `fake-tools-ui` | tools `write` and `web-only` (`sources` web and channel_dm; returns its call context), view `tasks`, a migration, skill `fake-notes`, template `fake-notes` (for fake-connector); no storage |
17
17
  * | `fake-storage-user` | tools `note` / `read_note` through `ctx.storage` (`permissions.storage`) |
18
+ * | `fake-lifecycle` | observes `org.member_removed`, `agent.deleted` and `org.deleted`; a migration with tables `calls` (every call) and `deliveries` (every call that succeeded), each row the mount and the payload; deployment config `failTimes` (default 0): the first `failTimes` calls of each (mount, payload) throw, and `label` (optional, at most 10 characters, overridable per org: an invalid org copy) |
18
19
  * | `fake-embed` | embeds `panel` (page) and `panel-conv` (conversation), static `/ui/panel.js`, token-checked routes, SSE over `ctx.bus` |
19
20
  * | `fake-bootstrap-a` | `model-provider@2` with a required secret `apiKey` (pending configuration until set) |
20
21
  * | `fake-bootstrap-b` | `object-store@1` kept in its own PG table; `bucket` + secret `secretKey` |
21
22
  * | `fake-dep-provider` / `fake-dep-requirer` | a dependency pair on `counter@1` (the requirer's plugin.json depends on the provider) |
22
23
  * | `fake-im` | a whole IM platform for `startFakeChannelServer`: `channel@1` (cards, edits, threads, 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 |
23
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`) |
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) |
24
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` |
25
27
  * | `fake-client-broken` | client code that throws: component `boom` (render), a `run.started` events listener, and a `conversation.empty` replacement (render) |
26
28
  * | `fake-config-form` | display name 表单样例 / Form sample; no extension point: an openai-compatible-shaped deployment config (endpoints with a preset menu, an API key per endpoint in the secret record `apiKeys`, model rows, advanced fields, localized custom issues) carrying the config form hints of the extension config forms spec §6, for the web form e2e |
@@ -31,6 +33,7 @@ export const FAKE_EXTENSIONS = [
31
33
  "fake-object-store",
32
34
  "fake-tools-ui",
33
35
  "fake-storage-user",
36
+ "fake-lifecycle",
34
37
  "fake-embed",
35
38
  "fake-bootstrap-a",
36
39
  "fake-bootstrap-b",
@@ -39,6 +42,7 @@ export const FAKE_EXTENSIONS = [
39
42
  "fake-im",
40
43
  "fake-web",
41
44
  "fake-web-2",
45
+ "fake-context",
42
46
  "fake-config-form",
43
47
  "fake-client",
44
48
  "fake-client-broken",
package/dist/index.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  * keys the kernel owns (assert on them instead of copying their values).
5
5
  */
6
6
  export { type ConversationEvent, createDb, gatewayReplicasKey, type KernelConfig, type KernelSchemaDb, kernelDb, MAINTENANCE_QUEUE_NAME, runJobId, SANDBOX_LOCK_TTL_MS, SANDBOX_RESTARTED_NOTICE, SANDBOX_STARTED_NOTICE, SANDBOX_SUSPEND_JOB, UNKNOWN_RESULT_TEXT, } from "@capybara-hq/kernel";
7
- export { createFreshDatabase, startTestPostgres, startTestRedis, startTestS3, TEST_S3_IMAGE, type TestContainer, type TestS3, } from "./containers.js";
7
+ export { createFreshDatabase, startPostgresContainer, startTestPostgres, startTestRedis, startTestS3, TEST_PG_IMAGE, TEST_S3_IMAGE, type TestContainer, type TestS3, } from "./containers.js";
8
8
  export { createDualReplicaHarness, type DualReplicaOptions, type ExtraReplicaHandle, type Harness, REPLICA_HEADER, type ReplicaHandle, type ReplicaResponse, replicaOf, } from "./dual-replica.js";
9
9
  export { assertExtensionSecretsReachable, extensionDeploymentSecretValues, } from "./extension-config.js";
10
10
  export { FAKE_CHANNEL_BAD_SECRET, FAKE_WEBHOOK_SIGNATURE_HEADER, type FakeChannelCheckCall, type FakeChannelFailMatch, type FakeChannelPost, type FakeChannelSent, type FakeChannelServer, type FakeChannelServerOptions, type FakeChannelStream, type FakeChannelUser, type FakeDirectoryBook, type FakeSenderProfile, fakeCardAction, fakeDirectoryMember, fakeDm, fakeGroupMessage, fakeWebhookChallenge, fakeWebhookEvents, signFakeWebhook, startFakeChannelServer, } from "./fake-channel.js";
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@
4
4
  * keys the kernel owns (assert on them instead of copying their values).
5
5
  */
6
6
  export { createDb, gatewayReplicasKey, kernelDb, MAINTENANCE_QUEUE_NAME, runJobId, SANDBOX_LOCK_TTL_MS, SANDBOX_RESTARTED_NOTICE, SANDBOX_STARTED_NOTICE, SANDBOX_SUSPEND_JOB, UNKNOWN_RESULT_TEXT, } from "@capybara-hq/kernel";
7
- export { createFreshDatabase, startTestPostgres, startTestRedis, startTestS3, TEST_S3_IMAGE, } from "./containers.js";
7
+ export { createFreshDatabase, startPostgresContainer, startTestPostgres, startTestRedis, startTestS3, TEST_PG_IMAGE, TEST_S3_IMAGE, } from "./containers.js";
8
8
  export { createDualReplicaHarness, REPLICA_HEADER, replicaOf, } from "./dual-replica.js";
9
9
  export { assertExtensionSecretsReachable, extensionDeploymentSecretValues, } from "./extension-config.js";
10
10
  export { FAKE_CHANNEL_BAD_SECRET, FAKE_WEBHOOK_SIGNATURE_HEADER, fakeCardAction, fakeDirectoryMember, fakeDm, fakeGroupMessage, fakeWebhookChallenge, fakeWebhookEvents, signFakeWebhook, startFakeChannelServer, } from "./fake-channel.js";
@@ -97,7 +97,8 @@ export declare function joinOrg(k: Pick<TestKernel, "http">, owner: KernelReques
97
97
  }>;
98
98
  /**
99
99
  * Creates an org-visible agent; returns its id. An agent has every tool the org offers unless
100
- * `disabledTools` turns it off (tools default-on spec); with several tools model-fake answers
100
+ * `disabledTools` turns it off (tools default-on spec), and every skill on in the org unless
101
+ * `disabledSkills` turns it off (skills default-on spec); with several tools model-fake answers
101
102
  * ordinary messages instead of calling one.
102
103
  */
103
104
  export declare function createAgent(req: KernelRequest, orgId: string, opts?: {
@@ -106,6 +107,7 @@ export declare function createAgent(req: KernelRequest, orgId: string, opts?: {
106
107
  model: string;
107
108
  };
108
109
  disabledTools?: unknown[];
110
+ disabledSkills?: unknown[];
109
111
  }): Promise<string>;
110
112
  /** Creates a conversation with the agent; returns its id. */
111
113
  export declare function createConversation(req: KernelRequest, orgId: string, agentId: string): Promise<string>;
@@ -179,7 +179,8 @@ export async function joinOrg(k, owner, orgId, name, role = "member") {
179
179
  }
180
180
  /**
181
181
  * Creates an org-visible agent; returns its id. An agent has every tool the org offers unless
182
- * `disabledTools` turns it off (tools default-on spec); with several tools model-fake answers
182
+ * `disabledTools` turns it off (tools default-on spec), and every skill on in the org unless
183
+ * `disabledSkills` turns it off (skills default-on spec); with several tools model-fake answers
183
184
  * ordinary messages instead of calling one.
184
185
  */
185
186
  export async function createAgent(req, orgId, opts = {}) {
@@ -192,6 +193,7 @@ export async function createAgent(req, orgId, opts = {}) {
192
193
  instructions: "Be helpful.",
193
194
  model: opts.model ?? { provider: "model-fake", model: "fake-1" },
194
195
  disabledTools: opts.disabledTools ?? [],
196
+ ...(opts.disabledSkills !== undefined && { disabledSkills: opts.disabledSkills }),
195
197
  },
196
198
  visibility: "org",
197
199
  },
@@ -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
+ });
@@ -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
+ });
@@ -13,6 +13,8 @@ import { z } from "zod";
13
13
  * it needs no object store (storage is `fake-storage-user`'s).
14
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."
@@ -126,7 +138,7 @@ export default defineExtension({
126
138
  },
127
139
  ],
128
140
  permissions: {
129
- tools: ["write"],
141
+ tools: ["write", "web-only"],
130
142
  ui: { views: ["tasks", "agent-notes", "org-admin", "platform-home"] },
131
143
  },
132
144
  setup(ctx) {
@@ -156,6 +168,14 @@ export default defineExtension({
156
168
  },
157
169
  };
158
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
+ });
159
179
  ctx.ui.view("tasks", async ({ conversationId }) =>
160
180
  tasksView(conversationId === undefined ? [] : await readItems(ctx.db, conversationId)),
161
181
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/testing",
3
- "version": "0.1.0-rc.15",
3
+ "version": "0.1.0-rc.17",
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,17 +47,17 @@
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.16"
50
+ "@capybara-hq/kernel": "^0.1.0-rc.25"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@types/pg": "^8.23.1",
54
54
  "@types/ws": "^8.18.2",
55
- "@capybara-hq/plugin-client": "^0.1.0-rc.2",
56
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.12"
55
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.19",
56
+ "@capybara-hq/plugin-client": "^0.1.0-rc.4"
57
57
  },
58
58
  "peerDependencies": {
59
59
  "vitest": "^5.0.5",
60
- "@capybara-hq/plugin-sdk": "^0.1.0-rc.12",
60
+ "@capybara-hq/plugin-sdk": "^0.1.0-rc.19",
61
61
  "@capybara-hq/plugin-tools": "^0.1.0-rc.13"
62
62
  },
63
63
  "peerDependenciesMeta": {