@granular-software/sdk 0.4.18 → 0.4.20

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,2051 @@
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
+ /**
866
+ * Metadata for one completed HTTP chunk in `recordObjects()`.
867
+ * Chunk indices follow input order; when concurrency is greater than 1, completion order may differ.
868
+ */
869
+ interface RecordObjectsChunkInfo {
870
+ /** Zero-based chunk index */
871
+ chunkIndex: number;
872
+ totalChunks: number;
873
+ /** Zero-based offset into the original `records` array */
874
+ offset: number;
875
+ /** Number of records in this chunk */
876
+ recordCount: number;
877
+ /** Wall time for this chunk’s POST (including retries) */
878
+ durationMs: number;
879
+ /** Acknowledgements for this chunk, in the same order as the slice sent */
880
+ results: RecordObjectResult[];
881
+ }
882
+ /**
883
+ * Optional tuning for `recordObjects()` — batching, parallelism, and progress hooks.
884
+ */
885
+ interface RecordObjectsOptions {
886
+ /**
887
+ * Max records per HTTP POST to the control-plane batch endpoint. Default 100.
888
+ * Smaller values: more round trips and finer `onChunkComplete` updates.
889
+ * Larger values: fewer requests (watch request size/timeouts).
890
+ */
891
+ batchSize?: number;
892
+ /**
893
+ * How many chunk POSTs may run concurrently. Default 1 (strictly sequential).
894
+ * Values above 1 can reduce wall time when the server can overlap work; capped at 16.
895
+ */
896
+ concurrency?: number;
897
+ /**
898
+ * Called after each chunk succeeds (after retries). Useful for UI progress bars.
899
+ */
900
+ onChunkComplete?: (info: RecordObjectsChunkInfo) => void | Promise<void>;
901
+ }
902
+ type RecordImportStatus = 'queued' | 'processing' | 'completed' | 'failed' | 'canceled';
903
+ type RecordImportItemStatus = 'queued' | 'processing' | 'completed' | 'failed' | 'canceled';
904
+ interface RecordImportStats {
905
+ totalRecords: number;
906
+ queuedRecords: number;
907
+ processingRecords: number;
908
+ completedRecords: number;
909
+ failedRecords: number;
910
+ canceledRecords: number;
911
+ awaitingRecords: number;
912
+ }
913
+ interface RecordImportItem {
914
+ itemId: string;
915
+ importId: string;
916
+ tenantId: string;
917
+ environmentId: string;
918
+ className: string;
919
+ id: string;
920
+ label: string | null;
921
+ fields: Record<string, string | number | boolean | null> | null;
922
+ relationships: Record<string, string | string[]> | null;
923
+ status: RecordImportItemStatus;
924
+ attempts: number;
925
+ errorMessage: string | null;
926
+ resultPath: string | null;
927
+ resultCreated: boolean | null;
928
+ createdAt: number;
929
+ updatedAt: number;
930
+ processedAt: number | null;
931
+ }
932
+ interface RecordImport {
933
+ importId: string;
934
+ tenantId: string;
935
+ environmentId: string;
936
+ sandboxId: string;
937
+ subjectId: string;
938
+ status: RecordImportStatus;
939
+ batchSize: number;
940
+ errorMessage: string | null;
941
+ createdAt: number;
942
+ updatedAt: number;
943
+ startedAt: number | null;
944
+ finishedAt: number | null;
945
+ canceledAt: number | null;
946
+ stats: RecordImportStats;
947
+ }
948
+ interface EnvironmentRecordImportSummary extends RecordImportStats {
949
+ environmentId: string;
950
+ totalImports: number;
951
+ activeImports: number;
952
+ updatedAt: number;
953
+ }
954
+ /**
955
+ * Property specification in a manifest operation
956
+ */
957
+ interface ManifestPropertySpec {
958
+ value?: string | number | boolean;
959
+ ref?: string;
960
+ instanceOf?: string;
961
+ create?: string;
962
+ has?: Record<string, ManifestPropertySpec>;
963
+ type?: string;
964
+ description?: string;
965
+ required?: boolean;
966
+ note?: string | string[];
967
+ enum?: string[] | ManifestEnumRuleSpec;
968
+ filterBy?: boolean | string[] | ManifestFilterBySpec;
969
+ validate?: ManifestValidationRuleSpec[];
970
+ }
971
+ type ManifestValidationOperator = 'eq' | 'neq' | 'gt' | 'gte' | 'lt' | 'lte' | 'true' | 'false' | 'regex' | 'contains' | 'not_contains' | 'starts_with' | 'ends_with';
972
+ interface ManifestEnumRuleSpec {
973
+ values: string[];
974
+ message?: string;
975
+ }
976
+ interface ManifestFilterBySpec {
977
+ operators: string[];
978
+ scalarType?: string;
979
+ }
980
+ interface ManifestValidationRuleSpec {
981
+ operator: ManifestValidationOperator;
982
+ stringValue?: string;
983
+ numberValue?: number;
984
+ booleanValue?: boolean;
985
+ message?: string;
986
+ }
987
+ interface ManifestStateMachineStateSpec {
988
+ name: string;
989
+ isFinal?: boolean;
990
+ }
991
+ interface ManifestStateMachineTransitionSpec {
992
+ name: string;
993
+ from: string;
994
+ to: string;
995
+ }
996
+ interface ManifestStateMachineSpec {
997
+ name: string;
998
+ entryState: string;
999
+ states: Array<string | ManifestStateMachineStateSpec>;
1000
+ transitions: ManifestStateMachineTransitionSpec[];
1001
+ finalStates?: string[];
1002
+ }
1003
+ interface ManifestPostConditionSpec {
1004
+ condition: string;
1005
+ description?: string;
1006
+ }
1007
+ interface ManifestDryRunSpec {
1008
+ enabled?: boolean;
1009
+ description?: string;
1010
+ }
1011
+ interface ManifestReverseSpec {
1012
+ handler?: string;
1013
+ description?: string;
1014
+ }
1015
+ interface ManifestApprovalRequiredSpec {
1016
+ required?: boolean;
1017
+ reason?: string;
1018
+ mode?: string;
1019
+ }
1020
+ interface ManifestEffectMetamodelSpec {
1021
+ postCondition?: string | ManifestPostConditionSpec;
1022
+ dryRun?: boolean | ManifestDryRunSpec;
1023
+ reverse?: string | ManifestReverseSpec;
1024
+ approvalRequired?: boolean | ManifestApprovalRequiredSpec;
1025
+ }
1026
+ /**
1027
+ * Relationship definition between two classes
1028
+ */
1029
+ interface ManifestRelationshipDef {
1030
+ /** Optional name (auto-generated from left_right if omitted) */
1031
+ name?: string;
1032
+ /** Left model path */
1033
+ left: string;
1034
+ /** Right model path */
1035
+ right: string;
1036
+ /** Submodel name on the left model */
1037
+ leftSubmodel: string;
1038
+ /** Submodel name on the right model */
1039
+ rightSubmodel: string;
1040
+ /** Whether the left side is a collection */
1041
+ leftIsMany: boolean;
1042
+ /** Whether the right side is a collection */
1043
+ rightIsMany: boolean;
1044
+ }
1045
+ interface ManifestEffectSchema {
1046
+ type: string;
1047
+ properties?: Record<string, unknown>;
1048
+ required?: string[];
1049
+ items?: unknown;
1050
+ description?: string;
1051
+ [key: string]: unknown;
1052
+ }
1053
+ interface ManifestEffectDeclaration {
1054
+ name: string;
1055
+ description?: string;
1056
+ attachedClass?: string;
1057
+ isStatic?: boolean;
1058
+ inputSchema: ManifestEffectSchema;
1059
+ outputSchema?: ManifestEffectSchema;
1060
+ stability?: 'stable' | 'experimental' | 'deprecated';
1061
+ tags?: string[];
1062
+ metamodels?: ManifestEffectMetamodelSpec;
1063
+ }
1064
+ /**
1065
+ * An event type within an event stream definition
1066
+ */
1067
+ interface ManifestEventTypeDef {
1068
+ name: string;
1069
+ description?: string;
1070
+ payloadSchema: ManifestEffectSchema;
1071
+ }
1072
+ /**
1073
+ * Event stream definition for outgoing typed events
1074
+ */
1075
+ interface ManifestEventStreamDef {
1076
+ name: string;
1077
+ description?: string;
1078
+ eventTypes: ManifestEventTypeDef[];
1079
+ }
1080
+ /**
1081
+ * A single operation in a manifest volume
1082
+ */
1083
+ interface ManifestOperation {
1084
+ /** Create a new model/class */
1085
+ create?: string;
1086
+ /** Target an existing model for modification */
1087
+ on?: string;
1088
+ /** Extend from a parent class */
1089
+ extends?: string;
1090
+ /** Instantiate a type */
1091
+ instanceOf?: string;
1092
+ /** Define submodels/fields */
1093
+ has?: Record<string, ManifestPropertySpec>;
1094
+ /** Advisory notes attached to the model/class itself */
1095
+ note?: string | string[];
1096
+ /** State machines attached to the created or targeted class */
1097
+ stateMachines?: ManifestStateMachineSpec[];
1098
+ /** Define a relationship between two classes */
1099
+ defineRelationship?: ManifestRelationshipDef;
1100
+ /** Declare a build-owned effect */
1101
+ withEffect?: ManifestEffectDeclaration;
1102
+ /** Define an outgoing event stream with typed events */
1103
+ defineEventStream?: ManifestEventStreamDef;
1104
+ }
1105
+ /**
1106
+ * A volume in a manifest
1107
+ */
1108
+ /**
1109
+ * Import descriptor for referencing modules
1110
+ */
1111
+ interface ManifestImport {
1112
+ /** Alias prefix used in operations (e.g., "@std") */
1113
+ alias: string;
1114
+ /** Module name (e.g., "standard_modules") */
1115
+ name: string;
1116
+ /** Version label (e.g., "prod", "v1.2.3") */
1117
+ label?: string;
1118
+ }
1119
+ interface ManifestVolume {
1120
+ name: string;
1121
+ scope: 'sandbox' | 'build' | 'user';
1122
+ imports?: ManifestImport[];
1123
+ operations: ManifestOperation[];
1124
+ }
1125
+ /**
1126
+ * A manifest defines the structure of a sandbox's data model
1127
+ */
1128
+ interface ManifestContent {
1129
+ schemaVersion: 2;
1130
+ name: string;
1131
+ description?: string;
1132
+ volumes: ManifestVolume[];
1133
+ }
1134
+ /**
1135
+ * Result from a GraphQL query execution
1136
+ */
1137
+ interface GraphQLResult<T = any> {
1138
+ data?: T;
1139
+ errors?: Array<{
1140
+ message: string;
1141
+ locations?: Array<{
1142
+ line: number;
1143
+ column: number;
1144
+ }>;
1145
+ path?: Array<string | number>;
1146
+ extensions?: Record<string, any>;
1147
+ }>;
1148
+ }
1149
+ interface APIError {
1150
+ error: string;
1151
+ message?: string;
1152
+ }
1153
+ interface DeleteResponse {
1154
+ deleted: boolean;
1155
+ }
1156
+ interface StreamEvent {
1157
+ eventId: string;
1158
+ streamName: string;
1159
+ eventType: string;
1160
+ payload: Record<string, unknown>;
1161
+ environmentId: string;
1162
+ sessionId?: string;
1163
+ subjectId?: string;
1164
+ source: 'sandbox' | 'api';
1165
+ isAcked: boolean;
1166
+ createdAt: number;
1167
+ }
1168
+ interface StreamSubscription {
1169
+ unsubscribe(): void;
1170
+ }
1171
+ interface StreamStats {
1172
+ streamName: string;
1173
+ eventType: string;
1174
+ total: number;
1175
+ last1h: number;
1176
+ last24h: number;
1177
+ unacked: number;
1178
+ }
1179
+
1180
+ declare class WSClient {
1181
+ private ws;
1182
+ private url;
1183
+ private sessionId;
1184
+ private token;
1185
+ private messageQueue;
1186
+ private syncHandlers;
1187
+ private rpcHandlers;
1188
+ private eventHandlers;
1189
+ private nextRpcId;
1190
+ doc: Automerge.Doc<Record<string, unknown>>;
1191
+ private syncState;
1192
+ private reconnectTimer;
1193
+ private tokenRefreshTimer;
1194
+ private isExplicitlyDisconnected;
1195
+ private options;
1196
+ constructor(options: WSClientOptions);
1197
+ get currentSessionId(): string;
1198
+ private clearTokenRefreshTimer;
1199
+ private decodeBase64Url;
1200
+ private getTokenExpiryMs;
1201
+ private scheduleTokenRefresh;
1202
+ private refreshTokenInBackground;
1203
+ private resolveTokenForConnect;
1204
+ /**
1205
+ * Connect to the WebSocket server
1206
+ * @returns {Promise<void>} Resolves when connection is open
1207
+ */
1208
+ connect(): Promise<void>;
1209
+ private normalizeReason;
1210
+ private rejectPending;
1211
+ private buildDisconnectError;
1212
+ private handleDisconnect;
1213
+ private handleMessage;
1214
+ /**
1215
+ * Make an RPC call to the server
1216
+ * @param {string} method - RPC method name
1217
+ * @param {unknown} params - Request parameters
1218
+ * @returns {Promise<unknown>} Response result
1219
+ * @throws {Error} If connection is closed or timeout occurs
1220
+ */
1221
+ call(method: string, params: unknown): Promise<unknown>;
1222
+ private handleIncomingRpc;
1223
+ /**
1224
+ * Subscribe to client events
1225
+ * @param {string} event - Event name
1226
+ * @param {Function} handler - Event handler
1227
+ */
1228
+ on(event: string, handler: (params: unknown) => void): void;
1229
+ /**
1230
+ * Register an RPC handler for incoming server requests
1231
+ * @param {string} method - RPC method name
1232
+ * @param {Function} handler - Handler function
1233
+ */
1234
+ registerRpcHandler(method: string, handler: (params: unknown) => Promise<unknown>): void;
1235
+ /**
1236
+ * Unsubscribe from client events
1237
+ * @param {string} event - Event name
1238
+ * @param {Function} handler - Handler to remove
1239
+ */
1240
+ off(event: string, handler: (params: unknown) => void): void;
1241
+ /**
1242
+ * Emit an event locally
1243
+ * @param {string} event - Event name
1244
+ * @param params - Event data
1245
+ */
1246
+ emit(event: string, params: unknown): void;
1247
+ /**
1248
+ * Disconnect the WebSocket and clear state
1249
+ */
1250
+ disconnect(): void;
1251
+ }
1252
+
1253
+ declare class Session {
1254
+ protected client: WSClient;
1255
+ private clientId;
1256
+ private jobsMap;
1257
+ private eventListeners;
1258
+ private toolHandlers;
1259
+ /** Tracks which tools are instance methods (className set, not static) */
1260
+ private instanceTools;
1261
+ private currentDomainRevision;
1262
+ /** Local effect registry: name → full ToolWithHandler */
1263
+ private effects;
1264
+ /** Last known tools for diffing */
1265
+ private lastKnownTools;
1266
+ /** Last seen live prompts, keyed by prompt id, for answer normalization */
1267
+ private promptCache;
1268
+ constructor(client: WSClient, clientId?: string);
1269
+ private extractDomainRevisionFromDoc;
1270
+ private buildLegacyEffectContext;
1271
+ get document(): Doc<Record<string, unknown>>;
1272
+ get sessionId(): string;
1273
+ get domainRevision(): string | null;
1274
+ /**
1275
+ * Make a raw RPC call to the session's Durable Object.
1276
+ *
1277
+ * Use this when you need to call an RPC method that doesn't have a
1278
+ * dedicated wrapper method on the Session/Environment class.
1279
+ *
1280
+ * @param method - RPC method name (e.g. 'domain.fetchPackagePart')
1281
+ * @param params - Request parameters
1282
+ * @returns The raw RPC response
1283
+ *
1284
+ * @example
1285
+ * ```typescript
1286
+ * const result = await env.rpc('domain.fetchPackagePart', {
1287
+ * moduleSpecifier: '@sandbox/domain',
1288
+ * part: 'types',
1289
+ * });
1290
+ * ```
1291
+ */
1292
+ rpc<T = unknown>(method: string, params?: Record<string, unknown>): Promise<T>;
1293
+ /**
1294
+ * Send client hello to establish the session
1295
+ */
1296
+ hello(): Promise<{
1297
+ ok: boolean;
1298
+ environmentId?: string;
1299
+ docId?: string;
1300
+ graphContainerStatus?: {
1301
+ lastKeepAliveAt: number;
1302
+ status: 'warming' | 'hot' | 'unknown';
1303
+ };
1304
+ }>;
1305
+ publishTools(tools: ToolWithHandler[], revision?: string): Promise<PublishToolsResult>;
1306
+ publishEffect(effect: ToolWithHandler): Promise<PublishToolsResult>;
1307
+ publishEffects(effects: ToolWithHandler[]): Promise<PublishToolsResult>;
1308
+ unpublishEffect(name: string): Promise<PublishToolsResult>;
1309
+ unpublishAllEffects(): Promise<PublishToolsResult>;
1310
+ /**
1311
+ * Submit a job to execute code in the sandbox.
1312
+ *
1313
+ * The code can import typed classes from `./sandbox-tools`:
1314
+ * ```typescript
1315
+ * import { Author, Book, global_search } from './sandbox-tools';
1316
+ *
1317
+ * const authors = await Author.list({ limit: 10, saveAs: 'recent_authors' });
1318
+ * const tolkien = await Author.get({ path: 'author_tolkien' });
1319
+ * const bio = await tolkien.get_bio({ detailed: true });
1320
+ * const books = await tolkien.get_books();
1321
+ * ```
1322
+ *
1323
+ * Effect calls (instance methods, static methods, global functions) trigger
1324
+ * `effect.invoke` RPC back to the sandbox effect host, where the registered handlers
1325
+ * execute locally and return the result to the sandbox.
1326
+ */
1327
+ submitJob(code: string, domainRevision?: string): Promise<Job>;
1328
+ /**
1329
+ * Register a handler for a specific tool.
1330
+ * @param isInstance - If true, handler will receive (id, params) for instance method dispatch.
1331
+ */
1332
+ registerToolHandler(name: string, handler: ToolHandler | InstanceToolHandler, isInstance?: boolean): void;
1333
+ /**
1334
+ * Respond to a prompt request from the sandbox
1335
+ */
1336
+ answerPrompt(promptId: string, answer: unknown): Promise<void>;
1337
+ /**
1338
+ * Get the current list of available effects.
1339
+ * Consolidates effect declarations and live availability for the session.
1340
+ */
1341
+ getEffects(): EffectInfo[];
1342
+ /**
1343
+ * Backwards-compatible alias for `getEffects()`.
1344
+ */
1345
+ getTools(): ToolInfo[];
1346
+ /**
1347
+ * Subscribe to effect changes (added, removed, updated).
1348
+ * @param callback - Function called with change events
1349
+ * @returns Unsubscribe function
1350
+ */
1351
+ onEffectsChanged(callback: (event: EffectsChangedEvent) => void): () => void;
1352
+ /**
1353
+ * Backwards-compatible alias for `onEffectsChanged()`.
1354
+ */
1355
+ onToolsChanged(callback: (event: ToolsChangedEvent) => void): () => void;
1356
+ /**
1357
+ * Get the current domain state and available tools
1358
+ */
1359
+ getDomain(): Promise<DomainState>;
1360
+ /**
1361
+ * Fetch a domain package part from the backend (no fallback).
1362
+ */
1363
+ private fetchDomainPart;
1364
+ /**
1365
+ * Get TypeScript class declarations for the current domain (for LLM/code gen).
1366
+ */
1367
+ getDomainTypes(): Promise<string>;
1368
+ /**
1369
+ * Get Markdown documentation for the current domain (human-readable).
1370
+ */
1371
+ getDomainDocs(): Promise<string>;
1372
+ /**
1373
+ * Get domain documentation for LLMs. Returns types (preferred) or fallback.
1374
+ */
1375
+ getDomainDocumentation(): Promise<string>;
1376
+ /**
1377
+ * Generate markdown documentation from the domain summary.
1378
+ * Class-aware: groups tools by class with property/relationship info.
1379
+ */
1380
+ private generateFallbackDocs;
1381
+ /**
1382
+ * Close the session and disconnect from the sandbox
1383
+ */
1384
+ disconnect(): Promise<void>;
1385
+ /**
1386
+ * Subscribe to session events
1387
+ */
1388
+ on(event: string, handler: (data: unknown) => void): void;
1389
+ /**
1390
+ * Unsubscribe from session events
1391
+ */
1392
+ off(event: string, handler: (data: unknown) => void): void;
1393
+ private setupToolInvokeHandler;
1394
+ private setupEventHandlers;
1395
+ protected emit(event: string, data: unknown): void;
1396
+ /**
1397
+ * Check for changes in the effect catalog and emit change events if needed.
1398
+ */
1399
+ private checkForToolChanges;
1400
+ }
1401
+
1402
+ /**
1403
+ * Environment represents a connected session to a sandbox for a specific user.
1404
+ *
1405
+ * After connecting, you can:
1406
+ * 1. Define your domain ontology via `applyManifest()` (classes, properties, relationships)
1407
+ * 2. Record object instances via `recordObject()` (with fields and relationship attachments)
1408
+ * 3. Register sandbox-scoped effects via `granular.registerEffect()` / `granular.registerEffects()`
1409
+ * 4. Submit jobs via `submitJob()` that import auto-generated typed classes from `./sandbox-tools`
1410
+ * 5. Execute GraphQL queries via `graphql()` (authenticated automatically)
1411
+ * 6. List available effects via `getEffects()` and listen for updates via `onEffectsChanged()`
1412
+ *
1413
+ * Tool calls from the sandbox automatically invoke your handlers via reverse-RPC.
1414
+ *
1415
+ * Object IDs are unique per class. Internally, the graph path is `{className}_{id}`
1416
+ * (e.g., `author_tolkien`). Use `Environment.toGraphPath()` and
1417
+ * `Environment.extractIdFromGraphPath()` for conversions.
1418
+ */
1419
+ declare class Environment extends Session {
1420
+ private envData;
1421
+ private _apiKey;
1422
+ private _apiEndpoint;
1423
+ constructor(client: WSClient, envData: EnvironmentData, clientId: string, apiKey: string, apiEndpoint: string);
1424
+ /** The environment ID */
1425
+ get environmentId(): string;
1426
+ /** The sandbox ID */
1427
+ get sandboxId(): string;
1428
+ /** The ontology ID */
1429
+ get ontologyId(): string;
1430
+ /** The subject ID */
1431
+ get subjectId(): string;
1432
+ /** The named environment slot, such as dev or prod */
1433
+ get envName(): string;
1434
+ /** The named environment slot, such as dev or prod */
1435
+ get environment(): string;
1436
+ /** The resolved ontology version backing this environment */
1437
+ get versionId(): string;
1438
+ /** Internal Granular user identifier for this environment */
1439
+ get granularId(): string;
1440
+ /** The permission profile ID */
1441
+ get permissionProfileId(): string;
1442
+ /** The GraphQL API endpoint URL */
1443
+ get apiEndpoint(): string;
1444
+ /**
1445
+ * Return a plain JS snapshot of the synced session heap.
1446
+ *
1447
+ * The heap lives in the Automerge document, so this method does not perform
1448
+ * any extra network roundtrip.
1449
+ */
1450
+ getHeap(): SessionHeapSnapshot;
1451
+ private getRuntimeBaseUrl;
1452
+ private controlPlaneRequest;
1453
+ /**
1454
+ * Close the session and disconnect from the sandbox.
1455
+ *
1456
+ * Sends `client.goodbye` over WebSocket first, then issues an HTTP fallback
1457
+ * to the runtime goodbye endpoint if no definitive WS-side runtime notify
1458
+ * acknowledgement was observed.
1459
+ */
1460
+ disconnect(): Promise<void>;
1461
+ /** The last known graph container status, updated by checkReadiness() or on heartbeat */
1462
+ graphContainerStatus: {
1463
+ lastKeepAliveAt: number;
1464
+ status: 'warming' | 'hot' | 'unknown';
1465
+ } | null;
1466
+ /**
1467
+ * Check if the graph container is ready and warm.
1468
+ *
1469
+ * Sends a lightweight heartbeat RPC to the Session DO which internally
1470
+ * pings the FalkorDB container. The response includes `graphContainerStatus`,
1471
+ * which is stored locally and emitted as a `readiness` event.
1472
+ *
1473
+ * Use this method to proactively warm the graph container before any
1474
+ * GraphQL query that requires it, or to poll the container's state in
1475
+ * the background.
1476
+ *
1477
+ * @returns The current graph container status object
1478
+ *
1479
+ * @example
1480
+ * ```typescript
1481
+ * const status = await env.checkReadiness();
1482
+ * console.log(status.status); // 'hot' | 'warming' | 'unknown'
1483
+ *
1484
+ * // Or listen for live updates
1485
+ * env.on('readiness', (status) => {
1486
+ * console.log('Graph is now:', status.status);
1487
+ * });
1488
+ * ```
1489
+ */
1490
+ checkReadiness(): Promise<{
1491
+ lastKeepAliveAt: number;
1492
+ status: 'warming' | 'hot' | 'unknown';
1493
+ }>;
1494
+ /**
1495
+ * Convert a class name + real-world ID into a unique graph path.
1496
+ *
1497
+ * Two objects of *different* classes may share the same real-world ID,
1498
+ * so the graph path must incorporate the class to guarantee uniqueness.
1499
+ *
1500
+ * Format: `{className}_{id}` — deterministic, human-readable.
1501
+ *
1502
+ * **Convention**: class names should be simple identifiers without
1503
+ * underscores (e.g. `author`, `book`). This ensures the prefix is
1504
+ * unambiguously parseable by `extractIdFromGraphPath`.
1505
+ */
1506
+ static toGraphPath(className: string, id: string): string;
1507
+ /**
1508
+ * Extract the real-world ID from a graph path, given the class name.
1509
+ *
1510
+ * Strips the `{className}_` prefix. Returns the raw path if the
1511
+ * expected prefix is not found.
1512
+ */
1513
+ static extractIdFromGraphPath(graphPath: string, className: string): string;
1514
+ /**
1515
+ * Execute a GraphQL query against the environment's graph.
1516
+ *
1517
+ * The query uses the Granular graph query language (based on Cypher/GraphQL).
1518
+ * Authentication is handled automatically using the SDK's API key.
1519
+ *
1520
+ * @param query - The GraphQL query string
1521
+ * @param variables - Optional variables for the query
1522
+ * @returns The query result data
1523
+ *
1524
+ * @example
1525
+ * ```typescript
1526
+ * // Read the workspace
1527
+ * const result = await env.graphql(
1528
+ * `query { model(path: "workspace") { path label submodels { path label } } }`
1529
+ * );
1530
+ * console.log(result.data);
1531
+ *
1532
+ * // Create a model
1533
+ * const created = await env.graphql(
1534
+ * `mutation { at(path: "workspace") { create_submodel(subpath: "my_node", label: "My Node", prototype: "Model") { model { path label } } } }`
1535
+ * );
1536
+ * ```
1537
+ */
1538
+ graphql<T = any>(query: string, variables?: Record<string, any>): Promise<GraphQLResult<T>>;
1539
+ /**
1540
+ * Define a relationship between two model types.
1541
+ *
1542
+ * Creates both submodels (if they don't exist) and links them with
1543
+ * a RelationshipDef node that encodes cardinality.
1544
+ *
1545
+ * @example
1546
+ * ```typescript
1547
+ * // Author has many Books, Book has one Author
1548
+ * const rel = await env.defineRelationship({
1549
+ * model: 'author',
1550
+ * localSubmodel: 'books',
1551
+ * localIsMany: true,
1552
+ * foreignModel: 'book',
1553
+ * foreignSubmodel: 'author',
1554
+ * foreignIsMany: false,
1555
+ * });
1556
+ * console.log(rel.relationship_kind); // "one_to_many"
1557
+ * ```
1558
+ */
1559
+ defineRelationship(options: DefineRelationshipOptions): Promise<RelationshipInfo>;
1560
+ /**
1561
+ * Get all relationships for a model type.
1562
+ *
1563
+ * @param modelPath - The model type path (e.g., "author")
1564
+ * @returns Array of relationships from this model's perspective
1565
+ *
1566
+ * @example
1567
+ * ```typescript
1568
+ * const rels = await env.getRelationships('author');
1569
+ * for (const rel of rels) {
1570
+ * console.log(`${rel.local_submodel.path} -> ${rel.foreign_model.path} (${rel.relationship_kind})`);
1571
+ * }
1572
+ * ```
1573
+ */
1574
+ getRelationships(modelPath: string): Promise<RelationshipInfo[]>;
1575
+ /**
1576
+ * Attach a target model to a relationship submodel.
1577
+ *
1578
+ * Handles cardinality automatically:
1579
+ * - "One" side: sets/replaces the reference
1580
+ * - "Many" side: adds the target to the collection
1581
+ *
1582
+ * If the target model doesn't exist, it's created as an instance of the foreign type.
1583
+ * Bidirectional sync is automatic.
1584
+ *
1585
+ * @param modelPath - The model instance path (e.g., "tolkien")
1586
+ * @param submodelPath - The relationship submodel (e.g., "books")
1587
+ * @param targetPath - The target model to attach (e.g., "lord_of_the_rings")
1588
+ *
1589
+ * @example
1590
+ * ```typescript
1591
+ * // Attach a book to an author (many side)
1592
+ * await env.attach('tolkien', 'books', 'lord_of_the_rings');
1593
+ * // This also automatically sets lord_of_the_rings:author -> tolkien
1594
+ * ```
1595
+ */
1596
+ attach(modelPath: string, submodelPath: string, targetPath: string): Promise<void>;
1597
+ /**
1598
+ * Detach a target model from a relationship submodel.
1599
+ *
1600
+ * Handles bidirectional cleanup automatically.
1601
+ *
1602
+ * @param modelPath - The model instance path
1603
+ * @param submodelPath - The relationship submodel
1604
+ * @param targetPath - The target to detach (optional for "one" side; omit on "many" side to detach all)
1605
+ *
1606
+ * @example
1607
+ * ```typescript
1608
+ * // Detach a specific book
1609
+ * await env.detach('tolkien', 'books', 'lord_of_the_rings');
1610
+ *
1611
+ * // Detach all books
1612
+ * await env.detach('tolkien', 'books');
1613
+ * ```
1614
+ */
1615
+ detach(modelPath: string, submodelPath: string, targetPath?: string): Promise<void>;
1616
+ /**
1617
+ * List all related models through a relationship submodel.
1618
+ *
1619
+ * @param modelPath - The model instance path
1620
+ * @param submodelPath - The relationship submodel
1621
+ * @returns Array of related model references
1622
+ *
1623
+ * @example
1624
+ * ```typescript
1625
+ * const books = await env.listRelated('tolkien', 'books');
1626
+ * console.log(books); // [{ path: "lord_of_the_rings", label: "Lord of the Rings" }, ...]
1627
+ * ```
1628
+ */
1629
+ listRelated(modelPath: string, submodelPath: string): Promise<ModelRef[]>;
1630
+ /**
1631
+ * Apply a manifest to the current environment's graph.
1632
+ *
1633
+ * Translates each manifest operation into GraphQL mutations and executes them
1634
+ * in order. This is the core mechanism for creating classes, fields, and
1635
+ * relationships from a declarative manifest.
1636
+ *
1637
+ * @param manifest - The manifest content to apply
1638
+ * @returns Summary of applied operations
1639
+ *
1640
+ * @example
1641
+ * ```typescript
1642
+ * await environment.applyManifest({
1643
+ * schemaVersion: 2,
1644
+ * name: 'my-app',
1645
+ * volumes: [{
1646
+ * name: 'schema',
1647
+ * scope: 'sandbox',
1648
+ * operations: [
1649
+ * { create: 'author', extends: 'class', has: { name: { type: 'string' } } },
1650
+ * { create: 'book', extends: 'class', has: { title: { type: 'string' } } },
1651
+ * { defineRelationship: {
1652
+ * left: 'author', right: 'book',
1653
+ * leftSubmodel: 'books', rightSubmodel: 'author',
1654
+ * leftIsMany: true, rightIsMany: false,
1655
+ * }},
1656
+ * ],
1657
+ * }],
1658
+ * });
1659
+ * ```
1660
+ */
1661
+ applyManifest(manifest: ManifestContent): Promise<{
1662
+ applied: number;
1663
+ errors: string[];
1664
+ }>;
1665
+ /**
1666
+ * Resolve an alias reference like "@std/class" → "class"
1667
+ * Strips the alias prefix, returning the bare model path.
1668
+ */
1669
+ private _resolveAlias;
1670
+ private _runGraphql;
1671
+ private _applyFieldMetamodels;
1672
+ private _applyModelMetamodels;
1673
+ private _ensureWorkspaceToolsRoot;
1674
+ private _storeEffectSchemas;
1675
+ private _applyEffectMetamodels;
1676
+ private _ensureWorkspaceStreamsRoot;
1677
+ private _applyEventStreamDeclaration;
1678
+ private _applyEffectDeclaration;
1679
+ /**
1680
+ * Apply a single manifest operation via GraphQL
1681
+ */
1682
+ private _applyOperation;
1683
+ /**
1684
+ * Apply field definitions (has) to a model via GraphQL
1685
+ */
1686
+ private _applyFields;
1687
+ /**
1688
+ * Create or update an instance of a class in the graph.
1689
+ *
1690
+ * Uses `instantiate` under the hood, which has find-or-create semantics:
1691
+ * if an instance with the given `id` already exists for the class it is
1692
+ * returned; otherwise a new instance is created. Fields are then set
1693
+ * (overwriting previous values) and relationships are attached.
1694
+ *
1695
+ * The graph path is derived as `{className}_{id}` to ensure uniqueness
1696
+ * across classes (two objects of different classes may share the same
1697
+ * real-world ID). Relationship targets are also resolved automatically
1698
+ * using the foreign class from the relationship definition.
1699
+ *
1700
+ * @param options - The object specification
1701
+ * @returns The graph path, real-world ID, and creation status
1702
+ *
1703
+ * @example
1704
+ * ```typescript
1705
+ * // Create an author with fields
1706
+ * const result = await env.recordObject({
1707
+ * className: 'author',
1708
+ * id: 'tolkien',
1709
+ * label: 'J.R.R. Tolkien',
1710
+ * fields: { name: 'J.R.R. Tolkien', birth_year: 1892 },
1711
+ * relationships: { books: ['lotr', 'silmarillion'] },
1712
+ * });
1713
+ * // result.path → 'author_tolkien' (internal graph path)
1714
+ * // result.id → 'tolkien' (real-world ID)
1715
+ * // result.created → true
1716
+ * ```
1717
+ */
1718
+ recordObject(options: RecordObjectOptions): Promise<RecordObjectResult>;
1719
+ /**
1720
+ * Batch version of `recordObject()`.
1721
+ *
1722
+ * Sends rows through the control-plane **`/records/batch`** endpoint in **chunks** (default
1723
+ * **100** records per HTTP request) so individual requests stay bounded and gateway timeouts are
1724
+ * unlikely. Each chunk is retried on transient network / worker errors.
1725
+ *
1726
+ * Use the optional second argument to:
1727
+ * - **`batchSize`** — rows per POST (smaller = more progress events; larger = fewer round trips).
1728
+ * - **`concurrency`** — run up to N chunk POSTs in parallel (capped at 16) when you want lower wall time.
1729
+ * - **`onChunkComplete`** — hook for UIs after each chunk succeeds (row order in the returned array
1730
+ * always matches `records`; chunk **completion** order may differ when `concurrency > 1`).
1731
+ *
1732
+ * For **asynchronous** ingestion with worker-side batching and aggregate counters (`queued`,
1733
+ * `completed`, …), use **`enqueueRecordImport`** and poll **`getRecordImport`** /
1734
+ * **`getRecordImportSummary`** — best for very large fire-and-forget loads when immediate
1735
+ * synchronous commit of every row is not required.
1736
+ */
1737
+ recordObjects(records: RecordObjectOptions[], options?: RecordObjectsOptions): Promise<RecordObjectResult[]>;
1738
+ private executeRecordObjectsChunk;
1739
+ /**
1740
+ * Queue a background record import for this environment (async worker pipeline).
1741
+ *
1742
+ * **vs `recordObjects`:** this path accepts the full payload in one request, returns an
1743
+ * **`importId`**, and processes rows in the background — use **`getRecordImport`** /
1744
+ * **`getRecordImportSummary`** for progress. Choose it for large bulk loads where you do not
1745
+ * need every row committed before the HTTP call returns. Use **`recordObjects`** when you need
1746
+ * synchronous upserts and fine-grained chunk progress via **`onChunkComplete`**.
1747
+ */
1748
+ enqueueRecordImport(records: RecordObjectOptions[], options?: {
1749
+ batchSize?: number;
1750
+ }): Promise<RecordImport>;
1751
+ /**
1752
+ * List queued or completed record imports for this environment.
1753
+ */
1754
+ listRecordImports(status?: RecordImportStatus): Promise<RecordImport[]>;
1755
+ /**
1756
+ * Fetch the latest aggregate import counters for this environment.
1757
+ */
1758
+ getRecordImportSummary(): Promise<EnvironmentRecordImportSummary>;
1759
+ /**
1760
+ * Convenience helper returning queued + processing records for this environment.
1761
+ */
1762
+ getAwaitingRecordCount(): Promise<number>;
1763
+ /**
1764
+ * Fetch a single record import by id.
1765
+ */
1766
+ getRecordImport(importId: string): Promise<RecordImport>;
1767
+ /**
1768
+ * Cancel a queued/background record import.
1769
+ */
1770
+ cancelRecordImport(importId: string): Promise<RecordImport>;
1771
+ /**
1772
+ * Removed: environment-scoped effect publication is no longer supported.
1773
+ */
1774
+ publishTools(tools: ToolWithHandler[], revision?: string): Promise<PublishToolsResult>;
1775
+ /**
1776
+ * Removed: environment-scoped effect publication is no longer supported.
1777
+ */
1778
+ publishEffect(effect: ToolWithHandler): Promise<PublishToolsResult>;
1779
+ /**
1780
+ * Removed: environment-scoped effect publication is no longer supported.
1781
+ */
1782
+ publishEffects(effects: ToolWithHandler[]): Promise<PublishToolsResult>;
1783
+ /**
1784
+ * Removed: environment-scoped effect publication is no longer supported.
1785
+ */
1786
+ unpublishEffect(name: string): Promise<PublishToolsResult>;
1787
+ /**
1788
+ * Removed: environment-scoped effect publication is no longer supported.
1789
+ */
1790
+ unpublishAllEffects(): Promise<PublishToolsResult>;
1791
+ }
1792
+ declare class Granular {
1793
+ private apiKey;
1794
+ private apiUrl;
1795
+ private httpUrl;
1796
+ private tokenProvider?;
1797
+ private WebSocketCtor?;
1798
+ private onUnexpectedClose?;
1799
+ private onReconnectError?;
1800
+ private debugHttp;
1801
+ /** Sandbox-level effect registry: sandboxId → (effectKey → ToolWithHandler) */
1802
+ private sandboxEffects;
1803
+ /** Live sandbox-scoped effect hosts keyed by sandboxId */
1804
+ private sandboxEffectHosts;
1805
+ /** In-flight host connection promises to avoid duplicate concurrent connects */
1806
+ private sandboxEffectHostPromises;
1807
+ /**
1808
+ * Create a new Granular client
1809
+ * @param options - Client configuration
1810
+ */
1811
+ constructor(options: GranularOptions);
1812
+ /**
1813
+ * Records/upserts a user and prepares them for sandbox connections
1814
+ *
1815
+ * @param options - User options
1816
+ * @returns The recorded user with both `userId` and `granularId`
1817
+ *
1818
+ * @example
1819
+ * ```typescript
1820
+ * const user = await granular.recordUser({
1821
+ * userId: 'user_123',
1822
+ * name: 'John Doe',
1823
+ * permissions: ['agent'],
1824
+ * });
1825
+ * ```
1826
+ */
1827
+ recordUser(options: RecordUserOptions): Promise<User>;
1828
+ private resolveConnectUser;
1829
+ /**
1830
+ * Connect to an ontology environment and establish a real-time session.
1831
+ *
1832
+ * Effects are registered at the sandbox level via `granular.registerEffect()`
1833
+ * or `granular.registerEffects()`. Sessions pick up live availability from
1834
+ * the sandbox registry automatically.
1835
+ *
1836
+ * @param options - Connection options
1837
+ * @returns An active environment session
1838
+ *
1839
+ * @example
1840
+ * ```typescript
1841
+ * const environment = await granular.connect({
1842
+ * ontology: 'my-ontology',
1843
+ * environment: 'dev',
1844
+ * userId: 'user_123',
1845
+ * permissions: ['agent'],
1846
+ * });
1847
+ *
1848
+ * await granular.registerEffect('my-sandbox', {
1849
+ * name: 'greet',
1850
+ * description: 'Say hello',
1851
+ * inputSchema: { type: 'object', properties: {} },
1852
+ * handler: async () => 'Hello!',
1853
+ * });
1854
+ *
1855
+ * // Submit job
1856
+ * const job = await environment.submitJob(`
1857
+ * import { tools } from './sandbox-tools';
1858
+ * return await tools.greet({});
1859
+ * `);
1860
+ *
1861
+ * console.log(await job.result); // 'Hello!'
1862
+ * ```
1863
+ */
1864
+ connect(options: ConnectOptions): Promise<Environment>;
1865
+ /**
1866
+ * List active (open) sessions for an environment — each session is one agent conversation thread.
1867
+ */
1868
+ listOpenSessions(filters: {
1869
+ environmentId: string;
1870
+ }): Promise<ConversationSessionInfo[]>;
1871
+ /**
1872
+ * List closed sessions for an environment (conversations that have disconnected).
1873
+ */
1874
+ listClosedSessions(filters: {
1875
+ environmentId: string;
1876
+ }): Promise<ConversationSessionInfo[]>;
1877
+ private listSessionsForEnvironment;
1878
+ private normalizeConversationSession;
1879
+ private static coerceIsoDate;
1880
+ /**
1881
+ * Create a new session (conversation) for an existing environment and connect to it.
1882
+ * The runtime graph is shared across all sessions for the same environment.
1883
+ */
1884
+ createSession(options: {
1885
+ environmentId: string;
1886
+ clientId?: string;
1887
+ initialHeap?: ConnectOptions['initialHeap'];
1888
+ }): Promise<Environment>;
1889
+ /**
1890
+ * Connect to an existing open session (same conversation thread) using a freshly minted WebSocket token.
1891
+ */
1892
+ connectSession(options: {
1893
+ sessionId: string;
1894
+ clientId?: string;
1895
+ }): Promise<Environment>;
1896
+ /**
1897
+ * Mark a session closed in the control plane. If `environment` is the connected handle for that
1898
+ * `sessionId`, disconnects the WebSocket so the runtime tears down cleanly.
1899
+ */
1900
+ closeSession(sessionId: string, environment?: Environment | null): Promise<void>;
1901
+ /**
1902
+ * Re-open a closed session in the index and connect to its existing runtime document.
1903
+ */
1904
+ reopenSession(sessionId: string, options?: {
1905
+ clientId?: string;
1906
+ }): Promise<Environment>;
1907
+ private bindWebSocketEnvironment;
1908
+ private activateEnvironment;
1909
+ private getSandboxEffectMap;
1910
+ private serializeEffect;
1911
+ private publishSandboxEffectCatalog;
1912
+ private syncSandboxEffectCatalog;
1913
+ private recoverEffectHost;
1914
+ private startEffectHostHeartbeat;
1915
+ private stopEffectHostHeartbeat;
1916
+ private synchronizeEffectHost;
1917
+ private ensureSandboxEffectHost;
1918
+ private disconnectSandboxEffectHost;
1919
+ /**
1920
+ * Register an effect (tool) for a specific sandbox.
1921
+ *
1922
+ * @param sandboxNameOrId - The name or ID of the sandbox
1923
+ * @param effect - The tool definition and handler
1924
+ */
1925
+ registerEffect(sandboxNameOrId: string, effect: ToolWithHandler): Promise<void>;
1926
+ /**
1927
+ * Register multiple effects (tools) for a specific sandbox.
1928
+ *
1929
+ * batch version of `registerEffect`.
1930
+ */
1931
+ registerEffects(sandboxNameOrId: string, effects: ToolWithHandler[]): Promise<void>;
1932
+ /**
1933
+ * Unregister an effect from a sandbox.
1934
+ *
1935
+ * Removes it from the local sandbox registry and updates the
1936
+ * sandbox-scoped live catalog.
1937
+ */
1938
+ unregisterEffect(sandboxNameOrId: string, name: string): Promise<void>;
1939
+ /**
1940
+ * Disconnect one sandbox-scoped effect host, or all of them when no sandbox is provided.
1941
+ *
1942
+ * This is primarily useful for long-lived helper processes such as generated
1943
+ * `granular-effects.ts` scripts that need to shut down cleanly on SIGINT/SIGTERM.
1944
+ */
1945
+ disconnectEffects(sandboxNameOrId?: string): Promise<void>;
1946
+ /**
1947
+ * Unregister all effects for a sandbox.
1948
+ */
1949
+ unregisterAllEffects(sandboxNameOrId: string): Promise<void>;
1950
+ /**
1951
+ * Find a sandbox by name or create it if it doesn't exist
1952
+ */
1953
+ private findOrCreateSandbox;
1954
+ /**
1955
+ * Ensure a permission profile exists for a sandbox, creating it if needed.
1956
+ * If profileName matches an existing profile name, returns its ID.
1957
+ * Otherwise, creates a new profile with default allow-all rules.
1958
+ */
1959
+ private ensurePermissionProfile;
1960
+ /**
1961
+ * Ensure an assignment exists for a subject in a sandbox with a permission profile
1962
+ */
1963
+ private ensureAssignment;
1964
+ /**
1965
+ * Sandbox management API
1966
+ */
1967
+ get sandboxes(): {
1968
+ list: () => Promise<SandboxListResponse>;
1969
+ get: (id: string) => Promise<Sandbox>;
1970
+ create: (data: CreateSandboxData) => Promise<Sandbox>;
1971
+ update: (id: string, data: Partial<CreateSandboxData>) => Promise<Sandbox>;
1972
+ delete: (id: string) => Promise<DeleteResponse>;
1973
+ };
1974
+ /**
1975
+ * Permission Profile management for sandboxes
1976
+ */
1977
+ get permissionProfiles(): {
1978
+ list: (sandboxId: string) => Promise<PermissionProfile[]>;
1979
+ get: (sandboxId: string, profileId: string) => Promise<PermissionProfile>;
1980
+ create: (sandboxId: string, data: CreatePermissionProfileData) => Promise<PermissionProfile>;
1981
+ delete: (sandboxId: string, profileId: string) => Promise<DeleteResponse>;
1982
+ };
1983
+ /**
1984
+ * Environment management
1985
+ */
1986
+ get environments(): {
1987
+ list: (sandboxId: string) => Promise<EnvironmentData[]>;
1988
+ get: (environmentId: string) => Promise<EnvironmentData>;
1989
+ create: (sandboxId: string, data: CreateEnvironmentData) => Promise<EnvironmentData>;
1990
+ delete: (environmentId: string) => Promise<DeleteResponse>;
1991
+ };
1992
+ /**
1993
+ * Event stream operations: query, subscribe, and acknowledge stream events
1994
+ */
1995
+ get streams(): {
1996
+ getEvents: (params: {
1997
+ ontology: string;
1998
+ stream: string;
1999
+ environment?: string;
2000
+ session?: string;
2001
+ eventTypes?: string[];
2002
+ since?: Date;
2003
+ until?: Date;
2004
+ isAcked?: boolean;
2005
+ limit?: number;
2006
+ offset?: number;
2007
+ }) => Promise<StreamEvent[]>;
2008
+ subscribe: (params: {
2009
+ ontology: string;
2010
+ stream: string;
2011
+ environment?: string;
2012
+ session?: string;
2013
+ eventTypes?: string[];
2014
+ since?: Date;
2015
+ onEvent: (event: StreamEvent) => void;
2016
+ onError?: (err: Error) => void;
2017
+ pollIntervalMs?: number;
2018
+ }) => StreamSubscription;
2019
+ ack: (eventId: string) => Promise<void>;
2020
+ ackBatch: (eventIds: string[]) => Promise<void>;
2021
+ getStats: (params: {
2022
+ ontology: string;
2023
+ environment?: string;
2024
+ }) => Promise<StreamStats[]>;
2025
+ };
2026
+ /**
2027
+ * Subject management
2028
+ */
2029
+ get subjects(): {
2030
+ get: (subjectId: string) => Promise<Subject>;
2031
+ listAssignments: (subjectId: string) => Promise<AssignmentListResponse>;
2032
+ };
2033
+ /**
2034
+ * @deprecated Use recordUser() instead
2035
+ */
2036
+ get users(): {
2037
+ create: (data: {
2038
+ id: string;
2039
+ name?: string;
2040
+ email?: string;
2041
+ }) => Promise<Subject>;
2042
+ get: (id: string) => Promise<Subject>;
2043
+ };
2044
+ private _resolveSandboxId;
2045
+ /**
2046
+ * Make an authenticated API request
2047
+ */
2048
+ private request;
2049
+ }
2050
+
2051
+ 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 ManifestContent 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 RecordObjectsOptions as aA, type RecordImportStatus as aB, type RecordImportItemStatus as aC, type RecordImportStats as aD, type RecordImportItem as aE, type RecordImport as aF, type EnvironmentRecordImportSummary as aG, type ManifestPropertySpec as aH, type ManifestValidationOperator as aI, type ManifestEnumRuleSpec as aJ, type ManifestFilterBySpec as aK, type ManifestValidationRuleSpec as aL, type ManifestStateMachineStateSpec as aM, type ManifestStateMachineTransitionSpec as aN, type ManifestStateMachineSpec as aO, type ManifestPostConditionSpec as aP, type ManifestDryRunSpec as aQ, type ManifestReverseSpec as aR, type ManifestApprovalRequiredSpec as aS, type ManifestRelationshipDef as aT, type ManifestEffectSchema as aU, type ManifestEffectDeclaration as aV, type ManifestEventTypeDef as aW, type ManifestEventStreamDef as aX, type ManifestOperation as aY, type ManifestImport as aZ, type ManifestVolume 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 RecordObjectsChunkInfo as az, type SessionHeapSnapshot as b, type GraphQLResult as b0, type APIError as b1, type DeleteResponse as b2, type StreamEvent as b3, type StreamSubscription as b4, type StreamStats as b5, 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 };