@nixet/sdk 0.0.0-stage → 0.1.1

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 (67) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/LICENSE +21 -0
  3. package/README.md +870 -2
  4. package/SECURITY.md +30 -0
  5. package/api.md +485 -0
  6. package/dist/cjs/errors.d.ts +37 -0
  7. package/dist/cjs/errors.js +79 -0
  8. package/dist/cjs/index.d.ts +89 -0
  9. package/dist/cjs/index.js +118 -0
  10. package/dist/cjs/resources/agents.d.ts +67 -0
  11. package/dist/cjs/resources/agents.js +74 -0
  12. package/dist/cjs/resources/connections.d.ts +94 -0
  13. package/dist/cjs/resources/connections.js +106 -0
  14. package/dist/cjs/resources/conversations.d.ts +62 -0
  15. package/dist/cjs/resources/conversations.js +86 -0
  16. package/dist/cjs/resources/documents.d.ts +65 -0
  17. package/dist/cjs/resources/documents.js +61 -0
  18. package/dist/cjs/resources/guardrails.d.ts +56 -0
  19. package/dist/cjs/resources/guardrails.js +76 -0
  20. package/dist/cjs/resources/knowledge.d.ts +189 -0
  21. package/dist/cjs/resources/knowledge.js +218 -0
  22. package/dist/cjs/resources/mcp-servers.d.ts +83 -0
  23. package/dist/cjs/resources/mcp-servers.js +107 -0
  24. package/dist/cjs/resources/memory.d.ts +95 -0
  25. package/dist/cjs/resources/memory.js +127 -0
  26. package/dist/cjs/resources/runs.d.ts +78 -0
  27. package/dist/cjs/resources/runs.js +87 -0
  28. package/dist/cjs/resources/secrets.d.ts +60 -0
  29. package/dist/cjs/resources/secrets.js +85 -0
  30. package/dist/cjs/resources/skills.d.ts +57 -0
  31. package/dist/cjs/resources/skills.js +78 -0
  32. package/dist/cjs/resources/tasks.d.ts +91 -0
  33. package/dist/cjs/resources/tasks.js +129 -0
  34. package/dist/cjs/resources/tools.d.ts +42 -0
  35. package/dist/cjs/resources/tools.js +57 -0
  36. package/dist/cjs/resources/users.d.ts +39 -0
  37. package/dist/cjs/resources/users.js +57 -0
  38. package/dist/cjs/resources/versions.d.ts +105 -0
  39. package/dist/cjs/resources/versions.js +78 -0
  40. package/dist/cjs/stream.d.ts +57 -0
  41. package/dist/cjs/stream.js +170 -0
  42. package/dist/cjs/transport.d.ts +45 -0
  43. package/dist/cjs/transport.js +106 -0
  44. package/dist/cjs/types.d.ts +537 -0
  45. package/dist/cjs/types.js +3 -0
  46. package/dist/esm/errors.js +66 -0
  47. package/dist/esm/index.js +103 -0
  48. package/dist/esm/package.json +1 -0
  49. package/dist/esm/resources/agents.js +70 -0
  50. package/dist/esm/resources/connections.js +102 -0
  51. package/dist/esm/resources/conversations.js +82 -0
  52. package/dist/esm/resources/documents.js +57 -0
  53. package/dist/esm/resources/guardrails.js +72 -0
  54. package/dist/esm/resources/knowledge.js +212 -0
  55. package/dist/esm/resources/mcp-servers.js +103 -0
  56. package/dist/esm/resources/memory.js +123 -0
  57. package/dist/esm/resources/runs.js +83 -0
  58. package/dist/esm/resources/secrets.js +81 -0
  59. package/dist/esm/resources/skills.js +74 -0
  60. package/dist/esm/resources/tasks.js +125 -0
  61. package/dist/esm/resources/tools.js +53 -0
  62. package/dist/esm/resources/users.js +53 -0
  63. package/dist/esm/resources/versions.js +74 -0
  64. package/dist/esm/stream.js +166 -0
  65. package/dist/esm/transport.js +102 -0
  66. package/dist/esm/types.js +2 -0
  67. package/package.json +59 -4
@@ -0,0 +1,42 @@
1
+ import type { Transport } from "../transport.js";
2
+ import type { ListParams, McpTool, Page } from "../types.js";
3
+ /**
4
+ * Tools: what your servers offer, and what agents may do with each.
5
+ *
6
+ * ```ts
7
+ * const tools = await nixet.tools.list({ serverName: "github" });
8
+ *
9
+ * await nixet.agents.versions.create(agent.id, {
10
+ * instructions: "Use the GitHub tools to answer questions about the repo.",
11
+ * mcpServers: ["github"],
12
+ * toolPolicies: { "github.delete_repo": "deny" },
13
+ * });
14
+ * ```
15
+ *
16
+ * Read-only: a tool exists because a server advertised it, so there is nothing
17
+ * here to create. Discovery runs when a server is registered and again when its
18
+ * URL moves, which is why a server that could not be reached has none listed.
19
+ *
20
+ * Each tool carries `tags` and a `default_policy`, and the two are not the same
21
+ * kind of thing. A tag is a claim — taken from the server's own annotations
22
+ * where it published any, and from our reading of the name where it did not —
23
+ * and the MCP specification is explicit that a server can claim `readOnlyHint`
24
+ * and delete your files regardless. So tags decide what you are shown and which
25
+ * default applies. What actually happens is the policy on the version, which is
26
+ * yours to set.
27
+ */
28
+ export declare class Tools {
29
+ private readonly transport;
30
+ constructor(transport: Transport);
31
+ /** One tool, by id. */
32
+ retrieve(toolId: string, options?: {
33
+ signal?: AbortSignal;
34
+ }): Promise<McpTool>;
35
+ /** Every tool on record, or those of one server. */
36
+ list(params?: ListParams & {
37
+ serverName?: string;
38
+ name?: string;
39
+ }, options?: {
40
+ signal?: AbortSignal;
41
+ }): Promise<Page<McpTool>>;
42
+ }
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Tools = void 0;
4
+ /**
5
+ * Tools: what your servers offer, and what agents may do with each.
6
+ *
7
+ * ```ts
8
+ * const tools = await nixet.tools.list({ serverName: "github" });
9
+ *
10
+ * await nixet.agents.versions.create(agent.id, {
11
+ * instructions: "Use the GitHub tools to answer questions about the repo.",
12
+ * mcpServers: ["github"],
13
+ * toolPolicies: { "github.delete_repo": "deny" },
14
+ * });
15
+ * ```
16
+ *
17
+ * Read-only: a tool exists because a server advertised it, so there is nothing
18
+ * here to create. Discovery runs when a server is registered and again when its
19
+ * URL moves, which is why a server that could not be reached has none listed.
20
+ *
21
+ * Each tool carries `tags` and a `default_policy`, and the two are not the same
22
+ * kind of thing. A tag is a claim — taken from the server's own annotations
23
+ * where it published any, and from our reading of the name where it did not —
24
+ * and the MCP specification is explicit that a server can claim `readOnlyHint`
25
+ * and delete your files regardless. So tags decide what you are shown and which
26
+ * default applies. What actually happens is the policy on the version, which is
27
+ * yours to set.
28
+ */
29
+ class Tools {
30
+ transport;
31
+ constructor(transport) {
32
+ this.transport = transport;
33
+ }
34
+ /** One tool, by id. */
35
+ retrieve(toolId, options = {}) {
36
+ return this.transport.request({
37
+ method: "GET",
38
+ path: `/mcp/tools/${encodeURIComponent(toolId)}`,
39
+ signal: options.signal,
40
+ });
41
+ }
42
+ /** Every tool on record, or those of one server. */
43
+ list(params = {}, options = {}) {
44
+ return this.transport.requestPage({
45
+ method: "GET",
46
+ path: "/mcp/tools",
47
+ query: {
48
+ $limit: params.limit,
49
+ $offset: params.offset,
50
+ server_name: params.serverName,
51
+ name: params.name,
52
+ },
53
+ signal: options.signal,
54
+ });
55
+ }
56
+ }
57
+ exports.Tools = Tools;
@@ -0,0 +1,39 @@
1
+ import type { Transport } from "../transport.js";
2
+ import type { ListParams, Page, User } from "../types.js";
3
+ export interface CreateUserParams {
4
+ /** Your own identifier for this person. Unique within your workspace. */
5
+ reference: string;
6
+ email?: string;
7
+ name?: string;
8
+ metadata?: Record<string, unknown>;
9
+ }
10
+ /**
11
+ * Users: the people your agent serves.
12
+ *
13
+ * Not the people who sign into the Nixet console — those are members. A user
14
+ * is yours: you supply the reference, and memory is isolated per user so one
15
+ * of your customers can never read another's.
16
+ */
17
+ export declare class Users {
18
+ private readonly transport;
19
+ constructor(transport: Transport);
20
+ /**
21
+ * Register a user.
22
+ *
23
+ * ```ts
24
+ * const user = await nixet.users.create({ reference: "acme_user_8821" });
25
+ * ```
26
+ */
27
+ create(params: CreateUserParams, options?: {
28
+ signal?: AbortSignal;
29
+ }): Promise<User>;
30
+ retrieve(userId: string, options?: {
31
+ signal?: AbortSignal;
32
+ }): Promise<User>;
33
+ /** Filter by `reference` to find a person by your own identifier. */
34
+ list(params?: ListParams & {
35
+ reference?: string;
36
+ }, options?: {
37
+ signal?: AbortSignal;
38
+ }): Promise<Page<User>>;
39
+ }
@@ -0,0 +1,57 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Users = void 0;
4
+ /**
5
+ * Users: the people your agent serves.
6
+ *
7
+ * Not the people who sign into the Nixet console — those are members. A user
8
+ * is yours: you supply the reference, and memory is isolated per user so one
9
+ * of your customers can never read another's.
10
+ */
11
+ class Users {
12
+ transport;
13
+ constructor(transport) {
14
+ this.transport = transport;
15
+ }
16
+ /**
17
+ * Register a user.
18
+ *
19
+ * ```ts
20
+ * const user = await nixet.users.create({ reference: "acme_user_8821" });
21
+ * ```
22
+ */
23
+ create(params, options = {}) {
24
+ return this.transport.request({
25
+ method: "POST",
26
+ path: "/users",
27
+ body: {
28
+ reference: params.reference,
29
+ ...(params.email ? { email: params.email } : {}),
30
+ ...(params.name ? { name: params.name } : {}),
31
+ ...(params.metadata ? { metadata: params.metadata } : {}),
32
+ },
33
+ signal: options.signal,
34
+ });
35
+ }
36
+ retrieve(userId, options = {}) {
37
+ return this.transport.request({
38
+ method: "GET",
39
+ path: `/users/${encodeURIComponent(userId)}`,
40
+ signal: options.signal,
41
+ });
42
+ }
43
+ /** Filter by `reference` to find a person by your own identifier. */
44
+ list(params = {}, options = {}) {
45
+ return this.transport.requestPage({
46
+ method: "GET",
47
+ path: "/users",
48
+ query: {
49
+ $limit: params.limit,
50
+ $offset: params.offset,
51
+ reference: params.reference,
52
+ },
53
+ signal: options.signal,
54
+ });
55
+ }
56
+ }
57
+ exports.Users = Users;
@@ -0,0 +1,105 @@
1
+ import type { Transport } from "../transport.js";
2
+ import type { AgentVersion, ListParams, ModelConfig, Page, RedactionPolicyInput, ToolPolicy, ToolRef } from "../types.js";
3
+ export interface CreateVersionParams {
4
+ /** System prompt that defines the agent's behaviour. */
5
+ instructions: string;
6
+ /** Defaults to the managed provider at its balanced tier. */
7
+ model?: ModelConfig;
8
+ /** Tools the agent may call. Unknown names are rejected at publish. */
9
+ tools?: (ToolRef | string)[];
10
+ /** Skills to use, as `name` or `name@v2`. Pinned at publish. */
11
+ skills?: string[];
12
+ /**
13
+ * Mask personal data in run input and output before dispatch.
14
+ *
15
+ * Defaults to off. Traces are not redacted, and about one item in ten is
16
+ * missed, so this reduces personal data rather than removing it.
17
+ */
18
+ redaction?: RedactionPolicyInput;
19
+ /**
20
+ * Names of registered MCP servers this version may use.
21
+ *
22
+ * Pinned by name rather than by id, so moving a server's URL changes what a
23
+ * published version reaches without republishing it. Cannot be combined with
24
+ * redaction: a masked run would hand tools placeholders instead of values.
25
+ */
26
+ mcpServers?: string[];
27
+ /**
28
+ * What this version may do with a tool, as `server.tool` to policy.
29
+ *
30
+ * Only the exceptions: anything unnamed takes the default its tags imply, so
31
+ * a version does not need rewriting when a server adds a tool. Qualified by
32
+ * server because two servers can both offer `search`.
33
+ *
34
+ * `ask` is refused at publish until approvals exist — nothing can pause a run
35
+ * for a human yet, and a policy that cannot mean what it says should not
36
+ * become runnable.
37
+ */
38
+ toolPolicies?: Record<string, ToolPolicy>;
39
+ /**
40
+ * Knowledge collections this version may search, by name.
41
+ *
42
+ * Named rather than embedded, so a document added after publishing is found
43
+ * without a new version. A collection with no ready sources is not an error:
44
+ * it returns nothing until one finishes ingesting.
45
+ */
46
+ knowledgeCollections?: string[];
47
+ /**
48
+ * Placeholders in `instructions`, as `{{name}}`, that a run supplies.
49
+ *
50
+ * Declared rather than inferred, and checked against the instructions at
51
+ * publish: a placeholder used without being declared, or declared without
52
+ * being used, is refused. Both are mistakes in a version, and a version is
53
+ * immutable, so publish is the only time they are cheap to find.
54
+ *
55
+ * Declaring them is also what keeps a run from reaching a slot this version
56
+ * never named — a run that could inject arbitrary prompt text would make
57
+ * your own backend a prompt-injection surface.
58
+ */
59
+ variables?: string[];
60
+ /**
61
+ * Guardrails to run, by name, per stage.
62
+ *
63
+ * Created with `nixet.guardrails.create` and named here, the way MCP servers
64
+ * and knowledge collections are. Order is the order given: under `run_all`
65
+ * each guard sees the text the previous one produced, so four scrubbing
66
+ * rules compose into one rewritten response rather than the last one
67
+ * winning.
68
+ *
69
+ * `tool_result` is the stage worth not forgetting. A tool answering with
70
+ * structured data reaches the caller without passing through the agent's
71
+ * text, so an `output` guard never sees it.
72
+ */
73
+ guardrails?: {
74
+ input?: string[];
75
+ output?: string[];
76
+ tool_result?: string[];
77
+ /** Defaults to `run_all`. */
78
+ mode?: "run_all" | "fail_fast";
79
+ /** Defaults to `return_message`. */
80
+ on_block?: "return_message" | "error";
81
+ };
82
+ /** Make this the version new runs use. Defaults to true. */
83
+ publish?: boolean;
84
+ }
85
+ /**
86
+ * Immutable snapshots of an agent's configuration.
87
+ *
88
+ * A published version is never edited, which is what lets a past run be
89
+ * explained by the configuration it recorded.
90
+ */
91
+ export declare class Versions {
92
+ private readonly transport;
93
+ constructor(transport: Transport);
94
+ /** Publish a new version. Returns it, numbered in order: v1, v2, v3. */
95
+ create(agentId: string, params: CreateVersionParams, options?: {
96
+ signal?: AbortSignal;
97
+ }): Promise<AgentVersion>;
98
+ list(agentId: string, params?: ListParams, options?: {
99
+ signal?: AbortSignal;
100
+ }): Promise<Page<AgentVersion>>;
101
+ /** Retrieve one version by its label, such as `v1`. */
102
+ retrieve(agentId: string, version: string, options?: {
103
+ signal?: AbortSignal;
104
+ }): Promise<AgentVersion>;
105
+ }
@@ -0,0 +1,78 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Versions = void 0;
4
+ /**
5
+ * Immutable snapshots of an agent's configuration.
6
+ *
7
+ * A published version is never edited, which is what lets a past run be
8
+ * explained by the configuration it recorded.
9
+ */
10
+ class Versions {
11
+ transport;
12
+ constructor(transport) {
13
+ this.transport = transport;
14
+ }
15
+ /** Publish a new version. Returns it, numbered in order: v1, v2, v3. */
16
+ async create(agentId, params, options = {}) {
17
+ return this.transport.request({
18
+ method: "POST",
19
+ path: `/agents/${encodeURIComponent(agentId)}/versions`,
20
+ body: {
21
+ instructions: params.instructions,
22
+ ...(params.model ? { model: params.model } : {}),
23
+ // A bare string is the common case, so accept it as shorthand.
24
+ ...(params.tools ? { tools: params.tools.map(toToolRef) } : {}),
25
+ ...(params.skills ? { skills: params.skills } : {}),
26
+ // Named in the SDK's own casing, so a caller is not asked to know
27
+ // which fields happen to reach the wire untouched.
28
+ ...(params.redaction
29
+ ? {
30
+ redaction: {
31
+ mode: params.redaction.mode,
32
+ ...(params.redaction.reversible === undefined
33
+ ? {}
34
+ : { reversible: params.redaction.reversible }),
35
+ ...(params.redaction.minimumConfidence === undefined
36
+ ? {}
37
+ : { minimum_confidence: params.redaction.minimumConfidence }),
38
+ ...(params.redaction.labels ? { labels: params.redaction.labels } : {}),
39
+ ...(params.redaction.retainFor
40
+ ? { retain_for: params.redaction.retainFor }
41
+ : {}),
42
+ },
43
+ }
44
+ : {}),
45
+ ...(params.mcpServers ? { mcp_servers: params.mcpServers } : {}),
46
+ ...(params.toolPolicies ? { tool_policies: params.toolPolicies } : {}),
47
+ ...(params.knowledgeCollections
48
+ ? { knowledge_collections: params.knowledgeCollections }
49
+ : {}),
50
+ ...(params.variables ? { variables: params.variables } : {}),
51
+ // Sent whole rather than field by field: the server defaults `mode`
52
+ // and `on_block`, and a partial object here would be a second place
53
+ // those defaults are decided.
54
+ ...(params.guardrails ? { guardrails: params.guardrails } : {}),
55
+ ...(params.publish === undefined ? {} : { publish: params.publish }),
56
+ },
57
+ signal: options.signal,
58
+ });
59
+ }
60
+ async list(agentId, params = {}, options = {}) {
61
+ return this.transport.requestPage({
62
+ method: "GET",
63
+ path: `/agents/${encodeURIComponent(agentId)}/versions`,
64
+ query: { $limit: params.limit, $offset: params.offset },
65
+ signal: options.signal,
66
+ });
67
+ }
68
+ /** Retrieve one version by its label, such as `v1`. */
69
+ async retrieve(agentId, version, options = {}) {
70
+ return this.transport.request({
71
+ method: "GET",
72
+ path: `/agents/${encodeURIComponent(agentId)}/versions/${encodeURIComponent(version)}`,
73
+ signal: options.signal,
74
+ });
75
+ }
76
+ }
77
+ exports.Versions = Versions;
78
+ const toToolRef = (tool) => typeof tool === "string" ? { name: tool } : tool;
@@ -0,0 +1,57 @@
1
+ import type { Run, RunEvent } from "./types.js";
2
+ /**
3
+ * A live run.
4
+ *
5
+ * Iterate it for events, await `text()` for the finished output, or attach
6
+ * handlers. All three read the same underlying stream, so choose one style per
7
+ * run rather than mixing them.
8
+ *
9
+ * ```ts
10
+ * for await (const event of stream) {
11
+ * if (event.type === "run.output") process.stdout.write(event.data ?? "");
12
+ * }
13
+ * ```
14
+ */
15
+ export declare class RunStream implements AsyncIterable<RunEvent> {
16
+ /**
17
+ * Resolves once the server acknowledges the run, before it finishes.
18
+ *
19
+ * Awaiting this starts reading the stream, so it is safe to call before
20
+ * iterating: the acceptance frame is consumed here and the events that follow
21
+ * are buffered for whichever reader comes next.
22
+ */
23
+ readonly runId: Promise<string>;
24
+ private readonly response;
25
+ private readonly handlers;
26
+ private resolveRunId;
27
+ private rejectRunId;
28
+ private consumed;
29
+ /** Events read while resolving `runId`, replayed to the first real reader. */
30
+ private buffered;
31
+ private reading;
32
+ private reader;
33
+ private pending;
34
+ private readonly decoder;
35
+ constructor(response: Response);
36
+ /**
37
+ * Subscribe to one event type, or to `"*"` for all of them.
38
+ * Returns an unsubscribe function.
39
+ */
40
+ on(type: RunEvent["type"] | "*", handler: (event: RunEvent) => void): () => void;
41
+ /** The concatenated output, once the run finishes. */
42
+ text(): Promise<string>;
43
+ /** Only the text deltas, for writing straight to a terminal or a socket. */
44
+ chunks(): AsyncGenerator<string>;
45
+ [Symbol.asyncIterator](): AsyncGenerator<RunEvent>;
46
+ /**
47
+ * Read until the acceptance frame arrives, then stop.
48
+ *
49
+ * Runs once, so `runId` is available without a consumer while the events
50
+ * after it stay queued for the first reader.
51
+ */
52
+ private pump;
53
+ /** One event from the shared cursor, or null at end of stream. */
54
+ private next;
55
+ private emit;
56
+ }
57
+ export type { Run };
@@ -0,0 +1,170 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RunStream = void 0;
4
+ /**
5
+ * A live run.
6
+ *
7
+ * Iterate it for events, await `text()` for the finished output, or attach
8
+ * handlers. All three read the same underlying stream, so choose one style per
9
+ * run rather than mixing them.
10
+ *
11
+ * ```ts
12
+ * for await (const event of stream) {
13
+ * if (event.type === "run.output") process.stdout.write(event.data ?? "");
14
+ * }
15
+ * ```
16
+ */
17
+ class RunStream {
18
+ /**
19
+ * Resolves once the server acknowledges the run, before it finishes.
20
+ *
21
+ * Awaiting this starts reading the stream, so it is safe to call before
22
+ * iterating: the acceptance frame is consumed here and the events that follow
23
+ * are buffered for whichever reader comes next.
24
+ */
25
+ runId;
26
+ response;
27
+ handlers = new Map();
28
+ resolveRunId;
29
+ rejectRunId;
30
+ consumed = false;
31
+ /** Events read while resolving `runId`, replayed to the first real reader. */
32
+ buffered = [];
33
+ reading = null;
34
+ reader = null;
35
+ pending = "";
36
+ decoder = new TextDecoder();
37
+ constructor(response) {
38
+ this.response = response;
39
+ this.runId = new Promise((resolve, reject) => {
40
+ this.resolveRunId = resolve;
41
+ this.rejectRunId = reject;
42
+ // The acceptance frame arrives first, so start reading rather than
43
+ // waiting for a consumer that may only appear after this is awaited.
44
+ queueMicrotask(() => this.pump());
45
+ });
46
+ }
47
+ /**
48
+ * Subscribe to one event type, or to `"*"` for all of them.
49
+ * Returns an unsubscribe function.
50
+ */
51
+ on(type, handler) {
52
+ const existing = this.handlers.get(type) ?? new Set();
53
+ existing.add(handler);
54
+ this.handlers.set(type, existing);
55
+ return () => existing.delete(handler);
56
+ }
57
+ /** The concatenated output, once the run finishes. */
58
+ async text() {
59
+ let output = "";
60
+ for await (const event of this) {
61
+ if (event.type === "run.output" && event.data)
62
+ output += event.data;
63
+ }
64
+ return output;
65
+ }
66
+ /** Only the text deltas, for writing straight to a terminal or a socket. */
67
+ async *chunks() {
68
+ for await (const event of this) {
69
+ if (event.type === "run.output" && event.data)
70
+ yield event.data;
71
+ }
72
+ }
73
+ async *[Symbol.asyncIterator]() {
74
+ if (this.consumed) {
75
+ throw new Error("This run stream has already been read.");
76
+ }
77
+ this.consumed = true;
78
+ // Anything the run-id pump already read is replayed first, so no event is
79
+ // lost between acknowledgement and the first consumer.
80
+ await this.reading;
81
+ for (const event of this.buffered)
82
+ yield event;
83
+ this.buffered = [];
84
+ for (;;) {
85
+ const event = await this.next();
86
+ if (!event)
87
+ break;
88
+ this.emit(event);
89
+ yield event;
90
+ }
91
+ }
92
+ /**
93
+ * Read until the acceptance frame arrives, then stop.
94
+ *
95
+ * Runs once, so `runId` is available without a consumer while the events
96
+ * after it stay queued for the first reader.
97
+ */
98
+ pump() {
99
+ if (this.reading)
100
+ return;
101
+ this.reading = (async () => {
102
+ try {
103
+ for (;;) {
104
+ const event = await this.next();
105
+ if (!event)
106
+ break;
107
+ this.buffered.push(event);
108
+ break;
109
+ }
110
+ }
111
+ catch (error) {
112
+ this.rejectRunId(error);
113
+ }
114
+ })();
115
+ }
116
+ /** One event from the shared cursor, or null at end of stream. */
117
+ async next() {
118
+ if (!this.reader) {
119
+ const body = this.response.body;
120
+ if (!body)
121
+ throw new Error("The response carried no stream.");
122
+ this.reader = body.getReader();
123
+ }
124
+ for (;;) {
125
+ // A frame may already be buffered from a previous chunk.
126
+ let boundary = this.pending.indexOf("\n\n");
127
+ while (boundary !== -1) {
128
+ const frame = this.pending.slice(0, boundary).trim();
129
+ this.pending = this.pending.slice(boundary + 2);
130
+ boundary = this.pending.indexOf("\n\n");
131
+ const event = parse(frame);
132
+ if (!event)
133
+ continue;
134
+ if (isAcceptance(event)) {
135
+ this.resolveRunId(event.run_id);
136
+ continue;
137
+ }
138
+ return event;
139
+ }
140
+ const { done, value } = await this.reader.read();
141
+ if (done) {
142
+ // A stream that ends without acknowledging leaves `runId` pending.
143
+ this.rejectRunId(new Error("The run was never acknowledged."));
144
+ return null;
145
+ }
146
+ this.pending += this.decoder.decode(value, { stream: true });
147
+ }
148
+ }
149
+ emit(event) {
150
+ for (const handler of this.handlers.get(event.type) ?? [])
151
+ handler(event);
152
+ for (const handler of this.handlers.get("*") ?? [])
153
+ handler(event);
154
+ }
155
+ }
156
+ exports.RunStream = RunStream;
157
+ function isAcceptance(event) {
158
+ return event.type === "run.accepted";
159
+ }
160
+ function parse(frame) {
161
+ if (!frame.startsWith("data:"))
162
+ return null;
163
+ try {
164
+ return JSON.parse(frame.slice(5).trim());
165
+ }
166
+ catch {
167
+ // A malformed frame is dropped rather than failing an otherwise good run.
168
+ return null;
169
+ }
170
+ }
@@ -0,0 +1,45 @@
1
+ export interface TransportOptions {
2
+ apiKey: string;
3
+ baseURL: string;
4
+ timeout: number;
5
+ maxRetries: number;
6
+ fetch: typeof fetch;
7
+ }
8
+ export interface RequestOptions {
9
+ method: "GET" | "POST" | "PATCH" | "DELETE";
10
+ path: string;
11
+ query?: Record<string, unknown>;
12
+ body?: unknown;
13
+ /**
14
+ * Send the body as multipart rather than JSON.
15
+ *
16
+ * One route takes a file, and bytes do not belong in JSON. When set, the
17
+ * body is handed to fetch untouched and the Content-Type header is omitted:
18
+ * the runtime generates a boundary and sets it, and a header we wrote would
19
+ * be the wrong one.
20
+ */
21
+ form?: boolean;
22
+ signal?: AbortSignal;
23
+ /** Ask for an event stream rather than JSON. */
24
+ stream?: boolean;
25
+ }
26
+ /**
27
+ * HTTP transport.
28
+ *
29
+ * Retries only what is safe to retry: a connection failure, a 429, or a 5xx.
30
+ * A 4xx means the request itself was wrong, so repeating it cannot help.
31
+ */
32
+ export declare class Transport {
33
+ private readonly options;
34
+ constructor(options: TransportOptions);
35
+ request<T>(request: RequestOptions): Promise<T>;
36
+ /** List responses carry a total alongside the rows. */
37
+ requestPage<T>(request: RequestOptions): Promise<{
38
+ data: T[];
39
+ count: number;
40
+ }>;
41
+ stream(request: RequestOptions): Promise<Response>;
42
+ private send;
43
+ private attempt;
44
+ private toError;
45
+ }