@fazpi-ai/sdk 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +35 -2
- package/dist/client.d.ts +33 -0
- package/dist/client.js +54 -0
- package/dist/errors.d.ts +18 -0
- package/dist/errors.js +27 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +2 -0
- package/dist/stream.d.ts +11 -0
- package/dist/stream.js +132 -0
- package/dist/transport.d.ts +32 -0
- package/dist/transport.js +197 -0
- package/dist/types.d.ts +79 -0
- package/dist/types.js +1 -0
- package/package.json +50 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Fazpi AI
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,36 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @fazpi-ai/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
TypeScript and JavaScript client for Node.js 20+. Version 0.2.0. No browser SDK or UI.
|
|
4
|
+
|
|
5
|
+
```js
|
|
6
|
+
import { Fazpi } from '@fazpi-ai/sdk';
|
|
7
|
+
const client = new Fazpi({ apiKey: process.env.FAZPI_API_KEY, baseURL: process.env.FAZPI_BASE_URL });
|
|
8
|
+
const conversation = await client.conversations.create({ subject_id: trustedUserID, target: { type: 'agent', id: agentID } });
|
|
9
|
+
const run = await client.conversations.messages.create(conversation.id, { text: 'Hello' }, { idempotencyKey: durableOperationID });
|
|
10
|
+
for await (const event of client.runs.stream(run.id)) {
|
|
11
|
+
await handlePublicEvent(event);
|
|
12
|
+
// Persist event.id after processing. Keep it as a string.
|
|
13
|
+
}
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
Install with `npm install @fazpi-ai/sdk@0.2.0` or `pnpm add @fazpi-ai/sdk@0.2.0`. For the deployed API, use base URL `https://api.fazpi.ai/v2/api/v1`. Applications import the package by name; source-checkout examples use the local build.
|
|
17
|
+
|
|
18
|
+
Persist `conversation.id` and retrieve it in another process to continue without resending history. Both Go and Node clients use the same conversation IDs. For a group, use target type `group`.
|
|
19
|
+
|
|
20
|
+
Events include visible text, messages, agent attribution, thinking/tool/compaction activity and run states. Tools execute within Fazpi. Private reasoning, tool arguments/results, prompts and secrets are not part of the public event contract. No remote browser controls are exposed.
|
|
21
|
+
|
|
22
|
+
Use `runs.stream(runID, {after: lastProcessedEventID})` to resume observation. Closing the iterator or aborting its signal does not cancel inference; use `runs.cancel(runID)` explicitly. A conversation ID is not a credential. Keep the key in your backend and authenticate your end users before granting access to conversations.
|
|
23
|
+
|
|
24
|
+
Defaults: 30-second request/stream-connection timeout, two request retries, two observer reconnections, 8 MiB JSON response limit, 1 MiB SSE frame limit. Set a longer `timeoutMs` for long-running agents. Retries preserve idempotency keys; persist your own key to recover writes across process restarts. No automatic model fallback.
|
|
25
|
+
|
|
26
|
+
Errors are typed: `APIError` includes status, code and requestID; `TransportError`, `ProtocolError`, `TimeoutError` and `AbortError` identify client/transport failures. HTTP is restricted to loopback unless explicitly enabled. Redirects never forward credentials.
|
|
27
|
+
|
|
28
|
+
See the repository root README and `RELEASING.md` for runnable Go/Node examples, tests, local API setup, limitations and verification evidence. The SDK is backend-only and requires an authorized Fazpi integration key.
|
|
29
|
+
|
|
30
|
+
## PDF attachments (0.2.0)
|
|
31
|
+
|
|
32
|
+
Send `files: [{ name: "documento.pdf", content_base64: pdf.toString("base64") }]`
|
|
33
|
+
with `conversations.messages.create`. Up to five PDFs, 10 MiB per PDF and 20 MiB
|
|
34
|
+
combined. Use `text: ""` for PDF-only messages and reuse the same idempotency key
|
|
35
|
+
when retrying. The matching server update must be deployed. History and message
|
|
36
|
+
events include safe `files` metadata. See the repository README for full examples.
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { type StreamOptions } from './stream.js';
|
|
2
|
+
import type { Conversation, CreateConversation, CreateMessage, MessagePage, Run } from './types.js';
|
|
3
|
+
import { Transport, type ClientOptions, type RequestOptions } from './transport.js';
|
|
4
|
+
export interface MessageListParams {
|
|
5
|
+
after?: string;
|
|
6
|
+
limit?: number;
|
|
7
|
+
}
|
|
8
|
+
declare class Messages {
|
|
9
|
+
private readonly transport;
|
|
10
|
+
constructor(transport: Transport);
|
|
11
|
+
create(conversationID: string, body: CreateMessage, options?: RequestOptions): Promise<Run>;
|
|
12
|
+
list(conversationID: string, params?: MessageListParams, options?: RequestOptions): Promise<MessagePage>;
|
|
13
|
+
}
|
|
14
|
+
declare class Conversations {
|
|
15
|
+
private readonly transport;
|
|
16
|
+
readonly messages: Messages;
|
|
17
|
+
constructor(transport: Transport);
|
|
18
|
+
create(body: CreateConversation, options?: RequestOptions): Promise<Conversation>;
|
|
19
|
+
retrieve(id: string, options?: RequestOptions): Promise<Conversation>;
|
|
20
|
+
}
|
|
21
|
+
declare class Runs {
|
|
22
|
+
private readonly transport;
|
|
23
|
+
stream(id: string, options?: StreamOptions): AsyncGenerator<import("./types.js").PublicEvent, any, any>;
|
|
24
|
+
constructor(transport: Transport);
|
|
25
|
+
retrieve(id: string, options?: RequestOptions): Promise<Run>;
|
|
26
|
+
cancel(id: string, options?: RequestOptions): Promise<Run>;
|
|
27
|
+
}
|
|
28
|
+
export declare class Fazpi {
|
|
29
|
+
readonly conversations: Conversations;
|
|
30
|
+
readonly runs: Runs;
|
|
31
|
+
constructor(options: ClientOptions);
|
|
32
|
+
}
|
|
33
|
+
export default Fazpi;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { streamRun } from './stream.js';
|
|
2
|
+
import { Transport, operationKey, resourceID } from './transport.js';
|
|
3
|
+
class Messages {
|
|
4
|
+
transport;
|
|
5
|
+
constructor(transport) {
|
|
6
|
+
this.transport = transport;
|
|
7
|
+
}
|
|
8
|
+
create(conversationID, body, options = {}) {
|
|
9
|
+
return this.transport.request('POST', `/conversations/${resourceID(conversationID)}/messages`, body, { ...options, idempotencyKey: operationKey(options.idempotencyKey) });
|
|
10
|
+
}
|
|
11
|
+
list(conversationID, params = {}, options) {
|
|
12
|
+
const query = new URLSearchParams();
|
|
13
|
+
if (params.after !== undefined)
|
|
14
|
+
query.set('after', params.after);
|
|
15
|
+
if (params.limit !== undefined)
|
|
16
|
+
query.set('limit', String(params.limit));
|
|
17
|
+
// Transport appends paths to preserve deployment prefixes such as /v2.
|
|
18
|
+
const path = `/conversations/${resourceID(conversationID)}/messages`;
|
|
19
|
+
return this.transport.request('GET', path, undefined, options, true, query);
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
class Conversations {
|
|
23
|
+
transport;
|
|
24
|
+
messages;
|
|
25
|
+
constructor(transport) {
|
|
26
|
+
this.transport = transport;
|
|
27
|
+
this.messages = new Messages(transport);
|
|
28
|
+
}
|
|
29
|
+
create(body, options = {}) {
|
|
30
|
+
return this.transport.request('POST', '/conversations', body, { ...options, idempotencyKey: operationKey(options.idempotencyKey) });
|
|
31
|
+
}
|
|
32
|
+
retrieve(id, options) {
|
|
33
|
+
return this.transport.request('GET', `/conversations/${resourceID(id)}`, undefined, options);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
class Runs {
|
|
37
|
+
transport;
|
|
38
|
+
stream(id, options) { return streamRun(this.transport, id, options); }
|
|
39
|
+
constructor(transport) {
|
|
40
|
+
this.transport = transport;
|
|
41
|
+
}
|
|
42
|
+
retrieve(id, options) { return this.transport.request('GET', `/runs/${resourceID(id)}`, undefined, options); }
|
|
43
|
+
cancel(id, options) { return this.transport.request('POST', `/runs/${resourceID(id)}/cancel`, undefined, options, true); }
|
|
44
|
+
}
|
|
45
|
+
export class Fazpi {
|
|
46
|
+
conversations;
|
|
47
|
+
runs;
|
|
48
|
+
constructor(options) {
|
|
49
|
+
const transport = new Transport(options);
|
|
50
|
+
this.conversations = new Conversations(transport);
|
|
51
|
+
this.runs = new Runs(transport);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
export default Fazpi;
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export declare class FazpiError extends Error {
|
|
2
|
+
constructor(message: string, options?: ErrorOptions);
|
|
3
|
+
}
|
|
4
|
+
export declare class APIError extends FazpiError {
|
|
5
|
+
readonly status: number;
|
|
6
|
+
readonly code: string;
|
|
7
|
+
readonly requestID: string;
|
|
8
|
+
readonly retryAfterMs?: number | undefined;
|
|
9
|
+
constructor(status: number, code: string, message: string, requestID: string, retryAfterMs?: number | undefined);
|
|
10
|
+
}
|
|
11
|
+
export declare class TransportError extends FazpiError {
|
|
12
|
+
}
|
|
13
|
+
export declare class ProtocolError extends FazpiError {
|
|
14
|
+
}
|
|
15
|
+
export declare class TimeoutError extends FazpiError {
|
|
16
|
+
}
|
|
17
|
+
export declare class AbortError extends FazpiError {
|
|
18
|
+
}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
export class FazpiError extends Error {
|
|
2
|
+
constructor(message, options) {
|
|
3
|
+
super(message, options);
|
|
4
|
+
this.name = new.target.name;
|
|
5
|
+
}
|
|
6
|
+
}
|
|
7
|
+
export class APIError extends FazpiError {
|
|
8
|
+
status;
|
|
9
|
+
code;
|
|
10
|
+
requestID;
|
|
11
|
+
retryAfterMs;
|
|
12
|
+
constructor(status, code, message, requestID, retryAfterMs) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.status = status;
|
|
15
|
+
this.code = code;
|
|
16
|
+
this.requestID = requestID;
|
|
17
|
+
this.retryAfterMs = retryAfterMs;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
export class TransportError extends FazpiError {
|
|
21
|
+
}
|
|
22
|
+
export class ProtocolError extends FazpiError {
|
|
23
|
+
}
|
|
24
|
+
export class TimeoutError extends FazpiError {
|
|
25
|
+
}
|
|
26
|
+
export class AbortError extends FazpiError {
|
|
27
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export type { Target, Agent, Conversation, Message, File, RunStatus, APIErrorBody, Run, MessagePage, CreateConversation, CreateMessage, InputFile, PublicEvent, Activity, } from './types.js';
|
|
2
|
+
export { Fazpi, default } from './client.js';
|
|
3
|
+
export type { MessageListParams } from './client.js';
|
|
4
|
+
export type { ClientOptions, RequestOptions } from './transport.js';
|
|
5
|
+
export { FazpiError, APIError, TransportError, ProtocolError, TimeoutError, AbortError } from './errors.js';
|
|
6
|
+
export type { StreamOptions } from './stream.js';
|
package/dist/index.js
ADDED
package/dist/stream.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { type RequestOptions, type Transport } from './transport.js';
|
|
2
|
+
import type { PublicEvent } from './types.js';
|
|
3
|
+
export interface StreamOptions extends RequestOptions {
|
|
4
|
+
/** Last fully processed event ID, persisted as a string. */
|
|
5
|
+
after?: string;
|
|
6
|
+
/** Bounded automatic reconnections; never resends the user message. Default 2. */
|
|
7
|
+
maxReconnects?: number;
|
|
8
|
+
}
|
|
9
|
+
/** Incremental SSE framing, bounded even when a peer omits frame/line separators. */
|
|
10
|
+
export declare function parseEvents(body: ReadableStream<Uint8Array>): AsyncGenerator<PublicEvent>;
|
|
11
|
+
export declare function streamRun(transport: Transport, runID: string, options?: StreamOptions): AsyncGenerator<PublicEvent>;
|
package/dist/stream.js
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { APIError, AbortError, ProtocolError, TransportError } from './errors.js';
|
|
2
|
+
import { resourceID } from './transport.js';
|
|
3
|
+
function cursor(value) {
|
|
4
|
+
if (!/^[0-9]+$/.test(value) || value.length > 19 || BigInt(value) > 9223372036854775807n)
|
|
5
|
+
throw new ProtocolError('Invalid stream cursor.');
|
|
6
|
+
return BigInt(value);
|
|
7
|
+
}
|
|
8
|
+
/** Incremental SSE framing, bounded even when a peer omits frame/line separators. */
|
|
9
|
+
export async function* parseEvents(body) {
|
|
10
|
+
const reader = body.getReader();
|
|
11
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
12
|
+
const maxFrame = 1024 * 1024;
|
|
13
|
+
let pending = '';
|
|
14
|
+
let data = [];
|
|
15
|
+
let id = '';
|
|
16
|
+
let event = '';
|
|
17
|
+
let size = 0;
|
|
18
|
+
let skipLF = false;
|
|
19
|
+
function line(value) {
|
|
20
|
+
size += Buffer.byteLength(value, 'utf8') + 1;
|
|
21
|
+
if (size > maxFrame)
|
|
22
|
+
throw new ProtocolError('SSE frame exceeds 1 MiB.');
|
|
23
|
+
if (value === '') {
|
|
24
|
+
let parsed;
|
|
25
|
+
if (data.length) {
|
|
26
|
+
try {
|
|
27
|
+
parsed = JSON.parse(data.join('\n'));
|
|
28
|
+
}
|
|
29
|
+
catch {
|
|
30
|
+
throw new ProtocolError('Invalid SSE JSON.');
|
|
31
|
+
}
|
|
32
|
+
if (!parsed || typeof parsed !== 'object' || typeof parsed.id !== 'string' || !id || parsed.id !== id || parsed.type !== event || typeof parsed.run_id !== 'string' || typeof parsed.conversation_id !== 'string')
|
|
33
|
+
throw new ProtocolError('Invalid SSE event envelope.');
|
|
34
|
+
cursor(id);
|
|
35
|
+
}
|
|
36
|
+
data = [];
|
|
37
|
+
id = '';
|
|
38
|
+
event = '';
|
|
39
|
+
size = 0;
|
|
40
|
+
return parsed;
|
|
41
|
+
}
|
|
42
|
+
if (value.startsWith(':'))
|
|
43
|
+
return;
|
|
44
|
+
const colon = value.indexOf(':');
|
|
45
|
+
const field = colon < 0 ? value : value.slice(0, colon);
|
|
46
|
+
let content = colon < 0 ? '' : value.slice(colon + 1);
|
|
47
|
+
if (content.startsWith(' '))
|
|
48
|
+
content = content.slice(1);
|
|
49
|
+
if (field === 'data')
|
|
50
|
+
data.push(content);
|
|
51
|
+
else if (field === 'id')
|
|
52
|
+
id = content;
|
|
53
|
+
else if (field === 'event')
|
|
54
|
+
event = content;
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
try {
|
|
58
|
+
for (;;) {
|
|
59
|
+
const { value, done } = await reader.read();
|
|
60
|
+
let decoded;
|
|
61
|
+
try {
|
|
62
|
+
decoded = done ? decoder.decode() : decoder.decode(value, { stream: true });
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
throw new ProtocolError('Invalid UTF-8 stream.');
|
|
66
|
+
}
|
|
67
|
+
for (const char of decoded) {
|
|
68
|
+
if (skipLF) {
|
|
69
|
+
skipLF = false;
|
|
70
|
+
if (char === '\n')
|
|
71
|
+
continue;
|
|
72
|
+
}
|
|
73
|
+
if (char === '\r' || char === '\n') {
|
|
74
|
+
const result = line(pending);
|
|
75
|
+
pending = '';
|
|
76
|
+
skipLF = char === '\r';
|
|
77
|
+
if (result)
|
|
78
|
+
yield result;
|
|
79
|
+
}
|
|
80
|
+
else {
|
|
81
|
+
pending += char;
|
|
82
|
+
if (pending.length > maxFrame)
|
|
83
|
+
throw new ProtocolError('SSE line exceeds 1 MiB.');
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
if (done)
|
|
87
|
+
return; // An incomplete final frame is deliberately not delivered/acknowledged.
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
finally {
|
|
91
|
+
await reader.cancel().catch(() => { });
|
|
92
|
+
reader.releaseLock();
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
export async function* streamRun(transport, runID, options = {}) {
|
|
96
|
+
resourceID(runID);
|
|
97
|
+
let after = options.after ?? '0';
|
|
98
|
+
cursor(after);
|
|
99
|
+
const reconnects = options.maxReconnects ?? 2;
|
|
100
|
+
if (!Number.isSafeInteger(reconnects) || reconnects < 0 || reconnects > 5)
|
|
101
|
+
throw new TypeError('Invalid maxReconnects.');
|
|
102
|
+
for (let attempt = 0;; attempt++) {
|
|
103
|
+
let opened;
|
|
104
|
+
try {
|
|
105
|
+
opened = await transport.request('GET', `/runs/${runID}/events`, undefined, options, true, new URLSearchParams({ after }), true);
|
|
106
|
+
if (!opened.response.body)
|
|
107
|
+
throw new ProtocolError('Missing SSE response body.');
|
|
108
|
+
for await (const value of parseEvents(opened.response.body)) {
|
|
109
|
+
if (value.run_id !== runID)
|
|
110
|
+
throw new ProtocolError('Stream returned another run.');
|
|
111
|
+
if (cursor(value.id) <= cursor(after))
|
|
112
|
+
continue;
|
|
113
|
+
after = value.id;
|
|
114
|
+
yield value;
|
|
115
|
+
if ((value.type === 'run.status' || value.type === 'run.error') && value.run && ['completed', 'failed', 'cancelled'].includes(value.run.status))
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
catch (error) {
|
|
120
|
+
if (options.signal?.aborted)
|
|
121
|
+
throw new AbortError('Stream aborted.');
|
|
122
|
+
if (error instanceof ProtocolError || error instanceof APIError || attempt >= reconnects)
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
finally {
|
|
126
|
+
opened?.close();
|
|
127
|
+
await opened?.response.body?.cancel().catch(() => { });
|
|
128
|
+
}
|
|
129
|
+
if (attempt >= reconnects)
|
|
130
|
+
throw new TransportError('Stream ended before a terminal run status; resume using the last processed event ID.');
|
|
131
|
+
}
|
|
132
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
export interface ClientOptions {
|
|
2
|
+
apiKey: string;
|
|
3
|
+
baseURL: string;
|
|
4
|
+
fetch?: typeof globalThis.fetch;
|
|
5
|
+
timeoutMs?: number;
|
|
6
|
+
maxRetries?: number;
|
|
7
|
+
maxResponseBytes?: number;
|
|
8
|
+
allowInsecureHTTP?: boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface RequestOptions {
|
|
11
|
+
signal?: AbortSignal;
|
|
12
|
+
timeoutMs?: number;
|
|
13
|
+
maxRetries?: number;
|
|
14
|
+
/** Persist this key when retrying an operation from another process. */
|
|
15
|
+
idempotencyKey?: string;
|
|
16
|
+
}
|
|
17
|
+
export declare function resourceID(id: string): string;
|
|
18
|
+
export declare function operationKey(value?: string): string;
|
|
19
|
+
export interface OpenedStream {
|
|
20
|
+
response: Response;
|
|
21
|
+
close: () => void;
|
|
22
|
+
}
|
|
23
|
+
export declare class Transport {
|
|
24
|
+
readonly baseURL: URL;
|
|
25
|
+
readonly timeoutMs: number;
|
|
26
|
+
readonly maxRetries: number;
|
|
27
|
+
readonly maxResponseBytes: number;
|
|
28
|
+
private readonly credential;
|
|
29
|
+
private readonly fetcher;
|
|
30
|
+
constructor(options: ClientOptions);
|
|
31
|
+
request<T>(method: string, path: string, body: unknown, options?: RequestOptions, safe?: boolean, query?: URLSearchParams, stream?: boolean): Promise<T>;
|
|
32
|
+
}
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { APIError, AbortError, ProtocolError, TimeoutError, TransportError } from './errors.js';
|
|
3
|
+
function integer(value, min, max, name) {
|
|
4
|
+
if (!Number.isSafeInteger(value) || value < min || value > max)
|
|
5
|
+
throw new TypeError(`Invalid ${name}.`);
|
|
6
|
+
return value;
|
|
7
|
+
}
|
|
8
|
+
export function resourceID(id) {
|
|
9
|
+
if (typeof id !== 'string' || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id))
|
|
10
|
+
throw new TypeError('Invalid resource ID.');
|
|
11
|
+
return id;
|
|
12
|
+
}
|
|
13
|
+
export function operationKey(value) {
|
|
14
|
+
const key = value ?? randomUUID();
|
|
15
|
+
if (!/^[\x21-\x7e]{1,128}$/.test(key))
|
|
16
|
+
throw new TypeError('Invalid idempotency key.');
|
|
17
|
+
return key;
|
|
18
|
+
}
|
|
19
|
+
function abortScope(signal, timeoutMs) {
|
|
20
|
+
const controller = new AbortController();
|
|
21
|
+
let timedOut = false;
|
|
22
|
+
const timer = setTimeout(() => { timedOut = true; controller.abort(); }, timeoutMs);
|
|
23
|
+
const cancel = () => { clearTimeout(timer); controller.abort(); };
|
|
24
|
+
if (signal?.aborted)
|
|
25
|
+
cancel();
|
|
26
|
+
else
|
|
27
|
+
signal?.addEventListener('abort', cancel, { once: true });
|
|
28
|
+
return { signal: controller.signal, timedOut: () => timedOut, close: () => { clearTimeout(timer); signal?.removeEventListener('abort', cancel); } };
|
|
29
|
+
}
|
|
30
|
+
function wait(ms, signal) {
|
|
31
|
+
return new Promise((resolve, reject) => {
|
|
32
|
+
if (signal.aborted) {
|
|
33
|
+
reject(new AbortError('Request aborted.'));
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
const abort = () => { clearTimeout(timer); reject(new AbortError('Request aborted.')); };
|
|
37
|
+
const timer = setTimeout(() => { signal.removeEventListener('abort', abort); resolve(); }, ms);
|
|
38
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
async function readLimited(response, limit) {
|
|
42
|
+
if (!response.body)
|
|
43
|
+
return '';
|
|
44
|
+
const reader = response.body.getReader();
|
|
45
|
+
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
46
|
+
let bytes = 0;
|
|
47
|
+
let result = '';
|
|
48
|
+
try {
|
|
49
|
+
for (;;) {
|
|
50
|
+
const { done, value } = await reader.read();
|
|
51
|
+
if (done)
|
|
52
|
+
break;
|
|
53
|
+
bytes += value.byteLength;
|
|
54
|
+
if (bytes > limit) {
|
|
55
|
+
await reader.cancel();
|
|
56
|
+
throw new ProtocolError('Response exceeds maxResponseBytes; reduce the page size or raise the configured limit.');
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
result += decoder.decode(value, { stream: true });
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
throw new ProtocolError('Invalid UTF-8 response.');
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
return result + decoder.decode();
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
throw new ProtocolError('Invalid UTF-8 response.');
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
if (error instanceof ProtocolError)
|
|
74
|
+
throw error;
|
|
75
|
+
throw error;
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
reader.releaseLock();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
function retryAfter(value) {
|
|
82
|
+
if (value === null)
|
|
83
|
+
return undefined;
|
|
84
|
+
const seconds = Number(value);
|
|
85
|
+
if (value.trim() !== '' && Number.isFinite(seconds) && seconds >= 0)
|
|
86
|
+
return Math.min(30_000, seconds * 1000);
|
|
87
|
+
const timestamp = Date.parse(value);
|
|
88
|
+
return Number.isFinite(timestamp) ? Math.min(30_000, Math.max(0, timestamp - Date.now())) : undefined;
|
|
89
|
+
}
|
|
90
|
+
export class Transport {
|
|
91
|
+
baseURL;
|
|
92
|
+
timeoutMs;
|
|
93
|
+
maxRetries;
|
|
94
|
+
maxResponseBytes;
|
|
95
|
+
credential;
|
|
96
|
+
fetcher;
|
|
97
|
+
constructor(options) {
|
|
98
|
+
if (typeof process === 'undefined' || !process.versions?.node)
|
|
99
|
+
throw new TypeError('Fazpi SDK supports backend Node.js only.');
|
|
100
|
+
if (!options || typeof options.apiKey !== 'string' || !/^fz_sk_[0-9a-f]{64}$/.test(options.apiKey))
|
|
101
|
+
throw new TypeError('A valid server API key is required.');
|
|
102
|
+
let base;
|
|
103
|
+
try {
|
|
104
|
+
base = new URL(options.baseURL);
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
throw new TypeError('A valid baseURL is required.');
|
|
108
|
+
}
|
|
109
|
+
if (!['http:', 'https:'].includes(base.protocol) || base.username || base.password || base.search || base.hash)
|
|
110
|
+
throw new TypeError('baseURL must be an HTTP(S) URL without credentials, query or fragment.');
|
|
111
|
+
const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(base.hostname);
|
|
112
|
+
if (base.protocol === 'http:' && !loopback && !options.allowInsecureHTTP)
|
|
113
|
+
throw new TypeError('Use HTTPS, or explicitly enable allowInsecureHTTP for a trusted development server.');
|
|
114
|
+
base.pathname = base.pathname.replace(/\/+$/, '');
|
|
115
|
+
this.baseURL = base;
|
|
116
|
+
this.credential = options.apiKey;
|
|
117
|
+
this.fetcher = options.fetch ?? globalThis.fetch.bind(globalThis);
|
|
118
|
+
this.timeoutMs = integer(options.timeoutMs ?? 30_000, 1, 3_600_000, 'timeoutMs');
|
|
119
|
+
this.maxRetries = integer(options.maxRetries ?? 2, 0, 5, 'maxRetries');
|
|
120
|
+
this.maxResponseBytes = integer(options.maxResponseBytes ?? 8 * 1024 * 1024, 1, 64 * 1024 * 1024, 'maxResponseBytes');
|
|
121
|
+
}
|
|
122
|
+
async request(method, path, body, options = {}, safe = method === 'GET', query, stream = false) {
|
|
123
|
+
const timeout = integer(options.timeoutMs ?? this.timeoutMs, 1, 3_600_000, 'timeoutMs');
|
|
124
|
+
const retries = integer(options.maxRetries ?? this.maxRetries, 0, 5, 'maxRetries');
|
|
125
|
+
const url = new URL(this.baseURL);
|
|
126
|
+
url.pathname = this.baseURL.pathname + path;
|
|
127
|
+
if (query)
|
|
128
|
+
url.search = query.toString();
|
|
129
|
+
const scope = abortScope(options.signal, timeout);
|
|
130
|
+
let handedOff = false;
|
|
131
|
+
const deadline = Date.now() + timeout;
|
|
132
|
+
const key = options.idempotencyKey;
|
|
133
|
+
const serialized = body === undefined ? undefined : JSON.stringify(body);
|
|
134
|
+
const retryable = safe || key !== undefined;
|
|
135
|
+
try {
|
|
136
|
+
for (let attempt = 0;; attempt++) {
|
|
137
|
+
if (scope.signal.aborted)
|
|
138
|
+
throw options.signal?.aborted ? new AbortError('Request aborted.') : new TimeoutError('Request timed out.');
|
|
139
|
+
try {
|
|
140
|
+
const response = await this.fetcher(url, { method, redirect: 'manual', signal: scope.signal, headers: {
|
|
141
|
+
Authorization: `Bearer ${this.credential}`, Accept: stream ? 'text/event-stream' : 'application/json', 'X-Fazpi-SDK': 'typescript/0.2.0',
|
|
142
|
+
...(serialized === undefined ? {} : { 'Content-Type': 'application/json' }),
|
|
143
|
+
...(key === undefined ? {} : { 'Idempotency-Key': key }),
|
|
144
|
+
}, ...(serialized === undefined ? {} : { body: serialized }) });
|
|
145
|
+
if (stream && response.ok) {
|
|
146
|
+
if (!response.headers.get('content-type')?.toLowerCase().startsWith('text/event-stream')) {
|
|
147
|
+
await response.body?.cancel();
|
|
148
|
+
throw new ProtocolError('Expected text/event-stream response.');
|
|
149
|
+
}
|
|
150
|
+
handedOff = true;
|
|
151
|
+
return { response, close: scope.close };
|
|
152
|
+
}
|
|
153
|
+
const text = await readLimited(response, this.maxResponseBytes);
|
|
154
|
+
let value;
|
|
155
|
+
try {
|
|
156
|
+
value = JSON.parse(text);
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
if (response.ok)
|
|
160
|
+
throw new ProtocolError('API returned invalid JSON.');
|
|
161
|
+
}
|
|
162
|
+
if (!response.ok) {
|
|
163
|
+
const detail = value?.error;
|
|
164
|
+
const code = typeof detail?.code === 'string' ? detail.code : 'http_error';
|
|
165
|
+
const message = typeof detail?.message === 'string' ? detail.message : `Fazpi API returned HTTP ${response.status}.`;
|
|
166
|
+
const id = response.headers.get('x-request-id') ?? (typeof detail?.request_id === 'string' ? detail.request_id : '');
|
|
167
|
+
throw new APIError(response.status, code, message, id, retryAfter(response.headers.get('retry-after')));
|
|
168
|
+
}
|
|
169
|
+
return value;
|
|
170
|
+
}
|
|
171
|
+
catch (error) {
|
|
172
|
+
if (scope.signal.aborted)
|
|
173
|
+
throw options.signal?.aborted ? new AbortError('Request aborted.') : new TimeoutError('Request timed out.');
|
|
174
|
+
if (error instanceof ProtocolError || error instanceof AbortError || error instanceof TimeoutError)
|
|
175
|
+
throw error;
|
|
176
|
+
const failure = error instanceof APIError ? error : new TransportError('Network request failed.', { cause: error });
|
|
177
|
+
const transient = failure instanceof TransportError || (failure instanceof APIError && [408, 429, 500, 502, 503, 504].includes(failure.status));
|
|
178
|
+
if (!retryable || !transient || attempt >= retries)
|
|
179
|
+
throw failure;
|
|
180
|
+
const delay = failure instanceof APIError && failure.retryAfterMs !== undefined ? failure.retryAfterMs : Math.min(2000, 200 * 2 ** attempt);
|
|
181
|
+
if (Date.now() + delay >= deadline)
|
|
182
|
+
throw failure;
|
|
183
|
+
try {
|
|
184
|
+
await wait(delay, scope.signal);
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
throw scope.timedOut() ? new TimeoutError('Request timed out.') : new AbortError('Request aborted.');
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
finally {
|
|
193
|
+
if (!handedOff)
|
|
194
|
+
scope.close();
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/** Public inference types. No private account or runtime objects cross this API. */
|
|
2
|
+
export type Target = {
|
|
3
|
+
type: 'agent' | 'group';
|
|
4
|
+
id: string;
|
|
5
|
+
};
|
|
6
|
+
export interface Agent {
|
|
7
|
+
id: string;
|
|
8
|
+
name: string;
|
|
9
|
+
}
|
|
10
|
+
export interface Conversation {
|
|
11
|
+
id: string;
|
|
12
|
+
target: Target;
|
|
13
|
+
created_at: string;
|
|
14
|
+
}
|
|
15
|
+
export interface File {
|
|
16
|
+
id: string;
|
|
17
|
+
name: string;
|
|
18
|
+
media_type: string;
|
|
19
|
+
size: number;
|
|
20
|
+
}
|
|
21
|
+
export interface Message {
|
|
22
|
+
files?: File[];
|
|
23
|
+
incomplete?: boolean;
|
|
24
|
+
id: string;
|
|
25
|
+
conversation_id: string;
|
|
26
|
+
role: 'user' | 'assistant';
|
|
27
|
+
text: string;
|
|
28
|
+
agent: Agent | null;
|
|
29
|
+
created_at: string;
|
|
30
|
+
}
|
|
31
|
+
export type RunStatus = 'queued' | 'running' | 'cancelling' | 'completed' | 'failed' | 'cancelled';
|
|
32
|
+
export interface APIErrorBody {
|
|
33
|
+
code: string;
|
|
34
|
+
message: string;
|
|
35
|
+
request_id: string;
|
|
36
|
+
}
|
|
37
|
+
export interface Run {
|
|
38
|
+
id: string;
|
|
39
|
+
conversation_id: string;
|
|
40
|
+
status: RunStatus;
|
|
41
|
+
created_at: string;
|
|
42
|
+
error: APIErrorBody | null;
|
|
43
|
+
}
|
|
44
|
+
export interface MessagePage {
|
|
45
|
+
data: Message[];
|
|
46
|
+
next_cursor: string | null;
|
|
47
|
+
}
|
|
48
|
+
export interface CreateConversation {
|
|
49
|
+
subject_id: string;
|
|
50
|
+
target: Target;
|
|
51
|
+
}
|
|
52
|
+
/** Up to five PDFs, 10 MiB per PDF, 20 MiB combined. content_base64 is standard base64 without a data URL prefix. */
|
|
53
|
+
export interface InputFile {
|
|
54
|
+
name: string;
|
|
55
|
+
content_base64: string;
|
|
56
|
+
}
|
|
57
|
+
export interface CreateMessage {
|
|
58
|
+
text: string;
|
|
59
|
+
files?: InputFile[];
|
|
60
|
+
}
|
|
61
|
+
/** Keep persisted cursor IDs as strings; JavaScript numbers can lose precision. */
|
|
62
|
+
export interface PublicEvent {
|
|
63
|
+
id: string;
|
|
64
|
+
type: 'text.delta' | 'message.completed' | 'run.status' | 'run.error' | 'activity' | 'message.partial';
|
|
65
|
+
conversation_id: string;
|
|
66
|
+
run_id: string;
|
|
67
|
+
agent?: Agent | null;
|
|
68
|
+
delta?: string;
|
|
69
|
+
message?: Message;
|
|
70
|
+
run?: Run;
|
|
71
|
+
activity?: Activity;
|
|
72
|
+
}
|
|
73
|
+
export interface Activity {
|
|
74
|
+
kind: 'thinking' | 'tool' | 'compaction' | 'agent';
|
|
75
|
+
phase: 'started' | 'completed' | 'failed' | 'skipped';
|
|
76
|
+
label: string;
|
|
77
|
+
tool_name?: string;
|
|
78
|
+
call_id?: string;
|
|
79
|
+
}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fazpi-ai/sdk",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"sideEffects": false,
|
|
6
|
+
"files": [
|
|
7
|
+
"dist",
|
|
8
|
+
"LICENSE"
|
|
9
|
+
],
|
|
10
|
+
"engines": {
|
|
11
|
+
"node": ">=20"
|
|
12
|
+
},
|
|
13
|
+
"scripts": {
|
|
14
|
+
"build": "tsc",
|
|
15
|
+
"typecheck": "tsc --noEmit",
|
|
16
|
+
"test": "pnpm run build && node --test tests/*.test.mjs",
|
|
17
|
+
"prepack": "pnpm run build"
|
|
18
|
+
},
|
|
19
|
+
"devDependencies": {
|
|
20
|
+
"typescript": "5.9.3",
|
|
21
|
+
"@types/node": "24.19.4"
|
|
22
|
+
},
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"exports": {
|
|
25
|
+
".": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"import": "./dist/index.js"
|
|
28
|
+
}
|
|
29
|
+
},
|
|
30
|
+
"description": "Official backend TypeScript and JavaScript SDK for the Fazpi API.",
|
|
31
|
+
"license": "MIT",
|
|
32
|
+
"author": "Fazpi AI",
|
|
33
|
+
"homepage": "https://github.com/fazpi-ai/sdk#readme",
|
|
34
|
+
"repository": {
|
|
35
|
+
"type": "git",
|
|
36
|
+
"url": "git+https://github.com/fazpi-ai/sdk.git",
|
|
37
|
+
"directory": "typescript"
|
|
38
|
+
},
|
|
39
|
+
"bugs": {
|
|
40
|
+
"url": "https://github.com/fazpi-ai/sdk/issues"
|
|
41
|
+
},
|
|
42
|
+
"publishConfig": {
|
|
43
|
+
"access": "public"
|
|
44
|
+
},
|
|
45
|
+
"keywords": [
|
|
46
|
+
"fazpi",
|
|
47
|
+
"ai",
|
|
48
|
+
"agents",
|
|
49
|
+
"sdk",
|
|
50
|
+
"typescript"
|
|
51
|
+
]
|
|
52
|
+
}
|