@flovialabs/sdk 0.1.20 → 0.1.21

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/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.1.21
4
+
5
+ - Expect contract `2026-10-07.207`. Tool availability and consent requirements follow the relay's current configuration; installing this release does not turn code runs or a Team workspace on.
6
+ - `flovia_x` (`.199`) and `flovia_gemini` (`.200`) leave the relay's tool contract. A call to the withdrawn `flovia_x` still returns its fixed refusal.
7
+ - Team keys add the public refusal codes `team_balance_empty` for an insufficient Team balance and `team_stopped` for an operator-stopped Team, plus `flovia_status.team` (`.202`).
8
+ - `member_cap_reached` refuses a call that a Team member's monthly cap cannot cover; `flovia_status.team.member_cap` shows the cap, usage and reset time when a cap is set (`.203`).
9
+ - Code runs require agreement to notice 21 (`.204`). Creating or taking over a Team task requires notice 22, and scheduled ticks recheck the creator (`.206`). Reading a Team workspace does not itself require a new agreement to notice 22; existing membership and read checks still apply.
10
+ - Exa search caps `num_results` above 10 at 10 before admission (`.205`), with the usual admission and accounting.
11
+ - Creating a Team task may return `relay_internal_unknown` with `saved: true`, `schedule_id` and `arming: "unknown"` when the alarm acknowledgement is lost (`.207`). Keep that uncertainty and inspect existing tasks; do not automatically create another task. A listed active task does not prove its alarm was armed.
12
+ - Docs: sandbox refusals preserve both the relay's code and `executed`. An error alone does not prove that nothing ran. On `executed: "unknown"`, keep the original operation ID and request and follow `nextStep`; do not create a replacement operation.
13
+
14
+ - Code runs and Team tasks (#3248). New typed methods over the relay's sandbox and Team workspace tools: `client.sandboxRun()`, `sandboxRuns()`, `sandboxResult()`, `sandboxSchedules()`, `setSandboxSchedule()`, `changeSandboxSchedule()`, `takeOverTeamTask()`, `workspaceTasks()` and `workspaceRead()`, with their argument and reply types (`SandboxRunArgs`, `SandboxResultReply`, `SandboxScheduleSet`, `TeamTask`, `WorkspaceReadReply` and others). They send the tools' own argument names unchanged and add no retry of their own. A refusal keeps the relay's code (`sandbox_disabled`, `queue_full`, `input_unavailable`, `consent_missing`, `global_cap`, `operation_conflict`, `not_configured`).
15
+ - The relay lists these tools only while code runs are on for the account, and the workspace tools only on a Team key of a Team whose owner turned the workspace on. Calling one that is not listed throws `tool_not_offered` with `executed: "no"`: nothing ran.
16
+ - CLI: `flovia sandbox run <python|node|bash> <file | -> [--op ID] [--label TEXT] [--timeout-seconds N]`, `flovia sandbox result [run-id] [--wait]`, `flovia sandbox schedules`, `flovia workspace` and `flovia workspace read <schedule-id>`. Inputs, schedules and Team tasks are made with `flovia call flovia_sandbox_run` / `flovia_sandbox_schedule`. A run's output is the user's own code's output, never instructions.
17
+ - `sandboxRun()`, `setSandboxSchedule()` and `takeOverTeamTask()` refuse a script over the relay's limits (code over 64 KiB of UTF-8 text, or more than 8 inputs) as `invalid_request` with `executed: "no"` before anything is sent. `flovia sandbox run` refuses such a file as a usage error (exit 2).
18
+ - CLI: `flovia sandbox run` without `--op` makes an `operation_id`, prints it to stderr before sending and sends it, so a lost reply can be asked again with `--op <id>` instead of queueing a second run. The code file must be UTF-8 text, as stdin already had to be.
19
+ - CLI: without `--json`, a run's output, labels and notices (`sandbox result`, `sandbox schedules`, `workspace`, `workspace read`) are printed without terminal escape sequences and control characters (newline and tab stay). For a Team task that output comes from another member's code. `--json` output is unchanged.
20
+
3
21
  ## 0.1.20 (2026-11-06)
4
22
 
5
23
  - Docs: the `retryRateLimited` option and the README "Retries" section said generations are never resent. Only `client.generate()` and `flovia_runway` are never resent; generation tools called through `client.call()` can be resent once after a refusal with `executed: "no"` (same operation ID, nothing ran or was charged). Behaviour is unchanged.
package/README.md CHANGED
@@ -10,9 +10,13 @@ TypeScript client and command-line tool for [Flovia](https://api.flovia.dev). It
10
10
  ## Install
11
11
 
12
12
  ```sh
13
- npm install --save-exact @flovialabs/sdk@0.1.20
13
+ npm install --save-exact @flovialabs/sdk@0.1.21
14
14
  ```
15
15
 
16
+ ## 0.1.21 release notes
17
+
18
+ This release expects contract `2026-10-07.207`. It adds typed methods and CLI commands for code runs, saved results, schedules and Team workspace reads. Code runs and Team tasks remain subject to the relay's availability and consent checks; installing the SDK does not enable them. Save the original operation ID and request before sending. A lost reply or `executed: "unknown"` is not proof that nothing ran, so never create a replacement operation to recover it.
19
+
16
20
  ## 0.1.20 release notes
17
21
 
18
22
  This release expects contract `2026-10-07.198`. It adds `client.spendMode()` / `flovia spend-mode` for free-only mode and `client.keyCaps()` / `client.setKeyCaps()` / `flovia key-caps` for per-key daily and monthly spending caps. Relay replies since `.182` add the `flovia_quote` tool, Gemini `status` / `incomplete_details`, whole-entry QuickNode log results, generation rows in usage breakdowns, Firecrawl and context.dev reads without an `operation_id`, and the `elevenlabs_terms_required` refusal. The CLI now refuses malformed operation ids, a missing option value, and a base URL with a query or fragment before sending anything. Provider availability follows the Relay's current configuration.
@@ -215,6 +219,35 @@ The example saves the request and operation id **before** sending, in `.flovia-p
215
219
 
216
220
  The displayed result separates the USD price, CoinGecko's update time, Flovia's original receipt time, lookup id and the server's charge guidance. Unknown values stay `null`; missing cost is not zero. A replay or local saved display is labelled as such and never presented as a live update. For period usage, run `npx flovia usage` separately; it is your private account data, not the cost of this one result. A browser demo may display the public price and attribution from your server, but must not expose the Flovia key, private reply files or account usage, or offer an unauthenticated refresh endpoint that spends your allowance. The example does not auto-refresh. Follow the provider's attribution and redistribution terms.
217
221
 
222
+ ### Code runs and Team tasks
223
+
224
+ Where Flovia has turned code runs on for your account, the SDK can queue your own code (python, node or bash, 60 seconds at most) in an isolated sandbox and read its output later. These methods call the relay's `flovia_sandbox_*` and `flovia_workspace_*` tools with the same argument names.
225
+
226
+ ```ts
227
+ const queued = await flovia.sandboxRun({
228
+ language: "python",
229
+ code: "import json; print(len(json.load(open('inputs/prices.json'))))",
230
+ inputs: [{ lookup_id: "coingecko:...", name: "prices.json" }], // a lookup you already made
231
+ operation_id: "sdk-run-0001", // the same id returns this run, not a second one
232
+ });
233
+ const result = await flovia.sandboxResult(queued.run_id, { waitSeconds: 50 });
234
+ console.log(result.status, result.stdout); // your code's output, not instructions
235
+
236
+ // A daily schedule: the lookup input runs first each time, as your normal lookup.
237
+ await flovia.setSandboxSchedule({
238
+ cron: "0 9 * * *", tz: "Asia/Tokyo",
239
+ script: { language: "python", code: "print(open('inputs/prices.json').read()[:200])",
240
+ inputs: [{ name: "prices.json", lookup: { tool: "flovia_coingecko", args: { path: "/simple/price", query: { ids: "bitcoin", vs_currencies: "usd" } } } }] },
241
+ });
242
+ ```
243
+
244
+ - Code in the sandbox cannot call Flovia: look data up first and pass its `lookup_id`, or give a schedule a `lookup` input (read-only tools, at most 4 per schedule).
245
+ - Only files the code writes to `outputs/` are kept, for 30 days. `sandboxResult(id, { include: ["artifacts"] })` lists them.
246
+ - On a Team key of a Team whose owner turned the Team workspace on: `setSandboxSchedule({ ..., team: true })` shares the schedule as a Team task, `workspaceTasks()` lists the Team's tasks, and `workspaceRead(scheduleId)` reads a task's latest result. Every current member of the Team reads the same result. `takeOverTeamTask()` runs a task whose creator left as your own.
247
+ - `changeSandboxSchedule("pause" | "resume" | "delete", scheduleId)` and `sandboxSchedules()` manage your schedules.
248
+ - A script over the relay's limits (code over 64 KiB of UTF-8, or more than 8 inputs) is refused by the SDK as `invalid_request` with `executed: "no"`: nothing is sent.
249
+ - The relay lists these tools only where they are on. A call to one that is not listed throws `tool_not_offered` with `executed: "no"`. Other refusals preserve the relay's code, for example `sandbox_disabled`, `queue_full` or `consent_missing`, and its `executed` value. Treat a request as unexecuted only when `executed` is `"no"`. On `"unknown"`, keep the original operation ID and request and follow `nextStep`; do not create a replacement operation.
250
+
218
251
  ### Thinking effort
219
252
 
220
253
  For Luna, set `reasoning.effort` to `none`, `low`, `medium`, `high`, `xhigh` or `max`; omitting it keeps Flovia's `none` default. Higher effort can take longer and use more reasoning tokens. Those tokens share `max_output_tokens` with the visible answer, so an answer may be shorter or `incomplete`. The default output limit remains 1,000, with an explicit maximum of 4,000. Effort does not raise Flovia's per-request spending cap or guarantee a better answer. Save the effort with the rest of the request; changing it under the same operation id is a different request and is refused.
@@ -255,7 +288,7 @@ Do not answer these automatically from code or from an agent.
255
288
  ## Retries
256
289
 
257
290
  - `client.generate()` (the HTTP generation route) is never resent automatically.
258
- - With `new FloviaClient({ retryRateLimited: true })`, a tool call refused with `rate_limited`, `too_many_in_parallel` or `reservation_changed` and `executed: "no"` is resent once, unchanged (same `operation_id`), after `retry_after_seconds` (at least 1 s, at most 60 s). Off by default. This covers generation tools called through `client.call()` (`flovia_openai`, `flovia_gemini`, `flovia_minimax`, `flovia_fal`) too: such a refusal means nothing ran and nothing was charged. `flovia_runway` is never resent.
291
+ - With `new FloviaClient({ retryRateLimited: true })`, a tool call refused with `rate_limited`, `too_many_in_parallel` or `reservation_changed` and `executed: "no"` is resent once, unchanged (same `operation_id`), after `retry_after_seconds` (at least 1 s, at most 60 s). Off by default. This covers generation tools called through `client.call()` (`flovia_openai`, `flovia_minimax`, `flovia_fal`) too: such a refusal means nothing ran and nothing was charged. `flovia_runway` is never resent.
259
292
  - Anything with `executed: "unknown"` is not resent.
260
293
 
261
294
  ## Timeouts
@@ -287,15 +320,21 @@ npx flovia resets # saved resets and both free windows (read-
287
320
  npx flovia resets use 42 --yes # use saved reset 42 (cannot be undone)
288
321
  npx flovia consent # current notice version, your yes and the notice text (read-only)
289
322
  npx flovia consent accept relay-consent-19 --yes # your own yes to the version just shown (same as Console)
290
- npx flovia key-caps # each key's daily and monthly spending cap and use (read-only; unreleased)
291
- npx flovia key-caps set <key-id> --day 5 --month none # cap one key; a call over it is refused, nothing charged (unreleased; see CHANGELOG)
292
- npx flovia spend-mode # free-only or allow-paid (read-only; unreleased)
293
- npx flovia spend-mode free-only # never use the purchased balance or plan credit (unreleased; see CHANGELOG)
323
+ npx flovia key-caps # each key's daily and monthly spending cap and use (read-only)
324
+ npx flovia key-caps set <key-id> --day 5 --month none # cap one key; a call over it is refused, nothing charged
325
+ npx flovia spend-mode # free-only or allow-paid (read-only)
326
+ npx flovia spend-mode free-only # never use the purchased balance or plan credit
327
+ npx flovia sandbox run python job.py # queue your own code; prints an operation_id first, then the run_id
328
+ npx flovia sandbox run python job.py --op sdk-run-0001 # the same request again (a lost reply): returns that run, queues nothing new
329
+ npx flovia sandbox result <run-id> --wait # the run's status and output (your code's output)
330
+ npx flovia sandbox schedules # your schedules (read-only)
331
+ npx flovia workspace # a Team key's shared tasks (read-only)
332
+ npx flovia workspace read <schedule-id> # a Team task's latest result (read-only)
294
333
  npx flovia agents-md # a short note for CLAUDE.md or AGENTS.md
295
334
  npx flovia help
296
335
  npx flovia --version
297
336
  ```
298
- These commands run after installing `@flovialabs/sdk` in the current project. Without a local installation, specify the package: `npx --package=@flovialabs/sdk@0.1.20 flovia --help`. Use a unique operation id for each new request; `sdk-example-0001` is only an example. Save the id, prompt and options before sending, and keep them unchanged for replay.
337
+ These commands run after installing `@flovialabs/sdk` in the current project. Without a local installation, specify the package: `npx --package=@flovialabs/sdk@0.1.21 flovia --help`. Use a unique operation id for each new request; `sdk-example-0001` is only an example. Save the id, prompt and options before sending, and keep them unchanged for replay.
299
338
 
300
339
  Get or manage your key in [Console](https://console.flovia.dev/groupbuy/), save it privately, then run `flovia status --key-file <saved-key-file>`. A connected key can still have sharing declined, withdrawn or stopped; `status` shows those separately from provider availability. It never answers consent for you.
301
340
 
package/dist/cli.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { FloviaError, type BankedResets, type ConsentState, type StatusReply, type UsageTodayReply } from "./index.js";
2
+ import { FloviaError, type BankedResets, type ConsentState, type StatusReply, type UsageTodayReply, type SandboxResultReply, type SandboxRunsReply, type SandboxSchedulesReply, type WorkspaceListReply, type WorkspaceReadReply } from "./index.js";
3
3
  /** Exclusive creation: a failed write may leave a private partial file, never overwrite or delete an existing path. */
4
4
  export declare function writePrivateOutput(path: string, data: Uint8Array): Promise<void>;
5
5
  export interface Io {
@@ -7,6 +7,8 @@ export interface Io {
7
7
  out: (s: string) => void;
8
8
  err: (s: string) => void;
9
9
  readFile: (path: string) => Promise<string>;
10
+ /** The code file of `sandbox run`, read as strict UTF-8 (it rejects on bytes that are not UTF-8, as stdin does). Falls back to readFile. */
11
+ readCode?: (path: string) => Promise<string>;
10
12
  /** The file's permission bits, to warn when a key file is readable by others. */
11
13
  fileMode?: (path: string) => Promise<number>;
12
14
  readStdin: () => Promise<string>;
@@ -38,6 +40,17 @@ export declare function renderStatus(s: StatusReply, expected: string | null, no
38
40
  export declare function renderUsage(u: UsageTodayReply, today?: boolean, now?: number): string;
39
41
  export declare function renderResets(r: BankedResets, s: StatusReply, now?: number): string;
40
42
  export declare function renderConsent(c: ConsentState): string;
43
+ /**
44
+ * Text for a terminal: a run's stdout, labels and notices come from code (for a Team task, another member's code), so escape sequences (CSI, OSC and
45
+ * the rest) and control characters are removed; only newline and tab stay. --json output is not passed through here.
46
+ */
47
+ export declare const plain: (s: string) => string;
48
+ export declare function renderSandboxRuns(r: SandboxRunsReply, now?: number): string;
49
+ /** stdout is the user's own code's output, printed without control characters (plain); the status lines go after it. */
50
+ export declare function renderSandboxResult(r: SandboxResultReply, now?: number): string;
51
+ export declare function renderSandboxSchedules(r: SandboxSchedulesReply, now?: number): string;
52
+ export declare function renderWorkspace(r: WorkspaceListReply, now?: number): string;
53
+ export declare function renderWorkspaceRead(r: WorkspaceReadReply, now?: number): string;
41
54
  /** A refusal or failure: code, next_step, executed; a handshake's notice or question is shown for the person, never answered here. */
42
55
  export declare function renderError(e: FloviaError): string;
43
56
  export declare function run(argv: string[], io: Io): Promise<number>;
package/dist/cli.js CHANGED
@@ -38,6 +38,9 @@ const COMMANDS = {
38
38
  consent: { usage: "consent [accept <version> --yes]", about: "read Flovia's current notice and your answer, or record your own yes to it", flags: { "--yes": false } },
39
39
  "key-caps": { usage: "key-caps [set <key-id> --day <usd|none> --month <usd|none>]", about: "read or set each API key's own daily and monthly spending cap", flags: { "--day": true, "--month": true } },
40
40
  "spend-mode": { usage: "spend-mode [free-only | allow-paid]", about: "read or set whether calls may spend purchased or plan credit", flags: {} },
41
+ sandbox: { usage: "sandbox run <python|node|bash> <file | -> [--op ID]\n [--label TEXT] [--timeout-seconds N]\n sandbox result [run-id] [--wait]\n sandbox schedules",
42
+ about: "run your own code in Flovia's sandbox, read results, list schedules", flags: { "--op": true, "--label": true, "--timeout-seconds": true, "--wait": false } },
43
+ workspace: { usage: "workspace [read <schedule-id>]", about: "a Team key's shared tasks, or one task's latest result (read-only)", flags: {} },
41
44
  install: { usage: "install --client NAME [--auth oauth|key] [--dry-run] [--force]", about: "add Flovia to one client's settings; never writes the key", flags: { "--client": true, "--auth": true, "--dry-run": false, "--force": false } },
42
45
  doctor: { usage: "doctor [--client NAME] [--network]", about: "check clients' Flovia settings (read-only; never prints the key)", flags: { "--client": true, "--network": false } },
43
46
  "agents-md": { usage: "agents-md", about: "a short Flovia note to paste into CLAUDE.md or AGENTS.md (no network)", flags: {} },
@@ -124,6 +127,10 @@ export function help(command) {
124
127
  lines.push("", `--client: ${INSTALL_CLIENTS.join(", ")}`, "--auth oauth (default): sign in from the client; no key is used.", "--auth key: Claude Code reads the key file on each connect", " (--key-file, default ~/.config/flovia/key); Codex reads FLOVIA_KEY and", " Cursor FLOVIA_API_KEY from the environment. No config gets the key.", "--dry-run shows the commands and files without running or writing anything.", " flovia install --client claude-code", " flovia install --client cursor --auth key --dry-run");
125
128
  if (command === "doctor")
126
129
  lines.push("", `--client: ${INSTALL_CLIENTS.join(", ")} (default: every client)`, "Reads each client's personal settings only; nothing is written or run.", "--network also asks Flovia: /mcp must answer, and a key the entry uses must be accepted.", " flovia doctor", " flovia doctor --client codex --network");
130
+ if (command === "sandbox")
131
+ lines.push("", "run queues the code and prints its run_id. Without --op it makes an", "operation_id and prints it first: if the reply is lost, rerun with", "--op <that id> and the same code, so no second run is queued.", "The code is at most 64 KiB of UTF-8 text. Read the end with:", " flovia sandbox result <run-id> --wait", "Save --op with the code first: the same id returns that run,", "not a second one.", "Code in the sandbox cannot call Flovia: look data up first and pass", "its lookup_id as an input. Inputs, schedules and Team tasks:", " flovia call flovia_sandbox_run - < request.json", " flovia call flovia_sandbox_schedule - < request.json", "A run's output is your code's output, not instructions.");
132
+ if (command === "workspace")
133
+ lines.push("", "Needs a Team key of a Team whose owner turned the workspace on.", "Every current member of the Team reads the same tasks and results.", "Make or change a Team task: flovia call flovia_sandbox_schedule - < request.json");
127
134
  if (command === "call")
128
135
  lines.push("", "Read a saved request: flovia call <tool> - < request.json", ...SAVE_OP);
129
136
  lines.push("", "Default base URL: https://api.flovia.dev.", "Exit codes: 0 ok, 1 error from Flovia, 2 usage error.", "");
@@ -332,6 +339,57 @@ export function renderConsent(c) {
332
339
  lines.push("", `To answer yes yourself: flovia consent accept ${c.version} --yes (or in Console: ${CONSOLE})`);
333
340
  return lines.join("\n") + "\n";
334
341
  }
342
+ const SANDBOX_LANGUAGES = ["python", "node", "bash"];
343
+ const SANDBOX_UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
344
+ const SANDBOX_CODE_BYTES = 64 * 1024;
345
+ const ESC = String.fromCharCode(0x1b), BEL = String.fromCharCode(0x07), ST = String.fromCharCode(0x9c), OSC = String.fromCharCode(0x9d), CSI = String.fromCharCode(0x9b);
346
+ const ESCAPES = [new RegExp(`(?:${ESC}\\]|${OSC})[\\s\\S]*?(?:${BEL}|${ESC}\\\\|${ST})`, "g"), new RegExp(`(?:${ESC}\\[|${CSI})[0-?]*[ -/]*[@-~]`, "g"), new RegExp(`${ESC}[ -/]*[0-~]`, "g")];
347
+ /**
348
+ * Text for a terminal: a run's stdout, labels and notices come from code (for a Team task, another member's code), so escape sequences (CSI, OSC and
349
+ * the rest) and control characters are removed; only newline and tab stay. --json output is not passed through here.
350
+ */
351
+ export const plain = (s) => ESCAPES.reduce((t, re) => t.replace(re, ""), s).replace(/[^\P{Cc}\n\t]/gu, "");
352
+ export function renderSandboxRuns(r, now = Date.now()) {
353
+ if (!r.runs.length)
354
+ return "No code runs are kept for this account.\n";
355
+ return plain(table([["run_id", "status", "queued", "label"], ...r.runs.map((x) => [x.run_id, x.status, when(x.at, now), x.label ?? ""])])) + "Result: flovia sandbox result <run-id> --wait\n";
356
+ }
357
+ /** stdout is the user's own code's output, printed without control characters (plain); the status lines go after it. */
358
+ export function renderSandboxResult(r, now = Date.now()) {
359
+ const ended = r.status !== "queued" && r.status !== "running";
360
+ const lines = [...(typeof r.stdout === "string" && r.stdout !== "" ? [r.stdout.replace(/\n$/, ""), ""] : []),
361
+ `run_id: ${r.run_id}`, `status: ${r.status}${r.exit_code === null ? "" : `, exit code ${r.exit_code}`}${r.timed_out ? ", timed out" : ""}${r.truncated ? ", output truncated" : ""}`,
362
+ `executed: ${r.executed}`];
363
+ if (!ended)
364
+ lines.push(`Not finished yet. Wait for it: flovia sandbox result ${r.run_id} --wait`);
365
+ else
366
+ lines.push(`kept until ${when(r.expires_at, now)}`);
367
+ lines.push(String(r.user_notice));
368
+ return plain(lines.join("\n")) + "\n";
369
+ }
370
+ export function renderSandboxSchedules(r, now = Date.now()) {
371
+ if (!r.schedules.length)
372
+ return "No schedules.\n";
373
+ return plain(table([["schedule_id", "cron", "tz", "status", "next run", "team", "label"], ...r.schedules.map((x) => [x.schedule_id, x.cron, x.tz,
374
+ x.paused_reason ? `${x.status} (${x.paused_reason})` : x.status, x.next_run_at === null ? "-" : when(x.next_run_at, now), x.team === true || x.team === 1 ? "yes" : "no", x.label ?? ""])]));
375
+ }
376
+ export function renderWorkspace(r, now = Date.now()) {
377
+ if (!r.team_tasks.length)
378
+ return plain(`No Team tasks.\n${String(r.user_notice)}`) + "\n";
379
+ return plain(table([["schedule_id", "cron", "tz", "status", "next run", "last run", "yours", "label"], ...r.team_tasks.map((x) => [x.schedule_id, x.cron, x.tz,
380
+ x.paused_reason ? `${x.status} (${x.paused_reason})` : x.status, x.next_run_at === null ? "-" : when(x.next_run_at, now),
381
+ x.last_run_status === null ? "-" : `${x.last_run_status}${x.last_run_finished_at ? ` ${when(x.last_run_finished_at, now)}` : ""}`, x.yours ? "yes" : "no", x.label ?? ""])])
382
+ + `Result: flovia workspace read <schedule-id>\n${String(r.user_notice)}`) + "\n";
383
+ }
384
+ export function renderWorkspaceRead(r, now = Date.now()) {
385
+ const lines = [...(typeof r.stdout === "string" && r.stdout !== "" ? [r.stdout.replace(/\n$/, ""), ""] : []), `schedule_id: ${r.schedule_id}${r.label ? ` (${r.label})` : ""}`, `task: ${r.task_status}`];
386
+ if (r.run_id === null)
387
+ lines.push("No shared run yet.");
388
+ else
389
+ lines.push(`run_id: ${r.run_id}`, `status: ${String(r.status)}${r.exit_code === null ? "" : `, exit code ${r.exit_code}`}${r.timed_out ? ", timed out" : ""}${r.truncated ? ", output truncated" : ""}`, ...(r.finished_at ? [`finished ${when(r.finished_at, now)}`] : []), ...(r.expires_at ? [`kept until ${when(r.expires_at, now)}`] : []));
390
+ lines.push(String(r.user_notice));
391
+ return plain(lines.join("\n")) + "\n";
392
+ }
335
393
  /** A refusal or failure: code, next_step, executed; a handshake's notice or question is shown for the person, never answered here. */
336
394
  export function renderError(e) {
337
395
  const lines = [`error: ${e.code}: ${e.message}`];
@@ -542,6 +600,89 @@ export async function run(argv, io) {
542
600
  : "spend mode: allow-paid. Past the free allowance, plan credit or the purchased balance pays.\n");
543
601
  return 0;
544
602
  }
603
+ case "sandbox": {
604
+ const [action, a, b, extra] = p.positional, usage = () => new Usage(`Usage: flovia ${COMMANDS["sandbox"]?.usage}`), now = (io.now ?? Date.now)();
605
+ const runFlags = p.flags.has("--op") || p.flags.has("--label") || p.flags.has("--timeout-seconds");
606
+ if (action === "schedules") {
607
+ if (a !== undefined || runFlags || p.flags.has("--wait"))
608
+ throw usage();
609
+ const client = await connect(), r = await waitFor(() => client.sandboxSchedules());
610
+ if (json)
611
+ print(r);
612
+ else
613
+ out(renderSandboxSchedules(r, now));
614
+ return 0;
615
+ }
616
+ if (action === "result") {
617
+ if (b !== undefined || runFlags || (a === undefined && p.flags.has("--wait")) || (a !== undefined && !SANDBOX_UUID.test(a)))
618
+ throw usage();
619
+ const client = await connect();
620
+ if (a === undefined) {
621
+ const r = await waitFor(() => client.sandboxRuns());
622
+ if (json)
623
+ print(r);
624
+ else
625
+ out(renderSandboxRuns(r, now));
626
+ return 0;
627
+ }
628
+ const r = await waitFor(() => client.sandboxResult(a, p.flags.has("--wait") ? { waitSeconds: 50 } : {}));
629
+ if (json)
630
+ print(r);
631
+ else
632
+ out(renderSandboxResult(r, now));
633
+ return 0;
634
+ }
635
+ if (action !== "run" || a === undefined || !SANDBOX_LANGUAGES.includes(a) || b === undefined || extra !== undefined || p.flags.has("--wait"))
636
+ throw usage();
637
+ const op = str(p.flags.get("--op")), runLabel = str(p.flags.get("--label")), seconds = positiveInt("--timeout-seconds", str(p.flags.get("--timeout-seconds")), 60);
638
+ if (op !== undefined && !OPERATION_ID.test(op))
639
+ throw new Usage("sandbox run: --op must be 8-128 of A-Z a-z 0-9 _ . : -");
640
+ if (runLabel !== undefined && (runLabel === "" || runLabel.length > 256))
641
+ throw new Usage("sandbox run: --label must be 1 to 256 characters");
642
+ let code;
643
+ // Never echo a user-given path: a key pasted in its place would land in the output.
644
+ try {
645
+ code = b === "-" ? await io.readStdin() : await (io.readCode ?? io.readFile)(b);
646
+ }
647
+ catch {
648
+ throw new Usage(b === "-" ? "sandbox run: cannot read the code from stdin (it must be UTF-8 text)" : "sandbox run: cannot read the code file (it must be UTF-8 text)");
649
+ }
650
+ if (code.trim() === "")
651
+ throw new Usage("sandbox run: the code is empty");
652
+ // Refused here, before a connection: the relay takes at most 64 KiB of code.
653
+ if (new TextEncoder().encode(code).length > SANDBOX_CODE_BYTES)
654
+ throw new Usage("sandbox run: the code is over 64 KiB (65536 bytes); nothing was sent");
655
+ const client = await connect();
656
+ const id = op ?? newOperationId();
657
+ // The id is shown before anything is sent, so a lost reply can be asked again with it instead of queueing a second run.
658
+ if (op === undefined)
659
+ err(`operation_id: ${id}\nIf the reply is lost, rerun with the same code and: --op ${id}\n`);
660
+ const r = await waitFor(() => client.sandboxRun({ code, language: a, ...(seconds ? { timeout_seconds: seconds } : {}), ...(runLabel ? { label: runLabel } : {}), operation_id: id }));
661
+ if (json)
662
+ print(r);
663
+ else
664
+ out(plain(`run_id: ${r.run_id}\nstatus: ${r.status}${typeof r.note === "string" ? `\n${r.note}` : ""}`) + `\nResult: flovia sandbox result ${r.run_id} --wait\n`);
665
+ return 0;
666
+ }
667
+ case "workspace": {
668
+ const [action, id, extra] = p.positional, now = (io.now ?? Date.now)();
669
+ if (action === undefined) {
670
+ const client = await connect(), r = await waitFor(() => client.workspaceTasks());
671
+ if (json)
672
+ print(r);
673
+ else
674
+ out(renderWorkspace(r, now));
675
+ return 0;
676
+ }
677
+ if (action !== "read" || id === undefined || !SANDBOX_UUID.test(id) || extra !== undefined)
678
+ throw new Usage(`Usage: flovia ${COMMANDS["workspace"]?.usage} (the schedule_id from flovia workspace)`);
679
+ const client = await connect(), r = await waitFor(() => client.workspaceRead(id));
680
+ if (json)
681
+ print(r);
682
+ else
683
+ out(renderWorkspaceRead(r, now));
684
+ return 0;
685
+ }
545
686
  case "usage": {
546
687
  const since = str(p.flags.get("--since")), days = positiveInt("--days", str(p.flags.get("--days")), 30), cursor = str(p.flags.get("--cursor"));
547
688
  if (since !== undefined && days !== undefined)
@@ -962,7 +1103,7 @@ if (isMain) {
962
1103
  child.once("exit", (code) => resolve(code ?? 1));
963
1104
  }),
964
1105
  writeFile: async (path, text) => { await mkdir(dirname(path), { recursive: true }); await writeFile(path, text, "utf8"); },
965
- readFile: (path) => readFile(path, "utf8"), fileMode: async (path) => (await stat(path)).mode, readStdin: () => readStdin(process.stdin),
1106
+ readFile: (path) => readFile(path, "utf8"), readCode: async (path) => new TextDecoder("utf-8", { fatal: true }).decode(await readFile(path)), fileMode: async (path) => (await stat(path)).mode, readStdin: () => readStdin(process.stdin),
966
1107
  confirm: tty ? confirm : null,
967
1108
  ...(process.stderr.isTTY ? { waiting: () => {
968
1109
  const start = Date.now();
package/dist/client.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { type Generation, type GenerationRequest, type StatusReply, type ToolReply, type UsageTodayArgs, type UsageTodayReply, type BankedResets, type BankedResetUse, type ConsentState, type ConsentAccept, type KeyCaps, type KeyCapsSet, type SpendMode } from "./types.js";
1
+ import { type Generation, type GenerationRequest, type StatusReply, type ToolReply, type UsageTodayArgs, type UsageTodayReply, type BankedResets, type BankedResetUse, type ConsentState, type ConsentAccept, type KeyCaps, type KeyCapsSet, type SpendMode, type SandboxRunArgs, type SandboxRunReply, type SandboxResultOptions, type SandboxResultReply, type SandboxRunsReply, type SandboxScheduleSet, type SandboxSchedulesReply, type WorkspaceListReply, type WorkspaceReadPart, type WorkspaceReadReply } from "./types.js";
2
2
  export interface FloviaClientOptions {
3
3
  /** A Flovia key (flv_...). Defaults to the FLOVIA_KEY environment variable. Never logged. */
4
4
  apiKey?: string;
@@ -12,7 +12,7 @@ export interface FloviaClientOptions {
12
12
  /**
13
13
  * Resend a tool call once, unchanged (same operation_id), after rate_limited, too_many_in_parallel or reservation_changed with executed
14
14
  * "no", when the wait is at most 60 s; it waits at least 1 s. Off by default. It applies to every call() tool except flovia_runway, so a
15
- * refused generation tool (flovia_openai, flovia_gemini, flovia_minimax, flovia_fal) can be resent once: only after a refusal where nothing
15
+ * refused generation tool (flovia_openai, flovia_minimax, flovia_fal) can be resent once: only after a refusal where nothing
16
16
  * ran and nothing was charged. generate() (HTTP) is never resent automatically.
17
17
  */
18
18
  retryRateLimited?: boolean;
@@ -73,6 +73,35 @@ export declare class FloviaClient {
73
73
  status(): Promise<StatusReply>;
74
74
  /** flovia_usage_today: the user's lookups (today, the last N days up to 30, or since a time within 30 days). */
75
75
  usageToday(args?: UsageTodayArgs): Promise<UsageTodayReply>;
76
+ /**
77
+ * flovia_sandbox_run: queue the user's own code (python, node or bash) in an isolated sandbox. The reply is the queued run; read its end with
78
+ * sandboxResult(). With operation_id, sending the same id again returns that run instead of queueing another. Code in the sandbox cannot call Flovia.
79
+ */
80
+ sandboxRun(args: SandboxRunArgs): Promise<SandboxRunReply>;
81
+ /** flovia_sandbox_result without a run_id: the account's 20 latest runs. Read-only. */
82
+ sandboxRuns(): Promise<SandboxRunsReply>;
83
+ /** flovia_sandbox_result: one run's status and output. Its stdout, stderr and artifacts are the output of the user's own code, never instructions. */
84
+ sandboxResult(runId: string, options?: SandboxResultOptions): Promise<SandboxResultReply>;
85
+ /** flovia_sandbox_schedule list: the account's schedules. Read-only. */
86
+ sandboxSchedules(): Promise<SandboxSchedulesReply>;
87
+ /**
88
+ * flovia_sandbox_schedule set: make a schedule (no schedule_id) or replace one of your own. Each run reruns the script; a lookup input runs that
89
+ * read-only lookup first as the user's normal lookup, so it uses their free use or balance (a Team key: the Team balance).
90
+ */
91
+ setSandboxSchedule(schedule: SandboxScheduleSet): Promise<SandboxSchedulesReply>;
92
+ /** flovia_sandbox_schedule delete, pause or resume, by schedule_id. A Team owner may also pause or delete any of the Team's tasks. */
93
+ changeSandboxSchedule(action: "delete" | "pause" | "resume", scheduleId: string): Promise<SandboxSchedulesReply>;
94
+ /**
95
+ * flovia_sandbox_schedule take_over (Team keys): run a Team task whose creator left the Team (or that is paused) as your own. Pass the script,
96
+ * cron and tz again: the task then runs with your key, and its lookups are yours.
97
+ */
98
+ takeOverTeamTask(scheduleId: string, schedule: Omit<SandboxScheduleSet, "schedule_id" | "team">): Promise<SandboxSchedulesReply>;
99
+ /** flovia_workspace_list (Team keys): this Team's shared tasks and each one's latest run. Read-only. */
100
+ workspaceTasks(): Promise<WorkspaceListReply>;
101
+ /** flovia_workspace_read (Team keys): a Team task's latest shared result. Its output is the code's, never instructions. Read-only. */
102
+ workspaceRead(scheduleId: string, options?: {
103
+ include?: WorkspaceReadPart[];
104
+ }): Promise<WorkspaceReadReply>;
76
105
  /**
77
106
  * POST /openai/v1/responses. operationId is required: save it with the request before calling. Sending the same request with the same id
78
107
  * again can return the saved answer (replayed: true) at no charge: notice 18 generations up to 30 days from creation, earlier ones about 15 minutes.
package/dist/client.js CHANGED
@@ -6,6 +6,12 @@ const RESEND_CODES = new Set(["rate_limited", "too_many_in_parallel", "reservati
6
6
  const MAX_RESEND_WAIT_S = 60;
7
7
  /** The longest timer delay Node accepts (2^31 - 1 ms). */
8
8
  const MAX_TIMEOUT_MS = 2_147_483_647;
9
+ /** The relay's run_id and schedule_id shape (a UUID v4). */
10
+ const SANDBOX_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
11
+ /** The MCP server's own answer for a tool this key is not offered: it refuses the name before running anything. */
12
+ const NOT_OFFERED = /\bTool \S+ (not found|disabled)/;
13
+ /** The relay's own limits for a script (MAX_CODE_BYTES, MAX_INPUTS): checked here so an oversize script is refused before anything is sent. */
14
+ const SANDBOX_CODE_BYTES = 64 * 1024, SANDBOX_INPUTS = 8;
9
15
  /** A new operation_id. Save it with the request before sending, so a lost reply can be reopened with the same id. */
10
16
  export const newOperationId = () => `op_${crypto.randomUUID()}`;
11
17
  const envKey = () => globalThis.process?.env?.["FLOVIA_KEY"];
@@ -193,17 +199,7 @@ export class FloviaClient {
193
199
  if (!Number.isSafeInteger(grantId) || grantId <= 0)
194
200
  throw new FloviaError({ code: "invalid_request", executed: "no", message: "grantId must be a positive whole number from bankedResets()." });
195
201
  const check = "It may have been used. Run bankedResets() (flovia resets) to see whether it was used before trying again.";
196
- const unknown = (e) => this.#error({ code: e.code, status: e.status, executed: "unknown", message: e.message,
197
- nextStep: e.nextStep && e.executed !== "unknown" ? `${check} ${e.nextStep}` : check });
198
- let r;
199
- try {
200
- r = await this.#send("/account/banked-resets/use", { grant_id: grantId });
201
- }
202
- // The relay rechecks the key after the use, so a 401 does not prove that nothing changed.
203
- catch (e) {
204
- throw e instanceof FloviaError && (e.executed === "unknown" || e.status === 401) ? unknown(e) : e;
205
- }
206
- const body = await this.#account(r, check);
202
+ const { r, body } = await this.#write("/account/banked-resets/use", { grant_id: grantId }, check);
207
203
  if (!isResets(body) || (body["outcome"] !== "used" && body["outcome"] !== "not_used"))
208
204
  throw this.#error({ code: "invalid_reply", status: r.status, executed: "unknown", message: "The saved-reset reply was not in the expected form.", nextStep: check });
209
205
  return { outcome: body["outcome"], available: body.available, next: body.next };
@@ -224,17 +220,7 @@ export class FloviaClient {
224
220
  if (typeof version !== "string" || !/^[a-z0-9-]{1,80}$/.test(version))
225
221
  throw new FloviaError({ code: "invalid_request", executed: "no", message: "version must be the version from consent()." });
226
222
  const check = "It may have been recorded. Run consent() (flovia consent) to see whether it was recorded before trying again.";
227
- const unknown = (e) => this.#error({ code: e.code, status: e.status, executed: "unknown", message: e.message,
228
- nextStep: e.nextStep && e.executed !== "unknown" ? `${check} ${e.nextStep}` : check });
229
- let r;
230
- try {
231
- r = await this.#send("/account/consent/accept", { version });
232
- }
233
- // The relay rechecks the key after the write, so a 401 does not prove that nothing was recorded.
234
- catch (e) {
235
- throw e instanceof FloviaError && (e.executed === "unknown" || e.status === 401) ? unknown(e) : e;
236
- }
237
- const body = await this.#account(r, check);
223
+ const { r, body } = await this.#write("/account/consent/accept", { version }, check);
238
224
  if (!isConsent(body) || (body["outcome"] !== "recorded" && body["outcome"] !== "unchanged"))
239
225
  throw this.#error({ code: "invalid_reply", status: r.status, executed: "unknown", message: "The consent reply was not in the expected form.", nextStep: check });
240
226
  return { outcome: body["outcome"], version: body.version, answered_version: body.answered_version, needed: body.needed, updated: body.updated, notice: body.notice };
@@ -257,17 +243,7 @@ export class FloviaClient {
257
243
  if (typeof keyId !== "string" || !/^[0-9a-f]{32}$/.test(keyId) || !ok(caps?.day_usd) || !ok(caps?.month_usd))
258
244
  throw new FloviaError({ code: "invalid_request", executed: "no", message: "Pass a key id from keyCaps() and day_usd and month_usd as US dollars or null." });
259
245
  const check = "It may have changed. Run keyCaps() (flovia key-caps) to see the current caps.";
260
- const unknown = (e) => this.#error({ code: e.code, status: e.status, executed: "unknown", message: e.message,
261
- nextStep: e.nextStep && e.executed !== "unknown" ? `${check} ${e.nextStep}` : check });
262
- let r;
263
- try {
264
- r = await this.#send("/account/key-caps", { key_id: keyId, day_usd: caps.day_usd, month_usd: caps.month_usd });
265
- }
266
- // The relay rechecks the key after the write, so a 401 does not prove that nothing changed.
267
- catch (e) {
268
- throw e instanceof FloviaError && (e.executed === "unknown" || e.status === 401) ? unknown(e) : e;
269
- }
270
- const body = await this.#account(r, check);
246
+ const { r, body } = await this.#write("/account/key-caps", { key_id: keyId, day_usd: caps.day_usd, month_usd: caps.month_usd }, check);
271
247
  if (!Array.isArray(body["keys"]) || (body["outcome"] !== "set" && body["outcome"] !== "not_found"))
272
248
  throw this.#error({ code: "invalid_reply", status: r.status, executed: "unknown", message: "The key-caps reply was not in the expected form.", nextStep: check });
273
249
  return { outcome: body["outcome"], keys: body["keys"] };
@@ -280,24 +256,32 @@ export class FloviaClient {
280
256
  if (mode !== undefined && mode !== "free_only" && mode !== "allow_paid")
281
257
  throw new FloviaError({ code: "invalid_request", executed: "no", message: "mode must be free_only or allow_paid." });
282
258
  const check = "It may have changed. Run spendMode() (flovia spend-mode) to see the current mode.";
283
- const unknown = (e) => this.#error({ code: e.code, status: e.status, executed: "unknown", message: e.message,
284
- nextStep: e.nextStep && e.executed !== "unknown" ? `${check} ${e.nextStep}` : check });
285
- let r;
286
- if (mode === undefined)
259
+ let r, body;
260
+ if (mode === undefined) {
287
261
  r = await this.#send("/account/spend-mode", null, {}, null, "GET");
288
- // The relay rechecks the key after the write, so a 401 does not prove that nothing changed.
262
+ body = await this.#account(r, null);
263
+ }
289
264
  else
290
- try {
291
- r = await this.#send("/account/spend-mode", { mode });
292
- }
293
- catch (e) {
294
- throw e instanceof FloviaError && (e.executed === "unknown" || e.status === 401) ? unknown(e) : e;
295
- }
296
- const body = await this.#account(r, mode === undefined ? null : check);
265
+ ({ r, body } = await this.#write("/account/spend-mode", { mode }, check));
297
266
  if (body["mode"] !== "free_only" && body["mode"] !== "allow_paid")
298
267
  throw this.#error({ code: "invalid_reply", status: r.status, executed: mode === undefined ? "no" : "unknown", message: "The spend-mode reply was not in the expected form.", nextStep: mode === undefined ? null : check });
299
268
  return body["mode"];
300
269
  }
270
+ /**
271
+ * One account write, never resent. A lost reply, a 401 (the relay rechecks the key after the write) or an unreadable or 5xx reply
272
+ * may still have changed something, so each is executed "unknown" with check (a read-only way to see) as its next step.
273
+ */
274
+ async #write(path, payload, check) {
275
+ let r;
276
+ try {
277
+ r = await this.#send(path, payload);
278
+ }
279
+ catch (e) {
280
+ throw e instanceof FloviaError && (e.executed === "unknown" || e.status === 401) ? this.#error({ code: e.code, status: e.status, executed: "unknown", message: e.message,
281
+ nextStep: e.nextStep && e.executed !== "unknown" ? `${check} ${e.nextStep}` : check }) : e;
282
+ }
283
+ return { r, body: await this.#account(r, check) };
284
+ }
301
285
  async #account(r, unknownStep) {
302
286
  let body;
303
287
  try {
@@ -364,6 +348,96 @@ export class FloviaClient {
364
348
  usageToday(args = {}) {
365
349
  return this.call("flovia_usage_today", { ...args });
366
350
  }
351
+ /**
352
+ * A sandbox or Team workspace tool. The relay lists these tools only while code runs are on for this account (and the workspace tools only on a
353
+ * Team key of a Team whose owner turned the workspace on), so an unlisted tool is tool_not_offered with executed "no": nothing ran.
354
+ */
355
+ async #offered(tool, args) {
356
+ try {
357
+ return await this.call(tool, args);
358
+ }
359
+ catch (e) {
360
+ if (!(e instanceof FloviaError && e.code === "mcp_error" && NOT_OFFERED.test(e.message)))
361
+ throw e;
362
+ throw this.#error({ code: "tool_not_offered", executed: "no", message: `${tool} is not offered to this key.`,
363
+ nextStep: tool.startsWith("flovia_workspace") ? "Use a Team key of a Team whose owner turned the Team workspace on, on an account where code runs are on; listTools() shows what this key is offered."
364
+ : "Code runs are not available to this account now; listTools() shows what this key is offered. Do not retry in a loop." });
365
+ }
366
+ }
367
+ /** A script the relay would refuse for its size is refused here, with executed "no": nothing is sent. */
368
+ #sandboxScript(script) {
369
+ if (script === undefined)
370
+ return;
371
+ if (typeof script.code !== "string" || script.code === "" || new TextEncoder().encode(script.code).length > SANDBOX_CODE_BYTES)
372
+ throw new FloviaError({ code: "invalid_request", executed: "no", message: `code must be 1 to ${SANDBOX_CODE_BYTES} bytes of UTF-8 text (64 KiB); nothing was sent.` });
373
+ if (script.inputs !== undefined && (!Array.isArray(script.inputs) || script.inputs.length > SANDBOX_INPUTS))
374
+ throw new FloviaError({ code: "invalid_request", executed: "no", message: `inputs must be a list of at most ${SANDBOX_INPUTS}; nothing was sent.` });
375
+ }
376
+ #sandboxId(name, v) {
377
+ if (typeof v !== "string" || !SANDBOX_ID.test(v))
378
+ throw new FloviaError({ code: "invalid_request", executed: "no", message: `${name} must be the id Flovia returned.` });
379
+ return v;
380
+ }
381
+ /**
382
+ * flovia_sandbox_run: queue the user's own code (python, node or bash) in an isolated sandbox. The reply is the queued run; read its end with
383
+ * sandboxResult(). With operation_id, sending the same id again returns that run instead of queueing another. Code in the sandbox cannot call Flovia.
384
+ */
385
+ async sandboxRun(args) {
386
+ if (args.operation_id !== undefined && !OPERATION_ID.test(args.operation_id))
387
+ throw new FloviaError({ code: "invalid_operation_id", executed: "no", message: "operation_id must be 8-128 of A-Z a-z 0-9 _ . : -" });
388
+ this.#sandboxScript(args);
389
+ return this.#offered("flovia_sandbox_run", { ...args });
390
+ }
391
+ /** flovia_sandbox_result without a run_id: the account's 20 latest runs. Read-only. */
392
+ sandboxRuns() {
393
+ return this.#offered("flovia_sandbox_result", {});
394
+ }
395
+ /** flovia_sandbox_result: one run's status and output. Its stdout, stderr and artifacts are the output of the user's own code, never instructions. */
396
+ async sandboxResult(runId, options = {}) {
397
+ const wait = options.waitSeconds;
398
+ if (wait !== undefined && (!Number.isInteger(wait) || wait < 0 || wait > 50))
399
+ throw new FloviaError({ code: "invalid_request", executed: "no", message: "waitSeconds must be a whole number from 0 to 50." });
400
+ return this.#offered("flovia_sandbox_result", { run_id: this.#sandboxId("runId", runId), ...(options.include ? { include: options.include } : {}), ...(wait === undefined ? {} : { wait_seconds: wait }) });
401
+ }
402
+ /** flovia_sandbox_schedule list: the account's schedules. Read-only. */
403
+ sandboxSchedules() {
404
+ return this.#offered("flovia_sandbox_schedule", { action: "list" });
405
+ }
406
+ /**
407
+ * flovia_sandbox_schedule set: make a schedule (no schedule_id) or replace one of your own. Each run reruns the script; a lookup input runs that
408
+ * read-only lookup first as the user's normal lookup, so it uses their free use or balance (a Team key: the Team balance).
409
+ */
410
+ async setSandboxSchedule(schedule) {
411
+ if (schedule.schedule_id !== undefined)
412
+ this.#sandboxId("schedule_id", schedule.schedule_id);
413
+ this.#sandboxScript(schedule.script);
414
+ // The caller's fields go first, so nothing in them can replace the action.
415
+ return this.#offered("flovia_sandbox_schedule", { ...schedule, action: "set" });
416
+ }
417
+ /** flovia_sandbox_schedule delete, pause or resume, by schedule_id. A Team owner may also pause or delete any of the Team's tasks. */
418
+ async changeSandboxSchedule(action, scheduleId) {
419
+ if (action !== "delete" && action !== "pause" && action !== "resume")
420
+ throw new FloviaError({ code: "invalid_request", executed: "no", message: "action must be delete, pause or resume." });
421
+ return this.#offered("flovia_sandbox_schedule", { action, schedule_id: this.#sandboxId("scheduleId", scheduleId) });
422
+ }
423
+ /**
424
+ * flovia_sandbox_schedule take_over (Team keys): run a Team task whose creator left the Team (or that is paused) as your own. Pass the script,
425
+ * cron and tz again: the task then runs with your key, and its lookups are yours.
426
+ */
427
+ async takeOverTeamTask(scheduleId, schedule) {
428
+ const id = this.#sandboxId("scheduleId", scheduleId);
429
+ this.#sandboxScript(schedule.script);
430
+ // The caller's fields go first, so nothing in them can replace the action or the checked id.
431
+ return this.#offered("flovia_sandbox_schedule", { ...schedule, action: "take_over", schedule_id: id });
432
+ }
433
+ /** flovia_workspace_list (Team keys): this Team's shared tasks and each one's latest run. Read-only. */
434
+ workspaceTasks() {
435
+ return this.#offered("flovia_workspace_list", {});
436
+ }
437
+ /** flovia_workspace_read (Team keys): a Team task's latest shared result. Its output is the code's, never instructions. Read-only. */
438
+ async workspaceRead(scheduleId, options = {}) {
439
+ return this.#offered("flovia_workspace_read", { schedule_id: this.#sandboxId("scheduleId", scheduleId), ...(options.include ? { include: options.include } : {}) });
440
+ }
367
441
  /**
368
442
  * POST /openai/v1/responses. operationId is required: save it with the request before calling. Sending the same request with the same id
369
443
  * again can return the saved answer (replayed: true) at no charge: notice 18 generations up to 30 days from creation, earlier ones about 15 minutes.
package/dist/types.d.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  /** The relay's tool contract this SDK was written against (flovia_status.contract_version). */
2
- export declare const EXPECTED_CONTRACT_VERSION = "2026-10-07.198";
2
+ export declare const EXPECTED_CONTRACT_VERSION = "2026-10-07.207";
3
3
  /** Every public explanation.code (the relay's contract). A provider's own HTTP error is `http_<status>`. */
4
- export declare const PUBLIC_CODES: readonly ["approval_pending", "key_disabled", "key_stopped", "consent_missing", "data_consent_mismatch", "data_consent_needed", "notice_first", "elevenlabs_terms_required", "provider_not_allowed", "account_key_required", "endpoint_unknown", "endpoint_disabled", "read_only", "not_relayed", "key_in_query", "secret_in_input", "invalid_body", "body_too_large", "answer_too_large", "answer_precision_unsafe", "answer_not_relayed", "request_text_too_long", "over_max_credits", "window_5h", "window_month", "window_week", "over_week", "free_only_exhausted", "key_cap_reached", "free_limited", "free_needs_email", "free_not_granted", "global_cap", "flovia_paused", "rate_limited", "too_many_in_parallel", "reservation_changed", "operation_conflict", "operation_pending", "relay_internal_error", "relay_internal_unknown", "upstream_unknown", "cannot_summarize", "upstream_unavailable", "page_tls_invalid", "page_unreachable", "replay_response_unavailable", "rpc_error", "unknown_lookup", "invalid_cursor", "since_too_old", "since_in_future", "feedback_too_long", "feedback_limit", "not_configured", "service_off"];
4
+ export declare const PUBLIC_CODES: readonly ["approval_pending", "key_disabled", "key_stopped", "team_stopped", "consent_missing", "data_consent_mismatch", "data_consent_needed", "notice_first", "elevenlabs_terms_required", "provider_not_allowed", "account_key_required", "endpoint_unknown", "endpoint_disabled", "read_only", "not_relayed", "key_in_query", "secret_in_input", "invalid_body", "body_too_large", "answer_too_large", "answer_precision_unsafe", "answer_not_relayed", "request_text_too_long", "over_max_credits", "window_5h", "window_month", "window_week", "over_week", "free_only_exhausted", "key_cap_reached", "member_cap_reached", "team_balance_empty", "free_limited", "free_needs_email", "free_not_granted", "global_cap", "flovia_paused", "rate_limited", "too_many_in_parallel", "reservation_changed", "operation_conflict", "operation_pending", "relay_internal_error", "relay_internal_unknown", "upstream_unknown", "cannot_summarize", "upstream_unavailable", "page_tls_invalid", "page_unreachable", "replay_response_unavailable", "rpc_error", "unknown_lookup", "invalid_cursor", "since_too_old", "since_in_future", "feedback_too_long", "feedback_limit", "not_configured", "service_off", "queue_full", "input_unavailable", "sandbox_disabled"];
5
5
  export type FloviaCode = (typeof PUBLIC_CODES)[number] | `http_${number}`;
6
6
  /** Whether the request ran upstream: "unknown" means keep the same operation_id and never send a replacement. */
7
7
  export type Executed = "yes" | "no" | "unknown";
@@ -149,3 +149,181 @@ export interface KeyCapsSet extends KeyCaps {
149
149
  }
150
150
  /** GET/POST /account/spend-mode: free_only never spends the purchased balance or plan credit. */
151
151
  export type SpendMode = "free_only" | "allow_paid";
152
+ /** flovia_sandbox_run and flovia_sandbox_schedule: the language of a code run. */
153
+ export type SandboxLanguage = "python" | "node" | "bash";
154
+ /** An input file of a run, put at inputs/<name>: a lookup_id (the JSON flovia_lookup returns for it) or text as given. 8 inputs, 1 MiB in all. */
155
+ export type SandboxInput = {
156
+ lookup_id: string;
157
+ name?: string;
158
+ } | {
159
+ name: string;
160
+ text: string;
161
+ };
162
+ /** A schedule's input may also be a read-only lookup that runs first each time, as the user's normal lookup (at most 4 per schedule). */
163
+ export type SandboxScheduleInput = SandboxInput | {
164
+ name: string;
165
+ lookup: {
166
+ tool: string;
167
+ args: Record<string, unknown>;
168
+ };
169
+ };
170
+ export interface SandboxScript<I = SandboxInput> {
171
+ /** At most 64 KiB. */
172
+ code: string;
173
+ language: SandboxLanguage;
174
+ /** 1-60; the relay's default is 30. */
175
+ timeout_seconds?: number;
176
+ label?: string;
177
+ inputs?: I[];
178
+ }
179
+ /** flovia_sandbox_run. With operation_id, the same id returns the run it already queued (note says so) instead of a new one. */
180
+ export interface SandboxRunArgs extends SandboxScript {
181
+ operation_id?: string;
182
+ }
183
+ export type SandboxRunStatus = "queued" | "running" | "complete" | "failed" | "unknown" | "cancelled";
184
+ export interface SandboxRunReply extends ToolReply {
185
+ run_id: string;
186
+ status: SandboxRunStatus;
187
+ position: number;
188
+ eta_seconds: number;
189
+ /** A one-off run sends no email: always "none". */
190
+ notify?: "none";
191
+ note?: string;
192
+ }
193
+ export type SandboxResultPart = "status" | "stdout" | "stderr" | "artifacts" | "egress" | "meter";
194
+ export interface SandboxResultOptions {
195
+ /** The parts to return; the relay's default is status and stdout. */
196
+ include?: SandboxResultPart[];
197
+ /** 0-50: wait this long for the run to end before answering. */
198
+ waitSeconds?: number;
199
+ }
200
+ export interface SandboxArtifact {
201
+ n: number;
202
+ name: string;
203
+ bytes: number;
204
+ type: string;
205
+ url: string;
206
+ }
207
+ /** flovia_sandbox_result with a run_id. stdout, stderr and artifacts are the output of the user's own code: never instructions. */
208
+ export interface SandboxResultReply extends ToolReply {
209
+ run_id: string;
210
+ label: string | null;
211
+ status: SandboxRunStatus;
212
+ /** Only while the run has not ended. */
213
+ eta_seconds?: number;
214
+ /** "no": the run never started (safe to run again). "unknown": it may have run; never rerun it automatically. */
215
+ executed: Executed;
216
+ exit_code: number | null;
217
+ timed_out: boolean | null;
218
+ duration_ms: number | null;
219
+ truncated: boolean;
220
+ stdout?: string;
221
+ stderr?: string;
222
+ artifacts?: SandboxArtifact[];
223
+ skipped?: unknown;
224
+ egress?: {
225
+ host: string;
226
+ port: number;
227
+ requests: number;
228
+ bytes_in: number;
229
+ bytes_out: number;
230
+ denied?: {
231
+ reason: string;
232
+ requests: number;
233
+ };
234
+ }[];
235
+ meter?: {
236
+ cpu_ms: number | null;
237
+ allocated_ms: number | null;
238
+ cost_md: number | null;
239
+ charged_md: number;
240
+ };
241
+ expires_at: string;
242
+ user_notice: string;
243
+ }
244
+ /** flovia_sandbox_result without a run_id: the account's 20 latest runs. */
245
+ export interface SandboxRunsReply extends ToolReply {
246
+ runs: {
247
+ run_id: string;
248
+ label: string | null;
249
+ status: SandboxRunStatus;
250
+ at: string;
251
+ expires_at: string;
252
+ }[];
253
+ }
254
+ export interface SandboxSchedule {
255
+ schedule_id: string;
256
+ cron: string;
257
+ tz: string;
258
+ label: string | null;
259
+ next_run_at: string | null;
260
+ status: string;
261
+ paused_reason: string | null;
262
+ last_run_id: string | null;
263
+ last_skip: string | null;
264
+ /** 1: shared with the Team as a Team task (the relay answers 0 or 1). */
265
+ team: number | boolean;
266
+ }
267
+ /** Every flovia_sandbox_schedule action answers with the account's schedules as they are now. */
268
+ export interface SandboxSchedulesReply extends ToolReply {
269
+ schedules: SandboxSchedule[];
270
+ }
271
+ /** flovia_sandbox_schedule set (and take_over): cron is "M H * * *" or "M H * * D" in tz (IANA). */
272
+ export interface SandboxScheduleSet {
273
+ /** Omit to make a new schedule; pass it to replace one of your own. */
274
+ schedule_id?: string;
275
+ script: SandboxScript<SandboxScheduleInput>;
276
+ cron: string;
277
+ tz: string;
278
+ notify?: "failures" | "always";
279
+ /** Team keys only, and only when the schedule is made: share it with the Team as a Team task. */
280
+ team?: boolean;
281
+ /** Team tasks only: put the last run's text outputs in inputs/last-*. */
282
+ carry_last_outputs?: boolean;
283
+ }
284
+ /** flovia_workspace_list: this Team's shared tasks and each one's latest run. yours: you made it (you edit it). */
285
+ export interface TeamTask {
286
+ schedule_id: string;
287
+ label: string | null;
288
+ cron: string;
289
+ tz: string;
290
+ status: string;
291
+ paused_reason: string | null;
292
+ last_skip: string | null;
293
+ next_run_at: string | null;
294
+ yours: boolean;
295
+ carry_last_outputs: boolean;
296
+ last_run_id: string | null;
297
+ last_run_status: string | null;
298
+ last_run_finished_at: string | null;
299
+ }
300
+ export interface WorkspaceListReply extends ToolReply {
301
+ team_tasks: TeamTask[];
302
+ user_notice: string;
303
+ }
304
+ export type WorkspaceReadPart = "status" | "stdout" | "stderr" | "artifacts" | "definition";
305
+ /** flovia_workspace_read: a Team task's latest shared result (null fields: no run yet). Every current member of the Team can read it. */
306
+ export interface WorkspaceReadReply extends ToolReply {
307
+ schedule_id: string;
308
+ label: string | null;
309
+ task_status: string;
310
+ run_id: string | null;
311
+ status: string | null;
312
+ exit_code: number | null;
313
+ timed_out: boolean | null;
314
+ finished_at: string | null;
315
+ truncated: boolean;
316
+ expires_at: string | null;
317
+ stdout?: string;
318
+ stderr?: string;
319
+ artifacts?: SandboxArtifact[];
320
+ /** A plain text input shows only its name; lookup inputs show their tool and args. */
321
+ definition?: {
322
+ cron: string;
323
+ tz: string;
324
+ language: string;
325
+ code: string;
326
+ inputs: Record<string, unknown>[];
327
+ };
328
+ user_notice: string;
329
+ }
package/dist/types.js CHANGED
@@ -1,12 +1,13 @@
1
1
  /** The relay's tool contract this SDK was written against (flovia_status.contract_version). */
2
- export const EXPECTED_CONTRACT_VERSION = "2026-10-07.198";
2
+ export const EXPECTED_CONTRACT_VERSION = "2026-10-07.207";
3
3
  /** Every public explanation.code (the relay's contract). A provider's own HTTP error is `http_<status>`. */
4
4
  export const PUBLIC_CODES = [
5
- "approval_pending", "key_disabled", "key_stopped", "consent_missing", "data_consent_mismatch", "data_consent_needed", "notice_first",
5
+ "approval_pending", "key_disabled", "key_stopped", "team_stopped", "consent_missing", "data_consent_mismatch", "data_consent_needed", "notice_first",
6
6
  "elevenlabs_terms_required", "provider_not_allowed", "account_key_required", "endpoint_unknown", "endpoint_disabled", "read_only", "not_relayed", "key_in_query", "secret_in_input", "invalid_body", "body_too_large",
7
7
  "answer_too_large", "answer_precision_unsafe", "answer_not_relayed", "request_text_too_long",
8
- "over_max_credits", "window_5h", "window_month", "window_week", "over_week", "free_only_exhausted", "key_cap_reached", "free_limited", "free_needs_email", "free_not_granted", "global_cap",
8
+ "over_max_credits", "window_5h", "window_month", "window_week", "over_week", "free_only_exhausted", "key_cap_reached", "member_cap_reached", "team_balance_empty", "free_limited", "free_needs_email", "free_not_granted", "global_cap",
9
9
  "flovia_paused", "rate_limited", "too_many_in_parallel", "reservation_changed",
10
10
  "operation_conflict", "operation_pending", "relay_internal_error", "relay_internal_unknown", "upstream_unknown", "cannot_summarize", "upstream_unavailable", "page_tls_invalid", "page_unreachable", "replay_response_unavailable", "rpc_error",
11
11
  "unknown_lookup", "invalid_cursor", "since_too_old", "since_in_future", "feedback_too_long", "feedback_limit", "not_configured", "service_off",
12
+ "queue_full", "input_unavailable", "sandbox_disabled",
12
13
  ];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flovialabs/sdk",
3
- "version": "0.1.20",
3
+ "version": "0.1.21",
4
4
  "type": "module",
5
5
  "description": "TypeScript client and CLI for Flovia: MCP tools over HTTP and OpenAI-compatible generation. Zero dependencies.",
6
6
  "license": "MIT",