@tangle-network/sandbox 0.60.2 → 0.60.6

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.
Files changed (52) hide show
  1. package/README.md +2 -0
  2. package/dist/agent/index.d.ts +4 -4
  3. package/dist/agent/index.js +5 -5
  4. package/dist/agent/preview.d.ts +1 -1
  5. package/dist/agent/preview.js +2 -2
  6. package/dist/{agent-run-outcome-BDxby7zK.d.ts → agent-run-outcome-B7w8HpoL.d.ts} +1 -1
  7. package/dist/auth/index.d.ts +2 -2
  8. package/dist/auth/index.js +1 -1
  9. package/dist/{browser-interactive-control-controller-C2qVGzQz.d.ts → browser-interactive-control-controller-C-3MDol8.d.ts} +1 -1
  10. package/dist/{client-BFilDKO8.d.ts → client-AXO7ykS7.d.ts} +5 -5
  11. package/dist/{client-p2T45dAv.js → client-qSyPPokh.js} +84 -355
  12. package/dist/collaboration/index.d.ts +1 -1
  13. package/dist/collaboration/index.js +1 -1
  14. package/dist/{collaboration-C1JAl5kE.js → collaboration-B7QeBrFQ.js} +1 -1
  15. package/dist/core.d.ts +6 -6
  16. package/dist/core.js +4 -4
  17. package/dist/{errors-CKl_BSlD.js → errors-D1JIX7Jm.js} +13 -1
  18. package/dist/{index-DGuTeptP.d.ts → index-BPt77jdR.d.ts} +88 -3
  19. package/dist/index.d.ts +13 -13
  20. package/dist/index.js +7 -7
  21. package/dist/intelligence/index.js +1 -1
  22. package/dist/interactive-control.d.ts +1 -1
  23. package/dist/{interactive-controller-DV1HT3NR.js → interactive-controller-f_ePJqoh.js} +14 -8
  24. package/dist/{interactive-controller-Dghv9yMk.d.ts → interactive-controller-iYddZt8b.d.ts} +2 -2
  25. package/dist/{line-application-DJYY1v8U.js → line-application-C2SuT1zK.js} +24 -0
  26. package/dist/{lines-T2D6xHHx.d.ts → lines-ggdLY7xy.d.ts} +37 -12
  27. package/dist/lines.d.ts +2 -2
  28. package/dist/lines.js +4 -5
  29. package/dist/{local-cli-auth-CdIM0B6p.js → local-cli-auth-D4T4wi9r.js} +1 -1
  30. package/dist/{mcp-local-BSvH4yAU.js → mcp-local-DjryqUiY.js} +1 -1
  31. package/dist/{preview-ZaYvOOXz.d.ts → preview-CAiSrOuZ.d.ts} +3 -3
  32. package/dist/runtime.d.ts +6 -6
  33. package/dist/runtime.js +2 -2
  34. package/dist/{sandbox-DeE2MDx9.js → sandbox-DF2Z1lqW.js} +128 -558
  35. package/dist/{sandbox-LRvBzGGm.d.ts → sandbox-DsJ3ZJdA.d.ts} +5 -5
  36. package/dist/secp256k1-CyKOxB5J.js +2619 -0
  37. package/dist/session-gateway/index.d.ts +31 -25
  38. package/dist/session-gateway/index.js +75 -79
  39. package/dist/tangle/index.d.ts +2 -2
  40. package/dist/tangle/index.js +2 -2
  41. package/dist/tangle-CDtwGZtf.js +2847 -0
  42. package/dist/{types-C9w6MdZB.d.ts → types-BbgO-4f8.d.ts} +6 -2
  43. package/dist/utils-ChcSLv53.js +170 -0
  44. package/package.json +8 -7
  45. package/dist/tangle-SNShua9T.js +0 -1146
  46. /package/dist/{cli-auth-bundle-gs7xEnA1.d.ts → cli-auth-bundle-CTia4WWs.d.ts} +0 -0
  47. /package/dist/{cli-auth-bundle-ChOdvrjd.js → cli-auth-bundle-DzbqR2nA.js} +0 -0
  48. /package/dist/{errors-C6dll8Qf.d.ts → errors-DS32ViPj.d.ts} +0 -0
  49. /package/dist/{index-BKhRnV0i.d.ts → index-BXcL8P-U.d.ts} +0 -0
  50. /package/dist/{index-BSCz2Q0v.d.ts → index-BoQeoNOD.d.ts} +0 -0
  51. /package/dist/{preview-operations-BLsclF88.js → preview-operations-DqSo-IBm.js} +0 -0
  52. /package/dist/{terminal-stream-C9jxoB07.d.ts → terminal-stream-BUMu8Oae.d.ts} +0 -0
@@ -1,1146 +0,0 @@
1
- import { _ as parseErrorResponse } from "./errors-CKl_BSlD.js";
2
- import { n as createSandboxInstanceFromResponse } from "./sandbox-DeE2MDx9.js";
3
- //#region src/tangle/abi.ts
4
- /**
5
- * Tangle Contract ABI Definitions
6
- *
7
- * Viem-compatible ABI for the ITangleJobs precompile, the AgentSandbox
8
- * blueprint contract views/events, and ABI parameter definitions for
9
- * encoding/decoding blueprint job inputs and outputs.
10
- */
11
- const ITangleJobsAbi = [
12
- {
13
- type: "function",
14
- name: "submitJob",
15
- inputs: [
16
- {
17
- name: "serviceId",
18
- type: "uint64"
19
- },
20
- {
21
- name: "jobIndex",
22
- type: "uint8"
23
- },
24
- {
25
- name: "inputs",
26
- type: "bytes"
27
- }
28
- ],
29
- outputs: [{
30
- name: "callId",
31
- type: "uint64"
32
- }],
33
- stateMutability: "payable"
34
- },
35
- {
36
- type: "function",
37
- name: "getJobCall",
38
- inputs: [{
39
- name: "serviceId",
40
- type: "uint64"
41
- }, {
42
- name: "callId",
43
- type: "uint64"
44
- }],
45
- outputs: [{
46
- name: "",
47
- type: "tuple",
48
- components: [
49
- {
50
- name: "jobIndex",
51
- type: "uint8"
52
- },
53
- {
54
- name: "caller",
55
- type: "address"
56
- },
57
- {
58
- name: "createdAt",
59
- type: "uint64"
60
- },
61
- {
62
- name: "resultCount",
63
- type: "uint32"
64
- },
65
- {
66
- name: "payment",
67
- type: "uint256"
68
- },
69
- {
70
- name: "completed",
71
- type: "bool"
72
- }
73
- ]
74
- }],
75
- stateMutability: "view"
76
- },
77
- {
78
- type: "event",
79
- name: "JobSubmitted",
80
- inputs: [
81
- {
82
- name: "serviceId",
83
- type: "uint64",
84
- indexed: true
85
- },
86
- {
87
- name: "callId",
88
- type: "uint64",
89
- indexed: true
90
- },
91
- {
92
- name: "jobIndex",
93
- type: "uint8",
94
- indexed: false
95
- },
96
- {
97
- name: "caller",
98
- type: "address",
99
- indexed: false
100
- },
101
- {
102
- name: "inputs",
103
- type: "bytes",
104
- indexed: false
105
- }
106
- ]
107
- },
108
- {
109
- type: "event",
110
- name: "JobResultSubmitted",
111
- inputs: [
112
- {
113
- name: "serviceId",
114
- type: "uint64",
115
- indexed: true
116
- },
117
- {
118
- name: "callId",
119
- type: "uint64",
120
- indexed: true
121
- },
122
- {
123
- name: "operator",
124
- type: "address",
125
- indexed: true
126
- },
127
- {
128
- name: "result",
129
- type: "bytes",
130
- indexed: false
131
- }
132
- ]
133
- }
134
- ];
135
- const SandboxCreateParamTypes = [{
136
- name: "request",
137
- type: "tuple",
138
- components: [
139
- {
140
- name: "name",
141
- type: "string"
142
- },
143
- {
144
- name: "image",
145
- type: "string"
146
- },
147
- {
148
- name: "stack",
149
- type: "string"
150
- },
151
- {
152
- name: "agent_identifier",
153
- type: "string"
154
- },
155
- {
156
- name: "env_json",
157
- type: "string"
158
- },
159
- {
160
- name: "metadata_json",
161
- type: "string"
162
- },
163
- {
164
- name: "ssh_enabled",
165
- type: "bool"
166
- },
167
- {
168
- name: "ssh_public_key",
169
- type: "string"
170
- },
171
- {
172
- name: "web_terminal_enabled",
173
- type: "bool"
174
- },
175
- {
176
- name: "max_lifetime_seconds",
177
- type: "uint64"
178
- },
179
- {
180
- name: "idle_timeout_seconds",
181
- type: "uint64"
182
- },
183
- {
184
- name: "cpu_cores",
185
- type: "uint64"
186
- },
187
- {
188
- name: "memory_mb",
189
- type: "uint64"
190
- },
191
- {
192
- name: "disk_gb",
193
- type: "uint64"
194
- },
195
- {
196
- name: "tee_required",
197
- type: "bool"
198
- },
199
- {
200
- name: "tee_type",
201
- type: "uint8"
202
- },
203
- {
204
- name: "attestation_nonce",
205
- type: "string"
206
- },
207
- {
208
- name: "capabilities_json",
209
- type: "string"
210
- }
211
- ]
212
- }];
213
- const SandboxIdParamTypes = [{
214
- name: "request",
215
- type: "tuple",
216
- components: [{
217
- name: "sandbox_id",
218
- type: "string"
219
- }]
220
- }];
221
- const SandboxCreateResponseParamTypes = [{
222
- name: "response",
223
- type: "tuple",
224
- components: [{
225
- name: "sandboxId",
226
- type: "string"
227
- }, {
228
- name: "json",
229
- type: "string"
230
- }]
231
- }];
232
- const JsonResponseParamTypes = [{
233
- name: "response",
234
- type: "tuple",
235
- components: [{
236
- name: "json",
237
- type: "string"
238
- }]
239
- }];
240
- const AgentSandboxBlueprintAbi = [
241
- {
242
- type: "function",
243
- name: "getAvailableCapacity",
244
- inputs: [],
245
- outputs: [{
246
- name: "available",
247
- type: "uint32"
248
- }],
249
- stateMutability: "view"
250
- },
251
- {
252
- type: "function",
253
- name: "getServiceStats",
254
- inputs: [],
255
- outputs: [{
256
- name: "totalSandboxes",
257
- type: "uint32"
258
- }, {
259
- name: "totalCapacity",
260
- type: "uint32"
261
- }],
262
- stateMutability: "view"
263
- },
264
- {
265
- type: "function",
266
- name: "getOperatorLoad",
267
- inputs: [{
268
- name: "operator",
269
- type: "address"
270
- }],
271
- outputs: [{
272
- name: "active",
273
- type: "uint32"
274
- }, {
275
- name: "max",
276
- type: "uint32"
277
- }],
278
- stateMutability: "view"
279
- },
280
- {
281
- type: "function",
282
- name: "getSandboxOperator",
283
- inputs: [{
284
- name: "sandboxId",
285
- type: "string"
286
- }],
287
- outputs: [{
288
- name: "",
289
- type: "address"
290
- }],
291
- stateMutability: "view"
292
- },
293
- {
294
- type: "function",
295
- name: "isSandboxActive",
296
- inputs: [{
297
- name: "sandboxId",
298
- type: "string"
299
- }],
300
- outputs: [{
301
- name: "",
302
- type: "bool"
303
- }],
304
- stateMutability: "view"
305
- },
306
- {
307
- type: "event",
308
- name: "OperatorAssigned",
309
- inputs: [
310
- {
311
- name: "serviceId",
312
- type: "uint64",
313
- indexed: true
314
- },
315
- {
316
- name: "callId",
317
- type: "uint64",
318
- indexed: true
319
- },
320
- {
321
- name: "operator",
322
- type: "address",
323
- indexed: true
324
- }
325
- ]
326
- },
327
- {
328
- type: "event",
329
- name: "OperatorRouted",
330
- inputs: [
331
- {
332
- name: "serviceId",
333
- type: "uint64",
334
- indexed: true
335
- },
336
- {
337
- name: "callId",
338
- type: "uint64",
339
- indexed: true
340
- },
341
- {
342
- name: "operator",
343
- type: "address",
344
- indexed: true
345
- }
346
- ]
347
- },
348
- {
349
- type: "event",
350
- name: "SandboxCreated",
351
- inputs: [{
352
- name: "sandboxHash",
353
- type: "bytes32",
354
- indexed: true
355
- }, {
356
- name: "operator",
357
- type: "address",
358
- indexed: true
359
- }]
360
- },
361
- {
362
- type: "event",
363
- name: "SandboxDeleted",
364
- inputs: [{
365
- name: "sandboxHash",
366
- type: "bytes32",
367
- indexed: true
368
- }, {
369
- name: "operator",
370
- type: "address",
371
- indexed: true
372
- }]
373
- }
374
- ];
375
- //#endregion
376
- //#region src/tangle/types.ts
377
- /**
378
- * Tangle Sandbox Client types and constants.
379
- */
380
- /** Tangle mainnet chain ID. */
381
- const TANGLE_CHAIN_ID = 5845;
382
- /** ITangleJobs precompile contract address. */
383
- const TANGLE_JOBS_CONTRACT = "0x0000000000000000000000000000000000000808";
384
- /** Job indices matching the blueprint's job IDs. */
385
- const JOB_SANDBOX_CREATE = 0;
386
- const JOB_SANDBOX_DELETE = 1;
387
- //#endregion
388
- //#region src/tangle/chain-client.ts
389
- function confidentialFromOptions(options) {
390
- if (options.confidential) return options.confidential;
391
- const profile = options.backend?.profile;
392
- if (typeof profile === "object" && profile?.confidential) return profile.confidential;
393
- }
394
- function teeTypeId(tee) {
395
- switch (tee) {
396
- case "tdx":
397
- case "phala-dstack": return 1;
398
- case "nitro": return 2;
399
- case "sev-snp": return 3;
400
- case "any":
401
- case void 0: return 0;
402
- default: throw new Error(`Unsupported TEE type for Tangle blueprint: ${tee}`);
403
- }
404
- }
405
- function teeCreateValues(options) {
406
- const confidential = confidentialFromOptions(options);
407
- const teeRequired = Boolean(confidential?.tee);
408
- return [
409
- teeRequired,
410
- teeRequired ? teeTypeId(confidential?.tee) : 0,
411
- confidential?.attestationNonce ?? ""
412
- ];
413
- }
414
- var TangleChainClient = class {
415
- config;
416
- publicClient = null;
417
- walletClient = null;
418
- account = null;
419
- constructor(config) {
420
- this.config = config;
421
- }
422
- async ensureInitialized() {
423
- if (this.publicClient && this.walletClient) return {
424
- publicClient: this.publicClient,
425
- walletClient: this.walletClient
426
- };
427
- const rpcUrl = this.config.rpcUrl;
428
- if (typeof rpcUrl !== "string" || rpcUrl.trim().length === 0) throw new Error("TangleSandboxClient requires rpcUrl: the SDK has no default Tangle RPC endpoint");
429
- let viem;
430
- try {
431
- viem = await import("viem");
432
- } catch {
433
- throw new Error("viem is required for TangleSandboxClient. Install it: npm install viem");
434
- }
435
- const chain = {
436
- id: TANGLE_CHAIN_ID,
437
- name: "Tangle",
438
- nativeCurrency: {
439
- name: "TNT",
440
- symbol: "TNT",
441
- decimals: 18
442
- },
443
- rpcUrls: { default: { http: [rpcUrl] } }
444
- };
445
- const transport = viem.http(rpcUrl);
446
- this.publicClient = viem.createPublicClient({
447
- chain,
448
- transport
449
- });
450
- if (this.config.privateKey) {
451
- const { privateKeyToAccount } = await import("viem/accounts");
452
- this.account = privateKeyToAccount(this.config.privateKey);
453
- this.walletClient = viem.createWalletClient({
454
- account: this.account,
455
- chain,
456
- transport
457
- });
458
- } else if (this.config.wallet) {
459
- const wallet = this.config.wallet;
460
- this.walletClient = wallet;
461
- this.account = wallet.account ?? null;
462
- } else throw new Error("TangleSandboxClient requires either privateKey or wallet");
463
- return {
464
- publicClient: this.publicClient,
465
- walletClient: this.walletClient
466
- };
467
- }
468
- encodeSandboxCreateInputs(options) {
469
- if ((options.sshPublicKeys?.length ?? 0) > 1) throw new Error("Tangle sandbox creation accepts one SSH public key; pass at most one sshPublicKeys entry");
470
- const [teeRequired, teeType, attestationNonce] = teeCreateValues(options);
471
- return {
472
- types: SandboxCreateParamTypes,
473
- values: [{
474
- name: options.name ?? "",
475
- image: options.environment ?? "",
476
- stack: "",
477
- agent_identifier: "",
478
- env_json: options.env ? JSON.stringify(options.env) : "",
479
- metadata_json: options.metadata ? JSON.stringify(options.metadata) : "",
480
- ssh_enabled: options.sshEnabled ?? false,
481
- ssh_public_key: options.sshPublicKeys?.[0] ?? "",
482
- web_terminal_enabled: options.webTerminalEnabled ?? false,
483
- max_lifetime_seconds: BigInt(options.maxLifetimeSeconds ?? 0),
484
- idle_timeout_seconds: BigInt(options.idleTimeoutSeconds ?? 0),
485
- cpu_cores: BigInt(options.resources?.cpuCores ?? 0),
486
- memory_mb: BigInt(options.resources?.memoryMB ?? 0),
487
- disk_gb: BigInt(options.resources?.diskGB ?? 0),
488
- tee_required: teeRequired,
489
- tee_type: teeType,
490
- attestation_nonce: attestationNonce,
491
- capabilities_json: options.capabilities?.length ? JSON.stringify(options.capabilities) : ""
492
- }]
493
- };
494
- }
495
- encodeSandboxIdInputs(sandboxId) {
496
- return {
497
- types: SandboxIdParamTypes,
498
- values: [{ sandbox_id: sandboxId }]
499
- };
500
- }
501
- async submitJobAndWait(jobIndex, encoded) {
502
- const { publicClient, walletClient } = await this.ensureInitialized();
503
- const viem = await import("viem");
504
- const contractAddress = this.config.contractAddress ?? "0x0000000000000000000000000000000000000808";
505
- const serviceId = this.config.serviceId;
506
- const inputs = viem.encodeAbiParameters(encoded.types, encoded.values);
507
- const hash = await walletClient.writeContract({
508
- address: contractAddress,
509
- abi: ITangleJobsAbi,
510
- functionName: "submitJob",
511
- args: [
512
- serviceId,
513
- jobIndex,
514
- inputs
515
- ]
516
- });
517
- const receipt = await publicClient.waitForTransactionReceipt({ hash });
518
- const jobSubmittedEvent = receipt.logs.find((log) => {
519
- try {
520
- return viem.decodeEventLog({
521
- abi: ITangleJobsAbi,
522
- data: log.data,
523
- topics: log.topics
524
- }).eventName === "JobSubmitted";
525
- } catch {
526
- return false;
527
- }
528
- });
529
- if (!jobSubmittedEvent) throw new Error("JobSubmitted event not found in transaction receipt");
530
- const callId = viem.decodeEventLog({
531
- abi: ITangleJobsAbi,
532
- data: jobSubmittedEvent.data,
533
- topics: jobSubmittedEvent.topics
534
- }).args.callId;
535
- const timeoutMs = this.config.jobTimeoutMs ?? 144e5;
536
- const pollIntervalMs = this.config.pollIntervalMs ?? 5e3;
537
- const deadline = Date.now() + timeoutMs;
538
- while (Date.now() < deadline) {
539
- await new Promise((resolve) => setTimeout(resolve, pollIntervalMs));
540
- const jobCall = await publicClient.readContract({
541
- address: contractAddress,
542
- abi: ITangleJobsAbi,
543
- functionName: "getJobCall",
544
- args: [serviceId, callId]
545
- });
546
- if (jobCall.completed) return {
547
- result: jobCall,
548
- callId,
549
- blockNumber: receipt.blockNumber
550
- };
551
- }
552
- throw new Error(`Job ${jobIndex} (callId=${callId}) did not complete within ${timeoutMs}ms`);
553
- }
554
- async getJobResult(callId, fromBlock) {
555
- const { publicClient } = await this.ensureInitialized();
556
- const viem = await import("viem");
557
- const contractAddress = this.config.contractAddress ?? "0x0000000000000000000000000000000000000808";
558
- const logs = await publicClient.getLogs({
559
- address: contractAddress,
560
- event: viem.parseAbiItem("event JobResultSubmitted(uint64 indexed serviceId, uint64 indexed callId, address indexed operator, bytes result)"),
561
- args: {
562
- serviceId: this.config.serviceId,
563
- callId
564
- },
565
- fromBlock: fromBlock ?? "earliest"
566
- });
567
- if (logs.length === 0) return null;
568
- return logs[0]?.args.result ?? null;
569
- }
570
- async getAvailableCapacity() {
571
- const { publicClient } = await this.ensureInitialized();
572
- if (!this.config.blueprintContractAddress) throw new Error("blueprintContractAddress is required for getAvailableCapacity");
573
- const result = await publicClient.readContract({
574
- address: this.config.blueprintContractAddress,
575
- abi: AgentSandboxBlueprintAbi,
576
- functionName: "getAvailableCapacity"
577
- });
578
- return Number(result);
579
- }
580
- async getServiceStats() {
581
- const { publicClient } = await this.ensureInitialized();
582
- if (!this.config.blueprintContractAddress) throw new Error("blueprintContractAddress is required for getServiceStats");
583
- const [totalSandboxes, totalCapacity] = await publicClient.readContract({
584
- address: this.config.blueprintContractAddress,
585
- abi: AgentSandboxBlueprintAbi,
586
- functionName: "getServiceStats"
587
- });
588
- return {
589
- totalSandboxes: Number(totalSandboxes),
590
- totalCapacity: Number(totalCapacity)
591
- };
592
- }
593
- getResponseParamTypes(jobIndex) {
594
- if (jobIndex === 0) return SandboxCreateResponseParamTypes;
595
- return JsonResponseParamTypes;
596
- }
597
- /**
598
- * Sign a message with the job submitter's key (EIP-191 personal_sign).
599
- *
600
- * This is the credential for the operator API's session flow: the operator
601
- * recovers the signer address and binds it to sandbox ownership, so only
602
- * the key that submitted the create job can mint a session that manages
603
- * that sandbox's secrets.
604
- */
605
- async signMessage(message) {
606
- await this.ensureInitialized();
607
- const account = this.account;
608
- if (!account) throw new Error("TangleChainClient has no account to sign with; privateKey or wallet is required");
609
- if (this.config.privateKey) {
610
- if (typeof account.signMessage !== "function") throw new Error("Configured account cannot sign messages; an EIP-191 signer is required for operator sessions");
611
- return account.signMessage({ message });
612
- }
613
- const walletClient = this.walletClient;
614
- if (!walletClient) throw new Error("TangleChainClient has no wallet client; privateKey or wallet is required");
615
- return walletClient.signMessage({
616
- account,
617
- message
618
- });
619
- }
620
- };
621
- //#endregion
622
- //#region src/tangle/operator-auth.ts
623
- const SESSION_REFRESH_MARGIN_MS = 6e4;
624
- var OperatorSessionError = class extends Error {
625
- constructor(message, status) {
626
- super(message);
627
- this.status = status;
628
- this.name = "OperatorSessionError";
629
- }
630
- };
631
- /**
632
- * A bearer session with the blueprint operator API, minted by proving control
633
- * of the job submitter's key. Establish lazily and reuse until near expiry;
634
- * the caller retries with a fresh session on 401.
635
- */
636
- var OperatorSession = class OperatorSession {
637
- constructor(token, address, expiresAtMs) {
638
- this.token = token;
639
- this.address = address;
640
- this.expiresAtMs = expiresAtMs;
641
- }
642
- get signerAddress() {
643
- return this.address;
644
- }
645
- /** True when the token is within the refresh margin of expiry. */
646
- needsRefresh(nowMs = Date.now()) {
647
- return nowMs >= this.expiresAtMs - SESSION_REFRESH_MARGIN_MS;
648
- }
649
- authorizationHeader() {
650
- return `Bearer ${this.token}`;
651
- }
652
- /**
653
- * Run the challenge-response flow against an operator API base URL.
654
- *
655
- * `signMessage` must implement EIP-191 personal_sign with the SAME key that
656
- * submitted the sandbox create job — the operator binds ownership to the
657
- * recovered address, so any other key yields a session that owns nothing.
658
- */
659
- static async establish(baseUrl, signMessage, fetchImpl = fetch) {
660
- const root = baseUrl.replace(/\/+$/, "");
661
- const challengeResponse = await fetchImpl(`${root}/api/auth/challenge`, { method: "POST" });
662
- if (!challengeResponse.ok) throw new OperatorSessionError(`Operator challenge failed (HTTP ${challengeResponse.status})`, challengeResponse.status);
663
- const challenge = await challengeResponse.json();
664
- if (!challenge?.nonce || !challenge?.message) throw new OperatorSessionError("Operator challenge response is missing nonce/message");
665
- const signature = await signMessage(challenge.message);
666
- const sessionResponse = await fetchImpl(`${root}/api/auth/session`, {
667
- method: "POST",
668
- headers: { "Content-Type": "application/json" },
669
- body: JSON.stringify({
670
- nonce: challenge.nonce,
671
- signature
672
- })
673
- });
674
- if (!sessionResponse.ok) {
675
- const body = await sessionResponse.text().catch(() => "");
676
- throw new OperatorSessionError(`Operator session rejected (HTTP ${sessionResponse.status}): ${body.slice(0, 200)}`, sessionResponse.status);
677
- }
678
- const session = await sessionResponse.json();
679
- if (!session?.token) throw new OperatorSessionError("Operator session response is missing a token");
680
- return new OperatorSession(session.token, session.address, session.expires_at * 1e3);
681
- }
682
- };
683
- //#endregion
684
- //#region src/tangle/client.ts
685
- /**
686
- * TangleSandboxClient — on-chain sandbox lifecycle via EVM calls.
687
- *
688
- * Implements HttpClient so `SandboxInstance` works unchanged. Lifecycle
689
- * operations (create/stop/resume/delete) go on-chain via Tangle jobs, and
690
- * runtime operations are routed directly to the sandbox runtime URL
691
- * returned by the on-chain job result.
692
- */
693
- function randomHexToken(bytes) {
694
- if (typeof globalThis.crypto === "undefined" || typeof globalThis.crypto.getRandomValues !== "function") throw new Error("randomHexToken: globalThis.crypto.getRandomValues is unavailable; this runtime cannot generate cryptographically secure nonces. Run on a host with WebCrypto support (Node 20+, browsers, Workers).");
695
- const buf = new Uint8Array(bytes);
696
- globalThis.crypto.getRandomValues(buf);
697
- return Array.from(buf).map((b) => b.toString(16).padStart(2, "0")).join("");
698
- }
699
- /** Key names that look like credentials. Heuristic, deliberately loud-but-not-blocking. */
700
- const SECRET_SHAPED_KEY = /(?:secret|token|password|passwd|api[_-]?key|private[_-]?key|credential)/i;
701
- /**
702
- * `env` on the Tangle driver is ABI-encoded into the job calldata and is
703
- * public on-chain forever. Warn (not block) when a key looks like a
704
- * credential so the common mistake surfaces at the call site instead of on
705
- * a block explorer.
706
- */
707
- function warnSecretShapedEnvKeys(env) {
708
- if (!env) return;
709
- const offenders = Object.keys(env).filter((key) => SECRET_SHAPED_KEY.test(key));
710
- if (offenders.length === 0) return;
711
- console.warn(`[tangle-sandbox] These env keys are published on-chain in the job calldata and are permanently public: ${offenders.join(", ")}. Pass confidential values via create({ tangleSecrets }) instead (requires operatorApiUrl; delivered over TLS via the operator's 2-phase secret endpoint).`);
712
- }
713
- function attestationNonceFromOptions(options) {
714
- const direct = options.confidential?.attestationNonce;
715
- if (direct) return direct;
716
- const profile = options.backend?.profile;
717
- if (typeof profile === "object") return profile.confidential?.attestationNonce;
718
- }
719
- function withAttestationNonce(options) {
720
- if (options.confidential?.attestationRefresh && !options.confidential.attestationNonce) return {
721
- ...options,
722
- confidential: {
723
- ...options.confidential,
724
- attestationNonce: randomHexToken(32)
725
- }
726
- };
727
- const profile = options.backend?.profile;
728
- if (options.backend && typeof profile === "object" && profile.confidential?.attestationRefresh && !profile.confidential.attestationNonce) return {
729
- ...options,
730
- backend: {
731
- ...options.backend,
732
- profile: {
733
- ...profile,
734
- confidential: {
735
- ...profile.confidential,
736
- attestationNonce: randomHexToken(32)
737
- }
738
- }
739
- }
740
- };
741
- return options;
742
- }
743
- function requirePathGroup(match, index) {
744
- const value = match[index];
745
- if (value === void 0) throw new Error(`Path matcher missing group ${index}`);
746
- return value;
747
- }
748
- /** Narrow one field of already-parsed JSON to a record without widening
749
- * the boundary to `unknown`. */
750
- function recordField(raw, key) {
751
- const value = raw[key];
752
- return value && typeof value === "object" ? value : void 0;
753
- }
754
- function readString(record, keys) {
755
- if (!record) return void 0;
756
- for (const key of keys) {
757
- const value = record[key];
758
- if (typeof value === "string" && value.length > 0) return value;
759
- }
760
- }
761
- /** The incarnation fields are one contract, not three independent hints. */
762
- function classifyFilesystemIncarnation(value) {
763
- const rawId = value.filesystemIncarnationId;
764
- const rawProvenance = value.filesystemIncarnationProvenance;
765
- const rawReadiness = value.filesystemIncarnationReadiness;
766
- const id = typeof rawId === "string" && rawId.length > 0 ? rawId : void 0;
767
- const provenance = rawProvenance === "fresh" || rawProvenance === "restored" || rawProvenance === "unknown" ? rawProvenance : void 0;
768
- const readiness = rawReadiness === "transitioning" || rawReadiness === "ready" ? rawReadiness : void 0;
769
- return {
770
- complete: id !== void 0 && provenance !== void 0 && readiness !== void 0,
771
- id,
772
- provenance,
773
- readiness
774
- };
775
- }
776
- function runtimeCredentialsAllowed(incarnation) {
777
- return incarnation.complete && incarnation.readiness === "ready";
778
- }
779
- function entryMetadata(entry) {
780
- const metadata = {
781
- ...entry.metadata ?? {},
782
- ...entry.teeAttestationJson ? { teeAttestationJson: entry.teeAttestationJson } : {},
783
- ...entry.teePublicKeyJson ? { teePublicKeyJson: entry.teePublicKeyJson } : {},
784
- ...entry.attestationNonce ? { attestationNonce: entry.attestationNonce } : {}
785
- };
786
- return Object.keys(metadata).length > 0 ? metadata : void 0;
787
- }
788
- function sandboxInfoFromEntry(entry) {
789
- const incarnation = classifyFilesystemIncarnation(entry);
790
- const allowRuntime = runtimeCredentialsAllowed(incarnation);
791
- return {
792
- id: entry.id,
793
- name: entry.name,
794
- filesystemIncarnationId: incarnation.complete ? incarnation.id : void 0,
795
- filesystemIncarnationProvenance: incarnation.complete ? incarnation.provenance : void 0,
796
- filesystemIncarnationReadiness: incarnation.complete ? incarnation.readiness : void 0,
797
- status: entry.status === "deleted" ? "stopped" : entry.status,
798
- connection: allowRuntime && entry.runtimeUrl ? {
799
- runtimeUrl: entry.runtimeUrl,
800
- authToken: entry.runtimeToken
801
- } : void 0,
802
- metadata: entryMetadata(entry),
803
- createdAt: entry.createdAt
804
- };
805
- }
806
- function sandboxEntryFromWire(fallbackId, raw) {
807
- const connection = recordField(raw, "connection");
808
- const metadata = recordField(raw, "metadata");
809
- const id = readString(raw, [
810
- "id",
811
- "sandboxId",
812
- "sandbox_id"
813
- ]) ?? fallbackId;
814
- const runtimeUrl = readString(connection, ["runtimeUrl", "sidecar_url"]) ?? readString(raw, ["runtimeUrl", "sidecar_url"]) ?? "";
815
- const runtimeToken = readString(connection, ["authToken", "runtimeToken"]) ?? readString(raw, [
816
- "authToken",
817
- "runtimeToken",
818
- "token"
819
- ]) ?? "";
820
- const tupleField = (key) => {
821
- const value = raw[key];
822
- return typeof value === "string" ? value : value;
823
- };
824
- const tupleId = tupleField("filesystemIncarnationId") === void 0 ? void 0 : typeof tupleField("filesystemIncarnationId") === "string" ? tupleField("filesystemIncarnationId") : "";
825
- const tupleProvenance = tupleField("filesystemIncarnationProvenance") === void 0 ? void 0 : tupleField("filesystemIncarnationProvenance");
826
- const tupleReadiness = tupleField("filesystemIncarnationReadiness") === void 0 ? void 0 : tupleField("filesystemIncarnationReadiness");
827
- const rawStatus = readString(raw, ["status"]) ?? "running";
828
- const createdAtRaw = readString(raw, ["createdAt", "created_at"]);
829
- const createdAt = createdAtRaw ? new Date(createdAtRaw) : /* @__PURE__ */ new Date();
830
- return {
831
- id,
832
- name: readString(raw, ["name"]),
833
- filesystemIncarnationId: tupleId,
834
- filesystemIncarnationProvenance: tupleProvenance,
835
- filesystemIncarnationReadiness: tupleReadiness,
836
- runtimeUrl,
837
- runtimeToken,
838
- status: rawStatus === "stopped" || rawStatus === "deleted" || rawStatus === "running" ? rawStatus : "running",
839
- createdAt,
840
- metadata,
841
- teeAttestationJson: readString(raw, ["teeAttestationJson"]),
842
- teePublicKeyJson: readString(raw, ["teePublicKeyJson"]),
843
- attestationNonce: readString(raw, ["attestationNonce"])
844
- };
845
- }
846
- var TangleSandboxClient = class {
847
- chain;
848
- sandboxes = /* @__PURE__ */ new Map();
849
- operatorApiUrl;
850
- operatorApiToken;
851
- operatorSession = null;
852
- constructor(config) {
853
- if (!config.privateKey && !config.wallet) throw new Error("TangleSandboxClient requires either privateKey or wallet");
854
- this.chain = new TangleChainClient(config);
855
- this.operatorApiUrl = config.operatorApiUrl?.replace(/\/+$/, "");
856
- this.operatorApiToken = config.operatorApiToken;
857
- }
858
- /**
859
- * Create a sandbox via on-chain job submission.
860
- *
861
- * Secrets never ride the chain: `options.tangleSecrets` is delivered to the
862
- * operator's 2-phase provisioning endpoint over an EIP-191-authenticated
863
- * session after the job completes (requires `operatorApiUrl`). Everything
864
- * in `options.env` IS published on-chain in the job calldata — secret-shaped
865
- * keys there trigger a warning pointing at `tangleSecrets`.
866
- */
867
- async create(options) {
868
- if (options?.billingOwnerId !== void 0) throw new Error("billingOwnerId is supported only by the HTTP Sandbox API client");
869
- warnSecretShapedEnvKeys(options?.env);
870
- const tangleSecrets = options?.tangleSecrets;
871
- if (tangleSecrets && Object.keys(tangleSecrets).length > 0) {
872
- if (!this.operatorApiUrl) throw new Error("tangleSecrets requires operatorApiUrl: secrets are delivered via the operator's 2-phase provisioning endpoint, never via on-chain calldata. Configure operatorApiUrl, or pass the values as plain env only if they are NOT confidential (env_json is public on-chain forever).");
873
- }
874
- const createOptions = withAttestationNonce(options ?? {});
875
- const encoded = this.chain.encodeSandboxCreateInputs(createOptions);
876
- const { result: _result, callId, blockNumber } = await this.chain.submitJobAndWait(0, encoded);
877
- const resultBytes = await this.chain.getJobResult(callId, blockNumber);
878
- let sandboxId;
879
- let responseJson = {};
880
- if (resultBytes) try {
881
- const [decoded] = (await import("viem")).decodeAbiParameters(this.chain.getResponseParamTypes(0), resultBytes);
882
- const decodedEntry = decoded;
883
- sandboxId = decodedEntry.sandboxId;
884
- try {
885
- responseJson = JSON.parse(decodedEntry.json);
886
- } catch {}
887
- } catch {
888
- throw new Error("Failed to decode create job result");
889
- }
890
- else throw new Error("No result returned from create job");
891
- const wireEntry = sandboxEntryFromWire(sandboxId, responseJson);
892
- if (wireEntry.runtimeUrl && !wireEntry.runtimeToken) throw new Error("Create job returned a runtime URL without an auth token");
893
- const allowRuntime = runtimeCredentialsAllowed(classifyFilesystemIncarnation(wireEntry));
894
- const entry = {
895
- ...wireEntry,
896
- id: sandboxId,
897
- name: options?.name ?? wireEntry.name,
898
- runtimeUrl: allowRuntime ? wireEntry.runtimeUrl : "",
899
- runtimeToken: allowRuntime ? wireEntry.runtimeToken : "",
900
- status: wireEntry.status,
901
- createdAt: wireEntry.createdAt,
902
- metadata: createOptions.metadata ?? wireEntry.metadata,
903
- teeAttestationJson: wireEntry.teeAttestationJson ?? responseJson.teeAttestationJson,
904
- teePublicKeyJson: wireEntry.teePublicKeyJson ?? responseJson.teePublicKeyJson,
905
- attestationNonce: attestationNonceFromOptions(createOptions) ?? wireEntry.attestationNonce
906
- };
907
- this.sandboxes.set(sandboxId, entry);
908
- if (tangleSecrets && Object.keys(tangleSecrets).length > 0) await this.injectSecrets(sandboxId, tangleSecrets);
909
- return createSandboxInstanceFromResponse(this, sandboxInfoFromEntry(entry));
910
- }
911
- /**
912
- * Get a sandbox by id. Rehydrates from the operator API when configured so
913
- * app servers can resolve sandboxes created by earlier requests.
914
- */
915
- async get(id) {
916
- const response = await this.fetch(`/v1/sandboxes/${encodeURIComponent(id)}`);
917
- if (response.status === 404) return null;
918
- if (!response.ok) {
919
- const body = await response.text();
920
- throw parseErrorResponse(response.status, body, void 0, response.headers);
921
- }
922
- const data = await response.json();
923
- return createSandboxInstanceFromResponse(this, sandboxInfoFromEntry(sandboxEntryFromWire(id, data)));
924
- }
925
- /**
926
- * Route interception for SandboxInstance lifecycle calls.
927
- *
928
- * SandboxInstance calls this.client.fetch() for:
929
- * - GET /v1/sandboxes/:id → return from local tracking
930
- * - POST /v1/sandboxes/:id/stop → unsupported until blueprint exposes stop
931
- * - POST /v1/sandboxes/:id/resume → unsupported until blueprint exposes resume
932
- * - DELETE /v1/sandboxes/:id → on-chain JOB_SANDBOX_DELETE
933
- */
934
- async fetch(path, options) {
935
- const method = options?.method ?? "GET";
936
- const runtimeMatch = path.match(/^\/v1\/sandboxes\/([^/]+)\/runtime(\/.*)$/);
937
- if (runtimeMatch) {
938
- const id = decodeURIComponent(requirePathGroup(runtimeMatch, 1));
939
- const runtimePath = requirePathGroup(runtimeMatch, 2);
940
- return this.fetchRuntime(id, runtimePath, options);
941
- }
942
- const getMatch = path.match(/^\/v1\/sandboxes\/([^/]+)$/);
943
- if (getMatch && method === "GET") {
944
- const id = decodeURIComponent(requirePathGroup(getMatch, 1));
945
- let entry = this.sandboxes.get(id);
946
- if (this.operatorApiUrl) {
947
- const operatorResponse = await this.fetchOperatorApi(`/api/sandboxes/${encodeURIComponent(id)}`, { method: "GET" });
948
- if (!operatorResponse.ok) return operatorResponse;
949
- entry = sandboxEntryFromWire(id, await operatorResponse.json());
950
- this.sandboxes.set(entry.id, entry);
951
- }
952
- if (!entry) return new Response(JSON.stringify({ error: "Not found" }), { status: 404 });
953
- const info = sandboxInfoFromEntry(entry);
954
- return new Response(JSON.stringify(info), {
955
- status: 200,
956
- headers: { "Content-Type": "application/json" }
957
- });
958
- }
959
- const attestationMatch = path.match(/^\/v1\/sandboxes\/([^/]+)\/tee\/attestation$/);
960
- if (attestationMatch && method === "GET") {
961
- const id = decodeURIComponent(requirePathGroup(attestationMatch, 1));
962
- if (this.operatorApiUrl) return this.fetchOperatorApi(`/api/sandboxes/${encodeURIComponent(id)}/tee/attestation`, options);
963
- const response = await this.fetchRuntime(id, "/tee/attestation", {
964
- ...options,
965
- method: "GET"
966
- });
967
- if (!response.ok) return response;
968
- const attestation = await response.json();
969
- return new Response(JSON.stringify({
970
- sandbox_id: id,
971
- attestation
972
- }), {
973
- status: 200,
974
- headers: { "Content-Type": "application/json" }
975
- });
976
- }
977
- if (attestationMatch && method === "POST") {
978
- if (this.operatorApiUrl) {
979
- const id = decodeURIComponent(requirePathGroup(attestationMatch, 1));
980
- return this.fetchOperatorApi(`/api/sandboxes/${encodeURIComponent(id)}/tee/attestation`, options);
981
- }
982
- return new Response(JSON.stringify({ error: "Nonce-bound TEE attestation requires the operator API and is not available through the direct sidecar Tangle client" }), {
983
- status: 501,
984
- headers: { "Content-Type": "application/json" }
985
- });
986
- }
987
- const publicKeyMatch = path.match(/^\/v1\/sandboxes\/([^/]+)\/tee\/public-key$/);
988
- if (publicKeyMatch && method === "GET") {
989
- const id = decodeURIComponent(requirePathGroup(publicKeyMatch, 1));
990
- if (this.operatorApiUrl) return this.fetchOperatorApi(`/api/sandboxes/${encodeURIComponent(id)}/tee/public-key`, options);
991
- const response = await this.fetchRuntime(id, "/tee/public-key", {
992
- ...options,
993
- method: "GET"
994
- });
995
- if (!response.ok) return response;
996
- const publicKey = await response.json();
997
- return new Response(JSON.stringify({
998
- sandbox_id: id,
999
- public_key: publicKey
1000
- }), {
1001
- status: 200,
1002
- headers: { "Content-Type": "application/json" }
1003
- });
1004
- }
1005
- if (path.match(/^\/v1\/sandboxes\/([^/]+)\/stop$/) && method === "POST") return new Response(JSON.stringify({ error: "Sandbox stop is not exposed by the current Tangle blueprint" }), {
1006
- status: 501,
1007
- headers: { "Content-Type": "application/json" }
1008
- });
1009
- if (path.match(/^\/v1\/sandboxes\/([^/]+)\/resume$/) && method === "POST") return new Response(JSON.stringify({ error: "Sandbox resume is not exposed by the current Tangle blueprint" }), {
1010
- status: 501,
1011
- headers: { "Content-Type": "application/json" }
1012
- });
1013
- const deleteMatch = path.match(/^\/v1\/sandboxes\/([^/]+)$/);
1014
- if (deleteMatch && method === "DELETE") {
1015
- const id = decodeURIComponent(requirePathGroup(deleteMatch, 1));
1016
- const encoded = this.chain.encodeSandboxIdInputs(id);
1017
- await this.chain.submitJobAndWait(1, encoded);
1018
- const entry = this.sandboxes.get(id);
1019
- if (entry) entry.status = "deleted";
1020
- this.sandboxes.delete(id);
1021
- return new Response(null, { status: 204 });
1022
- }
1023
- throw new Error(`Operation not supported via on-chain client: ${method} ${path}`);
1024
- }
1025
- async fetchRuntime(sandboxId, runtimePath, options) {
1026
- let entry = this.sandboxes.get(sandboxId);
1027
- if (this.operatorApiUrl) {
1028
- const operatorResponse = await this.fetchOperatorApi(`/api/sandboxes/${encodeURIComponent(sandboxId)}`, { method: "GET" });
1029
- if (!operatorResponse.ok) return operatorResponse;
1030
- entry = sandboxEntryFromWire(sandboxId, await operatorResponse.json());
1031
- this.sandboxes.set(entry.id, entry);
1032
- }
1033
- const incarnation = entry ? classifyFilesystemIncarnation(entry) : void 0;
1034
- if (!entry || !incarnation || !runtimeCredentialsAllowed(incarnation) || !entry.runtimeUrl || !entry.runtimeToken) return new Response(JSON.stringify({ error: "Sandbox runtime unavailable" }), {
1035
- status: 503,
1036
- headers: { "Content-Type": "application/json" }
1037
- });
1038
- const headers = new Headers(options?.headers);
1039
- headers.set("Authorization", `Bearer ${entry.runtimeToken}`);
1040
- const isFormDataBody = typeof FormData !== "undefined" && options?.body instanceof FormData;
1041
- if (!headers.has("Content-Type") && !isFormDataBody) headers.set("Content-Type", "application/json");
1042
- const method = options?.method ?? "GET";
1043
- return await fetch(`${entry.runtimeUrl.replace(/\/$/, "")}${runtimePath}`, {
1044
- ...options,
1045
- method,
1046
- headers
1047
- });
1048
- }
1049
- /**
1050
- * Get available capacity from the blueprint contract.
1051
- * Requires blueprintContractAddress in config.
1052
- */
1053
- async getAvailableCapacity() {
1054
- return this.chain.getAvailableCapacity();
1055
- }
1056
- /**
1057
- * Get service stats from the blueprint contract.
1058
- * Requires blueprintContractAddress in config.
1059
- */
1060
- async getServiceStats() {
1061
- return this.chain.getServiceStats();
1062
- }
1063
- /**
1064
- * Mint or reuse the EIP-191 session for the operator API.
1065
- *
1066
- * The session is signed by the SAME key that submits jobs (`chain.signMessage`),
1067
- * so the operator binds it to every sandbox this client created.
1068
- */
1069
- async getOperatorSession(force = false) {
1070
- if (!this.operatorApiUrl) throw new Error("Operator API URL is not configured");
1071
- if (!force && this.operatorSession && !this.operatorSession.needsRefresh()) return this.operatorSession;
1072
- const session = await OperatorSession.establish(this.operatorApiUrl, (message) => this.chain.signMessage(message));
1073
- this.operatorSession = session;
1074
- return session;
1075
- }
1076
- /**
1077
- * Deliver secrets to a sandbox via the operator's 2-phase provisioning
1078
- * endpoint (`POST /api/sandboxes/:id/secrets`).
1079
- *
1080
- * Unlike `env`, these values never appear on-chain: they ride TLS to the
1081
- * operator, which validates the session's recovered address against the
1082
- * sandbox's on-chain creator before injecting.
1083
- */
1084
- async injectSecrets(sandboxId, secrets) {
1085
- await this.withOperatorSession(sandboxId, async (session, url) => {
1086
- return await fetch(`${url}/api/sandboxes/${encodeURIComponent(sandboxId)}/secrets`, {
1087
- method: "POST",
1088
- headers: {
1089
- Authorization: session.authorizationHeader(),
1090
- "Content-Type": "application/json"
1091
- },
1092
- body: JSON.stringify({ env_json: secrets })
1093
- });
1094
- }, "inject secrets into");
1095
- }
1096
- /** Read a sandbox's provisioned secret keys and credential availability. */
1097
- async getSecrets(sandboxId) {
1098
- return this.withOperatorSession(sandboxId, async (session, url) => {
1099
- return await fetch(`${url}/api/sandboxes/${encodeURIComponent(sandboxId)}/secrets`, {
1100
- method: "GET",
1101
- headers: { Authorization: session.authorizationHeader() }
1102
- });
1103
- }, "read secrets for").then(async (response) => {
1104
- const body = await response.json();
1105
- return {
1106
- sandboxId: body.sandbox_id ?? sandboxId,
1107
- envJson: body.env_json ?? {},
1108
- credentialsAvailable: Boolean(body.credentials_available)
1109
- };
1110
- });
1111
- }
1112
- /**
1113
- * Run an operator-API request with a session, retrying once with a fresh
1114
- * session on 401 (expired PASETO). Any other failure names the sandbox so
1115
- * the caller can retry without losing the ID.
1116
- */
1117
- async withOperatorSession(sandboxId, request, action) {
1118
- if (!this.operatorApiUrl) throw new Error(`Cannot ${action} sandbox ${sandboxId}: operatorApiUrl is not configured`);
1119
- let session = await this.getOperatorSession();
1120
- let response = await request(session, this.operatorApiUrl);
1121
- if (response.status === 401) {
1122
- session = await this.getOperatorSession(true);
1123
- response = await request(session, this.operatorApiUrl);
1124
- }
1125
- if (!response.ok) {
1126
- const body = await response.text().catch(() => "");
1127
- throw new OperatorSessionError(`Failed to ${action} sandbox ${sandboxId} (HTTP ${response.status}): ${body.slice(0, 300)}`, response.status);
1128
- }
1129
- return response;
1130
- }
1131
- async fetchOperatorApi(path, options) {
1132
- if (!this.operatorApiUrl) return new Response(JSON.stringify({ error: "Operator API URL is not configured" }), {
1133
- status: 501,
1134
- headers: { "Content-Type": "application/json" }
1135
- });
1136
- const headers = new Headers(options?.headers);
1137
- if (this.operatorApiToken && !headers.has("Authorization")) headers.set("Authorization", `Bearer ${this.operatorApiToken}`);
1138
- if (options?.body && !headers.has("Content-Type")) headers.set("Content-Type", "application/json");
1139
- return fetch(`${this.operatorApiUrl}${path}`, {
1140
- ...options,
1141
- headers
1142
- });
1143
- }
1144
- };
1145
- //#endregion
1146
- export { JOB_SANDBOX_DELETE as a, AgentSandboxBlueprintAbi as c, SandboxCreateParamTypes as d, SandboxCreateResponseParamTypes as f, JOB_SANDBOX_CREATE as i, ITangleJobsAbi as l, OperatorSession as n, TANGLE_CHAIN_ID as o, SandboxIdParamTypes as p, OperatorSessionError as r, TANGLE_JOBS_CONTRACT as s, TangleSandboxClient as t, JsonResponseParamTypes as u };