@capybara-hq/testing 0.1.0-rc.1 → 0.1.0-rc.11

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 (44) hide show
  1. package/dist/dual-replica.d.ts +10 -6
  2. package/dist/dual-replica.js +3 -1
  3. package/dist/fake-channel.d.ts +15 -2
  4. package/dist/fake-channel.js +11 -2
  5. package/dist/fake-e2b.d.ts +36 -1
  6. package/dist/fake-e2b.js +95 -1
  7. package/dist/fake-git-server.js +3 -1
  8. package/dist/fake-oauth-server.d.ts +16 -2
  9. package/dist/fake-oauth-server.js +21 -1
  10. package/dist/fake-telegram.d.ts +165 -0
  11. package/dist/fake-telegram.js +569 -0
  12. package/dist/fixtures.d.ts +16 -3
  13. package/dist/fixtures.js +21 -3
  14. package/dist/index.d.ts +4 -3
  15. package/dist/index.js +2 -1
  16. package/dist/kernel-helpers.d.ts +38 -16
  17. package/dist/kernel-helpers.js +42 -13
  18. package/dist/model-conformance.d.ts +5 -0
  19. package/dist/model-conformance.js +33 -1
  20. package/dist/replica-runner.js +17 -9
  21. package/fixtures/extensions/fake-config-form/.capybara-plugin/plugin.json +11 -0
  22. package/fixtures/extensions/fake-config-form/package.json +12 -0
  23. package/fixtures/extensions/fake-config-form/src/index.ts +205 -0
  24. package/fixtures/extensions/fake-im/.capybara-plugin/plugin.json +33 -1
  25. package/fixtures/extensions/fake-im/guides/app.long-connection.yaml.tmpl +5 -0
  26. package/fixtures/extensions/fake-im/guides/app.webhook.json.tmpl +8 -0
  27. package/fixtures/extensions/fake-storage-user/src/index.ts +1 -1
  28. package/fixtures/extensions/fake-tools-ui/skills/fake-notes/SKILL.md +1 -1
  29. package/fixtures/extensions/fake-tools-ui/src/index.ts +1 -1
  30. package/fixtures/extensions/fake-web/.capybara-plugin/plugin.json +7 -0
  31. package/fixtures/extensions/fake-web/package.json +12 -0
  32. package/fixtures/extensions/fake-web/src/index.ts +22 -0
  33. package/fixtures/extensions/fake-web/src/web.ts +183 -0
  34. package/fixtures/extensions/fake-web-2/.capybara-plugin/plugin.json +7 -0
  35. package/fixtures/extensions/fake-web-2/package.json +12 -0
  36. package/fixtures/extensions/fake-web-2/src/index.ts +16 -0
  37. package/fixtures/extensions/fake-web-2/src/web.ts +183 -0
  38. package/fixtures/plugins/fake-theme/.capybara-plugin/plugin.json +7 -0
  39. package/fixtures/plugins/fake-theme/fonts/FakeSans.woff2 +1 -0
  40. package/fixtures/plugins/fake-theme/logo.svg +1 -0
  41. package/fixtures/plugins/fake-theme/package.json +8 -0
  42. package/fixtures/plugins/fake-theme/themes/night-city.json +13 -0
  43. package/fixtures/plugins/fake-theme/themes/paper.json +12 -0
  44. package/package.json +5 -5
package/dist/index.d.ts CHANGED
@@ -3,11 +3,11 @@
3
3
  * package and the SDK: the database helpers and types, and model-visible texts, queue names and
4
4
  * keys the kernel owns (assert on them instead of copying their values).
5
5
  */
6
- export { type ConversationEvent, createDb, gatewayReplicasKey, type Kernel, type KernelConfig, type KernelDb, kernelDb, MAINTENANCE_QUEUE_NAME, runJobId, SANDBOX_LOCK_TTL_MS, SANDBOX_RECREATED_NOTICE, SANDBOX_STARTED_NOTICE, SANDBOX_SUSPEND_JOB, UNKNOWN_RESULT_TEXT, } from "@capybara-hq/kernel";
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
7
  export { createFreshDatabase, startTestPostgres, startTestRedis, startTestS3, 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
- export { FAKE_CHANNEL_BAD_SECRET, FAKE_WEBHOOK_SIGNATURE_HEADER, 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";
10
+ export { FAKE_CHANNEL_BAD_SECRET, FAKE_WEBHOOK_SIGNATURE_HEADER, 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";
11
11
  export { type FakeE2BCall, type FakeE2BMatch, type FakeE2BOptions, type FakeE2BSandbox, type FakeE2BServer, startFakeE2B, } from "./fake-e2b.js";
12
12
  export { type FakeGitCommitOptions, type FakeGitRequest, type FakeGitServer, startFakeGitServer, } from "./fake-git-server.js";
13
13
  export { encryptLarkWebhook, type FakeLarkAck, type FakeLarkApi, type FakeLarkButton, type FakeLarkCall, type FakeLarkDepartment, type FakeLarkFailure, type FakeLarkMessage, type FakeLarkOptions, type FakeLarkServer, type FakeLarkUser, findLarkButton, larkCardAction, larkMessageEvent, signLarkWebhook, startFakeLark, } from "./fake-lark.js";
@@ -18,8 +18,9 @@ export { type FakeNpmPackage, type FakeNpmRegistry, npmProvenanceAttestations, s
18
18
  export { type FakeOAuthClient, type FakeOAuthServer, type FakeOAuthServerOptions, type FakeTokenRequest, startFakeOAuthServer, } from "./fake-oauth-server.js";
19
19
  export { defaultFakeOpenApiSpec, type FakeOpenApiRequest, type FakeOpenApiServer, type FakeOpenApiServerOptions, type FakePet, startFakeOpenApiServer, } from "./fake-openapi-server.js";
20
20
  export { type FakeSlackAck, type FakeSlackCall, type FakeSlackFailure, type FakeSlackMessage, type FakeSlackOptions, type FakeSlackServer, type FakeSlackUser, findSlackButton, signSlackWebhook, slackBlockAction, slackDmEvent, slackEventCallback, slackInteractiveForm, slackMentionEvent, startFakeSlack, } from "./fake-slack.js";
21
+ export { type FakeTelegramBot, type FakeTelegramCall, type FakeTelegramFailure, type FakeTelegramMessage, type FakeTelegramOptions, type FakeTelegramServer, findTelegramButton, startFakeTelegram, type TgChat, type TgUser, telegramCallback, telegramGroupMessage, telegramPrivateMessage, telegramWebhookHeaders, } from "./fake-telegram.js";
21
22
  export { FAKE_EXTENSIONS, type FakeExtensionName, fakeExtensionDir, fakeExtensionEntry, type PackedFixture, packFixture, } from "./fixtures.js";
22
- export { cardRecorded, cookieRequest, createAgent, createConversation, createLocalAccount, createOrg, eventsOf, joinOrg, type KernelRequest, type KernelRequestOptions, type KernelResponse, login, pidOwningLocalPort, postMessage, sleep, startTestKernel, TEST_PASSWORD, testKernelConfig, truncateTables, waitFor, waitForEvent, waitForTerminal, } from "./kernel-helpers.js";
23
+ export { cardRecorded, cookieRequest, createAgent, createConversation, createLocalAccount, createOrg, eventsOf, joinOrg, type KernelApp, type KernelRequest, type KernelRequestOptions, type KernelResponse, login, pidOwningLocalPort, postMessage, sleep, startTestKernel, TEST_PASSWORD, type TestKernel, testKernelConfig, truncateTables, waitFor, waitForEvent, waitForTerminal, } from "./kernel-helpers.js";
23
24
  export { isPngBase64, pdfBase64, pdfSampleWord, redPngBase64, solidPngBase64, } from "./media-samples.js";
24
25
  export { type ConformanceTarget, checkDeclaredParameters, describeModelProviderConformance, MEDIA_SAMPLES, thinkingReplayParams, } from "./model-conformance.js";
25
26
  export { openSse, type SseClient, type SseMessage } from "./sse.js";
package/dist/index.js CHANGED
@@ -3,7 +3,7 @@
3
3
  * package and the SDK: the database helpers and types, and model-visible texts, queue names and
4
4
  * keys the kernel owns (assert on them instead of copying their values).
5
5
  */
6
- export { createDb, gatewayReplicasKey, kernelDb, MAINTENANCE_QUEUE_NAME, runJobId, SANDBOX_LOCK_TTL_MS, SANDBOX_RECREATED_NOTICE, SANDBOX_STARTED_NOTICE, SANDBOX_SUSPEND_JOB, UNKNOWN_RESULT_TEXT, } from "@capybara-hq/kernel";
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
7
  export { createFreshDatabase, startTestPostgres, startTestRedis, startTestS3, 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";
@@ -18,6 +18,7 @@ export { npmProvenanceAttestations, startFakeNpmRegistry, } from "./fake-npm-reg
18
18
  export { startFakeOAuthServer, } from "./fake-oauth-server.js";
19
19
  export { defaultFakeOpenApiSpec, startFakeOpenApiServer, } from "./fake-openapi-server.js";
20
20
  export { findSlackButton, signSlackWebhook, slackBlockAction, slackDmEvent, slackEventCallback, slackInteractiveForm, slackMentionEvent, startFakeSlack, } from "./fake-slack.js";
21
+ export { findTelegramButton, startFakeTelegram, telegramCallback, telegramGroupMessage, telegramPrivateMessage, telegramWebhookHeaders, } from "./fake-telegram.js";
21
22
  export { FAKE_EXTENSIONS, fakeExtensionDir, fakeExtensionEntry, packFixture, } from "./fixtures.js";
22
23
  export { cardRecorded, cookieRequest, createAgent, createConversation, createLocalAccount, createOrg, eventsOf, joinOrg, login, pidOwningLocalPort, postMessage, sleep, startTestKernel, TEST_PASSWORD, testKernelConfig, truncateTables, waitFor, waitForEvent, waitForTerminal, } from "./kernel-helpers.js";
23
24
  export { isPngBase64, pdfBase64, pdfSampleWord, redPngBase64, solidPngBase64, } from "./media-samples.js";
@@ -1,4 +1,4 @@
1
- import { type ConversationEvent, type Kernel, type KernelConfig, type KernelDb, type KernelHttp, type LogLevel } from "@capybara-hq/kernel";
1
+ import { type ConversationEvent, type KernelConfig, type KernelHttp, type KernelSchemaDb, type LogLevel, startKernelApp } from "@capybara-hq/kernel";
2
2
  import { type Kysely } from "kysely";
3
3
  /**
4
4
  * Helpers for extension tests that run a real kernel: in process (`startTestKernel` +
@@ -33,11 +33,32 @@ export declare function testKernelConfig(urls: {
33
33
  * it before creating anything.
34
34
  */
35
35
  export declare function assertOfflineOfficialMarketplace(config: KernelConfig, allow?: boolean): void;
36
+ /** The kernel's Nest application (what `createKernelApp` / `startKernelApp` return). */
37
+ export type KernelApp = Awaited<ReturnType<typeof startKernelApp>>;
38
+ /** A running in-process kernel ({@link startTestKernel}). */
39
+ export interface TestKernel {
40
+ /**
41
+ * The kernel's Nest application. Core's own tests reach a kernel service with `app.get(Class)`;
42
+ * a plugin test cannot import kernel classes (`plugin-test-imports`), so it drives the kernel
43
+ * through `http` and the helpers of this package.
44
+ */
45
+ readonly app: KernelApp;
46
+ /** In-process HTTP: `inject` requests, list the routes. */
47
+ readonly http: KernelHttp;
48
+ /**
49
+ * The port the kernel listens on (an ephemeral one with `http.port: 0`); undefined after
50
+ * `close()`.
51
+ */
52
+ readonly port: number | undefined;
53
+ /** Stops the kernel (the stop phases within their budgets, then Redis and the pool); idempotent. */
54
+ close(): Promise<void>;
55
+ }
36
56
  /**
37
- * Creates and starts an in-process kernel. Logs are discarded unless `log` is given (JSON lines at
38
- * `log.level` and above go to `log.write`, e.g. to assert a secret never reaches the log).
39
- * Extensions named by package resolve from `resolveFrom` (default `process.cwd()`). Stop it with
40
- * `stop()`.
57
+ * Creates and starts an in-process kernel (`startKernelApp`; it listens on `config.http.port`).
58
+ * The kernel gets no process-wide signal handlers: a test stops it with `close()`. Logs are
59
+ * discarded unless `log` is given (JSON lines at `log.level` and above go to `log.write`, e.g. to
60
+ * assert a secret never reaches the log). Extensions named by package resolve from `resolveFrom`
61
+ * (default `process.cwd()`).
41
62
  */
42
63
  export declare function startTestKernel(config: KernelConfig, opts?: {
43
64
  resolveFrom?: string;
@@ -47,7 +68,7 @@ export declare function startTestKernel(config: KernelConfig, opts?: {
47
68
  };
48
69
  /** Only for a test about the real default: allow the official marketplace at its real URL. */
49
70
  allowOfficialMarketplace?: boolean;
50
- }): Promise<Kernel>;
71
+ }): Promise<TestKernel>;
51
72
  /** Options of a {@link KernelRequest} call (`http.inject` options; `csrf: false` drops the header). */
52
73
  export type KernelRequestOptions = Parameters<KernelHttp["inject"]>[0] & {
53
74
  csrf?: boolean;
@@ -61,46 +82,47 @@ export type KernelRequest = (opts: KernelRequestOptions) => Promise<KernelRespon
61
82
  /** A request function with its own cookie jar (signed out until a response sets cookies). */
62
83
  export declare function cookieRequest(http: KernelHttp): KernelRequest;
63
84
  /** Creates a local account with {@link TEST_PASSWORD}; returns its id. */
64
- export declare function createLocalAccount(db: KernelDb, login: string, displayName?: string): Promise<string>;
85
+ export declare function createLocalAccount(db: KernelSchemaDb, login: string, displayName?: string): Promise<string>;
65
86
  /** Signs in over HTTP and returns the user's request function. */
66
- export declare function login(k: Pick<Kernel, "http">, name: string, password?: string): Promise<KernelRequest>;
87
+ export declare function login(k: Pick<TestKernel, "http">, name: string, password?: string): Promise<KernelRequest>;
67
88
  /** Creates an org as `req`'s user (who becomes its owner); returns its id. */
68
89
  export declare function createOrg(req: KernelRequest, name?: string): Promise<string>;
69
90
  /**
70
91
  * A new account joins the org through an invitation (created by `owner`, accepted with `login`
71
92
  * and {@link TEST_PASSWORD}); returns the account id and its signed-in request function.
72
93
  */
73
- export declare function joinOrg(k: Pick<Kernel, "http">, owner: KernelRequest, orgId: string, name: string, role?: "member" | "admin"): Promise<{
94
+ export declare function joinOrg(k: Pick<TestKernel, "http">, owner: KernelRequest, orgId: string, name: string, role?: "member" | "admin"): Promise<{
74
95
  accountId: string;
75
96
  req: KernelRequest;
76
97
  }>;
77
98
  /**
78
- * Creates an org-visible agent; returns its id. Without `tools` the agent has none (model-fake then
79
- * answers ordinary messages instead of calling the first tool).
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
101
+ * ordinary messages instead of calling one.
80
102
  */
81
103
  export declare function createAgent(req: KernelRequest, orgId: string, opts?: {
82
104
  model?: {
83
105
  provider: string;
84
106
  model: string;
85
107
  };
86
- tools?: unknown[];
108
+ disabledTools?: unknown[];
87
109
  }): Promise<string>;
88
110
  /** Creates a conversation with the agent; returns its id. */
89
111
  export declare function createConversation(req: KernelRequest, orgId: string, agentId: string): Promise<string>;
90
112
  /** Posts a user message; returns its event seq. */
91
113
  export declare function postMessage(req: KernelRequest, orgId: string, conversationId: string, text: string): Promise<number>;
92
114
  /** Every event of a conversation, in seq order (read from the database). */
93
- export declare function eventsOf(db: KernelDb, conversationId: string): Promise<ConversationEvent[]>;
115
+ export declare function eventsOf(db: KernelSchemaDb, conversationId: string): Promise<ConversationEvent[]>;
94
116
  /** Waits for the first event matching `pred` and returns it. */
95
- export declare function waitForEvent(db: KernelDb, conversationId: string, pred: (e: ConversationEvent) => boolean, timeoutMs?: number, label?: string): Promise<ConversationEvent>;
117
+ export declare function waitForEvent(db: KernelSchemaDb, conversationId: string, pred: (e: ConversationEvent) => boolean, timeoutMs?: number, label?: string): Promise<ConversationEvent>;
96
118
  /** Waits for the conversation's `n`-th terminal event (run_finished / run_failed / run_aborted). */
97
- export declare function waitForTerminal(db: KernelDb, conversationId: string, n?: number, timeoutMs?: number): Promise<ConversationEvent[]>;
119
+ export declare function waitForTerminal(db: KernelSchemaDb, conversationId: string, n?: number, timeoutMs?: number): Promise<ConversationEvent[]>;
98
120
  /**
99
121
  * Waits until an IM card's message id is recorded (`channel_card_messages`). The kernel writes it in
100
122
  * the transaction after the card is sent; a click before that is treated as "not a card of this
101
123
  * conversation", so a test waits for this before it clicks, not only for the platform to get it.
102
124
  */
103
- export declare function cardRecorded(db: KernelDb, card: {
125
+ export declare function cardRecorded(db: KernelSchemaDb, card: {
104
126
  messageId: string;
105
127
  } | {
106
128
  kind: "approval" | "question";
@@ -1,7 +1,8 @@
1
1
  import { execFile } from "node:child_process";
2
+ import { EventEmitter } from "node:events";
2
3
  import { readdir, readFile, readlink } from "node:fs/promises";
3
4
  import { promisify } from "node:util";
4
- import { AccountsService, createKernel, createLogger, KernelConfigSchema, MARKETPLACE_OFFICIAL_URL_DEFAULT, } from "@capybara-hq/kernel";
5
+ import { AccountsModule, AccountsService, closeKernelApp, createLogger, KernelConfigSchema, kernelAppHttp, kernelAppPort, MARKETPLACE_OFFICIAL_URL_DEFAULT, openKernelCliOverPool, startKernelApp, } from "@capybara-hq/kernel";
5
6
  import { sql } from "kysely";
6
7
  /**
7
8
  * Helpers for extension tests that run a real kernel: in process (`startTestKernel` +
@@ -60,20 +61,33 @@ export function assertOfflineOfficialMarketplace(config, allow = false) {
60
61
  "marketplaces.official.url at a fake, or build the config with testKernelConfig");
61
62
  }
62
63
  /**
63
- * Creates and starts an in-process kernel. Logs are discarded unless `log` is given (JSON lines at
64
- * `log.level` and above go to `log.write`, e.g. to assert a secret never reaches the log).
65
- * Extensions named by package resolve from `resolveFrom` (default `process.cwd()`). Stop it with
66
- * `stop()`.
64
+ * Creates and starts an in-process kernel (`startKernelApp`; it listens on `config.http.port`).
65
+ * The kernel gets no process-wide signal handlers: a test stops it with `close()`. Logs are
66
+ * discarded unless `log` is given (JSON lines at `log.level` and above go to `log.write`, e.g. to
67
+ * assert a secret never reaches the log). Extensions named by package resolve from `resolveFrom`
68
+ * (default `process.cwd()`).
67
69
  */
68
70
  export async function startTestKernel(config, opts = {}) {
69
71
  assertOfflineOfficialMarketplace(config, opts.allowOfficialMarketplace);
70
- const k = await createKernel(config, {
72
+ const app = await startKernelApp(config, {
71
73
  env: {},
72
74
  logger: createLogger(opts.log?.level ?? "error", { write: opts.log?.write ?? (() => { }) }),
73
75
  ...(opts.resolveFrom !== undefined && { resolveFrom: opts.resolveFrom }),
74
- });
75
- await k.start();
76
- return k;
76
+ },
77
+ // A signal source of its own: a test kernel never handles the process's SIGTERM / SIGINT
78
+ { signals: new EventEmitter() });
79
+ return testKernelOf(app);
80
+ }
81
+ /** The {@link TestKernel} view of a started kernel application. */
82
+ function testKernelOf(app) {
83
+ return {
84
+ app,
85
+ http: kernelAppHttp(app),
86
+ get port() {
87
+ return kernelAppPort(app);
88
+ },
89
+ close: () => closeKernelApp(app),
90
+ };
77
91
  }
78
92
  /** A request function with its own cookie jar (signed out until a response sets cookies). */
79
93
  export function cookieRequest(http) {
@@ -110,7 +124,21 @@ function expectStatus(res, status, what) {
110
124
  }
111
125
  /** Creates a local account with {@link TEST_PASSWORD}; returns its id. */
112
126
  export async function createLocalAccount(db, login, displayName = login) {
113
- return (await new AccountsService(db).createLocal({ login, password: TEST_PASSWORD, displayName })).id;
127
+ // the accounts module over the caller's Kysely; closing the context leaves it open
128
+ const app = await openKernelCliOverPool(db, {
129
+ logger: createLogger("error"),
130
+ modules: [AccountsModule],
131
+ });
132
+ try {
133
+ return (await app.get(AccountsService).createLocal({
134
+ login,
135
+ password: TEST_PASSWORD,
136
+ displayName,
137
+ })).id;
138
+ }
139
+ finally {
140
+ await app.close();
141
+ }
114
142
  }
115
143
  /** Signs in over HTTP and returns the user's request function. */
116
144
  export async function login(k, name, password = TEST_PASSWORD) {
@@ -150,8 +178,9 @@ export async function joinOrg(k, owner, orgId, name, role = "member") {
150
178
  return { accountId: accepted.json().account.id, req };
151
179
  }
152
180
  /**
153
- * Creates an org-visible agent; returns its id. Without `tools` the agent has none (model-fake then
154
- * answers ordinary messages instead of calling the first tool).
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
183
+ * ordinary messages instead of calling one.
155
184
  */
156
185
  export async function createAgent(req, orgId, opts = {}) {
157
186
  const res = await req({
@@ -162,7 +191,7 @@ export async function createAgent(req, orgId, opts = {}) {
162
191
  name: "Helper",
163
192
  instructions: "Be helpful.",
164
193
  model: opts.model ?? { provider: "model-fake", model: "fake-1" },
165
- tools: opts.tools ?? [],
194
+ disabledTools: opts.disabledTools ?? [],
166
195
  },
167
196
  visibility: "org",
168
197
  },
@@ -4,6 +4,11 @@ interface TargetCommon {
4
4
  expect: {
5
5
  thinking: boolean;
6
6
  caching: boolean;
7
+ /** Set when the provider lists an embedding model: runs the embedding cases. */
8
+ embedding?: {
9
+ model: string;
10
+ dimensions: number;
11
+ };
7
12
  };
8
13
  /** caching 用例的稳定前缀大小(约 token 数),默认 5000。 */
9
14
  cachePrefixTokens?: number;
@@ -1,4 +1,4 @@
1
- import { assertValidDeclarations, EFFORT_VALUES, isModelError, sanitizeParams, validateParams, } from "@capybara-hq/plugin-sdk";
1
+ import { assertValidDeclarations, EFFORT_VALUES, isModelError, sanitizeParams, validateEmbedResult, validateParams, } from "@capybara-hq/plugin-sdk";
2
2
  import { afterAll, beforeAll, describe, expect, it } from "vitest";
3
3
  import { pdfBase64, redPngBase64 } from "./media-samples.js";
4
4
  function streamOf(t, req, signal) {
@@ -260,6 +260,38 @@ export function describeModelProviderConformance(name, setup) {
260
260
  expect(done.stopReason).toBe("end_turn");
261
261
  expect(textOf(done.content).toUpperCase()).toContain(s.word);
262
262
  });
263
+ describe("embedding", () => {
264
+ const inputs = ["alpha", "bravo", "charlie"];
265
+ const run = async () => {
266
+ const emb = t.expect.embedding;
267
+ const provider = t.provider;
268
+ if (!emb || !provider.embed)
269
+ throw new Error("the target declares embedding but has no embed");
270
+ const req = { model: emb.model, input: inputs, dimensions: emb.dimensions };
271
+ const res = await provider.embed(req, { signal: new AbortController().signal });
272
+ const models = await provider.listModels();
273
+ const info = models.find((m) => m.id === emb.model)?.embedding;
274
+ return { req, res, info };
275
+ };
276
+ it("embeds a batch in order", async (ctx) => {
277
+ if (!t.expect.embedding)
278
+ return ctx.skip();
279
+ const { res } = await run();
280
+ expect(res.vectors).toHaveLength(inputs.length);
281
+ for (const v of res.vectors)
282
+ expect(v).toHaveLength(t.expect.embedding.dimensions);
283
+ expect(res.usage.inputTokens).toBeGreaterThanOrEqual(0);
284
+ });
285
+ it("embed result passes validateEmbedResult", async (ctx) => {
286
+ if (!t.expect.embedding)
287
+ return ctx.skip();
288
+ const { req, res, info } = await run();
289
+ expect(info).toBeDefined();
290
+ if (!info)
291
+ return;
292
+ expect(validateEmbedResult(req, info, res)).toBeNull();
293
+ });
294
+ });
263
295
  it("abort", async () => {
264
296
  const ac = new AbortController();
265
297
  const it = streamOf(t, base(), ac.signal)[Symbol.asyncIterator]();
@@ -1,5 +1,10 @@
1
- import { createKernel, KernelConfigSchema } from "@capybara-hq/kernel";
2
- let kernel;
1
+ import { EventEmitter } from "node:events";
2
+ import { KernelConfigSchema, kernelAppPort, startKernelApp } from "@capybara-hq/kernel";
3
+ /**
4
+ * The replica's signal source: the stop message (or the parent going away) raises SIGTERM on it, so
5
+ * the kernel stops through the same shutdown path as `capybara start` — also while it is starting.
6
+ */
7
+ const signals = new EventEmitter();
3
8
  const isPlainObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
4
9
  /** 深合并:普通对象逐键递归,其余(含数组)由 `over` 整体替换。 */
5
10
  function deepMerge(base, over) {
@@ -27,22 +32,25 @@ async function startKernel(c) {
27
32
  log: { level: "error" },
28
33
  };
29
34
  const config = KernelConfigSchema.parse(deepMerge(base, c.overrides));
30
- kernel = await createKernel(config, {
35
+ const app = await startKernelApp(config, {
31
36
  resolveFrom: c.resolveFrom,
32
- ...(c.bootstrapDir !== undefined && { bootstrapDir: c.bootstrapDir }),
37
+ ...(c.bootstrap !== undefined && { bootstrap: c.bootstrap }),
33
38
  ...(c.bootstrapManifest !== undefined && { bootstrapManifest: c.bootstrapManifest }),
34
- });
35
- await kernel.start();
36
- process.send?.({ type: "ready", port: kernel.port });
39
+ }, { signals, exit: (code) => process.exit(code) });
40
+ process.send?.({ type: "ready", port: kernelAppPort(app) });
37
41
  }
38
42
  let exiting = false;
39
- /** 停内核后退出;内核停机卡住时 10 秒后强制退出。 */
43
+ /** Stops the kernel, then exits; a stop stuck for 10 s exits with 1. */
40
44
  function shutdown() {
41
45
  if (exiting)
42
46
  return;
43
47
  exiting = true;
44
48
  setTimeout(() => process.exit(1), 10_000).unref();
45
- (kernel?.stop() ?? Promise.resolve()).finally(() => process.exit(0));
49
+ // No kernel handlers yet (still building) or any more (the start failed): nothing to stop
50
+ if (signals.listenerCount("SIGTERM") === 0)
51
+ process.exit(0);
52
+ else
53
+ signals.emit("SIGTERM", "SIGTERM");
46
54
  }
47
55
  // 父进程(含被 SIGKILL)消失后 IPC 通道断开,副本自行退出,不留孤儿
48
56
  process.on("disconnect", shutdown);
@@ -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
+ });
@@ -3,5 +3,37 @@
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
+ "title": { "en": "Create the fake IM app", "zh": "创建 fake IM 应用" },
12
+ "steps": [
13
+ {
14
+ "en": "Open the fake platform console and create an app from the manifest below.",
15
+ "zh": "打开 fake 平台控制台,用下面的 manifest 创建应用。"
16
+ },
17
+ {
18
+ "mode": "webhook",
19
+ "en": "The platform posts events to `{{webhookUrl}}`.",
20
+ "zh": "平台把事件发到 `{{webhookUrl}}`。"
21
+ }
22
+ ],
23
+ "files": [
24
+ {
25
+ "path": "./guides/app.long-connection.yaml.tmpl",
26
+ "title": { "en": "App manifest", "zh": "应用 manifest" },
27
+ "language": "yaml",
28
+ "mode": "long_connection"
29
+ },
30
+ {
31
+ "path": "./guides/app.webhook.json.tmpl",
32
+ "title": { "en": "App manifest", "zh": "应用 manifest" },
33
+ "language": "json",
34
+ "mode": "webhook"
35
+ }
36
+ ]
37
+ }
38
+ ]
7
39
  }
@@ -0,0 +1,5 @@
1
+ # The fake IM app for "{{connectionName}}" ({{orgName}}), fake-im {{pluginVersion}}.
2
+ app:
3
+ name: "{{connectionName}}"
4
+ long_connection: true
5
+ sign_in_redirect: "{{signInCallbackUrl}}"
@@ -0,0 +1,8 @@
1
+ {
2
+ "app": {
3
+ "name": "{{connectionName}}",
4
+ "long_connection": false,
5
+ "request_url": "{{webhookUrl}}",
6
+ "sign_in_redirect": "{{signInCallbackUrl}}"
7
+ }
8
+ }