@granular-software/sdk 0.4.18 → 0.4.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1995 @@
1
+ import * as Automerge from '@automerge/automerge';
2
+ import { Doc } from '@automerge/automerge/slim';
3
+
4
+ /**
5
+ * @module @granular-software/sdk/types
6
+ * Type definitions for the Granular SDK
7
+ */
8
+ /**
9
+ * Configuration for the Granular client
10
+ */
11
+ type AccessTokenProvider = () => Promise<string | null | undefined> | string | null | undefined;
12
+ type EndpointMode = 'auto' | 'local' | 'production';
13
+ interface GranularOptions {
14
+ /** Your Granular API key (for service/CLI auth; use with GRANULAR_API_KEY) */
15
+ apiKey?: string;
16
+ /** Application/session JWT (for user-context auth; use from simulator or getAccessToken) */
17
+ token?: string;
18
+ /** Optional provider used to refresh JWT before WebSocket (re)connect attempts */
19
+ tokenProvider?: AccessTokenProvider;
20
+ /** Optional API URL (for on-prem or testing) */
21
+ apiUrl?: string;
22
+ /** Optional endpoint mode when apiUrl is not explicitly provided */
23
+ endpointMode?: EndpointMode;
24
+ /** Optional WebSocket constructor (for Node.js environments) */
25
+ WebSocketCtor?: any;
26
+ /**
27
+ * Optional callback invoked when a connected WebSocket closes unexpectedly.
28
+ * Useful for forwarding close diagnostics to monitoring (e.g., Sentry).
29
+ */
30
+ onUnexpectedClose?: (info: WSDisconnectInfo) => void;
31
+ /**
32
+ * Optional callback invoked when automatic reconnect fails.
33
+ * Useful to capture auth or gateway rejection causes.
34
+ */
35
+ onReconnectError?: (info: WSReconnectErrorInfo) => void;
36
+ }
37
+ /** Resolved auth credential: either apiKey or token must be provided */
38
+ type GranularAuth = string;
39
+ /**
40
+ * A user/subject object returned from recordUser()
41
+ */
42
+ interface User {
43
+ /** Internal Granular user identifier */
44
+ granularId: string;
45
+ /** External user identifier from your app */
46
+ userId: string;
47
+ /** @deprecated Use `granularId` instead */
48
+ subjectId: string;
49
+ /** @deprecated Use `userId` instead */
50
+ identityId: string;
51
+ /** User's display name */
52
+ name?: string;
53
+ /** User's email */
54
+ email?: string;
55
+ /** Permission profile IDs to be assigned when connecting */
56
+ permissions: string[];
57
+ }
58
+ /**
59
+ * Options for recording a user
60
+ */
61
+ interface RecordUserOptions {
62
+ /** External user/identity ID (e.g. your Auth0 or database user ID) */
63
+ userId: string;
64
+ /** User's display name */
65
+ name?: string;
66
+ /** User's email */
67
+ email?: string;
68
+ /** Permission profile IDs to assign when connecting to sandboxes */
69
+ permissions?: string[];
70
+ }
71
+ /**
72
+ * Subject as returned from the API
73
+ */
74
+ interface Subject {
75
+ /** Internal Granular user identifier */
76
+ granularId: string;
77
+ /** External user identifier from your app */
78
+ userId: string;
79
+ subjectId: string;
80
+ tenantId: string;
81
+ identityId: string;
82
+ email?: string | null;
83
+ name?: string | null;
84
+ metadata?: Record<string, unknown>;
85
+ createdAt: number;
86
+ updatedAt: number;
87
+ }
88
+ /**
89
+ * Options for connecting to an ontology environment
90
+ */
91
+ interface ConnectOptions {
92
+ /** The ontology name or ID to connect to */
93
+ ontology: string;
94
+ /** Named environment slot such as `dev` or `prod` */
95
+ environment: string;
96
+ /** Advanced override for the version tag/channel to follow. In the common case, omit this. */
97
+ tagName?: string;
98
+ /**
99
+ * External user identifier from your app. This is the primary input for
100
+ * connecting to a sandbox and the only required user field in the common case.
101
+ */
102
+ userId?: string;
103
+ /**
104
+ * Internal Granular user identifier. Optional fallback when you only know
105
+ * the Granular-side ID for an existing subject.
106
+ */
107
+ granularId?: string;
108
+ /** Optional display name used when upserting the user */
109
+ name?: string;
110
+ /** Optional email used when upserting the user */
111
+ email?: string;
112
+ /** Permission profile IDs or names to ensure before connecting */
113
+ permissions?: string[];
114
+ /** Backwards-compatible user object returned from recordUser() */
115
+ user?: User;
116
+ /** Optional stable client ID. Defaults to `client_${Date.now()}`. Use a fixed
117
+ * value for long-lived effect hosts so tool catalogs don't accumulate. */
118
+ clientId?: string;
119
+ /** Optional session heap seed. Each item is eagerly hydrated into the session heap on connect. */
120
+ initialHeap?: Array<{
121
+ className: string;
122
+ id: string;
123
+ }>;
124
+ }
125
+ /**
126
+ * Control-plane session row: one real-time conversation thread with the agent for an environment.
127
+ */
128
+ interface ConversationSessionInfo {
129
+ sessionId: string;
130
+ tenantId?: string;
131
+ environmentId: string;
132
+ versionId?: string | null;
133
+ docId: string;
134
+ status: 'active' | 'closed' | 'expired';
135
+ createdAt: string;
136
+ lastSeenAt: string;
137
+ summary?: string | null;
138
+ summaryUpdatedAt?: string | null;
139
+ subjectId?: string | null;
140
+ jobCount?: number;
141
+ toolCallCount?: number;
142
+ }
143
+ /**
144
+ * A sandbox container
145
+ */
146
+ interface Sandbox {
147
+ sandboxId: string;
148
+ tenantId: string;
149
+ name: string;
150
+ description?: string | null;
151
+ createdAt: number;
152
+ updatedAt: number;
153
+ }
154
+ /**
155
+ * Data for creating a new sandbox
156
+ */
157
+ interface CreateSandboxData {
158
+ name: string;
159
+ description?: string;
160
+ }
161
+ /**
162
+ * List response for sandboxes
163
+ */
164
+ interface SandboxListResponse {
165
+ items: Sandbox[];
166
+ }
167
+ /**
168
+ * Rules defining what effects and resources are allowed or denied.
169
+ */
170
+ interface PermissionRules {
171
+ /** Effect access rules */
172
+ effects?: {
173
+ /** Patterns for allowed effects (e.g. ["*"] for all, ["read_*"] for prefix match) */
174
+ allow?: string[];
175
+ /** Patterns for denied effects */
176
+ deny?: string[];
177
+ };
178
+ /** Legacy alias accepted by the backend while migrating to `effects`. */
179
+ tools?: {
180
+ /** Patterns for allowed effects (e.g. ["*"] for all, ["read_*"] for prefix match) */
181
+ allow?: string[];
182
+ /** Patterns for denied effects */
183
+ deny?: string[];
184
+ };
185
+ /** Resource access rules */
186
+ resources?: {
187
+ /** Patterns for allowed resources */
188
+ allow?: string[];
189
+ /** Patterns for denied resources */
190
+ deny?: string[];
191
+ };
192
+ }
193
+ /**
194
+ * A permission profile defines access controls for an environment
195
+ */
196
+ interface PermissionProfile {
197
+ permissionProfileId: string;
198
+ sandboxId: string;
199
+ name: string;
200
+ rules: PermissionRules;
201
+ createdAt: number;
202
+ updatedAt: number;
203
+ }
204
+ /**
205
+ * Data for creating a new permission profile
206
+ */
207
+ interface CreatePermissionProfileData {
208
+ name: string;
209
+ rules: PermissionRules;
210
+ }
211
+ /**
212
+ * List response for permission profiles
213
+ */
214
+ interface PermissionProfileListResponse {
215
+ items: PermissionProfile[];
216
+ }
217
+ /**
218
+ * An assignment links a subject to a sandbox with a permission profile
219
+ */
220
+ interface Assignment {
221
+ assignmentId: string;
222
+ tenantId: string;
223
+ subjectId: string;
224
+ sandboxId: string;
225
+ permissionProfileId: string;
226
+ createdAt: number;
227
+ createdBy?: string | null;
228
+ }
229
+ /**
230
+ * List response for assignments
231
+ */
232
+ interface AssignmentListResponse {
233
+ items: Assignment[];
234
+ }
235
+ /**
236
+ * Version tracking policy for environments.
237
+ *
238
+ * Environments either follow a version tag such as `dev` or `prod`, or they
239
+ * pin themselves to one immutable ontology version.
240
+ */
241
+ interface BuildPolicy {
242
+ mode: 'tag' | 'current' | 'pinned';
243
+ buildId?: string;
244
+ versionId?: string;
245
+ tagId?: string;
246
+ tagName?: string;
247
+ }
248
+ type VersionTracking = BuildPolicy;
249
+ interface VersionTag {
250
+ tagId: string;
251
+ sandboxId: string;
252
+ name: string;
253
+ kind: 'channel' | 'release' | 'system';
254
+ targetBuildId?: string | null;
255
+ targetVersionId?: string | null;
256
+ description?: string | null;
257
+ protected?: boolean;
258
+ createdAt: number;
259
+ updatedAt: number;
260
+ }
261
+ /**
262
+ * An environment links a user (subject) to a sandbox with specific permissions
263
+ */
264
+ interface EnvironmentData {
265
+ environmentId: string;
266
+ sandboxId: string;
267
+ ontologyId?: string;
268
+ buildId: string;
269
+ versionId: string;
270
+ subjectId: string;
271
+ envName: string;
272
+ environment?: string;
273
+ permissionProfileId: string;
274
+ tagId?: string | null;
275
+ tag?: VersionTag | null;
276
+ tracking?: BuildPolicy;
277
+ buildPolicy: BuildPolicy;
278
+ updateState?: 'up_to_date' | 'update_available' | 'upgrading' | 'failed';
279
+ createdAt: number;
280
+ updatedAt: number;
281
+ }
282
+ /**
283
+ * Data for creating a new environment
284
+ */
285
+ interface CreateEnvironmentData {
286
+ /** The user/subject ID to create the environment for */
287
+ subjectId: string;
288
+ /** Named environment slot such as dev or prod */
289
+ environment?: string;
290
+ /** @deprecated Use `environment` instead. */
291
+ envName?: string;
292
+ /** The permission profile to apply (optional - uses assignment if not specified) */
293
+ permissionProfileId?: string | null;
294
+ /** Follow a tag directly */
295
+ tagId?: string;
296
+ /** Follow a tag by name, typically dev or prod */
297
+ tagName?: string;
298
+ /** Pin the environment to a specific version */
299
+ versionId?: string;
300
+ /** Legacy/compat environment tracking input */
301
+ buildPolicy?: BuildPolicy;
302
+ }
303
+ /**
304
+ * List response for environments
305
+ */
306
+ interface EnvironmentListResponse {
307
+ items: EnvironmentData[];
308
+ }
309
+ /**
310
+ * A manifest describes the structure and behavior of a sandbox
311
+ */
312
+ interface Manifest {
313
+ manifestId: string;
314
+ sandboxId: string;
315
+ version: string;
316
+ digest: string;
317
+ content?: Record<string, unknown>;
318
+ createdAt: number;
319
+ locked?: boolean;
320
+ }
321
+ /**
322
+ * List response for manifests
323
+ */
324
+ interface ManifestListResponse {
325
+ items: Manifest[];
326
+ }
327
+ type BuildStatus = 'queued' | 'building' | 'completed' | 'failed' | 'canceled';
328
+ /**
329
+ * An immutable ontology version derived from a specific manifest revision.
330
+ *
331
+ * The same version may have multiple build runs over time when the manifest
332
+ * content is unchanged but the compilation process is re-executed.
333
+ */
334
+ interface Build {
335
+ buildId: string;
336
+ sandboxId: string;
337
+ manifestId: string;
338
+ manifestDigest?: string;
339
+ versionNumber?: number;
340
+ status: BuildStatus;
341
+ graphBinaryId?: string | null;
342
+ logsUri?: string | null;
343
+ latestBuildRunId?: string | null;
344
+ buildRunId?: string;
345
+ createdNewVersion?: boolean;
346
+ environmentCount?: number;
347
+ laggingEnvironmentCount?: number;
348
+ sessionCount?: number;
349
+ createdAt: number;
350
+ updatedAt: number;
351
+ isCurrent?: boolean;
352
+ }
353
+ type Version = Build;
354
+ /**
355
+ * List response for versions
356
+ */
357
+ interface BuildListResponse {
358
+ items: Build[];
359
+ }
360
+ interface SemanticVersionDiffEntry {
361
+ operationId: string;
362
+ kind: 'create' | 'update' | 'relationship' | 'effect' | 'eventStream' | 'unknown';
363
+ changeType: 'added' | 'removed' | 'changed';
364
+ label: string;
365
+ additive: boolean;
366
+ breaking: boolean;
367
+ before?: Record<string, unknown>;
368
+ after?: Record<string, unknown>;
369
+ }
370
+ interface SemanticVersionDiff {
371
+ summary: {
372
+ added: number;
373
+ removed: number;
374
+ changed: number;
375
+ additive: number;
376
+ breaking: number;
377
+ onlyAdditiveChanges: boolean;
378
+ };
379
+ entries: SemanticVersionDiffEntry[];
380
+ }
381
+ /**
382
+ * Effect handler for static/global effects: receives (input, context)
383
+ */
384
+ interface EffectHandlerContext {
385
+ effectClientId: string;
386
+ sandboxId: string;
387
+ environmentId: string;
388
+ sessionId: string;
389
+ tenantId?: string;
390
+ principalId?: string;
391
+ permissionProfileId?: string;
392
+ user: {
393
+ granularId?: string;
394
+ userId?: string;
395
+ subjectId: string;
396
+ identityId?: string;
397
+ principalId?: string;
398
+ };
399
+ behaviors?: ResolvedEffectBehaviors;
400
+ invocation?: EffectInvocationMetadata;
401
+ }
402
+ interface ResolvedEffectPostCondition {
403
+ condition: string;
404
+ description?: string;
405
+ }
406
+ interface ResolvedEffectDryRun {
407
+ enabled: boolean;
408
+ description?: string;
409
+ }
410
+ interface ResolvedEffectReverse {
411
+ handler?: string;
412
+ description?: string;
413
+ }
414
+ interface ResolvedEffectApprovalRequired {
415
+ required: boolean;
416
+ reason?: string;
417
+ mode?: string;
418
+ }
419
+ interface ResolvedEffectBehaviors {
420
+ postCondition?: ResolvedEffectPostCondition;
421
+ dryRun?: ResolvedEffectDryRun;
422
+ reverse?: ResolvedEffectReverse;
423
+ approvalRequired?: ResolvedEffectApprovalRequired;
424
+ }
425
+ type EffectInvocationMode = 'execute' | 'dryRun' | 'reverse';
426
+ interface EffectInvocationMetadata {
427
+ mode?: EffectInvocationMode;
428
+ reverseHandler?: string;
429
+ sourceEffectKey?: string;
430
+ sourceEffectName?: string;
431
+ }
432
+ type ToolHandler = (input: any, context: EffectHandlerContext) => Promise<unknown>;
433
+ /**
434
+ * Effect handler for instance methods: receives (objectId, input, context)
435
+ */
436
+ type InstanceToolHandler = (id: string, input: any, context: EffectHandlerContext) => Promise<unknown>;
437
+ /**
438
+ * Effect schema for declaring or registering an effect.
439
+ *
440
+ * Effects come in three flavours:
441
+ *
442
+ * 1. **Instance methods** — set `className`, omit `static`.
443
+ * In the sandbox: `tolkien.get_bio({ detailed: true })`
444
+ * Handler signature: `(objectId: string, params: any) => any`
445
+ *
446
+ * 2. **Static methods** — set `className` + `static: true`.
447
+ * In the sandbox: `Author.search({ query: 'tolkien' })`
448
+ * Handler signature: `(params: any) => any`
449
+ *
450
+ * 3. **Global effects** — omit `className`.
451
+ * In the sandbox: `global_search({ query: 'rings' })`
452
+ * Handler signature: `(params: any) => any`
453
+ *
454
+ * Both `inputSchema` and `outputSchema` accept JSON Schema objects.
455
+ * The `outputSchema` drives the return type in the auto-generated
456
+ * TypeScript declarations that sandbox code imports from `./sandbox-tools`.
457
+ */
458
+ interface ToolSchema {
459
+ effectKey?: string;
460
+ name: string;
461
+ description: string;
462
+ /** JSON Schema for the effect input parameters */
463
+ inputSchema: Record<string, unknown>;
464
+ /**
465
+ * JSON Schema for the tool's return value.
466
+ * Used to generate typed return types in the sandbox TypeScript declarations.
467
+ *
468
+ * @example
469
+ * ```typescript
470
+ * outputSchema: {
471
+ * type: 'object',
472
+ * properties: {
473
+ * bio: { type: 'string', description: 'The biography text' },
474
+ * source: { type: 'string', description: 'Source of the bio' },
475
+ * },
476
+ * required: ['bio'],
477
+ * }
478
+ * // Generates: Promise<{ bio: string; source?: string }>
479
+ * ```
480
+ */
481
+ outputSchema?: Record<string, unknown>;
482
+ stability?: 'stable' | 'experimental' | 'deprecated';
483
+ provenance?: {
484
+ source: 'mcp' | 'custom';
485
+ };
486
+ tags?: string[];
487
+ /**
488
+ * The class this effect belongs to (e.g., `'author'`, `'book'`).
489
+ * When set, the effect becomes a method on the auto-generated class.
490
+ * Omit for global effects (standalone exported functions).
491
+ */
492
+ className?: string;
493
+ /**
494
+ * If `true`, this is a static/class-level method (no object ID required).
495
+ * If `false` or omitted and `className` is set, this is an instance method
496
+ * that operates on a specific object (the object's real-world ID is
497
+ * passed as the first argument to the handler).
498
+ */
499
+ static?: boolean;
500
+ /** Declarative runtime behaviors attached to the effect. */
501
+ metamodels?: ManifestEffectMetamodelSpec;
502
+ }
503
+ type EffectSchema = ToolSchema;
504
+ /**
505
+ * Effect with handler — what users provide to `registerEffect()`.
506
+ *
507
+ * - **Instance methods** (`className` set, `static` omitted):
508
+ * handler receives `(objectId: string, params: any)`
509
+ * - **Static methods** (`className` set, `static: true`):
510
+ * handler receives `(params: any)`
511
+ * - **Global tools** (no `className`):
512
+ * handler receives `(params: any)`
513
+ */
514
+ interface ToolWithHandler extends ToolSchema {
515
+ handler: ToolHandler | InstanceToolHandler;
516
+ dryRunHandler?: ToolHandler | InstanceToolHandler;
517
+ reverseHandler?: ToolHandler | InstanceToolHandler;
518
+ }
519
+ type EffectWithHandler = ToolWithHandler;
520
+ /**
521
+ * Result from publishing or synchronizing effects
522
+ */
523
+ interface PublishToolsResult {
524
+ accepted: boolean;
525
+ domainRevision: string;
526
+ rejected?: Array<{
527
+ name: string;
528
+ reason: string;
529
+ }>;
530
+ }
531
+ type PublishEffectsResult = PublishToolsResult;
532
+ /**
533
+ * Domain state response
534
+ */
535
+ interface DomainState {
536
+ activeDomainRevision?: string;
537
+ tools?: Array<{
538
+ name: string;
539
+ description?: string;
540
+ inputSchema?: Record<string, unknown>;
541
+ outputSchema?: Record<string, unknown>;
542
+ metamodels?: ManifestEffectMetamodelSpec;
543
+ }>;
544
+ [key: string]: unknown;
545
+ }
546
+ /**
547
+ * Information about a live or declared effect
548
+ */
549
+ interface ToolInfo {
550
+ effectKey?: string;
551
+ /** Unique name of the effect */
552
+ name: string;
553
+ /** Description of what the effect does */
554
+ description?: string;
555
+ /** JSON Schema for effect input */
556
+ inputSchema?: Record<string, unknown>;
557
+ /** JSON Schema for effect output */
558
+ outputSchema?: Record<string, unknown>;
559
+ /** Client ID that published this effect (absent for domain-only entries) */
560
+ clientId?: string;
561
+ /** Whether the effect is ready for use (has a registered handler) */
562
+ ready: boolean;
563
+ /** Timestamp when the effect was published */
564
+ publishedAt?: number;
565
+ /** Class this effect belongs to (instance/static method) */
566
+ className?: string;
567
+ /** Whether this is a static method */
568
+ static?: boolean;
569
+ /** Declarative runtime behaviors attached to the effect. */
570
+ metamodels?: ManifestEffectMetamodelSpec;
571
+ }
572
+ interface EffectInfo extends ToolInfo {
573
+ }
574
+ /**
575
+ * Event data when the list of available effects changes
576
+ */
577
+ interface ToolsChangedEvent {
578
+ /** The current list of all available effects */
579
+ tools: ToolInfo[];
580
+ /** Names of effects that were added or updated */
581
+ added: string[];
582
+ /** Names of effects that were removed */
583
+ removed: string[];
584
+ }
585
+ interface EffectsChangedEvent extends ToolsChangedEvent {
586
+ /** The current list of all available effects */
587
+ effects: EffectInfo[];
588
+ }
589
+ type EffectHandler = ToolHandler;
590
+ type InstanceEffectHandler = InstanceToolHandler;
591
+ type JobStatus = 'queued' | 'running' | 'awaitingTool' | 'awaitingHuman' | 'succeeded' | 'failed' | 'timeout' | 'canceled';
592
+ type JobFeedbackSentiment = 'good' | 'bad';
593
+ interface JobFeedbackToolCall {
594
+ callId?: string;
595
+ toolName?: string;
596
+ input?: unknown;
597
+ output?: unknown;
598
+ error?: string;
599
+ startedAt?: number;
600
+ completedAt?: number;
601
+ durationMs?: number | null;
602
+ }
603
+ interface JobFeedbackMetadata {
604
+ source: 'sdk';
605
+ status: JobStatus;
606
+ code: string;
607
+ domainRevision?: string;
608
+ createdAt: number;
609
+ startedAt?: number;
610
+ completedAt?: number;
611
+ durationMs?: number | null;
612
+ result?: unknown;
613
+ error?: string;
614
+ stdout: string[];
615
+ stderr: string[];
616
+ toolCalls: JobFeedbackToolCall[];
617
+ }
618
+ interface JobFeedbackInput {
619
+ sentiment: JobFeedbackSentiment;
620
+ comment?: string | null;
621
+ }
622
+ interface JobFeedbackRecord {
623
+ feedbackId: string;
624
+ tenantId?: string;
625
+ sessionId: string;
626
+ environmentId: string;
627
+ sandboxId?: string;
628
+ buildId?: string;
629
+ subjectId?: string;
630
+ jobId: string;
631
+ sentiment: JobFeedbackSentiment;
632
+ comment?: string | null;
633
+ metadata: JobFeedbackMetadata & Record<string, unknown>;
634
+ createdAt: number;
635
+ updatedAt: number;
636
+ }
637
+ /**
638
+ * Result from submitting a job
639
+ */
640
+ interface JobSubmitResult {
641
+ jobId: string;
642
+ }
643
+ /**
644
+ * Represents a job executed in the sandbox
645
+ */
646
+ interface Job {
647
+ /** Unique Job ID */
648
+ id: string;
649
+ /** Current status of the job */
650
+ status: JobStatus;
651
+ /** Promise that resolves with the job result */
652
+ result: Promise<unknown>;
653
+ /** Attach user feedback to this job and persist it with job/session metadata */
654
+ leaveFeedback(input: JobFeedbackInput): Promise<JobFeedbackRecord>;
655
+ /** Subscribe to job events */
656
+ on(event: string, handler: (data: unknown) => void): void;
657
+ }
658
+ interface Prompt {
659
+ id: string;
660
+ type: 'confirm' | 'choice' | 'input';
661
+ title: string;
662
+ message: string;
663
+ options?: Array<string | {
664
+ value: string;
665
+ label: string;
666
+ description?: string;
667
+ }>;
668
+ defaultValue?: unknown;
669
+ placeholder?: string;
670
+ allowEmpty?: boolean;
671
+ metadata?: Record<string, unknown>;
672
+ }
673
+ type SessionHeapFieldType = 'string' | 'number' | 'boolean' | 'null' | 'unknown';
674
+ interface SessionHeapFieldValue {
675
+ name: string;
676
+ type: SessionHeapFieldType;
677
+ value: string | number | boolean | null;
678
+ }
679
+ interface SessionHeapEntry {
680
+ path: string;
681
+ className: string;
682
+ id: string;
683
+ label?: string | null;
684
+ description?: string | null;
685
+ prototypes: string[];
686
+ fields: SessionHeapFieldValue[];
687
+ relatedJobIds: string[];
688
+ source: string;
689
+ createdAt: number;
690
+ updatedAt: number;
691
+ }
692
+ interface SessionHeapList {
693
+ name: string;
694
+ className: string;
695
+ paths: string[];
696
+ relatedJobIds: string[];
697
+ updatedAt: number;
698
+ }
699
+ interface SessionHeapVariable {
700
+ name: string;
701
+ kind: 'entry' | 'list' | 'scalar';
702
+ entryPath?: string;
703
+ listName?: string;
704
+ value?: string | number | boolean | null;
705
+ className?: string;
706
+ updatedAt: number;
707
+ }
708
+ interface SessionHeapSnapshot {
709
+ entriesByPath: Record<string, SessionHeapEntry>;
710
+ listsByName: Record<string, SessionHeapList>;
711
+ variablesByName: Record<string, SessionHeapVariable>;
712
+ updatedAt: number;
713
+ }
714
+ interface WSDisconnectInfo {
715
+ code?: number;
716
+ reason?: string;
717
+ wasClean?: boolean;
718
+ unexpected: boolean;
719
+ timestamp: number;
720
+ reconnectScheduled: boolean;
721
+ reconnectDelayMs?: number;
722
+ }
723
+ interface WSReconnectErrorInfo {
724
+ sessionId: string;
725
+ error: string;
726
+ timestamp: number;
727
+ }
728
+ interface WSClientOptions {
729
+ url: string;
730
+ sessionId: string;
731
+ token: string;
732
+ tokenProvider?: AccessTokenProvider;
733
+ WebSocketCtor?: any;
734
+ onUnexpectedClose?: (info: WSDisconnectInfo) => void;
735
+ onReconnectError?: (info: WSReconnectErrorInfo) => void;
736
+ }
737
+ interface RPCRequest {
738
+ type: 'rpc';
739
+ method: string;
740
+ params: unknown;
741
+ id: string;
742
+ }
743
+ interface RPCResponse {
744
+ type: 'rpc_result' | 'rpc_error';
745
+ id: string;
746
+ result?: unknown;
747
+ error?: {
748
+ code: number;
749
+ message: string;
750
+ data?: unknown;
751
+ };
752
+ }
753
+ interface SyncMessage {
754
+ type: 'sync';
755
+ message?: string | number[] | Uint8Array;
756
+ data?: number[];
757
+ }
758
+ interface RPCRequestFromServer {
759
+ type: 'rpc';
760
+ method: string;
761
+ params: unknown;
762
+ id: string;
763
+ }
764
+ interface ToolInvokeParams {
765
+ callId: string;
766
+ toolName: string;
767
+ input: unknown;
768
+ }
769
+ interface ToolResultParams {
770
+ callId: string;
771
+ result?: unknown;
772
+ error?: string | {
773
+ code: string;
774
+ message: string;
775
+ };
776
+ }
777
+ /**
778
+ * A model reference as returned from relationship queries
779
+ */
780
+ interface ModelRef {
781
+ path: string;
782
+ label?: string;
783
+ }
784
+ /**
785
+ * Relationship info as returned from the GraphQL API.
786
+ * Represents a typed, bidirectional relationship between two model types,
787
+ * seen from one model's perspective.
788
+ */
789
+ interface RelationshipInfo {
790
+ /** Unique name of this relationship definition */
791
+ name: string;
792
+ /** The submodel on this model that holds the relationship */
793
+ local_submodel: ModelRef;
794
+ /** Whether this side is a "many" collection */
795
+ local_is_many: boolean;
796
+ /** The submodel on the foreign model */
797
+ foreign_submodel: ModelRef;
798
+ /** Whether the foreign side is a "many" collection */
799
+ foreign_is_many: boolean;
800
+ /** The foreign model type */
801
+ foreign_model: ModelRef;
802
+ /** Computed relationship kind: "one_to_one" | "one_to_many" | "many_to_one" | "many_to_many" */
803
+ relationship_kind: 'one_to_one' | 'one_to_many' | 'many_to_one' | 'many_to_many';
804
+ }
805
+ /**
806
+ * Options for defining a relationship between two model types
807
+ */
808
+ interface DefineRelationshipOptions {
809
+ /** The model to define the relationship on (the "left" / "local" type) */
810
+ model: string;
811
+ /** The submodel name on the local model (e.g., "books") */
812
+ localSubmodel: string;
813
+ /** Whether the local side is "many" */
814
+ localIsMany: boolean;
815
+ /** The foreign model type (e.g., "book") */
816
+ foreignModel: string;
817
+ /** The submodel name on the foreign model (e.g., "author") */
818
+ foreignSubmodel: string;
819
+ /** Whether the foreign side is "many" */
820
+ foreignIsMany: boolean;
821
+ /** Optional relationship name (auto-generated if omitted) */
822
+ name?: string;
823
+ }
824
+ /**
825
+ * Options for creating or updating a class instance in the graph.
826
+ *
827
+ * `recordObject` uses the graph's `instantiate` (find-or-create) semantics:
828
+ * if an instance with the given `id` already exists under the class, its
829
+ * fields are updated in place; otherwise a new instance is created.
830
+ */
831
+ interface RecordObjectOptions {
832
+ /** The class to instantiate (e.g., "author") */
833
+ className: string;
834
+ /**
835
+ * Real-world object ID. Unique within its class, but two objects of
836
+ * different classes may share the same ID. Internally the SDK derives
837
+ * a unique graph path as `{className}__{id}`.
838
+ */
839
+ id: string;
840
+ /** Optional display label (defaults to `id`) */
841
+ label?: string;
842
+ /** Scalar field values to set on the instance */
843
+ fields?: Record<string, string | number | boolean | null>;
844
+ /**
845
+ * Relationship attachments.
846
+ * Keys are relationship submodel names. Values are real-world IDs
847
+ * (not graph paths) — the SDK resolves them using the foreign class
848
+ * derived from the relationship definition.
849
+ * - For a "one" side: pass a single target ID (string)
850
+ * - For a "many" side: pass an array of target IDs
851
+ */
852
+ relationships?: Record<string, string | string[]>;
853
+ }
854
+ /**
855
+ * Return value from `recordObject()`
856
+ */
857
+ interface RecordObjectResult {
858
+ /** The internal graph path (e.g., "author__tolkien") */
859
+ path: string;
860
+ /** The real-world object ID as provided by the caller (e.g., "tolkien") */
861
+ id: string;
862
+ /** Whether the instance was newly created (false = updated) */
863
+ created: boolean;
864
+ }
865
+ type RecordImportStatus = 'queued' | 'processing' | 'completed' | 'failed' | 'canceled';
866
+ type RecordImportItemStatus = 'queued' | 'processing' | 'completed' | 'failed' | 'canceled';
867
+ interface RecordImportStats {
868
+ totalRecords: number;
869
+ queuedRecords: number;
870
+ processingRecords: number;
871
+ completedRecords: number;
872
+ failedRecords: number;
873
+ canceledRecords: number;
874
+ awaitingRecords: number;
875
+ }
876
+ interface RecordImportItem {
877
+ itemId: string;
878
+ importId: string;
879
+ tenantId: string;
880
+ environmentId: string;
881
+ className: string;
882
+ id: string;
883
+ label: string | null;
884
+ fields: Record<string, string | number | boolean | null> | null;
885
+ relationships: Record<string, string | string[]> | null;
886
+ status: RecordImportItemStatus;
887
+ attempts: number;
888
+ errorMessage: string | null;
889
+ resultPath: string | null;
890
+ resultCreated: boolean | null;
891
+ createdAt: number;
892
+ updatedAt: number;
893
+ processedAt: number | null;
894
+ }
895
+ interface RecordImport {
896
+ importId: string;
897
+ tenantId: string;
898
+ environmentId: string;
899
+ sandboxId: string;
900
+ subjectId: string;
901
+ status: RecordImportStatus;
902
+ batchSize: number;
903
+ errorMessage: string | null;
904
+ createdAt: number;
905
+ updatedAt: number;
906
+ startedAt: number | null;
907
+ finishedAt: number | null;
908
+ canceledAt: number | null;
909
+ stats: RecordImportStats;
910
+ }
911
+ interface EnvironmentRecordImportSummary extends RecordImportStats {
912
+ environmentId: string;
913
+ totalImports: number;
914
+ activeImports: number;
915
+ updatedAt: number;
916
+ }
917
+ /**
918
+ * Property specification in a manifest operation
919
+ */
920
+ interface ManifestPropertySpec {
921
+ value?: string | number | boolean;
922
+ ref?: string;
923
+ instanceOf?: string;
924
+ create?: string;
925
+ has?: Record<string, ManifestPropertySpec>;
926
+ type?: string;
927
+ description?: string;
928
+ required?: boolean;
929
+ note?: string | string[];
930
+ enum?: string[] | ManifestEnumRuleSpec;
931
+ filterBy?: boolean | string[] | ManifestFilterBySpec;
932
+ validate?: ManifestValidationRuleSpec[];
933
+ }
934
+ type ManifestValidationOperator = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'true' | 'false' | 'regex' | 'contains' | 'not_contains' | 'starts_with' | 'ends_with';
935
+ interface ManifestEnumRuleSpec {
936
+ values: string[];
937
+ message?: string;
938
+ }
939
+ interface ManifestFilterBySpec {
940
+ operators: string[];
941
+ scalarType?: string;
942
+ }
943
+ interface ManifestValidationRuleSpec {
944
+ operator: ManifestValidationOperator;
945
+ stringValue?: string;
946
+ numberValue?: number;
947
+ booleanValue?: boolean;
948
+ message?: string;
949
+ }
950
+ interface ManifestStateMachineStateSpec {
951
+ name: string;
952
+ isFinal?: boolean;
953
+ }
954
+ interface ManifestStateMachineTransitionSpec {
955
+ name: string;
956
+ from: string;
957
+ to: string;
958
+ }
959
+ interface ManifestStateMachineSpec {
960
+ name: string;
961
+ entryState: string;
962
+ states: Array<string | ManifestStateMachineStateSpec>;
963
+ transitions: ManifestStateMachineTransitionSpec[];
964
+ finalStates?: string[];
965
+ }
966
+ interface ManifestPostConditionSpec {
967
+ condition: string;
968
+ description?: string;
969
+ }
970
+ interface ManifestDryRunSpec {
971
+ enabled?: boolean;
972
+ description?: string;
973
+ }
974
+ interface ManifestReverseSpec {
975
+ handler?: string;
976
+ description?: string;
977
+ }
978
+ interface ManifestApprovalRequiredSpec {
979
+ required?: boolean;
980
+ reason?: string;
981
+ mode?: string;
982
+ }
983
+ interface ManifestEffectMetamodelSpec {
984
+ postCondition?: string | ManifestPostConditionSpec;
985
+ dryRun?: boolean | ManifestDryRunSpec;
986
+ reverse?: string | ManifestReverseSpec;
987
+ approvalRequired?: boolean | ManifestApprovalRequiredSpec;
988
+ }
989
+ /**
990
+ * Relationship definition between two classes
991
+ */
992
+ interface ManifestRelationshipDef {
993
+ /** Optional name (auto-generated from left_right if omitted) */
994
+ name?: string;
995
+ /** Left model path */
996
+ left: string;
997
+ /** Right model path */
998
+ right: string;
999
+ /** Submodel name on the left model */
1000
+ leftSubmodel: string;
1001
+ /** Submodel name on the right model */
1002
+ rightSubmodel: string;
1003
+ /** Whether the left side is a collection */
1004
+ leftIsMany: boolean;
1005
+ /** Whether the right side is a collection */
1006
+ rightIsMany: boolean;
1007
+ }
1008
+ interface ManifestEffectSchema {
1009
+ type: string;
1010
+ properties?: Record<string, unknown>;
1011
+ required?: string[];
1012
+ items?: unknown;
1013
+ description?: string;
1014
+ [key: string]: unknown;
1015
+ }
1016
+ interface ManifestEffectDeclaration {
1017
+ name: string;
1018
+ description?: string;
1019
+ attachedClass?: string;
1020
+ isStatic?: boolean;
1021
+ inputSchema: ManifestEffectSchema;
1022
+ outputSchema?: ManifestEffectSchema;
1023
+ stability?: 'stable' | 'experimental' | 'deprecated';
1024
+ tags?: string[];
1025
+ metamodels?: ManifestEffectMetamodelSpec;
1026
+ }
1027
+ /**
1028
+ * An event type within an event stream definition
1029
+ */
1030
+ interface ManifestEventTypeDef {
1031
+ name: string;
1032
+ description?: string;
1033
+ payloadSchema: ManifestEffectSchema;
1034
+ }
1035
+ /**
1036
+ * Event stream definition for outgoing typed events
1037
+ */
1038
+ interface ManifestEventStreamDef {
1039
+ name: string;
1040
+ description?: string;
1041
+ eventTypes: ManifestEventTypeDef[];
1042
+ }
1043
+ /**
1044
+ * A single operation in a manifest volume
1045
+ */
1046
+ interface ManifestOperation {
1047
+ /** Create a new model/class */
1048
+ create?: string;
1049
+ /** Target an existing model for modification */
1050
+ on?: string;
1051
+ /** Extend from a parent class */
1052
+ extends?: string;
1053
+ /** Instantiate a type */
1054
+ instanceOf?: string;
1055
+ /** Define submodels/fields */
1056
+ has?: Record<string, ManifestPropertySpec>;
1057
+ /** Advisory notes attached to the model/class itself */
1058
+ note?: string | string[];
1059
+ /** State machines attached to the created or targeted class */
1060
+ stateMachines?: ManifestStateMachineSpec[];
1061
+ /** Define a relationship between two classes */
1062
+ defineRelationship?: ManifestRelationshipDef;
1063
+ /** Declare a build-owned effect */
1064
+ withEffect?: ManifestEffectDeclaration;
1065
+ /** Define an outgoing event stream with typed events */
1066
+ defineEventStream?: ManifestEventStreamDef;
1067
+ }
1068
+ /**
1069
+ * A volume in a manifest
1070
+ */
1071
+ /**
1072
+ * Import descriptor for referencing modules
1073
+ */
1074
+ interface ManifestImport {
1075
+ /** Alias prefix used in operations (e.g., "@std") */
1076
+ alias: string;
1077
+ /** Module name (e.g., "standard_modules") */
1078
+ name: string;
1079
+ /** Version label (e.g., "prod", "v1.2.3") */
1080
+ label?: string;
1081
+ }
1082
+ interface ManifestVolume {
1083
+ name: string;
1084
+ scope: 'sandbox' | 'build' | 'user';
1085
+ imports?: ManifestImport[];
1086
+ operations: ManifestOperation[];
1087
+ }
1088
+ /**
1089
+ * A manifest defines the structure of a sandbox's data model
1090
+ */
1091
+ interface ManifestContent {
1092
+ schemaVersion: 2;
1093
+ name: string;
1094
+ description?: string;
1095
+ volumes: ManifestVolume[];
1096
+ }
1097
+ /**
1098
+ * Result from a GraphQL query execution
1099
+ */
1100
+ interface GraphQLResult<T = any> {
1101
+ data?: T;
1102
+ errors?: Array<{
1103
+ message: string;
1104
+ locations?: Array<{
1105
+ line: number;
1106
+ column: number;
1107
+ }>;
1108
+ path?: Array<string | number>;
1109
+ extensions?: Record<string, any>;
1110
+ }>;
1111
+ }
1112
+ interface APIError {
1113
+ error: string;
1114
+ message?: string;
1115
+ }
1116
+ interface DeleteResponse {
1117
+ deleted: boolean;
1118
+ }
1119
+ interface StreamEvent {
1120
+ eventId: string;
1121
+ streamName: string;
1122
+ eventType: string;
1123
+ payload: Record<string, unknown>;
1124
+ environmentId: string;
1125
+ sessionId?: string;
1126
+ subjectId?: string;
1127
+ source: 'sandbox' | 'api';
1128
+ isAcked: boolean;
1129
+ createdAt: number;
1130
+ }
1131
+ interface StreamSubscription {
1132
+ unsubscribe(): void;
1133
+ }
1134
+ interface StreamStats {
1135
+ streamName: string;
1136
+ eventType: string;
1137
+ total: number;
1138
+ last1h: number;
1139
+ last24h: number;
1140
+ unacked: number;
1141
+ }
1142
+
1143
+ declare class WSClient {
1144
+ private ws;
1145
+ private url;
1146
+ private sessionId;
1147
+ private token;
1148
+ private messageQueue;
1149
+ private syncHandlers;
1150
+ private rpcHandlers;
1151
+ private eventHandlers;
1152
+ private nextRpcId;
1153
+ doc: Automerge.Doc<Record<string, unknown>>;
1154
+ private syncState;
1155
+ private reconnectTimer;
1156
+ private tokenRefreshTimer;
1157
+ private isExplicitlyDisconnected;
1158
+ private options;
1159
+ constructor(options: WSClientOptions);
1160
+ get currentSessionId(): string;
1161
+ private clearTokenRefreshTimer;
1162
+ private decodeBase64Url;
1163
+ private getTokenExpiryMs;
1164
+ private scheduleTokenRefresh;
1165
+ private refreshTokenInBackground;
1166
+ private resolveTokenForConnect;
1167
+ /**
1168
+ * Connect to the WebSocket server
1169
+ * @returns {Promise<void>} Resolves when connection is open
1170
+ */
1171
+ connect(): Promise<void>;
1172
+ private normalizeReason;
1173
+ private rejectPending;
1174
+ private buildDisconnectError;
1175
+ private handleDisconnect;
1176
+ private handleMessage;
1177
+ /**
1178
+ * Make an RPC call to the server
1179
+ * @param {string} method - RPC method name
1180
+ * @param {unknown} params - Request parameters
1181
+ * @returns {Promise<unknown>} Response result
1182
+ * @throws {Error} If connection is closed or timeout occurs
1183
+ */
1184
+ call(method: string, params: unknown): Promise<unknown>;
1185
+ private handleIncomingRpc;
1186
+ /**
1187
+ * Subscribe to client events
1188
+ * @param {string} event - Event name
1189
+ * @param {Function} handler - Event handler
1190
+ */
1191
+ on(event: string, handler: (params: unknown) => void): void;
1192
+ /**
1193
+ * Register an RPC handler for incoming server requests
1194
+ * @param {string} method - RPC method name
1195
+ * @param {Function} handler - Handler function
1196
+ */
1197
+ registerRpcHandler(method: string, handler: (params: unknown) => Promise<unknown>): void;
1198
+ /**
1199
+ * Unsubscribe from client events
1200
+ * @param {string} event - Event name
1201
+ * @param {Function} handler - Handler to remove
1202
+ */
1203
+ off(event: string, handler: (params: unknown) => void): void;
1204
+ /**
1205
+ * Emit an event locally
1206
+ * @param {string} event - Event name
1207
+ * @param params - Event data
1208
+ */
1209
+ emit(event: string, params: unknown): void;
1210
+ /**
1211
+ * Disconnect the WebSocket and clear state
1212
+ */
1213
+ disconnect(): void;
1214
+ }
1215
+
1216
+ declare class Session {
1217
+ protected client: WSClient;
1218
+ private clientId;
1219
+ private jobsMap;
1220
+ private eventListeners;
1221
+ private toolHandlers;
1222
+ /** Tracks which tools are instance methods (className set, not static) */
1223
+ private instanceTools;
1224
+ private currentDomainRevision;
1225
+ /** Local effect registry: name → full ToolWithHandler */
1226
+ private effects;
1227
+ /** Last known tools for diffing */
1228
+ private lastKnownTools;
1229
+ /** Last seen live prompts, keyed by prompt id, for answer normalization */
1230
+ private promptCache;
1231
+ constructor(client: WSClient, clientId?: string);
1232
+ private extractDomainRevisionFromDoc;
1233
+ private buildLegacyEffectContext;
1234
+ get document(): Doc<Record<string, unknown>>;
1235
+ get sessionId(): string;
1236
+ get domainRevision(): string | null;
1237
+ /**
1238
+ * Make a raw RPC call to the session's Durable Object.
1239
+ *
1240
+ * Use this when you need to call an RPC method that doesn't have a
1241
+ * dedicated wrapper method on the Session/Environment class.
1242
+ *
1243
+ * @param method - RPC method name (e.g. 'domain.fetchPackagePart')
1244
+ * @param params - Request parameters
1245
+ * @returns The raw RPC response
1246
+ *
1247
+ * @example
1248
+ * ```typescript
1249
+ * const result = await env.rpc('domain.fetchPackagePart', {
1250
+ * moduleSpecifier: '@sandbox/domain',
1251
+ * part: 'types',
1252
+ * });
1253
+ * ```
1254
+ */
1255
+ rpc<T = unknown>(method: string, params?: Record<string, unknown>): Promise<T>;
1256
+ /**
1257
+ * Send client hello to establish the session
1258
+ */
1259
+ hello(): Promise<{
1260
+ ok: boolean;
1261
+ environmentId?: string;
1262
+ docId?: string;
1263
+ graphContainerStatus?: {
1264
+ lastKeepAliveAt: number;
1265
+ status: 'warming' | 'hot' | 'unknown';
1266
+ };
1267
+ }>;
1268
+ publishTools(tools: ToolWithHandler[], revision?: string): Promise<PublishToolsResult>;
1269
+ publishEffect(effect: ToolWithHandler): Promise<PublishToolsResult>;
1270
+ publishEffects(effects: ToolWithHandler[]): Promise<PublishToolsResult>;
1271
+ unpublishEffect(name: string): Promise<PublishToolsResult>;
1272
+ unpublishAllEffects(): Promise<PublishToolsResult>;
1273
+ /**
1274
+ * Submit a job to execute code in the sandbox.
1275
+ *
1276
+ * The code can import typed classes from `./sandbox-tools`:
1277
+ * ```typescript
1278
+ * import { Author, Book, global_search } from './sandbox-tools';
1279
+ *
1280
+ * const authors = await Author.list({ limit: 10, saveAs: 'recent_authors' });
1281
+ * const tolkien = await Author.get({ path: 'author_tolkien' });
1282
+ * const bio = await tolkien.get_bio({ detailed: true });
1283
+ * const books = await tolkien.get_books();
1284
+ * ```
1285
+ *
1286
+ * Effect calls (instance methods, static methods, global functions) trigger
1287
+ * `effect.invoke` RPC back to the sandbox effect host, where the registered handlers
1288
+ * execute locally and return the result to the sandbox.
1289
+ */
1290
+ submitJob(code: string, domainRevision?: string): Promise<Job>;
1291
+ /**
1292
+ * Register a handler for a specific tool.
1293
+ * @param isInstance - If true, handler will receive (id, params) for instance method dispatch.
1294
+ */
1295
+ registerToolHandler(name: string, handler: ToolHandler | InstanceToolHandler, isInstance?: boolean): void;
1296
+ /**
1297
+ * Respond to a prompt request from the sandbox
1298
+ */
1299
+ answerPrompt(promptId: string, answer: unknown): Promise<void>;
1300
+ /**
1301
+ * Get the current list of available effects.
1302
+ * Consolidates effect declarations and live availability for the session.
1303
+ */
1304
+ getEffects(): EffectInfo[];
1305
+ /**
1306
+ * Backwards-compatible alias for `getEffects()`.
1307
+ */
1308
+ getTools(): ToolInfo[];
1309
+ /**
1310
+ * Subscribe to effect changes (added, removed, updated).
1311
+ * @param callback - Function called with change events
1312
+ * @returns Unsubscribe function
1313
+ */
1314
+ onEffectsChanged(callback: (event: EffectsChangedEvent) => void): () => void;
1315
+ /**
1316
+ * Backwards-compatible alias for `onEffectsChanged()`.
1317
+ */
1318
+ onToolsChanged(callback: (event: ToolsChangedEvent) => void): () => void;
1319
+ /**
1320
+ * Get the current domain state and available tools
1321
+ */
1322
+ getDomain(): Promise<DomainState>;
1323
+ /**
1324
+ * Fetch a domain package part from the backend (no fallback).
1325
+ */
1326
+ private fetchDomainPart;
1327
+ /**
1328
+ * Get TypeScript class declarations for the current domain (for LLM/code gen).
1329
+ */
1330
+ getDomainTypes(): Promise<string>;
1331
+ /**
1332
+ * Get Markdown documentation for the current domain (human-readable).
1333
+ */
1334
+ getDomainDocs(): Promise<string>;
1335
+ /**
1336
+ * Get domain documentation for LLMs. Returns types (preferred) or fallback.
1337
+ */
1338
+ getDomainDocumentation(): Promise<string>;
1339
+ /**
1340
+ * Generate markdown documentation from the domain summary.
1341
+ * Class-aware: groups tools by class with property/relationship info.
1342
+ */
1343
+ private generateFallbackDocs;
1344
+ /**
1345
+ * Close the session and disconnect from the sandbox
1346
+ */
1347
+ disconnect(): Promise<void>;
1348
+ /**
1349
+ * Subscribe to session events
1350
+ */
1351
+ on(event: string, handler: (data: unknown) => void): void;
1352
+ /**
1353
+ * Unsubscribe from session events
1354
+ */
1355
+ off(event: string, handler: (data: unknown) => void): void;
1356
+ private setupToolInvokeHandler;
1357
+ private setupEventHandlers;
1358
+ protected emit(event: string, data: unknown): void;
1359
+ /**
1360
+ * Check for changes in the effect catalog and emit change events if needed.
1361
+ */
1362
+ private checkForToolChanges;
1363
+ }
1364
+
1365
+ /**
1366
+ * Environment represents a connected session to a sandbox for a specific user.
1367
+ *
1368
+ * After connecting, you can:
1369
+ * 1. Define your domain ontology via `applyManifest()` (classes, properties, relationships)
1370
+ * 2. Record object instances via `recordObject()` (with fields and relationship attachments)
1371
+ * 3. Register sandbox-scoped effects via `granular.registerEffect()` / `granular.registerEffects()`
1372
+ * 4. Submit jobs via `submitJob()` that import auto-generated typed classes from `./sandbox-tools`
1373
+ * 5. Execute GraphQL queries via `graphql()` (authenticated automatically)
1374
+ * 6. List available effects via `getEffects()` and listen for updates via `onEffectsChanged()`
1375
+ *
1376
+ * Tool calls from the sandbox automatically invoke your handlers via reverse-RPC.
1377
+ *
1378
+ * Object IDs are unique per class. Internally, the graph path is `{className}_{id}`
1379
+ * (e.g., `author_tolkien`). Use `Environment.toGraphPath()` and
1380
+ * `Environment.extractIdFromGraphPath()` for conversions.
1381
+ */
1382
+ declare class Environment extends Session {
1383
+ private envData;
1384
+ private _apiKey;
1385
+ private _apiEndpoint;
1386
+ constructor(client: WSClient, envData: EnvironmentData, clientId: string, apiKey: string, apiEndpoint: string);
1387
+ /** The environment ID */
1388
+ get environmentId(): string;
1389
+ /** The sandbox ID */
1390
+ get sandboxId(): string;
1391
+ /** The ontology ID */
1392
+ get ontologyId(): string;
1393
+ /** The subject ID */
1394
+ get subjectId(): string;
1395
+ /** The named environment slot, such as dev or prod */
1396
+ get envName(): string;
1397
+ /** The named environment slot, such as dev or prod */
1398
+ get environment(): string;
1399
+ /** The resolved ontology version backing this environment */
1400
+ get versionId(): string;
1401
+ /** Internal Granular user identifier for this environment */
1402
+ get granularId(): string;
1403
+ /** The permission profile ID */
1404
+ get permissionProfileId(): string;
1405
+ /** The GraphQL API endpoint URL */
1406
+ get apiEndpoint(): string;
1407
+ /**
1408
+ * Return a plain JS snapshot of the synced session heap.
1409
+ *
1410
+ * The heap lives in the Automerge document, so this method does not perform
1411
+ * any extra network roundtrip.
1412
+ */
1413
+ getHeap(): SessionHeapSnapshot;
1414
+ private getRuntimeBaseUrl;
1415
+ private controlPlaneRequest;
1416
+ /**
1417
+ * Close the session and disconnect from the sandbox.
1418
+ *
1419
+ * Sends `client.goodbye` over WebSocket first, then issues an HTTP fallback
1420
+ * to the runtime goodbye endpoint if no definitive WS-side runtime notify
1421
+ * acknowledgement was observed.
1422
+ */
1423
+ disconnect(): Promise<void>;
1424
+ /** The last known graph container status, updated by checkReadiness() or on heartbeat */
1425
+ graphContainerStatus: {
1426
+ lastKeepAliveAt: number;
1427
+ status: 'warming' | 'hot' | 'unknown';
1428
+ } | null;
1429
+ /**
1430
+ * Check if the graph container is ready and warm.
1431
+ *
1432
+ * Sends a lightweight heartbeat RPC to the Session DO which internally
1433
+ * pings the FalkorDB container. The response includes `graphContainerStatus`,
1434
+ * which is stored locally and emitted as a `readiness` event.
1435
+ *
1436
+ * Use this method to proactively warm the graph container before any
1437
+ * GraphQL query that requires it, or to poll the container's state in
1438
+ * the background.
1439
+ *
1440
+ * @returns The current graph container status object
1441
+ *
1442
+ * @example
1443
+ * ```typescript
1444
+ * const status = await env.checkReadiness();
1445
+ * console.log(status.status); // 'hot' | 'warming' | 'unknown'
1446
+ *
1447
+ * // Or listen for live updates
1448
+ * env.on('readiness', (status) => {
1449
+ * console.log('Graph is now:', status.status);
1450
+ * });
1451
+ * ```
1452
+ */
1453
+ checkReadiness(): Promise<{
1454
+ lastKeepAliveAt: number;
1455
+ status: 'warming' | 'hot' | 'unknown';
1456
+ }>;
1457
+ /**
1458
+ * Convert a class name + real-world ID into a unique graph path.
1459
+ *
1460
+ * Two objects of *different* classes may share the same real-world ID,
1461
+ * so the graph path must incorporate the class to guarantee uniqueness.
1462
+ *
1463
+ * Format: `{className}_{id}` — deterministic, human-readable.
1464
+ *
1465
+ * **Convention**: class names should be simple identifiers without
1466
+ * underscores (e.g. `author`, `book`). This ensures the prefix is
1467
+ * unambiguously parseable by `extractIdFromGraphPath`.
1468
+ */
1469
+ static toGraphPath(className: string, id: string): string;
1470
+ /**
1471
+ * Extract the real-world ID from a graph path, given the class name.
1472
+ *
1473
+ * Strips the `{className}_` prefix. Returns the raw path if the
1474
+ * expected prefix is not found.
1475
+ */
1476
+ static extractIdFromGraphPath(graphPath: string, className: string): string;
1477
+ /**
1478
+ * Execute a GraphQL query against the environment's graph.
1479
+ *
1480
+ * The query uses the Granular graph query language (based on Cypher/GraphQL).
1481
+ * Authentication is handled automatically using the SDK's API key.
1482
+ *
1483
+ * @param query - The GraphQL query string
1484
+ * @param variables - Optional variables for the query
1485
+ * @returns The query result data
1486
+ *
1487
+ * @example
1488
+ * ```typescript
1489
+ * // Read the workspace
1490
+ * const result = await env.graphql(
1491
+ * `query { model(path: "workspace") { path label submodels { path label } } }`
1492
+ * );
1493
+ * console.log(result.data);
1494
+ *
1495
+ * // Create a model
1496
+ * const created = await env.graphql(
1497
+ * `mutation { at(path: "workspace") { create_submodel(subpath: "my_node", label: "My Node", prototype: "Model") { model { path label } } } }`
1498
+ * );
1499
+ * ```
1500
+ */
1501
+ graphql<T = any>(query: string, variables?: Record<string, any>): Promise<GraphQLResult<T>>;
1502
+ /**
1503
+ * Define a relationship between two model types.
1504
+ *
1505
+ * Creates both submodels (if they don't exist) and links them with
1506
+ * a RelationshipDef node that encodes cardinality.
1507
+ *
1508
+ * @example
1509
+ * ```typescript
1510
+ * // Author has many Books, Book has one Author
1511
+ * const rel = await env.defineRelationship({
1512
+ * model: 'author',
1513
+ * localSubmodel: 'books',
1514
+ * localIsMany: true,
1515
+ * foreignModel: 'book',
1516
+ * foreignSubmodel: 'author',
1517
+ * foreignIsMany: false,
1518
+ * });
1519
+ * console.log(rel.relationship_kind); // "one_to_many"
1520
+ * ```
1521
+ */
1522
+ defineRelationship(options: DefineRelationshipOptions): Promise<RelationshipInfo>;
1523
+ /**
1524
+ * Get all relationships for a model type.
1525
+ *
1526
+ * @param modelPath - The model type path (e.g., "author")
1527
+ * @returns Array of relationships from this model's perspective
1528
+ *
1529
+ * @example
1530
+ * ```typescript
1531
+ * const rels = await env.getRelationships('author');
1532
+ * for (const rel of rels) {
1533
+ * console.log(`${rel.local_submodel.path} -> ${rel.foreign_model.path} (${rel.relationship_kind})`);
1534
+ * }
1535
+ * ```
1536
+ */
1537
+ getRelationships(modelPath: string): Promise<RelationshipInfo[]>;
1538
+ /**
1539
+ * Attach a target model to a relationship submodel.
1540
+ *
1541
+ * Handles cardinality automatically:
1542
+ * - "One" side: sets/replaces the reference
1543
+ * - "Many" side: adds the target to the collection
1544
+ *
1545
+ * If the target model doesn't exist, it's created as an instance of the foreign type.
1546
+ * Bidirectional sync is automatic.
1547
+ *
1548
+ * @param modelPath - The model instance path (e.g., "tolkien")
1549
+ * @param submodelPath - The relationship submodel (e.g., "books")
1550
+ * @param targetPath - The target model to attach (e.g., "lord_of_the_rings")
1551
+ *
1552
+ * @example
1553
+ * ```typescript
1554
+ * // Attach a book to an author (many side)
1555
+ * await env.attach('tolkien', 'books', 'lord_of_the_rings');
1556
+ * // This also automatically sets lord_of_the_rings:author -> tolkien
1557
+ * ```
1558
+ */
1559
+ attach(modelPath: string, submodelPath: string, targetPath: string): Promise<void>;
1560
+ /**
1561
+ * Detach a target model from a relationship submodel.
1562
+ *
1563
+ * Handles bidirectional cleanup automatically.
1564
+ *
1565
+ * @param modelPath - The model instance path
1566
+ * @param submodelPath - The relationship submodel
1567
+ * @param targetPath - The target to detach (optional for "one" side; omit on "many" side to detach all)
1568
+ *
1569
+ * @example
1570
+ * ```typescript
1571
+ * // Detach a specific book
1572
+ * await env.detach('tolkien', 'books', 'lord_of_the_rings');
1573
+ *
1574
+ * // Detach all books
1575
+ * await env.detach('tolkien', 'books');
1576
+ * ```
1577
+ */
1578
+ detach(modelPath: string, submodelPath: string, targetPath?: string): Promise<void>;
1579
+ /**
1580
+ * List all related models through a relationship submodel.
1581
+ *
1582
+ * @param modelPath - The model instance path
1583
+ * @param submodelPath - The relationship submodel
1584
+ * @returns Array of related model references
1585
+ *
1586
+ * @example
1587
+ * ```typescript
1588
+ * const books = await env.listRelated('tolkien', 'books');
1589
+ * console.log(books); // [{ path: "lord_of_the_rings", label: "Lord of the Rings" }, ...]
1590
+ * ```
1591
+ */
1592
+ listRelated(modelPath: string, submodelPath: string): Promise<ModelRef[]>;
1593
+ /**
1594
+ * Apply a manifest to the current environment's graph.
1595
+ *
1596
+ * Translates each manifest operation into GraphQL mutations and executes them
1597
+ * in order. This is the core mechanism for creating classes, fields, and
1598
+ * relationships from a declarative manifest.
1599
+ *
1600
+ * @param manifest - The manifest content to apply
1601
+ * @returns Summary of applied operations
1602
+ *
1603
+ * @example
1604
+ * ```typescript
1605
+ * await environment.applyManifest({
1606
+ * schemaVersion: 2,
1607
+ * name: 'my-app',
1608
+ * volumes: [{
1609
+ * name: 'schema',
1610
+ * scope: 'sandbox',
1611
+ * operations: [
1612
+ * { create: 'author', extends: 'class', has: { name: { type: 'string' } } },
1613
+ * { create: 'book', extends: 'class', has: { title: { type: 'string' } } },
1614
+ * { defineRelationship: {
1615
+ * left: 'author', right: 'book',
1616
+ * leftSubmodel: 'books', rightSubmodel: 'author',
1617
+ * leftIsMany: true, rightIsMany: false,
1618
+ * }},
1619
+ * ],
1620
+ * }],
1621
+ * });
1622
+ * ```
1623
+ */
1624
+ applyManifest(manifest: ManifestContent): Promise<{
1625
+ applied: number;
1626
+ errors: string[];
1627
+ }>;
1628
+ /**
1629
+ * Resolve an alias reference like "@std/class" → "class"
1630
+ * Strips the alias prefix, returning the bare model path.
1631
+ */
1632
+ private _resolveAlias;
1633
+ private _runGraphql;
1634
+ private _applyFieldMetamodels;
1635
+ private _applyModelMetamodels;
1636
+ private _ensureWorkspaceToolsRoot;
1637
+ private _storeEffectSchemas;
1638
+ private _applyEffectMetamodels;
1639
+ private _ensureWorkspaceStreamsRoot;
1640
+ private _applyEventStreamDeclaration;
1641
+ private _applyEffectDeclaration;
1642
+ /**
1643
+ * Apply a single manifest operation via GraphQL
1644
+ */
1645
+ private _applyOperation;
1646
+ /**
1647
+ * Apply field definitions (has) to a model via GraphQL
1648
+ */
1649
+ private _applyFields;
1650
+ /**
1651
+ * Create or update an instance of a class in the graph.
1652
+ *
1653
+ * Uses `instantiate` under the hood, which has find-or-create semantics:
1654
+ * if an instance with the given `id` already exists for the class it is
1655
+ * returned; otherwise a new instance is created. Fields are then set
1656
+ * (overwriting previous values) and relationships are attached.
1657
+ *
1658
+ * The graph path is derived as `{className}_{id}` to ensure uniqueness
1659
+ * across classes (two objects of different classes may share the same
1660
+ * real-world ID). Relationship targets are also resolved automatically
1661
+ * using the foreign class from the relationship definition.
1662
+ *
1663
+ * @param options - The object specification
1664
+ * @returns The graph path, real-world ID, and creation status
1665
+ *
1666
+ * @example
1667
+ * ```typescript
1668
+ * // Create an author with fields
1669
+ * const result = await env.recordObject({
1670
+ * className: 'author',
1671
+ * id: 'tolkien',
1672
+ * label: 'J.R.R. Tolkien',
1673
+ * fields: { name: 'J.R.R. Tolkien', birth_year: 1892 },
1674
+ * relationships: { books: ['lotr', 'silmarillion'] },
1675
+ * });
1676
+ * // result.path → 'author_tolkien' (internal graph path)
1677
+ * // result.id → 'tolkien' (real-world ID)
1678
+ * // result.created → true
1679
+ * ```
1680
+ */
1681
+ recordObject(options: RecordObjectOptions): Promise<RecordObjectResult>;
1682
+ /**
1683
+ * Batch version of `recordObject()`.
1684
+ *
1685
+ * Sends several upserts through the control-plane batch endpoint so the
1686
+ * server can collapse the graph mutations into far fewer round trips.
1687
+ */
1688
+ recordObjects(records: RecordObjectOptions[]): Promise<RecordObjectResult[]>;
1689
+ /**
1690
+ * Queue a background record import for this environment.
1691
+ */
1692
+ enqueueRecordImport(records: RecordObjectOptions[], options?: {
1693
+ batchSize?: number;
1694
+ }): Promise<RecordImport>;
1695
+ /**
1696
+ * List queued or completed record imports for this environment.
1697
+ */
1698
+ listRecordImports(status?: RecordImportStatus): Promise<RecordImport[]>;
1699
+ /**
1700
+ * Fetch the latest aggregate import counters for this environment.
1701
+ */
1702
+ getRecordImportSummary(): Promise<EnvironmentRecordImportSummary>;
1703
+ /**
1704
+ * Convenience helper returning queued + processing records for this environment.
1705
+ */
1706
+ getAwaitingRecordCount(): Promise<number>;
1707
+ /**
1708
+ * Fetch a single record import by id.
1709
+ */
1710
+ getRecordImport(importId: string): Promise<RecordImport>;
1711
+ /**
1712
+ * Cancel a queued/background record import.
1713
+ */
1714
+ cancelRecordImport(importId: string): Promise<RecordImport>;
1715
+ /**
1716
+ * Removed: environment-scoped effect publication is no longer supported.
1717
+ */
1718
+ publishTools(tools: ToolWithHandler[], revision?: string): Promise<PublishToolsResult>;
1719
+ /**
1720
+ * Removed: environment-scoped effect publication is no longer supported.
1721
+ */
1722
+ publishEffect(effect: ToolWithHandler): Promise<PublishToolsResult>;
1723
+ /**
1724
+ * Removed: environment-scoped effect publication is no longer supported.
1725
+ */
1726
+ publishEffects(effects: ToolWithHandler[]): Promise<PublishToolsResult>;
1727
+ /**
1728
+ * Removed: environment-scoped effect publication is no longer supported.
1729
+ */
1730
+ unpublishEffect(name: string): Promise<PublishToolsResult>;
1731
+ /**
1732
+ * Removed: environment-scoped effect publication is no longer supported.
1733
+ */
1734
+ unpublishAllEffects(): Promise<PublishToolsResult>;
1735
+ }
1736
+ declare class Granular {
1737
+ private apiKey;
1738
+ private apiUrl;
1739
+ private httpUrl;
1740
+ private tokenProvider?;
1741
+ private WebSocketCtor?;
1742
+ private onUnexpectedClose?;
1743
+ private onReconnectError?;
1744
+ private debugHttp;
1745
+ /** Sandbox-level effect registry: sandboxId → (effectKey → ToolWithHandler) */
1746
+ private sandboxEffects;
1747
+ /** Live sandbox-scoped effect hosts keyed by sandboxId */
1748
+ private sandboxEffectHosts;
1749
+ /** In-flight host connection promises to avoid duplicate concurrent connects */
1750
+ private sandboxEffectHostPromises;
1751
+ /**
1752
+ * Create a new Granular client
1753
+ * @param options - Client configuration
1754
+ */
1755
+ constructor(options: GranularOptions);
1756
+ /**
1757
+ * Records/upserts a user and prepares them for sandbox connections
1758
+ *
1759
+ * @param options - User options
1760
+ * @returns The recorded user with both `userId` and `granularId`
1761
+ *
1762
+ * @example
1763
+ * ```typescript
1764
+ * const user = await granular.recordUser({
1765
+ * userId: 'user_123',
1766
+ * name: 'John Doe',
1767
+ * permissions: ['agent'],
1768
+ * });
1769
+ * ```
1770
+ */
1771
+ recordUser(options: RecordUserOptions): Promise<User>;
1772
+ private resolveConnectUser;
1773
+ /**
1774
+ * Connect to an ontology environment and establish a real-time session.
1775
+ *
1776
+ * Effects are registered at the sandbox level via `granular.registerEffect()`
1777
+ * or `granular.registerEffects()`. Sessions pick up live availability from
1778
+ * the sandbox registry automatically.
1779
+ *
1780
+ * @param options - Connection options
1781
+ * @returns An active environment session
1782
+ *
1783
+ * @example
1784
+ * ```typescript
1785
+ * const environment = await granular.connect({
1786
+ * ontology: 'my-ontology',
1787
+ * environment: 'dev',
1788
+ * userId: 'user_123',
1789
+ * permissions: ['agent'],
1790
+ * });
1791
+ *
1792
+ * await granular.registerEffect('my-sandbox', {
1793
+ * name: 'greet',
1794
+ * description: 'Say hello',
1795
+ * inputSchema: { type: 'object', properties: {} },
1796
+ * handler: async () => 'Hello!',
1797
+ * });
1798
+ *
1799
+ * // Submit job
1800
+ * const job = await environment.submitJob(`
1801
+ * import { tools } from './sandbox-tools';
1802
+ * return await tools.greet({});
1803
+ * `);
1804
+ *
1805
+ * console.log(await job.result); // 'Hello!'
1806
+ * ```
1807
+ */
1808
+ connect(options: ConnectOptions): Promise<Environment>;
1809
+ /**
1810
+ * List active (open) sessions for an environment — each session is one agent conversation thread.
1811
+ */
1812
+ listOpenSessions(filters: {
1813
+ environmentId: string;
1814
+ }): Promise<ConversationSessionInfo[]>;
1815
+ /**
1816
+ * List closed sessions for an environment (conversations that have disconnected).
1817
+ */
1818
+ listClosedSessions(filters: {
1819
+ environmentId: string;
1820
+ }): Promise<ConversationSessionInfo[]>;
1821
+ private listSessionsForEnvironment;
1822
+ private normalizeConversationSession;
1823
+ private static coerceIsoDate;
1824
+ /**
1825
+ * Create a new session (conversation) for an existing environment and connect to it.
1826
+ * The runtime graph is shared across all sessions for the same environment.
1827
+ */
1828
+ createSession(options: {
1829
+ environmentId: string;
1830
+ clientId?: string;
1831
+ initialHeap?: ConnectOptions['initialHeap'];
1832
+ }): Promise<Environment>;
1833
+ /**
1834
+ * Connect to an existing open session (same conversation thread) using a freshly minted WebSocket token.
1835
+ */
1836
+ connectSession(options: {
1837
+ sessionId: string;
1838
+ clientId?: string;
1839
+ }): Promise<Environment>;
1840
+ /**
1841
+ * Mark a session closed in the control plane. If `environment` is the connected handle for that
1842
+ * `sessionId`, disconnects the WebSocket so the runtime tears down cleanly.
1843
+ */
1844
+ closeSession(sessionId: string, environment?: Environment | null): Promise<void>;
1845
+ /**
1846
+ * Re-open a closed session in the index and connect to its existing runtime document.
1847
+ */
1848
+ reopenSession(sessionId: string, options?: {
1849
+ clientId?: string;
1850
+ }): Promise<Environment>;
1851
+ private bindWebSocketEnvironment;
1852
+ private activateEnvironment;
1853
+ private getSandboxEffectMap;
1854
+ private serializeEffect;
1855
+ private publishSandboxEffectCatalog;
1856
+ private syncSandboxEffectCatalog;
1857
+ private recoverEffectHost;
1858
+ private startEffectHostHeartbeat;
1859
+ private stopEffectHostHeartbeat;
1860
+ private synchronizeEffectHost;
1861
+ private ensureSandboxEffectHost;
1862
+ private disconnectSandboxEffectHost;
1863
+ /**
1864
+ * Register an effect (tool) for a specific sandbox.
1865
+ *
1866
+ * @param sandboxNameOrId - The name or ID of the sandbox
1867
+ * @param effect - The tool definition and handler
1868
+ */
1869
+ registerEffect(sandboxNameOrId: string, effect: ToolWithHandler): Promise<void>;
1870
+ /**
1871
+ * Register multiple effects (tools) for a specific sandbox.
1872
+ *
1873
+ * batch version of `registerEffect`.
1874
+ */
1875
+ registerEffects(sandboxNameOrId: string, effects: ToolWithHandler[]): Promise<void>;
1876
+ /**
1877
+ * Unregister an effect from a sandbox.
1878
+ *
1879
+ * Removes it from the local sandbox registry and updates the
1880
+ * sandbox-scoped live catalog.
1881
+ */
1882
+ unregisterEffect(sandboxNameOrId: string, name: string): Promise<void>;
1883
+ /**
1884
+ * Disconnect one sandbox-scoped effect host, or all of them when no sandbox is provided.
1885
+ *
1886
+ * This is primarily useful for long-lived helper processes such as generated
1887
+ * `granular-effects.ts` scripts that need to shut down cleanly on SIGINT/SIGTERM.
1888
+ */
1889
+ disconnectEffects(sandboxNameOrId?: string): Promise<void>;
1890
+ /**
1891
+ * Unregister all effects for a sandbox.
1892
+ */
1893
+ unregisterAllEffects(sandboxNameOrId: string): Promise<void>;
1894
+ /**
1895
+ * Find a sandbox by name or create it if it doesn't exist
1896
+ */
1897
+ private findOrCreateSandbox;
1898
+ /**
1899
+ * Ensure a permission profile exists for a sandbox, creating it if needed.
1900
+ * If profileName matches an existing profile name, returns its ID.
1901
+ * Otherwise, creates a new profile with default allow-all rules.
1902
+ */
1903
+ private ensurePermissionProfile;
1904
+ /**
1905
+ * Ensure an assignment exists for a subject in a sandbox with a permission profile
1906
+ */
1907
+ private ensureAssignment;
1908
+ /**
1909
+ * Sandbox management API
1910
+ */
1911
+ get sandboxes(): {
1912
+ list: () => Promise<SandboxListResponse>;
1913
+ get: (id: string) => Promise<Sandbox>;
1914
+ create: (data: CreateSandboxData) => Promise<Sandbox>;
1915
+ update: (id: string, data: Partial<CreateSandboxData>) => Promise<Sandbox>;
1916
+ delete: (id: string) => Promise<DeleteResponse>;
1917
+ };
1918
+ /**
1919
+ * Permission Profile management for sandboxes
1920
+ */
1921
+ get permissionProfiles(): {
1922
+ list: (sandboxId: string) => Promise<PermissionProfile[]>;
1923
+ get: (sandboxId: string, profileId: string) => Promise<PermissionProfile>;
1924
+ create: (sandboxId: string, data: CreatePermissionProfileData) => Promise<PermissionProfile>;
1925
+ delete: (sandboxId: string, profileId: string) => Promise<DeleteResponse>;
1926
+ };
1927
+ /**
1928
+ * Environment management
1929
+ */
1930
+ get environments(): {
1931
+ list: (sandboxId: string) => Promise<EnvironmentData[]>;
1932
+ get: (environmentId: string) => Promise<EnvironmentData>;
1933
+ create: (sandboxId: string, data: CreateEnvironmentData) => Promise<EnvironmentData>;
1934
+ delete: (environmentId: string) => Promise<DeleteResponse>;
1935
+ };
1936
+ /**
1937
+ * Event stream operations: query, subscribe, and acknowledge stream events
1938
+ */
1939
+ get streams(): {
1940
+ getEvents: (params: {
1941
+ ontology: string;
1942
+ stream: string;
1943
+ environment?: string;
1944
+ session?: string;
1945
+ eventTypes?: string[];
1946
+ since?: Date;
1947
+ until?: Date;
1948
+ isAcked?: boolean;
1949
+ limit?: number;
1950
+ offset?: number;
1951
+ }) => Promise<StreamEvent[]>;
1952
+ subscribe: (params: {
1953
+ ontology: string;
1954
+ stream: string;
1955
+ environment?: string;
1956
+ session?: string;
1957
+ eventTypes?: string[];
1958
+ since?: Date;
1959
+ onEvent: (event: StreamEvent) => void;
1960
+ onError?: (err: Error) => void;
1961
+ pollIntervalMs?: number;
1962
+ }) => StreamSubscription;
1963
+ ack: (eventId: string) => Promise<void>;
1964
+ ackBatch: (eventIds: string[]) => Promise<void>;
1965
+ getStats: (params: {
1966
+ ontology: string;
1967
+ environment?: string;
1968
+ }) => Promise<StreamStats[]>;
1969
+ };
1970
+ /**
1971
+ * Subject management
1972
+ */
1973
+ get subjects(): {
1974
+ get: (subjectId: string) => Promise<Subject>;
1975
+ listAssignments: (subjectId: string) => Promise<AssignmentListResponse>;
1976
+ };
1977
+ /**
1978
+ * @deprecated Use recordUser() instead
1979
+ */
1980
+ get users(): {
1981
+ create: (data: {
1982
+ id: string;
1983
+ name?: string;
1984
+ email?: string;
1985
+ }) => Promise<Subject>;
1986
+ get: (id: string) => Promise<Subject>;
1987
+ };
1988
+ private _resolveSandboxId;
1989
+ /**
1990
+ * Make an authenticated API request
1991
+ */
1992
+ private request;
1993
+ }
1994
+
1995
+ export { type EffectInvocationMode as $, type AccessTokenProvider as A, type BuildPolicy as B, type ConnectOptions as C, type DomainState as D, type EffectHandlerContext as E, type Manifest as F, Granular as G, type ManifestListResponse as H, type InstanceToolHandler as I, type BuildStatus as J, type Build as K, type Version as L, type ManifestEffectMetamodelSpec as M, type BuildListResponse as N, type SemanticVersionDiffEntry as O, type Prompt as P, type SemanticVersionDiff as Q, type ResolvedEffectBehaviors as R, type SessionHeapEntry as S, type ToolWithHandler as T, type User as U, type VersionTracking as V, WSClient as W, type ResolvedEffectPostCondition as X, type ResolvedEffectDryRun as Y, type ResolvedEffectReverse as Z, type ResolvedEffectApprovalRequired as _, type SessionHeapList as a, type APIError as a$, type EffectInvocationMetadata as a0, type EffectSchema as a1, type EffectWithHandler as a2, type PublishEffectsResult as a3, type ToolInfo as a4, type EffectInfo as a5, type ToolsChangedEvent as a6, type EffectsChangedEvent as a7, type EffectHandler as a8, type InstanceEffectHandler as a9, type RecordImportItemStatus as aA, type RecordImportStats as aB, type RecordImportItem as aC, type RecordImport as aD, type EnvironmentRecordImportSummary as aE, type ManifestPropertySpec as aF, type ManifestValidationOperator as aG, type ManifestEnumRuleSpec as aH, type ManifestFilterBySpec as aI, type ManifestValidationRuleSpec as aJ, type ManifestStateMachineStateSpec as aK, type ManifestStateMachineTransitionSpec as aL, type ManifestStateMachineSpec as aM, type ManifestPostConditionSpec as aN, type ManifestDryRunSpec as aO, type ManifestReverseSpec as aP, type ManifestApprovalRequiredSpec as aQ, type ManifestRelationshipDef as aR, type ManifestEffectSchema as aS, type ManifestEffectDeclaration as aT, type ManifestEventTypeDef as aU, type ManifestEventStreamDef as aV, type ManifestOperation as aW, type ManifestImport as aX, type ManifestVolume as aY, type ManifestContent as aZ, type GraphQLResult as a_, type JobStatus as aa, type JobFeedbackSentiment as ab, type JobFeedbackToolCall as ac, type JobFeedbackMetadata as ad, type JobFeedbackInput as ae, type JobFeedbackRecord as af, type JobSubmitResult as ag, type Job as ah, type SessionHeapFieldType as ai, type SessionHeapFieldValue as aj, type SessionHeapVariable as ak, type WSDisconnectInfo as al, type WSReconnectErrorInfo as am, type WSClientOptions as an, type RPCRequest as ao, type RPCResponse as ap, type SyncMessage as aq, type RPCRequestFromServer as ar, type ToolInvokeParams as as, type ToolResultParams as at, type ModelRef as au, type RelationshipInfo as av, type DefineRelationshipOptions as aw, type RecordObjectOptions as ax, type RecordObjectResult as ay, type RecordImportStatus as az, type SessionHeapSnapshot as b, type DeleteResponse as b0, type StreamEvent as b1, type StreamSubscription as b2, type StreamStats as b3, Environment as c, Session as d, type ToolSchema as e, type PublishToolsResult as f, type ToolHandler as g, type EndpointMode as h, type GranularOptions as i, type GranularAuth as j, type RecordUserOptions as k, type Subject as l, type ConversationSessionInfo as m, type Sandbox as n, type CreateSandboxData as o, type SandboxListResponse as p, type PermissionRules as q, type PermissionProfile as r, type CreatePermissionProfileData as s, type PermissionProfileListResponse as t, type Assignment as u, type AssignmentListResponse as v, type VersionTag as w, type EnvironmentData as x, type CreateEnvironmentData as y, type EnvironmentListResponse as z };