@craftedxp/sdk-node 0.10.1 → 0.12.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.
- package/dist/index.d.mts +89 -1
- package/dist/index.d.ts +89 -1
- package/dist/index.js +135 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +135 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -23,6 +23,7 @@ interface HttpRequest {
|
|
|
23
23
|
}
|
|
24
24
|
declare const createHttpClient: (opts: HttpClientOptions) => {
|
|
25
25
|
request: <T>(req: HttpRequest) => Promise<T>;
|
|
26
|
+
stream: <T = unknown>(req: HttpRequest) => AsyncIterable<T>;
|
|
26
27
|
};
|
|
27
28
|
type HttpClient = ReturnType<typeof createHttpClient>;
|
|
28
29
|
|
|
@@ -283,6 +284,8 @@ interface CallRecord {
|
|
|
283
284
|
costBreakdown?: CostBreakdown;
|
|
284
285
|
errorMessage?: string;
|
|
285
286
|
metadata?: Record<string, string>;
|
|
287
|
+
/** Transport channel the call was carried over (`'voice'` = WebRTC/WS audio, `'text'` = text-only). */
|
|
288
|
+
channel?: 'voice' | 'text';
|
|
286
289
|
}
|
|
287
290
|
interface CallListFilters {
|
|
288
291
|
agentId?: string;
|
|
@@ -385,6 +388,18 @@ interface CallTokenMintInput {
|
|
|
385
388
|
* default user-initiated connect. See docs/sdks.md "Agent-initiated calls".
|
|
386
389
|
*/
|
|
387
390
|
initiatedBy?: 'user' | 'agent';
|
|
391
|
+
/**
|
|
392
|
+
* Session channel selector. `voice` (default) routes to WS/WebRTC audio;
|
|
393
|
+
* `text` routes to HTTP+SSE chat via the `chats` resource. Rejected at
|
|
394
|
+
* mint when the agent has `transcribeOnly: true` or when `mode: 'learning'`
|
|
395
|
+
* is supplied.
|
|
396
|
+
*/
|
|
397
|
+
channel?: 'voice' | 'text';
|
|
398
|
+
/**
|
|
399
|
+
* Session purpose. `standard` (default) is a regular call. `learning`
|
|
400
|
+
* (admin-bypass only) flags a self-learning session — see Phase 19.
|
|
401
|
+
*/
|
|
402
|
+
mode?: 'standard' | 'learning';
|
|
388
403
|
}
|
|
389
404
|
interface CallTokenMintResult {
|
|
390
405
|
tokenId: string;
|
|
@@ -406,6 +421,12 @@ interface CallTokenMintResult {
|
|
|
406
421
|
* of falling back to the Phase-1 routes on the API base (local dev).
|
|
407
422
|
*/
|
|
408
423
|
webrtcGatewayBase?: string;
|
|
424
|
+
/**
|
|
425
|
+
* Session channel echoed back from the mint. Useful for the client SDK
|
|
426
|
+
* to dispatch correctly — text-mode tokens go to `chatsFor(token)`,
|
|
427
|
+
* voice-mode tokens go to `voice-js`/`voice-rn`.
|
|
428
|
+
*/
|
|
429
|
+
channel?: 'voice' | 'text';
|
|
409
430
|
}
|
|
410
431
|
interface CallTokenSummary {
|
|
411
432
|
tokenId: string;
|
|
@@ -537,6 +558,37 @@ interface ListUtterancesResponse {
|
|
|
537
558
|
interface RoomEventAck {
|
|
538
559
|
eventId: string;
|
|
539
560
|
}
|
|
561
|
+
/**
|
|
562
|
+
* SSE events emitted by the text-channel chat endpoints. Concatenate
|
|
563
|
+
* `token.text` chunks to build up the agent's reply; render `tool.call`
|
|
564
|
+
* and `tool.result` as "doing-something" UI hints; treat `turn.end` as
|
|
565
|
+
* the signal that the current POST has finished streaming.
|
|
566
|
+
*/
|
|
567
|
+
type ChatEvent = {
|
|
568
|
+
type: 'chat.started';
|
|
569
|
+
chatId: string;
|
|
570
|
+
callId: string;
|
|
571
|
+
} | {
|
|
572
|
+
type: 'token';
|
|
573
|
+
text: string;
|
|
574
|
+
} | {
|
|
575
|
+
type: 'tool.call';
|
|
576
|
+
name: string;
|
|
577
|
+
args: unknown;
|
|
578
|
+
} | {
|
|
579
|
+
type: 'tool.result';
|
|
580
|
+
name: string;
|
|
581
|
+
ok?: boolean;
|
|
582
|
+
[key: string]: unknown;
|
|
583
|
+
} | {
|
|
584
|
+
type: 'turn.end';
|
|
585
|
+
finishReason: 'stop' | 'aborted' | 'length' | 'tool_error';
|
|
586
|
+
committedText?: string;
|
|
587
|
+
} | {
|
|
588
|
+
type: 'error';
|
|
589
|
+
code: string;
|
|
590
|
+
message: string;
|
|
591
|
+
};
|
|
540
592
|
|
|
541
593
|
declare const createMeResource: (http: HttpClient) => {
|
|
542
594
|
get: () => Promise<MeResponse>;
|
|
@@ -682,6 +734,31 @@ declare const createRoomsResource: (http: HttpClient) => {
|
|
|
682
734
|
};
|
|
683
735
|
type RoomsResource = ReturnType<typeof createRoomsResource>;
|
|
684
736
|
|
|
737
|
+
interface StartChatInput {
|
|
738
|
+
agentId: string;
|
|
739
|
+
text?: string;
|
|
740
|
+
}
|
|
741
|
+
interface Chat {
|
|
742
|
+
id: string;
|
|
743
|
+
callId: string;
|
|
744
|
+
greeting: AsyncIterable<ChatEvent>;
|
|
745
|
+
send(text: string): AsyncIterable<ChatEvent>;
|
|
746
|
+
end(): Promise<void>;
|
|
747
|
+
}
|
|
748
|
+
/**
|
|
749
|
+
* Per-token chat resource. Construct via `client.chatsFor(callToken)` —
|
|
750
|
+
* `callToken` is a raw `ct_…` minted with `channel: 'text'`.
|
|
751
|
+
*
|
|
752
|
+
* The async iterables stream SSE events: `chat.started` (start only),
|
|
753
|
+
* then a sequence of `token` / `tool.call` / `tool.result` / `error`,
|
|
754
|
+
* then `turn.end` which closes the stream. The client must NOT keep
|
|
755
|
+
* a connection open between turns — each `send` is a fresh POST.
|
|
756
|
+
*/
|
|
757
|
+
declare const createChatsResource: (http: HttpClient, callToken: string) => {
|
|
758
|
+
start(input: StartChatInput): Promise<Chat>;
|
|
759
|
+
};
|
|
760
|
+
type ChatsResource = ReturnType<typeof createChatsResource>;
|
|
761
|
+
|
|
685
762
|
interface PlatformClientOptions {
|
|
686
763
|
apiKey: string;
|
|
687
764
|
baseUrl?: string;
|
|
@@ -700,7 +777,18 @@ declare class PlatformClient {
|
|
|
700
777
|
readonly webhooks: WebhooksResource;
|
|
701
778
|
readonly orgs: OrgsResource;
|
|
702
779
|
readonly rooms: RoomsResource;
|
|
780
|
+
private readonly _http;
|
|
703
781
|
constructor(options: PlatformClientOptions);
|
|
782
|
+
/**
|
|
783
|
+
* Returns a per-token chat resource bound to the given `ct_…` call token.
|
|
784
|
+
* The token must have been minted with `channel: 'text'`.
|
|
785
|
+
*
|
|
786
|
+
* Note: `chatsFor` is a factory method (not a fixed property) because the
|
|
787
|
+
* underlying resource is scoped to a single call token, whereas this client
|
|
788
|
+
* was constructed with an `sk_` admin key. Each end-user session needs its
|
|
789
|
+
* own `chatsFor(token)` handle.
|
|
790
|
+
*/
|
|
791
|
+
chatsFor(callToken: string): ChatsResource;
|
|
704
792
|
}
|
|
705
793
|
|
|
706
794
|
type ApiErrorCode = 'unauthorized' | 'forbidden' | 'not_found' | 'bad_request' | 'conflict' | 'rate_limited' | 'payment_required' | 'internal_error' | 'unknown';
|
|
@@ -723,4 +811,4 @@ declare class PlatformError extends Error {
|
|
|
723
811
|
|
|
724
812
|
declare const verifyWebhookSignature: (rawBody: Buffer | string, signatureHeader: string, secret: string) => boolean;
|
|
725
813
|
|
|
726
|
-
export { type Agent, type AgentCreateInput, type AgentEndpointing, type AgentHttpTool, type AgentModel, type AgentRecording, type AgentTool, type AgentTranscriber, type AgentUpdateInput, type AgentVoice, type AgentWebhooksResource, type AgentsResource, type ApiErrorCode, type CallListFilters, type CallRecord, type CallRecordingUrlResponse, type CallStatus, type CallSummary, type CallTokenMintInput, type CallTokenMintResult, type CallTokenSummary, type CallTokensResource, type CallsResource, type CatalogAgent, type CatalogListInput, type CostBreakdown, type CreateRoomInput, type CreateRoomResponse, type CreditsResource, type EndReason, type EndpointingMode, type GuestRole, type KnowledgeBase, type KnowledgeBaseFile, type KnowledgeBasesResource, type LedgerEntry, type ListRoomsResponse, type ListUtterancesResponse, type LlmProvider, type MeResource, type MeResponse, type OrgsResource, PlatformClient, type PlatformClientOptions, PlatformError, type PlatformEventName, type RecordingMeta, type RoomDoc, type RoomEndReason, type RoomEventAck, type RoomListFilters, type RoomMetricsWire, type RoomStatus, type RoomTranscriptOptions, type RoomsResource, type SttProvider, type TranscriptTurn, type TtsProvider, type UtteranceWire, type WebhookConfig, type WebhookCreateInput, type WebhookDelivery, type WebhookUpdateInput, type WebhooksResource, type WorkerStatus, verifyWebhookSignature };
|
|
814
|
+
export { type Agent, type AgentCreateInput, type AgentEndpointing, type AgentHttpTool, type AgentModel, type AgentRecording, type AgentTool, type AgentTranscriber, type AgentUpdateInput, type AgentVoice, type AgentWebhooksResource, type AgentsResource, type ApiErrorCode, type CallListFilters, type CallRecord, type CallRecordingUrlResponse, type CallStatus, type CallSummary, type CallTokenMintInput, type CallTokenMintResult, type CallTokenSummary, type CallTokensResource, type CallsResource, type CatalogAgent, type CatalogListInput, type Chat, type ChatEvent, type ChatsResource, type CostBreakdown, type CreateRoomInput, type CreateRoomResponse, type CreditsResource, type EndReason, type EndpointingMode, type GuestRole, type KnowledgeBase, type KnowledgeBaseFile, type KnowledgeBasesResource, type LedgerEntry, type ListRoomsResponse, type ListUtterancesResponse, type LlmProvider, type MeResource, type MeResponse, type OrgsResource, PlatformClient, type PlatformClientOptions, PlatformError, type PlatformEventName, type RecordingMeta, type RoomDoc, type RoomEndReason, type RoomEventAck, type RoomListFilters, type RoomMetricsWire, type RoomStatus, type RoomTranscriptOptions, type RoomsResource, type StartChatInput, type SttProvider, type TranscriptTurn, type TtsProvider, type UtteranceWire, type WebhookConfig, type WebhookCreateInput, type WebhookDelivery, type WebhookUpdateInput, type WebhooksResource, type WorkerStatus, verifyWebhookSignature };
|
package/dist/index.d.ts
CHANGED
|
@@ -23,6 +23,7 @@ interface HttpRequest {
|
|
|
23
23
|
}
|
|
24
24
|
declare const createHttpClient: (opts: HttpClientOptions) => {
|
|
25
25
|
request: <T>(req: HttpRequest) => Promise<T>;
|
|
26
|
+
stream: <T = unknown>(req: HttpRequest) => AsyncIterable<T>;
|
|
26
27
|
};
|
|
27
28
|
type HttpClient = ReturnType<typeof createHttpClient>;
|
|
28
29
|
|
|
@@ -283,6 +284,8 @@ interface CallRecord {
|
|
|
283
284
|
costBreakdown?: CostBreakdown;
|
|
284
285
|
errorMessage?: string;
|
|
285
286
|
metadata?: Record<string, string>;
|
|
287
|
+
/** Transport channel the call was carried over (`'voice'` = WebRTC/WS audio, `'text'` = text-only). */
|
|
288
|
+
channel?: 'voice' | 'text';
|
|
286
289
|
}
|
|
287
290
|
interface CallListFilters {
|
|
288
291
|
agentId?: string;
|
|
@@ -385,6 +388,18 @@ interface CallTokenMintInput {
|
|
|
385
388
|
* default user-initiated connect. See docs/sdks.md "Agent-initiated calls".
|
|
386
389
|
*/
|
|
387
390
|
initiatedBy?: 'user' | 'agent';
|
|
391
|
+
/**
|
|
392
|
+
* Session channel selector. `voice` (default) routes to WS/WebRTC audio;
|
|
393
|
+
* `text` routes to HTTP+SSE chat via the `chats` resource. Rejected at
|
|
394
|
+
* mint when the agent has `transcribeOnly: true` or when `mode: 'learning'`
|
|
395
|
+
* is supplied.
|
|
396
|
+
*/
|
|
397
|
+
channel?: 'voice' | 'text';
|
|
398
|
+
/**
|
|
399
|
+
* Session purpose. `standard` (default) is a regular call. `learning`
|
|
400
|
+
* (admin-bypass only) flags a self-learning session — see Phase 19.
|
|
401
|
+
*/
|
|
402
|
+
mode?: 'standard' | 'learning';
|
|
388
403
|
}
|
|
389
404
|
interface CallTokenMintResult {
|
|
390
405
|
tokenId: string;
|
|
@@ -406,6 +421,12 @@ interface CallTokenMintResult {
|
|
|
406
421
|
* of falling back to the Phase-1 routes on the API base (local dev).
|
|
407
422
|
*/
|
|
408
423
|
webrtcGatewayBase?: string;
|
|
424
|
+
/**
|
|
425
|
+
* Session channel echoed back from the mint. Useful for the client SDK
|
|
426
|
+
* to dispatch correctly — text-mode tokens go to `chatsFor(token)`,
|
|
427
|
+
* voice-mode tokens go to `voice-js`/`voice-rn`.
|
|
428
|
+
*/
|
|
429
|
+
channel?: 'voice' | 'text';
|
|
409
430
|
}
|
|
410
431
|
interface CallTokenSummary {
|
|
411
432
|
tokenId: string;
|
|
@@ -537,6 +558,37 @@ interface ListUtterancesResponse {
|
|
|
537
558
|
interface RoomEventAck {
|
|
538
559
|
eventId: string;
|
|
539
560
|
}
|
|
561
|
+
/**
|
|
562
|
+
* SSE events emitted by the text-channel chat endpoints. Concatenate
|
|
563
|
+
* `token.text` chunks to build up the agent's reply; render `tool.call`
|
|
564
|
+
* and `tool.result` as "doing-something" UI hints; treat `turn.end` as
|
|
565
|
+
* the signal that the current POST has finished streaming.
|
|
566
|
+
*/
|
|
567
|
+
type ChatEvent = {
|
|
568
|
+
type: 'chat.started';
|
|
569
|
+
chatId: string;
|
|
570
|
+
callId: string;
|
|
571
|
+
} | {
|
|
572
|
+
type: 'token';
|
|
573
|
+
text: string;
|
|
574
|
+
} | {
|
|
575
|
+
type: 'tool.call';
|
|
576
|
+
name: string;
|
|
577
|
+
args: unknown;
|
|
578
|
+
} | {
|
|
579
|
+
type: 'tool.result';
|
|
580
|
+
name: string;
|
|
581
|
+
ok?: boolean;
|
|
582
|
+
[key: string]: unknown;
|
|
583
|
+
} | {
|
|
584
|
+
type: 'turn.end';
|
|
585
|
+
finishReason: 'stop' | 'aborted' | 'length' | 'tool_error';
|
|
586
|
+
committedText?: string;
|
|
587
|
+
} | {
|
|
588
|
+
type: 'error';
|
|
589
|
+
code: string;
|
|
590
|
+
message: string;
|
|
591
|
+
};
|
|
540
592
|
|
|
541
593
|
declare const createMeResource: (http: HttpClient) => {
|
|
542
594
|
get: () => Promise<MeResponse>;
|
|
@@ -682,6 +734,31 @@ declare const createRoomsResource: (http: HttpClient) => {
|
|
|
682
734
|
};
|
|
683
735
|
type RoomsResource = ReturnType<typeof createRoomsResource>;
|
|
684
736
|
|
|
737
|
+
interface StartChatInput {
|
|
738
|
+
agentId: string;
|
|
739
|
+
text?: string;
|
|
740
|
+
}
|
|
741
|
+
interface Chat {
|
|
742
|
+
id: string;
|
|
743
|
+
callId: string;
|
|
744
|
+
greeting: AsyncIterable<ChatEvent>;
|
|
745
|
+
send(text: string): AsyncIterable<ChatEvent>;
|
|
746
|
+
end(): Promise<void>;
|
|
747
|
+
}
|
|
748
|
+
/**
|
|
749
|
+
* Per-token chat resource. Construct via `client.chatsFor(callToken)` —
|
|
750
|
+
* `callToken` is a raw `ct_…` minted with `channel: 'text'`.
|
|
751
|
+
*
|
|
752
|
+
* The async iterables stream SSE events: `chat.started` (start only),
|
|
753
|
+
* then a sequence of `token` / `tool.call` / `tool.result` / `error`,
|
|
754
|
+
* then `turn.end` which closes the stream. The client must NOT keep
|
|
755
|
+
* a connection open between turns — each `send` is a fresh POST.
|
|
756
|
+
*/
|
|
757
|
+
declare const createChatsResource: (http: HttpClient, callToken: string) => {
|
|
758
|
+
start(input: StartChatInput): Promise<Chat>;
|
|
759
|
+
};
|
|
760
|
+
type ChatsResource = ReturnType<typeof createChatsResource>;
|
|
761
|
+
|
|
685
762
|
interface PlatformClientOptions {
|
|
686
763
|
apiKey: string;
|
|
687
764
|
baseUrl?: string;
|
|
@@ -700,7 +777,18 @@ declare class PlatformClient {
|
|
|
700
777
|
readonly webhooks: WebhooksResource;
|
|
701
778
|
readonly orgs: OrgsResource;
|
|
702
779
|
readonly rooms: RoomsResource;
|
|
780
|
+
private readonly _http;
|
|
703
781
|
constructor(options: PlatformClientOptions);
|
|
782
|
+
/**
|
|
783
|
+
* Returns a per-token chat resource bound to the given `ct_…` call token.
|
|
784
|
+
* The token must have been minted with `channel: 'text'`.
|
|
785
|
+
*
|
|
786
|
+
* Note: `chatsFor` is a factory method (not a fixed property) because the
|
|
787
|
+
* underlying resource is scoped to a single call token, whereas this client
|
|
788
|
+
* was constructed with an `sk_` admin key. Each end-user session needs its
|
|
789
|
+
* own `chatsFor(token)` handle.
|
|
790
|
+
*/
|
|
791
|
+
chatsFor(callToken: string): ChatsResource;
|
|
704
792
|
}
|
|
705
793
|
|
|
706
794
|
type ApiErrorCode = 'unauthorized' | 'forbidden' | 'not_found' | 'bad_request' | 'conflict' | 'rate_limited' | 'payment_required' | 'internal_error' | 'unknown';
|
|
@@ -723,4 +811,4 @@ declare class PlatformError extends Error {
|
|
|
723
811
|
|
|
724
812
|
declare const verifyWebhookSignature: (rawBody: Buffer | string, signatureHeader: string, secret: string) => boolean;
|
|
725
813
|
|
|
726
|
-
export { type Agent, type AgentCreateInput, type AgentEndpointing, type AgentHttpTool, type AgentModel, type AgentRecording, type AgentTool, type AgentTranscriber, type AgentUpdateInput, type AgentVoice, type AgentWebhooksResource, type AgentsResource, type ApiErrorCode, type CallListFilters, type CallRecord, type CallRecordingUrlResponse, type CallStatus, type CallSummary, type CallTokenMintInput, type CallTokenMintResult, type CallTokenSummary, type CallTokensResource, type CallsResource, type CatalogAgent, type CatalogListInput, type CostBreakdown, type CreateRoomInput, type CreateRoomResponse, type CreditsResource, type EndReason, type EndpointingMode, type GuestRole, type KnowledgeBase, type KnowledgeBaseFile, type KnowledgeBasesResource, type LedgerEntry, type ListRoomsResponse, type ListUtterancesResponse, type LlmProvider, type MeResource, type MeResponse, type OrgsResource, PlatformClient, type PlatformClientOptions, PlatformError, type PlatformEventName, type RecordingMeta, type RoomDoc, type RoomEndReason, type RoomEventAck, type RoomListFilters, type RoomMetricsWire, type RoomStatus, type RoomTranscriptOptions, type RoomsResource, type SttProvider, type TranscriptTurn, type TtsProvider, type UtteranceWire, type WebhookConfig, type WebhookCreateInput, type WebhookDelivery, type WebhookUpdateInput, type WebhooksResource, type WorkerStatus, verifyWebhookSignature };
|
|
814
|
+
export { type Agent, type AgentCreateInput, type AgentEndpointing, type AgentHttpTool, type AgentModel, type AgentRecording, type AgentTool, type AgentTranscriber, type AgentUpdateInput, type AgentVoice, type AgentWebhooksResource, type AgentsResource, type ApiErrorCode, type CallListFilters, type CallRecord, type CallRecordingUrlResponse, type CallStatus, type CallSummary, type CallTokenMintInput, type CallTokenMintResult, type CallTokenSummary, type CallTokensResource, type CallsResource, type CatalogAgent, type CatalogListInput, type Chat, type ChatEvent, type ChatsResource, type CostBreakdown, type CreateRoomInput, type CreateRoomResponse, type CreditsResource, type EndReason, type EndpointingMode, type GuestRole, type KnowledgeBase, type KnowledgeBaseFile, type KnowledgeBasesResource, type LedgerEntry, type ListRoomsResponse, type ListUtterancesResponse, type LlmProvider, type MeResource, type MeResponse, type OrgsResource, PlatformClient, type PlatformClientOptions, PlatformError, type PlatformEventName, type RecordingMeta, type RoomDoc, type RoomEndReason, type RoomEventAck, type RoomListFilters, type RoomMetricsWire, type RoomStatus, type RoomTranscriptOptions, type RoomsResource, type StartChatInput, type SttProvider, type TranscriptTurn, type TtsProvider, type UtteranceWire, type WebhookConfig, type WebhookCreateInput, type WebhookDelivery, type WebhookUpdateInput, type WebhooksResource, type WorkerStatus, verifyWebhookSignature };
|
package/dist/index.js
CHANGED
|
@@ -179,7 +179,82 @@ var createHttpClient = (opts) => {
|
|
|
179
179
|
}
|
|
180
180
|
throw lastErr instanceof Error ? lastErr : new Error("request exhausted retries");
|
|
181
181
|
};
|
|
182
|
-
|
|
182
|
+
async function* stream(req) {
|
|
183
|
+
const url = buildUrl(opts.baseUrl, req.path, req.query);
|
|
184
|
+
const headers = {
|
|
185
|
+
Authorization: `Bearer ${opts.apiKey}`,
|
|
186
|
+
"Content-Type": "application/json",
|
|
187
|
+
Accept: "text/event-stream",
|
|
188
|
+
...req.headers ?? {}
|
|
189
|
+
};
|
|
190
|
+
const started = Date.now();
|
|
191
|
+
let res;
|
|
192
|
+
try {
|
|
193
|
+
res = await fetchImpl(url, {
|
|
194
|
+
method: req.method,
|
|
195
|
+
headers,
|
|
196
|
+
body: req.body !== void 0 ? JSON.stringify(req.body) : void 0
|
|
197
|
+
});
|
|
198
|
+
} catch (err) {
|
|
199
|
+
const msg = err instanceof Error ? err.message : "network error";
|
|
200
|
+
throw new PlatformError({
|
|
201
|
+
code: "unknown",
|
|
202
|
+
message: `Network error: ${msg}`,
|
|
203
|
+
status: 0
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
opts.onRequest?.({
|
|
207
|
+
method: req.method,
|
|
208
|
+
url,
|
|
209
|
+
status: res.status,
|
|
210
|
+
durationMs: Date.now() - started,
|
|
211
|
+
attempt: 1
|
|
212
|
+
});
|
|
213
|
+
if (!res.ok || !res.body) {
|
|
214
|
+
const text = await res.text().catch(() => "");
|
|
215
|
+
let parsed = void 0;
|
|
216
|
+
try {
|
|
217
|
+
parsed = text ? JSON.parse(text) : void 0;
|
|
218
|
+
} catch {
|
|
219
|
+
}
|
|
220
|
+
const errObj = parsed?.error;
|
|
221
|
+
throw new PlatformError({
|
|
222
|
+
code: errObj?.code ?? "unknown",
|
|
223
|
+
message: errObj?.message ?? res.statusText ?? `HTTP ${res.status}`,
|
|
224
|
+
status: res.status,
|
|
225
|
+
field: errObj?.field,
|
|
226
|
+
docsUrl: errObj?.docs_url,
|
|
227
|
+
body: parsed ?? text
|
|
228
|
+
});
|
|
229
|
+
}
|
|
230
|
+
const reader = res.body.getReader();
|
|
231
|
+
const decoder = new TextDecoder();
|
|
232
|
+
let buf = "";
|
|
233
|
+
while (true) {
|
|
234
|
+
const { value, done } = await reader.read();
|
|
235
|
+
if (done) return;
|
|
236
|
+
buf += decoder.decode(value, { stream: true });
|
|
237
|
+
let idx;
|
|
238
|
+
while ((idx = buf.indexOf("\n\n")) >= 0) {
|
|
239
|
+
const block = buf.slice(0, idx);
|
|
240
|
+
buf = buf.slice(idx + 2);
|
|
241
|
+
let event = "message";
|
|
242
|
+
let data = "";
|
|
243
|
+
for (const line of block.split("\n")) {
|
|
244
|
+
if (line.startsWith(":")) continue;
|
|
245
|
+
if (line.startsWith("event:")) event = line.slice(6).trim();
|
|
246
|
+
else if (line.startsWith("data:")) data += line.slice(5).trim();
|
|
247
|
+
}
|
|
248
|
+
if (!data) continue;
|
|
249
|
+
try {
|
|
250
|
+
const parsed = JSON.parse(data);
|
|
251
|
+
yield { type: event, ...parsed };
|
|
252
|
+
} catch {
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return { request, stream };
|
|
183
258
|
};
|
|
184
259
|
|
|
185
260
|
// src/resources/me.ts
|
|
@@ -533,6 +608,51 @@ var createRoomsResource = (http) => ({
|
|
|
533
608
|
})
|
|
534
609
|
});
|
|
535
610
|
|
|
611
|
+
// src/resources/chats.ts
|
|
612
|
+
var createChatsResource = (http, callToken) => ({
|
|
613
|
+
async start(input) {
|
|
614
|
+
const tokenQs = `?token=${encodeURIComponent(callToken)}`;
|
|
615
|
+
const streamIterable = http.stream({
|
|
616
|
+
method: "POST",
|
|
617
|
+
path: `/v1/agents/${input.agentId}/chat${tokenQs}`,
|
|
618
|
+
body: input.text ? { text: input.text } : {}
|
|
619
|
+
});
|
|
620
|
+
let chatId = "";
|
|
621
|
+
let callId = "";
|
|
622
|
+
const buffered = [];
|
|
623
|
+
const iter = streamIterable[Symbol.asyncIterator]();
|
|
624
|
+
while (true) {
|
|
625
|
+
const { value, done } = await iter.next();
|
|
626
|
+
if (done) break;
|
|
627
|
+
if (value.type === "chat.started") {
|
|
628
|
+
chatId = value.chatId;
|
|
629
|
+
callId = value.callId;
|
|
630
|
+
break;
|
|
631
|
+
}
|
|
632
|
+
buffered.push(value);
|
|
633
|
+
}
|
|
634
|
+
return {
|
|
635
|
+
id: chatId,
|
|
636
|
+
callId,
|
|
637
|
+
greeting: replayThen(buffered, { [Symbol.asyncIterator]: () => iter }),
|
|
638
|
+
send(text) {
|
|
639
|
+
return http.stream({
|
|
640
|
+
method: "POST",
|
|
641
|
+
path: `/v1/chats/${chatId}/messages${tokenQs}`,
|
|
642
|
+
body: { text }
|
|
643
|
+
});
|
|
644
|
+
},
|
|
645
|
+
async end() {
|
|
646
|
+
await http.request({ method: "DELETE", path: `/v1/calls/${callId}` });
|
|
647
|
+
}
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
});
|
|
651
|
+
async function* replayThen(buffered, rest) {
|
|
652
|
+
for (const x of buffered) yield x;
|
|
653
|
+
for await (const x of rest) yield x;
|
|
654
|
+
}
|
|
655
|
+
|
|
536
656
|
// src/PlatformClient.ts
|
|
537
657
|
var PlatformClient = class {
|
|
538
658
|
me;
|
|
@@ -544,6 +664,7 @@ var PlatformClient = class {
|
|
|
544
664
|
webhooks;
|
|
545
665
|
orgs;
|
|
546
666
|
rooms;
|
|
667
|
+
_http;
|
|
547
668
|
constructor(options) {
|
|
548
669
|
if (!options.apiKey) {
|
|
549
670
|
throw new Error("PlatformClient: `apiKey` is required");
|
|
@@ -565,6 +686,19 @@ var PlatformClient = class {
|
|
|
565
686
|
this.webhooks = createWebhooksResource(http);
|
|
566
687
|
this.orgs = createOrgsResource(http);
|
|
567
688
|
this.rooms = createRoomsResource(http);
|
|
689
|
+
this._http = http;
|
|
690
|
+
}
|
|
691
|
+
/**
|
|
692
|
+
* Returns a per-token chat resource bound to the given `ct_…` call token.
|
|
693
|
+
* The token must have been minted with `channel: 'text'`.
|
|
694
|
+
*
|
|
695
|
+
* Note: `chatsFor` is a factory method (not a fixed property) because the
|
|
696
|
+
* underlying resource is scoped to a single call token, whereas this client
|
|
697
|
+
* was constructed with an `sk_` admin key. Each end-user session needs its
|
|
698
|
+
* own `chatsFor(token)` handle.
|
|
699
|
+
*/
|
|
700
|
+
chatsFor(callToken) {
|
|
701
|
+
return createChatsResource(this._http, callToken);
|
|
568
702
|
}
|
|
569
703
|
};
|
|
570
704
|
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/http.ts","../src/resources/me.ts","../src/resources/agentWebhooks.ts","../src/resources/agents.ts","../src/resources/calls.ts","../src/resources/knowledgeBases.ts","../src/resources/credits.ts","../src/resources/callTokens.ts","../src/resources/webhooks.ts","../src/resources/orgs.ts","../src/resources/rooms.ts","../src/PlatformClient.ts","../src/verify.ts"],"sourcesContent":["// Public API of @craftedxp/sdk-node.\n\nexport { PlatformClient } from './PlatformClient'\nexport type { PlatformClientOptions } from './PlatformClient'\n\n// Error class for `instanceof` checks in consumer code.\nexport { PlatformError } from './errors'\nexport type { ApiErrorCode } from './errors'\n\n// Webhook signature verification helper — standalone so frameworks\n// (Express, Koa, Next.js route handlers) can use it without instantiating\n// a PlatformClient.\nexport { verifyWebhookSignature } from './verify'\n\n// Re-export DTO types. Consumers often type their own storage models\n// against these — re-exporting avoids `import type` gymnastics.\nexport type * from './types'\n\n// Advanced: expose the resource types for consumers subclassing / wrapping\n// the client. 99% of users don't need these.\nexport type { MeResource } from './resources/me'\nexport type { AgentsResource } from './resources/agents'\nexport type { AgentWebhooksResource } from './resources/agentWebhooks'\nexport type { CallsResource } from './resources/calls'\nexport type { KnowledgeBasesResource } from './resources/knowledgeBases'\nexport type { CreditsResource } from './resources/credits'\nexport type { CallTokensResource } from './resources/callTokens'\nexport type { WebhooksResource } from './resources/webhooks'\nexport type { OrgsResource } from './resources/orgs'\nexport type { RoomsResource } from './resources/rooms'\n","// Typed error class mirroring the server's ErrorV1 shape:\n// { error: { code, message, field?, docs_url? } }\n//\n// Consumers do `err instanceof PlatformError` to branch on code without\n// parsing string messages. `status` carries the HTTP code for the 1% of\n// cases where the code field isn't enough (e.g. rate-limit → retry-after\n// header correlation).\n\nexport type ApiErrorCode =\n | 'unauthorized'\n | 'forbidden'\n | 'not_found'\n | 'bad_request'\n | 'conflict'\n | 'rate_limited'\n | 'payment_required'\n | 'internal_error'\n | 'unknown'\n\nexport class PlatformError extends Error {\n readonly code: ApiErrorCode\n readonly status: number\n readonly field?: string\n readonly docsUrl?: string\n // The raw response body for debugging. Intentionally optional — we clear\n // it on `error.toJSON()` so logging libraries don't dump the whole\n // server response into production logs.\n readonly body?: unknown\n\n constructor(params: {\n code: ApiErrorCode\n message: string\n status: number\n field?: string\n docsUrl?: string\n body?: unknown\n }) {\n super(params.message)\n this.name = 'PlatformError'\n this.code = params.code\n this.status = params.status\n this.field = params.field\n this.docsUrl = params.docsUrl\n this.body = params.body\n // Preserve the stack trace — Node's Error doesn't capture it\n // automatically when subclassing in some older runtimes.\n if (\n typeof (Error as typeof Error & { captureStackTrace?: unknown }).captureStackTrace ===\n 'function'\n ) {\n ;(\n Error as typeof Error & { captureStackTrace: (target: unknown, ctor: unknown) => void }\n ).captureStackTrace(this, PlatformError)\n }\n }\n\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n status: this.status,\n field: this.field,\n docsUrl: this.docsUrl,\n }\n }\n}\n","import { PlatformError, type ApiErrorCode } from './errors'\n\n// Low-level HTTP wrapper around `fetch` (native in Node 18+). Every resource\n// method routes through here for consistent auth + error handling + retries.\n//\n// v1 scope: JSON-in / JSON-out + multipart for file uploads. No streaming —\n// call WebSockets go through @craftedxp/voice-rn (the React Native client)\n// or a web equivalent, not this server-side SDK.\n\nexport interface HttpClientOptions {\n apiKey: string\n baseUrl: string\n // Default 30s. File uploads can override per-request.\n timeoutMs?: number\n // 429 + 5xx retries. Defaults to 3 attempts (original + 2 retries) with\n // exponential backoff (250ms, 1s). Set to 0 to disable.\n maxRetries?: number\n // Optional — lets consumers swap in a test/mock fetch (or a custom one\n // with instrumentation). Defaults to the global.\n fetch?: typeof fetch\n // Optional — a callback that fires per-request with the final status and\n // duration. Handy for dropping traces into the consumer's observability\n // stack without wrapping each call.\n onRequest?: (info: {\n method: string\n url: string\n status: number\n durationMs: number\n attempt: number\n }) => void\n}\n\nexport interface HttpRequest {\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE'\n path: string // starts with `/`, e.g. `/v1/agents/123`\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown // JSON-serialised — for multipart use `formData`\n formData?: FormData\n timeoutMs?: number\n // Exposed for edge cases where a resource wants to tack on extra\n // headers (we don't have any today but leave the hook).\n headers?: Record<string, string>\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000\nconst DEFAULT_MAX_RETRIES = 2 // total attempts = 3\n\nconst buildUrl = (baseUrl: string, path: string, query?: HttpRequest['query']): string => {\n const u = new URL(path, baseUrl)\n if (query) {\n for (const [k, v] of Object.entries(query)) {\n if (v === undefined) continue\n u.searchParams.set(k, String(v))\n }\n }\n return u.toString()\n}\n\nconst sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))\n\nconst isRetryable = (status: number): boolean => status === 429 || (status >= 500 && status < 600)\n\n// Parse whatever the server returned into a PlatformError. Falls back to\n// synthesising a sensible error for non-JSON responses.\nconst errorFromResponse = async (res: Response): Promise<PlatformError> => {\n const bodyText = await res.text().catch(() => '')\n let parsed: unknown = undefined\n try {\n parsed = bodyText ? JSON.parse(bodyText) : undefined\n } catch {\n // non-JSON response (e.g. an HTML error page from a proxy). Fall\n // through with parsed = undefined.\n }\n const errObj = (\n parsed as { error?: { code?: string; message?: string; field?: string; docs_url?: string } }\n )?.error\n return new PlatformError({\n code: (errObj?.code as ApiErrorCode) ?? 'unknown',\n message: errObj?.message ?? res.statusText ?? `HTTP ${res.status}`,\n status: res.status,\n field: errObj?.field,\n docsUrl: errObj?.docs_url,\n body: parsed ?? bodyText,\n })\n}\n\nexport const createHttpClient = (opts: HttpClientOptions) => {\n const fetchImpl = opts.fetch ?? globalThis.fetch\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const maxRetries = opts.maxRetries ?? DEFAULT_MAX_RETRIES\n\n if (!fetchImpl) {\n throw new Error('No global fetch available. @craftedxp/sdk-node requires Node >= 18.')\n }\n\n const request = async <T>(req: HttpRequest): Promise<T> => {\n const url = buildUrl(opts.baseUrl, req.path, req.query)\n const headers: Record<string, string> = {\n Authorization: `Bearer ${opts.apiKey}`,\n Accept: 'application/json',\n ...(req.headers ?? {}),\n }\n\n // Body shaping: prefer formData when provided; otherwise JSON.\n // `FormData` sets its own Content-Type with boundary — don't preempt it.\n // Typed as `string | FormData | undefined` (a subset of the global\n // BodyInit) so we don't need DOM lib types in this server-side SDK.\n let body: string | FormData | undefined\n if (req.formData) {\n body = req.formData\n } else if (req.body !== undefined) {\n headers['Content-Type'] = 'application/json'\n body = JSON.stringify(req.body)\n }\n\n const reqTimeout = req.timeoutMs ?? timeoutMs\n let lastErr: unknown\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), reqTimeout)\n const started = Date.now()\n try {\n const res = await fetchImpl(url, {\n method: req.method,\n headers,\n body,\n signal: controller.signal,\n })\n const durationMs = Date.now() - started\n opts.onRequest?.({\n method: req.method,\n url,\n status: res.status,\n durationMs,\n attempt: attempt + 1,\n })\n\n if (res.ok) {\n // 204 No Content — some endpoints (DELETE webhooks) return nothing.\n if (res.status === 204) return undefined as T\n const ct = res.headers.get('content-type') ?? ''\n if (ct.includes('application/json')) {\n return (await res.json()) as T\n }\n // Non-JSON 2xx — rare. Return raw text cast as T.\n return (await res.text()) as unknown as T\n }\n\n // Retryable error: back off + retry up to maxRetries.\n if (isRetryable(res.status) && attempt < maxRetries) {\n const retryAfter = res.headers.get('Retry-After')\n const backoff = retryAfter ? Number(retryAfter) * 1000 : 250 * Math.pow(2, attempt)\n await sleep(backoff)\n continue\n }\n\n throw await errorFromResponse(res)\n } catch (err) {\n if (err instanceof PlatformError) throw err\n // AbortError / network / DNS failures — retry up to maxRetries.\n if (attempt < maxRetries) {\n lastErr = err\n await sleep(250 * Math.pow(2, attempt))\n continue\n }\n const msg = err instanceof Error ? err.message : 'network error'\n throw new PlatformError({\n code: 'unknown',\n message: `Network error: ${msg}`,\n status: 0,\n })\n } finally {\n clearTimeout(timer)\n }\n }\n\n // Should be unreachable — the loop either returns, throws, or continues.\n throw lastErr instanceof Error ? lastErr : new Error('request exhausted retries')\n }\n\n return { request }\n}\n\nexport type HttpClient = ReturnType<typeof createHttpClient>\n","import type { HttpClient } from '../http'\nimport type { MeResponse } from '../types'\n\nexport const createMeResource = (http: HttpClient) => ({\n // Smoke test — confirms the API key is valid and returns the org + balance.\n // Most consumers use this as a ping on startup.\n get: async (): Promise<MeResponse> => http.request<MeResponse>({ method: 'GET', path: '/v1/me' }),\n})\n\nexport type MeResource = ReturnType<typeof createMeResource>\n","import type { HttpClient } from '../http'\nimport type {\n WebhookConfig,\n WebhookCreateInput,\n WebhookDelivery,\n WebhookUpdateInput,\n} from '../types'\n\n// Per-agent webhook resource, scoped at factory time to a specific agentId.\n// All endpoints mirror /v1/agents/:agentId/webhooks[/:id].\n\nexport const createAgentWebhooksResource = (http: HttpClient, agentId: string) => ({\n // Returns the webhook + its signing secret. The secret is only present in\n // this response — persist immediately, subsequent GETs omit it. Use the\n // secret to verify `X-Platform-Signature-256` (sha256=hex HMAC over body).\n create: async (input: WebhookCreateInput): Promise<WebhookConfig> =>\n http.request<WebhookConfig>({\n method: 'POST',\n path: `/v1/agents/${agentId}/webhooks`,\n body: input,\n }),\n\n list: async (): Promise<WebhookConfig[]> => {\n const res = await http.request<{ data: WebhookConfig[] }>({\n method: 'GET',\n path: `/v1/agents/${agentId}/webhooks`,\n })\n return res.data\n },\n\n get: async (webhookId: string): Promise<WebhookConfig> =>\n http.request<WebhookConfig>({\n method: 'GET',\n path: `/v1/agents/${agentId}/webhooks/${webhookId}`,\n }),\n\n update: async (webhookId: string, patch: WebhookUpdateInput): Promise<WebhookConfig> =>\n http.request<WebhookConfig>({\n method: 'PATCH',\n path: `/v1/agents/${agentId}/webhooks/${webhookId}`,\n body: patch,\n }),\n\n delete: async (webhookId: string): Promise<void> =>\n http.request<void>({\n method: 'DELETE',\n path: `/v1/agents/${agentId}/webhooks/${webhookId}`,\n }),\n\n // Fires a synthetic call.started against this webhook and returns the\n // full delivery record (including attempt status codes) once the retry\n // sequence has finished. Useful during setup to verify receiver wiring.\n test: async (webhookId: string): Promise<WebhookDelivery> =>\n http.request<WebhookDelivery>({\n method: 'POST',\n path: `/v1/agents/${agentId}/webhooks/${webhookId}/test`,\n }),\n})\n\nexport type AgentWebhooksResource = ReturnType<typeof createAgentWebhooksResource>\n","import type { HttpClient } from '../http'\nimport type { Agent, AgentCreateInput, AgentUpdateInput } from '../types'\nimport { createAgentWebhooksResource, type AgentWebhooksResource } from './agentWebhooks'\n\n// The server returns Agent with `apiKey` stripped and `hasApiKey: boolean`\n// on the model. We type the happy path but keep our input type permissive\n// so consumers can POST a plaintext `apiKey` that the server encrypts +\n// swaps for `apiKeySecret` on persistence.\n\nexport const createAgentsResource = (http: HttpClient) => {\n const agents = {\n create: async (input: AgentCreateInput): Promise<Agent> =>\n http.request<Agent>({ method: 'POST', path: '/v1/agents', body: input }),\n\n list: async (): Promise<Agent[]> => {\n const res = await http.request<{ data: Agent[] }>({ method: 'GET', path: '/v1/agents' })\n return res.data\n },\n\n // Async iterator for \"give me every agent\" — v1 server returns the full\n // list in one page, so this is just a thin convenience. When the server\n // picks up cursor pagination, this is the method that papers over that\n // migration without consumer changes.\n listAll: async function* (): AsyncIterable<Agent> {\n const page = await agents.list()\n for (const a of page) yield a\n },\n\n get: async (agentId: string): Promise<Agent> =>\n http.request<Agent>({ method: 'GET', path: `/v1/agents/${agentId}` }),\n\n update: async (agentId: string, patch: AgentUpdateInput): Promise<Agent> =>\n http.request<Agent>({ method: 'PATCH', path: `/v1/agents/${agentId}`, body: patch }),\n\n delete: async (agentId: string): Promise<void> =>\n http.request<void>({ method: 'DELETE', path: `/v1/agents/${agentId}` }),\n\n /**\n * Upload an avatar image for the agent. Server re-encodes to a 512×512\n * WebP and stores it in the public-read avatars bucket; the returned\n * `Agent` has `avatarUrl` set to the canonical public URL with a\n * `?v=` cache-buster.\n *\n * `file` accepts a Node Buffer / Uint8Array / Blob / typed-array.\n * `filename` and `contentType` are optional but help the server log\n * meaningful errors when something rejects.\n */\n uploadAvatar: async (\n agentId: string,\n file: Buffer | Uint8Array | Blob | ArrayBuffer,\n opts: { filename?: string; contentType?: string } = {},\n ): Promise<Agent> => {\n const fd = new FormData()\n const blob =\n file instanceof Blob\n ? file\n : // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new Blob([file as any], { type: opts.contentType ?? 'application/octet-stream' })\n fd.append('file', blob, opts.filename ?? 'avatar')\n return http.request<Agent>({\n method: 'POST',\n path: `/v1/agents/${agentId}/avatar`,\n formData: fd,\n })\n },\n\n /**\n * Remove the agent's avatar — both the GCS object and the `avatarUrl`\n * field. Idempotent: calling on an agent without an avatar still\n * returns the agent.\n */\n removeAvatar: async (agentId: string): Promise<Agent> =>\n http.request<Agent>({ method: 'DELETE', path: `/v1/agents/${agentId}/avatar` }),\n\n // Nested resource. Per-agent webhook CRUD lives at\n // /v1/agents/:agentId/webhooks/* — we expose it as a factory keyed on\n // agentId so consumers can bind once and reuse:\n //\n // const hooks = client.agents.webhooks(myAgentId)\n // await hooks.create({ url, events })\n // await hooks.list()\n webhooks: (agentId: string): AgentWebhooksResource =>\n createAgentWebhooksResource(http, agentId),\n }\n return agents\n}\n\nexport type AgentsResource = ReturnType<typeof createAgentsResource>\n","import type { HttpClient } from '../http'\nimport type {\n CallListFilters,\n CallRecord,\n CallRecordingUrlResponse,\n CallSummary,\n TranscriptTurn,\n} from '../types'\n\nexport const createCallsResource = (http: HttpClient) => {\n const calls = {\n list: async (filters: CallListFilters = {}): Promise<CallSummary[]> => {\n const res = await http.request<{ data: CallSummary[] }>({\n method: 'GET',\n path: '/v1/calls',\n query: filters as Record<string, string | number | undefined>,\n })\n return res.data\n },\n\n // Auto-pagination helper. v1 server caps at limit (max 200) in a single\n // page — consumers who ask for \"every call since X\" get that page, the\n // iterator ends. This is the shape we'd extend with cursor support\n // without breaking callers.\n listAll: async function* (filters: CallListFilters = {}): AsyncIterable<CallSummary> {\n const page = await calls.list(filters)\n for (const c of page) yield c\n },\n\n get: async (callId: string): Promise<CallRecord> =>\n http.request<CallRecord>({ method: 'GET', path: `/v1/calls/${callId}` }),\n\n transcript: async (callId: string): Promise<{ callId: string; transcript: TranscriptTurn[] }> =>\n http.request<{ callId: string; transcript: TranscriptTurn[] }>({\n method: 'GET',\n path: `/v1/calls/${callId}/transcript`,\n }),\n\n // Returns a V4 signed URL (1-hour TTL). `ready: false` + `artifact:\n // 'caller-raw'` means the async mix job hasn't finished — the URL still\n // points at a playable file (raw caller PCM).\n recording: async (callId: string): Promise<CallRecordingUrlResponse> =>\n http.request<CallRecordingUrlResponse>({\n method: 'GET',\n path: `/v1/calls/${callId}/recording`,\n }),\n\n // Outbound dialling (POST /v1/calls) + in-call control are Phase 1.4.4 /\n // 1.4.5 respectively — blocked on telephony. Surface clear \"not built\n // yet\" errors here if consumers guess those method names, so they don't\n // silently hit a non-existent endpoint and wonder why it 404s.\n }\n return calls\n}\n\nexport type CallsResource = ReturnType<typeof createCallsResource>\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport type { HttpClient } from '../http'\nimport type { KnowledgeBase, KnowledgeBaseFile } from '../types'\n\nexport const createKnowledgeBasesResource = (http: HttpClient) => ({\n create: async (name: string): Promise<KnowledgeBase> =>\n http.request<KnowledgeBase>({\n method: 'POST',\n path: '/v1/knowledge-bases',\n body: { name },\n }),\n\n list: async (): Promise<KnowledgeBase[]> => {\n const res = await http.request<{ data: KnowledgeBase[] }>({\n method: 'GET',\n path: '/v1/knowledge-bases',\n })\n return res.data\n },\n\n get: async (kbId: string): Promise<KnowledgeBase> =>\n http.request<KnowledgeBase>({ method: 'GET', path: `/v1/knowledge-bases/${kbId}` }),\n\n delete: async (kbId: string): Promise<void> =>\n http.request<void>({ method: 'DELETE', path: `/v1/knowledge-bases/${kbId}` }),\n\n // File upload — accepts either a local file path OR raw bytes + filename.\n // The server ingests synchronously today (Phase 3.1.4 Cloud Tasks is a\n // followup), so the returned file has status='ready' in most cases.\n uploadFile: async (\n kbId: string,\n source:\n | { path: string; filename?: string; mimeType?: string }\n | { data: Buffer | Uint8Array; filename: string; mimeType?: string },\n ): Promise<KnowledgeBaseFile> => {\n const form = new FormData()\n let blob: Blob\n let filename: string\n let mime: string\n\n if ('path' in source) {\n const buf = await fs.promises.readFile(source.path)\n filename = source.filename ?? path.basename(source.path)\n mime = source.mimeType ?? 'application/octet-stream'\n blob = new Blob([new Uint8Array(buf)], { type: mime })\n } else {\n filename = source.filename\n mime = source.mimeType ?? 'application/octet-stream'\n const bytes = source.data instanceof Buffer ? new Uint8Array(source.data) : source.data\n blob = new Blob([bytes], { type: mime })\n }\n form.append('file', blob, filename)\n\n // File uploads can take a while (OCR, chunking, embedding) — give them\n // room before timing out. 5 min cap matches the server's own\n // processing budget.\n return http.request<KnowledgeBaseFile>({\n method: 'POST',\n path: `/v1/knowledge-bases/${kbId}/files`,\n formData: form,\n timeoutMs: 5 * 60 * 1000,\n })\n },\n\n listFiles: async (kbId: string): Promise<KnowledgeBaseFile[]> => {\n const res = await http.request<{ data: KnowledgeBaseFile[] }>({\n method: 'GET',\n path: `/v1/knowledge-bases/${kbId}/files`,\n })\n return res.data\n },\n\n deleteFile: async (kbId: string, fileId: string): Promise<void> =>\n http.request<void>({\n method: 'DELETE',\n path: `/v1/knowledge-bases/${kbId}/files/${fileId}`,\n }),\n})\n\nexport type KnowledgeBasesResource = ReturnType<typeof createKnowledgeBasesResource>\n","import type { HttpClient } from '../http'\nimport type { LedgerEntry } from '../types'\n\nexport const createCreditsResource = (http: HttpClient) => {\n const credits = {\n getBalance: async (): Promise<{ orgId: string; balanceCents: number }> =>\n http.request<{ orgId: string; balanceCents: number }>({\n method: 'GET',\n path: '/v1/credits/balance',\n }),\n\n // Returns ledger entries newest-first. `limit` is capped at 500 server-side.\n getLedger: async (opts: { limit?: number } = {}): Promise<LedgerEntry[]> => {\n const res = await http.request<{ data: LedgerEntry[] }>({\n method: 'GET',\n path: '/v1/credits/ledger',\n query: opts as Record<string, string | number | undefined>,\n })\n return res.data\n },\n\n // Auto-pagination scaffold — v1 server returns a single page up to\n // limit=500. When cursor pagination lands this is where it gets wired.\n getLedgerAll: async function* (opts: { limit?: number } = {}): AsyncIterable<LedgerEntry> {\n const page = await credits.getLedger(opts)\n for (const e of page) yield e\n },\n }\n return credits\n}\n\nexport type CreditsResource = ReturnType<typeof createCreditsResource>\n","import type { HttpClient } from '../http'\nimport type { CallTokenMintInput, CallTokenMintResult, CallTokenSummary } from '../types'\n\n// Short-lived, agent-scoped `ct_` tokens. Mint one per user session on your\n// backend, hand the raw value to the browser; let this SDK handle lifecycle\n// (revoke on sign-out, list active tokens for an admin panel).\n\nexport const createCallTokensResource = (http: HttpClient) => ({\n // Returns the RAW token value once. Don't log it; pass it straight to the\n // browser + discard server-side. `tokenId` is the stable public handle\n // used for revocation later.\n mint: async (input: CallTokenMintInput): Promise<CallTokenMintResult> =>\n http.request<CallTokenMintResult>({\n method: 'POST',\n path: '/v1/call-tokens',\n body: input,\n }),\n\n // Live tokens only by default. Pass includeRevoked/includeExpired when\n // debugging \"why did my token stop working\".\n list: async (\n opts: { includeRevoked?: boolean; includeExpired?: boolean; limit?: number } = {},\n ): Promise<CallTokenSummary[]> => {\n const query: Record<string, string | number | undefined> = {}\n if (opts.includeRevoked) query.includeRevoked = '1'\n if (opts.includeExpired) query.includeExpired = '1'\n if (opts.limit !== undefined) query.limit = opts.limit\n const res = await http.request<{ data: CallTokenSummary[] }>({\n method: 'GET',\n path: '/v1/call-tokens',\n query,\n })\n return res.data\n },\n\n // Idempotent — re-revoking a revoked token returns `alreadyRevoked: true`.\n revoke: async (\n tokenId: string,\n ): Promise<{ tokenId: string; revoked: boolean; alreadyRevoked?: boolean }> =>\n http.request<{ tokenId: string; revoked: boolean; alreadyRevoked?: boolean }>({\n method: 'DELETE',\n path: `/v1/call-tokens/${tokenId}`,\n }),\n})\n\nexport type CallTokensResource = ReturnType<typeof createCallTokensResource>\n","import type { HttpClient } from '../http'\nimport type { WebhookDelivery } from '../types'\n\n// Org-wide webhook delivery log. Per-agent CRUD lives on\n// `client.agents.webhooks(agentId)` — this namespace is just the\n// read-only deliveries surface that spans all agents.\n\nexport const createWebhooksResource = (http: HttpClient) => ({\n deliveries: async (\n filters: {\n agentId?: string\n webhookId?: string\n callId?: string\n limit?: number\n } = {},\n ): Promise<WebhookDelivery[]> => {\n const res = await http.request<{ data: WebhookDelivery[] }>({\n method: 'GET',\n path: '/v1/webhooks/deliveries',\n query: filters as Record<string, string | number | undefined>,\n })\n return res.data\n },\n})\n\nexport type WebhooksResource = ReturnType<typeof createWebhooksResource>\n","import type { HttpClient } from '../http'\nimport type { CatalogAgent, CatalogListInput } from '../types'\n\n// Org-scoped consumer endpoints. Today this is just the agent catalog —\n// the trimmed shape your mobile app picks an agent from. Lives at\n// `/v1/orgs/:orgId/agents` rather than reusing the admin `/v1/agents/*`\n// tree on purpose: the catalog response intentionally excludes the\n// operator-only fields (system prompt, tools, KB IDs) so a leaked\n// consumer-backend `sk_` can't lift the operator config out of it.\n//\n// Pattern from your backend:\n//\n// const client = new PlatformClient({ apiKey: process.env.SK })\n// const visible = await client.orgs.listAgents({\n// orgId: process.env.ORG_ID!,\n// userTags: ['tier1'], // omit to get the unfiltered admin view\n// })\n// res.json(visible)\n\nexport const createOrgsResource = (http: HttpClient) => ({\n /**\n * Fetch the agent catalog for an org. Returns the consumer-trimmed shape;\n * no system prompt, tools, or KB info. Use `client.agents.get(agentId)`\n * with the same `sk_` if you need the full admin shape.\n *\n * `userTags`: end-user entitlement tags. When supplied, hides agents\n * whose `allowedUserTags` is non-empty and doesn't intersect with the\n * supplied list. Omit to get the unfiltered admin view.\n *\n * Persona / category filtering is intentionally not a server param —\n * filter the returned list client-side over `name`s if you need it.\n *\n * Throws `403 forbidden` if `orgId` doesn't match the key's org.\n */\n listAgents: async (input: CatalogListInput): Promise<CatalogAgent[]> => {\n const query: Record<string, string | undefined> = {}\n if (input.userTags && input.userTags.length > 0) query.userTags = input.userTags.join(',')\n const res = await http.request<{ data: CatalogAgent[] }>({\n method: 'GET',\n path: `/v1/orgs/${input.orgId}/agents`,\n query,\n })\n return res.data\n },\n})\n\nexport type OrgsResource = ReturnType<typeof createOrgsResource>\n","import type { HttpClient } from '../http'\nimport type {\n CreateRoomInput,\n CreateRoomResponse,\n ListRoomsResponse,\n ListUtterancesResponse,\n RoomDoc,\n RoomEventAck,\n RoomListFilters,\n RoomTranscriptOptions,\n} from '../types'\n\n// REST wrappers for /v1/rooms — the multi-party video room surface (see\n// docs/superpowers/specs/2026-05-18-multiparty-rooms-design.md). Lets\n// server-side code mint rooms, fetch state, list transcript pages, and end\n// rooms programmatically.\n//\n// Auth model: same Bearer `sk_` flow as every other resource — the server\n// derives `orgId` from the API key, so the SDK never sets a tenant header.\n//\n// Host actions beyond `end` (promote/demote/kick) and observer-token mint\n// live in the server but aren't surfaced here yet — they're operator-side\n// flows that the dashboard hits directly. Re-add here if a programmatic\n// use-case shows up (CI tests, integration harnesses).\n\nexport const createRoomsResource = (http: HttpClient) => ({\n // Provision a new room. Server returns 201 with ONE shared room-level\n // `joinToken` + `joinUrl`. Share the single link with everyone you want in\n // the room — each visitor supplies their own display name at join time and\n // becomes a fresh, distinct participant. The server persists only the\n // token's sha256 hash; the raw token is returned here once and never stored.\n create: async (input: CreateRoomInput): Promise<CreateRoomResponse> =>\n http.request<CreateRoomResponse>({\n method: 'POST',\n path: '/v1/rooms',\n body: input,\n }),\n\n // Listing — opaque cursor pagination (`nextCursor` returned by the server\n // is whatever startAfter() needs, don't parse client-side).\n list: async (filters: RoomListFilters = {}): Promise<ListRoomsResponse> => {\n const query: Record<string, string | number | undefined> = {}\n if (filters.status) query.status = filters.status\n if (filters.limit !== undefined) query.limit = filters.limit\n if (filters.cursor) query.cursor = filters.cursor\n return http.request<ListRoomsResponse>({\n method: 'GET',\n path: '/v1/rooms',\n query,\n })\n },\n\n // Fetch a single room. 404s are surfaced as PlatformError('not_found').\n get: async (roomId: string): Promise<RoomDoc> =>\n http.request<RoomDoc>({\n method: 'GET',\n path: `/v1/rooms/${roomId}`,\n }),\n\n // Transcript pages — utterances are ordered by `startedAt asc`. Cursor is\n // an ISO timestamp (server enforces, don't construct yourself).\n transcript: async (\n roomId: string,\n opts: RoomTranscriptOptions = {},\n ): Promise<ListUtterancesResponse> => {\n const query: Record<string, string | number | undefined> = {}\n if (opts.cursor) query.cursor = opts.cursor\n if (opts.limit !== undefined) query.limit = opts.limit\n return http.request<ListUtterancesResponse>({\n method: 'GET',\n path: `/v1/rooms/${roomId}/transcript`,\n query,\n })\n },\n\n // End a room — async on the server: returns 202 + eventId once the\n // controlEvents entry is written. The room-worker observes the entry,\n // broadcasts the system message, and tears down LiveKit shortly after.\n end: async (roomId: string): Promise<RoomEventAck> =>\n http.request<RoomEventAck>({\n method: 'POST',\n path: `/v1/rooms/${roomId}/end`,\n }),\n})\n\nexport type RoomsResource = ReturnType<typeof createRoomsResource>\n","import { createHttpClient, type HttpClientOptions } from './http'\nimport { createMeResource, type MeResource } from './resources/me'\nimport { createAgentsResource, type AgentsResource } from './resources/agents'\nimport { createCallsResource, type CallsResource } from './resources/calls'\nimport {\n createKnowledgeBasesResource,\n type KnowledgeBasesResource,\n} from './resources/knowledgeBases'\nimport { createCreditsResource, type CreditsResource } from './resources/credits'\nimport { createCallTokensResource, type CallTokensResource } from './resources/callTokens'\nimport { createWebhooksResource, type WebhooksResource } from './resources/webhooks'\nimport { createOrgsResource, type OrgsResource } from './resources/orgs'\nimport { createRoomsResource, type RoomsResource } from './resources/rooms'\n\nexport interface PlatformClientOptions {\n // Full-org API key minted from the dashboard or bootstrap CLI. Start with\n // `sk_`. Never ship to a browser — use `client.callTokens.mint(...)` to\n // generate a narrow `ct_` token for client-side use instead.\n apiKey: string\n // Defaults to the hosted platform. Point at `http://localhost:8080` for\n // local dev or at a self-hosted deployment.\n baseUrl?: string\n // Passthrough tuning for the HTTP layer.\n timeoutMs?: number\n maxRetries?: number\n fetch?: HttpClientOptions['fetch']\n onRequest?: HttpClientOptions['onRequest']\n}\n\n// Single entry point. All resources are lazy-constructed in the constructor\n// so their refs don't incur any per-call allocation. Shape mirrors Stripe /\n// Twilio / Vapi's `resource.method()` convention for familiarity.\nexport class PlatformClient {\n readonly me: MeResource\n readonly agents: AgentsResource\n readonly calls: CallsResource\n readonly knowledgeBases: KnowledgeBasesResource\n readonly credits: CreditsResource\n readonly callTokens: CallTokensResource\n readonly webhooks: WebhooksResource\n readonly orgs: OrgsResource\n readonly rooms: RoomsResource\n\n constructor(options: PlatformClientOptions) {\n if (!options.apiKey) {\n throw new Error('PlatformClient: `apiKey` is required')\n }\n const http = createHttpClient({\n apiKey: options.apiKey,\n baseUrl: options.baseUrl ?? 'https://api.example.com',\n timeoutMs: options.timeoutMs,\n maxRetries: options.maxRetries,\n fetch: options.fetch,\n onRequest: options.onRequest,\n })\n\n this.me = createMeResource(http)\n this.agents = createAgentsResource(http)\n this.calls = createCallsResource(http)\n this.knowledgeBases = createKnowledgeBasesResource(http)\n this.credits = createCreditsResource(http)\n this.callTokens = createCallTokensResource(http)\n this.webhooks = createWebhooksResource(http)\n this.orgs = createOrgsResource(http)\n this.rooms = createRoomsResource(http)\n }\n}\n","import crypto from 'node:crypto'\n\n// Helper for consumers receiving webhooks: verify the `X-Platform-Signature-256`\n// header against the raw body + secret. Plain function (not tied to\n// PlatformClient) so Express/Koa/Next.js middleware can use it without\n// instantiating a client.\n//\n// import { verifyWebhookSignature } from '@craftedxp/sdk-node'\n// app.post('/webhooks/voice-agent', express.raw({ type: 'application/json' }), (req, res) => {\n// const sig = req.header('X-Platform-Signature-256') ?? ''\n// if (!verifyWebhookSignature(req.body, sig, process.env.VOICE_AGENT_WEBHOOK_SECRET!)) {\n// return res.status(401).send('invalid signature')\n// }\n// const event = JSON.parse(req.body.toString('utf8'))\n// // ...handle event\n// })\n//\n// The signature is `sha256=<hex HMAC-SHA256 of rawBody with secret>`.\n// Timing-safe compare to avoid microtiming side channels.\n\nexport const verifyWebhookSignature = (\n rawBody: Buffer | string,\n signatureHeader: string,\n secret: string,\n): boolean => {\n if (!signatureHeader || !secret) return false\n const [algo, provided] = signatureHeader.split('=')\n if (algo !== 'sha256' || !provided) return false\n\n const expected = crypto\n .createHmac('sha256', secret)\n .update(typeof rawBody === 'string' ? rawBody : rawBody)\n .digest('hex')\n\n // Buffers must match in length for timingSafeEqual.\n const a = Buffer.from(expected, 'hex')\n const b = Buffer.from(provided, 'h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BAAAC,QACd,WAAW,UAAU,MAAM,EAC3B,OAAO,OAAO,YAAY,WAAW,UAAU,OAAO,EACtD,OAAO,KAAK;AAGf,QAAM,IAAI,OAAO,KAAK,UAAU,KAAK;AACrC,QAAM,IAAI,OAAO,KAAK,UAAU,KAAK;AACrC,MAAI,EAAE,WAAW,EAAE,OAAQ,QAAO;AAClC,SAAO,mBAAAA,QAAO,gBAAgB,GAAG,CAAC;AACpC;","names":["path","fs","path","crypto"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/errors.ts","../src/http.ts","../src/resources/me.ts","../src/resources/agentWebhooks.ts","../src/resources/agents.ts","../src/resources/calls.ts","../src/resources/knowledgeBases.ts","../src/resources/credits.ts","../src/resources/callTokens.ts","../src/resources/webhooks.ts","../src/resources/orgs.ts","../src/resources/rooms.ts","../src/resources/chats.ts","../src/PlatformClient.ts","../src/verify.ts"],"sourcesContent":["// Public API of @craftedxp/sdk-node.\n\nexport { PlatformClient } from './PlatformClient'\nexport type { PlatformClientOptions } from './PlatformClient'\n\n// Error class for `instanceof` checks in consumer code.\nexport { PlatformError } from './errors'\nexport type { ApiErrorCode } from './errors'\n\n// Webhook signature verification helper — standalone so frameworks\n// (Express, Koa, Next.js route handlers) can use it without instantiating\n// a PlatformClient.\nexport { verifyWebhookSignature } from './verify'\n\n// Re-export DTO types. Consumers often type their own storage models\n// against these — re-exporting avoids `import type` gymnastics.\nexport type * from './types'\n\n// Advanced: expose the resource types for consumers subclassing / wrapping\n// the client. 99% of users don't need these.\nexport type { MeResource } from './resources/me'\nexport type { AgentsResource } from './resources/agents'\nexport type { AgentWebhooksResource } from './resources/agentWebhooks'\nexport type { CallsResource } from './resources/calls'\nexport type { KnowledgeBasesResource } from './resources/knowledgeBases'\nexport type { CreditsResource } from './resources/credits'\nexport type { CallTokensResource } from './resources/callTokens'\nexport type { WebhooksResource } from './resources/webhooks'\nexport type { OrgsResource } from './resources/orgs'\nexport type { RoomsResource } from './resources/rooms'\nexport type { ChatsResource } from './resources/chats'\nexport type { StartChatInput, Chat } from './resources/chats'\n","// Typed error class mirroring the server's ErrorV1 shape:\n// { error: { code, message, field?, docs_url? } }\n//\n// Consumers do `err instanceof PlatformError` to branch on code without\n// parsing string messages. `status` carries the HTTP code for the 1% of\n// cases where the code field isn't enough (e.g. rate-limit → retry-after\n// header correlation).\n\nexport type ApiErrorCode =\n | 'unauthorized'\n | 'forbidden'\n | 'not_found'\n | 'bad_request'\n | 'conflict'\n | 'rate_limited'\n | 'payment_required'\n | 'internal_error'\n | 'unknown'\n\nexport class PlatformError extends Error {\n readonly code: ApiErrorCode\n readonly status: number\n readonly field?: string\n readonly docsUrl?: string\n // The raw response body for debugging. Intentionally optional — we clear\n // it on `error.toJSON()` so logging libraries don't dump the whole\n // server response into production logs.\n readonly body?: unknown\n\n constructor(params: {\n code: ApiErrorCode\n message: string\n status: number\n field?: string\n docsUrl?: string\n body?: unknown\n }) {\n super(params.message)\n this.name = 'PlatformError'\n this.code = params.code\n this.status = params.status\n this.field = params.field\n this.docsUrl = params.docsUrl\n this.body = params.body\n // Preserve the stack trace — Node's Error doesn't capture it\n // automatically when subclassing in some older runtimes.\n if (\n typeof (Error as typeof Error & { captureStackTrace?: unknown }).captureStackTrace ===\n 'function'\n ) {\n ;(\n Error as typeof Error & { captureStackTrace: (target: unknown, ctor: unknown) => void }\n ).captureStackTrace(this, PlatformError)\n }\n }\n\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n status: this.status,\n field: this.field,\n docsUrl: this.docsUrl,\n }\n }\n}\n","import { PlatformError, type ApiErrorCode } from './errors'\n\n// Low-level HTTP wrapper around `fetch` (native in Node 18+). Every resource\n// method routes through here for consistent auth + error handling + retries.\n//\n// v1 scope: JSON-in / JSON-out + multipart for file uploads. No streaming —\n// call WebSockets go through @craftedxp/voice-rn (the React Native client)\n// or a web equivalent, not this server-side SDK.\n\nexport interface HttpClientOptions {\n apiKey: string\n baseUrl: string\n // Default 30s. File uploads can override per-request.\n timeoutMs?: number\n // 429 + 5xx retries. Defaults to 3 attempts (original + 2 retries) with\n // exponential backoff (250ms, 1s). Set to 0 to disable.\n maxRetries?: number\n // Optional — lets consumers swap in a test/mock fetch (or a custom one\n // with instrumentation). Defaults to the global.\n fetch?: typeof fetch\n // Optional — a callback that fires per-request with the final status and\n // duration. Handy for dropping traces into the consumer's observability\n // stack without wrapping each call.\n onRequest?: (info: {\n method: string\n url: string\n status: number\n durationMs: number\n attempt: number\n }) => void\n}\n\nexport interface HttpRequest {\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE'\n path: string // starts with `/`, e.g. `/v1/agents/123`\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown // JSON-serialised — for multipart use `formData`\n formData?: FormData\n timeoutMs?: number\n // Exposed for edge cases where a resource wants to tack on extra\n // headers (we don't have any today but leave the hook).\n headers?: Record<string, string>\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000\nconst DEFAULT_MAX_RETRIES = 2 // total attempts = 3\n\nconst buildUrl = (baseUrl: string, path: string, query?: HttpRequest['query']): string => {\n const u = new URL(path, baseUrl)\n if (query) {\n for (const [k, v] of Object.entries(query)) {\n if (v === undefined) continue\n u.searchParams.set(k, String(v))\n }\n }\n return u.toString()\n}\n\nconst sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))\n\nconst isRetryable = (status: number): boolean => status === 429 || (status >= 500 && status < 600)\n\n// Parse whatever the server returned into a PlatformError. Falls back to\n// synthesising a sensible error for non-JSON responses.\nconst errorFromResponse = async (res: Response): Promise<PlatformError> => {\n const bodyText = await res.text().catch(() => '')\n let parsed: unknown = undefined\n try {\n parsed = bodyText ? JSON.parse(bodyText) : undefined\n } catch {\n // non-JSON response (e.g. an HTML error page from a proxy). Fall\n // through with parsed = undefined.\n }\n const errObj = (\n parsed as { error?: { code?: string; message?: string; field?: string; docs_url?: string } }\n )?.error\n return new PlatformError({\n code: (errObj?.code as ApiErrorCode) ?? 'unknown',\n message: errObj?.message ?? res.statusText ?? `HTTP ${res.status}`,\n status: res.status,\n field: errObj?.field,\n docsUrl: errObj?.docs_url,\n body: parsed ?? bodyText,\n })\n}\n\nexport const createHttpClient = (opts: HttpClientOptions) => {\n const fetchImpl = opts.fetch ?? globalThis.fetch\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const maxRetries = opts.maxRetries ?? DEFAULT_MAX_RETRIES\n\n if (!fetchImpl) {\n throw new Error('No global fetch available. @craftedxp/sdk-node requires Node >= 18.')\n }\n\n const request = async <T>(req: HttpRequest): Promise<T> => {\n const url = buildUrl(opts.baseUrl, req.path, req.query)\n const headers: Record<string, string> = {\n Authorization: `Bearer ${opts.apiKey}`,\n Accept: 'application/json',\n ...(req.headers ?? {}),\n }\n\n // Body shaping: prefer formData when provided; otherwise JSON.\n // `FormData` sets its own Content-Type with boundary — don't preempt it.\n // Typed as `string | FormData | undefined` (a subset of the global\n // BodyInit) so we don't need DOM lib types in this server-side SDK.\n let body: string | FormData | undefined\n if (req.formData) {\n body = req.formData\n } else if (req.body !== undefined) {\n headers['Content-Type'] = 'application/json'\n body = JSON.stringify(req.body)\n }\n\n const reqTimeout = req.timeoutMs ?? timeoutMs\n let lastErr: unknown\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), reqTimeout)\n const started = Date.now()\n try {\n const res = await fetchImpl(url, {\n method: req.method,\n headers,\n body,\n signal: controller.signal,\n })\n const durationMs = Date.now() - started\n opts.onRequest?.({\n method: req.method,\n url,\n status: res.status,\n durationMs,\n attempt: attempt + 1,\n })\n\n if (res.ok) {\n // 204 No Content — some endpoints (DELETE webhooks) return nothing.\n if (res.status === 204) return undefined as T\n const ct = res.headers.get('content-type') ?? ''\n if (ct.includes('application/json')) {\n return (await res.json()) as T\n }\n // Non-JSON 2xx — rare. Return raw text cast as T.\n return (await res.text()) as unknown as T\n }\n\n // Retryable error: back off + retry up to maxRetries.\n if (isRetryable(res.status) && attempt < maxRetries) {\n const retryAfter = res.headers.get('Retry-After')\n const backoff = retryAfter ? Number(retryAfter) * 1000 : 250 * Math.pow(2, attempt)\n await sleep(backoff)\n continue\n }\n\n throw await errorFromResponse(res)\n } catch (err) {\n if (err instanceof PlatformError) throw err\n // AbortError / network / DNS failures — retry up to maxRetries.\n if (attempt < maxRetries) {\n lastErr = err\n await sleep(250 * Math.pow(2, attempt))\n continue\n }\n const msg = err instanceof Error ? err.message : 'network error'\n throw new PlatformError({\n code: 'unknown',\n message: `Network error: ${msg}`,\n status: 0,\n })\n } finally {\n clearTimeout(timer)\n }\n }\n\n // Should be unreachable — the loop either returns, throws, or continues.\n throw lastErr instanceof Error ? lastErr : new Error('request exhausted retries')\n }\n\n // SSE streaming: returns an AsyncIterable<T> over parsed SSE events.\n // Each event is the JSON `data` payload merged with the `event` name as\n // `type`. No retry/backoff mid-stream (stream != request); the caller\n // should treat `error` events from the typed channel as the error path.\n async function* stream<T = unknown>(req: HttpRequest): AsyncIterable<T> {\n const url = buildUrl(opts.baseUrl, req.path, req.query)\n const headers: Record<string, string> = {\n Authorization: `Bearer ${opts.apiKey}`,\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream',\n ...(req.headers ?? {}),\n }\n\n const started = Date.now()\n let res: Response\n try {\n res = await fetchImpl(url, {\n method: req.method,\n headers,\n body: req.body !== undefined ? JSON.stringify(req.body) : undefined,\n })\n } catch (err) {\n const msg = err instanceof Error ? err.message : 'network error'\n throw new PlatformError({\n code: 'unknown',\n message: `Network error: ${msg}`,\n status: 0,\n })\n }\n\n opts.onRequest?.({\n method: req.method,\n url,\n status: res.status,\n durationMs: Date.now() - started,\n attempt: 1,\n })\n\n if (!res.ok || !res.body) {\n const text = await res.text().catch(() => '')\n let parsed: unknown = undefined\n try {\n parsed = text ? JSON.parse(text) : undefined\n } catch {\n // non-JSON — fall through\n }\n const errObj = (\n parsed as { error?: { code?: string; message?: string; field?: string; docs_url?: string } }\n )?.error\n throw new PlatformError({\n code: (errObj?.code as import('./errors').ApiErrorCode) ?? 'unknown',\n message: errObj?.message ?? res.statusText ?? `HTTP ${res.status}`,\n status: res.status,\n field: errObj?.field,\n docsUrl: errObj?.docs_url,\n body: parsed ?? text,\n })\n }\n\n const reader = res.body.getReader()\n const decoder = new TextDecoder()\n let buf = ''\n\n while (true) {\n const { value, done } = await reader.read()\n if (done) return\n buf += decoder.decode(value, { stream: true })\n let idx: number\n while ((idx = buf.indexOf('\\n\\n')) >= 0) {\n const block = buf.slice(0, idx)\n buf = buf.slice(idx + 2)\n let event = 'message'\n let data = ''\n for (const line of block.split('\\n')) {\n if (line.startsWith(':')) continue // SSE comment / keepalive\n if (line.startsWith('event:')) event = line.slice(6).trim()\n else if (line.startsWith('data:')) data += line.slice(5).trim()\n }\n if (!data) continue\n try {\n const parsed = JSON.parse(data)\n yield { type: event, ...parsed } as T\n } catch {\n // Drop malformed JSON; an error event will arrive via the typed channel.\n }\n }\n }\n }\n\n return { request, stream }\n}\n\nexport type HttpClient = ReturnType<typeof createHttpClient>\n","import type { HttpClient } from '../http'\nimport type { MeResponse } from '../types'\n\nexport const createMeResource = (http: HttpClient) => ({\n // Smoke test — confirms the API key is valid and returns the org + balance.\n // Most consumers use this as a ping on startup.\n get: async (): Promise<MeResponse> => http.request<MeResponse>({ method: 'GET', path: '/v1/me' }),\n})\n\nexport type MeResource = ReturnType<typeof createMeResource>\n","import type { HttpClient } from '../http'\nimport type {\n WebhookConfig,\n WebhookCreateInput,\n WebhookDelivery,\n WebhookUpdateInput,\n} from '../types'\n\n// Per-agent webhook resource, scoped at factory time to a specific agentId.\n// All endpoints mirror /v1/agents/:agentId/webhooks[/:id].\n\nexport const createAgentWebhooksResource = (http: HttpClient, agentId: string) => ({\n // Returns the webhook + its signing secret. The secret is only present in\n // this response — persist immediately, subsequent GETs omit it. Use the\n // secret to verify `X-Platform-Signature-256` (sha256=hex HMAC over body).\n create: async (input: WebhookCreateInput): Promise<WebhookConfig> =>\n http.request<WebhookConfig>({\n method: 'POST',\n path: `/v1/agents/${agentId}/webhooks`,\n body: input,\n }),\n\n list: async (): Promise<WebhookConfig[]> => {\n const res = await http.request<{ data: WebhookConfig[] }>({\n method: 'GET',\n path: `/v1/agents/${agentId}/webhooks`,\n })\n return res.data\n },\n\n get: async (webhookId: string): Promise<WebhookConfig> =>\n http.request<WebhookConfig>({\n method: 'GET',\n path: `/v1/agents/${agentId}/webhooks/${webhookId}`,\n }),\n\n update: async (webhookId: string, patch: WebhookUpdateInput): Promise<WebhookConfig> =>\n http.request<WebhookConfig>({\n method: 'PATCH',\n path: `/v1/agents/${agentId}/webhooks/${webhookId}`,\n body: patch,\n }),\n\n delete: async (webhookId: string): Promise<void> =>\n http.request<void>({\n method: 'DELETE',\n path: `/v1/agents/${agentId}/webhooks/${webhookId}`,\n }),\n\n // Fires a synthetic call.started against this webhook and returns the\n // full delivery record (including attempt status codes) once the retry\n // sequence has finished. Useful during setup to verify receiver wiring.\n test: async (webhookId: string): Promise<WebhookDelivery> =>\n http.request<WebhookDelivery>({\n method: 'POST',\n path: `/v1/agents/${agentId}/webhooks/${webhookId}/test`,\n }),\n})\n\nexport type AgentWebhooksResource = ReturnType<typeof createAgentWebhooksResource>\n","import type { HttpClient } from '../http'\nimport type { Agent, AgentCreateInput, AgentUpdateInput } from '../types'\nimport { createAgentWebhooksResource, type AgentWebhooksResource } from './agentWebhooks'\n\n// The server returns Agent with `apiKey` stripped and `hasApiKey: boolean`\n// on the model. We type the happy path but keep our input type permissive\n// so consumers can POST a plaintext `apiKey` that the server encrypts +\n// swaps for `apiKeySecret` on persistence.\n\nexport const createAgentsResource = (http: HttpClient) => {\n const agents = {\n create: async (input: AgentCreateInput): Promise<Agent> =>\n http.request<Agent>({ method: 'POST', path: '/v1/agents', body: input }),\n\n list: async (): Promise<Agent[]> => {\n const res = await http.request<{ data: Agent[] }>({ method: 'GET', path: '/v1/agents' })\n return res.data\n },\n\n // Async iterator for \"give me every agent\" — v1 server returns the full\n // list in one page, so this is just a thin convenience. When the server\n // picks up cursor pagination, this is the method that papers over that\n // migration without consumer changes.\n listAll: async function* (): AsyncIterable<Agent> {\n const page = await agents.list()\n for (const a of page) yield a\n },\n\n get: async (agentId: string): Promise<Agent> =>\n http.request<Agent>({ method: 'GET', path: `/v1/agents/${agentId}` }),\n\n update: async (agentId: string, patch: AgentUpdateInput): Promise<Agent> =>\n http.request<Agent>({ method: 'PATCH', path: `/v1/agents/${agentId}`, body: patch }),\n\n delete: async (agentId: string): Promise<void> =>\n http.request<void>({ method: 'DELETE', path: `/v1/agents/${agentId}` }),\n\n /**\n * Upload an avatar image for the agent. Server re-encodes to a 512×512\n * WebP and stores it in the public-read avatars bucket; the returned\n * `Agent` has `avatarUrl` set to the canonical public URL with a\n * `?v=` cache-buster.\n *\n * `file` accepts a Node Buffer / Uint8Array / Blob / typed-array.\n * `filename` and `contentType` are optional but help the server log\n * meaningful errors when something rejects.\n */\n uploadAvatar: async (\n agentId: string,\n file: Buffer | Uint8Array | Blob | ArrayBuffer,\n opts: { filename?: string; contentType?: string } = {},\n ): Promise<Agent> => {\n const fd = new FormData()\n const blob =\n file instanceof Blob\n ? file\n : // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new Blob([file as any], { type: opts.contentType ?? 'application/octet-stream' })\n fd.append('file', blob, opts.filename ?? 'avatar')\n return http.request<Agent>({\n method: 'POST',\n path: `/v1/agents/${agentId}/avatar`,\n formData: fd,\n })\n },\n\n /**\n * Remove the agent's avatar — both the GCS object and the `avatarUrl`\n * field. Idempotent: calling on an agent without an avatar still\n * returns the agent.\n */\n removeAvatar: async (agentId: string): Promise<Agent> =>\n http.request<Agent>({ method: 'DELETE', path: `/v1/agents/${agentId}/avatar` }),\n\n // Nested resource. Per-agent webhook CRUD lives at\n // /v1/agents/:agentId/webhooks/* — we expose it as a factory keyed on\n // agentId so consumers can bind once and reuse:\n //\n // const hooks = client.agents.webhooks(myAgentId)\n // await hooks.create({ url, events })\n // await hooks.list()\n webhooks: (agentId: string): AgentWebhooksResource =>\n createAgentWebhooksResource(http, agentId),\n }\n return agents\n}\n\nexport type AgentsResource = ReturnType<typeof createAgentsResource>\n","import type { HttpClient } from '../http'\nimport type {\n CallListFilters,\n CallRecord,\n CallRecordingUrlResponse,\n CallSummary,\n TranscriptTurn,\n} from '../types'\n\nexport const createCallsResource = (http: HttpClient) => {\n const calls = {\n list: async (filters: CallListFilters = {}): Promise<CallSummary[]> => {\n const res = await http.request<{ data: CallSummary[] }>({\n method: 'GET',\n path: '/v1/calls',\n query: filters as Record<string, string | number | undefined>,\n })\n return res.data\n },\n\n // Auto-pagination helper. v1 server caps at limit (max 200) in a single\n // page — consumers who ask for \"every call since X\" get that page, the\n // iterator ends. This is the shape we'd extend with cursor support\n // without breaking callers.\n listAll: async function* (filters: CallListFilters = {}): AsyncIterable<CallSummary> {\n const page = await calls.list(filters)\n for (const c of page) yield c\n },\n\n get: async (callId: string): Promise<CallRecord> =>\n http.request<CallRecord>({ method: 'GET', path: `/v1/calls/${callId}` }),\n\n transcript: async (callId: string): Promise<{ callId: string; transcript: TranscriptTurn[] }> =>\n http.request<{ callId: string; transcript: TranscriptTurn[] }>({\n method: 'GET',\n path: `/v1/calls/${callId}/transcript`,\n }),\n\n // Returns a V4 signed URL (1-hour TTL). `ready: false` + `artifact:\n // 'caller-raw'` means the async mix job hasn't finished — the URL still\n // points at a playable file (raw caller PCM).\n recording: async (callId: string): Promise<CallRecordingUrlResponse> =>\n http.request<CallRecordingUrlResponse>({\n method: 'GET',\n path: `/v1/calls/${callId}/recording`,\n }),\n\n // Outbound dialling (POST /v1/calls) + in-call control are Phase 1.4.4 /\n // 1.4.5 respectively — blocked on telephony. Surface clear \"not built\n // yet\" errors here if consumers guess those method names, so they don't\n // silently hit a non-existent endpoint and wonder why it 404s.\n }\n return calls\n}\n\nexport type CallsResource = ReturnType<typeof createCallsResource>\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport type { HttpClient } from '../http'\nimport type { KnowledgeBase, KnowledgeBaseFile } from '../types'\n\nexport const createKnowledgeBasesResource = (http: HttpClient) => ({\n create: async (name: string): Promise<KnowledgeBase> =>\n http.request<KnowledgeBase>({\n method: 'POST',\n path: '/v1/knowledge-bases',\n body: { name },\n }),\n\n list: async (): Promise<KnowledgeBase[]> => {\n const res = await http.request<{ data: KnowledgeBase[] }>({\n method: 'GET',\n path: '/v1/knowledge-bases',\n })\n return res.data\n },\n\n get: async (kbId: string): Promise<KnowledgeBase> =>\n http.request<KnowledgeBase>({ method: 'GET', path: `/v1/knowledge-bases/${kbId}` }),\n\n delete: async (kbId: string): Promise<void> =>\n http.request<void>({ method: 'DELETE', path: `/v1/knowledge-bases/${kbId}` }),\n\n // File upload — accepts either a local file path OR raw bytes + filename.\n // The server ingests synchronously today (Phase 3.1.4 Cloud Tasks is a\n // followup), so the returned file has status='ready' in most cases.\n uploadFile: async (\n kbId: string,\n source:\n | { path: string; filename?: string; mimeType?: string }\n | { data: Buffer | Uint8Array; filename: string; mimeType?: string },\n ): Promise<KnowledgeBaseFile> => {\n const form = new FormData()\n let blob: Blob\n let filename: string\n let mime: string\n\n if ('path' in source) {\n const buf = await fs.promises.readFile(source.path)\n filename = source.filename ?? path.basename(source.path)\n mime = source.mimeType ?? 'application/octet-stream'\n blob = new Blob([new Uint8Array(buf)], { type: mime })\n } else {\n filename = source.filename\n mime = source.mimeType ?? 'application/octet-stream'\n const bytes = source.data instanceof Buffer ? new Uint8Array(source.data) : source.data\n blob = new Blob([bytes], { type: mime })\n }\n form.append('file', blob, filename)\n\n // File uploads can take a while (OCR, chunking, embedding) — give them\n // room before timing out. 5 min cap matches the server's own\n // processing budget.\n return http.request<KnowledgeBaseFile>({\n method: 'POST',\n path: `/v1/knowledge-bases/${kbId}/files`,\n formData: form,\n timeoutMs: 5 * 60 * 1000,\n })\n },\n\n listFiles: async (kbId: string): Promise<KnowledgeBaseFile[]> => {\n const res = await http.request<{ data: KnowledgeBaseFile[] }>({\n method: 'GET',\n path: `/v1/knowledge-bases/${kbId}/files`,\n })\n return res.data\n },\n\n deleteFile: async (kbId: string, fileId: string): Promise<void> =>\n http.request<void>({\n method: 'DELETE',\n path: `/v1/knowledge-bases/${kbId}/files/${fileId}`,\n }),\n})\n\nexport type KnowledgeBasesResource = ReturnType<typeof createKnowledgeBasesResource>\n","import type { HttpClient } from '../http'\nimport type { LedgerEntry } from '../types'\n\nexport const createCreditsResource = (http: HttpClient) => {\n const credits = {\n getBalance: async (): Promise<{ orgId: string; balanceCents: number }> =>\n http.request<{ orgId: string; balanceCents: number }>({\n method: 'GET',\n path: '/v1/credits/balance',\n }),\n\n // Returns ledger entries newest-first. `limit` is capped at 500 server-side.\n getLedger: async (opts: { limit?: number } = {}): Promise<LedgerEntry[]> => {\n const res = await http.request<{ data: LedgerEntry[] }>({\n method: 'GET',\n path: '/v1/credits/ledger',\n query: opts as Record<string, string | number | undefined>,\n })\n return res.data\n },\n\n // Auto-pagination scaffold — v1 server returns a single page up to\n // limit=500. When cursor pagination lands this is where it gets wired.\n getLedgerAll: async function* (opts: { limit?: number } = {}): AsyncIterable<LedgerEntry> {\n const page = await credits.getLedger(opts)\n for (const e of page) yield e\n },\n }\n return credits\n}\n\nexport type CreditsResource = ReturnType<typeof createCreditsResource>\n","import type { HttpClient } from '../http'\nimport type { CallTokenMintInput, CallTokenMintResult, CallTokenSummary } from '../types'\n\n// Short-lived, agent-scoped `ct_` tokens. Mint one per user session on your\n// backend, hand the raw value to the browser; let this SDK handle lifecycle\n// (revoke on sign-out, list active tokens for an admin panel).\n\nexport const createCallTokensResource = (http: HttpClient) => ({\n // Returns the RAW token value once. Don't log it; pass it straight to the\n // browser + discard server-side. `tokenId` is the stable public handle\n // used for revocation later.\n mint: async (input: CallTokenMintInput): Promise<CallTokenMintResult> =>\n http.request<CallTokenMintResult>({\n method: 'POST',\n path: '/v1/call-tokens',\n body: input,\n }),\n\n // Live tokens only by default. Pass includeRevoked/includeExpired when\n // debugging \"why did my token stop working\".\n list: async (\n opts: { includeRevoked?: boolean; includeExpired?: boolean; limit?: number } = {},\n ): Promise<CallTokenSummary[]> => {\n const query: Record<string, string | number | undefined> = {}\n if (opts.includeRevoked) query.includeRevoked = '1'\n if (opts.includeExpired) query.includeExpired = '1'\n if (opts.limit !== undefined) query.limit = opts.limit\n const res = await http.request<{ data: CallTokenSummary[] }>({\n method: 'GET',\n path: '/v1/call-tokens',\n query,\n })\n return res.data\n },\n\n // Idempotent — re-revoking a revoked token returns `alreadyRevoked: true`.\n revoke: async (\n tokenId: string,\n ): Promise<{ tokenId: string; revoked: boolean; alreadyRevoked?: boolean }> =>\n http.request<{ tokenId: string; revoked: boolean; alreadyRevoked?: boolean }>({\n method: 'DELETE',\n path: `/v1/call-tokens/${tokenId}`,\n }),\n})\n\nexport type CallTokensResource = ReturnType<typeof createCallTokensResource>\n","import type { HttpClient } from '../http'\nimport type { WebhookDelivery } from '../types'\n\n// Org-wide webhook delivery log. Per-agent CRUD lives on\n// `client.agents.webhooks(agentId)` — this namespace is just the\n// read-only deliveries surface that spans all agents.\n\nexport const createWebhooksResource = (http: HttpClient) => ({\n deliveries: async (\n filters: {\n agentId?: string\n webhookId?: string\n callId?: string\n limit?: number\n } = {},\n ): Promise<WebhookDelivery[]> => {\n const res = await http.request<{ data: WebhookDelivery[] }>({\n method: 'GET',\n path: '/v1/webhooks/deliveries',\n query: filters as Record<string, string | number | undefined>,\n })\n return res.data\n },\n})\n\nexport type WebhooksResource = ReturnType<typeof createWebhooksResource>\n","import type { HttpClient } from '../http'\nimport type { CatalogAgent, CatalogListInput } from '../types'\n\n// Org-scoped consumer endpoints. Today this is just the agent catalog —\n// the trimmed shape your mobile app picks an agent from. Lives at\n// `/v1/orgs/:orgId/agents` rather than reusing the admin `/v1/agents/*`\n// tree on purpose: the catalog response intentionally excludes the\n// operator-only fields (system prompt, tools, KB IDs) so a leaked\n// consumer-backend `sk_` can't lift the operator config out of it.\n//\n// Pattern from your backend:\n//\n// const client = new PlatformClient({ apiKey: process.env.SK })\n// const visible = await client.orgs.listAgents({\n// orgId: process.env.ORG_ID!,\n// userTags: ['tier1'], // omit to get the unfiltered admin view\n// })\n// res.json(visible)\n\nexport const createOrgsResource = (http: HttpClient) => ({\n /**\n * Fetch the agent catalog for an org. Returns the consumer-trimmed shape;\n * no system prompt, tools, or KB info. Use `client.agents.get(agentId)`\n * with the same `sk_` if you need the full admin shape.\n *\n * `userTags`: end-user entitlement tags. When supplied, hides agents\n * whose `allowedUserTags` is non-empty and doesn't intersect with the\n * supplied list. Omit to get the unfiltered admin view.\n *\n * Persona / category filtering is intentionally not a server param —\n * filter the returned list client-side over `name`s if you need it.\n *\n * Throws `403 forbidden` if `orgId` doesn't match the key's org.\n */\n listAgents: async (input: CatalogListInput): Promise<CatalogAgent[]> => {\n const query: Record<string, string | undefined> = {}\n if (input.userTags && input.userTags.length > 0) query.userTags = input.userTags.join(',')\n const res = await http.request<{ data: CatalogAgent[] }>({\n method: 'GET',\n path: `/v1/orgs/${input.orgId}/agents`,\n query,\n })\n return res.data\n },\n})\n\nexport type OrgsResource = ReturnType<typeof createOrgsResource>\n","import type { HttpClient } from '../http'\nimport type {\n CreateRoomInput,\n CreateRoomResponse,\n ListRoomsResponse,\n ListUtterancesResponse,\n RoomDoc,\n RoomEventAck,\n RoomListFilters,\n RoomTranscriptOptions,\n} from '../types'\n\n// REST wrappers for /v1/rooms — the multi-party video room surface (see\n// docs/superpowers/specs/2026-05-18-multiparty-rooms-design.md). Lets\n// server-side code mint rooms, fetch state, list transcript pages, and end\n// rooms programmatically.\n//\n// Auth model: same Bearer `sk_` flow as every other resource — the server\n// derives `orgId` from the API key, so the SDK never sets a tenant header.\n//\n// Host actions beyond `end` (promote/demote/kick) and observer-token mint\n// live in the server but aren't surfaced here yet — they're operator-side\n// flows that the dashboard hits directly. Re-add here if a programmatic\n// use-case shows up (CI tests, integration harnesses).\n\nexport const createRoomsResource = (http: HttpClient) => ({\n // Provision a new room. Server returns 201 with ONE shared room-level\n // `joinToken` + `joinUrl`. Share the single link with everyone you want in\n // the room — each visitor supplies their own display name at join time and\n // becomes a fresh, distinct participant. The server persists only the\n // token's sha256 hash; the raw token is returned here once and never stored.\n create: async (input: CreateRoomInput): Promise<CreateRoomResponse> =>\n http.request<CreateRoomResponse>({\n method: 'POST',\n path: '/v1/rooms',\n body: input,\n }),\n\n // Listing — opaque cursor pagination (`nextCursor` returned by the server\n // is whatever startAfter() needs, don't parse client-side).\n list: async (filters: RoomListFilters = {}): Promise<ListRoomsResponse> => {\n const query: Record<string, string | number | undefined> = {}\n if (filters.status) query.status = filters.status\n if (filters.limit !== undefined) query.limit = filters.limit\n if (filters.cursor) query.cursor = filters.cursor\n return http.request<ListRoomsResponse>({\n method: 'GET',\n path: '/v1/rooms',\n query,\n })\n },\n\n // Fetch a single room. 404s are surfaced as PlatformError('not_found').\n get: async (roomId: string): Promise<RoomDoc> =>\n http.request<RoomDoc>({\n method: 'GET',\n path: `/v1/rooms/${roomId}`,\n }),\n\n // Transcript pages — utterances are ordered by `startedAt asc`. Cursor is\n // an ISO timestamp (server enforces, don't construct yourself).\n transcript: async (\n roomId: string,\n opts: RoomTranscriptOptions = {},\n ): Promise<ListUtterancesResponse> => {\n const query: Record<string, string | number | undefined> = {}\n if (opts.cursor) query.cursor = opts.cursor\n if (opts.limit !== undefined) query.limit = opts.limit\n return http.request<ListUtterancesResponse>({\n method: 'GET',\n path: `/v1/rooms/${roomId}/transcript`,\n query,\n })\n },\n\n // End a room — async on the server: returns 202 + eventId once the\n // controlEvents entry is written. The room-worker observes the entry,\n // broadcasts the system message, and tears down LiveKit shortly after.\n end: async (roomId: string): Promise<RoomEventAck> =>\n http.request<RoomEventAck>({\n method: 'POST',\n path: `/v1/rooms/${roomId}/end`,\n }),\n})\n\nexport type RoomsResource = ReturnType<typeof createRoomsResource>\n","import type { HttpClient } from '../http'\nimport type { ChatEvent } from '../types'\n\nexport interface StartChatInput {\n agentId: string\n text?: string\n}\n\nexport interface Chat {\n id: string\n callId: string\n greeting: AsyncIterable<ChatEvent>\n send(text: string): AsyncIterable<ChatEvent>\n end(): Promise<void>\n}\n\n/**\n * Per-token chat resource. Construct via `client.chatsFor(callToken)` —\n * `callToken` is a raw `ct_…` minted with `channel: 'text'`.\n *\n * The async iterables stream SSE events: `chat.started` (start only),\n * then a sequence of `token` / `tool.call` / `tool.result` / `error`,\n * then `turn.end` which closes the stream. The client must NOT keep\n * a connection open between turns — each `send` is a fresh POST.\n */\nexport const createChatsResource = (http: HttpClient, callToken: string) => ({\n async start(input: StartChatInput): Promise<Chat> {\n const tokenQs = `?token=${encodeURIComponent(callToken)}`\n const streamIterable = http.stream<ChatEvent>({\n method: 'POST',\n path: `/v1/agents/${input.agentId}/chat${tokenQs}`,\n body: input.text ? { text: input.text } : {},\n })\n\n // Pull events from the stream until we see chat.started — that's our\n // first event and carries the ids. Pass the rest through as `greeting`.\n let chatId = ''\n let callId = ''\n const buffered: ChatEvent[] = []\n const iter = streamIterable[Symbol.asyncIterator]()\n while (true) {\n const { value, done } = await iter.next()\n if (done) break\n if (value.type === 'chat.started') {\n chatId = value.chatId\n callId = value.callId\n break\n }\n buffered.push(value)\n }\n\n return {\n id: chatId,\n callId,\n greeting: replayThen(buffered, { [Symbol.asyncIterator]: () => iter }),\n send(text: string) {\n return http.stream<ChatEvent>({\n method: 'POST',\n path: `/v1/chats/${chatId}/messages${tokenQs}`,\n body: { text },\n })\n },\n async end() {\n await http.request({ method: 'DELETE', path: `/v1/calls/${callId}` })\n },\n }\n },\n})\n\nasync function* replayThen<T>(buffered: T[], rest: AsyncIterable<T>): AsyncIterable<T> {\n for (const x of buffered) yield x\n for await (const x of rest) yield x\n}\n\nexport type ChatsResource = ReturnType<typeof createChatsResource>\n","import { createHttpClient, type HttpClient, type HttpClientOptions } from './http'\nimport { createMeResource, type MeResource } from './resources/me'\nimport { createAgentsResource, type AgentsResource } from './resources/agents'\nimport { createCallsResource, type CallsResource } from './resources/calls'\nimport {\n createKnowledgeBasesResource,\n type KnowledgeBasesResource,\n} from './resources/knowledgeBases'\nimport { createCreditsResource, type CreditsResource } from './resources/credits'\nimport { createCallTokensResource, type CallTokensResource } from './resources/callTokens'\nimport { createWebhooksResource, type WebhooksResource } from './resources/webhooks'\nimport { createOrgsResource, type OrgsResource } from './resources/orgs'\nimport { createRoomsResource, type RoomsResource } from './resources/rooms'\nimport { createChatsResource, type ChatsResource } from './resources/chats'\n\nexport interface PlatformClientOptions {\n // Full-org API key minted from the dashboard or bootstrap CLI. Start with\n // `sk_`. Never ship to a browser — use `client.callTokens.mint(...)` to\n // generate a narrow `ct_` token for client-side use instead.\n apiKey: string\n // Defaults to the hosted platform. Point at `http://localhost:8080` for\n // local dev or at a self-hosted deployment.\n baseUrl?: string\n // Passthrough tuning for the HTTP layer.\n timeoutMs?: number\n maxRetries?: number\n fetch?: HttpClientOptions['fetch']\n onRequest?: HttpClientOptions['onRequest']\n}\n\n// Single entry point. All resources are lazy-constructed in the constructor\n// so their refs don't incur any per-call allocation. Shape mirrors Stripe /\n// Twilio / Vapi's `resource.method()` convention for familiarity.\nexport class PlatformClient {\n readonly me: MeResource\n readonly agents: AgentsResource\n readonly calls: CallsResource\n readonly knowledgeBases: KnowledgeBasesResource\n readonly credits: CreditsResource\n readonly callTokens: CallTokensResource\n readonly webhooks: WebhooksResource\n readonly orgs: OrgsResource\n readonly rooms: RoomsResource\n private readonly _http: HttpClient\n\n constructor(options: PlatformClientOptions) {\n if (!options.apiKey) {\n throw new Error('PlatformClient: `apiKey` is required')\n }\n const http = createHttpClient({\n apiKey: options.apiKey,\n baseUrl: options.baseUrl ?? 'https://api.example.com',\n timeoutMs: options.timeoutMs,\n maxRetries: options.maxRetries,\n fetch: options.fetch,\n onRequest: options.onRequest,\n })\n\n this.me = createMeResource(http)\n this.agents = createAgentsResource(http)\n this.calls = createCallsResource(http)\n this.knowledgeBases = createKnowledgeBasesResource(http)\n this.credits = createCreditsResource(http)\n this.callTokens = createCallTokensResource(http)\n this.webhooks = createWebhooksResource(http)\n this.orgs = createOrgsResource(http)\n this.rooms = createRoomsResource(http)\n this._http = http\n }\n\n /**\n * Returns a per-token chat resource bound to the given `ct_…` call token.\n * The token must have been minted with `channel: 'text'`.\n *\n * Note: `chatsFor` is a factory method (not a fixed property) because the\n * underlying resource is scoped to a single call token, whereas this client\n * was constructed with an `sk_` admin key. Each end-user session needs its\n * own `chatsFor(token)` handle.\n */\n public chatsFor(callToken: string): ChatsResource {\n return createChatsResource(this._http, callToken)\n }\n}\n","import crypto from 'node:crypto'\n\n// Helper for consumers receiving webhooks: verify the `X-Platform-Signature-256`\n// header against the raw body + secret. Plain function (not tied to\n// PlatformClient) so Express/Koa/Next.js middleware can use it without\n// instantiating a client.\n//\n// import { verifyWebhookSignature } from '@craftedxp/sdk-node'\n// app.post('/webhooks/voice-agent', express.raw({ type: 'application/json' }), (req, res) => {\n// const sig = req.header('X-Platform-Signature-256') ?? ''\n// if (!verifyWebhookSignature(req.body, sig, process.env.VOICE_AGENT_WEBHOOK_SECRET!)) {\n// return res.status(401).send('invalid signature')\n// }\n// const event = JSON.parse(req.body.toString('utf8'))\n// // ...handle event\n// })\n//\n// The signature is `sha256=<hex HMAC-SHA256 of rawBody with secret>`.\n// Timing-safe compare to avoid microtiming side channels.\n\nexport const verifyWebhookSignature = (\n rawBody: Buffer | string,\n signatureHeader: string,\n secret: string,\n): boolean => {\n if (!signatureHeader || !secret) return false\n const [algo, provided] = signatureHeader.split('=')\n if (algo !== 'sha256' || !provided) return false\n\n const expected = crypto\n .createHmac('sha256', secret)\n .update(typeof rawBody === 'string' ? rawBody : rawBody)\n .digest('hex')\n\n // Buffers must match in length for timingSafeEqual.\n const a = Buffer.from(expected, 'hex')\n const b = Buffer.from(provided, 'hex')\n if (a.length !== b.length) return false\n return crypto.timingSafeEqual(a, b)\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACmBO,IAAM,gBAAN,MAA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QAAQ;AAAA,MACpB,OAAO,QAAQ;AAAA,MACf,WAAW,QAAQ;AAAA,IACrB,CAAC;AAED,SAAK,KAAK,iBAAiB,IAAI;AAC/B,SAAK,SAAS,qBAAqB,IAAI;AACvC,SAAK,QAAQ,oBAAoB,IAAI;AACrC,SAAK,iBAAiB,6BAA6B,IAAI;AACvD,SAAK,UAAU,sBAAsB,IAAI;AACzC,SAAK,aAAa,yBAAyB,IAAI;AAC/C,SAAK,WAAW,uBAAuB,IAAI;AAC3C,SAAK,OAAO,mBAAmB,IAAI;AACnC,SAAK,QAAQ,oBAAoB,IAAI;AACrC,SAAK,QAAQ;AAAA,EACf;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWO,SAAS,WAAkC;AAChD,WAAO,oBAAoB,KAAK,OAAO,SAAS;AAAA,EAClD;AACF;;;AClFA,yBAAmB;AAoBZ,IAAM,yBAAyB,CACpC,SACA,iBACA,WACY;AACZ,MAAI,CAAC,mBAAmB,CAAC,OAAQ,QAAO;AACxC,QAAM,CAAC,MAAM,QAAQ,IAAI,gBAAgB,MAAM,GAAG;AAClD,MAAI,SAAS,YAAY,CAAC,SAAU,QAAO;AAE3C,QAAM,WAAW,mBAAAC,QACd,WAAW,UAAU,MAAM,EAC3B,OAAO,OAAO,YAAY,WAAW,UAAU,OAAO,EACtD,OAAO,KAAK;AAGf,QAAM,IAAI,OAAO,KAAK,UAAU,KAAK;AACrC,QAAM,IAAI,OAAO,KAAK,UAAU,KAAK;AACrC,MAAI,EAAE,WAAW,EAAE,OAAQ,QAAO;AAClC,SAAO,mBAAAA,QAAO,gBAAgB,GAAG,CAAC;AACpC;","names":["path","fs","path","crypto"]}
|
package/dist/index.mjs
CHANGED
|
@@ -141,7 +141,82 @@ var createHttpClient = (opts) => {
|
|
|
141
141
|
}
|
|
142
142
|
throw lastErr instanceof Error ? lastErr : new Error("request exhausted retries");
|
|
143
143
|
};
|
|
144
|
-
|
|
144
|
+
async function* stream(req) {
|
|
145
|
+
const url = buildUrl(opts.baseUrl, req.path, req.query);
|
|
146
|
+
const headers = {
|
|
147
|
+
Authorization: `Bearer ${opts.apiKey}`,
|
|
148
|
+
"Content-Type": "application/json",
|
|
149
|
+
Accept: "text/event-stream",
|
|
150
|
+
...req.headers ?? {}
|
|
151
|
+
};
|
|
152
|
+
const started = Date.now();
|
|
153
|
+
let res;
|
|
154
|
+
try {
|
|
155
|
+
res = await fetchImpl(url, {
|
|
156
|
+
method: req.method,
|
|
157
|
+
headers,
|
|
158
|
+
body: req.body !== void 0 ? JSON.stringify(req.body) : void 0
|
|
159
|
+
});
|
|
160
|
+
} catch (err) {
|
|
161
|
+
const msg = err instanceof Error ? err.message : "network error";
|
|
162
|
+
throw new PlatformError({
|
|
163
|
+
code: "unknown",
|
|
164
|
+
message: `Network error: ${msg}`,
|
|
165
|
+
status: 0
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
opts.onRequest?.({
|
|
169
|
+
method: req.method,
|
|
170
|
+
url,
|
|
171
|
+
status: res.status,
|
|
172
|
+
durationMs: Date.now() - started,
|
|
173
|
+
attempt: 1
|
|
174
|
+
});
|
|
175
|
+
if (!res.ok || !res.body) {
|
|
176
|
+
const text = await res.text().catch(() => "");
|
|
177
|
+
let parsed = void 0;
|
|
178
|
+
try {
|
|
179
|
+
parsed = text ? JSON.parse(text) : void 0;
|
|
180
|
+
} catch {
|
|
181
|
+
}
|
|
182
|
+
const errObj = parsed?.error;
|
|
183
|
+
throw new PlatformError({
|
|
184
|
+
code: errObj?.code ?? "unknown",
|
|
185
|
+
message: errObj?.message ?? res.statusText ?? `HTTP ${res.status}`,
|
|
186
|
+
status: res.status,
|
|
187
|
+
field: errObj?.field,
|
|
188
|
+
docsUrl: errObj?.docs_url,
|
|
189
|
+
body: parsed ?? text
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
const reader = res.body.getReader();
|
|
193
|
+
const decoder = new TextDecoder();
|
|
194
|
+
let buf = "";
|
|
195
|
+
while (true) {
|
|
196
|
+
const { value, done } = await reader.read();
|
|
197
|
+
if (done) return;
|
|
198
|
+
buf += decoder.decode(value, { stream: true });
|
|
199
|
+
let idx;
|
|
200
|
+
while ((idx = buf.indexOf("\n\n")) >= 0) {
|
|
201
|
+
const block = buf.slice(0, idx);
|
|
202
|
+
buf = buf.slice(idx + 2);
|
|
203
|
+
let event = "message";
|
|
204
|
+
let data = "";
|
|
205
|
+
for (const line of block.split("\n")) {
|
|
206
|
+
if (line.startsWith(":")) continue;
|
|
207
|
+
if (line.startsWith("event:")) event = line.slice(6).trim();
|
|
208
|
+
else if (line.startsWith("data:")) data += line.slice(5).trim();
|
|
209
|
+
}
|
|
210
|
+
if (!data) continue;
|
|
211
|
+
try {
|
|
212
|
+
const parsed = JSON.parse(data);
|
|
213
|
+
yield { type: event, ...parsed };
|
|
214
|
+
} catch {
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
return { request, stream };
|
|
145
220
|
};
|
|
146
221
|
|
|
147
222
|
// src/resources/me.ts
|
|
@@ -495,6 +570,51 @@ var createRoomsResource = (http) => ({
|
|
|
495
570
|
})
|
|
496
571
|
});
|
|
497
572
|
|
|
573
|
+
// src/resources/chats.ts
|
|
574
|
+
var createChatsResource = (http, callToken) => ({
|
|
575
|
+
async start(input) {
|
|
576
|
+
const tokenQs = `?token=${encodeURIComponent(callToken)}`;
|
|
577
|
+
const streamIterable = http.stream({
|
|
578
|
+
method: "POST",
|
|
579
|
+
path: `/v1/agents/${input.agentId}/chat${tokenQs}`,
|
|
580
|
+
body: input.text ? { text: input.text } : {}
|
|
581
|
+
});
|
|
582
|
+
let chatId = "";
|
|
583
|
+
let callId = "";
|
|
584
|
+
const buffered = [];
|
|
585
|
+
const iter = streamIterable[Symbol.asyncIterator]();
|
|
586
|
+
while (true) {
|
|
587
|
+
const { value, done } = await iter.next();
|
|
588
|
+
if (done) break;
|
|
589
|
+
if (value.type === "chat.started") {
|
|
590
|
+
chatId = value.chatId;
|
|
591
|
+
callId = value.callId;
|
|
592
|
+
break;
|
|
593
|
+
}
|
|
594
|
+
buffered.push(value);
|
|
595
|
+
}
|
|
596
|
+
return {
|
|
597
|
+
id: chatId,
|
|
598
|
+
callId,
|
|
599
|
+
greeting: replayThen(buffered, { [Symbol.asyncIterator]: () => iter }),
|
|
600
|
+
send(text) {
|
|
601
|
+
return http.stream({
|
|
602
|
+
method: "POST",
|
|
603
|
+
path: `/v1/chats/${chatId}/messages${tokenQs}`,
|
|
604
|
+
body: { text }
|
|
605
|
+
});
|
|
606
|
+
},
|
|
607
|
+
async end() {
|
|
608
|
+
await http.request({ method: "DELETE", path: `/v1/calls/${callId}` });
|
|
609
|
+
}
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
});
|
|
613
|
+
async function* replayThen(buffered, rest) {
|
|
614
|
+
for (const x of buffered) yield x;
|
|
615
|
+
for await (const x of rest) yield x;
|
|
616
|
+
}
|
|
617
|
+
|
|
498
618
|
// src/PlatformClient.ts
|
|
499
619
|
var PlatformClient = class {
|
|
500
620
|
me;
|
|
@@ -506,6 +626,7 @@ var PlatformClient = class {
|
|
|
506
626
|
webhooks;
|
|
507
627
|
orgs;
|
|
508
628
|
rooms;
|
|
629
|
+
_http;
|
|
509
630
|
constructor(options) {
|
|
510
631
|
if (!options.apiKey) {
|
|
511
632
|
throw new Error("PlatformClient: `apiKey` is required");
|
|
@@ -527,6 +648,19 @@ var PlatformClient = class {
|
|
|
527
648
|
this.webhooks = createWebhooksResource(http);
|
|
528
649
|
this.orgs = createOrgsResource(http);
|
|
529
650
|
this.rooms = createRoomsResource(http);
|
|
651
|
+
this._http = http;
|
|
652
|
+
}
|
|
653
|
+
/**
|
|
654
|
+
* Returns a per-token chat resource bound to the given `ct_…` call token.
|
|
655
|
+
* The token must have been minted with `channel: 'text'`.
|
|
656
|
+
*
|
|
657
|
+
* Note: `chatsFor` is a factory method (not a fixed property) because the
|
|
658
|
+
* underlying resource is scoped to a single call token, whereas this client
|
|
659
|
+
* was constructed with an `sk_` admin key. Each end-user session needs its
|
|
660
|
+
* own `chatsFor(token)` handle.
|
|
661
|
+
*/
|
|
662
|
+
chatsFor(callToken) {
|
|
663
|
+
return createChatsResource(this._http, callToken);
|
|
530
664
|
}
|
|
531
665
|
};
|
|
532
666
|
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/http.ts","../src/resources/me.ts","../src/resources/agentWebhooks.ts","../src/resources/agents.ts","../src/resources/calls.ts","../src/resources/knowledgeBases.ts","../src/resources/credits.ts","../src/resources/callTokens.ts","../src/resources/webhooks.ts","../src/resources/orgs.ts","../src/resources/rooms.ts","../src/PlatformClient.ts","../src/verify.ts"],"sourcesContent":["// Typed error class mirroring the server's ErrorV1 shape:\n// { error: { code, message, field?, docs_url? } }\n//\n// Consumers do `err instanceof PlatformError` to branch on code without\n// parsing string messages. `status` carries the HTTP code for the 1% of\n// cases where the code field isn't enough (e.g. rate-limit → retry-after\n// header correlation).\n\nexport type ApiErrorCode =\n | 'unauthorized'\n | 'forbidden'\n | 'not_found'\n | 'bad_request'\n | 'conflict'\n | 'rate_limited'\n | 'payment_required'\n | 'internal_error'\n | 'unknown'\n\nexport class PlatformError extends Error {\n readonly code: ApiErrorCode\n readonly status: number\n readonly field?: string\n readonly docsUrl?: string\n // The raw response body for debugging. Intentionally optional — we clear\n // it on `error.toJSON()` so logging libraries don't dump the whole\n // server response into production logs.\n readonly body?: unknown\n\n constructor(params: {\n code: ApiErrorCode\n message: string\n status: number\n field?: string\n docsUrl?: string\n body?: unknown\n }) {\n super(params.message)\n this.name = 'PlatformError'\n this.code = params.code\n this.status = params.status\n this.field = params.field\n this.docsUrl = params.docsUrl\n this.body = params.body\n // Preserve the stack trace — Node's Error doesn't capture it\n // automatically when subclassing in some older runtimes.\n if (\n typeof (Error as typeof Error & { captureStackTrace?: unknown }).captureStackTrace ===\n 'function'\n ) {\n ;(\n Error as typeof Error & { captureStackTrace: (target: unknown, ctor: unknown) => void }\n ).captureStackTrace(this, PlatformError)\n }\n }\n\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n status: this.status,\n field: this.field,\n docsUrl: this.docsUrl,\n }\n }\n}\n","import { PlatformError, type ApiErrorCode } from './errors'\n\n// Low-level HTTP wrapper around `fetch` (native in Node 18+). Every resource\n// method routes through here for consistent auth + error handling + retries.\n//\n// v1 scope: JSON-in / JSON-out + multipart for file uploads. No streaming —\n// call WebSockets go through @craftedxp/voice-rn (the React Native client)\n// or a web equivalent, not this server-side SDK.\n\nexport interface HttpClientOptions {\n apiKey: string\n baseUrl: string\n // Default 30s. File uploads can override per-request.\n timeoutMs?: number\n // 429 + 5xx retries. Defaults to 3 attempts (original + 2 retries) with\n // exponential backoff (250ms, 1s). Set to 0 to disable.\n maxRetries?: number\n // Optional — lets consumers swap in a test/mock fetch (or a custom one\n // with instrumentation). Defaults to the global.\n fetch?: typeof fetch\n // Optional — a callback that fires per-request with the final status and\n // duration. Handy for dropping traces into the consumer's observability\n // stack without wrapping each call.\n onRequest?: (info: {\n method: string\n url: string\n status: number\n durationMs: number\n attempt: number\n }) => void\n}\n\nexport interface HttpRequest {\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE'\n path: string // starts with `/`, e.g. `/v1/agents/123`\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown // JSON-serialised — for multipart use `formData`\n formData?: FormData\n timeoutMs?: number\n // Exposed for edge cases where a resource wants to tack on extra\n // headers (we don't have any today but leave the hook).\n headers?: Record<string, string>\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000\nconst DEFAULT_MAX_RETRIES = 2 // total attempts = 3\n\nconst buildUrl = (baseUrl: string, path: string, query?: HttpRequest['query']): string => {\n const u = new URL(path, baseUrl)\n if (query) {\n for (const [k, v] of Object.entries(query)) {\n if (v === undefined) continue\n u.searchParams.set(k, String(v))\n }\n }\n return u.toString()\n}\n\nconst sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))\n\nconst isRetryable = (status: number): boolean => status === 429 || (status >= 500 && status < 600)\n\n// Parse whatever the server returned into a PlatformError. Falls back to\n// synthesising a sensible error for non-JSON responses.\nconst errorFromResponse = async (res: Response): Promise<PlatformError> => {\n const bodyText = await res.text().catch(() => '')\n let parsed: unknown = undefined\n try {\n parsed = bodyText ? JSON.parse(bodyText) : undefined\n } catch {\n // non-JSON response (e.g. an HTML error page from a proxy). Fall\n // through with parsed = undefined.\n }\n const errObj = (\n parsed as { error?: { code?: string; message?: string; field?: string; docs_url?: string } }\n )?.error\n return new PlatformError({\n code: (errObj?.code as ApiErrorCode) ?? 'unknown',\n message: errObj?.message ?? res.statusText ?? `HTTP ${res.status}`,\n status: res.status,\n field: errObj?.field,\n docsUrl: errObj?.docs_url,\n body: parsed ?? bodyText,\n })\n}\n\nexport const createHttpClient = (opts: HttpClientOptions) => {\n const fetchImpl = opts.fetch ?? globalThis.fetch\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const maxRetries = opts.maxRetries ?? DEFAULT_MAX_RETRIES\n\n if (!fetchImpl) {\n throw new Error('No global fetch available. @craftedxp/sdk-node requires Node >= 18.')\n }\n\n const request = async <T>(req: HttpRequest): Promise<T> => {\n const url = buildUrl(opts.baseUrl, req.path, req.query)\n const headers: Record<string, string> = {\n Authorization: `Bearer ${opts.apiKey}`,\n Accept: 'application/json',\n ...(req.headers ?? {}),\n }\n\n // Body shaping: prefer formData when provided; otherwise JSON.\n // `FormData` sets its own Content-Type with boundary — don't preempt it.\n // Typed as `string | FormData | undefined` (a subset of the global\n // BodyInit) so we don't need DOM lib types in this server-side SDK.\n let body: string | FormData | undefined\n if (req.formData) {\n body = req.formData\n } else if (req.body !== undefined) {\n headers['Content-Type'] = 'application/json'\n body = JSON.stringify(req.body)\n }\n\n const reqTimeout = req.timeoutMs ?? timeoutMs\n let lastErr: unknown\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), reqTimeout)\n const started = Date.now()\n try {\n const res = await fetchImpl(url, {\n method: req.method,\n headers,\n body,\n signal: controller.signal,\n })\n const durationMs = Date.now() - started\n opts.onRequest?.({\n method: req.method,\n url,\n status: res.status,\n durationMs,\n attempt: attempt + 1,\n })\n\n if (res.ok) {\n // 204 No Content — some endpoints (DELETE webhooks) return nothing.\n if (res.status === 204) return undefined as T\n const ct = res.headers.get('content-type') ?? ''\n if (ct.includes('application/json')) {\n return (await res.json()) as T\n }\n // Non-JSON 2xx — rare. Return raw text cast as T.\n return (await res.text()) as unknown as T\n }\n\n // Retryable error: back off + retry up to maxRetries.\n if (isRetryable(res.status) && attempt < maxRetries) {\n const retryAfter = res.headers.get('Retry-After')\n const backoff = retryAfter ? Number(retryAfter) * 1000 : 250 * Math.pow(2, attempt)\n await sleep(backoff)\n continue\n }\n\n throw await errorFromResponse(res)\n } catch (err) {\n if (err instanceof PlatformError) throw err\n // AbortError / network / DNS failures — retry up to maxRetries.\n if (attempt < maxRetries) {\n lastErr = err\n await sleep(250 * Math.pow(2, attempt))\n continue\n }\n const msg = err instanceof Error ? err.message : 'network error'\n throw new PlatformError({\n code: 'unknown',\n message: `Network error: ${msg}`,\n status: 0,\n })\n } finally {\n clearTimeout(timer)\n }\n }\n\n // Should be unreachable — the loop either returns, throws, or continues.\n throw lastErr instanceof Error ? lastErr : new Error('request exhausted retries')\n }\n\n return { request }\n}\n\nexport type HttpClient = ReturnType<typeof createHttpClient>\n","import type { HttpClient } from '../http'\nimport type { MeResponse } from '../types'\n\nexport const createMeResource = (http: HttpClient) => ({\n // Smoke test — confirms the API key is valid and returns the org + balance.\n // Most consumers use this as a ping on startup.\n get: async (): Promise<MeResponse> => http.request<MeResponse>({ method: 'GET', path: '/v1/me' }),\n})\n\nexport type MeResource = ReturnType<typeof createMeResource>\n","import type { HttpClient } from '../http'\nimport type {\n WebhookConfig,\n WebhookCreateInput,\n WebhookDelivery,\n WebhookUpdateInput,\n} from '../types'\n\n// Per-agent webhook resource, scoped at factory time to a specific agentId.\n// All endpoints mirror /v1/agents/:agentId/webhooks[/:id].\n\nexport const createAgentWebhooksResource = (http: HttpClient, agentId: string) => ({\n // Returns the webhook + its signing secret. The secret is only present in\n // this response — persist immediately, subsequent GETs omit it. Use the\n // secret to verify `X-Platform-Signature-256` (sha256=hex HMAC over body).\n create: async (input: WebhookCreateInput): Promise<WebhookConfig> =>\n http.request<WebhookConfig>({\n method: 'POST',\n path: `/v1/agents/${agentId}/webhooks`,\n body: input,\n }),\n\n list: async (): Promise<WebhookConfig[]> => {\n const res = await http.request<{ data: WebhookConfig[] }>({\n method: 'GET',\n path: `/v1/agents/${agentId}/webhooks`,\n })\n return res.data\n },\n\n get: async (webhookId: string): Promise<WebhookConfig> =>\n http.request<WebhookConfig>({\n method: 'GET',\n path: `/v1/agents/${agentId}/webhooks/${webhookId}`,\n }),\n\n update: async (webhookId: string, patch: WebhookUpdateInput): Promise<WebhookConfig> =>\n http.request<WebhookConfig>({\n method: 'PATCH',\n path: `/v1/agents/${agentId}/webhooks/${webhookId}`,\n body: patch,\n }),\n\n delete: async (webhookId: string): Promise<void> =>\n http.request<void>({\n method: 'DELETE',\n path: `/v1/agents/${agentId}/webhooks/${webhookId}`,\n }),\n\n // Fires a synthetic call.started against this webhook and returns the\n // full delivery record (including attempt status codes) once the retry\n // sequence has finished. Useful during setup to verify receiver wiring.\n test: async (webhookId: string): Promise<WebhookDelivery> =>\n http.request<WebhookDelivery>({\n method: 'POST',\n path: `/v1/agents/${agentId}/webhooks/${webhookId}/test`,\n }),\n})\n\nexport type AgentWebhooksResource = ReturnType<typeof createAgentWebhooksResource>\n","import type { HttpClient } from '../http'\nimport type { Agent, AgentCreateInput, AgentUpdateInput } from '../types'\nimport { createAgentWebhooksResource, type AgentWebhooksResource } from './agentWebhooks'\n\n// The server returns Agent with `apiKey` stripped and `hasApiKey: boolean`\n// on the model. We type the happy path but keep our input type permissive\n// so consumers can POST a plaintext `apiKey` that the server encrypts +\n// swaps for `apiKeySecret` on persistence.\n\nexport const createAgentsResource = (http: HttpClient) => {\n const agents = {\n create: async (input: AgentCreateInput): Promise<Agent> =>\n http.request<Agent>({ method: 'POST', path: '/v1/agents', body: input }),\n\n list: async (): Promise<Agent[]> => {\n const res = await http.request<{ data: Agent[] }>({ method: 'GET', path: '/v1/agents' })\n return res.data\n },\n\n // Async iterator for \"give me every agent\" — v1 server returns the full\n // list in one page, so this is just a thin convenience. When the server\n // picks up cursor pagination, this is the method that papers over that\n // migration without consumer changes.\n listAll: async function* (): AsyncIterable<Agent> {\n const page = await agents.list()\n for (const a of page) yield a\n },\n\n get: async (agentId: string): Promise<Agent> =>\n http.request<Agent>({ method: 'GET', path: `/v1/agents/${agentId}` }),\n\n update: async (agentId: string, patch: AgentUpdateInput): Promise<Agent> =>\n http.request<Agent>({ method: 'PATCH', path: `/v1/agents/${agentId}`, body: patch }),\n\n delete: async (agentId: string): Promise<void> =>\n http.request<void>({ method: 'DELETE', path: `/v1/agents/${agentId}` }),\n\n /**\n * Upload an avatar image for the agent. Server re-encodes to a 512×512\n * WebP and stores it in the public-read avatars bucket; the returned\n * `Agent` has `avatarUrl` set to the canonical public URL with a\n * `?v=` cache-buster.\n *\n * `file` accepts a Node Buffer / Uint8Array / Blob / typed-array.\n * `filename` and `contentType` are optional but help the server log\n * meaningful errors when something rejects.\n */\n uploadAvatar: async (\n agentId: string,\n file: Buffer | Uint8Array | Blob | ArrayBuffer,\n opts: { filename?: string; contentType?: string } = {},\n ): Promise<Agent> => {\n const fd = new FormData()\n const blob =\n file instanceof Blob\n ? file\n : // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new Blob([file as any], { type: opts.contentType ?? 'application/octet-stream' })\n fd.append('file', blob, opts.filename ?? 'avatar')\n return http.request<Agent>({\n method: 'POST',\n path: `/v1/agents/${agentId}/avatar`,\n formData: fd,\n })\n },\n\n /**\n * Remove the agent's avatar — both the GCS object and the `avatarUrl`\n * field. Idempotent: calling on an agent without an avatar still\n * returns the agent.\n */\n removeAvatar: async (agentId: string): Promise<Agent> =>\n http.request<Agent>({ method: 'DELETE', path: `/v1/agents/${agentId}/avatar` }),\n\n // Nested resource. Per-agent webhook CRUD lives at\n // /v1/agents/:agentId/webhooks/* — we expose it as a factory keyed on\n // agentId so consumers can bind once and reuse:\n //\n // const hooks = client.agents.webhooks(myAgentId)\n // await hooks.create({ url, events })\n // await hooks.list()\n webhooks: (agentId: string): AgentWebhooksResource =>\n createAgentWebhooksResource(http, agentId),\n }\n return agents\n}\n\nexport type AgentsResource = ReturnType<typeof createAgentsResource>\n","import type { HttpClient } from '../http'\nimport type {\n CallListFilters,\n CallRecord,\n CallRecordingUrlResponse,\n CallSummary,\n TranscriptTurn,\n} from '../types'\n\nexport const createCallsResource = (http: HttpClient) => {\n const calls = {\n list: async (filters: CallListFilters = {}): Promise<CallSummary[]> => {\n const res = await http.request<{ data: CallSummary[] }>({\n method: 'GET',\n path: '/v1/calls',\n query: filters as Record<string, string | number | undefined>,\n })\n return res.data\n },\n\n // Auto-pagination helper. v1 server caps at limit (max 200) in a single\n // page — consumers who ask for \"every call since X\" get that page, the\n // iterator ends. This is the shape we'd extend with cursor support\n // without breaking callers.\n listAll: async function* (filters: CallListFilters = {}): AsyncIterable<CallSummary> {\n const page = await calls.list(filters)\n for (const c of page) yield c\n },\n\n get: async (callId: string): Promise<CallRecord> =>\n http.request<CallRecord>({ method: 'GET', path: `/v1/calls/${callId}` }),\n\n transcript: async (callId: string): Promise<{ callId: string; transcript: TranscriptTurn[] }> =>\n http.request<{ callId: string; transcript: TranscriptTurn[] }>({\n method: 'GET',\n path: `/v1/calls/${callId}/transcript`,\n }),\n\n // Returns a V4 signed URL (1-hour TTL). `ready: false` + `artifact:\n // 'caller-raw'` means the async mix job hasn't finished — the URL still\n // points at a playable file (raw caller PCM).\n recording: async (callId: string): Promise<CallRecordingUrlResponse> =>\n http.request<CallRecordingUrlResponse>({\n method: 'GET',\n path: `/v1/calls/${callId}/recording`,\n }),\n\n // Outbound dialling (POST /v1/calls) + in-call control are Phase 1.4.4 /\n // 1.4.5 respectively — blocked on telephony. Surface clear \"not built\n // yet\" errors here if consumers guess those method names, so they don't\n // silently hit a non-existent endpoint and wonder why it 404s.\n }\n return calls\n}\n\nexport type CallsResource = ReturnType<typeof createCallsResource>\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport type { HttpClient } from '../http'\nimport type { KnowledgeBase, KnowledgeBaseFile } from '../types'\n\nexport const createKnowledgeBasesResource = (http: HttpClient) => ({\n create: async (name: string): Promise<KnowledgeBase> =>\n http.request<KnowledgeBase>({\n method: 'POST',\n path: '/v1/knowledge-bases',\n body: { name },\n }),\n\n list: async (): Promise<KnowledgeBase[]> => {\n const res = await http.request<{ data: KnowledgeBase[] }>({\n method: 'GET',\n path: '/v1/knowledge-bases',\n })\n return res.data\n },\n\n get: async (kbId: string): Promise<KnowledgeBase> =>\n http.request<KnowledgeBase>({ method: 'GET', path: `/v1/knowledge-bases/${kbId}` }),\n\n delete: async (kbId: string): Promise<void> =>\n http.request<void>({ method: 'DELETE', path: `/v1/knowledge-bases/${kbId}` }),\n\n // File upload — accepts either a local file path OR raw bytes + filename.\n // The server ingests synchronously today (Phase 3.1.4 Cloud Tasks is a\n // followup), so the returned file has status='ready' in most cases.\n uploadFile: async (\n kbId: string,\n source:\n | { path: string; filename?: string; mimeType?: string }\n | { data: Buffer | Uint8Array; filename: string; mimeType?: string },\n ): Promise<KnowledgeBaseFile> => {\n const form = new FormData()\n let blob: Blob\n let filename: string\n let mime: string\n\n if ('path' in source) {\n const buf = await fs.promises.readFile(source.path)\n filename = source.filename ?? path.basename(source.path)\n mime = source.mimeType ?? 'application/octet-stream'\n blob = new Blob([new Uint8Array(buf)], { type: mime })\n } else {\n filename = source.filename\n mime = source.mimeType ?? 'application/octet-stream'\n const bytes = source.data instanceof Buffer ? new Uint8Array(source.data) : source.data\n blob = new Blob([bytes], { type: mime })\n }\n form.append('file', blob, filename)\n\n // File uploads can take a while (OCR, chunking, embedding) — give them\n // room before timing out. 5 min cap matches the server's own\n // processing budget.\n return http.request<KnowledgeBaseFile>({\n method: 'POST',\n path: `/v1/knowledge-bases/${kbId}/files`,\n formData: form,\n timeoutMs: 5 * 60 * 1000,\n })\n },\n\n listFiles: async (kbId: string): Promise<KnowledgeBaseFile[]> => {\n const res = await http.request<{ data: KnowledgeBaseFile[] }>({\n method: 'GET',\n path: `/v1/knowledge-bases/${kbId}/files`,\n })\n return res.data\n },\n\n deleteFile: async (kbId: string, fileId: string): Promise<void> =>\n http.request<void>({\n method: 'DELETE',\n path: `/v1/knowledge-bases/${kbId}/files/${fileId}`,\n }),\n})\n\nexport type KnowledgeBasesResource = ReturnType<typeof createKnowledgeBasesResource>\n","import type { HttpClient } from '../http'\nimport type { LedgerEntry } from '../types'\n\nexport const createCreditsResource = (http: HttpClient) => {\n const credits = {\n getBalance: async (): Promise<{ orgId: string; balanceCents: number }> =>\n http.request<{ orgId: string; balanceCents: number }>({\n method: 'GET',\n path: '/v1/credits/balance',\n }),\n\n // Returns ledger entries newest-first. `limit` is capped at 500 server-side.\n getLedger: async (opts: { limit?: number } = {}): Promise<LedgerEntry[]> => {\n const res = await http.request<{ data: LedgerEntry[] }>({\n method: 'GET',\n path: '/v1/credits/ledger',\n query: opts as Record<string, string | number | undefined>,\n })\n return res.data\n },\n\n // Auto-pagination scaffold — v1 server returns a single page up to\n // limit=500. When cursor pagination lands this is where it gets wired.\n getLedgerAll: async function* (opts: { limit?: number } = {}): AsyncIterable<LedgerEntry> {\n const page = await credits.getLedger(opts)\n for (const e of page) yield e\n },\n }\n return credits\n}\n\nexport type CreditsResource = ReturnType<typeof createCreditsResource>\n","import type { HttpClient } from '../http'\nimport type { CallTokenMintInput, CallTokenMintResult, CallTokenSummary } from '../types'\n\n// Short-lived, agent-scoped `ct_` tokens. Mint one per user session on your\n// backend, hand the raw value to the browser; let this SDK handle lifecycle\n// (revoke on sign-out, list active tokens for an admin panel).\n\nexport const createCallTokensResource = (http: HttpClient) => ({\n // Returns the RAW token value once. Don't log it; pass it straight to the\n // browser + discard server-side. `tokenId` is the stable public handle\n // used for revocation later.\n mint: async (input: CallTokenMintInput): Promise<CallTokenMintResult> =>\n http.request<CallTokenMintResult>({\n method: 'POST',\n path: '/v1/call-tokens',\n body: input,\n }),\n\n // Live tokens only by default. Pass includeRevoked/includeExpired when\n // debugging \"why did my token stop working\".\n list: async (\n opts: { includeRevoked?: boolean; includeExpired?: boolean; limit?: number } = {},\n ): Promise<CallTokenSummary[]> => {\n const query: Record<string, string | number | undefined> = {}\n if (opts.includeRevoked) query.includeRevoked = '1'\n if (opts.includeExpired) query.includeExpired = '1'\n if (opts.limit !== undefined) query.limit = opts.limit\n const res = await http.request<{ data: CallTokenSummary[] }>({\n method: 'GET',\n path: '/v1/call-tokens',\n query,\n })\n return res.data\n },\n\n // Idempotent — re-revoking a revoked token returns `alreadyRevoked: true`.\n revoke: async (\n tokenId: string,\n ): Promise<{ tokenId: string; revoked: boolean; alreadyRevoked?: boolean }> =>\n http.request<{ tokenId: string; revoked: boolean; alreadyRevoked?: boolean }>({\n method: 'DELETE',\n path: `/v1/call-tokens/${tokenId}`,\n }),\n})\n\nexport type CallTokensResource = ReturnType<typeof createCallTokensResource>\n","import type { HttpClient } from '../http'\nimport type { WebhookDelivery } from '../types'\n\n// Org-wide webhook delivery log. Per-agent CRUD lives on\n// `client.agents.webhooks(agentId)` — this namespace is just the\n// read-only deliveries surface that spans all agents.\n\nexport const createWebhooksResource = (http: HttpClient) => ({\n deliveries: async (\n filters: {\n agentId?: string\n webhookId?: string\n callId?: string\n limit?: number\n } = {},\n ): Promise<WebhookDelivery[]> => {\n const res = await http.request<{ data: WebhookDelivery[] }>({\n method: 'GET',\n path: '/v1/webhooks/deliveries',\n query: filters as Record<string, string | number | undefined>,\n })\n return res.data\n },\n})\n\nexport type WebhooksResource = ReturnType<typeof createWebhooksResource>\n","import type { HttpClient } from '../http'\nimport type { CatalogAgent, CatalogListInput } from '../types'\n\n// Org-scoped consumer endpoints. Today this is just the agent catalog —\n// the trimmed shape your mobile app picks an agent from. Lives at\n// `/v1/orgs/:orgId/agents` rather than reusing the admin `/v1/agents/*`\n// tree on purpose: the catalog response intentionally excludes the\n// operator-only fields (system prompt, tools, KB IDs) so a leaked\n// consumer-backend `sk_` can't lift the operator config out of it.\n//\n// Pattern from your backend:\n//\n// const client = new PlatformClient({ apiKey: process.env.SK })\n// const visible = await client.orgs.listAgents({\n// orgId: process.env.ORG_ID!,\n// userTags: ['tier1'], // omit to get the unfiltered admin view\n// })\n// res.json(visible)\n\nexport const createOrgsResource = (http: HttpClient) => ({\n /**\n * Fetch the agent catalog for an org. Returns the consumer-trimmed shape;\n * no system prompt, tools, or KB info. Use `client.agents.get(agentId)`\n * with the same `sk_` if you need the full admin shape.\n *\n * `userTags`: end-user entitlement tags. When supplied, hides agents\n * whose `allowedUserTags` is non-empty and doesn't intersect with the\n * supplied list. Omit to get the unfiltered admin view.\n *\n * Persona / category filtering is intentionally not a server param —\n * filter the returned list client-side over `name`s if you need it.\n *\n * Throws `403 forbidden` if `orgId` doesn't match the key's org.\n */\n listAgents: async (input: CatalogListInput): Promise<CatalogAgent[]> => {\n const query: Record<string, string | undefined> = {}\n if (input.userTags && input.userTags.length > 0) query.userTags = input.userTags.join(',')\n const res = await http.request<{ data: CatalogAgent[] }>({\n method: 'GET',\n path: `/v1/orgs/${input.orgId}/agents`,\n query,\n })\n return res.data\n },\n})\n\nexport type OrgsResource = ReturnType<typeof createOrgsResource>\n","import type { HttpClient } from '../http'\nimport type {\n CreateRoomInput,\n CreateRoomResponse,\n ListRoomsResponse,\n ListUtterancesResponse,\n RoomDoc,\n RoomEventAck,\n RoomListFilters,\n RoomTranscriptOptions,\n} from '../types'\n\n// REST wrappers for /v1/rooms — the multi-party video room surface (see\n// docs/superpowers/specs/2026-05-18-multiparty-rooms-design.md). Lets\n// server-side code mint rooms, fetch state, list transcript pages, and end\n// rooms programmatically.\n//\n// Auth model: same Bearer `sk_` flow as every other resource — the server\n// derives `orgId` from the API key, so the SDK never sets a tenant header.\n//\n// Host actions beyond `end` (promote/demote/kick) and observer-token mint\n// live in the server but aren't surfaced here yet — they're operator-side\n// flows that the dashboard hits directly. Re-add here if a programmatic\n// use-case shows up (CI tests, integration harnesses).\n\nexport const createRoomsResource = (http: HttpClient) => ({\n // Provision a new room. Server returns 201 with ONE shared room-level\n // `joinToken` + `joinUrl`. Share the single link with everyone you want in\n // the room — each visitor supplies their own display name at join time and\n // becomes a fresh, distinct participant. The server persists only the\n // token's sha256 hash; the raw token is returned here once and never stored.\n create: async (input: CreateRoomInput): Promise<CreateRoomResponse> =>\n http.request<CreateRoomResponse>({\n method: 'POST',\n path: '/v1/rooms',\n body: input,\n }),\n\n // Listing — opaque cursor pagination (`nextCursor` returned by the server\n // is whatever startAfter() needs, don't parse client-side).\n list: async (filters: RoomListFilters = {}): Promise<ListRoomsResponse> => {\n const query: Record<string, string | number | undefined> = {}\n if (filters.status) query.status = filters.status\n if (filters.limit !== undefined) query.limit = filters.limit\n if (filters.cursor) query.cursor = filters.cursor\n return http.request<ListRoomsResponse>({\n method: 'GET',\n path: '/v1/rooms',\n query,\n })\n },\n\n // Fetch a single room. 404s are surfaced as PlatformError('not_found').\n get: async (roomId: string): Promise<RoomDoc> =>\n http.request<RoomDoc>({\n method: 'GET',\n path: `/v1/rooms/${roomId}`,\n }),\n\n // Transcript pages — utterances are ordered by `startedAt asc`. Cursor is\n // an ISO timestamp (server enforces, don't construct yourself).\n transcript: async (\n roomId: string,\n opts: RoomTranscriptOptions = {},\n ): Promise<ListUtterancesResponse> => {\n const query: Record<string, string | number | undefined> = {}\n if (opts.cursor) query.cursor = opts.cursor\n if (opts.limit !== undefined) query.limit = opts.limit\n return http.request<ListUtterancesResponse>({\n method: 'GET',\n path: `/v1/rooms/${roomId}/transcript`,\n query,\n })\n },\n\n // End a room — async on the server: returns 202 + eventId once the\n // controlEvents entry is written. The room-worker observes the entry,\n // broadcasts the system message, and tears down LiveKit shortly after.\n end: async (roomId: string): Promise<RoomEventAck> =>\n http.request<RoomEventAck>({\n method: 'POST',\n path: `/v1/rooms/${roomId}/end`,\n }),\n})\n\nexport type RoomsResource = ReturnType<typeof createRoomsResource>\n","import { createHttpClient, type HttpClientOptions } from './http'\nimport { createMeResource, type MeResource } from './resources/me'\nimport { createAgentsResource, type AgentsResource } from './resources/agents'\nimport { createCallsResource, type CallsResource } from './resources/calls'\nimport {\n createKnowledgeBasesResource,\n type KnowledgeBasesResource,\n} from './resources/knowledgeBases'\nimport { createCreditsResource, type CreditsResource } from './resources/credits'\nimport { createCallTokensResource, type CallTokensResource } from './resources/callTokens'\nimport { createWebhooksResource, type WebhooksResource } from './resources/webhooks'\nimport { createOrgsResource, type OrgsResource } from './resources/orgs'\nimport { createRoomsResource, type RoomsResource } from './resources/rooms'\n\nexport interface PlatformClientOptions {\n // Full-org API key minted from the dashboard or bootstrap CLI. Start with\n // `sk_`. Never ship to a browser — use `client.callTokens.mint(...)` to\n // generate a narrow `ct_` token for client-side use instead.\n apiKey: string\n // Defaults to the hosted platform. Point at `http://localhost:8080` for\n // local dev or at a self-hosted deployment.\n baseUrl?: string\n // Passthrough tuning for the HTTP layer.\n timeoutMs?: number\n maxRetries?: number\n fetch?: HttpClientOptions['fetch']\n onRequest?: HttpClientOptions['onRequest']\n}\n\n// Single entry point. All resources are lazy-constructed in the constructor\n// so their refs don't incur any per-call allocation. Shape mirrors Stripe /\n// Twilio / Vapi's `resource.method()` convention for familiarity.\nexport class PlatformClient {\n readonly me: MeResource\n readonly agents: AgentsResource\n readonly calls: CallsResource\n readonly knowledgeBases: KnowledgeBasesResource\n readonly credits: CreditsResource\n readonly callTokens: CallTokensResource\n readonly webhooks: WebhooksResource\n readonly orgs: OrgsResource\n readonly rooms: RoomsResource\n\n constructor(options: PlatformClientOptions) {\n if (!options.apiKey) {\n throw new Error('PlatformClient: `apiKey` is required')\n }\n const http = createHttpClient({\n apiKey: options.apiKey,\n baseUrl: options.baseUrl ?? 'https://api.example.com',\n timeoutMs: options.timeoutMs,\n maxRetries: options.maxRetries,\n fetch: options.fetch,\n onRequest: options.onRequest,\n })\n\n this.me = createMeResource(http)\n this.agents = createAgentsResource(http)\n this.calls = createCallsResource(http)\n this.knowledgeBases = createKnowledgeBasesResource(http)\n this.credits = createCreditsResource(http)\n this.callTokens = createCallTokensResource(http)\n this.webhooks = createWebhooksResource(http)\n this.orgs = createOrgsResource(http)\n this.rooms = createRoomsResource(http)\n }\n}\n","import crypto from 'node:crypto'\n\n// Helper for consumers receiving webhooks: verify the `X-Platform-Signature-256`\n// header against the raw body + secret. Plain function (not tied to\n// PlatformClient) so Express/Koa/Next.js middleware can use it without\n// instantiating a client.\n//\n// import { verifyWebhookSignature } from '@craftedxp/sdk-node'\n// app.post('/webhooks/voice-agent', express.raw({ type: 'application/json' }), (req, res) => {\n// const sig = req.header('X-Platform-Signature-256') ?? ''\n// if (!verifyWebhookSignature(req.body, sig, process.env.VOICE_AGENT_WEBHOOK_SECRET!)) {\n// return res.status(401).send('invalid signature')\n// }\n// const event = JSON.parse(req.body.toString('utf8'))\n// // ...handle event\n// })\n//\n// The signature is `sha256=<hex HMAC-SHA256 of rawBody with secret>`.\n// Timing-safe compare to avoid microtiming side channels.\n\nexport const verifyWebhookSignature = (\n rawBody: Buffer | string,\n signatureHeader: string,\n secret: string,\n): boolean => {\n if (!signatureHeader || !secret) return false\n const [algo, provided] = signatureHeader.split('=')\n if (algo !== 'sha256' || !provided) return false\n\n const expected = crypto\n .createHmac('sha256', secret)\n .update(typeof rawBody === 'string' ? rawBody : rawBody)\n .digest('hex')\n\n // Buffers must match in length for timingSafeEqual.\n const a = Buffer.from(expected, 'hex')\n const b = Buffer.from(provided, 'hex')\n if (a.length !== b.length) return false\n return crypto.timingSafeEqual(a, b)\n}\n"],"mappings":";AAmBO,IAAM,gBAAN,MAAM,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ACrC,MAAI,EAAE,WAAW,EAAE,OAAQ,QAAO;AAClC,SAAO,OAAO,gBAAgB,GAAG,CAAC;AACpC;","names":["path"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/http.ts","../src/resources/me.ts","../src/resources/agentWebhooks.ts","../src/resources/agents.ts","../src/resources/calls.ts","../src/resources/knowledgeBases.ts","../src/resources/credits.ts","../src/resources/callTokens.ts","../src/resources/webhooks.ts","../src/resources/orgs.ts","../src/resources/rooms.ts","../src/resources/chats.ts","../src/PlatformClient.ts","../src/verify.ts"],"sourcesContent":["// Typed error class mirroring the server's ErrorV1 shape:\n// { error: { code, message, field?, docs_url? } }\n//\n// Consumers do `err instanceof PlatformError` to branch on code without\n// parsing string messages. `status` carries the HTTP code for the 1% of\n// cases where the code field isn't enough (e.g. rate-limit → retry-after\n// header correlation).\n\nexport type ApiErrorCode =\n | 'unauthorized'\n | 'forbidden'\n | 'not_found'\n | 'bad_request'\n | 'conflict'\n | 'rate_limited'\n | 'payment_required'\n | 'internal_error'\n | 'unknown'\n\nexport class PlatformError extends Error {\n readonly code: ApiErrorCode\n readonly status: number\n readonly field?: string\n readonly docsUrl?: string\n // The raw response body for debugging. Intentionally optional — we clear\n // it on `error.toJSON()` so logging libraries don't dump the whole\n // server response into production logs.\n readonly body?: unknown\n\n constructor(params: {\n code: ApiErrorCode\n message: string\n status: number\n field?: string\n docsUrl?: string\n body?: unknown\n }) {\n super(params.message)\n this.name = 'PlatformError'\n this.code = params.code\n this.status = params.status\n this.field = params.field\n this.docsUrl = params.docsUrl\n this.body = params.body\n // Preserve the stack trace — Node's Error doesn't capture it\n // automatically when subclassing in some older runtimes.\n if (\n typeof (Error as typeof Error & { captureStackTrace?: unknown }).captureStackTrace ===\n 'function'\n ) {\n ;(\n Error as typeof Error & { captureStackTrace: (target: unknown, ctor: unknown) => void }\n ).captureStackTrace(this, PlatformError)\n }\n }\n\n toJSON(): Record<string, unknown> {\n return {\n name: this.name,\n code: this.code,\n message: this.message,\n status: this.status,\n field: this.field,\n docsUrl: this.docsUrl,\n }\n }\n}\n","import { PlatformError, type ApiErrorCode } from './errors'\n\n// Low-level HTTP wrapper around `fetch` (native in Node 18+). Every resource\n// method routes through here for consistent auth + error handling + retries.\n//\n// v1 scope: JSON-in / JSON-out + multipart for file uploads. No streaming —\n// call WebSockets go through @craftedxp/voice-rn (the React Native client)\n// or a web equivalent, not this server-side SDK.\n\nexport interface HttpClientOptions {\n apiKey: string\n baseUrl: string\n // Default 30s. File uploads can override per-request.\n timeoutMs?: number\n // 429 + 5xx retries. Defaults to 3 attempts (original + 2 retries) with\n // exponential backoff (250ms, 1s). Set to 0 to disable.\n maxRetries?: number\n // Optional — lets consumers swap in a test/mock fetch (or a custom one\n // with instrumentation). Defaults to the global.\n fetch?: typeof fetch\n // Optional — a callback that fires per-request with the final status and\n // duration. Handy for dropping traces into the consumer's observability\n // stack without wrapping each call.\n onRequest?: (info: {\n method: string\n url: string\n status: number\n durationMs: number\n attempt: number\n }) => void\n}\n\nexport interface HttpRequest {\n method: 'GET' | 'POST' | 'PATCH' | 'DELETE'\n path: string // starts with `/`, e.g. `/v1/agents/123`\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown // JSON-serialised — for multipart use `formData`\n formData?: FormData\n timeoutMs?: number\n // Exposed for edge cases where a resource wants to tack on extra\n // headers (we don't have any today but leave the hook).\n headers?: Record<string, string>\n}\n\nconst DEFAULT_TIMEOUT_MS = 30_000\nconst DEFAULT_MAX_RETRIES = 2 // total attempts = 3\n\nconst buildUrl = (baseUrl: string, path: string, query?: HttpRequest['query']): string => {\n const u = new URL(path, baseUrl)\n if (query) {\n for (const [k, v] of Object.entries(query)) {\n if (v === undefined) continue\n u.searchParams.set(k, String(v))\n }\n }\n return u.toString()\n}\n\nconst sleep = (ms: number) => new Promise<void>((r) => setTimeout(r, ms))\n\nconst isRetryable = (status: number): boolean => status === 429 || (status >= 500 && status < 600)\n\n// Parse whatever the server returned into a PlatformError. Falls back to\n// synthesising a sensible error for non-JSON responses.\nconst errorFromResponse = async (res: Response): Promise<PlatformError> => {\n const bodyText = await res.text().catch(() => '')\n let parsed: unknown = undefined\n try {\n parsed = bodyText ? JSON.parse(bodyText) : undefined\n } catch {\n // non-JSON response (e.g. an HTML error page from a proxy). Fall\n // through with parsed = undefined.\n }\n const errObj = (\n parsed as { error?: { code?: string; message?: string; field?: string; docs_url?: string } }\n )?.error\n return new PlatformError({\n code: (errObj?.code as ApiErrorCode) ?? 'unknown',\n message: errObj?.message ?? res.statusText ?? `HTTP ${res.status}`,\n status: res.status,\n field: errObj?.field,\n docsUrl: errObj?.docs_url,\n body: parsed ?? bodyText,\n })\n}\n\nexport const createHttpClient = (opts: HttpClientOptions) => {\n const fetchImpl = opts.fetch ?? globalThis.fetch\n const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS\n const maxRetries = opts.maxRetries ?? DEFAULT_MAX_RETRIES\n\n if (!fetchImpl) {\n throw new Error('No global fetch available. @craftedxp/sdk-node requires Node >= 18.')\n }\n\n const request = async <T>(req: HttpRequest): Promise<T> => {\n const url = buildUrl(opts.baseUrl, req.path, req.query)\n const headers: Record<string, string> = {\n Authorization: `Bearer ${opts.apiKey}`,\n Accept: 'application/json',\n ...(req.headers ?? {}),\n }\n\n // Body shaping: prefer formData when provided; otherwise JSON.\n // `FormData` sets its own Content-Type with boundary — don't preempt it.\n // Typed as `string | FormData | undefined` (a subset of the global\n // BodyInit) so we don't need DOM lib types in this server-side SDK.\n let body: string | FormData | undefined\n if (req.formData) {\n body = req.formData\n } else if (req.body !== undefined) {\n headers['Content-Type'] = 'application/json'\n body = JSON.stringify(req.body)\n }\n\n const reqTimeout = req.timeoutMs ?? timeoutMs\n let lastErr: unknown\n\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), reqTimeout)\n const started = Date.now()\n try {\n const res = await fetchImpl(url, {\n method: req.method,\n headers,\n body,\n signal: controller.signal,\n })\n const durationMs = Date.now() - started\n opts.onRequest?.({\n method: req.method,\n url,\n status: res.status,\n durationMs,\n attempt: attempt + 1,\n })\n\n if (res.ok) {\n // 204 No Content — some endpoints (DELETE webhooks) return nothing.\n if (res.status === 204) return undefined as T\n const ct = res.headers.get('content-type') ?? ''\n if (ct.includes('application/json')) {\n return (await res.json()) as T\n }\n // Non-JSON 2xx — rare. Return raw text cast as T.\n return (await res.text()) as unknown as T\n }\n\n // Retryable error: back off + retry up to maxRetries.\n if (isRetryable(res.status) && attempt < maxRetries) {\n const retryAfter = res.headers.get('Retry-After')\n const backoff = retryAfter ? Number(retryAfter) * 1000 : 250 * Math.pow(2, attempt)\n await sleep(backoff)\n continue\n }\n\n throw await errorFromResponse(res)\n } catch (err) {\n if (err instanceof PlatformError) throw err\n // AbortError / network / DNS failures — retry up to maxRetries.\n if (attempt < maxRetries) {\n lastErr = err\n await sleep(250 * Math.pow(2, attempt))\n continue\n }\n const msg = err instanceof Error ? err.message : 'network error'\n throw new PlatformError({\n code: 'unknown',\n message: `Network error: ${msg}`,\n status: 0,\n })\n } finally {\n clearTimeout(timer)\n }\n }\n\n // Should be unreachable — the loop either returns, throws, or continues.\n throw lastErr instanceof Error ? lastErr : new Error('request exhausted retries')\n }\n\n // SSE streaming: returns an AsyncIterable<T> over parsed SSE events.\n // Each event is the JSON `data` payload merged with the `event` name as\n // `type`. No retry/backoff mid-stream (stream != request); the caller\n // should treat `error` events from the typed channel as the error path.\n async function* stream<T = unknown>(req: HttpRequest): AsyncIterable<T> {\n const url = buildUrl(opts.baseUrl, req.path, req.query)\n const headers: Record<string, string> = {\n Authorization: `Bearer ${opts.apiKey}`,\n 'Content-Type': 'application/json',\n Accept: 'text/event-stream',\n ...(req.headers ?? {}),\n }\n\n const started = Date.now()\n let res: Response\n try {\n res = await fetchImpl(url, {\n method: req.method,\n headers,\n body: req.body !== undefined ? JSON.stringify(req.body) : undefined,\n })\n } catch (err) {\n const msg = err instanceof Error ? err.message : 'network error'\n throw new PlatformError({\n code: 'unknown',\n message: `Network error: ${msg}`,\n status: 0,\n })\n }\n\n opts.onRequest?.({\n method: req.method,\n url,\n status: res.status,\n durationMs: Date.now() - started,\n attempt: 1,\n })\n\n if (!res.ok || !res.body) {\n const text = await res.text().catch(() => '')\n let parsed: unknown = undefined\n try {\n parsed = text ? JSON.parse(text) : undefined\n } catch {\n // non-JSON — fall through\n }\n const errObj = (\n parsed as { error?: { code?: string; message?: string; field?: string; docs_url?: string } }\n )?.error\n throw new PlatformError({\n code: (errObj?.code as import('./errors').ApiErrorCode) ?? 'unknown',\n message: errObj?.message ?? res.statusText ?? `HTTP ${res.status}`,\n status: res.status,\n field: errObj?.field,\n docsUrl: errObj?.docs_url,\n body: parsed ?? text,\n })\n }\n\n const reader = res.body.getReader()\n const decoder = new TextDecoder()\n let buf = ''\n\n while (true) {\n const { value, done } = await reader.read()\n if (done) return\n buf += decoder.decode(value, { stream: true })\n let idx: number\n while ((idx = buf.indexOf('\\n\\n')) >= 0) {\n const block = buf.slice(0, idx)\n buf = buf.slice(idx + 2)\n let event = 'message'\n let data = ''\n for (const line of block.split('\\n')) {\n if (line.startsWith(':')) continue // SSE comment / keepalive\n if (line.startsWith('event:')) event = line.slice(6).trim()\n else if (line.startsWith('data:')) data += line.slice(5).trim()\n }\n if (!data) continue\n try {\n const parsed = JSON.parse(data)\n yield { type: event, ...parsed } as T\n } catch {\n // Drop malformed JSON; an error event will arrive via the typed channel.\n }\n }\n }\n }\n\n return { request, stream }\n}\n\nexport type HttpClient = ReturnType<typeof createHttpClient>\n","import type { HttpClient } from '../http'\nimport type { MeResponse } from '../types'\n\nexport const createMeResource = (http: HttpClient) => ({\n // Smoke test — confirms the API key is valid and returns the org + balance.\n // Most consumers use this as a ping on startup.\n get: async (): Promise<MeResponse> => http.request<MeResponse>({ method: 'GET', path: '/v1/me' }),\n})\n\nexport type MeResource = ReturnType<typeof createMeResource>\n","import type { HttpClient } from '../http'\nimport type {\n WebhookConfig,\n WebhookCreateInput,\n WebhookDelivery,\n WebhookUpdateInput,\n} from '../types'\n\n// Per-agent webhook resource, scoped at factory time to a specific agentId.\n// All endpoints mirror /v1/agents/:agentId/webhooks[/:id].\n\nexport const createAgentWebhooksResource = (http: HttpClient, agentId: string) => ({\n // Returns the webhook + its signing secret. The secret is only present in\n // this response — persist immediately, subsequent GETs omit it. Use the\n // secret to verify `X-Platform-Signature-256` (sha256=hex HMAC over body).\n create: async (input: WebhookCreateInput): Promise<WebhookConfig> =>\n http.request<WebhookConfig>({\n method: 'POST',\n path: `/v1/agents/${agentId}/webhooks`,\n body: input,\n }),\n\n list: async (): Promise<WebhookConfig[]> => {\n const res = await http.request<{ data: WebhookConfig[] }>({\n method: 'GET',\n path: `/v1/agents/${agentId}/webhooks`,\n })\n return res.data\n },\n\n get: async (webhookId: string): Promise<WebhookConfig> =>\n http.request<WebhookConfig>({\n method: 'GET',\n path: `/v1/agents/${agentId}/webhooks/${webhookId}`,\n }),\n\n update: async (webhookId: string, patch: WebhookUpdateInput): Promise<WebhookConfig> =>\n http.request<WebhookConfig>({\n method: 'PATCH',\n path: `/v1/agents/${agentId}/webhooks/${webhookId}`,\n body: patch,\n }),\n\n delete: async (webhookId: string): Promise<void> =>\n http.request<void>({\n method: 'DELETE',\n path: `/v1/agents/${agentId}/webhooks/${webhookId}`,\n }),\n\n // Fires a synthetic call.started against this webhook and returns the\n // full delivery record (including attempt status codes) once the retry\n // sequence has finished. Useful during setup to verify receiver wiring.\n test: async (webhookId: string): Promise<WebhookDelivery> =>\n http.request<WebhookDelivery>({\n method: 'POST',\n path: `/v1/agents/${agentId}/webhooks/${webhookId}/test`,\n }),\n})\n\nexport type AgentWebhooksResource = ReturnType<typeof createAgentWebhooksResource>\n","import type { HttpClient } from '../http'\nimport type { Agent, AgentCreateInput, AgentUpdateInput } from '../types'\nimport { createAgentWebhooksResource, type AgentWebhooksResource } from './agentWebhooks'\n\n// The server returns Agent with `apiKey` stripped and `hasApiKey: boolean`\n// on the model. We type the happy path but keep our input type permissive\n// so consumers can POST a plaintext `apiKey` that the server encrypts +\n// swaps for `apiKeySecret` on persistence.\n\nexport const createAgentsResource = (http: HttpClient) => {\n const agents = {\n create: async (input: AgentCreateInput): Promise<Agent> =>\n http.request<Agent>({ method: 'POST', path: '/v1/agents', body: input }),\n\n list: async (): Promise<Agent[]> => {\n const res = await http.request<{ data: Agent[] }>({ method: 'GET', path: '/v1/agents' })\n return res.data\n },\n\n // Async iterator for \"give me every agent\" — v1 server returns the full\n // list in one page, so this is just a thin convenience. When the server\n // picks up cursor pagination, this is the method that papers over that\n // migration without consumer changes.\n listAll: async function* (): AsyncIterable<Agent> {\n const page = await agents.list()\n for (const a of page) yield a\n },\n\n get: async (agentId: string): Promise<Agent> =>\n http.request<Agent>({ method: 'GET', path: `/v1/agents/${agentId}` }),\n\n update: async (agentId: string, patch: AgentUpdateInput): Promise<Agent> =>\n http.request<Agent>({ method: 'PATCH', path: `/v1/agents/${agentId}`, body: patch }),\n\n delete: async (agentId: string): Promise<void> =>\n http.request<void>({ method: 'DELETE', path: `/v1/agents/${agentId}` }),\n\n /**\n * Upload an avatar image for the agent. Server re-encodes to a 512×512\n * WebP and stores it in the public-read avatars bucket; the returned\n * `Agent` has `avatarUrl` set to the canonical public URL with a\n * `?v=` cache-buster.\n *\n * `file` accepts a Node Buffer / Uint8Array / Blob / typed-array.\n * `filename` and `contentType` are optional but help the server log\n * meaningful errors when something rejects.\n */\n uploadAvatar: async (\n agentId: string,\n file: Buffer | Uint8Array | Blob | ArrayBuffer,\n opts: { filename?: string; contentType?: string } = {},\n ): Promise<Agent> => {\n const fd = new FormData()\n const blob =\n file instanceof Blob\n ? file\n : // eslint-disable-next-line @typescript-eslint/no-explicit-any\n new Blob([file as any], { type: opts.contentType ?? 'application/octet-stream' })\n fd.append('file', blob, opts.filename ?? 'avatar')\n return http.request<Agent>({\n method: 'POST',\n path: `/v1/agents/${agentId}/avatar`,\n formData: fd,\n })\n },\n\n /**\n * Remove the agent's avatar — both the GCS object and the `avatarUrl`\n * field. Idempotent: calling on an agent without an avatar still\n * returns the agent.\n */\n removeAvatar: async (agentId: string): Promise<Agent> =>\n http.request<Agent>({ method: 'DELETE', path: `/v1/agents/${agentId}/avatar` }),\n\n // Nested resource. Per-agent webhook CRUD lives at\n // /v1/agents/:agentId/webhooks/* — we expose it as a factory keyed on\n // agentId so consumers can bind once and reuse:\n //\n // const hooks = client.agents.webhooks(myAgentId)\n // await hooks.create({ url, events })\n // await hooks.list()\n webhooks: (agentId: string): AgentWebhooksResource =>\n createAgentWebhooksResource(http, agentId),\n }\n return agents\n}\n\nexport type AgentsResource = ReturnType<typeof createAgentsResource>\n","import type { HttpClient } from '../http'\nimport type {\n CallListFilters,\n CallRecord,\n CallRecordingUrlResponse,\n CallSummary,\n TranscriptTurn,\n} from '../types'\n\nexport const createCallsResource = (http: HttpClient) => {\n const calls = {\n list: async (filters: CallListFilters = {}): Promise<CallSummary[]> => {\n const res = await http.request<{ data: CallSummary[] }>({\n method: 'GET',\n path: '/v1/calls',\n query: filters as Record<string, string | number | undefined>,\n })\n return res.data\n },\n\n // Auto-pagination helper. v1 server caps at limit (max 200) in a single\n // page — consumers who ask for \"every call since X\" get that page, the\n // iterator ends. This is the shape we'd extend with cursor support\n // without breaking callers.\n listAll: async function* (filters: CallListFilters = {}): AsyncIterable<CallSummary> {\n const page = await calls.list(filters)\n for (const c of page) yield c\n },\n\n get: async (callId: string): Promise<CallRecord> =>\n http.request<CallRecord>({ method: 'GET', path: `/v1/calls/${callId}` }),\n\n transcript: async (callId: string): Promise<{ callId: string; transcript: TranscriptTurn[] }> =>\n http.request<{ callId: string; transcript: TranscriptTurn[] }>({\n method: 'GET',\n path: `/v1/calls/${callId}/transcript`,\n }),\n\n // Returns a V4 signed URL (1-hour TTL). `ready: false` + `artifact:\n // 'caller-raw'` means the async mix job hasn't finished — the URL still\n // points at a playable file (raw caller PCM).\n recording: async (callId: string): Promise<CallRecordingUrlResponse> =>\n http.request<CallRecordingUrlResponse>({\n method: 'GET',\n path: `/v1/calls/${callId}/recording`,\n }),\n\n // Outbound dialling (POST /v1/calls) + in-call control are Phase 1.4.4 /\n // 1.4.5 respectively — blocked on telephony. Surface clear \"not built\n // yet\" errors here if consumers guess those method names, so they don't\n // silently hit a non-existent endpoint and wonder why it 404s.\n }\n return calls\n}\n\nexport type CallsResource = ReturnType<typeof createCallsResource>\n","import fs from 'node:fs'\nimport path from 'node:path'\nimport type { HttpClient } from '../http'\nimport type { KnowledgeBase, KnowledgeBaseFile } from '../types'\n\nexport const createKnowledgeBasesResource = (http: HttpClient) => ({\n create: async (name: string): Promise<KnowledgeBase> =>\n http.request<KnowledgeBase>({\n method: 'POST',\n path: '/v1/knowledge-bases',\n body: { name },\n }),\n\n list: async (): Promise<KnowledgeBase[]> => {\n const res = await http.request<{ data: KnowledgeBase[] }>({\n method: 'GET',\n path: '/v1/knowledge-bases',\n })\n return res.data\n },\n\n get: async (kbId: string): Promise<KnowledgeBase> =>\n http.request<KnowledgeBase>({ method: 'GET', path: `/v1/knowledge-bases/${kbId}` }),\n\n delete: async (kbId: string): Promise<void> =>\n http.request<void>({ method: 'DELETE', path: `/v1/knowledge-bases/${kbId}` }),\n\n // File upload — accepts either a local file path OR raw bytes + filename.\n // The server ingests synchronously today (Phase 3.1.4 Cloud Tasks is a\n // followup), so the returned file has status='ready' in most cases.\n uploadFile: async (\n kbId: string,\n source:\n | { path: string; filename?: string; mimeType?: string }\n | { data: Buffer | Uint8Array; filename: string; mimeType?: string },\n ): Promise<KnowledgeBaseFile> => {\n const form = new FormData()\n let blob: Blob\n let filename: string\n let mime: string\n\n if ('path' in source) {\n const buf = await fs.promises.readFile(source.path)\n filename = source.filename ?? path.basename(source.path)\n mime = source.mimeType ?? 'application/octet-stream'\n blob = new Blob([new Uint8Array(buf)], { type: mime })\n } else {\n filename = source.filename\n mime = source.mimeType ?? 'application/octet-stream'\n const bytes = source.data instanceof Buffer ? new Uint8Array(source.data) : source.data\n blob = new Blob([bytes], { type: mime })\n }\n form.append('file', blob, filename)\n\n // File uploads can take a while (OCR, chunking, embedding) — give them\n // room before timing out. 5 min cap matches the server's own\n // processing budget.\n return http.request<KnowledgeBaseFile>({\n method: 'POST',\n path: `/v1/knowledge-bases/${kbId}/files`,\n formData: form,\n timeoutMs: 5 * 60 * 1000,\n })\n },\n\n listFiles: async (kbId: string): Promise<KnowledgeBaseFile[]> => {\n const res = await http.request<{ data: KnowledgeBaseFile[] }>({\n method: 'GET',\n path: `/v1/knowledge-bases/${kbId}/files`,\n })\n return res.data\n },\n\n deleteFile: async (kbId: string, fileId: string): Promise<void> =>\n http.request<void>({\n method: 'DELETE',\n path: `/v1/knowledge-bases/${kbId}/files/${fileId}`,\n }),\n})\n\nexport type KnowledgeBasesResource = ReturnType<typeof createKnowledgeBasesResource>\n","import type { HttpClient } from '../http'\nimport type { LedgerEntry } from '../types'\n\nexport const createCreditsResource = (http: HttpClient) => {\n const credits = {\n getBalance: async (): Promise<{ orgId: string; balanceCents: number }> =>\n http.request<{ orgId: string; balanceCents: number }>({\n method: 'GET',\n path: '/v1/credits/balance',\n }),\n\n // Returns ledger entries newest-first. `limit` is capped at 500 server-side.\n getLedger: async (opts: { limit?: number } = {}): Promise<LedgerEntry[]> => {\n const res = await http.request<{ data: LedgerEntry[] }>({\n method: 'GET',\n path: '/v1/credits/ledger',\n query: opts as Record<string, string | number | undefined>,\n })\n return res.data\n },\n\n // Auto-pagination scaffold — v1 server returns a single page up to\n // limit=500. When cursor pagination lands this is where it gets wired.\n getLedgerAll: async function* (opts: { limit?: number } = {}): AsyncIterable<LedgerEntry> {\n const page = await credits.getLedger(opts)\n for (const e of page) yield e\n },\n }\n return credits\n}\n\nexport type CreditsResource = ReturnType<typeof createCreditsResource>\n","import type { HttpClient } from '../http'\nimport type { CallTokenMintInput, CallTokenMintResult, CallTokenSummary } from '../types'\n\n// Short-lived, agent-scoped `ct_` tokens. Mint one per user session on your\n// backend, hand the raw value to the browser; let this SDK handle lifecycle\n// (revoke on sign-out, list active tokens for an admin panel).\n\nexport const createCallTokensResource = (http: HttpClient) => ({\n // Returns the RAW token value once. Don't log it; pass it straight to the\n // browser + discard server-side. `tokenId` is the stable public handle\n // used for revocation later.\n mint: async (input: CallTokenMintInput): Promise<CallTokenMintResult> =>\n http.request<CallTokenMintResult>({\n method: 'POST',\n path: '/v1/call-tokens',\n body: input,\n }),\n\n // Live tokens only by default. Pass includeRevoked/includeExpired when\n // debugging \"why did my token stop working\".\n list: async (\n opts: { includeRevoked?: boolean; includeExpired?: boolean; limit?: number } = {},\n ): Promise<CallTokenSummary[]> => {\n const query: Record<string, string | number | undefined> = {}\n if (opts.includeRevoked) query.includeRevoked = '1'\n if (opts.includeExpired) query.includeExpired = '1'\n if (opts.limit !== undefined) query.limit = opts.limit\n const res = await http.request<{ data: CallTokenSummary[] }>({\n method: 'GET',\n path: '/v1/call-tokens',\n query,\n })\n return res.data\n },\n\n // Idempotent — re-revoking a revoked token returns `alreadyRevoked: true`.\n revoke: async (\n tokenId: string,\n ): Promise<{ tokenId: string; revoked: boolean; alreadyRevoked?: boolean }> =>\n http.request<{ tokenId: string; revoked: boolean; alreadyRevoked?: boolean }>({\n method: 'DELETE',\n path: `/v1/call-tokens/${tokenId}`,\n }),\n})\n\nexport type CallTokensResource = ReturnType<typeof createCallTokensResource>\n","import type { HttpClient } from '../http'\nimport type { WebhookDelivery } from '../types'\n\n// Org-wide webhook delivery log. Per-agent CRUD lives on\n// `client.agents.webhooks(agentId)` — this namespace is just the\n// read-only deliveries surface that spans all agents.\n\nexport const createWebhooksResource = (http: HttpClient) => ({\n deliveries: async (\n filters: {\n agentId?: string\n webhookId?: string\n callId?: string\n limit?: number\n } = {},\n ): Promise<WebhookDelivery[]> => {\n const res = await http.request<{ data: WebhookDelivery[] }>({\n method: 'GET',\n path: '/v1/webhooks/deliveries',\n query: filters as Record<string, string | number | undefined>,\n })\n return res.data\n },\n})\n\nexport type WebhooksResource = ReturnType<typeof createWebhooksResource>\n","import type { HttpClient } from '../http'\nimport type { CatalogAgent, CatalogListInput } from '../types'\n\n// Org-scoped consumer endpoints. Today this is just the agent catalog —\n// the trimmed shape your mobile app picks an agent from. Lives at\n// `/v1/orgs/:orgId/agents` rather than reusing the admin `/v1/agents/*`\n// tree on purpose: the catalog response intentionally excludes the\n// operator-only fields (system prompt, tools, KB IDs) so a leaked\n// consumer-backend `sk_` can't lift the operator config out of it.\n//\n// Pattern from your backend:\n//\n// const client = new PlatformClient({ apiKey: process.env.SK })\n// const visible = await client.orgs.listAgents({\n// orgId: process.env.ORG_ID!,\n// userTags: ['tier1'], // omit to get the unfiltered admin view\n// })\n// res.json(visible)\n\nexport const createOrgsResource = (http: HttpClient) => ({\n /**\n * Fetch the agent catalog for an org. Returns the consumer-trimmed shape;\n * no system prompt, tools, or KB info. Use `client.agents.get(agentId)`\n * with the same `sk_` if you need the full admin shape.\n *\n * `userTags`: end-user entitlement tags. When supplied, hides agents\n * whose `allowedUserTags` is non-empty and doesn't intersect with the\n * supplied list. Omit to get the unfiltered admin view.\n *\n * Persona / category filtering is intentionally not a server param —\n * filter the returned list client-side over `name`s if you need it.\n *\n * Throws `403 forbidden` if `orgId` doesn't match the key's org.\n */\n listAgents: async (input: CatalogListInput): Promise<CatalogAgent[]> => {\n const query: Record<string, string | undefined> = {}\n if (input.userTags && input.userTags.length > 0) query.userTags = input.userTags.join(',')\n const res = await http.request<{ data: CatalogAgent[] }>({\n method: 'GET',\n path: `/v1/orgs/${input.orgId}/agents`,\n query,\n })\n return res.data\n },\n})\n\nexport type OrgsResource = ReturnType<typeof createOrgsResource>\n","import type { HttpClient } from '../http'\nimport type {\n CreateRoomInput,\n CreateRoomResponse,\n ListRoomsResponse,\n ListUtterancesResponse,\n RoomDoc,\n RoomEventAck,\n RoomListFilters,\n RoomTranscriptOptions,\n} from '../types'\n\n// REST wrappers for /v1/rooms — the multi-party video room surface (see\n// docs/superpowers/specs/2026-05-18-multiparty-rooms-design.md). Lets\n// server-side code mint rooms, fetch state, list transcript pages, and end\n// rooms programmatically.\n//\n// Auth model: same Bearer `sk_` flow as every other resource — the server\n// derives `orgId` from the API key, so the SDK never sets a tenant header.\n//\n// Host actions beyond `end` (promote/demote/kick) and observer-token mint\n// live in the server but aren't surfaced here yet — they're operator-side\n// flows that the dashboard hits directly. Re-add here if a programmatic\n// use-case shows up (CI tests, integration harnesses).\n\nexport const createRoomsResource = (http: HttpClient) => ({\n // Provision a new room. Server returns 201 with ONE shared room-level\n // `joinToken` + `joinUrl`. Share the single link with everyone you want in\n // the room — each visitor supplies their own display name at join time and\n // becomes a fresh, distinct participant. The server persists only the\n // token's sha256 hash; the raw token is returned here once and never stored.\n create: async (input: CreateRoomInput): Promise<CreateRoomResponse> =>\n http.request<CreateRoomResponse>({\n method: 'POST',\n path: '/v1/rooms',\n body: input,\n }),\n\n // Listing — opaque cursor pagination (`nextCursor` returned by the server\n // is whatever startAfter() needs, don't parse client-side).\n list: async (filters: RoomListFilters = {}): Promise<ListRoomsResponse> => {\n const query: Record<string, string | number | undefined> = {}\n if (filters.status) query.status = filters.status\n if (filters.limit !== undefined) query.limit = filters.limit\n if (filters.cursor) query.cursor = filters.cursor\n return http.request<ListRoomsResponse>({\n method: 'GET',\n path: '/v1/rooms',\n query,\n })\n },\n\n // Fetch a single room. 404s are surfaced as PlatformError('not_found').\n get: async (roomId: string): Promise<RoomDoc> =>\n http.request<RoomDoc>({\n method: 'GET',\n path: `/v1/rooms/${roomId}`,\n }),\n\n // Transcript pages — utterances are ordered by `startedAt asc`. Cursor is\n // an ISO timestamp (server enforces, don't construct yourself).\n transcript: async (\n roomId: string,\n opts: RoomTranscriptOptions = {},\n ): Promise<ListUtterancesResponse> => {\n const query: Record<string, string | number | undefined> = {}\n if (opts.cursor) query.cursor = opts.cursor\n if (opts.limit !== undefined) query.limit = opts.limit\n return http.request<ListUtterancesResponse>({\n method: 'GET',\n path: `/v1/rooms/${roomId}/transcript`,\n query,\n })\n },\n\n // End a room — async on the server: returns 202 + eventId once the\n // controlEvents entry is written. The room-worker observes the entry,\n // broadcasts the system message, and tears down LiveKit shortly after.\n end: async (roomId: string): Promise<RoomEventAck> =>\n http.request<RoomEventAck>({\n method: 'POST',\n path: `/v1/rooms/${roomId}/end`,\n }),\n})\n\nexport type RoomsResource = ReturnType<typeof createRoomsResource>\n","import type { HttpClient } from '../http'\nimport type { ChatEvent } from '../types'\n\nexport interface StartChatInput {\n agentId: string\n text?: string\n}\n\nexport interface Chat {\n id: string\n callId: string\n greeting: AsyncIterable<ChatEvent>\n send(text: string): AsyncIterable<ChatEvent>\n end(): Promise<void>\n}\n\n/**\n * Per-token chat resource. Construct via `client.chatsFor(callToken)` —\n * `callToken` is a raw `ct_…` minted with `channel: 'text'`.\n *\n * The async iterables stream SSE events: `chat.started` (start only),\n * then a sequence of `token` / `tool.call` / `tool.result` / `error`,\n * then `turn.end` which closes the stream. The client must NOT keep\n * a connection open between turns — each `send` is a fresh POST.\n */\nexport const createChatsResource = (http: HttpClient, callToken: string) => ({\n async start(input: StartChatInput): Promise<Chat> {\n const tokenQs = `?token=${encodeURIComponent(callToken)}`\n const streamIterable = http.stream<ChatEvent>({\n method: 'POST',\n path: `/v1/agents/${input.agentId}/chat${tokenQs}`,\n body: input.text ? { text: input.text } : {},\n })\n\n // Pull events from the stream until we see chat.started — that's our\n // first event and carries the ids. Pass the rest through as `greeting`.\n let chatId = ''\n let callId = ''\n const buffered: ChatEvent[] = []\n const iter = streamIterable[Symbol.asyncIterator]()\n while (true) {\n const { value, done } = await iter.next()\n if (done) break\n if (value.type === 'chat.started') {\n chatId = value.chatId\n callId = value.callId\n break\n }\n buffered.push(value)\n }\n\n return {\n id: chatId,\n callId,\n greeting: replayThen(buffered, { [Symbol.asyncIterator]: () => iter }),\n send(text: string) {\n return http.stream<ChatEvent>({\n method: 'POST',\n path: `/v1/chats/${chatId}/messages${tokenQs}`,\n body: { text },\n })\n },\n async end() {\n await http.request({ method: 'DELETE', path: `/v1/calls/${callId}` })\n },\n }\n },\n})\n\nasync function* replayThen<T>(buffered: T[], rest: AsyncIterable<T>): AsyncIterable<T> {\n for (const x of buffered) yield x\n for await (const x of rest) yield x\n}\n\nexport type ChatsResource = ReturnType<typeof createChatsResource>\n","import { createHttpClient, type HttpClient, type HttpClientOptions } from './http'\nimport { createMeResource, type MeResource } from './resources/me'\nimport { createAgentsResource, type AgentsResource } from './resources/agents'\nimport { createCallsResource, type CallsResource } from './resources/calls'\nimport {\n createKnowledgeBasesResource,\n type KnowledgeBasesResource,\n} from './resources/knowledgeBases'\nimport { createCreditsResource, type CreditsResource } from './resources/credits'\nimport { createCallTokensResource, type CallTokensResource } from './resources/callTokens'\nimport { createWebhooksResource, type WebhooksResource } from './resources/webhooks'\nimport { createOrgsResource, type OrgsResource } from './resources/orgs'\nimport { createRoomsResource, type RoomsResource } from './resources/rooms'\nimport { createChatsResource, type ChatsResource } from './resources/chats'\n\nexport interface PlatformClientOptions {\n // Full-org API key minted from the dashboard or bootstrap CLI. Start with\n // `sk_`. Never ship to a browser — use `client.callTokens.mint(...)` to\n // generate a narrow `ct_` token for client-side use instead.\n apiKey: string\n // Defaults to the hosted platform. Point at `http://localhost:8080` for\n // local dev or at a self-hosted deployment.\n baseUrl?: string\n // Passthrough tuning for the HTTP layer.\n timeoutMs?: number\n maxRetries?: number\n fetch?: HttpClientOptions['fetch']\n onRequest?: HttpClientOptions['onRequest']\n}\n\n// Single entry point. All resources are lazy-constructed in the constructor\n// so their refs don't incur any per-call allocation. Shape mirrors Stripe /\n// Twilio / Vapi's `resource.method()` convention for familiarity.\nexport class PlatformClient {\n readonly me: MeResource\n readonly agents: AgentsResource\n readonly calls: CallsResource\n readonly knowledgeBases: KnowledgeBasesResource\n readonly credits: CreditsResource\n readonly callTokens: CallTokensResource\n readonly webhooks: WebhooksResource\n readonly orgs: OrgsResource\n readonly rooms: RoomsResource\n private readonly _http: HttpClient\n\n constructor(options: PlatformClientOptions) {\n if (!options.apiKey) {\n throw new Error('PlatformClient: `apiKey` is required')\n }\n const http = createHttpClient({\n apiKey: options.apiKey,\n baseUrl: options.baseUrl ?? 'https://api.example.com',\n timeoutMs: options.timeoutMs,\n maxRetries: options.maxRetries,\n fetch: options.fetch,\n onRequest: options.onRequest,\n })\n\n this.me = createMeResource(http)\n this.agents = createAgentsResource(http)\n this.calls = createCallsResource(http)\n this.knowledgeBases = createKnowledgeBasesResource(http)\n this.credits = createCreditsResource(http)\n this.callTokens = createCallTokensResource(http)\n this.webhooks = createWebhooksResource(http)\n this.orgs = createOrgsResource(http)\n this.rooms = createRoomsResource(http)\n this._http = http\n }\n\n /**\n * Returns a per-token chat resource bound to the given `ct_…` call token.\n * The token must have been minted with `channel: 'text'`.\n *\n * Note: `chatsFor` is a factory method (not a fixed property) because the\n * underlying resource is scoped to a single call token, whereas this client\n * was constructed with an `sk_` admin key. Each end-user session needs its\n * own `chatsFor(token)` handle.\n */\n public chatsFor(callToken: string): ChatsResource {\n return createChatsResource(this._http, callToken)\n }\n}\n","import crypto from 'node:crypto'\n\n// Helper for consumers receiving webhooks: verify the `X-Platform-Signature-256`\n// header against the raw body + secret. Plain function (not tied to\n// PlatformClient) so Express/Koa/Next.js middleware can use it without\n// instantiating a client.\n//\n// import { verifyWebhookSignature } from '@craftedxp/sdk-node'\n// app.post('/webhooks/voice-agent', express.raw({ type: 'application/json' }), (req, res) => {\n// const sig = req.header('X-Platform-Signature-256') ?? ''\n// if (!verifyWebhookSignature(req.body, sig, process.env.VOICE_AGENT_WEBHOOK_SECRET!)) {\n// return res.status(401).send('invalid signature')\n// }\n// const event = JSON.parse(req.body.toString('utf8'))\n// // ...handle event\n// })\n//\n// The signature is `sha256=<hex HMAC-SHA256 of rawBody with secret>`.\n// Timing-safe compare to avoid microtiming side channels.\n\nexport const verifyWebhookSignature = (\n rawBody: Buffer | string,\n signatureHeader: string,\n secret: string,\n): boolean => {\n if (!signatureHeader || !secret) return false\n const [algo, provided] = signatureHeader.split('=')\n if (algo !== 'sha256' || !provided) return false\n\n const expected = crypto\n .createHmac('sha256', secret)\n .update(typeof rawBody === 'string' ? rawBody : rawBody)\n .digest('hex')\n\n // Buffers must match in length for timingSafeEqual.\n const a = Buffer.from(expected, 'hex')\n const b = Buffer.from(provided, 'hex')\n if (a.length !== b.length) return false\n return crypto.timingSafeEqual(a, b)\n}\n"],"mappings":";AAmBO,IAAM,gBAAN,MAAM,uBAAsB,MAAM;AAAA,EAC9B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA,EAIA;AAAA,EAET,YAAY,QAOT;AACD,UAAM,OAAO,OAAO;AACpB,SAAK,OAAO;AACZ,SAAK,OAAO,OAAO;AACnB,SAAK,SAAS,OAAO;AACrB,SAAK,QAAQ,OAAO;AACpB,SAAK,UAAU,OAAO;AACtB,SAAK,OAAO,OAAO;AAGnB,QACE,OAAQ,MAAyD,sBACjE,YACA;AACA;AAAC,MACC,MACA,kBAAkB,MAAM,cAAa;AAAA,IACzC;AAAA,EACF;AAAA,EAEA,SAAkC;AAChC,WAAO;AAAA,MACL,MAAM,KAAK;AAAA,MACX,MAAM,KAAK;AAAA,MACX,SAAS,KAAK;AAAA,MACd,QAAQ,KAAK;AAAA,MACb,OAAO,KAAK;AAAA,MACZ,SAAS,KAAK;AAAA,IAChB;AAAA,EACF;AACF;;;ACtBA,IAAM,qBAAqB;AAC3B,IAAM,sBAAsB;AAE5B,IAAM,WAAW,CAAC,SAAiBA,OAAc,UAAyC;AACxF,QAAM,IAAI,IAAI,IAAIA,OAAM,OAAO;AAC/B,MAAI,OAAO;AACT,eAAW,CAAC,GAAG,CAAC,KAAK,OAAO,QAAQ,KAAK,GAAG;AAC1C,UAAI,MAAM,OAAW;AACrB,QAAE,aAAa,IAAI,GAAG,OAAO,CAAC,CAAC;AAAA,IACjC;AAAA,EACF;AACA,SAAO,EAAE,SAAS;AACpB;AAEA,IAAM,QAAQ,CAAC,OAAe,IAAI,QAAc,CAAC,MAAM,WAAW,GAAG,EAAE,CAAC;AA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GAAG,CAAC;AACpC;","names":["path"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@craftedxp/sdk-node",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.12.0",
|
|
4
4
|
"description": "Node.js / TypeScript SDK for the voice agent platform. Server-side API client — mint call tokens, manage agents, query calls, upload knowledge-base docs.",
|
|
5
5
|
"author": "Crafted XP",
|
|
6
6
|
"license": "MIT",
|