@opengeni/sdk 0.32.1 → 0.33.1

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.
@@ -0,0 +1,2971 @@
1
+ // src/errors.ts
2
+ var OpenGeniApiError = class extends Error {
3
+ status;
4
+ code;
5
+ retryable;
6
+ correlationId;
7
+ /** True only when an uncontrolled transport failed after a mutation may have been accepted. */
8
+ outcomeUnknown;
9
+ body;
10
+ constructor(status, body, options = {}) {
11
+ const decoded = decodeApiErrorBody(body);
12
+ const correlationId = decoded?.requestId ?? boundedCorrelationId(options.correlationId);
13
+ const gatewayFailure = status >= 502 && status <= 504;
14
+ const fromResponse = options.mutation !== void 0;
15
+ const message = decoded?.message ?? (fromResponse ? "Request failed." : body || "(empty body)");
16
+ const displayMessage = options.displayMessage ?? (gatewayFailure && fromResponse ? "OpenGeni is temporarily unavailable \u2014 retry." : `OpenGeni API ${status}: ${message}`);
17
+ super(correlationId ? `${displayMessage} Reference: ${correlationId}.` : displayMessage);
18
+ this.name = "OpenGeniApiError";
19
+ this.status = status;
20
+ this.code = options.code ?? decoded?.code ?? (gatewayFailure && fromResponse ? "upstream_unavailable" : void 0);
21
+ this.retryable = options.retryable ?? decoded?.retryable ?? retryableApiStatus(status);
22
+ this.correlationId = correlationId;
23
+ this.outcomeUnknown = options.outcomeUnknown ?? (gatewayFailure && !!options.mutation && !decoded);
24
+ this.body = !fromResponse || decoded ? body : "";
25
+ }
26
+ };
27
+ function decodeApiErrorBody(body) {
28
+ if (!body) return null;
29
+ try {
30
+ const decoded = JSON.parse(body);
31
+ if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) return null;
32
+ const record = decoded;
33
+ const nested = record.error && typeof record.error === "object" && !Array.isArray(record.error) ? record.error : record;
34
+ const code = boundedApiField(nested.code);
35
+ const message = boundedApiField(nested.message);
36
+ const requestId = boundedCorrelationId(nested.requestId);
37
+ const retryable = typeof nested.retryable === "boolean" ? nested.retryable : void 0;
38
+ if (!code && !message && !requestId && retryable === void 0) return null;
39
+ return {
40
+ code,
41
+ message,
42
+ requestId,
43
+ retryable
44
+ };
45
+ } catch {
46
+ return null;
47
+ }
48
+ }
49
+ function boundedApiField(value) {
50
+ if (typeof value !== "string") return;
51
+ const bytes = new TextEncoder().encode(value);
52
+ return bytes.byteLength <= 512 ? value : new TextDecoder().decode(bytes.slice(0, 512));
53
+ }
54
+ function retryableApiStatus(status) {
55
+ return status === 408 || status === 409 || status === 425 || status === 429 || status >= 500;
56
+ }
57
+ function boundedCorrelationId(value) {
58
+ if (typeof value !== "string" || value.length > 128 || !/^[\w.:-]+$/.test(value)) {
59
+ return;
60
+ }
61
+ return value;
62
+ }
63
+ var OpenGeniSessionListCursorError = class extends OpenGeniApiError {
64
+ };
65
+ var OpenGeniApiContractMismatchError = class extends Error {
66
+ expected;
67
+ actual;
68
+ constructor(expected, actual) {
69
+ super(`OpenGeni API contract mismatch: client expects ${expected}, API serves ${actual}`);
70
+ this.name = "OpenGeniApiContractMismatchError";
71
+ this.expected = expected;
72
+ this.actual = actual;
73
+ }
74
+ };
75
+ var OpenGeniStreamError = class extends Error {
76
+ constructor(message) {
77
+ super(message);
78
+ this.name = "OpenGeniStreamError";
79
+ }
80
+ };
81
+ function isAbortError(error) {
82
+ return error instanceof DOMException && error.name === "AbortError" || error instanceof Error && error.name === "AbortError";
83
+ }
84
+ function isRetryableStreamError(error) {
85
+ if (error instanceof OpenGeniApiError) return error.retryable;
86
+ return error instanceof TypeError;
87
+ }
88
+
89
+ // src/sse.ts
90
+ async function* parseSseStream(stream) {
91
+ const reader = stream.getReader();
92
+ const decoder = new TextDecoder();
93
+ let buffer = "";
94
+ let id;
95
+ let event;
96
+ let dataLines = null;
97
+ const dispatch = () => {
98
+ const message = dataLines === null ? null : {
99
+ ...id !== void 0 ? { id } : {},
100
+ ...event !== void 0 ? { event } : {},
101
+ data: dataLines.join("\n")
102
+ };
103
+ id = void 0;
104
+ event = void 0;
105
+ dataLines = null;
106
+ return message;
107
+ };
108
+ const handleLine = (line) => {
109
+ if (line === "") {
110
+ return dispatch();
111
+ }
112
+ if (line.startsWith(":")) {
113
+ return null;
114
+ }
115
+ const colon = line.indexOf(":");
116
+ const field = colon === -1 ? line : line.slice(0, colon);
117
+ let value = colon === -1 ? "" : line.slice(colon + 1);
118
+ if (value.startsWith(" ")) {
119
+ value = value.slice(1);
120
+ }
121
+ if (field === "data") {
122
+ (dataLines ??= []).push(value);
123
+ } else if (field === "event") {
124
+ event = value;
125
+ } else if (field === "id") {
126
+ id = value;
127
+ }
128
+ return null;
129
+ };
130
+ try {
131
+ while (true) {
132
+ const { done, value } = await reader.read();
133
+ if (done) {
134
+ break;
135
+ }
136
+ buffer += decoder.decode(value, { stream: true });
137
+ let newline = buffer.indexOf("\n");
138
+ while (newline !== -1) {
139
+ let line = buffer.slice(0, newline);
140
+ buffer = buffer.slice(newline + 1);
141
+ if (line.endsWith("\r")) {
142
+ line = line.slice(0, -1);
143
+ }
144
+ const message = handleLine(line);
145
+ if (message) {
146
+ yield message;
147
+ }
148
+ newline = buffer.indexOf("\n");
149
+ }
150
+ }
151
+ } finally {
152
+ await reader.cancel().catch(() => {
153
+ });
154
+ reader.releaseLock();
155
+ }
156
+ }
157
+
158
+ // src/stream.ts
159
+ async function* streamSessionEvents(transport, options = {}) {
160
+ const signal = options.signal;
161
+ const reconnect = options.reconnect ?? true;
162
+ const baseDelayMs = options.reconnectDelayMs ?? 500;
163
+ const maxDelayMs = options.maxReconnectDelayMs ?? 1e4;
164
+ const maxAttempts = options.maxReconnectAttempts ?? Number.POSITIVE_INFINITY;
165
+ let cursor = options.after ?? 0;
166
+ let failedAttempts = 0;
167
+ let delayMs = baseDelayMs;
168
+ let everConnected = false;
169
+ while (true) {
170
+ if (signal?.aborted) break;
171
+ options.onStateChange?.(everConnected || failedAttempts > 0 ? "reconnecting" : "connecting");
172
+ const cursorAtOpen = cursor;
173
+ try {
174
+ const body = await transport.openStream(cursor, signal);
175
+ everConnected = true;
176
+ failedAttempts = 0;
177
+ delayMs = baseDelayMs;
178
+ await options.beforeLive?.();
179
+ options.onStateChange?.("live");
180
+ for await (const message of parseSseStream(body)) {
181
+ if (signal?.aborted) {
182
+ return;
183
+ }
184
+ const event = parseSessionEvent(message.data);
185
+ if (!event || event.sequence <= cursor) {
186
+ continue;
187
+ }
188
+ if (event.sequence > cursor + 1) {
189
+ for await (const missed of backfillEvents(transport, cursor, event.sequence - 1)) {
190
+ cursor = missed.sequence;
191
+ yield missed;
192
+ if (signal?.aborted) {
193
+ return;
194
+ }
195
+ }
196
+ }
197
+ cursor = event.sequence;
198
+ yield event;
199
+ }
200
+ if (!reconnect) {
201
+ return;
202
+ }
203
+ if (cursor === cursorAtOpen) {
204
+ await sleep(baseDelayMs, signal);
205
+ }
206
+ continue;
207
+ } catch (error) {
208
+ if (signal?.aborted || isAbortError(error)) {
209
+ return;
210
+ }
211
+ if (!reconnect || !isRetryableStreamError(error)) {
212
+ throw error;
213
+ }
214
+ failedAttempts += 1;
215
+ if (failedAttempts > maxAttempts) {
216
+ throw new OpenGeniStreamError(
217
+ `event stream gave up after ${maxAttempts} consecutive failed reconnect attempts: ${error instanceof Error ? error.message : String(error)}`
218
+ );
219
+ }
220
+ }
221
+ await sleep(delayMs, signal);
222
+ delayMs = Math.min(Math.max(delayMs * 2, baseDelayMs), maxDelayMs);
223
+ }
224
+ }
225
+ async function* backfillEvents(transport, fromExclusive, toInclusive) {
226
+ let cursor = fromExclusive;
227
+ while (cursor < toInclusive) {
228
+ const page = await transport.listEvents(cursor, Math.min(500, toInclusive - cursor));
229
+ const advancing = page.filter((event) => event.sequence > cursor && event.sequence <= toInclusive).sort((a, b) => a.sequence - b.sequence);
230
+ if (advancing.length === 0) {
231
+ throw new OpenGeniStreamError(
232
+ `event replay backfill stalled: expected sequences ${cursor + 1}..${toInclusive} but the replay endpoint returned none of them`
233
+ );
234
+ }
235
+ for (const event of advancing) {
236
+ if (event.sequence !== cursor + 1) {
237
+ throw new OpenGeniStreamError(
238
+ `event replay backfill is missing sequence ${cursor + 1} (replay endpoint skipped to ${event.sequence}); refusing to deliver with a gap`
239
+ );
240
+ }
241
+ cursor = event.sequence;
242
+ yield event;
243
+ }
244
+ }
245
+ }
246
+ function parseSessionEvent(data) {
247
+ let parsed;
248
+ try {
249
+ parsed = JSON.parse(data);
250
+ } catch {
251
+ return null;
252
+ }
253
+ if (typeof parsed !== "object" || parsed === null || typeof parsed.sequence !== "number" || typeof parsed.type !== "string" || typeof parsed.id !== "string") {
254
+ return null;
255
+ }
256
+ return parsed;
257
+ }
258
+ async function sleep(delayMs, signal) {
259
+ if (signal?.aborted || delayMs <= 0) {
260
+ return;
261
+ }
262
+ await new Promise((resolve) => {
263
+ const timer = setTimeout(done, delayMs);
264
+ function done() {
265
+ clearTimeout(timer);
266
+ signal?.removeEventListener("abort", done);
267
+ resolve();
268
+ }
269
+ signal?.addEventListener("abort", done, { once: true });
270
+ });
271
+ }
272
+
273
+ // src/workspace-control-stream.ts
274
+ async function* streamWorkspaceControlEvents(transport, options = {}) {
275
+ const signal = options.signal;
276
+ const reconnect = options.reconnect ?? true;
277
+ const baseDelayMs = options.reconnectDelayMs ?? 500;
278
+ const maxDelayMs = options.maxReconnectDelayMs ?? 1e4;
279
+ const maxAttempts = options.maxReconnectAttempts ?? Number.POSITIVE_INFINITY;
280
+ let cursor = options.after ?? 0;
281
+ let failures = 0;
282
+ let delayMs = baseDelayMs;
283
+ let everConnected = false;
284
+ for (; ; ) {
285
+ if (signal?.aborted) return;
286
+ options.onStateChange?.(everConnected || failures > 0 ? "reconnecting" : "connecting");
287
+ const cursorAtOpen = cursor;
288
+ try {
289
+ const body = await transport.openStream(cursor, signal);
290
+ everConnected = true;
291
+ failures = 0;
292
+ delayMs = baseDelayMs;
293
+ await options.beforeLive?.();
294
+ options.onStateChange?.("live");
295
+ for await (const message of parseSseStream(body)) {
296
+ if (signal?.aborted) return;
297
+ const event = parseWorkspaceControlEvent(message.data);
298
+ if (!event || event.sequence <= cursor) continue;
299
+ cursor = event.sequence;
300
+ yield event;
301
+ }
302
+ if (!reconnect) return;
303
+ if (cursor === cursorAtOpen) await sleep2(baseDelayMs, signal);
304
+ continue;
305
+ } catch (error) {
306
+ if (signal?.aborted || isAbortError(error)) return;
307
+ if (!reconnect || !isRetryableStreamError(error)) throw error;
308
+ failures += 1;
309
+ if (failures > maxAttempts) {
310
+ throw new OpenGeniStreamError(
311
+ `workspace control stream gave up after ${maxAttempts} reconnect attempts: ${error instanceof Error ? error.message : String(error)}`
312
+ );
313
+ }
314
+ }
315
+ await sleep2(delayMs, signal);
316
+ delayMs = Math.min(Math.max(delayMs * 2, baseDelayMs), maxDelayMs);
317
+ }
318
+ }
319
+ function parseWorkspaceControlEvent(data) {
320
+ let value;
321
+ try {
322
+ value = JSON.parse(data);
323
+ } catch {
324
+ return null;
325
+ }
326
+ if (typeof value !== "object" || value === null || value.type !== "workspace.control.changed" || typeof value.id !== "string" || typeof value.sequence !== "number") {
327
+ return null;
328
+ }
329
+ return value;
330
+ }
331
+ async function sleep2(delayMs, signal) {
332
+ if (signal?.aborted || delayMs <= 0) return;
333
+ await new Promise((resolve) => {
334
+ const timer = setTimeout(done, delayMs);
335
+ function done() {
336
+ clearTimeout(timer);
337
+ signal?.removeEventListener("abort", done);
338
+ resolve();
339
+ }
340
+ signal?.addEventListener("abort", done, { once: true });
341
+ });
342
+ }
343
+
344
+ // src/types.ts
345
+ var SESSION_EVENT_TYPES = [
346
+ "session.created",
347
+ // Defensive bounded projection for malformed/legacy oversized envelopes.
348
+ "session.event.envelope_omitted",
349
+ "session.status.changed",
350
+ "session.requiresAction",
351
+ "session.humanInput.requested",
352
+ "session.context.compaction.requested",
353
+ "session.context.compaction.started",
354
+ "session.context.compacted",
355
+ "session.context.compaction.skipped",
356
+ "session.context.cleared",
357
+ "user.message",
358
+ "user.pause",
359
+ "user.approvalDecision",
360
+ "user.humanInputResponse",
361
+ "turn.queued",
362
+ "turn.started",
363
+ "turn.completed",
364
+ "turn.failed",
365
+ "turn.cancelled",
366
+ "turn.superseded",
367
+ "turn.recovery.requested",
368
+ "turn.capacity_waiting",
369
+ "agent.message.delta",
370
+ "agent.message.completed",
371
+ "agent.reasoning.delta",
372
+ "agent.toolCall.created",
373
+ "agent.toolCall.output",
374
+ "agent.model.request",
375
+ "agent.model.usage",
376
+ "tool.auth_needed",
377
+ "credential.auth_needed",
378
+ "agent.updated",
379
+ "rig.setup.started",
380
+ "rig.setup.completed",
381
+ "rig.setup.skipped",
382
+ "rig.setup.failed",
383
+ "sandbox.operation.started",
384
+ "sandbox.operation.completed",
385
+ "sandbox.operation.failed",
386
+ "sandbox.command.output.delta",
387
+ "artifact.created",
388
+ "goal.set",
389
+ "goal.updated",
390
+ "goal.completed",
391
+ "goal.paused",
392
+ "goal.resumed",
393
+ "goal.cleared",
394
+ "goal.continuation",
395
+ "system.update.pending",
396
+ "system.update.delivered",
397
+ "system.update.superseded",
398
+ "system.update.cancelled",
399
+ "system.update.settled",
400
+ "session.control.paused",
401
+ "session.control.resumed",
402
+ "session.control.steer_requested",
403
+ "workspace.inference.paused",
404
+ "workspace.inference.resumed",
405
+ "session.queue.changed",
406
+ "session.queue.prompt.cancelled",
407
+ "session.queue.history",
408
+ "turn.event.rejected_late",
409
+ "memory.saved",
410
+ "memory.corrected",
411
+ // Channel-B desktop pixel-plane signals (mirror of contracts SessionEventType;
412
+ // the contract-parity test asserts sorted equality).
413
+ "stream.url.rotated",
414
+ "stream.opened",
415
+ "stream.closed",
416
+ "stream.revoked",
417
+ // Channel-B recording signals (P4.3 — "agent films itself proving the fix").
418
+ "recording.started",
419
+ "recording.available",
420
+ "recording.failed",
421
+ // Channel-A structured-service notifications (P4.4; mirror of contracts
422
+ // SessionEventType — the contract-parity test asserts sorted equality).
423
+ "fs.changed",
424
+ "git.changed",
425
+ "terminal.pty.started",
426
+ "terminal.pty.output.delta",
427
+ "terminal.pty.exited",
428
+ "session.title_set",
429
+ "session.mcp.approval_policy.updated",
430
+ "session.tool_policy.updated",
431
+ // Multi-account Codex (P1): the session's inference account changed.
432
+ "codex.account.switched",
433
+ // credential allocator metadata-only per-turn credential selection audit.
434
+ "codex.credential.selected",
435
+ // Bounded, identity-free deterministic shadow/replay decision.
436
+ "codex.fleet.decision",
437
+ // credential allocator durable zero-capacity wait lifecycle. These are system/runtime
438
+ // events, never synthetic user messages.
439
+ "codex.capacity.waiting",
440
+ "codex.capacity.resumed",
441
+ "codex.capacity.superseded",
442
+ // Sandbox durability observability (mirror of contracts SessionEventType):
443
+ // box lifecycle + manifest-env drift, attributable from the DB alone.
444
+ "sandbox.box.created",
445
+ "sandbox.box.lost",
446
+ "sandbox.box.terminated",
447
+ "sandbox.box.snapshot",
448
+ "sandbox.env.drift",
449
+ // Active-sandbox pointer reconcile (issue #341; announce-only; mirror of contracts
450
+ // SessionEventType — the contract-parity test asserts sorted equality).
451
+ "session.route.reconciled",
452
+ // Workbench v2 turn-end workspace capture (announce-only; mirror of contracts
453
+ // SessionEventType — the contract-parity test asserts sorted equality).
454
+ "workspace.revision.captured",
455
+ "workspace.revision.degraded",
456
+ // Connected Machine op-outcome observability (announce-only, quiet; mirror of
457
+ // contracts SessionEventType — the contract-parity test asserts sorted equality).
458
+ "machine.op.failed",
459
+ "machine.op.recovered",
460
+ // Connected Machine link-plane observability (announce-only, quiet; mirror of
461
+ // contracts SessionEventType — the contract-parity test asserts sorted equality).
462
+ "machine.link.lost",
463
+ "machine.link.restored",
464
+ "machine.runner.restarted"
465
+ ];
466
+ var KNOWN_PERMISSIONS = [
467
+ "account:read",
468
+ "account:admin",
469
+ "members:manage",
470
+ "workspace:create",
471
+ "billing:read",
472
+ "billing:manage",
473
+ "workspace:read",
474
+ "workspace:admin",
475
+ "sessions:create",
476
+ "sessions:read",
477
+ "sessions:control",
478
+ // sandbox workspace (mirror of @opengeni/contracts Permission). stream:view is
479
+ // strictly broader than sessions:read (un-redacted pixels); stream:control is
480
+ // the never-granted-v1 raw-input plane; stream:acknowledge is the secret-leak
481
+ // consent gate.
482
+ "stream:view",
483
+ "stream:control",
484
+ "stream:acknowledge",
485
+ "files:upload",
486
+ "files:read",
487
+ "files:write",
488
+ "terminal:attach",
489
+ "documents:manage",
490
+ "documents:search",
491
+ "scheduled_tasks:manage",
492
+ "scheduled_tasks:run",
493
+ "github:manage",
494
+ "github:use",
495
+ "api_keys:manage",
496
+ "connections:read",
497
+ "connections:write",
498
+ "environments:manage",
499
+ "environments:use",
500
+ "variable-sets:manage",
501
+ "variable-sets:use",
502
+ "mcp_servers:attach",
503
+ "toolspace:call",
504
+ "goals:manage",
505
+ "enrollments:read",
506
+ "enrollments:manage",
507
+ "rigs:use",
508
+ "rigs:manage",
509
+ "artifacts:read",
510
+ "artifacts:publish"
511
+ ];
512
+ var OPENGENI_API_CONTRACT_REVISION = "2026-07-workspace-artifacts-v1";
513
+ var OPENGENI_API_CONTRACT_HEADER = "x-opengeni-api-contract";
514
+ var OPENGENI_CORRELATION_HEADER = "x-opengeni-correlation-id";
515
+ var RETAINED_OUTPUT_DEFAULT_PAGE_BYTES = 256 * 1024;
516
+ var RETAINED_OUTPUT_MAX_PAGE_BYTES = 1024 * 1024;
517
+ var KNOWN_USAGE_EVENT_TYPES = [
518
+ "agent_run.created",
519
+ "agent_run.completed",
520
+ "model.tokens",
521
+ "model.cost",
522
+ "file.uploaded",
523
+ "file.deleted",
524
+ "document.indexed",
525
+ "scheduled_task.fired",
526
+ "api_key.request",
527
+ // sandbox warm-time metering (P2.1) — mirrors contracts UsageEventType.
528
+ "sandbox.warm_seconds",
529
+ "sandbox.warm_cost"
530
+ ];
531
+
532
+ // src/client.ts
533
+ function sessionListQuery(options) {
534
+ const { limit, parentSessionId } = options;
535
+ return {
536
+ ...limit === void 0 ? {} : { limit: String(limit) },
537
+ ...parentSessionId === void 0 ? {} : { parentSessionId: parentSessionId ?? "null" }
538
+ };
539
+ }
540
+ var OpenGeniClient = class {
541
+ baseUrl;
542
+ options;
543
+ fetchImpl;
544
+ constructor(options) {
545
+ this.baseUrl = options.baseUrl.replace(/\/+$/, "");
546
+ this.options = options;
547
+ this.fetchImpl = options.fetch ?? ((input, init) => fetch(input, init));
548
+ }
549
+ // --- Session lifecycle ---------------------------------------------------
550
+ /** Upload one ephemeral browser recording. This method never retries. */
551
+ async transcribeAudio(workspaceId, input) {
552
+ const correlationId = crypto.randomUUID();
553
+ const form = new FormData();
554
+ const filename = filenameForAudioMimeType(input.mimeType);
555
+ const audio = input.audio instanceof File ? input.audio : input.audio instanceof Uint8Array ? new File([Uint8Array.from(input.audio)], filename, { type: input.mimeType }) : new File([input.audio], filename, { type: input.mimeType || input.audio.type });
556
+ form.append("audio", audio, filename);
557
+ form.append("mimeType", input.mimeType);
558
+ if (input.durationSeconds !== void 0) {
559
+ form.append("durationSeconds", String(input.durationSeconds));
560
+ }
561
+ let response;
562
+ try {
563
+ response = await this.fetchImpl(this.url(`/v1/workspaces/${workspaceId}/transcriptions`), {
564
+ method: "POST",
565
+ headers: { ...this.headers(correlationId), Accept: "application/json" },
566
+ body: form,
567
+ ...input.signal ? { signal: input.signal } : {}
568
+ });
569
+ } catch (error) {
570
+ if (input.signal?.aborted) throw error;
571
+ throw mutationTransportError(correlationId);
572
+ }
573
+ assertApiContractResponse(response);
574
+ if (!response.ok) throw await apiErrorFromResponse(response, { method: "POST", correlationId });
575
+ await assertJsonResponse(response, { method: "POST", correlationId });
576
+ let body;
577
+ try {
578
+ body = await response.json();
579
+ } catch {
580
+ throw new OpenGeniApiError(response.status, "Invalid transcription response.", {
581
+ code: "invalid_response",
582
+ mutation: true,
583
+ correlationId
584
+ });
585
+ }
586
+ if (!isTranscribeAudioResponse(body)) {
587
+ throw new OpenGeniApiError(response.status, "Invalid transcription response.", {
588
+ code: "invalid_response",
589
+ mutation: true,
590
+ correlationId
591
+ });
592
+ }
593
+ return body;
594
+ }
595
+ async createSession(workspaceId, request) {
596
+ return await this.requestJson(
597
+ "POST",
598
+ `/v1/workspaces/${workspaceId}/sessions`,
599
+ request
600
+ );
601
+ }
602
+ async getNewSessionDraft(workspaceId) {
603
+ return await this.requestJson(
604
+ "GET",
605
+ `/v1/workspaces/${workspaceId}/new-session-draft`
606
+ );
607
+ }
608
+ async saveNewSessionDraft(workspaceId, request) {
609
+ return await this.requestJson(
610
+ "PUT",
611
+ `/v1/workspaces/${workspaceId}/new-session-draft`,
612
+ request
613
+ );
614
+ }
615
+ async getSession(workspaceId, sessionId) {
616
+ return await this.requestJson(
617
+ "GET",
618
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}`
619
+ );
620
+ }
621
+ async updateSession(workspaceId, sessionId, request) {
622
+ return await this.requestJson(
623
+ "PATCH",
624
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}`,
625
+ request
626
+ );
627
+ }
628
+ /** Replace the durable tool policy or explicitly adopt workspace defaults. */
629
+ async updateSessionToolPolicy(workspaceId, sessionId, request) {
630
+ return await this.requestJson(
631
+ "PUT",
632
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/tool-policy`,
633
+ request
634
+ );
635
+ }
636
+ /**
637
+ * Replace one attached MCP server's approval policy. The change is captured
638
+ * by the next claimed attempt; already-claimed work keeps its immutable
639
+ * policy snapshot.
640
+ */
641
+ async updateSessionMcpApprovalPolicy(workspaceId, sessionId, serverId, request) {
642
+ return await this.requestJson(
643
+ "PATCH",
644
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/mcp-servers/${encodeURIComponent(serverId)}/approval-policy`,
645
+ request
646
+ );
647
+ }
648
+ async listSessions(workspaceId, options = {}) {
649
+ if (options.search?.trim()) {
650
+ const page = await this.listSessionPage(workspaceId, options);
651
+ return [...page.pinned, ...page.sessions];
652
+ }
653
+ return await this.requestJson(
654
+ "GET",
655
+ `/v1/workspaces/${workspaceId}/sessions`,
656
+ void 0,
657
+ sessionListQuery(options)
658
+ );
659
+ }
660
+ /** Pin-aware ordinary-session page with a stable keyset cursor. */
661
+ async listSessionPage(workspaceId, options = {}) {
662
+ const search = options.search?.trim();
663
+ let response;
664
+ try {
665
+ response = await this.requestJson(
666
+ "GET",
667
+ `/v1/workspaces/${workspaceId}/sessions`,
668
+ void 0,
669
+ {
670
+ view: "page",
671
+ ...sessionListQuery(options),
672
+ ...options.cursor !== void 0 ? { cursor: options.cursor } : {},
673
+ ...search ? { search } : {},
674
+ ...options.pinsOnly ? { pinsOnly: "true" } : {}
675
+ }
676
+ );
677
+ } catch (error) {
678
+ if (error instanceof OpenGeniApiError && error.status === 410) {
679
+ throw new OpenGeniSessionListCursorError(error.status, error.body, {
680
+ ...error.code ? { code: error.code } : {},
681
+ retryable: error.retryable,
682
+ ...error.correlationId ? { correlationId: error.correlationId } : {},
683
+ outcomeUnknown: error.outcomeUnknown,
684
+ displayMessage: "The session list changed \u2014 refresh and try again."
685
+ });
686
+ }
687
+ throw error;
688
+ }
689
+ if (Array.isArray(response)) {
690
+ if (options.cursor) {
691
+ throw new Error("The connected OpenGeni API does not support stable session-page cursors");
692
+ }
693
+ if (search) {
694
+ throw new Error("The connected OpenGeni API does not support session search");
695
+ }
696
+ if (options.pinsOnly) {
697
+ throw new Error("The connected OpenGeni API does not support pins-only session lists");
698
+ }
699
+ return { pinned: [], sessions: response, nextCursor: null };
700
+ }
701
+ return response;
702
+ }
703
+ /** Set this authenticated member's personal workspace pin for a session. */
704
+ async updateSessionPin(workspaceId, sessionId, request) {
705
+ return await this.requestJson(
706
+ "PUT",
707
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/pin`,
708
+ request
709
+ );
710
+ }
711
+ async getSessionLineage(workspaceId, sessionId) {
712
+ return await this.requestJson(
713
+ "GET",
714
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/lineage`
715
+ );
716
+ }
717
+ async listTurns(workspaceId, sessionId, options = {}) {
718
+ return await this.requestJson(
719
+ "GET",
720
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/turns`,
721
+ void 0,
722
+ {
723
+ ...options.limit !== void 0 ? { limit: String(options.limit) } : {},
724
+ ...options.latestStarted ? { latestStarted: "1" } : {}
725
+ }
726
+ );
727
+ }
728
+ /** Newest turn that durably emitted `turn.started`, or null before any admission. */
729
+ async getLatestStartedTurn(workspaceId, sessionId) {
730
+ const turns = await this.listTurns(workspaceId, sessionId, { latestStarted: true });
731
+ return turns[0] ?? null;
732
+ }
733
+ // --- Bring-your-own-compute: Machines dashboard + metrics (M10) ------------
734
+ /**
735
+ * List the workspace's machines (the Machines dashboard). Each enrolled
736
+ * selfhosted machine carries its derived state + latest metrics +
737
+ * sharedSessionCount. Pass `sessionId` for an in-session view, which adds the
738
+ * session's synthetic Modal group box + the active-sandbox pointer.
739
+ */
740
+ async listMachines(workspaceId, options = {}) {
741
+ return await this.requestJson(
742
+ "GET",
743
+ `/v1/workspaces/${workspaceId}/machines`,
744
+ void 0,
745
+ {
746
+ ...options.sessionId !== void 0 ? { sessionId: options.sessionId } : {}
747
+ },
748
+ { signal: options.signal }
749
+ );
750
+ }
751
+ /**
752
+ * Read the downsampled (~1/min) metrics series for ONE machine over a time
753
+ * window (default 1h). The samples are oldest-first (a left-to-right chart).
754
+ */
755
+ async machineMetricsSeries(workspaceId, enrollmentId, options = {}) {
756
+ const response = await this.requestJson(
757
+ "GET",
758
+ `/v1/workspaces/${workspaceId}/machines/${enrollmentId}/metrics/series`,
759
+ void 0,
760
+ { ...options.window !== void 0 ? { window: options.window } : {} }
761
+ );
762
+ return response.samples;
763
+ }
764
+ // --- Self-hosted enrollment UX (design 11) --------------------------------
765
+ /**
766
+ * Resolve a pending device-enrollment flow by its user_code for the click-Grant
767
+ * approve page (EnrollmentConsent). NO workspace in the path — the server
768
+ * resolves the workspace from the (globally-unique-among-pending) code, then
769
+ * authorizes the caller against it (enrollments:read). Rejects (404) when the
770
+ * code is unknown/expired OR the caller lacks the grant — the two are
771
+ * indistinguishable by design (no cross-workspace disclosure). Does not consume
772
+ * the request.
773
+ */
774
+ async lookupDeviceEnrollment(userCode) {
775
+ return await this.requestJson(
776
+ "POST",
777
+ "/v1/enrollments/device/lookup",
778
+ { userCode }
779
+ );
780
+ }
781
+ /**
782
+ * Approve a pending device-enrollment flow (the LOUD consent step). `allowScreenControl`
783
+ * is the authoritative screen-control consent (whole-machine is mandatory/implicit).
784
+ * Lands an enrollment + a selfhosted sandbox and unblocks the agent's poll.
785
+ */
786
+ async approveDeviceEnrollment(workspaceId, request) {
787
+ return await this.requestJson(
788
+ "POST",
789
+ `/v1/workspaces/${workspaceId}/enrollments/device/approve`,
790
+ { userCode: request.userCode, allowScreenControl: request.allowScreenControl ?? false }
791
+ );
792
+ }
793
+ /** Deny a pending device-enrollment flow (the explicit "no" at the approve page). */
794
+ async denyDeviceEnrollment(workspaceId, request) {
795
+ return await this.requestJson(
796
+ "POST",
797
+ `/v1/workspaces/${workspaceId}/enrollments/device/deny`,
798
+ { userCode: request.userCode }
799
+ );
800
+ }
801
+ /**
802
+ * Mint a short-TTL headless enroll token (the `oget_` token) for the fleet /
803
+ * non-interactive enroll path. The returned `token` is SECRET — surface it once
804
+ * with a copy-now warning; it cannot be re-read. `allowScreenControl` bakes the
805
+ * screen-control consent into the token.
806
+ */
807
+ async mintEnrollToken(workspaceId, request = {}) {
808
+ return await this.requestJson(
809
+ "POST",
810
+ `/v1/workspaces/${workspaceId}/enrollments/token`,
811
+ { allowScreenControl: request.allowScreenControl ?? false }
812
+ );
813
+ }
814
+ /**
815
+ * Swap a session's active sandbox (the user-authenticated equivalent of the
816
+ * M7 `sandbox_swap` MCP tool). `target` is a `MachineView.sandboxId` from
817
+ * `listMachines`, or "session"/"default" to swap back to the session's own
818
+ * group box. Validation (ownership/liveness/epoch fence) is server-side; the
819
+ * result echoes the resulting pointer (`swapped: false` + `reason` on a
820
+ * rejected target or a lost epoch fence).
821
+ */
822
+ async swapActiveSandbox(workspaceId, sessionId, request) {
823
+ return await this.requestJson(
824
+ "POST",
825
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/active-sandbox`,
826
+ request
827
+ );
828
+ }
829
+ // --- Scheduled tasks -------------------------------------------------------
830
+ async listScheduledTasks(workspaceId, options = {}) {
831
+ return await this.requestJson(
832
+ "GET",
833
+ `/v1/workspaces/${workspaceId}/scheduled-tasks`,
834
+ void 0,
835
+ {
836
+ ...options.limit !== void 0 ? { limit: String(options.limit) } : {}
837
+ }
838
+ );
839
+ }
840
+ async getScheduledTask(workspaceId, taskId) {
841
+ return await this.requestJson(
842
+ "GET",
843
+ `/v1/workspaces/${workspaceId}/scheduled-tasks/${taskId}`
844
+ );
845
+ }
846
+ // --- Events: replay, send, stream ----------------------------------------
847
+ /**
848
+ * Return the events from one bounded page. With no cursor, this uses the safe
849
+ * semantic monitoring tail; pass explicit forensic options and a cursor for
850
+ * retained audit replay. Use `listEventPage` when projection, coverage, or
851
+ * resume-cursor facts are required.
852
+ */
853
+ async listEvents(workspaceId, sessionId, options = {}) {
854
+ return (await this.listEventPage(workspaceId, sessionId, options)).events;
855
+ }
856
+ async listEventPage(workspaceId, sessionId, options = {}) {
857
+ if (options.latest && ["includeTypes", "excludeTypes", "includeClasses", "excludeClasses"].some(
858
+ (name) => Object.prototype.hasOwnProperty.call(options, name)
859
+ )) {
860
+ throw new TypeError("latest cannot be combined with event filters");
861
+ }
862
+ if (options.resultMode === "compact" && !options.latest) {
863
+ throw new TypeError("resultMode=compact requires latest");
864
+ }
865
+ const listOptions = options.resultMode === "compact" ? null : options;
866
+ const correlationId = crypto.randomUUID();
867
+ const response = await this.fetchImpl(
868
+ this.url(`/v1/workspaces/${workspaceId}/sessions/${sessionId}/events`, {
869
+ ...listOptions?.after !== void 0 ? { after: String(listOptions.after) } : {},
870
+ ...listOptions?.before !== void 0 ? { before: String(listOptions.before) } : {},
871
+ ...listOptions?.limit !== void 0 ? { limit: String(listOptions.limit) } : {},
872
+ ...listOptions?.compact ? { compact: "1" } : {},
873
+ ...options.mode ? { mode: options.mode } : {},
874
+ ...listOptions?.direction ? { direction: listOptions.direction } : {},
875
+ ...options.payloadMode ? { payloadMode: options.payloadMode } : {},
876
+ ...options.resultMode ? { resultMode: options.resultMode } : {},
877
+ ...listOptions?.includeTypes?.length ? { includeTypes: listOptions.includeTypes.join(",") } : {},
878
+ ...listOptions?.excludeTypes?.length ? { excludeTypes: listOptions.excludeTypes.join(",") } : {},
879
+ ...listOptions?.includeClasses?.length ? { includeClasses: listOptions.includeClasses.join(",") } : {},
880
+ ...listOptions?.excludeClasses?.length ? { excludeClasses: listOptions.excludeClasses.join(",") } : {},
881
+ ...options.latest ? { latest: options.latest } : {}
882
+ }),
883
+ {
884
+ method: "GET",
885
+ headers: { ...this.headers(correlationId), Accept: "application/json" }
886
+ }
887
+ );
888
+ assertApiContractResponse(response);
889
+ if (!response.ok) {
890
+ throw await apiErrorFromResponse(response, { method: "GET", correlationId });
891
+ }
892
+ await assertJsonResponse(response, { method: "GET", correlationId });
893
+ const body = await response.json();
894
+ if (options.resultMode === "compact") {
895
+ return body;
896
+ }
897
+ const events = body;
898
+ const integerHeader = (name) => {
899
+ const raw = response.headers.get(name);
900
+ if (raw === null) return null;
901
+ const value = Number(raw);
902
+ return Number.isSafeInteger(value) && value >= 0 ? value : null;
903
+ };
904
+ const mode = response.headers.get("X-OpenGeni-Event-Mode") === "forensic" ? "forensic" : "monitoring";
905
+ const direction = response.headers.get("X-OpenGeni-Event-Direction") === "after" ? "after" : "before";
906
+ const payloadHeader = response.headers.get("X-OpenGeni-Payload-Mode");
907
+ const payloadMode = payloadHeader === "none" || payloadHeader === "full" ? payloadHeader : "summary";
908
+ const first = integerHeader("X-OpenGeni-Covered-First");
909
+ const last = integerHeader("X-OpenGeni-Covered-Last");
910
+ const bytes = integerHeader("X-OpenGeni-Page-Bytes") ?? new TextEncoder().encode(JSON.stringify(events)).byteLength;
911
+ const maxBytes = integerHeader("X-OpenGeni-Page-Max-Bytes") ?? 1024 * 1024;
912
+ const truncatedByHeader = response.headers.get("X-OpenGeni-Truncated-By");
913
+ const truncatedBy = truncatedByHeader === "count" || truncatedByHeader === "bytes" || truncatedByHeader === "http_bytes" ? truncatedByHeader : null;
914
+ return {
915
+ events,
916
+ mode,
917
+ payloadMode,
918
+ direction,
919
+ bytes,
920
+ maxBytes,
921
+ truncated: response.headers.get("X-OpenGeni-Page-Truncated") === "true",
922
+ hasMore: response.headers.get("X-OpenGeni-Has-More") === "true",
923
+ truncatedBy,
924
+ coveredSequence: first === null || last === null ? null : { first, last },
925
+ nextAfter: integerHeader("X-OpenGeni-Next-After"),
926
+ nextBefore: integerHeader("X-OpenGeni-Next-Before"),
927
+ forensicExact: response.headers.get("X-OpenGeni-Forensic-Exact") === "true"
928
+ };
929
+ }
930
+ /**
931
+ * Fetch the authoritative newest-sequence semantic result directly. This is
932
+ * the callback-loss recovery path: it reads one compact durable result and
933
+ * never creates a model turn. `latest: "receipt"` aliases `tool_receipt`;
934
+ * turn generation remains scoped retry metadata.
935
+ */
936
+ async getLatestEventResult(workspaceId, sessionId, options = { latest: "terminal" }) {
937
+ return await this.listEventPage(workspaceId, sessionId, {
938
+ ...options,
939
+ resultMode: "compact"
940
+ });
941
+ }
942
+ /** POST a user/control event to the session. Returns the accepted event. */
943
+ async sendEvent(workspaceId, sessionId, event) {
944
+ return await this.requestJson(
945
+ "POST",
946
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/events`,
947
+ event
948
+ );
949
+ }
950
+ async sendMessage(workspaceId, sessionId, message) {
951
+ const input = typeof message === "string" ? { text: message } : message;
952
+ const { clientEventId, ...payload } = input;
953
+ return await this.sendEvent(workspaceId, sessionId, {
954
+ type: "user.message",
955
+ ...clientEventId !== void 0 ? { clientEventId } : {},
956
+ payload
957
+ });
958
+ }
959
+ async pauseSession(workspaceId, sessionId, options = {}) {
960
+ return await this.controlSession(workspaceId, sessionId, {
961
+ action: "pause",
962
+ clientEventId: options.clientEventId ?? crypto.randomUUID(),
963
+ ...options.reason ? { reason: options.reason } : {},
964
+ ...options.expectedControlEtag ? { expectedControlEtag: options.expectedControlEtag } : {}
965
+ });
966
+ }
967
+ async sendApprovalDecision(workspaceId, sessionId, decision) {
968
+ const { clientEventId, ...payload } = decision;
969
+ return await this.sendEvent(workspaceId, sessionId, {
970
+ type: "user.approvalDecision",
971
+ ...clientEventId !== void 0 ? { clientEventId } : {},
972
+ payload
973
+ });
974
+ }
975
+ async listHumanInputRequests(workspaceId, sessionId, options = {}) {
976
+ const result = await this.requestJson(
977
+ "GET",
978
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/human-input-requests`,
979
+ void 0,
980
+ options.status ? { status: options.status } : void 0
981
+ );
982
+ return result.requests;
983
+ }
984
+ async getHumanInputRequest(workspaceId, sessionId, requestId) {
985
+ return await this.requestJson(
986
+ "GET",
987
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/human-input-requests/${requestId}`
988
+ );
989
+ }
990
+ async submitHumanInputResponse(workspaceId, sessionId, requestId, response, options = {}) {
991
+ return await this.sendEvent(workspaceId, sessionId, {
992
+ type: "user.humanInputResponse",
993
+ ...options.clientEventId ? { clientEventId: options.clientEventId } : {},
994
+ payload: { requestId, response }
995
+ });
996
+ }
997
+ /**
998
+ * Live-stream a session's events with automatic reconnect, resume from the
999
+ * last seen sequence, gap backfill, and duplicate suppression. See
1000
+ * {@link streamSessionEvents} for the delivery guarantees.
1001
+ */
1002
+ streamEvents(workspaceId, sessionId, options = {}) {
1003
+ return streamSessionEvents(this.eventStreamTransport(workspaceId, sessionId), options);
1004
+ }
1005
+ /** The transport `streamEvents` runs on; useful for custom streaming layers. */
1006
+ eventStreamTransport(workspaceId, sessionId) {
1007
+ return {
1008
+ openStream: async (after, signal) => await this.openEventStream(workspaceId, sessionId, {
1009
+ after,
1010
+ ...signal ? { signal } : {}
1011
+ }),
1012
+ listEvents: async (after, limit) => await this.listEvents(workspaceId, sessionId, { after, limit })
1013
+ };
1014
+ }
1015
+ /** Open one raw SSE connection (no reconnect). Most callers want `streamEvents`. */
1016
+ async openEventStream(workspaceId, sessionId, options = {}) {
1017
+ const url = this.url(`/v1/workspaces/${workspaceId}/sessions/${sessionId}/events/stream`, {
1018
+ after: String(options.after ?? 0)
1019
+ });
1020
+ const correlationId = crypto.randomUUID();
1021
+ const response = await this.fetchImpl(url, {
1022
+ method: "GET",
1023
+ headers: { ...this.headers(correlationId), Accept: "text/event-stream" },
1024
+ ...options.signal ? { signal: options.signal } : {}
1025
+ });
1026
+ assertApiContractResponse(response);
1027
+ if (!response.ok) {
1028
+ throw await apiErrorFromResponse(response, { method: "GET", correlationId });
1029
+ }
1030
+ if (!response.body) {
1031
+ throw new OpenGeniApiError(response.status, "SSE response did not include a readable body");
1032
+ }
1033
+ return response.body;
1034
+ }
1035
+ // --- Turn queue ------------------------------------------------------------
1036
+ async getQueue(workspaceId, sessionId) {
1037
+ return await this.requestJson(
1038
+ "GET",
1039
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/queue`
1040
+ );
1041
+ }
1042
+ async moveQueueItem(workspaceId, sessionId, turnId, request) {
1043
+ return await this.requestJson(
1044
+ "POST",
1045
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/queue/${turnId}/move`,
1046
+ request
1047
+ );
1048
+ }
1049
+ async editQueueItem(workspaceId, sessionId, turnId, request) {
1050
+ return await this.requestJson(
1051
+ "POST",
1052
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/queue/${turnId}/edit`,
1053
+ request
1054
+ );
1055
+ }
1056
+ async steerQueueItem(workspaceId, sessionId, turnId, request) {
1057
+ return await this.requestJson(
1058
+ "POST",
1059
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/queue/${turnId}/steer`,
1060
+ request
1061
+ );
1062
+ }
1063
+ async deleteQueueItem(workspaceId, sessionId, turnId, request) {
1064
+ return await this.requestJson(
1065
+ "POST",
1066
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/queue/${turnId}/delete`,
1067
+ request
1068
+ );
1069
+ }
1070
+ async getComposerDraft(workspaceId, sessionId) {
1071
+ return await this.requestJson(
1072
+ "GET",
1073
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/composer-draft`
1074
+ );
1075
+ }
1076
+ async saveComposerDraft(workspaceId, sessionId, request) {
1077
+ return await this.requestJson(
1078
+ "PUT",
1079
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/composer-draft`,
1080
+ request
1081
+ );
1082
+ }
1083
+ async controlSession(workspaceId, sessionId, request) {
1084
+ return await this.requestJson(
1085
+ "POST",
1086
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/control`,
1087
+ request
1088
+ );
1089
+ }
1090
+ async resumeSession(workspaceId, sessionId, options = {}) {
1091
+ return await this.controlSession(workspaceId, sessionId, {
1092
+ action: "resume",
1093
+ clientEventId: options.clientEventId ?? crypto.randomUUID(),
1094
+ ...options.reason ? { reason: options.reason } : {},
1095
+ ...options.expectedControlEtag ? { expectedControlEtag: options.expectedControlEtag } : {}
1096
+ });
1097
+ }
1098
+ async setWorkspaceInferenceState(workspaceId, request) {
1099
+ return await this.requestJson(
1100
+ "POST",
1101
+ `/v1/workspaces/${workspaceId}/inference-control`,
1102
+ request
1103
+ );
1104
+ }
1105
+ async listWorkspaceControlEvents(workspaceId, options = {}) {
1106
+ return (await this.listWorkspaceControlEventPage(workspaceId, options)).events;
1107
+ }
1108
+ /** Count/byte-bounded page plus an explicit continuation cursor. */
1109
+ async listWorkspaceControlEventPage(workspaceId, options = {}) {
1110
+ const correlationId = crypto.randomUUID();
1111
+ const response = await this.fetchImpl(
1112
+ this.url(`/v1/workspaces/${workspaceId}/control-events`, {
1113
+ ...options.after !== void 0 ? { after: String(options.after) } : {},
1114
+ ...options.limit !== void 0 ? { limit: String(options.limit) } : {}
1115
+ }),
1116
+ {
1117
+ method: "GET",
1118
+ headers: { ...this.headers(correlationId), Accept: "application/json" }
1119
+ }
1120
+ );
1121
+ assertApiContractResponse(response);
1122
+ if (!response.ok) {
1123
+ throw await apiErrorFromResponse(response, { method: "GET", correlationId });
1124
+ }
1125
+ await assertJsonResponse(response, { method: "GET", correlationId });
1126
+ const events = await response.json();
1127
+ const bytesHeader = response.headers.get("X-OpenGeni-Page-Bytes");
1128
+ const nextHeader = response.headers.get("X-OpenGeni-Next-After");
1129
+ const parsedBytes = bytesHeader === null ? Number.NaN : Number(bytesHeader);
1130
+ const parsedNext = nextHeader === null ? null : Number(nextHeader);
1131
+ return {
1132
+ events,
1133
+ bytes: Number.isSafeInteger(parsedBytes) && parsedBytes >= 0 ? parsedBytes : new TextEncoder().encode(JSON.stringify(events)).byteLength,
1134
+ truncated: response.headers.get("X-OpenGeni-Page-Truncated") === "true",
1135
+ nextAfter: parsedNext !== null && Number.isSafeInteger(parsedNext) && parsedNext >= 0 ? parsedNext : null
1136
+ };
1137
+ }
1138
+ streamWorkspaceControlEvents(workspaceId, options = {}) {
1139
+ return streamWorkspaceControlEvents(this.workspaceControlStreamTransport(workspaceId), options);
1140
+ }
1141
+ workspaceControlStreamTransport(workspaceId) {
1142
+ return {
1143
+ openStream: async (after, signal) => await this.openWorkspaceControlEventStream(workspaceId, {
1144
+ after,
1145
+ ...signal ? { signal } : {}
1146
+ })
1147
+ };
1148
+ }
1149
+ async openWorkspaceControlEventStream(workspaceId, options = {}) {
1150
+ const correlationId = crypto.randomUUID();
1151
+ const response = await this.fetchImpl(
1152
+ this.url(`/v1/workspaces/${workspaceId}/control-events/stream`, {
1153
+ after: String(options.after ?? 0)
1154
+ }),
1155
+ {
1156
+ method: "GET",
1157
+ headers: { ...this.headers(correlationId), Accept: "text/event-stream" },
1158
+ ...options.signal ? { signal: options.signal } : {}
1159
+ }
1160
+ );
1161
+ assertApiContractResponse(response);
1162
+ if (!response.ok) {
1163
+ throw await apiErrorFromResponse(response, { method: "GET", correlationId });
1164
+ }
1165
+ if (!response.body) {
1166
+ throw new OpenGeniApiError(response.status, "SSE response did not include a readable body");
1167
+ }
1168
+ return response.body;
1169
+ }
1170
+ /**
1171
+ * Steer: atomically put this prompt at the head and supersede the current
1172
+ * inference. The client performs one request and renders server order.
1173
+ */
1174
+ async steerMessage(workspaceId, sessionId, message) {
1175
+ const input = typeof message === "string" ? { text: message } : message;
1176
+ return await this.requestJson(
1177
+ "POST",
1178
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/steer`,
1179
+ input
1180
+ );
1181
+ }
1182
+ // --- Goals -------------------------------------------------------------------
1183
+ /** The session's goal. 404s when the session never had one. */
1184
+ async getGoal(workspaceId, sessionId) {
1185
+ return await this.requestJson(
1186
+ "GET",
1187
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/goal`
1188
+ );
1189
+ }
1190
+ async updateGoal(workspaceId, sessionId, request) {
1191
+ return await this.requestJson(
1192
+ "PATCH",
1193
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/goal`,
1194
+ request
1195
+ );
1196
+ }
1197
+ async deleteGoal(workspaceId, sessionId) {
1198
+ await this.requestVoid("DELETE", `/v1/workspaces/${workspaceId}/sessions/${sessionId}/goal`);
1199
+ }
1200
+ /** Pause the goal loop: the session stops self-continuing until resumed. */
1201
+ async pauseGoal(workspaceId, sessionId, options = {}) {
1202
+ return await this.updateGoal(workspaceId, sessionId, {
1203
+ status: "paused",
1204
+ ...options.rationale !== void 0 ? { rationale: options.rationale } : {}
1205
+ });
1206
+ }
1207
+ /** Resume a paused goal: resets counters and re-arms the continuation loop. */
1208
+ async resumeGoal(workspaceId, sessionId) {
1209
+ return await this.updateGoal(workspaceId, sessionId, { status: "active" });
1210
+ }
1211
+ // --- Operator context controls (/clear, /compact) ---------------------------
1212
+ /**
1213
+ * Clear the session's conversation context. Destructive and audit-preserving:
1214
+ * the server supersedes (never deletes) the live history and emits a
1215
+ * `session.context.cleared` event. Refused (409) while a turn is in flight or
1216
+ * awaiting action. `confirm:true` is sent so an accidental call cannot wipe
1217
+ * context — the destructive intent is explicit on the wire.
1218
+ */
1219
+ async clearSessionContext(workspaceId, sessionId) {
1220
+ await this.requestVoid(
1221
+ "POST",
1222
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/context/clear`,
1223
+ { confirm: true }
1224
+ );
1225
+ }
1226
+ /** Request one durable portable compaction at the next safe model boundary. */
1227
+ async compactSessionContext(workspaceId, sessionId) {
1228
+ return await this.requestJson(
1229
+ "POST",
1230
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/context/compact`,
1231
+ {}
1232
+ );
1233
+ }
1234
+ // --- Channel-A structured services (P4.4) ------------------------------------
1235
+ // FileSystem (Pierre tree), Git (Pierre diff), Terminal (exec + PTY). Each is a
1236
+ // synchronous API-direct point query; the fs.changed/git.changed/terminal.pty.*
1237
+ // notifications + the PTY output stream arrive on the existing event SSE.
1238
+ /** FileSystem: list a directory tree (feeds the Pierre file tree). */
1239
+ async fsList(workspaceId, sessionId, request = {}, options = {}) {
1240
+ return await this.requestJson(
1241
+ "POST",
1242
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/fs/list`,
1243
+ request,
1244
+ {},
1245
+ options
1246
+ );
1247
+ }
1248
+ /** FileSystem: read a file (text or base64; binary-safe, size-capped). */
1249
+ async fsRead(workspaceId, sessionId, request, options = {}) {
1250
+ return await this.requestJson(
1251
+ "POST",
1252
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/fs/read`,
1253
+ request,
1254
+ {},
1255
+ options
1256
+ );
1257
+ }
1258
+ /** FileSystem: write a file (last-writer-wins; emits fs.changed). */
1259
+ async fsWrite(workspaceId, sessionId, request) {
1260
+ return await this.requestJson(
1261
+ "POST",
1262
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/fs/write`,
1263
+ request
1264
+ );
1265
+ }
1266
+ /** FileSystem: delete a path (emits fs.changed). */
1267
+ async fsDelete(workspaceId, sessionId, request) {
1268
+ return await this.requestJson(
1269
+ "POST",
1270
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/fs/delete`,
1271
+ request
1272
+ );
1273
+ }
1274
+ /** FileSystem: move/rename a path (emits fs.changed; 409 if destination exists and overwrite is false). */
1275
+ async fsMove(workspaceId, sessionId, request) {
1276
+ return await this.requestJson(
1277
+ "POST",
1278
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/fs/move`,
1279
+ request
1280
+ );
1281
+ }
1282
+ /** FileSystem: create a directory (emits fs.changed; recursive defaults to true). */
1283
+ async fsMkdir(workspaceId, sessionId, request) {
1284
+ return await this.requestJson(
1285
+ "POST",
1286
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/fs/mkdir`,
1287
+ request
1288
+ );
1289
+ }
1290
+ /** Git: working-tree/index status (the Pierre file-status feed). */
1291
+ async gitStatus(workspaceId, sessionId, request = {}, options = {}) {
1292
+ return await this.requestJson(
1293
+ "POST",
1294
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/git/status`,
1295
+ request,
1296
+ {},
1297
+ options
1298
+ );
1299
+ }
1300
+ /** Git: structured diff hunks (the Pierre diff feed). */
1301
+ async gitDiff(workspaceId, sessionId, request = {}, options = {}) {
1302
+ return await this.requestJson(
1303
+ "POST",
1304
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/git/diff`,
1305
+ request,
1306
+ {},
1307
+ options
1308
+ );
1309
+ }
1310
+ /** Git: commit log. */
1311
+ async gitLog(workspaceId, sessionId, request = {}) {
1312
+ return await this.requestJson(
1313
+ "POST",
1314
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/git/log`,
1315
+ request
1316
+ );
1317
+ }
1318
+ /** Git: show a commit (diff vs first parent) or fetch a raw blob at a ref. */
1319
+ async gitShow(workspaceId, sessionId, request) {
1320
+ return await this.requestJson(
1321
+ "POST",
1322
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/git/show`,
1323
+ request
1324
+ );
1325
+ }
1326
+ /** Workspace capture: the latest turn-end snapshot of the session's workspace
1327
+ * (tree + per-repo diff + file after-image refs), served from durable storage
1328
+ * WITHOUT warming a machine — the workbench cold-paint source. Returns
1329
+ * `{available:false}` when no capture exists yet (fall back to the live path). */
1330
+ async getWorkspaceCapture(workspaceId, sessionId, options = {}) {
1331
+ return await this.requestJson(
1332
+ "GET",
1333
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/workspace/capture`,
1334
+ void 0,
1335
+ {},
1336
+ options
1337
+ );
1338
+ }
1339
+ /** Workspace capture: a single file's after-image from the capture (revision
1340
+ * pins a specific one; omitted → latest). Content is inline for small files,
1341
+ * else a short-TTL signed URL; a tooLarge file returns metadata only. */
1342
+ async getWorkspaceCaptureFile(workspaceId, sessionId, path, revision, options = {}) {
1343
+ const query = { path };
1344
+ if (revision !== void 0) query.revision = String(revision);
1345
+ return await this.requestJson(
1346
+ "GET",
1347
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/workspace/capture/file`,
1348
+ void 0,
1349
+ query,
1350
+ options
1351
+ );
1352
+ }
1353
+ /** Terminal: run a bounded command, returning buffered stdout/stderr inline. */
1354
+ async terminalExec(workspaceId, sessionId, request) {
1355
+ return await this.requestJson(
1356
+ "POST",
1357
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/terminal/exec`,
1358
+ request
1359
+ );
1360
+ }
1361
+ /** Terminal: open an interactive PTY. Output streams on the event SSE as
1362
+ * terminal.pty.output.delta; drive it with terminalPtyWrite. */
1363
+ async terminalPtyOpen(workspaceId, sessionId, request = {}) {
1364
+ return await this.requestJson(
1365
+ "POST",
1366
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/terminal/pty`,
1367
+ request
1368
+ );
1369
+ }
1370
+ /** Terminal: send stdin to an open PTY (output rides A1). */
1371
+ async terminalPtyWrite(workspaceId, sessionId, request) {
1372
+ await this.requestVoid(
1373
+ "POST",
1374
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/terminal/pty/write`,
1375
+ request
1376
+ );
1377
+ }
1378
+ /** Terminal: resize an open PTY. */
1379
+ async terminalPtyResize(workspaceId, sessionId, request) {
1380
+ await this.requestVoid(
1381
+ "POST",
1382
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/terminal/pty/resize`,
1383
+ request
1384
+ );
1385
+ }
1386
+ /** Terminal: close an open PTY (idempotent). */
1387
+ async terminalPtyClose(workspaceId, sessionId, request) {
1388
+ await this.requestVoid(
1389
+ "POST",
1390
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/terminal/pty/close`,
1391
+ request
1392
+ );
1393
+ }
1394
+ // --- Stream surfacing: capability negotiation + viewer lifecycle (Phase 5) ---
1395
+ // The capability doc is the single source of UI truth (degradation is always a
1396
+ // value, never a crash). The desktop pixel plane (Channel B) is gated behind an
1397
+ // un-redacted-acknowledgment + a viewer holder; the structured terminal/files/
1398
+ // git surfaces (Channel A) ride the methods above and the event SSE.
1399
+ /** Read the negotiated capability doc for a session WITHOUT acquiring a viewer
1400
+ * holder (no warm, no spawn). Drives capability-gated rendering: which
1401
+ * surfaces mount, the per-surface unavailability reasons, and the lease
1402
+ * liveness the client polls on while `cold`/`warming`. The desktop URL/token
1403
+ * are minted in-process only when the box is warm AND the principal has
1404
+ * acknowledged the un-redacted plane. */
1405
+ async getStreamCapabilities(workspaceId, sessionId, options = {}) {
1406
+ return await this.requestJson(
1407
+ "GET",
1408
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/stream-capabilities`,
1409
+ void 0,
1410
+ {},
1411
+ options
1412
+ );
1413
+ }
1414
+ /** Record the calling principal's acknowledgment of the un-redacted desktop
1415
+ * pixel plane (and, when the box is shared, the shared-exposure disclosure).
1416
+ * The desktop viewer-attach path returns 409 until this is recorded. */
1417
+ async acknowledgeStream(workspaceId, sessionId, request = {}) {
1418
+ return await this.requestJson(
1419
+ "POST",
1420
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/stream-capabilities/acknowledge`,
1421
+ request
1422
+ );
1423
+ }
1424
+ /** Attach a viewer holder (refcounted liveness — keeps the box warm while
1425
+ * watched/used), spinning the box up in-process when cold, and mint the scoped
1426
+ * direct-to-provider URLs for the requested plane(s). `request.desktop:true`
1427
+ * opts into the un-redacted pixel plane and mints the noVNC URL — that plane
1428
+ * alone throws `OpenGeniApiError(409)` when the un-redacted/shared
1429
+ * acknowledgment is missing (the consent gate). A terminal-only attach
1430
+ * (`desktop` omitted/false) warms the box + mints the pty-ws terminal cell with
1431
+ * NO consent gate. An omitted `viewerId` mints a fresh one. */
1432
+ async attachViewer(workspaceId, sessionId, request = {}) {
1433
+ return await this.requestJson(
1434
+ "POST",
1435
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/viewers`,
1436
+ request
1437
+ );
1438
+ }
1439
+ /** Heartbeat a viewer holder (Channel-A app-level liveness). A closed laptop
1440
+ * stops sending these → the reaper drops the holder within ~90s. Echoes
1441
+ * `leaseEpoch` so a superseded epoch is rejected (`alive:false` → re-attach). */
1442
+ async heartbeatViewer(workspaceId, sessionId, viewerId, request) {
1443
+ return await this.requestJson(
1444
+ "POST",
1445
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/viewers/${viewerId}/heartbeat`,
1446
+ request
1447
+ );
1448
+ }
1449
+ /** Detach a viewer (delete this holder; idempotent delete-my-row). */
1450
+ async detachViewer(workspaceId, sessionId, viewerId) {
1451
+ await this.requestVoid(
1452
+ "DELETE",
1453
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/viewers/${viewerId}`
1454
+ );
1455
+ }
1456
+ // --- Access + workspaces -----------------------------------------------------
1457
+ /**
1458
+ * The deployment's public client bootstrap config: the host-exposed models
1459
+ * (provider-grouped in `models`, flat in `allowedModels` for back-compat),
1460
+ * reasoning efforts, MCP servers, file-upload limits, and how the client is
1461
+ * expected to authenticate. Drives a composer's model picker without prior
1462
+ * knowledge of the host setup; safe to call before any auth is established.
1463
+ */
1464
+ async getClientConfig() {
1465
+ const config = await this.requestJson("GET", "/v1/config/client");
1466
+ if (config.apiContractRevision !== OPENGENI_API_CONTRACT_REVISION) {
1467
+ throw new OpenGeniApiContractMismatchError(
1468
+ OPENGENI_API_CONTRACT_REVISION,
1469
+ String(config.apiContractRevision || "(missing)")
1470
+ );
1471
+ }
1472
+ return config;
1473
+ }
1474
+ /** Authenticated model definitions plus workspace-specific selectability. */
1475
+ async getWorkspaceModelCatalog(workspaceId) {
1476
+ return await this.requestJson(
1477
+ "GET",
1478
+ `/v1/workspaces/${workspaceId}/model-catalog`
1479
+ );
1480
+ }
1481
+ /** The caller's access context: subject, account + workspace grants, defaults. */
1482
+ async getAccessContext() {
1483
+ return await this.requestJson("GET", "/v1/access/me");
1484
+ }
1485
+ async listWorkspaces() {
1486
+ return await this.requestJson("GET", "/v1/workspaces");
1487
+ }
1488
+ async createWorkspace(request) {
1489
+ return await this.requestJson("POST", "/v1/workspaces", request);
1490
+ }
1491
+ async getWorkspace(workspaceId) {
1492
+ return await this.requestJson("GET", `/v1/workspaces/${workspaceId}`);
1493
+ }
1494
+ /** Read-time, secret-safe inventory of policy heads and visible workspace knowledge. */
1495
+ async getWorkspaceState(workspaceId) {
1496
+ return await this.requestJson(
1497
+ "GET",
1498
+ `/v1/workspaces/${workspaceId}/workspace-state`
1499
+ );
1500
+ }
1501
+ async updateWorkspace(workspaceId, request) {
1502
+ return await this.requestJson("PATCH", `/v1/workspaces/${workspaceId}`, request);
1503
+ }
1504
+ /** Inspect immutable instruction-policy history, active heads, and activation audit evidence. */
1505
+ async listWorkspaceInstructionPolicies(workspaceId, options = {}) {
1506
+ const params = new URLSearchParams();
1507
+ if (options.kind !== void 0) params.set("kind", options.kind);
1508
+ if (options.scope !== void 0) params.set("scope", options.scope);
1509
+ if (options.roleKey !== void 0) params.set("roleKey", options.roleKey);
1510
+ if (options.afterRevision !== void 0) {
1511
+ params.set("afterRevision", String(options.afterRevision));
1512
+ }
1513
+ if (options.limit !== void 0) params.set("limit", String(options.limit));
1514
+ const query = params.toString();
1515
+ return await this.requestJson(
1516
+ "GET",
1517
+ `/v1/workspaces/${workspaceId}/instruction-policies${query ? `?${query}` : ""}`
1518
+ );
1519
+ }
1520
+ async getWorkspaceInstructionPolicyRevision(workspaceId, revisionId) {
1521
+ return await this.requestJson(
1522
+ "GET",
1523
+ `/v1/workspaces/${workspaceId}/instruction-policies/${encodeURIComponent(revisionId)}`
1524
+ );
1525
+ }
1526
+ async createWorkspaceInstructionPolicyDraft(workspaceId, request) {
1527
+ return await this.requestJson(
1528
+ "POST",
1529
+ `/v1/workspaces/${workspaceId}/instruction-policies/drafts`,
1530
+ request
1531
+ );
1532
+ }
1533
+ /** Import the stored legacy workspace override as an inactive charter draft. */
1534
+ async importLegacyWorkspaceInstructionPolicyDraft(workspaceId, request = {}) {
1535
+ return await this.requestJson(
1536
+ "POST",
1537
+ `/v1/workspaces/${workspaceId}/instruction-policies/import-legacy`,
1538
+ request
1539
+ );
1540
+ }
1541
+ async diffWorkspaceInstructionPolicyRevisions(workspaceId, request) {
1542
+ const params = new URLSearchParams({
1543
+ fromRevisionId: request.fromRevisionId,
1544
+ toRevisionId: request.toRevisionId
1545
+ });
1546
+ return await this.requestJson(
1547
+ "GET",
1548
+ `/v1/workspaces/${workspaceId}/instruction-policies/diff?${params}`
1549
+ );
1550
+ }
1551
+ async activateWorkspaceInstructionPolicyRevision(workspaceId, revisionId, request) {
1552
+ return await this.requestJson(
1553
+ "POST",
1554
+ `/v1/workspaces/${workspaceId}/instruction-policies/${encodeURIComponent(revisionId)}/activate`,
1555
+ request
1556
+ );
1557
+ }
1558
+ async rollbackWorkspaceInstructionPolicyRevision(workspaceId, request) {
1559
+ return await this.requestJson(
1560
+ "POST",
1561
+ `/v1/workspaces/${workspaceId}/instruction-policies/rollback`,
1562
+ request
1563
+ );
1564
+ }
1565
+ async listPreferenceRegistry(workspaceId, options = {}) {
1566
+ const params = new URLSearchParams();
1567
+ if (options.scope) params.set("scope", options.scope);
1568
+ if (options.status) params.set("status", options.status);
1569
+ if (options.limit !== void 0) params.set("limit", String(options.limit));
1570
+ const query = params.toString();
1571
+ return await this.requestJson(
1572
+ "GET",
1573
+ `/v1/workspaces/${workspaceId}/preferences${query ? `?${query}` : ""}`
1574
+ );
1575
+ }
1576
+ async getPreferenceRegistry(workspaceId, preferenceId) {
1577
+ return await this.requestJson(
1578
+ "GET",
1579
+ `/v1/workspaces/${workspaceId}/preferences/${encodeURIComponent(preferenceId)}`
1580
+ );
1581
+ }
1582
+ async createPreferenceRegistryProposal(workspaceId, request) {
1583
+ return await this.requestJson(
1584
+ "POST",
1585
+ `/v1/workspaces/${workspaceId}/preferences/proposals`,
1586
+ request
1587
+ );
1588
+ }
1589
+ async activatePreferenceRegistryRevision(workspaceId, preferenceId, request) {
1590
+ return await this.requestJson(
1591
+ "POST",
1592
+ `/v1/workspaces/${workspaceId}/preferences/${encodeURIComponent(preferenceId)}/activate`,
1593
+ request
1594
+ );
1595
+ }
1596
+ async correctPreferenceRegistry(workspaceId, preferenceId, request) {
1597
+ return await this.requestJson(
1598
+ "POST",
1599
+ `/v1/workspaces/${workspaceId}/preferences/${encodeURIComponent(preferenceId)}/correct`,
1600
+ request
1601
+ );
1602
+ }
1603
+ async changePreferenceRegistryScope(workspaceId, preferenceId, request) {
1604
+ return await this.requestJson(
1605
+ "POST",
1606
+ `/v1/workspaces/${workspaceId}/preferences/${encodeURIComponent(preferenceId)}/scope`,
1607
+ request
1608
+ );
1609
+ }
1610
+ async deactivatePreferenceRegistry(workspaceId, preferenceId, request) {
1611
+ return await this.requestJson(
1612
+ "POST",
1613
+ `/v1/workspaces/${workspaceId}/preferences/${encodeURIComponent(preferenceId)}/deactivate`,
1614
+ request
1615
+ );
1616
+ }
1617
+ async supersedePreferenceRegistry(workspaceId, preferenceId, request) {
1618
+ return await this.requestJson(
1619
+ "POST",
1620
+ `/v1/workspaces/${workspaceId}/preferences/${encodeURIComponent(preferenceId)}/supersede`,
1621
+ request
1622
+ );
1623
+ }
1624
+ async rejectPreferenceRegistryProposal(workspaceId, preferenceId, request) {
1625
+ return await this.requestJson(
1626
+ "POST",
1627
+ `/v1/workspaces/${workspaceId}/preferences/${encodeURIComponent(preferenceId)}/reject`,
1628
+ request
1629
+ );
1630
+ }
1631
+ async getPreferenceRegistrySummary(workspaceId) {
1632
+ return await this.requestJson(
1633
+ "GET",
1634
+ `/v1/workspaces/${workspaceId}/preferences/summary`
1635
+ );
1636
+ }
1637
+ async getPreferenceRegistryFullContent(workspaceId, retrievalHandle) {
1638
+ return await this.requestJson(
1639
+ "POST",
1640
+ `/v1/workspaces/${workspaceId}/preferences/full-content`,
1641
+ { retrievalHandle }
1642
+ );
1643
+ }
1644
+ /**
1645
+ * Delete a workspace and everything in it. Refused (409) for the account's
1646
+ * only workspace and while it still has a running session. Irreversible.
1647
+ */
1648
+ async deleteWorkspace(workspaceId) {
1649
+ await this.requestVoid("DELETE", `/v1/workspaces/${workspaceId}`);
1650
+ }
1651
+ // --- Members ("People with access") -------------------------------------------
1652
+ /** The workspace's members (user + api_key subjects). */
1653
+ async listWorkspaceMembers(workspaceId) {
1654
+ const response = await this.requestJson(
1655
+ "GET",
1656
+ `/v1/workspaces/${workspaceId}/members`
1657
+ );
1658
+ return response.members;
1659
+ }
1660
+ /**
1661
+ * Add an already-registered user by email. 404s when no user with that email
1662
+ * exists (email invites for unknown users are deferred).
1663
+ */
1664
+ async addWorkspaceMember(workspaceId, request) {
1665
+ return await this.requestJson(
1666
+ "POST",
1667
+ `/v1/workspaces/${workspaceId}/members`,
1668
+ request
1669
+ );
1670
+ }
1671
+ async updateWorkspaceMember(workspaceId, subjectId, request) {
1672
+ return await this.requestJson(
1673
+ "PATCH",
1674
+ `/v1/workspaces/${workspaceId}/members/${encodeURIComponent(subjectId)}`,
1675
+ request
1676
+ );
1677
+ }
1678
+ /**
1679
+ * Remove a member. Refused (409) for your own membership and for the last
1680
+ * member who can still manage the workspace.
1681
+ */
1682
+ async removeWorkspaceMember(workspaceId, subjectId) {
1683
+ await this.requestVoid(
1684
+ "DELETE",
1685
+ `/v1/workspaces/${workspaceId}/members/${encodeURIComponent(subjectId)}`
1686
+ );
1687
+ }
1688
+ // --- Scheduled tasks (write + runs) -------------------------------------------
1689
+ async createScheduledTask(workspaceId, request) {
1690
+ return await this.requestJson(
1691
+ "POST",
1692
+ `/v1/workspaces/${workspaceId}/scheduled-tasks`,
1693
+ request
1694
+ );
1695
+ }
1696
+ async updateScheduledTask(workspaceId, taskId, request) {
1697
+ return await this.requestJson(
1698
+ "PATCH",
1699
+ `/v1/workspaces/${workspaceId}/scheduled-tasks/${taskId}`,
1700
+ request
1701
+ );
1702
+ }
1703
+ async pauseScheduledTask(workspaceId, taskId) {
1704
+ return await this.requestJson(
1705
+ "POST",
1706
+ `/v1/workspaces/${workspaceId}/scheduled-tasks/${taskId}/pause`
1707
+ );
1708
+ }
1709
+ async resumeScheduledTask(workspaceId, taskId) {
1710
+ return await this.requestJson(
1711
+ "POST",
1712
+ `/v1/workspaces/${workspaceId}/scheduled-tasks/${taskId}/resume`
1713
+ );
1714
+ }
1715
+ /**
1716
+ * Fire the task immediately (manual trigger), independent of its schedule.
1717
+ * Pass a stable `triggerId` to make a retried trigger idempotent — the same
1718
+ * token charges once and starts one run. Omit it and each call is distinct.
1719
+ */
1720
+ async triggerScheduledTask(workspaceId, taskId, options = {}) {
1721
+ return await this.requestJson(
1722
+ "POST",
1723
+ `/v1/workspaces/${workspaceId}/scheduled-tasks/${taskId}/trigger`,
1724
+ options.triggerId ? { triggerId: options.triggerId } : void 0
1725
+ );
1726
+ }
1727
+ async deleteScheduledTask(workspaceId, taskId) {
1728
+ await this.requestJson(
1729
+ "DELETE",
1730
+ `/v1/workspaces/${workspaceId}/scheduled-tasks/${taskId}`
1731
+ );
1732
+ }
1733
+ async listScheduledTaskRuns(workspaceId, taskId, options = {}) {
1734
+ return await this.requestJson(
1735
+ "GET",
1736
+ `/v1/workspaces/${workspaceId}/scheduled-tasks/${taskId}/runs`,
1737
+ void 0,
1738
+ { ...options.limit !== void 0 ? { limit: String(options.limit) } : {} }
1739
+ );
1740
+ }
1741
+ // --- VariableSets --------------------------------------------------------------
1742
+ // Variable values are write-only: reads return name/version metadata only.
1743
+ async listVariableSets(workspaceId) {
1744
+ return await this.requestJson(
1745
+ "GET",
1746
+ `/v1/workspaces/${workspaceId}/variable-sets`
1747
+ );
1748
+ }
1749
+ async createVariableSet(workspaceId, request) {
1750
+ return await this.requestJson(
1751
+ "POST",
1752
+ `/v1/workspaces/${workspaceId}/variable-sets`,
1753
+ request
1754
+ );
1755
+ }
1756
+ async getVariableSet(workspaceId, variableSetId) {
1757
+ return await this.requestJson(
1758
+ "GET",
1759
+ `/v1/workspaces/${workspaceId}/variable-sets/${variableSetId}`
1760
+ );
1761
+ }
1762
+ async updateVariableSet(workspaceId, variableSetId, request) {
1763
+ return await this.requestJson(
1764
+ "PATCH",
1765
+ `/v1/workspaces/${workspaceId}/variable-sets/${variableSetId}`,
1766
+ request
1767
+ );
1768
+ }
1769
+ async deleteVariableSet(workspaceId, variableSetId) {
1770
+ await this.requestJson(
1771
+ "DELETE",
1772
+ `/v1/workspaces/${workspaceId}/variable-sets/${variableSetId}`
1773
+ );
1774
+ }
1775
+ /** Create or rotate a variable. The value never comes back on any read. */
1776
+ async setVariableSetVariable(workspaceId, variableSetId, name, value) {
1777
+ return await this.requestJson(
1778
+ "PUT",
1779
+ `/v1/workspaces/${workspaceId}/variable-sets/${variableSetId}/variables/${encodeURIComponent(name)}`,
1780
+ { value }
1781
+ );
1782
+ }
1783
+ async deleteVariableSetVariable(workspaceId, variableSetId, name) {
1784
+ await this.requestJson(
1785
+ "DELETE",
1786
+ `/v1/workspaces/${workspaceId}/variable-sets/${variableSetId}/variables/${encodeURIComponent(name)}`
1787
+ );
1788
+ }
1789
+ // --- Rigs ------------------------------------------------------------------
1790
+ // Workspace-scoped, versioned sandbox machine definitions. rigs:use gates read
1791
+ // + proposeRigChange; rigs:manage gates create / update / delete / activate.
1792
+ async listRigs(workspaceId) {
1793
+ return await this.requestJson("GET", `/v1/workspaces/${workspaceId}/rigs`);
1794
+ }
1795
+ async createRig(workspaceId, request) {
1796
+ return await this.requestJson("POST", `/v1/workspaces/${workspaceId}/rigs`, request);
1797
+ }
1798
+ async getRig(workspaceId, rigId) {
1799
+ return await this.requestJson("GET", `/v1/workspaces/${workspaceId}/rigs/${rigId}`);
1800
+ }
1801
+ async updateRig(workspaceId, rigId, request) {
1802
+ return await this.requestJson(
1803
+ "PATCH",
1804
+ `/v1/workspaces/${workspaceId}/rigs/${rigId}`,
1805
+ request
1806
+ );
1807
+ }
1808
+ async deleteRig(workspaceId, rigId) {
1809
+ await this.requestJson("DELETE", `/v1/workspaces/${workspaceId}/rigs/${rigId}`);
1810
+ }
1811
+ async listRigVersions(workspaceId, rigId) {
1812
+ return await this.requestJson(
1813
+ "GET",
1814
+ `/v1/workspaces/${workspaceId}/rigs/${rigId}/versions`
1815
+ );
1816
+ }
1817
+ /** Roll the active version to an existing one (rollback / promote-activate). */
1818
+ async activateRigVersion(workspaceId, rigId, versionId) {
1819
+ return await this.requestJson(
1820
+ "POST",
1821
+ `/v1/workspaces/${workspaceId}/rigs/${rigId}/versions/${versionId}/activate`
1822
+ );
1823
+ }
1824
+ async listRigChanges(workspaceId, rigId) {
1825
+ return await this.requestJson(
1826
+ "GET",
1827
+ `/v1/workspaces/${workspaceId}/rigs/${rigId}/changes`
1828
+ );
1829
+ }
1830
+ /** Propose a change against the rig's active version (rigs:use). */
1831
+ async proposeRigChange(workspaceId, rigId, request) {
1832
+ return await this.requestJson(
1833
+ "POST",
1834
+ `/v1/workspaces/${workspaceId}/rigs/${rigId}/changes`,
1835
+ request
1836
+ );
1837
+ }
1838
+ async getRigChange(workspaceId, rigId, changeId) {
1839
+ return await this.requestJson(
1840
+ "GET",
1841
+ `/v1/workspaces/${workspaceId}/rigs/${rigId}/changes/${changeId}`
1842
+ );
1843
+ }
1844
+ /**
1845
+ * Re-run verification for a change (rigs:use). Verification is asynchronous:
1846
+ * this returns the change immediately with status `verifying`; poll
1847
+ * `getRigChange`/`listRigChanges` for the terminal outcome + logs.
1848
+ */
1849
+ async verifyRigChange(workspaceId, rigId, changeId) {
1850
+ return await this.requestJson(
1851
+ "POST",
1852
+ `/v1/workspaces/${workspaceId}/rigs/${rigId}/changes/${changeId}/verify`
1853
+ );
1854
+ }
1855
+ /**
1856
+ * Promote a verified `definition_edit` change into a new active rig version
1857
+ * (rigs:manage). Only valid once the change's verification passed; returns the
1858
+ * newly minted version.
1859
+ */
1860
+ async promoteRigChange(workspaceId, rigId, changeId) {
1861
+ return await this.requestJson(
1862
+ "POST",
1863
+ `/v1/workspaces/${workspaceId}/rigs/${rigId}/changes/${changeId}/promote`
1864
+ );
1865
+ }
1866
+ /**
1867
+ * Re-run the active version's checks in a clean throwaway sandbox (rigs:use).
1868
+ * Asynchronous — returns the version id being verified; the outcome lands on
1869
+ * the version's audit trail.
1870
+ */
1871
+ async verifyRig(workspaceId, rigId) {
1872
+ return await this.requestJson(
1873
+ "POST",
1874
+ `/v1/workspaces/${workspaceId}/rigs/${rigId}/verify`
1875
+ );
1876
+ }
1877
+ /** @deprecated use listVariableSets */
1878
+ async listEnvironments(workspaceId) {
1879
+ return await this.listVariableSets(workspaceId);
1880
+ }
1881
+ /** @deprecated use createVariableSet */
1882
+ async createEnvironment(workspaceId, request) {
1883
+ return await this.createVariableSet(workspaceId, request);
1884
+ }
1885
+ /** @deprecated use getVariableSet */
1886
+ async getEnvironment(workspaceId, environmentId) {
1887
+ return await this.getVariableSet(workspaceId, environmentId);
1888
+ }
1889
+ /** @deprecated use updateVariableSet */
1890
+ async updateEnvironment(workspaceId, environmentId, request) {
1891
+ return await this.updateVariableSet(workspaceId, environmentId, request);
1892
+ }
1893
+ /** @deprecated use deleteVariableSet */
1894
+ async deleteEnvironment(workspaceId, environmentId) {
1895
+ await this.deleteVariableSet(workspaceId, environmentId);
1896
+ }
1897
+ /** @deprecated use setVariableSetVariable */
1898
+ async setEnvironmentVariable(workspaceId, environmentId, name, value) {
1899
+ return await this.setVariableSetVariable(workspaceId, environmentId, name, value);
1900
+ }
1901
+ /** @deprecated use deleteVariableSetVariable */
1902
+ async deleteEnvironmentVariable(workspaceId, environmentId, name) {
1903
+ await this.deleteVariableSetVariable(workspaceId, environmentId, name);
1904
+ }
1905
+ // --- Files -----------------------------------------------------------------------
1906
+ /** Step 1 of the upload flow: returns the pre-signed PUT target. */
1907
+ async beginFileUpload(workspaceId, request) {
1908
+ return await this.requestJson(
1909
+ "POST",
1910
+ `/v1/workspaces/${workspaceId}/files/uploads`,
1911
+ request
1912
+ );
1913
+ }
1914
+ /** Step 3 of the upload flow: server verifies the object and marks it ready. */
1915
+ async completeFileUpload(workspaceId, uploadId) {
1916
+ const response = await this.requestJson(
1917
+ "POST",
1918
+ `/v1/workspaces/${workspaceId}/files/uploads/${uploadId}/complete`
1919
+ );
1920
+ return response.file;
1921
+ }
1922
+ /**
1923
+ * The whole upload flow as one call: begin -> PUT the bytes to the signed
1924
+ * URL (with its required headers; no API auth is sent to object storage)
1925
+ * -> complete. Returns the ready `FileAsset`.
1926
+ */
1927
+ async uploadFile(workspaceId, input) {
1928
+ const body = input.data instanceof Uint8Array ? new Blob([input.data.slice()]) : input.data instanceof ArrayBuffer ? input.data.slice(0) : input.data;
1929
+ const sizeBytes = typeof body === "string" ? new TextEncoder().encode(body).byteLength : body instanceof Blob ? body.size : body.byteLength;
1930
+ const sha256 = input.sha256 ?? await sha256ForUpload(body);
1931
+ const upload = await this.beginFileUpload(workspaceId, {
1932
+ filename: input.filename,
1933
+ contentType: input.contentType,
1934
+ sizeBytes,
1935
+ sha256
1936
+ });
1937
+ const putResponse = await this.fetchImpl(upload.putUrl, {
1938
+ method: "PUT",
1939
+ // The backend's requiredHeaders already carry the canonical lowercase
1940
+ // `content-type` for every storage backend (Azure/S3/GCS). Do NOT also set
1941
+ // a `Content-Type` key here: WHATWG Headers treats the two casings as the
1942
+ // same header and comma-joins their values (e.g. "text/plain, text/plain"),
1943
+ // which the object store persists verbatim and COMPLETE then rejects (422),
1944
+ // and which breaks S3's presigned-URL signature.
1945
+ headers: { ...upload.requiredHeaders },
1946
+ body
1947
+ });
1948
+ if (!putResponse.ok) {
1949
+ throw await apiErrorFromResponse(putResponse, { method: "PUT" });
1950
+ }
1951
+ return await this.completeFileUpload(workspaceId, upload.uploadId);
1952
+ }
1953
+ async getFile(workspaceId, fileId) {
1954
+ return await this.requestJson(
1955
+ "GET",
1956
+ `/v1/workspaces/${workspaceId}/files/${fileId}`
1957
+ );
1958
+ }
1959
+ /** Read provider-neutral retained evidence metadata; never returns a storage location. */
1960
+ async getRetainedArtifact(workspaceId, artifactId) {
1961
+ return await this.requestJson(
1962
+ "GET",
1963
+ `/v1/workspaces/${workspaceId}/artifacts/${artifactId}`
1964
+ );
1965
+ }
1966
+ /**
1967
+ * Read at most one authenticated retained-evidence range from the API. This
1968
+ * deliberately does not use the ordinary signed file-download URL.
1969
+ */
1970
+ async getRetainedArtifactContent(workspaceId, artifactId, options = {}) {
1971
+ if (options.range && (options.range.length > 128 || /[^\x20-\x7e]/.test(options.range))) {
1972
+ throw new RangeError("retained artifact range must be at most 128 printable ASCII bytes");
1973
+ }
1974
+ const correlationId = crypto.randomUUID();
1975
+ const response = await this.fetchImpl(
1976
+ this.url(`/v1/workspaces/${workspaceId}/artifacts/${artifactId}/content`),
1977
+ {
1978
+ method: "GET",
1979
+ headers: {
1980
+ ...this.headers(correlationId),
1981
+ Accept: "application/octet-stream",
1982
+ ...options.range ? { Range: options.range } : {}
1983
+ },
1984
+ ...options.signal ? { signal: options.signal } : {}
1985
+ }
1986
+ );
1987
+ try {
1988
+ assertApiContractResponse(response);
1989
+ } catch (error) {
1990
+ await cancelResponseBody(response, "retained artifact API contract mismatch");
1991
+ throw error;
1992
+ }
1993
+ if (!response.ok) {
1994
+ throw await apiErrorFromResponse(response, { method: "GET", correlationId });
1995
+ }
1996
+ if (response.status !== 200 && response.status !== 206) {
1997
+ await cancelResponseBody(response, "unexpected retained artifact response status");
1998
+ throw new OpenGeniApiError(response.status, "unexpected retained artifact response status");
1999
+ }
2000
+ if (response.headers.get("accept-ranges") !== "bytes") {
2001
+ await cancelResponseBody(response, "retained artifact response omitted byte-range support");
2002
+ throw new OpenGeniApiError(502, "retained artifact response omitted byte-range support");
2003
+ }
2004
+ let declaredLength;
2005
+ try {
2006
+ declaredLength = parseBoundedContentLength(response.headers.get("content-length"));
2007
+ } catch (error) {
2008
+ await cancelResponseBody(response, "invalid retained artifact content-length");
2009
+ throw error;
2010
+ }
2011
+ const bytes = await readBoundedResponseBytes(
2012
+ response,
2013
+ RETAINED_OUTPUT_MAX_PAGE_BYTES,
2014
+ declaredLength
2015
+ );
2016
+ return {
2017
+ bytes,
2018
+ status: response.status,
2019
+ contentType: response.headers.get("content-type") ?? "application/octet-stream",
2020
+ contentLength: bytes.byteLength,
2021
+ contentRange: response.headers.get("content-range"),
2022
+ acceptRanges: "bytes"
2023
+ };
2024
+ }
2025
+ /** Mint a short-lived signed download URL for a ready file. */
2026
+ async createFileDownloadUrl(workspaceId, fileId) {
2027
+ return await this.requestJson(
2028
+ "POST",
2029
+ `/v1/workspaces/${workspaceId}/files/${fileId}/download-url`
2030
+ );
2031
+ }
2032
+ // --- Documents ----------------------------------------------------------------------
2033
+ async createDocumentBase(workspaceId, request) {
2034
+ return await this.requestJson(
2035
+ "POST",
2036
+ `/v1/workspaces/${workspaceId}/document-bases`,
2037
+ request
2038
+ );
2039
+ }
2040
+ async listDocumentBases(workspaceId) {
2041
+ return await this.requestJson(
2042
+ "GET",
2043
+ `/v1/workspaces/${workspaceId}/document-bases`
2044
+ );
2045
+ }
2046
+ async getDocumentBase(workspaceId, baseId) {
2047
+ return await this.requestJson(
2048
+ "GET",
2049
+ `/v1/workspaces/${workspaceId}/document-bases/${baseId}`
2050
+ );
2051
+ }
2052
+ /** Index an uploaded file into the base. The file must be `ready`. */
2053
+ async addDocument(workspaceId, baseId, request) {
2054
+ return await this.requestJson(
2055
+ "POST",
2056
+ `/v1/workspaces/${workspaceId}/document-bases/${baseId}/documents`,
2057
+ request
2058
+ );
2059
+ }
2060
+ async listDocuments(workspaceId, baseId) {
2061
+ return await this.requestJson(
2062
+ "GET",
2063
+ `/v1/workspaces/${workspaceId}/document-bases/${baseId}/documents`
2064
+ );
2065
+ }
2066
+ /**
2067
+ * Drop raw text or an already-uploaded file into the workspace's Default
2068
+ * base. When curation is enabled, it may name, summarize, categorize, and
2069
+ * (confidence permitting) file the document into the best-matching base;
2070
+ * provider=none leaves caller metadata and Default placement unchanged.
2071
+ */
2072
+ async createKnowledgeDrop(workspaceId, request) {
2073
+ return await this.requestJson(
2074
+ "POST",
2075
+ `/v1/workspaces/${workspaceId}/knowledge/drops`,
2076
+ request
2077
+ );
2078
+ }
2079
+ /**
2080
+ * Move a document (and its indexed chunks) to another base. With no
2081
+ * targetBaseId, applies the document's stored curation suggestion.
2082
+ */
2083
+ async moveDocument(workspaceId, documentId, request = {}) {
2084
+ return await this.requestJson(
2085
+ "POST",
2086
+ `/v1/workspaces/${workspaceId}/documents/${documentId}/move`,
2087
+ request
2088
+ );
2089
+ }
2090
+ /** Retry indexing for a failed document. */
2091
+ async reindexDocument(workspaceId, baseId, documentId) {
2092
+ return await this.requestJson(
2093
+ "POST",
2094
+ `/v1/workspaces/${workspaceId}/document-bases/${baseId}/documents/${documentId}/reindex`
2095
+ );
2096
+ }
2097
+ /**
2098
+ * Delete a document from a base. Removes the document row and its indexed
2099
+ * chunks while leaving the uploaded file asset available for other uses.
2100
+ */
2101
+ async deleteDocument(workspaceId, baseId, documentId) {
2102
+ await this.requestVoid(
2103
+ "DELETE",
2104
+ `/v1/workspaces/${workspaceId}/document-bases/${baseId}/documents/${documentId}`
2105
+ );
2106
+ }
2107
+ async searchDocuments(workspaceId, baseId, request) {
2108
+ return await this.requestJson(
2109
+ "POST",
2110
+ `/v1/workspaces/${workspaceId}/document-bases/${baseId}/search`,
2111
+ request
2112
+ );
2113
+ }
2114
+ async searchKnowledge(workspaceId, request) {
2115
+ return await this.requestJson(
2116
+ "POST",
2117
+ `/v1/workspaces/${workspaceId}/knowledge/search`,
2118
+ request
2119
+ );
2120
+ }
2121
+ async listKnowledgeMemories(workspaceId, request = {}) {
2122
+ const params = new URLSearchParams();
2123
+ if (request.query) params.set("query", request.query);
2124
+ if (request.status) params.set("status", request.status);
2125
+ if (request.kind) params.set("kind", request.kind);
2126
+ if (request.scope) params.set("scope", request.scope);
2127
+ if (request.limit) params.set("limit", String(request.limit));
2128
+ const query = params.toString();
2129
+ return await this.requestJson(
2130
+ "GET",
2131
+ `/v1/workspaces/${workspaceId}/knowledge/memories${query ? `?${query}` : ""}`
2132
+ );
2133
+ }
2134
+ async getKnowledgeMemory(workspaceId, memoryId) {
2135
+ return await this.requestJson(
2136
+ "GET",
2137
+ `/v1/workspaces/${workspaceId}/knowledge/memories/${memoryId}`
2138
+ );
2139
+ }
2140
+ async createKnowledgeMemory(workspaceId, request) {
2141
+ return await this.requestJson(
2142
+ "POST",
2143
+ `/v1/workspaces/${workspaceId}/knowledge/memories`,
2144
+ request
2145
+ );
2146
+ }
2147
+ async updateKnowledgeMemory(workspaceId, memoryId, request) {
2148
+ return await this.requestJson(
2149
+ "PATCH",
2150
+ `/v1/workspaces/${workspaceId}/knowledge/memories/${memoryId}`,
2151
+ request
2152
+ );
2153
+ }
2154
+ /** Hybrid (semantic + keyword) search over the workspace's agent-visible memory. */
2155
+ async searchWorkspaceMemories(workspaceId, request) {
2156
+ return await this.requestJson(
2157
+ "POST",
2158
+ `/v1/workspaces/${workspaceId}/knowledge/memories/search`,
2159
+ request
2160
+ );
2161
+ }
2162
+ /** Deep-merge a settings patch into the workspace (preserves unknown keys). */
2163
+ async updateWorkspaceSettings(workspaceId, request) {
2164
+ return await this.requestJson(
2165
+ "PATCH",
2166
+ `/v1/workspaces/${workspaceId}/settings`,
2167
+ request
2168
+ );
2169
+ }
2170
+ async setWorkspaceDefaultRig(workspaceId, request) {
2171
+ return await this.requestJson(
2172
+ "PUT",
2173
+ `/v1/workspaces/${workspaceId}/default-rig`,
2174
+ request
2175
+ );
2176
+ }
2177
+ // --- Capability packs ------------------------------------------------------------------
2178
+ /** Built-in + registered packs, with the workspace's installations. */
2179
+ async listPacks(workspaceId) {
2180
+ return await this.requestJson("GET", `/v1/workspaces/${workspaceId}/packs`);
2181
+ }
2182
+ /** Register (or replace) a workspace-scoped pack from a manifest. */
2183
+ async registerPack(workspaceId, manifest) {
2184
+ return await this.requestJson(
2185
+ "POST",
2186
+ `/v1/workspaces/${workspaceId}/packs`,
2187
+ manifest
2188
+ );
2189
+ }
2190
+ async getPack(workspaceId, packId) {
2191
+ return await this.requestJson(
2192
+ "GET",
2193
+ `/v1/workspaces/${workspaceId}/packs/${encodeURIComponent(packId)}`
2194
+ );
2195
+ }
2196
+ async enablePack(workspaceId, packId, request = {}) {
2197
+ return await this.requestJson(
2198
+ "POST",
2199
+ `/v1/workspaces/${workspaceId}/packs/${encodeURIComponent(packId)}/enable`,
2200
+ request
2201
+ );
2202
+ }
2203
+ /** Unregister a workspace-scoped pack (built-in packs cannot be deleted). */
2204
+ async deletePack(workspaceId, packId) {
2205
+ await this.requestVoid(
2206
+ "DELETE",
2207
+ `/v1/workspaces/${workspaceId}/packs/${encodeURIComponent(packId)}`
2208
+ );
2209
+ }
2210
+ async listPackInstallations(workspaceId) {
2211
+ return await this.requestJson(
2212
+ "GET",
2213
+ `/v1/workspaces/${workspaceId}/packs/installations`
2214
+ );
2215
+ }
2216
+ // --- Capabilities -------------------------------------------------------------------------
2217
+ async listCapabilities(workspaceId) {
2218
+ return await this.requestJson(
2219
+ "GET",
2220
+ `/v1/workspaces/${workspaceId}/capabilities`
2221
+ );
2222
+ }
2223
+ /** Add a manual capability catalog item (e.g. a remote MCP server). */
2224
+ async createCapability(workspaceId, request) {
2225
+ return await this.requestJson(
2226
+ "POST",
2227
+ `/v1/workspaces/${workspaceId}/capabilities`,
2228
+ request
2229
+ );
2230
+ }
2231
+ async enableCapability(workspaceId, capabilityId, request = {}) {
2232
+ return await this.requestJson(
2233
+ "POST",
2234
+ `/v1/workspaces/${workspaceId}/capabilities/${encodeURIComponent(capabilityId)}/enable`,
2235
+ request
2236
+ );
2237
+ }
2238
+ async disableCapability(workspaceId, capabilityId) {
2239
+ return await this.requestJson(
2240
+ "POST",
2241
+ `/v1/workspaces/${workspaceId}/capabilities/${encodeURIComponent(capabilityId)}/disable`
2242
+ );
2243
+ }
2244
+ /** Search the official MCP registry for installable capabilities. */
2245
+ async discoverMcpCapabilities(workspaceId, options = {}) {
2246
+ return await this.requestJson(
2247
+ "GET",
2248
+ `/v1/workspaces/${workspaceId}/capabilities/discovery/mcp-registry`,
2249
+ void 0,
2250
+ {
2251
+ ...options.query !== void 0 ? { query: options.query } : {},
2252
+ ...options.limit !== void 0 ? { limit: String(options.limit) } : {}
2253
+ }
2254
+ );
2255
+ }
2256
+ // --- Connections -------------------------------------------------------------------------------
2257
+ async listConnections(workspaceId) {
2258
+ const response = await this.requestJson(
2259
+ "GET",
2260
+ `/v1/workspaces/${workspaceId}/connections`
2261
+ );
2262
+ return response.connections;
2263
+ }
2264
+ async createConnection(workspaceId, request) {
2265
+ const response = await this.requestJson(
2266
+ "POST",
2267
+ `/v1/workspaces/${workspaceId}/connections`,
2268
+ request
2269
+ );
2270
+ return response.connection;
2271
+ }
2272
+ /** Start the public Slack installation flow for the workspace-shared OpenGeni bot. */
2273
+ async startOpenGeniSlackBotInstall(workspaceId, request = {}) {
2274
+ return await this.requestJson(
2275
+ "POST",
2276
+ `/v1/workspaces/${workspaceId}/connections/slack-bot/install`,
2277
+ request
2278
+ );
2279
+ }
2280
+ async updateConnection(workspaceId, connectionId, request) {
2281
+ const response = await this.requestJson(
2282
+ "PATCH",
2283
+ `/v1/workspaces/${workspaceId}/connections/${connectionId}`,
2284
+ request
2285
+ );
2286
+ return response.connection;
2287
+ }
2288
+ async deleteConnection(workspaceId, connectionId) {
2289
+ const response = await this.requestJson(
2290
+ "DELETE",
2291
+ `/v1/workspaces/${workspaceId}/connections/${connectionId}`
2292
+ );
2293
+ return response.connection;
2294
+ }
2295
+ /** Start an OAuth connection flow; redirect the user to the returned `authorizationUrl`. */
2296
+ async startConnectionOAuth(workspaceId, request, options = {}) {
2297
+ return await this.requestJson(
2298
+ "POST",
2299
+ `/v1/workspaces/${workspaceId}/connections/oauth/start`,
2300
+ request,
2301
+ {},
2302
+ options
2303
+ );
2304
+ }
2305
+ /** Public, immutably-cached URL for a catalog item's logo, or null when the item has none. */
2306
+ catalogAssetUrl(logoAssetPath) {
2307
+ return logoAssetPath ? `${this.baseUrl}/v1/${logoAssetPath}` : null;
2308
+ }
2309
+ // --- GitHub ----------------------------------------------------------------------------------
2310
+ /** GitHub App server configuration plus truthful workspace binding status. */
2311
+ async getGitHubApp(workspaceId) {
2312
+ return await this.requestJson("GET", `/v1/workspaces/${workspaceId}/github/app`);
2313
+ }
2314
+ /** Build the GitHub owner-consent entry URL for fresh workspace-bound state. */
2315
+ githubConnectUrl(workspaceId, state) {
2316
+ return this.url(`/v1/workspaces/${workspaceId}/github/connect`, { state });
2317
+ }
2318
+ async listGitHubRepositories(workspaceId) {
2319
+ return await this.requestJson(
2320
+ "GET",
2321
+ `/v1/workspaces/${workspaceId}/github/repositories`
2322
+ );
2323
+ }
2324
+ /** Re-sync the installation's repository list from GitHub. */
2325
+ async syncGitHubRepositories(workspaceId) {
2326
+ return await this.requestJson(
2327
+ "POST",
2328
+ `/v1/workspaces/${workspaceId}/github/repositories/sync`
2329
+ );
2330
+ }
2331
+ /** Remove one workspace binding without uninstalling the GitHub App itself. */
2332
+ async unlinkGitHubInstallation(workspaceId, installationId) {
2333
+ await this.requestVoid(
2334
+ "DELETE",
2335
+ `/v1/workspaces/${workspaceId}/github/installations/${installationId}`
2336
+ );
2337
+ }
2338
+ /** Build a GitHub App manifest + the GitHub URL to submit it to. */
2339
+ async createGitHubAppManifest(workspaceId, request = {}) {
2340
+ return await this.requestJson(
2341
+ "POST",
2342
+ `/v1/workspaces/${workspaceId}/github/app-manifest`,
2343
+ request
2344
+ );
2345
+ }
2346
+ // --- API keys ----------------------------------------------------------------------------------
2347
+ async listApiKeys(workspaceId) {
2348
+ const response = await this.requestJson(
2349
+ "GET",
2350
+ `/v1/workspaces/${workspaceId}/api-keys`
2351
+ );
2352
+ return response.apiKeys;
2353
+ }
2354
+ /** The returned `token` is shown once; only its prefix is stored. */
2355
+ async createApiKey(workspaceId, request) {
2356
+ return await this.requestJson(
2357
+ "POST",
2358
+ `/v1/workspaces/${workspaceId}/api-keys`,
2359
+ request
2360
+ );
2361
+ }
2362
+ /** Revoke an API key. Returns the revoked key. */
2363
+ async deleteApiKey(workspaceId, apiKeyId) {
2364
+ return await this.requestJson(
2365
+ "DELETE",
2366
+ `/v1/workspaces/${workspaceId}/api-keys/${apiKeyId}`
2367
+ );
2368
+ }
2369
+ // --- Billing (account-scoped) --------------------------------------------------------------------
2370
+ async getBilling(options = {}) {
2371
+ return await this.requestJson("GET", "/v1/billing", void 0, {
2372
+ ...options.accountId !== void 0 ? { accountId: options.accountId } : {}
2373
+ });
2374
+ }
2375
+ async getBillingUsage(options = {}) {
2376
+ return await this.requestJson("GET", "/v1/billing/usage", void 0, {
2377
+ ...options.accountId !== void 0 ? { accountId: options.accountId } : {},
2378
+ ...options.workspaceId !== void 0 ? { workspaceId: options.workspaceId } : {}
2379
+ });
2380
+ }
2381
+ async getWorkspaceInsights(workspaceId, options = {}) {
2382
+ return await this.requestJson(
2383
+ "GET",
2384
+ `/v1/workspaces/${workspaceId}/insights`,
2385
+ void 0,
2386
+ {
2387
+ range: options.range ?? "week",
2388
+ ...options.provider !== void 0 ? { provider: options.provider } : {},
2389
+ ...options.model !== void 0 ? { model: options.model } : {}
2390
+ }
2391
+ );
2392
+ }
2393
+ async getBillingEntitlements(options = {}) {
2394
+ return await this.requestJson(
2395
+ "GET",
2396
+ "/v1/billing/entitlements",
2397
+ void 0,
2398
+ {
2399
+ ...options.accountId !== void 0 ? { accountId: options.accountId } : {}
2400
+ }
2401
+ );
2402
+ }
2403
+ /** Start a Stripe checkout for prepaid credits. */
2404
+ async createBillingCheckout(request) {
2405
+ return await this.requestJson("POST", "/v1/billing/checkout", request);
2406
+ }
2407
+ // --- Internals -------------------------------------------------------------
2408
+ headers(correlationId) {
2409
+ const extra = typeof this.options.headers === "function" ? this.options.headers() : this.options.headers;
2410
+ return {
2411
+ ...this.options.apiKey ? { Authorization: `Bearer ${this.options.apiKey}` } : {},
2412
+ ...extra,
2413
+ [OPENGENI_API_CONTRACT_HEADER]: OPENGENI_API_CONTRACT_REVISION,
2414
+ ...correlationId ? { [OPENGENI_CORRELATION_HEADER]: correlationId } : {}
2415
+ };
2416
+ }
2417
+ url(path, query = {}) {
2418
+ const params = new URLSearchParams(query).toString();
2419
+ return `${this.baseUrl}${path}${params ? `?${params}` : ""}`;
2420
+ }
2421
+ // --- Codex (ChatGPT) subscription (workspace-scoped) --------------------------------------------
2422
+ /** Connection state + the codex models the workspace may select (empty until connected). */
2423
+ async codexStatus(workspaceId) {
2424
+ return await this.requestJson(
2425
+ "GET",
2426
+ `/v1/workspaces/${workspaceId}/codex/status`
2427
+ );
2428
+ }
2429
+ /** Begin device-code login: show `userCode` at `verificationUri`, then poll with `state`. */
2430
+ async codexConnectStart(workspaceId) {
2431
+ return await this.requestJson(
2432
+ "POST",
2433
+ `/v1/workspaces/${workspaceId}/codex/connect/start`
2434
+ );
2435
+ }
2436
+ /** Poll device-code authorization with the `state` from {@link codexConnectStart}. */
2437
+ async codexConnectPoll(workspaceId, state) {
2438
+ return await this.requestJson(
2439
+ "POST",
2440
+ `/v1/workspaces/${workspaceId}/codex/connect/poll`,
2441
+ { state }
2442
+ );
2443
+ }
2444
+ /** Remaining usage / limits for the connected (ACTIVE) subscription. Back-compat. */
2445
+ async codexUsage(workspaceId) {
2446
+ return await this.requestJson("GET", `/v1/workspaces/${workspaceId}/codex/usage`);
2447
+ }
2448
+ /** Live per-account usage read (refreshes THIS account's bearer; writes the cache). */
2449
+ async codexAccountUsage(workspaceId, accountId) {
2450
+ return await this.requestJson(
2451
+ "GET",
2452
+ `/v1/workspaces/${workspaceId}/codex/accounts/${accountId}/usage`
2453
+ );
2454
+ }
2455
+ /** Batched live refresh across every connected account, keyed by credential id. */
2456
+ async refreshCodexUsage(workspaceId) {
2457
+ return await this.requestJson(
2458
+ "POST",
2459
+ `/v1/workspaces/${workspaceId}/codex/usage/refresh`
2460
+ );
2461
+ }
2462
+ /** Live independently-settled quota + reset-credit overview for every account. */
2463
+ async codexOverview(workspaceId) {
2464
+ return await this.requestJson(
2465
+ "GET",
2466
+ `/v1/workspaces/${workspaceId}/codex/overview`
2467
+ );
2468
+ }
2469
+ /** Disconnect ALL accounts (legacy workspace-wide). Prefer `disconnectCodexAccount`. */
2470
+ async codexDisconnect(workspaceId) {
2471
+ return await this.requestJson(
2472
+ "DELETE",
2473
+ `/v1/workspaces/${workspaceId}/codex`
2474
+ );
2475
+ }
2476
+ /** List every connected Codex account + the workspace active pointer + settings. */
2477
+ async listCodexAccounts(workspaceId) {
2478
+ return await this.requestJson(
2479
+ "GET",
2480
+ `/v1/workspaces/${workspaceId}/codex/accounts`
2481
+ );
2482
+ }
2483
+ /** Switch the workspace ACTIVE Codex account (the one unpinned sessions use). */
2484
+ async activateCodexAccount(workspaceId, accountId) {
2485
+ return await this.requestJson(
2486
+ "POST",
2487
+ `/v1/workspaces/${workspaceId}/codex/accounts/${accountId}/activate`
2488
+ );
2489
+ }
2490
+ /** P3: enable/disable Codex auto-rotation and/or pick the strategy. Returns the effective settings. */
2491
+ async setCodexRotationSettings(workspaceId, patch) {
2492
+ return await this.requestJson(
2493
+ "PATCH",
2494
+ `/v1/workspaces/${workspaceId}/codex/settings`,
2495
+ patch
2496
+ );
2497
+ }
2498
+ /** Toggle only NEW automatic allocations under independent allocator OCC. */
2499
+ async setCodexAccountAllocator(workspaceId, accountId, input) {
2500
+ return await this.requestJson(
2501
+ "PATCH",
2502
+ `/v1/workspaces/${workspaceId}/codex/accounts/${accountId}/allocator`,
2503
+ input
2504
+ );
2505
+ }
2506
+ /** Disconnect ONE Codex account by id (re-picks active when the removed one was active). */
2507
+ async disconnectCodexAccount(workspaceId, accountId) {
2508
+ return await this.requestJson(
2509
+ "DELETE",
2510
+ `/v1/workspaces/${workspaceId}/codex/accounts/${accountId}`
2511
+ );
2512
+ }
2513
+ /** Rename a Codex account (label only in P1). */
2514
+ async renameCodexAccount(workspaceId, accountId, label) {
2515
+ return await this.requestJson(
2516
+ "PATCH",
2517
+ `/v1/workspaces/${workspaceId}/codex/accounts/${accountId}`,
2518
+ { label }
2519
+ );
2520
+ }
2521
+ /** Pin (or unpin via "auto") a session's Codex account. Applies on the next turn. */
2522
+ async pinSessionCodexAccount(workspaceId, sessionId, target) {
2523
+ return await this.requestJson(
2524
+ "POST",
2525
+ `/v1/workspaces/${workspaceId}/sessions/${sessionId}/codex-account`,
2526
+ { target }
2527
+ );
2528
+ }
2529
+ async requestJson(method, path, body, query = {}, options = {}) {
2530
+ const correlationId = crypto.randomUUID();
2531
+ let response;
2532
+ try {
2533
+ response = await this.fetchImpl(this.url(path, query), {
2534
+ method,
2535
+ headers: {
2536
+ ...this.headers(correlationId),
2537
+ Accept: "application/json",
2538
+ ...body !== void 0 ? { "Content-Type": "application/json" } : {}
2539
+ },
2540
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {},
2541
+ ...options.signal ? { signal: options.signal } : {}
2542
+ });
2543
+ } catch (error) {
2544
+ if (isMutationMethod(method)) {
2545
+ throw mutationTransportError(correlationId);
2546
+ }
2547
+ throw error;
2548
+ }
2549
+ assertApiContractResponse(response);
2550
+ if (!response.ok) {
2551
+ throw await apiErrorFromResponse(response, { method, correlationId });
2552
+ }
2553
+ await assertJsonResponse(response, { method, correlationId });
2554
+ try {
2555
+ return await response.json();
2556
+ } catch (error) {
2557
+ if (isMutationMethod(method)) {
2558
+ throw mutationTransportError(correlationId);
2559
+ }
2560
+ throw error;
2561
+ }
2562
+ }
2563
+ /** Like `requestJson` for endpoints that respond with no body (204). */
2564
+ async requestVoid(method, path, body) {
2565
+ const correlationId = crypto.randomUUID();
2566
+ let response;
2567
+ try {
2568
+ response = await this.fetchImpl(this.url(path), {
2569
+ method,
2570
+ headers: {
2571
+ ...this.headers(correlationId),
2572
+ Accept: "application/json",
2573
+ ...body !== void 0 ? { "Content-Type": "application/json" } : {}
2574
+ },
2575
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
2576
+ });
2577
+ } catch (error) {
2578
+ if (isMutationMethod(method)) {
2579
+ throw mutationTransportError(correlationId);
2580
+ }
2581
+ throw error;
2582
+ }
2583
+ assertApiContractResponse(response);
2584
+ if (!response.ok) {
2585
+ throw await apiErrorFromResponse(response, { method, correlationId });
2586
+ }
2587
+ }
2588
+ };
2589
+ function assertApiContractResponse(response) {
2590
+ const actual = response.headers.get(OPENGENI_API_CONTRACT_HEADER);
2591
+ if (actual && actual !== OPENGENI_API_CONTRACT_REVISION) {
2592
+ throw new OpenGeniApiContractMismatchError(OPENGENI_API_CONTRACT_REVISION, actual);
2593
+ }
2594
+ }
2595
+ function isTranscribeAudioResponse(value) {
2596
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
2597
+ const record = value;
2598
+ return typeof record.text === "string" && Array.isArray(record.languages) && record.languages.every((language) => typeof language === "string");
2599
+ }
2600
+ function filenameForAudioMimeType(mimeType) {
2601
+ const bare = mimeType.trim().toLowerCase().split(";")[0] ?? "audio/webm";
2602
+ switch (bare) {
2603
+ case "audio/mp4":
2604
+ case "audio/m4a":
2605
+ return "audio.mp4";
2606
+ case "audio/ogg":
2607
+ return "audio.ogg";
2608
+ case "audio/mpeg":
2609
+ case "audio/mp3":
2610
+ return "audio.mp3";
2611
+ case "audio/wav":
2612
+ case "audio/x-wav":
2613
+ return "audio.wav";
2614
+ case "audio/webm":
2615
+ default:
2616
+ return "audio.webm";
2617
+ }
2618
+ }
2619
+ var API_ERROR_MAX_BYTES = 16 * 1024;
2620
+ async function apiErrorFromResponse(response, context) {
2621
+ return new OpenGeniApiError(response.status, await readBoundedJsonErrorBody(response), {
2622
+ correlationId: response.headers.get(OPENGENI_CORRELATION_HEADER) ?? context.correlationId,
2623
+ mutation: isMutationMethod(context.method)
2624
+ });
2625
+ }
2626
+ async function assertJsonResponse(response, context) {
2627
+ if (isJsonContentType(response.headers.get("content-type"))) return;
2628
+ await cancelResponseBody(response, "unexpected non-JSON API response");
2629
+ throw new OpenGeniApiError(502, "", {
2630
+ code: "upstream_unavailable",
2631
+ retryable: true,
2632
+ correlationId: response.headers.get(OPENGENI_CORRELATION_HEADER) ?? context.correlationId,
2633
+ outcomeUnknown: isMutationMethod(context.method),
2634
+ displayMessage: "OpenGeni is temporarily unavailable \u2014 retry."
2635
+ });
2636
+ }
2637
+ async function readBoundedJsonErrorBody(response) {
2638
+ if (!isJsonContentType(response.headers.get("content-type"))) {
2639
+ await cancelResponseBody(response, "discarding API error body");
2640
+ return "";
2641
+ }
2642
+ if (Number(response.headers.get("content-length")) > API_ERROR_MAX_BYTES) {
2643
+ await cancelResponseBody(response, "discarding API error body");
2644
+ return "";
2645
+ }
2646
+ try {
2647
+ return new TextDecoder().decode(
2648
+ await readBoundedResponseBytes(response, API_ERROR_MAX_BYTES, null)
2649
+ );
2650
+ } catch {
2651
+ return "";
2652
+ }
2653
+ }
2654
+ function isJsonContentType(value) {
2655
+ return /^(application\/json|[^;]+\+json)\s*(;|$)/i.test(value ?? "");
2656
+ }
2657
+ function isMutationMethod(method) {
2658
+ return method !== "GET" && method !== "HEAD" && method !== "OPTIONS";
2659
+ }
2660
+ function mutationTransportError(correlationId) {
2661
+ return new OpenGeniApiError(0, "", {
2662
+ code: "network_error",
2663
+ retryable: true,
2664
+ correlationId,
2665
+ outcomeUnknown: true,
2666
+ mutation: true,
2667
+ displayMessage: "OpenGeni could not confirm the request \u2014 reconcile before retrying."
2668
+ });
2669
+ }
2670
+ async function sha256ForUpload(body) {
2671
+ const bytes = typeof body === "string" ? new TextEncoder().encode(body) : body instanceof Blob ? new Uint8Array(await body.arrayBuffer()) : new Uint8Array(body);
2672
+ const digest = await globalThis.crypto.subtle.digest("SHA-256", bytes);
2673
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, "0")).join("");
2674
+ }
2675
+ async function cancelResponseBody(response, reason) {
2676
+ await response.body?.cancel(reason).catch(() => void 0);
2677
+ }
2678
+ function parseBoundedContentLength(value) {
2679
+ if (value === null) return null;
2680
+ if (!/^\d+$/.test(value)) {
2681
+ throw new OpenGeniApiError(502, "invalid retained artifact content-length");
2682
+ }
2683
+ const length = Number(value);
2684
+ if (!Number.isSafeInteger(length) || length > RETAINED_OUTPUT_MAX_PAGE_BYTES) {
2685
+ throw new OpenGeniApiError(502, "retained artifact response exceeds the SDK byte limit");
2686
+ }
2687
+ return length;
2688
+ }
2689
+ async function readBoundedResponseBytes(response, maxBytes, expectedBytes) {
2690
+ if (!response.body) {
2691
+ if (expectedBytes !== null && expectedBytes !== 0) {
2692
+ throw new OpenGeniApiError(502, "retained artifact response length mismatch");
2693
+ }
2694
+ return new Uint8Array();
2695
+ }
2696
+ const reader = response.body.getReader();
2697
+ const chunks = [];
2698
+ let totalBytes = 0;
2699
+ try {
2700
+ while (true) {
2701
+ const { done, value } = await reader.read();
2702
+ if (done) break;
2703
+ totalBytes += value.byteLength;
2704
+ if (totalBytes > maxBytes) {
2705
+ await reader.cancel("retained artifact response exceeded the SDK byte limit").catch(() => void 0);
2706
+ throw new OpenGeniApiError(502, "retained artifact response exceeds the SDK byte limit");
2707
+ }
2708
+ chunks.push(value);
2709
+ }
2710
+ } finally {
2711
+ reader.releaseLock();
2712
+ }
2713
+ if (expectedBytes !== null && totalBytes !== expectedBytes) {
2714
+ throw new OpenGeniApiError(502, "retained artifact response length mismatch");
2715
+ }
2716
+ const bytes = new Uint8Array(totalBytes);
2717
+ let offset = 0;
2718
+ for (const chunk of chunks) {
2719
+ bytes.set(chunk, offset);
2720
+ offset += chunk.byteLength;
2721
+ }
2722
+ return bytes;
2723
+ }
2724
+
2725
+ // src/transcription.ts
2726
+ var DEFAULT_WORKSPACE_TRANSCRIPTION_POLICY = {
2727
+ enabled: false,
2728
+ acceptanceId: null,
2729
+ primary: null,
2730
+ language: null,
2731
+ autoDetectLanguage: false,
2732
+ diarization: { enabled: false, maxSpeakers: null },
2733
+ retention: { mode: "none", maxDays: null },
2734
+ privacy: { allowProviderLogging: false, allowProviderTraining: false },
2735
+ fallback: { mode: "disabled", targets: [] },
2736
+ cost: { currency: "USD", maxPerHour: null, maxPerMonth: null }
2737
+ };
2738
+ function resolveWorkspaceVoiceInputEnabled(settings) {
2739
+ if (!isRecord(settings)) return null;
2740
+ const voiceInput = settings.voiceInput;
2741
+ if (isRecord(voiceInput) && typeof voiceInput.enabled === "boolean") {
2742
+ return voiceInput.enabled;
2743
+ }
2744
+ const legacy = settings.transcription;
2745
+ return isRecord(legacy) && typeof legacy.enabled === "boolean" ? legacy.enabled : null;
2746
+ }
2747
+ function resolveWorkspaceTranscriptionPolicy(settings) {
2748
+ if (!isRecord(settings)) return cloneDefaultPolicy();
2749
+ const candidate = settings.transcription;
2750
+ if (!isWorkspaceTranscriptionPolicy(candidate)) return cloneDefaultPolicy();
2751
+ return {
2752
+ ...candidate,
2753
+ primary: candidate.primary ? normalizeTarget(candidate.primary) : null,
2754
+ language: candidate.language?.trim() ?? null,
2755
+ diarization: { ...candidate.diarization },
2756
+ retention: { ...candidate.retention },
2757
+ privacy: { ...candidate.privacy },
2758
+ fallback: {
2759
+ mode: candidate.fallback.mode,
2760
+ targets: candidate.fallback.targets.map(normalizeTarget)
2761
+ },
2762
+ cost: { ...candidate.cost }
2763
+ };
2764
+ }
2765
+ function authorizeTranscriptionAdapter(policy, descriptor, selection = { kind: "primary" }) {
2766
+ if (!isWorkspaceTranscriptionPolicy(policy)) {
2767
+ return { authorized: false, reason: "unaccepted" };
2768
+ }
2769
+ if (!policy.enabled) return { authorized: false, reason: "disabled" };
2770
+ if (!policy.acceptanceId) return { authorized: false, reason: "unaccepted" };
2771
+ let target;
2772
+ if (selection.kind === "primary") {
2773
+ target = policy.primary;
2774
+ } else {
2775
+ if (policy.fallback.mode !== "explicit") {
2776
+ return { authorized: false, reason: "fallback_disabled" };
2777
+ }
2778
+ target = policy.fallback.targets[selection.index];
2779
+ if (!target) return { authorized: false, reason: "fallback_unaccepted" };
2780
+ }
2781
+ if (!target) return { authorized: false, reason: "target_missing" };
2782
+ const acceptedTarget = normalizeTarget(target);
2783
+ if (acceptedTarget.provider !== descriptor.provider) {
2784
+ return { authorized: false, reason: "provider_mismatch" };
2785
+ }
2786
+ if (acceptedTarget.model !== descriptor.model) {
2787
+ return { authorized: false, reason: "model_mismatch" };
2788
+ }
2789
+ if (acceptedTarget.credentialMode !== descriptor.credentialMode) {
2790
+ return { authorized: false, reason: "credential_mode_mismatch" };
2791
+ }
2792
+ if (acceptedTarget.region !== descriptor.region) {
2793
+ return { authorized: false, reason: "region_mismatch" };
2794
+ }
2795
+ return {
2796
+ authorized: true,
2797
+ acceptanceId: policy.acceptanceId,
2798
+ target: acceptedTarget,
2799
+ selection
2800
+ };
2801
+ }
2802
+ function createTranscriptionSessionRequest(input) {
2803
+ const sequenceFloor = input.sequenceFloor ?? 0;
2804
+ if (!Number.isSafeInteger(sequenceFloor) || sequenceFloor < 0) return null;
2805
+ const authorization = authorizeTranscriptionAdapter(
2806
+ input.policy,
2807
+ input.adapter.descriptor,
2808
+ input.selection
2809
+ );
2810
+ if (!authorization.authorized) return null;
2811
+ return {
2812
+ localSessionId: input.localSessionId,
2813
+ policyAcceptanceId: authorization.acceptanceId,
2814
+ selection: authorization.selection,
2815
+ target: { ...authorization.target },
2816
+ language: input.policy.language?.trim() ?? null,
2817
+ autoDetectLanguage: input.policy.autoDetectLanguage,
2818
+ diarization: { ...input.policy.diarization },
2819
+ retention: { ...input.policy.retention },
2820
+ privacy: { ...input.policy.privacy },
2821
+ cost: { ...input.policy.cost },
2822
+ sequenceFloor
2823
+ };
2824
+ }
2825
+ function cloneDefaultPolicy() {
2826
+ return {
2827
+ ...DEFAULT_WORKSPACE_TRANSCRIPTION_POLICY,
2828
+ diarization: { ...DEFAULT_WORKSPACE_TRANSCRIPTION_POLICY.diarization },
2829
+ retention: { ...DEFAULT_WORKSPACE_TRANSCRIPTION_POLICY.retention },
2830
+ privacy: { ...DEFAULT_WORKSPACE_TRANSCRIPTION_POLICY.privacy },
2831
+ fallback: { mode: "disabled", targets: [] },
2832
+ cost: { ...DEFAULT_WORKSPACE_TRANSCRIPTION_POLICY.cost }
2833
+ };
2834
+ }
2835
+ function isWorkspaceTranscriptionPolicy(value) {
2836
+ if (!isRecord(value) || typeof value.enabled !== "boolean") return false;
2837
+ if (!hasOnlyKeys(value, [
2838
+ "enabled",
2839
+ "acceptanceId",
2840
+ "primary",
2841
+ "language",
2842
+ "autoDetectLanguage",
2843
+ "diarization",
2844
+ "retention",
2845
+ "privacy",
2846
+ "fallback",
2847
+ "cost"
2848
+ ])) {
2849
+ return false;
2850
+ }
2851
+ if (!(value.acceptanceId === null || isUuid(value.acceptanceId))) return false;
2852
+ if (!(value.primary === null || isTarget(value.primary))) return false;
2853
+ if (!(value.language === null || isBoundedString(value.language, 64))) return false;
2854
+ if (typeof value.autoDetectLanguage !== "boolean") return false;
2855
+ if (!isRecord(value.diarization) || !hasOnlyKeys(value.diarization, ["enabled", "maxSpeakers"]) || typeof value.diarization.enabled !== "boolean" || !(value.diarization.maxSpeakers === null || isBoundedInteger(value.diarization.maxSpeakers, 100) && value.diarization.maxSpeakers >= 2)) {
2856
+ return false;
2857
+ }
2858
+ if (!value.diarization.enabled && value.diarization.maxSpeakers !== null) return false;
2859
+ if (!isRecord(value.retention) || !hasOnlyKeys(value.retention, ["mode", "maxDays"])) {
2860
+ return false;
2861
+ }
2862
+ if (value.retention.mode !== "none" && value.retention.mode !== "provider-policy") return false;
2863
+ if (!(value.retention.maxDays === null || isBoundedInteger(value.retention.maxDays, 3650))) {
2864
+ return false;
2865
+ }
2866
+ if (!isRecord(value.privacy) || !hasOnlyKeys(value.privacy, ["allowProviderLogging", "allowProviderTraining"]) || typeof value.privacy.allowProviderLogging !== "boolean" || typeof value.privacy.allowProviderTraining !== "boolean") {
2867
+ return false;
2868
+ }
2869
+ if (!isRecord(value.fallback) || !hasOnlyKeys(value.fallback, ["mode", "targets"])) {
2870
+ return false;
2871
+ }
2872
+ if (value.fallback.mode !== "disabled" && value.fallback.mode !== "explicit") return false;
2873
+ if (!Array.isArray(value.fallback.targets) || value.fallback.targets.length > 8 || !value.fallback.targets.every(isTarget)) {
2874
+ return false;
2875
+ }
2876
+ if (value.fallback.mode === "disabled" && value.fallback.targets.length !== 0) return false;
2877
+ if (value.fallback.mode === "explicit" && value.fallback.targets.length === 0) return false;
2878
+ if (!isRecord(value.cost) || !hasOnlyKeys(value.cost, ["currency", "maxPerHour", "maxPerMonth"]) || value.cost.currency !== "USD") {
2879
+ return false;
2880
+ }
2881
+ if (!isNullableBoundedNumber(value.cost.maxPerHour, 1e4)) return false;
2882
+ if (!isNullableBoundedNumber(value.cost.maxPerMonth, 1e6)) return false;
2883
+ if (value.enabled && (!value.acceptanceId || !value.primary)) return false;
2884
+ if (value.enabled && !value.autoDetectLanguage && value.language === null) return false;
2885
+ if (value.autoDetectLanguage && value.language !== null) return false;
2886
+ const targets = [value.primary, ...value.fallback.targets].filter(
2887
+ (target) => target !== null
2888
+ );
2889
+ if (new Set(targets.map(targetKey)).size !== targets.length) return false;
2890
+ return true;
2891
+ }
2892
+ function targetKey(target) {
2893
+ return [
2894
+ target.provider.trim(),
2895
+ target.model?.trim() ?? "",
2896
+ target.credentialMode,
2897
+ target.credentialConnectionId ?? "",
2898
+ target.region?.trim() ?? ""
2899
+ ].join("\0");
2900
+ }
2901
+ function isTarget(value) {
2902
+ if (!isRecord(value)) return false;
2903
+ if (!hasOnlyKeys(value, ["provider", "model", "credentialMode", "credentialConnectionId", "region"])) {
2904
+ return false;
2905
+ }
2906
+ if (!isBoundedString(value.provider, 128)) return false;
2907
+ if (!(value.model === null || isBoundedString(value.model, 256))) return false;
2908
+ if (value.credentialMode !== "managed" && value.credentialMode !== "byok") return false;
2909
+ if (value.provider.trim() === "azure-speech" && value.credentialMode !== "byok") return false;
2910
+ if (!(value.credentialConnectionId === null || isUuid(value.credentialConnectionId))) {
2911
+ return false;
2912
+ }
2913
+ if (!(value.region === null || isBoundedString(value.region, 128))) return false;
2914
+ if (value.credentialMode === "byok" && value.credentialConnectionId === null) return false;
2915
+ if (value.credentialMode === "managed" && value.credentialConnectionId !== null) return false;
2916
+ return true;
2917
+ }
2918
+ function normalizeTarget(target) {
2919
+ return {
2920
+ provider: target.provider.trim(),
2921
+ model: target.model?.trim() ?? null,
2922
+ credentialMode: target.credentialMode,
2923
+ credentialConnectionId: target.credentialConnectionId,
2924
+ region: target.region?.trim() ?? null
2925
+ };
2926
+ }
2927
+ function isRecord(value) {
2928
+ return typeof value === "object" && value !== null;
2929
+ }
2930
+ function hasOnlyKeys(value, keys) {
2931
+ const accepted = new Set(keys);
2932
+ return Object.keys(value).every((key) => accepted.has(key));
2933
+ }
2934
+ function isBoundedString(value, maximum) {
2935
+ return typeof value === "string" && value.trim().length > 0 && value.length <= maximum;
2936
+ }
2937
+ function isUuid(value) {
2938
+ return typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
2939
+ }
2940
+ function isBoundedInteger(value, maximum) {
2941
+ return Number.isInteger(value) && value >= 0 && value <= maximum;
2942
+ }
2943
+ function isNullableBoundedNumber(value, maximum) {
2944
+ return value === null || typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= maximum;
2945
+ }
2946
+
2947
+ export {
2948
+ OpenGeniApiError,
2949
+ OpenGeniSessionListCursorError,
2950
+ OpenGeniApiContractMismatchError,
2951
+ OpenGeniStreamError,
2952
+ isRetryableStreamError,
2953
+ parseSseStream,
2954
+ streamSessionEvents,
2955
+ streamWorkspaceControlEvents,
2956
+ SESSION_EVENT_TYPES,
2957
+ KNOWN_PERMISSIONS,
2958
+ OPENGENI_API_CONTRACT_REVISION,
2959
+ OPENGENI_API_CONTRACT_HEADER,
2960
+ OPENGENI_CORRELATION_HEADER,
2961
+ RETAINED_OUTPUT_DEFAULT_PAGE_BYTES,
2962
+ RETAINED_OUTPUT_MAX_PAGE_BYTES,
2963
+ KNOWN_USAGE_EVENT_TYPES,
2964
+ OpenGeniClient,
2965
+ DEFAULT_WORKSPACE_TRANSCRIPTION_POLICY,
2966
+ resolveWorkspaceVoiceInputEnabled,
2967
+ resolveWorkspaceTranscriptionPolicy,
2968
+ authorizeTranscriptionAdapter,
2969
+ createTranscriptionSessionRequest
2970
+ };
2971
+ //# sourceMappingURL=chunk-YROWFD7R.js.map