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