channelstack 0.0.0-stage → 0.2.0

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 (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +56 -2
  3. package/bin/channelstack.mjs +31 -0
  4. package/dist/integrations/checks/checks.test.d.ts +1 -0
  5. package/dist/integrations/checks/checks.test.js +31 -0
  6. package/dist/integrations/checks/index.d.ts +102 -0
  7. package/dist/integrations/checks/index.js +1034 -0
  8. package/dist/integrations/matchers-core/index.d.ts +217 -0
  9. package/dist/integrations/matchers-core/index.js +799 -0
  10. package/dist/integrations/matchers-core/matchers.test.d.ts +1 -0
  11. package/dist/integrations/matchers-core/matchers.test.js +407 -0
  12. package/dist/integrations/vitest/global-setup.d.ts +3 -0
  13. package/dist/integrations/vitest/global-setup.js +19 -0
  14. package/dist/integrations/vitest/index.d.ts +82 -0
  15. package/dist/integrations/vitest/index.js +42 -0
  16. package/dist/integrations/vitest/plugin.test.d.ts +1 -0
  17. package/dist/integrations/vitest/plugin.test.js +19 -0
  18. package/dist/integrations/vitest/refused.d.ts +22 -0
  19. package/dist/integrations/vitest/refused.js +49 -0
  20. package/dist/integrations/vitest/setup.d.ts +1 -0
  21. package/dist/integrations/vitest/setup.js +139 -0
  22. package/dist/sdks/typescript/client.d.ts +14 -0
  23. package/dist/sdks/typescript/client.js +11 -0
  24. package/dist/sdks/typescript/generated/channels.d.ts +32 -0
  25. package/dist/sdks/typescript/generated/channels.js +4 -0
  26. package/dist/sdks/typescript/generated/index.d.ts +4178 -0
  27. package/dist/sdks/typescript/generated/index.js +4608 -0
  28. package/dist/sdks/typescript/generated/normalisation.d.ts +18 -0
  29. package/dist/sdks/typescript/generated/normalisation.js +14 -0
  30. package/dist/sdks/typescript/runtime/client.d.ts +56 -0
  31. package/dist/sdks/typescript/runtime/client.js +74 -0
  32. package/dist/sdks/typescript/runtime/credentials.d.ts +7 -0
  33. package/dist/sdks/typescript/runtime/credentials.js +20 -0
  34. package/dist/sdks/typescript/runtime/duration.d.ts +4 -0
  35. package/dist/sdks/typescript/runtime/duration.js +13 -0
  36. package/dist/sdks/typescript/runtime/files.d.ts +47 -0
  37. package/dist/sdks/typescript/runtime/files.js +53 -0
  38. package/dist/sdks/typescript/runtime/launcher.d.ts +27 -0
  39. package/dist/sdks/typescript/runtime/launcher.js +124 -0
  40. package/dist/sdks/typescript/runtime/responder.d.ts +26 -0
  41. package/dist/sdks/typescript/runtime/responder.js +42 -0
  42. package/dist/sdks/typescript/runtime/transport.d.ts +43 -0
  43. package/dist/sdks/typescript/runtime/transport.js +95 -0
  44. package/dist/sdks/typescript/runtime/wait.d.ts +96 -0
  45. package/dist/sdks/typescript/runtime/wait.js +159 -0
  46. package/dist/sdks/typescript/types.d.ts +82 -0
  47. package/dist/sdks/typescript/types.js +1 -0
  48. package/package.json +82 -4
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Text as the server compares it for attribution: each rule replaces every match of its pattern
3
+ * (`$1` is its first group), in order; then, as its flags say, whitespace collapsed and trimmed and case lowered.
4
+ */
5
+ export declare const TEXT_NORMALISATION: {
6
+ readonly rules: readonly [{
7
+ readonly pattern: "<[@#!][^>]*>";
8
+ readonly replacement: " ";
9
+ }, {
10
+ readonly pattern: "<(https?:[^>|]+)(\\|[^>]*)?>";
11
+ readonly replacement: " $1 ";
12
+ }, {
13
+ readonly pattern: "(^|\\s)@[A-Za-z0-9_.-]+";
14
+ readonly replacement: " ";
15
+ }];
16
+ readonly collapseWhitespace: true;
17
+ readonly lowercase: true;
18
+ };
@@ -0,0 +1,14 @@
1
+ // Generated by codegen from spec/ir.json. Do not edit: change the routes and run `pnpm sdk`.
2
+ /**
3
+ * Text as the server compares it for attribution: each rule replaces every match of its pattern
4
+ * (`$1` is its first group), in order; then, as its flags say, whitespace collapsed and trimmed and case lowered.
5
+ */
6
+ export const TEXT_NORMALISATION = {
7
+ rules: [
8
+ { pattern: "<[@#!][^>]*>", replacement: " " },
9
+ { pattern: "<(https?:[^>|]+)(\\|[^>]*)?>", replacement: " $1 " },
10
+ { pattern: "(^|\\s)@[A-Za-z0-9_.-]+", replacement: " " },
11
+ ],
12
+ collapseWhitespace: true,
13
+ lowercase: true,
14
+ };
@@ -0,0 +1,56 @@
1
+ import { type LaunchOptions } from "./launcher.ts";
2
+ import { type ErrorClasses, Transport } from "./transport.ts";
3
+ import type { QuietState } from "./wait.ts";
4
+ /** What a handle needs to call the server: the transport, and the session it lives in. */
5
+ export interface HandleContext {
6
+ readonly transport: Transport;
7
+ readonly session: string | undefined;
8
+ }
9
+ /** The session a handle lives in. Only the root client has none. */
10
+ export declare function sessionOf(context: HandleContext): string;
11
+ /**
12
+ * Every handle that lives in a session answers this: is the agent quiet there? Matchers use it for
13
+ * negative and exact-count checks, whatever handle they are given.
14
+ */
15
+ export declare const QUIET: unique symbol;
16
+ /** Anything a matcher can ask about quiet: any generated handle in a session. */
17
+ export interface InSession {
18
+ [QUIET](): Promise<QuietState>;
19
+ }
20
+ /**
21
+ * Every generated handle answers this with its context: the server and the session it lives in. A
22
+ * failing matcher reads the session's model calls with it, whatever handle it was given.
23
+ */
24
+ export declare const CONTEXT: unique symbol;
25
+ /** A handle a matcher can read its session through. */
26
+ export interface WithContext {
27
+ [CONTEXT](): HandleContext;
28
+ }
29
+ /** Give a value its text form: `String(value)` and `value.toString()` return `text`, and the value keeps its fields. */
30
+ export declare function printsAs<T extends object>(value: T, text: string): T & {
31
+ toString(): string;
32
+ };
33
+ /** Ask the server whether the agent is quiet in the session a handle lives in. */
34
+ export declare function quietOf(context: HandleContext): Promise<QuietState>;
35
+ /**
36
+ * Run a handle's disposer. Disposing only cleans up and never fails a test: when the handle is
37
+ * already gone on the server (closed earlier, or dropped by a reset), there is nothing left to do.
38
+ * An explicit call to the same method still reports that.
39
+ */
40
+ export declare function disposeQuietly(dispose: () => Promise<void>): Promise<void>;
41
+ /** Base of the generated root client: closing it stops the server if this client started it. */
42
+ export declare abstract class ClientBase implements AsyncDisposable {
43
+ #private;
44
+ constructor(stop: () => Promise<void>);
45
+ close(): Promise<void>;
46
+ [Symbol.asyncDispose](): Promise<void>;
47
+ }
48
+ /** What the generated SDK knows about the protocol it was generated from. */
49
+ export interface Protocol {
50
+ basePath: string;
51
+ errors: ErrorClasses;
52
+ /** The server version the SDK was generated for. */
53
+ version: string;
54
+ }
55
+ /** Find or start the server, check that it speaks this SDK's major version, and build the root client. */
56
+ export declare function connectWith<T>(create: (transport: Transport, stop: () => Promise<void>) => T, protocol: Protocol, options: LaunchOptions): Promise<T>;
@@ -0,0 +1,74 @@
1
+ import { launch } from "./launcher.js";
2
+ import { ChannelstackError, segment, Transport } from "./transport.js";
3
+ /** The session a handle lives in. Only the root client has none. */
4
+ export function sessionOf(context) {
5
+ if (context.session === undefined)
6
+ throw new Error("This handle doesn't belong to a session");
7
+ return context.session;
8
+ }
9
+ /**
10
+ * Every handle that lives in a session answers this: is the agent quiet there? Matchers use it for
11
+ * negative and exact-count checks, whatever handle they are given.
12
+ */
13
+ export const QUIET = Symbol.for("channelstack.quiet");
14
+ /**
15
+ * Every generated handle answers this with its context: the server and the session it lives in. A
16
+ * failing matcher reads the session's model calls with it, whatever handle it was given.
17
+ */
18
+ export const CONTEXT = Symbol.for("channelstack.context");
19
+ /** Give a value its text form: `String(value)` and `value.toString()` return `text`, and the value keeps its fields. */
20
+ export function printsAs(value, text) {
21
+ return Object.defineProperty(value, "toString", { value: () => text, enumerable: false });
22
+ }
23
+ /** Ask the server whether the agent is quiet in the session a handle lives in. */
24
+ export async function quietOf(context) {
25
+ return (await context.transport.request("GET", `/sessions/${segment(sessionOf(context))}/quiet`));
26
+ }
27
+ /**
28
+ * Run a handle's disposer. Disposing only cleans up and never fails a test: when the handle is
29
+ * already gone on the server (closed earlier, or dropped by a reset), there is nothing left to do.
30
+ * An explicit call to the same method still reports that.
31
+ */
32
+ export async function disposeQuietly(dispose) {
33
+ try {
34
+ await dispose();
35
+ }
36
+ catch (error) {
37
+ if (!(error instanceof ChannelstackError && error.status === 404))
38
+ throw error;
39
+ }
40
+ }
41
+ /** Base of the generated root client: closing it stops the server if this client started it. */
42
+ export class ClientBase {
43
+ #stop;
44
+ constructor(stop) {
45
+ this.#stop = stop;
46
+ }
47
+ async close() {
48
+ await this.#stop();
49
+ }
50
+ async [Symbol.asyncDispose]() {
51
+ await this.close();
52
+ }
53
+ }
54
+ /** Find or start the server, check that it speaks this SDK's major version, and build the root client. */
55
+ export async function connectWith(create, protocol, options) {
56
+ const server = await launch(options);
57
+ const transport = new Transport({
58
+ url: server.url,
59
+ token: server.token,
60
+ basePath: protocol.basePath,
61
+ errors: protocol.errors,
62
+ });
63
+ try {
64
+ const { version } = (await transport.request("GET", "/status"));
65
+ if (version.split(".")[0] !== protocol.version.split(".")[0]) {
66
+ throw new Error(`The channelstack server is version ${version}, but this SDK was generated for ${protocol.version}`);
67
+ }
68
+ }
69
+ catch (error) {
70
+ await server.stop();
71
+ throw error;
72
+ }
73
+ return create(transport, server.stop);
74
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * A credential from the environment, when a test leaves it out: `CHANNELSTACK_SLACK_USER_{name}_TOKEN`
3
+ * with `{ name: "Ana" }` reads `CHANNELSTACK_SLACK_USER_ANA_TOKEN`. Unset (or empty), it is
4
+ * `undefined`, and the object is fake. So one test runs fake on every PR and live where the
5
+ * variables are set (live-mode.md, section 4).
6
+ */
7
+ export declare function credential(template: string, values: Readonly<Record<string, unknown>>): string | undefined;
@@ -0,0 +1,20 @@
1
+ /** A name as it appears in an environment variable: `Ana` → `ANA`, `ana-smith` → `ANA_SMITH`. */
2
+ function envName(value) {
3
+ return String(value)
4
+ .toUpperCase()
5
+ .replace(/[^A-Z0-9]+/g, "_");
6
+ }
7
+ /**
8
+ * A credential from the environment, when a test leaves it out: `CHANNELSTACK_SLACK_USER_{name}_TOKEN`
9
+ * with `{ name: "Ana" }` reads `CHANNELSTACK_SLACK_USER_ANA_TOKEN`. Unset (or empty), it is
10
+ * `undefined`, and the object is fake. So one test runs fake on every PR and live where the
11
+ * variables are set (live-mode.md, section 4).
12
+ */
13
+ export function credential(template, values) {
14
+ const missing = [...template.matchAll(/\{(\w+)\}/g)].some((match) => values[match[1]] === undefined);
15
+ if (missing)
16
+ return undefined;
17
+ const variable = template.replace(/\{(\w+)\}/g, (_, field) => envName(values[field]));
18
+ const env = globalThis.process?.env ?? {};
19
+ return env[variable] || undefined;
20
+ }
@@ -0,0 +1,4 @@
1
+ /** A duration: milliseconds as a number, or `"250ms"`, `"3s"`, `"1m"`. */
2
+ export type Duration = number | `${number}ms` | `${number}s` | `${number}m`;
3
+ /** A duration in milliseconds. */
4
+ export declare function parseDuration(duration: Duration): number;
@@ -0,0 +1,13 @@
1
+ const UNITS = { ms: 1, s: 1000, m: 60_000 };
2
+ /** A duration in milliseconds. */
3
+ export function parseDuration(duration) {
4
+ if (typeof duration === "number") {
5
+ if (!Number.isFinite(duration) || duration < 0)
6
+ throw new TypeError(`Not a duration: ${duration}`);
7
+ return duration;
8
+ }
9
+ const match = /^(\d+(?:\.\d+)?)(ms|s|m)$/.exec(duration);
10
+ if (!match)
11
+ throw new TypeError(`Not a duration: "${duration}". Use milliseconds, or "250ms", "3s", "1m".`);
12
+ return Number(match[1]) * UNITS[match[2]];
13
+ }
@@ -0,0 +1,47 @@
1
+ /** Files in a test: inline contents, or a path to a fixture file or directory. */
2
+ export type FileInput = {
3
+ name: string;
4
+ content: string | Uint8Array;
5
+ mimeType?: string;
6
+ } | {
7
+ path: string;
8
+ name?: string;
9
+ };
10
+ /** A file as it travels to the server: where it goes, and its bytes in base64. */
11
+ interface WireFile {
12
+ path: string;
13
+ content: string;
14
+ }
15
+ /**
16
+ * Where relative fixture paths start from. A test framework integration sets it to the directory
17
+ * of the test file, so `files: "./fixtures/web"` means what it means in an import. Without it,
18
+ * paths start from the working directory.
19
+ */
20
+ export declare function setFilesRoot(directory: string | undefined): void;
21
+ /** A whole tree of files: a fixture directory, one fixture file, or a list of files. */
22
+ export declare function readTree(input: string | FileInput[]): WireFile[];
23
+ /** Changes to files: a list of files, or a map of path to its new contents, where `null` deletes the file. */
24
+ export declare function readChanges(input: FileInput[] | Record<string, string | null>): Array<{
25
+ path: string;
26
+ content: string | null;
27
+ }>;
28
+ /** One text a test hands over: inline, or the contents of a fixture file (`{ path }`). Structured content passes as it is. */
29
+ export declare function readDocument(input: string | {
30
+ path: string;
31
+ } | unknown[]): string | unknown[];
32
+ /** A placeholder picture, recording or video the server makes: its size, or its length in seconds. */
33
+ interface Placeholder {
34
+ placeholder: {
35
+ width?: number;
36
+ height?: number;
37
+ seconds?: number;
38
+ };
39
+ }
40
+ /** A picture, a recording or a video a test hands over: a fixture file's path, its bytes, or a placeholder. */
41
+ export type MediaSource = string | Uint8Array | Placeholder;
42
+ /** One media source as it travels to the server: a file's bytes in base64 (and its name), or a placeholder as it is. */
43
+ export declare function readMedia(input: MediaSource): {
44
+ content: string;
45
+ name?: string;
46
+ } | Placeholder;
47
+ export {};
@@ -0,0 +1,53 @@
1
+ import { readdirSync, readFileSync, statSync } from "node:fs";
2
+ import { basename, isAbsolute, join, relative, resolve, sep } from "node:path";
3
+ let root;
4
+ /**
5
+ * Where relative fixture paths start from. A test framework integration sets it to the directory
6
+ * of the test file, so `files: "./fixtures/web"` means what it means in an import. Without it,
7
+ * paths start from the working directory.
8
+ */
9
+ export function setFilesRoot(directory) {
10
+ root = directory;
11
+ }
12
+ const located = (path) => (isAbsolute(path) ? path : resolve(root ?? process.cwd(), path));
13
+ const base64 = (content) => Buffer.from(content).toString("base64");
14
+ /** Every file under a directory, by its path inside it, with forward slashes. */
15
+ function walk(directory) {
16
+ return readdirSync(directory, { recursive: true, withFileTypes: true })
17
+ .filter((entry) => entry.isFile())
18
+ .map((entry) => join(entry.parentPath, entry.name))
19
+ .sort()
20
+ .map((file) => ({ path: relative(directory, file).split(sep).join("/"), content: base64(readFileSync(file)) }));
21
+ }
22
+ /** One file input as wire files: inline contents, a file on disk, or everything under a directory on disk. */
23
+ function read(input) {
24
+ if ("content" in input)
25
+ return [{ path: input.name, content: base64(input.content) }];
26
+ const path = located(input.path);
27
+ if (statSync(path).isDirectory()) {
28
+ return walk(path).map((file) => ({ ...file, path: input.name ? `${input.name}/${file.path}` : file.path }));
29
+ }
30
+ return [{ path: input.name ?? input.path.split(/[\\/]/).at(-1) ?? input.path, content: base64(readFileSync(path)) }];
31
+ }
32
+ /** A whole tree of files: a fixture directory, one fixture file, or a list of files. */
33
+ export function readTree(input) {
34
+ return typeof input === "string" ? read({ path: input }) : input.flatMap(read);
35
+ }
36
+ /** Changes to files: a list of files, or a map of path to its new contents, where `null` deletes the file. */
37
+ export function readChanges(input) {
38
+ if (Array.isArray(input))
39
+ return input.flatMap(read);
40
+ return Object.entries(input).map(([path, content]) => ({ path, content: content === null ? null : base64(content) }));
41
+ }
42
+ /** One text a test hands over: inline, or the contents of a fixture file (`{ path }`). Structured content passes as it is. */
43
+ export function readDocument(input) {
44
+ return typeof input === "string" || Array.isArray(input) ? input : readFileSync(located(input.path), "utf8");
45
+ }
46
+ /** One media source as it travels to the server: a file's bytes in base64 (and its name), or a placeholder as it is. */
47
+ export function readMedia(input) {
48
+ if (input instanceof Uint8Array)
49
+ return { content: base64(input) };
50
+ if (typeof input !== "string")
51
+ return input;
52
+ return { content: base64(readFileSync(located(input))), name: basename(input) };
53
+ }
@@ -0,0 +1,27 @@
1
+ export interface LaunchOptions {
2
+ /**
3
+ * `auto` (default): attach if a server is running, otherwise start one for the run.
4
+ * `attach`: fail if none is running. `start`: always start a private one.
5
+ */
6
+ mode?: "auto" | "attach" | "start";
7
+ /** Attach to this server instead of the one in `server.json`. Also `CHANNELSTACK_URL`, with `CHANNELSTACK_TOKEN`. */
8
+ server?: string;
9
+ /** The token for `server`, when the caller has it. It then never needs to be in the environment. */
10
+ token?: string;
11
+ }
12
+ /** A server to talk to. `stop` only stops a server this launcher started. */
13
+ export interface ServerConnection {
14
+ url: string;
15
+ token: string;
16
+ stop(): Promise<void>;
17
+ }
18
+ /** The npm package that carries the server binary for this machine. */
19
+ export declare function serverPackageName(platform?: string, arch?: string): string;
20
+ export declare function serverBinaryName(platform?: string): string;
21
+ /**
22
+ * The server binary: `CHANNELSTACK_SERVER_BIN`, or the one installed with the `channelstack` package
23
+ * (found with `resolve`, Node's module resolution from this file).
24
+ */
25
+ export declare function resolveServerBinary(env?: NodeJS.ProcessEnv, resolve?: (specifier: string) => string): string;
26
+ /** Find or start the server, by `mode`. */
27
+ export declare function launch(options?: LaunchOptions, env?: NodeJS.ProcessEnv): Promise<ServerConnection>;
@@ -0,0 +1,124 @@
1
+ import { spawn } from "node:child_process";
2
+ import { mkdtempSync, readFileSync, rmSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import { homedir, tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { waitFor } from "./wait.js";
7
+ const STATUS_PATH = "/_channelstack/status";
8
+ function withoutTrailingSlash(url) {
9
+ return url ? url.replace(/\/+$/, "") : undefined;
10
+ }
11
+ function readServerFile(path) {
12
+ try {
13
+ const { url, token } = JSON.parse(readFileSync(path, "utf8"));
14
+ return typeof url === "string" && typeof token === "string" ? { url: url.replace(/\/+$/, ""), token } : undefined;
15
+ }
16
+ catch {
17
+ return undefined;
18
+ }
19
+ }
20
+ async function isUp({ url, token }) {
21
+ try {
22
+ const response = await fetch(new URL(STATUS_PATH, url), {
23
+ headers: { authorization: `Bearer ${token}` },
24
+ signal: AbortSignal.timeout(2000),
25
+ });
26
+ return response.ok;
27
+ }
28
+ catch {
29
+ return false;
30
+ }
31
+ }
32
+ /** The running server a client should attach to, if there is one: an explicit URL, or the one in `server.json`. */
33
+ function attachTarget(options, env) {
34
+ // An empty variable (an unset CI secret) counts as not set, and a trailing slash doesn't matter.
35
+ const url = withoutTrailingSlash(options.server || env.CHANNELSTACK_URL);
36
+ const home = env.CHANNELSTACK_HOME || join(homedir(), ".channelstack");
37
+ const file = readServerFile(join(home, "server.json"));
38
+ if (url === undefined)
39
+ return file;
40
+ const token = options.token || env.CHANNELSTACK_TOKEN || (file?.url === url ? file.token : undefined);
41
+ return token === undefined ? undefined : { url, token };
42
+ }
43
+ /** The npm package that carries the server binary for this machine. */
44
+ export function serverPackageName(platform = process.platform, arch = process.arch) {
45
+ return `@channelstack/server-${platform}-${arch}`;
46
+ }
47
+ export function serverBinaryName(platform = process.platform) {
48
+ return platform === "win32" ? "channelstack.exe" : "channelstack";
49
+ }
50
+ /**
51
+ * The server binary: `CHANNELSTACK_SERVER_BIN`, or the one installed with the `channelstack` package
52
+ * (found with `resolve`, Node's module resolution from this file).
53
+ */
54
+ export function resolveServerBinary(env = process.env, resolve = createRequire(import.meta.url).resolve) {
55
+ if (env.CHANNELSTACK_SERVER_BIN)
56
+ return env.CHANNELSTACK_SERVER_BIN;
57
+ const name = serverPackageName();
58
+ try {
59
+ return resolve(`${name}/bin/${serverBinaryName()}`);
60
+ }
61
+ catch {
62
+ throw new Error(`channelstack has no server binary for ${process.platform}-${process.arch}: the optional dependency ${name} isn't installed. ` +
63
+ "Reinstall without --no-optional, or set CHANNELSTACK_SERVER_BIN.");
64
+ }
65
+ }
66
+ /** Start a private server on a free loopback port. Its token goes to a private file, never to the shared `server.json`. */
67
+ async function startServer(env) {
68
+ const directory = mkdtempSync(join(tmpdir(), "channelstack-"));
69
+ const serverFile = join(directory, "server.json");
70
+ const child = spawn(resolveServerBinary(env), ["start", "--no-portless", "--port", "0", "--server-file", serverFile], { env, stdio: ["ignore", "ignore", "inherit"] });
71
+ // Set once the process is gone: how it ended, in words for the error message.
72
+ let ended;
73
+ const exit = new Promise((resolve) => {
74
+ child.once("exit", (code, signal) => {
75
+ ended = `exited with ${code ?? signal}`;
76
+ resolve();
77
+ });
78
+ child.once("error", (error) => {
79
+ ended = `could not be started: ${error.message}`;
80
+ resolve();
81
+ });
82
+ });
83
+ // If this process ends without closing the client, the server must not outlive it.
84
+ const onProcessExit = () => {
85
+ child.kill("SIGTERM");
86
+ rmSync(directory, { recursive: true, force: true });
87
+ };
88
+ process.once("exit", onProcessExit);
89
+ const stop = async () => {
90
+ process.removeListener("exit", onProcessExit);
91
+ if (ended === undefined)
92
+ child.kill("SIGTERM");
93
+ await exit;
94
+ rmSync(directory, { recursive: true, force: true });
95
+ };
96
+ try {
97
+ const server = await waitFor("the channelstack server to start", async () => {
98
+ if (ended !== undefined)
99
+ throw new Error(`The channelstack server ${ended} before it was ready`);
100
+ const file = readServerFile(serverFile);
101
+ return file && (await isUp(file)) ? file : undefined;
102
+ }, { timeout: "15s" });
103
+ return { ...server, stop };
104
+ }
105
+ catch (error) {
106
+ await stop();
107
+ throw error;
108
+ }
109
+ }
110
+ /** Find or start the server, by `mode`. */
111
+ export async function launch(options = {}, env = process.env) {
112
+ const mode = options.mode ?? "auto";
113
+ if (mode !== "start") {
114
+ const target = attachTarget(options, env);
115
+ if (target && (await isUp(target)))
116
+ return { ...target, stop: async () => { } };
117
+ if (mode === "attach") {
118
+ throw new Error(target
119
+ ? `No channelstack server is answering at ${target.url}. Start one with \`npx channelstack\`.`
120
+ : "No running channelstack server found. Start one with `npx channelstack`, or set CHANNELSTACK_URL and CHANNELSTACK_TOKEN.");
121
+ }
122
+ }
123
+ return startServer(env);
124
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Answering model calls from the test (decision 0029): the server holds each call a responder
3
+ * script matches, and this loop reads them (a long poll), runs the test's function and posts what
4
+ * it returns. It runs until the script is undone or its session closes, which end its reads.
5
+ */
6
+ /** What the loop needs of a responder's handle: its long-poll read, and the way to answer. */
7
+ export interface ResponderIo<Request, Turn> {
8
+ held(options: {
9
+ since?: string;
10
+ waitMs?: number;
11
+ }): Promise<{
12
+ held: ReadonlyArray<{
13
+ id: string;
14
+ request: Request;
15
+ }>;
16
+ cursor: string;
17
+ }>;
18
+ answer(id: string, options: {
19
+ turn?: Turn;
20
+ error?: string;
21
+ }): Promise<void>;
22
+ }
23
+ /** A function a test answers model calls with: `Responder<OpenAIRequest, OpenAITurnInput>` for the fake OpenAI. */
24
+ export type Responder<Request = unknown, Turn = unknown> = (request: Request) => Turn | Promise<Turn>;
25
+ /** Start answering a responder script's calls in the background. */
26
+ export declare function respondWith<Request, Turn>(io: ResponderIo<Request, Turn>, respond: Responder<Request, Turn>): void;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Answering model calls from the test (decision 0029): the server holds each call a responder
3
+ * script matches, and this loop reads them (a long poll), runs the test's function and posts what
4
+ * it returns. It runs until the script is undone or its session closes, which end its reads.
5
+ */
6
+ /** How long one read waits on the server for a held call: well inside any HTTP timeout. */
7
+ const LONG_POLL_MS = 20_000;
8
+ /** Start answering a responder script's calls in the background. */
9
+ export function respondWith(io, respond) {
10
+ void (async () => {
11
+ let since;
12
+ for (;;) {
13
+ let page;
14
+ try {
15
+ page = await io.held({ ...(since === undefined ? {} : { since }), waitMs: LONG_POLL_MS });
16
+ }
17
+ catch {
18
+ // The script was undone, or its session closed: nothing more will be held for it.
19
+ return;
20
+ }
21
+ since = page.cursor;
22
+ for (const held of page.held) {
23
+ // Each call is answered on its own, so a slow answer doesn't hold up the next call.
24
+ void (async () => {
25
+ let answer;
26
+ try {
27
+ answer = { turn: await respond(held.request) };
28
+ }
29
+ catch (error) {
30
+ answer = { error: error instanceof Error ? `${error.name}: ${error.message}` : String(error) };
31
+ }
32
+ try {
33
+ await io.answer(held.id, answer);
34
+ }
35
+ catch {
36
+ // The agent hung up, or the call was answered by its timeout: the server has recorded why.
37
+ }
38
+ })();
39
+ }
40
+ }
41
+ })();
42
+ }
@@ -0,0 +1,43 @@
1
+ /** An error from the control API. `code` is the protocol's stable error code. */
2
+ export declare class ChannelstackError extends Error {
3
+ readonly code: string;
4
+ readonly status: number;
5
+ readonly data: Readonly<Record<string, unknown>>;
6
+ constructor(code: string, status: number, message: string, data?: Readonly<Record<string, unknown>>);
7
+ }
8
+ /**
9
+ * Called with every refusal before it is thrown. A test integration uses it to turn a refusal
10
+ * into its framework's own outcome: an operation live mode can't do skips the test, with the reason.
11
+ */
12
+ type RefusalHandler = (error: ChannelstackError, path: string) => void;
13
+ /** Set (or, with `undefined`, clear) what sees every refusal before it is thrown. */
14
+ export declare function onRefusal(handler: RefusalHandler | undefined): void;
15
+ /**
16
+ * Run a read whose refusals go only to its caller, not to the refusal handler: for what is only
17
+ * nice to have, like the open work a failure message adds. A refused read then can't turn a
18
+ * failing test into a skipped one.
19
+ */
20
+ export declare function unreportedRefusals<T>(read: () => Promise<T>): Promise<T>;
21
+ /** Error code → the typed exception the generated SDK declares for it. */
22
+ export type ErrorClasses = Readonly<Record<string, typeof ChannelstackError>>;
23
+ export interface TransportOptions {
24
+ /** The server's base URL, e.g. `https://channelstack.localhost`. */
25
+ url: string;
26
+ token: string;
27
+ /** The control API's path prefix on the server. */
28
+ basePath: string;
29
+ errors: ErrorClasses;
30
+ }
31
+ export interface RequestOptions {
32
+ body?: unknown;
33
+ query?: Readonly<Record<string, string | number | boolean | undefined>>;
34
+ }
35
+ /** One path segment, escaped. */
36
+ export declare function segment(value: string | number): string;
37
+ /** The HTTP client every generated method goes through: bearer token, retries while the server starts, typed errors. */
38
+ export declare class Transport {
39
+ #private;
40
+ constructor(options: TransportOptions);
41
+ request(method: string, path: string, options?: RequestOptions): Promise<unknown>;
42
+ }
43
+ export {};