@oaiz/sdk 0.0.0-stage → 0.1.4131

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 ADDED
@@ -0,0 +1,3706 @@
1
+ // src/errors.ts
2
+ var ApiError = class extends Error {
3
+ constructor(status, init = {}) {
4
+ super(`HTTP ${status}`);
5
+ this.status = status;
6
+ this.name = "ApiError";
7
+ this.headers = init.headers ?? new Headers();
8
+ this.requestId = init.requestId;
9
+ this.rawBody = init.rawBody ?? "";
10
+ this.jsonBody = init.jsonBody ?? null;
11
+ this.body = init.body ?? this.jsonBody;
12
+ }
13
+ isNotFound() {
14
+ return this.status === 404;
15
+ }
16
+ };
17
+ var AuthConfigurationError = class extends Error {
18
+ constructor(operationId, alternatives) {
19
+ super(`No configured credentials satisfy operation ${operationId}`);
20
+ this.operationId = operationId;
21
+ this.alternatives = alternatives;
22
+ this.name = "AuthConfigurationError";
23
+ }
24
+ };
25
+ var ResponseDecodeError = class extends Error {
26
+ constructor(failure, status, init = {}) {
27
+ super(`HTTP ${status}: response decode failed (${failure})`);
28
+ this.failure = failure;
29
+ this.status = status;
30
+ this.name = "ResponseDecodeError";
31
+ this.headers = init.headers ?? new Headers();
32
+ this.requestId = init.requestId;
33
+ this.rawBody = init.rawBody ?? "";
34
+ this.expectedContentType = init.expectedContentType ?? "application/json";
35
+ this.actualContentType = init.actualContentType;
36
+ this.cause = init.cause;
37
+ }
38
+ };
39
+
40
+ // src/app/response.ts
41
+ const REQUEST_INVALID_CODE = "storage-table-request-invalid";
42
+ function failure(status, error) {
43
+ return {
44
+ data: null,
45
+ error,
46
+ count: null,
47
+ status
48
+ };
49
+ }
50
+ function failureFrom(cause) {
51
+ if (cause instanceof ApiError) {
52
+ const body = isHttpError(cause.body) ? cause.body : void 0;
53
+ return failure(cause.status, {
54
+ message: body?.message ?? cause.message,
55
+ code: body?.slug ?? "",
56
+ hints: body?.hints ?? []
57
+ });
58
+ }
59
+ return failure(0, {
60
+ message: cause instanceof Error ? cause.message : String(cause),
61
+ code: "",
62
+ hints: []
63
+ });
64
+ }
65
+ function isHttpError(body) {
66
+ return typeof body === "object" && body !== null && typeof body.message === "string";
67
+ }
68
+
69
+ // src/app/sse-stream.ts
70
+ var SseFrames = class {
71
+ constructor(eventName) {
72
+ this.eventName = eventName;
73
+ this.decoder = new TextDecoder();
74
+ this.buffer = "";
75
+ }
76
+ *push(bytes) {
77
+ this.buffer += this.decoder.decode(bytes, { stream: bytes !== void 0 });
78
+ const held = bytes !== void 0 && this.buffer.endsWith("\r") ? "\r" : "";
79
+ const blocks = (held ? this.buffer.slice(0, -1) : this.buffer).replace(/\r\n?/g, "\n").split("\n\n");
80
+ this.buffer = (blocks.pop() ?? "") + held;
81
+ for (const block of blocks) {
82
+ let name = "";
83
+ let id;
84
+ const data = [];
85
+ for (const line of block.split("\n")) {
86
+ const colon = line.indexOf(":");
87
+ if (colon === 0) continue;
88
+ const field = colon < 0 ? line : line.slice(0, colon);
89
+ const raw = colon < 0 ? "" : line.slice(colon + 1);
90
+ const value = raw.startsWith(" ") ? raw.slice(1) : raw;
91
+ if (field === "event") name = value;
92
+ if (field === "id") id = value;
93
+ if (field === "data") data.push(value);
94
+ }
95
+ if (name === this.eventName && data.length > 0) yield {
96
+ data: JSON.parse(data.join("\n")),
97
+ id
98
+ };
99
+ }
100
+ }
101
+ };
102
+ async function* readSseStream(open, request, body, signal, eventName, isLast) {
103
+ let reader;
104
+ try {
105
+ const response = await open(request, body, signal);
106
+ if (!response.ok || response.body === null) {
107
+ const refusal = await response.json().catch(() => ({}));
108
+ yield failure(response.status, {
109
+ message: typeof refusal.message === "string" ? refusal.message : response.statusText,
110
+ code: typeof refusal.slug === "string" ? refusal.slug : "",
111
+ hints: Array.isArray(refusal.hints) ? refusal.hints : []
112
+ });
113
+ return;
114
+ }
115
+ reader = response.body.getReader();
116
+ const frames = new SseFrames(eventName);
117
+ while (true) {
118
+ const { done, value } = await reader.read();
119
+ for (const frame of frames.push(done ? void 0 : value)) {
120
+ yield {
121
+ data: frame,
122
+ error: null,
123
+ count: null,
124
+ status: 200
125
+ };
126
+ if (isLast(frame.data)) return;
127
+ }
128
+ if (done) return;
129
+ }
130
+ } catch (error) {
131
+ yield failureFrom(error);
132
+ } finally {
133
+ await reader?.cancel().catch(() => {});
134
+ }
135
+ }
136
+
137
+ // src/app/raw-request.ts
138
+ const rawOperations = {
139
+ executeJobStream: {
140
+ method: "POST",
141
+ path: "/ingest/jobs/{jobUuid}/execute/stream"
142
+ },
143
+ streamActionExecutionEvents: {
144
+ method: "GET",
145
+ path: "/ingest/action/log/{uuid}/events"
146
+ },
147
+ createAppChatMessage: {
148
+ method: "POST",
149
+ path: "/internalagents/chat/apps/{appUuid}/messages"
150
+ },
151
+ createAppChatApproval: {
152
+ method: "POST",
153
+ path: "/internalagents/chat/apps/{appUuid}/sessions/{sessionId}/approvals/{toolCallId}"
154
+ },
155
+ deleteAppLiveVoiceSession: {
156
+ method: "DELETE",
157
+ path: "/internalagents/chat/apps/{appUuid}/voice/sessions/{id}"
158
+ }
159
+ };
160
+ function sendRaw(url, request, init) {
161
+ const { method, path } = rawOperations[request.operation];
162
+ const params = request.params;
163
+ const search = request.query?.toString() ?? "";
164
+ const headers = { ...init.headers };
165
+ if (init.body !== void 0) headers["Content-Type"] = "application/json";
166
+ return fetch(url.replace(/\/+$/, "") + path.replace(/\{(\w+)\}/g, (_, name) => encodeURIComponent(params[name])) + (search === "" ? "" : `?${search}`), {
167
+ method,
168
+ headers,
169
+ body: init.body === void 0 ? void 0 : JSON.stringify(init.body),
170
+ signal: init.signal,
171
+ keepalive: init.keepalive
172
+ });
173
+ }
174
+
175
+ // src/app/voice.ts
176
+ const LIVE_VOICE_EVENT_CHANNEL = "oai-events";
177
+ const ICE_GATHERING_TIMEOUT_MS = 3e3;
178
+ const SESSION_CLOSE_TIMEOUT_MS = 2e3;
179
+ const LINES_TIMEOUT_MS = 2e3;
180
+ const SIGN_OUT_RELEASE_TIMEOUT_MS = 5e3;
181
+ const SUBSTANTIAL_ASSISTANT_WORDS = 4;
182
+ const STOPPED_SPEECH = "Okay, I stopped that.";
183
+ const FAILED_SPEECH = "That didn't work. There's an error on screen.";
184
+ const VOICE_UNAVAILABLE = {
185
+ message: "Voice needs a secure browser page with WebRTC and a microphone.",
186
+ code: "voice-browser-required",
187
+ hints: []
188
+ };
189
+ const VOICE_ALREADY_STARTED = {
190
+ message: "This voice conversation is already running.",
191
+ code: "voice-already-started",
192
+ hints: []
193
+ };
194
+ const VOICE_NOT_LIVE = {
195
+ message: "No voice conversation is live.",
196
+ code: "voice-not-live",
197
+ hints: []
198
+ };
199
+ const VOICE_TURN_ENDED = {
200
+ message: "The answer stopped before it finished.",
201
+ code: "voice-turn-ended",
202
+ hints: []
203
+ };
204
+ const NO_WEBRTC_OFFER = {
205
+ message: "The browser produced no WebRTC offer.",
206
+ code: "voice-no-webrtc-offer",
207
+ hints: []
208
+ };
209
+ const MICROPHONE_IN_FRAME = {
210
+ message: "The browser refuses the microphone to an app inside a frame. Open the app in its own tab to talk to it.",
211
+ code: "voice-microphone-in-frame",
212
+ hints: []
213
+ };
214
+ const MICROPHONE_BLOCKED = {
215
+ message: "Microphone access is blocked. Enable the mic permission for this site in your browser settings, then try again.",
216
+ code: "voice-microphone-blocked",
217
+ hints: []
218
+ };
219
+ const MICROPHONE_NOT_FOUND = {
220
+ message: "No microphone was found. Connect a microphone and try again.",
221
+ code: "voice-microphone-not-found",
222
+ hints: []
223
+ };
224
+ const MICROPHONE_IN_USE = {
225
+ message: "Your microphone is in use by another application. Close it and try again.",
226
+ code: "voice-microphone-in-use",
227
+ hints: []
228
+ };
229
+ const MICROPHONE_UNSUPPORTED = {
230
+ message: "Your microphone does not support the required audio settings.",
231
+ code: "voice-microphone-unsupported",
232
+ hints: []
233
+ };
234
+ const MICROPHONE_INTERRUPTED = {
235
+ message: "Microphone access was interrupted. Please try again.",
236
+ code: "voice-microphone-interrupted",
237
+ hints: []
238
+ };
239
+ const MICROPHONE_FAILED = {
240
+ message: "Could not start the microphone.",
241
+ code: "voice-microphone-failed",
242
+ hints: []
243
+ };
244
+ const IDLE_SNAPSHOT = {
245
+ state: "idle",
246
+ assistantSpeech: "",
247
+ outputAnalyser: null,
248
+ muted: false,
249
+ error: null,
250
+ sessionId: null,
251
+ turnRunning: false
252
+ };
253
+ var OaizVoice = class {
254
+ constructor(client, open, app, auth, url, options) {
255
+ this.client = client;
256
+ this.open = open;
257
+ this.app = app;
258
+ this.auth = auth;
259
+ this.url = url;
260
+ this.options = options;
261
+ this.snapshot = IDLE_SNAPSHOT;
262
+ this.listeners = /* @__PURE__ */ new Set();
263
+ this.peer = null;
264
+ this.channel = null;
265
+ this.stream = null;
266
+ this.audio = null;
267
+ this.audioContext = null;
268
+ this.outputSource = null;
269
+ this.liveSessionId = null;
270
+ this.chatSessionId = null;
271
+ this.closedResolve = null;
272
+ this.removeSignOutHook = null;
273
+ this.startAborted = false;
274
+ this.starting = Promise.resolve();
275
+ this.stopping = Promise.resolve();
276
+ this.eventSeq = 0;
277
+ this.pendingUserSpeech = "";
278
+ this.pendingAssistantSpeech = "";
279
+ this.seedContext = "";
280
+ this.turns = [];
281
+ this.runningTurn = null;
282
+ this.lines = Promise.resolve();
283
+ this.subscribe = (listener) => {
284
+ this.listeners.add(listener);
285
+ return () => {
286
+ this.listeners.delete(listener);
287
+ };
288
+ };
289
+ this.getSnapshot = () => this.snapshot;
290
+ this.stopTurn = () => {
291
+ this.runningTurn?.controller.abort();
292
+ };
293
+ this.stopAllTurns = () => {
294
+ this.turns = [];
295
+ this.runningTurn?.controller.abort();
296
+ };
297
+ this.toggleMute = () => {
298
+ const next = !this.snapshot.muted;
299
+ this.applyMute(next);
300
+ this.publish({ muted: next });
301
+ };
302
+ this.stop = () => {
303
+ const { state } = this.snapshot;
304
+ if (state === "idle") return Promise.resolve();
305
+ if (state === "closing") return this.stopping;
306
+ this.publish({ state: "closing" });
307
+ if (state === "connecting") {
308
+ this.startAborted = true;
309
+ this.stopping = this.starting.then(() => void 0);
310
+ return this.stopping;
311
+ }
312
+ this.flushPendingLines();
313
+ this.stopping = this.closeProviderSession();
314
+ return this.stopping;
315
+ };
316
+ this.releaseForSignOut = async () => {
317
+ this.stopAllTurns();
318
+ await within(this.stop(), SIGN_OUT_RELEASE_TIMEOUT_MS);
319
+ };
320
+ this.leavePage = () => {
321
+ this.stopAllTurns();
322
+ const liveSessionId = this.liveSessionId;
323
+ this.liveSessionId = null;
324
+ if (liveSessionId !== null) this.releaseOnLeave(liveSessionId);
325
+ if (this.snapshot.state === "connecting" || this.startAborted) {
326
+ this.startAborted = true;
327
+ this.publish({ state: "closing" });
328
+ this.closeMedia();
329
+ return;
330
+ }
331
+ this.teardown();
332
+ };
333
+ }
334
+ start(options = {}) {
335
+ if (voiceUnavailable()) return Promise.resolve(this.refuse(VOICE_UNAVAILABLE));
336
+ if (this.snapshot.state !== "idle") return Promise.resolve(failure(0, VOICE_ALREADY_STARTED));
337
+ const starting = this.connect(options);
338
+ this.starting = starting;
339
+ return starting;
340
+ }
341
+ send(content) {
342
+ if (this.snapshot.state !== "live" || this.chatSessionId === null) return { error: VOICE_NOT_LIVE };
343
+ this.flushPendingLines();
344
+ this.appendThinking(null, `The user typed this in the chat window: ${content}`);
345
+ this.enqueueTurn(content, null, this.chatSessionId);
346
+ return { error: null };
347
+ }
348
+ async connect({ sessionId, recentContext = "" }) {
349
+ this.startAborted = false;
350
+ this.chatSessionId = sessionId ?? null;
351
+ const recent = recentContext.trim();
352
+ this.seedContext = recent ? `Recent chat before this voice session:\n${recent}` : "";
353
+ this.publish({
354
+ state: "connecting",
355
+ error: null,
356
+ assistantSpeech: "",
357
+ muted: false,
358
+ sessionId: this.chatSessionId
359
+ });
360
+ this.removeSignOutHook = this.auth.beforeSignOut(this.releaseForSignOut);
361
+ window.addEventListener("pagehide", this.leavePage);
362
+ let localStream;
363
+ try {
364
+ localStream = await navigator.mediaDevices.getUserMedia({ audio: true });
365
+ } catch (cause) {
366
+ this.teardown();
367
+ return this.startAborted ? started(sessionId ?? null) : this.refuse(microphoneError(cause));
368
+ }
369
+ if (this.startAborted) {
370
+ stopTracks(localStream);
371
+ this.teardown();
372
+ return started(sessionId ?? null);
373
+ }
374
+ this.stream = localStream;
375
+ this.applyMute(this.snapshot.muted);
376
+ let answeredSession = sessionId ?? null;
377
+ try {
378
+ const connection = this.openPeerConnection(localStream);
379
+ await connection.setLocalDescription(await connection.createOffer());
380
+ await waitForIceGathering(connection);
381
+ if (this.startAborted) {
382
+ this.teardown();
383
+ return started(answeredSession);
384
+ }
385
+ const offerSdp = connection.localDescription?.sdp;
386
+ if (!offerSdp) {
387
+ await this.release();
388
+ return this.refuse(NO_WEBRTC_OFFER);
389
+ }
390
+ const session = await this.client.createAppLiveVoiceSession(this.app, {
391
+ sessionId,
392
+ offerSdp,
393
+ instructions: this.options.instructions
394
+ });
395
+ this.liveSessionId = session.liveSessionId;
396
+ this.chatSessionId = session.sessionId;
397
+ answeredSession = session.sessionId;
398
+ if (this.startAborted) {
399
+ await this.release();
400
+ return started(answeredSession);
401
+ }
402
+ this.publish({ sessionId: session.sessionId });
403
+ await connection.setRemoteDescription({
404
+ type: "answer",
405
+ sdp: session.answerSdp
406
+ });
407
+ if (this.startAborted) {
408
+ await this.release();
409
+ return started(answeredSession);
410
+ }
411
+ this.publish({ state: "live" });
412
+ return {
413
+ data: { sessionId: session.sessionId },
414
+ error: null,
415
+ count: null,
416
+ status: 201
417
+ };
418
+ } catch (cause) {
419
+ const aborted = this.startAborted;
420
+ await this.release();
421
+ if (aborted) return started(answeredSession);
422
+ const refusal = failureFrom(cause);
423
+ this.publish({ error: refusal.error });
424
+ return refusal;
425
+ }
426
+ }
427
+ openPeerConnection(localStream) {
428
+ const connection = new RTCPeerConnection();
429
+ this.peer = connection;
430
+ for (const track of localStream.getAudioTracks()) connection.addTrack(track, localStream);
431
+ const element = document.createElement("audio");
432
+ element.autoplay = true;
433
+ this.audio = element;
434
+ connection.ontrack = (ev) => {
435
+ const remote = ev.streams[0] ?? null;
436
+ element.srcObject = remote;
437
+ this.publish({ outputAnalyser: remote ? this.attachOutputAnalyser(remote) : null });
438
+ };
439
+ connection.onconnectionstatechange = () => {
440
+ if (this.peer !== connection) return;
441
+ const state = connection.connectionState;
442
+ if (state === "failed" || state === "disconnected" || state === "closed") this.release();
443
+ };
444
+ const dataChannel = connection.createDataChannel(LIVE_VOICE_EVENT_CHANNEL);
445
+ this.channel = dataChannel;
446
+ dataChannel.onmessage = (ev) => {
447
+ if (this.channel !== dataChannel) return;
448
+ this.auth.accessToken();
449
+ try {
450
+ this.handleProviderEvent(JSON.parse(ev.data));
451
+ } catch {
452
+ console.error("unparsable live voice event");
453
+ }
454
+ };
455
+ return connection;
456
+ }
457
+ handleProviderEvent(event) {
458
+ switch (event.type) {
459
+ case "session.started":
460
+ if (this.snapshot.state === "connecting") this.publish({ state: "live" });
461
+ if (this.seedContext) {
462
+ this.appendThinking(null, this.seedContext);
463
+ this.seedContext = "";
464
+ }
465
+ break;
466
+ case "session.input_transcript.delta":
467
+ if (this.pendingAssistantSpeech) this.closeAssistantLine();
468
+ this.pendingUserSpeech += event.delta ?? "";
469
+ this.publish({ assistantSpeech: "" });
470
+ break;
471
+ case "session.output_transcript.delta":
472
+ if (event.delta) {
473
+ this.pendingAssistantSpeech += event.delta;
474
+ this.publish({ assistantSpeech: this.snapshot.assistantSpeech + event.delta });
475
+ }
476
+ break;
477
+ case "session.delegation.created":
478
+ if (event.delegation?.id) this.dispatchDelegation(event.delegation.id);
479
+ break;
480
+ case "session.closed":
481
+ this.flushPendingLines();
482
+ if (this.closedResolve) {
483
+ this.closedResolve();
484
+ this.closedResolve = null;
485
+ break;
486
+ }
487
+ this.release();
488
+ }
489
+ }
490
+ dispatchDelegation(delegationId) {
491
+ const request = this.pendingUserSpeech.trim();
492
+ this.pendingUserSpeech = "";
493
+ if (!request || this.chatSessionId === null || this.snapshot.state !== "live") return;
494
+ this.enqueueTurn(request, delegationId, this.chatSessionId);
495
+ }
496
+ enqueueTurn(content, delegationId, sessionId) {
497
+ const clientMessageId = crypto.randomUUID();
498
+ this.options.onEvent?.({
499
+ type: "message.created",
500
+ message: {
501
+ id: clientMessageId,
502
+ clientMessageId,
503
+ role: "user",
504
+ messageType: "user_input",
505
+ content,
506
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
507
+ }
508
+ });
509
+ this.turns.push({
510
+ content,
511
+ delegationId,
512
+ sessionId,
513
+ clientMessageId,
514
+ controller: new AbortController(),
515
+ lastProgress: "",
516
+ channel: this.channel
517
+ });
518
+ this.runTurns();
519
+ }
520
+ async runTurns() {
521
+ if (this.runningTurn !== null) return;
522
+ for (let turn = this.turns.shift(); turn !== void 0; turn = this.turns.shift()) {
523
+ this.runningTurn = turn;
524
+ this.publish({ turnRunning: true });
525
+ await this.runTurn(turn);
526
+ this.runningTurn = null;
527
+ }
528
+ this.publish({ turnRunning: false });
529
+ }
530
+ async runTurn(turn) {
531
+ let result = false;
532
+ let refusal;
533
+ try {
534
+ await within(this.lines, LINES_TIMEOUT_MS);
535
+ this.publish({ error: null });
536
+ const body = {
537
+ ...this.options.turn(turn.delegationId === null ? "typed" : "spoken"),
538
+ content: turn.content,
539
+ sessionId: turn.sessionId,
540
+ clientMessageId: turn.clientMessageId,
541
+ type: "voice_delegation",
542
+ voiceDelegationId: turn.delegationId ?? void 0
543
+ };
544
+ const frames = readSseStream(this.open, {
545
+ operation: "createAppChatMessage",
546
+ params: { appUuid: this.app }
547
+ }, body, turn.controller.signal, "chat_event", (event) => event.type === "voice.delegationResult");
548
+ for await (const frame of frames) {
549
+ if (turn.controller.signal.aborted) break;
550
+ if (frame.error !== null) {
551
+ refusal = frame;
552
+ break;
553
+ }
554
+ const event = frame.data.data;
555
+ this.options.onEvent?.(event);
556
+ this.noteToolStep(turn, event);
557
+ if (event.voiceDelegationResult) {
558
+ result = true;
559
+ this.speakResult(turn, event.voiceDelegationResult);
560
+ }
561
+ }
562
+ } catch (cause) {
563
+ refusal = failureFrom(cause);
564
+ }
565
+ if (!result) this.finishWithoutResult(turn, refusal);
566
+ }
567
+ finishWithoutResult(turn, refusal) {
568
+ if (turn.controller.signal.aborted) {
569
+ this.appendCommentary(turn.delegationId, STOPPED_SPEECH, turn.channel);
570
+ return;
571
+ }
572
+ if (turn.delegationId === null && refusal !== void 0 && refusal.status >= 400) this.appendThinking(null, "The typed message was not sent. No answer is coming for it.", turn.channel);
573
+ this.appendCommentary(turn.delegationId, FAILED_SPEECH, turn.channel);
574
+ this.publish({ error: refusal?.error ?? VOICE_TURN_ENDED });
575
+ if (refusal?.status === 401) this.endForRefusedToken();
576
+ }
577
+ noteToolStep(turn, event) {
578
+ if (event.type !== "message.created" && event.type !== "message.updated") return;
579
+ const content = toolProgress(event.message);
580
+ if (content === null || content === turn.lastProgress) return;
581
+ turn.lastProgress = content;
582
+ this.appendThinking(turn.delegationId, content, turn.channel);
583
+ }
584
+ speakResult(turn, result) {
585
+ const delegationId = result.delegationId || null;
586
+ if (result.context) this.appendThinking(delegationId, `Written answer shown on screen:\n${result.context}`, turn.channel);
587
+ if (result.speech) this.appendCommentary(delegationId, result.speech, turn.channel);
588
+ }
589
+ closeAssistantLine() {
590
+ const assistantLine = this.pendingAssistantSpeech;
591
+ this.pendingAssistantSpeech = "";
592
+ if (isSubstantialAssistantLine(assistantLine)) {
593
+ this.recordLine("user", this.pendingUserSpeech);
594
+ this.pendingUserSpeech = "";
595
+ }
596
+ this.recordLine("assistant", assistantLine);
597
+ }
598
+ flushPendingLines() {
599
+ this.recordLine("user", this.pendingUserSpeech);
600
+ this.recordLine("assistant", this.pendingAssistantSpeech);
601
+ this.pendingUserSpeech = "";
602
+ this.pendingAssistantSpeech = "";
603
+ }
604
+ recordLine(speaker, text) {
605
+ const content = text.trim();
606
+ const sessionId = this.chatSessionId;
607
+ if (!content || sessionId === null) return;
608
+ this.lines = this.lines.then(() => this.postLine(sessionId, speaker, content));
609
+ }
610
+ async postLine(sessionId, speaker, content) {
611
+ try {
612
+ await this.client.createAppVoiceLine(this.app, sessionId, {
613
+ speaker,
614
+ content
615
+ });
616
+ } catch (cause) {
617
+ const { status, error } = failureFrom(cause);
618
+ console.warn("spoken line not recorded", {
619
+ status,
620
+ code: error?.code
621
+ });
622
+ if (status === 401) {
623
+ this.publish({ error });
624
+ this.endForRefusedToken();
625
+ }
626
+ }
627
+ }
628
+ endForRefusedToken() {
629
+ this.turns = [];
630
+ this.stop();
631
+ }
632
+ async closeProviderSession() {
633
+ const connection = this.peer;
634
+ const closed = new Promise((resolve) => {
635
+ this.closedResolve = resolve;
636
+ });
637
+ if (this.appendEvent({
638
+ type: "session.close",
639
+ event_id: this.nextEventId()
640
+ })) await within(closed, SESSION_CLOSE_TIMEOUT_MS);
641
+ if (this.peer === connection) await this.release();
642
+ }
643
+ async release() {
644
+ this.flushPendingLines();
645
+ const liveSessionId = this.liveSessionId;
646
+ const lines = this.lines;
647
+ this.liveSessionId = null;
648
+ this.teardown();
649
+ if (liveSessionId === null) return;
650
+ await within(lines, LINES_TIMEOUT_MS);
651
+ try {
652
+ await this.client.deleteAppLiveVoiceSession(this.app, liveSessionId);
653
+ } catch (cause) {
654
+ const { status, error } = failureFrom(cause);
655
+ console.warn("live voice session not released", {
656
+ status,
657
+ code: error?.code
658
+ });
659
+ }
660
+ }
661
+ releaseOnLeave(liveSessionId) {
662
+ const token = this.auth.storedAccessToken();
663
+ sendRaw(this.url, {
664
+ operation: "deleteAppLiveVoiceSession",
665
+ params: {
666
+ appUuid: this.app,
667
+ id: liveSessionId
668
+ }
669
+ }, {
670
+ headers: token === void 0 ? {} : { Authorization: `Bearer ${token}` },
671
+ keepalive: true
672
+ }).catch(() => void 0);
673
+ }
674
+ closeMedia() {
675
+ this.channel?.close();
676
+ this.channel = null;
677
+ this.peer?.close();
678
+ this.peer = null;
679
+ if (this.stream !== null) stopTracks(this.stream);
680
+ this.stream = null;
681
+ if (this.audio !== null) {
682
+ this.audio.srcObject = null;
683
+ this.audio.remove();
684
+ this.audio = null;
685
+ }
686
+ this.outputSource?.disconnect();
687
+ this.outputSource = null;
688
+ if (this.audioContext !== null) {
689
+ this.audioContext.close();
690
+ this.audioContext = null;
691
+ }
692
+ }
693
+ teardown() {
694
+ this.removeSignOutHook?.();
695
+ this.removeSignOutHook = null;
696
+ window.removeEventListener("pagehide", this.leavePage);
697
+ this.closeMedia();
698
+ this.closedResolve?.();
699
+ this.closedResolve = null;
700
+ this.chatSessionId = null;
701
+ this.pendingUserSpeech = "";
702
+ this.pendingAssistantSpeech = "";
703
+ this.seedContext = "";
704
+ this.publish({
705
+ ...IDLE_SNAPSHOT,
706
+ error: this.snapshot.error,
707
+ turnRunning: this.snapshot.turnRunning
708
+ });
709
+ }
710
+ publish(patch) {
711
+ if (Object.entries(patch).every(([key, value]) => Object.is(Reflect.get(this.snapshot, key), value))) return;
712
+ this.snapshot = {
713
+ ...this.snapshot,
714
+ ...patch
715
+ };
716
+ this.listeners.forEach((listener) => listener());
717
+ }
718
+ refuse(error) {
719
+ this.publish({ error });
720
+ return failure(0, error);
721
+ }
722
+ nextEventId() {
723
+ this.eventSeq += 1;
724
+ return `oaiz_${Date.now()}_${this.eventSeq}`;
725
+ }
726
+ appendEvent(event, channel = this.channel) {
727
+ if (channel?.readyState !== "open") return false;
728
+ channel.send(JSON.stringify(event));
729
+ return true;
730
+ }
731
+ appendThinking(delegationId, content, channel = this.channel) {
732
+ this.appendEvent({
733
+ type: "session.thinking.append",
734
+ event_id: this.nextEventId(),
735
+ delegation_id: delegationId,
736
+ content
737
+ }, channel);
738
+ }
739
+ appendCommentary(delegationId, content, channel = this.channel) {
740
+ this.appendEvent({
741
+ type: "session.commentary.append",
742
+ event_id: this.nextEventId(),
743
+ delegation_id: delegationId,
744
+ content
745
+ }, channel);
746
+ }
747
+ applyMute(muted) {
748
+ for (const track of this.stream?.getAudioTracks() ?? []) track.enabled = !muted;
749
+ }
750
+ attachOutputAnalyser(remote) {
751
+ const AudioContextCtor = window.AudioContext ?? window.webkitAudioContext;
752
+ if (!AudioContextCtor) return null;
753
+ const context = this.audioContext ?? new AudioContextCtor();
754
+ this.audioContext = context;
755
+ this.outputSource?.disconnect();
756
+ const analyser = context.createAnalyser();
757
+ analyser.fftSize = 512;
758
+ analyser.smoothingTimeConstant = .4;
759
+ this.outputSource = context.createMediaStreamSource(remote);
760
+ this.outputSource.connect(analyser);
761
+ context.resume();
762
+ return analyser;
763
+ }
764
+ };
765
+ function started(sessionId) {
766
+ return {
767
+ data: { sessionId },
768
+ error: null,
769
+ count: null,
770
+ status: 200
771
+ };
772
+ }
773
+ function voiceUnavailable() {
774
+ return typeof window === "undefined" || typeof RTCPeerConnection === "undefined" || typeof navigator === "undefined" || navigator.mediaDevices === void 0;
775
+ }
776
+ function stopTracks(stream) {
777
+ for (const track of stream.getTracks()) track.stop();
778
+ }
779
+ function microphoneError(cause) {
780
+ switch (typeof cause === "object" && cause !== null ? Reflect.get(cause, "name") : void 0) {
781
+ case "NotAllowedError":
782
+ case "SecurityError": return window.self !== window.top ? MICROPHONE_IN_FRAME : MICROPHONE_BLOCKED;
783
+ case "NotFoundError":
784
+ case "DevicesNotFoundError": return MICROPHONE_NOT_FOUND;
785
+ case "NotReadableError":
786
+ case "TrackStartError": return MICROPHONE_IN_USE;
787
+ case "OverconstrainedError": return MICROPHONE_UNSUPPORTED;
788
+ case "AbortError": return MICROPHONE_INTERRUPTED;
789
+ default: return MICROPHONE_FAILED;
790
+ }
791
+ }
792
+ function isSubstantialAssistantLine(text) {
793
+ const trimmed = text.trim();
794
+ if (trimmed.includes("?")) return true;
795
+ return trimmed.split(/\s+/).filter(Boolean).length >= SUBSTANTIAL_ASSISTANT_WORDS;
796
+ }
797
+ function toolProgress(message) {
798
+ const started = message?.messageType === "tool_started";
799
+ if (!started && message?.messageType !== "tool_finished") return null;
800
+ const call = message.artifacts?.find((artifact) => artifact.toolCallResult)?.toolCallResult;
801
+ if (!call?.toolName || !started && call.success) return null;
802
+ const label = call.displayName?.trim() || call.toolName.replace(/_/g, " ");
803
+ return `Backend step ${started ? "started" : "failed"}: ${label}`;
804
+ }
805
+ function within(work, ms) {
806
+ return new Promise((resolve) => {
807
+ const timer = setTimeout(resolve, ms);
808
+ const finish = () => {
809
+ clearTimeout(timer);
810
+ resolve();
811
+ };
812
+ work.then(finish, finish);
813
+ });
814
+ }
815
+ function waitForIceGathering(connection) {
816
+ if (connection.iceGatheringState === "complete") return Promise.resolve();
817
+ return new Promise((resolve) => {
818
+ const finish = () => {
819
+ clearTimeout(timer);
820
+ connection.removeEventListener("icegatheringstatechange", onStateChange);
821
+ resolve();
822
+ };
823
+ const onStateChange = () => {
824
+ if (connection.iceGatheringState === "complete") finish();
825
+ };
826
+ const timer = setTimeout(finish, ICE_GATHERING_TIMEOUT_MS);
827
+ connection.addEventListener("icegatheringstatechange", onStateChange);
828
+ });
829
+ }
830
+
831
+ // src/app/chat.ts
832
+ var OaizChatSessions = class {
833
+ constructor(client, app) {
834
+ this.client = client;
835
+ this.app = app;
836
+ }
837
+ async list(params) {
838
+ try {
839
+ return {
840
+ data: await this.client.listAppChatSessions(this.app, params),
841
+ error: null,
842
+ count: null,
843
+ status: 200
844
+ };
845
+ } catch (error) {
846
+ return failureFrom(error);
847
+ }
848
+ }
849
+ async get(sessionId) {
850
+ try {
851
+ return {
852
+ data: await this.client.getAppChatSession(this.app, sessionId),
853
+ error: null,
854
+ count: null,
855
+ status: 200
856
+ };
857
+ } catch (error) {
858
+ return failureFrom(error);
859
+ }
860
+ }
861
+ };
862
+ var OaizChat = class {
863
+ constructor(client, open, app, auth, url) {
864
+ this.client = client;
865
+ this.open = open;
866
+ this.app = app;
867
+ this.auth = auth;
868
+ this.url = url;
869
+ this.sessions = new OaizChatSessions(client, app);
870
+ }
871
+ send(message, options) {
872
+ const body = {
873
+ ...message,
874
+ clientMessageId: message.clientMessageId ?? crypto.randomUUID()
875
+ };
876
+ return this.stream({
877
+ operation: "createAppChatMessage",
878
+ params: { appUuid: this.app }
879
+ }, body, options?.signal);
880
+ }
881
+ approve(decision, options) {
882
+ return this.decide(decision, true, options);
883
+ }
884
+ decline(decision, options) {
885
+ return this.decide(decision, false, options);
886
+ }
887
+ voice(options) {
888
+ return new OaizVoice(this.client, this.open, this.app, this.auth, this.url, options);
889
+ }
890
+ async tools() {
891
+ try {
892
+ const [natives, list] = await Promise.all([this.client.getNativeTools({ surface: "app" }), this.client.listTools()]);
893
+ const integrationTools = list.items.filter((item) => item.kind === "integration");
894
+ return {
895
+ data: {
896
+ nativeTools: natives.items,
897
+ integrationTools
898
+ },
899
+ error: null,
900
+ count: null,
901
+ status: 200
902
+ };
903
+ } catch (error) {
904
+ return failureFrom(error);
905
+ }
906
+ }
907
+ decide(decision, approved, options) {
908
+ const { sessionId, toolCallId, ...settings } = decision;
909
+ const body = {
910
+ ...settings,
911
+ approved
912
+ };
913
+ const raw = {
914
+ operation: "createAppChatApproval",
915
+ params: {
916
+ appUuid: this.app,
917
+ sessionId,
918
+ toolCallId
919
+ }
920
+ };
921
+ return this.stream(raw, body, options?.signal);
922
+ }
923
+ async *stream(request, body, signal) {
924
+ const frames = readSseStream(this.open, request, body, signal, "chat_event", (event) => event.type === "generation.finished");
925
+ for await (const frame of frames) yield frame.error === null ? {
926
+ ...frame,
927
+ data: frame.data.data
928
+ } : frame;
929
+ }
930
+ };
931
+
932
+ // src/apis/api_action.ts
933
+ const listActionExecutionLogs = async function(params, options) {
934
+ let path = `/ingest/action/log`;
935
+ const selectedAuth = this._selectAuthAlternative("listActionExecutionLogs", [[{
936
+ schemeId: "BearerAuth",
937
+ kind: "bearer"
938
+ }], [{
939
+ schemeId: "ApiKeyAuth",
940
+ kind: "apiKey",
941
+ name: "authorization"
942
+ }]]);
943
+ const searchParams = new URLSearchParams();
944
+ if (params?.cursor !== void 0) for (const [wireName, wireValue] of wireParameterPairs$2("cursor", params.cursor, "form", true)) searchParams.append(wireName, wireValue);
945
+ if (params?.endTime !== void 0) for (const [wireName, wireValue] of wireParameterPairs$2("endTime", params.endTime, "form", true)) searchParams.append(wireName, wireValue);
946
+ if (params?.excludeTestRuns !== void 0) for (const [wireName, wireValue] of wireParameterPairs$2("excludeTestRuns", params.excludeTestRuns, "form", true)) searchParams.append(wireName, wireValue);
947
+ if (params?.includeRunSummaries !== void 0) for (const [wireName, wireValue] of wireParameterPairs$2("includeRunSummaries", params.includeRunSummaries, "form", true)) searchParams.append(wireName, wireValue);
948
+ if (params?.jobUuid !== void 0) for (const [wireName, wireValue] of wireParameterPairs$2("jobUuid", params.jobUuid, "form", true)) searchParams.append(wireName, wireValue);
949
+ if (params?.pageSize !== void 0) for (const [wireName, wireValue] of wireParameterPairs$2("pageSize", params.pageSize, "form", true)) searchParams.append(wireName, wireValue);
950
+ if (params?.startTime !== void 0) for (const [wireName, wireValue] of wireParameterPairs$2("startTime", params.startTime, "form", true)) searchParams.append(wireName, wireValue);
951
+ if (params?.statuses !== void 0) for (const [wireName, wireValue] of wireParameterPairs$2("statuses", params.statuses, "form", false)) searchParams.append(wireName, wireValue);
952
+ if (params?.testRunUuid !== void 0) for (const [wireName, wireValue] of wireParameterPairs$2("testRunUuid", params.testRunUuid, "form", true)) searchParams.append(wireName, wireValue);
953
+ if (params?.triggeringEventUuid !== void 0) for (const [wireName, wireValue] of wireParameterPairs$2("triggeringEventUuid", params.triggeringEventUuid, "form", true)) searchParams.append(wireName, wireValue);
954
+ if (params?.updatedAfter !== void 0) for (const [wireName, wireValue] of wireParameterPairs$2("updatedAfter", params.updatedAfter, "form", true)) searchParams.append(wireName, wireValue);
955
+ if (params?.workflowUuid !== void 0) for (const [wireName, wireValue] of wireParameterPairs$2("workflowUuid", params.workflowUuid, "form", true)) searchParams.append(wireName, wireValue);
956
+ if (params?.workflowVersionId !== void 0) for (const [wireName, wireValue] of wireParameterPairs$2("workflowVersionId", params.workflowVersionId, "form", true)) searchParams.append(wireName, wireValue);
957
+ const qs = wireQueryString$2(searchParams);
958
+ if (qs) path = path + "?" + qs;
959
+ const headers = {};
960
+ if (selectedAuth.has("ApiKeyAuth")) {
961
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
962
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
963
+ }
964
+ if (selectedAuth.has("BearerAuth")) {
965
+ const bearerAuth = this._bearerAuth();
966
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
967
+ }
968
+ const res = await this._request("GET", path, headers, void 0, {
969
+ operationId: "listActionExecutionLogs",
970
+ pathTemplate: "/ingest/action/log",
971
+ idempotent: false,
972
+ idempotencyKeyHeader: "Idempotency-Key",
973
+ successStatuses: [200]
974
+ }, options);
975
+ if (res.status < 200 || res.status >= 300) {
976
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
977
+ let errorBody = jsonBody;
978
+ if (res.status === 400) errorBody = jsonBody;
979
+ if (res.status === 401) errorBody = jsonBody;
980
+ if (res.status === 402) errorBody = jsonBody;
981
+ if (res.status === 403) errorBody = jsonBody;
982
+ if (res.status === 404) errorBody = jsonBody;
983
+ if (res.status === 409) errorBody = jsonBody;
984
+ if (res.status === 413) errorBody = jsonBody;
985
+ if (res.status === 429) errorBody = jsonBody;
986
+ if (res.status === 500) errorBody = jsonBody;
987
+ if (res.status === 503) errorBody = jsonBody;
988
+ throw new ApiError(res.status, {
989
+ headers: res.headers,
990
+ requestId: res.headers.get("x-request-id") ?? void 0,
991
+ rawBody,
992
+ jsonBody,
993
+ body: errorBody
994
+ });
995
+ }
996
+ if (res.status === 200) return await this._decodeJson(res);
997
+ throw new ApiError(res.status);
998
+ };
999
+ const listActionExecutionLogsPages = async function* (params, options) {
1000
+ const pageParams = { ...params };
1001
+ while (true) {
1002
+ const page = await this.listActionExecutionLogs(pageParams, options);
1003
+ yield page;
1004
+ const nextCursor = page.nextCursor;
1005
+ if (nextCursor === void 0 || nextCursor === null || nextCursor === "") break;
1006
+ pageParams.cursor = nextCursor;
1007
+ }
1008
+ };
1009
+ const iterateListActionExecutionLogs = async function* (params, options) {
1010
+ for await (const page of this.listActionExecutionLogsPages(params, options)) for (const item of page.items ?? []) yield item;
1011
+ };
1012
+ const getActionExecutionLogByUuid = async function(uuid, options) {
1013
+ let path = `/ingest/action/log/${wireEscape$4(String(uuid))}`;
1014
+ const selectedAuth = this._selectAuthAlternative("getActionExecutionLogByUUID", [[{
1015
+ schemeId: "BearerAuth",
1016
+ kind: "bearer"
1017
+ }], [{
1018
+ schemeId: "ApiKeyAuth",
1019
+ kind: "apiKey",
1020
+ name: "authorization"
1021
+ }]]);
1022
+ const headers = {};
1023
+ if (selectedAuth.has("ApiKeyAuth")) {
1024
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
1025
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
1026
+ }
1027
+ if (selectedAuth.has("BearerAuth")) {
1028
+ const bearerAuth = this._bearerAuth();
1029
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
1030
+ }
1031
+ const res = await this._request("GET", path, headers, void 0, {
1032
+ operationId: "getActionExecutionLogByUUID",
1033
+ pathTemplate: "/ingest/action/log/{uuid}",
1034
+ idempotent: false,
1035
+ idempotencyKeyHeader: "Idempotency-Key",
1036
+ successStatuses: [200]
1037
+ }, options);
1038
+ if (res.status < 200 || res.status >= 300) {
1039
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
1040
+ let errorBody = jsonBody;
1041
+ if (res.status === 400) errorBody = jsonBody;
1042
+ if (res.status === 401) errorBody = jsonBody;
1043
+ if (res.status === 402) errorBody = jsonBody;
1044
+ if (res.status === 403) errorBody = jsonBody;
1045
+ if (res.status === 404) errorBody = jsonBody;
1046
+ if (res.status === 409) errorBody = jsonBody;
1047
+ if (res.status === 413) errorBody = jsonBody;
1048
+ if (res.status === 429) errorBody = jsonBody;
1049
+ if (res.status === 500) errorBody = jsonBody;
1050
+ if (res.status === 503) errorBody = jsonBody;
1051
+ throw new ApiError(res.status, {
1052
+ headers: res.headers,
1053
+ requestId: res.headers.get("x-request-id") ?? void 0,
1054
+ rawBody,
1055
+ jsonBody,
1056
+ body: errorBody
1057
+ });
1058
+ }
1059
+ if (res.status === 200) return await this._decodeJson(res);
1060
+ throw new ApiError(res.status);
1061
+ };
1062
+ const streamActionExecutionEvents = async function(uuid, params, options) {
1063
+ let path = `/ingest/action/log/${wireEscape$4(String(uuid))}/events`;
1064
+ const selectedAuth = this._selectAuthAlternative("streamActionExecutionEvents", [[{
1065
+ schemeId: "BearerAuth",
1066
+ kind: "bearer"
1067
+ }], [{
1068
+ schemeId: "ApiKeyAuth",
1069
+ kind: "apiKey",
1070
+ name: "authorization"
1071
+ }]]);
1072
+ const searchParams = new URLSearchParams();
1073
+ if (params?.after !== void 0) for (const [wireName, wireValue] of wireParameterPairs$2("after", params.after, "form", true)) searchParams.append(wireName, wireValue);
1074
+ if (params?.publishEvents !== void 0) for (const [wireName, wireValue] of wireParameterPairs$2("publishEvents", params.publishEvents, "form", true)) searchParams.append(wireName, wireValue);
1075
+ const qs = wireQueryString$2(searchParams);
1076
+ if (qs) path = path + "?" + qs;
1077
+ const headers = {};
1078
+ if (params?.lastEventId !== void 0) headers["Last-Event-ID"] = String(params.lastEventId);
1079
+ if (selectedAuth.has("ApiKeyAuth")) {
1080
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
1081
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
1082
+ }
1083
+ if (selectedAuth.has("BearerAuth")) {
1084
+ const bearerAuth = this._bearerAuth();
1085
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
1086
+ }
1087
+ const res = await this._request("GET", path, headers, void 0, {
1088
+ operationId: "streamActionExecutionEvents",
1089
+ pathTemplate: "/ingest/action/log/{uuid}/events",
1090
+ idempotent: false,
1091
+ idempotencyKeyHeader: "Idempotency-Key",
1092
+ successStatuses: [200]
1093
+ }, options);
1094
+ if (res.status < 200 || res.status >= 300) {
1095
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
1096
+ let errorBody = jsonBody;
1097
+ if (res.status === 400) errorBody = jsonBody;
1098
+ if (res.status === 401) errorBody = jsonBody;
1099
+ if (res.status === 402) errorBody = jsonBody;
1100
+ if (res.status === 403) errorBody = jsonBody;
1101
+ if (res.status === 404) errorBody = jsonBody;
1102
+ if (res.status === 409) errorBody = jsonBody;
1103
+ if (res.status === 413) errorBody = jsonBody;
1104
+ if (res.status === 429) errorBody = jsonBody;
1105
+ if (res.status === 500) errorBody = jsonBody;
1106
+ if (res.status === 503) errorBody = jsonBody;
1107
+ throw new ApiError(res.status, {
1108
+ headers: res.headers,
1109
+ requestId: res.headers.get("x-request-id") ?? void 0,
1110
+ rawBody,
1111
+ jsonBody,
1112
+ body: errorBody
1113
+ });
1114
+ }
1115
+ if (res.status === 200) return await res.blob();
1116
+ throw new ApiError(res.status);
1117
+ };
1118
+ function wireParameterPairs$2(name, value, style, explode) {
1119
+ const delimiter = style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : ",";
1120
+ if (Array.isArray(value)) {
1121
+ const parts = value.map((item) => String(item));
1122
+ return explode && style === "form" ? parts.map((item) => [name, item]) : [[name, parts.join(delimiter)]];
1123
+ }
1124
+ if (value !== null && typeof value === "object") {
1125
+ const entries = Object.entries(value).sort(([a], [b]) => a.localeCompare(b));
1126
+ if (style === "deepObject") return entries.map(([key, item]) => [name + "[" + key + "]", String(item)]);
1127
+ if (explode && style === "form") return entries.map(([key, item]) => [key, String(item)]);
1128
+ return [[name, entries.flatMap(([key, item]) => explode ? [key + "=" + String(item)] : [key, String(item)]).join(delimiter)]];
1129
+ }
1130
+ return [[name, String(value)]];
1131
+ }
1132
+ function wireQueryString$2(values, allowReserved = /* @__PURE__ */ new Set()) {
1133
+ const restoreReserved = (value) => value.replace(/%3A|%2F|%3F|%23|%5B|%5D|%40|%21|%24|%26|%27|%28|%29|%2A|%2B|%2C|%3B|%3D/gi, (token) => decodeURIComponent(token));
1134
+ const parts = [];
1135
+ let index = 0;
1136
+ values.forEach((value, key) => {
1137
+ const encoded = wireEscape$4(value);
1138
+ parts.push(wireEscape$4(key) + "=" + (allowReserved.has(index) ? restoreReserved(encoded) : encoded));
1139
+ index += 1;
1140
+ });
1141
+ return parts.join("&");
1142
+ }
1143
+ function wireEscape$4(value) {
1144
+ return encodeURIComponent(value).replace(/[!'()*]/g, (char) => "%" + char.charCodeAt(0).toString(16).toUpperCase());
1145
+ }
1146
+
1147
+ // src/apis/api_app_chat.ts
1148
+ const createAppChatMessage = async function(appUuid, body, options) {
1149
+ let path = `/internalagents/chat/apps/${wireEscape$3(String(appUuid))}/messages`;
1150
+ const selectedAuth = this._selectAuthAlternative("createAppChatMessage", [[{
1151
+ schemeId: "BearerAuth",
1152
+ kind: "bearer"
1153
+ }], [{
1154
+ schemeId: "ApiKeyAuth",
1155
+ kind: "apiKey",
1156
+ name: "authorization"
1157
+ }]]);
1158
+ const headers = {};
1159
+ if (selectedAuth.has("ApiKeyAuth")) {
1160
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
1161
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
1162
+ }
1163
+ if (selectedAuth.has("BearerAuth")) {
1164
+ const bearerAuth = this._bearerAuth();
1165
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
1166
+ }
1167
+ headers["Content-Type"] = "application/json";
1168
+ const requestBody = JSON.stringify(body);
1169
+ const res = await this._request("POST", path, headers, requestBody, {
1170
+ operationId: "createAppChatMessage",
1171
+ pathTemplate: "/internalagents/chat/apps/{appUuid}/messages",
1172
+ idempotent: false,
1173
+ idempotencyKeyHeader: "Idempotency-Key",
1174
+ successStatuses: [200]
1175
+ }, options);
1176
+ if (res.status < 200 || res.status >= 300) {
1177
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
1178
+ let errorBody = jsonBody;
1179
+ if (res.status === 400) errorBody = jsonBody;
1180
+ if (res.status === 401) errorBody = jsonBody;
1181
+ if (res.status === 402) errorBody = jsonBody;
1182
+ if (res.status === 403) errorBody = jsonBody;
1183
+ if (res.status === 404) errorBody = jsonBody;
1184
+ if (res.status === 409) errorBody = jsonBody;
1185
+ if (res.status === 413) errorBody = jsonBody;
1186
+ if (res.status === 429) errorBody = jsonBody;
1187
+ if (res.status === 500) errorBody = jsonBody;
1188
+ if (res.status === 503) errorBody = jsonBody;
1189
+ throw new ApiError(res.status, {
1190
+ headers: res.headers,
1191
+ requestId: res.headers.get("x-request-id") ?? void 0,
1192
+ rawBody,
1193
+ jsonBody,
1194
+ body: errorBody
1195
+ });
1196
+ }
1197
+ if (res.status === 200) return await res.blob();
1198
+ throw new ApiError(res.status);
1199
+ };
1200
+ const listAppChatSessions = async function(appUuid, params, options) {
1201
+ let path = `/internalagents/chat/apps/${wireEscape$3(String(appUuid))}/sessions`;
1202
+ const selectedAuth = this._selectAuthAlternative("listAppChatSessions", [[{
1203
+ schemeId: "BearerAuth",
1204
+ kind: "bearer"
1205
+ }], [{
1206
+ schemeId: "ApiKeyAuth",
1207
+ kind: "apiKey",
1208
+ name: "authorization"
1209
+ }]]);
1210
+ const searchParams = new URLSearchParams();
1211
+ if (params?.cursor !== void 0) for (const [wireName, wireValue] of wireParameterPairs$1("cursor", params.cursor, "form", true)) searchParams.append(wireName, wireValue);
1212
+ if (params?.pageSize !== void 0) for (const [wireName, wireValue] of wireParameterPairs$1("pageSize", params.pageSize, "form", true)) searchParams.append(wireName, wireValue);
1213
+ const qs = wireQueryString$1(searchParams);
1214
+ if (qs) path = path + "?" + qs;
1215
+ const headers = {};
1216
+ if (selectedAuth.has("ApiKeyAuth")) {
1217
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
1218
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
1219
+ }
1220
+ if (selectedAuth.has("BearerAuth")) {
1221
+ const bearerAuth = this._bearerAuth();
1222
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
1223
+ }
1224
+ const res = await this._request("GET", path, headers, void 0, {
1225
+ operationId: "listAppChatSessions",
1226
+ pathTemplate: "/internalagents/chat/apps/{appUuid}/sessions",
1227
+ idempotent: false,
1228
+ idempotencyKeyHeader: "Idempotency-Key",
1229
+ successStatuses: [200]
1230
+ }, options);
1231
+ if (res.status < 200 || res.status >= 300) {
1232
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
1233
+ let errorBody = jsonBody;
1234
+ if (res.status === 400) errorBody = jsonBody;
1235
+ if (res.status === 401) errorBody = jsonBody;
1236
+ if (res.status === 402) errorBody = jsonBody;
1237
+ if (res.status === 403) errorBody = jsonBody;
1238
+ if (res.status === 404) errorBody = jsonBody;
1239
+ if (res.status === 409) errorBody = jsonBody;
1240
+ if (res.status === 413) errorBody = jsonBody;
1241
+ if (res.status === 429) errorBody = jsonBody;
1242
+ if (res.status === 500) errorBody = jsonBody;
1243
+ if (res.status === 503) errorBody = jsonBody;
1244
+ throw new ApiError(res.status, {
1245
+ headers: res.headers,
1246
+ requestId: res.headers.get("x-request-id") ?? void 0,
1247
+ rawBody,
1248
+ jsonBody,
1249
+ body: errorBody
1250
+ });
1251
+ }
1252
+ if (res.status === 200) return await this._decodeJson(res);
1253
+ throw new ApiError(res.status);
1254
+ };
1255
+ const getAppChatSession = async function(appUuid, sessionId, options) {
1256
+ let path = `/internalagents/chat/apps/${wireEscape$3(String(appUuid))}/sessions/${wireEscape$3(String(sessionId))}`;
1257
+ const selectedAuth = this._selectAuthAlternative("getAppChatSession", [[{
1258
+ schemeId: "BearerAuth",
1259
+ kind: "bearer"
1260
+ }], [{
1261
+ schemeId: "ApiKeyAuth",
1262
+ kind: "apiKey",
1263
+ name: "authorization"
1264
+ }]]);
1265
+ const headers = {};
1266
+ if (selectedAuth.has("ApiKeyAuth")) {
1267
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
1268
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
1269
+ }
1270
+ if (selectedAuth.has("BearerAuth")) {
1271
+ const bearerAuth = this._bearerAuth();
1272
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
1273
+ }
1274
+ const res = await this._request("GET", path, headers, void 0, {
1275
+ operationId: "getAppChatSession",
1276
+ pathTemplate: "/internalagents/chat/apps/{appUuid}/sessions/{sessionId}",
1277
+ idempotent: false,
1278
+ idempotencyKeyHeader: "Idempotency-Key",
1279
+ successStatuses: [200]
1280
+ }, options);
1281
+ if (res.status < 200 || res.status >= 300) {
1282
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
1283
+ let errorBody = jsonBody;
1284
+ if (res.status === 400) errorBody = jsonBody;
1285
+ if (res.status === 401) errorBody = jsonBody;
1286
+ if (res.status === 402) errorBody = jsonBody;
1287
+ if (res.status === 403) errorBody = jsonBody;
1288
+ if (res.status === 404) errorBody = jsonBody;
1289
+ if (res.status === 409) errorBody = jsonBody;
1290
+ if (res.status === 413) errorBody = jsonBody;
1291
+ if (res.status === 429) errorBody = jsonBody;
1292
+ if (res.status === 500) errorBody = jsonBody;
1293
+ if (res.status === 503) errorBody = jsonBody;
1294
+ throw new ApiError(res.status, {
1295
+ headers: res.headers,
1296
+ requestId: res.headers.get("x-request-id") ?? void 0,
1297
+ rawBody,
1298
+ jsonBody,
1299
+ body: errorBody
1300
+ });
1301
+ }
1302
+ if (res.status === 200) return await this._decodeJson(res);
1303
+ throw new ApiError(res.status);
1304
+ };
1305
+ const createAppChatApproval = async function(appUuid, sessionId, toolCallId, body, options) {
1306
+ let path = `/internalagents/chat/apps/${wireEscape$3(String(appUuid))}/sessions/${wireEscape$3(String(sessionId))}/approvals/${wireEscape$3(String(toolCallId))}`;
1307
+ const selectedAuth = this._selectAuthAlternative("createAppChatApproval", [[{
1308
+ schemeId: "BearerAuth",
1309
+ kind: "bearer"
1310
+ }], [{
1311
+ schemeId: "ApiKeyAuth",
1312
+ kind: "apiKey",
1313
+ name: "authorization"
1314
+ }]]);
1315
+ const headers = {};
1316
+ if (selectedAuth.has("ApiKeyAuth")) {
1317
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
1318
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
1319
+ }
1320
+ if (selectedAuth.has("BearerAuth")) {
1321
+ const bearerAuth = this._bearerAuth();
1322
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
1323
+ }
1324
+ headers["Content-Type"] = "application/json";
1325
+ const requestBody = JSON.stringify(body);
1326
+ const res = await this._request("POST", path, headers, requestBody, {
1327
+ operationId: "createAppChatApproval",
1328
+ pathTemplate: "/internalagents/chat/apps/{appUuid}/sessions/{sessionId}/approvals/{toolCallId}",
1329
+ idempotent: false,
1330
+ idempotencyKeyHeader: "Idempotency-Key",
1331
+ successStatuses: [200]
1332
+ }, options);
1333
+ if (res.status < 200 || res.status >= 300) {
1334
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
1335
+ let errorBody = jsonBody;
1336
+ if (res.status === 400) errorBody = jsonBody;
1337
+ if (res.status === 401) errorBody = jsonBody;
1338
+ if (res.status === 402) errorBody = jsonBody;
1339
+ if (res.status === 403) errorBody = jsonBody;
1340
+ if (res.status === 404) errorBody = jsonBody;
1341
+ if (res.status === 409) errorBody = jsonBody;
1342
+ if (res.status === 413) errorBody = jsonBody;
1343
+ if (res.status === 429) errorBody = jsonBody;
1344
+ if (res.status === 500) errorBody = jsonBody;
1345
+ if (res.status === 503) errorBody = jsonBody;
1346
+ throw new ApiError(res.status, {
1347
+ headers: res.headers,
1348
+ requestId: res.headers.get("x-request-id") ?? void 0,
1349
+ rawBody,
1350
+ jsonBody,
1351
+ body: errorBody
1352
+ });
1353
+ }
1354
+ if (res.status === 200) return await res.blob();
1355
+ throw new ApiError(res.status);
1356
+ };
1357
+ const createAppVoiceLine = async function(appUuid, sessionId, body, options) {
1358
+ let path = `/internalagents/chat/apps/${wireEscape$3(String(appUuid))}/sessions/${wireEscape$3(String(sessionId))}/voice-lines`;
1359
+ const selectedAuth = this._selectAuthAlternative("createAppVoiceLine", [[{
1360
+ schemeId: "BearerAuth",
1361
+ kind: "bearer"
1362
+ }], [{
1363
+ schemeId: "ApiKeyAuth",
1364
+ kind: "apiKey",
1365
+ name: "authorization"
1366
+ }]]);
1367
+ const headers = {};
1368
+ if (selectedAuth.has("ApiKeyAuth")) {
1369
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
1370
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
1371
+ }
1372
+ if (selectedAuth.has("BearerAuth")) {
1373
+ const bearerAuth = this._bearerAuth();
1374
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
1375
+ }
1376
+ headers["Content-Type"] = "application/json";
1377
+ const requestBody = JSON.stringify(body);
1378
+ const res = await this._request("POST", path, headers, requestBody, {
1379
+ operationId: "createAppVoiceLine",
1380
+ pathTemplate: "/internalagents/chat/apps/{appUuid}/sessions/{sessionId}/voice-lines",
1381
+ idempotent: false,
1382
+ idempotencyKeyHeader: "Idempotency-Key",
1383
+ successStatuses: [204]
1384
+ }, options);
1385
+ if (res.status < 200 || res.status >= 300) {
1386
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
1387
+ let errorBody = jsonBody;
1388
+ if (res.status === 400) errorBody = jsonBody;
1389
+ if (res.status === 401) errorBody = jsonBody;
1390
+ if (res.status === 402) errorBody = jsonBody;
1391
+ if (res.status === 403) errorBody = jsonBody;
1392
+ if (res.status === 404) errorBody = jsonBody;
1393
+ if (res.status === 409) errorBody = jsonBody;
1394
+ if (res.status === 413) errorBody = jsonBody;
1395
+ if (res.status === 429) errorBody = jsonBody;
1396
+ if (res.status === 500) errorBody = jsonBody;
1397
+ if (res.status === 503) errorBody = jsonBody;
1398
+ throw new ApiError(res.status, {
1399
+ headers: res.headers,
1400
+ requestId: res.headers.get("x-request-id") ?? void 0,
1401
+ rawBody,
1402
+ jsonBody,
1403
+ body: errorBody
1404
+ });
1405
+ }
1406
+ };
1407
+ const createAppLiveVoiceSession = async function(appUuid, body, options) {
1408
+ let path = `/internalagents/chat/apps/${wireEscape$3(String(appUuid))}/voice/sessions`;
1409
+ const selectedAuth = this._selectAuthAlternative("createAppLiveVoiceSession", [[{
1410
+ schemeId: "BearerAuth",
1411
+ kind: "bearer"
1412
+ }], [{
1413
+ schemeId: "ApiKeyAuth",
1414
+ kind: "apiKey",
1415
+ name: "authorization"
1416
+ }]]);
1417
+ const headers = {};
1418
+ if (selectedAuth.has("ApiKeyAuth")) {
1419
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
1420
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
1421
+ }
1422
+ if (selectedAuth.has("BearerAuth")) {
1423
+ const bearerAuth = this._bearerAuth();
1424
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
1425
+ }
1426
+ headers["Content-Type"] = "application/json";
1427
+ const requestBody = JSON.stringify(body);
1428
+ const res = await this._request("POST", path, headers, requestBody, {
1429
+ operationId: "createAppLiveVoiceSession",
1430
+ pathTemplate: "/internalagents/chat/apps/{appUuid}/voice/sessions",
1431
+ idempotent: false,
1432
+ idempotencyKeyHeader: "Idempotency-Key",
1433
+ successStatuses: [201]
1434
+ }, options);
1435
+ if (res.status < 200 || res.status >= 300) {
1436
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
1437
+ let errorBody = jsonBody;
1438
+ if (res.status === 400) errorBody = jsonBody;
1439
+ if (res.status === 401) errorBody = jsonBody;
1440
+ if (res.status === 402) errorBody = jsonBody;
1441
+ if (res.status === 403) errorBody = jsonBody;
1442
+ if (res.status === 404) errorBody = jsonBody;
1443
+ if (res.status === 409) errorBody = jsonBody;
1444
+ if (res.status === 413) errorBody = jsonBody;
1445
+ if (res.status === 429) errorBody = jsonBody;
1446
+ if (res.status === 500) errorBody = jsonBody;
1447
+ if (res.status === 503) errorBody = jsonBody;
1448
+ throw new ApiError(res.status, {
1449
+ headers: res.headers,
1450
+ requestId: res.headers.get("x-request-id") ?? void 0,
1451
+ rawBody,
1452
+ jsonBody,
1453
+ body: errorBody
1454
+ });
1455
+ }
1456
+ if (res.status === 201) return await this._decodeJson(res);
1457
+ throw new ApiError(res.status);
1458
+ };
1459
+ const deleteAppLiveVoiceSession = async function(appUuid, id, options) {
1460
+ let path = `/internalagents/chat/apps/${wireEscape$3(String(appUuid))}/voice/sessions/${wireEscape$3(String(id))}`;
1461
+ const selectedAuth = this._selectAuthAlternative("deleteAppLiveVoiceSession", [[{
1462
+ schemeId: "BearerAuth",
1463
+ kind: "bearer"
1464
+ }], [{
1465
+ schemeId: "ApiKeyAuth",
1466
+ kind: "apiKey",
1467
+ name: "authorization"
1468
+ }]]);
1469
+ const headers = {};
1470
+ if (selectedAuth.has("ApiKeyAuth")) {
1471
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
1472
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
1473
+ }
1474
+ if (selectedAuth.has("BearerAuth")) {
1475
+ const bearerAuth = this._bearerAuth();
1476
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
1477
+ }
1478
+ const res = await this._request("DELETE", path, headers, void 0, {
1479
+ operationId: "deleteAppLiveVoiceSession",
1480
+ pathTemplate: "/internalagents/chat/apps/{appUuid}/voice/sessions/{id}",
1481
+ idempotent: false,
1482
+ idempotencyKeyHeader: "Idempotency-Key",
1483
+ successStatuses: [204]
1484
+ }, options);
1485
+ if (res.status < 200 || res.status >= 300) {
1486
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
1487
+ let errorBody = jsonBody;
1488
+ if (res.status === 400) errorBody = jsonBody;
1489
+ if (res.status === 401) errorBody = jsonBody;
1490
+ if (res.status === 402) errorBody = jsonBody;
1491
+ if (res.status === 403) errorBody = jsonBody;
1492
+ if (res.status === 404) errorBody = jsonBody;
1493
+ if (res.status === 409) errorBody = jsonBody;
1494
+ if (res.status === 413) errorBody = jsonBody;
1495
+ if (res.status === 429) errorBody = jsonBody;
1496
+ if (res.status === 500) errorBody = jsonBody;
1497
+ if (res.status === 503) errorBody = jsonBody;
1498
+ throw new ApiError(res.status, {
1499
+ headers: res.headers,
1500
+ requestId: res.headers.get("x-request-id") ?? void 0,
1501
+ rawBody,
1502
+ jsonBody,
1503
+ body: errorBody
1504
+ });
1505
+ }
1506
+ };
1507
+ function wireParameterPairs$1(name, value, style, explode) {
1508
+ const delimiter = style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : ",";
1509
+ if (Array.isArray(value)) {
1510
+ const parts = value.map((item) => String(item));
1511
+ return explode && style === "form" ? parts.map((item) => [name, item]) : [[name, parts.join(delimiter)]];
1512
+ }
1513
+ if (value !== null && typeof value === "object") {
1514
+ const entries = Object.entries(value).sort(([a], [b]) => a.localeCompare(b));
1515
+ if (style === "deepObject") return entries.map(([key, item]) => [name + "[" + key + "]", String(item)]);
1516
+ if (explode && style === "form") return entries.map(([key, item]) => [key, String(item)]);
1517
+ return [[name, entries.flatMap(([key, item]) => explode ? [key + "=" + String(item)] : [key, String(item)]).join(delimiter)]];
1518
+ }
1519
+ return [[name, String(value)]];
1520
+ }
1521
+ function wireQueryString$1(values, allowReserved = /* @__PURE__ */ new Set()) {
1522
+ const restoreReserved = (value) => value.replace(/%3A|%2F|%3F|%23|%5B|%5D|%40|%21|%24|%26|%27|%28|%29|%2A|%2B|%2C|%3B|%3D/gi, (token) => decodeURIComponent(token));
1523
+ const parts = [];
1524
+ let index = 0;
1525
+ values.forEach((value, key) => {
1526
+ const encoded = wireEscape$3(value);
1527
+ parts.push(wireEscape$3(key) + "=" + (allowReserved.has(index) ? restoreReserved(encoded) : encoded));
1528
+ index += 1;
1529
+ });
1530
+ return parts.join("&");
1531
+ }
1532
+ function wireEscape$3(value) {
1533
+ return encodeURIComponent(value).replace(/[!'()*]/g, (char) => "%" + char.charCodeAt(0).toString(16).toUpperCase());
1534
+ }
1535
+
1536
+ // src/apis/api_event.ts
1537
+ const publishEvent = async function(body, options) {
1538
+ let path = `/ingest/event/publish`;
1539
+ const selectedAuth = this._selectAuthAlternative("publishEvent", [[{
1540
+ schemeId: "BearerAuth",
1541
+ kind: "bearer"
1542
+ }], [{
1543
+ schemeId: "ApiKeyAuth",
1544
+ kind: "apiKey",
1545
+ name: "authorization"
1546
+ }]]);
1547
+ const headers = {};
1548
+ if (selectedAuth.has("ApiKeyAuth")) {
1549
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
1550
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
1551
+ }
1552
+ if (selectedAuth.has("BearerAuth")) {
1553
+ const bearerAuth = this._bearerAuth();
1554
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
1555
+ }
1556
+ if (body.contentType !== "multipart/form-data") headers["Content-Type"] = body.contentType;
1557
+ let requestBody = void 0;
1558
+ switch (body.contentType) {
1559
+ case "application/json":
1560
+ requestBody = JSON.stringify(body.value);
1561
+ break;
1562
+ case "multipart/form-data": requestBody = this._multipartBody(body.value);
1563
+ }
1564
+ const res = await this._request("POST", path, headers, requestBody, {
1565
+ operationId: "publishEvent",
1566
+ pathTemplate: "/ingest/event/publish",
1567
+ idempotent: false,
1568
+ idempotencyKeyHeader: "Idempotency-Key",
1569
+ successStatuses: [201]
1570
+ }, options);
1571
+ if (res.status < 200 || res.status >= 300) {
1572
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
1573
+ let errorBody = jsonBody;
1574
+ if (res.status === 400) errorBody = jsonBody;
1575
+ if (res.status === 401) errorBody = jsonBody;
1576
+ if (res.status === 402) errorBody = jsonBody;
1577
+ if (res.status === 403) errorBody = jsonBody;
1578
+ if (res.status === 404) errorBody = jsonBody;
1579
+ if (res.status === 409) errorBody = jsonBody;
1580
+ if (res.status === 413) errorBody = jsonBody;
1581
+ if (res.status === 429) errorBody = jsonBody;
1582
+ if (res.status === 500) errorBody = jsonBody;
1583
+ if (res.status === 503) errorBody = jsonBody;
1584
+ throw new ApiError(res.status, {
1585
+ headers: res.headers,
1586
+ requestId: res.headers.get("x-request-id") ?? void 0,
1587
+ rawBody,
1588
+ jsonBody,
1589
+ body: errorBody
1590
+ });
1591
+ }
1592
+ if (res.status === 201) return await this._decodeJson(res);
1593
+ throw new ApiError(res.status);
1594
+ };
1595
+
1596
+ // src/apis/api_jobs.ts
1597
+ const executeJobStream = async function(jobUuid, body, options) {
1598
+ let path = `/ingest/jobs/${wireEscape$2(String(jobUuid))}/execute/stream`;
1599
+ const selectedAuth = this._selectAuthAlternative("executeJobStream", [[{
1600
+ schemeId: "BearerAuth",
1601
+ kind: "bearer"
1602
+ }], [{
1603
+ schemeId: "ApiKeyAuth",
1604
+ kind: "apiKey",
1605
+ name: "authorization"
1606
+ }]]);
1607
+ const headers = {};
1608
+ if (selectedAuth.has("ApiKeyAuth")) {
1609
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
1610
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
1611
+ }
1612
+ if (selectedAuth.has("BearerAuth")) {
1613
+ const bearerAuth = this._bearerAuth();
1614
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
1615
+ }
1616
+ headers["Content-Type"] = "application/json";
1617
+ const requestBody = JSON.stringify(body);
1618
+ const res = await this._request("POST", path, headers, requestBody, {
1619
+ operationId: "executeJobStream",
1620
+ pathTemplate: "/ingest/jobs/{jobUuid}/execute/stream",
1621
+ idempotent: false,
1622
+ idempotencyKeyHeader: "Idempotency-Key",
1623
+ successStatuses: [200]
1624
+ }, options);
1625
+ if (res.status < 200 || res.status >= 300) {
1626
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
1627
+ let errorBody = jsonBody;
1628
+ if (res.status === 400) errorBody = jsonBody;
1629
+ if (res.status === 401) errorBody = jsonBody;
1630
+ if (res.status === 402) errorBody = jsonBody;
1631
+ if (res.status === 403) errorBody = jsonBody;
1632
+ if (res.status === 404) errorBody = jsonBody;
1633
+ if (res.status === 409) errorBody = jsonBody;
1634
+ if (res.status === 413) errorBody = jsonBody;
1635
+ if (res.status === 429) errorBody = jsonBody;
1636
+ if (res.status === 500) errorBody = jsonBody;
1637
+ if (res.status === 503) errorBody = jsonBody;
1638
+ throw new ApiError(res.status, {
1639
+ headers: res.headers,
1640
+ requestId: res.headers.get("x-request-id") ?? void 0,
1641
+ rawBody,
1642
+ jsonBody,
1643
+ body: errorBody
1644
+ });
1645
+ }
1646
+ if (res.status === 200) return await res.blob();
1647
+ throw new ApiError(res.status);
1648
+ };
1649
+ function wireEscape$2(value) {
1650
+ return encodeURIComponent(value).replace(/[!'()*]/g, (char) => "%" + char.charCodeAt(0).toString(16).toUpperCase());
1651
+ }
1652
+
1653
+ // src/apis/api_llm.ts
1654
+ const createEmbeddings = async function(body, options) {
1655
+ let path = `/ingest/embeddings`;
1656
+ const selectedAuth = this._selectAuthAlternative("createEmbeddings", [[{
1657
+ schemeId: "BearerAuth",
1658
+ kind: "bearer"
1659
+ }], [{
1660
+ schemeId: "ApiKeyAuth",
1661
+ kind: "apiKey",
1662
+ name: "authorization"
1663
+ }]]);
1664
+ const headers = {};
1665
+ if (selectedAuth.has("ApiKeyAuth")) {
1666
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
1667
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
1668
+ }
1669
+ if (selectedAuth.has("BearerAuth")) {
1670
+ const bearerAuth = this._bearerAuth();
1671
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
1672
+ }
1673
+ headers["Content-Type"] = "application/json";
1674
+ const requestBody = JSON.stringify(body);
1675
+ const res = await this._request("POST", path, headers, requestBody, {
1676
+ operationId: "createEmbeddings",
1677
+ pathTemplate: "/ingest/embeddings",
1678
+ idempotent: false,
1679
+ idempotencyKeyHeader: "Idempotency-Key",
1680
+ successStatuses: [200]
1681
+ }, options);
1682
+ if (res.status < 200 || res.status >= 300) {
1683
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
1684
+ let errorBody = jsonBody;
1685
+ if (res.status === 400) errorBody = jsonBody;
1686
+ if (res.status === 401) errorBody = jsonBody;
1687
+ if (res.status === 402) errorBody = jsonBody;
1688
+ if (res.status === 403) errorBody = jsonBody;
1689
+ if (res.status === 404) errorBody = jsonBody;
1690
+ if (res.status === 409) errorBody = jsonBody;
1691
+ if (res.status === 413) errorBody = jsonBody;
1692
+ if (res.status === 429) errorBody = jsonBody;
1693
+ if (res.status === 500) errorBody = jsonBody;
1694
+ if (res.status === 503) errorBody = jsonBody;
1695
+ throw new ApiError(res.status, {
1696
+ headers: res.headers,
1697
+ requestId: res.headers.get("x-request-id") ?? void 0,
1698
+ rawBody,
1699
+ jsonBody,
1700
+ body: errorBody
1701
+ });
1702
+ }
1703
+ if (res.status === 200) return await this._decodeJson(res);
1704
+ throw new ApiError(res.status);
1705
+ };
1706
+ const createLlmCall = async function(body, options) {
1707
+ let path = `/ingest/llm/call`;
1708
+ const selectedAuth = this._selectAuthAlternative("createLLMCall", [[{
1709
+ schemeId: "BearerAuth",
1710
+ kind: "bearer"
1711
+ }], [{
1712
+ schemeId: "ApiKeyAuth",
1713
+ kind: "apiKey",
1714
+ name: "authorization"
1715
+ }]]);
1716
+ const headers = {};
1717
+ if (selectedAuth.has("ApiKeyAuth")) {
1718
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
1719
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
1720
+ }
1721
+ if (selectedAuth.has("BearerAuth")) {
1722
+ const bearerAuth = this._bearerAuth();
1723
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
1724
+ }
1725
+ headers["Content-Type"] = "application/json";
1726
+ const requestBody = JSON.stringify(body);
1727
+ const res = await this._request("POST", path, headers, requestBody, {
1728
+ operationId: "createLLMCall",
1729
+ pathTemplate: "/ingest/llm/call",
1730
+ idempotent: false,
1731
+ idempotencyKeyHeader: "Idempotency-Key",
1732
+ successStatuses: [200]
1733
+ }, options);
1734
+ if (res.status < 200 || res.status >= 300) {
1735
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
1736
+ let errorBody = jsonBody;
1737
+ if (res.status === 400) errorBody = jsonBody;
1738
+ if (res.status === 401) errorBody = jsonBody;
1739
+ if (res.status === 402) errorBody = jsonBody;
1740
+ if (res.status === 403) errorBody = jsonBody;
1741
+ if (res.status === 404) errorBody = jsonBody;
1742
+ if (res.status === 409) errorBody = jsonBody;
1743
+ if (res.status === 413) errorBody = jsonBody;
1744
+ if (res.status === 429) errorBody = jsonBody;
1745
+ if (res.status === 500) errorBody = jsonBody;
1746
+ if (res.status === 503) errorBody = jsonBody;
1747
+ throw new ApiError(res.status, {
1748
+ headers: res.headers,
1749
+ requestId: res.headers.get("x-request-id") ?? void 0,
1750
+ rawBody,
1751
+ jsonBody,
1752
+ body: errorBody
1753
+ });
1754
+ }
1755
+ if (res.status === 200) return await this._decodeJson(res);
1756
+ throw new ApiError(res.status);
1757
+ };
1758
+
1759
+ // src/apis/api_storage.ts
1760
+ const callStorageDatabaseFunction = async function(id, body, options) {
1761
+ let path = `/storage/databases/${wireEscape$1(String(id))}/functions/call`;
1762
+ const selectedAuth = this._selectAuthAlternative("callStorageDatabaseFunction", [[{
1763
+ schemeId: "BearerAuth",
1764
+ kind: "bearer"
1765
+ }], [{
1766
+ schemeId: "ApiKeyAuth",
1767
+ kind: "apiKey",
1768
+ name: "authorization"
1769
+ }]]);
1770
+ const headers = {};
1771
+ if (selectedAuth.has("ApiKeyAuth")) {
1772
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
1773
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
1774
+ }
1775
+ if (selectedAuth.has("BearerAuth")) {
1776
+ const bearerAuth = this._bearerAuth();
1777
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
1778
+ }
1779
+ headers["Content-Type"] = "application/json";
1780
+ const requestBody = JSON.stringify(body);
1781
+ const res = await this._request("POST", path, headers, requestBody, {
1782
+ operationId: "callStorageDatabaseFunction",
1783
+ pathTemplate: "/storage/databases/{id}/functions/call",
1784
+ idempotent: false,
1785
+ idempotencyKeyHeader: "Idempotency-Key",
1786
+ successStatuses: [200]
1787
+ }, options);
1788
+ if (res.status < 200 || res.status >= 300) {
1789
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
1790
+ let errorBody = jsonBody;
1791
+ if (res.status === 400) errorBody = jsonBody;
1792
+ if (res.status === 401) errorBody = jsonBody;
1793
+ if (res.status === 402) errorBody = jsonBody;
1794
+ if (res.status === 403) errorBody = jsonBody;
1795
+ if (res.status === 404) errorBody = jsonBody;
1796
+ if (res.status === 409) errorBody = jsonBody;
1797
+ if (res.status === 413) errorBody = jsonBody;
1798
+ if (res.status === 429) errorBody = jsonBody;
1799
+ if (res.status === 500) errorBody = jsonBody;
1800
+ if (res.status === 503) errorBody = jsonBody;
1801
+ throw new ApiError(res.status, {
1802
+ headers: res.headers,
1803
+ requestId: res.headers.get("x-request-id") ?? void 0,
1804
+ rawBody,
1805
+ jsonBody,
1806
+ body: errorBody
1807
+ });
1808
+ }
1809
+ if (res.status === 200) return await this._decodeJson(res);
1810
+ throw new ApiError(res.status);
1811
+ };
1812
+ const deleteStorageDatabaseRows = async function(id, body, options) {
1813
+ let path = `/storage/databases/${wireEscape$1(String(id))}/rows/delete`;
1814
+ const selectedAuth = this._selectAuthAlternative("deleteStorageDatabaseRows", [[{
1815
+ schemeId: "BearerAuth",
1816
+ kind: "bearer"
1817
+ }], [{
1818
+ schemeId: "ApiKeyAuth",
1819
+ kind: "apiKey",
1820
+ name: "authorization"
1821
+ }]]);
1822
+ const headers = {};
1823
+ if (selectedAuth.has("ApiKeyAuth")) {
1824
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
1825
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
1826
+ }
1827
+ if (selectedAuth.has("BearerAuth")) {
1828
+ const bearerAuth = this._bearerAuth();
1829
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
1830
+ }
1831
+ headers["Content-Type"] = "application/json";
1832
+ const requestBody = JSON.stringify(body);
1833
+ const res = await this._request("POST", path, headers, requestBody, {
1834
+ operationId: "deleteStorageDatabaseRows",
1835
+ pathTemplate: "/storage/databases/{id}/rows/delete",
1836
+ idempotent: false,
1837
+ idempotencyKeyHeader: "Idempotency-Key",
1838
+ successStatuses: [200]
1839
+ }, options);
1840
+ if (res.status < 200 || res.status >= 300) {
1841
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
1842
+ let errorBody = jsonBody;
1843
+ if (res.status === 400) errorBody = jsonBody;
1844
+ if (res.status === 401) errorBody = jsonBody;
1845
+ if (res.status === 402) errorBody = jsonBody;
1846
+ if (res.status === 403) errorBody = jsonBody;
1847
+ if (res.status === 404) errorBody = jsonBody;
1848
+ if (res.status === 409) errorBody = jsonBody;
1849
+ if (res.status === 413) errorBody = jsonBody;
1850
+ if (res.status === 429) errorBody = jsonBody;
1851
+ if (res.status === 500) errorBody = jsonBody;
1852
+ if (res.status === 503) errorBody = jsonBody;
1853
+ throw new ApiError(res.status, {
1854
+ headers: res.headers,
1855
+ requestId: res.headers.get("x-request-id") ?? void 0,
1856
+ rawBody,
1857
+ jsonBody,
1858
+ body: errorBody
1859
+ });
1860
+ }
1861
+ if (res.status === 200) return await this._decodeJson(res);
1862
+ throw new ApiError(res.status);
1863
+ };
1864
+ const insertStorageDatabaseRows = async function(id, body, options) {
1865
+ let path = `/storage/databases/${wireEscape$1(String(id))}/rows/insert`;
1866
+ const selectedAuth = this._selectAuthAlternative("insertStorageDatabaseRows", [[{
1867
+ schemeId: "BearerAuth",
1868
+ kind: "bearer"
1869
+ }], [{
1870
+ schemeId: "ApiKeyAuth",
1871
+ kind: "apiKey",
1872
+ name: "authorization"
1873
+ }]]);
1874
+ const headers = {};
1875
+ if (selectedAuth.has("ApiKeyAuth")) {
1876
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
1877
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
1878
+ }
1879
+ if (selectedAuth.has("BearerAuth")) {
1880
+ const bearerAuth = this._bearerAuth();
1881
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
1882
+ }
1883
+ headers["Content-Type"] = "application/json";
1884
+ const requestBody = JSON.stringify(body);
1885
+ const res = await this._request("POST", path, headers, requestBody, {
1886
+ operationId: "insertStorageDatabaseRows",
1887
+ pathTemplate: "/storage/databases/{id}/rows/insert",
1888
+ idempotent: false,
1889
+ idempotencyKeyHeader: "Idempotency-Key",
1890
+ successStatuses: [200]
1891
+ }, options);
1892
+ if (res.status < 200 || res.status >= 300) {
1893
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
1894
+ let errorBody = jsonBody;
1895
+ if (res.status === 400) errorBody = jsonBody;
1896
+ if (res.status === 401) errorBody = jsonBody;
1897
+ if (res.status === 402) errorBody = jsonBody;
1898
+ if (res.status === 403) errorBody = jsonBody;
1899
+ if (res.status === 404) errorBody = jsonBody;
1900
+ if (res.status === 409) errorBody = jsonBody;
1901
+ if (res.status === 413) errorBody = jsonBody;
1902
+ if (res.status === 429) errorBody = jsonBody;
1903
+ if (res.status === 500) errorBody = jsonBody;
1904
+ if (res.status === 503) errorBody = jsonBody;
1905
+ throw new ApiError(res.status, {
1906
+ headers: res.headers,
1907
+ requestId: res.headers.get("x-request-id") ?? void 0,
1908
+ rawBody,
1909
+ jsonBody,
1910
+ body: errorBody
1911
+ });
1912
+ }
1913
+ if (res.status === 200) return await this._decodeJson(res);
1914
+ throw new ApiError(res.status);
1915
+ };
1916
+ const selectStorageDatabaseRows = async function(id, body, options) {
1917
+ let path = `/storage/databases/${wireEscape$1(String(id))}/rows/select`;
1918
+ const selectedAuth = this._selectAuthAlternative("selectStorageDatabaseRows", [[{
1919
+ schemeId: "BearerAuth",
1920
+ kind: "bearer"
1921
+ }], [{
1922
+ schemeId: "ApiKeyAuth",
1923
+ kind: "apiKey",
1924
+ name: "authorization"
1925
+ }]]);
1926
+ const headers = {};
1927
+ if (selectedAuth.has("ApiKeyAuth")) {
1928
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
1929
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
1930
+ }
1931
+ if (selectedAuth.has("BearerAuth")) {
1932
+ const bearerAuth = this._bearerAuth();
1933
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
1934
+ }
1935
+ headers["Content-Type"] = "application/json";
1936
+ const requestBody = JSON.stringify(body);
1937
+ const res = await this._request("POST", path, headers, requestBody, {
1938
+ operationId: "selectStorageDatabaseRows",
1939
+ pathTemplate: "/storage/databases/{id}/rows/select",
1940
+ idempotent: false,
1941
+ idempotencyKeyHeader: "Idempotency-Key",
1942
+ successStatuses: [200]
1943
+ }, options);
1944
+ if (res.status < 200 || res.status >= 300) {
1945
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
1946
+ let errorBody = jsonBody;
1947
+ if (res.status === 400) errorBody = jsonBody;
1948
+ if (res.status === 401) errorBody = jsonBody;
1949
+ if (res.status === 402) errorBody = jsonBody;
1950
+ if (res.status === 403) errorBody = jsonBody;
1951
+ if (res.status === 404) errorBody = jsonBody;
1952
+ if (res.status === 409) errorBody = jsonBody;
1953
+ if (res.status === 413) errorBody = jsonBody;
1954
+ if (res.status === 429) errorBody = jsonBody;
1955
+ if (res.status === 500) errorBody = jsonBody;
1956
+ if (res.status === 503) errorBody = jsonBody;
1957
+ throw new ApiError(res.status, {
1958
+ headers: res.headers,
1959
+ requestId: res.headers.get("x-request-id") ?? void 0,
1960
+ rawBody,
1961
+ jsonBody,
1962
+ body: errorBody
1963
+ });
1964
+ }
1965
+ if (res.status === 200) return await this._decodeJson(res);
1966
+ throw new ApiError(res.status);
1967
+ };
1968
+ const updateStorageDatabaseRows = async function(id, body, options) {
1969
+ let path = `/storage/databases/${wireEscape$1(String(id))}/rows/update`;
1970
+ const selectedAuth = this._selectAuthAlternative("updateStorageDatabaseRows", [[{
1971
+ schemeId: "BearerAuth",
1972
+ kind: "bearer"
1973
+ }], [{
1974
+ schemeId: "ApiKeyAuth",
1975
+ kind: "apiKey",
1976
+ name: "authorization"
1977
+ }]]);
1978
+ const headers = {};
1979
+ if (selectedAuth.has("ApiKeyAuth")) {
1980
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
1981
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
1982
+ }
1983
+ if (selectedAuth.has("BearerAuth")) {
1984
+ const bearerAuth = this._bearerAuth();
1985
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
1986
+ }
1987
+ headers["Content-Type"] = "application/json";
1988
+ const requestBody = JSON.stringify(body);
1989
+ const res = await this._request("POST", path, headers, requestBody, {
1990
+ operationId: "updateStorageDatabaseRows",
1991
+ pathTemplate: "/storage/databases/{id}/rows/update",
1992
+ idempotent: false,
1993
+ idempotencyKeyHeader: "Idempotency-Key",
1994
+ successStatuses: [200]
1995
+ }, options);
1996
+ if (res.status < 200 || res.status >= 300) {
1997
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
1998
+ let errorBody = jsonBody;
1999
+ if (res.status === 400) errorBody = jsonBody;
2000
+ if (res.status === 401) errorBody = jsonBody;
2001
+ if (res.status === 402) errorBody = jsonBody;
2002
+ if (res.status === 403) errorBody = jsonBody;
2003
+ if (res.status === 404) errorBody = jsonBody;
2004
+ if (res.status === 409) errorBody = jsonBody;
2005
+ if (res.status === 413) errorBody = jsonBody;
2006
+ if (res.status === 429) errorBody = jsonBody;
2007
+ if (res.status === 500) errorBody = jsonBody;
2008
+ if (res.status === 503) errorBody = jsonBody;
2009
+ throw new ApiError(res.status, {
2010
+ headers: res.headers,
2011
+ requestId: res.headers.get("x-request-id") ?? void 0,
2012
+ rawBody,
2013
+ jsonBody,
2014
+ body: errorBody
2015
+ });
2016
+ }
2017
+ if (res.status === 200) return await this._decodeJson(res);
2018
+ throw new ApiError(res.status);
2019
+ };
2020
+ const upsertStorageDatabaseRows = async function(id, body, options) {
2021
+ let path = `/storage/databases/${wireEscape$1(String(id))}/rows/upsert`;
2022
+ const selectedAuth = this._selectAuthAlternative("upsertStorageDatabaseRows", [[{
2023
+ schemeId: "BearerAuth",
2024
+ kind: "bearer"
2025
+ }], [{
2026
+ schemeId: "ApiKeyAuth",
2027
+ kind: "apiKey",
2028
+ name: "authorization"
2029
+ }]]);
2030
+ const headers = {};
2031
+ if (selectedAuth.has("ApiKeyAuth")) {
2032
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
2033
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
2034
+ }
2035
+ if (selectedAuth.has("BearerAuth")) {
2036
+ const bearerAuth = this._bearerAuth();
2037
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
2038
+ }
2039
+ headers["Content-Type"] = "application/json";
2040
+ const requestBody = JSON.stringify(body);
2041
+ const res = await this._request("POST", path, headers, requestBody, {
2042
+ operationId: "upsertStorageDatabaseRows",
2043
+ pathTemplate: "/storage/databases/{id}/rows/upsert",
2044
+ idempotent: false,
2045
+ idempotencyKeyHeader: "Idempotency-Key",
2046
+ successStatuses: [200]
2047
+ }, options);
2048
+ if (res.status < 200 || res.status >= 300) {
2049
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
2050
+ let errorBody = jsonBody;
2051
+ if (res.status === 400) errorBody = jsonBody;
2052
+ if (res.status === 401) errorBody = jsonBody;
2053
+ if (res.status === 402) errorBody = jsonBody;
2054
+ if (res.status === 403) errorBody = jsonBody;
2055
+ if (res.status === 404) errorBody = jsonBody;
2056
+ if (res.status === 409) errorBody = jsonBody;
2057
+ if (res.status === 413) errorBody = jsonBody;
2058
+ if (res.status === 429) errorBody = jsonBody;
2059
+ if (res.status === 500) errorBody = jsonBody;
2060
+ if (res.status === 503) errorBody = jsonBody;
2061
+ throw new ApiError(res.status, {
2062
+ headers: res.headers,
2063
+ requestId: res.headers.get("x-request-id") ?? void 0,
2064
+ rawBody,
2065
+ jsonBody,
2066
+ body: errorBody
2067
+ });
2068
+ }
2069
+ if (res.status === 200) return await this._decodeJson(res);
2070
+ throw new ApiError(res.status);
2071
+ };
2072
+ function wireEscape$1(value) {
2073
+ return encodeURIComponent(value).replace(/[!'()*]/g, (char) => "%" + char.charCodeAt(0).toString(16).toUpperCase());
2074
+ }
2075
+
2076
+ // src/apis/api_tools.ts
2077
+ const listTools = async function(params, options) {
2078
+ let path = `/ingest/tools`;
2079
+ const selectedAuth = this._selectAuthAlternative("listTools", [[{
2080
+ schemeId: "BearerAuth",
2081
+ kind: "bearer"
2082
+ }], [{
2083
+ schemeId: "ApiKeyAuth",
2084
+ kind: "apiKey",
2085
+ name: "authorization"
2086
+ }]]);
2087
+ const searchParams = new URLSearchParams();
2088
+ if (params?.integrationUuid !== void 0) for (const [wireName, wireValue] of wireParameterPairs("integrationUuid", params.integrationUuid, "form", true)) searchParams.append(wireName, wireValue);
2089
+ if (params?.job !== void 0) for (const [wireName, wireValue] of wireParameterPairs("job", params.job, "form", true)) searchParams.append(wireName, wireValue);
2090
+ if (params?.nativeOnly !== void 0) for (const [wireName, wireValue] of wireParameterPairs("nativeOnly", params.nativeOnly, "form", true)) searchParams.append(wireName, wireValue);
2091
+ if (params?.query !== void 0) for (const [wireName, wireValue] of wireParameterPairs("query", params.query, "form", true)) searchParams.append(wireName, wireValue);
2092
+ const qs = wireQueryString(searchParams);
2093
+ if (qs) path = path + "?" + qs;
2094
+ const headers = {};
2095
+ if (selectedAuth.has("ApiKeyAuth")) {
2096
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
2097
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
2098
+ }
2099
+ if (selectedAuth.has("BearerAuth")) {
2100
+ const bearerAuth = this._bearerAuth();
2101
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
2102
+ }
2103
+ const res = await this._request("GET", path, headers, void 0, {
2104
+ operationId: "listTools",
2105
+ pathTemplate: "/ingest/tools",
2106
+ idempotent: false,
2107
+ idempotencyKeyHeader: "Idempotency-Key",
2108
+ successStatuses: [200]
2109
+ }, options);
2110
+ if (res.status < 200 || res.status >= 300) {
2111
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
2112
+ let errorBody = jsonBody;
2113
+ if (res.status === 400) errorBody = jsonBody;
2114
+ if (res.status === 401) errorBody = jsonBody;
2115
+ if (res.status === 402) errorBody = jsonBody;
2116
+ if (res.status === 403) errorBody = jsonBody;
2117
+ if (res.status === 404) errorBody = jsonBody;
2118
+ if (res.status === 409) errorBody = jsonBody;
2119
+ if (res.status === 413) errorBody = jsonBody;
2120
+ if (res.status === 429) errorBody = jsonBody;
2121
+ if (res.status === 500) errorBody = jsonBody;
2122
+ if (res.status === 503) errorBody = jsonBody;
2123
+ throw new ApiError(res.status, {
2124
+ headers: res.headers,
2125
+ requestId: res.headers.get("x-request-id") ?? void 0,
2126
+ rawBody,
2127
+ jsonBody,
2128
+ body: errorBody
2129
+ });
2130
+ }
2131
+ if (res.status === 200) return await this._decodeJson(res);
2132
+ throw new ApiError(res.status);
2133
+ };
2134
+ const getNativeTools = async function(params, options) {
2135
+ let path = `/ingest/tools/native`;
2136
+ const selectedAuth = this._selectAuthAlternative("getNativeTools", [[{
2137
+ schemeId: "BearerAuth",
2138
+ kind: "bearer"
2139
+ }], [{
2140
+ schemeId: "ApiKeyAuth",
2141
+ kind: "apiKey",
2142
+ name: "authorization"
2143
+ }]]);
2144
+ const searchParams = new URLSearchParams();
2145
+ if (params?.surface !== void 0) for (const [wireName, wireValue] of wireParameterPairs("surface", params.surface, "form", true)) searchParams.append(wireName, wireValue);
2146
+ const qs = wireQueryString(searchParams);
2147
+ if (qs) path = path + "?" + qs;
2148
+ const headers = {};
2149
+ if (selectedAuth.has("ApiKeyAuth")) {
2150
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
2151
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
2152
+ }
2153
+ if (selectedAuth.has("BearerAuth")) {
2154
+ const bearerAuth = this._bearerAuth();
2155
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
2156
+ }
2157
+ const res = await this._request("GET", path, headers, void 0, {
2158
+ operationId: "getNativeTools",
2159
+ pathTemplate: "/ingest/tools/native",
2160
+ idempotent: false,
2161
+ idempotencyKeyHeader: "Idempotency-Key",
2162
+ successStatuses: [200]
2163
+ }, options);
2164
+ if (res.status < 200 || res.status >= 300) {
2165
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
2166
+ let errorBody = jsonBody;
2167
+ if (res.status === 400) errorBody = jsonBody;
2168
+ if (res.status === 401) errorBody = jsonBody;
2169
+ if (res.status === 402) errorBody = jsonBody;
2170
+ if (res.status === 403) errorBody = jsonBody;
2171
+ if (res.status === 404) errorBody = jsonBody;
2172
+ if (res.status === 409) errorBody = jsonBody;
2173
+ if (res.status === 413) errorBody = jsonBody;
2174
+ if (res.status === 429) errorBody = jsonBody;
2175
+ if (res.status === 500) errorBody = jsonBody;
2176
+ if (res.status === 503) errorBody = jsonBody;
2177
+ throw new ApiError(res.status, {
2178
+ headers: res.headers,
2179
+ requestId: res.headers.get("x-request-id") ?? void 0,
2180
+ rawBody,
2181
+ jsonBody,
2182
+ body: errorBody
2183
+ });
2184
+ }
2185
+ if (res.status === 200) return await this._decodeJson(res);
2186
+ throw new ApiError(res.status);
2187
+ };
2188
+ const runTool = async function(selector, body, options) {
2189
+ let path = `/ingest/tools/${wireEscape(String(selector))}/run`;
2190
+ const selectedAuth = this._selectAuthAlternative("runTool", [[{
2191
+ schemeId: "BearerAuth",
2192
+ kind: "bearer"
2193
+ }], [{
2194
+ schemeId: "ApiKeyAuth",
2195
+ kind: "apiKey",
2196
+ name: "authorization"
2197
+ }]]);
2198
+ const headers = {};
2199
+ if (selectedAuth.has("ApiKeyAuth")) {
2200
+ const apiKey0 = this._apiKey("ApiKeyAuth", "authorization");
2201
+ if (apiKey0 !== void 0) headers["authorization"] = apiKey0;
2202
+ }
2203
+ if (selectedAuth.has("BearerAuth")) {
2204
+ const bearerAuth = this._bearerAuth();
2205
+ if (bearerAuth !== void 0) headers["Authorization"] = bearerAuth;
2206
+ }
2207
+ headers["Content-Type"] = "application/json";
2208
+ const requestBody = JSON.stringify(body);
2209
+ const res = await this._request("POST", path, headers, requestBody, {
2210
+ operationId: "runTool",
2211
+ pathTemplate: "/ingest/tools/{selector}/run",
2212
+ idempotent: false,
2213
+ idempotencyKeyHeader: "Idempotency-Key",
2214
+ successStatuses: [200]
2215
+ }, options);
2216
+ if (res.status < 200 || res.status >= 300) {
2217
+ const { rawBody, jsonBody } = await this._readErrorBody(res);
2218
+ let errorBody = jsonBody;
2219
+ if (res.status === 400) errorBody = jsonBody;
2220
+ if (res.status === 401) errorBody = jsonBody;
2221
+ if (res.status === 402) errorBody = jsonBody;
2222
+ if (res.status === 403) errorBody = jsonBody;
2223
+ if (res.status === 404) errorBody = jsonBody;
2224
+ if (res.status === 409) errorBody = jsonBody;
2225
+ if (res.status === 413) errorBody = jsonBody;
2226
+ if (res.status === 429) errorBody = jsonBody;
2227
+ if (res.status === 500) errorBody = jsonBody;
2228
+ if (res.status === 503) errorBody = jsonBody;
2229
+ throw new ApiError(res.status, {
2230
+ headers: res.headers,
2231
+ requestId: res.headers.get("x-request-id") ?? void 0,
2232
+ rawBody,
2233
+ jsonBody,
2234
+ body: errorBody
2235
+ });
2236
+ }
2237
+ if (res.status === 200) return await this._decodeJson(res);
2238
+ throw new ApiError(res.status);
2239
+ };
2240
+ function wireParameterPairs(name, value, style, explode) {
2241
+ const delimiter = style === "spaceDelimited" ? " " : style === "pipeDelimited" ? "|" : ",";
2242
+ if (Array.isArray(value)) {
2243
+ const parts = value.map((item) => String(item));
2244
+ return explode && style === "form" ? parts.map((item) => [name, item]) : [[name, parts.join(delimiter)]];
2245
+ }
2246
+ if (value !== null && typeof value === "object") {
2247
+ const entries = Object.entries(value).sort(([a], [b]) => a.localeCompare(b));
2248
+ if (style === "deepObject") return entries.map(([key, item]) => [name + "[" + key + "]", String(item)]);
2249
+ if (explode && style === "form") return entries.map(([key, item]) => [key, String(item)]);
2250
+ return [[name, entries.flatMap(([key, item]) => explode ? [key + "=" + String(item)] : [key, String(item)]).join(delimiter)]];
2251
+ }
2252
+ return [[name, String(value)]];
2253
+ }
2254
+ function wireQueryString(values, allowReserved = /* @__PURE__ */ new Set()) {
2255
+ const restoreReserved = (value) => value.replace(/%3A|%2F|%3F|%23|%5B|%5D|%40|%21|%24|%26|%27|%28|%29|%2A|%2B|%2C|%3B|%3D/gi, (token) => decodeURIComponent(token));
2256
+ const parts = [];
2257
+ let index = 0;
2258
+ values.forEach((value, key) => {
2259
+ const encoded = wireEscape(value);
2260
+ parts.push(wireEscape(key) + "=" + (allowReserved.has(index) ? restoreReserved(encoded) : encoded));
2261
+ index += 1;
2262
+ });
2263
+ return parts.join("&");
2264
+ }
2265
+ function wireEscape(value) {
2266
+ return encodeURIComponent(value).replace(/[!'()*]/g, (char) => "%" + char.charCodeAt(0).toString(16).toUpperCase());
2267
+ }
2268
+
2269
+ // src/client.ts
2270
+ const BASE_RETRY_DELAY_MS = 100;
2271
+ const MAX_RETRY_DELAY_MS = 6e4;
2272
+ var Client = class {
2273
+ constructor(opts) {
2274
+ this.baseUrl = opts.baseUrl.replace(/\/+$/, "");
2275
+ this.fetchFn = opts.fetch ?? globalThis.fetch.bind(globalThis);
2276
+ this.authMode = opts.authMode ?? "credentials";
2277
+ this.apiKey = opts.apiKey;
2278
+ this.apiKeys = opts.apiKeys ?? {};
2279
+ this.timeoutMs = opts.timeoutMs ?? 6e4;
2280
+ this.maxRetries = opts.maxRetries ?? 0;
2281
+ this.retryStatuses = /* @__PURE__ */ new Set([408, 429]);
2282
+ this.retryUnsafeMethods = false;
2283
+ this.hooks = {
2284
+ request: opts.hooks?.request ?? [],
2285
+ response: opts.hooks?.response ?? [],
2286
+ error: opts.hooks?.error ?? []
2287
+ };
2288
+ this.bearerToken = opts.bearerToken;
2289
+ }
2290
+ _apiKey(...names) {
2291
+ for (const name of names) {
2292
+ const value = this.apiKeys[name];
2293
+ if (value !== void 0 && value !== "") return value;
2294
+ }
2295
+ return this.apiKey === "" ? void 0 : this.apiKey;
2296
+ }
2297
+ _bearerAuth() {
2298
+ if (this.bearerToken === void 0) return;
2299
+ return `Bearer ${this.bearerToken}`;
2300
+ }
2301
+ _selectAuthAlternative(operationId, alternatives) {
2302
+ if (alternatives.length === 0) return /* @__PURE__ */ new Set();
2303
+ if (this.authMode === "transport") return /* @__PURE__ */ new Set();
2304
+ for (const alternative of alternatives) if (alternative.every((requirement) => {
2305
+ if (requirement.kind === "apiKey") return this._apiKey(requirement.schemeId, requirement.name ?? "") !== void 0;
2306
+ if (requirement.kind === "bearer") return this.bearerToken !== void 0;
2307
+ return this.basicAuth !== void 0;
2308
+ })) return new Set(alternative.map((requirement) => requirement.schemeId));
2309
+ throw new AuthConfigurationError(operationId, alternatives.map((alternative) => alternative.map((requirement) => requirement.schemeId)));
2310
+ }
2311
+ async _decodeJson(response) {
2312
+ const rawBody = await response.text();
2313
+ const actualContentType = response.headers.get("content-type") ?? void 0;
2314
+ const mediaType = actualContentType?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
2315
+ const errorInit = {
2316
+ headers: response.headers,
2317
+ requestId: response.headers.get("x-request-id") ?? void 0,
2318
+ rawBody,
2319
+ expectedContentType: "application/json",
2320
+ actualContentType
2321
+ };
2322
+ if (rawBody.length === 0) throw new ResponseDecodeError("empty_body", response.status, errorInit);
2323
+ if (mediaType !== "application/json" && !mediaType.endsWith("+json")) throw new ResponseDecodeError("unexpected_content_type", response.status, errorInit);
2324
+ try {
2325
+ return JSON.parse(rawBody);
2326
+ } catch (cause) {
2327
+ throw new ResponseDecodeError("invalid_json", response.status, {
2328
+ ...errorInit,
2329
+ cause
2330
+ });
2331
+ }
2332
+ }
2333
+ async _decodeText(response) {
2334
+ const bytes = new Uint8Array(await response.arrayBuffer());
2335
+ try {
2336
+ return new TextDecoder("utf-8", {
2337
+ fatal: true,
2338
+ ignoreBOM: true
2339
+ }).decode(bytes);
2340
+ } catch (cause) {
2341
+ throw new ResponseDecodeError("invalid_text", response.status, {
2342
+ headers: response.headers,
2343
+ requestId: response.headers.get("x-request-id") ?? void 0,
2344
+ expectedContentType: "text/*",
2345
+ actualContentType: response.headers.get("content-type") ?? void 0,
2346
+ cause
2347
+ });
2348
+ }
2349
+ }
2350
+ async _readErrorBody(response) {
2351
+ const rawBody = await response.text();
2352
+ if (rawBody.length === 0) return {
2353
+ rawBody,
2354
+ jsonBody: null
2355
+ };
2356
+ const actualContentType = response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() ?? "";
2357
+ if (actualContentType !== "application/json" && !actualContentType.endsWith("+json")) return {
2358
+ rawBody,
2359
+ jsonBody: null
2360
+ };
2361
+ try {
2362
+ return {
2363
+ rawBody,
2364
+ jsonBody: JSON.parse(rawBody)
2365
+ };
2366
+ } catch {
2367
+ return {
2368
+ rawBody,
2369
+ jsonBody: null
2370
+ };
2371
+ }
2372
+ }
2373
+ _encodeBody(body) {
2374
+ if (body === void 0) return;
2375
+ if (body instanceof URLSearchParams || body instanceof FormData || body instanceof Blob || body instanceof ArrayBuffer || typeof body === "string") return body;
2376
+ if (ArrayBuffer.isView(body)) return new Blob([body]);
2377
+ return JSON.stringify(body);
2378
+ }
2379
+ _formBody(body) {
2380
+ const params = new URLSearchParams();
2381
+ for (const [key, value] of Object.entries(body)) {
2382
+ if (value === void 0 || value === null) continue;
2383
+ if (Array.isArray(value)) for (const item of value) params.append(key, String(item));
2384
+ else params.set(key, String(value));
2385
+ }
2386
+ return params;
2387
+ }
2388
+ _multipartBody(body) {
2389
+ const form = new FormData();
2390
+ for (const [key, value] of Object.entries(body)) {
2391
+ if (value === void 0 || value === null) continue;
2392
+ if (Array.isArray(value)) for (const item of value) this._appendMultipartValue(form, key, item);
2393
+ else this._appendMultipartValue(form, key, value);
2394
+ }
2395
+ return form;
2396
+ }
2397
+ _appendMultipartValue(form, key, value) {
2398
+ if (value === void 0 || value === null) return;
2399
+ if (value instanceof Blob) form.append(key, value);
2400
+ else if (value instanceof ArrayBuffer || ArrayBuffer.isView(value)) form.append(key, new Blob([value]), key);
2401
+ else form.append(key, String(value));
2402
+ }
2403
+ async _request(method, path, headers, body, requestContext, options = {}) {
2404
+ const context = requestContext ?? {
2405
+ operationId: "",
2406
+ pathTemplate: path
2407
+ };
2408
+ const url = `${this.baseUrl}${path}`;
2409
+ const requestMetadata = options.metadata ?? {};
2410
+ Object.assign(headers, options.headers ?? {});
2411
+ if (context.idempotent === true && options.idempotencyKey !== void 0) headers[context.idempotencyKeyHeader ?? "Idempotency-Key"] = options.idempotencyKey;
2412
+ const maxRetries = Math.max(0, options.maxRetries ?? this.maxRetries);
2413
+ const retryAttempts = this.retryUnsafeMethods || context.idempotent === true || this._retryableMethod(method) ? maxRetries : 0;
2414
+ const timeoutMs = options.timeoutMs ?? this.timeoutMs;
2415
+ const bodyPayload = this._encodeBody(body);
2416
+ let lastError = void 0;
2417
+ let retryBudgetMs = MAX_RETRY_DELAY_MS;
2418
+ for (let attempt = 0; attempt <= retryAttempts; attempt += 1) {
2419
+ const controller = timeoutMs !== void 0 && timeoutMs > 0 ? new AbortController() : void 0;
2420
+ const timeoutId = controller === void 0 ? void 0 : setTimeout(() => controller.abort(), timeoutMs);
2421
+ const signals = [options.signal, controller?.signal].filter((signal) => signal !== void 0);
2422
+ const init = {
2423
+ method,
2424
+ headers,
2425
+ body: bodyPayload ?? null,
2426
+ redirect: options.followRedirects === true ? "follow" : "manual",
2427
+ signal: signals.length > 1 ? AbortSignal.any(signals) : signals[0] ?? null
2428
+ };
2429
+ const hookContext = {
2430
+ operationId: context.operationId,
2431
+ method,
2432
+ pathTemplate: context.pathTemplate,
2433
+ url,
2434
+ headers: { ...headers },
2435
+ requestMetadata
2436
+ };
2437
+ try {
2438
+ for (const hook of this.hooks.request) await hook(hookContext, init);
2439
+ } catch (error) {
2440
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
2441
+ for (const hook of this.hooks.error) await hook(hookContext, error);
2442
+ throw error;
2443
+ }
2444
+ let response = void 0;
2445
+ try {
2446
+ response = await this.fetchFn(url, init);
2447
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
2448
+ } catch (error) {
2449
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
2450
+ lastError = error;
2451
+ if (attempt < retryAttempts && retryBudgetMs > 0) {
2452
+ const delayMs = Math.min(this._backoffDelayMs(attempt), retryBudgetMs);
2453
+ retryBudgetMs -= delayMs;
2454
+ await this._waitBeforeRetry(delayMs, options.signal, hookContext);
2455
+ continue;
2456
+ }
2457
+ for (const hook of this.hooks.error) await hook(hookContext, error);
2458
+ throw error;
2459
+ }
2460
+ if (response === void 0) throw new Error("request failed without response");
2461
+ const opaqueRedirect = response.type === "opaqueredirect" && options.followRedirects !== true && (context.successStatuses ?? []).some((status) => status >= 300 && status < 400);
2462
+ hookContext.status = response.status;
2463
+ hookContext.responseHeaders = response.headers;
2464
+ hookContext.opaqueRedirect = opaqueRedirect;
2465
+ try {
2466
+ for (const hook of this.hooks.response) await hook(hookContext, response);
2467
+ } catch (error) {
2468
+ for (const hook of this.hooks.error) await hook(hookContext, error);
2469
+ throw error;
2470
+ }
2471
+ if (this._shouldRetryStatus(response.status) && attempt < retryAttempts && retryBudgetMs > 0) {
2472
+ await this._discardBody(response);
2473
+ const delayMs = Math.min(this._retryDelayMs(response, attempt), retryBudgetMs);
2474
+ retryBudgetMs -= delayMs;
2475
+ await this._waitBeforeRetry(delayMs, options.signal, hookContext);
2476
+ continue;
2477
+ }
2478
+ if ((response.status < 200 || response.status >= 300) && !(context.successStatuses ?? []).includes(response.status) && !opaqueRedirect) {
2479
+ const error = new ApiError(response.status, {
2480
+ headers: response.headers,
2481
+ requestId: response.headers.get("x-request-id") ?? void 0
2482
+ });
2483
+ for (const hook of this.hooks.error) await hook(hookContext, error);
2484
+ }
2485
+ return response;
2486
+ }
2487
+ throw lastError ?? /* @__PURE__ */ new Error("request failed without response");
2488
+ }
2489
+ _retryableMethod(method) {
2490
+ return method === "GET" || method === "HEAD" || method === "OPTIONS" || method === "PUT" || method === "DELETE";
2491
+ }
2492
+ _shouldRetryStatus(status) {
2493
+ return this.retryStatuses.has(status) || status >= 500;
2494
+ }
2495
+ async _discardBody(response) {
2496
+ try {
2497
+ await response.body?.cancel();
2498
+ } catch {}
2499
+ }
2500
+ _retryDelayMs(response, attempt) {
2501
+ const retryAfter = response.headers.get("Retry-After");
2502
+ if (retryAfter !== null) {
2503
+ const seconds = Number.parseInt(retryAfter, 10);
2504
+ if (Number.isFinite(seconds) && seconds > 0) return Math.min(seconds * 1e3, MAX_RETRY_DELAY_MS);
2505
+ }
2506
+ return this._backoffDelayMs(attempt);
2507
+ }
2508
+ _backoffDelayMs(attempt) {
2509
+ return Math.min(BASE_RETRY_DELAY_MS * 2 ** attempt, MAX_RETRY_DELAY_MS);
2510
+ }
2511
+ async _waitBeforeRetry(ms, signal, hookContext) {
2512
+ try {
2513
+ await this._sleep(ms, signal);
2514
+ } catch (error) {
2515
+ for (const hook of this.hooks.error) await hook(hookContext, error);
2516
+ throw error;
2517
+ }
2518
+ }
2519
+ async _sleep(ms, signal) {
2520
+ if (ms <= 0) return;
2521
+ if (signal?.aborted === true) throw signal.reason ?? /* @__PURE__ */ new Error("request aborted");
2522
+ await new Promise((resolve, reject) => {
2523
+ const onAbort = () => {
2524
+ clearTimeout(timer);
2525
+ reject(signal?.reason ?? /* @__PURE__ */ new Error("request aborted"));
2526
+ };
2527
+ const timer = setTimeout(() => {
2528
+ signal?.removeEventListener("abort", onAbort);
2529
+ resolve();
2530
+ }, ms);
2531
+ signal?.addEventListener("abort", onAbort, { once: true });
2532
+ });
2533
+ }
2534
+ get action() {
2535
+ return new ActionApi(this);
2536
+ }
2537
+ get appChat() {
2538
+ return new AppChatApi(this);
2539
+ }
2540
+ get event() {
2541
+ return new EventApi(this);
2542
+ }
2543
+ get jobs() {
2544
+ return new JobsApi(this);
2545
+ }
2546
+ get llm() {
2547
+ return new LlmApi(this);
2548
+ }
2549
+ get storage() {
2550
+ return new StorageApi(this);
2551
+ }
2552
+ get tools() {
2553
+ return new ToolsApi(this);
2554
+ }
2555
+ };
2556
+ var ActionApi = class {
2557
+ constructor(client) {
2558
+ this.client = client;
2559
+ }
2560
+ listActionExecutionLogs(...args) {
2561
+ return this.client.listActionExecutionLogs(...args);
2562
+ }
2563
+ getActionExecutionLogByUuid(...args) {
2564
+ return this.client.getActionExecutionLogByUuid(...args);
2565
+ }
2566
+ streamActionExecutionEvents(...args) {
2567
+ return this.client.streamActionExecutionEvents(...args);
2568
+ }
2569
+ };
2570
+ var AppChatApi = class {
2571
+ constructor(client) {
2572
+ this.client = client;
2573
+ }
2574
+ createAppChatMessage(...args) {
2575
+ return this.client.createAppChatMessage(...args);
2576
+ }
2577
+ listAppChatSessions(...args) {
2578
+ return this.client.listAppChatSessions(...args);
2579
+ }
2580
+ getAppChatSession(...args) {
2581
+ return this.client.getAppChatSession(...args);
2582
+ }
2583
+ createAppChatApproval(...args) {
2584
+ return this.client.createAppChatApproval(...args);
2585
+ }
2586
+ createAppVoiceLine(...args) {
2587
+ return this.client.createAppVoiceLine(...args);
2588
+ }
2589
+ createAppLiveVoiceSession(...args) {
2590
+ return this.client.createAppLiveVoiceSession(...args);
2591
+ }
2592
+ deleteAppLiveVoiceSession(...args) {
2593
+ return this.client.deleteAppLiveVoiceSession(...args);
2594
+ }
2595
+ };
2596
+ var EventApi = class {
2597
+ constructor(client) {
2598
+ this.client = client;
2599
+ }
2600
+ publishEvent(...args) {
2601
+ return this.client.publishEvent(...args);
2602
+ }
2603
+ };
2604
+ var JobsApi = class {
2605
+ constructor(client) {
2606
+ this.client = client;
2607
+ }
2608
+ executeJobStream(...args) {
2609
+ return this.client.executeJobStream(...args);
2610
+ }
2611
+ };
2612
+ var LlmApi = class {
2613
+ constructor(client) {
2614
+ this.client = client;
2615
+ }
2616
+ createEmbeddings(...args) {
2617
+ return this.client.createEmbeddings(...args);
2618
+ }
2619
+ createLlmCall(...args) {
2620
+ return this.client.createLlmCall(...args);
2621
+ }
2622
+ };
2623
+ var StorageApi = class {
2624
+ constructor(client) {
2625
+ this.client = client;
2626
+ }
2627
+ callStorageDatabaseFunction(...args) {
2628
+ return this.client.callStorageDatabaseFunction(...args);
2629
+ }
2630
+ deleteStorageDatabaseRows(...args) {
2631
+ return this.client.deleteStorageDatabaseRows(...args);
2632
+ }
2633
+ insertStorageDatabaseRows(...args) {
2634
+ return this.client.insertStorageDatabaseRows(...args);
2635
+ }
2636
+ selectStorageDatabaseRows(...args) {
2637
+ return this.client.selectStorageDatabaseRows(...args);
2638
+ }
2639
+ updateStorageDatabaseRows(...args) {
2640
+ return this.client.updateStorageDatabaseRows(...args);
2641
+ }
2642
+ upsertStorageDatabaseRows(...args) {
2643
+ return this.client.upsertStorageDatabaseRows(...args);
2644
+ }
2645
+ };
2646
+ var ToolsApi = class {
2647
+ constructor(client) {
2648
+ this.client = client;
2649
+ }
2650
+ listTools(...args) {
2651
+ return this.client.listTools(...args);
2652
+ }
2653
+ getNativeTools(...args) {
2654
+ return this.client.getNativeTools(...args);
2655
+ }
2656
+ runTool(...args) {
2657
+ return this.client.runTool(...args);
2658
+ }
2659
+ };
2660
+ Client.prototype.listActionExecutionLogs = listActionExecutionLogs;
2661
+ Client.prototype.listActionExecutionLogsPages = listActionExecutionLogsPages;
2662
+ Client.prototype.iterateListActionExecutionLogs = iterateListActionExecutionLogs;
2663
+ Client.prototype.getActionExecutionLogByUuid = getActionExecutionLogByUuid;
2664
+ Client.prototype.streamActionExecutionEvents = streamActionExecutionEvents;
2665
+ Client.prototype.createAppChatMessage = createAppChatMessage;
2666
+ Client.prototype.listAppChatSessions = listAppChatSessions;
2667
+ Client.prototype.getAppChatSession = getAppChatSession;
2668
+ Client.prototype.createAppChatApproval = createAppChatApproval;
2669
+ Client.prototype.createAppVoiceLine = createAppVoiceLine;
2670
+ Client.prototype.createAppLiveVoiceSession = createAppLiveVoiceSession;
2671
+ Client.prototype.deleteAppLiveVoiceSession = deleteAppLiveVoiceSession;
2672
+ Client.prototype.publishEvent = publishEvent;
2673
+ Client.prototype.executeJobStream = executeJobStream;
2674
+ Client.prototype.createEmbeddings = createEmbeddings;
2675
+ Client.prototype.createLlmCall = createLlmCall;
2676
+ Client.prototype.callStorageDatabaseFunction = callStorageDatabaseFunction;
2677
+ Client.prototype.deleteStorageDatabaseRows = deleteStorageDatabaseRows;
2678
+ Client.prototype.insertStorageDatabaseRows = insertStorageDatabaseRows;
2679
+ Client.prototype.selectStorageDatabaseRows = selectStorageDatabaseRows;
2680
+ Client.prototype.updateStorageDatabaseRows = updateStorageDatabaseRows;
2681
+ Client.prototype.upsertStorageDatabaseRows = upsertStorageDatabaseRows;
2682
+ Client.prototype.listTools = listTools;
2683
+ Client.prototype.getNativeTools = getNativeTools;
2684
+ Client.prototype.runTool = runTool;
2685
+
2686
+ // src/app/auth.ts
2687
+ const RENEW_BEFORE_EXPIRY_MS = 6e4;
2688
+ const SCOPE = "openid email profile";
2689
+ const RESPONSE_PARAMETERS = [
2690
+ "code",
2691
+ "state",
2692
+ "iss",
2693
+ "error",
2694
+ "error_description"
2695
+ ];
2696
+ const NO_BROWSER = {
2697
+ message: "Signing in needs a browser page.",
2698
+ code: "auth-browser-required",
2699
+ hints: []
2700
+ };
2701
+ const SIGNED_OUT = {
2702
+ message: "No member is signed in to the app.",
2703
+ code: "auth-signed-out",
2704
+ hints: []
2705
+ };
2706
+ const STATE_MISMATCH = {
2707
+ message: "The sign-in answer does not belong to the sign-in this page started.",
2708
+ code: "auth-state-mismatch",
2709
+ hints: []
2710
+ };
2711
+ const ISSUER_MISMATCH = {
2712
+ message: "The sign-in answer does not come from the OAIZ this page signed in with.",
2713
+ code: "auth-issuer-mismatch",
2714
+ hints: []
2715
+ };
2716
+ function browser() {
2717
+ const scope = globalThis;
2718
+ if (scope.location === void 0 || scope.sessionStorage === void 0 || scope.history === void 0) return;
2719
+ return {
2720
+ location: scope.location,
2721
+ sessionStorage: scope.sessionStorage,
2722
+ history: scope.history
2723
+ };
2724
+ }
2725
+ var AppAuth = class {
2726
+ constructor(url, app) {
2727
+ this.app = app;
2728
+ this.signOutHooks = /* @__PURE__ */ new Set();
2729
+ this.issuer = `${url.replace(/\/+$/, "")}/oauth`;
2730
+ this.sessionKey = `oaiz.auth.${app}`;
2731
+ this.signInKey = `oaiz.auth.${app}.signIn`;
2732
+ this.redirect = this.completeSignIn();
2733
+ }
2734
+ async signIn() {
2735
+ const scope = browser();
2736
+ if (scope === void 0) return { error: NO_BROWSER };
2737
+ try {
2738
+ const response = await fetch(`${this.issuer}/.well-known/openid-configuration`, { headers: { Accept: "application/json" } });
2739
+ const discovery = await readJSON(response);
2740
+ if (!response.ok || !isRecord(discovery) || typeof discovery.issuer !== "string" || typeof discovery.authorization_endpoint !== "string") return { error: answerError(response.status, discovery) };
2741
+ const verifier = base64url(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32)));
2742
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
2743
+ const page = new URL(scope.location.href);
2744
+ page.hash = "";
2745
+ for (const name of RESPONSE_PARAMETERS) page.searchParams.delete(name);
2746
+ const pending = {
2747
+ state: base64url(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16))),
2748
+ verifier,
2749
+ redirectUri: page.toString(),
2750
+ issuer: discovery.issuer
2751
+ };
2752
+ scope.sessionStorage.setItem(this.signInKey, JSON.stringify(pending));
2753
+ const target = new URL(discovery.authorization_endpoint);
2754
+ target.searchParams.set("response_type", "code");
2755
+ target.searchParams.set("client_id", this.app);
2756
+ target.searchParams.set("redirect_uri", pending.redirectUri);
2757
+ target.searchParams.set("scope", SCOPE);
2758
+ target.searchParams.set("state", pending.state);
2759
+ target.searchParams.set("code_challenge", base64url(new Uint8Array(digest)));
2760
+ target.searchParams.set("code_challenge_method", "S256");
2761
+ scope.location.assign(target.toString());
2762
+ return { error: null };
2763
+ } catch (cause) {
2764
+ return { error: transportError(cause) };
2765
+ }
2766
+ }
2767
+ async getSession() {
2768
+ const read = await this.session();
2769
+ if (read.error !== null) return {
2770
+ data: null,
2771
+ error: read.error
2772
+ };
2773
+ if (read.session === void 0) return {
2774
+ data: null,
2775
+ error: null
2776
+ };
2777
+ const { accessToken, expiresAt, scope } = read.session;
2778
+ return {
2779
+ data: {
2780
+ accessToken,
2781
+ expiresAt,
2782
+ scope
2783
+ },
2784
+ error: null
2785
+ };
2786
+ }
2787
+ async getUser() {
2788
+ const read = await this.session();
2789
+ if (read.session === void 0) return {
2790
+ data: null,
2791
+ error: read.error ?? SIGNED_OUT
2792
+ };
2793
+ try {
2794
+ const response = await fetch(`${this.issuer}/userinfo`, { headers: { Authorization: `Bearer ${read.session.accessToken}` } });
2795
+ const claims = await readJSON(response);
2796
+ if (!response.ok || !isRecord(claims) || typeof claims.sub !== "string") return {
2797
+ data: null,
2798
+ error: answerError(response.status, claims)
2799
+ };
2800
+ const user = { id: claims.sub };
2801
+ if (typeof claims.email === "string") user.email = claims.email;
2802
+ if (typeof claims.email_verified === "boolean") user.emailVerified = claims.email_verified;
2803
+ if (typeof claims.name === "string") user.name = claims.name;
2804
+ return {
2805
+ data: user,
2806
+ error: null
2807
+ };
2808
+ } catch (cause) {
2809
+ return {
2810
+ data: null,
2811
+ error: transportError(cause)
2812
+ };
2813
+ }
2814
+ }
2815
+ async signOut() {
2816
+ await this.redirect;
2817
+ await Promise.all([...this.signOutHooks].map((hook) => hook()));
2818
+ await this.renewing;
2819
+ const stored = this.readSession();
2820
+ this.clearSession();
2821
+ if (stored === void 0) return { error: null };
2822
+ try {
2823
+ const response = await fetch(`${this.issuer}/revoke`, formRequest({
2824
+ token: stored.refreshToken,
2825
+ token_type_hint: "refresh_token",
2826
+ client_id: this.app
2827
+ }));
2828
+ if (response.status === 200) return { error: null };
2829
+ return { error: answerError(response.status, await readJSON(response)) };
2830
+ } catch (cause) {
2831
+ return { error: transportError(cause) };
2832
+ }
2833
+ }
2834
+ async accessToken() {
2835
+ return (await this.session()).session?.accessToken;
2836
+ }
2837
+ storedAccessToken() {
2838
+ return this.readSession()?.accessToken;
2839
+ }
2840
+ beforeSignOut(hook) {
2841
+ this.signOutHooks.add(hook);
2842
+ return () => {
2843
+ this.signOutHooks.delete(hook);
2844
+ };
2845
+ }
2846
+ async session() {
2847
+ const redirectError = await this.redirect;
2848
+ const stored = this.readSession();
2849
+ if (stored === void 0) return {
2850
+ session: void 0,
2851
+ error: redirectError
2852
+ };
2853
+ if (stored.expiresAt - Date.now() > RENEW_BEFORE_EXPIRY_MS) return {
2854
+ session: stored,
2855
+ error: redirectError
2856
+ };
2857
+ if (this.renewing === void 0) this.renewing = this.renew(stored).finally(() => {
2858
+ this.renewing = void 0;
2859
+ });
2860
+ const read = await this.renewing;
2861
+ return redirectError === null ? read : {
2862
+ session: read.session,
2863
+ error: redirectError
2864
+ };
2865
+ }
2866
+ async renew(stored) {
2867
+ const answer = await this.requestTokens({
2868
+ grant_type: "refresh_token",
2869
+ refresh_token: stored.refreshToken,
2870
+ client_id: this.app
2871
+ });
2872
+ if (answer.tokens !== void 0) {
2873
+ this.writeSession(answer.tokens);
2874
+ return {
2875
+ session: answer.tokens,
2876
+ error: null
2877
+ };
2878
+ }
2879
+ if (answer.refused) {
2880
+ this.clearSession();
2881
+ return {
2882
+ session: void 0,
2883
+ error: answer.error
2884
+ };
2885
+ }
2886
+ return {
2887
+ session: stored,
2888
+ error: null
2889
+ };
2890
+ }
2891
+ async completeSignIn() {
2892
+ const scope = browser();
2893
+ if (scope === void 0) return null;
2894
+ try {
2895
+ const page = new URL(scope.location.href);
2896
+ const parameters = new URLSearchParams(page.search);
2897
+ const state = parameters.get("state");
2898
+ const code = parameters.get("code");
2899
+ const error = parameters.get("error");
2900
+ if (state === null || code === null && error === null) return null;
2901
+ const raw = scope.sessionStorage.getItem(this.signInKey);
2902
+ if (raw === null) return null;
2903
+ scope.sessionStorage.removeItem(this.signInKey);
2904
+ for (const name of RESPONSE_PARAMETERS) page.searchParams.delete(name);
2905
+ scope.history.replaceState(scope.history.state, "", page.toString());
2906
+ const pending = parsePendingSignIn(raw);
2907
+ if (pending === void 0 || pending.state !== state) return STATE_MISMATCH;
2908
+ if (parameters.get("iss") !== pending.issuer) return ISSUER_MISMATCH;
2909
+ if (error !== null) return {
2910
+ message: parameters.get("error_description") ?? error,
2911
+ code: error,
2912
+ hints: []
2913
+ };
2914
+ const answer = await this.requestTokens({
2915
+ grant_type: "authorization_code",
2916
+ code: code ?? "",
2917
+ redirect_uri: pending.redirectUri,
2918
+ client_id: this.app,
2919
+ code_verifier: pending.verifier
2920
+ });
2921
+ if (answer.tokens === void 0) return answer.error;
2922
+ this.writeSession(answer.tokens);
2923
+ return null;
2924
+ } catch (cause) {
2925
+ return transportError(cause);
2926
+ }
2927
+ }
2928
+ async requestTokens(form) {
2929
+ let response;
2930
+ try {
2931
+ response = await fetch(`${this.issuer}/token`, formRequest(form));
2932
+ } catch (cause) {
2933
+ return {
2934
+ error: transportError(cause),
2935
+ refused: false
2936
+ };
2937
+ }
2938
+ const body = await readJSON(response);
2939
+ const tokens = response.ok ? parseTokens(body) : void 0;
2940
+ if (tokens !== void 0) return { tokens };
2941
+ const refused = (response.status === 400 || response.status === 401) && isRecord(body) && typeof body.error === "string";
2942
+ return {
2943
+ error: answerError(response.status, body),
2944
+ refused
2945
+ };
2946
+ }
2947
+ readSession() {
2948
+ const raw = browser()?.sessionStorage.getItem(this.sessionKey);
2949
+ return raw === null || raw === void 0 ? void 0 : parseSession(raw);
2950
+ }
2951
+ writeSession(session) {
2952
+ browser()?.sessionStorage.setItem(this.sessionKey, JSON.stringify(session));
2953
+ }
2954
+ clearSession() {
2955
+ browser()?.sessionStorage.removeItem(this.sessionKey);
2956
+ }
2957
+ };
2958
+ function formRequest(form) {
2959
+ return {
2960
+ method: "POST",
2961
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
2962
+ body: new URLSearchParams(form).toString()
2963
+ };
2964
+ }
2965
+ async function readJSON(response) {
2966
+ try {
2967
+ return await response.json();
2968
+ } catch {
2969
+ return;
2970
+ }
2971
+ }
2972
+ function isRecord(value) {
2973
+ return typeof value === "object" && value !== null;
2974
+ }
2975
+ function parseTokens(body) {
2976
+ if (!isRecord(body) || typeof body.access_token !== "string" || typeof body.refresh_token !== "string" || typeof body.expires_in !== "number") return;
2977
+ return {
2978
+ accessToken: body.access_token,
2979
+ refreshToken: body.refresh_token,
2980
+ expiresAt: Date.now() + body.expires_in * 1e3,
2981
+ scope: typeof body.scope === "string" ? body.scope : ""
2982
+ };
2983
+ }
2984
+ function parseSession(raw) {
2985
+ const value = parseStored(raw);
2986
+ if (!isRecord(value) || typeof value.accessToken !== "string" || typeof value.refreshToken !== "string" || typeof value.expiresAt !== "number" || typeof value.scope !== "string") return;
2987
+ return {
2988
+ accessToken: value.accessToken,
2989
+ refreshToken: value.refreshToken,
2990
+ expiresAt: value.expiresAt,
2991
+ scope: value.scope
2992
+ };
2993
+ }
2994
+ function parsePendingSignIn(raw) {
2995
+ const value = parseStored(raw);
2996
+ if (!isRecord(value) || typeof value.state !== "string" || typeof value.verifier !== "string" || typeof value.redirectUri !== "string" || typeof value.issuer !== "string") return;
2997
+ return {
2998
+ state: value.state,
2999
+ verifier: value.verifier,
3000
+ redirectUri: value.redirectUri,
3001
+ issuer: value.issuer
3002
+ };
3003
+ }
3004
+ function parseStored(raw) {
3005
+ try {
3006
+ return JSON.parse(raw);
3007
+ } catch {
3008
+ return;
3009
+ }
3010
+ }
3011
+ function answerError(status, body) {
3012
+ if (isRecord(body) && typeof body.error === "string") return {
3013
+ message: typeof body.error_description === "string" ? body.error_description : body.error,
3014
+ code: body.error,
3015
+ hints: []
3016
+ };
3017
+ return {
3018
+ message: `OAIZ answered ${status}.`,
3019
+ code: "",
3020
+ hints: []
3021
+ };
3022
+ }
3023
+ function transportError(cause) {
3024
+ return {
3025
+ message: cause instanceof Error ? cause.message : String(cause),
3026
+ code: "",
3027
+ hints: []
3028
+ };
3029
+ }
3030
+ function base64url(bytes) {
3031
+ let binary = "";
3032
+ for (const byte of bytes) binary += String.fromCharCode(byte);
3033
+ return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
3034
+ }
3035
+
3036
+ // src/app/embeddings.ts
3037
+ var OaizEmbeddings = class {
3038
+ constructor(client) {
3039
+ this.client = client;
3040
+ }
3041
+ async create(request) {
3042
+ try {
3043
+ const answer = await this.client.createEmbeddings(request, { timeoutMs: 12e4 });
3044
+ const embeddings = [];
3045
+ for (const item of answer.data) embeddings[item.index] = item.embedding;
3046
+ return {
3047
+ data: {
3048
+ model: answer.model,
3049
+ dimensions: answer.dimensions,
3050
+ embeddings,
3051
+ inputTokens: answer.usage.inputTokens
3052
+ },
3053
+ error: null,
3054
+ count: null,
3055
+ status: 200
3056
+ };
3057
+ } catch (error) {
3058
+ return failureFrom(error);
3059
+ }
3060
+ }
3061
+ };
3062
+
3063
+ // src/app/events.ts
3064
+ var OaizEvents = class {
3065
+ constructor(client) {
3066
+ this.client = client;
3067
+ }
3068
+ async publish(event) {
3069
+ try {
3070
+ return {
3071
+ data: await this.client.publishEvent({
3072
+ contentType: "application/json",
3073
+ value: event
3074
+ }),
3075
+ error: null,
3076
+ count: null,
3077
+ status: 201
3078
+ };
3079
+ } catch (error) {
3080
+ return failureFrom(error);
3081
+ }
3082
+ }
3083
+ };
3084
+
3085
+ // src/app/llm.ts
3086
+ var OaizLLM = class {
3087
+ constructor(client) {
3088
+ this.client = client;
3089
+ }
3090
+ async call(request) {
3091
+ try {
3092
+ const answer = await this.client.createLlmCall(request, { timeoutMs: 3e5 });
3093
+ return {
3094
+ data: {
3095
+ text: answer.text,
3096
+ model: answer.model,
3097
+ usage: answer.usage
3098
+ },
3099
+ error: null,
3100
+ count: null,
3101
+ status: 200
3102
+ };
3103
+ } catch (error) {
3104
+ return failureFrom(error);
3105
+ }
3106
+ }
3107
+ };
3108
+
3109
+ // src/app/filters.ts
3110
+ var FilterParseError = class extends Error {
3111
+ constructor(message) {
3112
+ super(message);
3113
+ this.name = "FilterParseError";
3114
+ }
3115
+ };
3116
+ const OPERATORS = [
3117
+ "eq",
3118
+ "neq",
3119
+ "gt",
3120
+ "gte",
3121
+ "lt",
3122
+ "lte",
3123
+ "like",
3124
+ "ilike",
3125
+ "in",
3126
+ "is"
3127
+ ];
3128
+ const IS_VALUES = [
3129
+ "null",
3130
+ "true",
3131
+ "false"
3132
+ ];
3133
+ function likePattern(pattern) {
3134
+ return pattern.replace(/\*/g, "%");
3135
+ }
3136
+ function condition(column, operator, raw, not) {
3137
+ if (OPERATORS.indexOf(operator) < 0) throw new FilterParseError(`unknown operator ${operator} on ${column}`);
3138
+ const filter = {
3139
+ column,
3140
+ operator
3141
+ };
3142
+ if (operator === "in") filter.values = parseList(raw, column);
3143
+ else if (operator === "is") {
3144
+ if (IS_VALUES.indexOf(raw) < 0) throw new FilterParseError(`is on ${column} takes null, true or false`);
3145
+ filter.value = raw;
3146
+ } else if (operator === "like" || operator === "ilike") filter.value = likePattern(raw);
3147
+ else filter.value = raw;
3148
+ if (not) filter.not = true;
3149
+ return filter;
3150
+ }
3151
+ function parseLogic(text) {
3152
+ const parser = new LogicParser(text);
3153
+ const filters = parser.list();
3154
+ if (!parser.done()) throw new FilterParseError(`unexpected ${JSON.stringify(text.charAt(parser.position))} at ${parser.position} in ${JSON.stringify(text)}`);
3155
+ return filters;
3156
+ }
3157
+ function parseList(raw, column) {
3158
+ if (raw.charAt(0) !== "(" || raw.charAt(raw.length - 1) !== ")") throw new FilterParseError(`in on ${column} takes a list such as (a,b)`);
3159
+ const parser = new LogicParser(raw.slice(1, -1));
3160
+ const values = [];
3161
+ if (parser.done()) return values;
3162
+ for (;;) {
3163
+ values.push(parser.value());
3164
+ if (parser.done()) return values;
3165
+ parser.expect(",");
3166
+ }
3167
+ }
3168
+ var LogicParser = class {
3169
+ constructor(text) {
3170
+ this.text = text;
3171
+ this.position = 0;
3172
+ }
3173
+ done() {
3174
+ return this.position >= this.text.length;
3175
+ }
3176
+ expect(char) {
3177
+ if (this.text.charAt(this.position) !== char) throw new FilterParseError(`expected ${JSON.stringify(char)} at ${this.position} in ${JSON.stringify(this.text)}`);
3178
+ this.position += 1;
3179
+ }
3180
+ list() {
3181
+ this.skipSpace();
3182
+ const filters = [this.item()];
3183
+ while (this.text.charAt(this.position) === ",") {
3184
+ this.position += 1;
3185
+ this.skipSpace();
3186
+ filters.push(this.item());
3187
+ }
3188
+ return filters;
3189
+ }
3190
+ skipSpace() {
3191
+ while (!this.done() && " ".indexOf(this.text.charAt(this.position)) >= 0) this.position += 1;
3192
+ }
3193
+ item() {
3194
+ let not = false;
3195
+ if (this.text.startsWith("not.", this.position)) {
3196
+ const rest = this.text.slice(this.position + 4);
3197
+ if (rest.startsWith("and(") || rest.startsWith("or(")) {
3198
+ not = true;
3199
+ this.position += 4;
3200
+ }
3201
+ }
3202
+ for (const kind of ["and", "or"]) if (this.text.startsWith(`${kind}(`, this.position)) {
3203
+ this.position += kind.length + 1;
3204
+ const members = this.list();
3205
+ this.expect(")");
3206
+ const group = kind === "and" ? { and: members } : { or: members };
3207
+ if (not) group.not = true;
3208
+ return group;
3209
+ }
3210
+ const column = this.column();
3211
+ this.expect(".");
3212
+ let operator = this.name("operator");
3213
+ let negated = false;
3214
+ if (operator === "not") {
3215
+ negated = true;
3216
+ this.expect(".");
3217
+ operator = this.name("operator");
3218
+ }
3219
+ this.expect(".");
3220
+ const raw = operator === "in" ? this.inList() : this.value();
3221
+ return condition(column, operator, raw, negated);
3222
+ }
3223
+ column() {
3224
+ if (this.text.charAt(this.position) === "\"") return this.quoted();
3225
+ const column = this.name("column").trim();
3226
+ if (column === "") throw new FilterParseError(`expected a column in ${JSON.stringify(this.text)}`);
3227
+ return column;
3228
+ }
3229
+ name(what) {
3230
+ const start = this.position;
3231
+ while (!this.done() && ".,()".indexOf(this.text.charAt(this.position)) < 0) this.position += 1;
3232
+ if (this.position === start) throw new FilterParseError(`expected a ${what} at ${start} in ${JSON.stringify(this.text)}`);
3233
+ return this.text.slice(start, this.position);
3234
+ }
3235
+ inList() {
3236
+ const start = this.position;
3237
+ this.expect("(");
3238
+ while (this.text.charAt(this.position) !== ")") {
3239
+ if (this.done()) throw new FilterParseError(`unclosed in list at ${start} in ${JSON.stringify(this.text)}`);
3240
+ if (this.text.charAt(this.position) === "\"") this.quoted();
3241
+ else this.position += 1;
3242
+ }
3243
+ this.position += 1;
3244
+ return this.text.slice(start, this.position);
3245
+ }
3246
+ value() {
3247
+ if (this.text.charAt(this.position) === "\"") {
3248
+ const value = this.quoted();
3249
+ if (!this.done() && ",)".indexOf(this.text.charAt(this.position)) < 0) throw new FilterParseError(`unexpected text after a quoted value at ${this.position} in ${JSON.stringify(this.text)}`);
3250
+ return value;
3251
+ }
3252
+ const start = this.position;
3253
+ while (!this.done() && ",)".indexOf(this.text.charAt(this.position)) < 0) this.position += 1;
3254
+ return this.text.slice(start, this.position);
3255
+ }
3256
+ quoted() {
3257
+ const start = this.position;
3258
+ this.position += 1;
3259
+ let value = "";
3260
+ while (!this.done()) {
3261
+ const char = this.text.charAt(this.position);
3262
+ if (char === "\"") {
3263
+ this.position += 1;
3264
+ return value;
3265
+ }
3266
+ if (char === "\\") {
3267
+ this.position += 1;
3268
+ if (this.done()) break;
3269
+ }
3270
+ value += this.text.charAt(this.position);
3271
+ this.position += 1;
3272
+ }
3273
+ throw new FilterParseError(`unclosed quoted value at ${start} in ${JSON.stringify(this.text)}`);
3274
+ }
3275
+ };
3276
+
3277
+ // src/app/query.ts
3278
+ var OaizQueryBuilder = class {
3279
+ constructor(client, database, table) {
3280
+ this.client = client;
3281
+ this.database = database;
3282
+ this.table = table;
3283
+ }
3284
+ select(columns, options = {}) {
3285
+ return this.builder({
3286
+ action: "select",
3287
+ table: this.table,
3288
+ select: compactSelect(columns ?? "*"),
3289
+ count: options.count
3290
+ });
3291
+ }
3292
+ insert(values, options = {}) {
3293
+ return this.builder({
3294
+ action: "insert",
3295
+ table: this.table,
3296
+ rows: Array.isArray(values) ? values : [values],
3297
+ count: options.count,
3298
+ defaultToNull: options.defaultToNull
3299
+ });
3300
+ }
3301
+ upsert(values, options = {}) {
3302
+ return this.builder({
3303
+ action: "upsert",
3304
+ table: this.table,
3305
+ rows: Array.isArray(values) ? values : [values],
3306
+ count: options.count,
3307
+ defaultToNull: options.defaultToNull,
3308
+ onConflict: options.onConflict === void 0 ? void 0 : options.onConflict.split(",").map((column) => column.trim()),
3309
+ ignoreDuplicates: options.ignoreDuplicates
3310
+ });
3311
+ }
3312
+ update(values, options = {}) {
3313
+ return this.builder({
3314
+ action: "update",
3315
+ table: this.table,
3316
+ values,
3317
+ count: options.count
3318
+ });
3319
+ }
3320
+ delete(...args) {
3321
+ const [options = {}] = args;
3322
+ return this.builder({
3323
+ action: "delete",
3324
+ table: this.table,
3325
+ count: options.count
3326
+ });
3327
+ }
3328
+ builder(request) {
3329
+ return new OaizFilterBuilder(this.client, this.database, request);
3330
+ }
3331
+ };
3332
+ var OaizFilterBuilder = class OaizFilterBuilder {
3333
+ constructor(client, database, request) {
3334
+ this.client = client;
3335
+ this.database = database;
3336
+ this.request = request;
3337
+ this.filters = [];
3338
+ this.orderTerms = [];
3339
+ this.singleValue = false;
3340
+ }
3341
+ eq(column, value) {
3342
+ return this.compare(column, "eq", value);
3343
+ }
3344
+ neq(column, value) {
3345
+ return this.compare(column, "neq", value);
3346
+ }
3347
+ gt(column, value) {
3348
+ return this.compare(column, "gt", value);
3349
+ }
3350
+ gte(column, value) {
3351
+ return this.compare(column, "gte", value);
3352
+ }
3353
+ lt(column, value) {
3354
+ return this.compare(column, "lt", value);
3355
+ }
3356
+ lte(column, value) {
3357
+ return this.compare(column, "lte", value);
3358
+ }
3359
+ like(column, pattern) {
3360
+ return this.compare(column, "like", likePattern(pattern));
3361
+ }
3362
+ ilike(column, pattern) {
3363
+ return this.compare(column, "ilike", likePattern(pattern));
3364
+ }
3365
+ in(column, values) {
3366
+ this.filters.push({
3367
+ column,
3368
+ operator: "in",
3369
+ values: values.map(filterText)
3370
+ });
3371
+ return this;
3372
+ }
3373
+ is(column, value) {
3374
+ return this.compare(column, "is", value);
3375
+ }
3376
+ not(column, operator, value) {
3377
+ return this.parse(() => [condition(column, operator, filterText(value), true)]);
3378
+ }
3379
+ or(filters) {
3380
+ return this.parse(() => [{ or: parseLogic(filters) }]);
3381
+ }
3382
+ order(column, options = {}) {
3383
+ const term = { column };
3384
+ if (options.ascending !== void 0) term.ascending = options.ascending;
3385
+ if (options.nullsFirst !== void 0) term.nullsFirst = options.nullsFirst;
3386
+ this.orderTerms.push(term);
3387
+ return this;
3388
+ }
3389
+ limit(count) {
3390
+ if (!isRowNumber(count)) return this.refuse(`limit takes a whole number of rows from 0, not ${count}`);
3391
+ this.limitValue = count;
3392
+ return this;
3393
+ }
3394
+ range(from, to) {
3395
+ if (!isRowNumber(from) || !isRowNumber(to) || to < from) return this.refuse(`range takes whole row numbers from 0 with from <= to, not ${from} to ${to}`);
3396
+ this.offsetValue = from;
3397
+ this.limitValue = to - from + 1;
3398
+ return this;
3399
+ }
3400
+ single() {
3401
+ const next = this.copy();
3402
+ next.singleValue = true;
3403
+ return next;
3404
+ }
3405
+ select(columns) {
3406
+ const next = this.copy();
3407
+ next.request.select = compactSelect(columns ?? "*");
3408
+ return next;
3409
+ }
3410
+ copy() {
3411
+ const next = new OaizFilterBuilder(this.client, this.database, { ...this.request });
3412
+ next.filters.push(...this.filters);
3413
+ next.orderTerms.push(...this.orderTerms);
3414
+ next.limitValue = this.limitValue;
3415
+ next.offsetValue = this.offsetValue;
3416
+ next.singleValue = this.singleValue;
3417
+ next.invalid = this.invalid;
3418
+ return next;
3419
+ }
3420
+ then(onfulfilled, onrejected) {
3421
+ return this.execute().then(onfulfilled, onrejected);
3422
+ }
3423
+ compare(column, operator, value) {
3424
+ this.filters.push({
3425
+ column,
3426
+ operator,
3427
+ value: filterText(value)
3428
+ });
3429
+ return this;
3430
+ }
3431
+ parse(build) {
3432
+ try {
3433
+ this.filters.push(...build());
3434
+ } catch (error) {
3435
+ if (!(error instanceof FilterParseError)) throw error;
3436
+ this.refuse(error.message);
3437
+ }
3438
+ return this;
3439
+ }
3440
+ refuse(reason) {
3441
+ this.invalid = this.invalid ?? reason;
3442
+ return this;
3443
+ }
3444
+ unsendable() {
3445
+ const { action } = this.request;
3446
+ if (action === "select") return;
3447
+ if (this.orderTerms.length > 0 || this.limitValue !== void 0 || this.offsetValue !== void 0) return `${action} takes no order, limit or range`;
3448
+ if ((action === "insert" || action === "upsert") && this.filters.length > 0) return `${action} takes no filters`;
3449
+ }
3450
+ async execute() {
3451
+ const invalid = this.invalid ?? this.unsendable();
3452
+ if (invalid !== void 0) return failure(400, {
3453
+ message: invalid,
3454
+ code: REQUEST_INVALID_CODE,
3455
+ hints: []
3456
+ });
3457
+ let answer;
3458
+ try {
3459
+ answer = await this.send();
3460
+ } catch (error) {
3461
+ return failureFrom(error);
3462
+ }
3463
+ const rows = answer.rows ?? [];
3464
+ const returnsRows = this.request.action === "select" || this.request.select !== void 0;
3465
+ let data = null;
3466
+ if (returnsRows) data = this.singleValue ? rows[0] ?? null : rows;
3467
+ return {
3468
+ data,
3469
+ error: null,
3470
+ count: answer.count ?? null,
3471
+ status: 200
3472
+ };
3473
+ }
3474
+ send() {
3475
+ const { action, table, select, count } = this.request;
3476
+ const shared = {
3477
+ table,
3478
+ ...select === void 0 ? {} : { select },
3479
+ ...count === void 0 ? {} : { count },
3480
+ ...this.singleValue ? { single: true } : {}
3481
+ };
3482
+ switch (action) {
3483
+ case "select": {
3484
+ const body = { ...shared };
3485
+ if (this.filters.length > 0) body.filters = this.filters;
3486
+ if (this.orderTerms.length > 0) body.order = this.orderTerms;
3487
+ if (this.limitValue !== void 0) body.limit = this.limitValue;
3488
+ if (this.offsetValue !== void 0) body.offset = this.offsetValue;
3489
+ return this.client.selectStorageDatabaseRows(this.database, body);
3490
+ }
3491
+ case "insert": {
3492
+ const body = {
3493
+ ...shared,
3494
+ rows: this.request.rows ?? []
3495
+ };
3496
+ if (this.request.defaultToNull !== void 0) body.defaultToNull = this.request.defaultToNull;
3497
+ return this.client.insertStorageDatabaseRows(this.database, body);
3498
+ }
3499
+ case "upsert": {
3500
+ const body = {
3501
+ ...shared,
3502
+ rows: this.request.rows ?? []
3503
+ };
3504
+ if (this.request.defaultToNull !== void 0) body.defaultToNull = this.request.defaultToNull;
3505
+ if (this.request.onConflict !== void 0) body.onConflict = this.request.onConflict;
3506
+ if (this.request.ignoreDuplicates !== void 0) body.ignoreDuplicates = this.request.ignoreDuplicates;
3507
+ return this.client.upsertStorageDatabaseRows(this.database, body);
3508
+ }
3509
+ case "update": {
3510
+ const body = {
3511
+ ...shared,
3512
+ values: this.request.values ?? {},
3513
+ filters: this.filters
3514
+ };
3515
+ return this.client.updateStorageDatabaseRows(this.database, body);
3516
+ }
3517
+ case "delete": {
3518
+ const body = {
3519
+ ...shared,
3520
+ filters: this.filters
3521
+ };
3522
+ return this.client.deleteStorageDatabaseRows(this.database, body);
3523
+ }
3524
+ }
3525
+ }
3526
+ };
3527
+ function compactSelect(columns) {
3528
+ let quoted = false;
3529
+ let escaped = false;
3530
+ let compact = "";
3531
+ for (const char of columns) {
3532
+ if (escaped) escaped = false;
3533
+ else if (quoted && char === "\\") escaped = true;
3534
+ else if (char === "\"") quoted = !quoted;
3535
+ else if (!quoted && /\s/.test(char)) continue;
3536
+ compact += char;
3537
+ }
3538
+ return compact;
3539
+ }
3540
+ function filterText(value) {
3541
+ return typeof value === "object" && value !== null ? JSON.stringify(value) : String(value);
3542
+ }
3543
+ function isRowNumber(value) {
3544
+ return Number.isInteger(value) && value >= 0;
3545
+ }
3546
+
3547
+ // src/app/runs.ts
3548
+ var OaizRuns = class {
3549
+ constructor(client, open) {
3550
+ this.client = client;
3551
+ this.open = open;
3552
+ }
3553
+ start(jobUuid, request, options) {
3554
+ return this.stream({
3555
+ operation: "executeJobStream",
3556
+ params: { jobUuid }
3557
+ }, request, options?.signal);
3558
+ }
3559
+ follow(actionExecutionUuid, options) {
3560
+ const query = new URLSearchParams();
3561
+ if (options?.after !== void 0) query.set("after", options.after);
3562
+ if (options?.publishEvents !== void 0) query.set("publishEvents", String(options.publishEvents));
3563
+ const raw = {
3564
+ operation: "streamActionExecutionEvents",
3565
+ params: { uuid: actionExecutionUuid },
3566
+ query
3567
+ };
3568
+ return this.stream(raw, void 0, options?.signal);
3569
+ }
3570
+ async get(actionExecutionUuid) {
3571
+ try {
3572
+ return {
3573
+ data: await this.client.getActionExecutionLogByUuid(actionExecutionUuid),
3574
+ error: null,
3575
+ count: null,
3576
+ status: 200
3577
+ };
3578
+ } catch (error) {
3579
+ return failureFrom(error);
3580
+ }
3581
+ }
3582
+ async list(params) {
3583
+ try {
3584
+ return {
3585
+ data: await this.client.listActionExecutionLogs(params),
3586
+ error: null,
3587
+ count: null,
3588
+ status: 200
3589
+ };
3590
+ } catch (error) {
3591
+ return failureFrom(error);
3592
+ }
3593
+ }
3594
+ async *stream(request, body, signal) {
3595
+ const frames = readSseStream(this.open, request, body, signal, "execute_progress", (event) => event.type === "terminal" || event.type === "waiting");
3596
+ for await (const frame of frames) yield frame.error === null ? {
3597
+ ...frame,
3598
+ data: {
3599
+ event: frame.data.data,
3600
+ after: frame.data.id
3601
+ }
3602
+ } : frame;
3603
+ }
3604
+ };
3605
+
3606
+ // src/app/tools.ts
3607
+ var OaizTools = class {
3608
+ constructor(client) {
3609
+ this.client = client;
3610
+ }
3611
+ async run(selector, request) {
3612
+ try {
3613
+ return {
3614
+ data: await this.client.runTool(selector, request, { timeoutMs: 12e5 }),
3615
+ error: null,
3616
+ count: null,
3617
+ status: 200
3618
+ };
3619
+ } catch (error) {
3620
+ return failureFrom(error);
3621
+ }
3622
+ }
3623
+ };
3624
+
3625
+ // src/app/client.ts
3626
+ var OaizClient = class OaizClient {
3627
+ constructor(client, databaseId, open) {
3628
+ this.client = client;
3629
+ this.databaseId = databaseId;
3630
+ this.open = open;
3631
+ this.events = new OaizEvents(client);
3632
+ this.tools = new OaizTools(client);
3633
+ this.embeddings = new OaizEmbeddings(client);
3634
+ this.llm = new OaizLLM(client);
3635
+ this.runs = new OaizRuns(client, open);
3636
+ }
3637
+ from(table) {
3638
+ return new OaizQueryBuilder(this.client, this.databaseId, table);
3639
+ }
3640
+ async rpc(name, ...[args]) {
3641
+ try {
3642
+ return {
3643
+ data: (await this.client.callStorageDatabaseFunction(this.databaseId, args === void 0 ? { name } : {
3644
+ name,
3645
+ args
3646
+ })).data ?? null,
3647
+ error: null,
3648
+ count: null,
3649
+ status: 200
3650
+ };
3651
+ } catch (error) {
3652
+ return failureFrom(error);
3653
+ }
3654
+ }
3655
+ database(id) {
3656
+ return new OaizClient(this.client, id, this.open);
3657
+ }
3658
+ };
3659
+ var OaizAppClient = class OaizAppClient extends OaizClient {
3660
+ constructor(client, databaseId, open, auth, chat) {
3661
+ super(client, databaseId, open);
3662
+ this.auth = auth;
3663
+ this.chat = chat;
3664
+ }
3665
+ database(id) {
3666
+ return new OaizAppClient(this.client, id, this.open, this.auth, this.chat);
3667
+ }
3668
+ };
3669
+ function createClient(options) {
3670
+ const { key, app } = options;
3671
+ if (key !== void 0 && app === void 0) {
3672
+ const client = new Client({
3673
+ baseUrl: options.url,
3674
+ bearerToken: key
3675
+ });
3676
+ return new OaizClient(client, options.database, streamOpener(options.url, async () => key));
3677
+ }
3678
+ if (app !== void 0 && key === void 0) {
3679
+ const auth = new AppAuth(options.url, app);
3680
+ const client = new Client({
3681
+ baseUrl: options.url,
3682
+ authMode: "transport",
3683
+ hooks: { request: [async (_context, init) => {
3684
+ const token = await auth.accessToken();
3685
+ if (token !== void 0) init.headers.Authorization = `Bearer ${token}`;
3686
+ }] }
3687
+ });
3688
+ const open = streamOpener(options.url, () => auth.accessToken());
3689
+ return new OaizAppClient(client, options.database, open, auth, new OaizChat(client, open, app, auth, options.url));
3690
+ }
3691
+ throw new TypeError("createClient needs exactly one of key and app.");
3692
+ }
3693
+ function streamOpener(url, token) {
3694
+ return async (request, body, signal) => {
3695
+ const headers = { Accept: "text/event-stream" };
3696
+ const credential = await token();
3697
+ if (credential !== void 0) headers.Authorization = `Bearer ${credential}`;
3698
+ return sendRaw(url, request, {
3699
+ headers,
3700
+ body,
3701
+ signal
3702
+ });
3703
+ };
3704
+ }
3705
+
3706
+ export { OaizAppClient, OaizChat, OaizChatSessions, OaizClient, OaizEmbeddings, OaizEvents, OaizFilterBuilder, OaizLLM, OaizQueryBuilder, OaizRuns, OaizTools, OaizVoice, createClient };