sandcovery 0.6.2 → 0.7.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.
@@ -1,8 +1,9 @@
1
1
  #!/usr/bin/env node
2
- import { t as start } from "../start-D1LPu-aN.mjs";
2
+ import { n as dockerRun, o as FORWARDER_ENV, s as forwardPorts, t as startTool } from "../tool-B8KvfvY5.mjs";
3
3
  // src/cli/sandcovery-docker.ts
4
- await start({
5
- argv: ["docker", ...process.argv.slice(2)],
6
- dropIn: true
4
+ await startTool({
5
+ run: dockerRun,
6
+ serve: forwardPorts,
7
+ variable: FORWARDER_ENV
7
8
  });
8
9
  export {};
@@ -1,8 +1,10 @@
1
1
  #!/usr/bin/env node
2
- import { t as start } from "../start-D1LPu-aN.mjs";
2
+ import { a as watchIdle, i as IDLE_WATCHER_ENV, n as kubectlRun } from "../kubectl-ClFWX65x.mjs";
3
+ import { t as startTool } from "../tool-B8KvfvY5.mjs";
3
4
  // src/cli/sandcovery-kubectl.ts
4
- await start({
5
- argv: ["kubectl", ...process.argv.slice(2)],
6
- dropIn: true
5
+ await startTool({
6
+ run: kubectlRun,
7
+ serve: watchIdle,
8
+ variable: IDLE_WATCHER_ENV
7
9
  });
8
10
  export {};
@@ -0,0 +1 @@
1
+ export {}
@@ -0,0 +1,198 @@
1
+ #!/usr/bin/env node
2
+ import { Hs as map, Is as getOrNull, Os as exists, Ps as fromUndefinedOr, Sn as decodeUnknownOption, Us as match, ln as Struct, qs as toArray, tn as NonEmptyString, wn as fromJsonString, zs as isNone } from "../x-account-BSasf-z-.mjs";
3
+ import { g as v7, t as startTool } from "../tool-B8KvfvY5.mjs";
4
+ import { r as onPath, t as answers } from "../kubectl-ClFWX65x.mjs";
5
+ import { spawn } from "node:child_process";
6
+ import { parseArgs } from "node:util";
7
+ // src/cli/commands/t3.ts
8
+ const T3_PORT = 3773;
9
+ const T3 = process.platform === "win32" ? "t3.exe" : "t3";
10
+ const VERB = "link a sandbox to T3 Code";
11
+ const EXEC_TIMEOUT_SECONDS = 600;
12
+ const ANSWER_WAIT_MS = 12e4;
13
+ const T3_HOME = "\"$HOME/.t3\"";
14
+ const ON_PATH = "export PATH=\"$HOME/.local/bin:$PATH\"";
15
+ const INSTALL_COMMAND = [
16
+ "set -e",
17
+ ON_PATH,
18
+ "curl -fsSL https://t3.codes/install.sh -o /tmp/t3-install.sh",
19
+ "sh /tmp/t3-install.sh",
20
+ "if ! command -v claude >/dev/null; then",
21
+ " curl -fsSL https://claude.ai/install.sh -o /tmp/claude-install.sh",
22
+ " bash /tmp/claude-install.sh",
23
+ "fi",
24
+ `mkdir -p ${T3_HOME}/userdata`,
25
+ `printf '%s\\n' '{"linkedEnvironmentsEnabled":true}' >${T3_HOME}/userdata/settings.json`
26
+ ].join("\n");
27
+ const SERVE_COMMAND = [ON_PATH, `setsid t3 serve --host 0.0.0.0 --port ${String(T3_PORT)} --base-dir ${T3_HOME} --no-browser </dev/null >>${T3_HOME}/serve.log 2>&1 &`].join("\n");
28
+ const PAIR_COMMAND = [
29
+ ON_PATH,
30
+ `for _ in $(seq 60); do curl -fsS -m 5 -o /dev/null http://127.0.0.1:${String(T3_PORT)}/.well-known/t3/environment && break; sleep 1; done`,
31
+ `t3 auth pairing create --base-dir ${T3_HOME} --json --ttl 10m --label sandcovery`
32
+ ].join("\n");
33
+ const decodePairing = decodeUnknownOption(fromJsonString(Struct({ credential: NonEmptyString })));
34
+ const providerOf = (sandbox) => sandbox.provider ?? "its provider";
35
+ const ranT3 = async ({ args, signal, t3 }) => {
36
+ const closed = Promise.withResolvers();
37
+ const child = spawn(t3, args, {
38
+ signal,
39
+ stdio: [
40
+ "ignore",
41
+ "pipe",
42
+ "pipe"
43
+ ]
44
+ });
45
+ child.once("error", closed.reject);
46
+ child.once("close", closed.resolve);
47
+ const [stdout, stderr, code] = await Promise.all([
48
+ child.stdout.toArray(),
49
+ child.stderr.toArray(),
50
+ closed.promise
51
+ ]);
52
+ return {
53
+ code: code ?? 1,
54
+ stderr: Buffer.concat(stderr).toString(),
55
+ stdout: Buffer.concat(stdout).toString()
56
+ };
57
+ };
58
+ const ranInSandbox = async ({ command, env, sandbox, step, tool }) => {
59
+ const result = await tool.client.sandboxes.exec(sandbox.id, {
60
+ command,
61
+ cwd: null,
62
+ env,
63
+ timeout_seconds: EXEC_TIMEOUT_SECONDS
64
+ }, { signal: tool.signal });
65
+ if (result.exit_code !== 0) throw new Error(`Can't ${VERB}. Couldn't ${step} in sandbox ${sandbox.id} on ${providerOf(sandbox)}, so Sandcovery destroyed it.`, { cause: result.stderr.slice(-2e3) });
66
+ return result.stdout;
67
+ };
68
+ const linked = async ({ access, env, sandbox, t3, tool, version }) => {
69
+ const preview = await tool.client.sandboxes.portPreview(sandbox.id, T3_PORT, { signal: tool.signal });
70
+ const address = new URL(preview.url);
71
+ if (Object.keys(preview.headers).length > 0 || address.href !== `${address.origin}/`) throw new Error(`Can't ${VERB} on ${providerOf(sandbox)}. Its URL for port ${String(T3_PORT)} needs headers or a path or query, and t3 environment link sends none of them, so Sandcovery destroyed sandbox ${sandbox.id}. Pick another provider with --provider.`);
72
+ if (preview.expires_at !== null && Date.parse(preview.expires_at) < Date.parse(sandbox.expires_at)) throw new Error(`Can't ${VERB} on ${providerOf(sandbox)}. Its URL for port ${String(T3_PORT)} stops working at ${preview.expires_at}, before the sandbox ends at ${sandbox.expires_at}, so Sandcovery destroyed sandbox ${sandbox.id}. Pick another provider with --provider, or a shorter --ttl.`);
73
+ const url = address.origin;
74
+ await ranInSandbox({
75
+ command: INSTALL_COMMAND,
76
+ env: { T3CODE_VERSION: version },
77
+ sandbox,
78
+ step: `install T3 Code ${version}`,
79
+ tool
80
+ });
81
+ await ranInSandbox({
82
+ command: SERVE_COMMAND,
83
+ env,
84
+ sandbox,
85
+ step: "start T3 Code",
86
+ tool
87
+ });
88
+ const paired = await ranInSandbox({
89
+ command: PAIR_COMMAND,
90
+ env: null,
91
+ sandbox,
92
+ step: "make a T3 Code pairing code",
93
+ tool
94
+ });
95
+ const pairing = decodePairing(paired.trim());
96
+ if (isNone(pairing)) throw new Error(`Can't ${VERB}. T3 Code in sandbox ${sandbox.id} on ${providerOf(sandbox)} gave no pairing code, so Sandcovery destroyed it.`);
97
+ if (!await answers({
98
+ deadline: Date.now() + ANSWER_WAIT_MS,
99
+ tool,
100
+ url: `${url}/.well-known/t3/environment`
101
+ })) throw new Error(`Can't ${VERB}. T3 Code in sandbox ${sandbox.id} on ${providerOf(sandbox)} didn't answer at ${url} within 2 minutes, so Sandcovery destroyed it.`);
102
+ const link = await ranT3({
103
+ args: [
104
+ "environment",
105
+ "link",
106
+ url,
107
+ "--pairing-code",
108
+ pairing.value.credential,
109
+ ...toArray(access).flatMap((value) => ["--access", value])
110
+ ],
111
+ signal: tool.signal,
112
+ t3
113
+ });
114
+ if (link.code !== 0) throw new Error(`Can't ${VERB}. t3 environment link exited with ${String(link.code)}, so Sandcovery destroyed sandbox ${sandbox.id}.`, { cause: `${link.stdout}${link.stderr}`.slice(-2e3) });
115
+ return link.stdout.trim();
116
+ };
117
+ const t3Run = async (tool) => {
118
+ const { values } = parseArgs({
119
+ args: [...tool.args],
120
+ options: {
121
+ access: { type: "string" },
122
+ env: {
123
+ type: "string",
124
+ multiple: true
125
+ },
126
+ provider: {
127
+ type: "string",
128
+ multiple: true
129
+ },
130
+ ttl: { type: "string" }
131
+ },
132
+ strict: true
133
+ });
134
+ const env = Object.fromEntries((values.env ?? []).map((pair) => {
135
+ const at = pair.indexOf("=");
136
+ if (at < 1) throw new Error("--env takes NAME=value.");
137
+ return [pair.slice(0, at), pair.slice(at + 1)];
138
+ }));
139
+ const ttl = fromUndefinedOr(values.ttl).pipe(map(Number));
140
+ if (exists(ttl, (seconds) => !Number.isSafeInteger(seconds) || seconds < 1)) throw new Error("--ttl takes a number of seconds.");
141
+ const t3 = onPath(T3);
142
+ if (isNone(t3)) throw new Error(`Can't ${VERB}. t3 isn't on PATH.`);
143
+ const own = await ranT3({
144
+ args: ["--version"],
145
+ signal: tool.signal,
146
+ t3: t3.value
147
+ });
148
+ const word = own.stdout.trim().split(" ").at(-1) ?? "";
149
+ const version = word.startsWith("v") ? word.slice(1) : word;
150
+ if (own.code !== 0 || version === "") throw new Error(`Can't ${VERB}. ${t3.value} --version printed no version.`, { cause: own.stderr.slice(-2e3) });
151
+ const sandbox = await tool.client.sandboxes.create({
152
+ disk_mib: null,
153
+ egress: null,
154
+ env: null,
155
+ gpu: null,
156
+ idle_timeout_seconds: null,
157
+ image: null,
158
+ os: null,
159
+ ports: [T3_PORT],
160
+ provider: match(fromUndefinedOr(values.provider), {
161
+ onNone: () => null,
162
+ onSome: (only) => ({
163
+ allow_fallbacks: null,
164
+ ignore: null,
165
+ only,
166
+ order: null,
167
+ sort: null
168
+ })
169
+ }),
170
+ region: null,
171
+ slug: null,
172
+ slugs: null,
173
+ snapshot_id: null,
174
+ ttl_seconds: getOrNull(ttl)
175
+ }, {
176
+ idempotencyKey: v7(),
177
+ signal: tool.signal
178
+ });
179
+ try {
180
+ const said = await linked({
181
+ access: fromUndefinedOr(values.access),
182
+ env,
183
+ sandbox,
184
+ t3: t3.value,
185
+ tool,
186
+ version
187
+ });
188
+ tool.io.stderr.write(`${said}\nT3 Code ${version} in sandbox ${sandbox.id} runs until ${sandbox.expires_at}. sandcovery sandboxes destroySandbox --sandbox_id ${sandbox.id} ends it sooner, and t3 environment unlink then removes the link here.\n`);
189
+ tool.io.stdout.write(`${sandbox.id}\n`);
190
+ } catch (error) {
191
+ if (!tool.signal.aborted) await tool.client.sandboxes.destroy(sandbox.id, { signal: tool.signal });
192
+ throw error;
193
+ }
194
+ return 0;
195
+ };
196
+ // src/cli/sandcovery-t3.ts
197
+ await startTool({ run: t3Run });
198
+ export {};
package/dist/index.d.mts CHANGED
@@ -1,20 +1,27 @@
1
- import { $ as FileList, An as XAccountStatus, B as DetachedExec, C as CiJob, Cn as UsageShareList, Ct as PortPreview, Dt as ProblemReportRequest, Ft as ProviderCatalog, I as CredentialFields, J as ExecEvent, K as EstimateList, L as CreditCheckout, Lt as ProviderCredential, M as CreateSandboxRequest, Mt as Provider, N as CreateUsageShareRequest, Nt as ProviderBoard, Ot as Process, P as CreatedKey, Pt as ProviderBoardEntry, R as CreditPurchaseRequest, Rt as ProviderCredentialList, S as CiInstallationList, T as CiJobList, Tn as UsageTotals, V as DetachedExecRequest, X as ExecResult, Y as ExecRequest, Z as FileEntry, Zt as Sandbox, _n as UpdateKeyRequest, c as AutoTopUpRequest, en as SandboxList, fn as Stats, ht as MonthlyCostList, i as ActivityList, in as SharedUsage, j as CreateKeyRequest, jn as XPostRequest, kn as XAccountLink, kt as ProcessRequest, o as AutoTopUp, pt as LiveUsage, q as EstimateRequest, s as AutoTopUpChange, sn as Snapshot, st as Key, tn as SandboxStatus, u as Billing, ut as KeyList, vn as Usage, vt as Offer, wt as Pricing, xn as UsageShare } from "./types-C4amb2QE.mjs";
2
- interface ProcessExit {
3
- readonly code: number;
4
- readonly signal: string | null;
5
- }
6
- interface AttachOptions {
7
- readonly signal?: AbortSignal;
8
- readonly stderr?: (data: Uint8Array) => void;
9
- readonly stdout?: (data: Uint8Array) => void;
10
- }
11
- interface ProcessAttachment {
12
- readonly endStdin: () => void;
13
- readonly exit: Promise<ProcessExit>;
14
- readonly resize: (cols: number, rows: number) => void;
15
- readonly sendSignal: (name: string) => void;
16
- readonly write: (data: Uint8Array) => Promise<void>;
17
- }
1
+ import { $ as FileEntry, An as UsageShare, At as Pricing, B as CreditPurchaseRequest, Bn as XPostRequest, Bt as ProviderBoardEntry, D as CiJobList, Dn as Usage, En as UpdateKeyRequest, F as CreateUsageShareRequest, Ft as ProcessRequest, H as DetachedExec, I as CreatedKey, J as EstimateList, Mn as UsageShareList, N as CreateKeyRequest, Nt as ProblemReportRequest, P as CreateSandboxRequest, Pn as UsageTotals, Pt as Process, Q as ExecResult, R as CredentialFields, Rn as XAccountLink, Rt as Provider, Sn as StatsShare, St as Offer, T as CiJob, U as DetachedExecRequest, Ut as ProviderCredential, Vt as ProviderCatalog, Wt as ProviderCredentialList, X as ExecEvent, Y as EstimateRequest, Z as ExecRequest, a as ActivityList, bn as Stats, c as AutoTopUpChange, d as Billing, dn as SharedUsage, dt as KeyList, gt as LiveUsage, hn as SnapshotList, kt as PortPreview, l as AutoTopUpRequest, lt as Key, mn as Snapshot, on as SandboxList, rn as Sandbox, s as AutoTopUp, sn as SandboxStatus, tt as FileList, un as SharedStats, vt as MonthlyCostList, w as CiInstallationList, wt as OperatingSystemPick, z as CreditCheckout, zn as XAccountStatus, zt as ProviderBoard } from "./types-B52jOW9v.mjs";
2
+ declare const attach: ({ check, credential, options, url }: {
3
+ readonly check: () => Promise<{
4
+ readonly status: string;
5
+ }>;
6
+ readonly credential: string | null;
7
+ readonly options: {
8
+ readonly signal: AbortSignal | null;
9
+ readonly stderr: ((data: Uint8Array) => void) | null;
10
+ readonly stdout: ((data: Uint8Array) => void) | null;
11
+ };
12
+ readonly url: URL;
13
+ }) => {
14
+ endStdin: () => void;
15
+ exit: Promise<{
16
+ readonly code: number;
17
+ readonly signal: string | null;
18
+ }>;
19
+ resize: (cols: number, rows: number) => void;
20
+ sendSignal: (name: string) => void;
21
+ write: (data: Uint8Array) => Promise<void>;
22
+ };
23
+ type AttachOptions = Parameters<typeof attach>[0]["options"];
24
+ type ProcessAttachment = ReturnType<typeof attach>;
18
25
  interface RequestOptions {
19
26
  readonly signal?: AbortSignal;
20
27
  }
@@ -30,6 +37,7 @@ interface ListSandboxesQuery extends PageQuery {
30
37
  }
31
38
  interface MonthlyCostQuery {
32
39
  readonly hours_per_day: number;
40
+ readonly os?: OperatingSystemPick;
33
41
  readonly size: string;
34
42
  }
35
43
  interface UsageQuery {
@@ -42,7 +50,7 @@ type SandboxCall<Result> = (sandboxId: string, options?: RequestOptions) => Prom
42
50
  type FileCall<Result> = (sandboxId: string, path: string, options?: RequestOptions) => Promise<Result>;
43
51
  interface SandboxesApi {
44
52
  readonly attachProcess: (sandboxId: string, processId: string, options?: AttachOptions) => ProcessAttachment;
45
- readonly create: (request?: CreateSandboxRequest, options?: CreateSandboxOptions) => Promise<Sandbox>;
53
+ readonly create: (request: CreateSandboxRequest, options?: CreateSandboxOptions) => Promise<Sandbox>;
46
54
  readonly destroy: SandboxCall<Sandbox>;
47
55
  readonly downloadFile: FileCall<ReadableStream<Uint8Array>>;
48
56
  readonly exec: (sandboxId: string, request: ExecRequest, options?: RequestOptions) => Promise<ExecResult>;
@@ -52,6 +60,7 @@ interface SandboxesApi {
52
60
  readonly getProcess: (sandboxId: string, processId: string, options?: RequestOptions) => Promise<Process>;
53
61
  readonly list: (query?: ListSandboxesQuery, options?: RequestOptions) => Promise<SandboxList>;
54
62
  readonly listFiles: FileCall<FileList>;
63
+ readonly listSnapshots: (options?: RequestOptions) => Promise<SnapshotList>;
55
64
  readonly pause: SandboxCall<Sandbox>;
56
65
  readonly portPreview: (sandboxId: string, port: number, options?: RequestOptions) => Promise<PortPreview>;
57
66
  readonly readFile: FileCall<Uint8Array>;
@@ -105,6 +114,10 @@ interface ProvidersApi {
105
114
  }
106
115
  interface StatsApi {
107
116
  readonly get: (options?: RequestOptions) => Promise<Stats>;
117
+ readonly getShare: (options?: RequestOptions) => Promise<StatsShare>;
118
+ readonly getShared: (token: string, options?: RequestOptions) => Promise<SharedStats>;
119
+ readonly share: (options?: RequestOptions) => Promise<StatsShare>;
120
+ readonly unshare: (options?: RequestOptions) => Promise<void>;
108
121
  }
109
122
  interface UsageKeyQuery {
110
123
  readonly api_key_id?: string;
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- export { t as Sandcovery } from "./src-BqfeIyqj.mjs";
1
+ export { t as Sandcovery } from "./src-gAv6vIvE.mjs";