@superclerk/sdk 0.1.1 → 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.
@@ -1,4 +1,4 @@
1
- export declare const SDK_VERSION = "0.1.1";
1
+ export declare const SDK_VERSION = "0.2.0";
2
2
  /** The API behavior this SDK was generated for. Every request pins it with the Superclerk-Version header. */
3
3
  export declare const API_VERSION = "2026-11-05";
4
4
  export declare const DEFAULT_BASE_URL = "https://api.superclerk.com";
@@ -1,5 +1,5 @@
1
1
  // Generated by script/generate.ts from the public OpenAPI document. Do not edit.
2
- export const SDK_VERSION = "0.1.1";
2
+ export const SDK_VERSION = "0.2.0";
3
3
  /** The API behavior this SDK was generated for. Every request pins it with the Superclerk-Version header. */
4
4
  export const API_VERSION = "2026-11-05";
5
5
  export const DEFAULT_BASE_URL = "https://api.superclerk.com";
@@ -1,4 +1,4 @@
1
- import type { ConnectLinkFailedEvent, ConnectLinkSucceededEvent, ConnectionRemovedEvent, ConnectionUpdatedEvent, ContactCreatedEvent, ContactMergedEvent, ConversationHandedOffEvent, ConversationMessageReceivedEvent, OpportunityStageChangedEvent, TaskCompletedEvent, ToolRunCompletedEvent, ToolRunFailedEvent } from "./types.js";
1
+ import type { ChatIdleEvent, ChatWaitingEvent, ConnectLinkFailedEvent, ConnectLinkSucceededEvent, ConnectionRemovedEvent, ConnectionUpdatedEvent, ContactCreatedEvent, ContactMergedEvent, ConversationHandedOffEvent, ConversationMessageReceivedEvent, OpportunityStageChangedEvent, TaskCompletedEvent, ToolRunCompletedEvent, ToolRunFailedEvent } from "./types.js";
2
2
  /** Every event a webhook endpoint receives, told apart by its `type`. */
3
- export type WebhookEvent = ConnectLinkSucceededEvent | ConnectLinkFailedEvent | ConnectionUpdatedEvent | ConnectionRemovedEvent | ToolRunCompletedEvent | ToolRunFailedEvent | ConversationMessageReceivedEvent | ConversationHandedOffEvent | ContactCreatedEvent | ContactMergedEvent | OpportunityStageChangedEvent | TaskCompletedEvent;
3
+ export type WebhookEvent = ConnectLinkSucceededEvent | ConnectLinkFailedEvent | ConnectionUpdatedEvent | ConnectionRemovedEvent | ToolRunCompletedEvent | ToolRunFailedEvent | ConversationMessageReceivedEvent | ConversationHandedOffEvent | ContactCreatedEvent | ContactMergedEvent | OpportunityStageChangedEvent | TaskCompletedEvent | ChatWaitingEvent | ChatIdleEvent;
4
4
  export type WebhookEventType = WebhookEvent["type"];
package/lib/chats.d.ts ADDED
@@ -0,0 +1,79 @@
1
+ import type { RequestOptions } from "../core/client.js";
2
+ import { ChatsBase } from "../generated/resources.js";
3
+ import type { Chat, ChatMessage, ChatsMessagesCreateParams } from "../generated/types.js";
4
+ export declare class Chats extends ChatsBase {
5
+ /**
6
+ * Sends a message and waits until the agent stops working on the chat. Answers the chat, idle or waiting on what its
7
+ * pending lists, and the agent's messages since this one, oldest first. Retries of this call, the SDK's own included,
8
+ * reuse one Idempotency-Key, so the message is sent once. Aborting the signal stops the waiting, not the agent.
9
+ */
10
+ send(chatID: string, params: ChatsMessagesCreateParams, options?: RequestOptions): Promise<{
11
+ chat: Chat;
12
+ message: ChatMessage;
13
+ replies: ChatMessage[];
14
+ }>;
15
+ /**
16
+ * The chat's events as they happen: the chat and its transcript first, then each change to a message or its parts. A
17
+ * dropped connection, one silent for 30 s (the API pings every 10 s), and an API that can't answer yet all reconnect
18
+ * after the last event received, so no change is missed. Back on the server running the agent's turn, a part the
19
+ * agent is still writing comes first without an `id`, holding its text so far to replace yours, and its deltas go on
20
+ * from there; elsewhere the part holds the whole text once it ends. A refusal, such as a deleted chat or a revoked key,
21
+ * ends the loop with its error. Stored changes carry the `id` to resume after, which a relay passes on. Break out of
22
+ * the loop or abort the signal to stop.
23
+ */
24
+ stream(chatID: string, params?: {
25
+ after?: number;
26
+ }, options?: RequestOptions): AsyncGenerator<{
27
+ id: number | undefined;
28
+ event: "chat";
29
+ data: Chat;
30
+ } | {
31
+ id: number | undefined;
32
+ event: "messages";
33
+ data: {
34
+ messages: Array<ChatMessage>;
35
+ };
36
+ } | {
37
+ id: number | undefined;
38
+ event: "message";
39
+ data: import("../generated/types.js").ChatMessageInfo;
40
+ } | {
41
+ id: number | undefined;
42
+ event: "part";
43
+ data: import("../generated/types.js").ChatPart;
44
+ } | {
45
+ id: number | undefined;
46
+ event: "delta";
47
+ data: {
48
+ messageID: string;
49
+ partID: string;
50
+ text: string;
51
+ };
52
+ } | {
53
+ id: number | undefined;
54
+ event: "removed";
55
+ data: {
56
+ messageID: string;
57
+ partID: string | null;
58
+ };
59
+ } | {
60
+ id: number | undefined;
61
+ event: "deleted";
62
+ data: {
63
+ chatID: string;
64
+ };
65
+ } | {
66
+ id: number | undefined;
67
+ event: "error";
68
+ data: import("../generated/types.js").ChatError;
69
+ }, void, unknown>;
70
+ }
71
+ type Frame = {
72
+ event?: string;
73
+ data?: string;
74
+ id?: number;
75
+ retry?: number;
76
+ };
77
+ /** A server-sent event stream's frames, comments skipped, as the WHATWG event stream format reads them. */
78
+ export declare function frames(response: Response, stalledAfterMs: number): AsyncGenerator<Frame>;
79
+ export {};
package/lib/chats.js ADDED
@@ -0,0 +1,122 @@
1
+ import { APIConnectionError, APIError } from "../core/errors.js";
2
+ import { settle, sleep } from "../core/timing.js";
3
+ import { ChatsBase } from "../generated/resources.js";
4
+ export class Chats extends ChatsBase {
5
+ /**
6
+ * Sends a message and waits until the agent stops working on the chat. Answers the chat, idle or waiting on what its
7
+ * pending lists, and the agent's messages since this one, oldest first. Retries of this call, the SDK's own included,
8
+ * reuse one Idempotency-Key, so the message is sent once. Aborting the signal stops the waiting, not the agent.
9
+ */
10
+ async send(chatID, params, options = {}) {
11
+ const message = await this.messages.create(chatID, params, options);
12
+ const chat = await settle(this._client, (held) => this.get(chatID, held), options);
13
+ const replies = [];
14
+ // Newest first, and message IDs sort as they were written.
15
+ for await (const item of this.messages.list(chatID, {}, options)) {
16
+ if (item.info.id <= message.info.id)
17
+ break;
18
+ if (item.info.role === "assistant")
19
+ replies.unshift(item);
20
+ }
21
+ return { chat, message, replies };
22
+ }
23
+ /**
24
+ * The chat's events as they happen: the chat and its transcript first, then each change to a message or its parts. A
25
+ * dropped connection, one silent for 30 s (the API pings every 10 s), and an API that can't answer yet all reconnect
26
+ * after the last event received, so no change is missed. Back on the server running the agent's turn, a part the
27
+ * agent is still writing comes first without an `id`, holding its text so far to replace yours, and its deltas go on
28
+ * from there; elsewhere the part holds the whole text once it ends. A refusal, such as a deleted chat or a revoked key,
29
+ * ends the loop with its error. Stored changes carry the `id` to resume after, which a relay passes on. Break out of
30
+ * the loop or abort the signal to stop.
31
+ */
32
+ async *stream(chatID, params = {}, options = {}) {
33
+ let after = params.after;
34
+ let retryMs = 3_000;
35
+ // Attempts in a row that heard nothing from the API.
36
+ let failures = 0;
37
+ for (;;) {
38
+ let response;
39
+ try {
40
+ response = await this.events(chatID, after === undefined ? {} : { after }, options);
41
+ for await (const frame of frames(response, STALLED_AFTER_MS)) {
42
+ failures = 0;
43
+ if (frame.retry !== undefined)
44
+ retryMs = frame.retry;
45
+ if (frame.data === undefined)
46
+ continue;
47
+ if (frame.id !== undefined)
48
+ after = frame.id;
49
+ yield { ...{ event: frame.event, data: JSON.parse(frame.data) }, id: frame.id };
50
+ }
51
+ }
52
+ catch (error) {
53
+ // Once open, any break reconnects; before, only an API that can't answer yet does. An event that isn't JSON is
54
+ // the API's bug, and an abort is yours.
55
+ if (options.signal?.aborted)
56
+ throw options.signal.reason;
57
+ if (error instanceof SyntaxError || (response === undefined && !unavailable(error)))
58
+ throw error;
59
+ }
60
+ // The first retry waits as the API's retry asks. Each failure after it waits up to twice as long, at random, so an
61
+ // API that is down isn't hammered, and clients that failed together don't come back together.
62
+ failures++;
63
+ const wait = failures > 1 ? Math.random() * Math.min(MAX_RETRY_MS, retryMs * 2 ** failures) : retryMs;
64
+ await sleep(wait, options.signal);
65
+ }
66
+ }
67
+ }
68
+ // The API pings an open stream every 10 s, so three missed pings mean its connection died without closing.
69
+ const STALLED_AFTER_MS = 30_000;
70
+ const MAX_RETRY_MS = 30_000;
71
+ /** An API that can't answer yet: unreachable, overloaded, or between deploys. */
72
+ function unavailable(error) {
73
+ return (error instanceof APIConnectionError || (error instanceof APIError && (error.status >= 500 || error.status === 429)));
74
+ }
75
+ /** A server-sent event stream's frames, comments skipped, as the WHATWG event stream format reads them. */
76
+ export async function* frames(response, stalledAfterMs) {
77
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
78
+ let buffer = "";
79
+ try {
80
+ for (;;) {
81
+ const { value, done } = await heard(reader.read(), stalledAfterMs);
82
+ if (done)
83
+ return;
84
+ buffer += value.replaceAll("\r\n", "\n");
85
+ yield* parsed();
86
+ }
87
+ }
88
+ finally {
89
+ // A caller that stops early closes the connection; one that dropped rejects the cancel, with nothing left to close.
90
+ await reader.cancel().catch(() => undefined);
91
+ }
92
+ function* parsed() {
93
+ for (let end = buffer.indexOf("\n\n"); end >= 0; end = buffer.indexOf("\n\n")) {
94
+ const frame = {};
95
+ for (const line of buffer.slice(0, end).split("\n")) {
96
+ const colon = line.indexOf(":");
97
+ if (colon === 0)
98
+ continue;
99
+ const field = colon < 0 ? line : line.slice(0, colon);
100
+ const value = colon < 0 ? "" : line.slice(colon + 1).replace(/^ /, "");
101
+ if (field === "data")
102
+ frame.data = frame.data === undefined ? value : `${frame.data}\n${value}`;
103
+ if (field === "event")
104
+ frame.event = value;
105
+ if (field === "id" && /^\d+$/.test(value))
106
+ frame.id = Number(value);
107
+ if (field === "retry" && /^\d+$/.test(value))
108
+ frame.retry = Number(value);
109
+ }
110
+ buffer = buffer.slice(end + 2);
111
+ yield frame;
112
+ }
113
+ }
114
+ }
115
+ /** A read that hears nothing for `ms` fails, as its connection died without closing. */
116
+ function heard(read, ms) {
117
+ let timer;
118
+ const silent = new Promise((_, reject) => {
119
+ timer = setTimeout(() => reject(new APIConnectionError("timeout", `The chat's stream sent nothing for ${ms} ms`)), ms);
120
+ });
121
+ return Promise.race([read, silent]).finally(() => clearTimeout(timer));
122
+ }
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@superclerk/sdk",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "The official TypeScript SDK for the Superclerk API",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "homepage": "https://docs.superclerk.com/sdk",
8
8
  "repository": {
9
9
  "type": "git",
10
- "url": "git+https://github.com/surgent-dev/capstan.git",
10
+ "url": "git+https://github.com/superclerkhq/superclerk.git",
11
11
  "directory": "packages/sdk"
12
12
  },
13
13
  "keywords": [