@granular-software/sdk 0.4.18 → 0.4.19

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