@omnara/sdk 0.1.8 → 0.1.9

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.js CHANGED
@@ -1,122 +1,302 @@
1
1
  import {
2
- ApiError
3
- } from "./chunk-5CVUE3YZ.js";
2
+ ApiError,
3
+ zErrorResponse,
4
+ zJsonText
5
+ } from "./chunk-UD4ZHHMO.js";
4
6
  import {
5
7
  client,
6
8
  createClient,
7
9
  createConfig,
8
- isUnknownEnumError,
9
- sdk_gen_exports,
10
- streamEvents
11
- } from "./chunk-WKCFMDBY.js";
10
+ sdk_gen_exports
11
+ } from "./chunk-HCB2J76N.js";
12
+ import {
13
+ relaxedSchema
14
+ } from "./chunk-6ZFYUHM3.js";
12
15
  import {
16
+ zAgentSequence,
13
17
  zStreamEventsResponse,
14
18
  zod_gen_exports
15
- } from "./chunk-P33FH4PQ.js";
19
+ } from "./chunk-6NNNQM73.js";
20
+
21
+ // src/agent-event-stream.ts
22
+ import * as z from "zod";
23
+
24
+ // src/server-sent-events.ts
25
+ function createServerSentEventParser() {
26
+ let parts = [];
27
+ let pendingCarriageReturn = false;
28
+ return {
29
+ push(chunk) {
30
+ if (chunk === "") return [];
31
+ let text = pendingCarriageReturn && chunk.startsWith("\n") ? chunk.slice(1) : chunk;
32
+ pendingCarriageReturn = chunk.endsWith("\r");
33
+ text = text.replaceAll(/\r\n?/g, "\n");
34
+ const last = parts.at(-1);
35
+ if (last?.endsWith("\n") === true) {
36
+ parts[parts.length - 1] = last.slice(0, -1);
37
+ text = `
38
+ ${text}`;
39
+ }
40
+ const messages = [];
41
+ let from = 0;
42
+ for (let end = text.indexOf("\n\n"); end !== -1; end = text.indexOf("\n\n", from)) {
43
+ const data = messageData(parts.join("") + text.slice(from, end));
44
+ parts = [];
45
+ if (data != null) messages.push(data);
46
+ from = end + 2;
47
+ }
48
+ if (from < text.length) parts.push(text.slice(from));
49
+ return messages;
50
+ }
51
+ };
52
+ }
53
+ function messageData(block) {
54
+ const data = [];
55
+ for (const line of block.split("\n")) {
56
+ if (line !== "data" && !line.startsWith("data:")) continue;
57
+ const value = line.slice("data:".length);
58
+ data.push(value.startsWith(" ") ? value.slice(1) : value);
59
+ }
60
+ return data.length === 0 ? void 0 : data.join("\n");
61
+ }
16
62
 
17
63
  // src/agent-event-stream.ts
18
64
  var AgentEventStreamError = class extends Error {
19
65
  kind;
20
- retryable;
21
66
  status;
67
+ code;
68
+ retryAfterMs;
22
69
  constructor({
23
70
  kind,
24
71
  message,
25
- retryable,
26
72
  status,
73
+ code,
74
+ retryAfterMs,
27
75
  cause
28
76
  }) {
29
77
  super(message, { cause });
30
78
  this.name = "AgentEventStreamError";
31
79
  this.kind = kind;
32
- this.retryable = retryable;
33
80
  this.status = status;
81
+ this.code = code;
82
+ this.retryAfterMs = retryAfterMs;
34
83
  }
35
84
  };
36
- var generatedHTTPError = /^SSE failed: (\d{3})(?:\s|$)/;
37
- function classifyStreamError(error, signal) {
38
- if (error instanceof AgentEventStreamError) return error;
39
- if (signal?.aborted === true || error instanceof Error && error.name === "AbortError") {
40
- return new AgentEventStreamError({
41
- kind: "aborted",
42
- message: "Agent event stream canceled",
43
- retryable: false,
44
- cause: error
45
- });
46
- }
47
- const match = error instanceof Error ? generatedHTTPError.exec(error.message) : null;
48
- const status = match?.[1] == null ? void 0 : Number.parseInt(match[1], 10);
49
- if (status != null) {
50
- return new AgentEventStreamError({
51
- kind: "http",
52
- message: `Agent event stream request failed with HTTP ${status}`,
53
- retryable: status === 408 || status === 429 || status >= 500,
54
- status,
55
- cause: error
56
- });
85
+ var streamUrl = "/orgs/{orgID}/projects/{projectID}/agents/{agentID}/events/stream";
86
+ var retryBaseDelayMs = 1e3;
87
+ var retryMaximumDelayMs = 3e4;
88
+ var retryAfterMaximumDelayMs = 6e4;
89
+ var stableConnectionResetMs = 1e4;
90
+ var stallTimeoutMs = 35e3;
91
+ var zDurableCursor = z.object({
92
+ event_kind: z.string(),
93
+ sequence: zAgentSequence
94
+ });
95
+ var relaxedStreamEvent = relaxedSchema(zStreamEventsResponse);
96
+ var zStreamFrame = zJsonText.pipe(relaxedStreamEvent);
97
+ function streamError(kind, message, options = {}) {
98
+ return new AgentEventStreamError({ kind, message, ...options });
99
+ }
100
+ function retryable(error) {
101
+ if (error.kind === "transport") return true;
102
+ if (error.kind === "api") return error.code === "service_unavailable";
103
+ return error.kind === "http" && (error.status === 408 || error.status === 429 || error.status != null && error.status >= 500);
104
+ }
105
+ function parseRetryAfter(value, now = Date.now()) {
106
+ if (value == null) return void 0;
107
+ const trimmed = value.trim();
108
+ if (/^\d+$/.test(trimmed)) {
109
+ return Math.min(Number.parseInt(trimmed, 10) * 1e3, retryAfterMaximumDelayMs);
57
110
  }
58
- return new AgentEventStreamError({
59
- kind: "transport",
60
- message: "Agent event stream disconnected",
61
- retryable: true,
62
- cause: error
111
+ const at = Date.parse(trimmed);
112
+ if (Number.isNaN(at)) return void 0;
113
+ return Math.min(Math.max(at - now, 0), retryAfterMaximumDelayMs);
114
+ }
115
+ function reconnectDelay(attempt) {
116
+ const maximum = Math.min(retryBaseDelayMs * 2 ** Math.max(attempt - 1, 0), retryMaximumDelayMs);
117
+ return Math.floor(Math.random() * maximum);
118
+ }
119
+ function abortableDelay(ms, signal) {
120
+ if (signal?.aborted === true) return Promise.resolve(false);
121
+ return new Promise((resolve) => {
122
+ const timeout = globalThis.setTimeout(() => {
123
+ finish(true);
124
+ }, ms);
125
+ const onAbort = () => {
126
+ finish(false);
127
+ };
128
+ function finish(completed) {
129
+ globalThis.clearTimeout(timeout);
130
+ signal?.removeEventListener("abort", onAbort);
131
+ resolve(completed);
132
+ }
133
+ signal?.addEventListener("abort", onAbort, { once: true });
63
134
  });
64
135
  }
65
- async function* validatedFrames(source, sourceError, signal) {
136
+ async function settleWithin(pending, ms, attempt) {
137
+ let timer;
138
+ const deadline = new Promise((_, reject) => {
139
+ timer = globalThis.setTimeout(() => {
140
+ const error = streamError("transport", "Agent event stream stalled");
141
+ attempt.abort(error);
142
+ reject(error);
143
+ }, ms);
144
+ });
66
145
  try {
67
- for await (const data of source) {
68
- const parsed = await zStreamEventsResponse.safeParseAsync(data);
69
- if (parsed.success) {
70
- yield parsed.data;
71
- } else if (isUnknownEnumError(parsed.error, data)) {
72
- yield data;
73
- } else {
74
- throw new AgentEventStreamError({
75
- kind: "contract",
76
- message: "Agent event stream received data that does not match the API contract",
77
- retryable: false,
78
- cause: parsed.error
79
- });
146
+ return await Promise.race([pending, deadline]);
147
+ } finally {
148
+ globalThis.clearTimeout(timer);
149
+ }
150
+ }
151
+ async function* openConnection(client2, { path, query, headers }, callerSignal) {
152
+ const attempt = new AbortController();
153
+ const signal = callerSignal == null ? attempt.signal : AbortSignal.any([callerSignal, attempt.signal]);
154
+ let reader;
155
+ try {
156
+ const dispatch = { started: false };
157
+ const { error, response } = await settleWithin(
158
+ client2.request({
159
+ method: "GET",
160
+ url: streamUrl,
161
+ path,
162
+ query,
163
+ headers: { Accept: "text/event-stream", ...headers },
164
+ parseAs: "stream",
165
+ signal,
166
+ throwOnError: false,
167
+ fetch: (input, init) => {
168
+ dispatch.started = true;
169
+ return (client2.getConfig().fetch ?? globalThis.fetch)(input, init);
170
+ }
171
+ }),
172
+ stallTimeoutMs,
173
+ attempt
174
+ );
175
+ if (response == null) {
176
+ throw dispatch.started ? streamError("transport", "Agent event stream disconnected", { cause: error }) : streamError("client", "Agent event stream request could not be prepared", {
177
+ cause: error
178
+ });
179
+ }
180
+ if (response.status !== 200) {
181
+ const apiError = await ApiError.fromResponse(response);
182
+ await response.body?.cancel().catch(() => void 0);
183
+ throw streamError("http", apiError.message, {
184
+ status: response.status,
185
+ code: apiError.code,
186
+ retryAfterMs: parseRetryAfter(response.headers.get("Retry-After")),
187
+ cause: apiError
188
+ });
189
+ }
190
+ if (error !== void 0) {
191
+ throw streamError("client", "Agent event stream response was rejected", { cause: error });
192
+ }
193
+ const mediaType = response.headers.get("Content-Type")?.split(";", 1)[0]?.trim().toLowerCase();
194
+ if (mediaType !== "text/event-stream") {
195
+ await response.body?.cancel().catch(() => void 0);
196
+ throw streamError("contract", "Agent event stream response is not text/event-stream");
197
+ }
198
+ if (response.body == null) {
199
+ throw streamError("contract", "Agent event stream response has no body");
200
+ }
201
+ reader = response.body.getReader();
202
+ signal.throwIfAborted();
203
+ yield { kind: "connected" };
204
+ const parser = createServerSentEventParser();
205
+ const decoder = new TextDecoder();
206
+ while (true) {
207
+ signal.throwIfAborted();
208
+ const chunk = await settleWithin(reader.read(), stallTimeoutMs, attempt);
209
+ if (chunk.done) throw streamError("transport", "Agent event stream ended unexpectedly");
210
+ for (const data of parser.push(decoder.decode(chunk.value, { stream: true }))) {
211
+ yield { kind: "message", data };
80
212
  }
81
213
  }
82
- } catch (error2) {
83
- throw classifyStreamError(error2, signal);
214
+ } catch (error) {
215
+ throw error instanceof AgentEventStreamError ? error : streamError("transport", "Agent event stream disconnected", { cause: error });
216
+ } finally {
217
+ await reader?.cancel().catch(() => void 0);
218
+ }
219
+ }
220
+ function decodeFrame(text) {
221
+ const frame = zStreamFrame.safeParse(text);
222
+ if (!frame.success) {
223
+ throw streamError("contract", "Agent event stream received data outside its API contract", {
224
+ cause: frame.error
225
+ });
84
226
  }
85
- const error = sourceError();
86
- if (error != null) throw error;
227
+ return frame.data;
228
+ }
229
+ function isErrorFrame(data) {
230
+ return zErrorResponse.safeParse(data).success;
231
+ }
232
+ function durableSequence(data) {
233
+ const cursor = zDurableCursor.safeParse(data);
234
+ return cursor.success ? cursor.data.sequence : void 0;
87
235
  }
88
- async function openAgentEventStream({
236
+ async function* openAgentEventStream({
89
237
  client: client2,
90
238
  path,
91
239
  query,
92
240
  headers,
93
- signal
241
+ signal,
242
+ onConnectionStateChange
94
243
  }) {
95
- let connectionError;
96
- try {
97
- const result = await streamEvents({
98
- client: client2,
99
- path,
100
- query,
101
- headers,
102
- signal,
103
- responseValidator: void 0,
104
- sseMaxRetryAttempts: 1,
105
- onSseError: (error) => {
106
- connectionError = classifyStreamError(error, signal);
244
+ let cursor;
245
+ let consecutiveFailures = 0;
246
+ let hasRetried = false;
247
+ while (true) {
248
+ let connectedAt;
249
+ try {
250
+ const connection = openConnection(
251
+ client2,
252
+ {
253
+ path,
254
+ query,
255
+ headers: cursor == null ? headers : { ...headers, "Last-Event-ID": cursor }
256
+ },
257
+ signal
258
+ );
259
+ for await (const event of connection) {
260
+ if (event.kind === "connected") {
261
+ connectedAt = Date.now();
262
+ onConnectionStateChange?.({ state: "connected", reconnected: hasRetried });
263
+ continue;
264
+ }
265
+ const data = decodeFrame(event.data);
266
+ signal?.throwIfAborted();
267
+ if (isErrorFrame(data)) throw streamError("api", data.error, { code: data.code });
268
+ const sequence = durableSequence(data);
269
+ if (sequence != null && cursor != null && sequence <= cursor) continue;
270
+ yield data;
271
+ consecutiveFailures = 0;
272
+ if (sequence != null) cursor = sequence;
107
273
  }
108
- });
109
- return {
110
- stream: validatedFrames(result.stream, () => connectionError, signal)
111
- };
112
- } catch (error) {
113
- throw classifyStreamError(error, signal);
274
+ } catch (error) {
275
+ if (signal?.aborted === true) return;
276
+ if (!(error instanceof AgentEventStreamError) || !retryable(error)) throw error;
277
+ if (connectedAt != null && Date.now() - connectedAt >= stableConnectionResetMs) {
278
+ consecutiveFailures = 0;
279
+ }
280
+ consecutiveFailures += 1;
281
+ const delayMs = Math.max(reconnectDelay(consecutiveFailures), error.retryAfterMs ?? 0);
282
+ onConnectionStateChange?.({
283
+ state: "reconnecting",
284
+ attempt: consecutiveFailures,
285
+ delayMs,
286
+ error
287
+ });
288
+ hasRetried = true;
289
+ if (!await abortableDelay(delayMs, signal)) return;
290
+ }
114
291
  }
115
292
  }
116
293
 
117
294
  // src/auth.ts
295
+ function isTokenResolver(token) {
296
+ return typeof token === "function";
297
+ }
118
298
  function bearerToken(token) {
119
- const resolve = typeof token === "function" ? token : () => token;
299
+ const resolve = isTokenResolver(token) ? token : () => token;
120
300
  return {
121
301
  async authenticate(request) {
122
302
  const value = await resolve();
@@ -143,31 +323,31 @@ function cliLoginTokenHost(token) {
143
323
  }
144
324
 
145
325
  // src/client.ts
326
+ var httpMethods = [
327
+ "connect",
328
+ "delete",
329
+ "get",
330
+ "head",
331
+ "options",
332
+ "patch",
333
+ "post",
334
+ "put",
335
+ "trace"
336
+ ];
337
+ function withoutClientSelector(options) {
338
+ const stripped = { ...options };
339
+ Reflect.deleteProperty(stripped, "client");
340
+ return stripped;
341
+ }
146
342
  function stripClientSelector(client2) {
147
- const strip = (dispatch) => (options) => {
148
- if (options == null || !("client" in options)) return dispatch(options);
149
- const rest = { ...options };
150
- delete rest.client;
151
- return dispatch(rest);
152
- };
153
- const methods = [
154
- "connect",
155
- "delete",
156
- "get",
157
- "head",
158
- "options",
159
- "patch",
160
- "post",
161
- "put",
162
- "request",
163
- "trace"
164
- ];
165
- const wrap = (target) => {
166
- const dispatches = target;
167
- for (const method of methods) dispatches[method] &&= strip(dispatches[method]);
168
- };
169
- wrap(client2);
170
- wrap(client2.sse);
343
+ const { request } = client2;
344
+ client2.request = (options) => request(withoutClientSelector(options));
345
+ for (const method of httpMethods) {
346
+ const dispatch = client2[method];
347
+ client2[method] = (options) => dispatch(withoutClientSelector(options));
348
+ const sseDispatch = client2.sse[method];
349
+ client2.sse[method] = (options) => sseDispatch(withoutClientSelector(options));
350
+ }
171
351
  }
172
352
  function createOmnaraClient(options = {}) {
173
353
  const client2 = createClient(
@@ -178,7 +358,8 @@ function createOmnaraClient(options = {}) {
178
358
  client2.setConfig({
179
359
  baseUrl: options.baseUrl ?? client.getConfig().baseUrl,
180
360
  credentials: options.credentials,
181
- headers: options.headers
361
+ headers: options.headers,
362
+ fetch: options.fetch
182
363
  });
183
364
  const { auth } = options;
184
365
  if (auth) {
@@ -196,31 +377,32 @@ function createOmnaraClient(options = {}) {
196
377
  }
197
378
 
198
379
  // src/device.ts
199
- import * as z from "zod";
380
+ import * as z2 from "zod";
200
381
  var OMNARA_CLI_OAUTH_CLIENT_ID = "omnara-cli";
201
382
  var OAUTH_DEVICE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
202
- var zAuthorizationServerMetadata = z.object({
203
- issuer: z.url(),
204
- device_authorization_endpoint: z.url(),
205
- token_endpoint: z.url(),
206
- grant_types_supported: z.array(z.string()),
207
- token_endpoint_auth_methods_supported: z.array(z.string())
383
+ var zAuthorizationServerMetadata = z2.object({
384
+ issuer: z2.url(),
385
+ device_authorization_endpoint: z2.url(),
386
+ token_endpoint: z2.url(),
387
+ grant_types_supported: z2.array(z2.string()),
388
+ token_endpoint_auth_methods_supported: z2.array(z2.string())
208
389
  });
209
- var zDeviceAuthStartResponse = z.object({
210
- device_code: z.string().min(1),
211
- user_code: z.string().min(1),
212
- verification_uri: z.string().min(1),
213
- verification_uri_complete: z.string().min(1),
214
- expires_in: z.number().int().positive(),
215
- interval: z.number().int().positive()
390
+ var zDeviceAuthStartResponse = z2.object({
391
+ device_code: z2.string().min(1),
392
+ user_code: z2.string().min(1),
393
+ verification_uri: z2.string().min(1),
394
+ verification_uri_complete: z2.string().min(1),
395
+ expires_in: z2.number().int().positive(),
396
+ interval: z2.number().int().positive()
216
397
  });
217
- var zDeviceAuthErrorResponse = z.object({
218
- error: z.string().min(1),
219
- error_description: z.string().optional()
398
+ var zDeviceAuthErrorResponse = z2.object({
399
+ error: z2.string().min(1),
400
+ error_description: z2.string().optional()
220
401
  });
221
- var zDeviceAuthApprovedResponse = z.object({
222
- access_token: z.string().min(1),
223
- token_type: z.string()
402
+ var zDeviceAuthFailure = zJsonText.pipe(zDeviceAuthErrorResponse);
403
+ var zDeviceAuthApprovedResponse = z2.object({
404
+ access_token: z2.string().min(1),
405
+ token_type: z2.string()
224
406
  });
225
407
  var DEVICE_AUTH_FAILURE_MESSAGES = {
226
408
  access_denied: "the login request was denied",
@@ -241,7 +423,7 @@ async function postOAuthForm(fetchImpl, endpoint, body) {
241
423
  Accept: "application/json",
242
424
  "Content-Type": "application/x-www-form-urlencoded"
243
425
  },
244
- body: new URLSearchParams(body).toString()
426
+ body: body.toString()
245
427
  });
246
428
  }
247
429
  function normalizeIssuer(raw) {
@@ -269,8 +451,8 @@ async function startDeviceAuth(options) {
269
451
  if (!metadata.token_endpoint_auth_methods_supported.includes("none")) {
270
452
  throw new Error("authorization server does not support public OAuth clients");
271
453
  }
272
- const body = { client_id: options.clientId };
273
- if (options.tokenName !== void 0) body.token_name = options.tokenName;
454
+ const body = new URLSearchParams({ client_id: options.clientId });
455
+ if (options.tokenName !== void 0) body.set("token_name", options.tokenName);
274
456
  const response = await postOAuthForm(fetchImpl, metadata.device_authorization_endpoint, body);
275
457
  if (!response.ok) throw await ApiError.fromResponse(response);
276
458
  const data = zDeviceAuthStartResponse.parse(await response.json());
@@ -294,18 +476,20 @@ async function pollDeviceAuthToken(options) {
294
476
  let interval = options.intervalSeconds;
295
477
  while (true) {
296
478
  await sleep(interval);
297
- const response = await postOAuthForm(fetchImpl, options.tokenEndpoint, {
298
- grant_type: OAUTH_DEVICE_GRANT_TYPE,
299
- device_code: options.deviceCode,
300
- client_id: options.clientId
301
- });
479
+ const response = await postOAuthForm(
480
+ fetchImpl,
481
+ options.tokenEndpoint,
482
+ new URLSearchParams({
483
+ grant_type: OAUTH_DEVICE_GRANT_TYPE,
484
+ device_code: options.deviceCode,
485
+ client_id: options.clientId
486
+ })
487
+ );
302
488
  if (response.status === 200) {
303
489
  return zDeviceAuthApprovedResponse.parse(await response.json()).access_token;
304
490
  }
305
491
  if (response.status === 400) {
306
- const failure = zDeviceAuthErrorResponse.safeParse(
307
- await response.clone().json().catch(() => void 0)
308
- );
492
+ const failure = zDeviceAuthFailure.safeParse(await response.clone().text());
309
493
  if (failure.success) {
310
494
  if (failure.data.error === "authorization_pending") continue;
311
495
  if (failure.data.error === "slow_down") {
@@ -335,6 +519,7 @@ export {
335
519
  pollDeviceAuthToken,
336
520
  zod_gen_exports as schemas,
337
521
  sdk_gen_exports as sdk,
338
- startDeviceAuth
522
+ startDeviceAuth,
523
+ zJsonText
339
524
  };
340
525
  //# sourceMappingURL=index.js.map