@lizard-build/cli 4.0.130 → 4.0.132

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.
@@ -13,6 +13,7 @@ The details behind the Sandboxes section of the core guide. Read the part the ta
13
13
  - [Interactive shell](#interactive-shell)
14
14
  - [Coding agents](#coding-agents)
15
15
  - [Schedules (wake, run, sleep)](#schedules-wake-run-sleep)
16
+ - [Environments (what a new sandbox starts with)](#environments-what-a-new-sandbox-starts-with)
16
17
  - [Desktop (computer use)](#desktop-computer-use)
17
18
  - [Volumes](#volumes)
18
19
  - [Snapshots and pause/resume](#snapshots-and-pauseresume)
@@ -139,12 +140,18 @@ The platform can wake a paused sandbox on a timer, run a prompt or a shell comma
139
140
  it back to sleep. You pay only while it is awake; files in `/workspace` carry over between runs.
140
141
 
141
142
  ```bash
142
- lizard sandbox schedule <id> --every 5m --prompt "Continue the research in /workspace/research; append findings to notes.md"
143
- lizard sandbox schedule <id> --every 10m --command "python3 /workspace/job.py"
144
- lizard sandbox schedule <id> --cron "0 9 * * mon-fri" --tz Europe/Berlin --command "./report.sh"
143
+ # A schedule is set when the sandbox is created (an existing sandbox takes no new one):
144
+ lizard sandbox create --timeout 0 --every 10m --command "python3 /workspace/job.py"
145
+ lizard sandbox create -t claude --timeout 0 --every 5m --prompt "Continue the research in /workspace/research; append findings to notes.md"
146
+ lizard sandbox create --timeout 0 --daily-at 09:00 --weekdays --tz Europe/Berlin --command "./report.sh"
147
+ lizard sandbox create --timeout 0 --cron "0 */6 * * *" --command "./sync.sh"
148
+ lizard sandbox create -e staging --timeout 0 --every 1h --command "./check.sh" # with an environment's variables
149
+ lizard sandbox schedule <id> --every 10m --command "..." # only in the sandbox's first 15 minutes
145
150
  lizard sandbox schedules [<id>] # list, with next and last run
151
+ lizard sandbox schedule-show <sch_id> # one schedule, with the full prompt or command
152
+ lizard sandbox schedule-runs [-p <project>] # the project's latest runs across all its schedules
153
+ lizard sandbox schedule-runs <sch_id> [-o] # one schedule's history; -o prints the latest output
146
154
  lizard sandbox schedule-run <sch_id> --wait # run now and print the result
147
- lizard sandbox schedule-runs <sch_id> [-o] # history; -o prints the latest output
148
155
  lizard sandbox schedule-set <sch_id> --every 15m | --off | --on
149
156
  lizard sandbox unschedule <sch_id>
150
157
  ```
@@ -157,8 +164,66 @@ lizard sandbox unschedule <sch_id>
157
164
  - A sandbox that was already running when a run starts is left running afterwards.
158
165
  - A run still going when the next is due makes that one skip. `--timeout` (default 10m) stops a
159
166
  run. Five failed runs in a row switch the schedule off (`schedules` shows why).
160
- - Every 1m at most often. Prompt schedules need a key with no scopes (`ACCOUNT_SCOPE_REQUIRED`);
161
- `--command` schedules work with scoped keys. Not on every account yet: `SCHEDULES_NOT_ENABLED`.
167
+ - Only at creation: a sandbox older than 15 minutes answers `SCHEDULE_ONLY_AT_CREATE` to a new
168
+ schedule; create a new sandbox with one. Its existing schedules can still be changed, run, deleted.
169
+ - `--prompt` needs a sandbox with an agent: create it from `-t claude`, `codex`, `opencode`, `pi`
170
+ or `prime`. The base template has none (`AGENT_NOT_IN_SANDBOX`); `--command` works anywhere.
171
+ - When: `--every` (1m to 30d), `--daily-at HH:MM` (add `--weekdays` for Monday to Friday), or
172
+ `--cron`; `--tz` is the time zone of the last two (UTC otherwise). One of the three.
173
+ - On `create` the run limit is `--run-timeout` and the label `--schedule-name` (create's own
174
+ `--timeout` is the sandbox's lifetime); on `schedule` / `schedule-set` they are `--timeout` and
175
+ `--name`. Prompt options: `--prompt-file <path>`, `--agent`, `-m <model>`, `--effort`. A run may
176
+ last 6 h at most. `schedule --disabled` creates it switched off.
177
+ - Prompt schedules need a key with no scopes (`ACCOUNT_SCOPE_REQUIRED`); `--command` schedules work
178
+ with scoped keys. A prompt schedule can be changed or run only by whoever created it
179
+ (`SCHEDULE_CREATOR_ONLY`); anyone in the project may switch it off, rename or delete it.
180
+ - At most 50 schedules per account (`SCHEDULE_LIMIT`); the last 200 runs of each are kept. Not on
181
+ every account yet: `SCHEDULES_NOT_ENABLED`.
182
+ - Keep the sandbox from expiring: create it with `--timeout 0`.
183
+
184
+ ## Environments (what a new sandbox starts with)
185
+
186
+ A project's environment is what every sandbox created in it starts with (dashboard: Sandboxes →
187
+ Environment). It has three parts:
188
+
189
+ - **Variables**: in every process of the sandbox. Stored encrypted; they survive pause and resume.
190
+ - **Agent instructions**: a user-level `CLAUDE.md` (Claude Code) and `AGENTS.md` (Codex, OpenCode,
191
+ pi, Prime), 32 KB each, written into the sandbox at create.
192
+ - **GitHub access**: chosen repositories (the first 10) are cloned into `/workspace/<name>` and
193
+ `git` and `gh` are signed in for them, read or write. Set up in the dashboard only.
194
+
195
+ A project can also hold **named environments**: other complete sets of variables. A sandbox
196
+ created with `-e <name>` gets that environment's variables INSTEAD of the default ones, never both.
197
+ Instructions and GitHub access are the project's, whatever the environment.
198
+
199
+ ```bash
200
+ lizard sandbox environments # the project's environments, instructions, GitHub access
201
+ lizard sandbox environment-show [name] [--values] # variables (values masked without --values)
202
+ lizard sandbox environment-set API_URL=https://api.example.com TOKEN=... # the default environment
203
+ lizard sandbox environment-create staging --copy-from default
204
+ lizard sandbox environment-set -e staging API_URL=https://staging.example.com
205
+ lizard sandbox environment-set -e staging --from-file .env.staging
206
+ lizard sandbox environment-unset -e staging OLD_KEY
207
+ lizard sandbox environment-rename staging preview
208
+ lizard sandbox environment-rm preview
209
+ lizard sandbox environment-instructions --claude-md ./CLAUDE.md --agents-md ./AGENTS.md
210
+ lizard sandbox environment-instructions --print claude-md | --clear-agents-md
211
+ lizard sandbox create -e staging # start with the staging variables
212
+ lizard sandbox create --repo owner/name # one repository of your own, instead of the project's
213
+ ```
214
+
215
+ - A change applies to sandboxes created after it; a running sandbox keeps what it started with.
216
+ - `-e` takes the environment's name; an unknown one is refused with the names there are
217
+ (`SANDBOX_ENVIRONMENT_NOT_FOUND`). `-e default` is the same as no `-e`.
218
+ - Every command takes `-p <project>`; without it, the linked project, else the default project.
219
+ - Up to 200 variables per environment (names: letters, digits and `_`; values up to 32 KB) and 20
220
+ named environments per project (names: letters, digits, spaces and `. _ -`, at most 40 characters).
221
+ - Never print values to the user or into a log: `environment-show` masks them unless `--values`.
222
+ - `create --repo owner/name` (add `--repo-workflows` to let it change `.github/workflows`) gives the
223
+ sandbox write access to that one repository, cloned into `/workspace/<name>`, in place of the
224
+ project's GitHub access. It needs your own GitHub sign-in and a key with no scopes.
225
+ - Not on every account yet: the commands answer `SANDBOX_ENVIRONMENT_NOT_ENABLED`, and creating a
226
+ second environment `SANDBOX_ENVIRONMENTS_NOT_ENABLED`.
162
227
 
163
228
  ## Desktop (computer use)
164
229
 
@@ -0,0 +1,235 @@
1
+ import chalk from "chalk";
2
+ import fs from "node:fs";
3
+ import { Command } from "commander";
4
+ import { api } from "../lib/api.js";
5
+ import { resolveProjectId } from "../lib/config.js";
6
+ import { success, info, isJSONMode, printJSON, table, fail } from "../lib/format.js";
7
+
8
+ // Sandbox environments: what a project's new sandboxes start with (the dashboard's Sandboxes →
9
+ // Environment tab). Server: /api/projects/:id/sandbox-environment (the default environment: its
10
+ // variables, the agents' instruction files, GitHub access) and /sandbox-environments (named
11
+ // environments: variables only). `lizard sandbox create -e <name>` picks one.
12
+
13
+ interface Summary { id: string; name: string; default: boolean; variableCount: number }
14
+ interface Variable { key: string; value: string }
15
+ interface ProjectEnvironment {
16
+ variables: Variable[];
17
+ instructions: { claudeMd: string | null; agentsMd: string | null };
18
+ github: { account: string; access: "read" | "write"; workflows: boolean; enabled: boolean; repos: { id: number; fullName: string }[] } | null;
19
+ }
20
+
21
+ const INSTRUCTIONS_MAX_BYTES = 32_768;
22
+ const isDefault = (name?: string) => !name || name.trim().toLowerCase() === "default";
23
+ const base = (projectId: string) => `/api/projects/${encodeURIComponent(projectId)}/sandbox-environment`;
24
+ const named = (projectId: string, name: string) => `${base(projectId)}s/${encodeURIComponent(name.trim())}`;
25
+
26
+ /** The server answers a bare 404 while the feature is off for the account: say that, not "not found". */
27
+ async function call<T>(run: () => Promise<T>): Promise<T> {
28
+ try {
29
+ return await run();
30
+ } catch (e: any) {
31
+ if (e?.status === 404 && !e?.code && /^not found$/i.test(String(e?.message ?? "").trim())) {
32
+ fail("Sandbox environments are not available on this account yet", 1, "SANDBOX_ENVIRONMENT_NOT_ENABLED");
33
+ }
34
+ throw e;
35
+ }
36
+ }
37
+
38
+ /** KEY=VALUE arguments (and --from-file lines) as { KEY: value }. */
39
+ export function parseAssignments(pairs: string[], file?: string): Record<string, string> {
40
+ const out: Record<string, string> = {};
41
+ const take = (line: string, where: string) => {
42
+ const i = line.indexOf("=");
43
+ if (i <= 0) fail(`${where}: expected KEY=VALUE, got "${line.slice(0, 40)}"`, 2, "USAGE");
44
+ out[line.slice(0, i).trim()] = line.slice(i + 1);
45
+ };
46
+ if (file) {
47
+ for (const raw of fs.readFileSync(file, "utf8").split(/\r?\n/)) {
48
+ const line = raw.trim();
49
+ if (!line || line.startsWith("#")) continue;
50
+ const stripped = line.replace(/^export\s+/, "");
51
+ const i = stripped.indexOf("=");
52
+ if (i <= 0) fail(`${file}: expected KEY=VALUE, got "${line.slice(0, 40)}"`, 2, "USAGE");
53
+ // A value in matching quotes is taken without them, as a .env file means it.
54
+ const value = stripped.slice(i + 1).trim().replace(/^(["'])(.*)\1$/, "$2");
55
+ out[stripped.slice(0, i).trim()] = value;
56
+ }
57
+ }
58
+ for (const p of pairs) take(p, "argument");
59
+ return out;
60
+ }
61
+
62
+ const mask = (v: string) => (v.length <= 4 ? "****" : `${v.slice(0, 2)}****${v.slice(-2)}`);
63
+
64
+ function readInstructions(path: string): string {
65
+ const text = fs.readFileSync(path, "utf8");
66
+ if (Buffer.byteLength(text, "utf8") > INSTRUCTIONS_MAX_BYTES) fail(`${path} is larger than ${INSTRUCTIONS_MAX_BYTES / 1024} KB`, 2, "USAGE");
67
+ return text;
68
+ }
69
+
70
+ export function registerSandboxEnvironmentCommands(sb: Command) {
71
+ const project = (c: Command) => c.option("-p, --project <id>", "Project (name, slug, or ID). Defaults to the linked project.");
72
+
73
+ project(sb.command("environments").alias("envs")
74
+ .description("List the project's sandbox environments: the sets of variables a new sandbox can start with (create -e <name>)"))
75
+ .addHelpText("after", `
76
+ A project's new sandboxes start with its environment: variables, the agents' instruction files
77
+ (CLAUDE.md / AGENTS.md) and GitHub access. The Default environment is the project's own; a named
78
+ environment is another complete set of variables, used INSTEAD of the default's when a sandbox is
79
+ created with it. Instructions and GitHub access are the project's, whatever the environment.
80
+
81
+ lizard sandbox environment-create staging --copy-from default
82
+ lizard sandbox environment-set -e staging API_URL=https://staging.example.com
83
+ lizard sandbox create -e staging`)
84
+ .action(async (opts) => {
85
+ const projectId = await resolveProjectId(opts.project);
86
+ const [list, env] = await call(() => Promise.all([
87
+ api.get<{ environments: Summary[]; canCreate: boolean }>(`${base(projectId)}s`),
88
+ api.get<ProjectEnvironment>(base(projectId)),
89
+ ]));
90
+ if (isJSONMode()) {
91
+ return printJSON({
92
+ environments: list.environments, canCreate: list.canCreate,
93
+ instructions: { claudeMd: env.instructions.claudeMd !== null, agentsMd: env.instructions.agentsMd !== null },
94
+ github: env.github ? { account: env.github.account, access: env.github.access, enabled: env.github.enabled, repos: env.github.repos.map((r) => r.fullName) } : null,
95
+ });
96
+ }
97
+ table(["environment", "variables"], list.environments.map((e) => [e.default ? `${e.name} ${chalk.dim("(default)")}` : e.name, String(e.variableCount)]));
98
+ const files = [env.instructions.claudeMd !== null && "CLAUDE.md", env.instructions.agentsMd !== null && "AGENTS.md"].filter(Boolean);
99
+ info(chalk.dim(`Agent instructions: ${files.length ? files.join(", ") : "none"}`));
100
+ info(chalk.dim(`GitHub access: ${!env.github ? "not set" : `${env.github.enabled ? env.github.access : "off"}, ${env.github.repos.length} ${env.github.repos.length === 1 ? "repository" : "repositories"} of ${env.github.account}`}`));
101
+ if (!list.canCreate) info(chalk.dim("More than one environment per project is not available on this account yet."));
102
+ });
103
+
104
+ project(sb.command("environment-show").alias("env-show")
105
+ .argument("[name]", "Environment name (default: the project's default environment)")
106
+ .description("Show an environment's variables (values masked; --values prints them)")
107
+ .option("--values", "Print the values in full"))
108
+ .action(async (name: string | undefined, opts) => {
109
+ const projectId = await resolveProjectId(opts.project);
110
+ if (!isDefault(name)) {
111
+ const e = await call(() => api.get<{ id: string; name: string; variables: Variable[] }>(named(projectId, name!)));
112
+ if (isJSONMode()) return printJSON(opts.values ? e : { ...e, variables: e.variables.map((v) => ({ key: v.key })) });
113
+ info(chalk.bold(e.name));
114
+ return printVariables(e.variables, opts.values);
115
+ }
116
+ const env = await call(() => api.get<ProjectEnvironment>(base(projectId)));
117
+ if (isJSONMode()) {
118
+ return printJSON({
119
+ id: "default", name: "Default",
120
+ variables: opts.values ? env.variables : env.variables.map((v) => ({ key: v.key })),
121
+ instructions: { claudeMd: env.instructions.claudeMd !== null, agentsMd: env.instructions.agentsMd !== null },
122
+ github: env.github ? { account: env.github.account, access: env.github.access, workflows: env.github.workflows, enabled: env.github.enabled, repos: env.github.repos.map((r) => r.fullName) } : null,
123
+ });
124
+ }
125
+ info(`${chalk.bold("Default")} ${chalk.dim("(the project's own)")}`);
126
+ printVariables(env.variables, opts.values);
127
+ console.log(`\nAgent instructions CLAUDE.md: ${env.instructions.claudeMd !== null ? "set" : chalk.dim("not set")} AGENTS.md: ${env.instructions.agentsMd !== null ? "set" : chalk.dim("not set")}`);
128
+ if (!env.github) console.log(`GitHub access ${chalk.dim("not set (set it in the dashboard: Sandboxes → Environment)")}`);
129
+ else {
130
+ console.log(`GitHub access ${env.github.enabled ? env.github.access : chalk.yellow("off")}${env.github.workflows ? " + workflows" : ""}, ${env.github.account}`);
131
+ for (const r of env.github.repos) console.log(` ${r.fullName}`);
132
+ }
133
+ });
134
+
135
+ project(sb.command("environment-create").alias("env-create")
136
+ .argument("<name>", "Name: letters, digits, spaces and . _ -, at most 40 characters")
137
+ .description("Create a named environment: another set of variables a sandbox can start with")
138
+ .option("--copy-from <name>", "Start with the variables of another environment (\"default\" or a name)"))
139
+ .action(async (name: string, opts) => {
140
+ const projectId = await resolveProjectId(opts.project);
141
+ const e = await call(() => api.post<{ id: string; name: string; variables: Variable[] }>(`${base(projectId)}s`, { name, ...(opts.copyFrom ? { copyFrom: opts.copyFrom } : {}) }));
142
+ if (isJSONMode()) return printJSON({ id: e.id, name: e.name, variables: e.variables.map((v) => ({ key: v.key })) });
143
+ success(`Environment ${chalk.bold(e.name)} created${e.variables.length ? ` with ${e.variables.length} variable${e.variables.length === 1 ? "" : "s"}` : ""}`);
144
+ info(chalk.dim(` lizard sandbox environment-set -e "${e.name}" KEY=VALUE add variables`));
145
+ info(chalk.dim(` lizard sandbox create -e "${e.name}" start a sandbox with it`));
146
+ });
147
+
148
+ project(sb.command("environment-set").alias("env-set")
149
+ .argument("[assignments...]", "KEY=VALUE ...")
150
+ .description("Set variables in an environment (new sandboxes get them; running ones keep what they started with)")
151
+ .option("-e, --environment <name>", "Environment (default: the project's default environment)")
152
+ .option("--from-file <path>", "Also read KEY=VALUE lines from a file (.env format)"))
153
+ .action(async (pairs: string[], opts) => {
154
+ const changes = parseAssignments(pairs, opts.fromFile);
155
+ if (!Object.keys(changes).length) fail("Nothing to set: give KEY=VALUE or --from-file .env", 2, "USAGE");
156
+ const projectId = await resolveProjectId(opts.project);
157
+ await call(() => api.put(isDefault(opts.environment) ? `${base(projectId)}/variables` : `${named(projectId, opts.environment)}/variables`, changes));
158
+ if (isJSONMode()) return printJSON({ ok: true, environment: isDefault(opts.environment) ? "default" : opts.environment, set: Object.keys(changes) });
159
+ success(`Set ${Object.keys(changes).join(", ")} in ${chalk.bold(isDefault(opts.environment) ? "Default" : opts.environment)}`);
160
+ });
161
+
162
+ project(sb.command("environment-unset").alias("env-unset")
163
+ .argument("<keys...>", "Variable names")
164
+ .description("Remove variables from an environment")
165
+ .option("-e, --environment <name>", "Environment (default: the project's default environment)"))
166
+ .action(async (keys: string[], opts) => {
167
+ const projectId = await resolveProjectId(opts.project);
168
+ const changes = Object.fromEntries(keys.map((k) => [k, null]));
169
+ await call(() => api.put(isDefault(opts.environment) ? `${base(projectId)}/variables` : `${named(projectId, opts.environment)}/variables`, changes));
170
+ if (isJSONMode()) return printJSON({ ok: true, environment: isDefault(opts.environment) ? "default" : opts.environment, removed: keys });
171
+ success(`Removed ${keys.join(", ")} from ${chalk.bold(isDefault(opts.environment) ? "Default" : opts.environment)}`);
172
+ });
173
+
174
+ project(sb.command("environment-rename").alias("env-rename")
175
+ .argument("<name>", "Environment name")
176
+ .argument("<newName>", "New name")
177
+ .description("Rename a named environment"))
178
+ .action(async (name: string, newName: string, opts) => {
179
+ if (isDefault(name)) fail("The default environment cannot be renamed", 2, "USAGE");
180
+ const projectId = await resolveProjectId(opts.project);
181
+ const e = await call(() => api.patch<{ id: string; name: string }>(named(projectId, name), { name: newName }));
182
+ if (isJSONMode()) return printJSON(e);
183
+ success(`Environment renamed to ${chalk.bold(e.name)}`);
184
+ });
185
+
186
+ project(sb.command("environment-rm").alias("env-rm").alias("environment-delete")
187
+ .argument("<name>", "Environment name")
188
+ .description("Delete a named environment (sandboxes already created with it keep their variables)"))
189
+ .action(async (name: string, opts) => {
190
+ if (isDefault(name)) fail("The default environment cannot be deleted; remove its variables with environment-unset", 2, "USAGE");
191
+ const projectId = await resolveProjectId(opts.project);
192
+ await call(() => api.delete(named(projectId, name)));
193
+ if (isJSONMode()) return printJSON({ name, deleted: true });
194
+ success(`Environment ${chalk.bold(name)} deleted`);
195
+ });
196
+
197
+ project(sb.command("environment-instructions").alias("env-instructions")
198
+ .description("Show or set the agents' instruction files every new sandbox of the project gets (CLAUDE.md, AGENTS.md)")
199
+ .option("--claude-md <path>", "Set the user-level CLAUDE.md (Claude Code) from a file")
200
+ .option("--agents-md <path>", "Set the user-level AGENTS.md (Codex, OpenCode, pi, Prime) from a file")
201
+ .option("--clear-claude-md", "Remove CLAUDE.md")
202
+ .option("--clear-agents-md", "Remove AGENTS.md")
203
+ .option("--print <file>", "Print one in full: claude-md or agents-md"))
204
+ .action(async (opts) => {
205
+ const projectId = await resolveProjectId(opts.project);
206
+ const body: Record<string, string | null> = {};
207
+ if (opts.claudeMd) body.claudeMd = readInstructions(opts.claudeMd);
208
+ if (opts.agentsMd) body.agentsMd = readInstructions(opts.agentsMd);
209
+ if (opts.clearClaudeMd) body.claudeMd = null;
210
+ if (opts.clearAgentsMd) body.agentsMd = null;
211
+ if (Object.keys(body).length) {
212
+ await call(() => api.put(`${base(projectId)}/instructions`, body));
213
+ if (isJSONMode()) return printJSON({ ok: true, changed: Object.keys(body) });
214
+ return success(`Agent instructions updated: ${Object.entries(body).map(([k, v]) => `${k === "claudeMd" ? "CLAUDE.md" : "AGENTS.md"} ${v === null ? "removed" : "set"}`).join(", ")}`);
215
+ }
216
+ const env = await call(() => api.get<ProjectEnvironment>(base(projectId)));
217
+ if (opts.print) {
218
+ const which = String(opts.print).toLowerCase().replace(/[^a-z]/g, "");
219
+ if (which !== "claudemd" && which !== "agentsmd") fail("--print takes claude-md or agents-md", 2, "USAGE");
220
+ const text = which === "claudemd" ? env.instructions.claudeMd : env.instructions.agentsMd;
221
+ if (isJSONMode()) return printJSON({ file: which === "claudemd" ? "CLAUDE.md" : "AGENTS.md", text });
222
+ if (text === null) return info("Not set.");
223
+ process.stdout.write(text.endsWith("\n") ? text : text + "\n");
224
+ return;
225
+ }
226
+ if (isJSONMode()) return printJSON({ claudeMd: env.instructions.claudeMd !== null, agentsMd: env.instructions.agentsMd !== null });
227
+ console.log(`CLAUDE.md ${env.instructions.claudeMd !== null ? `${Buffer.byteLength(env.instructions.claudeMd, "utf8")} bytes` : chalk.dim("not set")}`);
228
+ console.log(`AGENTS.md ${env.instructions.agentsMd !== null ? `${Buffer.byteLength(env.instructions.agentsMd, "utf8")} bytes` : chalk.dim("not set")}`);
229
+ });
230
+ }
231
+
232
+ function printVariables(vars: Variable[], values: boolean) {
233
+ if (!vars.length) return info(chalk.dim("No variables."));
234
+ table(["variable", "value"], vars.map((v) => [v.key, values ? v.value : chalk.dim(mask(v.value))]));
235
+ }
@@ -2,6 +2,7 @@ import chalk from "chalk";
2
2
  import fs from "node:fs";
3
3
  import { Command, InvalidArgumentError, Option } from "commander";
4
4
  import { api } from "../lib/api.js";
5
+ import { resolveProjectId } from "../lib/config.js";
5
6
  import { success, info, isJSONMode, printJSON, table, timeAgo, fail } from "../lib/format.js";
6
7
 
7
8
  // Sandbox schedules: the platform wakes a paused sandbox on a timer, runs a prompt (the coding
@@ -29,6 +30,13 @@ function parseDuration(v: string): number {
29
30
  return Number(m[1]) * { s: 1, m: 60, h: 3600, d: 86400 }[(m[2] ?? "s") as "s"];
30
31
  }
31
32
 
33
+ /** --daily-at "09:00" [--weekdays] as the cron the server runs: what the dashboard's "Daily at" makes. */
34
+ export function dailyCron(at: string, weekdays: boolean): string {
35
+ const m = String(at).trim().match(/^([01]?\d|2[0-3]):([0-5]\d)$/);
36
+ if (!m) fail(`--daily-at takes a time as HH:MM (24 h), e.g. 09:00; got "${at}"`, 2, "USAGE");
37
+ return `${Number(m![2])} ${Number(m![1])} * * ${weekdays ? "1-5" : "*"}`;
38
+ }
39
+
32
40
  const when = (s: Schedule) => (s.every ? `every ${s.every}` : `cron ${s.cron}${s.timezone !== "UTC" ? ` (${s.timezone})` : ""}`);
33
41
  const what = (s: Schedule) => {
34
42
  const t = (s.kind === "prompt" ? s.prompt : s.command) ?? "";
@@ -60,7 +68,9 @@ function addTaskOptions(c: Command, forCreate: boolean) {
60
68
  return c
61
69
  .option("--every <interval>", "How often: 1m minimum, e.g. 5m, 1h, 1d")
62
70
  .option("--cron <expr>", 'Cron instead: "m h dom mon dow", e.g. "*/5 * * * *", "0 9 * * mon-fri", @daily')
63
- .option("--tz <zone>", "Time zone for --cron (IANA name, e.g. Europe/Berlin)")
71
+ .option("--daily-at <HH:MM>", "Once a day at this time instead (24 h, in --tz; UTC by default)")
72
+ .option("--weekdays", "With --daily-at: Monday to Friday only")
73
+ .option("--tz <zone>", "Time zone for --daily-at and --cron (IANA name, e.g. Europe/Berlin)")
64
74
  .option("--prompt <text>", "Run the coding agent with this prompt (a new conversation each run)")
65
75
  .option("--prompt-file <path>", "Read the prompt from a file")
66
76
  .option("--command <cmd>", "Run this shell command instead (in /workspace, as root)")
@@ -75,10 +85,67 @@ function addTaskOptions(c: Command, forCreate: boolean) {
75
85
  .option("--name <name>", "A label for the schedule");
76
86
  }
77
87
 
88
+ /**
89
+ * The schedule options of `lizard sandbox create`: a schedule is set when a sandbox is created.
90
+ * The same options as `sandbox schedule`, except the two whose names `create` already uses for
91
+ * the sandbox itself: --run-timeout (create's --timeout is the sandbox's lifetime) and
92
+ * --schedule-name.
93
+ */
94
+ export function addCreateScheduleOptions(c: Command): Command {
95
+ return c
96
+ .option("--every <interval>", "Schedule: wake the sandbox this often and run --command or --prompt (1m minimum, e.g. 5m, 1h, 1d)")
97
+ .option("--cron <expr>", 'Schedule by cron instead: "m h dom mon dow", e.g. "0 9 * * mon-fri", @daily')
98
+ .option("--daily-at <HH:MM>", "Once a day at this time instead (24 h, in --tz; UTC by default)")
99
+ .option("--weekdays", "With --daily-at: Monday to Friday only")
100
+ .option("--tz <zone>", "Time zone for --daily-at and --cron (IANA name, e.g. Europe/Berlin)")
101
+ .option("--command <cmd>", "Schedule: run this shell command (in /workspace, as root)")
102
+ .option("--prompt <text>", "Schedule: run the coding agent with this prompt, a new conversation each run (needs an agent template: -t claude, codex, ...)")
103
+ .option("--prompt-file <path>", "Schedule: read the prompt from a file")
104
+ .option("--agent <agent>", "Agent for --prompt (codex, claude, ...)")
105
+ .option("-m, --model <model>", "Model for --prompt")
106
+ .option("--effort <level>", "Reasoning effort for --prompt (minimal, low, medium, high, xhigh)")
107
+ .option("--run-timeout <duration>", "Schedule: stop a run after this long (default 10m)", parseDuration)
108
+ .option("--schedule-name <name>", "A label for the schedule");
109
+ }
110
+
111
+ /** The schedule a `sandbox create` asked for, checked before anything is created; null: none. */
112
+ export function createScheduleBody(opts: Record<string, any>): Record<string, unknown> | null {
113
+ const timing = !!(opts.every || opts.cron || opts.dailyAt);
114
+ const task = !!(opts.prompt || opts.promptFile || opts.command);
115
+ const extras = ["tz", "weekdays", "agent", "model", "effort", "runTimeout", "scheduleName"].filter((k) => opts[k] !== undefined);
116
+ if (!timing && !task) {
117
+ if (extras.length) fail("These options belong to a schedule: add --every 10m (or --daily-at 09:00, or --cron) and --command \"...\" (or --prompt)", 2, "USAGE");
118
+ return null;
119
+ }
120
+ if (!timing) fail("Say when the schedule runs: --every 5m, --daily-at 09:00, or --cron \"*/5 * * * *\"", 2, "USAGE");
121
+ if (!task) fail("Say what the schedule runs: --command \"...\" or --prompt \"...\"", 2, "USAGE");
122
+ return taskBody({ ...opts, timeout: opts.runTimeout, name: opts.scheduleName });
123
+ }
124
+
125
+ /** Sets the schedule on a sandbox that was just created. The created schedule, or the error text. */
126
+ export async function scheduleNewSandbox(sandboxId: string, body: Record<string, unknown>): Promise<{ schedule?: Schedule; error?: string }> {
127
+ // The sandbox's row lands a moment after its create answers: one retry.
128
+ for (let attempt = 0; ; attempt++) {
129
+ try {
130
+ return { schedule: await api.post<Schedule>(`/api/sandboxes/${sandboxId}/schedules`, body) };
131
+ } catch (e: any) {
132
+ if (attempt === 0 && e?.status === 404) { await new Promise((r) => setTimeout(r, 1500)); continue; }
133
+ return { error: String(e?.message ?? e) };
134
+ }
135
+ }
136
+ }
137
+
138
+ /** One line for `sandbox create`'s output. */
139
+ export const scheduleLine = (s: Schedule) => `${s.id}: ${when(s)}${s.nextRunAt ? `, first run ${inFuture(s.nextRunAt)}` : ""}`;
140
+
78
141
  function taskBody(opts: Record<string, any>): Record<string, unknown> {
79
142
  const body: Record<string, unknown> = {};
80
143
  if (opts.every) body.every = opts.every;
81
144
  if (opts.cron) body.cron = opts.cron;
145
+ if (opts.dailyAt) {
146
+ if (opts.every || opts.cron) fail("Give one of --every, --daily-at and --cron", 2, "USAGE");
147
+ body.cron = dailyCron(opts.dailyAt, !!opts.weekdays);
148
+ } else if (opts.weekdays) fail("--weekdays goes with --daily-at HH:MM", 2, "USAGE");
82
149
  if (opts.tz) body.timezone = opts.tz;
83
150
  if (opts.promptFile) body.prompt = fs.readFileSync(opts.promptFile, "utf8");
84
151
  if (opts.prompt) body.prompt = opts.prompt;
@@ -96,7 +163,7 @@ export function registerSandboxScheduleCommands(sb: Command) {
96
163
  addTaskOptions(
97
164
  sb.command("schedule")
98
165
  .argument("<id>", "Sandbox ID")
99
- .description("Wake the sandbox on a schedule, run a prompt or command, put it back to sleep"),
166
+ .description("Set a schedule on a sandbox you just created (its first 15 minutes): wake it, run a prompt or command, put it back to sleep. Usually set at creation: lizard sandbox create --every ... --command ..."),
100
167
  true,
101
168
  )
102
169
  .option("--disabled", "Create it switched off")
@@ -108,12 +175,17 @@ left running. You pay only while it is awake. Files in /workspace carry over bet
108
175
  A run that is still going when the next one is due makes that one skip. Five failed runs in
109
176
  a row switch the schedule off.
110
177
 
178
+ A schedule is set when a sandbox is created: \`lizard sandbox create --every 10m --command "..."\`
179
+ does both. This command works on a sandbox created in the last 15 minutes; an older one takes no
180
+ new schedule (SCHEDULE_ONLY_AT_CREATE), though its schedules can still be changed (schedule-set),
181
+ run (schedule-run) and deleted (unschedule).
182
+
111
183
  Examples:
112
184
  lizard sandbox schedule sb_abc123 --every 5m --prompt "Continue the research in /workspace/research; append findings to notes.md"
113
185
  lizard sandbox schedule sb_abc123 --every 10m --command "python3 /workspace/job.py"
114
186
  lizard sandbox schedule sb_abc123 --cron "0 9 * * mon-fri" --tz Europe/Berlin --command "./report.sh"`)
115
187
  .action(async (id: string, opts) => {
116
- if (!opts.every && !opts.cron) fail("Say how often: --every 5m, or --cron \"*/5 * * * *\"", 2, "USAGE");
188
+ if (!opts.every && !opts.cron && !opts.dailyAt) fail("Say when: --every 5m, --daily-at 09:00, or --cron \"*/5 * * * *\"", 2, "USAGE");
117
189
  if (!opts.prompt && !opts.promptFile && !opts.command) fail("Say what to run: --prompt \"...\" or --command \"...\"", 2, "USAGE");
118
190
  const body = taskBody(opts);
119
191
  if (opts.disabled) body.enabled = false;
@@ -132,7 +204,7 @@ Examples:
132
204
  ? await api.get<{ schedules: Schedule[] }>(`/api/sandboxes/${id}/schedules`)
133
205
  : await api.get<{ schedules: Schedule[] }>(`/api/sandbox-schedules`);
134
206
  if (isJSONMode()) return printJSON(schedules);
135
- if (!schedules.length) return info("No schedules. Create one: lizard sandbox schedule <id> --every 5m --prompt \"...\"");
207
+ if (!schedules.length) return info("No schedules. One is set when a sandbox is created: lizard sandbox create --every 10m --command \"...\"");
136
208
  table(["id", "sandbox", "when", "runs", "next", "last"], schedules.map((s) => [
137
209
  s.id, s.sandboxId, when(s), what(s),
138
210
  !s.enabled ? chalk.dim("off") : s.running ? chalk.yellow("running") : s.nextRunAt ? inFuture(s.nextRunAt) : "-",
@@ -193,12 +265,31 @@ Examples:
193
265
  });
194
266
 
195
267
  sb.command("schedule-runs")
196
- .argument("<scheduleId>", "Schedule ID (sch_...)")
197
- .description("Show a schedule's recent runs; --output prints the latest run's output")
268
+ .argument("[scheduleId]", "Schedule ID (sch_...). Without one: the project's latest runs, across its schedules")
269
+ .description("Show a schedule's recent runs, or the project's latest runs across all its schedules; --output prints the latest run's output")
198
270
  .option("-n, --limit <n>", "How many runs", "20")
199
271
  .option("-o, --output", "Print the latest run's output in full")
200
- .action(async (sid: string, opts) => {
201
- const { runs } = await api.get<{ runs: Run[] }>(`/api/sandbox-schedules/${sid}/runs?limit=${Number(opts.limit) || 20}`);
272
+ .option("-p, --project <id>", "Without a schedule ID: this project (name, slug, or ID) instead of the linked one")
273
+ .action(async (sid: string | undefined, opts) => {
274
+ const limit = Math.min(Math.max(Number(opts.limit) || 20, 1), 200);
275
+ if (!sid) {
276
+ // What the dashboard's Schedules tab shows: every schedule of the project, their runs merged.
277
+ const projectId = await resolveProjectId(opts.project);
278
+ const { schedules } = await api.get<{ schedules: Schedule[] }>(`/api/sandbox-schedules?projectId=${encodeURIComponent(projectId)}`);
279
+ const per = await Promise.all(schedules.map((s) =>
280
+ api.get<{ runs: Run[] }>(`/api/sandbox-schedules/${s.id}/runs?limit=${Math.min(limit, 20)}`).then((r) => r.runs.map((run) => ({ run, schedule: s })), () => [])));
281
+ const rows = per.flat().sort((x, y) => Date.parse(y.run.startedAt) - Date.parse(x.run.startedAt)).slice(0, limit);
282
+ if (isJSONMode()) return printJSON(rows.map(({ run, schedule }) => ({ ...run, scheduleId: schedule.id, sandboxId: schedule.sandboxId })));
283
+ if (!rows.length) return info("No runs yet. A schedule is set when a sandbox is created: lizard sandbox create --every 10m --command \"...\"");
284
+ if (opts.output) return printRun(rows[0].run, true);
285
+ const worked = rows.reduce((n, r) => n + (r.run.durationMs ?? 0), 0);
286
+ table(["started", "sandbox", "ran", "status", "worked", "schedule"], rows.map(({ run, schedule }) => [
287
+ timeAgo(run.startedAt), schedule.sandboxId, what(schedule), runStatus(run.status),
288
+ run.durationMs != null ? `${Math.round(run.durationMs / 1000)}s` : "-", schedule.id,
289
+ ]));
290
+ return info(chalk.dim(`${rows.length} run${rows.length === 1 ? "" : "s"}, ${Math.round(worked / 1000)}s worked in total`));
291
+ }
292
+ const { runs } = await api.get<{ runs: Run[] }>(`/api/sandbox-schedules/${sid}/runs?limit=${limit}`);
202
293
  if (isJSONMode()) return printJSON(runs);
203
294
  if (!runs.length) return info("No runs yet.");
204
295
  if (opts.output) return printRun(runs[0], true);
@@ -14,7 +14,8 @@ import { resolveVolume } from "../lib/volume.js";
14
14
  import { sandboxShell } from "./sandbox-ssh.js";
15
15
  import { startVncTunnel, vncTarget } from "./sandbox-vnc.js";
16
16
  import { registerSandboxAgentCommands } from "./agents.js";
17
- import { registerSandboxScheduleCommands } from "./sandbox-schedules.js";
17
+ import { registerSandboxEnvironmentCommands } from "./sandbox-environments.js";
18
+ import { registerSandboxScheduleCommands, addCreateScheduleOptions, createScheduleBody, scheduleNewSandbox, scheduleLine } from "./sandbox-schedules.js";
18
19
  import { success, info, warn, error, isJSONMode, printJSON, table, statusColor, timeAgo, isTTY } from "../lib/format.js";
19
20
 
20
21
  // Templates are per-region rows in sandbox_templates, not a constant. Hardcoding them
@@ -178,7 +179,7 @@ export function registerSandbox(program: Command) {
178
179
  .alias("sb")
179
180
  .description("Manage ephemeral compute sandboxes");
180
181
 
181
- sb.command("create")
182
+ addCreateScheduleOptions(sb.command("create")
182
183
  .description("Create a sandbox")
183
184
  .option("-t, --template <name>", `Template (${TEMPLATE_HINT}; server validates)`, "base")
184
185
  .addOption(new Option("-s, --size <size>", `Machine size (${SIZE_HINT}); default medium, small on the Pro trial (1 Small, 2 Mini and 2 Nano at a time, US regions only; Medium, Large and Big unlock after the first payment). Mini works only with the ${MINI_TEMPLATES} templates, Nano only with ${NANO_TEMPLATES}`).choices(SANDBOX_SIZES))
@@ -193,7 +194,19 @@ export function registerSandbox(program: Command) {
193
194
  .option("--proxy <url>", "Send all of the sandbox's internet traffic through your proxy, any supplier: http://user:pass@host:port or socks5://user:pass@host:port. See `lizard sandbox proxy --help`")
194
195
  .option("--repo <owner/name>", "Start with this GitHub repository cloned into /workspace/<name>; the sandbox can push and open pull requests to it (only it). Needs GitHub connected and Lizard's GitHub App on the repository's owner")
195
196
  .option("--repo-workflows", "With --repo: may also change .github/workflows")
197
+ .option("-e, --environment <name>", "Start with the variables of this sandbox environment of the project (Sandboxes → Environment) instead of its default ones"))
198
+ .addHelpText("after", `
199
+ A schedule is set here, when the sandbox is created:
200
+ lizard sandbox create --timeout 0 --every 10m --command "python3 /workspace/job.py"
201
+ lizard sandbox create -t claude --timeout 0 --cron "0 9 * * mon-fri" --tz Europe/Berlin --prompt "Write today's report to /workspace/report.md"
202
+ Each run wakes the sandbox, runs the command or prompt, and puts it back to sleep (files only).
203
+ A prompt needs a sandbox from an agent template (claude, codex, opencode, pi, prime).`)
196
204
  .action(async (opts) => {
205
+ const scheduleBody = createScheduleBody(opts);
206
+ // Refused before anything is created: the server only finds out once the sandbox runs.
207
+ if (scheduleBody?.prompt && !opts.snapshot && ["base", "interpreter"].includes(opts.template)) {
208
+ throw new Error(`--prompt needs a sandbox with a coding agent, and the '${opts.template}' template has none. Add -t claude (or codex, opencode, pi, prime), or schedule a --command instead.`);
209
+ }
197
210
  // A snapshot restores at its source's size (a Firecracker VM's memory is part of it; a
198
211
  // pod snapshot goes back onto the machine it was captured on), so the server ignores a
199
212
  // size alongside it. Say so rather than quietly creating something other than asked.
@@ -273,6 +286,7 @@ export function registerSandbox(program: Command) {
273
286
  ...(opts.allowHost?.length ? { allowedHosts: opts.allowHost } : {}),
274
287
  ...(opts.proxy ? { proxy: opts.proxy } : {}),
275
288
  ...(opts.repo ? { repo: opts.repo, repoWorkflows: !!opts.repoWorkflows } : {}),
289
+ ...(opts.environment ? { environment: opts.environment } : {}),
276
290
  };
277
291
  try {
278
292
  sandbox = await createInDefaultRegion(body, defaultRegion);
@@ -313,8 +327,20 @@ export function registerSandbox(program: Command) {
313
327
  throw new Error("This region's platform does not support --proxy yet; the sandbox it started went out directly and was deleted.");
314
328
  }
315
329
 
330
+ // A platform that predates environments ignores the option: the sandbox would start with
331
+ // the project's default variables, not the ones asked for, so it is deleted.
332
+ if (opts.environment && opts.environment.trim().toLowerCase() !== "default" && !(sandbox as any).environment) {
333
+ await api.delete(`/api/sandboxes/${sandbox.id}`).catch(() => {});
334
+ throw new Error("This region's platform does not support --environment yet; the sandbox it started had the project's default variables and was deleted.");
335
+ }
336
+
337
+ // The schedule, right after the create. If it is refused the sandbox stays: it works, and
338
+ // the schedule can be set again in its first 15 minutes.
339
+ const scheduled = scheduleBody ? await scheduleNewSandbox(sandbox.id, scheduleBody) : null;
340
+
316
341
  if (isJSONMode()) {
317
- printJSON(sandbox);
342
+ printJSON(scheduled ? { ...sandbox, schedule: scheduled.schedule ?? null, ...(scheduled.error ? { scheduleError: scheduled.error } : {}) } : sandbox);
343
+ if (scheduled?.error) process.exitCode = 1;
318
344
  return;
319
345
  }
320
346
  success(`Sandbox ${chalk.bold(sandbox.id)} created`);
@@ -339,6 +365,14 @@ export function registerSandbox(program: Command) {
339
365
  else info(chalk.dim(` Repo: ${r.fullName} -> ${r.path}${r.status === "cloning" ? " (still cloning)" : ""}`));
340
366
  if (r.readOnly) info(chalk.yellow(` Read only: GitHub has not given Lizard write access on this account yet. Accept it at ${r.manageUrl}`));
341
367
  }
368
+ const usedEnvironment = (sandbox as any).environment as { name: string } | undefined;
369
+ if (usedEnvironment) info(chalk.dim(` Environment: ${usedEnvironment.name}`));
370
+ if (scheduled?.schedule) info(chalk.dim(` Schedule: ${scheduleLine(scheduled.schedule)}`));
371
+ if (scheduled?.error) {
372
+ warn(`The sandbox was created, but its schedule was not: ${scheduled.error}`);
373
+ info(chalk.dim(` Set it within 15 minutes: lizard sandbox schedule ${sandbox.id} --every ... --command "..."`));
374
+ process.exitCode = 1;
375
+ }
342
376
  info("");
343
377
  info(sandboxNextSteps(sandbox.id));
344
378
  });
@@ -488,6 +522,7 @@ Examples:
488
522
 
489
523
  registerSandboxAgentCommands(sb);
490
524
  registerSandboxScheduleCommands(sb);
525
+ registerSandboxEnvironmentCommands(sb);
491
526
 
492
527
  sb.command("ssh")
493
528
  .alias("shell")
@@ -6,7 +6,7 @@ import os from "node:os";
6
6
  import { spawn } from "node:child_process";
7
7
  import { createPublicKey, verify } from "node:crypto";
8
8
 
9
- export const CURRENT_VERSION = "4.0.130";
9
+ export const CURRENT_VERSION = "4.0.132";
10
10
  const RELEASES_API = "https://api.github.com/repos/lizard-build/lizard-cli/releases/latest";
11
11
  const RELEASE_BASE = "https://github.com/lizard-build/lizard-cli/releases/latest/download";
12
12