@tangle-network/sandbox 0.60.1 → 0.60.2
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/README.md +6 -0
- package/dist/agent/index.d.ts +4 -4
- package/dist/agent/index.js +2 -2
- package/dist/agent/preview.d.ts +1 -1
- package/dist/{agent-run-outcome-Cs5H4B3s.d.ts → agent-run-outcome-BDxby7zK.d.ts} +1 -1
- package/dist/{client-DGwZ0Swl.d.ts → client-BFilDKO8.d.ts} +3 -3
- package/dist/{client-BRocAWYy.js → client-p2T45dAv.js} +1 -1
- package/dist/core.d.ts +4 -4
- package/dist/core.js +2 -2
- package/dist/{index-CcMKzCk4.d.ts → index-DGuTeptP.d.ts} +177 -62
- package/dist/index.d.ts +7 -7
- package/dist/index.js +3 -3
- package/dist/{lines-CHK_7gLO.d.ts → lines-T2D6xHHx.d.ts} +1 -1
- package/dist/lines.d.ts +1 -1
- package/dist/{preview-DNx_ik7Y.d.ts → preview-ZaYvOOXz.d.ts} +3 -3
- package/dist/runtime.d.ts +2 -2
- package/dist/{sandbox-BsJecVCj.js → sandbox-DeE2MDx9.js} +99 -23
- package/dist/{sandbox-BsEk7BTy.d.ts → sandbox-LRvBzGGm.d.ts} +2 -2
- package/dist/tangle/index.d.ts +2 -2
- package/dist/tangle/index.js +2 -2
- package/dist/{tangle-DKaBCad0.js → tangle-SNShua9T.js} +317 -106
- package/dist/{types-BQlqLwrK.d.ts → types-C9w6MdZB.d.ts} +37 -2
- package/package.json +4 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { _ as parseErrorResponse } from "./errors-CKl_BSlD.js";
|
|
2
|
-
import { n as createSandboxInstanceFromResponse } from "./sandbox-
|
|
2
|
+
import { n as createSandboxInstanceFromResponse } from "./sandbox-DeE2MDx9.js";
|
|
3
3
|
//#region src/tangle/abi.ts
|
|
4
4
|
/**
|
|
5
5
|
* Tangle Contract ABI Definitions
|
|
@@ -132,90 +132,110 @@ const ITangleJobsAbi = [
|
|
|
132
132
|
]
|
|
133
133
|
}
|
|
134
134
|
];
|
|
135
|
-
const SandboxCreateParamTypes = [
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
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
|
+
}];
|
|
205
213
|
const SandboxIdParamTypes = [{
|
|
206
|
-
name: "
|
|
207
|
-
type: "
|
|
214
|
+
name: "request",
|
|
215
|
+
type: "tuple",
|
|
216
|
+
components: [{
|
|
217
|
+
name: "sandbox_id",
|
|
218
|
+
type: "string"
|
|
219
|
+
}]
|
|
208
220
|
}];
|
|
209
221
|
const SandboxCreateResponseParamTypes = [{
|
|
210
|
-
name: "
|
|
211
|
-
type: "
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
222
|
+
name: "response",
|
|
223
|
+
type: "tuple",
|
|
224
|
+
components: [{
|
|
225
|
+
name: "sandboxId",
|
|
226
|
+
type: "string"
|
|
227
|
+
}, {
|
|
228
|
+
name: "json",
|
|
229
|
+
type: "string"
|
|
230
|
+
}]
|
|
215
231
|
}];
|
|
216
232
|
const JsonResponseParamTypes = [{
|
|
217
|
-
name: "
|
|
218
|
-
type: "
|
|
233
|
+
name: "response",
|
|
234
|
+
type: "tuple",
|
|
235
|
+
components: [{
|
|
236
|
+
name: "json",
|
|
237
|
+
type: "string"
|
|
238
|
+
}]
|
|
219
239
|
}];
|
|
220
240
|
const AgentSandboxBlueprintAbi = [
|
|
221
241
|
{
|
|
@@ -447,31 +467,35 @@ var TangleChainClient = class {
|
|
|
447
467
|
}
|
|
448
468
|
encodeSandboxCreateInputs(options) {
|
|
449
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);
|
|
450
471
|
return {
|
|
451
472
|
types: SandboxCreateParamTypes,
|
|
452
|
-
values: [
|
|
453
|
-
options.name ?? "",
|
|
454
|
-
options.environment ?? "",
|
|
455
|
-
"",
|
|
456
|
-
"",
|
|
457
|
-
options.env ? JSON.stringify(options.env) : "",
|
|
458
|
-
options.metadata ? JSON.stringify(options.metadata) : "",
|
|
459
|
-
options.sshEnabled ?? false,
|
|
460
|
-
options.sshPublicKeys?.[0] ?? "",
|
|
461
|
-
options.webTerminalEnabled ?? false,
|
|
462
|
-
BigInt(options.maxLifetimeSeconds ?? 0),
|
|
463
|
-
BigInt(options.idleTimeoutSeconds ?? 0),
|
|
464
|
-
BigInt(options.resources?.cpuCores ?? 0),
|
|
465
|
-
BigInt(options.resources?.memoryMB ?? 0),
|
|
466
|
-
BigInt(options.resources?.diskGB ?? 0),
|
|
467
|
-
|
|
468
|
-
|
|
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
|
+
}]
|
|
469
493
|
};
|
|
470
494
|
}
|
|
471
495
|
encodeSandboxIdInputs(sandboxId) {
|
|
472
496
|
return {
|
|
473
497
|
types: SandboxIdParamTypes,
|
|
474
|
-
values: [sandboxId]
|
|
498
|
+
values: [{ sandbox_id: sandboxId }]
|
|
475
499
|
};
|
|
476
500
|
}
|
|
477
501
|
async submitJobAndWait(jobIndex, encoded) {
|
|
@@ -570,6 +594,91 @@ var TangleChainClient = class {
|
|
|
570
594
|
if (jobIndex === 0) return SandboxCreateResponseParamTypes;
|
|
571
595
|
return JsonResponseParamTypes;
|
|
572
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
|
+
}
|
|
573
682
|
};
|
|
574
683
|
//#endregion
|
|
575
684
|
//#region src/tangle/client.ts
|
|
@@ -587,6 +696,20 @@ function randomHexToken(bytes) {
|
|
|
587
696
|
globalThis.crypto.getRandomValues(buf);
|
|
588
697
|
return Array.from(buf).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
589
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
|
+
}
|
|
590
713
|
function attestationNonceFromOptions(options) {
|
|
591
714
|
const direct = options.confidential?.attestationNonce;
|
|
592
715
|
if (direct) return direct;
|
|
@@ -622,7 +745,10 @@ function requirePathGroup(match, index) {
|
|
|
622
745
|
if (value === void 0) throw new Error(`Path matcher missing group ${index}`);
|
|
623
746
|
return value;
|
|
624
747
|
}
|
|
625
|
-
|
|
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];
|
|
626
752
|
return value && typeof value === "object" ? value : void 0;
|
|
627
753
|
}
|
|
628
754
|
function readString(record, keys) {
|
|
@@ -678,8 +804,8 @@ function sandboxInfoFromEntry(entry) {
|
|
|
678
804
|
};
|
|
679
805
|
}
|
|
680
806
|
function sandboxEntryFromWire(fallbackId, raw) {
|
|
681
|
-
const connection =
|
|
682
|
-
const metadata =
|
|
807
|
+
const connection = recordField(raw, "connection");
|
|
808
|
+
const metadata = recordField(raw, "metadata");
|
|
683
809
|
const id = readString(raw, [
|
|
684
810
|
"id",
|
|
685
811
|
"sandboxId",
|
|
@@ -691,7 +817,10 @@ function sandboxEntryFromWire(fallbackId, raw) {
|
|
|
691
817
|
"runtimeToken",
|
|
692
818
|
"token"
|
|
693
819
|
]) ?? "";
|
|
694
|
-
const tupleField = (key) =>
|
|
820
|
+
const tupleField = (key) => {
|
|
821
|
+
const value = raw[key];
|
|
822
|
+
return typeof value === "string" ? value : value;
|
|
823
|
+
};
|
|
695
824
|
const tupleId = tupleField("filesystemIncarnationId") === void 0 ? void 0 : typeof tupleField("filesystemIncarnationId") === "string" ? tupleField("filesystemIncarnationId") : "";
|
|
696
825
|
const tupleProvenance = tupleField("filesystemIncarnationProvenance") === void 0 ? void 0 : tupleField("filesystemIncarnationProvenance");
|
|
697
826
|
const tupleReadiness = tupleField("filesystemIncarnationReadiness") === void 0 ? void 0 : tupleField("filesystemIncarnationReadiness");
|
|
@@ -719,6 +848,7 @@ var TangleSandboxClient = class {
|
|
|
719
848
|
sandboxes = /* @__PURE__ */ new Map();
|
|
720
849
|
operatorApiUrl;
|
|
721
850
|
operatorApiToken;
|
|
851
|
+
operatorSession = null;
|
|
722
852
|
constructor(config) {
|
|
723
853
|
if (!config.privateKey && !config.wallet) throw new Error("TangleSandboxClient requires either privateKey or wallet");
|
|
724
854
|
this.chain = new TangleChainClient(config);
|
|
@@ -727,9 +857,20 @@ var TangleSandboxClient = class {
|
|
|
727
857
|
}
|
|
728
858
|
/**
|
|
729
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`.
|
|
730
866
|
*/
|
|
731
867
|
async create(options) {
|
|
732
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
|
+
}
|
|
733
874
|
const createOptions = withAttestationNonce(options ?? {});
|
|
734
875
|
const encoded = this.chain.encodeSandboxCreateInputs(createOptions);
|
|
735
876
|
const { result: _result, callId, blockNumber } = await this.chain.submitJobAndWait(0, encoded);
|
|
@@ -737,10 +878,11 @@ var TangleSandboxClient = class {
|
|
|
737
878
|
let sandboxId;
|
|
738
879
|
let responseJson = {};
|
|
739
880
|
if (resultBytes) try {
|
|
740
|
-
const decoded = (await import("viem")).decodeAbiParameters(this.chain.getResponseParamTypes(0), resultBytes);
|
|
741
|
-
|
|
881
|
+
const [decoded] = (await import("viem")).decodeAbiParameters(this.chain.getResponseParamTypes(0), resultBytes);
|
|
882
|
+
const decodedEntry = decoded;
|
|
883
|
+
sandboxId = decodedEntry.sandboxId;
|
|
742
884
|
try {
|
|
743
|
-
responseJson = JSON.parse(
|
|
885
|
+
responseJson = JSON.parse(decodedEntry.json);
|
|
744
886
|
} catch {}
|
|
745
887
|
} catch {
|
|
746
888
|
throw new Error("Failed to decode create job result");
|
|
@@ -763,6 +905,7 @@ var TangleSandboxClient = class {
|
|
|
763
905
|
attestationNonce: attestationNonceFromOptions(createOptions) ?? wireEntry.attestationNonce
|
|
764
906
|
};
|
|
765
907
|
this.sandboxes.set(sandboxId, entry);
|
|
908
|
+
if (tangleSecrets && Object.keys(tangleSecrets).length > 0) await this.injectSecrets(sandboxId, tangleSecrets);
|
|
766
909
|
return createSandboxInstanceFromResponse(this, sandboxInfoFromEntry(entry));
|
|
767
910
|
}
|
|
768
911
|
/**
|
|
@@ -917,6 +1060,74 @@ var TangleSandboxClient = class {
|
|
|
917
1060
|
async getServiceStats() {
|
|
918
1061
|
return this.chain.getServiceStats();
|
|
919
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
|
+
}
|
|
920
1131
|
async fetchOperatorApi(path, options) {
|
|
921
1132
|
if (!this.operatorApiUrl) return new Response(JSON.stringify({ error: "Operator API URL is not configured" }), {
|
|
922
1133
|
status: 501,
|
|
@@ -932,4 +1143,4 @@ var TangleSandboxClient = class {
|
|
|
932
1143
|
}
|
|
933
1144
|
};
|
|
934
1145
|
//#endregion
|
|
935
|
-
export {
|
|
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 };
|
|
@@ -1779,6 +1779,26 @@ interface CreateSandboxOptions {
|
|
|
1779
1779
|
* ```
|
|
1780
1780
|
*/
|
|
1781
1781
|
secrets?: string[] | "all";
|
|
1782
|
+
/**
|
|
1783
|
+
* Confidential environment variables for the **Tangle (on-chain) driver**,
|
|
1784
|
+
* delivered OFF-chain via the operator's 2-phase secret provisioning
|
|
1785
|
+
* endpoint after the create job completes. Requires the client to be
|
|
1786
|
+
* configured with `operatorApiUrl`.
|
|
1787
|
+
*
|
|
1788
|
+
* Unlike {@link CreateSandboxOptions.env}, these values never appear in the
|
|
1789
|
+
* job calldata: the client mints an EIP-191-authenticated operator session
|
|
1790
|
+
* signed by the same key that submitted the job, and the operator injects
|
|
1791
|
+
* the secrets only after verifying that key owns the sandbox.
|
|
1792
|
+
*
|
|
1793
|
+
* @example
|
|
1794
|
+
* ```typescript
|
|
1795
|
+
* const box = await client.create({
|
|
1796
|
+
* environment: "universal",
|
|
1797
|
+
* tangleSecrets: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY },
|
|
1798
|
+
* });
|
|
1799
|
+
* ```
|
|
1800
|
+
*/
|
|
1801
|
+
tangleSecrets?: Record<string, string>;
|
|
1782
1802
|
/** Custom metadata to store with the sandbox */
|
|
1783
1803
|
metadata?: Record<string, unknown>;
|
|
1784
1804
|
/**
|
|
@@ -6450,9 +6470,22 @@ interface ChunkedUploadResult {
|
|
|
6450
6470
|
interface DownloadOptions {
|
|
6451
6471
|
/** Overwrite local file if exists (default: true) */
|
|
6452
6472
|
overwrite?: boolean;
|
|
6473
|
+
/** Maximum streamed bytes; refusal leaves the destination intact. */
|
|
6474
|
+
maxBytes?: number;
|
|
6475
|
+
/** Exact expected byte count, checked before publishing the local file. */
|
|
6476
|
+
expectedSize?: number;
|
|
6477
|
+
/** Expected SHA-256 digest, with an optional sha256: prefix. */
|
|
6478
|
+
expectedSha256?: string;
|
|
6479
|
+
/** Cancel the request and remove its incomplete local file. */
|
|
6480
|
+
signal?: AbortSignal;
|
|
6453
6481
|
/** Progress callback for large files */
|
|
6454
6482
|
onProgress?: (progress: DownloadProgress) => void;
|
|
6455
6483
|
}
|
|
6484
|
+
/** Exact bytes retained by a completed download. */
|
|
6485
|
+
interface DownloadResult {
|
|
6486
|
+
sizeBytes: number;
|
|
6487
|
+
sha256: string;
|
|
6488
|
+
}
|
|
6456
6489
|
/**
|
|
6457
6490
|
* Download progress information.
|
|
6458
6491
|
*/
|
|
@@ -6608,6 +6641,8 @@ interface WriteManyOptions {
|
|
|
6608
6641
|
interface FileSystem {
|
|
6609
6642
|
/** True when write/writeMany honor Unix mode bits such as 0o755. */
|
|
6610
6643
|
supportsWriteMode?: true;
|
|
6644
|
+
/** True when download enforces bounds and cancellation and returns a digest receipt. */
|
|
6645
|
+
supportsBoundedDownload?: true;
|
|
6611
6646
|
/**
|
|
6612
6647
|
* Read a file's contents as a string.
|
|
6613
6648
|
* For binary files, use download() instead.
|
|
@@ -6729,7 +6764,7 @@ interface FileSystem {
|
|
|
6729
6764
|
* await box.fs.download("/workspace/output.zip", "./results.zip");
|
|
6730
6765
|
* ```
|
|
6731
6766
|
*/
|
|
6732
|
-
download(remotePath: string, localPath: string, options?: DownloadOptions): Promise<
|
|
6767
|
+
download(remotePath: string, localPath: string, options?: DownloadOptions): Promise<DownloadResult>;
|
|
6733
6768
|
/**
|
|
6734
6769
|
* Upload a local directory to the sandbox.
|
|
6735
6770
|
* Uses tar for efficient transfer.
|
|
@@ -6940,4 +6975,4 @@ interface CodeExecutionOptions {
|
|
|
6940
6975
|
idempotencyKey?: string;
|
|
6941
6976
|
}
|
|
6942
6977
|
//#endregion
|
|
6943
|
-
export { DownloadOptions as $,
|
|
6978
|
+
export { DownloadOptions as $, SnapshotDeleteAcknowledgement as $i, PublicTemplateInfo as $n, SandboxFleetTraceEvent as $r, GPU_LEASE_PROVIDER_NAMES as $t, CommitTaskSessionOptions as A, WriteFileOptions as Aa, SandboxTraceOptions as Ai, NetworkConfig as An, SandboxFleetArtifact as Ar, FileUsageOptions as At, CreateSandboxOptions as B, BackendType as Ba, SessionEventStreamOptions as Bi, ProcessListOptions as Bn, SandboxFleetMachineMeteredUsage as Br, FleetDispatchStreamOptions as Bt, BranchOptions as C, UpdateUserOptions as Ca, SandboxTerminalInfo as Ci, ListMessagesOptions as Cn, SandboxDeleteAcknowledgement as Cr, FileReadError as Ct, CodeExecutionResult as D, WaitForOptions as Da, SandboxTraceBundle as Di, MAX_EGRESS_DENIALS_LIMIT as Dn, SandboxEvent as Dr, FileTreeFile as Dt, CodeExecutionOptions as E, UsageInfo as Ea, SandboxTerminals as Ei, ListSandboxOptions as En, SandboxEnvironment as Er, FileSystem as Et, CreateIntelligenceReportOptions as F, BatchEventDataMap as Fa, SecretsManager as Fi, PreviewLinkInfo as Fn, SandboxFleetDriverCapability as Fr, FleetAgentResult as Ft, DeleteMatchingSandboxesFilter as G, ManagedProcessRecord as Ga, SessionInfo as Gi, ProcessStatus as Gn, SandboxFleetOperationsSummary as Gr, FleetMachineId as Gt, CreateTaskSessionOptions as H, ManagedProcessClient as Ha, SessionExecutionStatus as Hi, ProcessManager as Hn, SandboxFleetMachineSpec as Hr, FleetDriveTurnRequest as Ht, CreateRequestOptions as I, BatchSidecarGroup as Ia, SendSessionMessageOptions as Ii, PreviewLinkManager as In, SandboxFleetDriverTimings as Ir, FleetAgentRunStatus as It, DeleteOptions as J, SessionMessage as Ji, PromptResult as Jn, SandboxFleetPolicy as Jr, FleetRunEvent as Jt, DeleteMatchingSandboxesOptions as K, ManagedProcessSpec as Ka, SessionInterruptOptions as Ki, PromptInputPart as Kn, SandboxFleetParent as Kr, FleetPromptDispatchOptions as Kt, CreateSandboxFleetOptions as L, BatchTaskUsage as La, SendSessionMessageRequest as Li, PreviewLinkWaitOptions as Ln, SandboxFleetInfo as Lr, FleetDispatchCancelResult as Lt, ConversationTurnOptions as M, WriteManyOptions as Ma, SearchMatch as Mi, NonHostAgentDriverConfig as Mn, SandboxFleetCostEstimate as Mr, FileWriteResult as Mt, ConversationTurnResult as N, BatchBackendStats as Na, SearchOptions as Ni, PermissionLevel as Nn, SandboxFleetDispatchFailureClass as Nr, FleetAgentId as Nt, CodeLanguage as O, WaitForRolloutOptions as Oa, SandboxTraceEvent as Oi, McpServerConfig as On, SandboxFleetAgent as Or, FileTreeOptions as Ot, CreateGpuLeaseOptions as P, BatchEvent as Pa, SecretInfo as Pi, PermissionsManager as Pn, SandboxFleetDispatchResponse as Pr, FleetAgentPlacement as Pt, DispatchedSession as Q, SessionStatus as Qi, ProvisionStep as Qn, SandboxFleetTraceBundle as Qr, ForkLookupOptions as Qt, CreateSandboxFleetTokenOptions as R, PublicBatchRunRequest as Ra, SentSessionMessage as Ri, Process as Rn, SandboxFleetIntelligenceEnvelope as Rr, FleetDispatchResultBuffer as Rt, BatchTaskResult as S, TurnDriveResult as Sa, SandboxTerminalCreateOptions as Si, JsonValue as Sn, SandboxCreateReceipt as Sr, FileReadBatchResult as St, ChunkedUploadResult as T, UploadProgress as Ta, SandboxTerminalRequestOptions as Ti, ListSandboxFleetOptions as Tn, SandboxDeleteOutcome as Tr, FileRenameResult as Tt, DeleteMatchingSandboxOutcome as U, ManagedProcessJobs as Ua, SessionFailureReason as Ui, ProcessSignal as Un, SandboxFleetManifest as Ur, FleetExecDispatchOptions as Ut, CreateSessionOptions as V, parseBackendType as Va, SessionExecutionInfo as Vi, ProcessLogEntry as Vn, SandboxFleetMachineRecord as Vr, FleetDriveTurnOutcome as Vt, DeleteMatchingSandboxResult as W, ManagedProcessOptions as Wa, SessionForkOptions as Wi, ProcessSpawnOptions as Wn, SandboxFleetManifestMachine as Wr, FleetExecDispatchResult as Wt, DirectoryPermission as X, SessionMessageInputPart as Xi, ProvisionResult as Xn, SandboxFleetSpend as Xr, ForkCounts as Xt, DevServerInfo as Y, SessionMessageAdmission as Yi, ProvisionEvent as Yn, SandboxFleetProfileRef as Yr, FleetRunOptions as Yt, DispatchPromptOptions as Z, SessionResultOptions as Zi, ProvisionStatus as Zn, SandboxFleetToken as Zr, ForkIdempotency as Zt, BatchBackend as _, TeeAttestationResponse as _a, SandboxShape as _i, IntelligenceReport as _n, SSHCommandDescriptor as _r, ExactProcessSpawnOptions as _t, AgentQuestionRequest as a, SshKeysManager as aa, SandboxFleetWorkspaceRestoreResult as ai, GitStatus as an, ReconcileSandboxFleetsOptions as ar, DriverType as at, BatchRunRequest as b, TokenRefreshHandler as ba, SandboxStatus as bi, IntelligenceReportSubjectType as bn, SandboxConnection as br, FileInfo as bt, AttachGpuLeaseOptions as c, StorageConfig as ca, SandboxInfo as ci, GpuLeaseCommandResult as cn, RestoreSnapshotOptions as cr, DurablePlanSnapshot as ct, BackendConfig as d, TaskSessionCommitResult as da, SandboxPortPreviewLink as di, GpuLeaseManager as dn, RolloutChildResult as dr, EffectiveBackendSource as dt, SnapshotDeleteOutcome as ea, SandboxFleetTraceExport as ei, GitAuth as en, PublicTemplateVersionInfo as er, DownloadProgress as et, BackendInfo as f, TaskSessionFileChange as fa, SandboxRemovalState as fi, GpuLeaseProviderName as fn, RolloutOptions as fr, EgressDenial as ft, BackendStatus as g, TeeAttestationReport as ga, SandboxRuntimeHealth as gi, InstalledTool as gn, RolloutTurnPart as gr, EventStreamOptions as gt, BackendRuntimeConfigUpdate as h, TeeAttestationOptions as ha, SandboxRuntimeCapabilities as hi, HostAgentRuntimeBackend as hn, RolloutStatus as hr, EnsureDevServerOptions as ht, AgentApprovalRequirement as i, SnapshotResult as ia, SandboxFleetWorkspaceReconcileResult as ii, GitDiff as in, ReapExpiredSandboxFleetsResult as ir, DriverInfo as it, CompletedTurnResult as j, WriteManyFile as ja, SandboxUser as ji, NetworkManager as jn, SandboxFleetArtifactSpec as jr, FileUsageResult as jt, CodeResultPart as k, WorkspaceOperationLookup as ka, SandboxTraceExport as ki, MkdirOptions as kn, SandboxFleetAgentSpec as kr, FileTreeResult as kt, AttachSandboxFleetMachineOptions as l, SubscriptionInfo as la, SandboxIntelligenceEnvelope as li, GpuLeaseExecOptions as ln, ResumeOptions as lr, EffectiveBackend as lt, BackendMcpServerStatus as m, TaskSessionProfile as ma, SandboxResources as mi, HostAgentDriverConfig as mn, RolloutStartResult as mr, EgressPolicy as mt, AccessPolicyRule as n, SnapshotInfo as na, SandboxFleetUsage as ni, GitCommit as nn, PublishPublicTemplateVersionOptions as nr, DriveTurnOptions as nt, AgentRunStatus as o, StartupDiagnostics as oa, SandboxFleetWorkspaceSnapshotResult as oi, GpuLease as on, ReconcileSandboxFleetsResult as or, DurablePlan as ot, BackendManager as p, TaskSessionInfo as pa, SandboxResourceUsage as pi, GpuLeaseStatus as pn, RolloutScorer as pr, EgressManager as pt, DeleteMatchingSandboxesResult as q, ManagedProcessState as qa, SessionListOptions as qi, PromptOptions as qn, SandboxFleetPlacement as qr, FleetPromptDispatchResult as qt, AddUserOptions as r, SnapshotOptions as ra, SandboxFleetWorkspace as ri, GitConfig as rn, ReapExpiredSandboxFleetsOptions as rr, DriverConfig as rt, AgentToolInvocation as s, StartupOperation as sa, SandboxIdentity as si, GpuLeaseBilling as sn, RenameOptions as sr, DurablePlanDecisionResult as st, AcceleratorKind as t, SnapshotIdempotency as ta, SandboxFleetTraceOptions as ti, GitBranch as tn, PublishPublicTemplateOptions as tr, DownloadResult as tt, BackendCapabilities as u, TaskSessionChanges as ua, SandboxPortBinding as ui, GpuLeaseExecResult as un, Rollout as ur, EffectiveBackendProfile as ut, BatchResult as v, TeePublicKey as va, SandboxShapePreset as vi, IntelligenceReportBudget as vn, SSHCredentials as vr, ExecOptions as vt, ChunkedUploadOptions as w, UploadOptions as wa, SandboxTerminalManager as wi, ListOptions as wn, SandboxDeleteOptions as wr, FileReadResult as wt, BatchTask as x, TokenUsage as xa, SandboxTerminalAttachOptions as xi, IntelligenceReportWindow as xn, SandboxCreateOutcome as xr, FileReadBatchOptions as xt, BatchRunOptions as y, TeePublicKeyResponse as ya, SandboxShapesInfo as yi, IntelligenceReportCompareTo as yn, SandboxConfig as yr, ExecResult as yt, CreateSandboxFleetWithCoordinatorOptions as z, ALL_BACKEND_TYPES as za, SessionBackendCredentials as zi, ProcessInfo as zn, SandboxFleetMachine as zr, FleetDispatchResultBufferOptions as zt };
|