sandcovery 0.7.0 → 0.10.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,10 +1,13 @@
1
1
  #!/usr/bin/env node
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";
2
+ import { bo as some } from "../src-Ce-b80jJ.mjs";
3
+ import { a as watchIdle, i as IDLE_WATCHER_ENV, n as kubectlRun } from "../kubectl-BZIzN5z0.mjs";
4
+ import { l as startTool } from "../saved-sandboxes-XNeQ5SEm.mjs";
4
5
  // src/cli/sandcovery-kubectl.ts
5
6
  await startTool({
6
7
  run: kubectlRun,
7
- serve: watchIdle,
8
- variable: IDLE_WATCHER_ENV
8
+ server: some({
9
+ serve: watchIdle,
10
+ variable: IDLE_WATCHER_ENV
11
+ })
9
12
  });
10
13
  export {};
@@ -1,18 +1,39 @@
1
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";
2
+ import { $a as exists, Mt as Struct, Wt as decodeUnknownOption, Zt as makeFilter, _o as match, fo as isNone, go as map, lo as getOrNull, qt as fromJsonString, so as fromUndefinedOr, vo as none, xo as toArray, xt as NonEmptyString } from "../src-Ce-b80jJ.mjs";
3
+ import { l as startTool, o as DESTROY_TIMEOUT_MS, s as createdSandbox, w as noop } from "../saved-sandboxes-XNeQ5SEm.mjs";
4
+ import { r as onPath, t as answers } from "../kubectl-BZIzN5z0.mjs";
5
5
  import { spawn } from "node:child_process";
6
+ import { once } from "node:events";
6
7
  import { parseArgs } from "node:util";
7
8
  // src/cli/commands/t3.ts
8
9
  const T3_PORT = 3773;
9
10
  const T3 = process.platform === "win32" ? "t3.exe" : "t3";
10
11
  const VERB = "link a sandbox to T3 Code";
11
- const EXEC_TIMEOUT_SECONDS = 600;
12
+ const USAGE = `Usage: sandcovery-t3 [--access <access>] [--env NAME=value]... [--provider <provider>]... [--ttl <seconds>]
13
+
14
+ Creates a sandbox, installs the same version of T3 Code there as your local t3, links it to your T3 Code as an environment, and prints the sandbox's ID. Any failed step destroys the sandbox.
15
+
16
+ --access <access> What agents on your computer may do there, as t3 environment link --access takes it.
17
+ --env NAME=value A variable only T3 Code and the agents it runs get. Repeat it for each variable.
18
+ --provider <provider> A provider to use. Repeat it for each provider.
19
+ --ttl <seconds> The sandbox's TTL in seconds.
20
+ -h, --help Print this help.
21
+
22
+ It reads your key from SANDCOVERY_API_KEY, or from sandcovery login, and the API origin from SANDCOVERY_BASE_URL.
23
+ `;
24
+ const STEP_SECONDS = 20;
25
+ const POLL_SECONDS = 12;
26
+ const INSTALL_WAIT_MS = 6e5;
27
+ const SERVE_WAIT_MS = 12e4;
12
28
  const ANSWER_WAIT_MS = 12e4;
29
+ const STDERR_CHARACTERS = 2e3;
13
30
  const T3_HOME = "\"$HOME/.t3\"";
14
31
  const ON_PATH = "export PATH=\"$HOME/.local/bin:$PATH\"";
15
- const INSTALL_COMMAND = [
32
+ const INSTALL_STATUS = `${T3_HOME}/install.status`;
33
+ const INSTALL_LOG = `${T3_HOME}/install.log`;
34
+ const INSTALL_PID = `${T3_HOME}/install.pid`;
35
+ const INSTALL_RUNNING = `{ p=$(cat ${INSTALL_PID}) s=; kill -0 "$p" 2>/dev/null && { read -r _ _ s _ 2>/dev/null </proc/"$p"/stat; test "$s" != Z; }; }`;
36
+ const INSTALL_SCRIPT = [
16
37
  "set -e",
17
38
  ON_PATH,
18
39
  "curl -fsSL https://t3.codes/install.sh -o /tmp/t3-install.sh",
@@ -24,33 +45,47 @@ const INSTALL_COMMAND = [
24
45
  `mkdir -p ${T3_HOME}/userdata`,
25
46
  `printf '%s\\n' '{"linkedEnvironmentsEnabled":true}' >${T3_HOME}/userdata/settings.json`
26
47
  ].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`
48
+ const INSTALL_COMMAND = [
49
+ `mkdir -p ${T3_HOME}`,
50
+ `rm -f ${INSTALL_STATUS}`,
51
+ `cat >${T3_HOME}/install.sh <<'T3_INSTALL'`,
52
+ INSTALL_SCRIPT,
53
+ "T3_INSTALL",
54
+ `$(command -v setsid) nohup sh -c 'sh ${T3_HOME}/install.sh >${INSTALL_LOG} 2>&1; echo $? >${T3_HOME}/install.code; mv ${T3_HOME}/install.code ${INSTALL_STATUS}' </dev/null >/dev/null 2>&1 &`,
55
+ `echo $! >${INSTALL_PID}`
56
+ ].join("\n");
57
+ const INSTALL_POLL_COMMAND = [
58
+ `for _ in $(seq ${String(POLL_SECONDS)}); do test -s ${INSTALL_STATUS} && break; ${INSTALL_RUNNING} || break; sleep 1; done`,
59
+ `tail -c ${String(STDERR_CHARACTERS)} ${INSTALL_LOG} >&2`,
60
+ `if test -s ${INSTALL_STATUS}; then cat ${INSTALL_STATUS}; elif ${INSTALL_RUNNING}; then :; elif test -s ${INSTALL_STATUS}; then cat ${INSTALL_STATUS}; else echo stopped; fi`
61
+ ].join("\n");
62
+ const SERVE_COMMAND = [ON_PATH, `$(command -v setsid) nohup 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");
63
+ const SERVED_POLL_COMMAND = [
64
+ `end=$(($(date +%s) + ${String(POLL_SECONDS)}))`,
65
+ `until curl -fsS -m 2 -o /dev/null http://127.0.0.1:${String(T3_PORT)}/.well-known/t3/environment; do test "$(date +%s)" -lt "$end" || { tail -c ${String(STDERR_CHARACTERS)} ${T3_HOME}/serve.log >&2; exit 0; }; sleep 1; done`,
66
+ "echo served"
32
67
  ].join("\n");
33
- const decodePairing = decodeUnknownOption(fromJsonString(Struct({ credential: NonEmptyString })));
68
+ const PAIR_COMMAND = [ON_PATH, `t3 auth pairing create --base-dir ${T3_HOME} --json --ttl 10m --label sandcovery`].join("\n");
69
+ const decodePairing = decodeUnknownOption(fromJsonString(Struct({ credential: NonEmptyString.check(makeFilter((credential) => !credential.includes("\n"))) })));
34
70
  const providerOf = (sandbox) => sandbox.provider ?? "its provider";
35
- const ranT3 = async ({ args, signal, t3 }) => {
36
- const closed = Promise.withResolvers();
71
+ const ranT3 = async ({ args, input, signal, t3 }) => {
37
72
  const child = spawn(t3, args, {
38
73
  signal,
39
74
  stdio: [
40
- "ignore",
75
+ "pipe",
41
76
  "pipe",
42
77
  "pipe"
43
78
  ]
44
79
  });
45
- child.once("error", closed.reject);
46
- child.once("close", closed.resolve);
47
- const [stdout, stderr, code] = await Promise.all([
80
+ child.stdin.on("error", noop);
81
+ child.stdin.end(input);
82
+ const [stdout, stderr] = await Promise.all([
48
83
  child.stdout.toArray(),
49
84
  child.stderr.toArray(),
50
- closed.promise
85
+ once(child, "close")
51
86
  ]);
52
87
  return {
53
- code: code ?? 1,
88
+ code: child.exitCode ?? 1,
54
89
  stderr: Buffer.concat(stderr).toString(),
55
90
  stdout: Buffer.concat(stdout).toString()
56
91
  };
@@ -58,12 +93,29 @@ const ranT3 = async ({ args, signal, t3 }) => {
58
93
  const ranInSandbox = async ({ command, env, sandbox, step, tool }) => {
59
94
  const result = await tool.client.sandboxes.exec(sandbox.id, {
60
95
  command,
61
- cwd: null,
62
96
  env,
63
- timeout_seconds: EXEC_TIMEOUT_SECONDS
97
+ cwd: null,
98
+ timeout_seconds: STEP_SECONDS
64
99
  }, { signal: tool.signal });
65
100
  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;
101
+ return result;
102
+ };
103
+ const awaited = async ({ command, deadline, sandbox, step, tool }) => {
104
+ const result = await ranInSandbox({
105
+ env: null,
106
+ command,
107
+ sandbox,
108
+ step,
109
+ tool
110
+ });
111
+ if (result.stdout.trim() !== "" || Date.now() > deadline) return result;
112
+ return await awaited({
113
+ command,
114
+ deadline,
115
+ sandbox,
116
+ step,
117
+ tool
118
+ });
67
119
  };
68
120
  const linked = async ({ access, env, sandbox, t3, tool, version }) => {
69
121
  const preview = await tool.client.sandboxes.portPreview(sandbox.id, T3_PORT, { signal: tool.signal });
@@ -74,40 +126,57 @@ const linked = async ({ access, env, sandbox, t3, tool, version }) => {
74
126
  await ranInSandbox({
75
127
  command: INSTALL_COMMAND,
76
128
  env: { T3CODE_VERSION: version },
129
+ step: `start installing T3 Code ${version}`,
77
130
  sandbox,
78
- step: `install T3 Code ${version}`,
79
131
  tool
80
132
  });
133
+ const installed = await awaited({
134
+ command: INSTALL_POLL_COMMAND,
135
+ deadline: Date.now() + INSTALL_WAIT_MS,
136
+ step: `check on the T3 Code ${version} install`,
137
+ sandbox,
138
+ tool
139
+ });
140
+ if (installed.stdout.trim() === "") throw new Error(`Can't ${VERB}. T3 Code ${version} didn't finish installing in sandbox ${sandbox.id} on ${providerOf(sandbox)} within 10 minutes, so Sandcovery destroyed it.`, { cause: installed.stderr });
141
+ if (installed.stdout.trim() !== "0") throw new Error(`Can't ${VERB}. Couldn't install T3 Code ${version} in sandbox ${sandbox.id} on ${providerOf(sandbox)}, so Sandcovery destroyed it.`, { cause: installed.stderr });
81
142
  await ranInSandbox({
82
143
  command: SERVE_COMMAND,
144
+ step: "start T3 Code",
83
145
  env,
84
146
  sandbox,
85
- step: "start T3 Code",
86
147
  tool
87
148
  });
149
+ const served = await awaited({
150
+ command: SERVED_POLL_COMMAND,
151
+ deadline: Date.now() + SERVE_WAIT_MS,
152
+ step: "check that T3 Code serves",
153
+ sandbox,
154
+ tool
155
+ });
156
+ if (served.stdout.trim() === "") throw new Error(`Can't ${VERB}. T3 Code ${version} didn't start serving in sandbox ${sandbox.id} on ${providerOf(sandbox)} within 2 minutes, so Sandcovery destroyed it.`, { cause: served.stderr });
88
157
  const paired = await ranInSandbox({
89
158
  command: PAIR_COMMAND,
90
159
  env: null,
91
- sandbox,
92
160
  step: "make a T3 Code pairing code",
161
+ sandbox,
93
162
  tool
94
163
  });
95
- const pairing = decodePairing(paired.trim());
164
+ const pairing = decodePairing(paired.stdout.trim());
96
165
  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
166
  if (!await answers({
98
167
  deadline: Date.now() + ANSWER_WAIT_MS,
99
- tool,
100
- url: `${url}/.well-known/t3/environment`
168
+ url: `${url}/.well-known/t3/environment`,
169
+ tool
101
170
  })) 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
171
  const link = await ranT3({
103
172
  args: [
104
173
  "environment",
105
174
  "link",
106
- url,
107
- "--pairing-code",
108
- pairing.value.credential,
175
+ "--from",
176
+ "-",
109
177
  ...toArray(access).flatMap((value) => ["--access", value])
110
178
  ],
179
+ input: `${url} ${pairing.value.credential}\n`,
111
180
  signal: tool.signal,
112
181
  t3
113
182
  });
@@ -123,6 +192,10 @@ const t3Run = async (tool) => {
123
192
  type: "string",
124
193
  multiple: true
125
194
  },
195
+ help: {
196
+ short: "h",
197
+ type: "boolean"
198
+ },
126
199
  provider: {
127
200
  type: "string",
128
201
  multiple: true
@@ -131,6 +204,10 @@ const t3Run = async (tool) => {
131
204
  },
132
205
  strict: true
133
206
  });
207
+ if (values.help === true) {
208
+ tool.io.stdout.write(USAGE);
209
+ return 0;
210
+ }
134
211
  const env = Object.fromEntries((values.env ?? []).map((pair) => {
135
212
  const at = pair.indexOf("=");
136
213
  if (at < 1) throw new Error("--env takes NAME=value.");
@@ -142,57 +219,62 @@ const t3Run = async (tool) => {
142
219
  if (isNone(t3)) throw new Error(`Can't ${VERB}. t3 isn't on PATH.`);
143
220
  const own = await ranT3({
144
221
  args: ["--version"],
222
+ input: "",
145
223
  signal: tool.signal,
146
224
  t3: t3.value
147
225
  });
148
226
  const word = own.stdout.trim().split(" ").at(-1) ?? "";
149
227
  const version = word.startsWith("v") ? word.slice(1) : word;
150
228
  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
229
+ const sandbox = await createdSandbox({
230
+ request: {
231
+ api_key_id: null,
232
+ disk_mib: null,
233
+ egress: null,
234
+ env: null,
235
+ gpu: null,
236
+ idle_timeout_seconds: null,
237
+ image: null,
238
+ os: null,
239
+ ports: [T3_PORT],
240
+ provider: match(fromUndefinedOr(values.provider), {
241
+ onNone: () => null,
242
+ onSome: (only) => ({
243
+ allow_fallbacks: null,
244
+ ignore: null,
245
+ order: null,
246
+ sort: null,
247
+ only
248
+ })
249
+ }),
250
+ region: null,
251
+ slug: null,
252
+ slugs: null,
253
+ snapshot_id: null,
254
+ ttl_seconds: getOrNull(ttl)
255
+ },
256
+ tool
178
257
  });
179
258
  try {
180
259
  const said = await linked({
181
260
  access: fromUndefinedOr(values.access),
261
+ t3: t3.value,
182
262
  env,
183
263
  sandbox,
184
- t3: t3.value,
185
264
  tool,
186
265
  version
187
266
  });
188
267
  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
268
  tool.io.stdout.write(`${sandbox.id}\n`);
190
269
  } catch (error) {
191
- if (!tool.signal.aborted) await tool.client.sandboxes.destroy(sandbox.id, { signal: tool.signal });
270
+ await tool.client.sandboxes.destroy(sandbox.id, { signal: AbortSignal.timeout(DESTROY_TIMEOUT_MS) });
192
271
  throw error;
193
272
  }
194
273
  return 0;
195
274
  };
196
275
  // src/cli/sandcovery-t3.ts
197
- await startTool({ run: t3Run });
276
+ await startTool({
277
+ run: t3Run,
278
+ server: none()
279
+ });
198
280
  export {};