@belonguniverseai/client 0.0.0-stage → 0.1.0-next.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/README.md CHANGED
@@ -1,3 +1,57 @@
1
- # Temporary Holding Version
1
+ # Belong headless client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ `@belonguniverseai/client` is a TypeScript client for Belong Cloud. The first release candidate supports Sessions, Messages, and resumable Runs in Node.js 22+ and browsers with Fetch and Web Streams.
4
+
5
+ ## Send and stream
6
+
7
+ ```ts
8
+ import { createBelongClient } from "@belonguniverseai/client";
9
+
10
+ const client = createBelongClient({
11
+ baseUrl,
12
+ getToken: hostTokenProvider,
13
+ refreshToken: refreshHostToken,
14
+ workspaceExternalId,
15
+ });
16
+
17
+ const { sessionId } = await client.sessions.create({ title: "Reconciliation" });
18
+ const { runId } = await client.messages.send(sessionId, {
19
+ text: "Summarize this workspace",
20
+ clientMessageId,
21
+ });
22
+
23
+ let cursor: string | undefined;
24
+ for await (const frame of client.runs.stream(runId, { signal })) {
25
+ if (frame.id !== null) cursor = frame.id;
26
+ consume(frame.data);
27
+ }
28
+ ```
29
+
30
+ Both token callbacks supply a Belong-compatible bearer token. The headless client reads the current token for each request and can retry once with a different token supplied by `refreshToken` after a 401. Auth0 sign-in and silent renewal belong to the browser host or SDK integration.
31
+
32
+ Persist the last delivered non-null SSE ID if you need to reconnect. Pass it as `lastEventId` on the next `runs.stream` call. The optional `resume: true` only attaches to a live Run. To replay a completed Run, omit `resume`. Aborting the stream or breaking out of the iterator closes the local reader. Call `runs.cancel(runId)` to request server cancellation.
33
+
34
+ Reuse the same `clientMessageId` when retrying a send whose acknowledgment was lost. The API acknowledges it with `idempotent: true` when the message already exists. `sessions.history` reads durable history and supports pagination. `BelongAuthError`, `BelongHttpError`, and `BelongProtocolError` distinguish missing auth, HTTP failures, and invalid response payloads.
35
+
36
+ ## Run the headless example locally
37
+
38
+ Build and test using the pinned workspace tools. Use `pnpm pack` to apply the workspace manifest's publication overrides and generate the production archive.
39
+
40
+ ```sh
41
+ pnpm --filter @belonguniverseai/client typecheck
42
+ pnpm --filter @belonguniverseai/client test
43
+ (cd packages/belong-client && pnpm pack --pack-destination /tmp)
44
+ node packages/belong-client/scripts/smoke-packed.mjs /tmp/belonguniverseai-client-0.1.0-next.0.tgz
45
+ ```
46
+
47
+ For a live run, install the archive in a local application and copy [examples/headless.mjs](examples/headless.mjs) there. Provide `BELONG_BASE_URL` and an authorized `BELONG_TOKEN` in that application's environment. Set `BELONG_WORKSPACE_ID` when the Session should be scoped to a workspace.
48
+
49
+ ```sh
50
+ node headless.mjs send "Summarize this workspace"
51
+ node headless.mjs resume <run-id> <last-event-id>
52
+ node headless.mjs history <session-id>
53
+ ```
54
+
55
+ ## Release
56
+
57
+ GitHub Actions typechecks, builds, runs tests, and installs the packed tarball into an isolated headless consumer. Ready pull requests and pushes to `main` run this validation when the change affects the client. SDK dock and voice readers import the decoder through the public `@belonguniverseai/client/sse` export. To publish an unpublished manifest version, manually run the **Belong headless client** workflow from `main`. The workflow publishes the tarball that passed validation in that run. Prereleases publish to `next`. The npm scope maintainer needs to bootstrap the package and authorize `publish-belong-client-npm.yml` for [npm Trusted Publishing](https://docs.npmjs.com/trusted-publishers/).
@@ -0,0 +1,43 @@
1
+ import { z } from "zod";
2
+ import { workspaceScopeSchema, type ActiveRun, type CancelRunResponse, type CreateSessionInput, type CreateSessionResponse, type HistoryQuery, type HistoryResponse, type ListSessionsQuery, type ListSessionsResponse, type SendMessageInput, type SendMessageResponse, type SessionDetail, type WirePart } from "./contracts.js";
3
+ export type TokenProvider = () => string | null | Promise<string | null>;
4
+ export type BelongClientOptions = {
5
+ readonly baseUrl: string;
6
+ readonly getToken: TokenProvider;
7
+ readonly refreshToken?: TokenProvider;
8
+ /** Sent when listing and creating sessions and when asserting a message workspace. */
9
+ readonly workspaceExternalId?: string;
10
+ readonly workspaceScope?: z.input<typeof workspaceScopeSchema>;
11
+ readonly fetch?: typeof fetch;
12
+ };
13
+ export type RequestOptions = {
14
+ readonly signal?: AbortSignal;
15
+ };
16
+ export type RunStreamOptions = RequestOptions & {
17
+ readonly lastEventId?: string;
18
+ /** Only attach to a live Run. An already finished Run yields no events. */
19
+ readonly resume?: boolean;
20
+ };
21
+ export type RunStreamEvent = {
22
+ /** The server's replay cursor, or null for a synthetic event. */
23
+ readonly id: string | null;
24
+ readonly event: string;
25
+ readonly data: WirePart;
26
+ };
27
+ export declare const createBelongClient: (options: BelongClientOptions) => {
28
+ sessions: {
29
+ create: (input?: CreateSessionInput, requestOptions?: RequestOptions) => Promise<CreateSessionResponse>;
30
+ list: (query?: ListSessionsQuery, requestOptions?: RequestOptions) => Promise<ListSessionsResponse>;
31
+ get: (sessionId: string, requestOptions?: RequestOptions) => Promise<SessionDetail>;
32
+ history: (sessionId: string, query?: HistoryQuery & RequestOptions) => Promise<HistoryResponse>;
33
+ activeRun: (sessionId: string, requestOptions?: RequestOptions) => Promise<ActiveRun>;
34
+ };
35
+ messages: {
36
+ send: (sessionId: string, input: SendMessageInput, requestOptions?: RequestOptions) => Promise<SendMessageResponse>;
37
+ };
38
+ runs: {
39
+ stream(runId: string, options?: RunStreamOptions): AsyncGenerator<RunStreamEvent, void>;
40
+ cancel: (runId: string, requestOptions?: RequestOptions) => Promise<CancelRunResponse>;
41
+ };
42
+ };
43
+ export type BelongClient = ReturnType<typeof createBelongClient>;
package/dist/client.js ADDED
@@ -0,0 +1,178 @@
1
+ import { z } from "zod";
2
+ import { activeRunSchema, cancelRunResponseSchema, createSessionInputSchema, createSessionResponseSchema, historyQuerySchema, historyResponseSchema, listSessionsQuerySchema, listSessionsResponseSchema, runEventIdSchema, sendMessageInputSchema, sendMessageResponseSchema, sessionDetailSchema, wirePartSchema, workspaceExternalIdSchema, workspaceScopeSchema, } from "./contracts.js";
3
+ import { BelongAuthError, BelongHttpError, BelongProtocolError } from "./errors.js";
4
+ import { parseSse } from "./sse.js";
5
+ const pathIdSchema = z
6
+ .string()
7
+ .min(1)
8
+ .refine((id) => id !== "." && id !== "..");
9
+ const pathId = (id) => encodeURIComponent(pathIdSchema.parse(id));
10
+ const withQuery = (path, query) => {
11
+ const params = new URLSearchParams();
12
+ for (const [key, value] of Object.entries(query)) {
13
+ if (value !== undefined)
14
+ params.set(key, String(value));
15
+ }
16
+ const encoded = params.toString();
17
+ return encoded === "" ? path : `${path}?${encoded}`;
18
+ };
19
+ const parseJson = (text) => JSON.parse(text);
20
+ const protocolJson = (schema, text, description) => {
21
+ try {
22
+ return schema.parse(parseJson(text));
23
+ }
24
+ catch (cause) {
25
+ throw new BelongProtocolError(`Invalid ${description} from Belong`, { cause });
26
+ }
27
+ };
28
+ const httpError = async (response) => {
29
+ const text = await response.text();
30
+ let body = text === "" ? null : text;
31
+ if (text !== "") {
32
+ try {
33
+ body = parseJson(text);
34
+ }
35
+ catch {
36
+ // Proxies can return an HTML or plain text error body.
37
+ }
38
+ }
39
+ return new BelongHttpError(response.status, body, response.headers.get("Retry-After"));
40
+ };
41
+ export const createBelongClient = (options) => {
42
+ const { getToken, refreshToken } = options;
43
+ const baseUrl = new URL(options.baseUrl);
44
+ const href = baseUrl.href;
45
+ if ((baseUrl.protocol !== "http:" && baseUrl.protocol !== "https:") ||
46
+ baseUrl.username !== "" ||
47
+ baseUrl.password !== "" ||
48
+ // The URL getters collapse a bare delimiter to the empty string.
49
+ href.includes("?") ||
50
+ href.includes("#")) {
51
+ throw new TypeError("Belong baseUrl must be an HTTP(S) URL without credentials, query or fragment");
52
+ }
53
+ let rootEnd = href.length;
54
+ while (href[rootEnd - 1] === "/")
55
+ rootEnd -= 1;
56
+ const root = href.slice(0, rootEnd);
57
+ const workspaceExternalId = workspaceExternalIdSchema
58
+ .optional()
59
+ .parse(options.workspaceExternalId);
60
+ const workspaceScope = workspaceScopeSchema.optional().parse(options.workspaceScope);
61
+ const fetchImpl = options.fetch ?? globalThis.fetch.bind(globalThis);
62
+ const request = async (path, input = {}) => {
63
+ const { method = "GET", signal, body } = input;
64
+ signal?.throwIfAborted();
65
+ const token = (await getToken())?.trim();
66
+ signal?.throwIfAborted();
67
+ if (token === undefined || token === "")
68
+ throw new BelongAuthError();
69
+ const headers = new Headers(input.headers);
70
+ if (!headers.has("Accept"))
71
+ headers.set("Accept", "application/json");
72
+ if (body !== undefined)
73
+ headers.set("Content-Type", "application/json");
74
+ const send = (bearer) => {
75
+ signal?.throwIfAborted();
76
+ headers.set("Authorization", `Bearer ${bearer}`);
77
+ return fetchImpl(`${root}${path}`, {
78
+ method,
79
+ headers: new Headers(headers),
80
+ credentials: "omit",
81
+ redirect: "error",
82
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
83
+ ...(signal === undefined ? {} : { signal }),
84
+ });
85
+ };
86
+ const response = await send(token);
87
+ if (response.ok)
88
+ return response;
89
+ if (response.status !== 401 || refreshToken === undefined)
90
+ throw await httpError(response);
91
+ // These endpoints authenticate before the handler runs, so a 401 can be
92
+ // retried once with a fresh bearer. Other failures can be ambiguous.
93
+ const rejection = await httpError(response);
94
+ signal?.throwIfAborted();
95
+ const fresh = (await refreshToken())?.trim();
96
+ signal?.throwIfAborted();
97
+ if (fresh === undefined || fresh === "" || fresh === token)
98
+ throw rejection;
99
+ const retried = await send(fresh);
100
+ if (!retried.ok)
101
+ throw await httpError(retried);
102
+ return retried;
103
+ };
104
+ const json = async (schema, path, input) => {
105
+ const response = await request(path, input);
106
+ const content = await response.text();
107
+ return protocolJson(schema, content, "API response");
108
+ };
109
+ return {
110
+ sessions: {
111
+ create: (input = {}, requestOptions) => {
112
+ const parsed = createSessionInputSchema.parse(input);
113
+ if (workspaceExternalId === undefined &&
114
+ (parsed.workspacePath !== undefined || parsed.workspaceName !== undefined)) {
115
+ throw new TypeError("Workspace path and name require a workspaceExternalId");
116
+ }
117
+ return json(createSessionResponseSchema, "/v1/sessions", {
118
+ ...requestOptions,
119
+ method: "POST",
120
+ body: { ...parsed, surface: parsed.surface ?? "api", workspaceExternalId },
121
+ });
122
+ },
123
+ list: (query = {}, requestOptions) => json(listSessionsResponseSchema, withQuery("/v1/sessions", {
124
+ ...listSessionsQuerySchema.parse(query),
125
+ workspaceExternalId,
126
+ }), requestOptions),
127
+ get: (sessionId, requestOptions) => json(sessionDetailSchema, `/v1/sessions/${pathId(sessionId)}`, requestOptions),
128
+ history: (sessionId, query = {}) => json(historyResponseSchema, withQuery(`/v1/sessions/${pathId(sessionId)}/messages`, historyQuerySchema.parse(query)), query.signal === undefined ? undefined : { signal: query.signal }),
129
+ activeRun: (sessionId, requestOptions) => json(activeRunSchema, `/v1/sessions/${pathId(sessionId)}/active-run`, requestOptions),
130
+ },
131
+ messages: {
132
+ send: (sessionId, input, requestOptions) => {
133
+ const parsed = sendMessageInputSchema.parse(input);
134
+ return json(sendMessageResponseSchema, `/v1/sessions/${pathId(sessionId)}/messages`, {
135
+ ...requestOptions,
136
+ method: "POST",
137
+ body: {
138
+ ...parsed,
139
+ workspaceExternalId,
140
+ workspaceScope,
141
+ questionPresentation: parsed.questionPresentation ?? "text",
142
+ cliReconnect: parsed.cliReconnect ?? "none",
143
+ },
144
+ });
145
+ },
146
+ },
147
+ runs: {
148
+ async *stream(runId, options = {}) {
149
+ const headers = new Headers({ Accept: "text/event-stream" });
150
+ if (options.lastEventId !== undefined) {
151
+ headers.set("Last-Event-Id", runEventIdSchema.parse(options.lastEventId));
152
+ }
153
+ const path = withQuery(`/v1/runs/${pathId(runId)}/stream`, {
154
+ resume: options.resume === true ? "1" : undefined,
155
+ });
156
+ const response = await request(path, { ...options, headers });
157
+ if (response.status === 204)
158
+ return;
159
+ const contentType = response.headers
160
+ .get("Content-Type")
161
+ ?.split(";")[0]
162
+ ?.trim()
163
+ .toLowerCase();
164
+ if (contentType !== "text/event-stream" || response.body === null) {
165
+ void response.body?.cancel().catch(() => undefined);
166
+ throw new BelongProtocolError("Expected a Belong event stream response");
167
+ }
168
+ for await (const frame of parseSse(response.body, options.signal)) {
169
+ yield { ...frame, data: protocolJson(wirePartSchema, frame.data, "event stream frame") };
170
+ }
171
+ },
172
+ cancel: (runId, requestOptions) => json(cancelRunResponseSchema, `/v1/runs/${pathId(runId)}/cancel`, {
173
+ ...requestOptions,
174
+ method: "POST",
175
+ }),
176
+ },
177
+ };
178
+ };
@@ -0,0 +1,201 @@
1
+ import { z } from "zod";
2
+ export declare const workspaceExternalIdSchema: z.ZodString;
3
+ export declare const workspaceScopeSchema: z.ZodEnum<{
4
+ open: "open";
5
+ strict: "strict";
6
+ }>;
7
+ export declare const runEventIdSchema: z.ZodString;
8
+ export declare const createSessionInputSchema: z.ZodObject<{
9
+ title: z.ZodOptional<z.ZodString>;
10
+ workspacePath: z.ZodOptional<z.ZodString>;
11
+ workspaceName: z.ZodOptional<z.ZodString>;
12
+ origin: z.ZodOptional<z.ZodEnum<{
13
+ user: "user";
14
+ benchmark: "benchmark";
15
+ }>>;
16
+ surface: z.ZodOptional<z.ZodEnum<{
17
+ unknown: "unknown";
18
+ dock: "dock";
19
+ connector: "connector";
20
+ api: "api";
21
+ }>>;
22
+ }, z.core.$strip>;
23
+ export type CreateSessionInput = z.input<typeof createSessionInputSchema>;
24
+ export declare const listSessionsQuerySchema: z.ZodObject<{
25
+ limit: z.ZodOptional<z.ZodNumber>;
26
+ }, z.core.$strip>;
27
+ export type ListSessionsQuery = z.input<typeof listSessionsQuerySchema>;
28
+ export declare const historyQuerySchema: z.ZodObject<{
29
+ limit: z.ZodOptional<z.ZodNumber>;
30
+ before: z.ZodOptional<z.ZodString>;
31
+ parts: z.ZodOptional<z.ZodEnum<{
32
+ full: "full";
33
+ summary: "summary";
34
+ }>>;
35
+ }, z.core.$strip>;
36
+ export type HistoryQuery = z.input<typeof historyQuerySchema>;
37
+ export declare const sendMessageInputSchema: z.ZodObject<{
38
+ text: z.ZodString;
39
+ clientMessageId: z.ZodString;
40
+ fileIds: z.ZodOptional<z.ZodArray<z.ZodUUID>>;
41
+ skill: z.ZodOptional<z.ZodString>;
42
+ mode: z.ZodOptional<z.ZodEnum<{
43
+ plan: "plan";
44
+ approve: "approve";
45
+ balanced: "balanced";
46
+ bypass: "bypass";
47
+ execute: "execute";
48
+ }>>;
49
+ responseMode: z.ZodOptional<z.ZodEnum<{
50
+ balanced: "balanced";
51
+ fast: "fast";
52
+ smart: "smart";
53
+ }>>;
54
+ timezone: z.ZodOptional<z.ZodString>;
55
+ locale: z.ZodOptional<z.ZodEnum<{
56
+ en: "en";
57
+ es: "es";
58
+ pt: "pt";
59
+ it: "it";
60
+ }>>;
61
+ pageContext: z.ZodOptional<z.ZodObject<{
62
+ label: z.ZodString;
63
+ }, z.core.$strip>>;
64
+ questionPresentation: z.ZodOptional<z.ZodEnum<{
65
+ text: "text";
66
+ card: "card";
67
+ }>>;
68
+ cliReconnect: z.ZodOptional<z.ZodEnum<{
69
+ dock: "dock";
70
+ none: "none";
71
+ }>>;
72
+ }, z.core.$strip>;
73
+ export type SendMessageInput = z.input<typeof sendMessageInputSchema>;
74
+ export declare const createSessionResponseSchema: z.ZodObject<{
75
+ sessionId: z.ZodString;
76
+ }, z.core.$strip>;
77
+ export type CreateSessionResponse = z.output<typeof createSessionResponseSchema>;
78
+ declare const sessionListItemSchema: z.ZodObject<{
79
+ sessionId: z.ZodString;
80
+ title: z.ZodNullable<z.ZodString>;
81
+ status: z.ZodEnum<{
82
+ active: "active";
83
+ archived: "archived";
84
+ deleted: "deleted";
85
+ }>;
86
+ updatedAt: z.ZodString;
87
+ }, z.core.$strip>;
88
+ export type SessionListItem = z.output<typeof sessionListItemSchema>;
89
+ export declare const listSessionsResponseSchema: z.ZodObject<{
90
+ sessions: z.ZodArray<z.ZodObject<{
91
+ sessionId: z.ZodString;
92
+ title: z.ZodNullable<z.ZodString>;
93
+ status: z.ZodEnum<{
94
+ active: "active";
95
+ archived: "archived";
96
+ deleted: "deleted";
97
+ }>;
98
+ updatedAt: z.ZodString;
99
+ }, z.core.$strip>>;
100
+ }, z.core.$strip>;
101
+ export type ListSessionsResponse = z.output<typeof listSessionsResponseSchema>;
102
+ export declare const sessionDetailSchema: z.ZodObject<{
103
+ sessionId: z.ZodString;
104
+ title: z.ZodNullable<z.ZodString>;
105
+ status: z.ZodEnum<{
106
+ active: "active";
107
+ archived: "archived";
108
+ deleted: "deleted";
109
+ }>;
110
+ updatedAt: z.ZodString;
111
+ workspaceExternalId: z.ZodNullable<z.ZodString>;
112
+ createdAt: z.ZodString;
113
+ readOnly: z.ZodOptional<z.ZodBoolean>;
114
+ }, z.core.$strip>;
115
+ export type SessionDetail = z.output<typeof sessionDetailSchema>;
116
+ export declare const activeRunSchema: z.ZodNullable<z.ZodObject<{
117
+ runId: z.ZodString;
118
+ taskId: z.ZodString;
119
+ status: z.ZodEnum<{
120
+ queued: "queued";
121
+ running: "running";
122
+ recovering: "recovering";
123
+ waiting_for_approval: "waiting_for_approval";
124
+ waiting_for_user: "waiting_for_user";
125
+ waiting_for_ui_action: "waiting_for_ui_action";
126
+ cancelling: "cancelling";
127
+ }>;
128
+ }, z.core.$strip>>;
129
+ export type ActiveRun = z.output<typeof activeRunSchema>;
130
+ export declare const sendMessageResponseSchema: z.ZodObject<{
131
+ messageId: z.ZodString;
132
+ taskId: z.ZodString;
133
+ runId: z.ZodString;
134
+ idempotent: z.ZodBoolean;
135
+ }, z.core.$strip>;
136
+ export type SendMessageResponse = z.output<typeof sendMessageResponseSchema>;
137
+ export declare const cancelRunResponseSchema: z.ZodObject<{
138
+ status: z.ZodLiteral<"cancelling">;
139
+ recalledMessages: z.ZodDefault<z.ZodArray<z.ZodObject<{
140
+ messageId: z.ZodString;
141
+ clientMessageId: z.ZodNullable<z.ZodString>;
142
+ text: z.ZodString;
143
+ }, z.core.$strip>>>;
144
+ }, z.core.$strip>;
145
+ export type CancelRunResponse = z.output<typeof cancelRunResponseSchema>;
146
+ export declare const wirePartSchema: z.ZodObject<{
147
+ type: z.ZodString;
148
+ }, z.core.$loose>;
149
+ export type WirePart = z.output<typeof wirePartSchema>;
150
+ declare const historyMessageSchema: z.ZodObject<{
151
+ id: z.ZodString;
152
+ role: z.ZodEnum<{
153
+ user: "user";
154
+ assistant: "assistant";
155
+ }>;
156
+ parts: z.ZodArray<z.ZodObject<{
157
+ type: z.ZodString;
158
+ }, z.core.$loose>>;
159
+ createdAt: z.ZodOptional<z.ZodString>;
160
+ clientMessageId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
161
+ metadata: z.ZodOptional<z.ZodObject<{
162
+ taskId: z.ZodString;
163
+ feedback: z.ZodNullable<z.ZodObject<{
164
+ sentiment: z.ZodEnum<{
165
+ up: "up";
166
+ down: "down";
167
+ }>;
168
+ reason: z.ZodNullable<z.ZodString>;
169
+ }, z.core.$strip>>;
170
+ }, z.core.$loose>>;
171
+ }, z.core.$loose>;
172
+ export type HistoryMessage = z.output<typeof historyMessageSchema>;
173
+ export declare const historyResponseSchema: z.ZodObject<{
174
+ messages: z.ZodArray<z.ZodObject<{
175
+ id: z.ZodString;
176
+ role: z.ZodEnum<{
177
+ user: "user";
178
+ assistant: "assistant";
179
+ }>;
180
+ parts: z.ZodArray<z.ZodObject<{
181
+ type: z.ZodString;
182
+ }, z.core.$loose>>;
183
+ createdAt: z.ZodOptional<z.ZodString>;
184
+ clientMessageId: z.ZodOptional<z.ZodNullable<z.ZodString>>;
185
+ metadata: z.ZodOptional<z.ZodObject<{
186
+ taskId: z.ZodString;
187
+ feedback: z.ZodNullable<z.ZodObject<{
188
+ sentiment: z.ZodEnum<{
189
+ up: "up";
190
+ down: "down";
191
+ }>;
192
+ reason: z.ZodNullable<z.ZodString>;
193
+ }, z.core.$strip>>;
194
+ }, z.core.$loose>>;
195
+ }, z.core.$loose>>;
196
+ page: z.ZodOptional<z.ZodObject<{
197
+ before: z.ZodNullable<z.ZodString>;
198
+ }, z.core.$loose>>;
199
+ }, z.core.$strip>;
200
+ export type HistoryResponse = z.output<typeof historyResponseSchema>;
201
+ export {};
@@ -0,0 +1,102 @@
1
+ import { z } from "zod";
2
+ export const workspaceExternalIdSchema = z.string().regex(/^[A-Za-z0-9._-]{1,64}$/);
3
+ export const workspaceScopeSchema = z.enum(["open", "strict"]);
4
+ export const runEventIdSchema = z.string().regex(/^\d+-0$/);
5
+ export const createSessionInputSchema = z.object({
6
+ title: z.string().min(1).max(200).optional(),
7
+ workspacePath: z.string().optional(),
8
+ workspaceName: z.string().optional(),
9
+ origin: z.enum(["user", "benchmark"]).optional(),
10
+ surface: z.enum(["unknown", "dock", "connector", "api"]).optional(),
11
+ });
12
+ export const listSessionsQuerySchema = z.object({
13
+ limit: z.number().int().min(1).max(100).optional(),
14
+ });
15
+ export const historyQuerySchema = listSessionsQuerySchema.extend({
16
+ before: z.string().min(1).max(512).optional(),
17
+ parts: z.enum(["full", "summary"]).optional(),
18
+ });
19
+ export const sendMessageInputSchema = z
20
+ .object({
21
+ text: z.string().max(50_000),
22
+ clientMessageId: z.string().min(1).max(120),
23
+ fileIds: z.array(z.uuid()).max(20).optional(),
24
+ skill: z.string().min(1).max(200).optional(),
25
+ mode: z.enum(["plan", "approve", "balanced", "bypass", "execute"]).optional(),
26
+ responseMode: z.enum(["fast", "balanced", "smart"]).optional(),
27
+ timezone: z.string().optional(),
28
+ locale: z.enum(["en", "es", "pt", "it"]).optional(),
29
+ pageContext: z.object({ label: z.string() }).optional(),
30
+ questionPresentation: z.enum(["card", "text"]).optional(),
31
+ cliReconnect: z.enum(["dock", "none"]).optional(),
32
+ })
33
+ .refine((input) => input.text.trim().length > 0 || (input.fileIds?.length ?? 0) > 0, {
34
+ message: "text or fileIds required",
35
+ path: ["text"],
36
+ });
37
+ export const createSessionResponseSchema = z.object({ sessionId: z.string() });
38
+ const sessionListItemSchema = z.object({
39
+ sessionId: z.string(),
40
+ title: z.string().nullable(),
41
+ status: z.enum(["active", "archived", "deleted"]),
42
+ updatedAt: z.string(),
43
+ });
44
+ export const listSessionsResponseSchema = z.object({ sessions: z.array(sessionListItemSchema) });
45
+ export const sessionDetailSchema = sessionListItemSchema.extend({
46
+ workspaceExternalId: z.string().nullable(),
47
+ createdAt: z.string(),
48
+ readOnly: z.boolean().optional(),
49
+ });
50
+ export const activeRunSchema = z
51
+ .object({
52
+ runId: z.string(),
53
+ taskId: z.string(),
54
+ status: z.enum([
55
+ "queued",
56
+ "running",
57
+ "recovering",
58
+ "waiting_for_approval",
59
+ "waiting_for_user",
60
+ "waiting_for_ui_action",
61
+ "cancelling",
62
+ ]),
63
+ })
64
+ .nullable();
65
+ export const sendMessageResponseSchema = z.object({
66
+ messageId: z.string(),
67
+ taskId: z.string(),
68
+ runId: z.string(),
69
+ idempotent: z.boolean(),
70
+ });
71
+ export const cancelRunResponseSchema = z.object({
72
+ status: z.literal("cancelling"),
73
+ recalledMessages: z
74
+ .array(z.object({
75
+ messageId: z.string(),
76
+ clientMessageId: z.string().nullable(),
77
+ text: z.string(),
78
+ }))
79
+ .default([]),
80
+ });
81
+ // Cloud adds stream/history part kinds over time. Validate the discriminator
82
+ // and preserve fields, including extension kinds a consumer can handle itself.
83
+ export const wirePartSchema = z.looseObject({ type: z.string().min(1) });
84
+ const historyMessageSchema = z.looseObject({
85
+ id: z.string(),
86
+ role: z.enum(["user", "assistant"]),
87
+ parts: z.array(wirePartSchema),
88
+ createdAt: z.string().optional(),
89
+ clientMessageId: z.string().nullable().optional(),
90
+ metadata: z
91
+ .looseObject({
92
+ taskId: z.string(),
93
+ feedback: z
94
+ .object({ sentiment: z.enum(["up", "down"]), reason: z.string().nullable() })
95
+ .nullable(),
96
+ })
97
+ .optional(),
98
+ });
99
+ export const historyResponseSchema = z.object({
100
+ messages: z.array(historyMessageSchema),
101
+ page: z.looseObject({ before: z.string().nullable() }).optional(),
102
+ });
@@ -0,0 +1,15 @@
1
+ export declare class BelongHttpError extends Error {
2
+ readonly status: number;
3
+ readonly body: unknown;
4
+ readonly retryAfter: string | null;
5
+ readonly name = "BelongHttpError";
6
+ readonly code: string | null;
7
+ constructor(status: number, body: unknown, retryAfter: string | null);
8
+ }
9
+ export declare class BelongAuthError extends Error {
10
+ readonly name = "BelongAuthError";
11
+ constructor();
12
+ }
13
+ export declare class BelongProtocolError extends Error {
14
+ readonly name = "BelongProtocolError";
15
+ }
package/dist/errors.js ADDED
@@ -0,0 +1,29 @@
1
+ import { z } from "zod";
2
+ const errorEnvelopeSchema = z.object({ error: z.object({ type: z.string() }) });
3
+ export class BelongHttpError extends Error {
4
+ status;
5
+ body;
6
+ retryAfter;
7
+ name = "BelongHttpError";
8
+ code;
9
+ constructor(status, body, retryAfter) {
10
+ const parsed = errorEnvelopeSchema.safeParse(body);
11
+ const code = parsed.success ? parsed.data.error.type : null;
12
+ super(code === null
13
+ ? `Belong API request failed (${status})`
14
+ : `Belong API request failed (${status}, ${code})`);
15
+ this.status = status;
16
+ this.body = body;
17
+ this.retryAfter = retryAfter;
18
+ this.code = code;
19
+ }
20
+ }
21
+ export class BelongAuthError extends Error {
22
+ name = "BelongAuthError";
23
+ constructor() {
24
+ super("Belong authentication requires a bearer token");
25
+ }
26
+ }
27
+ export class BelongProtocolError extends Error {
28
+ name = "BelongProtocolError";
29
+ }
@@ -0,0 +1,5 @@
1
+ export { createBelongClient } from "./client.js";
2
+ export type { BelongClient, BelongClientOptions, RequestOptions, RunStreamEvent, RunStreamOptions, TokenProvider, } from "./client.js";
3
+ export type { ActiveRun, CancelRunResponse, CreateSessionInput, CreateSessionResponse, HistoryMessage, HistoryQuery, HistoryResponse, ListSessionsQuery, ListSessionsResponse, SendMessageInput, SendMessageResponse, SessionDetail, SessionListItem, WirePart, } from "./contracts.js";
4
+ export { BelongAuthError, BelongHttpError, BelongProtocolError } from "./errors.js";
5
+ export { createSseLineDecoder, parseSse, type SseFrame } from "./sse.js";
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ export { createBelongClient } from "./client.js";
2
+ export { BelongAuthError, BelongHttpError, BelongProtocolError } from "./errors.js";
3
+ export { createSseLineDecoder, parseSse } from "./sse.js";
package/dist/sse.d.ts ADDED
@@ -0,0 +1,13 @@
1
+ export type SseFrame = {
2
+ /** Only the id supplied on this frame. Synthetic replay frames can be idless. */
3
+ readonly id: string | null;
4
+ readonly event: string;
5
+ readonly data: string;
6
+ };
7
+ /** Decode complete SSE lines, retaining split characters and lines between chunks. */
8
+ export declare const createSseLineDecoder: () => ((chunk: Uint8Array) => readonly string[]);
9
+ /**
10
+ * Read SSE frames from a fetch response. Releasing the iterator cancels the
11
+ * response body. Pass a signal to also interrupt a read while it is pending.
12
+ */
13
+ export declare function parseSse(body: ReadableStream<Uint8Array>, signal?: AbortSignal): AsyncGenerator<SseFrame, void>;
package/dist/sse.js ADDED
@@ -0,0 +1,92 @@
1
+ /** Decode complete SSE lines, retaining split characters and lines between chunks. */
2
+ export const createSseLineDecoder = () => {
3
+ const decoder = new TextDecoder();
4
+ let partialLine = "";
5
+ let skipLf = false;
6
+ return (chunk) => {
7
+ const text = decoder.decode(chunk, { stream: true });
8
+ const lines = [];
9
+ let start = 0;
10
+ for (let index = 0; index < text.length; index += 1) {
11
+ const character = text[index];
12
+ if (skipLf) {
13
+ skipLf = false;
14
+ if (character === "\n") {
15
+ start = index + 1;
16
+ continue;
17
+ }
18
+ }
19
+ if (character !== "\r" && character !== "\n")
20
+ continue;
21
+ lines.push(partialLine + text.slice(start, index));
22
+ partialLine = "";
23
+ start = index + 1;
24
+ skipLf = character === "\r";
25
+ }
26
+ partialLine += text.slice(start);
27
+ return lines;
28
+ };
29
+ };
30
+ /**
31
+ * Read SSE frames from a fetch response. Releasing the iterator cancels the
32
+ * response body. Pass a signal to also interrupt a read while it is pending.
33
+ */
34
+ export async function* parseSse(body, signal) {
35
+ const reader = body.getReader();
36
+ const decodeLines = createSseLineDecoder();
37
+ let event = "";
38
+ let id = null;
39
+ let data = [];
40
+ const consumeLine = (line) => {
41
+ if (line === "") {
42
+ const frame = data.length === 0
43
+ ? undefined
44
+ : {
45
+ id,
46
+ event: event === "" ? "message" : event,
47
+ data: data.join("\n"),
48
+ };
49
+ id = null;
50
+ event = "";
51
+ data = [];
52
+ return frame;
53
+ }
54
+ const colon = line.indexOf(":");
55
+ const field = colon === -1 ? line : line.slice(0, colon);
56
+ const rawValue = colon === -1 ? "" : line.slice(colon + 1);
57
+ const value = rawValue.startsWith(" ") ? rawValue.slice(1) : rawValue;
58
+ if (field === "data")
59
+ data.push(value);
60
+ if (field === "event")
61
+ event = value;
62
+ if (field === "id" && !value.includes("\0"))
63
+ id = value;
64
+ return undefined;
65
+ };
66
+ const cancel = () => {
67
+ void reader.cancel().catch(() => undefined);
68
+ };
69
+ signal?.addEventListener("abort", cancel, { once: true });
70
+ try {
71
+ for (;;) {
72
+ signal?.throwIfAborted();
73
+ const result = await reader.read();
74
+ signal?.throwIfAborted();
75
+ // An unterminated frame at EOF is incomplete and must not advance a cursor.
76
+ if (result.done)
77
+ return;
78
+ for (const line of decodeLines(result.value)) {
79
+ const frame = consumeLine(line);
80
+ if (frame !== undefined) {
81
+ signal?.throwIfAborted();
82
+ yield frame;
83
+ }
84
+ }
85
+ }
86
+ }
87
+ finally {
88
+ signal?.removeEventListener("abort", cancel);
89
+ cancel();
90
+ reader.releaseLock();
91
+ }
92
+ }
@@ -0,0 +1,73 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { BelongHttpError, createBelongClient } from "@belonguniverseai/client";
3
+
4
+ const print = (value) => process.stdout.write(JSON.stringify(value) + "\n");
5
+
6
+ async function main() {
7
+ const [command, first, second, ...extra] = process.argv.slice(2);
8
+ if (
9
+ extra.length > 0 ||
10
+ first === undefined ||
11
+ (command === "history" && second !== undefined) ||
12
+ !["send", "resume", "history"].includes(command)
13
+ ) {
14
+ throw new Error(
15
+ 'Usage: node headless.mjs send "message" [session-id] | resume run-id [last-event-id] | history session-id',
16
+ );
17
+ }
18
+
19
+ const { BELONG_BASE_URL, BELONG_TOKEN, BELONG_WORKSPACE_ID } = process.env;
20
+ if (!BELONG_BASE_URL || !BELONG_TOKEN) {
21
+ throw new Error("Set BELONG_BASE_URL and BELONG_TOKEN before running the example.");
22
+ }
23
+ const client = createBelongClient({
24
+ baseUrl: BELONG_BASE_URL,
25
+ getToken: () => BELONG_TOKEN,
26
+ workspaceExternalId: BELONG_WORKSPACE_ID,
27
+ });
28
+ const controller = new AbortController();
29
+ const stop = () => controller.abort();
30
+ process.once("SIGINT", stop);
31
+ const { signal } = controller;
32
+
33
+ try {
34
+ if (command === "history") {
35
+ print(await client.sessions.history(first, { signal }));
36
+ return;
37
+ }
38
+ if (command === "resume") {
39
+ for await (const frame of client.runs.stream(first, { lastEventId: second, signal })) {
40
+ print(frame);
41
+ }
42
+ return;
43
+ }
44
+
45
+ const sessionId = second ?? (await client.sessions.create({}, { signal })).sessionId;
46
+ const run = await client.messages.send(
47
+ sessionId,
48
+ { text: first, clientMessageId: randomUUID() },
49
+ { signal },
50
+ );
51
+ print({ sessionId, ...run });
52
+ for await (const frame of client.runs.stream(run.runId, { signal })) {
53
+ print(frame);
54
+ }
55
+ } finally {
56
+ process.removeListener("SIGINT", stop);
57
+ }
58
+ }
59
+
60
+ try {
61
+ await main();
62
+ } catch (error) {
63
+ if (error instanceof BelongHttpError) {
64
+ const reason = error.code ? [error.status, error.code].join(", ") : String(error.status);
65
+ process.stderr.write(`Belong request failed (${reason}).\n`);
66
+ process.exitCode = 1;
67
+ } else if (error instanceof Error && error.name === "AbortError") {
68
+ process.exitCode = 130;
69
+ } else {
70
+ process.stderr.write((error instanceof Error ? error.message : "Unexpected failure") + "\n");
71
+ process.exitCode = 1;
72
+ }
73
+ }
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@belonguniverseai/client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-next.0",
4
+ "description": "Headless Belong API client for Node.js and browsers",
5
+ "repository": {
6
+ "type": "git",
7
+ "url": "git+https://github.com/Belong-Universe/agent-as-a-service.git",
8
+ "directory": "packages/belong-client"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "examples/headless.mjs"
13
+ ],
14
+ "type": "module",
15
+ "sideEffects": false,
16
+ "types": "./dist/index.d.ts",
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js"
21
+ },
22
+ "./sse": {
23
+ "types": "./dist/sse.d.ts",
24
+ "import": "./dist/sse.js"
25
+ }
26
+ },
27
+ "publishConfig": {
28
+ "access": "public",
29
+ "provenance": false
30
+ },
31
+ "dependencies": {
32
+ "zod": ">=4.6.6 <5"
33
+ },
34
+ "devDependencies": {
35
+ "typescript": "^5.7.2"
36
+ },
37
+ "engines": {
38
+ "node": ">=22"
39
+ },
40
+ "scripts": {
41
+ "build": "tsc -p tsconfig.json",
42
+ "typecheck": "tsc -p tsconfig.json --noEmit",
43
+ "test": "tsc -p tsconfig.json && node --test test/*.test.mjs"
44
+ }
6
45
  }