@granular-software/sdk 0.4.36 → 0.4.38

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.
@@ -1,2402 +0,0 @@
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 opening an ontology environment for one delegated subject.
90
- *
91
- * This does not open a live runtime session. Use
92
- * `environment.sessions.create()` or `granular.createSession({ environmentId })`
93
- * when you need a conversation/session with jobs, prompts, heap, and effects.
94
- */
95
- interface OpenEnvironmentOptions {
96
- /** The ontology name or ID to open. */
97
- ontology: string;
98
- /** Version channel to follow, typically `dev` or `prod`. */
99
- tag?: string;
100
- /**
101
- * External user identifier from your app.
102
- *
103
- * Exactly one of `userId`, `granularId`, or `user` should be provided.
104
- */
105
- userId?: string;
106
- /**
107
- * Internal Granular user identifier.
108
- *
109
- * Exactly one of `userId`, `granularId`, or `user` should be provided.
110
- */
111
- granularId?: string;
112
- /** Optional display name used when upserting the user. */
113
- name?: string;
114
- /** Optional email used when upserting the user. */
115
- email?: string;
116
- /**
117
- * Permission profile names or IDs to ensure before opening the environment.
118
- * This should be provided even for existing users so the SDK can guarantee
119
- * assignments for first-time environment creation.
120
- */
121
- permissions: string[];
122
- /**
123
- * When true, if the latest environment for this ontology/user/tag is marked
124
- * outdated relative to the current tag target, create a fresh environment on
125
- * the newest tag target instead of reusing the outdated one.
126
- */
127
- createFreshIfOutdated?: boolean;
128
- /** Backwards-compatible user object returned from `recordUser()`. */
129
- user?: User;
130
- }
131
- /**
132
- * Deprecated compatibility alias for the legacy `connect()` entry point.
133
- *
134
- * `connect()` now resolves an environment handle and no longer opens a runtime
135
- * session automatically. Prefer `openEnvironment()` for new code.
136
- */
137
- interface ConnectOptions extends OpenEnvironmentOptions {
138
- /** @deprecated Legacy explicit environment slot name. Prefer `tag`. */
139
- environment?: string;
140
- /** @deprecated Legacy tag field. Prefer `tag`. */
141
- tagName?: string;
142
- /** @deprecated Ignored by `connect()` now that it no longer opens sessions. */
143
- clientId?: string;
144
- /** @deprecated Ignored by `connect()` now that it no longer opens sessions. */
145
- initialHeap?: Array<{
146
- className: string;
147
- id: string;
148
- }>;
149
- }
150
- /**
151
- * Options for creating a live runtime session from an opened environment.
152
- */
153
- interface CreateSessionOptions {
154
- /** Optional stable client ID. Defaults to `client_${Date.now()}`. */
155
- clientId?: string;
156
- /** Optional session heap seed. Each item is eagerly hydrated into the session heap on connect. */
157
- initialHeap?: Array<{
158
- className: string;
159
- id: string;
160
- }>;
161
- }
162
- /**
163
- * Control-plane session row: one real-time conversation thread with the agent for an environment.
164
- */
165
- interface ConversationSessionInfo {
166
- sessionId: string;
167
- tenantId?: string;
168
- environmentId: string;
169
- versionId?: string | null;
170
- docId: string;
171
- status: "active" | "closed" | "expired";
172
- createdAt: string;
173
- lastSeenAt: string;
174
- summary?: string | null;
175
- summaryUpdatedAt?: string | null;
176
- subjectId?: string | null;
177
- jobCount?: number;
178
- toolCallCount?: number;
179
- }
180
- /**
181
- * A sandbox container
182
- */
183
- interface Sandbox {
184
- sandboxId: string;
185
- tenantId: string;
186
- name: string;
187
- description?: string | null;
188
- createdAt: number;
189
- updatedAt: number;
190
- }
191
- /**
192
- * Data for creating a new sandbox
193
- */
194
- interface CreateSandboxData {
195
- name: string;
196
- description?: string;
197
- }
198
- /**
199
- * List response for sandboxes
200
- */
201
- interface SandboxListResponse {
202
- items: Sandbox[];
203
- }
204
- /**
205
- * Rules defining what effects and resources are allowed or denied.
206
- */
207
- interface PermissionRules {
208
- /** Effect access rules */
209
- effects?: {
210
- /** Patterns for allowed effects (e.g. ["*"] for all, ["read_*"] for prefix match) */
211
- allow?: string[];
212
- /** Patterns for denied effects */
213
- deny?: string[];
214
- };
215
- /** Legacy alias accepted by the backend while migrating to `effects`. */
216
- tools?: {
217
- /** Patterns for allowed effects (e.g. ["*"] for all, ["read_*"] for prefix match) */
218
- allow?: string[];
219
- /** Patterns for denied effects */
220
- deny?: string[];
221
- };
222
- /** Resource access rules */
223
- resources?: {
224
- /** Patterns for allowed resources */
225
- allow?: string[];
226
- /** Patterns for denied resources */
227
- deny?: string[];
228
- };
229
- }
230
- /**
231
- * A permission profile defines access controls for an environment
232
- */
233
- interface PermissionProfile {
234
- permissionProfileId: string;
235
- sandboxId: string;
236
- name: string;
237
- rules: PermissionRules;
238
- createdAt: number;
239
- updatedAt: number;
240
- }
241
- /**
242
- * Data for creating a new permission profile
243
- */
244
- interface CreatePermissionProfileData {
245
- name: string;
246
- rules: PermissionRules;
247
- }
248
- /**
249
- * List response for permission profiles
250
- */
251
- interface PermissionProfileListResponse {
252
- items: PermissionProfile[];
253
- }
254
- /**
255
- * An assignment links a subject to a sandbox with a permission profile
256
- */
257
- interface Assignment {
258
- assignmentId: string;
259
- tenantId: string;
260
- subjectId: string;
261
- sandboxId: string;
262
- permissionProfileId: string;
263
- createdAt: number;
264
- createdBy?: string | null;
265
- }
266
- /**
267
- * List response for assignments
268
- */
269
- interface AssignmentListResponse {
270
- items: Assignment[];
271
- }
272
- /**
273
- * Version tracking policy for environments.
274
- *
275
- * Environments either follow a version tag such as `dev` or `prod`, or they
276
- * pin themselves to one immutable ontology version.
277
- */
278
- interface BuildPolicy {
279
- mode: "tag" | "current" | "pinned";
280
- buildId?: string;
281
- versionId?: string;
282
- tagId?: string;
283
- tagName?: string;
284
- }
285
- type VersionTracking = BuildPolicy;
286
- interface VersionTag {
287
- tagId: string;
288
- sandboxId: string;
289
- name: string;
290
- kind: "channel" | "release" | "system";
291
- targetBuildId?: string | null;
292
- targetVersionId?: string | null;
293
- description?: string | null;
294
- protected?: boolean;
295
- createdAt: number;
296
- updatedAt: number;
297
- }
298
- /**
299
- * An environment links a user (subject) to a sandbox with specific permissions
300
- */
301
- interface EnvironmentData {
302
- environmentId: string;
303
- sandboxId: string;
304
- ontologyId?: string;
305
- buildId: string;
306
- versionNumber?: number | null;
307
- versionId: string;
308
- subjectId: string;
309
- envName: string;
310
- environment?: string;
311
- permissionProfileId: string;
312
- tagId?: string | null;
313
- tag?: VersionTag | null;
314
- tracking?: BuildPolicy;
315
- buildPolicy: BuildPolicy;
316
- setup?: EnvironmentSetupSummary | null;
317
- updateState?: "up_to_date" | "update_available" | "upgrading" | "failed";
318
- createdAt: number;
319
- updatedAt: number;
320
- }
321
- /**
322
- * Data for creating a new environment
323
- */
324
- interface CreateEnvironmentData {
325
- /** The user/subject ID to create the environment for */
326
- subjectId: string;
327
- /** Named environment slot such as dev or prod */
328
- environment?: string;
329
- /** @deprecated Use `environment` instead. */
330
- envName?: string;
331
- /** The permission profile to apply (optional - uses assignment if not specified) */
332
- permissionProfileId?: string | null;
333
- /** Follow a tag directly */
334
- tagId?: string;
335
- /** Follow a tag by name, typically dev or prod */
336
- tagName?: string;
337
- /** Pin the environment to a specific version */
338
- versionId?: string;
339
- /** Legacy/compat environment tracking input */
340
- buildPolicy?: BuildPolicy;
341
- }
342
- /**
343
- * List response for environments
344
- */
345
- interface EnvironmentListResponse {
346
- items: EnvironmentData[];
347
- }
348
- /**
349
- * A manifest describes the structure and behavior of a sandbox
350
- */
351
- interface Manifest {
352
- manifestId: string;
353
- sandboxId: string;
354
- version: string;
355
- digest: string;
356
- content?: Record<string, unknown>;
357
- createdAt: number;
358
- locked?: boolean;
359
- }
360
- /**
361
- * List response for manifests
362
- */
363
- interface ManifestListResponse {
364
- items: Manifest[];
365
- }
366
- type BuildStatus = "queued" | "building" | "completed" | "failed" | "canceled";
367
- /**
368
- * An immutable ontology version derived from a specific manifest revision.
369
- *
370
- * The same version may have multiple build runs over time when the manifest
371
- * content is unchanged but the compilation process is re-executed.
372
- */
373
- interface Build {
374
- buildId: string;
375
- sandboxId: string;
376
- manifestId: string;
377
- manifestDigest?: string;
378
- versionNumber?: number;
379
- status: BuildStatus;
380
- graphBinaryId?: string | null;
381
- logsUri?: string | null;
382
- latestBuildRunId?: string | null;
383
- buildRunId?: string;
384
- createdNewVersion?: boolean;
385
- environmentCount?: number;
386
- laggingEnvironmentCount?: number;
387
- sessionCount?: number;
388
- createdAt: number;
389
- updatedAt: number;
390
- isCurrent?: boolean;
391
- }
392
- type Version = Build;
393
- /**
394
- * List response for versions
395
- */
396
- interface BuildListResponse {
397
- items: Build[];
398
- }
399
- interface SemanticVersionDiffEntry {
400
- operationId: string;
401
- kind: "create" | "update" | "relationship" | "effect" | "eventStream" | "unknown";
402
- changeType: "added" | "removed" | "changed";
403
- label: string;
404
- additive: boolean;
405
- breaking: boolean;
406
- before?: Record<string, unknown>;
407
- after?: Record<string, unknown>;
408
- }
409
- interface SemanticVersionDiff {
410
- summary: {
411
- added: number;
412
- removed: number;
413
- changed: number;
414
- additive: number;
415
- breaking: number;
416
- onlyAdditiveChanges: boolean;
417
- };
418
- entries: SemanticVersionDiffEntry[];
419
- }
420
- /**
421
- * Effect handler for static/global effects: receives (input, context)
422
- */
423
- interface EffectHandlerContext {
424
- effectClientId: string;
425
- sandboxId: string;
426
- environmentId: string;
427
- buildId?: string;
428
- buildVersionNumber?: number;
429
- sessionId: string;
430
- tenantId?: string;
431
- principalId?: string;
432
- permissionProfileId?: string;
433
- user: {
434
- granularId?: string;
435
- userId?: string;
436
- subjectId: string;
437
- identityId?: string;
438
- principalId?: string;
439
- };
440
- behaviors?: ResolvedEffectBehaviors;
441
- invocation?: EffectInvocationMetadata;
442
- }
443
- interface ResolvedEffectPostCondition {
444
- condition: string;
445
- description?: string;
446
- }
447
- interface ResolvedEffectDryRun {
448
- enabled: boolean;
449
- description?: string;
450
- }
451
- interface ResolvedEffectReverse {
452
- handler?: string;
453
- description?: string;
454
- }
455
- interface ResolvedEffectApprovalRequired {
456
- required: boolean;
457
- reason?: string;
458
- mode?: string;
459
- }
460
- interface ResolvedEffectBehaviors {
461
- postCondition?: ResolvedEffectPostCondition;
462
- dryRun?: ResolvedEffectDryRun;
463
- reverse?: ResolvedEffectReverse;
464
- approvalRequired?: ResolvedEffectApprovalRequired;
465
- }
466
- type EffectInvocationMode = "execute" | "dryRun" | "reverse";
467
- interface EffectInvocationMetadata {
468
- mode?: EffectInvocationMode;
469
- reverseHandler?: string;
470
- sourceEffectKey?: string;
471
- sourceEffectName?: string;
472
- }
473
- type ToolHandler = (input: any, context: EffectHandlerContext) => Promise<unknown>;
474
- /**
475
- * Effect handler for instance methods: receives (objectId, input, context)
476
- */
477
- type InstanceToolHandler = (id: string, input: any, context: EffectHandlerContext) => Promise<unknown>;
478
- /**
479
- * Effect schema for declaring or registering an effect.
480
- *
481
- * Effects come in three flavours:
482
- *
483
- * 1. **Instance methods** — set `className`, omit `static`.
484
- * In the sandbox: `tolkien.get_bio({ detailed: true })`
485
- * Handler signature: `(objectId: string, params: any) => any`
486
- *
487
- * 2. **Static methods** — set `className` + `static: true`.
488
- * In the sandbox: `Author.search({ query: 'tolkien' })`
489
- * Handler signature: `(params: any) => any`
490
- *
491
- * 3. **Global effects** — omit `className`.
492
- * In the sandbox: `global_search({ query: 'rings' })`
493
- * Handler signature: `(params: any) => any`
494
- *
495
- * Both `inputSchema` and `outputSchema` accept JSON Schema objects.
496
- * The `outputSchema` drives the return type in the auto-generated
497
- * TypeScript declarations that sandbox code imports from `./sandbox-tools`.
498
- */
499
- interface ToolSchema {
500
- effectKey?: string;
501
- name: string;
502
- description: string;
503
- /** JSON Schema for the effect input parameters */
504
- inputSchema: Record<string, unknown>;
505
- /**
506
- * JSON Schema for the tool's return value.
507
- * Used to generate typed return types in the sandbox TypeScript declarations.
508
- *
509
- * @example
510
- * ```typescript
511
- * outputSchema: {
512
- * type: 'object',
513
- * properties: {
514
- * bio: { type: 'string', description: 'The biography text' },
515
- * source: { type: 'string', description: 'Source of the bio' },
516
- * },
517
- * required: ['bio'],
518
- * }
519
- * // Generates: Promise<{ bio: string; source?: string }>
520
- * ```
521
- */
522
- outputSchema?: Record<string, unknown>;
523
- stability?: "stable" | "experimental" | "deprecated";
524
- provenance?: {
525
- source: "mcp" | "custom";
526
- };
527
- tags?: string[];
528
- /**
529
- * The class this effect belongs to (e.g., `'author'`, `'book'`).
530
- * When set, the effect becomes a method on the auto-generated class.
531
- * Omit for global effects (standalone exported functions).
532
- */
533
- className?: string;
534
- /**
535
- * If `true`, this is a static/class-level method (no object ID required).
536
- * If `false` or omitted and `className` is set, this is an instance method
537
- * that operates on a specific object (the object's real-world ID is
538
- * passed as the first argument to the handler).
539
- */
540
- static?: boolean;
541
- /**
542
- * Optional build-version selector for this live effect binding.
543
- *
544
- * When omitted, the binding applies to all build versions for the sandbox.
545
- */
546
- versionSelector?: EffectVersionSelector;
547
- /** Declarative runtime behaviors attached to the effect. */
548
- metamodels?: ManifestEffectMetamodelSpec;
549
- }
550
- type EffectSchema = ToolSchema;
551
- /**
552
- * Effect with handler — what users provide to `registerEffect()`.
553
- *
554
- * - **Instance methods** (`className` set, `static` omitted):
555
- * handler receives `(objectId: string, params: any)`
556
- * - **Static methods** (`className` set, `static: true`):
557
- * handler receives `(params: any)`
558
- * - **Global tools** (no `className`):
559
- * handler receives `(params: any)`
560
- */
561
- interface ToolWithHandler extends ToolSchema {
562
- handler: ToolHandler | InstanceToolHandler;
563
- dryRunHandler?: ToolHandler | InstanceToolHandler;
564
- reverseHandler?: ToolHandler | InstanceToolHandler;
565
- }
566
- type EffectWithHandler = ToolWithHandler;
567
- /**
568
- * Result from publishing or synchronizing effects
569
- */
570
- interface PublishToolsResult {
571
- accepted: boolean;
572
- domainRevision: string;
573
- rejected?: Array<{
574
- name: string;
575
- reason: string;
576
- }>;
577
- }
578
- type PublishEffectsResult = PublishToolsResult;
579
- type EffectVersionSelector = {
580
- mode: "all";
581
- } | {
582
- mode: "exact";
583
- versionNumber: number;
584
- } | {
585
- mode: "before";
586
- versionNumber: number;
587
- } | {
588
- mode: "after";
589
- versionNumber: number;
590
- };
591
- /**
592
- * Domain state response
593
- */
594
- interface DomainState {
595
- activeDomainRevision?: string;
596
- tools?: Array<{
597
- name: string;
598
- description?: string;
599
- inputSchema?: Record<string, unknown>;
600
- outputSchema?: Record<string, unknown>;
601
- metamodels?: ManifestEffectMetamodelSpec;
602
- }>;
603
- [key: string]: unknown;
604
- }
605
- /**
606
- * Information about a live or declared effect
607
- */
608
- interface ToolInfo {
609
- effectKey?: string;
610
- /** Unique name of the effect */
611
- name: string;
612
- /** Description of what the effect does */
613
- description?: string;
614
- /** JSON Schema for effect input */
615
- inputSchema?: Record<string, unknown>;
616
- /** JSON Schema for effect output */
617
- outputSchema?: Record<string, unknown>;
618
- /** Client ID that published this effect (absent for domain-only entries) */
619
- clientId?: string;
620
- /** Whether the effect is ready for use (has a registered handler) */
621
- ready: boolean;
622
- /** Timestamp when the effect was published */
623
- publishedAt?: number;
624
- /** Class this effect belongs to (instance/static method) */
625
- className?: string;
626
- /** Whether this is a static method */
627
- static?: boolean;
628
- /** Optional build-version selector associated with the live binding. */
629
- versionSelector?: EffectVersionSelector;
630
- /** Declarative runtime behaviors attached to the effect. */
631
- metamodels?: ManifestEffectMetamodelSpec;
632
- }
633
- interface EffectInfo extends ToolInfo {
634
- }
635
- /**
636
- * Event data when the list of available effects changes
637
- */
638
- interface ToolsChangedEvent {
639
- /** The current list of all available effects */
640
- tools: ToolInfo[];
641
- /** Names of effects that were added or updated */
642
- added: string[];
643
- /** Names of effects that were removed */
644
- removed: string[];
645
- }
646
- interface EffectsChangedEvent extends ToolsChangedEvent {
647
- /** The current list of all available effects */
648
- effects: EffectInfo[];
649
- }
650
- type EffectHandler = ToolHandler;
651
- type InstanceEffectHandler = InstanceToolHandler;
652
- type JobStatus = "queued" | "running" | "awaitingTool" | "awaitingHuman" | "succeeded" | "failed" | "timeout" | "canceled";
653
- type JobFeedbackSentiment = "good" | "bad";
654
- interface JobFeedbackToolCall {
655
- callId?: string;
656
- toolName?: string;
657
- input?: unknown;
658
- output?: unknown;
659
- error?: string;
660
- startedAt?: number;
661
- completedAt?: number;
662
- durationMs?: number | null;
663
- }
664
- interface JobFeedbackMetadata {
665
- source: "sdk";
666
- status: JobStatus;
667
- code: string;
668
- domainRevision?: string;
669
- createdAt: number;
670
- startedAt?: number;
671
- completedAt?: number;
672
- durationMs?: number | null;
673
- result?: unknown;
674
- error?: string;
675
- stdout: string[];
676
- stderr: string[];
677
- toolCalls: JobFeedbackToolCall[];
678
- }
679
- interface JobFeedbackInput {
680
- sentiment: JobFeedbackSentiment;
681
- comment?: string | null;
682
- }
683
- interface JobFeedbackRecord {
684
- feedbackId: string;
685
- tenantId?: string;
686
- sessionId: string;
687
- environmentId: string;
688
- sandboxId?: string;
689
- buildId?: string;
690
- subjectId?: string;
691
- jobId: string;
692
- sentiment: JobFeedbackSentiment;
693
- comment?: string | null;
694
- metadata: JobFeedbackMetadata & Record<string, unknown>;
695
- createdAt: number;
696
- updatedAt: number;
697
- }
698
- /**
699
- * Persisted feedback row listed at the environment level.
700
- */
701
- interface EnvironmentFeedbackRecord {
702
- feedbackId: string;
703
- sessionId: string;
704
- jobId: string;
705
- sentiment: JobFeedbackSentiment;
706
- comment?: string | null;
707
- metadata?: Record<string, unknown> | null;
708
- createdAt: string | null;
709
- }
710
- /**
711
- * Result from submitting a job
712
- */
713
- interface JobSubmitResult {
714
- jobId: string;
715
- }
716
- /**
717
- * Represents a job executed in the sandbox
718
- */
719
- interface Job {
720
- /** Unique Job ID */
721
- id: string;
722
- /** Current status of the job */
723
- status: JobStatus;
724
- /** Promise that resolves with the job result */
725
- result: Promise<unknown>;
726
- /** Attach user feedback to this job and persist it with job/session metadata */
727
- leaveFeedback(input: JobFeedbackInput): Promise<JobFeedbackRecord>;
728
- /** Subscribe to job events */
729
- on(event: string, handler: (data: unknown) => void): () => void;
730
- }
731
- interface Prompt {
732
- id: string;
733
- type: "confirm" | "choice" | "input";
734
- title: string;
735
- message: string;
736
- options?: Array<string | {
737
- value: string;
738
- label: string;
739
- description?: string;
740
- }>;
741
- defaultValue?: unknown;
742
- placeholder?: string;
743
- allowEmpty?: boolean;
744
- metadata?: Record<string, unknown>;
745
- }
746
- interface ConversationMessageShowRefs {
747
- entryPaths?: string[];
748
- listNames?: string[];
749
- variableNames?: string[];
750
- }
751
- interface ConversationMessageInput {
752
- role: "user" | "assistant";
753
- content?: string;
754
- show?: ConversationMessageShowRefs;
755
- jobId?: string;
756
- promptId?: string;
757
- timestamp?: number;
758
- }
759
- interface ConversationAppendResult {
760
- ok: boolean;
761
- messageId: string;
762
- timestamp: number;
763
- jobId?: string;
764
- promptId?: string;
765
- }
766
- interface SessionConversationMessage {
767
- id: string;
768
- role: "user" | "assistant";
769
- content?: string;
770
- show?: ConversationMessageShowRefs;
771
- jobId?: string;
772
- promptId?: string;
773
- ts: number;
774
- [key: string]: unknown;
775
- }
776
- interface SessionTimelineEvent {
777
- id?: string;
778
- eventId?: string;
779
- kind?: string;
780
- type?: string;
781
- status?: string | null;
782
- message?: string;
783
- summary?: string;
784
- title?: string;
785
- ts?: number;
786
- timestamp?: number;
787
- at?: number;
788
- createdAt?: number;
789
- [key: string]: unknown;
790
- }
791
- interface SessionJobRecord {
792
- jobId: string;
793
- status: string;
794
- code?: string;
795
- createdAt?: number;
796
- startedAt?: number;
797
- completedAt?: number;
798
- durationMs?: number | null;
799
- progressPercent?: number | null;
800
- progressMessage?: string | null;
801
- stdout?: string[];
802
- stderr?: string[];
803
- result?: unknown;
804
- error?: string | null;
805
- toolCalls?: JobFeedbackToolCall[];
806
- prompts?: Record<string, unknown>;
807
- actionSummary?: string[];
808
- actionTrace?: Array<Record<string, unknown>>;
809
- agentMessages?: Array<Record<string, unknown>>;
810
- [key: string]: unknown;
811
- }
812
- interface SessionTranscriptEntry {
813
- id: string;
814
- role: "user" | "assistant";
815
- content: string;
816
- timestamp: number;
817
- jobId?: string;
818
- promptId?: string;
819
- code?: string;
820
- jobStatus?: string;
821
- jobResultPreview?: string;
822
- error?: string;
823
- show?: ConversationMessageShowRefs;
824
- historyContent?: string;
825
- source: "conversation" | "job_code" | "job_result" | "job_prompt" | "job_agent_message";
826
- }
827
- type SessionHeapFieldType = "string" | "number" | "boolean" | "null" | "unknown";
828
- interface SessionHeapFieldValue {
829
- name: string;
830
- type: SessionHeapFieldType;
831
- value: string | number | boolean | null;
832
- }
833
- interface SessionHeapEntry {
834
- path: string;
835
- className: string;
836
- id: string;
837
- label?: string | null;
838
- description?: string | null;
839
- prototypes: string[];
840
- fields: SessionHeapFieldValue[];
841
- relatedJobIds: string[];
842
- source: string;
843
- createdAt: number;
844
- updatedAt: number;
845
- }
846
- interface SessionHeapList {
847
- name: string;
848
- className: string;
849
- paths: string[];
850
- relatedJobIds: string[];
851
- updatedAt: number;
852
- }
853
- interface SessionHeapVariable {
854
- name: string;
855
- kind: "entry" | "list" | "scalar";
856
- entryPath?: string;
857
- listName?: string;
858
- value?: string | number | boolean | null;
859
- className?: string;
860
- updatedAt: number;
861
- }
862
- interface SessionHeapSnapshot {
863
- entriesByPath: Record<string, SessionHeapEntry>;
864
- listsByName: Record<string, SessionHeapList>;
865
- variablesByName: Record<string, SessionHeapVariable>;
866
- updatedAt: number;
867
- }
868
- interface SessionDocumentResult {
869
- sessionState: Record<string, unknown> | null;
870
- document: Record<string, unknown> | null;
871
- savedAt: number;
872
- }
873
- interface SessionCollectionListOptions {
874
- limit?: number;
875
- cursor?: string | null;
876
- }
877
- interface SessionJobListOptions extends SessionCollectionListOptions {
878
- status?: string | null;
879
- }
880
- interface SessionCollectionListResult<T = unknown> {
881
- items: T[];
882
- nextCursor: string | null;
883
- totalCount: number;
884
- }
885
- interface WSDisconnectInfo {
886
- code?: number;
887
- reason?: string;
888
- wasClean?: boolean;
889
- unexpected: boolean;
890
- timestamp: number;
891
- reconnectScheduled: boolean;
892
- reconnectDelayMs?: number;
893
- }
894
- interface WSReconnectErrorInfo {
895
- sessionId: string;
896
- error: string;
897
- timestamp: number;
898
- }
899
- interface WSClientOptions {
900
- url: string;
901
- sessionId: string;
902
- token: string;
903
- tokenProvider?: AccessTokenProvider;
904
- WebSocketCtor?: any;
905
- onUnexpectedClose?: (info: WSDisconnectInfo) => void;
906
- onReconnectError?: (info: WSReconnectErrorInfo) => void;
907
- }
908
- interface RPCRequest {
909
- type: "rpc";
910
- method: string;
911
- params: unknown;
912
- id: string;
913
- }
914
- interface RPCResponse {
915
- type: "rpc_result" | "rpc_error";
916
- id: string;
917
- result?: unknown;
918
- error?: {
919
- code: number;
920
- message: string;
921
- data?: unknown;
922
- };
923
- }
924
- interface SyncMessage {
925
- type: "sync";
926
- message?: string | number[] | Uint8Array;
927
- data?: number[];
928
- }
929
- interface RPCRequestFromServer {
930
- type: "rpc";
931
- method: string;
932
- params: unknown;
933
- id: string;
934
- }
935
- interface ToolInvokeParams {
936
- callId: string;
937
- toolName: string;
938
- input: unknown;
939
- }
940
- interface ToolResultParams {
941
- callId: string;
942
- result?: unknown;
943
- error?: string | {
944
- code: string;
945
- message: string;
946
- };
947
- }
948
- /**
949
- * A model reference as returned from relationship queries
950
- */
951
- interface ModelRef {
952
- path: string;
953
- label?: string;
954
- }
955
- /**
956
- * Relationship info as returned from the GraphQL API.
957
- * Represents a typed, bidirectional relationship between two model types,
958
- * seen from one model's perspective.
959
- */
960
- interface RelationshipInfo {
961
- /** Unique name of this relationship definition */
962
- name: string;
963
- /** The submodel on this model that holds the relationship */
964
- local_submodel: ModelRef;
965
- /** Whether this side is a "many" collection */
966
- local_is_many: boolean;
967
- /** The submodel on the foreign model */
968
- foreign_submodel: ModelRef;
969
- /** Whether the foreign side is a "many" collection */
970
- foreign_is_many: boolean;
971
- /** The foreign model type */
972
- foreign_model: ModelRef;
973
- /** Computed relationship kind: "one_to_one" | "one_to_many" | "many_to_one" | "many_to_many" */
974
- relationship_kind: "one_to_one" | "one_to_many" | "many_to_one" | "many_to_many";
975
- }
976
- /**
977
- * Options for defining a relationship between two model types
978
- */
979
- interface DefineRelationshipOptions {
980
- /** The model to define the relationship on (the "left" / "local" type) */
981
- model: string;
982
- /** The submodel name on the local model (e.g., "books") */
983
- localSubmodel: string;
984
- /** Whether the local side is "many" */
985
- localIsMany: boolean;
986
- /** The foreign model type (e.g., "book") */
987
- foreignModel: string;
988
- /** The submodel name on the foreign model (e.g., "author") */
989
- foreignSubmodel: string;
990
- /** Whether the foreign side is "many" */
991
- foreignIsMany: boolean;
992
- /** Optional relationship name (auto-generated if omitted) */
993
- name?: string;
994
- }
995
- /**
996
- * Options for creating or updating a class instance in the graph.
997
- *
998
- * `recordObject` uses the graph's `instantiate` (find-or-create) semantics:
999
- * if an instance with the given `id` already exists under the class, its
1000
- * fields are updated in place; otherwise a new instance is created.
1001
- */
1002
- interface RecordObjectOptions {
1003
- /** The class to instantiate (e.g., "author") */
1004
- className: string;
1005
- /**
1006
- * Real-world object ID. Unique within its class, but two objects of
1007
- * different classes may share the same ID. Internally the SDK derives
1008
- * a unique graph path as `{className}__{id}`.
1009
- */
1010
- id: string;
1011
- /** Optional display label (defaults to `id`) */
1012
- label?: string;
1013
- /** Scalar field values to set on the instance */
1014
- fields?: Record<string, string | number | boolean | null>;
1015
- /**
1016
- * Relationship attachments.
1017
- * Keys are relationship submodel names. Values are real-world IDs
1018
- * (not graph paths) — the SDK resolves them using the foreign class
1019
- * derived from the relationship definition.
1020
- * - For a "one" side: pass a single target ID (string)
1021
- * - For a "many" side: pass an array of target IDs
1022
- */
1023
- relationships?: Record<string, string | string[]>;
1024
- }
1025
- /**
1026
- * Return value from `recordObject()`
1027
- */
1028
- interface RecordObjectResult {
1029
- /** The internal graph path (e.g., "author__tolkien") */
1030
- path: string;
1031
- /** The real-world object ID as provided by the caller (e.g., "tolkien") */
1032
- id: string;
1033
- /** Whether the instance was newly created (false = updated) */
1034
- created: boolean;
1035
- }
1036
- /**
1037
- * Metadata for one completed HTTP chunk in `recordObjects()`.
1038
- * Chunk indices follow input order; when concurrency is greater than 1, completion order may differ.
1039
- */
1040
- interface RecordObjectsChunkInfo {
1041
- /** Zero-based chunk index */
1042
- chunkIndex: number;
1043
- totalChunks: number;
1044
- /** Zero-based offset into the original `records` array */
1045
- offset: number;
1046
- /** Number of records in this chunk */
1047
- recordCount: number;
1048
- /** Wall time for this chunk’s POST (including retries) */
1049
- durationMs: number;
1050
- /** Acknowledgements for this chunk, in the same order as the slice sent */
1051
- results: RecordObjectResult[];
1052
- }
1053
- /**
1054
- * Optional tuning for `recordObjects()` — batching, parallelism, and progress hooks.
1055
- */
1056
- interface RecordObjectsOptions {
1057
- /**
1058
- * Max records per HTTP POST to the control-plane batch endpoint. Default 100.
1059
- * Smaller values: more round trips and finer `onChunkComplete` updates.
1060
- * Larger values: fewer requests (watch request size/timeouts).
1061
- */
1062
- batchSize?: number;
1063
- /**
1064
- * How many chunk POSTs may run concurrently. Default 1 (strictly sequential).
1065
- * Values above 1 can reduce wall time when the server can overlap work; capped at 16.
1066
- */
1067
- concurrency?: number;
1068
- /**
1069
- * Called after each chunk succeeds (after retries). Useful for UI progress bars.
1070
- */
1071
- onChunkComplete?: (info: RecordObjectsChunkInfo) => void | Promise<void>;
1072
- }
1073
- type RecordImportStatus = "queued" | "processing" | "completed" | "failed" | "canceled";
1074
- type RecordImportItemStatus = "queued" | "processing" | "completed" | "failed" | "canceled";
1075
- interface RecordImportStats {
1076
- totalRecords: number;
1077
- queuedRecords: number;
1078
- processingRecords: number;
1079
- completedRecords: number;
1080
- failedRecords: number;
1081
- canceledRecords: number;
1082
- awaitingRecords: number;
1083
- }
1084
- interface RecordImportItem {
1085
- itemId: string;
1086
- importId: string;
1087
- tenantId: string;
1088
- environmentId: string;
1089
- className: string;
1090
- id: string;
1091
- label: string | null;
1092
- fields: Record<string, string | number | boolean | null> | null;
1093
- relationships: Record<string, string | string[]> | null;
1094
- status: RecordImportItemStatus;
1095
- attempts: number;
1096
- errorMessage: string | null;
1097
- resultPath: string | null;
1098
- resultCreated: boolean | null;
1099
- createdAt: number;
1100
- updatedAt: number;
1101
- processedAt: number | null;
1102
- }
1103
- interface RecordImport {
1104
- importId: string;
1105
- tenantId: string;
1106
- environmentId: string;
1107
- sandboxId: string;
1108
- subjectId: string;
1109
- setupRunId?: string | null;
1110
- status: RecordImportStatus;
1111
- batchSize: number;
1112
- errorMessage: string | null;
1113
- createdAt: number;
1114
- updatedAt: number;
1115
- startedAt: number | null;
1116
- finishedAt: number | null;
1117
- canceledAt: number | null;
1118
- stats: RecordImportStats;
1119
- }
1120
- interface EnvironmentRecordImportSummary extends RecordImportStats {
1121
- environmentId: string;
1122
- totalImports: number;
1123
- activeImports: number;
1124
- updatedAt: number;
1125
- }
1126
- type EnvironmentSetupTriggerReason = "new_environment" | "fresh_after_version_update";
1127
- type EnvironmentSetupLifecycleStatus = "running" | "completed" | "failed";
1128
- interface EnvironmentSetupSummary extends RecordImportStats {
1129
- setupRunId: string;
1130
- environmentId: string;
1131
- sandboxId: string;
1132
- subjectId: string;
1133
- triggerReason: EnvironmentSetupTriggerReason;
1134
- lifecycleStatus: EnvironmentSetupLifecycleStatus;
1135
- stage: string | null;
1136
- totalObjectsToImport: number;
1137
- totalImports: number;
1138
- activeImports: number;
1139
- errorMessage: string | null;
1140
- startedAt: number;
1141
- hookCompletedAt: number | null;
1142
- finishedAt: number | null;
1143
- updatedAt: number;
1144
- }
1145
- interface EnvironmentImporterImportOptions {
1146
- batchSize?: number;
1147
- }
1148
- interface EnvironmentImporter {
1149
- environmentId: string;
1150
- sandboxId: string;
1151
- subjectId: string;
1152
- reason: EnvironmentSetupTriggerReason;
1153
- incrementTotalObjectsToImportCount: (n: number) => Promise<void>;
1154
- setStage: (stage: string | null) => Promise<void>;
1155
- importRecords: (records: RecordObjectOptions[], options?: EnvironmentImporterImportOptions) => Promise<RecordImport>;
1156
- }
1157
- /**
1158
- * Property specification in a manifest operation
1159
- */
1160
- interface ManifestPropertySpec {
1161
- value?: string | number | boolean;
1162
- ref?: string;
1163
- instanceOf?: string;
1164
- create?: string;
1165
- has?: Record<string, ManifestPropertySpec>;
1166
- type?: string;
1167
- description?: string;
1168
- required?: boolean;
1169
- note?: string | string[];
1170
- enum?: string[] | ManifestEnumRuleSpec;
1171
- filterBy?: boolean | string[] | ManifestFilterBySpec;
1172
- validate?: ManifestValidationRuleSpec[];
1173
- }
1174
- type ManifestValidationOperator = "eq" | "neq" | "gt" | "gte" | "lt" | "lte" | "true" | "false" | "regex" | "contains" | "not_contains" | "starts_with" | "ends_with";
1175
- interface ManifestEnumRuleSpec {
1176
- values: string[];
1177
- message?: string;
1178
- }
1179
- interface ManifestFilterBySpec {
1180
- operators: string[];
1181
- scalarType?: string;
1182
- }
1183
- interface ManifestValidationRuleSpec {
1184
- operator: ManifestValidationOperator;
1185
- stringValue?: string;
1186
- numberValue?: number;
1187
- booleanValue?: boolean;
1188
- message?: string;
1189
- }
1190
- interface ManifestStateMachineStateSpec {
1191
- name: string;
1192
- isFinal?: boolean;
1193
- }
1194
- interface ManifestStateMachineTransitionSpec {
1195
- name: string;
1196
- from: string;
1197
- to: string;
1198
- }
1199
- interface ManifestStateMachineSpec {
1200
- name: string;
1201
- entryState: string;
1202
- states: Array<string | ManifestStateMachineStateSpec>;
1203
- transitions: ManifestStateMachineTransitionSpec[];
1204
- finalStates?: string[];
1205
- }
1206
- interface ManifestPostConditionSpec {
1207
- condition: string;
1208
- description?: string;
1209
- }
1210
- interface ManifestDryRunSpec {
1211
- enabled?: boolean;
1212
- description?: string;
1213
- }
1214
- interface ManifestReverseSpec {
1215
- handler?: string;
1216
- description?: string;
1217
- }
1218
- interface ManifestApprovalRequiredSpec {
1219
- required?: boolean;
1220
- reason?: string;
1221
- mode?: string;
1222
- }
1223
- interface ManifestEffectMetamodelSpec {
1224
- postCondition?: string | ManifestPostConditionSpec;
1225
- dryRun?: boolean | ManifestDryRunSpec;
1226
- reverse?: string | ManifestReverseSpec;
1227
- approvalRequired?: boolean | ManifestApprovalRequiredSpec;
1228
- }
1229
- /**
1230
- * Relationship definition between two classes
1231
- */
1232
- interface ManifestRelationshipDef {
1233
- /** Optional name (auto-generated from left_right if omitted) */
1234
- name?: string;
1235
- /** Left model path */
1236
- left: string;
1237
- /** Right model path */
1238
- right: string;
1239
- /** Submodel name on the left model */
1240
- leftSubmodel: string;
1241
- /** Submodel name on the right model */
1242
- rightSubmodel: string;
1243
- /** Whether the left side is a collection */
1244
- leftIsMany: boolean;
1245
- /** Whether the right side is a collection */
1246
- rightIsMany: boolean;
1247
- }
1248
- interface ManifestEffectSchema {
1249
- type: string;
1250
- properties?: Record<string, unknown>;
1251
- required?: string[];
1252
- items?: unknown;
1253
- description?: string;
1254
- [key: string]: unknown;
1255
- }
1256
- interface ManifestEffectDeclaration {
1257
- name: string;
1258
- description?: string;
1259
- attachedClass?: string;
1260
- isStatic?: boolean;
1261
- inputSchema: ManifestEffectSchema;
1262
- outputSchema?: ManifestEffectSchema;
1263
- stability?: "stable" | "experimental" | "deprecated";
1264
- tags?: string[];
1265
- metamodels?: ManifestEffectMetamodelSpec;
1266
- }
1267
- /**
1268
- * An event type within an event stream definition
1269
- */
1270
- interface ManifestEventTypeDef {
1271
- name: string;
1272
- description?: string;
1273
- payloadSchema: ManifestEffectSchema;
1274
- }
1275
- /**
1276
- * Event stream definition for outgoing typed events
1277
- */
1278
- interface ManifestEventStreamDef {
1279
- name: string;
1280
- description?: string;
1281
- eventTypes: ManifestEventTypeDef[];
1282
- }
1283
- /**
1284
- * A single operation in a manifest volume
1285
- */
1286
- interface ManifestOperation {
1287
- /** Create a new model/class */
1288
- create?: string;
1289
- /** Target an existing model for modification */
1290
- on?: string;
1291
- /** Extend from a parent class */
1292
- extends?: string;
1293
- /** Instantiate a type */
1294
- instanceOf?: string;
1295
- /** Define submodels/fields */
1296
- has?: Record<string, ManifestPropertySpec>;
1297
- /** Advisory notes attached to the model/class itself */
1298
- note?: string | string[];
1299
- /** State machines attached to the created or targeted class */
1300
- stateMachines?: ManifestStateMachineSpec[];
1301
- /** Define a relationship between two classes */
1302
- defineRelationship?: ManifestRelationshipDef;
1303
- /** Declare a build-owned effect */
1304
- withEffect?: ManifestEffectDeclaration;
1305
- /** Define an outgoing event stream with typed events */
1306
- defineEventStream?: ManifestEventStreamDef;
1307
- }
1308
- /**
1309
- * A volume in a manifest
1310
- */
1311
- /**
1312
- * Import descriptor for referencing modules
1313
- */
1314
- interface ManifestImport {
1315
- /** Alias prefix used in operations (e.g., "@std") */
1316
- alias: string;
1317
- /** Module name (e.g., "standard_modules") */
1318
- name: string;
1319
- /** Version label (e.g., "prod", "v1.2.3") */
1320
- label?: string;
1321
- }
1322
- interface ManifestVolume {
1323
- name: string;
1324
- scope: "sandbox" | "build" | "user";
1325
- imports?: ManifestImport[];
1326
- operations: ManifestOperation[];
1327
- }
1328
- /**
1329
- * A manifest defines the structure of a sandbox's data model
1330
- */
1331
- interface ManifestContent {
1332
- schemaVersion: 2;
1333
- name: string;
1334
- description?: string;
1335
- volumes: ManifestVolume[];
1336
- }
1337
- /**
1338
- * Result from a GraphQL query execution
1339
- */
1340
- interface GraphQLResult<T = any> {
1341
- data?: T;
1342
- errors?: Array<{
1343
- message: string;
1344
- locations?: Array<{
1345
- line: number;
1346
- column: number;
1347
- }>;
1348
- path?: Array<string | number>;
1349
- extensions?: Record<string, any>;
1350
- }>;
1351
- }
1352
- interface APIError {
1353
- error: string;
1354
- message?: string;
1355
- }
1356
- interface DeleteResponse {
1357
- deleted: boolean;
1358
- }
1359
- interface StreamEvent {
1360
- eventId: string;
1361
- streamName: string;
1362
- eventType: string;
1363
- payload: Record<string, unknown>;
1364
- environmentId: string;
1365
- sessionId?: string;
1366
- subjectId?: string;
1367
- source: "sandbox" | "api";
1368
- isAcked: boolean;
1369
- createdAt: number;
1370
- }
1371
- interface StreamSubscription {
1372
- unsubscribe(): void;
1373
- }
1374
- interface StreamStats {
1375
- streamName: string;
1376
- eventType: string;
1377
- total: number;
1378
- last1h: number;
1379
- last24h: number;
1380
- unacked: number;
1381
- }
1382
-
1383
- declare class WSClient {
1384
- private ws;
1385
- private url;
1386
- private sessionId;
1387
- private token;
1388
- private messageQueue;
1389
- private syncHandlers;
1390
- private rpcHandlers;
1391
- private eventHandlers;
1392
- private nextRpcId;
1393
- doc: Automerge.Doc<Record<string, unknown>>;
1394
- private syncState;
1395
- private reconnectTimer;
1396
- private tokenRefreshTimer;
1397
- private isExplicitlyDisconnected;
1398
- private options;
1399
- constructor(options: WSClientOptions);
1400
- get currentSessionId(): string;
1401
- private clearTokenRefreshTimer;
1402
- private decodeBase64Url;
1403
- private getTokenExpiryMs;
1404
- private scheduleTokenRefresh;
1405
- private refreshTokenInBackground;
1406
- private resolveTokenForConnect;
1407
- /**
1408
- * Connect to the WebSocket server
1409
- * @returns {Promise<void>} Resolves when connection is open
1410
- */
1411
- connect(): Promise<void>;
1412
- private normalizeReason;
1413
- private rejectPending;
1414
- private buildDisconnectError;
1415
- private handleDisconnect;
1416
- private handleMessage;
1417
- /**
1418
- * Make an RPC call to the server
1419
- * @param {string} method - RPC method name
1420
- * @param {unknown} params - Request parameters
1421
- * @returns {Promise<unknown>} Response result
1422
- * @throws {Error} If connection is closed or timeout occurs
1423
- */
1424
- call(method: string, params: unknown): Promise<unknown>;
1425
- private handleIncomingRpc;
1426
- /**
1427
- * Subscribe to client events
1428
- * @param {string} event - Event name
1429
- * @param {Function} handler - Event handler
1430
- */
1431
- on(event: string, handler: (params: unknown) => void): void;
1432
- /**
1433
- * Register an RPC handler for incoming server requests
1434
- * @param {string} method - RPC method name
1435
- * @param {Function} handler - Handler function
1436
- */
1437
- registerRpcHandler(method: string, handler: (params: unknown) => Promise<unknown>): void;
1438
- /**
1439
- * Unsubscribe from client events
1440
- * @param {string} event - Event name
1441
- * @param {Function} handler - Handler to remove
1442
- */
1443
- off(event: string, handler: (params: unknown) => void): void;
1444
- /**
1445
- * Emit an event locally
1446
- * @param {string} event - Event name
1447
- * @param params - Event data
1448
- */
1449
- emit(event: string, params: unknown): void;
1450
- /**
1451
- * Disconnect the WebSocket and clear state
1452
- */
1453
- disconnect(): void;
1454
- }
1455
-
1456
- declare class Session {
1457
- protected client: WSClient;
1458
- private clientId;
1459
- private jobsMap;
1460
- private pendingAgentMessagesByJobId;
1461
- private eventListeners;
1462
- private toolHandlers;
1463
- /** Tracks which tools are instance methods (className set, not static) */
1464
- private instanceTools;
1465
- private currentDomainRevision;
1466
- /** Local effect registry: name → full ToolWithHandler */
1467
- private effects;
1468
- /** Last known tools for diffing */
1469
- private lastKnownTools;
1470
- /** Last seen live prompts, keyed by prompt id, for answer normalization */
1471
- private promptCache;
1472
- constructor(client: WSClient, clientId?: string);
1473
- private extractDomainRevisionFromDoc;
1474
- private buildLegacyEffectContext;
1475
- private stringifyConversationValue;
1476
- get document(): Doc<Record<string, unknown>>;
1477
- get sessionId(): string;
1478
- get domainRevision(): string | null;
1479
- /**
1480
- * Make a raw RPC call to the session's Durable Object.
1481
- *
1482
- * Use this when you need to call an RPC method that doesn't have a
1483
- * dedicated wrapper method on the Session/Environment class.
1484
- *
1485
- * @param method - RPC method name (e.g. 'domain.fetchPackagePart')
1486
- * @param params - Request parameters
1487
- * @returns The raw RPC response
1488
- *
1489
- * @example
1490
- * ```typescript
1491
- * const result = await env.rpc('domain.fetchPackagePart', {
1492
- * moduleSpecifier: '@sandbox/domain',
1493
- * part: 'types',
1494
- * });
1495
- * ```
1496
- */
1497
- rpc<T = unknown>(method: string, params?: Record<string, unknown>): Promise<T>;
1498
- /**
1499
- * Send client hello to establish the session
1500
- */
1501
- hello(): Promise<{
1502
- ok: boolean;
1503
- environmentId?: string;
1504
- docId?: string;
1505
- graphContainerStatus?: {
1506
- lastKeepAliveAt: number;
1507
- status: "warming" | "hot" | "unknown";
1508
- };
1509
- }>;
1510
- publishTools(tools: ToolWithHandler[], revision?: string): Promise<PublishToolsResult>;
1511
- publishEffect(effect: ToolWithHandler): Promise<PublishToolsResult>;
1512
- publishEffects(effects: ToolWithHandler[]): Promise<PublishToolsResult>;
1513
- unpublishEffect(name: string): Promise<PublishToolsResult>;
1514
- unpublishAllEffects(): Promise<PublishToolsResult>;
1515
- /**
1516
- * Submit a job to execute code in the sandbox.
1517
- *
1518
- * The code can import typed classes from `./sandbox-tools`:
1519
- * ```typescript
1520
- * import { Author, Book, global_search } from './sandbox-tools';
1521
- *
1522
- * const totalAuthors = await Author.count();
1523
- * const firstAuthorsPage = await Author.page({ page: 1, perPage: 10, saveAs: 'recent_authors' });
1524
- * const authors = firstAuthorsPage.items;
1525
- * const tolkien = await Author.get({ path: 'author_tolkien' });
1526
- * const bio = await tolkien.get_bio({ detailed: true });
1527
- * const books = await tolkien.get_books();
1528
- * for await (const author of Author.iterate({ perPage: 100, maxItems: 500 })) {
1529
- * console.log(author.id);
1530
- * }
1531
- * ```
1532
- *
1533
- * Effect calls (instance methods, static methods, global functions) trigger
1534
- * `effect.invoke` RPC back to the sandbox effect host, where the registered handlers
1535
- * execute locally and return the result to the sandbox.
1536
- */
1537
- submitJob(code: string, domainRevision?: string): Promise<Job>;
1538
- /**
1539
- * Register a handler for a specific tool.
1540
- * @param isInstance - If true, handler will receive (id, params) for instance method dispatch.
1541
- */
1542
- registerToolHandler(name: string, handler: ToolHandler | InstanceToolHandler, isInstance?: boolean): void;
1543
- /**
1544
- * Respond to a prompt request from the sandbox
1545
- */
1546
- answerPrompt(promptId: string, answer: unknown): Promise<void>;
1547
- appendConversationMessage(input: ConversationMessageInput): Promise<ConversationAppendResult>;
1548
- /**
1549
- * Get the current list of available effects.
1550
- * Consolidates effect declarations and live availability for the session.
1551
- */
1552
- getEffects(): EffectInfo[];
1553
- /**
1554
- * Backwards-compatible alias for `getEffects()`.
1555
- */
1556
- getTools(): ToolInfo[];
1557
- /**
1558
- * Subscribe to effect changes (added, removed, updated).
1559
- * @param callback - Function called with change events
1560
- * @returns Unsubscribe function
1561
- */
1562
- onEffectsChanged(callback: (event: EffectsChangedEvent) => void): () => void;
1563
- /**
1564
- * Backwards-compatible alias for `onEffectsChanged()`.
1565
- */
1566
- onToolsChanged(callback: (event: ToolsChangedEvent) => void): () => void;
1567
- /**
1568
- * Get the current domain state and available tools
1569
- */
1570
- getDomain(): Promise<DomainState>;
1571
- /**
1572
- * Fetch a domain package part from the backend (no fallback).
1573
- */
1574
- private fetchDomainPart;
1575
- /**
1576
- * Get TypeScript class declarations for the current domain (for LLM/code gen).
1577
- */
1578
- getDomainTypes(): Promise<string>;
1579
- /**
1580
- * Get Markdown documentation for the current domain (human-readable).
1581
- */
1582
- getDomainDocs(): Promise<string>;
1583
- /**
1584
- * Get domain documentation for LLMs. Returns types (preferred) or fallback.
1585
- */
1586
- getDomainDocumentation(): Promise<string>;
1587
- /**
1588
- * Generate markdown documentation from the domain summary.
1589
- * Class-aware: groups tools by class with property/relationship info.
1590
- */
1591
- private generateFallbackDocs;
1592
- /**
1593
- * Close the session and disconnect from the sandbox
1594
- */
1595
- disconnect(): Promise<void>;
1596
- /**
1597
- * Subscribe to session events
1598
- */
1599
- on(event: string, handler: (data: unknown) => void): () => void;
1600
- /**
1601
- * Unsubscribe from session events
1602
- */
1603
- off(event: string, handler: (data: unknown) => void): void;
1604
- private setupToolInvokeHandler;
1605
- private setupEventHandlers;
1606
- protected emit(event: string, data: unknown): void;
1607
- /**
1608
- * Check for changes in the effect catalog and emit change events if needed.
1609
- */
1610
- private checkForToolChanges;
1611
- }
1612
-
1613
- type EnvironmentImporterHandler = (importer: EnvironmentImporter) => Promise<void> | void;
1614
- /**
1615
- * Environment is the sessionless handle for one resolved ontology environment.
1616
- *
1617
- * Use it to query or mutate environment data directly, or to open live runtime
1618
- * sessions through `environment.sessions.*` when you need jobs, prompts, or a
1619
- * synced Automerge document.
1620
- */
1621
- declare class Environment {
1622
- private granular;
1623
- private envData;
1624
- private _apiKey;
1625
- private _apiEndpoint;
1626
- constructor(granular: Granular, envData: EnvironmentData, apiKey: string, apiEndpoint: string);
1627
- /** The environment ID */
1628
- get environmentId(): string;
1629
- /** The sandbox ID */
1630
- get sandboxId(): string;
1631
- /** The ontology ID */
1632
- get ontologyId(): string;
1633
- /** The subject ID */
1634
- get subjectId(): string;
1635
- /** The named environment slot, such as dev or prod */
1636
- get envName(): string;
1637
- /** The named environment slot, such as dev or prod */
1638
- get environment(): string;
1639
- /** The resolved ontology version backing this environment */
1640
- get versionId(): string;
1641
- /** Internal Granular user identifier for this environment */
1642
- get granularId(): string;
1643
- /** The permission profile ID */
1644
- get permissionProfileId(): string;
1645
- /** The current build policy backing this environment */
1646
- get buildPolicy(): BuildPolicy;
1647
- /** The current update state relative to the followed tag */
1648
- get updateState(): EnvironmentData["updateState"];
1649
- /** The latest setup/import run summary for this environment, when available. */
1650
- get setup(): EnvironmentSetupSummary | null;
1651
- /** Convenience flag for whether this environment trails the current tag target */
1652
- get isOutdated(): boolean;
1653
- /** The followed tag name when this environment is tag-tracked */
1654
- get tag(): string | null;
1655
- /** The GraphQL API endpoint URL */
1656
- get apiEndpoint(): string;
1657
- /** Internal auth token used for control-plane and runtime fallback requests */
1658
- get authToken(): string;
1659
- /** Base runtime URL derived from the GraphQL endpoint */
1660
- get runtimeBaseUrl(): string;
1661
- syncEnvironmentData(envData: EnvironmentData): void;
1662
- get sessions(): {
1663
- list: (options?: {
1664
- status?: "active" | "closed" | "all";
1665
- }) => Promise<ConversationSessionInfo[]>;
1666
- create: (options?: CreateSessionOptions) => Promise<EnvironmentSession>;
1667
- connect: (sessionId: string, options?: {
1668
- clientId?: string;
1669
- }) => Promise<EnvironmentSession>;
1670
- reopen: (sessionId: string, options?: {
1671
- clientId?: string;
1672
- }) => Promise<EnvironmentSession>;
1673
- close: (sessionId: string, session?: EnvironmentSession | null) => Promise<void>;
1674
- };
1675
- get data(): {
1676
- record: (record: RecordObjectOptions) => Promise<RecordObjectResult>;
1677
- recordMany: (records: RecordObjectOptions[], options?: RecordObjectsOptions) => Promise<RecordObjectResult[]>;
1678
- import: (records: RecordObjectOptions[], options?: {
1679
- batchSize?: number;
1680
- }) => Promise<RecordImport>;
1681
- listImports: (status?: RecordImportStatus) => Promise<RecordImport[]>;
1682
- getImport: (importId: string) => Promise<RecordImport>;
1683
- getImportSummary: () => Promise<EnvironmentRecordImportSummary>;
1684
- cancelImport: (importId: string) => Promise<RecordImport>;
1685
- getAwaitingCount: () => Promise<number>;
1686
- };
1687
- get feedback(): {
1688
- list: () => Promise<EnvironmentFeedbackRecord[]>;
1689
- };
1690
- /**
1691
- * Sessionless environments do not own a live transport, so disconnecting the
1692
- * environment handle itself is a no-op. This keeps the public surface
1693
- * symmetric with `EnvironmentSession.disconnect()` and lets callers always
1694
- * clean up safely without tracking whether they currently hold an environment
1695
- * or a session.
1696
- */
1697
- disconnect(): Promise<void>;
1698
- listSessions(status?: "active" | "closed" | "all"): Promise<ConversationSessionInfo[]>;
1699
- createSession(options?: CreateSessionOptions): Promise<EnvironmentSession>;
1700
- connectSession(sessionId: string, options?: {
1701
- clientId?: string;
1702
- }): Promise<EnvironmentSession>;
1703
- reopenSession(sessionId: string, options?: {
1704
- clientId?: string;
1705
- }): Promise<EnvironmentSession>;
1706
- closeSession(sessionId: string, session?: EnvironmentSession | null): Promise<void>;
1707
- listFeedback(): Promise<EnvironmentFeedbackRecord[]>;
1708
- private getRuntimeBaseUrl;
1709
- private controlPlaneRequest;
1710
- /**
1711
- * Convert a class name + real-world ID into a unique graph path.
1712
- *
1713
- * Two objects of *different* classes may share the same real-world ID,
1714
- * so the graph path must incorporate the class to guarantee uniqueness.
1715
- *
1716
- * Format: `{className}_{id}` — deterministic, human-readable.
1717
- *
1718
- * **Convention**: class names should be simple identifiers without
1719
- * underscores (e.g. `author`, `book`). This ensures the prefix is
1720
- * unambiguously parseable by `extractIdFromGraphPath`.
1721
- */
1722
- static toGraphPath(className: string, id: string): string;
1723
- /**
1724
- * Extract the real-world ID from a graph path, given the class name.
1725
- *
1726
- * Strips the `{className}_` prefix. Returns the raw path if the
1727
- * expected prefix is not found.
1728
- */
1729
- static extractIdFromGraphPath(graphPath: string, className: string): string;
1730
- /**
1731
- * Execute a GraphQL query against the environment's graph.
1732
- *
1733
- * The query uses the Granular graph query language (based on Cypher/GraphQL).
1734
- * Authentication is handled automatically using the SDK's API key.
1735
- *
1736
- * @param query - The GraphQL query string
1737
- * @param variables - Optional variables for the query
1738
- * @returns The query result data
1739
- *
1740
- * @example
1741
- * ```typescript
1742
- * // Read the workspace
1743
- * const result = await env.graphql(
1744
- * `query { model(path: "workspace") { path label submodels { path label } } }`
1745
- * );
1746
- * console.log(result.data);
1747
- *
1748
- * // Create a model
1749
- * const created = await env.graphql(
1750
- * `mutation { at(path: "workspace") { create_submodel(subpath: "my_node", label: "My Node", prototype: "Model") { model { path label } } } }`
1751
- * );
1752
- * ```
1753
- */
1754
- graphql<T = any>(query: string, variables?: Record<string, any>): Promise<GraphQLResult<T>>;
1755
- /**
1756
- * Define a relationship between two model types.
1757
- *
1758
- * Creates both submodels (if they don't exist) and links them with
1759
- * a RelationshipDef node that encodes cardinality.
1760
- *
1761
- * @example
1762
- * ```typescript
1763
- * // Author has many Books, Book has one Author
1764
- * const rel = await env.defineRelationship({
1765
- * model: 'author',
1766
- * localSubmodel: 'books',
1767
- * localIsMany: true,
1768
- * foreignModel: 'book',
1769
- * foreignSubmodel: 'author',
1770
- * foreignIsMany: false,
1771
- * });
1772
- * console.log(rel.relationship_kind); // "one_to_many"
1773
- * ```
1774
- */
1775
- defineRelationship(options: DefineRelationshipOptions): Promise<RelationshipInfo>;
1776
- /**
1777
- * Get all relationships for a model type.
1778
- *
1779
- * @param modelPath - The model type path (e.g., "author")
1780
- * @returns Array of relationships from this model's perspective
1781
- *
1782
- * @example
1783
- * ```typescript
1784
- * const rels = await env.getRelationships('author');
1785
- * for (const rel of rels) {
1786
- * console.log(`${rel.local_submodel.path} -> ${rel.foreign_model.path} (${rel.relationship_kind})`);
1787
- * }
1788
- * ```
1789
- */
1790
- getRelationships(modelPath: string): Promise<RelationshipInfo[]>;
1791
- /**
1792
- * Attach a target model to a relationship submodel.
1793
- *
1794
- * Handles cardinality automatically:
1795
- * - "One" side: sets/replaces the reference
1796
- * - "Many" side: adds the target to the collection
1797
- *
1798
- * If the target model doesn't exist, it's created as an instance of the foreign type.
1799
- * Bidirectional sync is automatic.
1800
- *
1801
- * @param modelPath - The model instance path (e.g., "tolkien")
1802
- * @param submodelPath - The relationship submodel (e.g., "books")
1803
- * @param targetPath - The target model to attach (e.g., "lord_of_the_rings")
1804
- *
1805
- * @example
1806
- * ```typescript
1807
- * // Attach a book to an author (many side)
1808
- * await env.attach('tolkien', 'books', 'lord_of_the_rings');
1809
- * // This also automatically sets lord_of_the_rings:author -> tolkien
1810
- * ```
1811
- */
1812
- attach(modelPath: string, submodelPath: string, targetPath: string): Promise<void>;
1813
- /**
1814
- * Detach a target model from a relationship submodel.
1815
- *
1816
- * Handles bidirectional cleanup automatically.
1817
- *
1818
- * @param modelPath - The model instance path
1819
- * @param submodelPath - The relationship submodel
1820
- * @param targetPath - The target to detach (optional for "one" side; omit on "many" side to detach all)
1821
- *
1822
- * @example
1823
- * ```typescript
1824
- * // Detach a specific book
1825
- * await env.detach('tolkien', 'books', 'lord_of_the_rings');
1826
- *
1827
- * // Detach all books
1828
- * await env.detach('tolkien', 'books');
1829
- * ```
1830
- */
1831
- detach(modelPath: string, submodelPath: string, targetPath?: string): Promise<void>;
1832
- /**
1833
- * List all related models through a relationship submodel.
1834
- *
1835
- * @param modelPath - The model instance path
1836
- * @param submodelPath - The relationship submodel
1837
- * @returns Array of related model references
1838
- *
1839
- * @example
1840
- * ```typescript
1841
- * const books = await env.listRelated('tolkien', 'books');
1842
- * console.log(books); // [{ path: "lord_of_the_rings", label: "Lord of the Rings" }, ...]
1843
- * ```
1844
- */
1845
- listRelated(modelPath: string, submodelPath: string): Promise<ModelRef[]>;
1846
- /**
1847
- * Apply a manifest to the current environment's graph.
1848
- *
1849
- * Translates each manifest operation into GraphQL mutations and executes them
1850
- * in order. This is the core mechanism for creating classes, fields, and
1851
- * relationships from a declarative manifest.
1852
- *
1853
- * @param manifest - The manifest content to apply
1854
- * @returns Summary of applied operations
1855
- *
1856
- * @example
1857
- * ```typescript
1858
- * await environment.applyManifest({
1859
- * schemaVersion: 2,
1860
- * name: 'my-app',
1861
- * volumes: [{
1862
- * name: 'schema',
1863
- * scope: 'sandbox',
1864
- * operations: [
1865
- * { create: 'author', extends: 'class', has: { name: { type: 'string' } } },
1866
- * { create: 'book', extends: 'class', has: { title: { type: 'string' } } },
1867
- * { defineRelationship: {
1868
- * left: 'author', right: 'book',
1869
- * leftSubmodel: 'books', rightSubmodel: 'author',
1870
- * leftIsMany: true, rightIsMany: false,
1871
- * }},
1872
- * ],
1873
- * }],
1874
- * });
1875
- * ```
1876
- */
1877
- applyManifest(manifest: ManifestContent): Promise<{
1878
- applied: number;
1879
- errors: string[];
1880
- }>;
1881
- /**
1882
- * Resolve an alias reference like "@std/class" → "class"
1883
- * Strips the alias prefix, returning the bare model path.
1884
- */
1885
- private _resolveAlias;
1886
- private _runGraphql;
1887
- private _applyFieldMetamodels;
1888
- private _applyModelMetamodels;
1889
- private _ensureWorkspaceToolsRoot;
1890
- private _storeEffectSchemas;
1891
- private _applyEffectMetamodels;
1892
- private _ensureWorkspaceStreamsRoot;
1893
- private _applyEventStreamDeclaration;
1894
- private _applyEffectDeclaration;
1895
- /**
1896
- * Apply a single manifest operation via GraphQL
1897
- */
1898
- private _applyOperation;
1899
- /**
1900
- * Apply field definitions (has) to a model via GraphQL
1901
- */
1902
- private _applyFields;
1903
- /**
1904
- * Create or update an instance of a class in the graph.
1905
- *
1906
- * Uses `instantiate` under the hood, which has find-or-create semantics:
1907
- * if an instance with the given `id` already exists for the class it is
1908
- * returned; otherwise a new instance is created. Fields are then set
1909
- * (overwriting previous values) and relationships are attached.
1910
- *
1911
- * The graph path is derived as `{className}_{id}` to ensure uniqueness
1912
- * across classes (two objects of different classes may share the same
1913
- * real-world ID). Relationship targets are also resolved automatically
1914
- * using the foreign class from the relationship definition.
1915
- *
1916
- * @param options - The object specification
1917
- * @returns The graph path, real-world ID, and creation status
1918
- *
1919
- * @example
1920
- * ```typescript
1921
- * // Create an author with fields
1922
- * const result = await env.recordObject({
1923
- * className: 'author',
1924
- * id: 'tolkien',
1925
- * label: 'J.R.R. Tolkien',
1926
- * fields: { name: 'J.R.R. Tolkien', birth_year: 1892 },
1927
- * relationships: { books: ['lotr', 'silmarillion'] },
1928
- * });
1929
- * // result.path → 'author_tolkien' (internal graph path)
1930
- * // result.id → 'tolkien' (real-world ID)
1931
- * // result.created → true
1932
- * ```
1933
- */
1934
- recordObject(options: RecordObjectOptions): Promise<RecordObjectResult>;
1935
- /**
1936
- * Batch version of `recordObject()`.
1937
- *
1938
- * Sends rows through the control-plane **`/records/batch`** endpoint in **chunks** (default
1939
- * **100** records per HTTP request) so individual requests stay bounded and gateway timeouts are
1940
- * unlikely. Each chunk is retried on transient network / worker errors.
1941
- *
1942
- * Use the optional second argument to:
1943
- * - **`batchSize`** — rows per POST (smaller = more progress events; larger = fewer round trips).
1944
- * - **`concurrency`** — run up to N chunk POSTs in parallel (capped at 16) when you want lower wall time.
1945
- * - **`onChunkComplete`** — hook for UIs after each chunk succeeds (row order in the returned array
1946
- * always matches `records`; chunk **completion** order may differ when `concurrency > 1`).
1947
- *
1948
- * For **asynchronous** ingestion with worker-side batching and aggregate counters (`queued`,
1949
- * `completed`, …), use **`enqueueRecordImport`** and poll **`getRecordImport`** /
1950
- * **`getRecordImportSummary`** — best for very large fire-and-forget loads when immediate
1951
- * synchronous commit of every row is not required.
1952
- */
1953
- recordObjects(records: RecordObjectOptions[], options?: RecordObjectsOptions): Promise<RecordObjectResult[]>;
1954
- private executeRecordObjectsChunk;
1955
- /**
1956
- * Queue a background record import for this environment (async worker pipeline).
1957
- *
1958
- * **vs `recordObjects`:** this path accepts the full payload in one request, returns an
1959
- * **`importId`**, and processes rows in the background — use **`getRecordImport`** /
1960
- * **`getRecordImportSummary`** for progress. Choose it for large bulk loads where you do not
1961
- * need every row committed before the HTTP call returns. Use **`recordObjects`** when you need
1962
- * synchronous upserts and fine-grained chunk progress via **`onChunkComplete`**.
1963
- */
1964
- enqueueRecordImport(records: RecordObjectOptions[], options?: {
1965
- batchSize?: number;
1966
- setupRunId?: string;
1967
- }): Promise<RecordImport>;
1968
- /**
1969
- * List queued or completed record imports for this environment.
1970
- */
1971
- listRecordImports(status?: RecordImportStatus): Promise<RecordImport[]>;
1972
- /**
1973
- * Fetch the latest aggregate import counters for this environment.
1974
- */
1975
- getRecordImportSummary(): Promise<EnvironmentRecordImportSummary>;
1976
- /**
1977
- * Convenience helper returning queued + processing records for this environment.
1978
- */
1979
- getAwaitingRecordCount(): Promise<number>;
1980
- /**
1981
- * Fetch a single record import by id.
1982
- */
1983
- getRecordImport(importId: string): Promise<RecordImport>;
1984
- /**
1985
- * Cancel a queued/background record import.
1986
- */
1987
- cancelRecordImport(importId: string): Promise<RecordImport>;
1988
- }
1989
- /**
1990
- * Live runtime session attached to one opened environment.
1991
- *
1992
- * This is the object returned by `environment.sessions.create()` and friends.
1993
- * It owns websocket state, prompts, job execution, and the synced Automerge
1994
- * document while delegating environment-level data APIs back to
1995
- * `session.environment`.
1996
- */
1997
- declare class EnvironmentSession extends Session {
1998
- readonly environment: Environment;
1999
- /** The last known graph container status, updated by checkReadiness() or on heartbeat */
2000
- graphContainerStatus: {
2001
- lastKeepAliveAt: number;
2002
- status: "warming" | "hot" | "unknown";
2003
- } | null;
2004
- constructor(client: WSClient, environment: Environment, clientId: string);
2005
- get environmentId(): string;
2006
- get sandboxId(): string;
2007
- get ontologyId(): string;
2008
- get subjectId(): string;
2009
- get envName(): string;
2010
- get tag(): string | null;
2011
- get versionId(): string;
2012
- get granularId(): string;
2013
- get permissionProfileId(): string;
2014
- get apiEndpoint(): string;
2015
- get data(): {
2016
- record: (record: RecordObjectOptions) => Promise<RecordObjectResult>;
2017
- recordMany: (records: RecordObjectOptions[], options?: RecordObjectsOptions) => Promise<RecordObjectResult[]>;
2018
- import: (records: RecordObjectOptions[], options?: {
2019
- batchSize?: number;
2020
- } | undefined) => Promise<RecordImport>;
2021
- listImports: (status?: RecordImportStatus) => Promise<RecordImport[]>;
2022
- getImport: (importId: string) => Promise<RecordImport>;
2023
- getImportSummary: () => Promise<EnvironmentRecordImportSummary>;
2024
- cancelImport: (importId: string) => Promise<RecordImport>;
2025
- getAwaitingCount: () => Promise<number>;
2026
- };
2027
- get feedback(): {
2028
- list: () => Promise<EnvironmentFeedbackRecord[]>;
2029
- };
2030
- /**
2031
- * Return a plain JS copy of the synced session heap.
2032
- */
2033
- getHeap(): SessionHeapSnapshot;
2034
- private sessionDataRequest;
2035
- private collectAllSessionItems;
2036
- /**
2037
- * Fetch the live session document from the runtime DO.
2038
- *
2039
- * For history and saved artifacts, prefer the collection APIs on
2040
- * `messages`, `timeline`, `jobs`, and `heap`.
2041
- */
2042
- getDocument(): Promise<SessionDocumentResult>;
2043
- get messages(): {
2044
- list: (options?: SessionCollectionListOptions) => Promise<SessionCollectionListResult<SessionConversationMessage>>;
2045
- };
2046
- get timeline(): {
2047
- list: (options?: SessionCollectionListOptions) => Promise<SessionCollectionListResult<SessionTimelineEvent>>;
2048
- };
2049
- get jobs(): {
2050
- list: (options?: SessionJobListOptions) => Promise<SessionCollectionListResult<SessionJobRecord>>;
2051
- get: (jobId: string) => Promise<SessionJobRecord>;
2052
- };
2053
- get heap(): {
2054
- entries: {
2055
- list: (options?: SessionCollectionListOptions) => Promise<SessionCollectionListResult<SessionHeapEntry>>;
2056
- get: (path: string) => Promise<SessionHeapEntry>;
2057
- };
2058
- lists: {
2059
- list: (options?: SessionCollectionListOptions) => Promise<SessionCollectionListResult<SessionHeapList>>;
2060
- get: (name: string) => Promise<SessionHeapList>;
2061
- };
2062
- };
2063
- get transcript(): {
2064
- list: (options?: SessionCollectionListOptions) => Promise<SessionCollectionListResult<SessionTranscriptEntry>>;
2065
- };
2066
- graphql<T = any>(query: string, variables?: Record<string, any>): Promise<GraphQLResult<T>>;
2067
- defineRelationship(options: DefineRelationshipOptions): Promise<RelationshipInfo>;
2068
- getRelationships(modelPath: string): Promise<RelationshipInfo[]>;
2069
- attach(modelPath: string, submodelPath: string, targetPath: string): Promise<void>;
2070
- detach(modelPath: string, submodelPath: string, targetPath?: string): Promise<void>;
2071
- listRelated(modelPath: string, submodelPath: string): Promise<ModelRef[]>;
2072
- applyManifest(manifest: ManifestContent): Promise<{
2073
- applied: number;
2074
- errors: string[];
2075
- }>;
2076
- recordObject(options: RecordObjectOptions): Promise<RecordObjectResult>;
2077
- recordObjects(records: RecordObjectOptions[], options?: RecordObjectsOptions): Promise<RecordObjectResult[]>;
2078
- enqueueRecordImport(records: RecordObjectOptions[], options?: {
2079
- batchSize?: number;
2080
- }): Promise<RecordImport>;
2081
- listRecordImports(status?: RecordImportStatus): Promise<RecordImport[]>;
2082
- getRecordImportSummary(): Promise<EnvironmentRecordImportSummary>;
2083
- getAwaitingRecordCount(): Promise<number>;
2084
- getRecordImport(importId: string): Promise<RecordImport>;
2085
- cancelRecordImport(importId: string): Promise<RecordImport>;
2086
- listFeedback(): Promise<EnvironmentFeedbackRecord[]>;
2087
- /**
2088
- * Close the session and disconnect from the sandbox.
2089
- *
2090
- * Sends `client.goodbye` over WebSocket first, then issues an HTTP fallback
2091
- * to the runtime goodbye endpoint if no definitive WS-side runtime notify
2092
- * acknowledgement was observed.
2093
- */
2094
- disconnect(): Promise<void>;
2095
- /**
2096
- * Close only the socket transport without sending `client.goodbye`.
2097
- */
2098
- disconnectTransport(): void;
2099
- /**
2100
- * Backwards-compatible alias for `disconnect()`.
2101
- */
2102
- close(): Promise<void>;
2103
- /**
2104
- * Check if the graph container is ready and warm.
2105
- */
2106
- checkReadiness(): Promise<{
2107
- lastKeepAliveAt: number;
2108
- status: "warming" | "hot" | "unknown";
2109
- }>;
2110
- }
2111
- declare class OntologyHandle {
2112
- private granular;
2113
- private ontologyNameOrId;
2114
- constructor(granular: Granular, ontologyNameOrId: string);
2115
- get effects(): {
2116
- register: (effect: ToolWithHandler) => Promise<void>;
2117
- registerMany: (effects: ToolWithHandler[]) => Promise<void>;
2118
- unregister: (name: string) => Promise<void>;
2119
- clear: () => Promise<void>;
2120
- disconnect: () => Promise<void>;
2121
- };
2122
- get importer(): {
2123
- onEnvironmentCreate: (handler: EnvironmentImporterHandler) => void;
2124
- clear: () => void;
2125
- };
2126
- }
2127
- declare class Granular {
2128
- private apiKey;
2129
- private apiUrl;
2130
- private httpUrl;
2131
- private tokenProvider?;
2132
- private WebSocketCtor?;
2133
- private onUnexpectedClose?;
2134
- private onReconnectError?;
2135
- private debugHttp;
2136
- /** Sandbox-level effect registry: sandboxId → (effectKey@selector → ToolWithHandler) */
2137
- private sandboxEffects;
2138
- /** Live sandbox-scoped effect hosts keyed by sandboxId */
2139
- private sandboxEffectHosts;
2140
- /** In-flight host connection promises to avoid duplicate concurrent connects */
2141
- private sandboxEffectHostPromises;
2142
- /** Ontology-bound environment importer hooks keyed by the caller's ontology identifier. */
2143
- private ontologyImporters;
2144
- /** Resolved importer hooks keyed by sandboxId for fast lookups during openEnvironment(). */
2145
- private sandboxImporters;
2146
- /**
2147
- * Create a new Granular client
2148
- * @param options - Client configuration
2149
- */
2150
- constructor(options: GranularOptions);
2151
- /**
2152
- * Return an ontology-scoped handle for effects and other ontology-level APIs.
2153
- */
2154
- ontology(ontologyNameOrId: string): OntologyHandle;
2155
- registerEnvironmentImporter(ontologyNameOrId: string, handler: EnvironmentImporterHandler): void;
2156
- clearEnvironmentImporter(ontologyNameOrId: string): void;
2157
- /**
2158
- * Records/upserts a user and prepares them for sandbox connections
2159
- *
2160
- * @param options - User options
2161
- * @returns The recorded user with both `userId` and `granularId`
2162
- *
2163
- * @example
2164
- * ```typescript
2165
- * const user = await granular.recordUser({
2166
- * userId: 'user_123',
2167
- * name: 'John Doe',
2168
- * permissions: ['agent'],
2169
- * });
2170
- * ```
2171
- */
2172
- recordUser(options: RecordUserOptions): Promise<User>;
2173
- /**
2174
- * Alias for `recordUser()` with user-facing naming that matches upsert semantics.
2175
- */
2176
- upsertUser(options: RecordUserOptions): Promise<User>;
2177
- private resolveConnectUser;
2178
- /**
2179
- * Open or resolve an ontology environment for one user without opening a session.
2180
- *
2181
- * @example
2182
- * ```typescript
2183
- * const environment = await granular.openEnvironment({
2184
- * ontology: 'my-ontology',
2185
- * tag: 'dev',
2186
- * userId: 'user_123',
2187
- * permissions: ['agent'],
2188
- * });
2189
- *
2190
- * await environment.data.record({
2191
- * className: 'customer',
2192
- * id: 'acme',
2193
- * fields: { name: 'Acme' },
2194
- * });
2195
- *
2196
- * const session = await environment.sessions.create();
2197
- * const job = await session.submitJob(`return "hello";`);
2198
- * console.log(await job.result);
2199
- * ```
2200
- */
2201
- openEnvironment(options: OpenEnvironmentOptions): Promise<Environment>;
2202
- /**
2203
- * Deprecated compatibility alias for `openEnvironment()`.
2204
- *
2205
- * `connect()` no longer opens a runtime session automatically.
2206
- */
2207
- connect(options: ConnectOptions): Promise<Environment>;
2208
- private resolveRequestedTag;
2209
- private buildManagedEnvironmentName;
2210
- private matchesTagTrackedEnvironment;
2211
- private sortEnvironmentsByRecency;
2212
- private resolveOpenEnvironmentData;
2213
- /**
2214
- * List active (open) sessions for an environment — each session is one agent conversation thread.
2215
- */
2216
- listOpenSessions(filters: {
2217
- environmentId: string;
2218
- }): Promise<ConversationSessionInfo[]>;
2219
- /**
2220
- * List closed sessions for an environment (conversations that have disconnected).
2221
- */
2222
- listClosedSessions(filters: {
2223
- environmentId: string;
2224
- }): Promise<ConversationSessionInfo[]>;
2225
- private listSessionsForEnvironment;
2226
- private normalizeConversationSession;
2227
- private static coerceIsoDate;
2228
- /**
2229
- * Create a new session (conversation) for an existing environment and connect to it.
2230
- * The runtime graph is shared across all sessions for the same environment.
2231
- */
2232
- createSession(options: {
2233
- environmentId: string;
2234
- clientId?: string;
2235
- initialHeap?: CreateSessionOptions["initialHeap"];
2236
- }): Promise<EnvironmentSession>;
2237
- /**
2238
- * Connect to an existing open session (same conversation thread) using a freshly minted WebSocket token.
2239
- */
2240
- connectSession(options: {
2241
- sessionId: string;
2242
- clientId?: string;
2243
- }): Promise<EnvironmentSession>;
2244
- /**
2245
- * Mark a session closed in the control plane. If `environment` is the connected handle for that
2246
- * `sessionId`, disconnects the WebSocket so the runtime tears down cleanly.
2247
- */
2248
- closeSession(sessionId: string, environment?: EnvironmentSession | null): Promise<void>;
2249
- /**
2250
- * Re-open a closed session in the index and connect to its existing runtime document.
2251
- */
2252
- reopenSession(sessionId: string, options?: {
2253
- clientId?: string;
2254
- }): Promise<EnvironmentSession>;
2255
- private resolveEnvironmentImporter;
2256
- private maybeRunEnvironmentImporter;
2257
- private bindEnvironmentHandle;
2258
- private bindWebSocketEnvironmentSession;
2259
- private activateEnvironment;
2260
- private getSandboxEffectMap;
2261
- private serializeEffect;
2262
- private publishSandboxEffectCatalog;
2263
- private syncSandboxEffectCatalog;
2264
- private recoverEffectHost;
2265
- private startEffectHostHeartbeat;
2266
- private stopEffectHostHeartbeat;
2267
- private synchronizeEffectHost;
2268
- private ensureSandboxEffectHost;
2269
- private disconnectSandboxEffectHost;
2270
- /**
2271
- * Register an effect (tool) for a specific sandbox.
2272
- *
2273
- * @param sandboxNameOrId - The name or ID of the sandbox
2274
- * @param effect - The tool definition and handler
2275
- */
2276
- registerEffect(sandboxNameOrId: string, effect: ToolWithHandler): Promise<void>;
2277
- /**
2278
- * Register multiple effects (tools) for a specific sandbox.
2279
- *
2280
- * batch version of `registerEffect`.
2281
- */
2282
- registerEffects(sandboxNameOrId: string, effects: ToolWithHandler[]): Promise<void>;
2283
- /**
2284
- * Unregister an effect from a sandbox.
2285
- *
2286
- * Removes it from the local sandbox registry and updates the
2287
- * sandbox-scoped live catalog.
2288
- */
2289
- unregisterEffect(sandboxNameOrId: string, name: string): Promise<void>;
2290
- /**
2291
- * Disconnect one sandbox-scoped effect host, or all of them when no sandbox is provided.
2292
- *
2293
- * This is primarily useful for long-lived helper processes such as generated
2294
- * `granular-effects.ts` scripts that need to shut down cleanly on SIGINT/SIGTERM.
2295
- */
2296
- disconnectEffects(sandboxNameOrId?: string): Promise<void>;
2297
- /**
2298
- * Unregister all effects for a sandbox.
2299
- */
2300
- unregisterAllEffects(sandboxNameOrId: string): Promise<void>;
2301
- /**
2302
- * Find a sandbox by name or create it if it doesn't exist
2303
- */
2304
- private findOrCreateSandbox;
2305
- /**
2306
- * Ensure a permission profile exists for a sandbox, creating it if needed.
2307
- * If profileName matches an existing profile name, returns its ID.
2308
- * Otherwise, creates a new profile with default allow-all rules.
2309
- */
2310
- private ensurePermissionProfile;
2311
- /**
2312
- * Ensure an assignment exists for a subject in a sandbox with a permission profile
2313
- */
2314
- private ensureAssignment;
2315
- /**
2316
- * Sandbox management API
2317
- */
2318
- get sandboxes(): {
2319
- list: () => Promise<SandboxListResponse>;
2320
- get: (id: string) => Promise<Sandbox>;
2321
- create: (data: CreateSandboxData) => Promise<Sandbox>;
2322
- update: (id: string, data: Partial<CreateSandboxData>) => Promise<Sandbox>;
2323
- delete: (id: string) => Promise<DeleteResponse>;
2324
- };
2325
- /**
2326
- * Permission Profile management for sandboxes
2327
- */
2328
- get permissionProfiles(): {
2329
- list: (sandboxId: string) => Promise<PermissionProfile[]>;
2330
- get: (sandboxId: string, profileId: string) => Promise<PermissionProfile>;
2331
- create: (sandboxId: string, data: CreatePermissionProfileData) => Promise<PermissionProfile>;
2332
- delete: (sandboxId: string, profileId: string) => Promise<DeleteResponse>;
2333
- };
2334
- /**
2335
- * Environment management
2336
- */
2337
- get environments(): {
2338
- list: (sandboxId: string) => Promise<EnvironmentData[]>;
2339
- get: (environmentId: string) => Promise<EnvironmentData>;
2340
- create: (sandboxId: string, data: CreateEnvironmentData) => Promise<EnvironmentData>;
2341
- delete: (environmentId: string) => Promise<DeleteResponse>;
2342
- };
2343
- /**
2344
- * Event stream operations: query, subscribe, and acknowledge stream events
2345
- */
2346
- get streams(): {
2347
- getEvents: (params: {
2348
- ontology: string;
2349
- stream: string;
2350
- environment?: string;
2351
- session?: string;
2352
- eventTypes?: string[];
2353
- since?: Date;
2354
- until?: Date;
2355
- isAcked?: boolean;
2356
- limit?: number;
2357
- offset?: number;
2358
- }) => Promise<StreamEvent[]>;
2359
- subscribe: (params: {
2360
- ontology: string;
2361
- stream: string;
2362
- environment?: string;
2363
- session?: string;
2364
- eventTypes?: string[];
2365
- since?: Date;
2366
- onEvent: (event: StreamEvent) => void;
2367
- onError?: (err: Error) => void;
2368
- pollIntervalMs?: number;
2369
- }) => StreamSubscription;
2370
- ack: (eventId: string) => Promise<void>;
2371
- ackBatch: (eventIds: string[]) => Promise<void>;
2372
- getStats: (params: {
2373
- ontology: string;
2374
- environment?: string;
2375
- }) => Promise<StreamStats[]>;
2376
- };
2377
- /**
2378
- * Subject management
2379
- */
2380
- get subjects(): {
2381
- get: (subjectId: string) => Promise<Subject>;
2382
- listAssignments: (subjectId: string) => Promise<AssignmentListResponse>;
2383
- };
2384
- /**
2385
- * @deprecated Use recordUser() instead
2386
- */
2387
- get users(): {
2388
- create: (data: {
2389
- id: string;
2390
- name?: string;
2391
- email?: string;
2392
- }) => Promise<Subject>;
2393
- get: (id: string) => Promise<Subject>;
2394
- };
2395
- private _resolveSandboxId;
2396
- /**
2397
- * Make an authenticated API request
2398
- */
2399
- private request;
2400
- }
2401
-
2402
- export { type SemanticVersionDiff as $, type AccessTokenProvider as A, type BuildPolicy as B, type ConnectOptions as C, type DomainState as D, type EndpointMode as E, type VersionTag as F, Granular as G, type EnvironmentData as H, type InstanceToolHandler as I, type CreateEnvironmentData as J, type EnvironmentListResponse as K, type Manifest as L, type ManifestEffectMetamodelSpec as M, type ManifestListResponse as N, OntologyHandle as O, type Prompt as P, type BuildStatus 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 Build as X, type Version as Y, type BuildListResponse as Z, type SemanticVersionDiffEntry as _, type EffectHandlerContext as a, type EnvironmentImporterImportOptions as a$, type ResolvedEffectPostCondition as a0, type ResolvedEffectDryRun as a1, type ResolvedEffectReverse as a2, type ResolvedEffectApprovalRequired as a3, type EffectInvocationMode as a4, type EffectInvocationMetadata as a5, type EffectSchema as a6, type EffectWithHandler as a7, type PublishEffectsResult as a8, type EffectVersionSelector as a9, type SessionJobListOptions as aA, type SessionCollectionListResult as aB, type WSDisconnectInfo as aC, type WSReconnectErrorInfo as aD, type WSClientOptions as aE, type RPCRequest as aF, type RPCResponse as aG, type SyncMessage as aH, type RPCRequestFromServer as aI, type ToolInvokeParams as aJ, type ToolResultParams as aK, type ModelRef as aL, type RelationshipInfo as aM, type DefineRelationshipOptions as aN, type RecordObjectOptions as aO, type RecordObjectResult as aP, type RecordObjectsChunkInfo as aQ, type RecordObjectsOptions as aR, type RecordImportStatus as aS, type RecordImportItemStatus as aT, type RecordImportStats as aU, type RecordImportItem as aV, type RecordImport as aW, type EnvironmentRecordImportSummary as aX, type EnvironmentSetupTriggerReason as aY, type EnvironmentSetupLifecycleStatus as aZ, type EnvironmentSetupSummary as a_, type ToolInfo as aa, type EffectInfo as ab, type ToolsChangedEvent as ac, type EffectsChangedEvent as ad, type EffectHandler as ae, type InstanceEffectHandler as af, type JobStatus as ag, type JobFeedbackSentiment as ah, type JobFeedbackToolCall as ai, type JobFeedbackMetadata as aj, type JobFeedbackInput as ak, type JobFeedbackRecord as al, type EnvironmentFeedbackRecord as am, type JobSubmitResult as an, type Job as ao, type ConversationMessageShowRefs as ap, type ConversationMessageInput as aq, type ConversationAppendResult as ar, type SessionConversationMessage as as, type SessionTimelineEvent as at, type SessionJobRecord as au, type SessionHeapFieldType as av, type SessionHeapFieldValue as aw, type SessionHeapVariable as ax, type SessionDocumentResult as ay, type SessionCollectionListOptions as az, type SessionHeapList as b, type EnvironmentImporter as b0, type ManifestPropertySpec as b1, type ManifestValidationOperator as b2, type ManifestEnumRuleSpec as b3, type ManifestFilterBySpec as b4, type ManifestValidationRuleSpec as b5, type ManifestStateMachineStateSpec as b6, type ManifestStateMachineTransitionSpec as b7, type ManifestStateMachineSpec as b8, type ManifestPostConditionSpec as b9, type ManifestDryRunSpec as ba, type ManifestReverseSpec as bb, type ManifestApprovalRequiredSpec as bc, type ManifestRelationshipDef as bd, type ManifestEffectSchema as be, type ManifestEffectDeclaration as bf, type ManifestEventTypeDef as bg, type ManifestEventStreamDef as bh, type ManifestOperation as bi, type ManifestImport as bj, type ManifestVolume as bk, type ManifestContent as bl, type GraphQLResult as bm, type APIError as bn, type DeleteResponse as bo, type StreamEvent as bp, type StreamSubscription as bq, type StreamStats as br, type SessionHeapSnapshot as c, type SessionTranscriptEntry as d, Environment as e, EnvironmentSession as f, Session as g, type ToolSchema as h, type PublishToolsResult as i, type ToolHandler as j, type GranularOptions as k, type GranularAuth as l, type RecordUserOptions as m, type Subject as n, type OpenEnvironmentOptions as o, type CreateSessionOptions as p, type ConversationSessionInfo as q, type Sandbox as r, type CreateSandboxData as s, type SandboxListResponse as t, type PermissionRules as u, type PermissionProfile as v, type CreatePermissionProfileData as w, type PermissionProfileListResponse as x, type Assignment as y, type AssignmentListResponse as z };