@granular-software/sdk 0.1.0

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.mjs ADDED
@@ -0,0 +1,1773 @@
1
+ import WebSocket from 'ws';
2
+ import * as Automerge from '@automerge/automerge';
3
+
4
+ // src/ws-client.ts
5
+ var WSClient = class {
6
+ ws = null;
7
+ url;
8
+ sessionId;
9
+ token;
10
+ messageQueue = [];
11
+ syncHandlers = [];
12
+ rpcHandlers = /* @__PURE__ */ new Map();
13
+ eventHandlers = /* @__PURE__ */ new Map();
14
+ nextRpcId = 1;
15
+ doc = Automerge.init();
16
+ syncState = Automerge.initSyncState();
17
+ reconnectTimer = null;
18
+ isExplicitlyDisconnected = false;
19
+ constructor(options) {
20
+ this.url = options.url;
21
+ this.sessionId = options.sessionId;
22
+ this.token = options.token;
23
+ }
24
+ /**
25
+ * Connect to the WebSocket server
26
+ * @returns {Promise<void>} Resolves when connection is open
27
+ */
28
+ async connect() {
29
+ this.isExplicitlyDisconnected = false;
30
+ return new Promise((resolve, reject) => {
31
+ try {
32
+ const wsUrl = new URL(this.url);
33
+ wsUrl.searchParams.set("sessionId", this.sessionId);
34
+ wsUrl.searchParams.set("token", this.token);
35
+ this.ws = new WebSocket(wsUrl.toString());
36
+ this.ws.on("open", () => {
37
+ this.emit("open", {});
38
+ resolve();
39
+ });
40
+ this.ws.on("message", (data) => {
41
+ try {
42
+ const message = JSON.parse(data.toString());
43
+ this.handleMessage(message);
44
+ } catch (error) {
45
+ console.error("[Granular] Failed to parse message:", error);
46
+ }
47
+ });
48
+ this.ws.on("error", (error) => {
49
+ this.emit("error", error);
50
+ if (this.ws?.readyState !== WebSocket.OPEN) {
51
+ reject(error);
52
+ }
53
+ });
54
+ this.ws.on("close", () => {
55
+ this.emit("close", {});
56
+ this.handleDisconnect();
57
+ });
58
+ } catch (error) {
59
+ reject(error);
60
+ }
61
+ });
62
+ }
63
+ handleDisconnect() {
64
+ this.ws = null;
65
+ if (!this.isExplicitlyDisconnected) {
66
+ this.reconnectTimer = setTimeout(() => {
67
+ console.log("[Granular] Attempting reconnect...");
68
+ this.connect().catch((e) => console.error("[Granular] Reconnect failed:", e));
69
+ }, 3e3);
70
+ }
71
+ }
72
+ handleMessage(message) {
73
+ if (typeof message !== "object" || message === null) return;
74
+ console.log("[Granular DEBUG] Received message:", JSON.stringify(message).slice(0, 500));
75
+ if ("type" in message && message.type === "sync") {
76
+ const syncMessage = message;
77
+ try {
78
+ let bytes;
79
+ const payload = syncMessage.message || syncMessage.data;
80
+ if (typeof payload === "string") {
81
+ const binaryString = atob(payload);
82
+ const len = binaryString.length;
83
+ bytes = new Uint8Array(len);
84
+ for (let i = 0; i < len; i++) {
85
+ bytes[i] = binaryString.charCodeAt(i);
86
+ }
87
+ } else if (Array.isArray(payload)) {
88
+ bytes = new Uint8Array(payload);
89
+ } else if (payload instanceof Uint8Array) {
90
+ bytes = payload;
91
+ } else {
92
+ return;
93
+ }
94
+ const [newDoc, newSyncState] = Automerge.receiveSyncMessage(
95
+ this.doc,
96
+ this.syncState,
97
+ bytes
98
+ );
99
+ this.doc = newDoc;
100
+ this.syncState = newSyncState;
101
+ this.emit("sync", this.doc);
102
+ } catch (e) {
103
+ }
104
+ return;
105
+ }
106
+ if ("type" in message && (message.type === "rpc_result" || message.type === "rpc_error")) {
107
+ const response = message;
108
+ const pending = this.messageQueue.find((q) => q.id === response.id);
109
+ if (pending) {
110
+ if (response.type === "rpc_error") {
111
+ pending.reject(
112
+ new Error(`RPC error: ${response.error?.message || "Unknown error"}`)
113
+ );
114
+ } else {
115
+ pending.resolve(response.result);
116
+ }
117
+ this.messageQueue = this.messageQueue.filter((q) => q.id !== response.id);
118
+ }
119
+ return;
120
+ }
121
+ if ("type" in message && message.type === "rpc" && "method" in message && "id" in message) {
122
+ const request = message;
123
+ this.handleIncomingRpc(request).catch((error) => {
124
+ console.error("[Granular] Error handling incoming RPC:", error);
125
+ });
126
+ return;
127
+ }
128
+ if ("type" in message && typeof message.type === "string") {
129
+ this.emit(message.type, message);
130
+ }
131
+ }
132
+ /**
133
+ * Make an RPC call to the server
134
+ * @param {string} method - RPC method name
135
+ * @param {unknown} params - Request parameters
136
+ * @returns {Promise<unknown>} Response result
137
+ * @throws {Error} If connection is closed or timeout occurs
138
+ */
139
+ async call(method, params) {
140
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
141
+ throw new Error("WebSocket not connected");
142
+ }
143
+ const id = `rpc-${this.nextRpcId++}`;
144
+ const request = {
145
+ type: "rpc",
146
+ method,
147
+ params,
148
+ id
149
+ };
150
+ return new Promise((resolve, reject) => {
151
+ this.messageQueue.push({ resolve, reject, id });
152
+ this.ws.send(JSON.stringify(request));
153
+ setTimeout(() => {
154
+ const pending = this.messageQueue.find((q) => q.id === id);
155
+ if (pending) {
156
+ this.messageQueue = this.messageQueue.filter((q) => q.id !== id);
157
+ reject(new Error(`RPC timeout: ${method}`));
158
+ }
159
+ }, 3e4);
160
+ });
161
+ }
162
+ async handleIncomingRpc(request) {
163
+ const handler = this.rpcHandlers.get(request.method);
164
+ if (!handler) {
165
+ const errorResponse = {
166
+ type: "rpc_error",
167
+ id: request.id,
168
+ error: {
169
+ code: -32601,
170
+ message: `Method not found: ${request.method}`
171
+ }
172
+ };
173
+ this.ws?.send(JSON.stringify(errorResponse));
174
+ return;
175
+ }
176
+ try {
177
+ const result = await handler(request.params);
178
+ if (request.method !== "tool.invoke") {
179
+ const successResponse = {
180
+ type: "rpc_result",
181
+ id: request.id,
182
+ result
183
+ };
184
+ this.ws?.send(JSON.stringify(successResponse));
185
+ }
186
+ } catch (error) {
187
+ const errorResponse = {
188
+ type: "rpc_error",
189
+ id: request.id,
190
+ error: {
191
+ code: -32e3,
192
+ message: error instanceof Error ? error.message : "Unknown error"
193
+ }
194
+ };
195
+ this.ws?.send(JSON.stringify(errorResponse));
196
+ }
197
+ }
198
+ /**
199
+ * Subscribe to client events
200
+ * @param {string} event - Event name
201
+ * @param {Function} handler - Event handler
202
+ */
203
+ on(event, handler) {
204
+ if (!this.eventHandlers.has(event)) {
205
+ this.eventHandlers.set(event, []);
206
+ }
207
+ this.eventHandlers.get(event).push(handler);
208
+ }
209
+ /**
210
+ * Register an RPC handler for incoming server requests
211
+ * @param {string} method - RPC method name
212
+ * @param {Function} handler - Handler function
213
+ */
214
+ registerRpcHandler(method, handler) {
215
+ this.rpcHandlers.set(method, handler);
216
+ }
217
+ /**
218
+ * Unsubscribe from client events
219
+ * @param {string} event - Event name
220
+ * @param {Function} handler - Handler to remove
221
+ */
222
+ off(event, handler) {
223
+ const handlers = this.eventHandlers.get(event);
224
+ if (handlers) {
225
+ this.eventHandlers.set(
226
+ event,
227
+ handlers.filter((h) => h !== handler)
228
+ );
229
+ }
230
+ }
231
+ /**
232
+ * Emit an event locally
233
+ * @param {string} event - Event name
234
+ * @param params - Event data
235
+ */
236
+ emit(event, params) {
237
+ const handlers = this.eventHandlers.get(event);
238
+ if (handlers) {
239
+ handlers.forEach((handler) => handler(params));
240
+ }
241
+ }
242
+ /**
243
+ * Disconnect the WebSocket and clear state
244
+ */
245
+ disconnect() {
246
+ this.isExplicitlyDisconnected = true;
247
+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
248
+ if (this.ws) {
249
+ this.ws.close();
250
+ this.ws = null;
251
+ }
252
+ this.messageQueue.forEach((q) => q.reject(new Error("Client explicitly disconnected")));
253
+ this.messageQueue = [];
254
+ this.rpcHandlers.clear();
255
+ this.emit("disconnect", {});
256
+ }
257
+ };
258
+
259
+ // src/session.ts
260
+ var Session = class {
261
+ client;
262
+ clientId;
263
+ jobsMap = /* @__PURE__ */ new Map();
264
+ eventListeners = /* @__PURE__ */ new Map();
265
+ toolHandlers = /* @__PURE__ */ new Map();
266
+ /** Tracks which tools are instance methods (className set, not static) */
267
+ instanceTools = /* @__PURE__ */ new Set();
268
+ currentDomainRevision = null;
269
+ constructor(client, clientId) {
270
+ this.client = client;
271
+ this.clientId = clientId || `client_${Date.now()}`;
272
+ this.setupEventHandlers();
273
+ this.setupToolInvokeHandler();
274
+ }
275
+ // --- Public API ---
276
+ get document() {
277
+ return this.client.doc;
278
+ }
279
+ get domainRevision() {
280
+ return this.currentDomainRevision;
281
+ }
282
+ /**
283
+ * Make a raw RPC call to the session's Durable Object.
284
+ *
285
+ * Use this when you need to call an RPC method that doesn't have a
286
+ * dedicated wrapper method on the Session/Environment class.
287
+ *
288
+ * @param method - RPC method name (e.g. 'domain.fetchPackagePart')
289
+ * @param params - Request parameters
290
+ * @returns The raw RPC response
291
+ *
292
+ * @example
293
+ * ```typescript
294
+ * const result = await env.rpc('domain.fetchPackagePart', {
295
+ * moduleSpecifier: '@sandbox/domain',
296
+ * part: 'types',
297
+ * });
298
+ * ```
299
+ */
300
+ async rpc(method, params = {}) {
301
+ return this.client.call(method, params);
302
+ }
303
+ /**
304
+ * Send client hello to establish the session
305
+ */
306
+ async hello() {
307
+ const result = await this.client.call("client.hello", {
308
+ clientId: this.clientId,
309
+ protocolVersion: "2.0"
310
+ });
311
+ return result;
312
+ }
313
+ /**
314
+ * Publish tools to the sandbox and register handlers for reverse-RPC.
315
+ *
316
+ * Tools can be:
317
+ * - **Instance methods**: set `className` (handler receives `(objectId, params)`)
318
+ * - **Static methods**: set `className` + `static: true` (handler receives `(params)`)
319
+ * - **Global tools**: omit `className` (handler receives `(params)`)
320
+ *
321
+ * Both `inputSchema` and `outputSchema` accept JSON Schema objects. The
322
+ * `outputSchema` drives the return type in the auto-generated TypeScript
323
+ * class declarations that sandbox code imports from `./sandbox-tools`.
324
+ *
325
+ * This method:
326
+ * 1. Extracts tool schemas (including `outputSchema`) from the provided tools
327
+ * 2. Publishes them via `client.publishRawToolCatalog` RPC
328
+ * 3. Registers handlers locally for `tool.invoke` RPC calls
329
+ * 4. Returns the `domainRevision` needed for job submission
330
+ *
331
+ * @param tools - Array of tools with handlers
332
+ * @param revision - Optional revision string (default: "1.0.0")
333
+ * @returns PublishToolsResult with domainRevision
334
+ *
335
+ * @example
336
+ * ```typescript
337
+ * await env.publishTools([
338
+ * {
339
+ * name: 'get_bio',
340
+ * description: 'Get biography of an author',
341
+ * className: 'author',
342
+ * inputSchema: { type: 'object', properties: { detailed: { type: 'boolean' } } },
343
+ * outputSchema: { type: 'object', properties: { bio: { type: 'string' } }, required: ['bio'] },
344
+ * handler: async (id, params) => ({ bio: `Bio of ${id}` }),
345
+ * },
346
+ * ]);
347
+ * ```
348
+ */
349
+ async publishTools(tools, revision = "1.0.0") {
350
+ const schemas = tools.map((tool) => ({
351
+ name: tool.name,
352
+ description: tool.description,
353
+ inputSchema: tool.inputSchema,
354
+ outputSchema: tool.outputSchema,
355
+ stability: tool.stability || "stable",
356
+ provenance: tool.provenance || { source: "mcp" },
357
+ tags: tool.tags,
358
+ className: tool.className,
359
+ static: tool.static
360
+ }));
361
+ const result = await this.client.call("client.publishRawToolCatalog", {
362
+ clientId: this.clientId,
363
+ revision,
364
+ tools: schemas
365
+ });
366
+ if (!result.accepted || !result.domainRevision) {
367
+ throw new Error(`Failed to publish tools: ${JSON.stringify(result.rejected)}`);
368
+ }
369
+ for (const tool of tools) {
370
+ this.toolHandlers.set(tool.name, tool.handler);
371
+ if (tool.className && !tool.static) {
372
+ this.instanceTools.add(tool.name);
373
+ } else {
374
+ this.instanceTools.delete(tool.name);
375
+ }
376
+ }
377
+ this.currentDomainRevision = result.domainRevision;
378
+ return {
379
+ accepted: result.accepted,
380
+ domainRevision: result.domainRevision,
381
+ rejected: result.rejected
382
+ };
383
+ }
384
+ /**
385
+ * Submit a job to execute code in the sandbox.
386
+ *
387
+ * The code can import typed classes from `./sandbox-tools`:
388
+ * ```typescript
389
+ * import { Author, Book, global_search } from './sandbox-tools';
390
+ *
391
+ * const tolkien = await Author.find({ id: 'tolkien' });
392
+ * const bio = await tolkien.get_bio({ detailed: true });
393
+ * const books = await tolkien.get_books();
394
+ * ```
395
+ *
396
+ * Tool calls (instance methods, static methods, global functions) trigger
397
+ * `tool.invoke` RPC back to this client, where the registered handlers
398
+ * execute locally and return the result to the sandbox.
399
+ */
400
+ async submitJob(code, domainRevision) {
401
+ const revision = domainRevision || this.currentDomainRevision;
402
+ if (!revision) {
403
+ throw new Error("No domain revision available. Call publishTools() first.");
404
+ }
405
+ const result = await this.client.call("job.submit", {
406
+ domainRevision: revision,
407
+ code
408
+ });
409
+ if (!result.jobId) {
410
+ throw new Error("Failed to submit job: no jobId returned");
411
+ }
412
+ const job = new JobImplementation(result.jobId, this.client);
413
+ this.jobsMap.set(result.jobId, job);
414
+ return job;
415
+ }
416
+ /**
417
+ * Register a handler for a specific tool.
418
+ * @param isInstance - If true, handler will receive (id, params) for instance method dispatch.
419
+ */
420
+ registerToolHandler(name, handler, isInstance = false) {
421
+ this.toolHandlers.set(name, handler);
422
+ if (isInstance) {
423
+ this.instanceTools.add(name);
424
+ } else {
425
+ this.instanceTools.delete(name);
426
+ }
427
+ }
428
+ /**
429
+ * Respond to a prompt request from the sandbox
430
+ */
431
+ async answerPrompt(promptId, answer) {
432
+ await this.client.call("prompt.answer", { promptId, value: answer });
433
+ }
434
+ /**
435
+ * Get the current domain state and available tools
436
+ */
437
+ async getDomain() {
438
+ return this.client.call("domain.getSummary", {});
439
+ }
440
+ /**
441
+ * Get auto-generated TypeScript class declarations for the current domain.
442
+ *
443
+ * Returns typed declarations including:
444
+ * - Classes with readonly properties (from manifest)
445
+ * - `static find(query: { id: string })` for each class
446
+ * - Instance methods with typed input/output (from `publishTools` with `className`)
447
+ * - Static methods (from `publishTools` with `className` + `static: true`)
448
+ * - Relationship accessors (`get_books()`, `get_author()`, etc.)
449
+ * - Global tool functions (from `publishTools` without `className`)
450
+ *
451
+ * Pass this documentation to LLMs so they can write correct typed code
452
+ * that imports from `./sandbox-tools`.
453
+ *
454
+ * Falls back to generating markdown docs from the domain summary if
455
+ * the synthesis server is unavailable.
456
+ */
457
+ async getDomainDocumentation() {
458
+ try {
459
+ const typesResult = await this.client.call("domain.fetchPackagePart", {
460
+ moduleSpecifier: "@sandbox/domain",
461
+ part: "types"
462
+ });
463
+ if (typesResult.content) {
464
+ return typesResult.content;
465
+ }
466
+ } catch {
467
+ }
468
+ const summary = await this.getDomain();
469
+ return this.generateFallbackDocs(summary);
470
+ }
471
+ /**
472
+ * Generate markdown documentation from the domain summary.
473
+ * Class-aware: groups tools by class with property/relationship info.
474
+ */
475
+ generateFallbackDocs(summary) {
476
+ const classes = summary.classes;
477
+ const globalTools = summary.globalTools;
478
+ const tools = summary.tools || [];
479
+ if (classes && Object.keys(classes).length > 0) {
480
+ let docs2 = "# Domain Documentation\n\n";
481
+ docs2 += "Import classes and tools from `./sandbox-tools`:\n\n";
482
+ const classNames = Object.keys(classes).map(
483
+ (c) => c.charAt(0).toUpperCase() + c.slice(1)
484
+ );
485
+ const globalNames = (globalTools || []).map((t) => t.name);
486
+ const allImports = [...classNames, ...globalNames].join(", ");
487
+ docs2 += `\`\`\`typescript
488
+ import { ${allImports} } from "./sandbox-tools";
489
+ \`\`\`
490
+
491
+ `;
492
+ for (const [className, cls] of Object.entries(classes)) {
493
+ const TsName = className.charAt(0).toUpperCase() + className.slice(1);
494
+ docs2 += `## ${TsName}
495
+
496
+ `;
497
+ if (cls.description) docs2 += `${cls.description}
498
+
499
+ `;
500
+ if (cls.properties?.length > 0) {
501
+ docs2 += "**Properties:**\n";
502
+ for (const p of cls.properties) {
503
+ docs2 += `- \`${p.name}\`${p.description ? ": " + p.description : ""}
504
+ `;
505
+ }
506
+ docs2 += "\n";
507
+ }
508
+ if (cls.relationships?.length > 0) {
509
+ docs2 += "**Relationships:**\n";
510
+ for (const r of cls.relationships) {
511
+ const fModel = r.foreignModel?.charAt(0).toUpperCase() + r.foreignModel?.slice(1);
512
+ docs2 += `- \`${r.localSubmodel}\` \u2192 ${fModel} (${r.kind})
513
+ `;
514
+ }
515
+ docs2 += "\n";
516
+ }
517
+ if (cls.methods?.length > 0) {
518
+ docs2 += "**Methods:**\n";
519
+ for (const m of cls.methods) {
520
+ docs2 += `- \`${TsName}.${m.name}(input)\``;
521
+ if (m.description) docs2 += `: ${m.description}`;
522
+ docs2 += "\n";
523
+ if (m.inputSchema?.properties) {
524
+ docs2 += " ```json\n " + JSON.stringify(m.inputSchema, null, 2).replace(/\n/g, "\n ") + "\n ```\n";
525
+ }
526
+ }
527
+ docs2 += "\n";
528
+ }
529
+ }
530
+ if (globalTools && globalTools.length > 0) {
531
+ docs2 += "## Global Tools\n\n";
532
+ for (const tool of globalTools) {
533
+ docs2 += `### ${tool.name}
534
+
535
+ `;
536
+ if (tool.description) docs2 += `${tool.description}
537
+
538
+ `;
539
+ if (tool.inputSchema) {
540
+ docs2 += "**Input Schema:**\n```json\n";
541
+ docs2 += JSON.stringify(tool.inputSchema, null, 2);
542
+ docs2 += "\n```\n\n";
543
+ }
544
+ }
545
+ }
546
+ return docs2;
547
+ }
548
+ if (!tools || tools.length === 0) {
549
+ return "No tools available in this domain.";
550
+ }
551
+ let docs = "# Available Tools\n\n";
552
+ docs += "Import tools from `./sandbox-tools` and call them with await:\n\n";
553
+ docs += '```typescript\nimport { tools } from "./sandbox-tools";\n\n';
554
+ docs += "// Example:\n";
555
+ docs += `const result = await tools.${tools[0]?.name || "example"}(input);
556
+ `;
557
+ docs += "```\n\n";
558
+ for (const tool of tools) {
559
+ docs += `## ${tool.name}
560
+
561
+ `;
562
+ if (tool.description) {
563
+ docs += `${tool.description}
564
+
565
+ `;
566
+ }
567
+ if (tool.inputSchema) {
568
+ docs += "**Input Schema:**\n```json\n";
569
+ docs += JSON.stringify(tool.inputSchema, null, 2);
570
+ docs += "\n```\n\n";
571
+ }
572
+ if (tool.outputSchema) {
573
+ docs += "**Output Schema:**\n```json\n";
574
+ docs += JSON.stringify(tool.outputSchema, null, 2);
575
+ docs += "\n```\n\n";
576
+ }
577
+ }
578
+ return docs;
579
+ }
580
+ /**
581
+ * Close the session and disconnect from the sandbox
582
+ */
583
+ async disconnect() {
584
+ this.client.disconnect();
585
+ }
586
+ // --- Event Handling ---
587
+ /**
588
+ * Subscribe to session events
589
+ */
590
+ on(event, handler) {
591
+ if (!this.eventListeners.has(event)) {
592
+ this.eventListeners.set(event, []);
593
+ }
594
+ this.eventListeners.get(event).push(handler);
595
+ }
596
+ /**
597
+ * Unsubscribe from session events
598
+ */
599
+ off(event, handler) {
600
+ const handlers = this.eventListeners.get(event);
601
+ if (handlers) {
602
+ this.eventListeners.set(event, handlers.filter((h) => h !== handler));
603
+ }
604
+ }
605
+ // --- Internal ---
606
+ setupToolInvokeHandler() {
607
+ this.client.registerRpcHandler("tool.invoke", async (params) => {
608
+ const { callId, toolName, input } = params;
609
+ this.emit("tool:invoke", { callId, toolName, input });
610
+ const handler = this.toolHandlers.get(toolName);
611
+ if (!handler) {
612
+ await this.client.call("tool.result", {
613
+ callId,
614
+ error: { code: "TOOL_NOT_FOUND", message: `Tool handler not found: ${toolName}` }
615
+ });
616
+ return;
617
+ }
618
+ try {
619
+ let result;
620
+ if (this.instanceTools.has(toolName) && input && typeof input === "object" && "_objectId" in input) {
621
+ const { _objectId, ...restParams } = input;
622
+ result = await handler(_objectId, restParams);
623
+ } else {
624
+ result = await handler(input);
625
+ }
626
+ this.emit("tool:result", { callId, result });
627
+ await this.client.call("tool.result", {
628
+ callId,
629
+ result
630
+ });
631
+ } catch (error) {
632
+ const errorMessage = error instanceof Error ? error.message : String(error);
633
+ this.emit("tool:result", { callId, error: errorMessage });
634
+ await this.client.call("tool.result", {
635
+ callId,
636
+ error: { code: "TOOL_EXECUTION_FAILED", message: errorMessage }
637
+ });
638
+ }
639
+ });
640
+ }
641
+ setupEventHandlers() {
642
+ this.client.on("sync", (doc) => this.emit("sync", doc));
643
+ this.client.on("prompt", (prompt) => this.emit("prompt", prompt));
644
+ this.client.on("disconnect", () => this.emit("disconnect", {}));
645
+ this.client.on("job.status", (data) => {
646
+ this.emit("job:status", data);
647
+ });
648
+ this.client.on("exec.completed", (data) => {
649
+ this.emit("exec:completed", data);
650
+ });
651
+ this.client.on("exec.progress", (data) => {
652
+ this.emit("exec:progress", data);
653
+ });
654
+ }
655
+ emit(event, data) {
656
+ const handlers = this.eventListeners.get(event);
657
+ if (handlers) {
658
+ handlers.forEach((h) => h(data));
659
+ }
660
+ }
661
+ };
662
+ var JobImplementation = class {
663
+ id;
664
+ client;
665
+ status = "queued";
666
+ _resultPromise;
667
+ _resolveResult;
668
+ _rejectResult;
669
+ eventListeners = /* @__PURE__ */ new Map();
670
+ constructor(id, client) {
671
+ this.id = id;
672
+ this.client = client;
673
+ this._resultPromise = new Promise((resolve, reject) => {
674
+ this._resolveResult = resolve;
675
+ this._rejectResult = reject;
676
+ });
677
+ this.client.on("exec.completed", (data) => {
678
+ const execData = data;
679
+ if (execData.execId === id || execData.jobId === id) {
680
+ this.status = "succeeded";
681
+ this.emit("status", this.status);
682
+ if (execData.error) {
683
+ this._rejectResult(execData.error);
684
+ } else {
685
+ this._resolveResult(execData.result);
686
+ }
687
+ }
688
+ });
689
+ this.client.on("exec.progress", (data) => {
690
+ const progressData = data;
691
+ if (progressData.execId === id || progressData.jobId === id) {
692
+ if (progressData.stdout) {
693
+ this.emit("stdout", progressData.stdout);
694
+ }
695
+ if (progressData.stderr) {
696
+ this.emit("stderr", progressData.stderr);
697
+ }
698
+ }
699
+ });
700
+ this.client.on(`job.${id}.status`, (status) => {
701
+ this.status = status;
702
+ this.emit("status", status);
703
+ });
704
+ this.client.on(`job.${id}.stdout`, (line) => {
705
+ this.emit("stdout", line);
706
+ });
707
+ this.client.on(`job.${id}.stderr`, (line) => {
708
+ this.emit("stderr", line);
709
+ });
710
+ this.client.on(`job.${id}.result`, (result) => {
711
+ this.status = "succeeded";
712
+ this._resolveResult(result);
713
+ });
714
+ this.client.on(`job.${id}.error`, (error) => {
715
+ this.status = "failed";
716
+ this._rejectResult(error);
717
+ });
718
+ this.client.on("job.completed", (data) => {
719
+ const jobData = data;
720
+ if (jobData.jobId === id) {
721
+ this.status = "succeeded";
722
+ this.emit("status", this.status);
723
+ this._resolveResult(jobData.result);
724
+ }
725
+ });
726
+ this.client.on("job.failed", (data) => {
727
+ const jobData = data;
728
+ if (jobData.jobId === id) {
729
+ this.status = "failed";
730
+ this.emit("status", this.status);
731
+ this._rejectResult(jobData.error || new Error("Job failed"));
732
+ }
733
+ });
734
+ }
735
+ get result() {
736
+ return this._resultPromise;
737
+ }
738
+ on(event, handler) {
739
+ if (!this.eventListeners.has(event)) {
740
+ this.eventListeners.set(event, []);
741
+ }
742
+ this.eventListeners.get(event).push(handler);
743
+ }
744
+ emit(event, data) {
745
+ const handlers = this.eventListeners.get(event);
746
+ if (handlers) {
747
+ handlers.forEach((h) => h(data));
748
+ }
749
+ }
750
+ };
751
+
752
+ // src/client.ts
753
+ var STANDARD_MODULES_OPERATIONS = [
754
+ { create: "entity", has: { id: { value: "auto-generated" }, createdAt: { value: void 0 } } },
755
+ { create: "class", extends: "entity", has: {} },
756
+ { create: "user", extends: "entity", has: { email: { value: void 0 }, firstName: { value: void 0 }, lastName: { value: void 0 } } },
757
+ { create: "company", extends: "entity", has: { name: { value: void 0 }, website: { value: void 0 } } },
758
+ { create: "string", has: { value: { value: void 0 } } },
759
+ { create: "number", has: { value: { value: 0 } } },
760
+ { create: "boolean", has: { value: { value: false } } },
761
+ { create: "tool_parameter", has: { name: { value: void 0 }, type: { value: "string" }, description: { value: void 0 }, required: { value: false } } }
762
+ ];
763
+ var BUILTIN_MODULES = {
764
+ "standard_modules": STANDARD_MODULES_OPERATIONS
765
+ };
766
+ var Environment = class _Environment extends Session {
767
+ envData;
768
+ _apiKey;
769
+ _apiEndpoint;
770
+ constructor(client, envData, clientId, apiKey, apiEndpoint) {
771
+ super(client, clientId);
772
+ this.envData = envData;
773
+ this._apiKey = apiKey;
774
+ this._apiEndpoint = apiEndpoint;
775
+ }
776
+ /** The environment ID */
777
+ get environmentId() {
778
+ return this.envData.environmentId;
779
+ }
780
+ /** The sandbox ID */
781
+ get sandboxId() {
782
+ return this.envData.sandboxId;
783
+ }
784
+ /** The subject ID */
785
+ get subjectId() {
786
+ return this.envData.subjectId;
787
+ }
788
+ /** The permission profile ID */
789
+ get permissionProfileId() {
790
+ return this.envData.permissionProfileId;
791
+ }
792
+ /** The GraphQL API endpoint URL */
793
+ get apiEndpoint() {
794
+ return this._apiEndpoint;
795
+ }
796
+ // ==================== ID ↔ GRAPH PATH MAPPING ====================
797
+ /**
798
+ * Convert a class name + real-world ID into a unique graph path.
799
+ *
800
+ * Two objects of *different* classes may share the same real-world ID,
801
+ * so the graph path must incorporate the class to guarantee uniqueness.
802
+ *
803
+ * Format: `{className}_{id}` — deterministic, human-readable.
804
+ *
805
+ * **Convention**: class names should be simple identifiers without
806
+ * underscores (e.g. `author`, `book`). This ensures the prefix is
807
+ * unambiguously parseable by `extractIdFromGraphPath`.
808
+ */
809
+ static toGraphPath(className, id) {
810
+ return `${className}_${id}`;
811
+ }
812
+ /**
813
+ * Extract the real-world ID from a graph path, given the class name.
814
+ *
815
+ * Strips the `{className}_` prefix. Returns the raw path if the
816
+ * expected prefix is not found.
817
+ */
818
+ static extractIdFromGraphPath(graphPath, className) {
819
+ const prefix = `${className}_`;
820
+ return graphPath.startsWith(prefix) ? graphPath.substring(prefix.length) : graphPath;
821
+ }
822
+ /**
823
+ * Execute a GraphQL query against the environment's graph.
824
+ *
825
+ * The query uses the Granular graph query language (based on Cypher/GraphQL).
826
+ * Authentication is handled automatically using the SDK's API key.
827
+ *
828
+ * @param query - The GraphQL query string
829
+ * @param variables - Optional variables for the query
830
+ * @returns The query result data
831
+ *
832
+ * @example
833
+ * ```typescript
834
+ * // Read the workspace
835
+ * const result = await env.graphql(
836
+ * `query { model(path: "workspace") { path label submodels { path label } } }`
837
+ * );
838
+ * console.log(result.data);
839
+ *
840
+ * // Create a model
841
+ * const created = await env.graphql(
842
+ * `mutation { at(path: "workspace") { create_submodel(subpath: "my_node", label: "My Node", prototype: "Model") { model { path label } } } }`
843
+ * );
844
+ * ```
845
+ */
846
+ async graphql(query, variables) {
847
+ const response = await fetch(this._apiEndpoint, {
848
+ method: "POST",
849
+ headers: {
850
+ "Content-Type": "application/json",
851
+ "Authorization": `Bearer ${this._apiKey}`
852
+ },
853
+ body: JSON.stringify({
854
+ environmentId: this.environmentId,
855
+ query,
856
+ variables
857
+ })
858
+ });
859
+ if (!response.ok) {
860
+ const errorText = await response.text();
861
+ throw new Error(`GraphQL API Error (${response.status}): ${errorText}`);
862
+ }
863
+ return response.json();
864
+ }
865
+ // ==================== RELATIONSHIP METHODS ====================
866
+ /**
867
+ * Define a relationship between two model types.
868
+ *
869
+ * Creates both submodels (if they don't exist) and links them with
870
+ * a RelationshipDef node that encodes cardinality.
871
+ *
872
+ * @example
873
+ * ```typescript
874
+ * // Author has many Books, Book has one Author
875
+ * const rel = await env.defineRelationship({
876
+ * model: 'author',
877
+ * localSubmodel: 'books',
878
+ * localIsMany: true,
879
+ * foreignModel: 'book',
880
+ * foreignSubmodel: 'author',
881
+ * foreignIsMany: false,
882
+ * });
883
+ * console.log(rel.relationship_kind); // "one_to_many"
884
+ * ```
885
+ */
886
+ async defineRelationship(options) {
887
+ const result = await this.graphql(
888
+ `mutation DefineRelationship(
889
+ $localSubmodel: String!,
890
+ $foreignModel: String!,
891
+ $foreignSubmodel: String!,
892
+ $localIsMany: Boolean!,
893
+ $foreignIsMany: Boolean!,
894
+ $name: String
895
+ ) {
896
+ at(path: "${options.model}") {
897
+ define_relationship(
898
+ local_submodel: $localSubmodel
899
+ foreign_model: $foreignModel
900
+ foreign_submodel: $foreignSubmodel
901
+ local_is_many: $localIsMany
902
+ foreign_is_many: $foreignIsMany
903
+ name: $name
904
+ ) {
905
+ name
906
+ local_submodel { path label }
907
+ local_is_many
908
+ foreign_submodel { path label }
909
+ foreign_is_many
910
+ foreign_model { path label }
911
+ relationship_kind
912
+ }
913
+ }
914
+ }`,
915
+ {
916
+ localSubmodel: options.localSubmodel,
917
+ foreignModel: options.foreignModel,
918
+ foreignSubmodel: options.foreignSubmodel,
919
+ localIsMany: options.localIsMany,
920
+ foreignIsMany: options.foreignIsMany,
921
+ name: options.name
922
+ }
923
+ );
924
+ if (result.errors?.length) {
925
+ throw new Error(`defineRelationship failed: ${result.errors[0].message}`);
926
+ }
927
+ return result.data.at.define_relationship;
928
+ }
929
+ /**
930
+ * Get all relationships for a model type.
931
+ *
932
+ * @param modelPath - The model type path (e.g., "author")
933
+ * @returns Array of relationships from this model's perspective
934
+ *
935
+ * @example
936
+ * ```typescript
937
+ * const rels = await env.getRelationships('author');
938
+ * for (const rel of rels) {
939
+ * console.log(`${rel.local_submodel.path} -> ${rel.foreign_model.path} (${rel.relationship_kind})`);
940
+ * }
941
+ * ```
942
+ */
943
+ async getRelationships(modelPath) {
944
+ const result = await this.graphql(
945
+ `query GetRelationships($path: String) {
946
+ model(path: $path) {
947
+ relationships {
948
+ name
949
+ local_submodel { path label }
950
+ local_is_many
951
+ foreign_submodel { path label }
952
+ foreign_is_many
953
+ foreign_model { path label }
954
+ relationship_kind
955
+ }
956
+ }
957
+ }`,
958
+ { path: modelPath }
959
+ );
960
+ if (result.errors?.length) {
961
+ throw new Error(`getRelationships failed: ${result.errors[0].message}`);
962
+ }
963
+ return result.data?.model?.relationships || [];
964
+ }
965
+ /**
966
+ * Attach a target model to a relationship submodel.
967
+ *
968
+ * Handles cardinality automatically:
969
+ * - "One" side: sets/replaces the reference
970
+ * - "Many" side: adds the target to the collection
971
+ *
972
+ * If the target model doesn't exist, it's created as an instance of the foreign type.
973
+ * Bidirectional sync is automatic.
974
+ *
975
+ * @param modelPath - The model instance path (e.g., "tolkien")
976
+ * @param submodelPath - The relationship submodel (e.g., "books")
977
+ * @param targetPath - The target model to attach (e.g., "lord_of_the_rings")
978
+ *
979
+ * @example
980
+ * ```typescript
981
+ * // Attach a book to an author (many side)
982
+ * await env.attach('tolkien', 'books', 'lord_of_the_rings');
983
+ * // This also automatically sets lord_of_the_rings:author -> tolkien
984
+ * ```
985
+ */
986
+ async attach(modelPath, submodelPath, targetPath) {
987
+ const result = await this.graphql(
988
+ `mutation Attach($target: String!) {
989
+ at(path: "${modelPath}") {
990
+ at(submodel: "${submodelPath}") {
991
+ attach(target: $target) {
992
+ model { path }
993
+ }
994
+ }
995
+ }
996
+ }`,
997
+ { target: targetPath }
998
+ );
999
+ if (result.errors?.length) {
1000
+ throw new Error(`attach failed: ${result.errors[0].message}`);
1001
+ }
1002
+ }
1003
+ /**
1004
+ * Detach a target model from a relationship submodel.
1005
+ *
1006
+ * Handles bidirectional cleanup automatically.
1007
+ *
1008
+ * @param modelPath - The model instance path
1009
+ * @param submodelPath - The relationship submodel
1010
+ * @param targetPath - The target to detach (optional for "one" side; omit on "many" side to detach all)
1011
+ *
1012
+ * @example
1013
+ * ```typescript
1014
+ * // Detach a specific book
1015
+ * await env.detach('tolkien', 'books', 'lord_of_the_rings');
1016
+ *
1017
+ * // Detach all books
1018
+ * await env.detach('tolkien', 'books');
1019
+ * ```
1020
+ */
1021
+ async detach(modelPath, submodelPath, targetPath) {
1022
+ const targetArg = targetPath ? `target: "${targetPath}"` : "";
1023
+ const result = await this.graphql(
1024
+ `mutation Detach {
1025
+ at(path: "${modelPath}") {
1026
+ at(submodel: "${submodelPath}") {
1027
+ detach(${targetArg}) {
1028
+ model { path }
1029
+ }
1030
+ }
1031
+ }
1032
+ }`
1033
+ );
1034
+ if (result.errors?.length) {
1035
+ throw new Error(`detach failed: ${result.errors[0].message}`);
1036
+ }
1037
+ }
1038
+ /**
1039
+ * List all related models through a relationship submodel.
1040
+ *
1041
+ * @param modelPath - The model instance path
1042
+ * @param submodelPath - The relationship submodel
1043
+ * @returns Array of related model references
1044
+ *
1045
+ * @example
1046
+ * ```typescript
1047
+ * const books = await env.listRelated('tolkien', 'books');
1048
+ * console.log(books); // [{ path: "lord_of_the_rings", label: "Lord of the Rings" }, ...]
1049
+ * ```
1050
+ */
1051
+ async listRelated(modelPath, submodelPath) {
1052
+ const result = await this.graphql(
1053
+ `mutation ListRelated {
1054
+ at(path: "${modelPath}") {
1055
+ at(submodel: "${submodelPath}") {
1056
+ list_related { path label }
1057
+ }
1058
+ }
1059
+ }`
1060
+ );
1061
+ if (result.errors?.length) {
1062
+ throw new Error(`listRelated failed: ${result.errors[0].message}`);
1063
+ }
1064
+ return result.data?.at?.at?.list_related || [];
1065
+ }
1066
+ /**
1067
+ * Apply a manifest to the current environment's graph.
1068
+ *
1069
+ * Translates each manifest operation into GraphQL mutations and executes them
1070
+ * in order. This is the core mechanism for creating classes, fields, and
1071
+ * relationships from a declarative manifest.
1072
+ *
1073
+ * @param manifest - The manifest content to apply
1074
+ * @returns Summary of applied operations
1075
+ *
1076
+ * @example
1077
+ * ```typescript
1078
+ * await environment.applyManifest({
1079
+ * schemaVersion: 2,
1080
+ * name: 'my-app',
1081
+ * volumes: [{
1082
+ * name: 'schema',
1083
+ * scope: 'sandbox',
1084
+ * operations: [
1085
+ * { create: 'author', extends: 'class', has: { name: { type: 'string' } } },
1086
+ * { create: 'book', extends: 'class', has: { title: { type: 'string' } } },
1087
+ * { defineRelationship: {
1088
+ * left: 'author', right: 'book',
1089
+ * leftSubmodel: 'books', rightSubmodel: 'author',
1090
+ * leftIsMany: true, rightIsMany: false,
1091
+ * }},
1092
+ * ],
1093
+ * }],
1094
+ * });
1095
+ * ```
1096
+ */
1097
+ async applyManifest(manifest) {
1098
+ const errors = [];
1099
+ let applied = 0;
1100
+ for (const volume of manifest.volumes) {
1101
+ const aliasMap = {};
1102
+ if (volume.imports) {
1103
+ for (const imp of volume.imports) {
1104
+ aliasMap[imp.alias] = imp.name;
1105
+ const builtinOps = BUILTIN_MODULES[imp.name];
1106
+ if (builtinOps) {
1107
+ for (const op of builtinOps) {
1108
+ try {
1109
+ await this._applyOperation(op, {});
1110
+ applied++;
1111
+ } catch (err) {
1112
+ if (!err.message?.includes("already exists")) {
1113
+ errors.push(`Import ${imp.name} operation failed: ${err.message}`);
1114
+ }
1115
+ }
1116
+ }
1117
+ } else {
1118
+ errors.push(`Unknown module: "${imp.name}" (only built-in modules are supported)`);
1119
+ }
1120
+ }
1121
+ }
1122
+ for (const op of volume.operations) {
1123
+ try {
1124
+ await this._applyOperation(op, aliasMap);
1125
+ applied++;
1126
+ } catch (err) {
1127
+ errors.push(`Operation failed: ${err.message}`);
1128
+ }
1129
+ }
1130
+ }
1131
+ return { applied, errors };
1132
+ }
1133
+ /**
1134
+ * Resolve an alias reference like "@std/class" → "class"
1135
+ * Strips the alias prefix, returning the bare model path.
1136
+ */
1137
+ _resolveAlias(ref, aliasMap) {
1138
+ if (!ref.startsWith("@")) return ref;
1139
+ const slashIdx = ref.indexOf("/");
1140
+ if (slashIdx === -1) return ref;
1141
+ const alias = ref.substring(0, slashIdx);
1142
+ const symbolName = ref.substring(slashIdx + 1);
1143
+ if (aliasMap[alias]) {
1144
+ return symbolName;
1145
+ }
1146
+ return ref;
1147
+ }
1148
+ /**
1149
+ * Apply a single manifest operation via GraphQL
1150
+ */
1151
+ async _applyOperation(op, aliasMap) {
1152
+ if (op.defineRelationship) {
1153
+ const rel = op.defineRelationship;
1154
+ await this.defineRelationship({
1155
+ model: this._resolveAlias(rel.left, aliasMap),
1156
+ localSubmodel: rel.leftSubmodel,
1157
+ localIsMany: rel.leftIsMany,
1158
+ foreignModel: this._resolveAlias(rel.right, aliasMap),
1159
+ foreignSubmodel: rel.rightSubmodel,
1160
+ foreignIsMany: rel.rightIsMany,
1161
+ name: rel.name
1162
+ });
1163
+ return;
1164
+ }
1165
+ if (op.create) {
1166
+ const label = op.create.charAt(0).toUpperCase() + op.create.slice(1);
1167
+ const extendsRef = op.extends ? this._resolveAlias(op.extends, aliasMap) : void 0;
1168
+ const instanceOfRef = op.instanceOf ? this._resolveAlias(op.instanceOf, aliasMap) : void 0;
1169
+ if (extendsRef) {
1170
+ await this.graphql(
1171
+ `mutation { create_model(path: "${op.create}", label: "${label}") { model { path } } }`
1172
+ );
1173
+ await this.graphql(
1174
+ `mutation { at(path: "${op.create}") { add_superclass(superclass: "${extendsRef}") { model { path } } } }`
1175
+ );
1176
+ } else if (instanceOfRef) {
1177
+ await this.graphql(
1178
+ `mutation { at(path: "${instanceOfRef}") { instantiate(path: "${op.create}", label: "${label}") { model { path } } } }`
1179
+ );
1180
+ } else {
1181
+ await this.graphql(
1182
+ `mutation { create_model(path: "${op.create}", label: "${label}") { model { path } } }`
1183
+ );
1184
+ }
1185
+ if (op.has) {
1186
+ await this._applyFields(op.create, op.has);
1187
+ }
1188
+ return;
1189
+ }
1190
+ if (op.on) {
1191
+ const target = this._resolveAlias(op.on, aliasMap);
1192
+ if (op.has) {
1193
+ await this._applyFields(target, op.has);
1194
+ }
1195
+ return;
1196
+ }
1197
+ }
1198
+ /**
1199
+ * Apply field definitions (has) to a model via GraphQL
1200
+ */
1201
+ async _applyFields(modelPath, fields) {
1202
+ for (const [fieldName, spec] of Object.entries(fields)) {
1203
+ const fieldLabel = fieldName.charAt(0).toUpperCase() + fieldName.slice(1);
1204
+ await this.graphql(
1205
+ `mutation {
1206
+ at(path: "${modelPath}") {
1207
+ create_submodel(subpath: "${fieldName}", label: "${fieldLabel}") {
1208
+ model { path }
1209
+ }
1210
+ }
1211
+ }`
1212
+ );
1213
+ if (spec.type) {
1214
+ await this.graphql(
1215
+ `mutation {
1216
+ at(path: "${modelPath}") {
1217
+ at(submodel: "${fieldName}") {
1218
+ add_prototype(prototype: "${spec.type}") { done }
1219
+ }
1220
+ }
1221
+ }`
1222
+ );
1223
+ }
1224
+ if (spec.description) {
1225
+ await this.graphql(
1226
+ `mutation {
1227
+ at(path: "${modelPath}") {
1228
+ at(submodel: "${fieldName}") {
1229
+ set_description(description: "${spec.description}") { done }
1230
+ }
1231
+ }
1232
+ }`
1233
+ );
1234
+ }
1235
+ if (spec.value !== void 0 && spec.value !== null) {
1236
+ if (typeof spec.value === "string") {
1237
+ await this.graphql(
1238
+ `mutation {
1239
+ at(path: "${modelPath}") {
1240
+ at(submodel: "${fieldName}") {
1241
+ set_string_value(value: "${spec.value}") { done }
1242
+ }
1243
+ }
1244
+ }`
1245
+ );
1246
+ } else if (typeof spec.value === "number") {
1247
+ await this.graphql(
1248
+ `mutation {
1249
+ at(path: "${modelPath}") {
1250
+ at(submodel: "${fieldName}") {
1251
+ set_number_value(value: ${spec.value}) { done }
1252
+ }
1253
+ }
1254
+ }`
1255
+ );
1256
+ } else if (typeof spec.value === "boolean") {
1257
+ await this.graphql(
1258
+ `mutation {
1259
+ at(path: "${modelPath}") {
1260
+ at(submodel: "${fieldName}") {
1261
+ set_boolean_value(value: ${spec.value}) { done }
1262
+ }
1263
+ }
1264
+ }`
1265
+ );
1266
+ }
1267
+ }
1268
+ if (spec.ref) {
1269
+ await this.graphql(
1270
+ `mutation {
1271
+ at(path: "${modelPath}") {
1272
+ at(submodel: "${fieldName}") {
1273
+ set_reference(reference: "${spec.ref}") { done }
1274
+ }
1275
+ }
1276
+ }`
1277
+ );
1278
+ }
1279
+ if (spec.has) {
1280
+ await this._applyFields(`${modelPath}:${fieldName}`, spec.has);
1281
+ }
1282
+ }
1283
+ }
1284
+ // ==================== RECORD OBJECT ====================
1285
+ /**
1286
+ * Create or update an instance of a class in the graph.
1287
+ *
1288
+ * Uses `instantiate` under the hood, which has find-or-create semantics:
1289
+ * if an instance with the given `id` already exists for the class it is
1290
+ * returned; otherwise a new instance is created. Fields are then set
1291
+ * (overwriting previous values) and relationships are attached.
1292
+ *
1293
+ * The graph path is derived as `{className}_{id}` to ensure uniqueness
1294
+ * across classes (two objects of different classes may share the same
1295
+ * real-world ID). Relationship targets are also resolved automatically
1296
+ * using the foreign class from the relationship definition.
1297
+ *
1298
+ * @param options - The object specification
1299
+ * @returns The graph path, real-world ID, and creation status
1300
+ *
1301
+ * @example
1302
+ * ```typescript
1303
+ * // Create an author with fields
1304
+ * const result = await env.recordObject({
1305
+ * className: 'author',
1306
+ * id: 'tolkien',
1307
+ * label: 'J.R.R. Tolkien',
1308
+ * fields: { name: 'J.R.R. Tolkien', birth_year: 1892 },
1309
+ * relationships: { books: ['lotr', 'silmarillion'] },
1310
+ * });
1311
+ * // result.path → 'author_tolkien' (internal graph path)
1312
+ * // result.id → 'tolkien' (real-world ID)
1313
+ * // result.created → true
1314
+ * ```
1315
+ */
1316
+ async recordObject(options) {
1317
+ const { className, id, label, fields, relationships } = options;
1318
+ const graphPath = _Environment.toGraphPath(className, id);
1319
+ const existsResult = await this.graphql(
1320
+ `query { model(path: "${graphPath}") { path } }`
1321
+ );
1322
+ const alreadyExists = !!existsResult.data?.model;
1323
+ const instResult = await this.graphql(
1324
+ `mutation {
1325
+ at(path: "${className}") {
1326
+ instantiate(path: "${graphPath}"${label ? `, label: "${label}"` : ""}) {
1327
+ model { path }
1328
+ }
1329
+ }
1330
+ }`
1331
+ );
1332
+ if (instResult.errors?.length) {
1333
+ throw new Error(`recordObject instantiate failed: ${instResult.errors[0].message}`);
1334
+ }
1335
+ const instancePath = instResult.data?.at?.instantiate?.model?.path ?? graphPath;
1336
+ await this.graphql(
1337
+ `mutation {
1338
+ at(path: "${instancePath}") {
1339
+ create_submodel(subpath: "_realId", label: "_realId") {
1340
+ model { path }
1341
+ }
1342
+ }
1343
+ }`
1344
+ );
1345
+ await this.graphql(
1346
+ `mutation {
1347
+ at(path: "${instancePath}") {
1348
+ at(submodel: "_realId") {
1349
+ set_string_value(value: "${id.replace(/"/g, '\\"')}") { done }
1350
+ }
1351
+ }
1352
+ }`
1353
+ );
1354
+ if (fields) {
1355
+ for (const [fieldName, value] of Object.entries(fields)) {
1356
+ if (value === null) continue;
1357
+ await this.graphql(
1358
+ `mutation {
1359
+ at(path: "${instancePath}") {
1360
+ create_submodel(subpath: "${fieldName}", label: "${fieldName}") {
1361
+ model { path }
1362
+ }
1363
+ }
1364
+ }`
1365
+ );
1366
+ if (typeof value === "string") {
1367
+ await this.graphql(
1368
+ `mutation {
1369
+ at(path: "${instancePath}") {
1370
+ at(submodel: "${fieldName}") {
1371
+ set_string_value(value: "${value.replace(/"/g, '\\"')}") { done }
1372
+ }
1373
+ }
1374
+ }`
1375
+ );
1376
+ } else if (typeof value === "number") {
1377
+ await this.graphql(
1378
+ `mutation {
1379
+ at(path: "${instancePath}") {
1380
+ at(submodel: "${fieldName}") {
1381
+ set_number_value(value: ${value}) { done }
1382
+ }
1383
+ }
1384
+ }`
1385
+ );
1386
+ } else if (typeof value === "boolean") {
1387
+ await this.graphql(
1388
+ `mutation {
1389
+ at(path: "${instancePath}") {
1390
+ at(submodel: "${fieldName}") {
1391
+ set_boolean_value(value: ${value}) { done }
1392
+ }
1393
+ }
1394
+ }`
1395
+ );
1396
+ }
1397
+ }
1398
+ }
1399
+ if (relationships) {
1400
+ const rels = await this.getRelationships(className);
1401
+ const relMap = {};
1402
+ for (const rel of rels) {
1403
+ const submodelLeaf = rel.local_submodel.path.includes(":") ? rel.local_submodel.path.split(":").pop() : rel.local_submodel.path;
1404
+ relMap[submodelLeaf] = rel.foreign_model.path;
1405
+ }
1406
+ for (const [submodelName, targets] of Object.entries(relationships)) {
1407
+ const foreignClass = relMap[submodelName];
1408
+ const targetList = Array.isArray(targets) ? targets : [targets];
1409
+ for (const target of targetList) {
1410
+ const targetGraphPath = foreignClass ? _Environment.toGraphPath(foreignClass, target) : target;
1411
+ await this.attach(instancePath, submodelName, targetGraphPath);
1412
+ }
1413
+ }
1414
+ }
1415
+ return { path: instancePath, id, created: !alreadyExists };
1416
+ }
1417
+ // ==================== PUBLISH TOOLS ====================
1418
+ /**
1419
+ * Convenience method: publish tools and get back wrapped result.
1420
+ * This is the main entry point for setting up tools.
1421
+ *
1422
+ * @example
1423
+ * ```typescript
1424
+ * const tools = [
1425
+ * {
1426
+ * name: 'get_weather',
1427
+ * description: 'Get weather for a city',
1428
+ * inputSchema: { type: 'object', properties: { city: { type: 'string' } } },
1429
+ * handler: async ({ city }) => ({ temp: 22 }),
1430
+ * },
1431
+ * ];
1432
+ *
1433
+ * const { domainRevision } = await environment.publishTools(tools);
1434
+ *
1435
+ * // Now submit jobs that use those tools
1436
+ * const job = await environment.submitJob(`
1437
+ * import { Author } from './sandbox-tools';
1438
+ * const weather = await Author.get_weather({ city: 'Paris' });
1439
+ * return weather;
1440
+ * `);
1441
+ *
1442
+ * const result = await job.result;
1443
+ * ```
1444
+ */
1445
+ async publishTools(tools, revision = "1.0.0") {
1446
+ return super.publishTools(tools, revision);
1447
+ }
1448
+ };
1449
+ var Granular = class {
1450
+ apiKey;
1451
+ apiUrl;
1452
+ httpUrl;
1453
+ /**
1454
+ * Create a new Granular client
1455
+ * @param options - Client configuration
1456
+ */
1457
+ constructor(options) {
1458
+ this.apiKey = options.apiKey;
1459
+ this.apiUrl = options.apiUrl || "wss://api.granular.dev/v2/ws";
1460
+ this.httpUrl = this.apiUrl.replace("wss://", "https://").replace("/ws", "");
1461
+ }
1462
+ /**
1463
+ * Records/upserts a user and prepares them for sandbox connections
1464
+ *
1465
+ * @param options - User options
1466
+ * @returns The user object to pass to connect()
1467
+ *
1468
+ * @example
1469
+ * ```typescript
1470
+ * const user = await granular.recordUser({
1471
+ * userId: 'user_123',
1472
+ * name: 'John Doe',
1473
+ * permissions: ['agent'],
1474
+ * });
1475
+ * ```
1476
+ */
1477
+ async recordUser(options) {
1478
+ const subject = await this.request("/control/subjects", {
1479
+ method: "POST",
1480
+ body: JSON.stringify({
1481
+ identityId: options.userId,
1482
+ name: options.name,
1483
+ email: options.email
1484
+ })
1485
+ });
1486
+ return {
1487
+ subjectId: subject.subjectId,
1488
+ identityId: options.userId,
1489
+ name: options.name,
1490
+ email: options.email,
1491
+ permissions: options.permissions || []
1492
+ };
1493
+ }
1494
+ /**
1495
+ * Connect to a sandbox and establish a real-time environment session.
1496
+ *
1497
+ * After connecting, use `environment.publishTools()` to register tools,
1498
+ * then `environment.submitJob()` to execute code that uses those tools.
1499
+ *
1500
+ * @param options - Connection options
1501
+ * @returns An active environment session
1502
+ *
1503
+ * @example
1504
+ * ```typescript
1505
+ * const user = await granular.recordUser({
1506
+ * userId: 'user_123',
1507
+ * permissions: ['agent'],
1508
+ * });
1509
+ *
1510
+ * const environment = await granular.connect({
1511
+ * sandbox: 'my-sandbox',
1512
+ * user,
1513
+ * });
1514
+ *
1515
+ * // Publish tools
1516
+ * await environment.publishTools([
1517
+ * { name: 'greet', description: 'Say hello', inputSchema: {}, handler: async () => 'Hello!' },
1518
+ * ]);
1519
+ *
1520
+ * // Submit job
1521
+ * const job = await environment.submitJob(`
1522
+ * import { tools } from './sandbox-tools';
1523
+ * return await tools.greet({});
1524
+ * `);
1525
+ *
1526
+ * console.log(await job.result); // 'Hello!'
1527
+ * ```
1528
+ */
1529
+ async connect(options) {
1530
+ const clientId = `client_${Date.now()}`;
1531
+ const sandbox = await this.findOrCreateSandbox(options.sandbox);
1532
+ for (const profileName of options.user.permissions) {
1533
+ const profileId = await this.ensurePermissionProfile(sandbox.sandboxId, profileName);
1534
+ await this.ensureAssignment(options.user.subjectId, sandbox.sandboxId, profileId);
1535
+ }
1536
+ const envData = await this.environments.create(sandbox.sandboxId, {
1537
+ subjectId: options.user.subjectId,
1538
+ permissionProfileId: null
1539
+ });
1540
+ const client = new WSClient({
1541
+ url: this.apiUrl,
1542
+ sessionId: envData.environmentId,
1543
+ token: this.apiKey
1544
+ });
1545
+ await client.connect();
1546
+ const graphqlEndpoint = `${this.httpUrl}/orchestrator/graphql`;
1547
+ const environment = new Environment(client, envData, clientId, this.apiKey, graphqlEndpoint);
1548
+ await environment.hello();
1549
+ return environment;
1550
+ }
1551
+ /**
1552
+ * Find a sandbox by name or create it if it doesn't exist
1553
+ */
1554
+ async findOrCreateSandbox(nameOrId) {
1555
+ try {
1556
+ const sandbox = await this.sandboxes.get(nameOrId);
1557
+ return sandbox;
1558
+ } catch {
1559
+ const sandboxes = await this.sandboxes.list();
1560
+ const existing = sandboxes.items.find((s) => s.name === nameOrId);
1561
+ if (existing) {
1562
+ return existing;
1563
+ }
1564
+ const created = await this.sandboxes.create({ name: nameOrId });
1565
+ return created;
1566
+ }
1567
+ }
1568
+ /**
1569
+ * Ensure a permission profile exists for a sandbox, creating it if needed.
1570
+ * If profileName matches an existing profile name, returns its ID.
1571
+ * Otherwise, creates a new profile with default allow-all rules.
1572
+ */
1573
+ async ensurePermissionProfile(sandboxId, profileName) {
1574
+ try {
1575
+ const profiles = await this.permissionProfiles.list(sandboxId);
1576
+ const existing = profiles.find((p) => p.name === profileName);
1577
+ if (existing) {
1578
+ return existing.permissionProfileId;
1579
+ }
1580
+ } catch {
1581
+ }
1582
+ const created = await this.permissionProfiles.create(sandboxId, {
1583
+ name: profileName,
1584
+ rules: {
1585
+ tools: { allow: ["*"] },
1586
+ resources: { allow: ["*"] }
1587
+ }
1588
+ });
1589
+ return created.permissionProfileId;
1590
+ }
1591
+ /**
1592
+ * Ensure an assignment exists for a subject in a sandbox with a permission profile
1593
+ */
1594
+ async ensureAssignment(subjectId, sandboxId, permissionProfileId) {
1595
+ try {
1596
+ const assignments = await this.request(
1597
+ `/control/subjects/${subjectId}/assignments`
1598
+ );
1599
+ const existing = assignments.items.find(
1600
+ (a) => a.sandboxId === sandboxId
1601
+ );
1602
+ if (existing) {
1603
+ if (existing.permissionProfileId === permissionProfileId) {
1604
+ return;
1605
+ }
1606
+ await this.request(`/control/assignments/${existing.assignmentId}`, {
1607
+ method: "DELETE"
1608
+ });
1609
+ }
1610
+ } catch {
1611
+ }
1612
+ await this.request(`/control/subjects/${subjectId}/assignments`, {
1613
+ method: "POST",
1614
+ body: JSON.stringify({
1615
+ sandboxId,
1616
+ subjectId,
1617
+ permissionProfileId
1618
+ })
1619
+ });
1620
+ }
1621
+ /**
1622
+ * Sandbox management API
1623
+ */
1624
+ get sandboxes() {
1625
+ return {
1626
+ list: async () => {
1627
+ return this.request("/control/sandboxes");
1628
+ },
1629
+ get: async (id) => {
1630
+ return this.request(`/control/sandboxes/${id}`);
1631
+ },
1632
+ create: async (data) => {
1633
+ return this.request("/control/sandboxes", {
1634
+ method: "POST",
1635
+ body: JSON.stringify(data)
1636
+ });
1637
+ },
1638
+ update: async (id, data) => {
1639
+ return this.request(`/control/sandboxes/${id}`, {
1640
+ method: "PATCH",
1641
+ body: JSON.stringify(data)
1642
+ });
1643
+ },
1644
+ delete: async (id) => {
1645
+ return this.request(`/control/sandboxes/${id}`, {
1646
+ method: "DELETE"
1647
+ });
1648
+ }
1649
+ };
1650
+ }
1651
+ /**
1652
+ * Permission Profile management for sandboxes
1653
+ */
1654
+ get permissionProfiles() {
1655
+ return {
1656
+ list: async (sandboxId) => {
1657
+ const result = await this.request(
1658
+ `/control/sandboxes/${sandboxId}/permission-profiles`
1659
+ );
1660
+ return result.items;
1661
+ },
1662
+ get: async (sandboxId, profileId) => {
1663
+ return this.request(
1664
+ `/control/sandboxes/${sandboxId}/permission-profiles/${profileId}`
1665
+ );
1666
+ },
1667
+ create: async (sandboxId, data) => {
1668
+ return this.request(
1669
+ `/control/sandboxes/${sandboxId}/permission-profiles`,
1670
+ {
1671
+ method: "POST",
1672
+ body: JSON.stringify(data)
1673
+ }
1674
+ );
1675
+ },
1676
+ delete: async (sandboxId, profileId) => {
1677
+ return this.request(
1678
+ `/control/sandboxes/${sandboxId}/permission-profiles/${profileId}`,
1679
+ {
1680
+ method: "DELETE"
1681
+ }
1682
+ );
1683
+ }
1684
+ };
1685
+ }
1686
+ /**
1687
+ * Environment management
1688
+ */
1689
+ get environments() {
1690
+ return {
1691
+ list: async (sandboxId) => {
1692
+ const result = await this.request(
1693
+ `/control/sandboxes/${sandboxId}/environments`
1694
+ );
1695
+ return result.items;
1696
+ },
1697
+ get: async (environmentId) => {
1698
+ return this.request(`/control/environments/${environmentId}`);
1699
+ },
1700
+ create: async (sandboxId, data) => {
1701
+ return this.request(`/control/sandboxes/${sandboxId}/environments`, {
1702
+ method: "POST",
1703
+ body: JSON.stringify(data)
1704
+ });
1705
+ },
1706
+ delete: async (environmentId) => {
1707
+ return this.request(`/control/environments/${environmentId}`, {
1708
+ method: "DELETE"
1709
+ });
1710
+ }
1711
+ };
1712
+ }
1713
+ /**
1714
+ * Subject management
1715
+ */
1716
+ get subjects() {
1717
+ return {
1718
+ get: async (subjectId) => {
1719
+ return this.request(`/control/subjects/${subjectId}`);
1720
+ },
1721
+ listAssignments: async (subjectId) => {
1722
+ return this.request(`/control/subjects/${subjectId}/assignments`);
1723
+ }
1724
+ };
1725
+ }
1726
+ /**
1727
+ * @deprecated Use recordUser() instead
1728
+ */
1729
+ get users() {
1730
+ return {
1731
+ create: async (data) => {
1732
+ return this.request("/control/subjects", {
1733
+ method: "POST",
1734
+ body: JSON.stringify({
1735
+ identityId: data.id,
1736
+ name: data.name,
1737
+ email: data.email
1738
+ })
1739
+ });
1740
+ },
1741
+ get: async (id) => {
1742
+ return this.request(`/control/subjects/${id}`);
1743
+ }
1744
+ };
1745
+ }
1746
+ /**
1747
+ * Make an authenticated API request
1748
+ */
1749
+ async request(path, options = {}) {
1750
+ const url = `${this.httpUrl}${path}`;
1751
+ console.log(`[SDK] Requesting: ${url}`);
1752
+ const response = await fetch(url, {
1753
+ ...options,
1754
+ headers: {
1755
+ "Authorization": `Bearer ${this.apiKey}`,
1756
+ "Content-Type": "application/json",
1757
+ ...options.headers
1758
+ }
1759
+ });
1760
+ if (!response.ok) {
1761
+ const errorText = await response.text();
1762
+ throw new Error(`Granular API Error (${response.status}): ${errorText}`);
1763
+ }
1764
+ if (response.status === 204) {
1765
+ return { deleted: true };
1766
+ }
1767
+ return response.json();
1768
+ }
1769
+ };
1770
+
1771
+ export { Environment, Granular, Session, WSClient };
1772
+ //# sourceMappingURL=index.mjs.map
1773
+ //# sourceMappingURL=index.mjs.map